/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @lightSyntaxTransform * @noflow * @nolint * @preventMunge * @preserve-invariant-messages */ "use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __knownSymbol = (name, symbol2) => (symbol2 = Symbol[name]) ? symbol2 : Symbol.for("Symbol." + name); var __typeError = (msg) => { throw TypeError(msg); }; var __pow = Math.pow; var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key2 of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key2) && key2 !== except) __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); var __privateWrapper = (obj, member, setter, getter) => ({ set _(value) { __privateSet(obj, member, value, setter); }, get _() { return __privateGet(obj, member, getter); } }); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; var __await = function(promise2, isYieldStar) { this[0] = promise2; this[1] = isYieldStar; }; var __yieldStar = (value) => { var obj = value[__knownSymbol("asyncIterator")], isAwait = false, method, it = {}; if (obj == null) { obj = value[__knownSymbol("iterator")](); method = (k) => it[k] = (x) => obj[k](x); } else { obj = obj.call(value); method = (k) => it[k] = (v) => { if (isAwait) { isAwait = false; if (k === "throw") throw v; return v; } isAwait = true; return { done: false, value: new __await(new Promise((resolve) => { var x = obj[k](v); if (!(x instanceof Object)) __typeError("Object expected"); resolve(x); }), 1) }; }; } return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => { throw x; }, "return" in obj && method("return"), it; }; // node_modules/@babel/helpers/node_modules/@babel/traverse/lib/path/lib/virtual-types.js var require_virtual_types = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/traverse/lib/path/lib/virtual-types.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Var = exports2.User = exports2.Statement = exports2.SpreadProperty = exports2.Scope = exports2.RestProperty = exports2.ReferencedMemberExpression = exports2.ReferencedIdentifier = exports2.Referenced = exports2.Pure = exports2.NumericLiteralTypeAnnotation = exports2.Generated = exports2.ForAwaitStatement = exports2.Flow = exports2.Expression = exports2.ExistentialTypeParam = exports2.BlockScoped = exports2.BindingIdentifier = void 0; var ReferencedIdentifier = exports2.ReferencedIdentifier = ["Identifier", "JSXIdentifier"]; var ReferencedMemberExpression = exports2.ReferencedMemberExpression = ["MemberExpression"]; var BindingIdentifier = exports2.BindingIdentifier = ["Identifier"]; var Statement = exports2.Statement = ["Statement"]; var Expression = exports2.Expression = ["Expression"]; var Scope = exports2.Scope = ["Scopable", "Pattern"]; var Referenced = exports2.Referenced = null; var BlockScoped = exports2.BlockScoped = null; var Var = exports2.Var = ["VariableDeclaration"]; var User = exports2.User = null; var Generated = exports2.Generated = null; var Pure = exports2.Pure = null; var Flow = exports2.Flow = ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"]; var RestProperty = exports2.RestProperty = ["RestElement"]; var SpreadProperty = exports2.SpreadProperty = ["RestElement"]; var ExistentialTypeParam = exports2.ExistentialTypeParam = ["ExistsTypeAnnotation"]; var NumericLiteralTypeAnnotation = exports2.NumericLiteralTypeAnnotation = ["NumberLiteralTypeAnnotation"]; var ForAwaitStatement = exports2.ForAwaitStatement = ["ForOfStatement"]; } }); // ../../node_modules/ms/index.js var require_ms = __commonJS({ "../../node_modules/ms/index.js"(exports2, module2) { "use strict"; var s = 1e3; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; module2.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === "string" && val.length > 0) { return parse6(val); } else if (type === "number" && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) ); }; function parse6(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || "ms").toLowerCase(); switch (type) { case "years": case "year": case "yrs": case "yr": case "y": return n * y; case "weeks": case "week": case "w": return n * w; case "days": case "day": case "d": return n * d; case "hours": case "hour": case "hrs": case "hr": case "h": return n * h; case "minutes": case "minute": case "mins": case "min": case "m": return n * m; case "seconds": case "second": case "secs": case "sec": case "s": return n * s; case "milliseconds": case "millisecond": case "msecs": case "msec": case "ms": return n; default: return void 0; } } function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + "d"; } if (msAbs >= h) { return Math.round(ms / h) + "h"; } if (msAbs >= m) { return Math.round(ms / m) + "m"; } if (msAbs >= s) { return Math.round(ms / s) + "s"; } return ms + "ms"; } function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, "day"); } if (msAbs >= h) { return plural(ms, msAbs, h, "hour"); } if (msAbs >= m) { return plural(ms, msAbs, m, "minute"); } if (msAbs >= s) { return plural(ms, msAbs, s, "second"); } return ms + " ms"; } function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); } } }); // ../../node_modules/debug/src/common.js var require_common = __commonJS({ "../../node_modules/debug/src/common.js"(exports2, module2) { "use strict"; function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = require_ms(); createDebug.destroy = destroy; Object.keys(env).forEach((key2) => { createDebug[key2] = env[key2]; }); createDebug.names = []; createDebug.skips = []; createDebug.formatters = {}; function selectColor(namespace) { let hash2 = 0; for (let i = 0; i < namespace.length; i++) { hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); hash2 |= 0; } return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; } createDebug.selectColor = selectColor; function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { if (!debug.enabled) { return; } const self2 = debug; const curr = Number(/* @__PURE__ */ new Date()); const ms = curr - (prevTime || curr); self2.diff = ms; self2.prev = prevTime; self2.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== "string") { args.unshift("%O"); } let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { if (match === "%%") { return "%"; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === "function") { const val = args[index]; match = formatter.call(self2, val); args.splice(index, 1); index--; } return match; }); createDebug.formatArgs.call(self2, args); const logFn = self2.log || createDebug.log; logFn.apply(self2, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend2; debug.destroy = createDebug.destroy; Object.defineProperty(debug, "enabled", { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: (v) => { enableOverride = v; } }); if (typeof createDebug.init === "function") { createDebug.init(debug); } return debug; } function extend2(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); newDebug.log = this.log; return newDebug; } function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(" ", ",").split(",").filter(Boolean); for (const ns of split) { if (ns[0] === "-") { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { if (template[templateIndex] === "*") { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; } } while (templateIndex < template.length && template[templateIndex] === "*") { templateIndex++; } return templateIndex === template.length; } function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map((namespace) => "-" + namespace) ].join(","); createDebug.enable(""); return namespaces; } function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } function destroy() { console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } createDebug.enable(createDebug.load()); return createDebug; } module2.exports = setup; } }); // ../../node_modules/debug/src/browser.js var require_browser = __commonJS({ "../../node_modules/debug/src/browser.js"(exports2, module2) { "use strict"; exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load; exports2.useColors = useColors; exports2.storage = localstorage(); exports2.destroy = /* @__PURE__ */ (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } }; })(); exports2.colors = [ "#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33" ]; function useColors() { if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { return true; } if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } function formatArgs(args) { args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); if (!this.useColors) { return; } const c2 = "color: " + this.color; args.splice(1, 0, c2, "color: inherit"); let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, (match) => { if (match === "%%") { return; } index++; if (match === "%c") { lastC = index; } }); args.splice(lastC, 0, c2); } exports2.log = console.debug || console.log || (() => { }); function save(namespaces) { try { if (namespaces) { exports2.storage.setItem("debug", namespaces); } else { exports2.storage.removeItem("debug"); } } catch (error45) { } } function load() { let r; try { r = exports2.storage.getItem("debug"); } catch (error45) { } if (!r && typeof process !== "undefined" && "env" in process) { r = process.env.DEBUG; } return r; } function localstorage() { try { return localStorage; } catch (error45) { } } module2.exports = require_common()(exports2); var { formatters } = module2.exports; formatters.j = function(v) { try { return JSON.stringify(v); } catch (error45) { return "[UnexpectedJSONParseError]: " + error45.message; } }; } }); // ../../node_modules/has-flag/index.js var require_has_flag = __commonJS({ "../../node_modules/has-flag/index.js"(exports2, module2) { "use strict"; module2.exports = (flag, argv = process.argv) => { const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf("--"); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; } }); // ../../node_modules/supports-color/index.js var require_supports_color = __commonJS({ "../../node_modules/supports-color/index.js"(exports2, module2) { "use strict"; var os = require("os"); var tty = require("tty"); var hasFlag = require_has_flag(); var { env } = process; var flagForceColor; if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { flagForceColor = 0; } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { flagForceColor = 1; } function envForceColor() { if ("FORCE_COLOR" in env) { if (env.FORCE_COLOR === "true") { return 1; } if (env.FORCE_COLOR === "false") { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== void 0) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { return 3; } if (hasFlag("color=256")) { return 2; } } if (haveStream && !streamIsTTY && forceColor === void 0) { return 0; } const min = forceColor || 0; if (env.TERM === "dumb") { return min; } if (process.platform === "win32") { const osRelease = os.release().split("."); if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ("CI" in env) { if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign2) => sign2 in env) || env.CI_NAME === "codeship") { return 1; } return min; } if ("TEAMCITY_VERSION" in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === "truecolor") { return 3; } if ("TERM_PROGRAM" in env) { const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); switch (env.TERM_PROGRAM) { case "iTerm.app": return version2 >= 3 ? 3 : 2; case "Apple_Terminal": return 2; } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ("COLORTERM" in env) { return 1; } return min; } function getSupportLevel(stream, options = {}) { const level = supportsColor(stream, __spreadValues({ streamIsTTY: stream && stream.isTTY }, options)); return translateLevel(level); } module2.exports = { supportsColor: getSupportLevel, stdout: getSupportLevel({ isTTY: tty.isatty(1) }), stderr: getSupportLevel({ isTTY: tty.isatty(2) }) }; } }); // ../../node_modules/debug/src/node.js var require_node = __commonJS({ "../../node_modules/debug/src/node.js"(exports2, module2) { "use strict"; var tty = require("tty"); var util2 = require("util"); exports2.init = init; exports2.log = log2; exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load; exports2.useColors = useColors; exports2.destroy = util2.deprecate( () => { }, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." ); exports2.colors = [6, 2, 3, 4, 5, 1]; try { const supportsColor = require_supports_color(); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports2.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error45) { } exports2.inspectOpts = Object.keys(process.env).filter((key2) => { return /^debug_/i.test(key2); }).reduce((obj, key2) => { const prop = key2.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); let val = process.env[key2]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === "null") { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); function useColors() { return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); } function formatArgs(args) { const { namespace: name, useColors: useColors2 } = this; if (useColors2) { const c2 = this.color; const colorCode = "\x1B[3" + (c2 < 8 ? c2 : "8;5;" + c2); const prefix = ` ${colorCode};1m${name} \x1B[0m`; args[0] = prefix + args[0].split("\n").join("\n" + prefix); args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); } else { args[0] = getDate() + name + " " + args[0]; } } function getDate() { if (exports2.inspectOpts.hideDate) { return ""; } return (/* @__PURE__ */ new Date()).toISOString() + " "; } function log2(...args) { return process.stderr.write(util2.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); } function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { delete process.env.DEBUG; } } function load() { return process.env.DEBUG; } function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports2.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; } } module2.exports = require_common()(exports2); var { formatters } = module2.exports; formatters.o = function(v) { this.inspectOpts.colors = this.useColors; return util2.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); }; formatters.O = function(v) { this.inspectOpts.colors = this.useColors; return util2.inspect(v, this.inspectOpts); }; } }); // ../../node_modules/debug/src/index.js var require_src = __commonJS({ "../../node_modules/debug/src/index.js"(exports2, module2) { "use strict"; if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { module2.exports = require_browser(); } else { module2.exports = require_node(); } } }); // node_modules/@babel/helpers/node_modules/@babel/traverse/lib/path/lib/virtual-types-validator.js var require_virtual_types_validator = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/traverse/lib/path/lib/virtual-types-validator.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.isBindingIdentifier = isBindingIdentifier; exports2.isBlockScoped = isBlockScoped; exports2.isExpression = isExpression2; exports2.isFlow = isFlow; exports2.isForAwaitStatement = isForAwaitStatement; exports2.isGenerated = isGenerated; exports2.isPure = isPure; exports2.isReferenced = isReferenced; exports2.isReferencedIdentifier = isReferencedIdentifier; exports2.isReferencedMemberExpression = isReferencedMemberExpression; exports2.isRestProperty = isRestProperty; exports2.isScope = isScope; exports2.isSpreadProperty = isSpreadProperty; exports2.isStatement = isStatement2; exports2.isUser = isUser; exports2.isVar = isVar; var _t = require("@babel/types"); var { isBinding, isBlockScoped: nodeIsBlockScoped, isExportDeclaration, isExpression: nodeIsExpression, isFlow: nodeIsFlow, isForStatement, isForXStatement, isIdentifier, isImportDeclaration, isImportSpecifier, isJSXIdentifier, isJSXMemberExpression, isMemberExpression: isMemberExpression2, isRestElement: nodeIsRestElement, isReferenced: nodeIsReferenced, isScope: nodeIsScope, isStatement: nodeIsStatement, isVar: nodeIsVar, isVariableDeclaration: isVariableDeclaration2, react, isForOfStatement } = _t; var { isCompatTag } = react; function isReferencedIdentifier(opts) { const { node, parent } = this; if (!isIdentifier(node, opts) && !isJSXMemberExpression(parent, opts)) { if (isJSXIdentifier(node, opts)) { if (isCompatTag(node.name)) return false; } else { return false; } } return nodeIsReferenced(node, parent, this.parentPath.parent); } function isReferencedMemberExpression() { const { node, parent } = this; return isMemberExpression2(node) && nodeIsReferenced(node, parent); } function isBindingIdentifier() { const { node, parent } = this; const grandparent = this.parentPath.parent; return isIdentifier(node) && isBinding(node, parent, grandparent); } function isStatement2() { const { node, parent } = this; if (nodeIsStatement(node)) { if (isVariableDeclaration2(node)) { if (isForXStatement(parent, { left: node })) return false; if (isForStatement(parent, { init: node })) return false; } return true; } else { return false; } } function isExpression2() { if (this.isIdentifier()) { return this.isReferencedIdentifier(); } else { return nodeIsExpression(this.node); } } function isScope() { return nodeIsScope(this.node, this.parent); } function isReferenced() { return nodeIsReferenced(this.node, this.parent); } function isBlockScoped() { return nodeIsBlockScoped(this.node); } function isVar() { return nodeIsVar(this.node); } function isUser() { return this.node && !!this.node.loc; } function isGenerated() { return !this.isUser(); } function isPure(constantsOnly) { return this.scope.isPure(this.node, constantsOnly); } function isFlow() { const { node } = this; if (nodeIsFlow(node)) { return true; } else if (isImportDeclaration(node)) { return node.importKind === "type" || node.importKind === "typeof"; } else if (isExportDeclaration(node)) { return node.exportKind === "type"; } else if (isImportSpecifier(node)) { return node.importKind === "type" || node.importKind === "typeof"; } else { return false; } } function isRestProperty() { var _this$parentPath; return nodeIsRestElement(this.node) && ((_this$parentPath = this.parentPath) == null ? void 0 : _this$parentPath.isObjectPattern()); } function isSpreadProperty() { var _this$parentPath2; return nodeIsRestElement(this.node) && ((_this$parentPath2 = this.parentPath) == null ? void 0 : _this$parentPath2.isObjectExpression()); } function isForAwaitStatement() { return isForOfStatement(this.node, { await: true }); } { exports2.isExistentialTypeParam = function isExistentialTypeParam() { throw new Error("`path.isExistentialTypeParam` has been renamed to `path.isExistsTypeAnnotation()` in Babel 7."); }; exports2.isNumericLiteralTypeAnnotation = function isNumericLiteralTypeAnnotation() { throw new Error("`path.isNumericLiteralTypeAnnotation()` has been renamed to `path.isNumberLiteralTypeAnnotation()` in Babel 7."); }; } } }); // node_modules/@babel/helpers/node_modules/@babel/traverse/lib/visitors.js var require_visitors = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/traverse/lib/visitors.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.environmentVisitor = environmentVisitor; exports2.explode = explode$1; exports2.isExplodedVisitor = isExplodedVisitor; exports2.merge = merge4; exports2.verify = verify$1; var virtualTypes = require_virtual_types(); var virtualTypesValidators = require_virtual_types_validator(); var _t = require("@babel/types"); var _context3 = require_context2(); var { DEPRECATED_KEYS, DEPRECATED_ALIASES, FLIPPED_ALIAS_KEYS, TYPES, __internal__deprecationWarning: deprecationWarning } = _t; function isVirtualType(type) { return type in virtualTypes; } function isExplodedVisitor(visitor) { return visitor == null ? void 0 : visitor._exploded; } function explode$1(visitor) { if (isExplodedVisitor(visitor)) return visitor; visitor._exploded = true; for (const nodeType of Object.keys(visitor)) { if (shouldIgnoreKey(nodeType)) continue; const parts = nodeType.split("|"); if (parts.length === 1) continue; const fns = visitor[nodeType]; delete visitor[nodeType]; for (const part of parts) { visitor[part] = fns; } } verify$1(visitor); delete visitor.__esModule; ensureEntranceObjects(visitor); ensureCallbackArrays(visitor); for (const nodeType of Object.keys(visitor)) { if (shouldIgnoreKey(nodeType)) continue; if (!isVirtualType(nodeType)) continue; const fns = visitor[nodeType]; for (const type of Object.keys(fns)) { fns[type] = wrapCheck(nodeType, fns[type]); } delete visitor[nodeType]; const types = virtualTypes[nodeType]; if (types !== null) { for (const type of types) { if (visitor[type]) { mergePair(visitor[type], fns); } else { visitor[type] = fns; } } } else { mergePair(visitor, fns); } } for (const nodeType of Object.keys(visitor)) { if (shouldIgnoreKey(nodeType)) continue; let aliases = FLIPPED_ALIAS_KEYS[nodeType]; if (nodeType in DEPRECATED_KEYS) { const deprecatedKey = DEPRECATED_KEYS[nodeType]; deprecationWarning(nodeType, deprecatedKey, "Visitor "); aliases = [deprecatedKey]; } else if (nodeType in DEPRECATED_ALIASES) { const deprecatedAlias = DEPRECATED_ALIASES[nodeType]; deprecationWarning(nodeType, deprecatedAlias, "Visitor "); aliases = FLIPPED_ALIAS_KEYS[deprecatedAlias]; } if (!aliases) continue; const fns = visitor[nodeType]; delete visitor[nodeType]; for (const alias of aliases) { const existing = visitor[alias]; if (existing) { mergePair(existing, fns); } else { visitor[alias] = Object.assign({}, fns); } } } for (const nodeType of Object.keys(visitor)) { if (shouldIgnoreKey(nodeType)) continue; ensureCallbackArrays(visitor[nodeType]); } return visitor; } function verify$1(visitor) { if (visitor._verified) return; if (typeof visitor === "function") { throw new Error("You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?"); } for (const nodeType of Object.keys(visitor)) { if (nodeType === "enter" || nodeType === "exit") { validateVisitorMethods(nodeType, visitor[nodeType]); } if (shouldIgnoreKey(nodeType)) continue; if (!TYPES.includes(nodeType)) { throw new Error(`You gave us a visitor for the node type ${nodeType} but it's not a valid type in @babel/traverse ${"7.26.4"}`); } const visitors = visitor[nodeType]; if (typeof visitors === "object") { for (const visitorKey of Object.keys(visitors)) { if (visitorKey === "enter" || visitorKey === "exit") { validateVisitorMethods(`${nodeType}.${visitorKey}`, visitors[visitorKey]); } else { throw new Error(`You passed \`traverse()\` a visitor object with the property ${nodeType} that has the invalid property ${visitorKey}`); } } } } visitor._verified = true; } function validateVisitorMethods(path, val) { const fns = [].concat(val); for (const fn of fns) { if (typeof fn !== "function") { throw new TypeError(`Non-function found defined in ${path} with type ${typeof fn}`); } } } function merge4(visitors, states = [], wrapper) { const mergedVisitor = { _verified: true, _exploded: true }; { Object.defineProperty(mergedVisitor, "_exploded", { enumerable: false }); Object.defineProperty(mergedVisitor, "_verified", { enumerable: false }); } for (let i = 0; i < visitors.length; i++) { const visitor = explode$1(visitors[i]); const state = states[i]; let topVisitor = visitor; if (state || wrapper) { topVisitor = wrapWithStateOrWrapper(topVisitor, state, wrapper); } mergePair(mergedVisitor, topVisitor); for (const key2 of Object.keys(visitor)) { if (shouldIgnoreKey(key2)) continue; let typeVisitor = visitor[key2]; if (state || wrapper) { typeVisitor = wrapWithStateOrWrapper(typeVisitor, state, wrapper); } const nodeVisitor = mergedVisitor[key2] || (mergedVisitor[key2] = {}); mergePair(nodeVisitor, typeVisitor); } } return mergedVisitor; } function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { const newVisitor = {}; for (const phase of ["enter", "exit"]) { let fns = oldVisitor[phase]; if (!Array.isArray(fns)) continue; fns = fns.map(function(fn) { let newFn = fn; if (state) { newFn = function(path) { fn.call(state, path, state); }; } if (wrapper) { newFn = wrapper(state == null ? void 0 : state.key, phase, newFn); } if (newFn !== fn) { newFn.toString = () => fn.toString(); } return newFn; }); newVisitor[phase] = fns; } return newVisitor; } function ensureEntranceObjects(obj) { for (const key2 of Object.keys(obj)) { if (shouldIgnoreKey(key2)) continue; const fns = obj[key2]; if (typeof fns === "function") { obj[key2] = { enter: fns }; } } } function ensureCallbackArrays(obj) { if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; } function wrapCheck(nodeType, fn) { const fnKey = `is${nodeType}`; const validator = virtualTypesValidators[fnKey]; const newFn = function(path) { if (validator.call(path)) { return fn.apply(this, arguments); } }; newFn.toString = () => fn.toString(); return newFn; } function shouldIgnoreKey(key2) { if (key2[0] === "_") return true; if (key2 === "enter" || key2 === "exit" || key2 === "shouldSkip") return true; if (key2 === "denylist" || key2 === "noScope" || key2 === "skipKeys") { return true; } { if (key2 === "blacklist") { return true; } } return false; } function mergePair(dest, src) { for (const phase of ["enter", "exit"]) { if (!src[phase]) continue; dest[phase] = [].concat(dest[phase] || [], src[phase]); } } var _environmentVisitor = { FunctionParent(path) { if (path.isArrowFunctionExpression()) return; path.skip(); if (path.isMethod()) { if (!path.requeueComputedKeyAndDecorators) { _context3.requeueComputedKeyAndDecorators.call(path); } else { path.requeueComputedKeyAndDecorators(); } } }, Property(path) { if (path.isObjectProperty()) return; path.skip(); if (!path.requeueComputedKeyAndDecorators) { _context3.requeueComputedKeyAndDecorators.call(path); } else { path.requeueComputedKeyAndDecorators(); } } }; function environmentVisitor(visitor) { return merge4([_environmentVisitor, visitor]); } } }); // node_modules/@babel/helpers/node_modules/@babel/traverse/lib/scope/lib/renamer.js var require_renamer = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/traverse/lib/scope/lib/renamer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = void 0; var t6 = require("@babel/types"); var _t = t6; var _traverseNode = require_traverse_node(); var _visitors = require_visitors(); var _context3 = require_context2(); var { getAssignmentIdentifiers } = _t; var renameVisitor = { ReferencedIdentifier({ node }, state) { if (node.name === state.oldName) { node.name = state.newName; } }, Scope(path, state) { if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { path.skip(); if (path.isMethod()) { if (!path.requeueComputedKeyAndDecorators) { _context3.requeueComputedKeyAndDecorators.call(path); } else { path.requeueComputedKeyAndDecorators(); } } } }, ObjectProperty({ node, scope }, state) { const { name } = node.key; if (node.shorthand && (name === state.oldName || name === state.newName) && scope.getBindingIdentifier(name) === state.binding.identifier) { node.shorthand = false; { var _node$extra; if ((_node$extra = node.extra) != null && _node$extra.shorthand) node.extra.shorthand = false; } } }, "AssignmentExpression|Declaration|VariableDeclarator"(path, state) { if (path.isVariableDeclaration()) return; const ids = path.isAssignmentExpression() ? getAssignmentIdentifiers(path.node) : path.getOuterBindingIdentifiers(); for (const name in ids) { if (name === state.oldName) ids[name].name = state.newName; } } }; var Renamer = class { constructor(binding, oldName, newName) { this.newName = newName; this.oldName = oldName; this.binding = binding; } maybeConvertFromExportDeclaration(parentDeclar) { const maybeExportDeclar = parentDeclar.parentPath; if (!maybeExportDeclar.isExportDeclaration()) { return; } if (maybeExportDeclar.isExportDefaultDeclaration()) { const { declaration } = maybeExportDeclar.node; if (t6.isDeclaration(declaration) && !declaration.id) { return; } } if (maybeExportDeclar.isExportAllDeclaration()) { return; } maybeExportDeclar.splitExportDeclaration(); } maybeConvertFromClassFunctionDeclaration(path) { return path; } maybeConvertFromClassFunctionExpression(path) { return path; } rename() { const { binding, oldName, newName } = this; const { scope, path } = binding; const parentDeclar = path.find((path2) => path2.isDeclaration() || path2.isFunctionExpression() || path2.isClassExpression()); if (parentDeclar) { const bindingIds = parentDeclar.getOuterBindingIdentifiers(); if (bindingIds[oldName] === binding.identifier) { this.maybeConvertFromExportDeclaration(parentDeclar); } } const blockToTraverse = arguments[0] || scope.block; const skipKeys = { discriminant: true }; if (t6.isMethod(blockToTraverse)) { if (blockToTraverse.computed) { skipKeys.key = true; } if (!t6.isObjectMethod(blockToTraverse)) { skipKeys.decorators = true; } } (0, _traverseNode.traverseNode)(blockToTraverse, (0, _visitors.explode)(renameVisitor), scope, this, scope.path, skipKeys); if (!arguments[0]) { scope.removeOwnBinding(oldName); scope.bindings[newName] = binding; this.binding.identifier.name = newName; } if (parentDeclar) { this.maybeConvertFromClassFunctionDeclaration(path); this.maybeConvertFromClassFunctionExpression(path); } } }; exports2.default = Renamer; } }); // node_modules/@babel/helpers/node_modules/@babel/traverse/lib/scope/binding.js var require_binding = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/traverse/lib/scope/binding.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = void 0; var Binding = class { constructor({ identifier: identifier4, scope, path, kind }) { this.identifier = void 0; this.scope = void 0; this.path = void 0; this.kind = void 0; this.constantViolations = []; this.constant = true; this.referencePaths = []; this.referenced = false; this.references = 0; this.identifier = identifier4; this.scope = scope; this.path = path; this.kind = kind; if ((kind === "var" || kind === "hoisted") && isDeclaredInLoop(path)) { this.reassign(path); } this.clearValue(); } deoptValue() { this.clearValue(); this.hasDeoptedValue = true; } setValue(value) { if (this.hasDeoptedValue) return; this.hasValue = true; this.value = value; } clearValue() { this.hasDeoptedValue = false; this.hasValue = false; this.value = null; } reassign(path) { this.constant = false; if (this.constantViolations.includes(path)) { return; } this.constantViolations.push(path); } reference(path) { if (this.referencePaths.includes(path)) { return; } this.referenced = true; this.references++; this.referencePaths.push(path); } dereference() { this.references--; this.referenced = !!this.references; } }; exports2.default = Binding; function isDeclaredInLoop(path) { for (let { parentPath, key: key2 } = path; parentPath; { parentPath, key: key2 } = parentPath) { if (parentPath.isFunctionParent()) return false; if (parentPath.isWhile() || parentPath.isForXStatement() || parentPath.isForStatement() && key2 === "body") { return true; } } return false; } } }); // ../../node_modules/globals/globals.json var require_globals = __commonJS({ "../../node_modules/globals/globals.json"(exports2, module2) { module2.exports = { builtin: { Array: false, ArrayBuffer: false, Atomics: false, BigInt: false, BigInt64Array: false, BigUint64Array: false, Boolean: false, constructor: false, DataView: false, Date: false, decodeURI: false, decodeURIComponent: false, encodeURI: false, encodeURIComponent: false, Error: false, escape: false, eval: false, EvalError: false, Float32Array: false, Float64Array: false, Function: false, globalThis: false, hasOwnProperty: false, Infinity: false, Int16Array: false, Int32Array: false, Int8Array: false, isFinite: false, isNaN: false, isPrototypeOf: false, JSON: false, Map: false, Math: false, NaN: false, Number: false, Object: false, parseFloat: false, parseInt: false, Promise: false, propertyIsEnumerable: false, Proxy: false, RangeError: false, ReferenceError: false, Reflect: false, RegExp: false, Set: false, SharedArrayBuffer: false, String: false, Symbol: false, SyntaxError: false, toLocaleString: false, toString: false, TypeError: false, Uint16Array: false, Uint32Array: false, Uint8Array: false, Uint8ClampedArray: false, undefined: false, unescape: false, URIError: false, valueOf: false, WeakMap: false, WeakSet: false }, es5: { Array: false, Boolean: false, constructor: false, Date: false, decodeURI: false, decodeURIComponent: false, encodeURI: false, encodeURIComponent: false, Error: false, escape: false, eval: false, EvalError: false, Function: false, hasOwnProperty: false, Infinity: false, isFinite: false, isNaN: false, isPrototypeOf: false, JSON: false, Math: false, NaN: false, Number: false, Object: false, parseFloat: false, parseInt: false, propertyIsEnumerable: false, RangeError: false, ReferenceError: false, RegExp: false, String: false, SyntaxError: false, toLocaleString: false, toString: false, TypeError: false, undefined: false, unescape: false, URIError: false, valueOf: false }, es2015: { Array: false, ArrayBuffer: false, Boolean: false, constructor: false, DataView: false, Date: false, decodeURI: false, decodeURIComponent: false, encodeURI: false, encodeURIComponent: false, Error: false, escape: false, eval: false, EvalError: false, Float32Array: false, Float64Array: false, Function: false, hasOwnProperty: false, Infinity: false, Int16Array: false, Int32Array: false, Int8Array: false, isFinite: false, isNaN: false, isPrototypeOf: false, JSON: false, Map: false, Math: false, NaN: false, Number: false, Object: false, parseFloat: false, parseInt: false, Promise: false, propertyIsEnumerable: false, Proxy: false, RangeError: false, ReferenceError: false, Reflect: false, RegExp: false, Set: false, String: false, Symbol: false, SyntaxError: false, toLocaleString: false, toString: false, TypeError: false, Uint16Array: false, Uint32Array: false, Uint8Array: false, Uint8ClampedArray: false, undefined: false, unescape: false, URIError: false, valueOf: false, WeakMap: false, WeakSet: false }, es2017: { Array: false, ArrayBuffer: false, Atomics: false, Boolean: false, constructor: false, DataView: false, Date: false, decodeURI: false, decodeURIComponent: false, encodeURI: false, encodeURIComponent: false, Error: false, escape: false, eval: false, EvalError: false, Float32Array: false, Float64Array: false, Function: false, hasOwnProperty: false, Infinity: false, Int16Array: false, Int32Array: false, Int8Array: false, isFinite: false, isNaN: false, isPrototypeOf: false, JSON: false, Map: false, Math: false, NaN: false, Number: false, Object: false, parseFloat: false, parseInt: false, Promise: false, propertyIsEnumerable: false, Proxy: false, RangeError: false, ReferenceError: false, Reflect: false, RegExp: false, Set: false, SharedArrayBuffer: false, String: false, Symbol: false, SyntaxError: false, toLocaleString: false, toString: false, TypeError: false, Uint16Array: false, Uint32Array: false, Uint8Array: false, Uint8ClampedArray: false, undefined: false, unescape: false, URIError: false, valueOf: false, WeakMap: false, WeakSet: false }, browser: { AbortController: false, AbortSignal: false, addEventListener: false, alert: false, AnalyserNode: false, Animation: false, AnimationEffectReadOnly: false, AnimationEffectTiming: false, AnimationEffectTimingReadOnly: false, AnimationEvent: false, AnimationPlaybackEvent: false, AnimationTimeline: false, applicationCache: false, ApplicationCache: false, ApplicationCacheErrorEvent: false, atob: false, Attr: false, Audio: false, AudioBuffer: false, AudioBufferSourceNode: false, AudioContext: false, AudioDestinationNode: false, AudioListener: false, AudioNode: false, AudioParam: false, AudioProcessingEvent: false, AudioScheduledSourceNode: false, "AudioWorkletGlobalScope ": false, AudioWorkletNode: false, AudioWorkletProcessor: false, BarProp: false, BaseAudioContext: false, BatteryManager: false, BeforeUnloadEvent: false, BiquadFilterNode: false, Blob: false, BlobEvent: false, blur: false, BroadcastChannel: false, btoa: false, BudgetService: false, ByteLengthQueuingStrategy: false, Cache: false, caches: false, CacheStorage: false, cancelAnimationFrame: false, cancelIdleCallback: false, CanvasCaptureMediaStreamTrack: false, CanvasGradient: false, CanvasPattern: false, CanvasRenderingContext2D: false, ChannelMergerNode: false, ChannelSplitterNode: false, CharacterData: false, clearInterval: false, clearTimeout: false, clientInformation: false, ClipboardEvent: false, close: false, closed: false, CloseEvent: false, Comment: false, CompositionEvent: false, confirm: false, console: false, ConstantSourceNode: false, ConvolverNode: false, CountQueuingStrategy: false, createImageBitmap: false, Credential: false, CredentialsContainer: false, crypto: false, Crypto: false, CryptoKey: false, CSS: false, CSSConditionRule: false, CSSFontFaceRule: false, CSSGroupingRule: false, CSSImportRule: false, CSSKeyframeRule: false, CSSKeyframesRule: false, CSSMediaRule: false, CSSNamespaceRule: false, CSSPageRule: false, CSSRule: false, CSSRuleList: false, CSSStyleDeclaration: false, CSSStyleRule: false, CSSStyleSheet: false, CSSSupportsRule: false, CustomElementRegistry: false, customElements: false, CustomEvent: false, DataTransfer: false, DataTransferItem: false, DataTransferItemList: false, defaultstatus: false, defaultStatus: false, DelayNode: false, DeviceMotionEvent: false, DeviceOrientationEvent: false, devicePixelRatio: false, dispatchEvent: false, document: false, Document: false, DocumentFragment: false, DocumentType: false, DOMError: false, DOMException: false, DOMImplementation: false, DOMMatrix: false, DOMMatrixReadOnly: false, DOMParser: false, DOMPoint: false, DOMPointReadOnly: false, DOMQuad: false, DOMRect: false, DOMRectReadOnly: false, DOMStringList: false, DOMStringMap: false, DOMTokenList: false, DragEvent: false, DynamicsCompressorNode: false, Element: false, ErrorEvent: false, event: false, Event: false, EventSource: false, EventTarget: false, external: false, fetch: false, File: false, FileList: false, FileReader: false, find: false, focus: false, FocusEvent: false, FontFace: false, FontFaceSetLoadEvent: false, FormData: false, frameElement: false, frames: false, GainNode: false, Gamepad: false, GamepadButton: false, GamepadEvent: false, getComputedStyle: false, getSelection: false, HashChangeEvent: false, Headers: false, history: false, History: false, HTMLAllCollection: false, HTMLAnchorElement: false, HTMLAreaElement: false, HTMLAudioElement: false, HTMLBaseElement: false, HTMLBodyElement: false, HTMLBRElement: false, HTMLButtonElement: false, HTMLCanvasElement: false, HTMLCollection: false, HTMLContentElement: false, HTMLDataElement: false, HTMLDataListElement: false, HTMLDetailsElement: false, HTMLDialogElement: false, HTMLDirectoryElement: false, HTMLDivElement: false, HTMLDListElement: false, HTMLDocument: false, HTMLElement: false, HTMLEmbedElement: false, HTMLFieldSetElement: false, HTMLFontElement: false, HTMLFormControlsCollection: false, HTMLFormElement: false, HTMLFrameElement: false, HTMLFrameSetElement: false, HTMLHeadElement: false, HTMLHeadingElement: false, HTMLHRElement: false, HTMLHtmlElement: false, HTMLIFrameElement: false, HTMLImageElement: false, HTMLInputElement: false, HTMLLabelElement: false, HTMLLegendElement: false, HTMLLIElement: false, HTMLLinkElement: false, HTMLMapElement: false, HTMLMarqueeElement: false, HTMLMediaElement: false, HTMLMenuElement: false, HTMLMetaElement: false, HTMLMeterElement: false, HTMLModElement: false, HTMLObjectElement: false, HTMLOListElement: false, HTMLOptGroupElement: false, HTMLOptionElement: false, HTMLOptionsCollection: false, HTMLOutputElement: false, HTMLParagraphElement: false, HTMLParamElement: false, HTMLPictureElement: false, HTMLPreElement: false, HTMLProgressElement: false, HTMLQuoteElement: false, HTMLScriptElement: false, HTMLSelectElement: false, HTMLShadowElement: false, HTMLSlotElement: false, HTMLSourceElement: false, HTMLSpanElement: false, HTMLStyleElement: false, HTMLTableCaptionElement: false, HTMLTableCellElement: false, HTMLTableColElement: false, HTMLTableElement: false, HTMLTableRowElement: false, HTMLTableSectionElement: false, HTMLTemplateElement: false, HTMLTextAreaElement: false, HTMLTimeElement: false, HTMLTitleElement: false, HTMLTrackElement: false, HTMLUListElement: false, HTMLUnknownElement: false, HTMLVideoElement: false, IDBCursor: false, IDBCursorWithValue: false, IDBDatabase: false, IDBFactory: false, IDBIndex: false, IDBKeyRange: false, IDBObjectStore: false, IDBOpenDBRequest: false, IDBRequest: false, IDBTransaction: false, IDBVersionChangeEvent: false, IdleDeadline: false, IIRFilterNode: false, Image: false, ImageBitmap: false, ImageBitmapRenderingContext: false, ImageCapture: false, ImageData: false, indexedDB: false, innerHeight: false, innerWidth: false, InputEvent: false, IntersectionObserver: false, IntersectionObserverEntry: false, Intl: false, isSecureContext: false, KeyboardEvent: false, KeyframeEffect: false, KeyframeEffectReadOnly: false, length: false, localStorage: false, location: true, Location: false, locationbar: false, matchMedia: false, MediaDeviceInfo: false, MediaDevices: false, MediaElementAudioSourceNode: false, MediaEncryptedEvent: false, MediaError: false, MediaKeyMessageEvent: false, MediaKeySession: false, MediaKeyStatusMap: false, MediaKeySystemAccess: false, MediaList: false, MediaQueryList: false, MediaQueryListEvent: false, MediaRecorder: false, MediaSettingsRange: false, MediaSource: false, MediaStream: false, MediaStreamAudioDestinationNode: false, MediaStreamAudioSourceNode: false, MediaStreamEvent: false, MediaStreamTrack: false, MediaStreamTrackEvent: false, menubar: false, MessageChannel: false, MessageEvent: false, MessagePort: false, MIDIAccess: false, MIDIConnectionEvent: false, MIDIInput: false, MIDIInputMap: false, MIDIMessageEvent: false, MIDIOutput: false, MIDIOutputMap: false, MIDIPort: false, MimeType: false, MimeTypeArray: false, MouseEvent: false, moveBy: false, moveTo: false, MutationEvent: false, MutationObserver: false, MutationRecord: false, name: false, NamedNodeMap: false, NavigationPreloadManager: false, navigator: false, Navigator: false, NetworkInformation: false, Node: false, NodeFilter: false, NodeIterator: false, NodeList: false, Notification: false, OfflineAudioCompletionEvent: false, OfflineAudioContext: false, offscreenBuffering: false, OffscreenCanvas: true, onabort: true, onafterprint: true, onanimationend: true, onanimationiteration: true, onanimationstart: true, onappinstalled: true, onauxclick: true, onbeforeinstallprompt: true, onbeforeprint: true, onbeforeunload: true, onblur: true, oncancel: true, oncanplay: true, oncanplaythrough: true, onchange: true, onclick: true, onclose: true, oncontextmenu: true, oncuechange: true, ondblclick: true, ondevicemotion: true, ondeviceorientation: true, ondeviceorientationabsolute: true, ondrag: true, ondragend: true, ondragenter: true, ondragleave: true, ondragover: true, ondragstart: true, ondrop: true, ondurationchange: true, onemptied: true, onended: true, onerror: true, onfocus: true, ongotpointercapture: true, onhashchange: true, oninput: true, oninvalid: true, onkeydown: true, onkeypress: true, onkeyup: true, onlanguagechange: true, onload: true, onloadeddata: true, onloadedmetadata: true, onloadstart: true, onlostpointercapture: true, onmessage: true, onmessageerror: true, onmousedown: true, onmouseenter: true, onmouseleave: true, onmousemove: true, onmouseout: true, onmouseover: true, onmouseup: true, onmousewheel: true, onoffline: true, ononline: true, onpagehide: true, onpageshow: true, onpause: true, onplay: true, onplaying: true, onpointercancel: true, onpointerdown: true, onpointerenter: true, onpointerleave: true, onpointermove: true, onpointerout: true, onpointerover: true, onpointerup: true, onpopstate: true, onprogress: true, onratechange: true, onrejectionhandled: true, onreset: true, onresize: true, onscroll: true, onsearch: true, onseeked: true, onseeking: true, onselect: true, onstalled: true, onstorage: true, onsubmit: true, onsuspend: true, ontimeupdate: true, ontoggle: true, ontransitionend: true, onunhandledrejection: true, onunload: true, onvolumechange: true, onwaiting: true, onwheel: true, open: false, openDatabase: false, opener: false, Option: false, origin: false, OscillatorNode: false, outerHeight: false, outerWidth: false, PageTransitionEvent: false, pageXOffset: false, pageYOffset: false, PannerNode: false, parent: false, Path2D: false, PaymentAddress: false, PaymentRequest: false, PaymentRequestUpdateEvent: false, PaymentResponse: false, performance: false, Performance: false, PerformanceEntry: false, PerformanceLongTaskTiming: false, PerformanceMark: false, PerformanceMeasure: false, PerformanceNavigation: false, PerformanceNavigationTiming: false, PerformanceObserver: false, PerformanceObserverEntryList: false, PerformancePaintTiming: false, PerformanceResourceTiming: false, PerformanceTiming: false, PeriodicWave: false, Permissions: false, PermissionStatus: false, personalbar: false, PhotoCapabilities: false, Plugin: false, PluginArray: false, PointerEvent: false, PopStateEvent: false, postMessage: false, Presentation: false, PresentationAvailability: false, PresentationConnection: false, PresentationConnectionAvailableEvent: false, PresentationConnectionCloseEvent: false, PresentationConnectionList: false, PresentationReceiver: false, PresentationRequest: false, print: false, ProcessingInstruction: false, ProgressEvent: false, PromiseRejectionEvent: false, prompt: false, PushManager: false, PushSubscription: false, PushSubscriptionOptions: false, queueMicrotask: false, RadioNodeList: false, Range: false, ReadableStream: false, registerProcessor: false, RemotePlayback: false, removeEventListener: false, Request: false, requestAnimationFrame: false, requestIdleCallback: false, resizeBy: false, ResizeObserver: false, ResizeObserverEntry: false, resizeTo: false, Response: false, RTCCertificate: false, RTCDataChannel: false, RTCDataChannelEvent: false, RTCDtlsTransport: false, RTCIceCandidate: false, RTCIceGatherer: false, RTCIceTransport: false, RTCPeerConnection: false, RTCPeerConnectionIceEvent: false, RTCRtpContributingSource: false, RTCRtpReceiver: false, RTCRtpSender: false, RTCSctpTransport: false, RTCSessionDescription: false, RTCStatsReport: false, RTCTrackEvent: false, screen: false, Screen: false, screenLeft: false, ScreenOrientation: false, screenTop: false, screenX: false, screenY: false, ScriptProcessorNode: false, scroll: false, scrollbars: false, scrollBy: false, scrollTo: false, scrollX: false, scrollY: false, SecurityPolicyViolationEvent: false, Selection: false, self: false, ServiceWorker: false, ServiceWorkerContainer: false, ServiceWorkerRegistration: false, sessionStorage: false, setInterval: false, setTimeout: false, ShadowRoot: false, SharedWorker: false, SourceBuffer: false, SourceBufferList: false, speechSynthesis: false, SpeechSynthesisEvent: false, SpeechSynthesisUtterance: false, StaticRange: false, status: false, statusbar: false, StereoPannerNode: false, stop: false, Storage: false, StorageEvent: false, StorageManager: false, styleMedia: false, StyleSheet: false, StyleSheetList: false, SubtleCrypto: false, SVGAElement: false, SVGAngle: false, SVGAnimatedAngle: false, SVGAnimatedBoolean: false, SVGAnimatedEnumeration: false, SVGAnimatedInteger: false, SVGAnimatedLength: false, SVGAnimatedLengthList: false, SVGAnimatedNumber: false, SVGAnimatedNumberList: false, SVGAnimatedPreserveAspectRatio: false, SVGAnimatedRect: false, SVGAnimatedString: false, SVGAnimatedTransformList: false, SVGAnimateElement: false, SVGAnimateMotionElement: false, SVGAnimateTransformElement: false, SVGAnimationElement: false, SVGCircleElement: false, SVGClipPathElement: false, SVGComponentTransferFunctionElement: false, SVGDefsElement: false, SVGDescElement: false, SVGDiscardElement: false, SVGElement: false, SVGEllipseElement: false, SVGFEBlendElement: false, SVGFEColorMatrixElement: false, SVGFEComponentTransferElement: false, SVGFECompositeElement: false, SVGFEConvolveMatrixElement: false, SVGFEDiffuseLightingElement: false, SVGFEDisplacementMapElement: false, SVGFEDistantLightElement: false, SVGFEDropShadowElement: false, SVGFEFloodElement: false, SVGFEFuncAElement: false, SVGFEFuncBElement: false, SVGFEFuncGElement: false, SVGFEFuncRElement: false, SVGFEGaussianBlurElement: false, SVGFEImageElement: false, SVGFEMergeElement: false, SVGFEMergeNodeElement: false, SVGFEMorphologyElement: false, SVGFEOffsetElement: false, SVGFEPointLightElement: false, SVGFESpecularLightingElement: false, SVGFESpotLightElement: false, SVGFETileElement: false, SVGFETurbulenceElement: false, SVGFilterElement: false, SVGForeignObjectElement: false, SVGGElement: false, SVGGeometryElement: false, SVGGradientElement: false, SVGGraphicsElement: false, SVGImageElement: false, SVGLength: false, SVGLengthList: false, SVGLinearGradientElement: false, SVGLineElement: false, SVGMarkerElement: false, SVGMaskElement: false, SVGMatrix: false, SVGMetadataElement: false, SVGMPathElement: false, SVGNumber: false, SVGNumberList: false, SVGPathElement: false, SVGPatternElement: false, SVGPoint: false, SVGPointList: false, SVGPolygonElement: false, SVGPolylineElement: false, SVGPreserveAspectRatio: false, SVGRadialGradientElement: false, SVGRect: false, SVGRectElement: false, SVGScriptElement: false, SVGSetElement: false, SVGStopElement: false, SVGStringList: false, SVGStyleElement: false, SVGSVGElement: false, SVGSwitchElement: false, SVGSymbolElement: false, SVGTextContentElement: false, SVGTextElement: false, SVGTextPathElement: false, SVGTextPositioningElement: false, SVGTitleElement: false, SVGTransform: false, SVGTransformList: false, SVGTSpanElement: false, SVGUnitTypes: false, SVGUseElement: false, SVGViewElement: false, TaskAttributionTiming: false, Text: false, TextDecoder: false, TextEncoder: false, TextEvent: false, TextMetrics: false, TextTrack: false, TextTrackCue: false, TextTrackCueList: false, TextTrackList: false, TimeRanges: false, toolbar: false, top: false, Touch: false, TouchEvent: false, TouchList: false, TrackEvent: false, TransitionEvent: false, TreeWalker: false, UIEvent: false, URL: false, URLSearchParams: false, ValidityState: false, visualViewport: false, VisualViewport: false, VTTCue: false, WaveShaperNode: false, WebAssembly: false, WebGL2RenderingContext: false, WebGLActiveInfo: false, WebGLBuffer: false, WebGLContextEvent: false, WebGLFramebuffer: false, WebGLProgram: false, WebGLQuery: false, WebGLRenderbuffer: false, WebGLRenderingContext: false, WebGLSampler: false, WebGLShader: false, WebGLShaderPrecisionFormat: false, WebGLSync: false, WebGLTexture: false, WebGLTransformFeedback: false, WebGLUniformLocation: false, WebGLVertexArrayObject: false, WebSocket: false, WheelEvent: false, window: false, Window: false, Worker: false, WritableStream: false, XMLDocument: false, XMLHttpRequest: false, XMLHttpRequestEventTarget: false, XMLHttpRequestUpload: false, XMLSerializer: false, XPathEvaluator: false, XPathExpression: false, XPathResult: false, XSLTProcessor: false }, worker: { addEventListener: false, applicationCache: false, atob: false, Blob: false, BroadcastChannel: false, btoa: false, Cache: false, caches: false, clearInterval: false, clearTimeout: false, close: true, console: false, fetch: false, FileReaderSync: false, FormData: false, Headers: false, IDBCursor: false, IDBCursorWithValue: false, IDBDatabase: false, IDBFactory: false, IDBIndex: false, IDBKeyRange: false, IDBObjectStore: false, IDBOpenDBRequest: false, IDBRequest: false, IDBTransaction: false, IDBVersionChangeEvent: false, ImageData: false, importScripts: true, indexedDB: false, location: false, MessageChannel: false, MessagePort: false, name: false, navigator: false, Notification: false, onclose: true, onconnect: true, onerror: true, onlanguagechange: true, onmessage: true, onoffline: true, ononline: true, onrejectionhandled: true, onunhandledrejection: true, performance: false, Performance: false, PerformanceEntry: false, PerformanceMark: false, PerformanceMeasure: false, PerformanceNavigation: false, PerformanceResourceTiming: false, PerformanceTiming: false, postMessage: true, Promise: false, queueMicrotask: false, removeEventListener: false, Request: false, Response: false, self: true, ServiceWorkerRegistration: false, setInterval: false, setTimeout: false, TextDecoder: false, TextEncoder: false, URL: false, URLSearchParams: false, WebSocket: false, Worker: false, WorkerGlobalScope: false, XMLHttpRequest: false }, node: { __dirname: false, __filename: false, Buffer: false, clearImmediate: false, clearInterval: false, clearTimeout: false, console: false, exports: true, global: false, Intl: false, module: false, process: false, queueMicrotask: false, require: false, setImmediate: false, setInterval: false, setTimeout: false, TextDecoder: false, TextEncoder: false, URL: false, URLSearchParams: false }, commonjs: { exports: true, global: false, module: false, require: false }, amd: { define: false, require: false }, mocha: { after: false, afterEach: false, before: false, beforeEach: false, context: false, describe: false, it: false, mocha: false, run: false, setup: false, specify: false, suite: false, suiteSetup: false, suiteTeardown: false, teardown: false, test: false, xcontext: false, xdescribe: false, xit: false, xspecify: false }, jasmine: { afterAll: false, afterEach: false, beforeAll: false, beforeEach: false, describe: false, expect: false, fail: false, fdescribe: false, fit: false, it: false, jasmine: false, pending: false, runs: false, spyOn: false, spyOnProperty: false, waits: false, waitsFor: false, xdescribe: false, xit: false }, jest: { afterAll: false, afterEach: false, beforeAll: false, beforeEach: false, describe: false, expect: false, fdescribe: false, fit: false, it: false, jest: false, pit: false, require: false, test: false, xdescribe: false, xit: false, xtest: false }, qunit: { asyncTest: false, deepEqual: false, equal: false, expect: false, module: false, notDeepEqual: false, notEqual: false, notOk: false, notPropEqual: false, notStrictEqual: false, ok: false, propEqual: false, QUnit: false, raises: false, start: false, stop: false, strictEqual: false, test: false, throws: false }, phantomjs: { console: true, exports: true, phantom: true, require: true, WebPage: true }, couch: { emit: false, exports: false, getRow: false, log: false, module: false, provides: false, require: false, respond: false, send: false, start: false, sum: false }, rhino: { defineClass: false, deserialize: false, gc: false, help: false, importClass: false, importPackage: false, java: false, load: false, loadClass: false, Packages: false, print: false, quit: false, readFile: false, readUrl: false, runCommand: false, seal: false, serialize: false, spawn: false, sync: false, toint32: false, version: false }, nashorn: { __DIR__: false, __FILE__: false, __LINE__: false, com: false, edu: false, exit: false, java: false, Java: false, javafx: false, JavaImporter: false, javax: false, JSAdapter: false, load: false, loadWithNewGlobal: false, org: false, Packages: false, print: false, quit: false }, wsh: { ActiveXObject: true, Enumerator: true, GetObject: true, ScriptEngine: true, ScriptEngineBuildVersion: true, ScriptEngineMajorVersion: true, ScriptEngineMinorVersion: true, VBArray: true, WScript: true, WSH: true, XDomainRequest: true }, jquery: { $: false, jQuery: false }, yui: { YAHOO: false, YAHOO_config: false, YUI: false, YUI_config: false }, shelljs: { cat: false, cd: false, chmod: false, config: false, cp: false, dirs: false, echo: false, env: false, error: false, exec: false, exit: false, find: false, grep: false, ln: false, ls: false, mkdir: false, mv: false, popd: false, pushd: false, pwd: false, rm: false, sed: false, set: false, target: false, tempdir: false, test: false, touch: false, which: false }, prototypejs: { $: false, $$: false, $A: false, $break: false, $continue: false, $F: false, $H: false, $R: false, $w: false, Abstract: false, Ajax: false, Autocompleter: false, Builder: false, Class: false, Control: false, Draggable: false, Draggables: false, Droppables: false, Effect: false, Element: false, Enumerable: false, Event: false, Field: false, Form: false, Hash: false, Insertion: false, ObjectRange: false, PeriodicalExecuter: false, Position: false, Prototype: false, Scriptaculous: false, Selector: false, Sortable: false, SortableObserver: false, Sound: false, Template: false, Toggle: false, Try: false }, meteor: { _: false, $: false, Accounts: false, AccountsClient: false, AccountsCommon: false, AccountsServer: false, App: false, Assets: false, Blaze: false, check: false, Cordova: false, DDP: false, DDPRateLimiter: false, DDPServer: false, Deps: false, EJSON: false, Email: false, HTTP: false, Log: false, Match: false, Meteor: false, Mongo: false, MongoInternals: false, Npm: false, Package: false, Plugin: false, process: false, Random: false, ReactiveDict: false, ReactiveVar: false, Router: false, ServiceConfiguration: false, Session: false, share: false, Spacebars: false, Template: false, Tinytest: false, Tracker: false, UI: false, Utils: false, WebApp: false, WebAppInternals: false }, mongo: { _isWindows: false, _rand: false, BulkWriteResult: false, cat: false, cd: false, connect: false, db: false, getHostName: false, getMemInfo: false, hostname: false, ISODate: false, listFiles: false, load: false, ls: false, md5sumFile: false, mkdir: false, Mongo: false, NumberInt: false, NumberLong: false, ObjectId: false, PlanCache: false, print: false, printjson: false, pwd: false, quit: false, removeFile: false, rs: false, sh: false, UUID: false, version: false, WriteResult: false }, applescript: { $: false, Application: false, Automation: false, console: false, delay: false, Library: false, ObjC: false, ObjectSpecifier: false, Path: false, Progress: false, Ref: false }, serviceworker: { addEventListener: false, applicationCache: false, atob: false, Blob: false, BroadcastChannel: false, btoa: false, Cache: false, caches: false, CacheStorage: false, clearInterval: false, clearTimeout: false, Client: false, clients: false, Clients: false, close: true, console: false, ExtendableEvent: false, ExtendableMessageEvent: false, fetch: false, FetchEvent: false, FileReaderSync: false, FormData: false, Headers: false, IDBCursor: false, IDBCursorWithValue: false, IDBDatabase: false, IDBFactory: false, IDBIndex: false, IDBKeyRange: false, IDBObjectStore: false, IDBOpenDBRequest: false, IDBRequest: false, IDBTransaction: false, IDBVersionChangeEvent: false, ImageData: false, importScripts: false, indexedDB: false, location: false, MessageChannel: false, MessagePort: false, name: false, navigator: false, Notification: false, onclose: true, onconnect: true, onerror: true, onfetch: true, oninstall: true, onlanguagechange: true, onmessage: true, onmessageerror: true, onnotificationclick: true, onnotificationclose: true, onoffline: true, ononline: true, onpush: true, onpushsubscriptionchange: true, onrejectionhandled: true, onsync: true, onunhandledrejection: true, performance: false, Performance: false, PerformanceEntry: false, PerformanceMark: false, PerformanceMeasure: false, PerformanceNavigation: false, PerformanceResourceTiming: false, PerformanceTiming: false, postMessage: true, Promise: false, queueMicrotask: false, registration: false, removeEventListener: false, Request: false, Response: false, self: false, ServiceWorker: false, ServiceWorkerContainer: false, ServiceWorkerGlobalScope: false, ServiceWorkerMessageEvent: false, ServiceWorkerRegistration: false, setInterval: false, setTimeout: false, skipWaiting: false, TextDecoder: false, TextEncoder: false, URL: false, URLSearchParams: false, WebSocket: false, WindowClient: false, Worker: false, WorkerGlobalScope: false, XMLHttpRequest: false }, atomtest: { advanceClock: false, fakeClearInterval: false, fakeClearTimeout: false, fakeSetInterval: false, fakeSetTimeout: false, resetTimeouts: false, waitsForPromise: false }, embertest: { andThen: false, click: false, currentPath: false, currentRouteName: false, currentURL: false, fillIn: false, find: false, findAll: false, findWithAssert: false, keyEvent: false, pauseTest: false, resumeTest: false, triggerEvent: false, visit: false, wait: false }, protractor: { $: false, $$: false, browser: false, by: false, By: false, DartObject: false, element: false, protractor: false }, "shared-node-browser": { clearInterval: false, clearTimeout: false, console: false, setInterval: false, setTimeout: false, URL: false, URLSearchParams: false }, webextensions: { browser: false, chrome: false, opr: false }, greasemonkey: { cloneInto: false, createObjectIn: false, exportFunction: false, GM: false, GM_addStyle: false, GM_deleteValue: false, GM_getResourceText: false, GM_getResourceURL: false, GM_getValue: false, GM_info: false, GM_listValues: false, GM_log: false, GM_openInTab: false, GM_registerMenuCommand: false, GM_setClipboard: false, GM_setValue: false, GM_xmlhttpRequest: false, unsafeWindow: false }, devtools: { $: false, $_: false, $$: false, $0: false, $1: false, $2: false, $3: false, $4: false, $x: false, chrome: false, clear: false, copy: false, debug: false, dir: false, dirxml: false, getEventListeners: false, inspect: false, keys: false, monitor: false, monitorEvents: false, profile: false, profileEnd: false, queryObjects: false, table: false, undebug: false, unmonitor: false, unmonitorEvents: false, values: false } }; } }); // ../../node_modules/globals/index.js var require_globals2 = __commonJS({ "../../node_modules/globals/index.js"(exports2, module2) { "use strict"; module2.exports = require_globals(); } }); // node_modules/@babel/helpers/node_modules/@babel/traverse/lib/cache.js var require_cache = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/traverse/lib/cache.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.clear = clear; exports2.clearPath = clearPath; exports2.clearScope = clearScope; exports2.getCachedPaths = getCachedPaths; exports2.getOrCreateCachedPaths = getOrCreateCachedPaths; exports2.scope = exports2.path = void 0; var pathsCache = exports2.path = /* @__PURE__ */ new WeakMap(); var scope = exports2.scope = /* @__PURE__ */ new WeakMap(); function clear() { clearPath(); clearScope(); } function clearPath() { exports2.path = pathsCache = /* @__PURE__ */ new WeakMap(); } function clearScope() { exports2.scope = scope = /* @__PURE__ */ new WeakMap(); } var nullHub = Object.freeze({}); function getCachedPaths(hub, parent) { var _pathsCache$get, _hub; { hub = null; } return (_pathsCache$get = pathsCache.get((_hub = hub) != null ? _hub : nullHub)) == null ? void 0 : _pathsCache$get.get(parent); } function getOrCreateCachedPaths(hub, parent) { var _hub2, _hub3; { hub = null; } let parents = pathsCache.get((_hub2 = hub) != null ? _hub2 : nullHub); if (!parents) pathsCache.set((_hub3 = hub) != null ? _hub3 : nullHub, parents = /* @__PURE__ */ new WeakMap()); let paths = parents.get(parent); if (!paths) parents.set(parent, paths = /* @__PURE__ */ new Map()); return paths; } } }); // node_modules/@babel/helpers/node_modules/@babel/traverse/lib/scope/index.js var require_scope = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/traverse/lib/scope/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = void 0; var _renamer = require_renamer(); var _index = require_lib6(); var _binding = require_binding(); var _globals4 = require_globals2(); var _t = require("@babel/types"); var t6 = _t; var _cache = require_cache(); var _visitors = require_visitors(); var { NOT_LOCAL_BINDING, assignmentExpression: assignmentExpression2, callExpression: callExpression4, cloneNode: cloneNode2, getBindingIdentifiers, identifier: identifier4, isArrayExpression, isBinary, isCallExpression, isClass, isClassBody, isClassDeclaration, isExportAllDeclaration, isExportDefaultDeclaration, isExportNamedDeclaration, isFunctionDeclaration, isIdentifier, isImportDeclaration, isLiteral, isMemberExpression: isMemberExpression2, isMethod, isModuleSpecifier, isNullLiteral, isObjectExpression, isProperty, isPureish, isRegExpLiteral, isSuper, isTaggedTemplateExpression, isTemplateLiteral, isThisExpression, isUnaryExpression, isVariableDeclaration: isVariableDeclaration2, expressionStatement: expressionStatement2, matchesPattern, memberExpression: memberExpression2, numericLiteral: numericLiteral2, toIdentifier, variableDeclaration: variableDeclaration4, variableDeclarator: variableDeclarator4, isRecordExpression, isTupleExpression, isObjectProperty, isTopicReference, isMetaProperty, isPrivateName, isExportDeclaration, buildUndefinedNode, sequenceExpression: sequenceExpression2 } = _t; function gatherNodeParts(node, parts) { switch (node == null ? void 0 : node.type) { default: if (isImportDeclaration(node) || isExportDeclaration(node)) { var _node$specifiers; if ((isExportAllDeclaration(node) || isExportNamedDeclaration(node) || isImportDeclaration(node)) && node.source) { gatherNodeParts(node.source, parts); } else if ((isExportNamedDeclaration(node) || isImportDeclaration(node)) && (_node$specifiers = node.specifiers) != null && _node$specifiers.length) { for (const e of node.specifiers) gatherNodeParts(e, parts); } else if ((isExportDefaultDeclaration(node) || isExportNamedDeclaration(node)) && node.declaration) { gatherNodeParts(node.declaration, parts); } } else if (isModuleSpecifier(node)) { gatherNodeParts(node.local, parts); } else if (isLiteral(node) && !isNullLiteral(node) && !isRegExpLiteral(node) && !isTemplateLiteral(node)) { parts.push(node.value); } break; case "MemberExpression": case "OptionalMemberExpression": case "JSXMemberExpression": gatherNodeParts(node.object, parts); gatherNodeParts(node.property, parts); break; case "Identifier": case "JSXIdentifier": parts.push(node.name); break; case "CallExpression": case "OptionalCallExpression": case "NewExpression": gatherNodeParts(node.callee, parts); break; case "ObjectExpression": case "ObjectPattern": for (const e of node.properties) { gatherNodeParts(e, parts); } break; case "SpreadElement": case "RestElement": gatherNodeParts(node.argument, parts); break; case "ObjectProperty": case "ObjectMethod": case "ClassProperty": case "ClassMethod": case "ClassPrivateProperty": case "ClassPrivateMethod": gatherNodeParts(node.key, parts); break; case "ThisExpression": parts.push("this"); break; case "Super": parts.push("super"); break; case "Import": parts.push("import"); break; case "DoExpression": parts.push("do"); break; case "YieldExpression": parts.push("yield"); gatherNodeParts(node.argument, parts); break; case "AwaitExpression": parts.push("await"); gatherNodeParts(node.argument, parts); break; case "AssignmentExpression": gatherNodeParts(node.left, parts); break; case "VariableDeclarator": gatherNodeParts(node.id, parts); break; case "FunctionExpression": case "FunctionDeclaration": case "ClassExpression": case "ClassDeclaration": gatherNodeParts(node.id, parts); break; case "PrivateName": gatherNodeParts(node.id, parts); break; case "ParenthesizedExpression": gatherNodeParts(node.expression, parts); break; case "UnaryExpression": case "UpdateExpression": gatherNodeParts(node.argument, parts); break; case "MetaProperty": gatherNodeParts(node.meta, parts); gatherNodeParts(node.property, parts); break; case "JSXElement": gatherNodeParts(node.openingElement, parts); break; case "JSXOpeningElement": gatherNodeParts(node.name, parts); break; case "JSXFragment": gatherNodeParts(node.openingFragment, parts); break; case "JSXOpeningFragment": parts.push("Fragment"); break; case "JSXNamespacedName": gatherNodeParts(node.namespace, parts); gatherNodeParts(node.name, parts); break; } } var collectorVisitor = { ForStatement(path) { const declar = path.get("init"); if (declar.isVar()) { const { scope } = path; const parentScope = scope.getFunctionParent() || scope.getProgramParent(); parentScope.registerBinding("var", declar); } }, Declaration(path) { if (path.isBlockScoped()) return; if (path.isImportDeclaration()) return; if (path.isExportDeclaration()) return; const parent = path.scope.getFunctionParent() || path.scope.getProgramParent(); parent.registerDeclaration(path); }, ImportDeclaration(path) { const parent = path.scope.getBlockParent(); parent.registerDeclaration(path); }, ReferencedIdentifier(path, state) { state.references.push(path); }, ForXStatement(path, state) { const left = path.get("left"); if (left.isPattern() || left.isIdentifier()) { state.constantViolations.push(path); } else if (left.isVar()) { const { scope } = path; const parentScope = scope.getFunctionParent() || scope.getProgramParent(); parentScope.registerBinding("var", left); } }, ExportDeclaration: { exit(path) { const { node, scope } = path; if (isExportAllDeclaration(node)) return; const declar = node.declaration; if (isClassDeclaration(declar) || isFunctionDeclaration(declar)) { const id = declar.id; if (!id) return; const binding = scope.getBinding(id.name); binding == null || binding.reference(path); } else if (isVariableDeclaration2(declar)) { for (const decl of declar.declarations) { for (const name of Object.keys(getBindingIdentifiers(decl))) { const binding = scope.getBinding(name); binding == null || binding.reference(path); } } } } }, LabeledStatement(path) { path.scope.getBlockParent().registerDeclaration(path); }, AssignmentExpression(path, state) { state.assignments.push(path); }, UpdateExpression(path, state) { state.constantViolations.push(path); }, UnaryExpression(path, state) { if (path.node.operator === "delete") { state.constantViolations.push(path); } }, BlockScoped(path) { let scope = path.scope; if (scope.path === path) scope = scope.parent; const parent = scope.getBlockParent(); parent.registerDeclaration(path); if (path.isClassDeclaration() && path.node.id) { const id = path.node.id; const name = id.name; path.scope.bindings[name] = path.scope.parent.getBinding(name); } }, CatchClause(path) { path.scope.registerBinding("let", path); }, Function(path) { const params = path.get("params"); for (const param of params) { path.scope.registerBinding("param", param); } if (path.isFunctionExpression() && path.node.id && !path.node.id[NOT_LOCAL_BINDING]) { path.scope.registerBinding("local", path.get("id"), path); } }, ClassExpression(path) { if (path.node.id && !path.node.id[NOT_LOCAL_BINDING]) { path.scope.registerBinding("local", path.get("id"), path); } }, TSTypeAnnotation(path) { path.skip(); } }; var uid = 0; var Scope = class _Scope { constructor(path) { this.uid = void 0; this.path = void 0; this.block = void 0; this.inited = void 0; this.labels = void 0; this.bindings = void 0; this.references = void 0; this.globals = void 0; this.uids = void 0; this.data = void 0; this.crawling = void 0; const { node } = path; const cached2 = _cache.scope.get(node); if ((cached2 == null ? void 0 : cached2.path) === path) { return cached2; } _cache.scope.set(node, this); this.uid = uid++; this.block = node; this.path = path; this.labels = /* @__PURE__ */ new Map(); this.inited = false; } get parent() { var _parent; let parent, path = this.path; do { var _path; const shouldSkip = path.key === "key" || path.listKey === "decorators"; path = path.parentPath; if (shouldSkip && path.isMethod()) path = path.parentPath; if ((_path = path) != null && _path.isScope()) parent = path; } while (path && !parent); return (_parent = parent) == null ? void 0 : _parent.scope; } generateDeclaredUidIdentifier(name) { const id = this.generateUidIdentifier(name); this.push({ id }); return cloneNode2(id); } generateUidIdentifier(name) { return identifier4(this.generateUid(name)); } generateUid(name = "temp") { name = toIdentifier(name).replace(/^_+/, "").replace(/\d+$/g, ""); let uid2; let i = 1; do { uid2 = `_${name}`; if (i > 1) uid2 += i; i++; } while (this.hasLabel(uid2) || this.hasBinding(uid2) || this.hasGlobal(uid2) || this.hasReference(uid2)); const program = this.getProgramParent(); program.references[uid2] = true; program.uids[uid2] = true; return uid2; } generateUidBasedOnNode(node, defaultName) { const parts = []; gatherNodeParts(node, parts); let id = parts.join("$"); id = id.replace(/^_/, "") || defaultName || "ref"; return this.generateUid(id.slice(0, 20)); } generateUidIdentifierBasedOnNode(node, defaultName) { return identifier4(this.generateUidBasedOnNode(node, defaultName)); } isStatic(node) { if (isThisExpression(node) || isSuper(node) || isTopicReference(node)) { return true; } if (isIdentifier(node)) { const binding = this.getBinding(node.name); if (binding) { return binding.constant; } else { return this.hasBinding(node.name); } } return false; } maybeGenerateMemoised(node, dontPush) { if (this.isStatic(node)) { return null; } else { const id = this.generateUidIdentifierBasedOnNode(node); if (!dontPush) { this.push({ id }); return cloneNode2(id); } return id; } } checkBlockScopedCollisions(local, kind, name, id) { if (kind === "param") return; if (local.kind === "local") return; const duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && kind === "const"; if (duplicate) { throw this.path.hub.buildError(id, `Duplicate declaration "${name}"`, TypeError); } } rename(oldName, newName) { const binding = this.getBinding(oldName); if (binding) { newName || (newName = this.generateUidIdentifier(oldName).name); const renamer = new _renamer.default(binding, oldName, newName); { renamer.rename(arguments[2]); } } } dump() { const sep = "-".repeat(60); console.log(sep); let scope = this; do { console.log("#", scope.block.type); for (const name of Object.keys(scope.bindings)) { const binding = scope.bindings[name]; console.log(" -", name, { constant: binding.constant, references: binding.references, violations: binding.constantViolations.length, kind: binding.kind }); } } while (scope = scope.parent); console.log(sep); } hasLabel(name) { return !!this.getLabel(name); } getLabel(name) { return this.labels.get(name); } registerLabel(path) { this.labels.set(path.node.label.name, path); } registerDeclaration(path) { if (path.isLabeledStatement()) { this.registerLabel(path); } else if (path.isFunctionDeclaration()) { this.registerBinding("hoisted", path.get("id"), path); } else if (path.isVariableDeclaration()) { const declarations = path.get("declarations"); const { kind } = path.node; for (const declar of declarations) { this.registerBinding(kind === "using" || kind === "await using" ? "const" : kind, declar); } } else if (path.isClassDeclaration()) { if (path.node.declare) return; this.registerBinding("let", path); } else if (path.isImportDeclaration()) { const isTypeDeclaration = path.node.importKind === "type" || path.node.importKind === "typeof"; const specifiers = path.get("specifiers"); for (const specifier of specifiers) { const isTypeSpecifier = isTypeDeclaration || specifier.isImportSpecifier() && (specifier.node.importKind === "type" || specifier.node.importKind === "typeof"); this.registerBinding(isTypeSpecifier ? "unknown" : "module", specifier); } } else if (path.isExportDeclaration()) { const declar = path.get("declaration"); if (declar.isClassDeclaration() || declar.isFunctionDeclaration() || declar.isVariableDeclaration()) { this.registerDeclaration(declar); } } else { this.registerBinding("unknown", path); } } buildUndefinedNode() { return buildUndefinedNode(); } registerConstantViolation(path) { const ids = path.getAssignmentIdentifiers(); for (const name of Object.keys(ids)) { var _this$getBinding; (_this$getBinding = this.getBinding(name)) == null || _this$getBinding.reassign(path); } } registerBinding(kind, path, bindingPath = path) { if (!kind) throw new ReferenceError("no `kind`"); if (path.isVariableDeclaration()) { const declarators = path.get("declarations"); for (const declar of declarators) { this.registerBinding(kind, declar); } return; } const parent = this.getProgramParent(); const ids = path.getOuterBindingIdentifiers(true); for (const name of Object.keys(ids)) { parent.references[name] = true; for (const id of ids[name]) { const local = this.getOwnBinding(name); if (local) { if (local.identifier === id) continue; this.checkBlockScopedCollisions(local, kind, name, id); } if (local) { local.reassign(bindingPath); } else { this.bindings[name] = new _binding.default({ identifier: id, scope: this, path: bindingPath, kind }); } } } } addGlobal(node) { this.globals[node.name] = node; } hasUid(name) { let scope = this; do { if (scope.uids[name]) return true; } while (scope = scope.parent); return false; } hasGlobal(name) { let scope = this; do { if (scope.globals[name]) return true; } while (scope = scope.parent); return false; } hasReference(name) { return !!this.getProgramParent().references[name]; } isPure(node, constantsOnly) { if (isIdentifier(node)) { const binding = this.getBinding(node.name); if (!binding) return false; if (constantsOnly) return binding.constant; return true; } else if (isThisExpression(node) || isMetaProperty(node) || isTopicReference(node) || isPrivateName(node)) { return true; } else if (isClass(node)) { var _node$decorators; if (node.superClass && !this.isPure(node.superClass, constantsOnly)) { return false; } if (((_node$decorators = node.decorators) == null ? void 0 : _node$decorators.length) > 0) { return false; } return this.isPure(node.body, constantsOnly); } else if (isClassBody(node)) { for (const method of node.body) { if (!this.isPure(method, constantsOnly)) return false; } return true; } else if (isBinary(node)) { return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); } else if (isArrayExpression(node) || isTupleExpression(node)) { for (const elem of node.elements) { if (elem !== null && !this.isPure(elem, constantsOnly)) return false; } return true; } else if (isObjectExpression(node) || isRecordExpression(node)) { for (const prop of node.properties) { if (!this.isPure(prop, constantsOnly)) return false; } return true; } else if (isMethod(node)) { var _node$decorators2; if (node.computed && !this.isPure(node.key, constantsOnly)) return false; if (((_node$decorators2 = node.decorators) == null ? void 0 : _node$decorators2.length) > 0) { return false; } return true; } else if (isProperty(node)) { var _node$decorators3; if (node.computed && !this.isPure(node.key, constantsOnly)) return false; if (((_node$decorators3 = node.decorators) == null ? void 0 : _node$decorators3.length) > 0) { return false; } if (isObjectProperty(node) || node.static) { if (node.value !== null && !this.isPure(node.value, constantsOnly)) { return false; } } return true; } else if (isUnaryExpression(node)) { return this.isPure(node.argument, constantsOnly); } else if (isTemplateLiteral(node)) { for (const expression of node.expressions) { if (!this.isPure(expression, constantsOnly)) return false; } return true; } else if (isTaggedTemplateExpression(node)) { return matchesPattern(node.tag, "String.raw") && !this.hasBinding("String", { noGlobals: true }) && this.isPure(node.quasi, constantsOnly); } else if (isMemberExpression2(node)) { return !node.computed && isIdentifier(node.object) && node.object.name === "Symbol" && isIdentifier(node.property) && node.property.name !== "for" && !this.hasBinding("Symbol", { noGlobals: true }); } else if (isCallExpression(node)) { return matchesPattern(node.callee, "Symbol.for") && !this.hasBinding("Symbol", { noGlobals: true }) && node.arguments.length === 1 && t6.isStringLiteral(node.arguments[0]); } else { return isPureish(node); } } setData(key2, val) { return this.data[key2] = val; } getData(key2) { let scope = this; do { const data = scope.data[key2]; if (data != null) return data; } while (scope = scope.parent); } removeData(key2) { let scope = this; do { const data = scope.data[key2]; if (data != null) scope.data[key2] = null; } while (scope = scope.parent); } init() { if (!this.inited) { this.inited = true; this.crawl(); } } crawl() { const path = this.path; this.references = /* @__PURE__ */ Object.create(null); this.bindings = /* @__PURE__ */ Object.create(null); this.globals = /* @__PURE__ */ Object.create(null); this.uids = /* @__PURE__ */ Object.create(null); this.data = /* @__PURE__ */ Object.create(null); let scope = this; do { if (scope.crawling) return; if (scope.path.isProgram()) { break; } } while (scope = scope.parent); const programParent = scope; const state = { references: [], constantViolations: [], assignments: [] }; this.crawling = true; if (path.type !== "Program" && (0, _visitors.isExplodedVisitor)(collectorVisitor)) { for (const visit4 of collectorVisitor.enter) { visit4.call(state, path, state); } const typeVisitors = collectorVisitor[path.type]; if (typeVisitors) { for (const visit4 of typeVisitors.enter) { visit4.call(state, path, state); } } } path.traverse(collectorVisitor, state); this.crawling = false; for (const path2 of state.assignments) { const ids = path2.getAssignmentIdentifiers(); for (const name of Object.keys(ids)) { if (path2.scope.getBinding(name)) continue; programParent.addGlobal(ids[name]); } path2.scope.registerConstantViolation(path2); } for (const ref of state.references) { const binding = ref.scope.getBinding(ref.node.name); if (binding) { binding.reference(ref); } else { programParent.addGlobal(ref.node); } } for (const path2 of state.constantViolations) { path2.scope.registerConstantViolation(path2); } } push(opts) { let path = this.path; if (path.isPattern()) { path = this.getPatternParent().path; } else if (!path.isBlockStatement() && !path.isProgram()) { path = this.getBlockParent().path; } if (path.isSwitchStatement()) { path = (this.getFunctionParent() || this.getProgramParent()).path; } const { init, unique, kind = "var", id } = opts; if (!init && !unique && (kind === "var" || kind === "let") && path.isFunction() && !path.node.name && isCallExpression(path.parent, { callee: path.node }) && path.parent.arguments.length <= path.node.params.length && isIdentifier(id)) { path.pushContainer("params", id); path.scope.registerBinding("param", path.get("params")[path.node.params.length - 1]); return; } if (path.isLoop() || path.isCatchClause() || path.isFunction()) { path.ensureBlock(); path = path.get("body"); } const blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; const dataKey = `declaration:${kind}:${blockHoist}`; let declarPath = !unique && path.getData(dataKey); if (!declarPath) { const declar = variableDeclaration4(kind, []); declar._blockHoist = blockHoist; [declarPath] = path.unshiftContainer("body", [declar]); if (!unique) path.setData(dataKey, declarPath); } const declarator = variableDeclarator4(id, init); const len = declarPath.node.declarations.push(declarator); path.scope.registerBinding(kind, declarPath.get("declarations")[len - 1]); } getProgramParent() { let scope = this; do { if (scope.path.isProgram()) { return scope; } } while (scope = scope.parent); throw new Error("Couldn't find a Program"); } getFunctionParent() { let scope = this; do { if (scope.path.isFunctionParent()) { return scope; } } while (scope = scope.parent); return null; } getBlockParent() { let scope = this; do { if (scope.path.isBlockParent()) { return scope; } } while (scope = scope.parent); throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); } getPatternParent() { let scope = this; do { if (!scope.path.isPattern()) { return scope.getBlockParent(); } } while (scope = scope.parent.parent); throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); } getAllBindings() { const ids = /* @__PURE__ */ Object.create(null); let scope = this; do { for (const key2 of Object.keys(scope.bindings)) { if (key2 in ids === false) { ids[key2] = scope.bindings[key2]; } } scope = scope.parent; } while (scope); return ids; } bindingIdentifierEquals(name, node) { return this.getBindingIdentifier(name) === node; } getBinding(name) { let scope = this; let previousPath; do { const binding = scope.getOwnBinding(name); if (binding) { var _previousPath; if ((_previousPath = previousPath) != null && _previousPath.isPattern() && binding.kind !== "param" && binding.kind !== "local") { } else { return binding; } } else if (!binding && name === "arguments" && scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) { break; } previousPath = scope.path; } while (scope = scope.parent); } getOwnBinding(name) { return this.bindings[name]; } getBindingIdentifier(name) { var _this$getBinding2; return (_this$getBinding2 = this.getBinding(name)) == null ? void 0 : _this$getBinding2.identifier; } getOwnBindingIdentifier(name) { const binding = this.bindings[name]; return binding == null ? void 0 : binding.identifier; } hasOwnBinding(name) { return !!this.getOwnBinding(name); } hasBinding(name, opts) { if (!name) return false; let scope = this; do { if (scope.hasOwnBinding(name)) { return true; } } while (scope = scope.parent); let noGlobals; let noUids; if (typeof opts === "object") { noGlobals = opts.noGlobals; noUids = opts.noUids; } else if (typeof opts === "boolean") { noGlobals = opts; } if (!noUids && this.hasUid(name)) return true; if (!noGlobals && _Scope.globals.includes(name)) return true; if (!noGlobals && _Scope.contextVariables.includes(name)) return true; return false; } parentHasBinding(name, opts) { var _this$parent; return (_this$parent = this.parent) == null ? void 0 : _this$parent.hasBinding(name, opts); } moveBindingTo(name, scope) { const info = this.getBinding(name); if (info) { info.scope.removeOwnBinding(name); info.scope = scope; scope.bindings[name] = info; } } removeOwnBinding(name) { delete this.bindings[name]; } removeBinding(name) { var _this$getBinding3; (_this$getBinding3 = this.getBinding(name)) == null || _this$getBinding3.scope.removeOwnBinding(name); let scope = this; do { if (scope.uids[name]) { scope.uids[name] = false; } } while (scope = scope.parent); } hoistVariables(emit2 = (id) => this.push({ id })) { this.crawl(); const seen = /* @__PURE__ */ new Set(); for (const name of Object.keys(this.bindings)) { const binding = this.bindings[name]; if (!binding) continue; const { path } = binding; if (!path.isVariableDeclarator()) continue; const { parent, parentPath } = path; if (parent.kind !== "var" || seen.has(parent)) continue; seen.add(path.parent); let firstId; const init = []; for (const decl of parent.declarations) { var _firstId; (_firstId = firstId) != null ? _firstId : firstId = decl.id; if (decl.init) { init.push(assignmentExpression2("=", decl.id, decl.init)); } const ids = Object.keys(getBindingIdentifiers(decl, false, true, true)); for (const name2 of ids) { emit2(identifier4(name2), decl.init != null); } } if (parentPath.parentPath.isFor({ left: parent })) { parentPath.replaceWith(firstId); } else if (init.length === 0) { parentPath.remove(); } else { const expr = init.length === 1 ? init[0] : sequenceExpression2(init); if (parentPath.parentPath.isForStatement({ init: parent })) { parentPath.replaceWith(expr); } else { parentPath.replaceWith(expressionStatement2(expr)); } } } } }; exports2.default = Scope; Scope.globals = Object.keys(_globals4.builtin); Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"]; { Scope.prototype._renameFromMap = function _renameFromMap(map2, oldName, newName, value) { if (map2[oldName]) { map2[newName] = value; map2[oldName] = null; } }; Scope.prototype.traverse = function(node, opts, state) { (0, _index.default)(node, opts, this, state, this.path); }; Scope.prototype._generateUid = function _generateUid(name, i) { let id = name; if (i > 1) id += i; return `_${id}`; }; Scope.prototype.toArray = function toArray(node, i, arrayLikeIsIterable) { if (isIdentifier(node)) { const binding = this.getBinding(node.name); if (binding != null && binding.constant && binding.path.isGenericType("Array")) { return node; } } if (isArrayExpression(node)) { return node; } if (isIdentifier(node, { name: "arguments" })) { return callExpression4(memberExpression2(memberExpression2(memberExpression2(identifier4("Array"), identifier4("prototype")), identifier4("slice")), identifier4("call")), [node]); } let helperName; const args = [node]; if (i === true) { helperName = "toConsumableArray"; } else if (typeof i === "number") { args.push(numericLiteral2(i)); helperName = "slicedToArray"; } else { helperName = "toArray"; } if (arrayLikeIsIterable) { args.unshift(this.path.hub.addHelper(helperName)); helperName = "maybeArrayLike"; } return callExpression4(this.path.hub.addHelper(helperName), args); }; Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind(...kinds) { const ids = /* @__PURE__ */ Object.create(null); for (const kind of kinds) { let scope = this; do { for (const name of Object.keys(scope.bindings)) { const binding = scope.bindings[name]; if (binding.kind === kind) ids[name] = binding; } scope = scope.parent; } while (scope); } return ids; }; Object.defineProperties(Scope.prototype, { parentBlock: { configurable: true, enumerable: true, get() { return this.path.parent; } }, hub: { configurable: true, enumerable: true, get() { return this.path.hub; } } }); } } }); // ../../node_modules/@jridgewell/set-array/dist/set-array.umd.js var require_set_array_umd = __commonJS({ "../../node_modules/@jridgewell/set-array/dist/set-array.umd.js"(exports2, module2) { "use strict"; (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.setArray = {})); })(exports2, function(exports3) { "use strict"; class SetArray { constructor() { this._indexes = { __proto__: null }; this.array = []; } } function cast(set2) { return set2; } function get(setarr, key2) { return cast(setarr)._indexes[key2]; } function put(setarr, key2) { const index = get(setarr, key2); if (index !== void 0) return index; const { array: array2, _indexes: indexes } = cast(setarr); const length = array2.push(key2); return indexes[key2] = length - 1; } function pop2(setarr) { const { array: array2, _indexes: indexes } = cast(setarr); if (array2.length === 0) return; const last = array2.pop(); indexes[last] = void 0; } function remove(setarr, key2) { const index = get(setarr, key2); if (index === void 0) return; const { array: array2, _indexes: indexes } = cast(setarr); for (let i = index + 1; i < array2.length; i++) { const k = array2[i]; array2[i - 1] = k; indexes[k]--; } indexes[key2] = void 0; array2.pop(); } exports3.SetArray = SetArray; exports3.get = get; exports3.pop = pop2; exports3.put = put; exports3.remove = remove; Object.defineProperty(exports3, "__esModule", { value: true }); }); } }); // ../../node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js var require_sourcemap_codec_umd = __commonJS({ "../../node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js"(exports2, module2) { "use strict"; (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.sourcemapCodec = {})); })(exports2, function(exports3) { "use strict"; const comma = ",".charCodeAt(0); const semicolon = ";".charCodeAt(0); const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const intToChar = new Uint8Array(64); const charToInt = new Uint8Array(128); for (let i = 0; i < chars.length; i++) { const c2 = chars.charCodeAt(i); intToChar[i] = c2; charToInt[c2] = i; } const td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) { const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); return out.toString(); } } : { decode(buf) { let out = ""; for (let i = 0; i < buf.length; i++) { out += String.fromCharCode(buf[i]); } return out; } }; function decode3(mappings) { const state = new Int32Array(5); const decoded = []; let index = 0; do { const semi = indexOf(mappings, index); const line2 = []; let sorted = true; let lastCol = 0; state[0] = 0; for (let i = index; i < semi; i++) { let seg; i = decodeInteger(mappings, i, state, 0); const col = state[0]; if (col < lastCol) sorted = false; lastCol = col; if (hasMoreVlq(mappings, i, semi)) { i = decodeInteger(mappings, i, state, 1); i = decodeInteger(mappings, i, state, 2); i = decodeInteger(mappings, i, state, 3); if (hasMoreVlq(mappings, i, semi)) { i = decodeInteger(mappings, i, state, 4); seg = [col, state[1], state[2], state[3], state[4]]; } else { seg = [col, state[1], state[2], state[3]]; } } else { seg = [col]; } line2.push(seg); } if (!sorted) sort(line2); decoded.push(line2); index = semi + 1; } while (index <= mappings.length); return decoded; } function indexOf(mappings, index) { const idx = mappings.indexOf(";", index); return idx === -1 ? mappings.length : idx; } function decodeInteger(mappings, pos2, state, j) { let value = 0; let shift = 0; let integer2 = 0; do { const c2 = mappings.charCodeAt(pos2++); integer2 = charToInt[c2]; value |= (integer2 & 31) << shift; shift += 5; } while (integer2 & 32); const shouldNegate = value & 1; value >>>= 1; if (shouldNegate) { value = -2147483648 | -value; } state[j] += value; return pos2; } function hasMoreVlq(mappings, i, length) { if (i >= length) return false; return mappings.charCodeAt(i) !== comma; } function sort(line2) { line2.sort(sortComparator); } function sortComparator(a, b) { return a[0] - b[0]; } function encode3(decoded) { const state = new Int32Array(5); const bufLength = 1024 * 16; const subLength = bufLength - 36; const buf = new Uint8Array(bufLength); const sub = buf.subarray(0, subLength); let pos2 = 0; let out = ""; for (let i = 0; i < decoded.length; i++) { const line2 = decoded[i]; if (i > 0) { if (pos2 === bufLength) { out += td.decode(buf); pos2 = 0; } buf[pos2++] = semicolon; } if (line2.length === 0) continue; state[0] = 0; for (let j = 0; j < line2.length; j++) { const segment = line2[j]; if (pos2 > subLength) { out += td.decode(sub); buf.copyWithin(0, subLength, pos2); pos2 -= subLength; } if (j > 0) buf[pos2++] = comma; pos2 = encodeInteger(buf, pos2, state, segment, 0); if (segment.length === 1) continue; pos2 = encodeInteger(buf, pos2, state, segment, 1); pos2 = encodeInteger(buf, pos2, state, segment, 2); pos2 = encodeInteger(buf, pos2, state, segment, 3); if (segment.length === 4) continue; pos2 = encodeInteger(buf, pos2, state, segment, 4); } } return out + td.decode(buf.subarray(0, pos2)); } function encodeInteger(buf, pos2, state, segment, j) { const next = segment[j]; let num = next - state[j]; state[j] = next; num = num < 0 ? -num << 1 | 1 : num << 1; do { let clamped = num & 31; num >>>= 5; if (num > 0) clamped |= 32; buf[pos2++] = intToChar[clamped]; } while (num > 0); return pos2; } exports3.decode = decode3; exports3.encode = encode3; Object.defineProperty(exports3, "__esModule", { value: true }); }); } }); // ../../node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js var require_resolve_uri_umd = __commonJS({ "../../node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js"(exports2, module2) { "use strict"; (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.resolveURI = factory()); })(exports2, function() { "use strict"; const schemeRegex = /^[\w+.-]+:\/\//; const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; var UrlType; (function(UrlType2) { UrlType2[UrlType2["Empty"] = 1] = "Empty"; UrlType2[UrlType2["Hash"] = 2] = "Hash"; UrlType2[UrlType2["Query"] = 3] = "Query"; UrlType2[UrlType2["RelativePath"] = 4] = "RelativePath"; UrlType2[UrlType2["AbsolutePath"] = 5] = "AbsolutePath"; UrlType2[UrlType2["SchemeRelative"] = 6] = "SchemeRelative"; UrlType2[UrlType2["Absolute"] = 7] = "Absolute"; })(UrlType || (UrlType = {})); function isAbsoluteUrl(input) { return schemeRegex.test(input); } function isSchemeRelativeUrl(input) { return input.startsWith("//"); } function isAbsolutePath(input) { return input.startsWith("/"); } function isFileUrl(input) { return input.startsWith("file:"); } function isRelative(input) { return /^[.?#]/.test(input); } function parseAbsoluteUrl(input) { const match = urlRegex.exec(input); return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || ""); } function parseFileUrl(input) { const match = fileRegex.exec(input); const path = match[2]; return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || ""); } function makeUrl(scheme, user, host, port, path, query, hash2) { return { scheme, user, host, port, path, query, hash: hash2, type: UrlType.Absolute }; } function parseUrl(input) { if (isSchemeRelativeUrl(input)) { const url3 = parseAbsoluteUrl("http:" + input); url3.scheme = ""; url3.type = UrlType.SchemeRelative; return url3; } if (isAbsolutePath(input)) { const url3 = parseAbsoluteUrl("http://foo.com" + input); url3.scheme = ""; url3.host = ""; url3.type = UrlType.AbsolutePath; return url3; } if (isFileUrl(input)) return parseFileUrl(input); if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input); const url2 = parseAbsoluteUrl("http://foo.com/" + input); url2.scheme = ""; url2.host = ""; url2.type = input ? input.startsWith("?") ? UrlType.Query : input.startsWith("#") ? UrlType.Hash : UrlType.RelativePath : UrlType.Empty; return url2; } function stripPathFilename(path) { if (path.endsWith("/..")) return path; const index = path.lastIndexOf("/"); return path.slice(0, index + 1); } function mergePaths(url2, base) { normalizePath(base, base.type); if (url2.path === "/") { url2.path = base.path; } else { url2.path = stripPathFilename(base.path) + url2.path; } } function normalizePath(url2, type) { const rel = type <= UrlType.RelativePath; const pieces = url2.path.split("/"); let pointer = 1; let positive = 0; let addTrailingSlash = false; for (let i = 1; i < pieces.length; i++) { const piece = pieces[i]; if (!piece) { addTrailingSlash = true; continue; } addTrailingSlash = false; if (piece === ".") continue; if (piece === "..") { if (positive) { addTrailingSlash = true; positive--; pointer--; } else if (rel) { pieces[pointer++] = piece; } continue; } pieces[pointer++] = piece; positive++; } let path = ""; for (let i = 1; i < pointer; i++) { path += "/" + pieces[i]; } if (!path || addTrailingSlash && !path.endsWith("/..")) { path += "/"; } url2.path = path; } function resolve(input, base) { if (!input && !base) return ""; const url2 = parseUrl(input); let inputType = url2.type; if (base && inputType !== UrlType.Absolute) { const baseUrl = parseUrl(base); const baseType = baseUrl.type; switch (inputType) { case UrlType.Empty: url2.hash = baseUrl.hash; // fall through case UrlType.Hash: url2.query = baseUrl.query; // fall through case UrlType.Query: case UrlType.RelativePath: mergePaths(url2, baseUrl); // fall through case UrlType.AbsolutePath: url2.user = baseUrl.user; url2.host = baseUrl.host; url2.port = baseUrl.port; // fall through case UrlType.SchemeRelative: url2.scheme = baseUrl.scheme; } if (baseType > inputType) inputType = baseType; } normalizePath(url2, inputType); const queryHash = url2.query + url2.hash; switch (inputType) { // This is impossible, because of the empty checks at the start of the function. // case UrlType.Empty: case UrlType.Hash: case UrlType.Query: return queryHash; case UrlType.RelativePath: { const path = url2.path.slice(1); if (!path) return queryHash || "."; if (isRelative(base || input) && !isRelative(path)) { return "./" + path + queryHash; } return path + queryHash; } case UrlType.AbsolutePath: return url2.path + queryHash; default: return url2.scheme + "//" + url2.user + url2.host + url2.port + url2.path + queryHash; } } return resolve; }); } }); // ../../node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js var require_trace_mapping_umd = __commonJS({ "../../node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js"(exports2, module2) { "use strict"; (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2, require_sourcemap_codec_umd(), require_resolve_uri_umd()) : typeof define === "function" && define.amd ? define(["exports", "@jridgewell/sourcemap-codec", "@jridgewell/resolve-uri"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.traceMapping = {}, global2.sourcemapCodec, global2.resolveURI)); })(exports2, function(exports3, sourcemapCodec, resolveUri) { "use strict"; function resolve(input, base) { if (base && !base.endsWith("/")) base += "/"; return resolveUri(input, base); } function stripFilename(path) { if (!path) return ""; const index = path.lastIndexOf("/"); return path.slice(0, index + 1); } const COLUMN = 0; const SOURCES_INDEX = 1; const SOURCE_LINE = 2; const SOURCE_COLUMN = 3; const NAMES_INDEX = 4; const REV_GENERATED_LINE = 1; const REV_GENERATED_COLUMN = 2; function maybeSort(mappings, owned) { const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); if (unsortedIndex === mappings.length) return mappings; if (!owned) mappings = mappings.slice(); for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { mappings[i] = sortSegments(mappings[i], owned); } return mappings; } function nextUnsortedSegmentLine(mappings, start) { for (let i = start; i < mappings.length; i++) { if (!isSorted(mappings[i])) return i; } return mappings.length; } function isSorted(line2) { for (let j = 1; j < line2.length; j++) { if (line2[j][COLUMN] < line2[j - 1][COLUMN]) { return false; } } return true; } function sortSegments(line2, owned) { if (!owned) line2 = line2.slice(); return line2.sort(sortComparator); } function sortComparator(a, b) { return a[COLUMN] - b[COLUMN]; } let found = false; function binarySearch(haystack, needle, low, high) { while (low <= high) { const mid = low + (high - low >> 1); const cmp = haystack[mid][COLUMN] - needle; if (cmp === 0) { found = true; return mid; } if (cmp < 0) { low = mid + 1; } else { high = mid - 1; } } found = false; return low - 1; } function upperBound(haystack, needle, index) { for (let i = index + 1; i < haystack.length; index = i++) { if (haystack[i][COLUMN] !== needle) break; } return index; } function lowerBound(haystack, needle, index) { for (let i = index - 1; i >= 0; index = i--) { if (haystack[i][COLUMN] !== needle) break; } return index; } function memoizedState() { return { lastKey: -1, lastNeedle: -1, lastIndex: -1 }; } function memoizedBinarySearch(haystack, needle, state, key2) { const { lastKey, lastNeedle, lastIndex } = state; let low = 0; let high = haystack.length - 1; if (key2 === lastKey) { if (needle === lastNeedle) { found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; return lastIndex; } if (needle >= lastNeedle) { low = lastIndex === -1 ? 0 : lastIndex; } else { high = lastIndex; } } state.lastKey = key2; state.lastNeedle = needle; return state.lastIndex = binarySearch(haystack, needle, low, high); } function buildBySources(decoded, memos) { const sources = memos.map(buildNullArray); for (let i = 0; i < decoded.length; i++) { const line2 = decoded[i]; for (let j = 0; j < line2.length; j++) { const seg = line2[j]; if (seg.length === 1) continue; const sourceIndex2 = seg[SOURCES_INDEX]; const sourceLine = seg[SOURCE_LINE]; const sourceColumn = seg[SOURCE_COLUMN]; const originalSource = sources[sourceIndex2]; const originalLine = originalSource[sourceLine] || (originalSource[sourceLine] = []); const memo = memos[sourceIndex2]; let index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); memo.lastIndex = ++index; insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]); } } return sources; } function insert(array2, index, value) { for (let i = array2.length; i > index; i--) { array2[i] = array2[i - 1]; } array2[index] = value; } function buildNullArray() { return { __proto__: null }; } const AnyMap = function(map2, mapUrl) { const parsed = parse6(map2); if (!("sections" in parsed)) { return new TraceMap(parsed, mapUrl); } const mappings = []; const sources = []; const sourcesContent = []; const names = []; const ignoreList = []; recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, ignoreList, 0, 0, Infinity, Infinity); const joined = { version: 3, file: parsed.file, names, sources, sourcesContent, mappings, ignoreList }; return presortedDecodedMap(joined); }; function parse6(map2) { return typeof map2 === "string" ? JSON.parse(map2) : map2; } function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { const { sections } = input; for (let i = 0; i < sections.length; i++) { const { map: map2, offset } = sections[i]; let sl = stopLine; let sc = stopColumn; if (i + 1 < sections.length) { const nextOffset = sections[i + 1].offset; sl = Math.min(stopLine, lineOffset + nextOffset.line); if (sl === stopLine) { sc = Math.min(stopColumn, columnOffset + nextOffset.column); } else if (sl < stopLine) { sc = columnOffset + nextOffset.column; } } addSection(map2, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset + offset.line, columnOffset + offset.column, sl, sc); } } function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { const parsed = parse6(input); if ("sections" in parsed) return recurse(...arguments); const map2 = new TraceMap(parsed, mapUrl); const sourcesOffset = sources.length; const namesOffset = names.length; const decoded = decodedMappings(map2); const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map2; append(sources, resolvedSources); append(names, map2.names); if (contents) append(sourcesContent, contents); else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null); if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset); for (let i = 0; i < decoded.length; i++) { const lineI = lineOffset + i; if (lineI > stopLine) return; const out = getLine(mappings, lineI); const cOffset = i === 0 ? columnOffset : 0; const line2 = decoded[i]; for (let j = 0; j < line2.length; j++) { const seg = line2[j]; const column2 = cOffset + seg[COLUMN]; if (lineI === stopLine && column2 >= stopColumn) return; if (seg.length === 1) { out.push([column2]); continue; } const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; const sourceLine = seg[SOURCE_LINE]; const sourceColumn = seg[SOURCE_COLUMN]; out.push(seg.length === 4 ? [column2, sourcesIndex, sourceLine, sourceColumn] : [column2, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); } } } function append(arr, other) { for (let i = 0; i < other.length; i++) arr.push(other[i]); } function getLine(arr, index) { for (let i = arr.length; i <= index; i++) arr[i] = []; return arr[index]; } const LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; const COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; const LEAST_UPPER_BOUND = -1; const GREATEST_LOWER_BOUND = 1; class TraceMap { constructor(map2, mapUrl) { const isString = typeof map2 === "string"; if (!isString && map2._decodedMemo) return map2; const parsed = isString ? JSON.parse(map2) : map2; const { version: version2, file: file2, names, sourceRoot, sources, sourcesContent } = parsed; this.version = version2; this.file = file2; this.names = names || []; this.sourceRoot = sourceRoot; this.sources = sources; this.sourcesContent = sourcesContent; this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; const from = resolve(sourceRoot || "", stripFilename(mapUrl)); this.resolvedSources = sources.map((s) => resolve(s || "", from)); const { mappings } = parsed; if (typeof mappings === "string") { this._encoded = mappings; this._decoded = void 0; } else { this._encoded = void 0; this._decoded = maybeSort(mappings, isString); } this._decodedMemo = memoizedState(); this._bySources = void 0; this._bySourceMemos = void 0; } } function cast(map2) { return map2; } function encodedMappings(map2) { var _a; var _b; return (_a = (_b = cast(map2))._encoded) !== null && _a !== void 0 ? _a : _b._encoded = sourcemapCodec.encode(cast(map2)._decoded); } function decodedMappings(map2) { var _a; return (_a = cast(map2))._decoded || (_a._decoded = sourcemapCodec.decode(cast(map2)._encoded)); } function traceSegment(map2, line2, column2) { const decoded = decodedMappings(map2); if (line2 >= decoded.length) return null; const segments = decoded[line2]; const index = traceSegmentInternal(segments, cast(map2)._decodedMemo, line2, column2, GREATEST_LOWER_BOUND); return index === -1 ? null : segments[index]; } function originalPositionFor(map2, needle) { let { line: line2, column: column2, bias } = needle; line2--; if (line2 < 0) throw new Error(LINE_GTR_ZERO); if (column2 < 0) throw new Error(COL_GTR_EQ_ZERO); const decoded = decodedMappings(map2); if (line2 >= decoded.length) return OMapping(null, null, null, null); const segments = decoded[line2]; const index = traceSegmentInternal(segments, cast(map2)._decodedMemo, line2, column2, bias || GREATEST_LOWER_BOUND); if (index === -1) return OMapping(null, null, null, null); const segment = segments[index]; if (segment.length === 1) return OMapping(null, null, null, null); const { names, resolvedSources } = map2; return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); } function generatedPositionFor(map2, needle) { const { source: source2, line: line2, column: column2, bias } = needle; return generatedPosition(map2, source2, line2, column2, bias || GREATEST_LOWER_BOUND, false); } function allGeneratedPositionsFor(map2, needle) { const { source: source2, line: line2, column: column2, bias } = needle; return generatedPosition(map2, source2, line2, column2, bias || LEAST_UPPER_BOUND, true); } function eachMapping(map2, cb) { const decoded = decodedMappings(map2); const { names, resolvedSources } = map2; for (let i = 0; i < decoded.length; i++) { const line2 = decoded[i]; for (let j = 0; j < line2.length; j++) { const seg = line2[j]; const generatedLine = i + 1; const generatedColumn = seg[0]; let source2 = null; let originalLine = null; let originalColumn = null; let name = null; if (seg.length !== 1) { source2 = resolvedSources[seg[1]]; originalLine = seg[2] + 1; originalColumn = seg[3]; } if (seg.length === 5) name = names[seg[4]]; cb({ generatedLine, generatedColumn, source: source2, originalLine, originalColumn, name }); } } } function sourceIndex(map2, source2) { const { sources, resolvedSources } = map2; let index = sources.indexOf(source2); if (index === -1) index = resolvedSources.indexOf(source2); return index; } function sourceContentFor(map2, source2) { const { sourcesContent } = map2; if (sourcesContent == null) return null; const index = sourceIndex(map2, source2); return index === -1 ? null : sourcesContent[index]; } function isIgnored(map2, source2) { const { ignoreList } = map2; if (ignoreList == null) return false; const index = sourceIndex(map2, source2); return index === -1 ? false : ignoreList.includes(index); } function presortedDecodedMap(map2, mapUrl) { const tracer = new TraceMap(clone2(map2, []), mapUrl); cast(tracer)._decoded = map2.mappings; return tracer; } function decodedMap(map2) { return clone2(map2, decodedMappings(map2)); } function encodedMap(map2) { return clone2(map2, encodedMappings(map2)); } function clone2(map2, mappings) { return { version: map2.version, file: map2.file, names: map2.names, sourceRoot: map2.sourceRoot, sources: map2.sources, sourcesContent: map2.sourcesContent, mappings, ignoreList: map2.ignoreList || map2.x_google_ignoreList }; } function OMapping(source2, line2, column2, name) { return { source: source2, line: line2, column: column2, name }; } function GMapping(line2, column2) { return { line: line2, column: column2 }; } function traceSegmentInternal(segments, memo, line2, column2, bias) { let index = memoizedBinarySearch(segments, column2, memo, line2); if (found) { index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column2, index); } else if (bias === LEAST_UPPER_BOUND) index++; if (index === -1 || index === segments.length) return -1; return index; } function sliceGeneratedPositions(segments, memo, line2, column2, bias) { let min = traceSegmentInternal(segments, memo, line2, column2, GREATEST_LOWER_BOUND); if (!found && bias === LEAST_UPPER_BOUND) min++; if (min === -1 || min === segments.length) return []; const matchedColumn = found ? column2 : segments[min][COLUMN]; if (!found) min = lowerBound(segments, matchedColumn, min); const max = upperBound(segments, matchedColumn, min); const result = []; for (; min <= max; min++) { const segment = segments[min]; result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); } return result; } function generatedPosition(map2, source2, line2, column2, bias, all) { var _a; line2--; if (line2 < 0) throw new Error(LINE_GTR_ZERO); if (column2 < 0) throw new Error(COL_GTR_EQ_ZERO); const { sources, resolvedSources } = map2; let sourceIndex2 = sources.indexOf(source2); if (sourceIndex2 === -1) sourceIndex2 = resolvedSources.indexOf(source2); if (sourceIndex2 === -1) return all ? [] : GMapping(null, null); const generated = (_a = cast(map2))._bySources || (_a._bySources = buildBySources(decodedMappings(map2), cast(map2)._bySourceMemos = sources.map(memoizedState))); const segments = generated[sourceIndex2][line2]; if (segments == null) return all ? [] : GMapping(null, null); const memo = cast(map2)._bySourceMemos[sourceIndex2]; if (all) return sliceGeneratedPositions(segments, memo, line2, column2, bias); const index = traceSegmentInternal(segments, memo, line2, column2, bias); if (index === -1) return GMapping(null, null); const segment = segments[index]; return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); } exports3.AnyMap = AnyMap; exports3.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; exports3.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; exports3.TraceMap = TraceMap; exports3.allGeneratedPositionsFor = allGeneratedPositionsFor; exports3.decodedMap = decodedMap; exports3.decodedMappings = decodedMappings; exports3.eachMapping = eachMapping; exports3.encodedMap = encodedMap; exports3.encodedMappings = encodedMappings; exports3.generatedPositionFor = generatedPositionFor; exports3.isIgnored = isIgnored; exports3.originalPositionFor = originalPositionFor; exports3.presortedDecodedMap = presortedDecodedMap; exports3.sourceContentFor = sourceContentFor; exports3.traceSegment = traceSegment; }); } }); // ../../node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js var require_gen_mapping_umd = __commonJS({ "../../node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js"(exports2, module2) { "use strict"; (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2, require_set_array_umd(), require_sourcemap_codec_umd(), require_trace_mapping_umd()) : typeof define === "function" && define.amd ? define(["exports", "@jridgewell/set-array", "@jridgewell/sourcemap-codec", "@jridgewell/trace-mapping"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.genMapping = {}, global2.setArray, global2.sourcemapCodec, global2.traceMapping)); })(exports2, function(exports3, setArray, sourcemapCodec, traceMapping) { "use strict"; const COLUMN = 0; const SOURCES_INDEX = 1; const SOURCE_LINE = 2; const SOURCE_COLUMN = 3; const NAMES_INDEX = 4; const NO_NAME = -1; class GenMapping { constructor({ file: file2, sourceRoot } = {}) { this._names = new setArray.SetArray(); this._sources = new setArray.SetArray(); this._sourcesContent = []; this._mappings = []; this.file = file2; this.sourceRoot = sourceRoot; this._ignoreList = new setArray.SetArray(); } } function cast(map2) { return map2; } function addSegment(map2, genLine, genColumn, source2, sourceLine, sourceColumn, name, content) { return addSegmentInternal(false, map2, genLine, genColumn, source2, sourceLine, sourceColumn, name, content); } function addMapping(map2, mapping) { return addMappingInternal(false, map2, mapping); } const maybeAddSegment = (map2, genLine, genColumn, source2, sourceLine, sourceColumn, name, content) => { return addSegmentInternal(true, map2, genLine, genColumn, source2, sourceLine, sourceColumn, name, content); }; const maybeAddMapping = (map2, mapping) => { return addMappingInternal(true, map2, mapping); }; function setSourceContent(map2, source2, content) { const { _sources: sources, _sourcesContent: sourcesContent } = cast(map2); const index = setArray.put(sources, source2); sourcesContent[index] = content; } function setIgnore(map2, source2, ignore = true) { const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map2); const index = setArray.put(sources, source2); if (index === sourcesContent.length) sourcesContent[index] = null; if (ignore) setArray.put(ignoreList, index); else setArray.remove(ignoreList, index); } function toDecodedMap(map2) { const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast(map2); removeEmptyFinalLines(mappings); return { version: 3, file: map2.file || void 0, names: names.array, sourceRoot: map2.sourceRoot || void 0, sources: sources.array, sourcesContent, mappings, ignoreList: ignoreList.array }; } function toEncodedMap(map2) { const decoded = toDecodedMap(map2); return Object.assign(Object.assign({}, decoded), { mappings: sourcemapCodec.encode(decoded.mappings) }); } function fromMap(input) { const map2 = new traceMapping.TraceMap(input); const gen = new GenMapping({ file: map2.file, sourceRoot: map2.sourceRoot }); putAll(cast(gen)._names, map2.names); putAll(cast(gen)._sources, map2.sources); cast(gen)._sourcesContent = map2.sourcesContent || map2.sources.map(() => null); cast(gen)._mappings = traceMapping.decodedMappings(map2); if (map2.ignoreList) putAll(cast(gen)._ignoreList, map2.ignoreList); return gen; } function allMappings(map2) { const out = []; const { _mappings: mappings, _sources: sources, _names: names } = cast(map2); for (let i = 0; i < mappings.length; i++) { const line2 = mappings[i]; for (let j = 0; j < line2.length; j++) { const seg = line2[j]; const generated = { line: i + 1, column: seg[COLUMN] }; let source2 = void 0; let original = void 0; let name = void 0; if (seg.length !== 1) { source2 = sources.array[seg[SOURCES_INDEX]]; original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; if (seg.length === 5) name = names.array[seg[NAMES_INDEX]]; } out.push({ generated, source: source2, original, name }); } } return out; } function addSegmentInternal(skipable, map2, genLine, genColumn, source2, sourceLine, sourceColumn, name, content) { const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast(map2); const line2 = getLine(mappings, genLine); const index = getColumnIndex(line2, genColumn); if (!source2) { if (skipable && skipSourceless(line2, index)) return; return insert(line2, index, [genColumn]); } const sourcesIndex = setArray.put(sources, source2); const namesIndex = name ? setArray.put(names, name) : NO_NAME; if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; if (skipable && skipSource(line2, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { return; } return insert(line2, index, name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]); } function getLine(mappings, index) { for (let i = mappings.length; i <= index; i++) { mappings[i] = []; } return mappings[index]; } function getColumnIndex(line2, genColumn) { let index = line2.length; for (let i = index - 1; i >= 0; index = i--) { const current = line2[i]; if (genColumn >= current[COLUMN]) break; } return index; } function insert(array2, index, value) { for (let i = array2.length; i > index; i--) { array2[i] = array2[i - 1]; } array2[index] = value; } function removeEmptyFinalLines(mappings) { const { length } = mappings; let len = length; for (let i = len - 1; i >= 0; len = i, i--) { if (mappings[i].length > 0) break; } if (len < length) mappings.length = len; } function putAll(setarr, array2) { for (let i = 0; i < array2.length; i++) setArray.put(setarr, array2[i]); } function skipSourceless(line2, index) { if (index === 0) return true; const prev = line2[index - 1]; return prev.length === 1; } function skipSource(line2, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { if (index === 0) return false; const prev = line2[index - 1]; if (prev.length === 1) return false; return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME); } function addMappingInternal(skipable, map2, mapping) { const { generated, source: source2, original, name, content } = mapping; if (!source2) { return addSegmentInternal(skipable, map2, generated.line - 1, generated.column, null, null, null, null, null); } return addSegmentInternal(skipable, map2, generated.line - 1, generated.column, source2, original.line - 1, original.column, name, content); } exports3.GenMapping = GenMapping; exports3.addMapping = addMapping; exports3.addSegment = addSegment; exports3.allMappings = allMappings; exports3.fromMap = fromMap; exports3.maybeAddMapping = maybeAddMapping; exports3.maybeAddSegment = maybeAddSegment; exports3.setIgnore = setIgnore; exports3.setSourceContent = setSourceContent; exports3.toDecodedMap = toDecodedMap; exports3.toEncodedMap = toEncodedMap; Object.defineProperty(exports3, "__esModule", { value: true }); }); } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/source-map.js var require_source_map = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/source-map.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = void 0; var _genMapping = require_gen_mapping_umd(); var _traceMapping = require_trace_mapping_umd(); var SourceMap = class { constructor(opts, code) { var _opts$sourceFileName; this._map = void 0; this._rawMappings = void 0; this._sourceFileName = void 0; this._lastGenLine = 0; this._lastSourceLine = 0; this._lastSourceColumn = 0; this._inputMap = void 0; const map2 = this._map = new _genMapping.GenMapping({ sourceRoot: opts.sourceRoot }); this._sourceFileName = (_opts$sourceFileName = opts.sourceFileName) == null ? void 0 : _opts$sourceFileName.replace(/\\/g, "/"); this._rawMappings = void 0; if (opts.inputSourceMap) { this._inputMap = new _traceMapping.TraceMap(opts.inputSourceMap); const resolvedSources = this._inputMap.resolvedSources; if (resolvedSources.length) { for (let i = 0; i < resolvedSources.length; i++) { var _this$_inputMap$sourc; (0, _genMapping.setSourceContent)(map2, resolvedSources[i], (_this$_inputMap$sourc = this._inputMap.sourcesContent) == null ? void 0 : _this$_inputMap$sourc[i]); } } } if (typeof code === "string" && !opts.inputSourceMap) { (0, _genMapping.setSourceContent)(map2, this._sourceFileName, code); } else if (typeof code === "object") { for (const sourceFileName of Object.keys(code)) { (0, _genMapping.setSourceContent)(map2, sourceFileName.replace(/\\/g, "/"), code[sourceFileName]); } } } get() { return (0, _genMapping.toEncodedMap)(this._map); } getDecoded() { return (0, _genMapping.toDecodedMap)(this._map); } getRawMappings() { return this._rawMappings || (this._rawMappings = (0, _genMapping.allMappings)(this._map)); } mark(generated, line2, column2, identifierName, identifierNamePos, filename) { var _originalMapping; this._rawMappings = void 0; let originalMapping; if (line2 != null) { if (this._inputMap) { originalMapping = (0, _traceMapping.originalPositionFor)(this._inputMap, { line: line2, column: column2 }); if (!originalMapping.name && identifierNamePos) { const originalIdentifierMapping = (0, _traceMapping.originalPositionFor)(this._inputMap, identifierNamePos); if (originalIdentifierMapping.name) { identifierName = originalIdentifierMapping.name; } } } else { originalMapping = { source: (filename == null ? void 0 : filename.replace(/\\/g, "/")) || this._sourceFileName, line: line2, column: column2 }; } } (0, _genMapping.maybeAddMapping)(this._map, { name: identifierName, generated, source: (_originalMapping = originalMapping) == null ? void 0 : _originalMapping.source, original: originalMapping }); } }; exports2.default = SourceMap; } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/buffer.js var require_buffer = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/buffer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = void 0; var Buffer2 = class { constructor(map2, indentChar) { this._map = null; this._buf = ""; this._str = ""; this._appendCount = 0; this._last = 0; this._queue = []; this._queueCursor = 0; this._canMarkIdName = true; this._indentChar = ""; this._fastIndentations = []; this._position = { line: 1, column: 0 }; this._sourcePosition = { identifierName: void 0, identifierNamePos: void 0, line: void 0, column: void 0, filename: void 0 }; this._map = map2; this._indentChar = indentChar; for (let i = 0; i < 64; i++) { this._fastIndentations.push(indentChar.repeat(i)); } this._allocQueue(); } _allocQueue() { const queue = this._queue; for (let i = 0; i < 16; i++) { queue.push({ char: 0, repeat: 1, line: void 0, column: void 0, identifierName: void 0, identifierNamePos: void 0, filename: "" }); } } _pushQueue(char, repeat, line2, column2, filename) { const cursor = this._queueCursor; if (cursor === this._queue.length) { this._allocQueue(); } const item = this._queue[cursor]; item.char = char; item.repeat = repeat; item.line = line2; item.column = column2; item.filename = filename; this._queueCursor++; } _popQueue() { if (this._queueCursor === 0) { throw new Error("Cannot pop from empty queue"); } return this._queue[--this._queueCursor]; } get() { this._flush(); const map2 = this._map; const result = { code: (this._buf + this._str).trimRight(), decodedMap: map2 == null ? void 0 : map2.getDecoded(), get __mergedMap() { return this.map; }, get map() { const resultMap = map2 ? map2.get() : null; result.map = resultMap; return resultMap; }, set map(value) { Object.defineProperty(result, "map", { value, writable: true }); }, get rawMappings() { const mappings = map2 == null ? void 0 : map2.getRawMappings(); result.rawMappings = mappings; return mappings; }, set rawMappings(value) { Object.defineProperty(result, "rawMappings", { value, writable: true }); } }; return result; } append(str, maybeNewline) { this._flush(); this._append(str, this._sourcePosition, maybeNewline); } appendChar(char) { this._flush(); this._appendChar(char, 1, this._sourcePosition); } queue(char) { if (char === 10) { while (this._queueCursor !== 0) { const char2 = this._queue[this._queueCursor - 1].char; if (char2 !== 32 && char2 !== 9) { break; } this._queueCursor--; } } const sourcePosition = this._sourcePosition; this._pushQueue(char, 1, sourcePosition.line, sourcePosition.column, sourcePosition.filename); } queueIndentation(repeat) { if (repeat === 0) return; this._pushQueue(-1, repeat, void 0, void 0, void 0); } _flush() { const queueCursor = this._queueCursor; const queue = this._queue; for (let i = 0; i < queueCursor; i++) { const item = queue[i]; this._appendChar(item.char, item.repeat, item); } this._queueCursor = 0; } _appendChar(char, repeat, sourcePos) { this._last = char; if (char === -1) { const fastIndentation = this._fastIndentations[repeat]; if (fastIndentation !== void 0) { this._str += fastIndentation; } else { this._str += repeat > 1 ? this._indentChar.repeat(repeat) : this._indentChar; } } else { this._str += repeat > 1 ? String.fromCharCode(char).repeat(repeat) : String.fromCharCode(char); } if (char !== 10) { this._mark(sourcePos.line, sourcePos.column, sourcePos.identifierName, sourcePos.identifierNamePos, sourcePos.filename); this._position.column += repeat; } else { this._position.line++; this._position.column = 0; } if (this._canMarkIdName) { sourcePos.identifierName = void 0; sourcePos.identifierNamePos = void 0; } } _append(str, sourcePos, maybeNewline) { const len = str.length; const position = this._position; this._last = str.charCodeAt(len - 1); if (++this._appendCount > 4096) { +this._str; this._buf += this._str; this._str = str; this._appendCount = 0; } else { this._str += str; } if (!maybeNewline && !this._map) { position.column += len; return; } const { column: column2, identifierName, identifierNamePos, filename } = sourcePos; let line2 = sourcePos.line; if ((identifierName != null || identifierNamePos != null) && this._canMarkIdName) { sourcePos.identifierName = void 0; sourcePos.identifierNamePos = void 0; } let i = str.indexOf("\n"); let last = 0; if (i !== 0) { this._mark(line2, column2, identifierName, identifierNamePos, filename); } while (i !== -1) { position.line++; position.column = 0; last = i + 1; if (last < len && line2 !== void 0) { this._mark(++line2, 0, null, null, filename); } i = str.indexOf("\n", last); } position.column += len - last; } _mark(line2, column2, identifierName, identifierNamePos, filename) { var _this$_map; (_this$_map = this._map) == null || _this$_map.mark(this._position, line2, column2, identifierName, identifierNamePos, filename); } removeTrailingNewline() { const queueCursor = this._queueCursor; if (queueCursor !== 0 && this._queue[queueCursor - 1].char === 10) { this._queueCursor--; } } removeLastSemicolon() { const queueCursor = this._queueCursor; if (queueCursor !== 0 && this._queue[queueCursor - 1].char === 59) { this._queueCursor--; } } getLastChar() { const queueCursor = this._queueCursor; return queueCursor !== 0 ? this._queue[queueCursor - 1].char : this._last; } getNewlineCount() { const queueCursor = this._queueCursor; let count = 0; if (queueCursor === 0) return this._last === 10 ? 1 : 0; for (let i = queueCursor - 1; i >= 0; i--) { if (this._queue[i].char !== 10) { break; } count++; } return count === queueCursor && this._last === 10 ? count + 1 : count; } endsWithCharAndNewline() { const queue = this._queue; const queueCursor = this._queueCursor; if (queueCursor !== 0) { const lastCp = queue[queueCursor - 1].char; if (lastCp !== 10) return; if (queueCursor > 1) { return queue[queueCursor - 2].char; } else { return this._last; } } } hasContent() { return this._queueCursor !== 0 || !!this._last; } exactSource(loc, cb) { if (!this._map) { cb(); return; } this.source("start", loc); const identifierName = loc.identifierName; const sourcePos = this._sourcePosition; if (identifierName) { this._canMarkIdName = false; sourcePos.identifierName = identifierName; } cb(); if (identifierName) { this._canMarkIdName = true; sourcePos.identifierName = void 0; sourcePos.identifierNamePos = void 0; } this.source("end", loc); } source(prop, loc) { if (!this._map) return; this._normalizePosition(prop, loc, 0); } sourceWithOffset(prop, loc, columnOffset) { if (!this._map) return; this._normalizePosition(prop, loc, columnOffset); } _normalizePosition(prop, loc, columnOffset) { const pos2 = loc[prop]; const target = this._sourcePosition; if (pos2) { target.line = pos2.line; target.column = Math.max(pos2.column + columnOffset, 0); target.filename = loc.filename; } } getCurrentColumn() { const queue = this._queue; const queueCursor = this._queueCursor; let lastIndex = -1; let len = 0; for (let i = 0; i < queueCursor; i++) { const item = queue[i]; if (item.char === 10) { lastIndex = len; } len += item.repeat; } return lastIndex === -1 ? this._position.column + len : len - 1 - lastIndex; } getCurrentLine() { let count = 0; const queue = this._queue; for (let i = 0; i < this._queueCursor; i++) { if (queue[i].char === 10) { count++; } } return this._position.line + count; } }; exports2.default = Buffer2; } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/node/whitespace.js var require_whitespace = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/node/whitespace.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.nodes = void 0; var _t = require("@babel/types"); var { FLIPPED_ALIAS_KEYS, isArrayExpression, isAssignmentExpression, isBinary, isBlockStatement, isCallExpression, isFunction, isIdentifier, isLiteral, isMemberExpression: isMemberExpression2, isObjectExpression, isOptionalCallExpression, isOptionalMemberExpression: isOptionalMemberExpression2, isStringLiteral } = _t; function crawlInternal(node, state) { if (!node) return state; if (isMemberExpression2(node) || isOptionalMemberExpression2(node)) { crawlInternal(node.object, state); if (node.computed) crawlInternal(node.property, state); } else if (isBinary(node) || isAssignmentExpression(node)) { crawlInternal(node.left, state); crawlInternal(node.right, state); } else if (isCallExpression(node) || isOptionalCallExpression(node)) { state.hasCall = true; crawlInternal(node.callee, state); } else if (isFunction(node)) { state.hasFunction = true; } else if (isIdentifier(node)) { state.hasHelper = state.hasHelper || node.callee && isHelper(node.callee); } return state; } function crawl(node) { return crawlInternal(node, { hasCall: false, hasFunction: false, hasHelper: false }); } function isHelper(node) { if (!node) return false; if (isMemberExpression2(node)) { return isHelper(node.object) || isHelper(node.property); } else if (isIdentifier(node)) { return node.name === "require" || node.name.charCodeAt(0) === 95; } else if (isCallExpression(node)) { return isHelper(node.callee); } else if (isBinary(node) || isAssignmentExpression(node)) { return isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); } else { return false; } } function isType(node) { return isLiteral(node) || isObjectExpression(node) || isArrayExpression(node) || isIdentifier(node) || isMemberExpression2(node); } var nodes = exports2.nodes = { AssignmentExpression(node) { const state = crawl(node.right); if (state.hasCall && state.hasHelper || state.hasFunction) { return state.hasFunction ? 1 | 2 : 2; } }, SwitchCase(node, parent) { return (!!node.consequent.length || parent.cases[0] === node ? 1 : 0) | (!node.consequent.length && parent.cases[parent.cases.length - 1] === node ? 2 : 0); }, LogicalExpression(node) { if (isFunction(node.left) || isFunction(node.right)) { return 2; } }, Literal(node) { if (isStringLiteral(node) && node.value === "use strict") { return 2; } }, CallExpression(node) { if (isFunction(node.callee) || isHelper(node)) { return 1 | 2; } }, OptionalCallExpression(node) { if (isFunction(node.callee)) { return 1 | 2; } }, VariableDeclaration(node) { for (let i = 0; i < node.declarations.length; i++) { const declar = node.declarations[i]; let enabled = isHelper(declar.id) && !isType(declar.init); if (!enabled && declar.init) { const state = crawl(declar.init); enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; } if (enabled) { return 1 | 2; } } }, IfStatement(node) { if (isBlockStatement(node.consequent)) { return 1 | 2; } } }; nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function(node, parent) { if (parent.properties[0] === node) { return 1; } }; nodes.ObjectTypeCallProperty = function(node, parent) { var _parent$properties; if (parent.callProperties[0] === node && !((_parent$properties = parent.properties) != null && _parent$properties.length)) { return 1; } }; nodes.ObjectTypeIndexer = function(node, parent) { var _parent$properties2, _parent$callPropertie; if (parent.indexers[0] === node && !((_parent$properties2 = parent.properties) != null && _parent$properties2.length) && !((_parent$callPropertie = parent.callProperties) != null && _parent$callPropertie.length)) { return 1; } }; nodes.ObjectTypeInternalSlot = function(node, parent) { var _parent$properties3, _parent$callPropertie2, _parent$indexers; if (parent.internalSlots[0] === node && !((_parent$properties3 = parent.properties) != null && _parent$properties3.length) && !((_parent$callPropertie2 = parent.callProperties) != null && _parent$callPropertie2.length) && !((_parent$indexers = parent.indexers) != null && _parent$indexers.length)) { return 1; } }; [["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function([type, amounts]) { [type].concat(FLIPPED_ALIAS_KEYS[type] || []).forEach(function(type2) { const ret = amounts ? 1 | 2 : 0; nodes[type2] = () => ret; }); }); } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/node/parentheses.js var require_parentheses = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/node/parentheses.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AssignmentExpression = AssignmentExpression; exports2.Binary = Binary; exports2.BinaryExpression = BinaryExpression; exports2.ClassExpression = ClassExpression; exports2.ArrowFunctionExpression = exports2.ConditionalExpression = ConditionalExpression; exports2.DoExpression = DoExpression; exports2.FunctionExpression = FunctionExpression11; exports2.FunctionTypeAnnotation = FunctionTypeAnnotation; exports2.Identifier = Identifier25; exports2.LogicalExpression = LogicalExpression; exports2.NullableTypeAnnotation = NullableTypeAnnotation; exports2.ObjectExpression = ObjectExpression; exports2.OptionalIndexedAccessType = OptionalIndexedAccessType; exports2.OptionalCallExpression = exports2.OptionalMemberExpression = OptionalMemberExpression; exports2.SequenceExpression = SequenceExpression; exports2.TSSatisfiesExpression = exports2.TSAsExpression = TSAsExpression; exports2.TSConditionalType = TSConditionalType; exports2.TSConstructorType = exports2.TSFunctionType = TSFunctionType; exports2.TSInferType = TSInferType; exports2.TSInstantiationExpression = TSInstantiationExpression; exports2.TSIntersectionType = TSIntersectionType; exports2.UnaryLike = exports2.TSTypeAssertion = UnaryLike; exports2.TSTypeOperator = TSTypeOperator; exports2.TSUnionType = TSUnionType; exports2.IntersectionTypeAnnotation = exports2.UnionTypeAnnotation = UnionTypeAnnotation; exports2.UpdateExpression = UpdateExpression; exports2.AwaitExpression = exports2.YieldExpression = YieldExpression; var _t = require("@babel/types"); var _index = require_node2(); var { isArrayTypeAnnotation, isBinaryExpression, isCallExpression, isForOfStatement, isIndexedAccessType, isMemberExpression: isMemberExpression2, isObjectPattern, isOptionalMemberExpression: isOptionalMemberExpression2, isYieldExpression, isStatement: isStatement2 } = _t; var PRECEDENCE = /* @__PURE__ */ new Map([["||", 0], ["??", 0], ["|>", 0], ["&&", 1], ["|", 2], ["^", 3], ["&", 4], ["==", 5], ["===", 5], ["!=", 5], ["!==", 5], ["<", 6], [">", 6], ["<=", 6], [">=", 6], ["in", 6], ["instanceof", 6], [">>", 7], ["<<", 7], [">>>", 7], ["+", 8], ["-", 8], ["*", 9], ["/", 9], ["%", 9], ["**", 10]]); function getBinaryPrecedence(node, nodeType) { if (nodeType === "BinaryExpression" || nodeType === "LogicalExpression") { return PRECEDENCE.get(node.operator); } if (nodeType === "TSAsExpression" || nodeType === "TSSatisfiesExpression") { return PRECEDENCE.get("in"); } } function isTSTypeExpression(nodeType) { return nodeType === "TSAsExpression" || nodeType === "TSSatisfiesExpression" || nodeType === "TSTypeAssertion"; } var isClassExtendsClause = (node, parent) => { const parentType = parent.type; return (parentType === "ClassDeclaration" || parentType === "ClassExpression") && parent.superClass === node; }; var hasPostfixPart = (node, parent) => { const parentType = parent.type; return (parentType === "MemberExpression" || parentType === "OptionalMemberExpression") && parent.object === node || (parentType === "CallExpression" || parentType === "OptionalCallExpression" || parentType === "NewExpression") && parent.callee === node || parentType === "TaggedTemplateExpression" && parent.tag === node || parentType === "TSNonNullExpression"; }; function NullableTypeAnnotation(node, parent) { return isArrayTypeAnnotation(parent); } function FunctionTypeAnnotation(node, parent, tokenContext) { const parentType = parent.type; return parentType === "UnionTypeAnnotation" || parentType === "IntersectionTypeAnnotation" || parentType === "ArrayTypeAnnotation" || Boolean(tokenContext & _index.TokenContext.arrowFlowReturnType); } function UpdateExpression(node, parent) { return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent); } function needsParenBeforeExpressionBrace(tokenContext) { return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.arrowBody)); } function ObjectExpression(node, parent, tokenContext) { return needsParenBeforeExpressionBrace(tokenContext); } function DoExpression(node, parent, tokenContext) { return !node.async && Boolean(tokenContext & _index.TokenContext.expressionStatement); } function Binary(node, parent) { const parentType = parent.type; if (node.type === "BinaryExpression" && node.operator === "**" && parentType === "BinaryExpression" && parent.operator === "**") { return parent.left === node; } if (isClassExtendsClause(node, parent)) { return true; } if (hasPostfixPart(node, parent) || parentType === "UnaryExpression" || parentType === "SpreadElement" || parentType === "AwaitExpression") { return true; } const parentPos = getBinaryPrecedence(parent, parentType); if (parentPos != null) { const nodePos = getBinaryPrecedence(node, node.type); if (parentPos === nodePos && parentType === "BinaryExpression" && parent.right === node || parentPos > nodePos) { return true; } } return void 0; } function UnionTypeAnnotation(node, parent) { const parentType = parent.type; return parentType === "ArrayTypeAnnotation" || parentType === "NullableTypeAnnotation" || parentType === "IntersectionTypeAnnotation" || parentType === "UnionTypeAnnotation"; } function OptionalIndexedAccessType(node, parent) { return isIndexedAccessType(parent) && parent.objectType === node; } function TSAsExpression(node, parent) { if ((parent.type === "AssignmentExpression" || parent.type === "AssignmentPattern") && parent.left === node) { return true; } if (parent.type === "BinaryExpression" && (parent.operator === "|" || parent.operator === "&") && node === parent.left) { return true; } return Binary(node, parent); } function TSConditionalType(node, parent) { const parentType = parent.type; if (parentType === "TSArrayType" || parentType === "TSIndexedAccessType" && parent.objectType === node || parentType === "TSOptionalType" || parentType === "TSTypeOperator" || parentType === "TSTypeParameter") { return true; } if ((parentType === "TSIntersectionType" || parentType === "TSUnionType") && parent.types[0] === node) { return true; } if (parentType === "TSConditionalType" && (parent.checkType === node || parent.extendsType === node)) { return true; } return false; } function TSUnionType(node, parent) { const parentType = parent.type; return parentType === "TSIntersectionType" || parentType === "TSTypeOperator" || parentType === "TSArrayType" || parentType === "TSIndexedAccessType" && parent.objectType === node || parentType === "TSOptionalType"; } function TSIntersectionType(node, parent) { const parentType = parent.type; return parentType === "TSTypeOperator" || parentType === "TSArrayType" || parentType === "TSIndexedAccessType" && parent.objectType === node || parentType === "TSOptionalType"; } function TSInferType(node, parent) { const parentType = parent.type; if (parentType === "TSArrayType" || parentType === "TSIndexedAccessType" && parent.objectType === node || parentType === "TSOptionalType") { return true; } if (node.typeParameter.constraint) { if ((parentType === "TSIntersectionType" || parentType === "TSUnionType") && parent.types[0] === node) { return true; } } return false; } function TSTypeOperator(node, parent) { const parentType = parent.type; return parentType === "TSArrayType" || parentType === "TSIndexedAccessType" && parent.objectType === node || parentType === "TSOptionalType"; } function TSInstantiationExpression(node, parent) { const parentType = parent.type; return (parentType === "CallExpression" || parentType === "OptionalCallExpression" || parentType === "NewExpression" || parentType === "TSInstantiationExpression") && !!parent.typeParameters; } function TSFunctionType(node, parent) { const parentType = parent.type; return parentType === "TSIntersectionType" || parentType === "TSUnionType" || parentType === "TSTypeOperator" || parentType === "TSOptionalType" || parentType === "TSArrayType" || parentType === "TSIndexedAccessType" && parent.objectType === node || parentType === "TSConditionalType" && (parent.checkType === node || parent.extendsType === node); } function BinaryExpression(node, parent, tokenContext, inForStatementInit) { return node.operator === "in" && inForStatementInit; } function SequenceExpression(node, parent) { const parentType = parent.type; if (parentType === "SequenceExpression" || parentType === "ParenthesizedExpression" || parentType === "MemberExpression" && parent.property === node || parentType === "OptionalMemberExpression" && parent.property === node || parentType === "TemplateLiteral") { return false; } if (parentType === "ClassDeclaration") { return true; } if (parentType === "ForOfStatement") { return parent.right === node; } if (parentType === "ExportDefaultDeclaration") { return true; } return !isStatement2(parent); } function YieldExpression(node, parent) { const parentType = parent.type; return parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "UnaryExpression" || parentType === "SpreadElement" || hasPostfixPart(node, parent) || parentType === "AwaitExpression" && isYieldExpression(node) || parentType === "ConditionalExpression" && node === parent.test || isClassExtendsClause(node, parent) || isTSTypeExpression(parentType); } function ClassExpression(node, parent, tokenContext) { return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.exportDefault)); } function UnaryLike(node, parent) { return hasPostfixPart(node, parent) || isBinaryExpression(parent) && parent.operator === "**" && parent.left === node || isClassExtendsClause(node, parent); } function FunctionExpression11(node, parent, tokenContext) { return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.exportDefault)); } function ConditionalExpression(node, parent) { const parentType = parent.type; if (parentType === "UnaryExpression" || parentType === "SpreadElement" || parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "ConditionalExpression" && parent.test === node || parentType === "AwaitExpression" || isTSTypeExpression(parentType)) { return true; } return UnaryLike(node, parent); } function OptionalMemberExpression(node, parent) { return isCallExpression(parent) && parent.callee === node || isMemberExpression2(parent) && parent.object === node; } function AssignmentExpression(node, parent, tokenContext) { if (needsParenBeforeExpressionBrace(tokenContext) && isObjectPattern(node.left)) { return true; } else { return ConditionalExpression(node, parent); } } function LogicalExpression(node, parent) { const parentType = parent.type; if (isTSTypeExpression(parentType)) return true; if (parentType !== "LogicalExpression") return false; switch (node.operator) { case "||": return parent.operator === "??" || parent.operator === "&&"; case "&&": return parent.operator === "??"; case "??": return parent.operator !== "??"; } } function Identifier25(node, parent, tokenContext, _inForInit, getRawIdentifier) { var _node$extra; const parentType = parent.type; if ((_node$extra = node.extra) != null && _node$extra.parenthesized && parentType === "AssignmentExpression" && parent.left === node) { const rightType = parent.right.type; if ((rightType === "FunctionExpression" || rightType === "ClassExpression") && parent.right.id == null) { return true; } } if (getRawIdentifier && getRawIdentifier(node) !== node.name) { return false; } if (node.name === "let") { const isFollowedByBracket = isMemberExpression2(parent, { object: node, computed: true }) || isOptionalMemberExpression2(parent, { object: node, computed: true, optional: false }); if (isFollowedByBracket && tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.forHead | _index.TokenContext.forInHead)) { return true; } return Boolean(tokenContext & _index.TokenContext.forOfHead); } return node.name === "async" && isForOfStatement(parent, { left: node, await: false }); } } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/node/index.js var require_node2 = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/node/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.TokenContext = void 0; exports2.isLastChild = isLastChild; exports2.needsParens = needsParens; exports2.needsWhitespace = needsWhitespace; exports2.needsWhitespaceAfter = needsWhitespaceAfter; exports2.needsWhitespaceBefore = needsWhitespaceBefore; var whitespace = require_whitespace(); var parens = require_parentheses(); var _t = require("@babel/types"); var { FLIPPED_ALIAS_KEYS, VISITOR_KEYS, isCallExpression, isDecorator, isExpressionStatement, isMemberExpression: isMemberExpression2, isNewExpression, isParenthesizedExpression } = _t; var TokenContext = exports2.TokenContext = { expressionStatement: 1, arrowBody: 2, exportDefault: 4, forHead: 8, forInHead: 16, forOfHead: 32, arrowFlowReturnType: 64 }; function expandAliases(obj) { const map2 = /* @__PURE__ */ new Map(); function add(type, func) { const fn = map2.get(type); map2.set(type, fn ? function(node, parent, stack2, inForInit, getRawIdentifier) { var _fn; return (_fn = fn(node, parent, stack2, inForInit, getRawIdentifier)) != null ? _fn : func(node, parent, stack2, inForInit, getRawIdentifier); } : func); } for (const type of Object.keys(obj)) { const aliases = FLIPPED_ALIAS_KEYS[type]; if (aliases) { for (const alias of aliases) { add(alias, obj[type]); } } else { add(type, obj[type]); } } return map2; } var expandedParens = expandAliases(parens); var expandedWhitespaceNodes = expandAliases(whitespace.nodes); function isOrHasCallExpression(node) { if (isCallExpression(node)) { return true; } return isMemberExpression2(node) && isOrHasCallExpression(node.object); } function needsWhitespace(node, parent, type) { var _expandedWhitespaceNo; if (!node) return false; if (isExpressionStatement(node)) { node = node.expression; } const flag = (_expandedWhitespaceNo = expandedWhitespaceNodes.get(node.type)) == null ? void 0 : _expandedWhitespaceNo(node, parent); if (typeof flag === "number") { return (flag & type) !== 0; } return false; } function needsWhitespaceBefore(node, parent) { return needsWhitespace(node, parent, 1); } function needsWhitespaceAfter(node, parent) { return needsWhitespace(node, parent, 2); } function needsParens(node, parent, tokenContext, inForInit, getRawIdentifier) { var _expandedParens$get; if (!parent) return false; if (isNewExpression(parent) && parent.callee === node) { if (isOrHasCallExpression(node)) return true; } if (isDecorator(parent)) { return !isDecoratorMemberExpression(node) && !(isCallExpression(node) && isDecoratorMemberExpression(node.callee)) && !isParenthesizedExpression(node); } return (_expandedParens$get = expandedParens.get(node.type)) == null ? void 0 : _expandedParens$get(node, parent, tokenContext, inForInit, getRawIdentifier); } function isDecoratorMemberExpression(node) { switch (node.type) { case "Identifier": return true; case "MemberExpression": return !node.computed && node.property.type === "Identifier" && isDecoratorMemberExpression(node.object); default: return false; } } function isLastChild(parent, child) { const visitorKeys = VISITOR_KEYS[parent.type]; for (let i = visitorKeys.length - 1; i >= 0; i--) { const val = parent[visitorKeys[i]]; if (val === child) { return true; } else if (Array.isArray(val)) { let j = val.length - 1; while (j >= 0 && val[j] === null) j--; return j >= 0 && val[j] === child; } else if (val) { return false; } } return false; } } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/token-map.js var require_token_map = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/token-map.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.TokenMap = void 0; var _t = require("@babel/types"); var { traverseFast, VISITOR_KEYS } = _t; var TokenMap = class { constructor(ast, tokens, source2) { this._tokens = void 0; this._source = void 0; this._nodesToTokenIndexes = /* @__PURE__ */ new Map(); this._nodesOccurrencesCountCache = /* @__PURE__ */ new Map(); this._tokensCache = /* @__PURE__ */ new Map(); this._tokens = tokens; this._source = source2; traverseFast(ast, (node) => { const indexes = this._getTokensIndexesOfNode(node); if (indexes.length > 0) this._nodesToTokenIndexes.set(node, indexes); }); this._tokensCache = null; } has(node) { return this._nodesToTokenIndexes.has(node); } getIndexes(node) { return this._nodesToTokenIndexes.get(node); } find(node, condition) { const indexes = this._nodesToTokenIndexes.get(node); if (indexes) { for (let k = 0; k < indexes.length; k++) { const index = indexes[k]; const tok = this._tokens[index]; if (condition(tok, index)) return tok; } } return null; } findLastIndex(node, condition) { const indexes = this._nodesToTokenIndexes.get(node); if (indexes) { for (let k = indexes.length - 1; k >= 0; k--) { const index = indexes[k]; const tok = this._tokens[index]; if (condition(tok, index)) return index; } } return -1; } findMatching(node, test, occurrenceCount = 0) { const indexes = this._nodesToTokenIndexes.get(node); if (indexes) { let i = 0; const count = occurrenceCount; if (count > 1) { const cache = this._nodesOccurrencesCountCache.get(node); if (cache && cache.test === test && cache.count < count) { i = cache.i + 1; occurrenceCount -= cache.count + 1; } } for (; i < indexes.length; i++) { const tok = this._tokens[indexes[i]]; if (this.matchesOriginal(tok, test)) { if (occurrenceCount === 0) { if (count > 0) { this._nodesOccurrencesCountCache.set(node, { test, count, i }); } return tok; } occurrenceCount--; } } } return null; } matchesOriginal(token2, test) { if (token2.end - token2.start !== test.length) return false; if (token2.value != null) return token2.value === test; return this._source.startsWith(test, token2.start); } startMatches(node, test) { const indexes = this._nodesToTokenIndexes.get(node); if (!indexes) return false; const tok = this._tokens[indexes[0]]; if (tok.start !== node.start) return false; return this.matchesOriginal(tok, test); } endMatches(node, test) { const indexes = this._nodesToTokenIndexes.get(node); if (!indexes) return false; const tok = this._tokens[indexes[indexes.length - 1]]; if (tok.end !== node.end) return false; return this.matchesOriginal(tok, test); } _getTokensIndexesOfNode(node) { if (node.start == null || node.end == null) return []; const { first, last } = this._findTokensOfNode(node, 0, this._tokens.length - 1); let low = first; const children = childrenIterator(node); if ((node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") && node.declaration && node.declaration.type === "ClassDeclaration") { children.next(); } const indexes = []; for (const child of children) { if (child == null) continue; if (child.start == null || child.end == null) continue; const childTok = this._findTokensOfNode(child, low, last); const high = childTok.first; for (let k = low; k < high; k++) indexes.push(k); low = childTok.last + 1; } for (let k = low; k <= last; k++) indexes.push(k); return indexes; } _findTokensOfNode(node, low, high) { const cached2 = this._tokensCache.get(node); if (cached2) return cached2; const first = this._findFirstTokenOfNode(node.start, low, high); const last = this._findLastTokenOfNode(node.end, first, high); this._tokensCache.set(node, { first, last }); return { first, last }; } _findFirstTokenOfNode(start, low, high) { while (low <= high) { const mid = high + low >> 1; if (start < this._tokens[mid].start) { high = mid - 1; } else if (start > this._tokens[mid].start) { low = mid + 1; } else { return mid; } } return low; } _findLastTokenOfNode(end, low, high) { while (low <= high) { const mid = high + low >> 1; if (end < this._tokens[mid].end) { high = mid - 1; } else if (end > this._tokens[mid].end) { low = mid + 1; } else { return mid; } } return high; } }; exports2.TokenMap = TokenMap; function* childrenIterator(node) { if (node.type === "TemplateLiteral") { yield node.quasis[0]; for (let i = 1; i < node.quasis.length; i++) { yield node.expressions[i - 1]; yield node.quasis[i]; } return; } const keys = VISITOR_KEYS[node.type]; for (const key2 of keys) { const child = node[key2]; if (!child) continue; if (Array.isArray(child)) { yield* __yieldStar(child); } else { yield child; } } } } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/template-literals.js var require_template_literals = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/template-literals.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.TaggedTemplateExpression = TaggedTemplateExpression; exports2.TemplateElement = TemplateElement; exports2.TemplateLiteral = TemplateLiteral; exports2._printTemplate = _printTemplate; function TaggedTemplateExpression(node) { this.print(node.tag); { this.print(node.typeParameters); } this.print(node.quasi); } function TemplateElement() { throw new Error("TemplateElement printing is handled in TemplateLiteral"); } function _printTemplate(node, substitutions) { const quasis = node.quasis; let partRaw = "`"; for (let i = 0; i < quasis.length - 1; i++) { partRaw += quasis[i].value.raw; this.token(partRaw + "${", true); this.print(substitutions[i]); partRaw = "}"; if (this.tokenMap) { const token2 = this.tokenMap.findMatching(node, "}", i); if (token2) this._catchUpTo(token2.loc.start); } } partRaw += quasis[quasis.length - 1].value.raw; this.token(partRaw + "`", true); } function TemplateLiteral(node) { this._printTemplate(node, node.expressions); } } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/expressions.js var require_expressions = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/expressions.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.LogicalExpression = exports2.BinaryExpression = exports2.AssignmentExpression = AssignmentExpression; exports2.AssignmentPattern = AssignmentPattern; exports2.AwaitExpression = AwaitExpression; exports2.BindExpression = BindExpression; exports2.CallExpression = CallExpression4; exports2.ConditionalExpression = ConditionalExpression; exports2.Decorator = Decorator; exports2.DoExpression = DoExpression; exports2.EmptyStatement = EmptyStatement; exports2.ExpressionStatement = ExpressionStatement; exports2.Import = Import; exports2.MemberExpression = MemberExpression; exports2.MetaProperty = MetaProperty; exports2.ModuleExpression = ModuleExpression; exports2.NewExpression = NewExpression; exports2.OptionalCallExpression = OptionalCallExpression; exports2.OptionalMemberExpression = OptionalMemberExpression; exports2.ParenthesizedExpression = ParenthesizedExpression; exports2.PrivateName = PrivateName; exports2.SequenceExpression = SequenceExpression; exports2.Super = Super; exports2.ThisExpression = ThisExpression; exports2.UnaryExpression = UnaryExpression; exports2.UpdateExpression = UpdateExpression; exports2.V8IntrinsicIdentifier = V8IntrinsicIdentifier; exports2.YieldExpression = YieldExpression; exports2._shouldPrintDecoratorsBeforeExport = _shouldPrintDecoratorsBeforeExport; var _t = require("@babel/types"); var _index = require_node2(); var { isCallExpression, isLiteral, isMemberExpression: isMemberExpression2, isNewExpression, isPattern } = _t; function UnaryExpression(node) { const { operator } = node; if (operator === "void" || operator === "delete" || operator === "typeof" || operator === "throw") { this.word(operator); this.space(); } else { this.token(operator); } this.print(node.argument); } function DoExpression(node) { if (node.async) { this.word("async", true); this.space(); } this.word("do"); this.space(); this.print(node.body); } function ParenthesizedExpression(node) { this.tokenChar(40); const exit = this.enterDelimited(); this.print(node.expression); exit(); this.rightParens(node); } function UpdateExpression(node) { if (node.prefix) { this.token(node.operator); this.print(node.argument); } else { this.print(node.argument, true); this.token(node.operator); } } function ConditionalExpression(node) { this.print(node.test); this.space(); this.tokenChar(63); this.space(); this.print(node.consequent); this.space(); this.tokenChar(58); this.space(); this.print(node.alternate); } function NewExpression(node, parent) { this.word("new"); this.space(); this.print(node.callee); if (this.format.minified && node.arguments.length === 0 && !node.optional && !isCallExpression(parent, { callee: node }) && !isMemberExpression2(parent) && !isNewExpression(parent)) { return; } this.print(node.typeArguments); { this.print(node.typeParameters); } if (node.optional) { this.token("?."); } if (node.arguments.length === 0 && this.tokenMap && !this.tokenMap.endMatches(node, ")")) { return; } this.tokenChar(40); const exit = this.enterDelimited(); this.printList(node.arguments, this.shouldPrintTrailingComma(")")); exit(); this.rightParens(node); } function SequenceExpression(node) { this.printList(node.expressions); } function ThisExpression() { this.word("this"); } function Super() { this.word("super"); } function _shouldPrintDecoratorsBeforeExport(node) { if (typeof this.format.decoratorsBeforeExport === "boolean") { return this.format.decoratorsBeforeExport; } return typeof node.start === "number" && node.start === node.declaration.start; } function Decorator(node) { this.tokenChar(64); this.print(node.expression); this.newline(); } function OptionalMemberExpression(node) { let { computed } = node; const { optional: optional2, property } = node; this.print(node.object); if (!computed && isMemberExpression2(property)) { throw new TypeError("Got a MemberExpression for MemberExpression property"); } if (isLiteral(property) && typeof property.value === "number") { computed = true; } if (optional2) { this.token("?."); } if (computed) { this.tokenChar(91); this.print(property); this.tokenChar(93); } else { if (!optional2) { this.tokenChar(46); } this.print(property); } } function OptionalCallExpression(node) { this.print(node.callee); { this.print(node.typeParameters); } if (node.optional) { this.token("?."); } this.print(node.typeArguments); this.tokenChar(40); const exit = this.enterDelimited(); this.printList(node.arguments); exit(); this.rightParens(node); } function CallExpression4(node) { this.print(node.callee); this.print(node.typeArguments); { this.print(node.typeParameters); } this.tokenChar(40); const exit = this.enterDelimited(); this.printList(node.arguments, this.shouldPrintTrailingComma(")")); exit(); this.rightParens(node); } function Import() { this.word("import"); } function AwaitExpression(node) { this.word("await"); if (node.argument) { this.space(); this.printTerminatorless(node.argument); } } function YieldExpression(node) { this.word("yield", true); if (node.delegate) { this.tokenChar(42); if (node.argument) { this.space(); this.print(node.argument); } } else { if (node.argument) { this.space(); this.printTerminatorless(node.argument); } } } function EmptyStatement() { this.semicolon(true); } function ExpressionStatement(node) { this.tokenContext |= _index.TokenContext.expressionStatement; this.print(node.expression); this.semicolon(); } function AssignmentPattern(node) { this.print(node.left); if (node.left.type === "Identifier" || isPattern(node.left)) { if (node.left.optional) this.tokenChar(63); this.print(node.left.typeAnnotation); } this.space(); this.tokenChar(61); this.space(); this.print(node.right); } function AssignmentExpression(node) { this.print(node.left); this.space(); if (node.operator === "in" || node.operator === "instanceof") { this.word(node.operator); } else { this.token(node.operator); this._endsWithDiv = node.operator === "/"; } this.space(); this.print(node.right); } function BindExpression(node) { this.print(node.object); this.token("::"); this.print(node.callee); } function MemberExpression(node) { this.print(node.object); if (!node.computed && isMemberExpression2(node.property)) { throw new TypeError("Got a MemberExpression for MemberExpression property"); } let computed = node.computed; if (isLiteral(node.property) && typeof node.property.value === "number") { computed = true; } if (computed) { const exit = this.enterDelimited(); this.tokenChar(91); this.print(node.property); this.tokenChar(93); exit(); } else { this.tokenChar(46); this.print(node.property); } } function MetaProperty(node) { this.print(node.meta); this.tokenChar(46); this.print(node.property); } function PrivateName(node) { this.tokenChar(35); this.print(node.id); } function V8IntrinsicIdentifier(node) { this.tokenChar(37); this.word(node.name); } function ModuleExpression(node) { this.word("module", true); this.space(); this.tokenChar(123); this.indent(); const { body } = node; if (body.body.length || body.directives.length) { this.newline(); } this.print(body); this.dedent(); this.rightBrace(node); } } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/statements.js var require_statements = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/statements.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.BreakStatement = BreakStatement; exports2.CatchClause = CatchClause; exports2.ContinueStatement = ContinueStatement; exports2.DebuggerStatement = DebuggerStatement; exports2.DoWhileStatement = DoWhileStatement; exports2.ForOfStatement = exports2.ForInStatement = void 0; exports2.ForStatement = ForStatement; exports2.IfStatement = IfStatement; exports2.LabeledStatement = LabeledStatement; exports2.ReturnStatement = ReturnStatement; exports2.SwitchCase = SwitchCase; exports2.SwitchStatement = SwitchStatement; exports2.ThrowStatement = ThrowStatement; exports2.TryStatement = TryStatement; exports2.VariableDeclaration = VariableDeclaration; exports2.VariableDeclarator = VariableDeclarator; exports2.WhileStatement = WhileStatement; exports2.WithStatement = WithStatement; var _t = require("@babel/types"); var _index = require_node2(); var { isFor, isForStatement, isIfStatement, isStatement: isStatement2 } = _t; function WithStatement(node) { this.word("with"); this.space(); this.tokenChar(40); this.print(node.object); this.tokenChar(41); this.printBlock(node); } function IfStatement(node) { this.word("if"); this.space(); this.tokenChar(40); this.print(node.test); this.tokenChar(41); this.space(); const needsBlock = node.alternate && isIfStatement(getLastStatement(node.consequent)); if (needsBlock) { this.tokenChar(123); this.newline(); this.indent(); } this.printAndIndentOnComments(node.consequent); if (needsBlock) { this.dedent(); this.newline(); this.tokenChar(125); } if (node.alternate) { if (this.endsWith(125)) this.space(); this.word("else"); this.space(); this.printAndIndentOnComments(node.alternate); } } function getLastStatement(statement) { const { body } = statement; if (isStatement2(body) === false) { return statement; } return getLastStatement(body); } function ForStatement(node) { this.word("for"); this.space(); this.tokenChar(40); { const exit = this.enterForStatementInit(); this.tokenContext |= _index.TokenContext.forHead; this.print(node.init); exit(); } this.tokenChar(59); if (node.test) { this.space(); this.print(node.test); } this.token(";", false, 1); if (node.update) { this.space(); this.print(node.update); } this.tokenChar(41); this.printBlock(node); } function WhileStatement(node) { this.word("while"); this.space(); this.tokenChar(40); this.print(node.test); this.tokenChar(41); this.printBlock(node); } function ForXStatement(node) { this.word("for"); this.space(); const isForOf = node.type === "ForOfStatement"; if (isForOf && node.await) { this.word("await"); this.space(); } this.noIndentInnerCommentsHere(); this.tokenChar(40); { const exit = isForOf ? null : this.enterForStatementInit(); this.tokenContext |= isForOf ? _index.TokenContext.forOfHead : _index.TokenContext.forInHead; this.print(node.left); exit == null || exit(); } this.space(); this.word(isForOf ? "of" : "in"); this.space(); this.print(node.right); this.tokenChar(41); this.printBlock(node); } var ForInStatement = exports2.ForInStatement = ForXStatement; var ForOfStatement = exports2.ForOfStatement = ForXStatement; function DoWhileStatement(node) { this.word("do"); this.space(); this.print(node.body); this.space(); this.word("while"); this.space(); this.tokenChar(40); this.print(node.test); this.tokenChar(41); this.semicolon(); } function printStatementAfterKeyword(printer, node) { if (node) { printer.space(); printer.printTerminatorless(node); } printer.semicolon(); } function BreakStatement(node) { this.word("break"); printStatementAfterKeyword(this, node.label); } function ContinueStatement(node) { this.word("continue"); printStatementAfterKeyword(this, node.label); } function ReturnStatement(node) { this.word("return"); printStatementAfterKeyword(this, node.argument); } function ThrowStatement(node) { this.word("throw"); printStatementAfterKeyword(this, node.argument); } function LabeledStatement(node) { this.print(node.label); this.tokenChar(58); this.space(); this.print(node.body); } function TryStatement(node) { this.word("try"); this.space(); this.print(node.block); this.space(); if (node.handlers) { this.print(node.handlers[0]); } else { this.print(node.handler); } if (node.finalizer) { this.space(); this.word("finally"); this.space(); this.print(node.finalizer); } } function CatchClause(node) { this.word("catch"); this.space(); if (node.param) { this.tokenChar(40); this.print(node.param); this.print(node.param.typeAnnotation); this.tokenChar(41); this.space(); } this.print(node.body); } function SwitchStatement(node) { this.word("switch"); this.space(); this.tokenChar(40); this.print(node.discriminant); this.tokenChar(41); this.space(); this.tokenChar(123); this.printSequence(node.cases, true, void 0, function addNewlines(leading, cas) { if (!leading && node.cases[node.cases.length - 1] === cas) return -1; }); this.rightBrace(node); } function SwitchCase(node) { if (node.test) { this.word("case"); this.space(); this.print(node.test); this.tokenChar(58); } else { this.word("default"); this.tokenChar(58); } if (node.consequent.length) { this.newline(); this.printSequence(node.consequent, true); } } function DebuggerStatement() { this.word("debugger"); this.semicolon(); } function VariableDeclaration(node, parent) { if (node.declare) { this.word("declare"); this.space(); } const { kind } = node; if (kind === "await using") { this.word("await"); this.space(); this.word("using", true); } else { this.word(kind, kind === "using"); } this.space(); let hasInits = false; if (!isFor(parent)) { for (const declar of node.declarations) { if (declar.init) { hasInits = true; } } } this.printList(node.declarations, void 0, void 0, node.declarations.length > 1, hasInits ? function(occurrenceCount) { this.token(",", false, occurrenceCount); this.newline(); } : void 0); if (isFor(parent)) { if (isForStatement(parent)) { if (parent.init === node) return; } else { if (parent.left === node) return; } } this.semicolon(); } function VariableDeclarator(node) { this.print(node.id); if (node.definite) this.tokenChar(33); this.print(node.id.typeAnnotation); if (node.init) { this.space(); this.tokenChar(61); this.space(); this.print(node.init); } } } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/classes.js var require_classes = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/classes.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ClassAccessorProperty = ClassAccessorProperty; exports2.ClassBody = ClassBody; exports2.ClassExpression = exports2.ClassDeclaration = ClassDeclaration; exports2.ClassMethod = ClassMethod; exports2.ClassPrivateMethod = ClassPrivateMethod; exports2.ClassPrivateProperty = ClassPrivateProperty; exports2.ClassProperty = ClassProperty; exports2.StaticBlock = StaticBlock; exports2._classMethodHead = _classMethodHead; var _t = require("@babel/types"); var { isExportDefaultDeclaration, isExportNamedDeclaration } = _t; function ClassDeclaration(node, parent) { const inExport = isExportDefaultDeclaration(parent) || isExportNamedDeclaration(parent); if (!inExport || !this._shouldPrintDecoratorsBeforeExport(parent)) { this.printJoin(node.decorators); } if (node.declare) { this.word("declare"); this.space(); } if (node.abstract) { this.word("abstract"); this.space(); } this.word("class"); if (node.id) { this.space(); this.print(node.id); } this.print(node.typeParameters); if (node.superClass) { this.space(); this.word("extends"); this.space(); this.print(node.superClass); this.print(node.superTypeParameters); } if (node.implements) { this.space(); this.word("implements"); this.space(); this.printList(node.implements); } this.space(); this.print(node.body); } function ClassBody(node) { this.tokenChar(123); if (node.body.length === 0) { this.tokenChar(125); } else { this.newline(); const separator = classBodyEmptySemicolonsPrinter(this, node); separator == null || separator(-1); const exit = this.enterDelimited(); this.printJoin(node.body, true, true, separator, true); exit(); if (!this.endsWith(10)) this.newline(); this.rightBrace(node); } } function classBodyEmptySemicolonsPrinter(printer, node) { if (!printer.tokenMap || node.start == null || node.end == null) { return null; } const indexes = printer.tokenMap.getIndexes(node); if (!indexes) return null; let k = 1; let occurrenceCount = 0; let nextLocIndex = 0; const advanceNextLocIndex = () => { while (nextLocIndex < node.body.length && node.body[nextLocIndex].start == null) { nextLocIndex++; } }; advanceNextLocIndex(); return (i) => { if (nextLocIndex <= i) { nextLocIndex = i + 1; advanceNextLocIndex(); } const end = nextLocIndex === node.body.length ? node.end : node.body[nextLocIndex].start; let tok; while (k < indexes.length && printer.tokenMap.matchesOriginal(tok = printer._tokens[indexes[k]], ";") && tok.start < end) { printer.token(";", void 0, occurrenceCount++); k++; } }; } function ClassProperty(node) { this.printJoin(node.decorators); if (!node.static && !this.format.preserveFormat) { var _node$key$loc; const endLine = (_node$key$loc = node.key.loc) == null || (_node$key$loc = _node$key$loc.end) == null ? void 0 : _node$key$loc.line; if (endLine) this.catchUp(endLine); } this.tsPrintClassMemberModifiers(node); if (node.computed) { this.tokenChar(91); this.print(node.key); this.tokenChar(93); } else { this._variance(node); this.print(node.key); } if (node.optional) { this.tokenChar(63); } if (node.definite) { this.tokenChar(33); } this.print(node.typeAnnotation); if (node.value) { this.space(); this.tokenChar(61); this.space(); this.print(node.value); } this.semicolon(); } function ClassAccessorProperty(node) { var _node$key$loc2; this.printJoin(node.decorators); const endLine = (_node$key$loc2 = node.key.loc) == null || (_node$key$loc2 = _node$key$loc2.end) == null ? void 0 : _node$key$loc2.line; if (endLine) this.catchUp(endLine); this.tsPrintClassMemberModifiers(node); this.word("accessor", true); this.space(); if (node.computed) { this.tokenChar(91); this.print(node.key); this.tokenChar(93); } else { this._variance(node); this.print(node.key); } if (node.optional) { this.tokenChar(63); } if (node.definite) { this.tokenChar(33); } this.print(node.typeAnnotation); if (node.value) { this.space(); this.tokenChar(61); this.space(); this.print(node.value); } this.semicolon(); } function ClassPrivateProperty(node) { this.printJoin(node.decorators); this.tsPrintClassMemberModifiers(node); this.print(node.key); if (node.optional) { this.tokenChar(63); } if (node.definite) { this.tokenChar(33); } this.print(node.typeAnnotation); if (node.value) { this.space(); this.tokenChar(61); this.space(); this.print(node.value); } this.semicolon(); } function ClassMethod(node) { this._classMethodHead(node); this.space(); this.print(node.body); } function ClassPrivateMethod(node) { this._classMethodHead(node); this.space(); this.print(node.body); } function _classMethodHead(node) { this.printJoin(node.decorators); if (!this.format.preserveFormat) { var _node$key$loc3; const endLine = (_node$key$loc3 = node.key.loc) == null || (_node$key$loc3 = _node$key$loc3.end) == null ? void 0 : _node$key$loc3.line; if (endLine) this.catchUp(endLine); } this.tsPrintClassMemberModifiers(node); this._methodHead(node); } function StaticBlock(node) { this.word("static"); this.space(); this.tokenChar(123); if (node.body.length === 0) { this.tokenChar(125); } else { this.newline(); this.printSequence(node.body, true); this.rightBrace(node); } } } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/methods.js var require_methods = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/methods.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ArrowFunctionExpression = ArrowFunctionExpression; exports2.FunctionDeclaration = exports2.FunctionExpression = FunctionExpression11; exports2._functionHead = _functionHead; exports2._methodHead = _methodHead; exports2._param = _param; exports2._parameters = _parameters; exports2._params = _params; exports2._predicate = _predicate; exports2._shouldPrintArrowParamsParens = _shouldPrintArrowParamsParens; var _t = require("@babel/types"); var _index = require_node2(); var { isIdentifier } = _t; function _params(node, idNode, parentNode) { this.print(node.typeParameters); const nameInfo = _getFuncIdName.call(this, idNode, parentNode); if (nameInfo) { this.sourceIdentifierName(nameInfo.name, nameInfo.pos); } this.tokenChar(40); this._parameters(node.params, ")"); const noLineTerminator = node.type === "ArrowFunctionExpression"; this.print(node.returnType, noLineTerminator); this._noLineTerminator = noLineTerminator; } function _parameters(parameters, endToken) { const exit = this.enterDelimited(); const trailingComma = this.shouldPrintTrailingComma(endToken); const paramLength = parameters.length; for (let i = 0; i < paramLength; i++) { this._param(parameters[i]); if (trailingComma || i < paramLength - 1) { this.token(",", null, i); this.space(); } } this.token(endToken); exit(); } function _param(parameter) { this.printJoin(parameter.decorators); this.print(parameter); if (parameter.optional) { this.tokenChar(63); } this.print(parameter.typeAnnotation); } function _methodHead(node) { const kind = node.kind; const key2 = node.key; if (kind === "get" || kind === "set") { this.word(kind); this.space(); } if (node.async) { this.word("async", true); this.space(); } if (kind === "method" || kind === "init") { if (node.generator) { this.tokenChar(42); } } if (node.computed) { this.tokenChar(91); this.print(key2); this.tokenChar(93); } else { this.print(key2); } if (node.optional) { this.tokenChar(63); } this._params(node, node.computed && node.key.type !== "StringLiteral" ? void 0 : node.key, void 0); } function _predicate(node, noLineTerminatorAfter) { if (node.predicate) { if (!node.returnType) { this.tokenChar(58); } this.space(); this.print(node.predicate, noLineTerminatorAfter); } } function _functionHead(node, parent) { if (node.async) { this.word("async"); if (!this.format.preserveFormat) { this._endsWithInnerRaw = false; } this.space(); } this.word("function"); if (node.generator) { if (!this.format.preserveFormat) { this._endsWithInnerRaw = false; } this.tokenChar(42); } this.space(); if (node.id) { this.print(node.id); } this._params(node, node.id, parent); if (node.type !== "TSDeclareFunction") { this._predicate(node); } } function FunctionExpression11(node, parent) { this._functionHead(node, parent); this.space(); this.print(node.body); } function ArrowFunctionExpression(node, parent) { if (node.async) { this.word("async", true); this.space(); } if (this._shouldPrintArrowParamsParens(node)) { this._params(node, void 0, parent); } else { this.print(node.params[0], true); } this._predicate(node, true); this.space(); this.printInnerComments(); this.token("=>"); this.space(); this.tokenContext |= _index.TokenContext.arrowBody; this.print(node.body); } function _shouldPrintArrowParamsParens(node) { var _firstParam$leadingCo, _firstParam$trailingC; if (node.params.length !== 1) return true; if (node.typeParameters || node.returnType || node.predicate) { return true; } const firstParam = node.params[0]; if (!isIdentifier(firstParam) || firstParam.typeAnnotation || firstParam.optional || (_firstParam$leadingCo = firstParam.leadingComments) != null && _firstParam$leadingCo.length || (_firstParam$trailingC = firstParam.trailingComments) != null && _firstParam$trailingC.length) { return true; } if (this.tokenMap) { if (node.loc == null) return true; if (this.tokenMap.findMatching(node, "(") !== null) return true; const arrowToken = this.tokenMap.findMatching(node, "=>"); if ((arrowToken == null ? void 0 : arrowToken.loc) == null) return true; return arrowToken.loc.start.line !== node.loc.start.line; } if (this.format.retainLines) return true; return false; } function _getFuncIdName(idNode, parent) { let id = idNode; if (!id && parent) { const parentType = parent.type; if (parentType === "VariableDeclarator") { id = parent.id; } else if (parentType === "AssignmentExpression" || parentType === "AssignmentPattern") { id = parent.left; } else if (parentType === "ObjectProperty" || parentType === "ClassProperty") { if (!parent.computed || parent.key.type === "StringLiteral") { id = parent.key; } } else if (parentType === "ClassPrivateProperty" || parentType === "ClassAccessorProperty") { id = parent.key; } } if (!id) return; let nameInfo; if (id.type === "Identifier") { var _id$loc, _id$loc2; nameInfo = { pos: (_id$loc = id.loc) == null ? void 0 : _id$loc.start, name: ((_id$loc2 = id.loc) == null ? void 0 : _id$loc2.identifierName) || id.name }; } else if (id.type === "PrivateName") { var _id$loc3; nameInfo = { pos: (_id$loc3 = id.loc) == null ? void 0 : _id$loc3.start, name: "#" + id.id.name }; } else if (id.type === "StringLiteral") { var _id$loc4; nameInfo = { pos: (_id$loc4 = id.loc) == null ? void 0 : _id$loc4.start, name: id.value }; } return nameInfo; } } }); // node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/modules.js var require_modules = __commonJS({ "node_modules/@babel/helpers/node_modules/@babel/generator/lib/generators/modules.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ExportAllDeclaration = ExportAllDeclaration; exports2.ExportDefaultDeclaration = ExportDefaultDeclaration; exports2.ExportDefaultSpecifier = ExportDefaultSpecifier; exports2.ExportNamedDeclaration = ExportNamedDeclaration; exports2.ExportNamespaceSpecifier = ExportNamespaceSpecifier; exports2.ExportSpecifier = ExportSpecifier; exports2.ImportAttribute = ImportAttribute; exports2.ImportDeclaration = ImportDeclaration; exports2.ImportDefaultSpecifier = ImportDefaultSpecifier; exports2.ImportExpression = ImportExpression; exports2.ImportNamespaceSpecifier = ImportNamespaceSpecifier; exports2.ImportSpecifier = ImportSpecifier; exports2._printAttributes = _printAttributes; var _t = require("@babel/types"); var _index = require_node2(); var { isClassDeclaration, isExportDefaultSpecifier, isExportNamespaceSpecifier, isImportDefaultSpecifier, isImportNamespaceSpecifier, isStatement: isStatement2 } = _t; function ImportSpecifier(node) { if (node.importKind === "type" || node.importKind === "typeof") { this.word(node.importKind); this.space(); } this.print(node.imported); if (node.local && node.local.name !== node.imported.name) { this.space(); this.word("as"); this.space(); this.print(node.local); } } function ImportDefaultSpecifier(node) { this.print(node.local); } function ExportDefaultSpecifier(node) { this.print(node.exported); } function ExportSpecifier(node) { if (node.exportKind === "type") { this.word("type"); this.space(); } this.print(node.local); if (node.exported && node.local.name !== node.exported.name) { this.space(); this.word("as"); this.space(); this.print(node.exported); } } function ExportNamespaceSpecifier(node) { this.tokenChar(42); this.space(); this.word("as"); this.space(); this.print(node.exported); } var warningShown = false; function _printAttributes(node, hasPreviousBrace) { var _node$extra; const { importAttributesKeyword } = this.format; const { attributes, assertions } = node; if (attributes && !importAttributesKeyword && node.extra && (node.extra.deprecatedAssertSyntax || node.extra.deprecatedWithLegacySyntax) && !warningShown) { warningShown = true; console.warn(`You are using import attributes, without specifying the desired output syntax. Please specify the "importAttributesKeyword" generator option, whose value can be one of: - "with" : \`import { a } from "b" with { type: "json" };\` - "assert" : \`import { a } from "b" assert { type: "json" };\` - "with-legacy" : \`import { a } from "b" with type: "json";\` `); } const useAssertKeyword = importAttributesKeyword === "assert" || !importAttributesKeyword && assertions; this.word(useAssertKeyword ? "assert" : "with"); this.space(); if (!useAssertKeyword && (importAttributesKeyword === "with-legacy" || !importAttributesKeyword && (_node$extra = node.extra) != null && _node$extra.deprecatedWithLegacySyntax)) { this.printList(attributes || assertions); return; } const occurrenceCount = hasPreviousBrace ? 1 : 0; this.token("{", null, occurrenceCount); this.space(); this.printList(attributes || assertions, this.shouldPrintTrailingComma("}")); this.space(); this.token("}", null, occurrenceCount); } function ExportAllDeclaration(node) { var _node$attributes, _node$assertions; this.word("export"); this.space(); if (node.exportKind === "type") { this.word("type"); this.space(); } this.tokenChar(42); this.space(); this.word("from"); this.space(); if ((_node$attributes = node.attributes) != null && _node$attributes.length || (_node$assertions = node.assertions) != null && _node$assertions.length) { this.print(node.source, true); this.space(); this._printAttributes(node, false); } else { this.print(node.source); } this.semicolon(); } function maybePrintDecoratorsBeforeExport(printer, node) { if (isClassDeclaration(node.declaration) && printer._shouldPrintDecoratorsBeforeExport(node)) { printer.printJoin(node.declaration.decorators); } } function ExportNamedDeclaration(node) { maybePrintDecoratorsBeforeExport(this, node); this.word("export"); this.space(); if (node.declaration) { const declar = node.declaration; this.print(declar); if (!isStatement2(declar)) this.semicolon(); } else { if (node.exportKind === "type") { this.word("type"); this.space(); } const specifiers = node.specifiers.slice(0); let hasSpecial = false; for (; ; ) { const first = specifiers[0]; if (isExportDefaultSpecifier(first) || isExportNamespaceSpecifier(first)) { hasSpecial = true; this.print(specifiers.shift()); if (specifiers.length) { this.tokenChar(44); this.space(); } } else { break; } } let hasBrace = false; if (specifiers.length || !specifiers.length && !hasSpecial) { hasBrace = true; this.tokenChar(123); if (specifiers.length) { this.space(); this.printList(specifiers, this.shouldPrintTrailingComma("}")); this.space(); } this.tokenChar(125); } if (node.source) { var _node$attributes2, _node$assertions2; this.space(); this.word("from"); this.space(); if ((_node$attributes2 = node.attributes) != null && _node$attributes2.length || (_node$assertions2 = node.assertions) != null && _node$assertions2.length) { this.print(node.source, true); this.space(); this._printAttributes(node, hasBrace); } else { this.print(node.source); } } this.semicolon(); } } function ExportDefaultDeclaration(node) { maybePrintDecoratorsBeforeExport(this, node); this.word("export"); this.noIndentInnerCommentsHere(); this.space(); this.word("default"); this.space(); this.tokenContext |= _index.TokenContext.exportDefault; const declar = node.declaration; this.print(declar); if (!isStatement2(declar)) this.semicolon(); } function ImportDeclaration(node) { var _node$attributes3, _node$assertions3; this.word("import"); this.space(); const isTypeKind = node.importKind === "type" || node.importKind === "typeof"; if (isTypeKind) { this.noIndentInnerCommentsHere(); this.word(node.importKind); this.space(); } else if (node.module) { this.noIndentInnerCommentsHere(); this.word("module"); this.space(); } else if (node.phase) { this.noIndentInnerCommentsHere(); this.word(node.phase); this.space(); } const specifiers = node.specifiers.slice(0); const hasSpecifiers = !!specifiers.length; while (hasSpecifiers) { const first = specifiers[0]; if (isImportDefaultSpecifier(first) || isImportNamespaceSpecifier(first)) { this.print(specifiers.shift()); if (specifiers.length) { this.tokenChar(44); this.space(); } } else { break; } } let hasBrace = false; if (specifiers.length) { hasBrace = true; this.tokenChar(123); this.space(); this.printList(specifiers, this.shouldPrintTrailingComma("}")); this.space(); this.tokenChar(125); } else if (isTypeKind && !hasSpecifiers) { hasBrace = true; this.tokenChar(123); this.tokenChar(125); } if (hasSpecifiers || isTypeKind) { this.space(); this.word("from"); this.space(); } if ((_node$attributes3 = node.attributes) != null && _node$attributes3.length || (_node$assertions3 = node.assertions) != null && _node$assertions3.length) { this.print(node.source, true); this.space(); this._printAttributes(node, hasBrace); } else { this.print(node.source); } this.semicolon(); } function ImportAttribute(node) { this.print(node.key); this.tokenChar(58); this.space(); this.print(node.value); } function ImportNamespaceSpecifier(node) { this.tokenChar(42); this.space(); this.word("as"); this.space(); this.print(node.local); } function ImportExpression(node) { this.word("import"); if (node.phase) { this.tokenChar(46); this.word(node.phase); } this.tokenChar(40); this.print(node.source); if (node.options != null) { this.tokenChar(44); this.space(); this.print(node.options); } this.tokenChar(41); } } }); // node_modules/@babel/helpers/node_modules/jsesc/jsesc.js var require_jsesc = __commonJS({ "node_modules/@babel/helpers/node_modules/jsesc/jsesc.js"(exports2, module2) { "use strict"; var object2 = {}; var hasOwnProperty3 = object2.hasOwnProperty; var forOwn = (object3, callback) => { for (const key2 in object3) { if (hasOwnProperty3.call(object3, key2)) { callback(key2, object3[key2]); } } }; var extend2 = (destination, source2) => { if (!source2) { return destination; } forOwn(source2, (key2, value) => { destination[key2] = value; }); return destination; }; var forEach = (array2, callback) => { const length = array2.length; let index = -1; while (++index < length) { callback(array2[index]); } }; var fourHexEscape = (hex3) => { return "\\u" + ("0000" + hex3).slice(-4); }; var hexadecimal = (code, lowercase2) => { let hexadecimal2 = code.toString(16); if (lowercase2) return hexadecimal2; return hexadecimal2.toUpperCase(); }; var toString = object2.toString; var isArray = Array.isArray; var isBuffer = (value) => { return typeof Buffer === "function" && Buffer.isBuffer(value); }; var isObject2 = (value) => { return toString.call(value) == "[object Object]"; }; var isString = (value) => { return typeof value == "string" || toString.call(value) == "[object String]"; }; var isNumber = (value) => { return typeof value == "number" || toString.call(value) == "[object Number]"; }; var isBigInt = (value) => { return typeof value == "bigint"; }; var isFunction = (value) => { return typeof value == "function"; }; var isMap = (value) => { return toString.call(value) == "[object Map]"; }; var isSet = (value) => { return toString.call(value) == "[object Set]"; }; var singleEscapes = { "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", " ": "\\t" // `\v` is omitted intentionally, because in IE < 9, '\v' == 'v'. // '\v': '\\x0B' }; var regexSingleEscape = /[\\\b\f\n\r\t]/; var regexDigit = /[0-9]/; var regexWhitespace = /[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/; var escapeEverythingRegex = /([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^]/g; var escapeNonAsciiRegex = /([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^ !#-&\(-\[\]-_a-~]/g; var jsesc = (argument, options) => { const increaseIndentation = () => { oldIndent = indent; ++options.indentLevel; indent = options.indent.repeat(options.indentLevel); }; const defaults = { "escapeEverything": false, "minimal": false, "isScriptContext": false, "quotes": "single", "wrap": false, "es6": false, "json": false, "compact": true, "lowercaseHex": false, "numbers": "decimal", "indent": " ", "indentLevel": 0, "__inline1__": false, "__inline2__": false }; const json2 = options && options.json; if (json2) { defaults.quotes = "double"; defaults.wrap = true; } options = extend2(defaults, options); if (options.quotes != "single" && options.quotes != "double" && options.quotes != "backtick") { options.quotes = "single"; } const quote = options.quotes == "double" ? '"' : options.quotes == "backtick" ? "`" : "'"; const compact = options.compact; const lowercaseHex = options.lowercaseHex; let indent = options.indent.repeat(options.indentLevel); let oldIndent = ""; const inline1 = options.__inline1__; const inline2 = options.__inline2__; const newLine = compact ? "" : "\n"; let result; let isEmpty = true; const useBinNumbers = options.numbers == "binary"; const useOctNumbers = options.numbers == "octal"; const useDecNumbers = options.numbers == "decimal"; const useHexNumbers = options.numbers == "hexadecimal"; if (json2 && argument && isFunction(argument.toJSON)) { argument = argument.toJSON(); } if (!isString(argument)) { if (isMap(argument)) { if (argument.size == 0) { return "new Map()"; } if (!compact) { options.__inline1__ = true; options.__inline2__ = false; } return "new Map(" + jsesc(Array.from(argument), options) + ")"; } if (isSet(argument)) { if (argument.size == 0) { return "new Set()"; } return "new Set(" + jsesc(Array.from(argument), options) + ")"; } if (isBuffer(argument)) { if (argument.length == 0) { return "Buffer.from([])"; } return "Buffer.from(" + jsesc(Array.from(argument), options) + ")"; } if (isArray(argument)) { result = []; options.wrap = true; if (inline1) { options.__inline1__ = false; options.__inline2__ = true; } if (!inline2) { increaseIndentation(); } forEach(argument, (value) => { isEmpty = false; if (inline2) { options.__inline2__ = false; } result.push( (compact || inline2 ? "" : indent) + jsesc(value, options) ); }); if (isEmpty) { return "[]"; } if (inline2) { return "[" + result.join(", ") + "]"; } return "[" + newLine + result.join("," + newLine) + newLine + (compact ? "" : oldIndent) + "]"; } else if (isNumber(argument) || isBigInt(argument)) { if (json2) { return JSON.stringify(Number(argument)); } let result2; if (useDecNumbers) { result2 = String(argument); } else if (useHexNumbers) { let hexadecimal2 = argument.toString(16); if (!lowercaseHex) { hexadecimal2 = hexadecimal2.toUpperCase(); } result2 = "0x" + hexadecimal2; } else if (useBinNumbers) { result2 = "0b" + argument.toString(2); } else if (useOctNumbers) { result2 = "0o" + argument.toString(8); } if (isBigInt(argument)) { return result2 + "n"; } return result2; } else if (isBigInt(argument)) { if (json2) { return JSON.stringify(Number(argument)); } return argument + "n"; } else if (!isObject2(argument)) { if (json2) { return JSON.stringify(argument) || "null"; } return String(argument); } else { result = []; options.wrap = true; increaseIndentation(); forOwn(argument, (key2, value) => { isEmpty = false; result.push( (compact ? "" : indent) + jsesc(key2, options) + ":" + (compact ? "" : " ") + jsesc(value, options) ); }); if (isEmpty) { return "{}"; } return "{" + newLine + result.join("," + newLine) + newLine + (compact ? "" : oldIndent) + "}"; } } const regex = options.escapeEverything ? escapeEverythingRegex : escapeNonAsciiRegex; result = argument.replace(regex, (char, pair, lone, quoteChar, index, string4) => { if (pair) { if (options.minimal) return pair; const first = pair.charCodeAt(0); const second = pair.charCodeAt(1); if (options.es6) { const codePoint = (first - 55296) * 1024 + second - 56320 + 65536; const hex4 = hexadecimal(codePoint, lowercaseHex); return "\\u{" + hex4 + "}"; } return fourHexEscape(hexadecimal(first, lowercaseHex)) + fourHexEscape(hexadecimal(second, lowercaseHex)); } if (lone) { return fourHexEscape(hexadecimal(lone.charCodeAt(0), lowercaseHex)); } if (char == "\0" && !json2 && !regexDigit.test(string4.charAt(index + 1))) { return "\\0"; } if (quoteChar) { if (quoteChar == quote || options.escapeEverything) { return "\\" + quoteChar; } return quoteChar; } if (regexSingleEscape.test(char)) { return singleEscapes[char]; } if (options.minimal && !regexWhitespace.test(char)) { return char; } const hex3 = hexadecimal(char.charCodeAt(0), lowercaseHex); if (json2 || hex3.length > 2) { return fourHexEscape(hex3); } return "\\x" + ("00" + hex3).slice(-2); }); if (quote == "`") { result = result.replace(/\$\{/g, "\\${"); } if (options.isScriptContext) { result = result.replace(/<\/(script|style)/gi, "<\\/$1").replace(/" + commentColor.close; }; exports2.printComment = printComment; var printElement = (type, printedProps, printedChildren, config2, indentation) => { const tagColor = config2.colors.tag; return tagColor.open + "<" + type + (printedProps && tagColor.close + printedProps + config2.spacingOuter + indentation + tagColor.open) + (printedChildren ? ">" + tagColor.close + printedChildren + config2.spacingOuter + indentation + tagColor.open + "" + tagColor.close; }; exports2.printElement = printElement; var printElementAsLeaf = (type, config2) => { const tagColor = config2.colors.tag; return tagColor.open + "<" + type + tagColor.close + " \u2026" + tagColor.open + " />" + tagColor.close; }; exports2.printElementAsLeaf = printElementAsLeaf; } }); // node_modules/pretty-format/build/plugins/DOMElement.js var require_DOMElement = __commonJS({ "node_modules/pretty-format/build/plugins/DOMElement.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = exports2.serialize = exports2.test = void 0; var _markup = require_markup(); var ELEMENT_NODE = 1; var TEXT_NODE = 3; var COMMENT_NODE = 8; var FRAGMENT_NODE = 11; var ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; var testNode = (nodeType, name) => nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name) || nodeType === TEXT_NODE && name === "Text" || nodeType === COMMENT_NODE && name === "Comment" || nodeType === FRAGMENT_NODE && name === "DocumentFragment"; var test = (val) => val && val.constructor && val.constructor.name && testNode(val.nodeType, val.constructor.name); exports2.test = test; function nodeIsText(node) { return node.nodeType === TEXT_NODE; } function nodeIsComment(node) { return node.nodeType === COMMENT_NODE; } function nodeIsFragment(node) { return node.nodeType === FRAGMENT_NODE; } var serialize = (node, config2, indentation, depth, refs, printer) => { if (nodeIsText(node)) { return (0, _markup.printText)(node.data, config2); } if (nodeIsComment(node)) { return (0, _markup.printComment)(node.data, config2); } const type = nodeIsFragment(node) ? `DocumentFragment` : node.tagName.toLowerCase(); if (++depth > config2.maxDepth) { return (0, _markup.printElementAsLeaf)(type, config2); } return (0, _markup.printElement)( type, (0, _markup.printProps)( nodeIsFragment(node) ? [] : Array.from(node.attributes).map((attr) => attr.name).sort(), nodeIsFragment(node) ? [] : Array.from(node.attributes).reduce((props, attribute) => { props[attribute.name] = attribute.value; return props; }, {}), config2, indentation + config2.indent, depth, refs, printer ), (0, _markup.printChildren)( Array.prototype.slice.call(node.childNodes || node.children), config2, indentation + config2.indent, depth, refs, printer ), config2, indentation ); }; exports2.serialize = serialize; var plugin = { serialize, test }; var _default3 = plugin; exports2.default = _default3; } }); // node_modules/pretty-format/build/plugins/Immutable.js var require_Immutable = __commonJS({ "node_modules/pretty-format/build/plugins/Immutable.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = exports2.test = exports2.serialize = void 0; var _collections = require_collections(); var IS_ITERABLE_SENTINEL = "@@__IMMUTABLE_ITERABLE__@@"; var IS_LIST_SENTINEL = "@@__IMMUTABLE_LIST__@@"; var IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@"; var IS_MAP_SENTINEL = "@@__IMMUTABLE_MAP__@@"; var IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@"; var IS_RECORD_SENTINEL = "@@__IMMUTABLE_RECORD__@@"; var IS_SEQ_SENTINEL = "@@__IMMUTABLE_SEQ__@@"; var IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@"; var IS_STACK_SENTINEL = "@@__IMMUTABLE_STACK__@@"; var getImmutableName = (name) => "Immutable." + name; var printAsLeaf = (name) => "[" + name + "]"; var SPACE = " "; var LAZY = "\u2026"; var printImmutableEntries = (val, config2, indentation, depth, refs, printer, type) => ++depth > config2.maxDepth ? printAsLeaf(getImmutableName(type)) : getImmutableName(type) + SPACE + "{" + (0, _collections.printIteratorEntries)( val.entries(), config2, indentation, depth, refs, printer ) + "}"; var getRecordEntries = (val) => { let i = 0; return { next() { if (i < val._keys.length) { const key2 = val._keys[i++]; return { done: false, value: [key2, val.get(key2)] }; } return { done: true }; } }; }; var printImmutableRecord = (val, config2, indentation, depth, refs, printer) => { const name = getImmutableName(val._name || "Record"); return ++depth > config2.maxDepth ? printAsLeaf(name) : name + SPACE + "{" + (0, _collections.printIteratorEntries)( getRecordEntries(val), config2, indentation, depth, refs, printer ) + "}"; }; var printImmutableSeq = (val, config2, indentation, depth, refs, printer) => { const name = getImmutableName("Seq"); if (++depth > config2.maxDepth) { return printAsLeaf(name); } if (val[IS_KEYED_SENTINEL]) { return name + SPACE + "{" + // from Immutable collection of entries or from ECMAScript object (val._iter || val._object ? (0, _collections.printIteratorEntries)( val.entries(), config2, indentation, depth, refs, printer ) : LAZY) + "}"; } return name + SPACE + "[" + (val._iter || // from Immutable collection of values val._array || // from ECMAScript array val._collection || // from ECMAScript collection in immutable v4 val._iterable ? (0, _collections.printIteratorValues)( val.values(), config2, indentation, depth, refs, printer ) : LAZY) + "]"; }; var printImmutableValues = (val, config2, indentation, depth, refs, printer, type) => ++depth > config2.maxDepth ? printAsLeaf(getImmutableName(type)) : getImmutableName(type) + SPACE + "[" + (0, _collections.printIteratorValues)( val.values(), config2, indentation, depth, refs, printer ) + "]"; var serialize = (val, config2, indentation, depth, refs, printer) => { if (val[IS_MAP_SENTINEL]) { return printImmutableEntries( val, config2, indentation, depth, refs, printer, val[IS_ORDERED_SENTINEL] ? "OrderedMap" : "Map" ); } if (val[IS_LIST_SENTINEL]) { return printImmutableValues( val, config2, indentation, depth, refs, printer, "List" ); } if (val[IS_SET_SENTINEL]) { return printImmutableValues( val, config2, indentation, depth, refs, printer, val[IS_ORDERED_SENTINEL] ? "OrderedSet" : "Set" ); } if (val[IS_STACK_SENTINEL]) { return printImmutableValues( val, config2, indentation, depth, refs, printer, "Stack" ); } if (val[IS_SEQ_SENTINEL]) { return printImmutableSeq(val, config2, indentation, depth, refs, printer); } return printImmutableRecord(val, config2, indentation, depth, refs, printer); }; exports2.serialize = serialize; var test = (val) => val && (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); exports2.test = test; var plugin = { serialize, test }; var _default3 = plugin; exports2.default = _default3; } }); // node_modules/react-is/cjs/react-is.production.min.js var require_react_is_production_min = __commonJS({ "node_modules/react-is/cjs/react-is.production.min.js"(exports2) { "use strict"; var b = "function" === typeof Symbol && Symbol.for; var c2 = b ? Symbol.for("react.element") : 60103; var d = b ? Symbol.for("react.portal") : 60106; var e = b ? Symbol.for("react.fragment") : 60107; var f = b ? Symbol.for("react.strict_mode") : 60108; var g = b ? Symbol.for("react.profiler") : 60114; var h = b ? Symbol.for("react.provider") : 60109; var k = b ? Symbol.for("react.context") : 60110; var l = b ? Symbol.for("react.async_mode") : 60111; var m = b ? Symbol.for("react.concurrent_mode") : 60111; var n = b ? Symbol.for("react.forward_ref") : 60112; var p = b ? Symbol.for("react.suspense") : 60113; var q = b ? Symbol.for("react.suspense_list") : 60120; var r = b ? Symbol.for("react.memo") : 60115; var t6 = b ? Symbol.for("react.lazy") : 60116; var v = b ? Symbol.for("react.block") : 60121; var w = b ? Symbol.for("react.fundamental") : 60117; var x = b ? Symbol.for("react.responder") : 60118; var y = b ? Symbol.for("react.scope") : 60119; function z(a) { if ("object" === typeof a && null !== a) { var u = a.$$typeof; switch (u) { case c2: switch (a = a.type, a) { case l: case m: case e: case g: case f: case p: return a; default: switch (a = a && a.$$typeof, a) { case k: case n: case t6: case r: case h: return a; default: return u; } } case d: return u; } } } function A(a) { return z(a) === m; } exports2.AsyncMode = l; exports2.ConcurrentMode = m; exports2.ContextConsumer = k; exports2.ContextProvider = h; exports2.Element = c2; exports2.ForwardRef = n; exports2.Fragment = e; exports2.Lazy = t6; exports2.Memo = r; exports2.Portal = d; exports2.Profiler = g; exports2.StrictMode = f; exports2.Suspense = p; exports2.isAsyncMode = function(a) { return A(a) || z(a) === l; }; exports2.isConcurrentMode = A; exports2.isContextConsumer = function(a) { return z(a) === k; }; exports2.isContextProvider = function(a) { return z(a) === h; }; exports2.isElement = function(a) { return "object" === typeof a && null !== a && a.$$typeof === c2; }; exports2.isForwardRef = function(a) { return z(a) === n; }; exports2.isFragment = function(a) { return z(a) === e; }; exports2.isLazy = function(a) { return z(a) === t6; }; exports2.isMemo = function(a) { return z(a) === r; }; exports2.isPortal = function(a) { return z(a) === d; }; exports2.isProfiler = function(a) { return z(a) === g; }; exports2.isStrictMode = function(a) { return z(a) === f; }; exports2.isSuspense = function(a) { return z(a) === p; }; exports2.isValidElementType = function(a) { return "string" === typeof a || "function" === typeof a || a === e || a === m || a === g || a === f || a === p || a === q || "object" === typeof a && null !== a && (a.$$typeof === t6 || a.$$typeof === r || a.$$typeof === h || a.$$typeof === k || a.$$typeof === n || a.$$typeof === w || a.$$typeof === x || a.$$typeof === y || a.$$typeof === v); }; exports2.typeOf = z; } }); // node_modules/react-is/cjs/react-is.development.js var require_react_is_development = __commonJS({ "node_modules/react-is/cjs/react-is.development.js"(exports2) { "use strict"; if (process.env.NODE_ENV !== "production") { (function() { "use strict"; var hasSymbol = typeof Symbol === "function" && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 60103; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 60106; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 60107; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for("react.strict_mode") : 60108; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 60114; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 60109; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 60110; var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for("react.async_mode") : 60111; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for("react.concurrent_mode") : 60111; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for("react.forward_ref") : 60112; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113; var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for("react.suspense_list") : 60120; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for("react.block") : 60121; var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 60117; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 60118; var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 60119; function isValidElementType(type) { return typeof type === "string" || typeof type === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === "object" && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE); } function typeOf(object2) { if (typeof object2 === "object" && object2 !== null) { var $$typeof = object2.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object2.type; switch (type) { case REACT_ASYNC_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return void 0; } var AsyncMode = REACT_ASYNC_MODE_TYPE; var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; function isAsyncMode(object2) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API."); } } return isConcurrentMode(object2) || typeOf(object2) === REACT_ASYNC_MODE_TYPE; } function isConcurrentMode(object2) { return typeOf(object2) === REACT_CONCURRENT_MODE_TYPE; } function isContextConsumer(object2) { return typeOf(object2) === REACT_CONTEXT_TYPE; } function isContextProvider(object2) { return typeOf(object2) === REACT_PROVIDER_TYPE; } function isElement(object2) { return typeof object2 === "object" && object2 !== null && object2.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object2) { return typeOf(object2) === REACT_FORWARD_REF_TYPE; } function isFragment(object2) { return typeOf(object2) === REACT_FRAGMENT_TYPE; } function isLazy(object2) { return typeOf(object2) === REACT_LAZY_TYPE; } function isMemo(object2) { return typeOf(object2) === REACT_MEMO_TYPE; } function isPortal(object2) { return typeOf(object2) === REACT_PORTAL_TYPE; } function isProfiler(object2) { return typeOf(object2) === REACT_PROFILER_TYPE; } function isStrictMode(object2) { return typeOf(object2) === REACT_STRICT_MODE_TYPE; } function isSuspense(object2) { return typeOf(object2) === REACT_SUSPENSE_TYPE; } exports2.AsyncMode = AsyncMode; exports2.ConcurrentMode = ConcurrentMode; exports2.ContextConsumer = ContextConsumer; exports2.ContextProvider = ContextProvider; exports2.Element = Element; exports2.ForwardRef = ForwardRef; exports2.Fragment = Fragment; exports2.Lazy = Lazy; exports2.Memo = Memo; exports2.Portal = Portal; exports2.Profiler = Profiler; exports2.StrictMode = StrictMode; exports2.Suspense = Suspense; exports2.isAsyncMode = isAsyncMode; exports2.isConcurrentMode = isConcurrentMode; exports2.isContextConsumer = isContextConsumer; exports2.isContextProvider = isContextProvider; exports2.isElement = isElement; exports2.isForwardRef = isForwardRef; exports2.isFragment = isFragment; exports2.isLazy = isLazy; exports2.isMemo = isMemo; exports2.isPortal = isPortal; exports2.isProfiler = isProfiler; exports2.isStrictMode = isStrictMode; exports2.isSuspense = isSuspense; exports2.isValidElementType = isValidElementType; exports2.typeOf = typeOf; })(); } } }); // node_modules/react-is/index.js var require_react_is = __commonJS({ "node_modules/react-is/index.js"(exports2, module2) { "use strict"; if (process.env.NODE_ENV === "production") { module2.exports = require_react_is_production_min(); } else { module2.exports = require_react_is_development(); } } }); // node_modules/pretty-format/build/plugins/ReactElement.js var require_ReactElement = __commonJS({ "node_modules/pretty-format/build/plugins/ReactElement.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = exports2.test = exports2.serialize = void 0; var ReactIs = _interopRequireWildcard(require_react_is()); var _markup = require_markup(); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key2 in obj) { if (Object.prototype.hasOwnProperty.call(obj, key2)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key2) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key2, desc); } else { newObj[key2] = obj[key2]; } } } } newObj.default = obj; return newObj; } } var getChildren = (arg, children = []) => { if (Array.isArray(arg)) { arg.forEach((item) => { getChildren(item, children); }); } else if (arg != null && arg !== false) { children.push(arg); } return children; }; var getType = (element) => { const type = element.type; if (typeof type === "string") { return type; } if (typeof type === "function") { return type.displayName || type.name || "Unknown"; } if (ReactIs.isFragment(element)) { return "React.Fragment"; } if (ReactIs.isSuspense(element)) { return "React.Suspense"; } if (typeof type === "object" && type !== null) { if (ReactIs.isContextProvider(element)) { return "Context.Provider"; } if (ReactIs.isContextConsumer(element)) { return "Context.Consumer"; } if (ReactIs.isForwardRef(element)) { const functionName = type.render.displayName || type.render.name || ""; return functionName !== "" ? "ForwardRef(" + functionName + ")" : "ForwardRef"; } if (ReactIs.isMemo(type)) { const functionName = type.displayName || type.type.displayName || type.type.name || ""; return functionName !== "" ? "Memo(" + functionName + ")" : "Memo"; } } return "UNDEFINED"; }; var getPropKeys = (element) => { const props = element.props; return Object.keys(props).filter((key2) => key2 !== "children" && props[key2] !== void 0).sort(); }; var serialize = (element, config2, indentation, depth, refs, printer) => ++depth > config2.maxDepth ? (0, _markup.printElementAsLeaf)(getType(element), config2) : (0, _markup.printElement)( getType(element), (0, _markup.printProps)( getPropKeys(element), element.props, config2, indentation + config2.indent, depth, refs, printer ), (0, _markup.printChildren)( getChildren(element.props.children), config2, indentation + config2.indent, depth, refs, printer ), config2, indentation ); exports2.serialize = serialize; var test = (val) => val && ReactIs.isElement(val); exports2.test = test; var plugin = { serialize, test }; var _default3 = plugin; exports2.default = _default3; } }); // node_modules/pretty-format/build/plugins/ReactTestComponent.js var require_ReactTestComponent = __commonJS({ "node_modules/pretty-format/build/plugins/ReactTestComponent.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = exports2.test = exports2.serialize = void 0; var _markup = require_markup(); var Symbol2 = global["jest-symbol-do-not-touch"] || global.Symbol; var testSymbol = Symbol2.for("react.test.json"); var getPropKeys = (object2) => { const props = object2.props; return props ? Object.keys(props).filter((key2) => props[key2] !== void 0).sort() : []; }; var serialize = (object2, config2, indentation, depth, refs, printer) => ++depth > config2.maxDepth ? (0, _markup.printElementAsLeaf)(object2.type, config2) : (0, _markup.printElement)( object2.type, object2.props ? (0, _markup.printProps)( getPropKeys(object2), object2.props, config2, indentation + config2.indent, depth, refs, printer ) : "", object2.children ? (0, _markup.printChildren)( object2.children, config2, indentation + config2.indent, depth, refs, printer ) : "", config2, indentation ); exports2.serialize = serialize; var test = (val) => val && val.$$typeof === testSymbol; exports2.test = test; var plugin = { serialize, test }; var _default3 = plugin; exports2.default = _default3; } }); // node_modules/pretty-format/build/index.js var require_build = __commonJS({ "node_modules/pretty-format/build/index.js"(exports2, module2) { "use strict"; var _ansiStyles = _interopRequireDefault(require_ansi_styles()); var _collections = require_collections(); var _AsymmetricMatcher = _interopRequireDefault( require_AsymmetricMatcher() ); var _ConvertAnsi = _interopRequireDefault(require_ConvertAnsi()); var _DOMCollection = _interopRequireDefault(require_DOMCollection()); var _DOMElement = _interopRequireDefault(require_DOMElement()); var _Immutable = _interopRequireDefault(require_Immutable()); var _ReactElement = _interopRequireDefault(require_ReactElement()); var _ReactTestComponent = _interopRequireDefault( require_ReactTestComponent() ); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Symbol2 = global["jest-symbol-do-not-touch"] || global.Symbol; var toString = Object.prototype.toString; var toISOString = Date.prototype.toISOString; var errorToString = Error.prototype.toString; var regExpToString = RegExp.prototype.toString; var symbolToString = Symbol2.prototype.toString; var getConstructorName = (val) => typeof val.constructor === "function" && val.constructor.name || "Object"; var isWindow = (val) => typeof window !== "undefined" && val === window; var SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; var NEWLINE_REGEXP = /\n/gi; var PrettyFormatPluginError = class extends Error { constructor(message, stack2) { super(message); this.stack = stack2; this.name = this.constructor.name; } }; function isToStringedArrayType(toStringed) { return toStringed === "[object Array]" || toStringed === "[object ArrayBuffer]" || toStringed === "[object DataView]" || toStringed === "[object Float32Array]" || toStringed === "[object Float64Array]" || toStringed === "[object Int8Array]" || toStringed === "[object Int16Array]" || toStringed === "[object Int32Array]" || toStringed === "[object Uint8Array]" || toStringed === "[object Uint8ClampedArray]" || toStringed === "[object Uint16Array]" || toStringed === "[object Uint32Array]"; } function printNumber(val) { return Object.is(val, -0) ? "-0" : String(val); } function printBigInt(val) { return String(`${val}n`); } function printFunction2(val, printFunctionName) { if (!printFunctionName) { return "[Function]"; } return "[Function " + (val.name || "anonymous") + "]"; } function printSymbol(val) { return symbolToString.call(val).replace(SYMBOL_REGEXP, "Symbol($1)"); } function printError(val) { return "[" + errorToString.call(val) + "]"; } function printBasicValue(val, printFunctionName, escapeRegex2, escapeString) { if (val === true || val === false) { return "" + val; } if (val === void 0) { return "undefined"; } if (val === null) { return "null"; } const typeOf = typeof val; if (typeOf === "number") { return printNumber(val); } if (typeOf === "bigint") { return printBigInt(val); } if (typeOf === "string") { if (escapeString) { return '"' + val.replace(/"|\\/g, "\\$&") + '"'; } return '"' + val + '"'; } if (typeOf === "function") { return printFunction2(val, printFunctionName); } if (typeOf === "symbol") { return printSymbol(val); } const toStringed = toString.call(val); if (toStringed === "[object WeakMap]") { return "WeakMap {}"; } if (toStringed === "[object WeakSet]") { return "WeakSet {}"; } if (toStringed === "[object Function]" || toStringed === "[object GeneratorFunction]") { return printFunction2(val, printFunctionName); } if (toStringed === "[object Symbol]") { return printSymbol(val); } if (toStringed === "[object Date]") { return isNaN(+val) ? "Date { NaN }" : toISOString.call(val); } if (toStringed === "[object Error]") { return printError(val); } if (toStringed === "[object RegExp]") { if (escapeRegex2) { return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); } return regExpToString.call(val); } if (val instanceof Error) { return printError(val); } return null; } function printComplexValue(val, config2, indentation, depth, refs, hasCalledToJSON) { if (refs.indexOf(val) !== -1) { return "[Circular]"; } refs = refs.slice(); refs.push(val); const hitMaxDepth = ++depth > config2.maxDepth; const min = config2.min; if (config2.callToJSON && !hitMaxDepth && val.toJSON && typeof val.toJSON === "function" && !hasCalledToJSON) { return printer(val.toJSON(), config2, indentation, depth, refs, true); } const toStringed = toString.call(val); if (toStringed === "[object Arguments]") { return hitMaxDepth ? "[Arguments]" : (min ? "" : "Arguments ") + "[" + (0, _collections.printListItems)( val, config2, indentation, depth, refs, printer ) + "]"; } if (isToStringedArrayType(toStringed)) { return hitMaxDepth ? "[" + val.constructor.name + "]" : (min ? "" : val.constructor.name + " ") + "[" + (0, _collections.printListItems)( val, config2, indentation, depth, refs, printer ) + "]"; } if (toStringed === "[object Map]") { return hitMaxDepth ? "[Map]" : "Map {" + (0, _collections.printIteratorEntries)( val.entries(), config2, indentation, depth, refs, printer, " => " ) + "}"; } if (toStringed === "[object Set]") { return hitMaxDepth ? "[Set]" : "Set {" + (0, _collections.printIteratorValues)( val.values(), config2, indentation, depth, refs, printer ) + "}"; } return hitMaxDepth || isWindow(val) ? "[" + getConstructorName(val) + "]" : (min ? "" : getConstructorName(val) + " ") + "{" + (0, _collections.printObjectProperties)( val, config2, indentation, depth, refs, printer ) + "}"; } function isNewPlugin(plugin) { return plugin.serialize != null; } function printPlugin(plugin, val, config2, indentation, depth, refs) { let printed; try { printed = isNewPlugin(plugin) ? plugin.serialize(val, config2, indentation, depth, refs, printer) : plugin.print( val, (valChild) => printer(valChild, config2, indentation, depth, refs), (str) => { const indentationNext = indentation + config2.indent; return indentationNext + str.replace(NEWLINE_REGEXP, "\n" + indentationNext); }, { edgeSpacing: config2.spacingOuter, min: config2.min, spacing: config2.spacingInner }, config2.colors ); } catch (error45) { throw new PrettyFormatPluginError(error45.message, error45.stack); } if (typeof printed !== "string") { throw new Error( `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".` ); } return printed; } function findPlugin(plugins, val) { for (let p = 0; p < plugins.length; p++) { try { if (plugins[p].test(val)) { return plugins[p]; } } catch (error45) { throw new PrettyFormatPluginError(error45.message, error45.stack); } } return null; } function printer(val, config2, indentation, depth, refs, hasCalledToJSON) { const plugin = findPlugin(config2.plugins, val); if (plugin !== null) { return printPlugin(plugin, val, config2, indentation, depth, refs); } const basicResult = printBasicValue( val, config2.printFunctionName, config2.escapeRegex, config2.escapeString ); if (basicResult !== null) { return basicResult; } return printComplexValue( val, config2, indentation, depth, refs, hasCalledToJSON ); } var DEFAULT_THEME = { comment: "gray", content: "reset", prop: "yellow", tag: "cyan", value: "green" }; var DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); var DEFAULT_OPTIONS = { callToJSON: true, escapeRegex: false, escapeString: true, highlight: false, indent: 2, maxDepth: Infinity, min: false, plugins: [], printFunctionName: true, theme: DEFAULT_THEME }; function validateOptions(options) { Object.keys(options).forEach((key2) => { if (!DEFAULT_OPTIONS.hasOwnProperty(key2)) { throw new Error(`pretty-format: Unknown option "${key2}".`); } }); if (options.min && options.indent !== void 0 && options.indent !== 0) { throw new Error( 'pretty-format: Options "min" and "indent" cannot be used together.' ); } if (options.theme !== void 0) { if (options.theme === null) { throw new Error(`pretty-format: Option "theme" must not be null.`); } if (typeof options.theme !== "object") { throw new Error( `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".` ); } } } var getColorsHighlight = (options) => DEFAULT_THEME_KEYS.reduce((colors, key2) => { const value = options.theme && options.theme[key2] !== void 0 ? options.theme[key2] : DEFAULT_THEME[key2]; const color = value && _ansiStyles.default[value]; if (color && typeof color.close === "string" && typeof color.open === "string") { colors[key2] = color; } else { throw new Error( `pretty-format: Option "theme" has a key "${key2}" whose value "${value}" is undefined in ansi-styles.` ); } return colors; }, /* @__PURE__ */ Object.create(null)); var getColorsEmpty = () => DEFAULT_THEME_KEYS.reduce((colors, key2) => { colors[key2] = { close: "", open: "" }; return colors; }, /* @__PURE__ */ Object.create(null)); var getPrintFunctionName = (options) => options && options.printFunctionName !== void 0 ? options.printFunctionName : DEFAULT_OPTIONS.printFunctionName; var getEscapeRegex = (options) => options && options.escapeRegex !== void 0 ? options.escapeRegex : DEFAULT_OPTIONS.escapeRegex; var getEscapeString = (options) => options && options.escapeString !== void 0 ? options.escapeString : DEFAULT_OPTIONS.escapeString; var getConfig = (options) => ({ callToJSON: options && options.callToJSON !== void 0 ? options.callToJSON : DEFAULT_OPTIONS.callToJSON, colors: options && options.highlight ? getColorsHighlight(options) : getColorsEmpty(), escapeRegex: getEscapeRegex(options), escapeString: getEscapeString(options), indent: options && options.min ? "" : createIndent( options && options.indent !== void 0 ? options.indent : DEFAULT_OPTIONS.indent ), maxDepth: options && options.maxDepth !== void 0 ? options.maxDepth : DEFAULT_OPTIONS.maxDepth, min: options && options.min !== void 0 ? options.min : DEFAULT_OPTIONS.min, plugins: options && options.plugins !== void 0 ? options.plugins : DEFAULT_OPTIONS.plugins, printFunctionName: getPrintFunctionName(options), spacingInner: options && options.min ? " " : "\n", spacingOuter: options && options.min ? "" : "\n" }); function createIndent(indent) { return new Array(indent + 1).join(" "); } function prettyFormat4(val, options) { if (options) { validateOptions(options); if (options.plugins) { const plugin = findPlugin(options.plugins, val); if (plugin !== null) { return printPlugin(plugin, val, getConfig(options), "", 0, []); } } } const basicResult = printBasicValue( val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options) ); if (basicResult !== null) { return basicResult; } return printComplexValue(val, getConfig(options), "", 0, []); } prettyFormat4.plugins = { AsymmetricMatcher: _AsymmetricMatcher.default, ConvertAnsi: _ConvertAnsi.default, DOMCollection: _DOMCollection.default, DOMElement: _DOMElement.default, Immutable: _Immutable.default, ReactElement: _ReactElement.default, ReactTestComponent: _ReactTestComponent.default }; module2.exports = prettyFormat4; } }); // src/index.ts var index_exports = {}; __export(index_exports, { CompilerDiagnostic: () => CompilerDiagnostic, CompilerError: () => CompilerError, CompilerErrorDetail: () => CompilerErrorDetail, CompilerSuggestionOperation: () => CompilerSuggestionOperation, Effect: () => Effect, ErrorCategory: () => ErrorCategory, ErrorSeverity: () => ErrorSeverity, LintRules: () => LintRules, OPT_IN_DIRECTIVES: () => OPT_IN_DIRECTIVES, OPT_OUT_DIRECTIVES: () => OPT_OUT_DIRECTIVES, ProgramContext: () => ProgramContext, ValueKind: () => ValueKind, ValueReason: () => ValueReason, compile: () => compileFn, compileProgram: () => compileProgram, default: () => index_default, findDirectiveDisablingMemoization: () => findDirectiveDisablingMemoization, findDirectiveEnablingMemoization: () => tryFindDirectiveEnablingMemoization, parseConfigPragmaForTests: () => parseConfigPragmaForTests, parsePluginOptions: () => parsePluginOptions, printFunctionWithOutlined: () => printFunctionWithOutlined, printHIR: () => printHIR, printReactiveFunction: () => printReactiveFunction, printReactiveFunctionWithOutlined: () => printReactiveFunctionWithOutlined, runBabelPluginReactCompiler: () => runBabelPluginReactCompiler, validateEnvironmentConfig: () => validateEnvironmentConfig }); module.exports = __toCommonJS(index_exports); // src/Babel/RunReactCompilerBabelPlugin.ts var import_core8 = __toESM(require_lib10()); var BabelParser = __toESM(require_lib4()); var import_invariant4 = __toESM(require_invariant()); // src/Entrypoint/Gating.ts var t = __toESM(require("@babel/types")); // src/CompilerError.ts var import_code_frame = __toESM(require_lib3()); // src/Utils/Result.ts function Ok(val) { return new OkImpl(val); } var _val; var _OkImpl = class _OkImpl { constructor(val) { __privateAdd(this, _val); __privateSet(this, _val, val); } map(fn) { return new _OkImpl(fn(__privateGet(this, _val))); } mapErr(_fn) { return this; } mapOr(_fallback, fn) { return fn(__privateGet(this, _val)); } mapOrElse(_fallback, fn) { return fn(__privateGet(this, _val)); } andThen(fn) { return fn(__privateGet(this, _val)); } and(res) { return res; } or(_res) { return this; } orElse(_fn) { return this; } isOk() { return true; } isErr() { return false; } expect(_msg) { return __privateGet(this, _val); } expectErr(msg) { throw new Error(`${msg}: ${__privateGet(this, _val)}`); } unwrap() { return __privateGet(this, _val); } unwrapOr(_fallback) { return __privateGet(this, _val); } unwrapOrElse(_fallback) { return __privateGet(this, _val); } unwrapErr() { if (__privateGet(this, _val) instanceof Error) { throw __privateGet(this, _val); } throw new Error(`Can't unwrap \`Ok\` to \`Err\`: ${__privateGet(this, _val)}`); } }; _val = new WeakMap(); var OkImpl = _OkImpl; function Err(val) { return new ErrImpl(val); } var _val2; var _ErrImpl = class _ErrImpl { constructor(val) { __privateAdd(this, _val2); __privateSet(this, _val2, val); } map(_fn) { return this; } mapErr(fn) { return new _ErrImpl(fn(__privateGet(this, _val2))); } mapOr(fallback, _fn) { return fallback; } mapOrElse(fallback, _fn) { return fallback(); } andThen(_fn) { return this; } and(_res) { return this; } or(res) { return res; } orElse(fn) { return fn(__privateGet(this, _val2)); } isOk() { return false; } isErr() { return true; } expect(msg) { throw new Error(`${msg}: ${__privateGet(this, _val2)}`); } expectErr(_msg) { return __privateGet(this, _val2); } unwrap() { if (__privateGet(this, _val2) instanceof Error) { throw __privateGet(this, _val2); } throw new Error(`Can't unwrap \`Err\` to \`Ok\`: ${__privateGet(this, _val2)}`); } unwrapOr(fallback) { return fallback; } unwrapOrElse(fallback) { return fallback(__privateGet(this, _val2)); } unwrapErr() { return __privateGet(this, _val2); } }; _val2 = new WeakMap(); var ErrImpl = _ErrImpl; // src/Utils/utils.ts function assertExhaustive(_, errorMsg) { throw new Error(errorMsg); } function retainWhere(array2, predicate) { let writeIndex = 0; for (let readIndex = 0; readIndex < array2.length; readIndex++) { const item = array2[readIndex]; if (predicate(item, readIndex) === true) { array2[writeIndex++] = item; } } array2.length = writeIndex; } function retainWhere_Set(items, predicate) { for (const item of items) { if (!predicate(item)) { items.delete(item); } } } function getOrInsertWith(m, key2, makeDefault) { if (m.has(key2)) { return m.get(key2); } else { const defaultValue = makeDefault(); m.set(key2, defaultValue); return defaultValue; } } function getOrInsertDefault(m, key2, defaultValue) { if (m.has(key2)) { return m.get(key2); } else { m.set(key2, defaultValue); return defaultValue; } } function Set_equal(a, b) { if (a.size !== b.size) { return false; } for (const item of a) { if (!b.has(item)) { return false; } } return true; } function Set_union(a, b) { const union2 = new Set(a); for (const item of b) { union2.add(item); } return union2; } function Set_intersect(sets) { if (sets.length === 0 || sets.some((s) => s.size === 0)) { return /* @__PURE__ */ new Set(); } else if (sets.length === 1) { return new Set(sets[0]); } const result = /* @__PURE__ */ new Set(); const first = sets[0]; outer: for (const e of first) { for (let i = 1; i < sets.length; i++) { if (!sets[i].has(e)) { continue outer; } } result.add(e); } return result; } function Set_isSuperset(a, b) { for (const v of b) { if (!a.has(v)) { return false; } } return true; } function Iterable_some(iter, pred) { for (const item of iter) { if (pred(item)) { return true; } } return false; } function Set_filter(source2, fn) { const result = /* @__PURE__ */ new Set(); for (const entry of source2) { if (fn(entry)) { result.add(entry); } } return result; } function hasNode(input) { return input.node != null; } function hasOwnProperty2(obj, key2) { return Object.prototype.hasOwnProperty.call(obj, key2); } // src/CompilerError.ts var import_invariant = __toESM(require_invariant()); var ErrorSeverity = /* @__PURE__ */ ((ErrorSeverity2) => { ErrorSeverity2["Error"] = "Error"; ErrorSeverity2["Warning"] = "Warning"; ErrorSeverity2["Hint"] = "Hint"; ErrorSeverity2["Off"] = "Off"; return ErrorSeverity2; })(ErrorSeverity || {}); var CompilerSuggestionOperation = /* @__PURE__ */ ((CompilerSuggestionOperation2) => { CompilerSuggestionOperation2[CompilerSuggestionOperation2["InsertBefore"] = 0] = "InsertBefore"; CompilerSuggestionOperation2[CompilerSuggestionOperation2["InsertAfter"] = 1] = "InsertAfter"; CompilerSuggestionOperation2[CompilerSuggestionOperation2["Remove"] = 2] = "Remove"; CompilerSuggestionOperation2[CompilerSuggestionOperation2["Replace"] = 3] = "Replace"; return CompilerSuggestionOperation2; })(CompilerSuggestionOperation || {}); var CompilerDiagnostic = class _CompilerDiagnostic { constructor(options) { this.options = options; } static create(options) { return new _CompilerDiagnostic(__spreadProps(__spreadValues({}, options), { details: [] })); } get reason() { return this.options.reason; } get description() { return this.options.description; } get severity() { return getRuleForCategory(this.category).severity; } get suggestions() { return this.options.suggestions; } get category() { return this.options.category; } withDetails(...details) { this.options.details.push(...details); return this; } primaryLocation() { const firstErrorDetail = this.options.details.filter( (d) => d.kind === "error" )[0]; return firstErrorDetail != null && firstErrorDetail.kind === "error" ? firstErrorDetail.loc : null; } printErrorMessage(source2, options) { var _a, _b; const buffer2 = [printErrorSummary(this.category, this.reason)]; if (this.description != null) { buffer2.push("\n\n", `${this.description}.`); } for (const detail of this.options.details) { switch (detail.kind) { case "error": { const loc = detail.loc; if (loc == null || typeof loc === "symbol") { continue; } let codeFrame; try { codeFrame = printCodeFrame(source2, loc, (_a = detail.message) != null ? _a : ""); } catch (e) { codeFrame = (_b = detail.message) != null ? _b : ""; } buffer2.push("\n\n"); if (loc.filename != null) { const line2 = loc.start.line; const column2 = options.eslint ? loc.start.column + 1 : loc.start.column; buffer2.push(`${loc.filename}:${line2}:${column2} `); } buffer2.push(codeFrame); break; } case "hint": { buffer2.push("\n\n"); buffer2.push(detail.message); break; } default: { assertExhaustive( detail, `Unexpected detail kind ${detail.kind}` ); } } } return buffer2.join(""); } toString() { const buffer2 = [printErrorSummary(this.category, this.reason)]; if (this.description != null) { buffer2.push(`. ${this.description}.`); } const loc = this.primaryLocation(); if (loc != null && typeof loc !== "symbol") { buffer2.push(` (${loc.start.line}:${loc.start.column})`); } return buffer2.join(""); } }; var CompilerErrorDetail = class { constructor(options) { this.options = options; } get reason() { return this.options.reason; } get description() { return this.options.description; } get severity() { return getRuleForCategory(this.category).severity; } get loc() { return this.options.loc; } get suggestions() { return this.options.suggestions; } get category() { return this.options.category; } primaryLocation() { return this.loc; } printErrorMessage(source2, options) { const buffer2 = [printErrorSummary(this.category, this.reason)]; if (this.description != null) { buffer2.push(` ${this.description}.`); } const loc = this.loc; if (loc != null && typeof loc !== "symbol") { let codeFrame; try { codeFrame = printCodeFrame(source2, loc, this.reason); } catch (e) { codeFrame = ""; } buffer2.push(` `); if (loc.filename != null) { const line2 = loc.start.line; const column2 = options.eslint ? loc.start.column + 1 : loc.start.column; buffer2.push(`${loc.filename}:${line2}:${column2} `); } buffer2.push(codeFrame); buffer2.push("\n\n"); } return buffer2.join(""); } toString() { const buffer2 = [printErrorSummary(this.category, this.reason)]; if (this.description != null) { buffer2.push(`. ${this.description}.`); } const loc = this.loc; if (loc != null && typeof loc !== "symbol") { buffer2.push(` (${loc.start.line}:${loc.start.column})`); } return buffer2.join(""); } }; var CompilerError = class _CompilerError extends Error { constructor(...args) { super(...args); this.details = []; this.disabledDetails = []; this.printedMessage = null; this.name = "ReactCompilerError"; this.details = []; this.disabledDetails = []; } static invariant(condition, options) { if (!condition) { const errors = new _CompilerError(); errors.pushDiagnostic( CompilerDiagnostic.create({ reason: options.reason, description: options.description, category: "Invariant" /* Invariant */ }).withDetails(...options.details) ); throw errors; } } static throwDiagnostic(options) { const errors = new _CompilerError(); errors.pushDiagnostic(new CompilerDiagnostic(options)); throw errors; } static throwTodo(options) { const errors = new _CompilerError(); errors.pushErrorDetail( new CompilerErrorDetail(__spreadProps(__spreadValues({}, options), { category: "Todo" /* Todo */ })) ); throw errors; } static throwInvalidJS(options) { const errors = new _CompilerError(); errors.pushErrorDetail( new CompilerErrorDetail(__spreadProps(__spreadValues({}, options), { category: "Syntax" /* Syntax */ })) ); throw errors; } static throwInvalidReact(options) { const errors = new _CompilerError(); errors.pushErrorDetail(new CompilerErrorDetail(options)); throw errors; } static throwInvalidConfig(options) { const errors = new _CompilerError(); errors.pushErrorDetail( new CompilerErrorDetail(__spreadProps(__spreadValues({}, options), { category: "Config" /* Config */ })) ); throw errors; } static throw(options) { const errors = new _CompilerError(); errors.pushErrorDetail(new CompilerErrorDetail(options)); throw errors; } get message() { var _a; return (_a = this.printedMessage) != null ? _a : this.toString(); } set message(_message) { } toString() { if (this.printedMessage) { return this.printedMessage; } if (Array.isArray(this.details)) { return this.details.map((detail) => detail.toString()).join("\n\n"); } return this.name; } withPrintedMessage(source2, options) { this.printedMessage = this.printErrorMessage(source2, options); return this; } printErrorMessage(source2, options) { if (options.eslint && this.details.length === 1) { return this.details[0].printErrorMessage(source2, options); } return `Found ${this.details.length} error${this.details.length === 1 ? "" : "s"}: ` + this.details.map((detail) => detail.printErrorMessage(source2, options).trim()).join("\n\n"); } merge(other) { this.details.push(...other.details); this.disabledDetails.push(...other.disabledDetails); } pushDiagnostic(diagnostic) { if (diagnostic.severity === "Off" /* Off */) { this.disabledDetails.push(diagnostic); } else { this.details.push(diagnostic); } } /** * @deprecated use {@link pushDiagnostic} instead */ push(options) { var _a; const detail = new CompilerErrorDetail({ category: options.category, reason: options.reason, description: (_a = options.description) != null ? _a : null, suggestions: options.suggestions, loc: typeof options.loc === "symbol" ? null : options.loc }); return this.pushErrorDetail(detail); } /** * @deprecated use {@link pushDiagnostic} instead */ pushErrorDetail(detail) { if (detail.severity === "Off" /* Off */) { this.disabledDetails.push(detail); } else { this.details.push(detail); } return detail; } hasAnyErrors() { return this.details.length > 0; } asResult() { return this.hasAnyErrors() ? Err(this) : Ok(void 0); } /** * Returns true if any of the error details are of severity Error. */ hasErrors() { for (const detail of this.details) { if (detail.severity === "Error" /* Error */) { return true; } } return false; } /** * Returns true if there are no Errors and there is at least one Warning. */ hasWarning() { let res = false; for (const detail of this.details) { if (detail.severity === "Error" /* Error */) { return false; } if (detail.severity === "Warning" /* Warning */) { res = true; } } return res; } hasHints() { let res = false; for (const detail of this.details) { if (detail.severity === "Error" /* Error */) { return false; } if (detail.severity === "Warning" /* Warning */) { return false; } if (detail.severity === "Hint" /* Hint */) { res = true; } } return res; } }; function printCodeFrame(source2, loc, message) { return (0, import_code_frame.codeFrameColumns)( source2, { start: { line: loc.start.line, column: loc.start.column + 1 }, end: { line: loc.end.line, column: loc.end.column + 1 } }, { message } ); } function printErrorSummary(category, message) { let heading; switch (category) { case "AutomaticEffectDependencies" /* AutomaticEffectDependencies */: case "CapitalizedCalls" /* CapitalizedCalls */: case "Config" /* Config */: case "EffectDerivationsOfState" /* EffectDerivationsOfState */: case "EffectSetState" /* EffectSetState */: case "ErrorBoundaries" /* ErrorBoundaries */: case "Factories" /* Factories */: case "FBT" /* FBT */: case "Fire" /* Fire */: case "Gating" /* Gating */: case "Globals" /* Globals */: case "Hooks" /* Hooks */: case "Immutability" /* Immutability */: case "Purity" /* Purity */: case "Refs" /* Refs */: case "RenderSetState" /* RenderSetState */: case "StaticComponents" /* StaticComponents */: case "Suppression" /* Suppression */: case "Syntax" /* Syntax */: case "UseMemo" /* UseMemo */: { heading = "Error"; break; } case "EffectDependencies" /* EffectDependencies */: case "IncompatibleLibrary" /* IncompatibleLibrary */: case "PreserveManualMemo" /* PreserveManualMemo */: case "UnsupportedSyntax" /* UnsupportedSyntax */: { heading = "Compilation Skipped"; break; } case "Invariant" /* Invariant */: { heading = "Invariant"; break; } case "Todo" /* Todo */: { heading = "Todo"; break; } default: { assertExhaustive(category, `Unhandled category '${category}'`); } } return `${heading}: ${message}`; } var ErrorCategory = /* @__PURE__ */ ((ErrorCategory2) => { ErrorCategory2["Hooks"] = "Hooks"; ErrorCategory2["CapitalizedCalls"] = "CapitalizedCalls"; ErrorCategory2["StaticComponents"] = "StaticComponents"; ErrorCategory2["UseMemo"] = "UseMemo"; ErrorCategory2["Factories"] = "Factories"; ErrorCategory2["PreserveManualMemo"] = "PreserveManualMemo"; ErrorCategory2["IncompatibleLibrary"] = "IncompatibleLibrary"; ErrorCategory2["Immutability"] = "Immutability"; ErrorCategory2["Globals"] = "Globals"; ErrorCategory2["Refs"] = "Refs"; ErrorCategory2["EffectDependencies"] = "EffectDependencies"; ErrorCategory2["EffectSetState"] = "EffectSetState"; ErrorCategory2["EffectDerivationsOfState"] = "EffectDerivationsOfState"; ErrorCategory2["ErrorBoundaries"] = "ErrorBoundaries"; ErrorCategory2["Purity"] = "Purity"; ErrorCategory2["RenderSetState"] = "RenderSetState"; ErrorCategory2["Invariant"] = "Invariant"; ErrorCategory2["Todo"] = "Todo"; ErrorCategory2["Syntax"] = "Syntax"; ErrorCategory2["UnsupportedSyntax"] = "UnsupportedSyntax"; ErrorCategory2["Config"] = "Config"; ErrorCategory2["Gating"] = "Gating"; ErrorCategory2["Suppression"] = "Suppression"; ErrorCategory2["AutomaticEffectDependencies"] = "AutomaticEffectDependencies"; ErrorCategory2["Fire"] = "Fire"; ErrorCategory2["FBT"] = "FBT"; return ErrorCategory2; })(ErrorCategory || {}); var RULE_NAME_PATTERN = /^[a-z]+(-[a-z]+)*$/; function getRuleForCategory(category) { const rule = getRuleForCategoryImpl(category); (0, import_invariant.default)( RULE_NAME_PATTERN.test(rule.name), `Invalid rule name, got '${rule.name}' but rules must match ${RULE_NAME_PATTERN.toString()}` ); return rule; } function getRuleForCategoryImpl(category) { switch (category) { case "AutomaticEffectDependencies" /* AutomaticEffectDependencies */: { return { category, severity: "Error" /* Error */, name: "automatic-effect-dependencies", description: "Verifies that automatic effect dependencies are compiled if opted-in", recommended: false }; } case "CapitalizedCalls" /* CapitalizedCalls */: { return { category, severity: "Error" /* Error */, name: "capitalized-calls", description: "Validates against calling capitalized functions/methods instead of using JSX", recommended: false }; } case "Config" /* Config */: { return { category, severity: "Error" /* Error */, name: "config", description: "Validates the compiler configuration options", recommended: true }; } case "EffectDependencies" /* EffectDependencies */: { return { category, severity: "Error" /* Error */, name: "memoized-effect-dependencies", description: "Validates that effect dependencies are memoized", recommended: false }; } case "EffectDerivationsOfState" /* EffectDerivationsOfState */: { return { category, severity: "Error" /* Error */, name: "no-deriving-state-in-effects", description: "Validates against deriving values from state in an effect", recommended: false }; } case "EffectSetState" /* EffectSetState */: { return { category, severity: "Error" /* Error */, name: "set-state-in-effect", description: "Validates against calling setState synchronously in an effect, which can lead to re-renders that degrade performance", recommended: true }; } case "ErrorBoundaries" /* ErrorBoundaries */: { return { category, severity: "Error" /* Error */, name: "error-boundaries", description: "Validates usage of error boundaries instead of try/catch for errors in child components", recommended: true }; } case "Factories" /* Factories */: { return { category, severity: "Error" /* Error */, name: "component-hook-factories", description: "Validates against higher order functions defining nested components or hooks. Components and hooks should be defined at the module level", recommended: true }; } case "FBT" /* FBT */: { return { category, severity: "Error" /* Error */, name: "fbt", description: "Validates usage of fbt", recommended: false }; } case "Fire" /* Fire */: { return { category, severity: "Error" /* Error */, name: "fire", description: "Validates usage of `fire`", recommended: false }; } case "Gating" /* Gating */: { return { category, severity: "Error" /* Error */, name: "gating", description: "Validates configuration of [gating mode](https://react.dev/reference/react-compiler/gating)", recommended: true }; } case "Globals" /* Globals */: { return { category, severity: "Error" /* Error */, name: "globals", description: "Validates against assignment/mutation of globals during render, part of ensuring that [side effects must render outside of render](https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)", recommended: true }; } case "Hooks" /* Hooks */: { return { category, severity: "Error" /* Error */, name: "hooks", description: "Validates the rules of hooks", /** * TODO: the "Hooks" rule largely reimplements the "rules-of-hooks" non-compiler rule. * We need to dedeupe these (moving the remaining bits into the compiler) and then enable * this rule. */ recommended: false }; } case "Immutability" /* Immutability */: { return { category, severity: "Error" /* Error */, name: "immutability", description: "Validates against mutating props, state, and other values that [are immutable](https://react.dev/reference/rules/components-and-hooks-must-be-pure#props-and-state-are-immutable)", recommended: true }; } case "Invariant" /* Invariant */: { return { category, severity: "Error" /* Error */, name: "invariant", description: "Internal invariants", recommended: false }; } case "PreserveManualMemo" /* PreserveManualMemo */: { return { category, severity: "Error" /* Error */, name: "preserve-manual-memoization", description: "Validates that existing manual memoized is preserved by the compiler. React Compiler will only compile components and hooks if its inference [matches or exceeds the existing manual memoization](https://react.dev/learn/react-compiler/introduction#what-should-i-do-about-usememo-usecallback-and-reactmemo)", recommended: true }; } case "Purity" /* Purity */: { return { category, severity: "Error" /* Error */, name: "purity", description: "Validates that [components/hooks are pure](https://react.dev/reference/rules/components-and-hooks-must-be-pure) by checking that they do not call known-impure functions", recommended: true }; } case "Refs" /* Refs */: { return { category, severity: "Error" /* Error */, name: "refs", description: 'Validates correct usage of refs, not reading/writing during render. See the "pitfalls" section in [`useRef()` usage](https://react.dev/reference/react/useRef#usage)', recommended: true }; } case "RenderSetState" /* RenderSetState */: { return { category, severity: "Error" /* Error */, name: "set-state-in-render", description: "Validates against setting state during render, which can trigger additional renders and potential infinite render loops", recommended: true }; } case "StaticComponents" /* StaticComponents */: { return { category, severity: "Error" /* Error */, name: "static-components", description: "Validates that components are static, not recreated every render. Components that are recreated dynamically can reset state and trigger excessive re-rendering", recommended: true }; } case "Suppression" /* Suppression */: { return { category, severity: "Error" /* Error */, name: "rule-suppression", description: "Validates against suppression of other rules", recommended: false }; } case "Syntax" /* Syntax */: { return { category, severity: "Error" /* Error */, name: "syntax", description: "Validates against invalid syntax", recommended: false }; } case "Todo" /* Todo */: { return { category, severity: "Hint" /* Hint */, name: "todo", description: "Unimplemented features", recommended: false }; } case "UnsupportedSyntax" /* UnsupportedSyntax */: { return { category, severity: "Warning" /* Warning */, name: "unsupported-syntax", description: "Validates against syntax that we do not plan to support in React Compiler", recommended: true }; } case "UseMemo" /* UseMemo */: { return { category, severity: "Error" /* Error */, name: "use-memo", description: "Validates usage of the useMemo() hook against common mistakes. See [`useMemo()` docs](https://react.dev/reference/react/useMemo) for more information.", recommended: true }; } case "IncompatibleLibrary" /* IncompatibleLibrary */: { return { category, severity: "Warning" /* Warning */, name: "incompatible-library", description: "Validates against usage of libraries which are incompatible with memoization (manual or automatic)", recommended: true }; } default: { assertExhaustive(category, `Unsupported category ${category}`); } } } var LintRules = Object.keys(ErrorCategory).map( (category) => getRuleForCategory(category) ); // src/Entrypoint/Gating.ts function insertAdditionalFunctionDeclaration(fnPath, compiled, programContext, gatingFunctionIdentifierName) { var _a, _b; const originalFnName = fnPath.node.id; const originalFnParams = fnPath.node.params; const compiledParams = fnPath.node.params; CompilerError.invariant(originalFnName != null && compiled.id != null, { reason: "Expected function declarations that are referenced elsewhere to have a named identifier", description: null, details: [ { kind: "error", loc: (_a = fnPath.node.loc) != null ? _a : null, message: null } ] }); CompilerError.invariant(originalFnParams.length === compiledParams.length, { reason: "Expected React Compiler optimized function declarations to have the same number of parameters as source", description: null, details: [ { kind: "error", loc: (_b = fnPath.node.loc) != null ? _b : null, message: null } ] }); const gatingCondition = t.identifier( programContext.newUid(`${gatingFunctionIdentifierName}_result`) ); const unoptimizedFnName = t.identifier( programContext.newUid(`${originalFnName.name}_unoptimized`) ); const optimizedFnName = t.identifier( programContext.newUid(`${originalFnName.name}_optimized`) ); compiled.id.name = optimizedFnName.name; fnPath.get("id").replaceInline(unoptimizedFnName); const newParams = []; const genNewArgs = []; for (let i = 0; i < originalFnParams.length; i++) { const argName = `arg${i}`; if (originalFnParams[i].type === "RestElement") { newParams.push(t.restElement(t.identifier(argName))); genNewArgs.push(() => t.spreadElement(t.identifier(argName))); } else { newParams.push(t.identifier(argName)); genNewArgs.push(() => t.identifier(argName)); } } fnPath.insertAfter( t.functionDeclaration( originalFnName, newParams, t.blockStatement([ t.ifStatement( gatingCondition, t.returnStatement( t.callExpression( compiled.id, genNewArgs.map((fn) => fn()) ) ), t.returnStatement( t.callExpression( unoptimizedFnName, genNewArgs.map((fn) => fn()) ) ) ) ]) ) ); fnPath.insertBefore( t.variableDeclaration("const", [ t.variableDeclarator( gatingCondition, t.callExpression(t.identifier(gatingFunctionIdentifierName), []) ) ]) ); fnPath.insertBefore(compiled); } function insertGatedFunctionDeclaration(fnPath, compiled, programContext, gating, referencedBeforeDeclaration) { var _a; const gatingImportedName = programContext.addImportSpecifier(gating).name; if (referencedBeforeDeclaration && fnPath.isFunctionDeclaration()) { CompilerError.invariant(compiled.type === "FunctionDeclaration", { reason: "Expected compiled node type to match input type", description: `Got ${compiled.type} but expected FunctionDeclaration`, details: [ { kind: "error", loc: (_a = fnPath.node.loc) != null ? _a : null, message: null } ] }); insertAdditionalFunctionDeclaration( fnPath, compiled, programContext, gatingImportedName ); } else { const gatingExpression = t.conditionalExpression( t.callExpression(t.identifier(gatingImportedName), []), buildFunctionExpression(compiled), buildFunctionExpression(fnPath.node) ); if (fnPath.parentPath.node.type !== "ExportDefaultDeclaration" && fnPath.node.type === "FunctionDeclaration" && fnPath.node.id != null) { fnPath.replaceWith( t.variableDeclaration("const", [ t.variableDeclarator(fnPath.node.id, gatingExpression) ]) ); } else if (fnPath.parentPath.node.type === "ExportDefaultDeclaration" && fnPath.node.type !== "ArrowFunctionExpression" && fnPath.node.id != null) { fnPath.insertAfter( t.exportDefaultDeclaration(t.identifier(fnPath.node.id.name)) ); fnPath.parentPath.replaceWith( t.variableDeclaration("const", [ t.variableDeclarator( t.identifier(fnPath.node.id.name), gatingExpression ) ]) ); } else { fnPath.replaceWith(gatingExpression); } } } function buildFunctionExpression(node) { var _a, _b; if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") { return node; } else { const fn = { type: "FunctionExpression", async: node.async, generator: node.generator, loc: (_a = node.loc) != null ? _a : null, id: (_b = node.id) != null ? _b : null, params: node.params, body: node.body }; return fn; } } // src/Entrypoint/Imports.ts var t5 = __toESM(require("@babel/types")); // src/HIR/HIR.ts var t2 = __toESM(require("@babel/types")); // src/HIR/Types.ts var opaqueTypeId = Symbol(); function makeTypeId(id) { CompilerError.invariant(id >= 0 && Number.isInteger(id), { reason: "Expected instruction id to be a non-negative integer", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return id; } var typeCounter = 0; function makeType() { return { kind: "Type", id: makeTypeId(typeCounter++) }; } function typeEquals(tA, tB) { if (tA.kind !== tB.kind) return false; return typeVarEquals(tA, tB) || funcTypeEquals(tA, tB) || objectTypeEquals(tA, tB) || primitiveTypeEquals(tA, tB) || polyTypeEquals(tA, tB) || phiTypeEquals(tA, tB) || propTypeEquals(tA, tB) || objectMethodTypeEquals(tA, tB); } function typeVarEquals(tA, tB) { if (tA.kind === "Type" && tB.kind === "Type") { return tA.id === tB.id; } return false; } function typeKindCheck(tA, tb, type) { return tA.kind === type && tb.kind === type; } function objectMethodTypeEquals(tA, tB) { return typeKindCheck(tA, tB, "ObjectMethod"); } function propTypeEquals(tA, tB) { if (tA.kind === "Property" && tB.kind === "Property") { if (!typeEquals(tA.objectType, tB.objectType)) { return false; } return tA.propertyName === tB.propertyName && tA.objectName === tB.objectName; } return false; } function primitiveTypeEquals(tA, tB) { return typeKindCheck(tA, tB, "Primitive"); } function polyTypeEquals(tA, tB) { return typeKindCheck(tA, tB, "Poly"); } function objectTypeEquals(tA, tB) { if (tA.kind === "Object" && tB.kind == "Object") { return tA.shapeId === tB.shapeId; } return false; } function funcTypeEquals(tA, tB) { if (tA.kind !== "Function" || tB.kind !== "Function") { return false; } return typeEquals(tA.return, tB.return); } function phiTypeEquals(tA, tB) { if (tA.kind === "Phi" && tB.kind === "Phi") { if (tA.operands.length !== tB.operands.length) { return false; } let operands = new Set(tA.operands); for (let i = 0; i < tB.operands.length; i++) { if (!operands.has(tB.operands[i])) { return false; } } } return false; } // ../../node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodFile: () => ZodFile, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNanoID: () => ZodNanoID, ZodNever: () => ZodNever, ZodNonOptional: () => ZodNonOptional, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodNumberFormat: () => ZodNumberFormat, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodPipe: () => ZodPipe, ZodPrefault: () => ZodPrefault, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRealError: () => ZodRealError, ZodRecord: () => ZodRecord, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodStringFormat: () => ZodStringFormat, ZodSuccess: () => ZodSuccess, ZodSymbol: () => ZodSymbol, ZodTemplateLiteral: () => ZodTemplateLiteral, ZodTransform: () => ZodTransform, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodULID: () => ZodULID, ZodURL: () => ZodURL, ZodUUID: () => ZodUUID, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, ZodXID: () => ZodXID, _ZodString: () => _ZodString, _default: () => _default2, _function: () => _function, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, clone: () => clone, codec: () => codec, coerce: () => coerce_exports, config: () => config, core: () => core_exports2, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom, date: () => date3, decode: () => decode2, decodeAsync: () => decodeAsync2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, encode: () => encode2, encodeAsync: () => encodeAsync2, endsWith: () => _endsWith, enum: () => _enum2, file: () => file, flattenError: () => flattenError, float32: () => float32, float64: () => float64, formatError: () => formatError, function: () => _function, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, gte: () => _gte, guid: () => guid2, hash: () => hash, hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, includes: () => _includes, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, ipv4: () => ipv42, ipv6: () => ipv62, iso: () => iso_exports, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, length: () => _length, literal: () => literal2, locales: () => locales_exports, looseObject: () => looseObject, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, negative: () => _negative, never: () => never, nonnegative: () => _nonnegative, nonoptional: () => nonoptional, nonpositive: () => _nonpositive, normalize: () => _normalize, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object, optional: () => optional, overwrite: () => _overwrite, parse: () => parse4, parseAsync: () => parseAsync2, partialRecord: () => partialRecord, pipe: () => pipe, positive: () => _positive, prefault: () => prefault, preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, property: () => _property, readonly: () => readonly, record: () => record, refine: () => refine, regex: () => _regex, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode2, safeDecodeAsync: () => safeDecodeAsync2, safeEncode: () => safeEncode2, safeEncodeAsync: () => safeEncodeAsync2, safeParse: () => safeParse2, safeParseAsync: () => safeParseAsync2, set: () => set, setErrorMap: () => setErrorMap, size: () => _size, startsWith: () => _startsWith, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol, templateLiteral: () => templateLiteral, toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, uppercase: () => _uppercase, url: () => url, util: () => util_exports, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2 }); // ../../node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, $ZodArray: () => $ZodArray, $ZodAsyncError: () => $ZodAsyncError, $ZodBase64: () => $ZodBase64, $ZodBase64URL: () => $ZodBase64URL, $ZodBigInt: () => $ZodBigInt, $ZodBigIntFormat: () => $ZodBigIntFormat, $ZodBoolean: () => $ZodBoolean, $ZodCIDRv4: () => $ZodCIDRv4, $ZodCIDRv6: () => $ZodCIDRv6, $ZodCUID: () => $ZodCUID, $ZodCUID2: () => $ZodCUID2, $ZodCatch: () => $ZodCatch, $ZodCheck: () => $ZodCheck, $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, $ZodCheckEndsWith: () => $ZodCheckEndsWith, $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, $ZodCheckIncludes: () => $ZodCheckIncludes, $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, $ZodCheckLessThan: () => $ZodCheckLessThan, $ZodCheckLowerCase: () => $ZodCheckLowerCase, $ZodCheckMaxLength: () => $ZodCheckMaxLength, $ZodCheckMaxSize: () => $ZodCheckMaxSize, $ZodCheckMimeType: () => $ZodCheckMimeType, $ZodCheckMinLength: () => $ZodCheckMinLength, $ZodCheckMinSize: () => $ZodCheckMinSize, $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, $ZodCheckStartsWith: () => $ZodCheckStartsWith, $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, $ZodE164: () => $ZodE164, $ZodEmail: () => $ZodEmail, $ZodEmoji: () => $ZodEmoji, $ZodEncodeError: () => $ZodEncodeError, $ZodEnum: () => $ZodEnum, $ZodError: () => $ZodError, $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, $ZodISODateTime: () => $ZodISODateTime, $ZodISODuration: () => $ZodISODuration, $ZodISOTime: () => $ZodISOTime, $ZodIntersection: () => $ZodIntersection, $ZodJWT: () => $ZodJWT, $ZodKSUID: () => $ZodKSUID, $ZodLazy: () => $ZodLazy, $ZodLiteral: () => $ZodLiteral, $ZodMap: () => $ZodMap, $ZodNaN: () => $ZodNaN, $ZodNanoID: () => $ZodNanoID, $ZodNever: () => $ZodNever, $ZodNonOptional: () => $ZodNonOptional, $ZodNull: () => $ZodNull, $ZodNullable: () => $ZodNullable, $ZodNumber: () => $ZodNumber, $ZodNumberFormat: () => $ZodNumberFormat, $ZodObject: () => $ZodObject, $ZodObjectJIT: () => $ZodObjectJIT, $ZodOptional: () => $ZodOptional, $ZodPipe: () => $ZodPipe, $ZodPrefault: () => $ZodPrefault, $ZodPromise: () => $ZodPromise, $ZodReadonly: () => $ZodReadonly, $ZodRealError: () => $ZodRealError, $ZodRecord: () => $ZodRecord, $ZodRegistry: () => $ZodRegistry, $ZodSet: () => $ZodSet, $ZodString: () => $ZodString, $ZodStringFormat: () => $ZodStringFormat, $ZodSuccess: () => $ZodSuccess, $ZodSymbol: () => $ZodSymbol, $ZodTemplateLiteral: () => $ZodTemplateLiteral, $ZodTransform: () => $ZodTransform, $ZodTuple: () => $ZodTuple, $ZodType: () => $ZodType, $ZodULID: () => $ZodULID, $ZodURL: () => $ZodURL, $ZodUUID: () => $ZodUUID, $ZodUndefined: () => $ZodUndefined, $ZodUnion: () => $ZodUnion, $ZodUnknown: () => $ZodUnknown, $ZodVoid: () => $ZodVoid, $ZodXID: () => $ZodXID, $brand: () => $brand, $constructor: () => $constructor, $input: () => $input, $output: () => $output, Doc: () => Doc, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, _any: () => _any, _array: () => _array, _base64: () => _base64, _base64url: () => _base64url, _bigint: () => _bigint, _boolean: () => _boolean, _catch: () => _catch, _check: () => _check, _cidrv4: () => _cidrv4, _cidrv6: () => _cidrv6, _coercedBigint: () => _coercedBigint, _coercedBoolean: () => _coercedBoolean, _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, _date: () => _date, _decode: () => _decode, _decodeAsync: () => _decodeAsync, _default: () => _default, _discriminatedUnion: () => _discriminatedUnion, _e164: () => _e164, _email: () => _email, _emoji: () => _emoji2, _encode: () => _encode, _encodeAsync: () => _encodeAsync, _endsWith: () => _endsWith, _enum: () => _enum, _file: () => _file, _float32: () => _float32, _float64: () => _float64, _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, _includes: () => _includes, _int: () => _int, _int32: () => _int32, _int64: () => _int64, _intersection: () => _intersection, _ipv4: () => _ipv4, _ipv6: () => _ipv6, _isoDate: () => _isoDate, _isoDateTime: () => _isoDateTime, _isoDuration: () => _isoDuration, _isoTime: () => _isoTime, _jwt: () => _jwt, _ksuid: () => _ksuid, _lazy: () => _lazy, _length: () => _length, _literal: () => _literal, _lowercase: () => _lowercase, _lt: () => _lt, _lte: () => _lte, _map: () => _map, _max: () => _lte, _maxLength: () => _maxLength, _maxSize: () => _maxSize, _mime: () => _mime, _min: () => _gte, _minLength: () => _minLength, _minSize: () => _minSize, _multipleOf: () => _multipleOf, _nan: () => _nan, _nanoid: () => _nanoid, _nativeEnum: () => _nativeEnum, _negative: () => _negative, _never: () => _never, _nonnegative: () => _nonnegative, _nonoptional: () => _nonoptional, _nonpositive: () => _nonpositive, _normalize: () => _normalize, _null: () => _null2, _nullable: () => _nullable, _number: () => _number, _optional: () => _optional, _overwrite: () => _overwrite, _parse: () => _parse, _parseAsync: () => _parseAsync, _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, _property: () => _property, _readonly: () => _readonly, _record: () => _record, _refine: () => _refine, _regex: () => _regex, _safeDecode: () => _safeDecode, _safeDecodeAsync: () => _safeDecodeAsync, _safeEncode: () => _safeEncode, _safeEncodeAsync: () => _safeEncodeAsync, _safeParse: () => _safeParse, _safeParseAsync: () => _safeParseAsync, _set: () => _set, _size: () => _size, _startsWith: () => _startsWith, _string: () => _string, _stringFormat: () => _stringFormat, _stringbool: () => _stringbool, _success: () => _success, _superRefine: () => _superRefine, _symbol: () => _symbol, _templateLiteral: () => _templateLiteral, _toLowerCase: () => _toLowerCase, _toUpperCase: () => _toUpperCase, _transform: () => _transform, _trim: () => _trim, _tuple: () => _tuple, _uint32: () => _uint32, _uint64: () => _uint64, _ulid: () => _ulid, _undefined: () => _undefined2, _union: () => _union, _unknown: () => _unknown, _uppercase: () => _uppercase, _url: () => _url, _uuid: () => _uuid, _uuidv4: () => _uuidv4, _uuidv6: () => _uuidv6, _uuidv7: () => _uuidv7, _void: () => _void, _xid: () => _xid, clone: () => clone, config: () => config, decode: () => decode, decodeAsync: () => decodeAsync, encode: () => encode, encodeAsync: () => encodeAsync, flattenError: () => flattenError, formatError: () => formatError, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, isValidJWT: () => isValidJWT, locales: () => locales_exports, parse: () => parse3, parseAsync: () => parseAsync, prettifyError: () => prettifyError, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, safeDecodeAsync: () => safeDecodeAsync, safeEncode: () => safeEncode, safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, treeifyError: () => treeifyError, util: () => util_exports, version: () => version }); // ../../node_modules/zod/v4/core/core.js var NEVER = Object.freeze({ status: "aborted" }); // @__NO_SIDE_EFFECTS__ function $constructor(name, initializer3, params) { var _a; function init(inst, def) { var _a3, _b; var _a2; Object.defineProperty(inst, "_zod", { value: (_a3 = inst._zod) != null ? _a3 : {}, enumerable: false }); (_b = (_a2 = inst._zod).traits) != null ? _b : _a2.traits = /* @__PURE__ */ new Set(); inst._zod.traits.add(name); initializer3(inst, def); for (const k in _.prototype) { if (!(k in inst)) Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); } inst._zod.constr = _; inst._zod.def = def; } const Parent = (_a = params == null ? void 0 : params.Parent) != null ? _a : Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name }); function _(def) { var _a3; var _a2; const inst = (params == null ? void 0 : params.Parent) ? new Definition() : this; init(inst, def); (_a3 = (_a2 = inst._zod).deferred) != null ? _a3 : _a2.deferred = []; for (const fn of inst._zod.deferred) { fn(); } return inst; } Object.defineProperty(_, "init", { value: init }); Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { var _a2, _b; if ((params == null ? void 0 : params.Parent) && inst instanceof params.Parent) return true; return (_b = (_a2 = inst == null ? void 0 : inst._zod) == null ? void 0 : _a2.traits) == null ? void 0 : _b.has(name); } }); Object.defineProperty(_, "name", { value: name }); return _; } var $brand = Symbol("zod_brand"); var $ZodAsyncError = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; var $ZodEncodeError = class extends Error { constructor(name) { super(`Encountered unidirectional transform during encode: ${name}`); this.name = "ZodEncodeError"; } }; var globalConfig = {}; function config(newConfig) { if (newConfig) Object.assign(globalConfig, newConfig); return globalConfig; } // ../../node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, allowsEval: () => allowsEval, assert: () => assert, assertEqual: () => assertEqual, assertIs: () => assertIs, assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, captureStackTrace: () => captureStackTrace, cleanEnum: () => cleanEnum, cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, esc: () => esc, escapeRegex: () => escapeRegex, extend: () => extend, finalizeIssue: () => finalizeIssue, floatSafeRemainder: () => floatSafeRemainder, getElementAtPath: () => getElementAtPath, getEnumValues: () => getEnumValues, getLengthableOrigin: () => getLengthableOrigin, getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, isObject: () => isObject, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, nullish: () => nullish, numKeys: () => numKeys, objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, partial: () => partial, pick: () => pick, prefixIssues: () => prefixIssues, primitiveTypes: () => primitiveTypes, promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, stringifyPrimitive: () => stringifyPrimitive, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, unwrapMessage: () => unwrapMessage }); function assertEqual(val) { return val; } function assertNotEqual(val) { return val; } function assertIs(_arg) { } function assertNever(_x) { throw new Error(); } function assert(_) { } function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v) => typeof v === "number"); const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); return values; } function joinValues(array2, separator = "|") { return array2.map((val) => stringifyPrimitive(val)).join(separator); } function jsonStringifyReplacer(_, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached(getter) { const set2 = false; return { get value() { if (!set2) { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } throw new Error("cached value already set"); } }; } function nullish(input) { return input === null || input === void 0; } function cleanRegex(source2) { const start = source2.startsWith("^") ? 1 : 0; const end = source2.endsWith("$") ? source2.length - 1 : source2.length; return source2.slice(start, end); } function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepString = step.toString(); let stepDecCount = (stepString.split(".")[1] || "").length; if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { const match = stepString.match(/\d?e-(\d?)/); if (match == null ? void 0 : match[1]) { stepDecCount = Number.parseInt(match[1]); } } const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / __pow(10, decCount); } var EVALUATING = Symbol("evaluating"); function defineLazy(object2, key2, getter) { let value = void 0; Object.defineProperty(object2, key2, { get() { if (value === EVALUATING) { return void 0; } if (value === void 0) { value = EVALUATING; value = getter(); } return value; }, set(v) { Object.defineProperty(object2, key2, { value: v // configurable: true, }); }, configurable: true }); } function objectClone(obj) { return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true }); } function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { const descriptors = Object.getOwnPropertyDescriptors(def); Object.assign(mergedDescriptors, descriptors); } return Object.defineProperties({}, mergedDescriptors); } function cloneDef(schema) { return mergeDefs(schema._zod.def); } function getElementAtPath(obj, path) { if (!path) return obj; return path.reduce((acc, key2) => acc == null ? void 0 : acc[key2], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); const promises = keys.map((key2) => promisesObj[key2]); return Promise.all(promises).then((results) => { const resolvedObj = {}; for (let i = 0; i < keys.length; i++) { resolvedObj[keys[i]] = results[i]; } return resolvedObj; }); } function randomString(length = 10) { const chars = "abcdefghijklmnopqrstuvwxyz"; let str = ""; for (let i = 0; i < length; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } function esc(str) { return JSON.stringify(str); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } var allowsEval = cached(() => { var _a; if (typeof navigator !== "undefined" && ((_a = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a.includes("Cloudflare"))) { return false; } try { const F = Function; new F(""); return true; } catch (_) { return false; } }); function isPlainObject(o) { if (isObject(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function shallowClone(o) { if (isPlainObject(o)) return __spreadValues({}, o); if (Array.isArray(o)) return [...o]; return o; } function numKeys(data) { let keyCount = 0; for (const key2 in data) { if (Object.prototype.hasOwnProperty.call(data, key2)) { keyCount++; } } return keyCount; } var getParsedType = (data) => { const t6 = typeof data; switch (t6) { case "undefined": return "undefined"; case "string": return "string"; case "number": return Number.isNaN(data) ? "nan" : "number"; case "boolean": return "boolean"; case "function": return "function"; case "bigint": return "bigint"; case "symbol": return "symbol"; case "object": if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return "promise"; } if (typeof Map !== "undefined" && data instanceof Map) { return "map"; } if (typeof Set !== "undefined" && data instanceof Set) { return "set"; } if (typeof Date !== "undefined" && data instanceof Date) { return "date"; } if (typeof File !== "undefined" && data instanceof File) { return "file"; } return "object"; default: throw new Error(`Unknown data type: ${t6}`); } }; var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function clone(inst, def, params) { const cl = new inst._zod.constr(def != null ? def : inst._zod.def); if (!def || (params == null ? void 0 : params.parent)) cl._zod.parent = inst; return cl; } function normalizeParams(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if ((params == null ? void 0 : params.message) !== void 0) { if ((params == null ? void 0 : params.error) !== void 0) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return __spreadProps(__spreadValues({}, params), { error: () => params.error }); return params; } function createTransparentProxy(getter) { let target; return new Proxy({}, { get(_, prop, receiver) { target != null ? target : target = getter(); return Reflect.get(target, prop, receiver); }, set(_, prop, value, receiver) { target != null ? target : target = getter(); return Reflect.set(target, prop, value, receiver); }, has(_, prop) { target != null ? target : target = getter(); return Reflect.has(target, prop); }, deleteProperty(_, prop) { target != null ? target : target = getter(); return Reflect.deleteProperty(target, prop); }, ownKeys(_) { target != null ? target : target = getter(); return Reflect.ownKeys(target); }, getOwnPropertyDescriptor(_, prop) { target != null ? target : target = getter(); return Reflect.getOwnPropertyDescriptor(target, prop); }, defineProperty(_, prop, descriptor) { target != null ? target : target = getter(); return Reflect.defineProperty(target, prop, descriptor); } }); } function stringifyPrimitive(value) { if (typeof value === "bigint") return value.toString() + "n"; if (typeof value === "string") return `"${value}"`; return `${value}`; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } var NUMBER_FORMAT_RANGES = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] }; function pick(schema, mask) { const currDef = schema._zod.def; const def = mergeDefs(schema._zod.def, { get shape() { const newShape = {}; for (const key2 in mask) { if (!(key2 in currDef.shape)) { throw new Error(`Unrecognized key: "${key2}"`); } if (!mask[key2]) continue; newShape[key2] = currDef.shape[key2]; } assignProp(this, "shape", newShape); return newShape; }, checks: [] }); return clone(schema, def); } function omit(schema, mask) { const currDef = schema._zod.def; const def = mergeDefs(schema._zod.def, { get shape() { const newShape = __spreadValues({}, schema._zod.def.shape); for (const key2 in mask) { if (!(key2 in currDef.shape)) { throw new Error(`Unrecognized key: "${key2}"`); } if (!mask[key2]) continue; delete newShape[key2]; } assignProp(this, "shape", newShape); return newShape; }, checks: [] }); return clone(schema, def); } function extend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead."); } const def = mergeDefs(schema._zod.def, { get shape() { const _shape = __spreadValues(__spreadValues({}, schema._zod.def.shape), shape); assignProp(this, "shape", _shape); return _shape; }, checks: [] }); return clone(schema, def); } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } const def = __spreadProps(__spreadValues({}, schema._zod.def), { get shape() { const _shape = __spreadValues(__spreadValues({}, schema._zod.def.shape), shape); assignProp(this, "shape", _shape); return _shape; }, checks: schema._zod.def.checks }); return clone(schema, def); } function merge(a, b) { const def = mergeDefs(a._zod.def, { get shape() { const _shape = __spreadValues(__spreadValues({}, a._zod.def.shape), b._zod.def.shape); assignProp(this, "shape", _shape); return _shape; }, get catchall() { return b._zod.def.catchall; }, checks: [] // delete existing checks }); return clone(a, def); } function partial(Class2, schema, mask) { const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = __spreadValues({}, oldShape); if (mask) { for (const key2 in mask) { if (!(key2 in oldShape)) { throw new Error(`Unrecognized key: "${key2}"`); } if (!mask[key2]) continue; shape[key2] = Class2 ? new Class2({ type: "optional", innerType: oldShape[key2] }) : oldShape[key2]; } } else { for (const key2 in oldShape) { shape[key2] = Class2 ? new Class2({ type: "optional", innerType: oldShape[key2] }) : oldShape[key2]; } } assignProp(this, "shape", shape); return shape; }, checks: [] }); return clone(schema, def); } function required(Class2, schema, mask) { const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = __spreadValues({}, oldShape); if (mask) { for (const key2 in mask) { if (!(key2 in shape)) { throw new Error(`Unrecognized key: "${key2}"`); } if (!mask[key2]) continue; shape[key2] = new Class2({ type: "nonoptional", innerType: oldShape[key2] }); } } else { for (const key2 in oldShape) { shape[key2] = new Class2({ type: "nonoptional", innerType: oldShape[key2] }); } } assignProp(this, "shape", shape); return shape; }, checks: [] }); return clone(schema, def); } function aborted(x, startIndex = 0) { var _a; if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) { if (((_a = x.issues[i]) == null ? void 0 : _a.continue) !== true) { return true; } } return false; } function prefixIssues(path, issues) { return issues.map((iss) => { var _a2; var _a; (_a2 = (_a = iss).path) != null ? _a2 : _a.path = []; iss.path.unshift(path); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message == null ? void 0 : message.message; } function finalizeIssue(iss, ctx, config2) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; const full = __spreadProps(__spreadValues({}, iss), { path: (_a = iss.path) != null ? _a : [] }); if (!iss.message) { const message = (_k = (_j = (_h = (_f = unwrapMessage((_d = (_c = (_b = iss.inst) == null ? void 0 : _b._zod.def) == null ? void 0 : _c.error) == null ? void 0 : _d.call(_c, iss))) != null ? _f : unwrapMessage((_e = ctx == null ? void 0 : ctx.error) == null ? void 0 : _e.call(ctx, iss))) != null ? _h : unwrapMessage((_g = config2.customError) == null ? void 0 : _g.call(config2, iss))) != null ? _j : unwrapMessage((_i = config2.localeError) == null ? void 0 : _i.call(config2, iss))) != null ? _k : "Invalid input"; full.message = message; } delete full.inst; delete full.continue; if (!(ctx == null ? void 0 : ctx.reportInput)) { delete full.input; } return full; } function getSizableOrigin(input) { if (input instanceof Set) return "set"; if (input instanceof Map) return "map"; if (input instanceof File) return "file"; return "unknown"; } function getLengthableOrigin(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } function issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst }; } return __spreadValues({}, iss); } function cleanEnum(obj) { return Object.entries(obj).filter(([k, _]) => { return Number.isNaN(Number.parseInt(k, 10)); }).map((el) => el[1]); } function base64ToUint8Array(base643) { const binaryString = atob(base643); const bytes = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); } return bytes; } function uint8ArrayToBase64(bytes) { let binaryString = ""; for (let i = 0; i < bytes.length; i++) { binaryString += String.fromCharCode(bytes[i]); } return btoa(binaryString); } function base64urlToUint8Array(base64url3) { const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); const padding = "=".repeat((4 - base643.length % 4) % 4); return base64ToUint8Array(base643 + padding); } function uint8ArrayToBase64url(bytes) { return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } function hexToUint8Array(hex3) { const cleanHex = hex3.replace(/^0x/, ""); if (cleanHex.length % 2 !== 0) { throw new Error("Invalid hex string length"); } const bytes = new Uint8Array(cleanHex.length / 2); for (let i = 0; i < cleanHex.length; i += 2) { bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); } return bytes; } function uint8ArrayToHex(bytes) { return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); } var Class = class { constructor(..._args) { } }; // ../../node_modules/zod/v4/core/errors.js var initializer = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { value: inst._zod, enumerable: false }); Object.defineProperty(inst, "issues", { value: def, enumerable: false }); inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); Object.defineProperty(inst, "toString", { value: () => inst.message, enumerable: false }); }; var $ZodError = $constructor("$ZodError", initializer); var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); function flattenError(error45, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; for (const sub of error45.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 }; } function formatError(error45, _mapper) { const mapper = _mapper || function(issue2) { return issue2.message; }; const fieldErrors = { _errors: [] }; const processError = (error46) => { for (const issue2 of error46.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues })); } else if (issue2.code === "invalid_key") { processError({ issues: issue2.issues }); } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }); } else if (issue2.path.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; let i = 0; while (i < issue2.path.length) { const el = issue2.path[i]; const terminal = i === issue2.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; i++; } } } }; processError(error45); return fieldErrors; } function treeifyError(error45, _mapper) { const mapper = _mapper || function(issue2) { return issue2.message; }; const result = { errors: [] }; const processError = (error46, path = []) => { var _a2, _b2, _c, _d; var _a, _b; for (const issue2 of error46.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, issue2.path)); } else if (issue2.code === "invalid_key") { processError({ issues: issue2.issues }, issue2.path); } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }, issue2.path); } else { const fullpath = [...path, ...issue2.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue2)); continue; } let curr = result; let i = 0; while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; if (typeof el === "string") { (_a2 = curr.properties) != null ? _a2 : curr.properties = {}; (_b2 = (_a = curr.properties)[el]) != null ? _b2 : _a[el] = { errors: [] }; curr = curr.properties[el]; } else { (_c = curr.items) != null ? _c : curr.items = []; (_d = (_b = curr.items)[el]) != null ? _d : _b[el] = { errors: [] }; curr = curr.items[el]; } if (terminal) { curr.errors.push(mapper(issue2)); } i++; } } } }; processError(error45); return result; } function toDotPath(_path) { const segs = []; const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg); for (const seg of path) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); else { if (segs.length) segs.push("."); segs.push(seg); } } return segs.join(""); } function prettifyError(error45) { var _a; const lines = []; const issues = [...error45.issues].sort((a, b) => { var _a2, _b; return ((_a2 = a.path) != null ? _a2 : []).length - ((_b = b.path) != null ? _b : []).length; }); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if ((_a = issue2.path) == null ? void 0 : _a.length) lines.push(` \u2192 at ${toDotPath(issue2.path)}`); } return lines.join("\n"); } // ../../node_modules/zod/v4/core/parse.js var _parse = (_Err) => (schema, value, _ctx, _params) => { var _a; const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } if (result.issues.length) { const e = new ((_a = _params == null ? void 0 : _params.Err) != null ? _a : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, _params == null ? void 0 : _params.callee); throw e; } return result.value; }; var parse3 = /* @__PURE__ */ _parse($ZodRealError); var _parseAsync = (_Err) => (schema, value, _ctx, params) => __async(void 0, null, function* () { var _a; const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = yield result; if (result.issues.length) { const e = new ((_a = params == null ? void 0 : params.Err) != null ? _a : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, params == null ? void 0 : params.callee); throw e; } return result.value; }); var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? __spreadProps(__spreadValues({}, _ctx), { async: false }) : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } return result.issues.length ? { success: false, error: new (_Err != null ? _Err : $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); var _safeParseAsync = (_Err) => (schema, value, _ctx) => __async(void 0, null, function* () { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = yield result; return result.issues.length ? { success: false, error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }); var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); var _encode = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _parse(_Err)(schema, value, ctx); }; var encode = /* @__PURE__ */ _encode($ZodRealError); var _decode = (_Err) => (schema, value, _ctx) => { return _parse(_Err)(schema, value, _ctx); }; var decode = /* @__PURE__ */ _decode($ZodRealError); var _encodeAsync = (_Err) => (schema, value, _ctx) => __async(void 0, null, function* () { const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _parseAsync(_Err)(schema, value, ctx); }); var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); var _decodeAsync = (_Err) => (schema, value, _ctx) => __async(void 0, null, function* () { return _parseAsync(_Err)(schema, value, _ctx); }); var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _safeParse(_Err)(schema, value, ctx); }; var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); var _safeDecode = (_Err) => (schema, value, _ctx) => { return _safeParse(_Err)(schema, value, _ctx); }; var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); var _safeEncodeAsync = (_Err) => (schema, value, _ctx) => __async(void 0, null, function* () { const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _safeParseAsync(_Err)(schema, value, ctx); }); var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); var _safeDecodeAsync = (_Err) => (schema, value, _ctx) => __async(void 0, null, function* () { return _safeParseAsync(_Err)(schema, value, _ctx); }); var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); // ../../node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { base64: () => base64, base64url: () => base64url, bigint: () => bigint, boolean: () => boolean, browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, cuid: () => cuid, cuid2: () => cuid2, date: () => date, datetime: () => datetime, domain: () => domain, duration: () => duration, e164: () => e164, email: () => email, emoji: () => emoji, extendedDuration: () => extendedDuration, guid: () => guid, hex: () => hex, hostname: () => hostname, html5Email: () => html5Email, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, ipv6: () => ipv6, ksuid: () => ksuid, lowercase: () => lowercase, md5_base64: () => md5_base64, md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, sha1_base64: () => sha1_base64, sha1_base64url: () => sha1_base64url, sha1_hex: () => sha1_hex, sha256_base64: () => sha256_base64, sha256_base64url: () => sha256_base64url, sha256_hex: () => sha256_hex, sha384_base64: () => sha384_base64, sha384_base64url: () => sha384_base64url, sha384_hex: () => sha384_hex, sha512_base64: () => sha512_base64, sha512_base64url: () => sha512_base64url, sha512_hex: () => sha512_hex, string: () => string, time: () => time, ulid: () => ulid, undefined: () => _undefined, unicodeEmail: () => unicodeEmail, uppercase: () => uppercase, uuid: () => uuid, uuid4: () => uuid4, uuid6: () => uuid6, uuid7: () => uuid7, xid: () => xid }); var cuid = /^[cC][^\s-]{8,}$/; var cuid2 = /^[0-9a-z]+$/; var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?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 guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; var uuid = (version2) => { if (!version2) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji() { return new RegExp(_emoji, "u"); } var ipv4 = /^(?:(?: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 ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; var cidrv4 = /^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/; var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; var base64url = /^[A-Za-z0-9_-]*$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; var e164 = /^\+(?:[0-9]){6,14}[0-9]$/; var dateSource = `(?:(?:\\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 date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { const time3 = timeSource({ precision: args.precision }); const opts = ["Z"]; if (args.local) opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); const timeRegex = `${time3}(?:${opts.join("|")})`; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } var string = (params) => { var _a, _b; const regex = params ? `[\\s\\S]{${(_a = params == null ? void 0 : params.minimum) != null ? _a : 0},${(_b = params == null ? void 0 : params.maximum) != null ? _b : ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; var bigint = /^-?\d+n?$/; var integer = /^-?\d+$/; var number = /^-?\d+(?:\.\d+)?/; var boolean = /^(?:true|false)$/i; var _null = /^null$/i; var _undefined = /^undefined$/i; var lowercase = /^[^A-Z]*$/; var uppercase = /^[^a-z]*$/; var hex = /^[0-9a-fA-F]*$/; function fixedBase64(bodyLength, padding) { return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); } function fixedBase64url(length) { return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); } var md5_hex = /^[0-9a-fA-F]{32}$/; var md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); var md5_base64url = /* @__PURE__ */ fixedBase64url(22); var sha1_hex = /^[0-9a-fA-F]{40}$/; var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); var sha1_base64url = /* @__PURE__ */ fixedBase64url(27); var sha256_hex = /^[0-9a-fA-F]{64}$/; var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); var sha256_base64url = /* @__PURE__ */ fixedBase64url(43); var sha384_hex = /^[0-9a-fA-F]{96}$/; var sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); var sha384_base64url = /* @__PURE__ */ fixedBase64url(64); var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); // ../../node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a2, _b; var _a; (_a2 = inst._zod) != null ? _a2 : inst._zod = {}; inst._zod.def = def; (_b = (_a = inst._zod).onattach) != null ? _b : _a.onattach = []; }); var numericOriginMap = { number: "number", bigint: "bigint", object: "date" }; var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { var _a; const bag = inst2._zod.bag; const curr = (_a = def.inclusive ? bag.maximum : bag.exclusiveMaximum) != null ? _a : Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; else bag.exclusiveMaximum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ origin, code: "too_big", maximum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { var _a; const bag = inst2._zod.bag; const curr = (_a = def.inclusive ? bag.minimum : bag.exclusiveMinimum) != null ? _a : Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; else bag.exclusiveMinimum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ origin, code: "too_small", minimum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { var _a2; var _a; (_a2 = (_a = inst2._zod.bag).multipleOf) != null ? _a2 : _a.multipleOf = def.value; }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ origin: typeof payload.value, code: "not_multiple_of", divisor: def.value, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { var _a; $ZodCheck.init(inst, def); def.format = def.format || "float64"; const isInt = (_a = def.format) == null ? void 0 : _a.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; if (isInt) bag.pattern = integer; }); inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, input, inst }); return; } if (!Number.isSafeInteger(input)) { if (input > 0) { payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort }); } else { payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort }); } return; } } if (input < minimum) { payload.issues.push({ origin: "number", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "number", input, code: "too_big", maximum, inst }); } }; }); var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; }); inst._zod.check = (payload) => { const input = payload.value; if (input < minimum) { payload.issues.push({ origin: "bigint", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "bigint", input, code: "too_big", maximum, inst }); } }; }); var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a2; var _a; $ZodCheck.init(inst, def); (_a2 = (_a = inst._zod.def).when) != null ? _a2 : _a.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }; inst._zod.onattach.push((inst2) => { var _a3; const curr = (_a3 = inst2._zod.bag.maximum) != null ? _a3 : Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size <= def.maximum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a2; var _a; $ZodCheck.init(inst, def); (_a2 = (_a = inst._zod.def).when) != null ? _a2 : _a.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }; inst._zod.onattach.push((inst2) => { var _a3; const curr = (_a3 = inst2._zod.bag.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size >= def.minimum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a2; var _a; $ZodCheck.init(inst, def); (_a2 = (_a = inst._zod.def).when) != null ? _a2 : _a.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.size; bag.maximum = def.size; bag.size = def.size; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size === def.size) return; const tooBig = size > def.size; payload.issues.push(__spreadProps(__spreadValues({ origin: getSizableOrigin(input) }, tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), { inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort })); }; }); var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a2; var _a; $ZodCheck.init(inst, def); (_a2 = (_a = inst._zod.def).when) != null ? _a2 : _a.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }; inst._zod.onattach.push((inst2) => { var _a3; const curr = (_a3 = inst2._zod.bag.maximum) != null ? _a3 : Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length <= def.maximum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a2; var _a; $ZodCheck.init(inst, def); (_a2 = (_a = inst._zod.def).when) != null ? _a2 : _a.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }; inst._zod.onattach.push((inst2) => { var _a3; const curr = (_a3 = inst2._zod.bag.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length >= def.minimum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a2; var _a; $ZodCheck.init(inst, def); (_a2 = (_a = inst._zod.def).when) != null ? _a2 : _a.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.length; bag.maximum = def.length; bag.length = def.length; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length === def.length) return; const origin = getLengthableOrigin(input); const tooBig = length > def.length; payload.issues.push(__spreadProps(__spreadValues({ origin }, tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), { inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort })); }; }); var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a2, _b2; var _a, _b; $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { var _a3; const bag = inst2._zod.bag; bag.format = def.format; if (def.pattern) { (_a3 = bag.patterns) != null ? _a3 : bag.patterns = /* @__PURE__ */ new Set(); bag.patterns.add(def.pattern); } }); if (def.pattern) (_a2 = (_a = inst._zod).check) != null ? _a2 : _a.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; payload.issues.push(__spreadProps(__spreadValues({ origin: "string", code: "invalid_format", format: def.format, input: payload.value }, def.pattern ? { pattern: def.pattern.toString() } : {}), { inst, continue: !def.abort })); }; else (_b2 = (_b = inst._zod).check) != null ? _b2 : _b.check = () => { }; }); var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { $ZodCheckStringFormat.init(inst, def); inst._zod.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "regex", input: payload.value, pattern: def.pattern.toString(), inst, continue: !def.abort }); }; }); var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = lowercase; $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = uppercase; $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); def.pattern = pattern; inst._zod.onattach.push((inst2) => { var _a; const bag = inst2._zod.bag; (_a = bag.patterns) != null ? _a : bag.patterns = /* @__PURE__ */ new Set(); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: def.includes, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { var _a; $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); (_a = def.pattern) != null ? _a : def.pattern = pattern; inst._zod.onattach.push((inst2) => { var _a2; const bag = inst2._zod.bag; (_a2 = bag.patterns) != null ? _a2 : bag.patterns = /* @__PURE__ */ new Set(); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: def.prefix, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { var _a; $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); (_a = def.pattern) != null ? _a : def.pattern = pattern; inst._zod.onattach.push((inst2) => { var _a2; const bag = inst2._zod.bag; (_a2 = bag.patterns) != null ? _a2 : bag.patterns = /* @__PURE__ */ new Set(); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: def.suffix, input: payload.value, inst, continue: !def.abort }); }; }); function handleCheckPropertyResult(result, payload, property) { if (result.issues.length) { payload.issues.push(...prefixIssues(property, result.issues)); } } var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { const result = def.schema._zod.run({ value: payload.value[def.property], issues: [] }, {}); if (result instanceof Promise) { return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); } handleCheckPropertyResult(result, payload, def.property); return; }; }); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); inst._zod.onattach.push((inst2) => { inst2._zod.bag.mime = def.mime; }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; payload.issues.push({ code: "invalid_value", values: def.mime, input: payload.value.type, inst, continue: !def.abort }); }; }); var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { payload.value = def.tx(payload.value); }; }); // ../../node_modules/zod/v4/core/doc.js var Doc = class { constructor(args = []) { this.content = []; this.indent = 0; if (this) this.args = args; } indented(fn) { this.indent += 1; fn(this); this.indent -= 1; } write(arg) { if (typeof arg === "function") { arg(this, { execution: "sync" }); arg(this, { execution: "async" }); return; } const content = arg; const lines = content.split("\n").filter((x) => x); const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); for (const line2 of dedented) { this.content.push(line2); } } compile() { var _a; const F = Function; const args = this == null ? void 0 : this.args; const content = (_a = this == null ? void 0 : this.content) != null ? _a : [``]; const lines = [...content.map((x) => ` ${x}`)]; return new F(...args, lines.join("\n")); } }; // ../../node_modules/zod/v4/core/versions.js var version = { major: 4, minor: 1, patch: 11 }; // ../../node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a2, _b, _c; var _a; inst != null ? inst : inst = {}; inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; const checks = [...(_a2 = inst._zod.def.checks) != null ? _a2 : []]; if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst); } for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); } } if (checks.length === 0) { (_b = (_a = inst._zod).deferred) != null ? _b : _a.deferred = []; (_c = inst._zod.deferred) == null ? void 0 : _c.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = (payload, checks2, ctx) => { let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { if (ch._zod.def.when) { const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted) { continue; } const currLen = payload.issues.length; const _ = ch._zod.check(payload); if (_ instanceof Promise && (ctx == null ? void 0 : ctx.async) === false) { throw new $ZodAsyncError(); } if (asyncResult || _ instanceof Promise) { asyncResult = (asyncResult != null ? asyncResult : Promise.resolve()).then(() => __async(void 0, null, function* () { yield _; const nextLen = payload.issues.length; if (nextLen === currLen) return; if (!isAborted) isAborted = aborted(payload, currLen); })); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; if (!isAborted) isAborted = aborted(payload, currLen); } } if (asyncResult) { return asyncResult.then(() => { return payload; }); } return payload; }; const handleCanaryResult = (canary, payload, ctx) => { if (aborted(canary)) { canary.aborted = true; return canary; } const checkResult = runChecks(payload, checks, ctx); if (checkResult instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); } return inst._zod.parse(checkResult, ctx); }; inst._zod.run = (payload, ctx) => { if (ctx.skipChecks) { return inst._zod.parse(payload, ctx); } if (ctx.direction === "backward") { const canary = inst._zod.parse({ value: payload.value, issues: [] }, __spreadProps(__spreadValues({}, ctx), { skipChecks: true })); if (canary instanceof Promise) { return canary.then((canary2) => { return handleCanaryResult(canary2, payload, ctx); }); } return handleCanaryResult(canary, payload, ctx); } const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return result.then((result2) => runChecks(result2, checks, ctx)); } return runChecks(result, checks, ctx); }; } inst["~standard"] = { validate: (value) => { var _a3; try { const r = safeParse(inst, value); return r.success ? { value: r.data } : { issues: (_a3 = r.error) == null ? void 0 : _a3.issues }; } catch (_) { return safeParseAsync(inst, value).then((r) => { var _a4; return r.success ? { value: r.data } : { issues: (_a4 = r.error) == null ? void 0 : _a4.issues }; }); } }, vendor: "zod", version: 1 }; }); var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { var _a, _b, _c; $ZodType.init(inst, def); inst._zod.pattern = (_c = [...(_b = (_a = inst == null ? void 0 : inst._zod.bag) == null ? void 0 : _a.patterns) != null ? _b : []].pop()) != null ? _c : string(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_2) { } if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { $ZodCheckStringFormat.init(inst, def); $ZodString.init(inst, def); }); var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = guid; $ZodStringFormat.init(inst, def); }); var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { var _a, _b; if (def.version) { const versionMap = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8 }; const v = versionMap[def.version]; if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); (_a = def.pattern) != null ? _a : def.pattern = uuid(v); } else (_b = def.pattern) != null ? _b : def.pattern = uuid(); $ZodStringFormat.init(inst, def); }); var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = email; $ZodStringFormat.init(inst, def); }); var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); const url2 = new URL(trimmed); if (def.hostname) { def.hostname.lastIndex = 0; if (!def.hostname.test(url2.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: hostname.source, input: payload.value, inst, continue: !def.abort }); } } if (def.protocol) { def.protocol.lastIndex = 0; if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: def.protocol.source, input: payload.value, inst, continue: !def.abort }); } } if (def.normalize) { payload.value = url2.href; } else { payload.value = trimmed; } return; } catch (_) { payload.issues.push({ code: "invalid_format", format: "url", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = emoji(); $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = nanoid; $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = cuid; $ZodStringFormat.init(inst, def); }); var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = cuid2; $ZodStringFormat.init(inst, def); }); var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = ulid; $ZodStringFormat.init(inst, def); }); var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = xid; $ZodStringFormat.init(inst, def); }); var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = ksuid; $ZodStringFormat.init(inst, def); }); var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = datetime(def); $ZodStringFormat.init(inst, def); }); var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = date; $ZodStringFormat.init(inst, def); }); var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = time(def); $ZodStringFormat.init(inst, def); }); var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = duration; $ZodStringFormat.init(inst, def); }); var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = ipv4; $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = `ipv4`; }); }); var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = ipv6; $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = `ipv6`; }); inst._zod.check = (payload) => { try { new URL(`http://[${payload.value}]`); } catch (e) { payload.issues.push({ code: "invalid_format", format: "ipv6", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = cidrv4; $ZodStringFormat.init(inst, def); }); var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = cidrv6; $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { const parts = payload.value.split("/"); try { if (parts.length !== 2) throw new Error(); const [address, prefix] = parts; if (!prefix) throw new Error(); const prefixNum = Number(prefix); if (`${prefixNum}` !== prefix) throw new Error(); if (prefixNum < 0 || prefixNum > 128) throw new Error(); new URL(`http://[${address}]`); } catch (e) { payload.issues.push({ code: "invalid_format", format: "cidrv6", input: payload.value, inst, continue: !def.abort }); } }; }); function isValidBase64(data) { if (data === "") return true; if (data.length % 4 !== 0) return false; try { atob(data); return true; } catch (e) { return false; } } var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = base64; $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst2) => { inst2._zod.bag.contentEncoding = "base64"; }); inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64", input: payload.value, inst, continue: !def.abort }); }; }); function isValidBase64URL(data) { if (!base64url.test(data)) return false; const base643 = data.replace(/[-_]/g, (c2) => c2 === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = base64url; $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst2) => { inst2._zod.bag.contentEncoding = "base64url"; }); inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64url", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { var _a; (_a = def.pattern) != null ? _a : def.pattern = e164; $ZodStringFormat.init(inst, def); }); function isValidJWT(token2, algorithm = null) { try { const tokensParts = token2.split("."); if (tokensParts.length !== 3) return false; const [header] = tokensParts; if (!header) return false; const parsedHeader = JSON.parse(atob(header)); if ("typ" in parsedHeader && (parsedHeader == null ? void 0 : parsedHeader.typ) !== "JWT") return false; if (!parsedHeader.alg) return false; if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; return true; } catch (e) { return false; } } var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (isValidJWT(payload.value, def.alg)) return; payload.issues.push({ code: "invalid_format", format: "jwt", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (def.fn(payload.value)) return; payload.issues.push({ code: "invalid_format", format: def.format, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { var _a; $ZodType.init(inst, def); inst._zod.pattern = (_a = inst._zod.bag.pattern) != null ? _a : number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { return payload; } const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; payload.issues.push(__spreadValues({ expected: "number", code: "invalid_type", input, inst }, received ? { received } : {})); return payload; }; }); var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); }); var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = boolean; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Boolean(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", input, inst }); return payload; }; }); var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = bigint; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = BigInt(payload.value); } catch (_) { } if (typeof payload.value === "bigint") return payload; payload.issues.push({ expected: "bigint", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { $ZodCheckBigIntFormat.init(inst, def); $ZodBigInt.init(inst, def); }); var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", input, inst }); return payload; }; }); var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.optin = "optional"; inst._zod.optout = "optional"; inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", input, inst }); return payload; }; }); var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", input, inst }); return payload; }; }); var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.issues.push({ expected: "never", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", input, inst }); return payload; }; }); var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (def.coerce) { try { payload.value = new Date(payload.value); } catch (_err) { } } const input = payload.value; const isDate = input instanceof Date; const isValidDate = isDate && !Number.isNaN(input.getTime()); if (isValidDate) return payload; payload.issues.push(__spreadProps(__spreadValues({ expected: "date", code: "invalid_type", input }, isDate ? { received: "Invalid Date" } : {}), { inst })); return payload; }; }); function handleArrayResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ expected: "array", code: "invalid_type", input, inst }); return payload; } payload.value = Array(input.length); const proms = []; for (let i = 0; i < input.length; i++) { const item = input[i]; const result = def.element._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); function handlePropertyResult(result, final, key2, input) { if (result.issues.length) { final.issues.push(...prefixIssues(key2, result.issues)); } if (result.value === void 0) { if (key2 in input) { final.value[key2] = void 0; } } else { final.value[key2] = result.value; } } function normalizeDef(def) { var _a, _b, _c, _d; const keys = Object.keys(def.shape); for (const k of keys) { if (!((_d = (_c = (_b = (_a = def.shape) == null ? void 0 : _a[k]) == null ? void 0 : _b._zod) == null ? void 0 : _c.traits) == null ? void 0 : _d.has("$ZodType"))) { throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return __spreadProps(__spreadValues({}, def), { keys, keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }); } function handleCatchall(proms, input, payload, ctx, def, inst) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t6 = _catchall.def.type; for (const key2 of Object.keys(input)) { if (keySet.has(key2)) continue; if (t6 === "never") { unrecognized.push(key2); continue; } const r = _catchall.run({ value: input[key2], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r2) => handlePropertyResult(r2, payload, key2, input))); } else { handlePropertyResult(r, payload, key2, input); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, input, inst }); } if (!proms.length) return payload; return Promise.all(proms).then(() => { return payload; }); } var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc = Object.getOwnPropertyDescriptor(def, "shape"); if (!(desc == null ? void 0 : desc.get)) { const sh = def.shape; Object.defineProperty(def, "shape", { get: () => { const newSh = __spreadValues({}, sh); Object.defineProperty(def, "shape", { value: newSh }); return newSh; } }); } const _normalized = cached(() => normalizeDef(def)); defineLazy(inst._zod, "propValues", () => { var _a; const shape = def.shape; const propValues = {}; for (const key2 in shape) { const field = shape[key2]._zod; if (field.values) { (_a = propValues[key2]) != null ? _a : propValues[key2] = /* @__PURE__ */ new Set(); for (const v of field.values) propValues[key2].add(v); } } return propValues; }); const isObject2 = isObject; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value != null ? value : value = _normalized.value; const input = payload.value; if (!isObject2(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } payload.value = {}; const proms = []; const shape = value.shape; for (const key2 of value.keys) { const el = shape[key2]; const r = el._zod.run({ value: input[key2], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r2) => handlePropertyResult(r2, payload, key2, input))); } else { handlePropertyResult(r, payload, key2, input); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); const generateFastpass = (shape) => { const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; const parseStr = (key2) => { const k = esc(key2); return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; }; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; for (const key2 of normalized.keys) { ids[key2] = `key_${counter++}`; } doc.write(`const newResult = {};`); for (const key2 of normalized.keys) { const id = ids[key2]; const k = esc(key2); doc.write(`const ${id} = ${parseStr(key2)};`); doc.write(` if (${id}.issues.length) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } if (${id}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { newResult[${k}] = ${id}.value; } `); } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); const fn = doc.compile(); return (payload, ctx) => fn(shape, payload, ctx); }; let fastpass; const isObject2 = isObject; const jit = !globalConfig.jitless; const allowsEval2 = allowsEval; const fastEnabled = jit && allowsEval2.value; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value != null ? value : value = _normalized.value; const input = payload.value; if (!isObject2(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } if (jit && fastEnabled && (ctx == null ? void 0 : ctx.async) === false && ctx.jitless !== true) { if (!fastpass) fastpass = generateFastpass(def.shape); payload = fastpass(payload, ctx); if (!catchall) return payload; return handleCatchall([], input, payload, ctx, value, inst); } return superParse(payload, ctx); }; }); function handleUnionResults(results, final, inst, ctx) { for (const result of results) { if (result.issues.length === 0) { final.value = result.value; return final; } } const nonaborted = results.filter((r) => !aborted(r)); if (nonaborted.length === 1) { final.value = nonaborted[0].value; return nonaborted[0]; } final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); return final; } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); defineLazy(inst._zod, "values", () => { if (def.options.every((o) => o._zod.values)) { return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); defineLazy(inst._zod, "pattern", () => { if (def.options.every((o) => o._zod.pattern)) { const patterns = def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; }); const single = def.options.length === 1; const first = def.options[0]._zod.run; inst._zod.parse = (payload, ctx) => { if (single) { return first(payload, ctx); } let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { if (result.issues.length === 0) return result; results.push(result); } } if (!async) return handleUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleUnionResults(results2, payload, inst, ctx); }); }; }); var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { $ZodUnion.init(inst, def); const _super = inst._zod.parse; defineLazy(inst._zod, "propValues", () => { const propValues = {}; for (const option of def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); for (const [k, v] of Object.entries(pv)) { if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); for (const val of v) { propValues[k].add(val); } } } return propValues; }); const disc = cached(() => { var _a; const opts = def.options; const map2 = /* @__PURE__ */ new Map(); for (const o of opts) { const values = (_a = o._zod.propValues) == null ? void 0 : _a[def.discriminator]; if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); for (const v of values) { if (map2.has(v)) { throw new Error(`Duplicate discriminator value "${String(v)}"`); } map2.set(v, o); } } return map2; }); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isObject(input)) { payload.issues.push({ code: "invalid_type", expected: "object", input, inst }); return payload; } const opt = disc.value.get(input == null ? void 0 : input[def.discriminator]); if (opt) { return opt._zod.run(payload, ctx); } if (def.unionFallback) { return _super(payload, ctx); } payload.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", discriminator: def.discriminator, input, path: [def.discriminator], inst }); return payload; }; }); var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; const left = def.left._zod.run({ value: input, issues: [] }, ctx); const right = def.right._zod.run({ value: input, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { return handleIntersectionResults(payload, left2, right2); }); } return handleIntersectionResults(payload, left, right); }; }); function mergeValues(a, b) { if (a === b) { return { valid: true, data: a }; } if (a instanceof Date && b instanceof Date && +a === +b) { return { valid: true, data: a }; } if (isPlainObject(a) && isPlainObject(b)) { const bKeys = Object.keys(b); const sharedKeys = Object.keys(a).filter((key2) => bKeys.indexOf(key2) !== -1); const newObj = __spreadValues(__spreadValues({}, a), b); for (const key2 of sharedKeys) { const sharedValue = mergeValues(a[key2], b[key2]); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [key2, ...sharedValue.mergeErrorPath] }; } newObj[key2] = sharedValue.data; } return { valid: true, data: newObj }; } if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return { valid: false, mergeErrorPath: [] }; } 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, mergeErrorPath: [index, ...sharedValue.mergeErrorPath] }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } return { valid: false, mergeErrorPath: [] }; } function handleIntersectionResults(result, left, right) { if (left.issues.length) { result.issues.push(...left.issues); } if (right.issues.length) { result.issues.push(...right.issues); } if (aborted(result)) return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; return result; } var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ input, inst, expected: "tuple", code: "invalid_type" }); return payload; } payload.value = []; const proms = []; if (!def.rest) { const tooBig = input.length > items.length; const tooSmall = input.length < optStart - 1; if (tooBig || tooSmall) { payload.issues.push(__spreadProps(__spreadValues({}, tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }), { input, inst, origin: "array" })); return payload; } } let i = -1; for (const item of items) { i++; if (i >= input.length) { if (i >= optStart) continue; } const result = item._zod.run({ value: input[i], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); } else { handleTupleResult(result, payload, i); } } if (def.rest) { const rest = input.slice(items.length); for (const el of rest) { i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); } else { handleTupleResult(result, payload, i); } } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleTupleResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isPlainObject(input)) { payload.issues.push({ expected: "record", code: "invalid_type", input, inst }); return payload; } const proms = []; if (def.keyType._zod.values) { const values = def.keyType._zod.values; payload.value = {}; for (const key2 of values) { if (typeof key2 === "string" || typeof key2 === "number" || typeof key2 === "symbol") { const result = def.valueType._zod.run({ value: input[key2], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key2, result2.issues)); } payload.value[key2] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key2, result.issues)); } payload.value[key2] = result.value; } } } let unrecognized; for (const key2 in input) { if (!values.has(key2)) { unrecognized = unrecognized != null ? unrecognized : []; unrecognized.push(key2); } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", input, inst, keys: unrecognized }); } } else { payload.value = {}; for (const key2 of Reflect.ownKeys(input)) { if (key2 === "__proto__") continue; const keyResult = def.keyType._zod.run({ value: key2, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } if (keyResult.issues.length) { payload.issues.push({ code: "invalid_key", origin: "record", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key2, path: [key2], inst }); payload.value[keyResult.value] = keyResult.value; continue; } const result = def.valueType._zod.run({ value: input[key2], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key2, result2.issues)); } payload.value[keyResult.value] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key2, result.issues)); } payload.value[keyResult.value] = result.value; } } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", input, inst }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Map(); for (const [key2, value] of input) { const keyResult = def.keyType._zod.run({ value: key2, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { handleMapResult(keyResult2, valueResult2, payload, key2, input, inst, ctx); })); } else { handleMapResult(keyResult, valueResult, payload, key2, input, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleMapResult(keyResult, valueResult, final, key2, input, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key2)) { final.issues.push(...prefixIssues(key2, keyResult.issues)); } else { final.issues.push({ code: "invalid_key", origin: "map", input, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } if (valueResult.issues.length) { if (propertyKeyTypes.has(typeof key2)) { final.issues.push(...prefixIssues(key2, valueResult.issues)); } else { final.issues.push({ origin: "map", code: "invalid_element", input, inst, key: key2, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } final.value.set(keyResult.value, valueResult.value); } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Set)) { payload.issues.push({ input, inst, expected: "set", code: "invalid_type" }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Set(); for (const item of input) { const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); } else handleSetResult(result, payload); } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleSetResult(result, final) { if (result.issues.length) { final.issues.push(...result.issues); } final.value.add(result.value); } var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { $ZodType.init(inst, def); const values = getEnumValues(def.entries); const valuesSet = new Set(values); inst._zod.values = valuesSet; inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (valuesSet.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values, input, inst }); return payload; }; }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); if (def.values.length === 0) { throw new Error("Cannot create literal schema with no valid values"); } inst._zod.values = new Set(def.values); inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (inst._zod.values.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, input, inst }); return payload; }; }); var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", input, inst }); return payload; }; }); var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out2 = def.transform(payload.value, payload); if (ctx.async) { const output = _out2 instanceof Promise ? _out2 : Promise.resolve(_out2); return output.then((output2) => { payload.value = output2; return payload; }); } if (_out2 instanceof Promise) { throw new $ZodAsyncError(); } payload.value = _out2; return payload; }; }); function handleOptionalResult(result, input) { if (result.issues.length && input === void 0) { return { issues: [], value: void 0 }; } return result; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; inst._zod.optout = "optional"; defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; }); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { if (def.innerType._zod.optin === "optional") { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, payload.value)); return handleOptionalResult(result, payload.value); } if (payload.value === void 0) { return payload; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) return payload; return def.innerType._zod.run(payload, ctx); }; }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { payload.value = def.defaultValue; return payload; } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleDefaultResult(result2, def)); } return handleDefaultResult(result, def); }; }); function handleDefaultResult(payload, def) { if (payload.value === void 0) { payload.value = def.defaultValue; } return payload; } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { payload.value = def.defaultValue; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => { const v = def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleNonOptionalResult(result2, inst)); } return handleNonOptionalResult(result, inst); }; }); function handleNonOptionalResult(payload, inst) { if (!payload.issues.length && payload.value === void 0) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: payload.value, inst }); } return payload; } var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError("ZodSuccess"); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.issues.length === 0; return payload; }); } payload.value = result.issues.length === 0; return payload; }; }); var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.value; if (result2.issues.length) { payload.value = def.catchValue(__spreadProps(__spreadValues({}, payload), { error: { issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value })); payload.issues = []; } return payload; }); } payload.value = result.value; if (result.issues.length) { payload.value = def.catchValue(__spreadProps(__spreadValues({}, payload), { error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value })); payload.issues = []; } return payload; }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { payload.issues.push({ input: payload.value, inst, expected: "nan", code: "invalid_type" }); return payload; } return payload; }; }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); if (right instanceof Promise) { return right.then((right2) => handlePipeResult(right2, def.in, ctx)); } return handlePipeResult(right, def.in, ctx); } const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handlePipeResult(left2, def.out, ctx)); } return handlePipeResult(left, def.out, ctx); }; }); function handlePipeResult(left, next, ctx) { if (left.issues.length) { left.aborted = true; return left; } return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handleCodecAResult(left2, def, ctx)); } return handleCodecAResult(left, def, ctx); } else { const right = def.out._zod.run(payload, ctx); if (right instanceof Promise) { return right.then((right2) => handleCodecAResult(right2, def, ctx)); } return handleCodecAResult(right, def, ctx); } }; }); function handleCodecAResult(result, def, ctx) { if (result.issues.length) { result.aborted = true; return result; } const direction = ctx.direction || "forward"; if (direction === "forward") { const transformed = def.transform(result.value, result); if (transformed instanceof Promise) { return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); } return handleCodecTxResult(result, transformed, def.out, ctx); } else { const transformed = def.reverseTransform(result.value, result); if (transformed instanceof Promise) { return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); } return handleCodecTxResult(result, transformed, def.in, ctx); } } function handleCodecTxResult(left, value, nextSchema, ctx) { if (left.issues.length) { left.aborted = true; return left; } return nextSchema._zod.run({ value, issues: left.issues }, ctx); } var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then(handleReadonlyResult); } return handleReadonlyResult(result); }; }); function handleReadonlyResult(payload) { payload.value = Object.freeze(payload.value); return payload; } var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { if (!part._zod.pattern) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } const source2 = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; if (!source2) throw new Error(`Invalid template literal part: ${part._zod.traits}`); const start = source2.startsWith("^") ? 1 : 0; const end = source2.endsWith("$") ? source2.length - 1 : source2.length; regexParts.push(source2.slice(start, end)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { throw new Error(`Invalid template literal part: ${part}`); } } inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); inst._zod.parse = (payload, _ctx) => { var _a; if (typeof payload.value !== "string") { payload.issues.push({ input: payload.value, inst, expected: "template_literal", code: "invalid_type" }); return payload; } inst._zod.pattern.lastIndex = 0; if (!inst._zod.pattern.test(payload.value)) { payload.issues.push({ input: payload.value, inst, code: "invalid_format", format: (_a = def.format) != null ? _a : "template_literal", pattern: inst._zod.pattern.source }); return payload; } return payload; }; }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); inst._def = def; inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } return function(...args) { const parsedArgs = inst._def.input ? parse3(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse3(inst._def.output, result); } return result; }; }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } return function(...args) { return __async(this, null, function* () { const parsedArgs = inst._def.input ? yield parseAsync(inst._def.input, args) : args; const result = yield Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return yield parseAsync(inst._def.output, result); } return result; }); }; }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { payload.issues.push({ code: "invalid_type", expected: "function", input: payload.value, inst }); return payload; } const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; if (hasPromiseOutput) { payload.value = inst.implementAsync(payload.value); } else { payload.value = inst.implement(payload.value); } return payload; }; inst.input = (...args) => { const F = inst.constructor; if (Array.isArray(args[0])) { return new F({ type: "function", input: new $ZodTuple({ type: "tuple", items: args[0], rest: args[1] }), output: inst._def.output }); } return new F({ type: "function", input: args[0], output: inst._def.output }); }; inst.output = (output) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, output }); }; return inst; }); var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); }; }); var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "innerType", () => def.getter()); defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); defineLazy(inst._zod, "optin", () => { var _a; return (_a = inst._zod.innerType._zod.optin) != null ? _a : void 0; }); defineLazy(inst._zod, "optout", () => { var _a; return (_a = inst._zod.innerType._zod.optout) != null ? _a : void 0; }); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); }; }); var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { $ZodCheck.init(inst, def); $ZodType.init(inst, def); inst._zod.parse = (payload, _) => { return payload; }; inst._zod.check = (payload) => { const input = payload.value; const r = def.fn(input); if (r instanceof Promise) { return r.then((r2) => handleRefineResult(r2, payload, input, inst)); } handleRefineResult(r, payload, input, inst); return; }; }); function handleRefineResult(result, payload, input, inst) { var _a; if (!result) { const _iss = { code: "custom", input, inst, // incorporates params.error into issue reporting path: [...(_a = inst._zod.def.path) != null ? _a : []], // incorporates params.error into issue reporting continue: !inst._zod.def.abort // params: inst._zod.def.params, }; if (inst._zod.def.params) _iss.params = inst._zod.def.params; payload.issues.push(issue(_iss)); } } // ../../node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, ca: () => ca_default, cs: () => cs_default, da: () => da_default, de: () => de_default, en: () => en_default, eo: () => eo_default, es: () => es_default, fa: () => fa_default, fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, he: () => he_default, hu: () => hu_default, id: () => id_default, is: () => is_default, it: () => it_default, ja: () => ja_default, ka: () => ka_default, kh: () => kh_default, km: () => km_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, nl: () => nl_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, ru: () => ru_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, th: () => th_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, ur: () => ur_default, vi: () => vi_default, yo: () => yo_default, zhCN: () => zh_CN_default, zhTW: () => zh_TW_default }); // ../../node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0645\u062F\u062E\u0644", email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", url: "\u0631\u0627\u0628\u0637", emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${(_a = issue2.origin) != null ? _a : "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u0639\u0646\u0635\u0631"}`; return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${(_c = issue2.origin) != null ? _c : "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; if (_issue.format === "ends_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; if (_issue.format === "regex") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; } case "not_multiple_of": return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; case "unrecognized_keys": return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; case "invalid_key": return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; case "invalid_union": return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; case "invalid_element": return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; default: return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; } }; }; function ar_default() { return { localeError: error() }; } // ../../node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, set: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${issue2.expected}, daxil olan ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${(_a = issue2.origin) != null ? _a : "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "element"}`; return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${(_c = issue2.origin) != null ? _c : "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; if (_issue.format === "ends_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; if (_issue.format === "includes") return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; if (_issue.format === "regex") return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; return `Yanl\u0131\u015F ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; case "unrecognized_keys": return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; case "invalid_union": return "Yanl\u0131\u015F d\u0259y\u0259r"; case "invalid_element": return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; default: return `Yanl\u0131\u015F d\u0259y\u0259r`; } }; }; function az_default() { return { localeError: error2() }; } // ../../node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error3 = () => { const Sizable = { string: { unit: { one: "\u0441\u0456\u043C\u0432\u0430\u043B", few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u044B", many: "\u0431\u0430\u0439\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u043B\u0456\u043A"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0456\u045E"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0443\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0430\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0447\u0430\u0441", duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; return (issue2) => { var _a, _b, _c; switch (issue2.code) { case "invalid_type": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${(_a = issue2.origin) != null ? _a : "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${(_b = issue2.origin) != null ? _b : "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${(_c = Nouns[_issue.format]) != null ? _c : issue2.format}`; } case "not_multiple_of": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; case "invalid_union": return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; case "invalid_element": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; default: return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; } }; }; function be_default() { return { localeError: error3() }; } // ../../node_modules/zod/v4/locales/ca.js var error4 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, set: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "entrada", email: "adre\xE7a electr\xF2nica", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i hora ISO", date: "data ISO", time: "hora ISO", duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Tipus inv\xE0lid: s'esperava ${issue2.expected}, s'ha rebut ${parsedType7(issue2.input)}`; // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; case "too_big": { const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; const sizing = getSizing(issue2.origin); if (sizing) return `Massa gran: s'esperava que ${(_a = issue2.origin) != null ? _a : "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elements"}`; return `Massa gran: s'esperava que ${(_c = issue2.origin) != null ? _c : "el valor"} fos ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; const sizing = getSizing(issue2.origin); if (sizing) { return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; if (_issue.format === "includes") return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; if (_issue.format === "regex") return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; return `Format inv\xE0lid per a ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; case "unrecognized_keys": return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Clau inv\xE0lida a ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE0lida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general case "invalid_element": return `Element inv\xE0lid a ${issue2.origin}`; default: return `Entrada inv\xE0lida`; } }; }; function ca_default() { return { localeError: error4() }; } // ../../node_modules/zod/v4/locales/cs.js var error5 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, set: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u010D\xEDslo"; } case "string": { return "\u0159et\u011Bzec"; } case "boolean": { return "boolean"; } case "bigint": { return "bigint"; } case "function": { return "funkce"; } case "symbol": { return "symbol"; } case "undefined": { return "undefined"; } case "object": { if (Array.isArray(data)) { return "pole"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "regul\xE1rn\xED v\xFDraz", email: "e-mailov\xE1 adresa", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "datum a \u010Das ve form\xE1tu ISO", date: "datum ve form\xE1tu ISO", time: "\u010Das ve form\xE1tu ISO", duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", jwt: "JWT", template_literal: "vstup" }; return (issue2) => { var _a, _b, _c, _d, _e, _f, _g; switch (issue2.code) { case "invalid_type": return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${issue2.expected}, obdr\u017Eeno ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${(_a = issue2.origin) != null ? _a : "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${(_c = issue2.origin) != null ? _c : "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${(_d = issue2.origin) != null ? _d : "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${(_e = sizing.unit) != null ? _e : "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${(_f = issue2.origin) != null ? _f : "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; if (_issue.format === "includes") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; if (_issue.format === "regex") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; return `Neplatn\xFD form\xE1t ${(_g = Nouns[_issue.format]) != null ? _g : issue2.format}`; } case "not_multiple_of": return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; case "unrecognized_keys": return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; case "invalid_union": return "Neplatn\xFD vstup"; case "invalid_element": return `Neplatn\xE1 hodnota v ${issue2.origin}`; default: return `Neplatn\xFD vstup`; } }; }; function cs_default() { return { localeError: error5() }; } // ../../node_modules/zod/v4/locales/da.js var error6 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, set: { unit: "elementer", verb: "indeholdt" } }; const TypeNames = { string: "streng", number: "tal", boolean: "boolean", array: "liste", object: "objekt", set: "s\xE6t", file: "fil" }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } function getTypeName(type) { var _a; return (_a = TypeNames[type]) != null ? _a : type; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "tal"; } case "object": { if (Array.isArray(data)) { return "liste"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } return "objekt"; } } return t6; }; const Nouns = { regex: "input", email: "e-mailadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkesl\xE6t", date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; return (issue2) => { var _a, _b; switch (issue2.code) { case "invalid_type": return `Ugyldigt input: forventede ${getTypeName(issue2.expected)}, fik ${getTypeName(parsedType7(issue2.input))}`; case "invalid_value": if (issue2.values.length === 1) return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const origin = getTypeName(issue2.origin); if (sizing) return `For stor: forventede ${origin != null ? origin : "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${(_a = sizing.unit) != null ? _a : "elementer"}`; return `For stor: forventede ${origin != null ? origin : "value"} havde ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const origin = getTypeName(issue2.origin); if (sizing) { return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ugyldig streng: skal starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: skal ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: skal indeholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${(_b = Nouns[_issue.format]) != null ? _b : issue2.format}`; } case "not_multiple_of": return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8gle i ${issue2.origin}`; case "invalid_union": return "Ugyldigt input: matcher ingen af de tilladte typer"; case "invalid_element": return `Ugyldig v\xE6rdi i ${issue2.origin}`; default: return `Ugyldigt input`; } }; }; function da_default() { return { localeError: error6() }; } // ../../node_modules/zod/v4/locales/de.js var error7 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, set: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "Zahl"; } case "object": { if (Array.isArray(data)) { return "Array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "Eingabe", email: "E-Mail-Adresse", url: "URL", emoji: "Emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-Datum und -Uhrzeit", date: "ISO-Datum", time: "ISO-Uhrzeit", duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", jwt: "JWT", template_literal: "Eingabe" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Ung\xFCltige Eingabe: erwartet ${issue2.expected}, erhalten ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Zu gro\xDF: erwartet, dass ${(_a = issue2.origin) != null ? _a : "Wert"} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "Elemente"} hat`; return `Zu gro\xDF: erwartet, dass ${(_c = issue2.origin) != null ? _c : "Wert"} ${adj}${issue2.maximum.toString()} ist`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; } return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; if (_issue.format === "ends_with") return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; if (_issue.format === "includes") return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; if (_issue.format === "regex") return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; return `Ung\xFCltig: ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; case "invalid_union": return "Ung\xFCltige Eingabe"; case "invalid_element": return `Ung\xFCltiger Wert in ${issue2.origin}`; default: return `Ung\xFCltige Eingabe`; } }; }; function de_default() { return { localeError: error7() }; } // ../../node_modules/zod/v4/locales/en.js var parsedType = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; var error8 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, array: { unit: "items", verb: "to have" }, set: { unit: "items", verb: "to have" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const Nouns = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${(_a = issue2.origin) != null ? _a : "value"} to have ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elements"}`; return `Too big: expected ${(_c = issue2.origin) != null ? _c : "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Invalid string: must start with "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`; if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`; if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`; return `Invalid ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Invalid number: must be a multiple of ${issue2.divisor}`; case "unrecognized_keys": return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Invalid key in ${issue2.origin}`; case "invalid_union": return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; default: return `Invalid input`; } }; }; function en_default() { return { localeError: error8() }; } // ../../node_modules/zod/v4/locales/eo.js var parsedType2 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "nombro"; } case "object": { if (Array.isArray(data)) { return "tabelo"; } if (data === null) { return "senvalora"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; var error9 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, set: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const Nouns = { regex: "enigo", email: "retadreso", url: "URL", emoji: "emo\u011Dio", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datotempo", date: "ISO-dato", time: "ISO-tempo", duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", jwt: "JWT", template_literal: "enigo" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Nevalida enigo: atendi\u011Dis ${issue2.expected}, ricevi\u011Dis ${parsedType2(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Tro granda: atendi\u011Dis ke ${(_a = issue2.origin) != null ? _a : "valoro"} havu ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elementojn"}`; return `Tro granda: atendi\u011Dis ke ${(_c = issue2.origin) != null ? _c : "valoro"} havu ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; if (_issue.format === "includes") return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; if (_issue.format === "regex") return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; return `Nevalida ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; case "unrecognized_keys": return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Nevalida \u015Dlosilo en ${issue2.origin}`; case "invalid_union": return "Nevalida enigo"; case "invalid_element": return `Nevalida valoro en ${issue2.origin}`; default: return `Nevalida enigo`; } }; }; function eo_default() { return { localeError: error9() }; } // ../../node_modules/zod/v4/locales/es.js var error10 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, array: { unit: "elementos", verb: "tener" }, set: { unit: "elementos", verb: "tener" } }; const TypeNames = { string: "texto", number: "n\xFAmero", boolean: "booleano", array: "arreglo", object: "objeto", set: "conjunto", file: "archivo", date: "fecha", bigint: "n\xFAmero grande", symbol: "s\xEDmbolo", undefined: "indefinido", null: "nulo", function: "funci\xF3n", map: "mapa", record: "registro", tuple: "tupla", enum: "enumeraci\xF3n", union: "uni\xF3n", literal: "literal", promise: "promesa", void: "vac\xEDo", never: "nunca", unknown: "desconocido", any: "cualquiera" }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } function getTypeName(type) { var _a; return (_a = TypeNames[type]) != null ? _a : type; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype) { return data.constructor.name; } return "object"; } } return t6; }; const Nouns = { regex: "entrada", email: "direcci\xF3n de correo electr\xF3nico", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "fecha y hora ISO", date: "fecha ISO", time: "hora ISO", duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue2) => { var _a, _b; switch (issue2.code) { case "invalid_type": return `Entrada inv\xE1lida: se esperaba ${getTypeName(issue2.expected)}, recibido ${getTypeName(parsedType7(issue2.input))}`; // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const origin = getTypeName(issue2.origin); if (sizing) return `Demasiado grande: se esperaba que ${origin != null ? origin : "valor"} tuviera ${adj}${issue2.maximum.toString()} ${(_a = sizing.unit) != null ? _a : "elementos"}`; return `Demasiado grande: se esperaba que ${origin != null ? origin : "valor"} fuera ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const origin = getTypeName(issue2.origin); if (sizing) { return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; if (_issue.format === "includes") return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; return `Inv\xE1lido ${(_b = Nouns[_issue.format]) != null ? _b : issue2.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; case "unrecognized_keys": return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Llave inv\xE1lida en ${getTypeName(issue2.origin)}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido en ${getTypeName(issue2.origin)}`; default: return `Entrada inv\xE1lida`; } }; }; function es_default() { return { localeError: error10() }; } // ../../node_modules/zod/v4/locales/fa.js var error11 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F"; } case "object": { if (Array.isArray(data)) { return "\u0622\u0631\u0627\u06CC\u0647"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0648\u0631\u0648\u062F\u06CC", email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", url: "URL", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${parsedType7(issue2.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; case "invalid_value": if (issue2.values.length === 1) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; } return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${(_a = issue2.origin) != null ? _a : "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${(_c = issue2.origin) != null ? _c : "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; } if (_issue.format === "ends_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; } if (_issue.format === "includes") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; } if (_issue.format === "regex") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; } return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } case "not_multiple_of": return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; case "unrecognized_keys": return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; case "invalid_union": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; case "invalid_element": return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; default: return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } }; }; function fa_default() { return { localeError: error11() }; } // ../../node_modules/zod/v4/locales/fi.js var error12 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "s\xE4\xE4nn\xF6llinen lauseke", email: "s\xE4hk\xF6postiosoite", url: "URL-osoite", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-aikaleima", date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", time: "ISO-aika", duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", jwt: "JWT", template_literal: "templaattimerkkijono" }; return (issue2) => { var _a; switch (issue2.code) { case "invalid_type": return `Virheellinen tyyppi: odotettiin ${issue2.expected}, oli ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); } return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); } return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; if (_issue.format === "includes") return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; if (_issue.format === "regex") { return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; } return `Virheellinen ${(_a = Nouns[_issue.format]) != null ? _a : issue2.format}`; } case "not_multiple_of": return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return "Virheellinen avain tietueessa"; case "invalid_union": return "Virheellinen unioni"; case "invalid_element": return "Virheellinen arvo joukossa"; default: return `Virheellinen sy\xF6te`; } }; }; function fi_default() { return { localeError: error12() }; } // ../../node_modules/zod/v4/locales/fr.js var error13 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "nombre"; } case "object": { if (Array.isArray(data)) { return "tableau"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "entr\xE9e", email: "adresse e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date et heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Entr\xE9e invalide : ${issue2.expected} attendu, ${parsedType7(issue2.input)} re\xE7u`; case "invalid_value": if (issue2.values.length === 1) return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop grand : ${(_a = issue2.origin) != null ? _a : "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\xE9l\xE9ment(s)"}`; return `Trop grand : ${(_c = issue2.origin) != null ? _c : "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue2.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue2.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_default() { return { localeError: error13() }; } // ../../node_modules/zod/v4/locales/fr-CA.js var error14 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "entr\xE9e", email: "adresse courriel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date-heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; return (issue2) => { var _a, _b, _c; switch (issue2.code) { case "invalid_type": return `Entr\xE9e invalide : attendu ${issue2.expected}, re\xE7u ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "\u2264" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop grand : attendu que ${(_a = issue2.origin) != null ? _a : "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; return `Trop grand : attendu que ${(_b = issue2.origin) != null ? _b : "la valeur"} soit ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "\u2265" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; return `${(_c = Nouns[_issue.format]) != null ? _c : issue2.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue2.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue2.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_CA_default() { return { localeError: error14() }; } // ../../node_modules/zod/v4/locales/he.js var error15 = () => { const Sizable = { string: { unit: "\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u05E7\u05DC\u05D8", email: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", url: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", emoji: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", date: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", time: "\u05D6\u05DE\u05DF ISO", duration: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", ipv4: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", ipv6: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", cidrv4: "\u05D8\u05D5\u05D5\u05D7 IPv4", cidrv6: "\u05D8\u05D5\u05D5\u05D7 IPv6", base64: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", base64url: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", json_string: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", e164: "\u05DE\u05E1\u05E4\u05E8 E.164", jwt: "JWT", template_literal: "\u05E7\u05DC\u05D8" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${parsedType7(issue2.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${stringifyPrimitive(issue2.values[0])}`; return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${(_a = issue2.origin) != null ? _a : "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elements"}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${(_c = issue2.origin) != null ? _c : "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; if (_issue.format === "regex") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } case "not_multiple_of": return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; case "unrecognized_keys": return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`; case "invalid_union": return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; case "invalid_element": return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`; default: return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } }; }; function he_default() { return { localeError: error15() }; } // ../../node_modules/zod/v4/locales/hu.js var error16 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, set: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "sz\xE1m"; } case "object": { if (Array.isArray(data)) { return "t\xF6mb"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "bemenet", email: "email c\xEDm", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO id\u0151b\xE9lyeg", date: "ISO d\xE1tum", time: "ISO id\u0151", duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", jwt: "JWT", template_literal: "bemenet" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${issue2.expected}, a kapott \xE9rt\xE9k ${parsedType7(issue2.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `T\xFAl nagy: ${(_a = issue2.origin) != null ? _a : "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elem"}`; return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${(_c = issue2.origin) != null ? _c : "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; if (_issue.format === "ends_with") return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; if (_issue.format === "includes") return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; if (_issue.format === "regex") return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; return `\xC9rv\xE9nytelen ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; case "unrecognized_keys": return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; case "invalid_union": return "\xC9rv\xE9nytelen bemenet"; case "invalid_element": return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; default: return `\xC9rv\xE9nytelen bemenet`; } }; }; function hu_default() { return { localeError: error16() }; } // ../../node_modules/zod/v4/locales/id.js var error17 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, set: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "input", email: "alamat email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tanggal dan waktu format ISO", date: "tanggal format ISO", time: "jam format ISO", duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", jwt: "JWT", template_literal: "input" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Input tidak valid: diharapkan ${issue2.expected}, diterima ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Terlalu besar: diharapkan ${(_a = issue2.origin) != null ? _a : "value"} memiliki ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elemen"}`; return `Terlalu besar: diharapkan ${(_c = issue2.origin) != null ? _c : "value"} menjadi ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak valid: harus menyertakan "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak valid: harus sesuai pola ${_issue.pattern}`; return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} tidak valid`; } case "not_multiple_of": return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kunci tidak valid di ${issue2.origin}`; case "invalid_union": return "Input tidak valid"; case "invalid_element": return `Nilai tidak valid di ${issue2.origin}`; default: return `Input tidak valid`; } }; }; function id_default() { return { localeError: error17() }; } // ../../node_modules/zod/v4/locales/is.js var parsedType3 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "n\xFAmer"; } case "object": { if (Array.isArray(data)) { return "fylki"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; var error18 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, set: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const Nouns = { regex: "gildi", email: "netfang", url: "vefsl\xF3\xF0", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dagsetning og t\xEDmi", date: "ISO dagsetning", time: "ISO t\xEDmi", duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", jwt: "JWT", template_literal: "gildi" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Rangt gildi: \xDE\xFA sl\xF3st inn ${parsedType3(issue2.input)} \xFEar sem \xE1 a\xF0 vera ${issue2.expected}`; case "invalid_value": if (issue2.values.length === 1) return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${(_a = issue2.origin) != null ? _a : "gildi"} hafi ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "hluti"}`; return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${(_c = issue2.origin) != null ? _c : "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; if (_issue.format === "regex") return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; return `Rangt ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; case "unrecognized_keys": return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Rangur lykill \xED ${issue2.origin}`; case "invalid_union": return "Rangt gildi"; case "invalid_element": return `Rangt gildi \xED ${issue2.origin}`; default: return `Rangt gildi`; } }; }; function is_default() { return { localeError: error18() }; } // ../../node_modules/zod/v4/locales/it.js var error19 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, set: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "numero"; } case "object": { if (Array.isArray(data)) { return "vettore"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "input", email: "indirizzo email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e ora ISO", date: "data ISO", time: "ora ISO", duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", jwt: "JWT", template_literal: "input" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Input non valido: atteso ${issue2.expected}, ricevuto ${parsedType7(issue2.input)}`; // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Troppo grande: ${(_a = issue2.origin) != null ? _a : "valore"} deve avere ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elementi"}`; return `Troppo grande: ${(_c = issue2.origin) != null ? _c : "valore"} deve essere ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Stringa non valida: deve terminare con "${_issue.suffix}"`; if (_issue.format === "includes") return `Stringa non valida: deve includere "${_issue.includes}"`; if (_issue.format === "regex") return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; return `Invalid ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; case "unrecognized_keys": return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Chiave non valida in ${issue2.origin}`; case "invalid_union": return "Input non valido"; case "invalid_element": return `Valore non valido in ${issue2.origin}`; default: return `Input non valido`; } }; }; function it_default() { return { localeError: error19() }; } // ../../node_modules/zod/v4/locales/ja.js var error20 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u6570\u5024"; } case "object": { if (Array.isArray(data)) { return "\u914D\u5217"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u5165\u529B\u5024", email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", url: "URL", emoji: "\u7D75\u6587\u5B57", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u6642", date: "ISO\u65E5\u4ED8", time: "ISO\u6642\u523B", duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u7121\u52B9\u306A\u5165\u529B: ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${parsedType7(issue2.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; case "invalid_value": if (issue2.values.length === 1) return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "too_big": { const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; const sizing = getSizing(issue2.origin); if (sizing) return `\u5927\u304D\u3059\u304E\u308B\u5024: ${(_a = issue2.origin) != null ? _a : "\u5024"}\u306F${issue2.maximum.toString()}${(_b = sizing.unit) != null ? _b : "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5927\u304D\u3059\u304E\u308B\u5024: ${(_c = issue2.origin) != null ? _c : "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "too_small": { const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; const sizing = getSizing(issue2.origin); if (sizing) return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "ends_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "includes") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "regex") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u7121\u52B9\u306A${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "unrecognized_keys": return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; case "invalid_key": return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; case "invalid_union": return "\u7121\u52B9\u306A\u5165\u529B"; case "invalid_element": return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; default: return `\u7121\u52B9\u306A\u5165\u529B`; } }; }; function ja_default() { return { localeError: error20() }; } // ../../node_modules/zod/v4/locales/ka.js var parsedType4 = (data) => { var _a; const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8"; } case "object": { if (Array.isArray(data)) { return "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } const typeMap = { string: "\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", undefined: "undefined", bigint: "bigint", symbol: "symbol", function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0" }; return (_a = typeMap[t6]) != null ? _a : t6; }; var error21 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const Nouns = { regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", url: "URL", emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", time: "\u10D3\u10E0\u10DD", duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", json_string: "JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; return (issue2) => { var _a, _b, _c; switch (issue2.code) { case "invalid_type": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${(_a = issue2.origin) != null ? _a : "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${(_b = issue2.origin) != null ? _b : "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; } if (_issue.format === "ends_with") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; if (_issue.format === "includes") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; if (_issue.format === "regex") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${(_c = Nouns[_issue.format]) != null ? _c : issue2.format}`; } case "not_multiple_of": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; case "unrecognized_keys": return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; case "invalid_union": return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; case "invalid_element": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; default: return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; } }; }; function ka_default() { return { localeError: error21() }; } // ../../node_modules/zod/v4/locales/km.js var error22 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)" : "\u179B\u17C1\u1781"; } case "object": { if (Array.isArray(data)) { return "\u17A2\u17B6\u179A\u17C1 (Array)"; } if (data === null) { return "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", url: "URL", emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", time: "\u1798\u17C9\u17C4\u1784 ISO", duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${(_a = issue2.origin) != null ? _a : "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u1792\u17B6\u178F\u17BB"}`; return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${(_c = issue2.origin) != null ? _c : "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; if (_issue.format === "regex") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; case "unrecognized_keys": return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; case "invalid_union": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; case "invalid_element": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; default: return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; } }; }; function km_default() { return { localeError: error22() }; } // ../../node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } // ../../node_modules/zod/v4/locales/ko.js var error23 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, set: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\uC785\uB825", email: "\uC774\uBA54\uC77C \uC8FC\uC18C", url: "URL", emoji: "\uC774\uBAA8\uC9C0", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", date: "ISO \uB0A0\uC9DC", time: "ISO \uC2DC\uAC04", duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", jwt: "JWT", template_literal: "\uC785\uB825" }; return (issue2) => { var _a, _b, _c, _d, _e, _f, _g; switch (issue2.code) { case "invalid_type": return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${parsedType7(issue2.input)}\uC785\uB2C8\uB2E4`; case "invalid_value": if (issue2.values.length === 1) return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "too_big": { const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue2.origin); const unit = (_a = sizing == null ? void 0 : sizing.unit) != null ? _a : "\uC694\uC18C"; if (sizing) return `${(_b = issue2.origin) != null ? _b : "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; return `${(_c = issue2.origin) != null ? _c : "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; } case "too_small": { const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue2.origin); const unit = (_d = sizing == null ? void 0 : sizing.unit) != null ? _d : "\uC694\uC18C"; if (sizing) { return `${(_e = issue2.origin) != null ? _e : "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; } return `${(_f = issue2.origin) != null ? _f : "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; } if (_issue.format === "ends_with") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "includes") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "regex") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C ${(_g = Nouns[_issue.format]) != null ? _g : issue2.format}`; } case "not_multiple_of": return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "unrecognized_keys": return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; case "invalid_union": return `\uC798\uBABB\uB41C \uC785\uB825`; case "invalid_element": return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; default: return `\uC798\uBABB\uB41C \uC785\uB825`; } }; }; function ko_default() { return { localeError: error23() }; } // ../../node_modules/zod/v4/locales/lt.js var parsedType5 = (data) => { const t6 = typeof data; return parsedTypeFromType(t6, data); }; var parsedTypeFromType = (t6, data = void 0) => { switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "skai\u010Dius"; } case "bigint": { return "sveikasis skai\u010Dius"; } case "string": { return "eilut\u0117"; } case "boolean": { return "login\u0117 reik\u0161m\u0117"; } case "undefined": case "void": { return "neapibr\u0117\u017Eta reik\u0161m\u0117"; } case "function": { return "funkcija"; } case "symbol": { return "simbolis"; } case "object": { if (data === void 0) return "ne\u017Einomas objektas"; if (data === null) return "nulin\u0117 reik\u0161m\u0117"; if (Array.isArray(data)) return "masyvas"; if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } return "objektas"; } //Zod types below case "null": { return "nulin\u0117 reik\u0161m\u0117"; } } return t6; }; var capitalizeFirstCharacter = (text) => { return text.charAt(0).toUpperCase() + text.slice(1); }; function getUnitTypeFromNumber(number4) { const abs = Math.abs(number4); const last = abs % 10; const last2 = abs % 100; if (last2 >= 11 && last2 <= 19 || last === 0) return "many"; if (last === 1) return "one"; return "few"; } var error24 = () => { const Sizable = { string: { unit: { one: "simbolis", few: "simboliai", many: "simboli\u0173" }, verb: { smaller: { inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" }, bigger: { inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" } } }, file: { unit: { one: "baitas", few: "baitai", many: "bait\u0173" }, verb: { smaller: { inclusive: "turi b\u016Bti ne didesnis kaip", notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" }, bigger: { inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", notInclusive: "turi b\u016Bti didesnis kaip" } } }, array: { unit: { one: "element\u0105", few: "elementus", many: "element\u0173" }, verb: { smaller: { inclusive: "turi tur\u0117ti ne daugiau kaip", notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" }, bigger: { inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", notInclusive: "turi tur\u0117ti daugiau kaip" } } }, set: { unit: { one: "element\u0105", few: "elementus", many: "element\u0173" }, verb: { smaller: { inclusive: "turi tur\u0117ti ne daugiau kaip", notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" }, bigger: { inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", notInclusive: "turi tur\u0117ti daugiau kaip" } } } }; function getSizing(origin, unitType, inclusive, targetShouldBe) { var _a; const result = (_a = Sizable[origin]) != null ? _a : null; if (result === null) return result; return { unit: result.unit[unitType], verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] }; } const Nouns = { regex: "\u012Fvestis", email: "el. pa\u0161to adresas", url: "URL", emoji: "jaustukas", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO data ir laikas", date: "ISO data", time: "ISO laikas", duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", jwt: "JWT", template_literal: "\u012Fvestis" }; return (issue2) => { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; switch (issue2.code) { case "invalid_type": return `Gautas tipas ${parsedType5(issue2.input)}, o tik\u0117tasi - ${parsedTypeFromType(issue2.expected)}`; case "invalid_value": if (issue2.values.length === 1) return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; case "too_big": { const origin = parsedTypeFromType(issue2.origin); const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), (_a = issue2.inclusive) != null ? _a : false, "smaller"); if (sizing == null ? void 0 : sizing.verb) return `${capitalizeFirstCharacter((_b = origin != null ? origin : issue2.origin) != null ? _b : "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${(_c = sizing.unit) != null ? _c : "element\u0173"}`; const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; return `${capitalizeFirstCharacter((_d = origin != null ? origin : issue2.origin) != null ? _d : "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing == null ? void 0 : sizing.unit}`; } case "too_small": { const origin = parsedTypeFromType(issue2.origin); const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), (_e = issue2.inclusive) != null ? _e : false, "bigger"); if (sizing == null ? void 0 : sizing.verb) return `${capitalizeFirstCharacter((_f = origin != null ? origin : issue2.origin) != null ? _f : "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${(_g = sizing.unit) != null ? _g : "element\u0173"}`; const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; return `${capitalizeFirstCharacter((_h = origin != null ? origin : issue2.origin) != null ? _h : "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing == null ? void 0 : sizing.unit}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; if (_issue.format === "includes") return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; if (_issue.format === "regex") return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; return `Neteisingas ${(_i = Nouns[_issue.format]) != null ? _i : issue2.format}`; } case "not_multiple_of": return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; case "unrecognized_keys": return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return "Rastas klaidingas raktas"; case "invalid_union": return "Klaidinga \u012Fvestis"; case "invalid_element": { const origin = parsedTypeFromType(issue2.origin); return `${capitalizeFirstCharacter((_j = origin != null ? origin : issue2.origin) != null ? _j : "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; } default: return "Klaidinga \u012Fvestis"; } }; }; function lt_default() { return { localeError: error24() }; } // ../../node_modules/zod/v4/locales/mk.js var error25 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0431\u0440\u043E\u0458"; } case "object": { if (Array.isArray(data)) { return "\u043D\u0438\u0437\u0430"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0432\u043D\u0435\u0441", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", url: "URL", emoji: "\u0435\u043C\u043E\u045F\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0443\u043C", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${parsedType7(issue2.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${(_a = issue2.origin) != null ? _a : "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${(_c = issue2.origin) != null ? _c : "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; return `Invalid ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; case "invalid_union": return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; case "invalid_element": return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; default: return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; } }; }; function mk_default() { return { localeError: error25() }; } // ../../node_modules/zod/v4/locales/ms.js var error26 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, set: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "nombor"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "input", email: "alamat e-mel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tarikh masa ISO", date: "tarikh ISO", time: "masa ISO", duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", jwt: "JWT", template_literal: "input" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Input tidak sah: dijangka ${issue2.expected}, diterima ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Terlalu besar: dijangka ${(_a = issue2.origin) != null ? _a : "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elemen"}`; return `Terlalu besar: dijangka ${(_c = issue2.origin) != null ? _c : "nilai"} adalah ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak sah: mesti mengandungi "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} tidak sah`; } case "not_multiple_of": return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kunci tidak sah dalam ${issue2.origin}`; case "invalid_union": return "Input tidak sah"; case "invalid_element": return `Nilai tidak sah dalam ${issue2.origin}`; default: return `Input tidak sah`; } }; }; function ms_default() { return { localeError: error26() }; } // ../../node_modules/zod/v4/locales/nl.js var error27 = () => { const Sizable = { string: { unit: "tekens" }, file: { unit: "bytes" }, array: { unit: "elementen" }, set: { unit: "elementen" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "getal"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "invoer", email: "emailadres", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum en tijd", date: "ISO datum", time: "ISO tijd", duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", jwt: "JWT", template_literal: "invoer" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Ongeldige invoer: verwacht ${issue2.expected}, ontving ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Te lang: verwacht dat ${(_a = issue2.origin) != null ? _a : "waarde"} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elementen"} bevat`; return `Te lang: verwacht dat ${(_c = issue2.origin) != null ? _c : "waarde"} ${adj}${issue2.maximum.toString()} is`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} bevat`; } return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; } if (_issue.format === "ends_with") return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; if (_issue.format === "includes") return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; if (_issue.format === "regex") return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; return `Ongeldig: ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; case "unrecognized_keys": return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ongeldige key in ${issue2.origin}`; case "invalid_union": return "Ongeldige invoer"; case "invalid_element": return `Ongeldige waarde in ${issue2.origin}`; default: return `Ongeldige invoer`; } }; }; function nl_default() { return { localeError: error27() }; } // ../../node_modules/zod/v4/locales/no.js var error28 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, set: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "tall"; } case "object": { if (Array.isArray(data)) { return "liste"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "input", email: "e-postadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkeslett", date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Ugyldig input: forventet ${issue2.expected}, fikk ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `For stor(t): forventet ${(_a = issue2.origin) != null ? _a : "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elementer"}`; return `For stor(t): forventet ${(_c = issue2.origin) != null ? _c : "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8kkel i ${issue2.origin}`; case "invalid_union": return "Ugyldig input"; case "invalid_element": return `Ugyldig verdi i ${issue2.origin}`; default: return `Ugyldig input`; } }; }; function no_default() { return { localeError: error28() }; } // ../../node_modules/zod/v4/locales/ota.js var error29 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "numara"; } case "object": { if (Array.isArray(data)) { return "saf"; } if (data === null) { return "gayb"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "giren", email: "epostag\xE2h", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO heng\xE2m\u0131", date: "ISO tarihi", time: "ISO zaman\u0131", duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "giren" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `F\xE2sit giren: umulan ${issue2.expected}, al\u0131nan ${parsedType7(issue2.input)}`; // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Fazla b\xFCy\xFCk: ${(_a = issue2.origin) != null ? _a : "value"}, ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elements"} sahip olmal\u0131yd\u0131.`; return `Fazla b\xFCy\xFCk: ${(_c = issue2.origin) != null ? _c : "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; } return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; if (_issue.format === "ends_with") return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; if (_issue.format === "includes") return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; if (_issue.format === "regex") return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; return `F\xE2sit ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; case "invalid_union": return "Giren tan\u0131namad\u0131."; case "invalid_element": return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; default: return `K\u0131ymet tan\u0131namad\u0131.`; } }; }; function ota_default() { return { localeError: error29() }; } // ../../node_modules/zod/v4/locales/ps.js var error30 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F"; } case "object": { if (Array.isArray(data)) { return "\u0627\u0631\u06D0"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0648\u0631\u0648\u062F\u064A", email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", date: "\u0646\u06D0\u067C\u0647", time: "\u0648\u062E\u062A", duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${parsedType7(issue2.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; case "invalid_value": if (issue2.values.length === 1) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; } return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${(_a = issue2.origin) != null ? _a : "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${(_c = issue2.origin) != null ? _c : "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; } if (_issue.format === "ends_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; } if (_issue.format === "includes") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; } if (_issue.format === "regex") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; } return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; } case "not_multiple_of": return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; case "unrecognized_keys": return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; case "invalid_union": return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; case "invalid_element": return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; default: return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; } }; }; function ps_default() { return { localeError: error30() }; } // ../../node_modules/zod/v4/locales/pl.js var error31 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, set: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "liczba"; } case "object": { if (Array.isArray(data)) { return "tablica"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "wyra\u017Cenie", email: "adres email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i godzina w formacie ISO", date: "data w formacie ISO", time: "godzina w formacie ISO", duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", jwt: "JWT", template_literal: "wej\u015Bcie" }; return (issue2) => { var _a, _b, _c, _d, _e, _f, _g; switch (issue2.code) { case "invalid_type": return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${issue2.expected}, otrzymano ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${(_a = issue2.origin) != null ? _a : "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "element\xF3w"}`; } return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${(_c = issue2.origin) != null ? _c : "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${(_d = issue2.origin) != null ? _d : "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${(_e = sizing.unit) != null ? _e : "element\xF3w"}`; } return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${(_f = issue2.origin) != null ? _f : "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; if (_issue.format === "includes") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; if (_issue.format === "regex") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; return `Nieprawid\u0142ow(y/a/e) ${(_g = Nouns[_issue.format]) != null ? _g : issue2.format}`; } case "not_multiple_of": return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; case "unrecognized_keys": return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Nieprawid\u0142owy klucz w ${issue2.origin}`; case "invalid_union": return "Nieprawid\u0142owe dane wej\u015Bciowe"; case "invalid_element": return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; default: return `Nieprawid\u0142owe dane wej\u015Bciowe`; } }; }; function pl_default() { return { localeError: error31() }; } // ../../node_modules/zod/v4/locales/pt.js var error32 = () => { const Sizable = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, array: { unit: "itens", verb: "ter" }, set: { unit: "itens", verb: "ter" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "n\xFAmero"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "nulo"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "padr\xE3o", email: "endere\xE7o de e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e hora ISO", date: "data ISO", time: "hora ISO", duration: "dura\xE7\xE3o ISO", ipv4: "endere\xE7o IPv4", ipv6: "endere\xE7o IPv6", cidrv4: "faixa de IPv4", cidrv6: "faixa de IPv6", base64: "texto codificado em base64", base64url: "URL codificada em base64", json_string: "texto JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Tipo inv\xE1lido: esperado ${issue2.expected}, recebido ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Muito grande: esperado que ${(_a = issue2.origin) != null ? _a : "valor"} tivesse ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elementos"}`; return `Muito grande: esperado que ${(_c = issue2.origin) != null ? _c : "valor"} fosse ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; case "unrecognized_keys": return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Chave inv\xE1lida em ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido em ${issue2.origin}`; default: return `Campo inv\xE1lido`; } }; }; function pt_default() { return { localeError: error32() }; } // ../../node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error33 = () => { const Sizable = { string: { unit: { one: "\u0441\u0438\u043C\u0432\u043E\u043B", few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u0430", many: "\u0431\u0430\u0439\u0442" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0441\u0438\u0432"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0432\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u044F", duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; return (issue2) => { var _a, _b, _c; switch (issue2.code) { case "invalid_type": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${(_a = issue2.origin) != null ? _a : "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${(_b = issue2.origin) != null ? _b : "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${(_c = Nouns[_issue.format]) != null ? _c : issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; case "invalid_element": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; default: return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; } }; }; function ru_default() { return { localeError: error33() }; } // ../../node_modules/zod/v4/locales/sl.js var error34 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, set: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0161tevilo"; } case "object": { if (Array.isArray(data)) { return "tabela"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "vnos", email: "e-po\u0161tni naslov", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum in \u010Das", date: "ISO datum", time: "ISO \u010Das", duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", jwt: "JWT", template_literal: "vnos" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Neveljaven vnos: pri\u010Dakovano ${issue2.expected}, prejeto ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Preveliko: pri\u010Dakovano, da bo ${(_a = issue2.origin) != null ? _a : "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elementov"}`; return `Preveliko: pri\u010Dakovano, da bo ${(_c = issue2.origin) != null ? _c : "vrednost"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; if (_issue.format === "includes") return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; if (_issue.format === "regex") return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; return `Neveljaven ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; case "unrecognized_keys": return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neveljaven klju\u010D v ${issue2.origin}`; case "invalid_union": return "Neveljaven vnos"; case "invalid_element": return `Neveljavna vrednost v ${issue2.origin}`; default: return "Neveljaven vnos"; } }; }; function sl_default() { return { localeError: error34() }; } // ../../node_modules/zod/v4/locales/sv.js var error35 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, set: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "antal"; } case "object": { if (Array.isArray(data)) { return "lista"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "regulj\xE4rt uttryck", email: "e-postadress", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datum och tid", date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", ipv4: "IPv4-intervall", ipv6: "IPv6-intervall", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", jwt: "JWT", template_literal: "mall-literal" }; return (issue2) => { var _a, _b, _c, _d, _e, _f, _g, _h; switch (issue2.code) { case "invalid_type": return `Ogiltig inmatning: f\xF6rv\xE4ntat ${issue2.expected}, fick ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `F\xF6r stor(t): f\xF6rv\xE4ntade ${(_a = issue2.origin) != null ? _a : "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "element"}`; } return `F\xF6r stor(t): f\xF6rv\xE4ntat ${(_c = issue2.origin) != null ? _c : "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `F\xF6r lite(t): f\xF6rv\xE4ntade ${(_d = issue2.origin) != null ? _d : "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `F\xF6r lite(t): f\xF6rv\xE4ntade ${(_e = issue2.origin) != null ? _e : "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; if (_issue.format === "regex") return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; return `Ogiltig(t) ${(_f = Nouns[_issue.format]) != null ? _f : issue2.format}`; } case "not_multiple_of": return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ogiltig nyckel i ${(_g = issue2.origin) != null ? _g : "v\xE4rdet"}`; case "invalid_union": return "Ogiltig input"; case "invalid_element": return `Ogiltigt v\xE4rde i ${(_h = issue2.origin) != null ? _h : "v\xE4rdet"}`; default: return `Ogiltig input`; } }; }; function sv_default() { return { localeError: error35() }; } // ../../node_modules/zod/v4/locales/ta.js var error36 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1" : "\u0B8E\u0BA3\u0BCD"; } case "object": { if (Array.isArray(data)) { return "\u0B85\u0BA3\u0BBF"; } if (data === null) { return "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", jwt: "JWT", template_literal: "input" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${(_a = issue2.origin) != null ? _a : "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${(_c = issue2.origin) != null ? _c : "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "ends_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "includes") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "regex") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; case "unrecognized_keys": return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; case "invalid_union": return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; case "invalid_element": return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; default: return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; } }; }; function ta_default() { return { localeError: error36() }; } // ../../node_modules/zod/v4/locales/th.js var error37 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)" : "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02"; } case "object": { if (Array.isArray(data)) { return "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)"; } if (data === null) { return "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", url: "URL", emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${(_a = issue2.origin) != null ? _a : "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${(_c = issue2.origin) != null ? _c : "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; if (_issue.format === "regex") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; case "unrecognized_keys": return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; case "invalid_union": return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; case "invalid_element": return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; default: return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; } }; }; function th_default() { return { localeError: error37() }; } // ../../node_modules/zod/v4/locales/tr.js var parsedType6 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; var error38 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const Nouns = { regex: "girdi", email: "e-posta adresi", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO tarih ve saat", date: "ISO tarih", time: "ISO saat", duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `Ge\xE7ersiz de\u011Fer: beklenen ${issue2.expected}, al\u0131nan ${parsedType6(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ok b\xFCy\xFCk: beklenen ${(_a = issue2.origin) != null ? _a : "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\xF6\u011Fe"}`; return `\xC7ok b\xFCy\xFCk: beklenen ${(_c = issue2.origin) != null ? _c : "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; if (_issue.format === "ends_with") return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; if (_issue.format === "includes") return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; if (_issue.format === "regex") return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; return `Ge\xE7ersiz ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; case "invalid_union": return "Ge\xE7ersiz de\u011Fer"; case "invalid_element": return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; default: return `Ge\xE7ersiz de\u011Fer`; } }; }; function tr_default() { return { localeError: error38() }; } // ../../node_modules/zod/v4/locales/uk.js var error39 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0438\u0432"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", date: "\u0434\u0430\u0442\u0430 ISO", time: "\u0447\u0430\u0441 ISO", duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${parsedType7(issue2.input)}`; // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${(_a = issue2.origin) != null ? _a : "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${(_c = issue2.origin) != null ? _c : "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; case "invalid_element": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; default: return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; } }; }; function uk_default() { return { localeError: error39() }; } // ../../node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } // ../../node_modules/zod/v4/locales/ur.js var error40 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0646\u0645\u0628\u0631"; } case "object": { if (Array.isArray(data)) { return "\u0622\u0631\u06D2"; } if (data === null) { return "\u0646\u0644"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0627\u0646 \u067E\u0679", email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${parsedType7(issue2.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; case "invalid_value": if (issue2.values.length === 1) return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${(_a = issue2.origin) != null ? _a : "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${(_c = issue2.origin) != null ? _c : "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; } return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; } if (_issue.format === "ends_with") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "includes") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "regex") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; return `\u063A\u0644\u0637 ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; case "unrecognized_keys": return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; case "invalid_key": return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; case "invalid_union": return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; case "invalid_element": return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; default: return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; } }; }; function ur_default() { return { localeError: error40() }; } // ../../node_modules/zod/v4/locales/vi.js var error41 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "s\u1ED1"; } case "object": { if (Array.isArray(data)) { return "m\u1EA3ng"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u0111\u1EA7u v\xE0o", email: "\u0111\u1ECBa ch\u1EC9 email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ng\xE0y gi\u1EDD ISO", date: "ng\xE0y ISO", time: "gi\u1EDD ISO", duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${(_a = issue2.origin) != null ? _a : "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "ph\u1EA7n t\u1EED"}`; return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${(_c = issue2.origin) != null ? _c : "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; if (_issue.format === "includes") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; if (_issue.format === "regex") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; return `${(_d = Nouns[_issue.format]) != null ? _d : issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; } case "not_multiple_of": return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; case "unrecognized_keys": return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; case "invalid_union": return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; case "invalid_element": return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; default: return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; } }; }; function vi_default() { return { localeError: error41() }; } // ../../node_modules/zod/v4/locales/zh-CN.js var error42 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, set: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "\u975E\u6570\u5B57(NaN)" : "\u6570\u5B57"; } case "object": { if (Array.isArray(data)) { return "\u6570\u7EC4"; } if (data === null) { return "\u7A7A\u503C(null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u8F93\u5165", email: "\u7535\u5B50\u90AE\u4EF6", url: "URL", emoji: "\u8868\u60C5\u7B26\u53F7", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u671F\u65F6\u95F4", date: "ISO\u65E5\u671F", time: "ISO\u65F6\u95F4", duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", jwt: "JWT", template_literal: "\u8F93\u5165" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${(_a = issue2.origin) != null ? _a : "\u503C"} ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u4E2A\u5143\u7D20"}`; return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${(_c = issue2.origin) != null ? _c : "\u503C"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; if (_issue.format === "ends_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; if (_issue.format === "includes") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; return `\u65E0\u6548${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; case "unrecognized_keys": return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; case "invalid_union": return "\u65E0\u6548\u8F93\u5165"; case "invalid_element": return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; default: return `\u65E0\u6548\u8F93\u5165`; } }; }; function zh_CN_default() { return { localeError: error42() }; } // ../../node_modules/zod/v4/locales/zh-TW.js var error43 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u8F38\u5165", email: "\u90F5\u4EF6\u5730\u5740", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u65E5\u671F\u6642\u9593", date: "ISO \u65E5\u671F", time: "ISO \u6642\u9593", duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", jwt: "JWT", template_literal: "\u8F38\u5165" }; return (issue2) => { var _a, _b, _c, _d; switch (issue2.code) { case "invalid_type": return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${(_a = issue2.origin) != null ? _a : "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "\u500B\u5143\u7D20"}`; return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${(_c = issue2.origin) != null ? _c : "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; } if (_issue.format === "ends_with") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; if (_issue.format === "includes") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; return `\u7121\u6548\u7684 ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; } case "not_multiple_of": return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; case "unrecognized_keys": return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; case "invalid_key": return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; case "invalid_union": return "\u7121\u6548\u7684\u8F38\u5165\u503C"; case "invalid_element": return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; default: return `\u7121\u6548\u7684\u8F38\u5165\u503C`; } }; }; function zh_TW_default() { return { localeError: error43() }; } // ../../node_modules/zod/v4/locales/yo.js var error44 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, set: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { var _a; return (_a = Sizable[origin]) != null ? _a : null; } const parsedType7 = (data) => { const t6 = typeof data; switch (t6) { case "number": { return Number.isNaN(data) ? "NaN" : "n\u1ECD\u0301mb\xE0"; } case "object": { if (Array.isArray(data)) { return "akop\u1ECD"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t6; }; const Nouns = { regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\xE0k\xF3k\xF2 ISO", date: "\u1ECDj\u1ECD\u0301 ISO", time: "\xE0k\xF3k\xF2 ISO", duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; return (issue2) => { var _a, _b; switch (issue2.code) { case "invalid_type": return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${parsedType7(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${(_a = issue2.origin) != null ? _a : "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; if (_issue.format === "regex") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; return `A\u1E63\xEC\u1E63e: ${(_b = Nouns[_issue.format]) != null ? _b : issue2.format}`; } case "not_multiple_of": return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; case "unrecognized_keys": return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; case "invalid_union": return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; case "invalid_element": return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; default: return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; } }; }; function yo_default() { return { localeError: error44() }; } // ../../node_modules/zod/v4/core/registries.js var $output = Symbol("ZodOutput"); var $input = Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); } add(schema, ..._meta) { const meta = _meta[0]; this._map.set(schema, meta); if (meta && typeof meta === "object" && "id" in meta) { if (this._idmap.has(meta.id)) { throw new Error(`ID ${meta.id} already exists in the registry`); } this._idmap.set(meta.id, schema); } return this; } clear() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); return this; } remove(schema) { const meta = this._map.get(schema); if (meta && typeof meta === "object" && "id" in meta) { this._idmap.delete(meta.id); } this._map.delete(schema); return this; } get(schema) { var _a; const p = schema._zod.parent; if (p) { const pm = __spreadValues({}, (_a = this.get(p)) != null ? _a : {}); delete pm.id; const f = __spreadValues(__spreadValues({}, pm), this._map.get(schema)); return Object.keys(f).length ? f : void 0; } return this._map.get(schema); } has(schema) { return this._map.has(schema); } }; function registry() { return new $ZodRegistry(); } var globalRegistry = /* @__PURE__ */ registry(); // ../../node_modules/zod/v4/core/api.js function _string(Class2, params) { return new Class2(__spreadValues({ type: "string" }, normalizeParams(params))); } function _coercedString(Class2, params) { return new Class2(__spreadValues({ type: "string", coerce: true }, normalizeParams(params))); } function _email(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "email", check: "string_format", abort: false }, normalizeParams(params))); } function _guid(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "guid", check: "string_format", abort: false }, normalizeParams(params))); } function _uuid(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "uuid", check: "string_format", abort: false }, normalizeParams(params))); } function _uuidv4(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4" }, normalizeParams(params))); } function _uuidv6(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6" }, normalizeParams(params))); } function _uuidv7(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7" }, normalizeParams(params))); } function _url(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "url", check: "string_format", abort: false }, normalizeParams(params))); } function _emoji2(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "emoji", check: "string_format", abort: false }, normalizeParams(params))); } function _nanoid(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "nanoid", check: "string_format", abort: false }, normalizeParams(params))); } function _cuid(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "cuid", check: "string_format", abort: false }, normalizeParams(params))); } function _cuid2(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "cuid2", check: "string_format", abort: false }, normalizeParams(params))); } function _ulid(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "ulid", check: "string_format", abort: false }, normalizeParams(params))); } function _xid(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "xid", check: "string_format", abort: false }, normalizeParams(params))); } function _ksuid(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "ksuid", check: "string_format", abort: false }, normalizeParams(params))); } function _ipv4(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "ipv4", check: "string_format", abort: false }, normalizeParams(params))); } function _ipv6(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "ipv6", check: "string_format", abort: false }, normalizeParams(params))); } function _cidrv4(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "cidrv4", check: "string_format", abort: false }, normalizeParams(params))); } function _cidrv6(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "cidrv6", check: "string_format", abort: false }, normalizeParams(params))); } function _base64(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "base64", check: "string_format", abort: false }, normalizeParams(params))); } function _base64url(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "base64url", check: "string_format", abort: false }, normalizeParams(params))); } function _e164(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "e164", check: "string_format", abort: false }, normalizeParams(params))); } function _jwt(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "jwt", check: "string_format", abort: false }, normalizeParams(params))); } var TimePrecision = { Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6 }; function _isoDateTime(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null }, normalizeParams(params))); } function _isoDate(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "date", check: "string_format" }, normalizeParams(params))); } function _isoTime(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "time", check: "string_format", precision: null }, normalizeParams(params))); } function _isoDuration(Class2, params) { return new Class2(__spreadValues({ type: "string", format: "duration", check: "string_format" }, normalizeParams(params))); } function _number(Class2, params) { return new Class2(__spreadValues({ type: "number", checks: [] }, normalizeParams(params))); } function _coercedNumber(Class2, params) { return new Class2(__spreadValues({ type: "number", coerce: true, checks: [] }, normalizeParams(params))); } function _int(Class2, params) { return new Class2(__spreadValues({ type: "number", check: "number_format", abort: false, format: "safeint" }, normalizeParams(params))); } function _float32(Class2, params) { return new Class2(__spreadValues({ type: "number", check: "number_format", abort: false, format: "float32" }, normalizeParams(params))); } function _float64(Class2, params) { return new Class2(__spreadValues({ type: "number", check: "number_format", abort: false, format: "float64" }, normalizeParams(params))); } function _int32(Class2, params) { return new Class2(__spreadValues({ type: "number", check: "number_format", abort: false, format: "int32" }, normalizeParams(params))); } function _uint32(Class2, params) { return new Class2(__spreadValues({ type: "number", check: "number_format", abort: false, format: "uint32" }, normalizeParams(params))); } function _boolean(Class2, params) { return new Class2(__spreadValues({ type: "boolean" }, normalizeParams(params))); } function _coercedBoolean(Class2, params) { return new Class2(__spreadValues({ type: "boolean", coerce: true }, normalizeParams(params))); } function _bigint(Class2, params) { return new Class2(__spreadValues({ type: "bigint" }, normalizeParams(params))); } function _coercedBigint(Class2, params) { return new Class2(__spreadValues({ type: "bigint", coerce: true }, normalizeParams(params))); } function _int64(Class2, params) { return new Class2(__spreadValues({ type: "bigint", check: "bigint_format", abort: false, format: "int64" }, normalizeParams(params))); } function _uint64(Class2, params) { return new Class2(__spreadValues({ type: "bigint", check: "bigint_format", abort: false, format: "uint64" }, normalizeParams(params))); } function _symbol(Class2, params) { return new Class2(__spreadValues({ type: "symbol" }, normalizeParams(params))); } function _undefined2(Class2, params) { return new Class2(__spreadValues({ type: "undefined" }, normalizeParams(params))); } function _null2(Class2, params) { return new Class2(__spreadValues({ type: "null" }, normalizeParams(params))); } function _any(Class2) { return new Class2({ type: "any" }); } function _unknown(Class2) { return new Class2({ type: "unknown" }); } function _never(Class2, params) { return new Class2(__spreadValues({ type: "never" }, normalizeParams(params))); } function _void(Class2, params) { return new Class2(__spreadValues({ type: "void" }, normalizeParams(params))); } function _date(Class2, params) { return new Class2(__spreadValues({ type: "date" }, normalizeParams(params))); } function _coercedDate(Class2, params) { return new Class2(__spreadValues({ type: "date", coerce: true }, normalizeParams(params))); } function _nan(Class2, params) { return new Class2(__spreadValues({ type: "nan" }, normalizeParams(params))); } function _lt(value, params) { return new $ZodCheckLessThan(__spreadProps(__spreadValues({ check: "less_than" }, normalizeParams(params)), { value, inclusive: false })); } function _lte(value, params) { return new $ZodCheckLessThan(__spreadProps(__spreadValues({ check: "less_than" }, normalizeParams(params)), { value, inclusive: true })); } function _gt(value, params) { return new $ZodCheckGreaterThan(__spreadProps(__spreadValues({ check: "greater_than" }, normalizeParams(params)), { value, inclusive: false })); } function _gte(value, params) { return new $ZodCheckGreaterThan(__spreadProps(__spreadValues({ check: "greater_than" }, normalizeParams(params)), { value, inclusive: true })); } function _positive(params) { return _gt(0, params); } function _negative(params) { return _lt(0, params); } function _nonpositive(params) { return _lte(0, params); } function _nonnegative(params) { return _gte(0, params); } function _multipleOf(value, params) { return new $ZodCheckMultipleOf(__spreadProps(__spreadValues({ check: "multiple_of" }, normalizeParams(params)), { value })); } function _maxSize(maximum, params) { return new $ZodCheckMaxSize(__spreadProps(__spreadValues({ check: "max_size" }, normalizeParams(params)), { maximum })); } function _minSize(minimum, params) { return new $ZodCheckMinSize(__spreadProps(__spreadValues({ check: "min_size" }, normalizeParams(params)), { minimum })); } function _size(size, params) { return new $ZodCheckSizeEquals(__spreadProps(__spreadValues({ check: "size_equals" }, normalizeParams(params)), { size })); } function _maxLength(maximum, params) { const ch = new $ZodCheckMaxLength(__spreadProps(__spreadValues({ check: "max_length" }, normalizeParams(params)), { maximum })); return ch; } function _minLength(minimum, params) { return new $ZodCheckMinLength(__spreadProps(__spreadValues({ check: "min_length" }, normalizeParams(params)), { minimum })); } function _length(length, params) { return new $ZodCheckLengthEquals(__spreadProps(__spreadValues({ check: "length_equals" }, normalizeParams(params)), { length })); } function _regex(pattern, params) { return new $ZodCheckRegex(__spreadProps(__spreadValues({ check: "string_format", format: "regex" }, normalizeParams(params)), { pattern })); } function _lowercase(params) { return new $ZodCheckLowerCase(__spreadValues({ check: "string_format", format: "lowercase" }, normalizeParams(params))); } function _uppercase(params) { return new $ZodCheckUpperCase(__spreadValues({ check: "string_format", format: "uppercase" }, normalizeParams(params))); } function _includes(includes, params) { return new $ZodCheckIncludes(__spreadProps(__spreadValues({ check: "string_format", format: "includes" }, normalizeParams(params)), { includes })); } function _startsWith(prefix, params) { return new $ZodCheckStartsWith(__spreadProps(__spreadValues({ check: "string_format", format: "starts_with" }, normalizeParams(params)), { prefix })); } function _endsWith(suffix, params) { return new $ZodCheckEndsWith(__spreadProps(__spreadValues({ check: "string_format", format: "ends_with" }, normalizeParams(params)), { suffix })); } function _property(property, schema, params) { return new $ZodCheckProperty(__spreadValues({ check: "property", property, schema }, normalizeParams(params))); } function _mime(types, params) { return new $ZodCheckMimeType(__spreadValues({ check: "mime_type", mime: types }, normalizeParams(params))); } function _overwrite(tx) { return new $ZodCheckOverwrite({ check: "overwrite", tx }); } function _normalize(form) { return _overwrite((input) => input.normalize(form)); } function _trim() { return _overwrite((input) => input.trim()); } function _toLowerCase() { return _overwrite((input) => input.toLowerCase()); } function _toUpperCase() { return _overwrite((input) => input.toUpperCase()); } function _array(Class2, element, params) { return new Class2(__spreadValues({ type: "array", element }, normalizeParams(params))); } function _union(Class2, options, params) { return new Class2(__spreadValues({ type: "union", options }, normalizeParams(params))); } function _discriminatedUnion(Class2, discriminator, options, params) { return new Class2(__spreadValues({ type: "union", options, discriminator }, normalizeParams(params))); } function _intersection(Class2, left, right) { return new Class2({ type: "intersection", left, right }); } function _tuple(Class2, items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new Class2(__spreadValues({ type: "tuple", items, rest }, normalizeParams(params))); } function _record(Class2, keyType, valueType, params) { return new Class2(__spreadValues({ type: "record", keyType, valueType }, normalizeParams(params))); } function _map(Class2, keyType, valueType, params) { return new Class2(__spreadValues({ type: "map", keyType, valueType }, normalizeParams(params))); } function _set(Class2, valueType, params) { return new Class2(__spreadValues({ type: "set", valueType }, normalizeParams(params))); } function _enum(Class2, values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new Class2(__spreadValues({ type: "enum", entries }, normalizeParams(params))); } function _nativeEnum(Class2, entries, params) { return new Class2(__spreadValues({ type: "enum", entries }, normalizeParams(params))); } function _literal(Class2, value, params) { return new Class2(__spreadValues({ type: "literal", values: Array.isArray(value) ? value : [value] }, normalizeParams(params))); } function _file(Class2, params) { return new Class2(__spreadValues({ type: "file" }, normalizeParams(params))); } function _transform(Class2, fn) { return new Class2({ type: "transform", transform: fn }); } function _optional(Class2, innerType) { return new Class2({ type: "optional", innerType }); } function _nullable(Class2, innerType) { return new Class2({ type: "nullable", innerType }); } function _default(Class2, innerType, defaultValue) { return new Class2({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); } }); } function _nonoptional(Class2, innerType, params) { return new Class2(__spreadValues({ type: "nonoptional", innerType }, normalizeParams(params))); } function _success(Class2, innerType) { return new Class2({ type: "success", innerType }); } function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } function _pipe(Class2, in_, out) { return new Class2({ type: "pipe", in: in_, out }); } function _readonly(Class2, innerType) { return new Class2({ type: "readonly", innerType }); } function _templateLiteral(Class2, parts, params) { return new Class2(__spreadValues({ type: "template_literal", parts }, normalizeParams(params))); } function _lazy(Class2, getter) { return new Class2({ type: "lazy", getter }); } function _promise(Class2, innerType) { return new Class2({ type: "promise", innerType }); } function _custom(Class2, fn, _params) { var _a; const norm = normalizeParams(_params); (_a = norm.abort) != null ? _a : norm.abort = true; const schema = new Class2(__spreadValues({ type: "custom", check: "custom", fn }, norm)); return schema; } function _refine(Class2, fn, _params) { const schema = new Class2(__spreadValues({ type: "custom", check: "custom", fn }, normalizeParams(_params))); return schema; } function _superRefine(fn) { const ch = _check((payload) => { payload.addIssue = (issue2) => { var _a, _b, _c, _d; if (typeof issue2 === "string") { payload.issues.push(issue(issue2, payload.value, ch._zod.def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; (_a = _issue.code) != null ? _a : _issue.code = "custom"; (_b = _issue.input) != null ? _b : _issue.input = payload.value; (_c = _issue.inst) != null ? _c : _issue.inst = ch; (_d = _issue.continue) != null ? _d : _issue.continue = !ch._zod.def.abort; payload.issues.push(issue(_issue)); } }; return fn(payload.value, payload); }); return ch; } function _check(fn, params) { const ch = new $ZodCheck(__spreadValues({ check: "custom" }, normalizeParams(params))); ch._zod.check = fn; return ch; } function _stringbool(Classes, _params) { var _a, _b, _c, _d, _e; const params = normalizeParams(_params); let truthyArray = (_a = params.truthy) != null ? _a : ["true", "1", "yes", "on", "y", "enabled"]; let falsyArray = (_b = params.falsy) != null ? _b : ["false", "0", "no", "off", "n", "disabled"]; if (params.case !== "sensitive") { truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); } const truthySet = new Set(truthyArray); const falsySet = new Set(falsyArray); const _Codec = (_c = Classes.Codec) != null ? _c : $ZodCodec; const _Boolean = (_d = Classes.Boolean) != null ? _d : $ZodBoolean; const _String = (_e = Classes.String) != null ? _e : $ZodString; const stringSchema = new _String({ type: "string", error: params.error }); const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); const codec2 = new _Codec({ type: "pipe", in: stringSchema, out: booleanSchema, transform: (input, payload) => { let data = input; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { return true; } else if (falsySet.has(data)) { return false; } else { payload.issues.push({ code: "invalid_value", expected: "stringbool", values: [...truthySet, ...falsySet], input: payload.value, inst: codec2, continue: false }); return {}; } }, reverseTransform: (input, _payload) => { if (input === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; } }, error: params.error }); return codec2; } function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = __spreadValues(__spreadProps(__spreadValues({}, normalizeParams(_params)), { check: "string_format", type: "string", format, fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val) }), params); if (fnOrRegex instanceof RegExp) { def.pattern = fnOrRegex; } const inst = new Class2(def); return inst; } // ../../node_modules/zod/v4/core/to-json-schema.js var JSONSchemaGenerator = class { constructor(params) { var _a, _b, _c, _d, _e; this.counter = 0; this.metadataRegistry = (_a = params == null ? void 0 : params.metadata) != null ? _a : globalRegistry; this.target = (_b = params == null ? void 0 : params.target) != null ? _b : "draft-2020-12"; this.unrepresentable = (_c = params == null ? void 0 : params.unrepresentable) != null ? _c : "throw"; this.override = (_d = params == null ? void 0 : params.override) != null ? _d : () => { }; this.io = (_e = params == null ? void 0 : params.io) != null ? _e : "output"; this.seen = /* @__PURE__ */ new Map(); } process(schema, _params = { path: [], schemaPath: [] }) { var _a2, _b, _c, _d, _e; var _a; const def = schema._zod.def; const formatMap = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "" // do not set }; const seen = this.seen.get(schema); if (seen) { seen.count++; const isCycle = _params.schemaPath.includes(schema); if (isCycle) { seen.cycle = _params.path; } return seen.schema; } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; this.seen.set(schema, result); const overrideSchema = (_b = (_a2 = schema._zod).toJSONSchema) == null ? void 0 : _b.call(_a2); if (overrideSchema) { result.schema = overrideSchema; } else { const params = __spreadProps(__spreadValues({}, _params), { schemaPath: [..._params.schemaPath, schema], path: _params.path }); const parent = schema._zod.parent; if (parent) { result.ref = parent; this.process(parent, params); this.seen.get(parent).isParent = true; } else { const _json = result.schema; switch (def.type) { case "string": { const json2 = _json; json2.type = "string"; const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; if (typeof minimum === "number") json2.minLength = minimum; if (typeof maximum === "number") json2.maxLength = maximum; if (format) { json2.format = (_c = formatMap[format]) != null ? _c : format; if (json2.format === "") delete json2.format; } if (contentEncoding) json2.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { const regexes = [...patterns]; if (regexes.length === 1) json2.pattern = regexes[0].source; else if (regexes.length > 1) { result.schema.allOf = [ ...regexes.map((regex) => __spreadProps(__spreadValues({}, this.target === "draft-7" || this.target === "draft-4" || this.target === "openapi-3.0" ? { type: "string" } : {}), { pattern: regex.source })) ]; } } break; } case "number": { const json2 = _json; const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; if (typeof format === "string" && format.includes("int")) json2.type = "integer"; else json2.type = "number"; if (typeof exclusiveMinimum === "number") { if (this.target === "draft-4" || this.target === "openapi-3.0") { json2.minimum = exclusiveMinimum; json2.exclusiveMinimum = true; } else { json2.exclusiveMinimum = exclusiveMinimum; } } if (typeof minimum === "number") { json2.minimum = minimum; if (typeof exclusiveMinimum === "number" && this.target !== "draft-4") { if (exclusiveMinimum >= minimum) delete json2.minimum; else delete json2.exclusiveMinimum; } } if (typeof exclusiveMaximum === "number") { if (this.target === "draft-4" || this.target === "openapi-3.0") { json2.maximum = exclusiveMaximum; json2.exclusiveMaximum = true; } else { json2.exclusiveMaximum = exclusiveMaximum; } } if (typeof maximum === "number") { json2.maximum = maximum; if (typeof exclusiveMaximum === "number" && this.target !== "draft-4") { if (exclusiveMaximum <= maximum) delete json2.maximum; else delete json2.exclusiveMaximum; } } if (typeof multipleOf === "number") json2.multipleOf = multipleOf; break; } case "boolean": { const json2 = _json; json2.type = "boolean"; break; } case "bigint": { if (this.unrepresentable === "throw") { throw new Error("BigInt cannot be represented in JSON Schema"); } break; } case "symbol": { if (this.unrepresentable === "throw") { throw new Error("Symbols cannot be represented in JSON Schema"); } break; } case "null": { if (this.target === "openapi-3.0") { _json.type = "string"; _json.nullable = true; _json.enum = [null]; } else _json.type = "null"; break; } case "any": { break; } case "unknown": { break; } case "undefined": { if (this.unrepresentable === "throw") { throw new Error("Undefined cannot be represented in JSON Schema"); } break; } case "void": { if (this.unrepresentable === "throw") { throw new Error("Void cannot be represented in JSON Schema"); } break; } case "never": { _json.not = {}; break; } case "date": { if (this.unrepresentable === "throw") { throw new Error("Date cannot be represented in JSON Schema"); } break; } case "array": { const json2 = _json; const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json2.minItems = minimum; if (typeof maximum === "number") json2.maxItems = maximum; json2.type = "array"; json2.items = this.process(def.element, __spreadProps(__spreadValues({}, params), { path: [...params.path, "items"] })); break; } case "object": { const json2 = _json; json2.type = "object"; json2.properties = {}; const shape = def.shape; for (const key2 in shape) { json2.properties[key2] = this.process(shape[key2], __spreadProps(__spreadValues({}, params), { path: [...params.path, "properties", key2] })); } const allKeys = new Set(Object.keys(shape)); const requiredKeys = new Set([...allKeys].filter((key2) => { const v = def.shape[key2]._zod; if (this.io === "input") { return v.optin === void 0; } else { return v.optout === void 0; } })); if (requiredKeys.size > 0) { json2.required = Array.from(requiredKeys); } if (((_d = def.catchall) == null ? void 0 : _d._zod.def.type) === "never") { json2.additionalProperties = false; } else if (!def.catchall) { if (this.io === "output") json2.additionalProperties = false; } else if (def.catchall) { json2.additionalProperties = this.process(def.catchall, __spreadProps(__spreadValues({}, params), { path: [...params.path, "additionalProperties"] })); } break; } case "union": { const json2 = _json; const options = def.options.map((x, i) => this.process(x, __spreadProps(__spreadValues({}, params), { path: [...params.path, "anyOf", i] }))); json2.anyOf = options; break; } case "intersection": { const json2 = _json; const a = this.process(def.left, __spreadProps(__spreadValues({}, params), { path: [...params.path, "allOf", 0] })); const b = this.process(def.right, __spreadProps(__spreadValues({}, params), { path: [...params.path, "allOf", 1] })); const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; const allOf = [ ...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b] ]; json2.allOf = allOf; break; } case "tuple": { const json2 = _json; json2.type = "array"; const prefixPath = this.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = this.target === "draft-2020-12" ? "items" : this.target === "openapi-3.0" ? "items" : "additionalItems"; const prefixItems = def.items.map((x, i) => this.process(x, __spreadProps(__spreadValues({}, params), { path: [...params.path, prefixPath, i] }))); const rest = def.rest ? this.process(def.rest, __spreadProps(__spreadValues({}, params), { path: [...params.path, restPath, ...this.target === "openapi-3.0" ? [def.items.length] : []] })) : null; if (this.target === "draft-2020-12") { json2.prefixItems = prefixItems; if (rest) { json2.items = rest; } } else if (this.target === "openapi-3.0") { json2.items = { anyOf: prefixItems }; if (rest) { json2.items.anyOf.push(rest); } json2.minItems = prefixItems.length; if (!rest) { json2.maxItems = prefixItems.length; } } else { json2.items = prefixItems; if (rest) { json2.additionalItems = rest; } } const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json2.minItems = minimum; if (typeof maximum === "number") json2.maxItems = maximum; break; } case "record": { const json2 = _json; json2.type = "object"; if (this.target === "draft-7" || this.target === "draft-2020-12") { json2.propertyNames = this.process(def.keyType, __spreadProps(__spreadValues({}, params), { path: [...params.path, "propertyNames"] })); } json2.additionalProperties = this.process(def.valueType, __spreadProps(__spreadValues({}, params), { path: [...params.path, "additionalProperties"] })); break; } case "map": { if (this.unrepresentable === "throw") { throw new Error("Map cannot be represented in JSON Schema"); } break; } case "set": { if (this.unrepresentable === "throw") { throw new Error("Set cannot be represented in JSON Schema"); } break; } case "enum": { const json2 = _json; const values = getEnumValues(def.entries); if (values.every((v) => typeof v === "number")) json2.type = "number"; if (values.every((v) => typeof v === "string")) json2.type = "string"; json2.enum = values; break; } case "literal": { const json2 = _json; const vals = []; for (const val of def.values) { if (val === void 0) { if (this.unrepresentable === "throw") { throw new Error("Literal `undefined` cannot be represented in JSON Schema"); } else { } } else if (typeof val === "bigint") { if (this.unrepresentable === "throw") { throw new Error("BigInt literals cannot be represented in JSON Schema"); } else { vals.push(Number(val)); } } else { vals.push(val); } } if (vals.length === 0) { } else if (vals.length === 1) { const val = vals[0]; json2.type = val === null ? "null" : typeof val; if (this.target === "draft-4" || this.target === "openapi-3.0") { json2.enum = [val]; } else { json2.const = val; } } else { if (vals.every((v) => typeof v === "number")) json2.type = "number"; if (vals.every((v) => typeof v === "string")) json2.type = "string"; if (vals.every((v) => typeof v === "boolean")) json2.type = "string"; if (vals.every((v) => v === null)) json2.type = "null"; json2.enum = vals; } break; } case "file": { const json2 = _json; const file2 = { type: "string", format: "binary", contentEncoding: "binary" }; const { minimum, maximum, mime } = schema._zod.bag; if (minimum !== void 0) file2.minLength = minimum; if (maximum !== void 0) file2.maxLength = maximum; if (mime) { if (mime.length === 1) { file2.contentMediaType = mime[0]; Object.assign(json2, file2); } else { json2.anyOf = mime.map((m) => { const mFile = __spreadProps(__spreadValues({}, file2), { contentMediaType: m }); return mFile; }); } } else { Object.assign(json2, file2); } break; } case "transform": { if (this.unrepresentable === "throw") { throw new Error("Transforms cannot be represented in JSON Schema"); } break; } case "nullable": { const inner = this.process(def.innerType, params); if (this.target === "openapi-3.0") { result.ref = def.innerType; _json.nullable = true; } else { _json.anyOf = [inner, { type: "null" }]; } break; } case "nonoptional": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "success": { const json2 = _json; json2.type = "boolean"; break; } case "default": { this.process(def.innerType, params); result.ref = def.innerType; _json.default = JSON.parse(JSON.stringify(def.defaultValue)); break; } case "prefault": { this.process(def.innerType, params); result.ref = def.innerType; if (this.io === "input") _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); break; } case "catch": { this.process(def.innerType, params); result.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch (e) { throw new Error("Dynamic catch values are not supported in JSON Schema"); } _json.default = catchValue; break; } case "nan": { if (this.unrepresentable === "throw") { throw new Error("NaN cannot be represented in JSON Schema"); } break; } case "template_literal": { const json2 = _json; const pattern = schema._zod.pattern; if (!pattern) throw new Error("Pattern not found in template literal"); json2.type = "string"; json2.pattern = pattern.source; break; } case "pipe": { const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; this.process(innerType, params); result.ref = innerType; break; } case "readonly": { this.process(def.innerType, params); result.ref = def.innerType; _json.readOnly = true; break; } // passthrough types case "promise": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "optional": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "lazy": { const innerType = schema._zod.innerType; this.process(innerType, params); result.ref = innerType; break; } case "custom": { if (this.unrepresentable === "throw") { throw new Error("Custom types cannot be represented in JSON Schema"); } break; } case "function": { if (this.unrepresentable === "throw") { throw new Error("Function types cannot be represented in JSON Schema"); } break; } default: { def; } } } } const meta = this.metadataRegistry.get(schema); if (meta) Object.assign(result.schema, meta); if (this.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; } if (this.io === "input" && result.schema._prefault) (_e = (_a = result.schema).default) != null ? _e : _a.default = result.schema._prefault; delete result.schema._prefault; const _result = this.seen.get(schema); return _result.schema; } emit(schema, _params) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; const params = { cycles: (_a = _params == null ? void 0 : _params.cycles) != null ? _a : "ref", reused: (_b = _params == null ? void 0 : _params.reused) != null ? _b : "inline", // unrepresentable: _params?.unrepresentable ?? "throw", // uri: _params?.uri ?? ((id) => `${id}`), external: (_c = _params == null ? void 0 : _params.external) != null ? _c : void 0 }; const root2 = this.seen.get(schema); if (!root2) throw new Error("Unprocessed schema. This is a bug in Zod."); const makeURI = (entry) => { var _a2, _b2, _c2, _d2, _e2; const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; if (params.external) { const externalId = (_a2 = params.external.registry.get(entry[0])) == null ? void 0 : _a2.id; const uriGenerator = (_b2 = params.external.uri) != null ? _b2 : (id2) => id2; if (externalId) { return { ref: uriGenerator(externalId) }; } const id = (_d2 = (_c2 = entry[1].defId) != null ? _c2 : entry[1].schema.id) != null ? _d2 : `schema${this.counter++}`; entry[1].defId = id; return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } if (entry[1] === root2) { return { ref: "#" }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; const defId = (_e2 = entry[1].schema.id) != null ? _e2 : `__schema${this.counter++}`; return { defId, ref: defUriPrefix + defId }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { return; } const seen = entry[1]; const { ref, defId } = makeURI(entry); seen.def = __spreadValues({}, seen.schema); if (defId) seen.defId = defId; const schema2 = seen.schema; for (const key2 in schema2) { delete schema2[key2]; } schema2.$ref = ref; }; if (params.cycles === "throw") { for (const entry of this.seen.entries()) { const seen = entry[1]; if (seen.cycle) { throw new Error(`Cycle detected: #/${(_d = seen.cycle) == null ? void 0 : _d.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); } } } for (const entry of this.seen.entries()) { const seen = entry[1]; if (schema === entry[0]) { extractToDef(entry); continue; } if (params.external) { const ext = (_e = params.external.registry.get(entry[0])) == null ? void 0 : _e.id; if (schema !== entry[0] && ext) { extractToDef(entry); continue; } } const id = (_f = this.metadataRegistry.get(entry[0])) == null ? void 0 : _f.id; if (id) { extractToDef(entry); continue; } if (seen.cycle) { extractToDef(entry); continue; } if (seen.count > 1) { if (params.reused === "ref") { extractToDef(entry); continue; } } } const flattenRef = (zodSchema, params2) => { var _a2, _b2, _c2; const seen = this.seen.get(zodSchema); const schema2 = (_a2 = seen.def) != null ? _a2 : seen.schema; const _cached = __spreadValues({}, schema2); if (seen.ref === null) { return; } const ref = seen.ref; seen.ref = null; if (ref) { flattenRef(ref, params2); const refSchema = this.seen.get(ref).schema; if (refSchema.$ref && (params2.target === "draft-7" || params2.target === "draft-4" || params2.target === "openapi-3.0")) { schema2.allOf = (_b2 = schema2.allOf) != null ? _b2 : []; schema2.allOf.push(refSchema); } else { Object.assign(schema2, refSchema); Object.assign(schema2, _cached); } } if (!seen.isParent) this.override({ zodSchema, jsonSchema: schema2, path: (_c2 = seen.path) != null ? _c2 : [] }); }; for (const entry of [...this.seen.entries()].reverse()) { flattenRef(entry[0], { target: this.target }); } const result = {}; if (this.target === "draft-2020-12") { result.$schema = "https://json-schema.org/draft/2020-12/schema"; } else if (this.target === "draft-7") { result.$schema = "http://json-schema.org/draft-07/schema#"; } else if (this.target === "draft-4") { result.$schema = "http://json-schema.org/draft-04/schema#"; } else if (this.target === "openapi-3.0") { } else { console.warn(`Invalid target: ${this.target}`); } if ((_g = params.external) == null ? void 0 : _g.uri) { const id = (_h = params.external.registry.get(schema)) == null ? void 0 : _h.id; if (!id) throw new Error("Schema is missing an `id` property"); result.$id = params.external.uri(id); } Object.assign(result, root2.def); const defs = (_j = (_i = params.external) == null ? void 0 : _i.defs) != null ? _j : {}; for (const entry of this.seen.entries()) { const seen = entry[1]; if (seen.def && seen.defId) { defs[seen.defId] = seen.def; } } if (params.external) { } else { if (Object.keys(defs).length > 0) { if (this.target === "draft-2020-12") { result.$defs = defs; } else { result.definitions = defs; } } } try { return JSON.parse(JSON.stringify(result)); } catch (_err) { throw new Error("Error converting schema to JSON."); } } }; function toJSONSchema(input, _params) { if (input instanceof $ZodRegistry) { const gen2 = new JSONSchemaGenerator(_params); const defs = {}; for (const entry of input._idmap.entries()) { const [_, schema] = entry; gen2.process(schema); } const schemas = {}; const external = { registry: input, uri: _params == null ? void 0 : _params.uri, defs }; for (const entry of input._idmap.entries()) { const [key2, schema] = entry; schemas[key2] = gen2.emit(schema, __spreadProps(__spreadValues({}, _params), { external })); } if (Object.keys(defs).length > 0) { const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; schemas.__shared = { [defsSegment]: defs }; } return { schemas }; } const gen = new JSONSchemaGenerator(_params); gen.process(input); return gen.emit(input, _params); } function isTransforming(_schema, _ctx) { const ctx = _ctx != null ? _ctx : { seen: /* @__PURE__ */ new Set() }; if (ctx.seen.has(_schema)) return false; ctx.seen.add(_schema); const schema = _schema; const def = schema._zod.def; switch (def.type) { case "string": case "number": case "bigint": case "boolean": case "date": case "symbol": case "undefined": case "null": case "any": case "unknown": case "never": case "void": case "literal": case "enum": case "nan": case "file": case "template_literal": return false; case "array": { return isTransforming(def.element, ctx); } case "object": { for (const key2 in def.shape) { if (isTransforming(def.shape[key2], ctx)) return true; } return false; } case "union": { for (const option of def.options) { if (isTransforming(option, ctx)) return true; } return false; } case "intersection": { return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); } case "tuple": { for (const item of def.items) { if (isTransforming(item, ctx)) return true; } if (def.rest && isTransforming(def.rest, ctx)) return true; return false; } case "record": { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } case "map": { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } case "set": { return isTransforming(def.valueType, ctx); } // inner types case "promise": case "optional": case "nonoptional": case "nullable": case "readonly": return isTransforming(def.innerType, ctx); case "lazy": return isTransforming(def.getter(), ctx); case "default": { return isTransforming(def.innerType, ctx); } case "prefault": { return isTransforming(def.innerType, ctx); } case "custom": { return false; } case "transform": { return true; } case "pipe": { return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); } case "success": { return false; } case "catch": { return false; } case "function": { return false; } default: def; } throw new Error(`Unknown schema type: ${def.type}`); } // ../../node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; // ../../node_modules/zod/v4/classic/iso.js var iso_exports = {}; __export(iso_exports, { ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, date: () => date2, datetime: () => datetime2, duration: () => duration2, time: () => time2 }); var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { $ZodISODateTime.init(inst, def); ZodStringFormat.init(inst, def); }); function datetime2(params) { return _isoDateTime(ZodISODateTime, params); } var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { $ZodISODate.init(inst, def); ZodStringFormat.init(inst, def); }); function date2(params) { return _isoDate(ZodISODate, params); } var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { $ZodISOTime.init(inst, def); ZodStringFormat.init(inst, def); }); function time2(params) { return _isoTime(ZodISOTime, params); } var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { $ZodISODuration.init(inst, def); ZodStringFormat.init(inst, def); }); function duration2(params) { return _isoDuration(ZodISODuration, params); } // ../../node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; Object.defineProperties(inst, { format: { value: (mapper) => formatError(inst, mapper) // enumerable: false, }, flatten: { value: (mapper) => flattenError(inst, mapper) // enumerable: false, }, addIssue: { value: (issue2) => { inst.issues.push(issue2); inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); } // enumerable: false, }, addIssues: { value: (issues2) => { inst.issues.push(...issues2); inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); } // enumerable: false, }, isEmpty: { get() { return inst.issues.length === 0; } // enumerable: false, } }); }; var ZodError = $constructor("ZodError", initializer2); var ZodRealError = $constructor("ZodError", initializer2, { Parent: Error }); // ../../node_modules/zod/v4/classic/parse.js var parse4 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); var encode2 = /* @__PURE__ */ _encode(ZodRealError); var decode2 = /* @__PURE__ */ _decode(ZodRealError); var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); // ../../node_modules/zod/v4/classic/schemas.js var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { $ZodType.init(inst, def); inst.def = def; inst.type = def.type; Object.defineProperty(inst, "_def", { value: def }); inst.check = (...checks) => { var _a; return inst.clone(util_exports.mergeDefs(def, { checks: [ ...(_a = def.checks) != null ? _a : [], ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) ] })); }; inst.clone = (def2, params) => clone(inst, def2, params); inst.brand = () => inst; inst.register = (reg, meta) => { reg.add(inst, meta); return inst; }; inst.parse = (data, params) => parse4(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse2(inst, data, params); inst.parseAsync = (data, params) => __async(void 0, null, function* () { return parseAsync2(inst, data, params, { callee: inst.parseAsync }); }); inst.safeParseAsync = (data, params) => __async(void 0, null, function* () { return safeParseAsync2(inst, data, params); }); inst.spa = inst.safeParseAsync; inst.encode = (data, params) => encode2(inst, data, params); inst.decode = (data, params) => decode2(inst, data, params); inst.encodeAsync = (data, params) => __async(void 0, null, function* () { return encodeAsync2(inst, data, params); }); inst.decodeAsync = (data, params) => __async(void 0, null, function* () { return decodeAsync2(inst, data, params); }); inst.safeEncode = (data, params) => safeEncode2(inst, data, params); inst.safeDecode = (data, params) => safeDecode2(inst, data, params); inst.safeEncodeAsync = (data, params) => __async(void 0, null, function* () { return safeEncodeAsync2(inst, data, params); }); inst.safeDecodeAsync = (data, params) => __async(void 0, null, function* () { return safeDecodeAsync2(inst, data, params); }); inst.refine = (check2, params) => inst.check(refine(check2, params)); inst.superRefine = (refinement) => inst.check(superRefine(refinement)); inst.overwrite = (fn) => inst.check(_overwrite(fn)); inst.optional = () => optional(inst); inst.nullable = () => nullable(inst); inst.nullish = () => optional(nullable(inst)); inst.nonoptional = (params) => nonoptional(inst, params); inst.array = () => array(inst); inst.or = (arg) => union([inst, arg]); inst.and = (arg) => intersection(inst, arg); inst.transform = (tx) => pipe(inst, transform(tx)); inst.default = (def2) => _default2(inst, def2); inst.prefault = (def2) => prefault(inst, def2); inst.catch = (params) => _catch2(inst, params); inst.pipe = (target) => pipe(inst, target); inst.readonly = () => readonly(inst); inst.describe = (description) => { const cl = inst.clone(); globalRegistry.add(cl, { description }); return cl; }; Object.defineProperty(inst, "description", { get() { var _a; return (_a = globalRegistry.get(inst)) == null ? void 0 : _a.description; }, configurable: true }); inst.meta = (...args) => { if (args.length === 0) { return globalRegistry.get(inst); } const cl = inst.clone(); globalRegistry.add(cl, args[0]); return cl; }; inst.isOptional = () => inst.safeParse(void 0).success; inst.isNullable = () => inst.safeParse(null).success; return inst; }); var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { var _a, _b, _c; $ZodString.init(inst, def); ZodType.init(inst, def); const bag = inst._zod.bag; inst.format = (_a = bag.format) != null ? _a : null; inst.minLength = (_b = bag.minimum) != null ? _b : null; inst.maxLength = (_c = bag.maximum) != null ? _c : null; inst.regex = (...args) => inst.check(_regex(...args)); inst.includes = (...args) => inst.check(_includes(...args)); inst.startsWith = (...args) => inst.check(_startsWith(...args)); inst.endsWith = (...args) => inst.check(_endsWith(...args)); inst.min = (...args) => inst.check(_minLength(...args)); inst.max = (...args) => inst.check(_maxLength(...args)); inst.length = (...args) => inst.check(_length(...args)); inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); inst.lowercase = (params) => inst.check(_lowercase(params)); inst.uppercase = (params) => inst.check(_uppercase(params)); inst.trim = () => inst.check(_trim()); inst.normalize = (...args) => inst.check(_normalize(...args)); inst.toLowerCase = () => inst.check(_toLowerCase()); inst.toUpperCase = () => inst.check(_toUpperCase()); }); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); inst.email = (params) => inst.check(_email(ZodEmail, params)); inst.url = (params) => inst.check(_url(ZodURL, params)); inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); inst.guid = (params) => inst.check(_guid(ZodGUID, params)); inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); inst.guid = (params) => inst.check(_guid(ZodGUID, params)); inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); inst.xid = (params) => inst.check(_xid(ZodXID, params)); inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); inst.e164 = (params) => inst.check(_e164(ZodE164, params)); inst.datetime = (params) => inst.check(datetime2(params)); inst.date = (params) => inst.check(date2(params)); inst.time = (params) => inst.check(time2(params)); inst.duration = (params) => inst.check(duration2(params)); }); function string2(params) { return _string(ZodString, params); } var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); }); function email2(params) { return _email(ZodEmail, params); } var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { $ZodGUID.init(inst, def); ZodStringFormat.init(inst, def); }); function guid2(params) { return _guid(ZodGUID, params); } var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { $ZodUUID.init(inst, def); ZodStringFormat.init(inst, def); }); function uuid2(params) { return _uuid(ZodUUID, params); } function uuidv4(params) { return _uuidv4(ZodUUID, params); } function uuidv6(params) { return _uuidv6(ZodUUID, params); } function uuidv7(params) { return _uuidv7(ZodUUID, params); } var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { $ZodURL.init(inst, def); ZodStringFormat.init(inst, def); }); function url(params) { return _url(ZodURL, params); } function httpUrl(params) { return _url(ZodURL, __spreadValues({ protocol: /^https?$/, hostname: regexes_exports.domain }, util_exports.normalizeParams(params))); } var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { $ZodEmoji.init(inst, def); ZodStringFormat.init(inst, def); }); function emoji2(params) { return _emoji2(ZodEmoji, params); } var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { $ZodNanoID.init(inst, def); ZodStringFormat.init(inst, def); }); function nanoid2(params) { return _nanoid(ZodNanoID, params); } var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { $ZodCUID.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid3(params) { return _cuid(ZodCUID, params); } var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { $ZodCUID2.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid22(params) { return _cuid2(ZodCUID2, params); } var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { $ZodULID.init(inst, def); ZodStringFormat.init(inst, def); }); function ulid2(params) { return _ulid(ZodULID, params); } var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { $ZodXID.init(inst, def); ZodStringFormat.init(inst, def); }); function xid2(params) { return _xid(ZodXID, params); } var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { $ZodKSUID.init(inst, def); ZodStringFormat.init(inst, def); }); function ksuid2(params) { return _ksuid(ZodKSUID, params); } var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { $ZodIPv4.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv42(params) { return _ipv4(ZodIPv4, params); } var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { $ZodIPv6.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv62(params) { return _ipv6(ZodIPv6, params); } var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { $ZodCIDRv4.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv42(params) { return _cidrv4(ZodCIDRv4, params); } var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { $ZodCIDRv6.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv62(params) { return _cidrv6(ZodCIDRv6, params); } var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { $ZodBase64.init(inst, def); ZodStringFormat.init(inst, def); }); function base642(params) { return _base64(ZodBase64, params); } var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { $ZodBase64URL.init(inst, def); ZodStringFormat.init(inst, def); }); function base64url2(params) { return _base64url(ZodBase64URL, params); } var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { $ZodE164.init(inst, def); ZodStringFormat.init(inst, def); }); function e1642(params) { return _e164(ZodE164, params); } var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); }); function jwt(params) { return _jwt(ZodJWT, params); } var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { $ZodCustomStringFormat.init(inst, def); ZodStringFormat.init(inst, def); }); function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); } function hex2(_params) { return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); } function hash(alg, params) { var _a; const enc = (_a = params == null ? void 0 : params.enc) != null ? _a : "hex"; const format = `${alg}_${enc}`; const regex = regexes_exports[format]; if (!regex) throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { var _a, _b, _c, _d, _e, _f, _g, _h, _i; $ZodNumber.init(inst, def); ZodType.init(inst, def); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.lt = (value, params) => inst.check(_lt(value, params)); inst.lte = (value, params) => inst.check(_lte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); inst.int = (params) => inst.check(int(params)); inst.safe = (params) => inst.check(int(params)); inst.positive = (params) => inst.check(_gt(0, params)); inst.nonnegative = (params) => inst.check(_gte(0, params)); inst.negative = (params) => inst.check(_lt(0, params)); inst.nonpositive = (params) => inst.check(_lte(0, params)); inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); inst.step = (value, params) => inst.check(_multipleOf(value, params)); inst.finite = () => inst; const bag = inst._zod.bag; inst.minValue = (_c = Math.max((_a = bag.minimum) != null ? _a : Number.NEGATIVE_INFINITY, (_b = bag.exclusiveMinimum) != null ? _b : Number.NEGATIVE_INFINITY)) != null ? _c : null; inst.maxValue = (_f = Math.min((_d = bag.maximum) != null ? _d : Number.POSITIVE_INFINITY, (_e = bag.exclusiveMaximum) != null ? _e : Number.POSITIVE_INFINITY)) != null ? _f : null; inst.isInt = ((_g = bag.format) != null ? _g : "").includes("int") || Number.isSafeInteger((_h = bag.multipleOf) != null ? _h : 0.5); inst.isFinite = true; inst.format = (_i = bag.format) != null ? _i : null; }); function number2(params) { return _number(ZodNumber, params); } var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { $ZodNumberFormat.init(inst, def); ZodNumber.init(inst, def); }); function int(params) { return _int(ZodNumberFormat, params); } function float32(params) { return _float32(ZodNumberFormat, params); } function float64(params) { return _float64(ZodNumberFormat, params); } function int32(params) { return _int32(ZodNumberFormat, params); } function uint32(params) { return _uint32(ZodNumberFormat, params); } var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { $ZodBoolean.init(inst, def); ZodType.init(inst, def); }); function boolean2(params) { return _boolean(ZodBoolean, params); } var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { var _a, _b, _c; $ZodBigInt.init(inst, def); ZodType.init(inst, def); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.lt = (value, params) => inst.check(_lt(value, params)); inst.lte = (value, params) => inst.check(_lte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); inst.positive = (params) => inst.check(_gt(BigInt(0), params)); inst.negative = (params) => inst.check(_lt(BigInt(0), params)); inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); const bag = inst._zod.bag; inst.minValue = (_a = bag.minimum) != null ? _a : null; inst.maxValue = (_b = bag.maximum) != null ? _b : null; inst.format = (_c = bag.format) != null ? _c : null; }); function bigint2(params) { return _bigint(ZodBigInt, params); } var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { $ZodBigIntFormat.init(inst, def); ZodBigInt.init(inst, def); }); function int64(params) { return _int64(ZodBigIntFormat, params); } function uint64(params) { return _uint64(ZodBigIntFormat, params); } var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { $ZodSymbol.init(inst, def); ZodType.init(inst, def); }); function symbol(params) { return _symbol(ZodSymbol, params); } var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { $ZodUndefined.init(inst, def); ZodType.init(inst, def); }); function _undefined3(params) { return _undefined2(ZodUndefined, params); } var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { $ZodNull.init(inst, def); ZodType.init(inst, def); }); function _null3(params) { return _null2(ZodNull, params); } var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { $ZodAny.init(inst, def); ZodType.init(inst, def); }); function any() { return _any(ZodAny); } var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { $ZodUnknown.init(inst, def); ZodType.init(inst, def); }); function unknown() { return _unknown(ZodUnknown); } var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { $ZodNever.init(inst, def); ZodType.init(inst, def); }); function never(params) { return _never(ZodNever, params); } var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { $ZodVoid.init(inst, def); ZodType.init(inst, def); }); function _void2(params) { return _void(ZodVoid, params); } var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { $ZodDate.init(inst, def); ZodType.init(inst, def); inst.min = (value, params) => inst.check(_gte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); const c2 = inst._zod.bag; inst.minDate = c2.minimum ? new Date(c2.minimum) : null; inst.maxDate = c2.maximum ? new Date(c2.maximum) : null; }); function date3(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { $ZodArray.init(inst, def); ZodType.init(inst, def); inst.element = def.element; inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); inst.nonempty = (params) => inst.check(_minLength(1, params)); inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); inst.length = (len, params) => inst.check(_length(len, params)); inst.unwrap = () => inst.element; }); function array(element, params) { return _array(ZodArray, element, params); } function keyof(schema) { const shape = schema._zod.def.shape; return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); util_exports.defineLazy(inst, "shape", () => { return def.shape; }); inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); inst.catchall = (catchall) => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall })); inst.passthrough = () => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall: unknown() })); inst.loose = () => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall: unknown() })); inst.strict = () => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall: never() })); inst.strip = () => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall: void 0 })); inst.extend = (incoming) => { return util_exports.extend(inst, incoming); }; inst.safeExtend = (incoming) => { return util_exports.safeExtend(inst, incoming); }; inst.merge = (other) => util_exports.merge(inst, other); inst.pick = (mask) => util_exports.pick(inst, mask); inst.omit = (mask) => util_exports.omit(inst, mask); inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]); inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); }); function object(shape, params) { const def = __spreadValues({ type: "object", shape: shape != null ? shape : {} }, util_exports.normalizeParams(params)); return new ZodObject(def); } function strictObject(shape, params) { return new ZodObject(__spreadValues({ type: "object", shape, catchall: never() }, util_exports.normalizeParams(params))); } function looseObject(shape, params) { return new ZodObject(__spreadValues({ type: "object", shape, catchall: unknown() }, util_exports.normalizeParams(params))); } var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { $ZodUnion.init(inst, def); ZodType.init(inst, def); inst.options = def.options; }); function union(options, params) { return new ZodUnion(__spreadValues({ type: "union", options }, util_exports.normalizeParams(params))); } var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { ZodUnion.init(inst, def); $ZodDiscriminatedUnion.init(inst, def); }); function discriminatedUnion(discriminator, options, params) { return new ZodDiscriminatedUnion(__spreadValues({ type: "union", options, discriminator }, util_exports.normalizeParams(params))); } var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { $ZodIntersection.init(inst, def); ZodType.init(inst, def); }); function intersection(left, right) { return new ZodIntersection({ type: "intersection", left, right }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { $ZodTuple.init(inst, def); ZodType.init(inst, def); inst.rest = (rest) => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { rest })); }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new ZodTuple(__spreadValues({ type: "tuple", items, rest }, util_exports.normalizeParams(params))); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { $ZodRecord.init(inst, def); ZodType.init(inst, def); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function record(keyType, valueType, params) { return new ZodRecord(__spreadValues({ type: "record", keyType, valueType }, util_exports.normalizeParams(params))); } function partialRecord(keyType, valueType, params) { const k = clone(keyType); k._zod.values = void 0; return new ZodRecord(__spreadValues({ type: "record", keyType: k, valueType }, util_exports.normalizeParams(params))); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { $ZodMap.init(inst, def); ZodType.init(inst, def); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function map(keyType, valueType, params) { return new ZodMap(__spreadValues({ type: "map", keyType, valueType }, util_exports.normalizeParams(params))); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { $ZodSet.init(inst, def); ZodType.init(inst, def); inst.min = (...args) => inst.check(_minSize(...args)); inst.nonempty = (params) => inst.check(_minSize(1, params)); inst.max = (...args) => inst.check(_maxSize(...args)); inst.size = (...args) => inst.check(_size(...args)); }); function set(valueType, params) { return new ZodSet(__spreadValues({ type: "set", valueType }, util_exports.normalizeParams(params))); } var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { $ZodEnum.init(inst, def); ZodType.init(inst, def); inst.enum = def.entries; inst.options = Object.values(def.entries); const keys = new Set(Object.keys(def.entries)); inst.extract = (values, params) => { const newEntries = {}; for (const value of values) { if (keys.has(value)) { newEntries[value] = def.entries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum(__spreadProps(__spreadValues(__spreadProps(__spreadValues({}, def), { checks: [] }), util_exports.normalizeParams(params)), { entries: newEntries })); }; inst.exclude = (values, params) => { const newEntries = __spreadValues({}, def.entries); for (const value of values) { if (keys.has(value)) { delete newEntries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum(__spreadProps(__spreadValues(__spreadProps(__spreadValues({}, def), { checks: [] }), util_exports.normalizeParams(params)), { entries: newEntries })); }; }); function _enum2(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new ZodEnum(__spreadValues({ type: "enum", entries }, util_exports.normalizeParams(params))); } function nativeEnum(entries, params) { return new ZodEnum(__spreadValues({ type: "enum", entries }, util_exports.normalizeParams(params))); } var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { $ZodLiteral.init(inst, def); ZodType.init(inst, def); inst.values = new Set(def.values); Object.defineProperty(inst, "value", { get() { if (def.values.length > 1) { throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); } return def.values[0]; } }); }); function literal2(value, params) { return new ZodLiteral(__spreadValues({ type: "literal", values: Array.isArray(value) ? value : [value] }, util_exports.normalizeParams(params))); } var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { $ZodFile.init(inst, def); ZodType.init(inst, def); inst.min = (size, params) => inst.check(_minSize(size, params)); inst.max = (size, params) => inst.check(_maxSize(size, params)); inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); }); function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (_ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } payload.addIssue = (issue2) => { var _a, _b, _c; if (typeof issue2 === "string") { payload.issues.push(util_exports.issue(issue2, payload.value, def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; (_a = _issue.code) != null ? _a : _issue.code = "custom"; (_b = _issue.input) != null ? _b : _issue.input = payload.value; (_c = _issue.inst) != null ? _c : _issue.inst = inst; payload.issues.push(util_exports.issue(_issue)); } }; const output = def.transform(payload.value, payload); if (output instanceof Promise) { return output.then((output2) => { payload.value = output2; return payload; }); } payload.value = output; return payload; }; }); function transform(fn) { return new ZodTransform({ type: "transform", transform: fn }); } var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { $ZodOptional.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function optional(innerType) { return new ZodOptional({ type: "optional", innerType }); } var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { $ZodNullable.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function nullable(innerType) { return new ZodNullable({ type: "nullable", innerType }); } function nullish2(innerType) { return optional(nullable(innerType)); } var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { $ZodDefault.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); function _default2(innerType, defaultValue) { return new ZodDefault({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { $ZodPrefault.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function prefault(innerType, defaultValue) { return new ZodPrefault({ type: "prefault", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { $ZodNonOptional.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function nonoptional(innerType, params) { return new ZodNonOptional(__spreadValues({ type: "nonoptional", innerType }, util_exports.normalizeParams(params))); } var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { $ZodSuccess.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function success(innerType) { return new ZodSuccess({ type: "success", innerType }); } var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { $ZodCatch.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { $ZodNaN.init(inst, def); ZodType.init(inst, def); }); function nan(params) { return _nan(ZodNaN, params); } var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { $ZodPipe.init(inst, def); ZodType.init(inst, def); inst.in = def.in; inst.out = def.out; }); function pipe(in_, out) { return new ZodPipe({ type: "pipe", in: in_, out // ...util.normalizeParams(params), }); } var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { ZodPipe.init(inst, def); $ZodCodec.init(inst, def); }); function codec(in_, out, params) { return new ZodCodec({ type: "pipe", in: in_, out, transform: params.decode, reverseTransform: params.encode }); } var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { $ZodReadonly.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function readonly(innerType) { return new ZodReadonly({ type: "readonly", innerType }); } var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { $ZodTemplateLiteral.init(inst, def); ZodType.init(inst, def); }); function templateLiteral(parts, params) { return new ZodTemplateLiteral(__spreadValues({ type: "template_literal", parts }, util_exports.normalizeParams(params))); } var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { $ZodLazy.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.getter(); }); function lazy(getter) { return new ZodLazy({ type: "lazy", getter }); } var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { $ZodPromise.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function promise(innerType) { return new ZodPromise({ type: "promise", innerType }); } var ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { $ZodFunction.init(inst, def); ZodType.init(inst, def); }); function _function(params) { var _a, _b; return new ZodFunction({ type: "function", input: Array.isArray(params == null ? void 0 : params.input) ? tuple(params == null ? void 0 : params.input) : (_a = params == null ? void 0 : params.input) != null ? _a : array(unknown()), output: (_b = params == null ? void 0 : params.output) != null ? _b : unknown() }); } var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { $ZodCustom.init(inst, def); ZodType.init(inst, def); }); function check(fn) { const ch = new $ZodCheck({ check: "custom" // ...util.normalizeParams(params), }); ch._zod.check = fn; return ch; } function custom(fn, _params) { return _custom(ZodCustom, fn != null ? fn : () => true, _params); } function refine(fn, _params = {}) { return _refine(ZodCustom, fn, _params); } function superRefine(fn) { return _superRefine(fn); } function _instanceof(cls, params = { error: `Input not instance of ${cls.name}` }) { const inst = new ZodCustom(__spreadValues({ type: "custom", check: "custom", fn: (data) => data instanceof cls, abort: true }, util_exports.normalizeParams(params))); inst._zod.bag.Class = cls; return inst; } var stringbool = (...args) => _stringbool({ Codec: ZodCodec, Boolean: ZodBoolean, String: ZodString }, ...args); function json(params) { const jsonSchema = lazy(() => { return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); }); return jsonSchema; } function preprocess(fn, schema) { return pipe(transform(fn), schema); } // ../../node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", invalid_format: "invalid_format", not_multiple_of: "not_multiple_of", unrecognized_keys: "unrecognized_keys", invalid_union: "invalid_union", invalid_key: "invalid_key", invalid_element: "invalid_element", invalid_value: "invalid_value", custom: "custom" }; function setErrorMap(map2) { config({ customError: map2 }); } function getErrorMap() { return config().customError; } var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); // ../../node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, boolean: () => boolean3, date: () => date4, number: () => number3, string: () => string3 }); function string3(params) { return _coercedString(ZodString, params); } function number3(params) { return _coercedNumber(ZodNumber, params); } function boolean3(params) { return _coercedBoolean(ZodBoolean, params); } function bigint3(params) { return _coercedBigint(ZodBigInt, params); } function date4(params) { return _coercedDate(ZodDate, params); } // ../../node_modules/zod/v4/classic/external.js config(en_default()); // src/Utils/Keyword.ts var RESERVED_WORDS = /* @__PURE__ */ new Set([ "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with" ]); var STRICT_MODE_RESERVED_WORDS = /* @__PURE__ */ new Set([ "let", "static", "implements", "interface", "package", "private", "protected", "public" ]); var STRICT_MODE_RESTRICTED_WORDS = /* @__PURE__ */ new Set(["eval", "arguments"]); function isReservedWord(identifierName) { return RESERVED_WORDS.has(identifierName) || STRICT_MODE_RESERVED_WORDS.has(identifierName) || STRICT_MODE_RESTRICTED_WORDS.has(identifierName); } // src/HIR/HIR.ts var GeneratedSource = Symbol(); function isStatementBlockKind(kind) { return kind === "block" || kind === "catch"; } function isExpressionBlockKind(kind) { return !isStatementBlockKind(kind); } function convertHoistedLValueKind(kind) { switch (kind) { case "HoistedLet" /* HoistedLet */: return "Let" /* Let */; case "HoistedConst" /* HoistedConst */: return "Const" /* Const */; case "HoistedFunction" /* HoistedFunction */: return "Function" /* Function */; case "Let" /* Let */: case "Const" /* Const */: case "Function" /* Function */: case "Reassign" /* Reassign */: case "Catch" /* Catch */: return null; default: assertExhaustive(kind, "Unexpected lvalue kind"); } } var opaqueValidIdentifierName = Symbol(); function makeTemporaryIdentifier(id, loc) { return { id, name: null, declarationId: makeDeclarationId(id), mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, scope: null, type: makeType(), loc }; } function forkTemporaryIdentifier(id, source2) { return __spreadProps(__spreadValues({}, source2), { mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, id }); } function validateIdentifierName(name) { if (isReservedWord(name)) { const error45 = new CompilerError(); error45.pushDiagnostic( CompilerDiagnostic.create({ category: "Syntax" /* Syntax */, reason: "Expected a non-reserved identifier name", description: `\`${name}\` is a reserved word in JavaScript and cannot be used as an identifier name`, suggestions: null }).withDetails({ kind: "error", loc: GeneratedSource, message: "reserved word" }) ); return Err(error45); } else if (!t2.isValidIdentifier(name)) { const error45 = new CompilerError(); error45.pushDiagnostic( CompilerDiagnostic.create({ category: "Syntax" /* Syntax */, reason: `Expected a valid identifier name`, description: `\`${name}\` is not a valid JavaScript identifier`, suggestions: null }).withDetails({ kind: "error", loc: GeneratedSource, message: "reserved word" }) ); } return Ok({ kind: "named", value: name }); } function makeIdentifierName(name) { return validateIdentifierName(name).unwrap(); } function promoteTemporary(identifier4) { CompilerError.invariant(identifier4.name === null, { reason: `Expected a temporary (unnamed) identifier`, description: `Identifier already has a name, \`${identifier4.name}\``, details: [ { kind: "error", loc: GeneratedSource, message: null } ], suggestions: null }); identifier4.name = { kind: "promoted", value: `#t${identifier4.declarationId}` }; } function isPromotedTemporary(name) { return name.startsWith("#t"); } function promoteTemporaryJsxTag(identifier4) { CompilerError.invariant(identifier4.name === null, { reason: `Expected a temporary (unnamed) identifier`, description: `Identifier already has a name, \`${identifier4.name}\``, details: [ { kind: "error", loc: GeneratedSource, message: null } ], suggestions: null }); identifier4.name = { kind: "promoted", value: `#T${identifier4.declarationId}` }; } function isPromotedJsxTemporary(name) { return name.startsWith("#T"); } var ValueReason = /* @__PURE__ */ ((ValueReason4) => { ValueReason4["Global"] = "global"; ValueReason4["JsxCaptured"] = "jsx-captured"; ValueReason4["HookCaptured"] = "hook-captured"; ValueReason4["HookReturn"] = "hook-return"; ValueReason4["Effect"] = "effect"; ValueReason4["KnownReturnSignature"] = "known-return-signature"; ValueReason4["Context"] = "context"; ValueReason4["State"] = "state"; ValueReason4["ReducerState"] = "reducer-state"; ValueReason4["ReactiveFunctionArgument"] = "reactive-function-argument"; ValueReason4["Other"] = "other"; return ValueReason4; })(ValueReason || {}); var ValueKind = /* @__PURE__ */ ((ValueKind3) => { ValueKind3["MaybeFrozen"] = "maybefrozen"; ValueKind3["Frozen"] = "frozen"; ValueKind3["Primitive"] = "primitive"; ValueKind3["Global"] = "global"; ValueKind3["Mutable"] = "mutable"; ValueKind3["Context"] = "context"; return ValueKind3; })(ValueKind || {}); var ValueKindSchema = external_exports.enum([ "maybefrozen" /* MaybeFrozen */, "frozen" /* Frozen */, "primitive" /* Primitive */, "global" /* Global */, "mutable" /* Mutable */, "context" /* Context */ ]); var ValueReasonSchema = external_exports.enum([ "context" /* Context */, "effect" /* Effect */, "global" /* Global */, "hook-captured" /* HookCaptured */, "hook-return" /* HookReturn */, "jsx-captured" /* JsxCaptured */, "known-return-signature" /* KnownReturnSignature */, "other" /* Other */, "reactive-function-argument" /* ReactiveFunctionArgument */, "reducer-state" /* ReducerState */, "state" /* State */ ]); var Effect = /* @__PURE__ */ ((Effect2) => { Effect2["Unknown"] = ""; Effect2["Freeze"] = "freeze"; Effect2["Read"] = "read"; Effect2["Capture"] = "capture"; Effect2["ConditionallyMutateIterator"] = "mutate-iterator?"; Effect2["ConditionallyMutate"] = "mutate?"; Effect2["Mutate"] = "mutate"; Effect2["Store"] = "store"; return Effect2; })(Effect || {}); var EffectSchema = external_exports.enum([ "read" /* Read */, "mutate" /* Mutate */, "mutate?" /* ConditionallyMutate */, "mutate-iterator?" /* ConditionallyMutateIterator */, "capture" /* Capture */, "store" /* Store */, "freeze" /* Freeze */ ]); function isMutableEffect(effect, location) { switch (effect) { case "capture" /* Capture */: case "store" /* Store */: case "mutate?" /* ConditionallyMutate */: case "mutate-iterator?" /* ConditionallyMutateIterator */: case "mutate" /* Mutate */: { return true; } case "" /* Unknown */: { CompilerError.invariant(false, { reason: "Unexpected unknown effect", description: null, details: [ { kind: "error", loc: location, message: null } ], suggestions: null }); } case "read" /* Read */: case "freeze" /* Freeze */: { return false; } default: { assertExhaustive(effect, `Unexpected effect \`${effect}\``); } } } var opaquePropertyLiteral = Symbol(); function makePropertyLiteral(value) { return value; } function areEqualPaths(a, b) { return a.length === b.length && a.every( (item, ix) => item.property === b[ix].property && item.optional === b[ix].optional ); } function getPlaceScope(id, place) { const scope = place.identifier.scope; if (scope !== null && isScopeActive(scope, id)) { return scope; } return null; } function isScopeActive(scope, id) { return id >= scope.range.start && id < scope.range.end; } var opaqueBlockId = Symbol(); function makeBlockId(id) { CompilerError.invariant(id >= 0 && Number.isInteger(id), { reason: "Expected block id to be a non-negative integer", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return id; } var opaqueScopeId = Symbol(); function makeScopeId(id) { CompilerError.invariant(id >= 0 && Number.isInteger(id), { reason: "Expected block id to be a non-negative integer", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return id; } var opaqueIdentifierId = Symbol(); function makeIdentifierId(id) { CompilerError.invariant(id >= 0 && Number.isInteger(id), { reason: "Expected identifier id to be a non-negative integer", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return id; } var opageDeclarationId = Symbol(); function makeDeclarationId(id) { CompilerError.invariant(id >= 0 && Number.isInteger(id), { reason: "Expected declaration id to be a non-negative integer", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return id; } var opaqueInstructionId = Symbol(); function makeInstructionId(id) { CompilerError.invariant(id >= 0 && Number.isInteger(id), { reason: "Expected instruction id to be a non-negative integer", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return id; } function isObjectMethodType(id) { return id.type.kind == "ObjectMethod"; } function isPrimitiveType(id) { return id.type.kind === "Primitive"; } function isArrayType(id) { return id.type.kind === "Object" && id.type.shapeId === "BuiltInArray"; } function isMapType(id) { return id.type.kind === "Object" && id.type.shapeId === "BuiltInMap"; } function isSetType(id) { return id.type.kind === "Object" && id.type.shapeId === "BuiltInSet"; } function isPropsType(id) { return id.type.kind === "Object" && id.type.shapeId === "BuiltInProps"; } function isRefValueType(id) { return id.type.kind === "Object" && id.type.shapeId === "BuiltInRefValue"; } function isUseRefType(id) { return id.type.kind === "Object" && id.type.shapeId === "BuiltInUseRefId"; } function isUseStateType(id) { return id.type.kind === "Object" && id.type.shapeId === "BuiltInUseState"; } function isJsxType(type) { return type.kind === "Object" && type.shapeId === "BuiltInJsx"; } function isRefOrRefValue(id) { return isUseRefType(id) || isRefValueType(id); } function isRefOrRefLikeMutableType(type) { return type.kind === "Object" && (type.shapeId === "BuiltInUseRefId" || type.shapeId == "ReanimatedSharedValueId"); } function isSetStateType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInSetState"; } function isStartTransitionType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInStartTransition"; } function isSetActionStateType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInSetActionState"; } function isUseReducerType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInUseReducer"; } function isDispatcherType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInDispatch"; } function isFireFunctionType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInFireFunction"; } function isEffectEventFunctionType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInEffectEventFunction"; } function isStableType(id) { return isSetStateType(id) || isSetActionStateType(id) || isDispatcherType(id) || isUseRefType(id) || isStartTransitionType(id); } function isStableTypeContainer(id) { const type_ = id.type; if (type_.kind !== "Object") { return false; } return isUseStateType(id) || // setState type_.shapeId === "BuiltInUseActionState" || // setActionState isUseReducerType(id) || // dispatcher type_.shapeId === "BuiltInUseTransition"; } function evaluatesToStableTypeOrContainer(env, { value }) { if (value.kind === "CallExpression" || value.kind === "MethodCall") { const callee = value.kind === "CallExpression" ? value.callee : value.property; const calleeHookKind = getHookKind(env, callee.identifier); switch (calleeHookKind) { case "useState": case "useReducer": case "useActionState": case "useRef": case "useTransition": return true; } } return false; } function isUseEffectHookType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInUseEffectHook"; } function isUseLayoutEffectHookType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInUseLayoutEffectHook"; } function isUseInsertionEffectHookType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInUseInsertionEffectHook"; } function isUseContextHookType(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInUseContextHook"; } function getHookKind(env, id) { return getHookKindForType(env, id.type); } function isUseOperator(id) { return id.type.kind === "Function" && id.type.shapeId === "BuiltInUseOperator"; } function getHookKindForType(env, type) { var _a; if (type.kind === "Function") { const signature = env.getFunctionSignature(type); return (_a = signature == null ? void 0 : signature.hookKind) != null ? _a : null; } return null; } // src/ReactiveScopes/PrintReactiveFunction.ts function printReactiveFunctionWithOutlined(fn) { const writer = new Writer(); writeReactiveFunction(fn, writer); for (const outlined of fn.env.getOutlinedFunctions()) { writer.writeLine("\nfunction " + printFunction(outlined.fn)); } return writer.complete(); } function printReactiveFunction(fn) { const writer = new Writer(); writeReactiveFunction(fn, writer); return writer.complete(); } function writeReactiveFunction(fn, writer) { writer.writeLine(`function ${fn.id !== null ? fn.id : ""}(`); writer.indented(() => { for (const param of fn.params) { if (param.kind === "Identifier") { writer.writeLine(`${printPlace(param)},`); } else { writer.writeLine(`...${printPlace(param.place)},`); } } }); writer.writeLine(") {"); writeReactiveInstructions(writer, fn.body); writer.writeLine("}"); } function printReactiveScopeSummary(scope) { const items = []; items.push("scope"); items.push(`@${scope.id}`); items.push(`[${scope.range.start}:${scope.range.end}]`); items.push( `dependencies=[${Array.from(scope.dependencies).map((dep) => printDependency(dep)).join(", ")}]` ); items.push( `declarations=[${Array.from(scope.declarations).map( ([, decl]) => printIdentifier(__spreadProps(__spreadValues({}, decl.identifier), { scope: decl.scope })) ).join(", ")}]` ); items.push( `reassignments=[${Array.from(scope.reassignments).map( (reassign) => printIdentifier(reassign) )}]` ); if (scope.earlyReturnValue !== null) { items.push( `earlyReturn={id: ${printIdentifier( scope.earlyReturnValue.value )}, label: ${scope.earlyReturnValue.label}}}` ); } return items.join(" "); } function writeReactiveBlock(writer, block) { writer.writeLine(`${printReactiveScopeSummary(block.scope)} {`); writeReactiveInstructions(writer, block.instructions); writer.writeLine("}"); } function writePrunedScope(writer, block) { writer.writeLine(` ${printReactiveScopeSummary(block.scope)} {`); writeReactiveInstructions(writer, block.instructions); writer.writeLine("}"); } function printDependency(dependency) { const identifier4 = printIdentifier(dependency.identifier) + printType(dependency.identifier.type); return `${identifier4}${dependency.path.map((token2) => `${token2.optional ? "?." : "."}${token2.property}`).join("")}`; } function writeReactiveInstructions(writer, instructions) { writer.indented(() => { for (const instr of instructions) { writeReactiveInstruction(writer, instr); } }); } function writeReactiveInstruction(writer, instr) { switch (instr.kind) { case "instruction": { const { instruction } = instr; const id = `[${instruction.id}]`; if (instruction.lvalue !== null) { writer.write(`${id} ${printPlace(instruction.lvalue)} = `); writeReactiveValue(writer, instruction.value); writer.newline(); } else { writer.write(`${id} `); writeReactiveValue(writer, instruction.value); writer.newline(); } break; } case "scope": { writeReactiveBlock(writer, instr); break; } case "pruned-scope": { writePrunedScope(writer, instr); break; } case "terminal": { if (instr.label !== null) { writer.write(`bb${instr.label.id}: `); } writeTerminal(writer, instr.terminal); break; } default: { assertExhaustive( instr, `Unexpected terminal kind \`${instr.kind}\`` ); } } } function writeReactiveValue(writer, value) { switch (value.kind) { case "ConditionalExpression": { writer.writeLine(`Ternary `); writer.indented(() => { writeReactiveValue(writer, value.test); writer.writeLine(`? `); writer.indented(() => { writeReactiveValue(writer, value.consequent); }); writer.writeLine(`: `); writer.indented(() => { writeReactiveValue(writer, value.alternate); }); }); writer.newline(); break; } case "LogicalExpression": { writer.writeLine(`Logical`); writer.indented(() => { writeReactiveValue(writer, value.left); writer.write(`${value.operator} `); writeReactiveValue(writer, value.right); }); writer.newline(); break; } case "SequenceExpression": { writer.writeLine(`Sequence`); writer.indented(() => { writer.indented(() => { value.instructions.forEach( (instr) => writeReactiveInstruction(writer, { kind: "instruction", instruction: instr }) ); writer.write(`[${value.id}] `); writeReactiveValue(writer, value.value); }); }); writer.newline(); break; } case "OptionalExpression": { writer.append(`OptionalExpression optional=${value.optional}`); writer.newline(); writer.indented(() => { writeReactiveValue(writer, value.value); }); writer.newline(); break; } default: { const printed = printInstructionValue(value); const lines = printed.split("\n"); if (lines.length === 1) { writer.writeLine(printed); } else { writer.indented(() => { for (const line2 of lines) { writer.writeLine(line2); } }); } } } } function writeTerminal(writer, terminal) { switch (terminal.kind) { case "break": { const id = terminal.id !== null ? `[${terminal.id}]` : []; writer.writeLine( `${id} break bb${terminal.target} (${terminal.targetKind})` ); break; } case "continue": { const id = `[${terminal.id}]`; writer.writeLine( `${id} continue bb${terminal.target} (${terminal.targetKind})` ); break; } case "do-while": { writer.writeLine(`[${terminal.id}] do-while {`); writeReactiveInstructions(writer, terminal.loop); writer.writeLine("} ("); writer.indented(() => { writeReactiveValue(writer, terminal.test); }); writer.writeLine(")"); break; } case "while": { writer.writeLine(`[${terminal.id}] while (`); writer.indented(() => { writeReactiveValue(writer, terminal.test); }); writer.writeLine(") {"); writeReactiveInstructions(writer, terminal.loop); writer.writeLine("}"); break; } case "if": { const { test, consequent, alternate } = terminal; writer.writeLine(`[${terminal.id}] if (${printPlace(test)}) {`); writeReactiveInstructions(writer, consequent); if (alternate !== null) { writer.writeLine("} else {"); writeReactiveInstructions(writer, alternate); } writer.writeLine("}"); break; } case "switch": { writer.writeLine( `[${terminal.id}] switch (${printPlace(terminal.test)}) {` ); writer.indented(() => { for (const case_ of terminal.cases) { let prefix = case_.test !== null ? `case ${printPlace(case_.test)}` : "default"; writer.writeLine(`${prefix}: {`); writer.indented(() => { var _a, _b; const block = case_.block; CompilerError.invariant(block != null, { reason: "Expected case to have a block", description: null, details: [ { kind: "error", loc: (_b = (_a = case_.test) == null ? void 0 : _a.loc) != null ? _b : null, message: null } ], suggestions: null }); writeReactiveInstructions(writer, block); }); writer.writeLine("}"); } }); writer.writeLine("}"); break; } case "for": { writer.writeLine(`[${terminal.id}] for (`); writer.indented(() => { writeReactiveValue(writer, terminal.init); writer.writeLine(";"); writeReactiveValue(writer, terminal.test); writer.writeLine(";"); if (terminal.update !== null) { writeReactiveValue(writer, terminal.update); } }); writer.writeLine(") {"); writeReactiveInstructions(writer, terminal.loop); writer.writeLine("}"); break; } case "for-of": { writer.writeLine(`[${terminal.id}] for-of (`); writer.indented(() => { writeReactiveValue(writer, terminal.init); writer.writeLine(";"); writeReactiveValue(writer, terminal.test); }); writer.writeLine(") {"); writeReactiveInstructions(writer, terminal.loop); writer.writeLine("}"); break; } case "for-in": { writer.writeLine(`[${terminal.id}] for-in (`); writer.indented(() => { writeReactiveValue(writer, terminal.init); }); writer.writeLine(") {"); writeReactiveInstructions(writer, terminal.loop); writer.writeLine("}"); break; } case "throw": { writer.writeLine(`[${terminal.id}] throw ${printPlace(terminal.value)}`); break; } case "return": { writer.writeLine(`[${terminal.id}] return ${printPlace(terminal.value)}`); break; } case "label": { writer.writeLine("{"); writeReactiveInstructions(writer, terminal.block); writer.writeLine("}"); break; } case "try": { writer.writeLine(`[${terminal.id}] try {`); writeReactiveInstructions(writer, terminal.block); writer.write(`} catch `); if (terminal.handlerBinding !== null) { writer.writeLine(`(${printPlace(terminal.handlerBinding)}) {`); } else { writer.writeLine(`{`); } writeReactiveInstructions(writer, terminal.handler); writer.writeLine("}"); break; } default: assertExhaustive( terminal, `Unhandled terminal kind \`${terminal.kind}\`` ); } } var _out, _line, _depth; var Writer = class { constructor({ depth } = { depth: 0 }) { __privateAdd(this, _out, []); __privateAdd(this, _line); __privateAdd(this, _depth); __privateSet(this, _depth, Math.max(depth, 0)); __privateSet(this, _line, ""); } complete() { const line2 = __privateGet(this, _line).trimEnd(); if (line2.length > 0) { __privateGet(this, _out).push(line2); } return __privateGet(this, _out).join("\n"); } append(s) { this.write(s); } newline() { const line2 = __privateGet(this, _line).trimEnd(); if (line2.length > 0) { __privateGet(this, _out).push(line2); } __privateSet(this, _line, ""); } write(s) { if (__privateGet(this, _line).length === 0 && __privateGet(this, _depth) > 0) { __privateSet(this, _line, " ".repeat(__privateGet(this, _depth))); } __privateSet(this, _line, __privateGet(this, _line) + s); } writeLine(s) { this.write(s); this.newline(); } indented(f) { __privateWrapper(this, _depth)._++; f(); __privateWrapper(this, _depth)._--; } }; _out = new WeakMap(); _line = new WeakMap(); _depth = new WeakMap(); // src/HIR/PrintHIR.ts function printFunctionWithOutlined(fn) { const output = [printFunction(fn)]; for (const outlined of fn.env.getOutlinedFunctions()) { output.push(` function ${outlined.fn.id}: ${printHIR(outlined.fn.body)}`); } return output.join("\n"); } function printFunction(fn) { const output = []; let definition = ""; if (fn.id !== null) { definition += fn.id; } else { definition += "<>"; } if (fn.nameHint != null) { definition += ` ${fn.nameHint}`; } if (fn.params.length !== 0) { definition += "(" + fn.params.map((param) => { if (param.kind === "Identifier") { return printPlace(param); } else { return `...${printPlace(param.place)}`; } }).join(", ") + ")"; } else { definition += "()"; } definition += `: ${printPlace(fn.returns)}`; output.push(definition); output.push(...fn.directives); output.push(printHIR(fn.body)); return output.join("\n"); } function printHIR(ir, options = null) { var _a; let output = []; let indent = " ".repeat((_a = options == null ? void 0 : options.indent) != null ? _a : 0); const push2 = (text, indent2 = " ") => { output.push(`${indent2}${text}`); }; for (const [blockId, block] of ir.blocks) { output.push(`bb${blockId} (${block.kind}):`); if (block.preds.size > 0) { const preds = ["predecessor blocks:"]; for (const pred of block.preds) { preds.push(`bb${pred}`); } push2(preds.join(" ")); } for (const phi of block.phis) { push2(printPhi(phi)); } for (const instr of block.instructions) { push2(printInstruction(instr)); } const terminal = printTerminal(block.terminal); if (Array.isArray(terminal)) { terminal.forEach((line2) => push2(line2)); } else { push2(terminal); } } return output.map((line2) => indent + line2).join("\n"); } function printInstruction(instr) { const id = `[${instr.id}]`; let value = printInstructionValue(instr.value); if (instr.effects != null) { value += ` ${instr.effects.map(printAliasingEffect).join("\n ")}`; } if (instr.lvalue !== null) { return `${id} ${printPlace(instr.lvalue)} = ${value}`; } else { return `${id} ${value}`; } } function printPhi(phi) { const items = []; items.push(printPlace(phi.place)); items.push(printMutableRange(phi.place.identifier)); items.push(printType(phi.place.identifier.type)); items.push(": phi("); const phis = []; for (const [blockId, place] of phi.operands) { phis.push(`bb${blockId}: ${printPlace(place)}`); } items.push(phis.join(", ")); items.push(")"); return items.join(""); } function printTerminal(terminal) { let value; switch (terminal.kind) { case "if": { value = `[${terminal.id}] If (${printPlace(terminal.test)}) then:bb${terminal.consequent} else:bb${terminal.alternate}${terminal.fallthrough ? ` fallthrough=bb${terminal.fallthrough}` : ""}`; break; } case "branch": { value = `[${terminal.id}] Branch (${printPlace(terminal.test)}) then:bb${terminal.consequent} else:bb${terminal.alternate} fallthrough:bb${terminal.fallthrough}`; break; } case "logical": { value = `[${terminal.id}] Logical ${terminal.operator} test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; break; } case "ternary": { value = `[${terminal.id}] Ternary test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; break; } case "optional": { value = `[${terminal.id}] Optional (optional=${terminal.optional}) test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; break; } case "throw": { value = `[${terminal.id}] Throw ${printPlace(terminal.value)}`; break; } case "return": { value = `[${terminal.id}] Return ${terminal.returnVariant}${terminal.value != null ? " " + printPlace(terminal.value) : ""}`; if (terminal.effects != null) { value += ` ${terminal.effects.map(printAliasingEffect).join("\n ")}`; } break; } case "goto": { value = `[${terminal.id}] Goto${terminal.variant === "Continue" /* Continue */ ? "(Continue)" : ""} bb${terminal.block}`; break; } case "switch": { const output = []; output.push(`[${terminal.id}] Switch (${printPlace(terminal.test)})`); terminal.cases.forEach((case_) => { if (case_.test !== null) { output.push(` Case ${printPlace(case_.test)}: bb${case_.block}`); } else { output.push(` Default: bb${case_.block}`); } }); if (terminal.fallthrough) { output.push(` Fallthrough: bb${terminal.fallthrough}`); } value = output; break; } case "do-while": { value = `[${terminal.id}] DoWhile loop=${`bb${terminal.loop}`} test=bb${terminal.test} fallthrough=${`bb${terminal.fallthrough}`}`; break; } case "while": { value = `[${terminal.id}] While test=bb${terminal.test} loop=${terminal.loop !== null ? `bb${terminal.loop}` : ""} fallthrough=${terminal.fallthrough ? `bb${terminal.fallthrough}` : ""}`; break; } case "for": { value = `[${terminal.id}] For init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} update=bb${terminal.update} fallthrough=bb${terminal.fallthrough}`; break; } case "for-of": { value = `[${terminal.id}] ForOf init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`; break; } case "for-in": { value = `[${terminal.id}] ForIn init=bb${terminal.init} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`; break; } case "label": { value = `[${terminal.id}] Label block=bb${terminal.block} fallthrough=${terminal.fallthrough ? `bb${terminal.fallthrough}` : ""}`; break; } case "sequence": { value = `[${terminal.id}] Sequence block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; break; } case "unreachable": { value = `[${terminal.id}] Unreachable`; break; } case "unsupported": { value = `[${terminal.id}] Unsupported`; break; } case "maybe-throw": { value = `[${terminal.id}] MaybeThrow continuation=bb${terminal.continuation} handler=bb${terminal.handler}`; if (terminal.effects != null) { value += ` ${terminal.effects.map(printAliasingEffect).join("\n ")}`; } break; } case "scope": { value = `[${terminal.id}] Scope ${printReactiveScopeSummary( terminal.scope )} block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; break; } case "pruned-scope": { value = `[${terminal.id}] Scope ${printReactiveScopeSummary( terminal.scope )} block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; break; } case "try": { value = `[${terminal.id}] Try block=bb${terminal.block} handler=bb${terminal.handler}${terminal.handlerBinding !== null ? ` handlerBinding=(${printPlace(terminal.handlerBinding)})` : ""} fallthrough=${terminal.fallthrough != null ? `bb${terminal.fallthrough}` : ""}`; break; } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal}\`` ); } } return value; } function printHole() { return ""; } function printObjectPropertyKey(key2) { switch (key2.kind) { case "identifier": return key2.name; case "string": return `"${key2.name}"`; case "computed": { return `[${printPlace(key2.name)}]`; } case "number": { return String(key2.name); } } } function printInstructionValue(instrValue) { var _a, _b, _c, _d, _e; let value = ""; switch (instrValue.kind) { case "ArrayExpression": { value = `Array [${instrValue.elements.map((element) => { if (element.kind === "Identifier") { return printPlace(element); } else if (element.kind === "Hole") { return printHole(); } else { return `...${printPlace(element.place)}`; } }).join(", ")}]`; break; } case "ObjectExpression": { const properties = []; if (instrValue.properties !== null) { for (const property of instrValue.properties) { if (property.kind === "ObjectProperty") { properties.push( `${printObjectPropertyKey(property.key)}: ${printPlace( property.place )}` ); } else { properties.push(`...${printPlace(property.place)}`); } } } value = `Object { ${properties.join(", ")} }`; break; } case "UnaryExpression": { value = `Unary ${printPlace(instrValue.value)}`; break; } case "BinaryExpression": { value = `Binary ${printPlace(instrValue.left)} ${instrValue.operator} ${printPlace(instrValue.right)}`; break; } case "NewExpression": { value = `New ${printPlace(instrValue.callee)}(${instrValue.args.map((arg) => printPattern(arg)).join(", ")})`; break; } case "CallExpression": { value = `Call ${printPlace(instrValue.callee)}(${instrValue.args.map((arg) => printPattern(arg)).join(", ")})`; break; } case "MethodCall": { value = `MethodCall ${printPlace(instrValue.receiver)}.${printPlace( instrValue.property )}(${instrValue.args.map((arg) => printPattern(arg)).join(", ")})`; break; } case "JSXText": { value = `JSXText ${JSON.stringify(instrValue.value)}`; break; } case "Primitive": { if (instrValue.value === void 0) { value = ""; } else { value = JSON.stringify(instrValue.value); } break; } case "TypeCastExpression": { value = `TypeCast ${printPlace(instrValue.value)}: ${printType( instrValue.type )}`; break; } case "JsxExpression": { const propItems = []; for (const attribute of instrValue.props) { if (attribute.kind === "JsxAttribute") { propItems.push( `${attribute.name}={${attribute.place !== null ? printPlace(attribute.place) : ""}}` ); } else { propItems.push(`...${printPlace(attribute.argument)}`); } } const tag = instrValue.tag.kind === "Identifier" ? printPlace(instrValue.tag) : instrValue.tag.name; const props = propItems.length !== 0 ? " " + propItems.join(" ") : ""; if (instrValue.children !== null) { const children = instrValue.children.map((child) => { return `{${printPlace(child)}}`; }); value = `JSX <${tag}${props}${props.length > 0 ? " " : ""}>${children.join("")}`; } else { value = `JSX <${tag}${props}${props.length > 0 ? " " : ""}/>`; } break; } case "JsxFragment": { value = `JsxFragment [${instrValue.children.map((child) => printPlace(child)).join(", ")}]`; break; } case "UnsupportedNode": { value = `UnsupportedNode ${instrValue.node.type}`; break; } case "LoadLocal": { value = `LoadLocal ${printPlace(instrValue.place)}`; break; } case "DeclareLocal": { value = `DeclareLocal ${instrValue.lvalue.kind} ${printPlace( instrValue.lvalue.place )}`; break; } case "DeclareContext": { value = `DeclareContext ${instrValue.lvalue.kind} ${printPlace( instrValue.lvalue.place )}`; break; } case "StoreLocal": { value = `StoreLocal ${instrValue.lvalue.kind} ${printPlace( instrValue.lvalue.place )} = ${printPlace(instrValue.value)}`; break; } case "LoadContext": { value = `LoadContext ${printPlace(instrValue.place)}`; break; } case "StoreContext": { value = `StoreContext ${instrValue.lvalue.kind} ${printPlace( instrValue.lvalue.place )} = ${printPlace(instrValue.value)}`; break; } case "Destructure": { value = `Destructure ${instrValue.lvalue.kind} ${printPattern( instrValue.lvalue.pattern )} = ${printPlace(instrValue.value)}`; break; } case "PropertyLoad": { value = `PropertyLoad ${printPlace(instrValue.object)}.${instrValue.property}`; break; } case "PropertyStore": { value = `PropertyStore ${printPlace(instrValue.object)}.${instrValue.property} = ${printPlace(instrValue.value)}`; break; } case "PropertyDelete": { value = `PropertyDelete ${printPlace(instrValue.object)}.${instrValue.property}`; break; } case "ComputedLoad": { value = `ComputedLoad ${printPlace(instrValue.object)}[${printPlace( instrValue.property )}]`; break; } case "ComputedStore": { value = `ComputedStore ${printPlace(instrValue.object)}[${printPlace( instrValue.property )}] = ${printPlace(instrValue.value)}`; break; } case "ComputedDelete": { value = `ComputedDelete ${printPlace(instrValue.object)}[${printPlace( instrValue.property )}]`; break; } case "ObjectMethod": case "FunctionExpression": { const kind = instrValue.kind === "FunctionExpression" ? "Function" : "ObjectMethod"; const name = getFunctionName(instrValue, ""); const fn = printFunction(instrValue.loweredFunc.func).split("\n").map((line2) => ` ${line2}`).join("\n"); const context = instrValue.loweredFunc.func.context.map((dep) => printPlace(dep)).join(","); const aliasingEffects = (_c = (_b = (_a = instrValue.loweredFunc.func.aliasingEffects) == null ? void 0 : _a.map(printAliasingEffect)) == null ? void 0 : _b.join(", ")) != null ? _c : ""; value = `${kind} ${name} @context[${context}] @aliasingEffects=[${aliasingEffects}] ${fn}`; break; } case "TaggedTemplateExpression": { value = `${printPlace(instrValue.tag)}\`${instrValue.value.raw}\``; break; } case "LogicalExpression": { value = `Logical ${printInstructionValue(instrValue.left)} ${instrValue.operator} ${printInstructionValue(instrValue.right)}`; break; } case "SequenceExpression": { value = [ `Sequence`, ...instrValue.instructions.map( (instr) => ` ${printInstruction(instr)}` ), ` ${printInstructionValue(instrValue.value)}` ].join("\n"); break; } case "ConditionalExpression": { value = `Ternary ${printInstructionValue( instrValue.test )} ? ${printInstructionValue( instrValue.consequent )} : ${printInstructionValue(instrValue.alternate)}`; break; } case "TemplateLiteral": { value = "`"; CompilerError.invariant( instrValue.subexprs.length === instrValue.quasis.length - 1, { reason: "Bad assumption about quasi length.", description: null, details: [ { kind: "error", loc: instrValue.loc, message: null } ], suggestions: null } ); for (let i = 0; i < instrValue.subexprs.length; i++) { value += instrValue.quasis[i].raw; value += `\${${printPlace(instrValue.subexprs[i])}}`; } value += instrValue.quasis.at(-1).raw + "`"; break; } case "LoadGlobal": { switch (instrValue.binding.kind) { case "Global": { value = `LoadGlobal(global) ${instrValue.binding.name}`; break; } case "ModuleLocal": { value = `LoadGlobal(module) ${instrValue.binding.name}`; break; } case "ImportDefault": { value = `LoadGlobal import ${instrValue.binding.name} from '${instrValue.binding.module}'`; break; } case "ImportNamespace": { value = `LoadGlobal import * as ${instrValue.binding.name} from '${instrValue.binding.module}'`; break; } case "ImportSpecifier": { if (instrValue.binding.imported !== instrValue.binding.name) { value = `LoadGlobal import { ${instrValue.binding.imported} as ${instrValue.binding.name} } from '${instrValue.binding.module}'`; } else { value = `LoadGlobal import { ${instrValue.binding.name} } from '${instrValue.binding.module}'`; } break; } default: { assertExhaustive( instrValue.binding, `Unexpected binding kind \`${instrValue.binding.kind}\`` ); } } break; } case "StoreGlobal": { value = `StoreGlobal ${instrValue.name} = ${printPlace( instrValue.value )}`; break; } case "OptionalExpression": { value = `OptionalExpression ${printInstructionValue(instrValue.value)}`; break; } case "RegExpLiteral": { value = `RegExp /${instrValue.pattern}/${instrValue.flags}`; break; } case "MetaProperty": { value = `MetaProperty ${instrValue.meta}.${instrValue.property}`; break; } case "Await": { value = `Await ${printPlace(instrValue.value)}`; break; } case "GetIterator": { value = `GetIterator collection=${printPlace(instrValue.collection)}`; break; } case "IteratorNext": { value = `IteratorNext iterator=${printPlace( instrValue.iterator )} collection=${printPlace(instrValue.collection)}`; break; } case "NextPropertyOf": { value = `NextPropertyOf ${printPlace(instrValue.value)}`; break; } case "Debugger": { value = `Debugger`; break; } case "PostfixUpdate": { value = `PostfixUpdate ${printPlace(instrValue.lvalue)} = ${printPlace( instrValue.value )} ${instrValue.operation}`; break; } case "PrefixUpdate": { value = `PrefixUpdate ${printPlace(instrValue.lvalue)} = ${instrValue.operation} ${printPlace(instrValue.value)}`; break; } case "StartMemoize": { value = `StartMemoize deps=${(_e = (_d = instrValue.deps) == null ? void 0 : _d.map((dep) => printManualMemoDependency(dep, false))) != null ? _e : "(none)"}`; break; } case "FinishMemoize": { value = `FinishMemoize decl=${printPlace(instrValue.decl)}${instrValue.pruned ? " pruned" : ""}`; break; } default: { assertExhaustive( instrValue, `Unexpected instruction kind '${instrValue.kind}'` ); } } return value; } function isMutable(range) { return range.end > range.start + 1; } var DEBUG_MUTABLE_RANGES = false; function printMutableRange(identifier4) { var _a, _b, _c; if (DEBUG_MUTABLE_RANGES) { const range2 = identifier4.mutableRange; const scopeRange = (_a = identifier4.scope) == null ? void 0 : _a.range; if (scopeRange != null && (scopeRange.start !== range2.start || scopeRange.end !== range2.end)) { return `[${range2.start}:${range2.end}] scope=[${scopeRange.start}:${scopeRange.end}]`; } return isMutable(range2) ? `[${range2.start}:${range2.end}]` : ""; } const range = (_c = (_b = identifier4.scope) == null ? void 0 : _b.range) != null ? _c : identifier4.mutableRange; return isMutable(range) ? `[${range.start}:${range.end}]` : ""; } function printPattern(pattern) { switch (pattern.kind) { case "ArrayPattern": { return "[ " + pattern.items.map((item) => { if (item.kind === "Hole") { return ""; } return printPattern(item); }).join(", ") + " ]"; } case "ObjectPattern": { return "{ " + pattern.properties.map((item) => { switch (item.kind) { case "ObjectProperty": { return `${printObjectPropertyKey(item.key)}: ${printPattern( item.place )}`; } case "Spread": { return printPattern(item); } default: { assertExhaustive(item, "Unexpected object property kind"); } } }).join(", ") + " }"; } case "Spread": { return `...${printPlace(pattern.place)}`; } case "Identifier": { return printPlace(pattern); } default: { assertExhaustive( pattern, `Unexpected pattern kind \`${pattern.kind}\`` ); } } } function printPlace(place) { const items = [ place.effect, " ", printIdentifier(place.identifier), printMutableRange(place.identifier), printType(place.identifier.type), place.reactive ? "{reactive}" : null ]; return items.filter((x) => x != null).join(""); } function printIdentifier(id) { return `${printName(id.name)}$${id.id}${printScope(id.scope)}`; } function printName(name) { if (name === null) { return ""; } return name.value; } function printScope(scope) { return `${scope !== null ? `_@${scope.id}` : ""}`; } function printManualMemoDependency(val, nameOnly) { var _a; let rootStr; if (val.root.kind === "Global") { rootStr = val.root.identifierName; } else { CompilerError.invariant(((_a = val.root.value.identifier.name) == null ? void 0 : _a.kind) === "named", { reason: "DepsValidation: expected named local variable in depslist", description: null, suggestions: null, details: [ { kind: "error", loc: val.root.value.loc, message: null } ] }); rootStr = nameOnly ? val.root.value.identifier.name.value : printIdentifier(val.root.value.identifier); } return `${rootStr}${val.path.map((v) => `${v.optional ? "?." : "."}${v.property}`).join("")}`; } function printType(type) { if (type.kind === "Type") return ""; if (type.kind === "Object" && type.shapeId != null) { return `:T${type.kind}<${type.shapeId}>`; } else if (type.kind === "Function" && type.shapeId != null) { const returnType = printType(type.return); return `:T${type.kind}<${type.shapeId}>()${returnType !== "" ? `: ${returnType}` : ""}`; } else { return `:T${type.kind}`; } } function printSourceLocation(loc) { if (typeof loc === "symbol") { return "generated"; } else { return `${loc.start.line}:${loc.start.column}:${loc.end.line}:${loc.end.column}`; } } function printSourceLocationLine(loc) { if (typeof loc === "symbol") { return "generated"; } else { return `${loc.start.line}:${loc.end.line}`; } } function getFunctionName(instrValue, defaultValue) { var _a; switch (instrValue.kind) { case "FunctionExpression": return (_a = instrValue.name) != null ? _a : defaultValue; case "ObjectMethod": return defaultValue; } } function printAliasingEffect(effect) { var _a; switch (effect.kind) { case "Assign": { return `Assign ${printPlaceForAliasEffect(effect.into)} = ${printPlaceForAliasEffect(effect.from)}`; } case "Alias": { return `Alias ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; } case "MaybeAlias": { return `MaybeAlias ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; } case "Capture": { return `Capture ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; } case "ImmutableCapture": { return `ImmutableCapture ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; } case "Create": { return `Create ${printPlaceForAliasEffect(effect.into)} = ${effect.value}`; } case "CreateFrom": { return `Create ${printPlaceForAliasEffect(effect.into)} = kindOf(${printPlaceForAliasEffect(effect.from)})`; } case "CreateFunction": { return `Function ${printPlaceForAliasEffect(effect.into)} = Function captures=[${effect.captures.map(printPlaceForAliasEffect).join(", ")}]`; } case "Apply": { const receiverCallee = effect.receiver.identifier.id === effect.function.identifier.id ? printPlaceForAliasEffect(effect.receiver) : `${printPlaceForAliasEffect(effect.receiver)}.${printPlaceForAliasEffect(effect.function)}`; const args = effect.args.map((arg) => { if (arg.kind === "Identifier") { return printPlaceForAliasEffect(arg); } else if (arg.kind === "Hole") { return " "; } return `...${printPlaceForAliasEffect(arg.place)}`; }).join(", "); let signature = ""; if (effect.signature != null) { if (effect.signature.aliasing != null) { signature = printAliasingSignature(effect.signature.aliasing); } else { signature = JSON.stringify(effect.signature, null, 2); } } return `Apply ${printPlaceForAliasEffect(effect.into)} = ${receiverCallee}(${args})${signature != "" ? "\n " : ""}${signature}`; } case "Freeze": { return `Freeze ${printPlaceForAliasEffect(effect.value)} ${effect.reason}`; } case "Mutate": case "MutateConditionally": case "MutateTransitive": case "MutateTransitiveConditionally": { return `${effect.kind} ${printPlaceForAliasEffect(effect.value)}${effect.kind === "Mutate" && ((_a = effect.reason) == null ? void 0 : _a.kind) === "AssignCurrentProperty" ? " (assign `.current`)" : ""}`; } case "MutateFrozen": { return `MutateFrozen ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; } case "MutateGlobal": { return `MutateGlobal ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; } case "Impure": { return `Impure ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; } case "Render": { return `Render ${printPlaceForAliasEffect(effect.place)}`; } default: { assertExhaustive(effect, `Unexpected kind '${effect.kind}'`); } } } function printPlaceForAliasEffect(place) { return printIdentifier(place.identifier); } function printAliasingSignature(signature) { const tokens = ["function "]; if (signature.temporaries.length !== 0) { tokens.push("<"); tokens.push( signature.temporaries.map((temp) => `$${temp.identifier.id}`).join(", ") ); tokens.push(">"); } tokens.push("("); tokens.push("this=$" + String(signature.receiver)); for (const param of signature.params) { tokens.push(", $" + String(param)); } if (signature.rest != null) { tokens.push(`, ...$${String(signature.rest)}`); } tokens.push("): "); tokens.push("$" + String(signature.returns) + ":"); for (const effect of signature.effects) { tokens.push("\n " + printAliasingEffect(effect)); } return tokens.join(""); } // src/HIR/visitors.ts function* eachInstructionLValue(instr) { if (instr.lvalue !== null) { yield instr.lvalue; } yield* __yieldStar(eachInstructionValueLValue(instr.value)); } function* eachInstructionValueLValue(value) { switch (value.kind) { case "DeclareContext": case "StoreContext": case "DeclareLocal": case "StoreLocal": { yield value.lvalue.place; break; } case "Destructure": { yield* __yieldStar(eachPatternOperand(value.lvalue.pattern)); break; } case "PostfixUpdate": case "PrefixUpdate": { yield value.lvalue; break; } } } function* eachInstructionOperand(instr) { yield* __yieldStar(eachInstructionValueOperand(instr.value)); } function* eachInstructionValueOperand(instrValue) { switch (instrValue.kind) { case "NewExpression": case "CallExpression": { yield instrValue.callee; yield* __yieldStar(eachCallArgument(instrValue.args)); break; } case "BinaryExpression": { yield instrValue.left; yield instrValue.right; break; } case "MethodCall": { yield instrValue.receiver; yield instrValue.property; yield* __yieldStar(eachCallArgument(instrValue.args)); break; } case "DeclareContext": case "DeclareLocal": { break; } case "LoadLocal": case "LoadContext": { yield instrValue.place; break; } case "StoreLocal": { yield instrValue.value; break; } case "StoreContext": { yield instrValue.lvalue.place; yield instrValue.value; break; } case "StoreGlobal": { yield instrValue.value; break; } case "Destructure": { yield instrValue.value; break; } case "PropertyLoad": { yield instrValue.object; break; } case "PropertyDelete": { yield instrValue.object; break; } case "PropertyStore": { yield instrValue.object; yield instrValue.value; break; } case "ComputedLoad": { yield instrValue.object; yield instrValue.property; break; } case "ComputedDelete": { yield instrValue.object; yield instrValue.property; break; } case "ComputedStore": { yield instrValue.object; yield instrValue.property; yield instrValue.value; break; } case "UnaryExpression": { yield instrValue.value; break; } case "JsxExpression": { if (instrValue.tag.kind === "Identifier") { yield instrValue.tag; } for (const attribute of instrValue.props) { switch (attribute.kind) { case "JsxAttribute": { yield attribute.place; break; } case "JsxSpreadAttribute": { yield attribute.argument; break; } default: { assertExhaustive( attribute, `Unexpected attribute kind \`${attribute.kind}\`` ); } } } if (instrValue.children) { yield* __yieldStar(instrValue.children); } break; } case "JsxFragment": { yield* __yieldStar(instrValue.children); break; } case "ObjectExpression": { for (const property of instrValue.properties) { if (property.kind === "ObjectProperty" && property.key.kind === "computed") { yield property.key.name; } yield property.place; } break; } case "ArrayExpression": { for (const element of instrValue.elements) { if (element.kind === "Identifier") { yield element; } else if (element.kind === "Spread") { yield element.place; } } break; } case "ObjectMethod": case "FunctionExpression": { yield* __yieldStar(instrValue.loweredFunc.func.context); break; } case "TaggedTemplateExpression": { yield instrValue.tag; break; } case "TypeCastExpression": { yield instrValue.value; break; } case "TemplateLiteral": { yield* __yieldStar(instrValue.subexprs); break; } case "Await": { yield instrValue.value; break; } case "GetIterator": { yield instrValue.collection; break; } case "IteratorNext": { yield instrValue.iterator; yield instrValue.collection; break; } case "NextPropertyOf": { yield instrValue.value; break; } case "PostfixUpdate": case "PrefixUpdate": { yield instrValue.value; break; } case "StartMemoize": { if (instrValue.deps != null) { for (const dep of instrValue.deps) { if (dep.root.kind === "NamedLocal") { yield dep.root.value; } } } break; } case "FinishMemoize": { yield instrValue.decl; break; } case "Debugger": case "RegExpLiteral": case "MetaProperty": case "LoadGlobal": case "UnsupportedNode": case "Primitive": case "JSXText": { break; } default: { assertExhaustive( instrValue, `Unexpected instruction kind \`${instrValue.kind}\`` ); } } } function* eachCallArgument(args) { for (const arg of args) { if (arg.kind === "Identifier") { yield arg; } else { yield arg.place; } } } function doesPatternContainSpreadElement(pattern) { switch (pattern.kind) { case "ArrayPattern": { for (const item of pattern.items) { if (item.kind === "Spread") { return true; } } break; } case "ObjectPattern": { for (const property of pattern.properties) { if (property.kind === "Spread") { return true; } } break; } default: { assertExhaustive( pattern, `Unexpected pattern kind \`${pattern.kind}\`` ); } } return false; } function* eachPatternOperand(pattern) { switch (pattern.kind) { case "ArrayPattern": { for (const item of pattern.items) { if (item.kind === "Identifier") { yield item; } else if (item.kind === "Spread") { yield item.place; } else if (item.kind === "Hole") { continue; } else { assertExhaustive( item, `Unexpected item kind \`${item.kind}\`` ); } } break; } case "ObjectPattern": { for (const property of pattern.properties) { if (property.kind === "ObjectProperty") { yield property.place; } else if (property.kind === "Spread") { yield property.place; } else { assertExhaustive( property, `Unexpected item kind \`${property.kind}\`` ); } } break; } default: { assertExhaustive( pattern, `Unexpected pattern kind \`${pattern.kind}\`` ); } } } function* eachPatternItem(pattern) { switch (pattern.kind) { case "ArrayPattern": { for (const item of pattern.items) { if (item.kind === "Identifier") { yield item; } else if (item.kind === "Spread") { yield item; } else if (item.kind === "Hole") { continue; } else { assertExhaustive( item, `Unexpected item kind \`${item.kind}\`` ); } } break; } case "ObjectPattern": { for (const property of pattern.properties) { if (property.kind === "ObjectProperty") { yield property.place; } else if (property.kind === "Spread") { yield property; } else { assertExhaustive( property, `Unexpected item kind \`${property.kind}\`` ); } } break; } default: { assertExhaustive( pattern, `Unexpected pattern kind \`${pattern.kind}\`` ); } } } function mapInstructionLValues(instr, fn) { switch (instr.value.kind) { case "DeclareLocal": case "StoreLocal": { const lvalue = instr.value.lvalue; lvalue.place = fn(lvalue.place); break; } case "Destructure": { mapPatternOperands(instr.value.lvalue.pattern, fn); break; } case "PostfixUpdate": case "PrefixUpdate": { instr.value.lvalue = fn(instr.value.lvalue); break; } } if (instr.lvalue !== null) { instr.lvalue = fn(instr.lvalue); } } function mapInstructionOperands(instr, fn) { mapInstructionValueOperands(instr.value, fn); } function mapInstructionValueOperands(instrValue, fn) { switch (instrValue.kind) { case "BinaryExpression": { instrValue.left = fn(instrValue.left); instrValue.right = fn(instrValue.right); break; } case "PropertyLoad": { instrValue.object = fn(instrValue.object); break; } case "PropertyDelete": { instrValue.object = fn(instrValue.object); break; } case "PropertyStore": { instrValue.object = fn(instrValue.object); instrValue.value = fn(instrValue.value); break; } case "ComputedLoad": { instrValue.object = fn(instrValue.object); instrValue.property = fn(instrValue.property); break; } case "ComputedDelete": { instrValue.object = fn(instrValue.object); instrValue.property = fn(instrValue.property); break; } case "ComputedStore": { instrValue.object = fn(instrValue.object); instrValue.property = fn(instrValue.property); instrValue.value = fn(instrValue.value); break; } case "DeclareContext": case "DeclareLocal": { break; } case "LoadLocal": case "LoadContext": { instrValue.place = fn(instrValue.place); break; } case "StoreLocal": { instrValue.value = fn(instrValue.value); break; } case "StoreContext": { instrValue.lvalue.place = fn(instrValue.lvalue.place); instrValue.value = fn(instrValue.value); break; } case "StoreGlobal": { instrValue.value = fn(instrValue.value); break; } case "Destructure": { instrValue.value = fn(instrValue.value); break; } case "NewExpression": case "CallExpression": { instrValue.callee = fn(instrValue.callee); instrValue.args = mapCallArguments(instrValue.args, fn); break; } case "MethodCall": { instrValue.receiver = fn(instrValue.receiver); instrValue.property = fn(instrValue.property); instrValue.args = mapCallArguments(instrValue.args, fn); break; } case "UnaryExpression": { instrValue.value = fn(instrValue.value); break; } case "JsxExpression": { if (instrValue.tag.kind === "Identifier") { instrValue.tag = fn(instrValue.tag); } for (const attribute of instrValue.props) { switch (attribute.kind) { case "JsxAttribute": { attribute.place = fn(attribute.place); break; } case "JsxSpreadAttribute": { attribute.argument = fn(attribute.argument); break; } default: { assertExhaustive( attribute, `Unexpected attribute kind \`${attribute.kind}\`` ); } } } if (instrValue.children) { instrValue.children = instrValue.children.map((p) => fn(p)); } break; } case "ObjectExpression": { for (const property of instrValue.properties) { if (property.kind === "ObjectProperty" && property.key.kind === "computed") { property.key.name = fn(property.key.name); } property.place = fn(property.place); } break; } case "ArrayExpression": { instrValue.elements = instrValue.elements.map((element) => { if (element.kind === "Identifier") { return fn(element); } else if (element.kind === "Spread") { element.place = fn(element.place); return element; } else { return element; } }); break; } case "JsxFragment": { instrValue.children = instrValue.children.map((e) => fn(e)); break; } case "ObjectMethod": case "FunctionExpression": { instrValue.loweredFunc.func.context = instrValue.loweredFunc.func.context.map((d) => fn(d)); break; } case "TaggedTemplateExpression": { instrValue.tag = fn(instrValue.tag); break; } case "TypeCastExpression": { instrValue.value = fn(instrValue.value); break; } case "TemplateLiteral": { instrValue.subexprs = instrValue.subexprs.map(fn); break; } case "Await": { instrValue.value = fn(instrValue.value); break; } case "GetIterator": { instrValue.collection = fn(instrValue.collection); break; } case "IteratorNext": { instrValue.iterator = fn(instrValue.iterator); instrValue.collection = fn(instrValue.collection); break; } case "NextPropertyOf": { instrValue.value = fn(instrValue.value); break; } case "PostfixUpdate": case "PrefixUpdate": { instrValue.value = fn(instrValue.value); break; } case "StartMemoize": { if (instrValue.deps != null) { for (const dep of instrValue.deps) { if (dep.root.kind === "NamedLocal") { dep.root.value = fn(dep.root.value); } } } break; } case "FinishMemoize": { instrValue.decl = fn(instrValue.decl); break; } case "Debugger": case "RegExpLiteral": case "MetaProperty": case "LoadGlobal": case "UnsupportedNode": case "Primitive": case "JSXText": { break; } default: { assertExhaustive(instrValue, "Unexpected instruction kind"); } } } function mapCallArguments(args, fn) { return args.map((arg) => { if (arg.kind === "Identifier") { return fn(arg); } else { arg.place = fn(arg.place); return arg; } }); } function mapPatternOperands(pattern, fn) { switch (pattern.kind) { case "ArrayPattern": { pattern.items = pattern.items.map((item) => { if (item.kind === "Identifier") { return fn(item); } else if (item.kind === "Spread") { item.place = fn(item.place); return item; } else { return item; } }); break; } case "ObjectPattern": { for (const property of pattern.properties) { property.place = fn(property.place); } break; } default: { assertExhaustive( pattern, `Unexpected pattern kind \`${pattern.kind}\`` ); } } } function mapTerminalSuccessors(terminal, fn) { switch (terminal.kind) { case "goto": { const target = fn(terminal.block); return { kind: "goto", block: target, variant: terminal.variant, id: makeInstructionId(0), loc: terminal.loc }; } case "if": { const consequent = fn(terminal.consequent); const alternate = fn(terminal.alternate); const fallthrough = fn(terminal.fallthrough); return { kind: "if", test: terminal.test, consequent, alternate, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "branch": { const consequent = fn(terminal.consequent); const alternate = fn(terminal.alternate); const fallthrough = fn(terminal.fallthrough); return { kind: "branch", test: terminal.test, consequent, alternate, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "switch": { const cases = terminal.cases.map((case_) => { const target = fn(case_.block); return { test: case_.test, block: target }; }); const fallthrough = fn(terminal.fallthrough); return { kind: "switch", test: terminal.test, cases, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "logical": { const test = fn(terminal.test); const fallthrough = fn(terminal.fallthrough); return { kind: "logical", test, fallthrough, operator: terminal.operator, id: makeInstructionId(0), loc: terminal.loc }; } case "ternary": { const test = fn(terminal.test); const fallthrough = fn(terminal.fallthrough); return { kind: "ternary", test, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "optional": { const test = fn(terminal.test); const fallthrough = fn(terminal.fallthrough); return { kind: "optional", optional: terminal.optional, test, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "return": { return { kind: "return", returnVariant: terminal.returnVariant, loc: terminal.loc, value: terminal.value, id: makeInstructionId(0), effects: terminal.effects }; } case "throw": { return terminal; } case "do-while": { const loop = fn(terminal.loop); const test = fn(terminal.test); const fallthrough = fn(terminal.fallthrough); return { kind: "do-while", loc: terminal.loc, test, loop, fallthrough, id: makeInstructionId(0) }; } case "while": { const test = fn(terminal.test); const loop = fn(terminal.loop); const fallthrough = fn(terminal.fallthrough); return { kind: "while", loc: terminal.loc, test, loop, fallthrough, id: makeInstructionId(0) }; } case "for": { const init = fn(terminal.init); const test = fn(terminal.test); const update2 = terminal.update !== null ? fn(terminal.update) : null; const loop = fn(terminal.loop); const fallthrough = fn(terminal.fallthrough); return { kind: "for", loc: terminal.loc, init, test, update: update2, loop, fallthrough, id: makeInstructionId(0) }; } case "for-of": { const init = fn(terminal.init); const loop = fn(terminal.loop); const test = fn(terminal.test); const fallthrough = fn(terminal.fallthrough); return { kind: "for-of", loc: terminal.loc, init, test, loop, fallthrough, id: makeInstructionId(0) }; } case "for-in": { const init = fn(terminal.init); const loop = fn(terminal.loop); const fallthrough = fn(terminal.fallthrough); return { kind: "for-in", loc: terminal.loc, init, loop, fallthrough, id: makeInstructionId(0) }; } case "label": { const block = fn(terminal.block); const fallthrough = fn(terminal.fallthrough); return { kind: "label", block, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "sequence": { const block = fn(terminal.block); const fallthrough = fn(terminal.fallthrough); return { kind: "sequence", block, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "maybe-throw": { const continuation = fn(terminal.continuation); const handler = fn(terminal.handler); return { kind: "maybe-throw", continuation, handler, id: makeInstructionId(0), loc: terminal.loc, effects: terminal.effects }; } case "try": { const block = fn(terminal.block); const handler = fn(terminal.handler); const fallthrough = fn(terminal.fallthrough); return { kind: "try", block, handlerBinding: terminal.handlerBinding, handler, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "scope": case "pruned-scope": { const block = fn(terminal.block); const fallthrough = fn(terminal.fallthrough); return { kind: terminal.kind, scope: terminal.scope, block, fallthrough, id: makeInstructionId(0), loc: terminal.loc }; } case "unreachable": case "unsupported": { return terminal; } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } function terminalHasFallthrough(terminal) { switch (terminal.kind) { case "maybe-throw": case "goto": case "return": case "throw": case "unreachable": case "unsupported": { const _ = terminal.fallthrough; return false; } case "branch": case "try": case "do-while": case "for-of": case "for-in": case "for": case "if": case "label": case "logical": case "optional": case "sequence": case "switch": case "ternary": case "while": case "scope": case "pruned-scope": { const _ = terminal.fallthrough; return true; } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } function terminalFallthrough(terminal) { if (terminalHasFallthrough(terminal)) { return terminal.fallthrough; } else { return null; } } function* eachTerminalSuccessor(terminal) { switch (terminal.kind) { case "goto": { yield terminal.block; break; } case "if": { yield terminal.consequent; yield terminal.alternate; break; } case "branch": { yield terminal.consequent; yield terminal.alternate; break; } case "switch": { for (const case_ of terminal.cases) { yield case_.block; } break; } case "optional": case "ternary": case "logical": { yield terminal.test; break; } case "return": { break; } case "throw": { break; } case "do-while": { yield terminal.loop; break; } case "while": { yield terminal.test; break; } case "for": { yield terminal.init; break; } case "for-of": { yield terminal.init; break; } case "for-in": { yield terminal.init; break; } case "label": { yield terminal.block; break; } case "sequence": { yield terminal.block; break; } case "maybe-throw": { yield terminal.continuation; yield terminal.handler; break; } case "try": { yield terminal.block; break; } case "scope": case "pruned-scope": { yield terminal.block; break; } case "unreachable": case "unsupported": break; default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } function mapTerminalOperands(terminal, fn) { switch (terminal.kind) { case "if": { terminal.test = fn(terminal.test); break; } case "branch": { terminal.test = fn(terminal.test); break; } case "switch": { terminal.test = fn(terminal.test); for (const case_ of terminal.cases) { if (case_.test === null) { continue; } case_.test = fn(case_.test); } break; } case "return": case "throw": { terminal.value = fn(terminal.value); break; } case "try": { if (terminal.handlerBinding !== null) { terminal.handlerBinding = fn(terminal.handlerBinding); } else { terminal.handlerBinding = null; } break; } case "maybe-throw": case "sequence": case "label": case "optional": case "ternary": case "logical": case "do-while": case "while": case "for": case "for-of": case "for-in": case "goto": case "unreachable": case "unsupported": case "scope": case "pruned-scope": { break; } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } function* eachTerminalOperand(terminal) { switch (terminal.kind) { case "if": { yield terminal.test; break; } case "branch": { yield terminal.test; break; } case "switch": { yield terminal.test; for (const case_ of terminal.cases) { if (case_.test === null) { continue; } yield case_.test; } break; } case "return": case "throw": { yield terminal.value; break; } case "try": { if (terminal.handlerBinding !== null) { yield terminal.handlerBinding; } break; } case "maybe-throw": case "sequence": case "label": case "optional": case "ternary": case "logical": case "do-while": case "while": case "for": case "for-of": case "for-in": case "goto": case "unreachable": case "unsupported": case "scope": case "pruned-scope": { break; } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } var _activeScopes; var ScopeBlockTraversal = class { constructor() { // Live stack of active scopes __privateAdd(this, _activeScopes, []); this.blockInfos = /* @__PURE__ */ new Map(); } recordScopes(block) { var _a, _b; const blockInfo = this.blockInfos.get(block.id); if ((blockInfo == null ? void 0 : blockInfo.kind) === "begin") { __privateGet(this, _activeScopes).push(blockInfo.scope.id); } else if ((blockInfo == null ? void 0 : blockInfo.kind) === "end") { const top = __privateGet(this, _activeScopes).at(-1); CompilerError.invariant(blockInfo.scope.id === top, { reason: "Expected traversed block fallthrough to match top-most active scope", description: null, details: [ { kind: "error", loc: (_b = (_a = block.instructions[0]) == null ? void 0 : _a.loc) != null ? _b : block.terminal.id, message: null } ] }); __privateGet(this, _activeScopes).pop(); } if (block.terminal.kind === "scope" || block.terminal.kind === "pruned-scope") { CompilerError.invariant( !this.blockInfos.has(block.terminal.block) && !this.blockInfos.has(block.terminal.fallthrough), { reason: "Expected unique scope blocks and fallthroughs", description: null, details: [ { kind: "error", loc: block.terminal.loc, message: null } ] } ); this.blockInfos.set(block.terminal.block, { kind: "begin", scope: block.terminal.scope, pruned: block.terminal.kind === "pruned-scope", fallthrough: block.terminal.fallthrough }); this.blockInfos.set(block.terminal.fallthrough, { kind: "end", scope: block.terminal.scope, pruned: block.terminal.kind === "pruned-scope" }); } } /** * @returns if the given scope is currently 'active', i.e. if the scope start * block but not the scope fallthrough has been recorded. */ isScopeActive(scopeId) { return __privateGet(this, _activeScopes).indexOf(scopeId) !== -1; } /** * The current, innermost active scope. */ get currentScope() { var _a; return (_a = __privateGet(this, _activeScopes).at(-1)) != null ? _a : null; } }; _activeScopes = new WeakMap(); // src/HIR/AssertConsistentIdentifiers.ts function assertConsistentIdentifiers(fn) { const identifiers = /* @__PURE__ */ new Map(); const assignments = /* @__PURE__ */ new Set(); for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { validate(identifiers, phi.place.identifier); for (const [, operand] of phi.operands) { validate(identifiers, operand.identifier); } } for (const instr of block.instructions) { CompilerError.invariant(instr.lvalue.identifier.name === null, { reason: `Expected all lvalues to be temporaries`, description: `Found named lvalue \`${instr.lvalue.identifier.name}\``, details: [ { kind: "error", loc: instr.lvalue.loc, message: null } ], suggestions: null }); CompilerError.invariant(!assignments.has(instr.lvalue.identifier.id), { reason: `Expected lvalues to be assigned exactly once`, description: `Found duplicate assignment of '${printPlace( instr.lvalue )}'`, details: [ { kind: "error", loc: instr.lvalue.loc, message: null } ], suggestions: null }); assignments.add(instr.lvalue.identifier.id); for (const operand of eachInstructionLValue(instr)) { validate(identifiers, operand.identifier, operand.loc); } for (const operand of eachInstructionValueOperand(instr.value)) { validate(identifiers, operand.identifier, operand.loc); } } for (const operand of eachTerminalOperand(block.terminal)) { validate(identifiers, operand.identifier, operand.loc); } } } function validate(identifiers, identifier4, loc = null) { const previous = identifiers.get(identifier4.id); if (previous === void 0) { identifiers.set(identifier4.id, identifier4); } else { CompilerError.invariant(identifier4 === previous, { reason: `Duplicate identifier object`, description: `Found duplicate identifier object for id ${identifier4.id}`, details: [ { kind: "error", loc: loc != null ? loc : GeneratedSource, message: null } ], suggestions: null }); } } // src/HIR/AssertTerminalBlocksExist.ts function assertTerminalSuccessorsExist(fn) { for (const [, block] of fn.body.blocks) { mapTerminalSuccessors(block.terminal, (successor) => { var _a; CompilerError.invariant(fn.body.blocks.has(successor), { reason: `Terminal successor references unknown block`, description: `Block bb${successor} does not exist for terminal '${printTerminal( block.terminal )}'`, details: [ { kind: "error", loc: (_a = block.terminal.loc) != null ? _a : GeneratedSource, message: null } ], suggestions: null }); return successor; }); } } function assertTerminalPredsExist(fn) { for (const [, block] of fn.body.blocks) { for (const pred of block.preds) { const predBlock = fn.body.blocks.get(pred); CompilerError.invariant(predBlock != null, { reason: "Expected predecessor block to exist", description: `Block ${block.id} references non-existent ${pred}`, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); CompilerError.invariant( [...eachTerminalSuccessor(predBlock.terminal)].includes(block.id), { reason: "Terminal successor does not reference correct predecessor", description: `Block bb${block.id} has bb${predBlock.id} as a predecessor, but bb${predBlock.id}'s successors do not include bb${block.id}`, details: [ { kind: "error", loc: GeneratedSource, message: null } ] } ); } } } // src/HIR/AssertValidBlockNesting.ts function getScopes(fn) { const scopes = /* @__PURE__ */ new Set(); function visitPlace2(place) { const scope = place.identifier.scope; if (scope != null) { if (scope.range.start !== scope.range.end) { scopes.add(scope); } } } for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { for (const operand of eachInstructionLValue(instr)) { visitPlace2(operand); } for (const operand of eachInstructionOperand(instr)) { visitPlace2(operand); } } for (const operand of eachTerminalOperand(block.terminal)) { visitPlace2(operand); } } return scopes; } function rangePreOrderComparator(a, b) { const startDiff = a.start - b.start; if (startDiff !== 0) return startDiff; return b.end - a.end; } function recursivelyTraverseItems(items, getRange, context, enter, exit) { items.sort((a, b) => rangePreOrderComparator(getRange(a), getRange(b))); let activeItems = []; const ranges = items.map(getRange); for (let i = 0; i < items.length; i++) { const curr2 = items[i]; const currRange = ranges[i]; for (let i2 = activeItems.length - 1; i2 >= 0; i2--) { const maybeParent = activeItems[i2]; const maybeParentRange = getRange(maybeParent); const disjoint = currRange.start >= maybeParentRange.end; const nested = currRange.end <= maybeParentRange.end; CompilerError.invariant(disjoint || nested, { reason: "Invalid nesting in program blocks or scopes", description: `Items overlap but are not nested: ${maybeParentRange.start}:${maybeParentRange.end}(${currRange.start}:${currRange.end})`, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); if (disjoint) { exit(maybeParent, context); activeItems.length = i2; } else { break; } } enter(curr2, context); activeItems.push(curr2); } let curr = activeItems.pop(); while (curr != null) { exit(curr, context); curr = activeItems.pop(); } } var no_op = () => { }; function assertValidBlockNesting(fn) { var _a, _b; const scopes = getScopes(fn); const blocks = [...scopes].map((scope) => __spreadValues({ kind: "Scope", id: scope.id }, scope.range)); for (const [, block] of fn.body.blocks) { const fallthroughId = terminalFallthrough(block.terminal); if (fallthroughId != null) { const fallthrough = fn.body.blocks.get(fallthroughId); const end = (_b = (_a = fallthrough.instructions[0]) == null ? void 0 : _a.id) != null ? _b : fallthrough.terminal.id; blocks.push({ kind: "ProgramBlockSubtree", id: block.id, start: block.terminal.id, end }); } } recursivelyTraverseItems(blocks, (block) => block, null, no_op, no_op); } // src/HIR/AssertValidMutableRanges.ts function assertValidMutableRanges(fn) { for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { visit(phi.place, `phi for block bb${block.id}`); for (const [pred, operand] of phi.operands) { visit(operand, `phi predecessor bb${pred} for block bb${block.id}`); } } for (const instr of block.instructions) { for (const operand of eachInstructionLValue(instr)) { visit(operand, `instruction [${instr.id}]`); } for (const operand of eachInstructionOperand(instr)) { visit(operand, `instruction [${instr.id}]`); } } for (const operand of eachTerminalOperand(block.terminal)) { visit(operand, `terminal [${block.terminal.id}]`); } } } function visit(place, description) { validateMutableRange(place, place.identifier.mutableRange, description); if (place.identifier.scope !== null) { validateMutableRange(place, place.identifier.scope.range, description); } } function validateMutableRange(place, range, description) { CompilerError.invariant( range.start === 0 && range.end === 0 || range.end > range.start, { reason: `Invalid mutable range: [${range.start}:${range.end}]`, description: `${printPlace(place)} in ${description}`, details: [ { kind: "error", loc: place.loc, message: null } ] } ); } // src/HIR/BuildHIR.ts var import_invariant2 = __toESM(require_invariant()); // src/HIR/HIRBuilder.ts function newBlock(id, kind) { return { id, kind, instructions: [] }; } var _completed, _current, _entry, _scopes, _context, _bindings, _env, _exceptionHandlerStack, _HIRBuilder_instances, resolveBabelBinding_fn; var HIRBuilder = class { constructor(env, options) { __privateAdd(this, _HIRBuilder_instances); __privateAdd(this, _completed, /* @__PURE__ */ new Map()); __privateAdd(this, _current); __privateAdd(this, _entry); __privateAdd(this, _scopes, []); __privateAdd(this, _context); __privateAdd(this, _bindings); __privateAdd(this, _env); __privateAdd(this, _exceptionHandlerStack, []); this.errors = new CompilerError(); /** * Traversal context: counts the number of `fbt` tag parents * of the current babel node. */ this.fbtDepth = 0; var _a, _b, _c; __privateSet(this, _env, env); __privateSet(this, _bindings, (_a = options == null ? void 0 : options.bindings) != null ? _a : /* @__PURE__ */ new Map()); __privateSet(this, _context, (_b = options == null ? void 0 : options.context) != null ? _b : /* @__PURE__ */ new Map()); __privateSet(this, _entry, makeBlockId(env.nextBlockId)); __privateSet(this, _current, newBlock(__privateGet(this, _entry), (_c = options == null ? void 0 : options.entryBlockKind) != null ? _c : "block")); } get nextIdentifierId() { return __privateGet(this, _env).nextIdentifierId; } get context() { return __privateGet(this, _context); } get bindings() { return __privateGet(this, _bindings); } get environment() { return __privateGet(this, _env); } currentBlockKind() { return __privateGet(this, _current).kind; } // Push a statement or expression onto the current block push(instruction) { __privateGet(this, _current).instructions.push(instruction); const exceptionHandler = __privateGet(this, _exceptionHandlerStack).at(-1); if (exceptionHandler !== void 0) { const continuationBlock = this.reserve(this.currentBlockKind()); this.terminateWithContinuation( { kind: "maybe-throw", continuation: continuationBlock.id, handler: exceptionHandler, id: makeInstructionId(0), loc: instruction.loc, effects: null }, continuationBlock ); } } enterTryCatch(handler, fn) { __privateGet(this, _exceptionHandlerStack).push(handler); fn(); __privateGet(this, _exceptionHandlerStack).pop(); } resolveThrowHandler() { const handler = __privateGet(this, _exceptionHandlerStack).at(-1); return handler != null ? handler : null; } makeTemporary(loc) { const id = this.nextIdentifierId; return makeTemporaryIdentifier(id, loc); } /* * Maps an Identifier (or JSX identifier) Babel node to an internal `Identifier` * which represents the variable being referenced, according to the JS scoping rules. * * Because Forget does not preserve _all_ block scopes in the input (only those that * happen to occur from control flow), this resolution ensures that different variables * with the same name are mapped to a unique name. Concretely, this function maintains * the invariant that all references to a given variable will return an `Identifier` * with the same (unique for the function) `name` and `id`. * * Example: * * ```javascript * function foo() { * const x = 0; * { * const x = 1; * } * return x; * } * ``` * * The above converts as follows: * * ``` * Const Identifier { name: 'x', id: 0 } = Primitive { value: 0 }; * Const Identifier { name: 'x_0', id: 1 } = Primitive { value: 1 }; * Return Identifier { name: 'x', id: 0}; * ``` */ resolveIdentifier(path) { const originalName = path.node.name; const babelBinding = __privateMethod(this, _HIRBuilder_instances, resolveBabelBinding_fn).call(this, path); if (babelBinding == null) { return { kind: "Global", name: originalName }; } const outerBinding = __privateGet(this, _env).parentFunction.scope.parent.getBinding(originalName); if (babelBinding === outerBinding) { const path2 = babelBinding.path; if (path2.isImportDefaultSpecifier()) { const importDeclaration2 = path2.parentPath; return { kind: "ImportDefault", name: originalName, module: importDeclaration2.node.source.value }; } else if (path2.isImportSpecifier()) { const importDeclaration2 = path2.parentPath; return { kind: "ImportSpecifier", name: originalName, module: importDeclaration2.node.source.value, imported: path2.node.imported.type === "Identifier" ? path2.node.imported.name : path2.node.imported.value }; } else if (path2.isImportNamespaceSpecifier()) { const importDeclaration2 = path2.parentPath; return { kind: "ImportNamespace", name: originalName, module: importDeclaration2.node.source.value }; } else { return { kind: "ModuleLocal", name: originalName }; } } const resolvedBinding = this.resolveBinding(babelBinding.identifier); if (resolvedBinding.name && resolvedBinding.name.value !== originalName) { babelBinding.scope.rename(originalName, resolvedBinding.name.value); } return { kind: "Identifier", identifier: resolvedBinding, bindingKind: babelBinding.kind }; } isContextIdentifier(path) { const binding = __privateMethod(this, _HIRBuilder_instances, resolveBabelBinding_fn).call(this, path); if (binding) { const outerBinding = __privateGet(this, _env).parentFunction.scope.parent.getBinding( path.node.name ); if (binding === outerBinding) { return false; } return __privateGet(this, _env).isContextIdentifier(binding.identifier); } else { return false; } } resolveBinding(node) { var _a, _b, _c; if (node.name === "fbt") { CompilerError.throwDiagnostic({ category: "Todo" /* Todo */, reason: "Support local variables named `fbt`", description: "Local variables named `fbt` may conflict with the fbt plugin and are not yet supported", details: [ { kind: "error", message: "Rename to avoid conflict with fbt plugin", loc: (_a = node.loc) != null ? _a : GeneratedSource } ] }); } if (node.name === "this") { CompilerError.throwDiagnostic({ category: "UnsupportedSyntax" /* UnsupportedSyntax */, reason: "`this` is not supported syntax", description: "React Compiler does not support compiling functions that use `this`", details: [ { kind: "error", message: "`this` was used here", loc: (_b = node.loc) != null ? _b : GeneratedSource } ] }); } const originalName = node.name; let name = originalName; let index = 0; while (true) { const mapping = __privateGet(this, _bindings).get(name); if (mapping === void 0) { const id = this.nextIdentifierId; const identifier4 = { id, declarationId: makeDeclarationId(id), name: makeIdentifierName(name), mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, scope: null, type: makeType(), loc: (_c = node.loc) != null ? _c : GeneratedSource }; __privateGet(this, _env).programContext.addNewReference(name); __privateGet(this, _bindings).set(name, { node, identifier: identifier4 }); return identifier4; } else if (mapping.node === node) { return mapping.identifier; } else { name = `${originalName}_${index++}`; } } } // Construct a final CFG from this context build() { var _a, _b; let ir = { blocks: __privateGet(this, _completed), entry: __privateGet(this, _entry) }; const rpoBlocks = getReversePostorderedBlocks(ir); for (const [id, block] of ir.blocks) { if (!rpoBlocks.has(id) && block.instructions.some( (instr) => instr.value.kind === "FunctionExpression" )) { CompilerError.throwTodo({ reason: `Support functions with unreachable code that may contain hoisted declarations`, loc: (_b = (_a = block.instructions[0]) == null ? void 0 : _a.loc) != null ? _b : block.terminal.loc, description: null, suggestions: null }); } } ir.blocks = rpoBlocks; removeUnreachableForUpdates(ir); removeDeadDoWhileStatements(ir); removeUnnecessaryTryCatch(ir); markInstructionIds(ir); markPredecessors(ir); return ir; } // Terminate the current block w the given terminal, and start a new block terminate(terminal, nextBlockKind) { const { id: blockId, kind, instructions } = __privateGet(this, _current); __privateGet(this, _completed).set(blockId, { kind, id: blockId, instructions, terminal, preds: /* @__PURE__ */ new Set(), phis: /* @__PURE__ */ new Set() }); if (nextBlockKind) { const nextId = __privateGet(this, _env).nextBlockId; __privateSet(this, _current, newBlock(nextId, nextBlockKind)); } return blockId; } /* * Terminate the current block w the given terminal, and set the previously * reserved block as the new current block */ terminateWithContinuation(terminal, continuation) { const { id: blockId, kind, instructions } = __privateGet(this, _current); __privateGet(this, _completed).set(blockId, { kind, id: blockId, instructions, terminal, preds: /* @__PURE__ */ new Set(), phis: /* @__PURE__ */ new Set() }); __privateSet(this, _current, continuation); } /* * Reserve a block so that it can be referenced prior to construction. * Make this the current block with `terminateWithContinuation()` or * call `complete()` to save it without setting it as the current block. */ reserve(kind) { return newBlock(makeBlockId(__privateGet(this, _env).nextBlockId), kind); } // Save a previously reserved block as completed complete(block, terminal) { const { id: blockId, kind, instructions } = block; __privateGet(this, _completed).set(blockId, { kind, id: blockId, instructions, terminal, preds: /* @__PURE__ */ new Set(), phis: /* @__PURE__ */ new Set() }); } /* * Sets the given wip block as the current block, executes the provided callback to populate the block * up to its terminal, and then resets the previous actively block. */ enterReserved(wip, fn) { const current = __privateGet(this, _current); __privateSet(this, _current, wip); const terminal = fn(); const { id: blockId, kind, instructions } = __privateGet(this, _current); __privateGet(this, _completed).set(blockId, { kind, id: blockId, instructions, terminal, preds: /* @__PURE__ */ new Set(), phis: /* @__PURE__ */ new Set() }); __privateSet(this, _current, current); } /* * Create a new block and execute the provided callback with the new block * set as the current, resetting to the previously active block upon exit. * The lambda must return a terminal node, which is used to terminate the * newly constructed block. */ enter(nextBlockKind, fn) { const wip = this.reserve(nextBlockKind); this.enterReserved(wip, () => { return fn(wip.id); }); return wip.id; } label(label, breakBlock, fn) { __privateGet(this, _scopes).push({ kind: "label", breakBlock, label }); const value = fn(); const last = __privateGet(this, _scopes).pop(); CompilerError.invariant( last != null && last.kind === "label" && last.label === label && last.breakBlock === breakBlock, { reason: "Mismatched label", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null } ); return value; } switch(label, breakBlock, fn) { __privateGet(this, _scopes).push({ kind: "switch", breakBlock, label }); const value = fn(); const last = __privateGet(this, _scopes).pop(); CompilerError.invariant( last != null && last.kind === "switch" && last.label === label && last.breakBlock === breakBlock, { reason: "Mismatched label", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null } ); return value; } /* * Executes the provided lambda inside a scope in which the provided loop * information is cached for lookup with `lookupBreak()` and `lookupContinue()` */ loop(label, continueBlock, breakBlock, fn) { __privateGet(this, _scopes).push({ kind: "loop", label, continueBlock, breakBlock }); const value = fn(); const last = __privateGet(this, _scopes).pop(); CompilerError.invariant( last != null && last.kind === "loop" && last.label === label && last.continueBlock === continueBlock && last.breakBlock === breakBlock, { reason: "Mismatched loops", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null } ); return value; } /* * Lookup the block target for a break statement, based on loops and switch statements * in scope. Throws if there is no available location to break. */ lookupBreak(label) { for (let ii = __privateGet(this, _scopes).length - 1; ii >= 0; ii--) { const scope = __privateGet(this, _scopes)[ii]; if (label === null && (scope.kind === "loop" || scope.kind === "switch") || label === scope.label) { return scope.breakBlock; } } CompilerError.invariant(false, { reason: "Expected a loop or switch to be in scope", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); } /* * Lookup the block target for a continue statement, based on loops * in scope. Throws if there is no available location to continue, or if the given * label does not correspond to a loop (this should also be validated at parse time). */ lookupContinue(label) { for (let ii = __privateGet(this, _scopes).length - 1; ii >= 0; ii--) { const scope = __privateGet(this, _scopes)[ii]; if (scope.kind === "loop") { if (label === null || label === scope.label) { return scope.continueBlock; } } else if (label !== null && scope.label === label) { CompilerError.invariant(false, { reason: "Continue may only refer to a labeled loop", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); } } CompilerError.invariant(false, { reason: "Expected a loop to be in scope", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); } }; _completed = new WeakMap(); _current = new WeakMap(); _entry = new WeakMap(); _scopes = new WeakMap(); _context = new WeakMap(); _bindings = new WeakMap(); _env = new WeakMap(); _exceptionHandlerStack = new WeakMap(); _HIRBuilder_instances = new WeakSet(); resolveBabelBinding_fn = function(path) { const originalName = path.node.name; const binding = path.scope.getBinding(originalName); if (binding == null) { return null; } return binding; }; function removeUnreachableForUpdates(fn) { for (const [, block] of fn.blocks) { if (block.terminal.kind === "for" && block.terminal.update !== null && !fn.blocks.has(block.terminal.update)) { block.terminal.update = null; } } } function removeDeadDoWhileStatements(func) { const visited = /* @__PURE__ */ new Set(); for (const [_, block] of func.blocks) { visited.add(block.id); } for (const [_, block] of func.blocks) { if (block.terminal.kind === "do-while") { if (!visited.has(block.terminal.test)) { block.terminal = { kind: "goto", block: block.terminal.loop, variant: "Break" /* Break */, id: block.terminal.id, loc: block.terminal.loc }; } } } } function reversePostorderBlocks(func) { const rpoBlocks = getReversePostorderedBlocks(func); func.blocks = rpoBlocks; } function getReversePostorderedBlocks(func) { const visited = /* @__PURE__ */ new Set(); const used = /* @__PURE__ */ new Set(); const usedFallthroughs = /* @__PURE__ */ new Set(); const postorder = []; function visit4(blockId, isUsed) { const wasUsed = used.has(blockId); const wasVisited = visited.has(blockId); visited.add(blockId); if (isUsed) { used.add(blockId); } if (wasVisited && (wasUsed || !isUsed)) { return; } const block = func.blocks.get(blockId); CompilerError.invariant(block != null, { reason: "[HIRBuilder] Unexpected null block", description: `expected block ${blockId} to exist`, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); const successors = [...eachTerminalSuccessor(block.terminal)].reverse(); const fallthrough = terminalFallthrough(block.terminal); if (fallthrough != null) { if (isUsed) { usedFallthroughs.add(fallthrough); } visit4(fallthrough, false); } for (const successor of successors) { visit4(successor, isUsed); } if (!wasVisited) { postorder.push(blockId); } } visit4(func.entry, true); const blocks = /* @__PURE__ */ new Map(); for (const blockId of postorder.reverse()) { const block = func.blocks.get(blockId); if (used.has(blockId)) { blocks.set(blockId, func.blocks.get(blockId)); } else if (usedFallthroughs.has(blockId)) { blocks.set(blockId, __spreadProps(__spreadValues({}, block), { instructions: [], terminal: { kind: "unreachable", id: block.terminal.id, loc: block.terminal.loc } })); } } return blocks; } function markInstructionIds(func) { let id = 0; const visited = /* @__PURE__ */ new Set(); for (const [_, block] of func.blocks) { for (const instr of block.instructions) { CompilerError.invariant(!visited.has(instr), { reason: `${printInstruction(instr)} already visited!`, description: null, details: [ { kind: "error", loc: instr.loc, message: null } ], suggestions: null }); visited.add(instr); instr.id = makeInstructionId(++id); } block.terminal.id = makeInstructionId(++id); } } function markPredecessors(func) { for (const [, block] of func.blocks) { block.preds.clear(); } const visited = /* @__PURE__ */ new Set(); function visit4(blockId, prevBlock) { const block = func.blocks.get(blockId); if (block == null) { return; } CompilerError.invariant(block != null, { reason: "unexpected missing block", description: `block ${blockId}`, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); if (prevBlock) { block.preds.add(prevBlock.id); } if (visited.has(blockId)) { return; } visited.add(blockId); const { terminal } = block; for (const successor of eachTerminalSuccessor(terminal)) { visit4(successor, block); } } visit4(func.entry, null); } function removeUnnecessaryTryCatch(fn) { for (const [, block] of fn.blocks) { if (block.terminal.kind === "try" && !fn.blocks.has(block.terminal.handler)) { const handlerId = block.terminal.handler; const fallthroughId = block.terminal.fallthrough; const fallthrough = fn.blocks.get(fallthroughId); block.terminal = { kind: "goto", block: block.terminal.block, id: makeInstructionId(0), loc: block.terminal.loc, variant: "Break" /* Break */ }; if (fallthrough != null) { if (fallthrough.preds.size === 1 && fallthrough.preds.has(handlerId)) { fn.blocks.delete(fallthroughId); } else { fallthrough.preds.delete(handlerId); } } } } } function createTemporaryPlace(env, loc) { return { kind: "Identifier", identifier: makeTemporaryIdentifier(env.nextIdentifierId, loc), reactive: false, effect: "" /* Unknown */, loc: GeneratedSource }; } function clonePlaceToTemporary(env, place) { const temp = createTemporaryPlace(env, place.loc); temp.effect = place.effect; temp.identifier.type = place.identifier.type; temp.reactive = place.reactive; return temp; } function fixScopeAndIdentifierRanges(func) { var _a, _b; for (const [, block] of func.blocks) { const terminal = block.terminal; if (terminal.kind === "scope" || terminal.kind === "pruned-scope") { const fallthroughBlock = func.blocks.get(terminal.fallthrough); const firstId = (_b = (_a = fallthroughBlock.instructions[0]) == null ? void 0 : _a.id) != null ? _b : fallthroughBlock.terminal.id; terminal.scope.range.start = terminal.id; terminal.scope.range.end = firstId; } } } // src/HIR/ObjectShape.ts var PRIMITIVE_TYPE = { kind: "Primitive" }; var nextAnonId = 0; function createAnonId() { return ``; } function addFunction(registry2, properties, fn, id = null, isConstructor = false) { const shapeId = id != null ? id : createAnonId(); const aliasing = fn.aliasing != null ? parseAliasingSignatureConfig(fn.aliasing, "", GeneratedSource) : null; addShape(registry2, shapeId, properties, __spreadProps(__spreadValues({}, fn), { aliasing, hookKind: null })); return { kind: "Function", return: fn.returnType, shapeId, isConstructor }; } function addHook(registry2, fn, id = null) { const shapeId = id != null ? id : createAnonId(); const aliasing = fn.aliasing != null ? parseAliasingSignatureConfig(fn.aliasing, "", GeneratedSource) : null; addShape(registry2, shapeId, [], __spreadProps(__spreadValues({}, fn), { aliasing })); return { kind: "Function", return: fn.returnType, shapeId, isConstructor: false }; } function parseAliasingSignatureConfig(typeConfig, moduleName, loc) { const lifetimes = /* @__PURE__ */ new Map(); function define2(temp) { CompilerError.invariant(!lifetimes.has(temp), { reason: `Invalid type configuration for module`, description: `Expected aliasing signature to have unique names for receiver, params, rest, returns, and temporaries in module '${moduleName}'`, details: [ { kind: "error", loc, message: null } ] }); const place = signatureArgument(lifetimes.size); lifetimes.set(temp, place); return place; } function lookup(temp) { const place = lifetimes.get(temp); CompilerError.invariant(place != null, { reason: `Invalid type configuration for module`, description: `Expected aliasing signature effects to reference known names from receiver/params/rest/returns/temporaries, but '${temp}' is not a known name in '${moduleName}'`, details: [ { kind: "error", loc, message: null } ] }); return place; } const receiver = define2(typeConfig.receiver); const params = typeConfig.params.map(define2); const rest = typeConfig.rest != null ? define2(typeConfig.rest) : null; const returns = define2(typeConfig.returns); const temporaries = typeConfig.temporaries.map(define2); const effects = typeConfig.effects.map( (effect) => { switch (effect.kind) { case "ImmutableCapture": case "CreateFrom": case "Capture": case "Alias": case "Assign": { const from = lookup(effect.from); const into = lookup(effect.into); return { kind: effect.kind, from, into }; } case "Mutate": case "MutateTransitiveConditionally": { const value = lookup(effect.value); return { kind: effect.kind, value }; } case "Create": { const into = lookup(effect.into); return { kind: "Create", into, reason: effect.reason, value: effect.value }; } case "Freeze": { const value = lookup(effect.value); return { kind: "Freeze", value, reason: effect.reason }; } case "Impure": { const place = lookup(effect.place); return { kind: "Impure", place, error: CompilerError.throwTodo({ reason: "Support impure effect declarations", loc: GeneratedSource }) }; } case "Apply": { const receiver2 = lookup(effect.receiver); const fn = lookup(effect.function); const args = effect.args.map( (arg) => { if (typeof arg === "string") { return lookup(arg); } else if (arg.kind === "Spread") { return { kind: "Spread", place: lookup(arg.place) }; } else { return arg; } } ); const into = lookup(effect.into); return { kind: "Apply", receiver: receiver2, function: fn, mutatesFunction: effect.mutatesFunction, args, into, loc, signature: null }; } default: { assertExhaustive( effect, `Unexpected effect kind '${effect.kind}'` ); } } } ); return { receiver: receiver.identifier.id, params: params.map((p) => p.identifier.id), rest: rest != null ? rest.identifier.id : null, returns: returns.identifier.id, temporaries, effects }; } function addObject(registry2, id, properties) { const shapeId = id != null ? id : createAnonId(); addShape(registry2, shapeId, properties, null); return { kind: "Object", shapeId }; } function addShape(registry2, id, properties, functionType) { const shape = { properties: new Map(properties), functionType }; CompilerError.invariant(!registry2.has(id), { reason: `[ObjectShape] Could not add shape to registry: name ${id} already exists.`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); registry2.set(id, shape); return shape; } var BuiltInPropsId = "BuiltInProps"; var BuiltInArrayId = "BuiltInArray"; var BuiltInSetId = "BuiltInSet"; var BuiltInMapId = "BuiltInMap"; var BuiltInWeakSetId = "BuiltInWeakSet"; var BuiltInWeakMapId = "BuiltInWeakMap"; var BuiltInFunctionId = "BuiltInFunction"; var BuiltInJsxId = "BuiltInJsx"; var BuiltInObjectId = "BuiltInObject"; var BuiltInUseStateId = "BuiltInUseState"; var BuiltInSetStateId = "BuiltInSetState"; var BuiltInUseActionStateId = "BuiltInUseActionState"; var BuiltInSetActionStateId = "BuiltInSetActionState"; var BuiltInUseRefId = "BuiltInUseRefId"; var BuiltInRefValueId = "BuiltInRefValue"; var BuiltInMixedReadonlyId = "BuiltInMixedReadonly"; var BuiltInUseEffectHookId = "BuiltInUseEffectHook"; var BuiltInUseLayoutEffectHookId = "BuiltInUseLayoutEffectHook"; var BuiltInUseInsertionEffectHookId = "BuiltInUseInsertionEffectHook"; var BuiltInUseOperatorId = "BuiltInUseOperator"; var BuiltInUseReducerId = "BuiltInUseReducer"; var BuiltInDispatchId = "BuiltInDispatch"; var BuiltInUseContextHookId = "BuiltInUseContextHook"; var BuiltInUseTransitionId = "BuiltInUseTransition"; var BuiltInStartTransitionId = "BuiltInStartTransition"; var BuiltInFireId = "BuiltInFire"; var BuiltInFireFunctionId = "BuiltInFireFunction"; var BuiltInUseEffectEventId = "BuiltInUseEffectEvent"; var BuiltinEffectEventId = "BuiltInEffectEventFunction"; var BuiltInAutodepsId = "BuiltInAutoDepsId"; var ReanimatedSharedValueId = "ReanimatedSharedValueId"; var BUILTIN_SHAPES = /* @__PURE__ */ new Map(); addObject(BUILTIN_SHAPES, BuiltInPropsId, [ ["ref", { kind: "Object", shapeId: BuiltInUseRefId }] ]); addObject(BUILTIN_SHAPES, BuiltInArrayId, [ [ "indexOf", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "includes", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "pop", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "store" /* Store */, returnValueKind: "mutable" /* Mutable */ }) ], [ "at", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "concat", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "capture" /* Capture */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], ["length", PRIMITIVE_TYPE], [ "push", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "capture" /* Capture */, returnType: PRIMITIVE_TYPE, calleeEffect: "store" /* Store */, returnValueKind: "primitive" /* Primitive */, aliasing: { receiver: "@receiver", params: [], rest: "@rest", returns: "@returns", temporaries: [], effects: [ // Push directly mutates the array itself { kind: "Mutate", value: "@receiver" }, // The arguments are captured into the array { kind: "Capture", from: "@rest", into: "@receiver" }, // Returns the new length, a primitive { kind: "Create", into: "@returns", value: "primitive" /* Primitive */, reason: "known-return-signature" /* KnownReturnSignature */ } ] } }) ], [ "slice", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "map", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, /* * callee is ConditionallyMutate because items of the array * flow into the lambda and may be mutated there, even though * the array object itself is not modified */ calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "mutable" /* Mutable */, noAlias: true, mutableOnlyIfOperandsAreMutable: true, aliasing: { receiver: "@receiver", params: ["@callback"], rest: null, returns: "@returns", temporaries: [ // Temporary representing captured items of the receiver "@item", // Temporary representing the result of the callback "@callbackReturn", /* * Undefined `this` arg to the callback. Note the signature does not * support passing an explicit thisArg second param */ "@thisArg" ], effects: [ // Map creates a new mutable array { kind: "Create", into: "@returns", value: "mutable" /* Mutable */, reason: "known-return-signature" /* KnownReturnSignature */ }, // The first arg to the callback is an item extracted from the receiver array { kind: "CreateFrom", from: "@receiver", into: "@item" }, // The undefined this for the callback { kind: "Create", into: "@thisArg", value: "primitive" /* Primitive */, reason: "known-return-signature" /* KnownReturnSignature */ }, // calls the callback, returning the result into a temporary { kind: "Apply", receiver: "@thisArg", args: ["@item", { kind: "Hole" }, "@receiver"], function: "@callback", into: "@callbackReturn", mutatesFunction: false }, // captures the result of the callback into the return array { kind: "Capture", from: "@callbackReturn", into: "@returns" } ] } }) ], [ "flatMap", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, /* * callee is ConditionallyMutate because items of the array * flow into the lambda and may be mutated there, even though * the array object itself is not modified */ calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "mutable" /* Mutable */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "filter", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, /* * callee is ConditionallyMutate because items of the array * flow into the lambda and may be mutated there, even though * the array object itself is not modified */ calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "mutable" /* Mutable */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "every", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Primitive" }, /* * callee is ConditionallyMutate because items of the array * flow into the lambda and may be mutated there, even though * the array object itself is not modified */ calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "primitive" /* Primitive */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "some", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Primitive" }, /* * callee is ConditionallyMutate because items of the array * flow into the lambda and may be mutated there, even though * the array object itself is not modified */ calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "primitive" /* Primitive */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "find", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Poly" }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "mutable" /* Mutable */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "findIndex", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Primitive" }, /* * callee is ConditionallyMutate because items of the array * flow into the lambda and may be mutated there, even though * the array object itself is not modified */ calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "primitive" /* Primitive */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "join", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ] // TODO: rest of Array properties ]); addObject(BUILTIN_SHAPES, BuiltInObjectId, [ [ "toString", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ] /* * TODO: * hasOwnProperty, isPrototypeOf, propertyIsEnumerable, toLocaleString, valueOf */ ]); addObject(BUILTIN_SHAPES, BuiltInSetId, [ [ /** * add(value) * Parameters * value: the value of the element to add to the Set object. * Returns the Set object with added value. */ "add", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInSetId }, calleeEffect: "store" /* Store */, // returnValueKind is technically dependent on the ValueKind of the set itself returnValueKind: "mutable" /* Mutable */, aliasing: { receiver: "@receiver", params: [], rest: "@rest", returns: "@returns", temporaries: [], effects: [ // Set.add returns the receiver Set { kind: "Assign", from: "@receiver", into: "@returns" }, // Set.add mutates the set itself { kind: "Mutate", value: "@receiver" }, // Captures the rest params into the set { kind: "Capture", from: "@rest", into: "@receiver" } ] } }) ], [ /** * clear() * Parameters none * Returns undefined */ "clear", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "store" /* Store */, returnValueKind: "primitive" /* Primitive */ }) ], [ /** * setInstance.delete(value) * Returns true if value was already in Set; otherwise false. */ "delete", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "store" /* Store */, returnValueKind: "primitive" /* Primitive */ }) ], [ "has", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], ["size", PRIMITIVE_TYPE], [ /** * difference(other) * Parameters * other: A Set object, or set-like object. * Returns a new Set object containing elements in this set but not in the other set. */ "difference", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInSetId }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ /** * union(other) * Parameters * other: A Set object, or set-like object. * Returns a new Set object containing elements in either this set or the other set. */ "union", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInSetId }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ /** * symmetricalDifference(other) * Parameters * other: A Set object, or set-like object. * A new Set object containing elements which are in either this set or the other set, but not in both. */ "symmetricalDifference", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInSetId }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ /** * isSubsetOf(other) * Parameters * other: A Set object, or set-like object. * Returns true if all elements in this set are also in the other set, and false otherwise. */ "isSubsetOf", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ /** * isSupersetOf(other) * Parameters * other: A Set object, or set-like object. * Returns true if all elements in the other set are also in this set, and false otherwise. */ "isSupersetOf", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ /** * forEach(callbackFn) * forEach(callbackFn, thisArg) */ "forEach", addFunction(BUILTIN_SHAPES, [], { /** * see Array.map explanation for why arguments are marked `ConditionallyMutate` */ positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: PRIMITIVE_TYPE, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "primitive" /* Primitive */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], /** * Iterators */ [ "entries", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "keys", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "values", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ] ]); addObject(BUILTIN_SHAPES, BuiltInMapId, [ [ /** * clear() * Parameters none * Returns undefined */ "clear", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "store" /* Store */, returnValueKind: "primitive" /* Primitive */ }) ], [ "delete", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "store" /* Store */, returnValueKind: "primitive" /* Primitive */ }) ], [ "get", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "has", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ /** * Params * key: the key of the element to add to the Map object. The key may be * any JavaScript type (any primitive value or any type of JavaScript * object). * value: the value of the element to add to the Map object. * Returns the Map object. */ "set", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["capture" /* Capture */, "capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInMapId }, calleeEffect: "store" /* Store */, returnValueKind: "mutable" /* Mutable */ }) ], ["size", PRIMITIVE_TYPE], [ "forEach", addFunction(BUILTIN_SHAPES, [], { /** * see Array.map explanation for why arguments are marked `ConditionallyMutate` */ positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: PRIMITIVE_TYPE, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "primitive" /* Primitive */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], /** * Iterators */ [ "entries", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "keys", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "values", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ] ]); addObject(BUILTIN_SHAPES, BuiltInWeakSetId, [ [ /** * add(value) * Parameters * value: the value of the element to add to the Set object. * Returns the Set object with added value. */ "add", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInWeakSetId }, calleeEffect: "store" /* Store */, // returnValueKind is technically dependent on the ValueKind of the set itself returnValueKind: "mutable" /* Mutable */ }) ], [ /** * setInstance.delete(value) * Returns true if value was already in Set; otherwise false. */ "delete", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "store" /* Store */, returnValueKind: "primitive" /* Primitive */ }) ], [ "has", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ] ]); addObject(BUILTIN_SHAPES, BuiltInWeakMapId, [ [ "delete", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "store" /* Store */, returnValueKind: "primitive" /* Primitive */ }) ], [ "get", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: { kind: "Poly" }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "has", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ /** * Params * key: the key of the element to add to the Map object. The key may be * any JavaScript type (any primitive value or any type of JavaScript * object). * value: the value of the element to add to the Map object. * Returns the Map object. */ "set", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["capture" /* Capture */, "capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInWeakMapId }, calleeEffect: "store" /* Store */, returnValueKind: "mutable" /* Mutable */ }) ] ]); addObject(BUILTIN_SHAPES, BuiltInUseStateId, [ ["0", { kind: "Poly" }], [ "1", addFunction( BUILTIN_SHAPES, [], { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }, BuiltInSetStateId ) ] ]); addObject(BUILTIN_SHAPES, BuiltInUseTransitionId, [ ["0", { kind: "Primitive" }], [ "1", addFunction( BUILTIN_SHAPES, [], { positionalParams: [], restParam: null, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }, BuiltInStartTransitionId ) ] ]); addObject(BUILTIN_SHAPES, BuiltInUseActionStateId, [ ["0", { kind: "Poly" }], [ "1", addFunction( BUILTIN_SHAPES, [], { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }, BuiltInSetActionStateId ) ] ]); addObject(BUILTIN_SHAPES, BuiltInUseReducerId, [ ["0", { kind: "Poly" }], [ "1", addFunction( BUILTIN_SHAPES, [], { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }, BuiltInDispatchId ) ] ]); addObject(BUILTIN_SHAPES, BuiltInUseRefId, [ ["current", { kind: "Object", shapeId: BuiltInRefValueId }] ]); addObject(BUILTIN_SHAPES, BuiltInRefValueId, [ ["*", { kind: "Object", shapeId: BuiltInRefValueId }] ]); addObject(BUILTIN_SHAPES, ReanimatedSharedValueId, []); addFunction( BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Poly" }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "mutable" /* Mutable */ }, BuiltinEffectEventId ); addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [ [ "toString", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "indexOf", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "includes", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "at", addFunction(BUILTIN_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInMixedReadonlyId }, calleeEffect: "capture" /* Capture */, returnValueKind: "frozen" /* Frozen */ }) ], [ "map", addFunction(BUILTIN_SHAPES, [], { /** * Note `map`'s arguments are annotated as Effect.ConditionallyMutate as * calling `.map(fn)` might invoke `fn`, which means replaying its * effects. * * (Note that Effect.Read / Effect.Capture on a function type means * potential data dependency or aliasing respectively.) */ positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "mutable" /* Mutable */, noAlias: true }) ], [ "flatMap", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "mutable" /* Mutable */, noAlias: true }) ], [ "filter", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "mutable" /* Mutable */, noAlias: true }) ], [ "concat", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "capture" /* Capture */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "slice", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "capture" /* Capture */, returnValueKind: "mutable" /* Mutable */ }) ], [ "every", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Primitive" }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "primitive" /* Primitive */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "some", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Primitive" }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "primitive" /* Primitive */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "find", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Object", shapeId: BuiltInMixedReadonlyId }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "frozen" /* Frozen */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "findIndex", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Primitive" }, calleeEffect: "mutate?" /* ConditionallyMutate */, returnValueKind: "primitive" /* Primitive */, noAlias: true, mutableOnlyIfOperandsAreMutable: true }) ], [ "join", addFunction(BUILTIN_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: PRIMITIVE_TYPE, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], ["*", { kind: "Object", shapeId: BuiltInMixedReadonlyId }] ]); addObject(BUILTIN_SHAPES, BuiltInJsxId, []); addObject(BUILTIN_SHAPES, BuiltInFunctionId, []); var DefaultMutatingHook = addHook( BUILTIN_SHAPES, { positionalParams: [], restParam: "mutate?" /* ConditionallyMutate */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, hookKind: "Custom", returnValueKind: "mutable" /* Mutable */ }, "DefaultMutatingHook" ); var DefaultNonmutatingHook = addHook( BUILTIN_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, hookKind: "Custom", returnValueKind: "frozen" /* Frozen */, aliasing: { receiver: "@receiver", params: [], rest: "@rest", returns: "@returns", temporaries: [], effects: [ // Freeze the arguments { kind: "Freeze", value: "@rest", reason: "hook-captured" /* HookCaptured */ }, // Returns a frozen value { kind: "Create", into: "@returns", value: "frozen" /* Frozen */, reason: "hook-return" /* HookReturn */ }, // May alias any arguments into the return { kind: "Alias", from: "@rest", into: "@returns" } ] } }, "DefaultNonmutatingHook" ); function signatureArgument(id) { const place = { kind: "Identifier", effect: "" /* Unknown */, loc: GeneratedSource, reactive: false, identifier: { declarationId: makeDeclarationId(id), id: makeIdentifierId(id), loc: GeneratedSource, mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, name: null, scope: null, type: makeType() } }; return place; } // src/HIR/BuildHIR.ts function lower(func, env, bindings = null, capturedRefs = /* @__PURE__ */ new Map()) { var _a, _b, _c; const builder = new HIRBuilder(env, { bindings, context: capturedRefs }); const context = []; for (const [ref, loc] of capturedRefs != null ? capturedRefs : []) { context.push({ kind: "Identifier", identifier: builder.resolveBinding(ref), effect: "" /* Unknown */, reactive: false, loc }); } let id = null; if (func.isFunctionDeclaration() || func.isFunctionExpression()) { const idNode = func.get("id"); if (hasNode(idNode)) { id = idNode.node.name; } } const params = []; func.get("params").forEach((param) => { var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i; if (param.isIdentifier()) { const binding = builder.resolveIdentifier(param); if (binding.kind !== "Identifier") { builder.errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Invariant" /* Invariant */, reason: "Could not find binding", description: `[BuildHIR] Could not find binding for param \`${param.node.name}\`` }).withDetails({ kind: "error", loc: (_a2 = param.node.loc) != null ? _a2 : null, message: "Could not find binding" }) ); return; } const place = { kind: "Identifier", identifier: binding.identifier, effect: "" /* Unknown */, reactive: false, loc: (_b2 = param.node.loc) != null ? _b2 : GeneratedSource }; params.push(place); } else if (param.isObjectPattern() || param.isArrayPattern() || param.isAssignmentPattern()) { const place = { kind: "Identifier", identifier: builder.makeTemporary((_c2 = param.node.loc) != null ? _c2 : GeneratedSource), effect: "" /* Unknown */, reactive: false, loc: (_d = param.node.loc) != null ? _d : GeneratedSource }; promoteTemporary(place.identifier); params.push(place); lowerAssignment( builder, (_e = param.node.loc) != null ? _e : GeneratedSource, "Let" /* Let */, param, place, "Assignment" ); } else if (param.isRestElement()) { const place = { kind: "Identifier", identifier: builder.makeTemporary((_f = param.node.loc) != null ? _f : GeneratedSource), effect: "" /* Unknown */, reactive: false, loc: (_g = param.node.loc) != null ? _g : GeneratedSource }; params.push({ kind: "Spread", place }); lowerAssignment( builder, (_h = param.node.loc) != null ? _h : GeneratedSource, "Let" /* Let */, param.get("argument"), place, "Assignment" ); } else { builder.errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Todo" /* Todo */, reason: `Handle ${param.node.type} parameters`, description: `[BuildHIR] Add support for ${param.node.type} parameters` }).withDetails({ kind: "error", loc: (_i = param.node.loc) != null ? _i : null, message: "Unsupported parameter type" }) ); } }); let directives = []; const body = func.get("body"); if (body.isExpression()) { const fallthrough = builder.reserve("block"); const terminal = { kind: "return", returnVariant: "Implicit", loc: GeneratedSource, value: lowerExpressionToTemporary(builder, body), id: makeInstructionId(0), effects: null }; builder.terminateWithContinuation(terminal, fallthrough); } else if (body.isBlockStatement()) { lowerStatement(builder, body); directives = body.get("directives").map((d) => d.node.value.value); } else { builder.errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Syntax" /* Syntax */, reason: `Unexpected function body kind`, description: `Expected function body to be an expression or a block statement, got \`${body.type}\`` }).withDetails({ kind: "error", loc: (_a = body.node.loc) != null ? _a : null, message: "Expected a block statement or expression" }) ); } let validatedId = null; if (id != null) { const idResult = validateIdentifierName(id); if (idResult.isErr()) { builder.errors.merge(idResult.unwrapErr()); } else { validatedId = idResult.unwrap().value; } } if (builder.errors.hasAnyErrors()) { return Err(builder.errors); } builder.terminate( { kind: "return", returnVariant: "Void", loc: GeneratedSource, value: lowerValueToTemporary(builder, { kind: "Primitive", value: void 0, loc: GeneratedSource }), id: makeInstructionId(0), effects: null }, null ); return Ok({ id: validatedId, nameHint: null, params, fnType: bindings == null ? env.fnType : "Other", returnTypeAnnotation: null, // TODO: extract the actual return type node if present returns: createTemporaryPlace(env, (_b = func.node.loc) != null ? _b : GeneratedSource), body: builder.build(), context, generator: func.node.generator === true, async: func.node.async === true, loc: (_c = func.node.loc) != null ? _c : GeneratedSource, env, effects: null, aliasingEffects: null, directives }); } function lowerStatement(builder, stmtPath, label = null) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga; const stmtNode = stmtPath.node; switch (stmtNode.type) { case "ThrowStatement": { const stmt = stmtPath; const value = lowerExpressionToTemporary(builder, stmt.get("argument")); const handler = builder.resolveThrowHandler(); if (handler != null) { builder.errors.push({ reason: "(BuildHIR::lowerStatement) Support ThrowStatement inside of try/catch", category: "Todo" /* Todo */, loc: (_a = stmt.node.loc) != null ? _a : null, suggestions: null }); } const terminal = { kind: "throw", value, id: makeInstructionId(0), loc: (_b = stmt.node.loc) != null ? _b : GeneratedSource }; builder.terminate(terminal, "block"); return; } case "ReturnStatement": { const stmt = stmtPath; const argument = stmt.get("argument"); let value; if (argument.node === null) { value = lowerValueToTemporary(builder, { kind: "Primitive", value: void 0, loc: GeneratedSource }); } else { value = lowerExpressionToTemporary( builder, argument ); } const terminal = { kind: "return", returnVariant: "Explicit", loc: (_c = stmt.node.loc) != null ? _c : GeneratedSource, value, id: makeInstructionId(0), effects: null }; builder.terminate(terminal, "block"); return; } case "IfStatement": { const stmt = stmtPath; const continuationBlock = builder.reserve("block"); const consequentBlock = builder.enter("block", (_blockId) => { var _a2; const consequent = stmt.get("consequent"); lowerStatement(builder, consequent); return { kind: "goto", block: continuationBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_a2 = consequent.node.loc) != null ? _a2 : GeneratedSource }; }); let alternateBlock; const alternate = stmt.get("alternate"); if (hasNode(alternate)) { alternateBlock = builder.enter("block", (_blockId) => { var _a2, _b2; lowerStatement(builder, alternate); return { kind: "goto", block: continuationBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_b2 = (_a2 = alternate.node) == null ? void 0 : _a2.loc) != null ? _b2 : GeneratedSource }; }); } else { alternateBlock = continuationBlock.id; } const test = lowerExpressionToTemporary(builder, stmt.get("test")); const terminal = { kind: "if", test, consequent: consequentBlock, alternate: alternateBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: (_d = stmt.node.loc) != null ? _d : GeneratedSource }; builder.terminateWithContinuation(terminal, continuationBlock); return; } case "BlockStatement": { const stmt = stmtPath; const statements = stmt.get("body"); const hoistableIdentifiers = /* @__PURE__ */ new Set(); for (const [, binding] of Object.entries(stmt.scope.bindings)) { if (binding.kind !== "param") { hoistableIdentifiers.add(binding.identifier); } } for (const s of statements) { const willHoist = /* @__PURE__ */ new Set(); let fnDepth = s.isFunctionDeclaration() ? 1 : 0; const withFunctionContext = { enter: () => { fnDepth++; }, exit: () => { fnDepth--; } }; s.traverse({ FunctionExpression: withFunctionContext, FunctionDeclaration: withFunctionContext, ArrowFunctionExpression: withFunctionContext, ObjectMethod: withFunctionContext, Identifier(id) { const id2 = id; if (!id2.isReferencedIdentifier() && // isReferencedIdentifier is broken and returns false for reassignments id.parent.type !== "AssignmentExpression") { return; } const binding = id.scope.getBinding(id.node.name); if (binding != null && hoistableIdentifiers.has(binding.identifier) && (fnDepth > 0 || binding.kind === "hoisted")) { willHoist.add(id); } } }); s.traverse({ Identifier(path) { if (hoistableIdentifiers.has(path.node)) { hoistableIdentifiers.delete(path.node); } } }); for (const id of willHoist) { const binding = stmt.scope.getBinding(id.node.name); CompilerError.invariant(binding != null, { reason: "Expected to find binding for hoisted identifier", description: `Could not find a binding for ${id.node.name}`, suggestions: null, details: [ { kind: "error", loc: (_e = id.node.loc) != null ? _e : GeneratedSource, message: null } ] }); if (builder.environment.isHoistedIdentifier(binding.identifier)) { continue; } let kind; if (binding.kind === "const" || binding.kind === "var") { kind = "HoistedConst" /* HoistedConst */; } else if (binding.kind === "let") { kind = "HoistedLet" /* HoistedLet */; } else if (binding.path.isFunctionDeclaration()) { kind = "HoistedFunction" /* HoistedFunction */; } else if (!binding.path.isVariableDeclarator()) { builder.errors.push({ category: "Todo" /* Todo */, reason: "Unsupported declaration type for hoisting", description: `variable "${binding.identifier.name}" declared with ${binding.path.type}`, suggestions: null, loc: (_f = id.parentPath.node.loc) != null ? _f : GeneratedSource }); continue; } else { builder.errors.push({ category: "Todo" /* Todo */, reason: "Handle non-const declarations for hoisting", description: `variable "${binding.identifier.name}" declared with ${binding.kind}`, suggestions: null, loc: (_g = id.parentPath.node.loc) != null ? _g : GeneratedSource }); continue; } const identifier4 = builder.resolveIdentifier(id); CompilerError.invariant(identifier4.kind === "Identifier", { reason: "Expected hoisted binding to be a local identifier, not a global", description: null, details: [ { kind: "error", loc: (_h = id.node.loc) != null ? _h : GeneratedSource, message: null } ] }); const place = { effect: "" /* Unknown */, identifier: identifier4.identifier, kind: "Identifier", reactive: false, loc: (_i = id.node.loc) != null ? _i : GeneratedSource }; lowerValueToTemporary(builder, { kind: "DeclareContext", lvalue: { kind, place }, loc: (_j = id.node.loc) != null ? _j : GeneratedSource }); builder.environment.addHoistedIdentifier(binding.identifier); } lowerStatement(builder, s); } return; } case "BreakStatement": { const stmt = stmtPath; const block = builder.lookupBreak((_l = (_k = stmt.node.label) == null ? void 0 : _k.name) != null ? _l : null); builder.terminate( { kind: "goto", block, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_m = stmt.node.loc) != null ? _m : GeneratedSource }, "block" ); return; } case "ContinueStatement": { const stmt = stmtPath; const block = builder.lookupContinue((_o = (_n = stmt.node.label) == null ? void 0 : _n.name) != null ? _o : null); builder.terminate( { kind: "goto", block, variant: "Continue" /* Continue */, id: makeInstructionId(0), loc: (_p = stmt.node.loc) != null ? _p : GeneratedSource }, "block" ); return; } case "ForStatement": { const stmt = stmtPath; const testBlock = builder.reserve("loop"); const continuationBlock = builder.reserve("block"); const initBlock = builder.enter("loop", (_blockId) => { var _a2, _b2, _c2, _d2; const init = stmt.get("init"); if (!init.isVariableDeclaration()) { builder.errors.push({ reason: "(BuildHIR::lowerStatement) Handle non-variable initialization in ForStatement", category: "Todo" /* Todo */, loc: (_a2 = stmt.node.loc) != null ? _a2 : null, suggestions: null }); return { kind: "unsupported", id: makeInstructionId(0), loc: (_c2 = (_b2 = init.node) == null ? void 0 : _b2.loc) != null ? _c2 : GeneratedSource }; } lowerStatement(builder, init); return { kind: "goto", block: testBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_d2 = init.node.loc) != null ? _d2 : GeneratedSource }; }); let updateBlock = null; const update2 = stmt.get("update"); if (hasNode(update2)) { updateBlock = builder.enter("loop", (_blockId) => { var _a2, _b2; lowerExpressionToTemporary(builder, update2); return { kind: "goto", block: testBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_b2 = (_a2 = update2.node) == null ? void 0 : _a2.loc) != null ? _b2 : GeneratedSource }; }); } const bodyBlock = builder.enter("block", (_blockId) => { return builder.loop( label, updateBlock != null ? updateBlock : testBlock.id, continuationBlock.id, () => { var _a2; const body = stmt.get("body"); lowerStatement(builder, body); return { kind: "goto", block: updateBlock != null ? updateBlock : testBlock.id, variant: "Continue" /* Continue */, id: makeInstructionId(0), loc: (_a2 = body.node.loc) != null ? _a2 : GeneratedSource }; } ); }); builder.terminateWithContinuation( { kind: "for", loc: (_q = stmtNode.loc) != null ? _q : GeneratedSource, init: initBlock, test: testBlock.id, update: updateBlock, loop: bodyBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0) }, testBlock ); const test = stmt.get("test"); if (test.node == null) { builder.errors.push({ reason: `(BuildHIR::lowerStatement) Handle empty test in ForStatement`, category: "Todo" /* Todo */, loc: (_r = stmt.node.loc) != null ? _r : null, suggestions: null }); } else { builder.terminateWithContinuation( { kind: "branch", test: lowerExpressionToTemporary( builder, test ), consequent: bodyBlock, alternate: continuationBlock.id, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: (_s = stmt.node.loc) != null ? _s : GeneratedSource }, continuationBlock ); } return; } case "WhileStatement": { const stmt = stmtPath; const conditionalBlock = builder.reserve("loop"); const continuationBlock = builder.reserve("block"); const loopBlock = builder.enter("block", (_blockId) => { return builder.loop( label, conditionalBlock.id, continuationBlock.id, () => { var _a2; const body = stmt.get("body"); lowerStatement(builder, body); return { kind: "goto", block: conditionalBlock.id, variant: "Continue" /* Continue */, id: makeInstructionId(0), loc: (_a2 = body.node.loc) != null ? _a2 : GeneratedSource }; } ); }); const loc = (_t = stmt.node.loc) != null ? _t : GeneratedSource; builder.terminateWithContinuation( { kind: "while", loc, test: conditionalBlock.id, loop: loopBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0) }, conditionalBlock ); const test = lowerExpressionToTemporary(builder, stmt.get("test")); const terminal = { kind: "branch", test, consequent: loopBlock, alternate: continuationBlock.id, fallthrough: conditionalBlock.id, id: makeInstructionId(0), loc: (_u = stmt.node.loc) != null ? _u : GeneratedSource }; builder.terminateWithContinuation(terminal, continuationBlock); return; } case "LabeledStatement": { const stmt = stmtPath; const label2 = stmt.node.label.name; const body = stmt.get("body"); switch (body.node.type) { case "ForInStatement": case "ForOfStatement": case "ForStatement": case "WhileStatement": case "DoWhileStatement": { lowerStatement(builder, stmt.get("body"), label2); break; } default: { const continuationBlock = builder.reserve("block"); const block = builder.enter("block", () => { var _a2; const body2 = stmt.get("body"); builder.label(label2, continuationBlock.id, () => { lowerStatement(builder, body2); }); return { kind: "goto", block: continuationBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_a2 = body2.node.loc) != null ? _a2 : GeneratedSource }; }); builder.terminateWithContinuation( { kind: "label", block, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: (_v = stmt.node.loc) != null ? _v : GeneratedSource }, continuationBlock ); } } return; } case "SwitchStatement": { const stmt = stmtPath; const continuationBlock = builder.reserve("block"); let fallthrough = continuationBlock.id; const cases = []; let hasDefault = false; for (let ii = stmt.get("cases").length - 1; ii >= 0; ii--) { const case_ = stmt.get("cases")[ii]; const testExpr = case_.get("test"); if (testExpr.node == null) { if (hasDefault) { builder.errors.push({ reason: `Expected at most one \`default\` branch in a switch statement, this code should have failed to parse`, category: "Syntax" /* Syntax */, loc: (_w = case_.node.loc) != null ? _w : null, suggestions: null }); break; } hasDefault = true; } const block = builder.enter("block", (_blockId) => { return builder.switch(label, continuationBlock.id, () => { var _a2; case_.get("consequent").forEach((consequent) => lowerStatement(builder, consequent)); return { kind: "goto", block: fallthrough, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_a2 = case_.node.loc) != null ? _a2 : GeneratedSource }; }); }); let test2 = null; if (hasNode(testExpr)) { test2 = lowerReorderableExpression(builder, testExpr); } cases.push({ test: test2, block }); fallthrough = block; } cases.reverse(); if (!hasDefault) { cases.push({ test: null, block: continuationBlock.id }); } const test = lowerExpressionToTemporary( builder, stmt.get("discriminant") ); builder.terminateWithContinuation( { kind: "switch", test, cases, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: (_x = stmt.node.loc) != null ? _x : GeneratedSource }, continuationBlock ); return; } case "VariableDeclaration": { const stmt = stmtPath; const nodeKind = stmt.node.kind; if (nodeKind === "var") { builder.errors.push({ reason: `(BuildHIR::lowerStatement) Handle ${nodeKind} kinds in VariableDeclaration`, category: "Todo" /* Todo */, loc: (_y = stmt.node.loc) != null ? _y : null, suggestions: null }); return; } const kind = nodeKind === "let" ? "Let" /* Let */ : "Const" /* Const */; for (const declaration of stmt.get("declarations")) { const id = declaration.get("id"); const init = declaration.get("init"); if (hasNode(init)) { const value = lowerExpressionToTemporary(builder, init); lowerAssignment( builder, (_z = stmt.node.loc) != null ? _z : GeneratedSource, kind, id, value, id.isObjectPattern() || id.isArrayPattern() ? "Destructure" : "Assignment" ); } else if (id.isIdentifier()) { const binding = builder.resolveIdentifier(id); if (binding.kind !== "Identifier") { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Could not find binding for declaration.`, category: "Invariant" /* Invariant */, loc: (_A = id.node.loc) != null ? _A : null, suggestions: null }); } else { const place = { effect: "" /* Unknown */, identifier: binding.identifier, kind: "Identifier", reactive: false, loc: (_B = id.node.loc) != null ? _B : GeneratedSource }; if (builder.isContextIdentifier(id)) { if (kind === "Const" /* Const */) { const declRangeStart = declaration.parentPath.node.start; builder.errors.push({ reason: `Expect \`const\` declaration not to be reassigned`, category: "Syntax" /* Syntax */, loc: (_C = id.node.loc) != null ? _C : null, suggestions: [ { description: "Change to a `let` declaration", op: 3 /* Replace */, range: [declRangeStart, declRangeStart + 5], // "const".length text: "let" } ] }); } lowerValueToTemporary(builder, { kind: "DeclareContext", lvalue: { kind: "Let" /* Let */, place }, loc: (_D = id.node.loc) != null ? _D : GeneratedSource }); } else { const typeAnnotation2 = id.get("typeAnnotation"); let type; if (typeAnnotation2.isTSTypeAnnotation()) { const typePath = typeAnnotation2.get("typeAnnotation"); type = typePath.node; } else if (typeAnnotation2.isTypeAnnotation()) { const typePath = typeAnnotation2.get("typeAnnotation"); type = typePath.node; } else { type = null; } lowerValueToTemporary(builder, { kind: "DeclareLocal", lvalue: { kind, place }, type, loc: (_E = id.node.loc) != null ? _E : GeneratedSource }); } } } else { builder.errors.push({ reason: `Expected variable declaration to be an identifier if no initializer was provided`, description: `Got a \`${id.type}\``, category: "Syntax" /* Syntax */, loc: (_F = stmt.node.loc) != null ? _F : null, suggestions: null }); } } return; } case "ExpressionStatement": { const stmt = stmtPath; const expression = stmt.get("expression"); lowerExpressionToTemporary(builder, expression); return; } case "DoWhileStatement": { const stmt = stmtPath; const conditionalBlock = builder.reserve("loop"); const continuationBlock = builder.reserve("block"); const loopBlock = builder.enter("block", (_loopBlockId) => { return builder.loop( label, conditionalBlock.id, continuationBlock.id, () => { var _a2; const body = stmt.get("body"); lowerStatement(builder, body); return { kind: "goto", block: conditionalBlock.id, variant: "Continue" /* Continue */, id: makeInstructionId(0), loc: (_a2 = body.node.loc) != null ? _a2 : GeneratedSource }; } ); }); const loc = (_G = stmt.node.loc) != null ? _G : GeneratedSource; builder.terminateWithContinuation( { kind: "do-while", loc, test: conditionalBlock.id, loop: loopBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0) }, conditionalBlock ); const test = lowerExpressionToTemporary(builder, stmt.get("test")); const terminal = { kind: "branch", test, consequent: loopBlock, alternate: continuationBlock.id, fallthrough: conditionalBlock.id, id: makeInstructionId(0), loc }; builder.terminateWithContinuation(terminal, continuationBlock); return; } case "FunctionDeclaration": { const stmt = stmtPath; stmt.skip(); CompilerError.invariant(stmt.get("id").type === "Identifier", { reason: "function declarations must have a name", description: null, details: [ { kind: "error", loc: (_H = stmt.node.loc) != null ? _H : null, message: null } ], suggestions: null }); const id = stmt.get("id"); const fn = lowerValueToTemporary( builder, lowerFunctionToValue(builder, stmt) ); lowerAssignment( builder, (_I = stmt.node.loc) != null ? _I : GeneratedSource, "Function" /* Function */, id, fn, "Assignment" ); return; } case "ForOfStatement": { const stmt = stmtPath; const continuationBlock = builder.reserve("block"); const initBlock = builder.reserve("loop"); const testBlock = builder.reserve("loop"); if (stmt.node.await) { builder.errors.push({ reason: `(BuildHIR::lowerStatement) Handle for-await loops`, category: "Todo" /* Todo */, loc: (_J = stmt.node.loc) != null ? _J : null, suggestions: null }); return; } const loopBlock = builder.enter("block", (_blockId) => { return builder.loop(label, initBlock.id, continuationBlock.id, () => { var _a2; const body = stmt.get("body"); lowerStatement(builder, body); return { kind: "goto", block: initBlock.id, variant: "Continue" /* Continue */, id: makeInstructionId(0), loc: (_a2 = body.node.loc) != null ? _a2 : GeneratedSource }; }); }); const loc = (_K = stmt.node.loc) != null ? _K : GeneratedSource; const value = lowerExpressionToTemporary(builder, stmt.get("right")); builder.terminateWithContinuation( { kind: "for-of", loc, init: initBlock.id, test: testBlock.id, loop: loopBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0) }, initBlock ); const iterator = lowerValueToTemporary(builder, { kind: "GetIterator", loc: value.loc, collection: __spreadValues({}, value) }); builder.terminateWithContinuation( { id: makeInstructionId(0), kind: "goto", block: testBlock.id, variant: "Break" /* Break */, loc: (_L = stmt.node.loc) != null ? _L : GeneratedSource }, testBlock ); const left = stmt.get("left"); const leftLoc = (_M = left.node.loc) != null ? _M : GeneratedSource; let test; const advanceIterator = lowerValueToTemporary(builder, { kind: "IteratorNext", loc: leftLoc, iterator: __spreadValues({}, iterator), collection: __spreadValues({}, value) }); if (left.isVariableDeclaration()) { const declarations = left.get("declarations"); CompilerError.invariant(declarations.length === 1, { reason: `Expected only one declaration in the init of a ForOfStatement, got ${declarations.length}`, description: null, details: [ { kind: "error", loc: (_N = left.node.loc) != null ? _N : null, message: null } ], suggestions: null }); const id = declarations[0].get("id"); const assign = lowerAssignment( builder, leftLoc, "Let" /* Let */, id, advanceIterator, "Assignment" ); test = lowerValueToTemporary(builder, assign); } else { CompilerError.invariant(left.isLVal(), { reason: "Expected ForOf init to be a variable declaration or lval", description: null, details: [ { kind: "error", loc: leftLoc, message: null } ] }); const assign = lowerAssignment( builder, leftLoc, "Reassign" /* Reassign */, left, advanceIterator, "Assignment" ); test = lowerValueToTemporary(builder, assign); } builder.terminateWithContinuation( { id: makeInstructionId(0), kind: "branch", test, consequent: loopBlock, alternate: continuationBlock.id, loc: (_O = stmt.node.loc) != null ? _O : GeneratedSource, fallthrough: continuationBlock.id }, continuationBlock ); return; } case "ForInStatement": { const stmt = stmtPath; const continuationBlock = builder.reserve("block"); const initBlock = builder.reserve("loop"); const loopBlock = builder.enter("block", (_blockId) => { return builder.loop(label, initBlock.id, continuationBlock.id, () => { var _a2; const body = stmt.get("body"); lowerStatement(builder, body); return { kind: "goto", block: initBlock.id, variant: "Continue" /* Continue */, id: makeInstructionId(0), loc: (_a2 = body.node.loc) != null ? _a2 : GeneratedSource }; }); }); const loc = (_P = stmt.node.loc) != null ? _P : GeneratedSource; const value = lowerExpressionToTemporary(builder, stmt.get("right")); builder.terminateWithContinuation( { kind: "for-in", loc, init: initBlock.id, loop: loopBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0) }, initBlock ); const left = stmt.get("left"); const leftLoc = (_Q = left.node.loc) != null ? _Q : GeneratedSource; let test; const nextPropertyTemp = lowerValueToTemporary(builder, { kind: "NextPropertyOf", loc: leftLoc, value }); if (left.isVariableDeclaration()) { const declarations = left.get("declarations"); CompilerError.invariant(declarations.length === 1, { reason: `Expected only one declaration in the init of a ForInStatement, got ${declarations.length}`, description: null, details: [ { kind: "error", loc: (_R = left.node.loc) != null ? _R : null, message: null } ], suggestions: null }); const id = declarations[0].get("id"); const assign = lowerAssignment( builder, leftLoc, "Let" /* Let */, id, nextPropertyTemp, "Assignment" ); test = lowerValueToTemporary(builder, assign); } else { CompilerError.invariant(left.isLVal(), { reason: "Expected ForIn init to be a variable declaration or lval", description: null, details: [ { kind: "error", loc: leftLoc, message: null } ] }); const assign = lowerAssignment( builder, leftLoc, "Reassign" /* Reassign */, left, nextPropertyTemp, "Assignment" ); test = lowerValueToTemporary(builder, assign); } builder.terminateWithContinuation( { id: makeInstructionId(0), kind: "branch", test, consequent: loopBlock, alternate: continuationBlock.id, fallthrough: continuationBlock.id, loc: (_S = stmt.node.loc) != null ? _S : GeneratedSource }, continuationBlock ); return; } case "DebuggerStatement": { const stmt = stmtPath; const loc = (_T = stmt.node.loc) != null ? _T : GeneratedSource; builder.push({ id: makeInstructionId(0), lvalue: buildTemporaryPlace(builder, loc), value: { kind: "Debugger", loc }, effects: null, loc }); return; } case "EmptyStatement": { return; } case "TryStatement": { const stmt = stmtPath; const continuationBlock = builder.reserve("block"); const handlerPath = stmt.get("handler"); if (!hasNode(handlerPath)) { builder.errors.push({ reason: `(BuildHIR::lowerStatement) Handle TryStatement without a catch clause`, category: "Todo" /* Todo */, loc: (_U = stmt.node.loc) != null ? _U : null, suggestions: null }); return; } if (hasNode(stmt.get("finalizer"))) { builder.errors.push({ reason: `(BuildHIR::lowerStatement) Handle TryStatement with a finalizer ('finally') clause`, category: "Todo" /* Todo */, loc: (_V = stmt.node.loc) != null ? _V : null, suggestions: null }); } const handlerBindingPath = handlerPath.get("param"); let handlerBinding = null; if (hasNode(handlerBindingPath)) { const place = { kind: "Identifier", identifier: builder.makeTemporary( (_W = handlerBindingPath.node.loc) != null ? _W : GeneratedSource ), effect: "" /* Unknown */, reactive: false, loc: (_X = handlerBindingPath.node.loc) != null ? _X : GeneratedSource }; promoteTemporary(place.identifier); lowerValueToTemporary(builder, { kind: "DeclareLocal", lvalue: { kind: "Catch" /* Catch */, place: __spreadValues({}, place) }, type: null, loc: (_Y = handlerBindingPath.node.loc) != null ? _Y : GeneratedSource }); handlerBinding = { path: handlerBindingPath, place }; } const handler = builder.enter("catch", (_blockId) => { var _a2, _b2; if (handlerBinding !== null) { lowerAssignment( builder, (_a2 = handlerBinding.path.node.loc) != null ? _a2 : GeneratedSource, "Catch" /* Catch */, handlerBinding.path, __spreadValues({}, handlerBinding.place), "Assignment" ); } lowerStatement(builder, handlerPath.get("body")); return { kind: "goto", block: continuationBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_b2 = handlerPath.node.loc) != null ? _b2 : GeneratedSource }; }); const block = builder.enter("block", (_blockId) => { var _a2; const block2 = stmt.get("block"); builder.enterTryCatch(handler, () => { lowerStatement(builder, block2); }); return { kind: "goto", block: continuationBlock.id, variant: "Try" /* Try */, id: makeInstructionId(0), loc: (_a2 = block2.node.loc) != null ? _a2 : GeneratedSource }; }); builder.terminateWithContinuation( { kind: "try", block, handlerBinding: handlerBinding !== null ? __spreadValues({}, handlerBinding.place) : null, handler, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: (_Z = stmt.node.loc) != null ? _Z : GeneratedSource }, continuationBlock ); return; } case "WithStatement": { builder.errors.push({ reason: `JavaScript 'with' syntax is not supported`, description: `'with' syntax is considered deprecated and removed from JavaScript standards, consider alternatives`, category: "UnsupportedSyntax" /* UnsupportedSyntax */, loc: (__ = stmtPath.node.loc) != null ? __ : null, suggestions: null }); lowerValueToTemporary(builder, { kind: "UnsupportedNode", loc: (_$ = stmtPath.node.loc) != null ? _$ : GeneratedSource, node: stmtPath.node }); return; } case "ClassDeclaration": { builder.errors.push({ reason: "Inline `class` declarations are not supported", description: `Move class declarations outside of components/hooks`, category: "UnsupportedSyntax" /* UnsupportedSyntax */, loc: (_aa = stmtPath.node.loc) != null ? _aa : null, suggestions: null }); lowerValueToTemporary(builder, { kind: "UnsupportedNode", loc: (_ba = stmtPath.node.loc) != null ? _ba : GeneratedSource, node: stmtPath.node }); return; } case "EnumDeclaration": case "TSEnumDeclaration": { lowerValueToTemporary(builder, { kind: "UnsupportedNode", loc: (_ca = stmtPath.node.loc) != null ? _ca : GeneratedSource, node: stmtPath.node }); return; } case "ExportAllDeclaration": case "ExportDefaultDeclaration": case "ExportNamedDeclaration": case "ImportDeclaration": case "TSExportAssignment": case "TSImportEqualsDeclaration": { builder.errors.push({ reason: "JavaScript `import` and `export` statements may only appear at the top level of a module", category: "Syntax" /* Syntax */, loc: (_da = stmtPath.node.loc) != null ? _da : null, suggestions: null }); lowerValueToTemporary(builder, { kind: "UnsupportedNode", loc: (_ea = stmtPath.node.loc) != null ? _ea : GeneratedSource, node: stmtPath.node }); return; } case "TSNamespaceExportDeclaration": { builder.errors.push({ reason: "TypeScript `namespace` statements may only appear at the top level of a module", category: "Syntax" /* Syntax */, loc: (_fa = stmtPath.node.loc) != null ? _fa : null, suggestions: null }); lowerValueToTemporary(builder, { kind: "UnsupportedNode", loc: (_ga = stmtPath.node.loc) != null ? _ga : GeneratedSource, node: stmtPath.node }); return; } case "DeclareClass": case "DeclareExportAllDeclaration": case "DeclareExportDeclaration": case "DeclareFunction": case "DeclareInterface": case "DeclareModule": case "DeclareModuleExports": case "DeclareOpaqueType": case "DeclareTypeAlias": case "DeclareVariable": case "InterfaceDeclaration": case "OpaqueType": case "TSDeclareFunction": case "TSInterfaceDeclaration": case "TSModuleDeclaration": case "TSTypeAliasDeclaration": case "TypeAlias": { return; } default: { return assertExhaustive( stmtNode, `Unsupported statement kind '${stmtNode.type}'` ); } } } function lowerObjectMethod(builder, property) { var _a; const loc = (_a = property.node.loc) != null ? _a : GeneratedSource; const loweredFunc = lowerFunction(builder, property); if (!loweredFunc) { return { kind: "UnsupportedNode", node: property.node, loc }; } return { kind: "ObjectMethod", loc, loweredFunc }; } function lowerObjectPropertyKey(builder, property) { var _a, _b; const key2 = property.get("key"); if (key2.isStringLiteral()) { return { kind: "string", name: key2.node.value }; } else if (property.node.computed && key2.isExpression()) { if (!key2.isIdentifier() && !key2.isMemberExpression()) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Expected Identifier, got ${key2.type} key in ObjectExpression`, category: "Todo" /* Todo */, loc: (_a = key2.node.loc) != null ? _a : null, suggestions: null }); return null; } const place = lowerExpressionToTemporary(builder, key2); return { kind: "computed", name: place }; } else if (key2.isIdentifier()) { return { kind: "identifier", name: key2.node.name }; } else if (key2.isNumericLiteral()) { return { kind: "identifier", name: String(key2.node.value) }; } builder.errors.push({ reason: `(BuildHIR::lowerExpression) Expected Identifier, got ${key2.type} key in ObjectExpression`, category: "Todo" /* Todo */, loc: (_b = key2.node.loc) != null ? _b : null, suggestions: null }); return null; } function lowerExpression(builder, exprPath) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V; const exprNode = exprPath.node; const exprLoc = (_a = exprNode.loc) != null ? _a : GeneratedSource; switch (exprNode.type) { case "Identifier": { const expr = exprPath; const place = lowerIdentifier(builder, expr); return { kind: getLoadKind(builder, expr), place, loc: exprLoc }; } case "NullLiteral": { return { kind: "Primitive", value: null, loc: exprLoc }; } case "BooleanLiteral": case "NumericLiteral": case "StringLiteral": { const expr = exprPath; const value = expr.node.value; return { kind: "Primitive", value, loc: exprLoc }; } case "ObjectExpression": { const expr = exprPath; const propertyPaths = expr.get("properties"); const properties = []; for (const propertyPath of propertyPaths) { if (propertyPath.isObjectProperty()) { const loweredKey = lowerObjectPropertyKey(builder, propertyPath); if (!loweredKey) { continue; } const valuePath = propertyPath.get("value"); if (!valuePath.isExpression()) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${valuePath.type} values in ObjectExpression`, category: "Todo" /* Todo */, loc: (_b = valuePath.node.loc) != null ? _b : null, suggestions: null }); continue; } const value = lowerExpressionToTemporary(builder, valuePath); properties.push({ kind: "ObjectProperty", type: "property", place: value, key: loweredKey }); } else if (propertyPath.isSpreadElement()) { const place = lowerExpressionToTemporary( builder, propertyPath.get("argument") ); properties.push({ kind: "Spread", place }); } else if (propertyPath.isObjectMethod()) { if (propertyPath.node.kind !== "method") { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${propertyPath.node.kind} functions in ObjectExpression`, category: "Todo" /* Todo */, loc: (_c = propertyPath.node.loc) != null ? _c : null, suggestions: null }); continue; } const method = lowerObjectMethod(builder, propertyPath); const place = lowerValueToTemporary(builder, method); const loweredKey = lowerObjectPropertyKey(builder, propertyPath); if (!loweredKey) { continue; } properties.push({ kind: "ObjectProperty", type: "method", place, key: loweredKey }); } else { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${propertyPath.type} properties in ObjectExpression`, category: "Todo" /* Todo */, loc: (_d = propertyPath.node.loc) != null ? _d : null, suggestions: null }); continue; } } return { kind: "ObjectExpression", properties, loc: exprLoc }; } case "ArrayExpression": { const expr = exprPath; let elements = []; for (const element of expr.get("elements")) { if (element.node == null) { elements.push({ kind: "Hole" }); continue; } else if (element.isExpression()) { elements.push(lowerExpressionToTemporary(builder, element)); } else if (element.isSpreadElement()) { const place = lowerExpressionToTemporary( builder, element.get("argument") ); elements.push({ kind: "Spread", place }); } else { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${element.type} elements in ArrayExpression`, category: "Todo" /* Todo */, loc: (_e = element.node.loc) != null ? _e : null, suggestions: null }); continue; } } return { kind: "ArrayExpression", elements, loc: exprLoc }; } case "NewExpression": { const expr = exprPath; const calleePath = expr.get("callee"); if (!calleePath.isExpression()) { builder.errors.push({ reason: `Expected an expression as the \`new\` expression receiver (v8 intrinsics are not supported)`, description: `Got a \`${calleePath.node.type}\``, category: "Syntax" /* Syntax */, loc: (_f = calleePath.node.loc) != null ? _f : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } const callee = lowerExpressionToTemporary(builder, calleePath); const args = lowerArguments(builder, expr.get("arguments")); return { kind: "NewExpression", callee, args, loc: exprLoc }; } case "OptionalCallExpression": { const expr = exprPath; return lowerOptionalCallExpression(builder, expr, null); } case "CallExpression": { const expr = exprPath; const calleePath = expr.get("callee"); if (!calleePath.isExpression()) { builder.errors.push({ reason: `Expected Expression, got ${calleePath.type} in CallExpression (v8 intrinsics not supported). This error is likely caused by a bug in React Compiler. Please file an issue`, category: "Todo" /* Todo */, loc: (_g = calleePath.node.loc) != null ? _g : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } if (calleePath.isMemberExpression()) { const memberExpr = lowerMemberExpression(builder, calleePath); const propertyPlace = lowerValueToTemporary(builder, memberExpr.value); const args = lowerArguments(builder, expr.get("arguments")); return { kind: "MethodCall", receiver: memberExpr.object, property: __spreadValues({}, propertyPlace), args, loc: exprLoc }; } else { const callee = lowerExpressionToTemporary(builder, calleePath); const args = lowerArguments(builder, expr.get("arguments")); return { kind: "CallExpression", callee, args, loc: exprLoc }; } } case "BinaryExpression": { const expr = exprPath; const leftPath = expr.get("left"); if (!leftPath.isExpression()) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Expected Expression, got ${leftPath.type} lval in BinaryExpression`, category: "Todo" /* Todo */, loc: (_h = leftPath.node.loc) != null ? _h : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } const left = lowerExpressionToTemporary(builder, leftPath); const right = lowerExpressionToTemporary(builder, expr.get("right")); const operator = expr.node.operator; if (operator === "|>") { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Pipe operator not supported`, category: "Todo" /* Todo */, loc: (_i = leftPath.node.loc) != null ? _i : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } return { kind: "BinaryExpression", operator, left, right, loc: exprLoc }; } case "SequenceExpression": { const expr = exprPath; const exprLoc2 = (_j = expr.node.loc) != null ? _j : GeneratedSource; const continuationBlock = builder.reserve(builder.currentBlockKind()); const place = buildTemporaryPlace(builder, exprLoc2); const sequenceBlock = builder.enter("sequence", (_) => { var _a2; let last = null; for (const item of expr.get("expressions")) { last = lowerExpressionToTemporary(builder, item); } if (last === null) { builder.errors.push({ reason: `Expected sequence expression to have at least one expression`, category: "Syntax" /* Syntax */, loc: (_a2 = expr.node.loc) != null ? _a2 : null, suggestions: null }); } else { lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: last, type: null, loc: exprLoc2 }); } return { kind: "goto", id: makeInstructionId(0), block: continuationBlock.id, loc: exprLoc2, variant: "Break" /* Break */ }; }); builder.terminateWithContinuation( { kind: "sequence", block: sequenceBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: exprLoc2 }, continuationBlock ); return { kind: "LoadLocal", place, loc: place.loc }; } case "ConditionalExpression": { const expr = exprPath; const exprLoc2 = (_k = expr.node.loc) != null ? _k : GeneratedSource; const continuationBlock = builder.reserve(builder.currentBlockKind()); const testBlock = builder.reserve("value"); const place = buildTemporaryPlace(builder, exprLoc2); const consequentBlock = builder.enter("value", (_blockId) => { var _a2; const consequentPath = expr.get("consequent"); const consequent = lowerExpressionToTemporary(builder, consequentPath); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: consequent, type: null, loc: exprLoc2 }); return { kind: "goto", block: continuationBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_a2 = consequentPath.node.loc) != null ? _a2 : GeneratedSource }; }); const alternateBlock = builder.enter("value", (_blockId) => { var _a2; const alternatePath = expr.get("alternate"); const alternate = lowerExpressionToTemporary(builder, alternatePath); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: alternate, type: null, loc: exprLoc2 }); return { kind: "goto", block: continuationBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: (_a2 = alternatePath.node.loc) != null ? _a2 : GeneratedSource }; }); builder.terminateWithContinuation( { kind: "ternary", fallthrough: continuationBlock.id, id: makeInstructionId(0), test: testBlock.id, loc: exprLoc2 }, testBlock ); const testPlace = lowerExpressionToTemporary(builder, expr.get("test")); builder.terminateWithContinuation( { kind: "branch", test: __spreadValues({}, testPlace), consequent: consequentBlock, alternate: alternateBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: exprLoc2 }, continuationBlock ); return { kind: "LoadLocal", place, loc: place.loc }; } case "LogicalExpression": { const expr = exprPath; const exprLoc2 = (_l = expr.node.loc) != null ? _l : GeneratedSource; const continuationBlock = builder.reserve(builder.currentBlockKind()); const testBlock = builder.reserve("value"); const place = buildTemporaryPlace(builder, exprLoc2); const leftPlace = buildTemporaryPlace( builder, (_m = expr.get("left").node.loc) != null ? _m : GeneratedSource ); const consequent = builder.enter("value", () => { lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: __spreadValues({}, leftPlace), type: null, loc: leftPlace.loc }); return { kind: "goto", block: continuationBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: leftPlace.loc }; }); const alternate = builder.enter("value", () => { const right = lowerExpressionToTemporary(builder, expr.get("right")); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: __spreadValues({}, right), type: null, loc: right.loc }); return { kind: "goto", block: continuationBlock.id, variant: "Break" /* Break */, id: makeInstructionId(0), loc: right.loc }; }); builder.terminateWithContinuation( { kind: "logical", fallthrough: continuationBlock.id, id: makeInstructionId(0), test: testBlock.id, operator: expr.node.operator, loc: exprLoc2 }, testBlock ); const leftValue = lowerExpressionToTemporary(builder, expr.get("left")); builder.push({ id: makeInstructionId(0), lvalue: __spreadValues({}, leftPlace), value: { kind: "LoadLocal", place: leftValue, loc: exprLoc2 }, effects: null, loc: exprLoc2 }); builder.terminateWithContinuation( { kind: "branch", test: __spreadValues({}, leftPlace), consequent, alternate, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: exprLoc2 }, continuationBlock ); return { kind: "LoadLocal", place, loc: place.loc }; } case "AssignmentExpression": { const expr = exprPath; const operator = expr.node.operator; if (operator === "=") { const left2 = expr.get("left"); if (left2.isLVal()) { return lowerAssignment( builder, (_n = left2.node.loc) != null ? _n : GeneratedSource, "Reassign" /* Reassign */, left2, lowerExpressionToTemporary(builder, expr.get("right")), left2.isArrayPattern() || left2.isObjectPattern() ? "Destructure" : "Assignment" ); } else { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Unsupported syntax on the left side of an AssignmentExpression`, description: `Expected an LVal, got: ${left2.type}`, category: "Todo" /* Todo */, loc: (_o = left2.node.loc) != null ? _o : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } } const operators = { "+=": "+", "-=": "-", "/=": "/", "%=": "%", "*=": "*", "**=": "**", "&=": "&", "|=": "|", ">>=": ">>", ">>>=": ">>>", "<<=": "<<", "^=": "^" }; const binaryOperator = operators[operator]; if (binaryOperator == null) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${operator} operators in AssignmentExpression`, category: "Todo" /* Todo */, loc: (_p = expr.node.loc) != null ? _p : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } const left = expr.get("left"); const leftNode = left.node; switch (leftNode.type) { case "Identifier": { const leftExpr = left; const leftPlace = lowerExpressionToTemporary(builder, leftExpr); const right = lowerExpressionToTemporary(builder, expr.get("right")); const binaryPlace = lowerValueToTemporary(builder, { kind: "BinaryExpression", operator: binaryOperator, left: leftPlace, right, loc: exprLoc }); const binding = builder.resolveIdentifier(leftExpr); if (binding.kind === "Identifier") { const identifier4 = lowerIdentifier(builder, leftExpr); const kind = getStoreKind(builder, leftExpr); if (kind === "StoreLocal") { lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { place: __spreadValues({}, identifier4), kind: "Reassign" /* Reassign */ }, value: __spreadValues({}, binaryPlace), type: null, loc: exprLoc }); return { kind: "LoadLocal", place: identifier4, loc: exprLoc }; } else { lowerValueToTemporary(builder, { kind: "StoreContext", lvalue: { place: __spreadValues({}, identifier4), kind: "Reassign" /* Reassign */ }, value: __spreadValues({}, binaryPlace), loc: exprLoc }); return { kind: "LoadContext", place: identifier4, loc: exprLoc }; } } else { const temporary = lowerValueToTemporary(builder, { kind: "StoreGlobal", name: leftExpr.node.name, value: __spreadValues({}, binaryPlace), loc: exprLoc }); return { kind: "LoadLocal", place: temporary, loc: temporary.loc }; } } case "MemberExpression": { const leftExpr = left; const { object: object2, property, value } = lowerMemberExpression( builder, leftExpr ); const previousValuePlace = lowerValueToTemporary(builder, value); const newValuePlace = lowerValueToTemporary(builder, { kind: "BinaryExpression", operator: binaryOperator, left: __spreadValues({}, previousValuePlace), right: lowerExpressionToTemporary(builder, expr.get("right")), loc: (_q = leftExpr.node.loc) != null ? _q : GeneratedSource }); if (typeof property === "string" || typeof property === "number") { return { kind: "PropertyStore", object: __spreadValues({}, object2), property: makePropertyLiteral(property), value: __spreadValues({}, newValuePlace), loc: (_r = leftExpr.node.loc) != null ? _r : GeneratedSource }; } else { return { kind: "ComputedStore", object: __spreadValues({}, object2), property: __spreadValues({}, property), value: __spreadValues({}, newValuePlace), loc: (_s = leftExpr.node.loc) != null ? _s : GeneratedSource }; } } default: { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Expected Identifier or MemberExpression, got ${expr.type} lval in AssignmentExpression`, category: "Todo" /* Todo */, loc: (_t = expr.node.loc) != null ? _t : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } } } case "OptionalMemberExpression": { const expr = exprPath; const { value } = lowerOptionalMemberExpression(builder, expr, null); return { kind: "LoadLocal", place: value, loc: value.loc }; } case "MemberExpression": { const expr = exprPath; const { value } = lowerMemberExpression(builder, expr); const place = lowerValueToTemporary(builder, value); return { kind: "LoadLocal", place, loc: place.loc }; } case "JSXElement": { const expr = exprPath; const opening = expr.get("openingElement"); const openingLoc = (_u = opening.node.loc) != null ? _u : GeneratedSource; const tag = lowerJsxElementName(builder, opening.get("name")); const props = []; for (const attribute of opening.get("attributes")) { if (attribute.isJSXSpreadAttribute()) { const argument = lowerExpressionToTemporary( builder, attribute.get("argument") ); props.push({ kind: "JsxSpreadAttribute", argument }); continue; } if (!attribute.isJSXAttribute()) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${attribute.type} attributes in JSXElement`, category: "Todo" /* Todo */, loc: (_v = attribute.node.loc) != null ? _v : null, suggestions: null }); continue; } const namePath = attribute.get("name"); let propName; if (namePath.isJSXIdentifier()) { propName = namePath.node.name; if (propName.indexOf(":") !== -1) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Unexpected colon in attribute name \`${propName}\``, category: "Todo" /* Todo */, loc: (_w = namePath.node.loc) != null ? _w : null, suggestions: null }); } } else { CompilerError.invariant(namePath.isJSXNamespacedName(), { reason: "Refinement", description: null, details: [ { kind: "error", loc: (_x = namePath.node.loc) != null ? _x : null, message: null } ], suggestions: null }); const namespace = namePath.node.namespace.name; const name = namePath.node.name.name; propName = `${namespace}:${name}`; } const valueExpr = attribute.get("value"); let value; if (valueExpr.isJSXElement() || valueExpr.isStringLiteral()) { value = lowerExpressionToTemporary(builder, valueExpr); } else if (valueExpr.type == null) { value = lowerValueToTemporary(builder, { kind: "Primitive", value: true, loc: (_y = attribute.node.loc) != null ? _y : GeneratedSource }); } else { if (!valueExpr.isJSXExpressionContainer()) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${valueExpr.type} attribute values in JSXElement`, category: "Todo" /* Todo */, loc: (_A = (_z = valueExpr.node) == null ? void 0 : _z.loc) != null ? _A : null, suggestions: null }); continue; } const expression = valueExpr.get("expression"); if (!expression.isExpression()) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${expression.type} expressions in JSXExpressionContainer within JSXElement`, category: "Todo" /* Todo */, loc: (_B = valueExpr.node.loc) != null ? _B : null, suggestions: null }); continue; } value = lowerExpressionToTemporary(builder, expression); } props.push({ kind: "JsxAttribute", name: propName, place: value }); } const isFbt = tag.kind === "BuiltinTag" && (tag.name === "fbt" || tag.name === "fbs"); if (isFbt) { const tagName = tag.name; const openingIdentifier = opening.get("name"); const tagIdentifier = openingIdentifier.isJSXIdentifier() ? builder.resolveIdentifier(openingIdentifier) : null; if (tagIdentifier != null) { CompilerError.invariant(tagIdentifier.kind !== "Identifier", { reason: `<${tagName}> tags should be module-level imports`, description: null, details: [ { kind: "error", loc: (_C = openingIdentifier.node.loc) != null ? _C : GeneratedSource, message: null } ], suggestions: null }); } const fbtLocations = { enum: new Array(), plural: new Array(), pronoun: new Array() }; expr.traverse({ JSXClosingElement(path) { path.skip(); }, JSXNamespacedName(path) { var _a2, _b2, _c2; if (path.node.namespace.name === tagName) { switch (path.node.name.name) { case "enum": fbtLocations.enum.push((_a2 = path.node.loc) != null ? _a2 : GeneratedSource); break; case "plural": fbtLocations.plural.push((_b2 = path.node.loc) != null ? _b2 : GeneratedSource); break; case "pronoun": fbtLocations.pronoun.push((_c2 = path.node.loc) != null ? _c2 : GeneratedSource); break; } } } }); for (const [name, locations] of Object.entries(fbtLocations)) { if (locations.length > 1) { CompilerError.throwDiagnostic({ category: "Todo" /* Todo */, reason: "Support duplicate fbt tags", description: `Support \`<${tagName}>\` tags with multiple \`<${tagName}:${name}>\` values`, details: locations.map((loc) => { return { kind: "error", message: `Multiple \`<${tagName}:${name}>\` tags found`, loc }; }) }); } } } isFbt && builder.fbtDepth++; const children = expr.get("children").map((child) => lowerJsxElement(builder, child)).filter(notNull); isFbt && builder.fbtDepth--; return { kind: "JsxExpression", tag, props, children: children.length === 0 ? null : children, loc: exprLoc, openingLoc, closingLoc: (_E = (_D = expr.get("closingElement").node) == null ? void 0 : _D.loc) != null ? _E : GeneratedSource }; } case "JSXFragment": { const expr = exprPath; const children = expr.get("children").map((child) => lowerJsxElement(builder, child)).filter(notNull); return { kind: "JsxFragment", children, loc: exprLoc }; } case "ArrowFunctionExpression": case "FunctionExpression": { const expr = exprPath; return lowerFunctionToValue(builder, expr); } case "TaggedTemplateExpression": { const expr = exprPath; if (expr.get("quasi").get("expressions").length !== 0) { builder.errors.push({ reason: "(BuildHIR::lowerExpression) Handle tagged template with interpolations", category: "Todo" /* Todo */, loc: (_F = exprPath.node.loc) != null ? _F : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } CompilerError.invariant(expr.get("quasi").get("quasis").length == 1, { reason: "there should be only one quasi as we don't support interpolations yet", description: null, details: [ { kind: "error", loc: (_G = expr.node.loc) != null ? _G : null, message: null } ], suggestions: null }); const value = expr.get("quasi").get("quasis").at(0).node.value; if (value.raw !== value.cooked) { builder.errors.push({ reason: "(BuildHIR::lowerExpression) Handle tagged template where cooked value is different from raw value", category: "Todo" /* Todo */, loc: (_H = exprPath.node.loc) != null ? _H : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } return { kind: "TaggedTemplateExpression", tag: lowerExpressionToTemporary(builder, expr.get("tag")), value, loc: exprLoc }; } case "TemplateLiteral": { const expr = exprPath; const subexprs = expr.get("expressions"); const quasis = expr.get("quasis"); if (subexprs.length !== quasis.length - 1) { builder.errors.push({ reason: `Unexpected quasi and subexpression lengths in template literal`, category: "Syntax" /* Syntax */, loc: (_I = exprPath.node.loc) != null ? _I : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } if (subexprs.some((e) => !e.isExpression())) { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Handle TSType in TemplateLiteral.`, category: "Todo" /* Todo */, loc: (_J = exprPath.node.loc) != null ? _J : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } const subexprPlaces = subexprs.map( (e) => lowerExpressionToTemporary(builder, e) ); return { kind: "TemplateLiteral", subexprs: subexprPlaces, quasis: expr.get("quasis").map((q) => q.node.value), loc: exprLoc }; } case "UnaryExpression": { let expr = exprPath; if (expr.node.operator === "delete") { const argument = expr.get("argument"); if (argument.isMemberExpression()) { const { object: object2, property } = lowerMemberExpression(builder, argument); if (typeof property === "string" || typeof property === "number") { return { kind: "PropertyDelete", object: object2, property: makePropertyLiteral(property), loc: exprLoc }; } else { return { kind: "ComputedDelete", object: object2, property, loc: exprLoc }; } } else { builder.errors.push({ reason: `Only object properties can be deleted`, category: "Syntax" /* Syntax */, loc: (_K = expr.node.loc) != null ? _K : null, suggestions: [ { description: "Remove this line", range: [expr.node.start, expr.node.end], op: 2 /* Remove */ } ] }); return { kind: "UnsupportedNode", node: expr.node, loc: exprLoc }; } } else if (expr.node.operator === "throw") { builder.errors.push({ reason: `Throw expressions are not supported`, category: "Syntax" /* Syntax */, loc: (_L = expr.node.loc) != null ? _L : null, suggestions: [ { description: "Remove this line", range: [expr.node.start, expr.node.end], op: 2 /* Remove */ } ] }); return { kind: "UnsupportedNode", node: expr.node, loc: exprLoc }; } else { return { kind: "UnaryExpression", operator: expr.node.operator, value: lowerExpressionToTemporary(builder, expr.get("argument")), loc: exprLoc }; } } case "AwaitExpression": { let expr = exprPath; return { kind: "Await", value: lowerExpressionToTemporary(builder, expr.get("argument")), loc: exprLoc }; } case "TypeCastExpression": { let expr = exprPath; const typeAnnotation2 = expr.get("typeAnnotation").get("typeAnnotation"); return { kind: "TypeCastExpression", value: lowerExpressionToTemporary(builder, expr.get("expression")), typeAnnotation: typeAnnotation2.node, typeAnnotationKind: "cast", type: lowerType(typeAnnotation2.node), loc: exprLoc }; } case "TSSatisfiesExpression": { let expr = exprPath; const typeAnnotation2 = expr.get("typeAnnotation"); return { kind: "TypeCastExpression", value: lowerExpressionToTemporary(builder, expr.get("expression")), typeAnnotation: typeAnnotation2.node, typeAnnotationKind: "satisfies", type: lowerType(typeAnnotation2.node), loc: exprLoc }; } case "TSAsExpression": { let expr = exprPath; const typeAnnotation2 = expr.get("typeAnnotation"); return { kind: "TypeCastExpression", value: lowerExpressionToTemporary(builder, expr.get("expression")), typeAnnotation: typeAnnotation2.node, typeAnnotationKind: "as", type: lowerType(typeAnnotation2.node), loc: exprLoc }; } case "UpdateExpression": { let expr = exprPath; const argument = expr.get("argument"); if (argument.isMemberExpression()) { const binaryOperator = expr.node.operator === "++" ? "+" : "-"; const leftExpr = argument; const { object: object2, property, value: value2 } = lowerMemberExpression( builder, leftExpr ); const previousValuePlace = lowerValueToTemporary(builder, value2); const updatedValue = lowerValueToTemporary(builder, { kind: "BinaryExpression", operator: binaryOperator, left: __spreadValues({}, previousValuePlace), right: lowerValueToTemporary(builder, { kind: "Primitive", value: 1, loc: GeneratedSource }), loc: (_M = leftExpr.node.loc) != null ? _M : GeneratedSource }); let newValuePlace; if (typeof property === "string" || typeof property === "number") { newValuePlace = lowerValueToTemporary(builder, { kind: "PropertyStore", object: __spreadValues({}, object2), property: makePropertyLiteral(property), value: __spreadValues({}, updatedValue), loc: (_N = leftExpr.node.loc) != null ? _N : GeneratedSource }); } else { newValuePlace = lowerValueToTemporary(builder, { kind: "ComputedStore", object: __spreadValues({}, object2), property: __spreadValues({}, property), value: __spreadValues({}, updatedValue), loc: (_O = leftExpr.node.loc) != null ? _O : GeneratedSource }); } return { kind: "LoadLocal", place: expr.node.prefix ? __spreadValues({}, newValuePlace) : __spreadValues({}, previousValuePlace), loc: exprLoc }; } if (!argument.isIdentifier()) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle UpdateExpression with ${argument.type} argument`, category: "Todo" /* Todo */, loc: (_P = exprPath.node.loc) != null ? _P : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } else if (builder.isContextIdentifier(argument)) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle UpdateExpression to variables captured within lambdas.`, category: "Todo" /* Todo */, loc: (_Q = exprPath.node.loc) != null ? _Q : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } const lvalue = lowerIdentifierForAssignment( builder, (_R = argument.node.loc) != null ? _R : GeneratedSource, "Reassign" /* Reassign */, argument ); if (lvalue === null) { if (!builder.errors.hasAnyErrors()) { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Found an invalid UpdateExpression without a previously reported error`, category: "Invariant" /* Invariant */, loc: exprLoc, suggestions: null }); } return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } else if (lvalue.kind === "Global") { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Support UpdateExpression where argument is a global`, category: "Todo" /* Todo */, loc: exprLoc, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } const value = lowerIdentifier(builder, argument); if (expr.node.prefix) { return { kind: "PrefixUpdate", lvalue, operation: expr.node.operator, value, loc: exprLoc }; } else { return { kind: "PostfixUpdate", lvalue, operation: expr.node.operator, value, loc: exprLoc }; } } case "RegExpLiteral": { let expr = exprPath; return { kind: "RegExpLiteral", pattern: expr.node.pattern, flags: expr.node.flags, loc: (_S = expr.node.loc) != null ? _S : GeneratedSource }; } case "TSInstantiationExpression": case "TSNonNullExpression": { let expr = exprPath; return lowerExpression(builder, expr.get("expression")); } case "MetaProperty": { let expr = exprPath; if (expr.node.meta.name === "import" && expr.node.property.name === "meta") { return { kind: "MetaProperty", meta: expr.node.meta.name, property: expr.node.property.name, loc: (_T = expr.node.loc) != null ? _T : GeneratedSource }; } builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle MetaProperty expressions other than import.meta`, category: "Todo" /* Todo */, loc: (_U = exprPath.node.loc) != null ? _U : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } default: { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${exprPath.type} expressions`, category: "Todo" /* Todo */, loc: (_V = exprPath.node.loc) != null ? _V : null, suggestions: null }); return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } } } function lowerOptionalMemberExpression(builder, expr, parentAlternate) { var _a; const optional2 = expr.node.optional; const loc = (_a = expr.node.loc) != null ? _a : GeneratedSource; const place = buildTemporaryPlace(builder, loc); const continuationBlock = builder.reserve(builder.currentBlockKind()); const consequent = builder.reserve("value"); const alternate = parentAlternate !== null ? parentAlternate : builder.enter("value", () => { const temp = lowerValueToTemporary(builder, { kind: "Primitive", value: void 0, loc }); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: __spreadValues({}, temp), type: null, loc }); return { kind: "goto", variant: "Break" /* Break */, block: continuationBlock.id, id: makeInstructionId(0), loc }; }); let object2 = null; const testBlock = builder.enter("value", () => { const objectPath = expr.get("object"); if (objectPath.isOptionalMemberExpression()) { const { value } = lowerOptionalMemberExpression( builder, objectPath, alternate ); object2 = value; } else if (objectPath.isOptionalCallExpression()) { const value = lowerOptionalCallExpression(builder, objectPath, alternate); object2 = lowerValueToTemporary(builder, value); } else { object2 = lowerExpressionToTemporary(builder, objectPath); } return { kind: "branch", test: __spreadValues({}, object2), consequent: consequent.id, alternate, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc }; }); CompilerError.invariant(object2 !== null, { reason: "Satisfy type checker", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); builder.enterReserved(consequent, () => { const { value } = lowerMemberExpression(builder, expr, object2); const temp = lowerValueToTemporary(builder, value); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: __spreadValues({}, temp), type: null, loc }); return { kind: "goto", variant: "Break" /* Break */, block: continuationBlock.id, id: makeInstructionId(0), loc }; }); builder.terminateWithContinuation( { kind: "optional", optional: optional2, test: testBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc }, continuationBlock ); return { object: object2, value: place }; } function lowerOptionalCallExpression(builder, expr, parentAlternate) { var _a; const optional2 = expr.node.optional; const calleePath = expr.get("callee"); const loc = (_a = expr.node.loc) != null ? _a : GeneratedSource; const place = buildTemporaryPlace(builder, loc); const continuationBlock = builder.reserve(builder.currentBlockKind()); const consequent = builder.reserve("value"); const alternate = parentAlternate !== null ? parentAlternate : builder.enter("value", () => { const temp = lowerValueToTemporary(builder, { kind: "Primitive", value: void 0, loc }); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: __spreadValues({}, temp), type: null, loc }); return { kind: "goto", variant: "Break" /* Break */, block: continuationBlock.id, id: makeInstructionId(0), loc }; }); let callee; const testBlock = builder.enter("value", () => { if (calleePath.isOptionalCallExpression()) { const value = lowerOptionalCallExpression(builder, calleePath, alternate); const valuePlace = lowerValueToTemporary(builder, value); callee = { kind: "CallExpression", callee: valuePlace }; } else if (calleePath.isOptionalMemberExpression()) { const { object: object2, value } = lowerOptionalMemberExpression( builder, calleePath, alternate ); callee = { kind: "MethodCall", receiver: object2, property: value }; } else if (calleePath.isMemberExpression()) { const memberExpr = lowerMemberExpression(builder, calleePath); const propertyPlace = lowerValueToTemporary(builder, memberExpr.value); callee = { kind: "MethodCall", receiver: memberExpr.object, property: propertyPlace }; } else { callee = { kind: "CallExpression", callee: lowerExpressionToTemporary(builder, calleePath) }; } const testPlace = callee.kind === "CallExpression" ? callee.callee : callee.property; return { kind: "branch", test: __spreadValues({}, testPlace), consequent: consequent.id, alternate, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc }; }); builder.enterReserved(consequent, () => { const args = lowerArguments(builder, expr.get("arguments")); const temp = buildTemporaryPlace(builder, loc); if (callee.kind === "CallExpression") { builder.push({ id: makeInstructionId(0), lvalue: __spreadValues({}, temp), value: { kind: "CallExpression", callee: __spreadValues({}, callee.callee), args, loc }, effects: null, loc }); } else { builder.push({ id: makeInstructionId(0), lvalue: __spreadValues({}, temp), value: { kind: "MethodCall", receiver: __spreadValues({}, callee.receiver), property: __spreadValues({}, callee.property), args, loc }, effects: null, loc }); } lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, place) }, value: __spreadValues({}, temp), type: null, loc }); return { kind: "goto", variant: "Break" /* Break */, block: continuationBlock.id, id: makeInstructionId(0), loc }; }); builder.terminateWithContinuation( { kind: "optional", optional: optional2, test: testBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc }, continuationBlock ); return { kind: "LoadLocal", place, loc: place.loc }; } function lowerReorderableExpression(builder, expr) { var _a; if (!isReorderableExpression(builder, expr, true)) { builder.errors.push({ reason: `(BuildHIR::node.lowerReorderableExpression) Expression type \`${expr.type}\` cannot be safely reordered`, category: "Todo" /* Todo */, loc: (_a = expr.node.loc) != null ? _a : null, suggestions: null }); } return lowerExpressionToTemporary(builder, expr); } function isReorderableExpression(builder, expr, allowLocalIdentifiers) { switch (expr.node.type) { case "Identifier": { const binding = builder.resolveIdentifier(expr); if (binding.kind === "Identifier") { return allowLocalIdentifiers; } else { return true; } } case "TSInstantiationExpression": { const innerExpr = expr.get( "expression" ); return isReorderableExpression(builder, innerExpr, allowLocalIdentifiers); } case "RegExpLiteral": case "StringLiteral": case "NumericLiteral": case "NullLiteral": case "BooleanLiteral": case "BigIntLiteral": { return true; } case "UnaryExpression": { const unary = expr; switch (expr.node.operator) { case "!": case "+": case "-": { return isReorderableExpression( builder, unary.get("argument"), allowLocalIdentifiers ); } default: { return false; } } } case "TSAsExpression": case "TSNonNullExpression": case "TypeCastExpression": { return isReorderableExpression( builder, expr.get("expression"), allowLocalIdentifiers ); } case "LogicalExpression": { const logical = expr; return isReorderableExpression( builder, logical.get("left"), allowLocalIdentifiers ) && isReorderableExpression( builder, logical.get("right"), allowLocalIdentifiers ); } case "ConditionalExpression": { const conditional = expr; return isReorderableExpression( builder, conditional.get("test"), allowLocalIdentifiers ) && isReorderableExpression( builder, conditional.get("consequent"), allowLocalIdentifiers ) && isReorderableExpression( builder, conditional.get("alternate"), allowLocalIdentifiers ); } case "ArrayExpression": { return expr.get("elements").every( (element) => element.isExpression() && isReorderableExpression(builder, element, allowLocalIdentifiers) ); } case "ObjectExpression": { return expr.get("properties").every((property) => { if (!property.isObjectProperty() || property.node.computed) { return false; } const value = property.get("value"); return value.isExpression() && isReorderableExpression(builder, value, allowLocalIdentifiers); }); } case "MemberExpression": { const test = expr; let innerObject = test; while (innerObject.isMemberExpression()) { innerObject = innerObject.get("object"); } if (innerObject.isIdentifier() && builder.resolveIdentifier(innerObject).kind !== "Identifier") { return true; } else { return false; } } case "ArrowFunctionExpression": { const fn = expr; const body = fn.get("body"); if (body.node.type === "BlockStatement") { return body.node.body.length === 0; } else { (0, import_invariant2.default)(body.isExpression(), "Expected an expression"); return isReorderableExpression( builder, body, /* disallow local identifiers in the body */ false ); } } case "CallExpression": { const call = expr; const callee = call.get("callee"); return callee.isExpression() && isReorderableExpression(builder, callee, allowLocalIdentifiers) && call.get("arguments").every( (arg) => arg.isExpression() && isReorderableExpression(builder, arg, allowLocalIdentifiers) ); } default: { return false; } } } function lowerArguments(builder, expr) { var _a; let args = []; for (const argPath of expr) { if (argPath.isSpreadElement()) { args.push({ kind: "Spread", place: lowerExpressionToTemporary(builder, argPath.get("argument")) }); } else if (argPath.isExpression()) { args.push(lowerExpressionToTemporary(builder, argPath)); } else { builder.errors.push({ reason: `(BuildHIR::lowerExpression) Handle ${argPath.type} arguments in CallExpression`, category: "Todo" /* Todo */, loc: (_a = argPath.node.loc) != null ? _a : null, suggestions: null }); } } return args; } function lowerMemberExpression(builder, expr, loweredObject = null) { var _a, _b, _c; const exprNode = expr.node; const exprLoc = (_a = exprNode.loc) != null ? _a : GeneratedSource; const objectNode = expr.get("object"); const propertyNode = expr.get("property"); const object2 = loweredObject != null ? loweredObject : lowerExpressionToTemporary(builder, objectNode); if (!expr.node.computed || expr.node.property.type === "NumericLiteral") { let property; if (propertyNode.isIdentifier()) { property = makePropertyLiteral(propertyNode.node.name); } else if (propertyNode.isNumericLiteral()) { property = makePropertyLiteral(propertyNode.node.value); } else { builder.errors.push({ reason: `(BuildHIR::lowerMemberExpression) Handle ${propertyNode.type} property`, category: "Todo" /* Todo */, loc: (_b = propertyNode.node.loc) != null ? _b : null, suggestions: null }); return { object: object2, property: propertyNode.toString(), value: { kind: "UnsupportedNode", node: exprNode, loc: exprLoc } }; } const value = { kind: "PropertyLoad", object: __spreadValues({}, object2), property, loc: exprLoc }; return { object: object2, property, value }; } else { if (!propertyNode.isExpression()) { builder.errors.push({ reason: `(BuildHIR::lowerMemberExpression) Expected Expression, got ${propertyNode.type} property`, category: "Todo" /* Todo */, loc: (_c = propertyNode.node.loc) != null ? _c : null, suggestions: null }); return { object: object2, property: propertyNode.toString(), value: { kind: "UnsupportedNode", node: exprNode, loc: exprLoc } }; } const property = lowerExpressionToTemporary(builder, propertyNode); const value = { kind: "ComputedLoad", object: __spreadValues({}, object2), property: __spreadValues({}, property), loc: exprLoc }; return { object: object2, property, value }; } } function lowerJsxElementName(builder, exprPath) { var _a, _b, _c; const exprNode = exprPath.node; const exprLoc = (_a = exprNode.loc) != null ? _a : GeneratedSource; if (exprPath.isJSXIdentifier()) { const tag = exprPath.node.name; if (tag.match(/^[A-Z]/)) { const kind = getLoadKind(builder, exprPath); return lowerValueToTemporary(builder, { kind, place: lowerIdentifier(builder, exprPath), loc: exprLoc }); } else { return { kind: "BuiltinTag", name: tag, loc: exprLoc }; } } else if (exprPath.isJSXMemberExpression()) { return lowerJsxMemberExpression(builder, exprPath); } else if (exprPath.isJSXNamespacedName()) { const namespace = exprPath.node.namespace.name; const name = exprPath.node.name.name; const tag = `${namespace}:${name}`; if (namespace.indexOf(":") !== -1 || name.indexOf(":") !== -1) { builder.errors.push({ reason: `Expected JSXNamespacedName to have no colons in the namespace or name`, description: `Got \`${namespace}\` : \`${name}\``, category: "Syntax" /* Syntax */, loc: (_b = exprPath.node.loc) != null ? _b : null, suggestions: null }); } const place = lowerValueToTemporary(builder, { kind: "Primitive", value: tag, loc: exprLoc }); return place; } else { builder.errors.push({ reason: `(BuildHIR::lowerJsxElementName) Handle ${exprPath.type} tags`, category: "Todo" /* Todo */, loc: (_c = exprPath.node.loc) != null ? _c : null, suggestions: null }); return lowerValueToTemporary(builder, { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }); } } function lowerJsxMemberExpression(builder, exprPath) { var _a, _b, _c; const loc = (_a = exprPath.node.loc) != null ? _a : GeneratedSource; const object2 = exprPath.get("object"); let objectPlace; if (object2.isJSXMemberExpression()) { objectPlace = lowerJsxMemberExpression(builder, object2); } else { CompilerError.invariant(object2.isJSXIdentifier(), { reason: `TypeScript refinement fail: expected 'JsxIdentifier', got \`${object2.node.type}\``, description: null, details: [ { kind: "error", loc: (_b = object2.node.loc) != null ? _b : null, message: null } ], suggestions: null }); const kind = getLoadKind(builder, object2); objectPlace = lowerValueToTemporary(builder, { kind, place: lowerIdentifier(builder, object2), loc: (_c = exprPath.node.loc) != null ? _c : GeneratedSource }); } const property = exprPath.get("property").node.name; return lowerValueToTemporary(builder, { kind: "PropertyLoad", object: objectPlace, property: makePropertyLiteral(property), loc }); } function lowerJsxElement(builder, exprPath) { var _a, _b, _c; const exprNode = exprPath.node; const exprLoc = (_a = exprNode.loc) != null ? _a : GeneratedSource; if (exprPath.isJSXElement() || exprPath.isJSXFragment()) { return lowerExpressionToTemporary(builder, exprPath); } else if (exprPath.isJSXExpressionContainer()) { const expression = exprPath.get("expression"); if (expression.isJSXEmptyExpression()) { return null; } else { CompilerError.invariant(expression.isExpression(), { reason: `(BuildHIR::lowerJsxElement) Expected Expression but found ${expression.type}!`, description: null, details: [ { kind: "error", loc: (_b = expression.node.loc) != null ? _b : null, message: null } ], suggestions: null }); return lowerExpressionToTemporary(builder, expression); } } else if (exprPath.isJSXText()) { let text; if (builder.fbtDepth > 0) { text = exprPath.node.value; } else { text = trimJsxText(exprPath.node.value); } if (text === null) { return null; } const place = lowerValueToTemporary(builder, { kind: "JSXText", value: text, loc: exprLoc }); return place; } else { builder.errors.push({ reason: `(BuildHIR::lowerJsxElement) Unhandled JsxElement, got: ${exprPath.type}`, category: "Todo" /* Todo */, loc: (_c = exprPath.node.loc) != null ? _c : null, suggestions: null }); const place = lowerValueToTemporary(builder, { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }); return place; } } function trimJsxText(original) { const lines = original.split(/\r\n|\n|\r/); let lastNonEmptyLine = 0; for (let i = 0; i < lines.length; i++) { if (lines[i].match(/[^ \t]/)) { lastNonEmptyLine = i; } } let str = ""; for (let i = 0; i < lines.length; i++) { const line2 = lines[i]; const isFirstLine = i === 0; const isLastLine = i === lines.length - 1; const isLastNonEmptyLine = i === lastNonEmptyLine; let trimmedLine = line2.replace(/\t/g, " "); if (!isFirstLine) { trimmedLine = trimmedLine.replace(/^[ ]+/, ""); } if (!isLastLine) { trimmedLine = trimmedLine.replace(/[ ]+$/, ""); } if (trimmedLine) { if (!isLastNonEmptyLine) { trimmedLine += " "; } str += trimmedLine; } } if (str.length !== 0) { return str; } else { return null; } } function lowerFunctionToValue(builder, expr) { var _a; const exprNode = expr.node; const exprLoc = (_a = exprNode.loc) != null ? _a : GeneratedSource; const loweredFunc = lowerFunction(builder, expr); if (!loweredFunc) { return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc }; } return { kind: "FunctionExpression", name: loweredFunc.func.id, nameHint: null, type: expr.node.type, loc: exprLoc, loweredFunc }; } function lowerFunction(builder, expr) { const componentScope = builder.environment.parentFunction.scope; const capturedContext = gatherCapturedContext(expr, componentScope); const lowering = lower( expr, builder.environment, builder.bindings, new Map([...builder.context, ...capturedContext]) ); let loweredFunc; if (lowering.isErr()) { const functionErrors = lowering.unwrapErr(); builder.errors.merge(functionErrors); return null; } loweredFunc = lowering.unwrap(); return { func: loweredFunc }; } function lowerExpressionToTemporary(builder, exprPath) { const value = lowerExpression(builder, exprPath); return lowerValueToTemporary(builder, value); } function lowerValueToTemporary(builder, value) { if (value.kind === "LoadLocal" && value.place.identifier.name === null) { return value.place; } const place = buildTemporaryPlace(builder, value.loc); builder.push({ id: makeInstructionId(0), lvalue: __spreadValues({}, place), value, effects: null, loc: value.loc }); return place; } function lowerIdentifier(builder, exprPath) { var _a, _b; const exprNode = exprPath.node; const exprLoc = (_a = exprNode.loc) != null ? _a : GeneratedSource; const binding = builder.resolveIdentifier(exprPath); switch (binding.kind) { case "Identifier": { const place = { kind: "Identifier", identifier: binding.identifier, effect: "" /* Unknown */, reactive: false, loc: exprLoc }; return place; } default: { if (binding.kind === "Global" && binding.name === "eval") { builder.errors.push({ reason: `The 'eval' function is not supported`, description: "Eval is an anti-pattern in JavaScript, and the code executed cannot be evaluated by React Compiler", category: "UnsupportedSyntax" /* UnsupportedSyntax */, loc: (_b = exprPath.node.loc) != null ? _b : null, suggestions: null }); } return lowerValueToTemporary(builder, { kind: "LoadGlobal", binding, loc: exprLoc }); } } } function buildTemporaryPlace(builder, loc) { const place = { kind: "Identifier", identifier: builder.makeTemporary(loc), effect: "" /* Unknown */, reactive: false, loc }; return place; } function getStoreKind(builder, identifier4) { const isContext = builder.isContextIdentifier(identifier4); return isContext ? "StoreContext" : "StoreLocal"; } function getLoadKind(builder, identifier4) { const isContext = builder.isContextIdentifier(identifier4); return isContext ? "LoadContext" : "LoadLocal"; } function lowerIdentifierForAssignment(builder, loc, kind, path) { var _a, _b; const binding = builder.resolveIdentifier(path); if (binding.kind !== "Identifier") { if (kind === "Reassign" /* Reassign */) { return { kind: "Global", name: path.node.name }; } else { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Could not find binding for declaration.`, category: "Invariant" /* Invariant */, loc: (_a = path.node.loc) != null ? _a : null, suggestions: null }); return null; } } else if (binding.bindingKind === "const" && kind === "Reassign" /* Reassign */) { builder.errors.push({ reason: `Cannot reassign a \`const\` variable`, category: "Syntax" /* Syntax */, loc: (_b = path.node.loc) != null ? _b : null, description: binding.identifier.name != null ? `\`${binding.identifier.name.value}\` is declared as const` : null }); return null; } const place = { kind: "Identifier", identifier: binding.identifier, effect: "" /* Unknown */, reactive: false, loc }; return place; } function lowerAssignment(builder, loc, kind, lvaluePath, value, assignmentKind) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A; const lvalueNode = lvaluePath.node; switch (lvalueNode.type) { case "Identifier": { const lvalue = lvaluePath; const place = lowerIdentifierForAssignment(builder, loc, kind, lvalue); if (place === null) { return { kind: "UnsupportedNode", loc: (_a = lvalue.node.loc) != null ? _a : GeneratedSource, node: lvalue.node }; } else if (place.kind === "Global") { const temporary2 = lowerValueToTemporary(builder, { kind: "StoreGlobal", name: place.name, value, loc }); return { kind: "LoadLocal", place: temporary2, loc: temporary2.loc }; } const isHoistedIdentifier = builder.environment.isHoistedIdentifier( lvalue.node ); let temporary; if (builder.isContextIdentifier(lvalue)) { if (kind === "Const" /* Const */ && !isHoistedIdentifier) { builder.errors.push({ reason: `Expected \`const\` declaration not to be reassigned`, category: "Syntax" /* Syntax */, loc: (_b = lvalue.node.loc) != null ? _b : null, suggestions: null }); } if (kind !== "Const" /* Const */ && kind !== "Reassign" /* Reassign */ && kind !== "Let" /* Let */ && kind !== "Function" /* Function */) { builder.errors.push({ reason: `Unexpected context variable kind`, category: "Syntax" /* Syntax */, loc: (_c = lvalue.node.loc) != null ? _c : null, suggestions: null }); temporary = lowerValueToTemporary(builder, { kind: "UnsupportedNode", node: lvalueNode, loc: (_d = lvalueNode.loc) != null ? _d : GeneratedSource }); } else { temporary = lowerValueToTemporary(builder, { kind: "StoreContext", lvalue: { place: __spreadValues({}, place), kind }, value, loc }); } } else { const typeAnnotation2 = lvalue.get("typeAnnotation"); let type; if (typeAnnotation2.isTSTypeAnnotation()) { const typePath = typeAnnotation2.get("typeAnnotation"); type = typePath.node; } else if (typeAnnotation2.isTypeAnnotation()) { const typePath = typeAnnotation2.get("typeAnnotation"); type = typePath.node; } else { type = null; } temporary = lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { place: __spreadValues({}, place), kind }, value, type, loc }); } return { kind: "LoadLocal", place: temporary, loc: temporary.loc }; } case "MemberExpression": { CompilerError.invariant(kind === "Reassign" /* Reassign */, { reason: "MemberExpression may only appear in an assignment expression", description: null, details: [ { kind: "error", loc: (_e = lvaluePath.node.loc) != null ? _e : null, message: null } ], suggestions: null }); const lvalue = lvaluePath; const property = lvalue.get("property"); const object2 = lowerExpressionToTemporary(builder, lvalue.get("object")); if (!lvalue.node.computed || lvalue.get("property").isNumericLiteral()) { let temporary; if (property.isIdentifier()) { temporary = lowerValueToTemporary(builder, { kind: "PropertyStore", object: object2, property: makePropertyLiteral(property.node.name), value, loc }); } else if (property.isNumericLiteral()) { temporary = lowerValueToTemporary(builder, { kind: "PropertyStore", object: object2, property: makePropertyLiteral(property.node.value), value, loc }); } else { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Handle ${property.type} properties in MemberExpression`, category: "Todo" /* Todo */, loc: (_f = property.node.loc) != null ? _f : null, suggestions: null }); return { kind: "UnsupportedNode", node: lvalueNode, loc }; } return { kind: "LoadLocal", place: temporary, loc: temporary.loc }; } else { if (!property.isExpression()) { builder.errors.push({ reason: "(BuildHIR::lowerAssignment) Expected private name to appear as a non-computed property", category: "Todo" /* Todo */, loc: (_g = property.node.loc) != null ? _g : null, suggestions: null }); return { kind: "UnsupportedNode", node: lvalueNode, loc }; } const propertyPlace = lowerExpressionToTemporary(builder, property); const temporary = lowerValueToTemporary(builder, { kind: "ComputedStore", object: object2, property: propertyPlace, value, loc }); return { kind: "LoadLocal", place: temporary, loc: temporary.loc }; } } case "ArrayPattern": { const lvalue = lvaluePath; const elements = lvalue.get("elements"); const items = []; const followups = []; const forceTemporaries = kind === "Reassign" /* Reassign */ && (elements.some((element) => !element.isIdentifier()) || elements.some( (element) => element.isIdentifier() && (getStoreKind(builder, element) !== "StoreLocal" || builder.resolveIdentifier(element).kind !== "Identifier") )); for (let i = 0; i < elements.length; i++) { const element = elements[i]; if (element.node == null) { items.push({ kind: "Hole" }); continue; } if (element.isRestElement()) { const argument = element.get("argument"); if (argument.isIdentifier() && !forceTemporaries && (assignmentKind === "Assignment" || getStoreKind(builder, argument) === "StoreLocal")) { const identifier4 = lowerIdentifierForAssignment( builder, (_h = element.node.loc) != null ? _h : GeneratedSource, kind, argument ); if (identifier4 === null) { continue; } else if (identifier4.kind === "Global") { builder.errors.push({ category: "Todo" /* Todo */, reason: "Expected reassignment of globals to enable forceTemporaries", loc: (_i = element.node.loc) != null ? _i : GeneratedSource }); continue; } items.push({ kind: "Spread", place: identifier4 }); } else { const temp = buildTemporaryPlace( builder, (_j = element.node.loc) != null ? _j : GeneratedSource ); promoteTemporary(temp.identifier); items.push({ kind: "Spread", place: __spreadValues({}, temp) }); followups.push({ place: temp, path: argument }); } } else if (element.isIdentifier() && !forceTemporaries && (assignmentKind === "Assignment" || getStoreKind(builder, element) === "StoreLocal")) { const identifier4 = lowerIdentifierForAssignment( builder, (_k = element.node.loc) != null ? _k : GeneratedSource, kind, element ); if (identifier4 === null) { continue; } else if (identifier4.kind === "Global") { builder.errors.push({ category: "Todo" /* Todo */, reason: "Expected reassignment of globals to enable forceTemporaries", loc: (_l = element.node.loc) != null ? _l : GeneratedSource }); continue; } items.push(identifier4); } else { const temp = buildTemporaryPlace( builder, (_m = element.node.loc) != null ? _m : GeneratedSource ); promoteTemporary(temp.identifier); items.push(__spreadValues({}, temp)); followups.push({ place: temp, path: element }); } } const temporary = lowerValueToTemporary(builder, { kind: "Destructure", lvalue: { kind, pattern: { kind: "ArrayPattern", items } }, value, loc }); for (const { place, path } of followups) { lowerAssignment( builder, (_n = path.node.loc) != null ? _n : loc, kind, path, place, assignmentKind ); } return { kind: "LoadLocal", place: temporary, loc: value.loc }; } case "ObjectPattern": { const lvalue = lvaluePath; const propertiesPaths = lvalue.get("properties"); const properties = []; const followups = []; const forceTemporaries = kind === "Reassign" /* Reassign */ && propertiesPaths.some( (property) => property.isRestElement() || property.isObjectProperty() && (!property.get("value").isIdentifier() || builder.resolveIdentifier( property.get("value") ).kind !== "Identifier") ); for (let i = 0; i < propertiesPaths.length; i++) { const property = propertiesPaths[i]; if (property.isRestElement()) { const argument = property.get("argument"); if (!argument.isIdentifier()) { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Handle ${argument.node.type} rest element in ObjectPattern`, category: "Todo" /* Todo */, loc: (_o = argument.node.loc) != null ? _o : null, suggestions: null }); continue; } if (forceTemporaries || getStoreKind(builder, argument) === "StoreContext") { const temp = buildTemporaryPlace( builder, (_p = property.node.loc) != null ? _p : GeneratedSource ); promoteTemporary(temp.identifier); properties.push({ kind: "Spread", place: __spreadValues({}, temp) }); followups.push({ place: temp, path: argument }); } else { const identifier4 = lowerIdentifierForAssignment( builder, (_q = property.node.loc) != null ? _q : GeneratedSource, kind, argument ); if (identifier4 === null) { continue; } else if (identifier4.kind === "Global") { builder.errors.push({ category: "Todo" /* Todo */, reason: "Expected reassignment of globals to enable forceTemporaries", loc: (_r = property.node.loc) != null ? _r : GeneratedSource }); continue; } properties.push({ kind: "Spread", place: identifier4 }); } } else { if (!property.isObjectProperty()) { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Handle ${property.type} properties in ObjectPattern`, category: "Todo" /* Todo */, loc: (_s = property.node.loc) != null ? _s : null, suggestions: null }); continue; } if (property.node.computed) { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern`, category: "Todo" /* Todo */, loc: (_t = property.node.loc) != null ? _t : null, suggestions: null }); continue; } const loweredKey = lowerObjectPropertyKey(builder, property); if (!loweredKey) { continue; } const element = property.get("value"); if (!element.isLVal()) { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Expected object property value to be an LVal, got: ${element.type}`, category: "Todo" /* Todo */, loc: (_u = element.node.loc) != null ? _u : null, suggestions: null }); continue; } if (element.isIdentifier() && !forceTemporaries && (assignmentKind === "Assignment" || getStoreKind(builder, element) === "StoreLocal")) { const identifier4 = lowerIdentifierForAssignment( builder, (_v = element.node.loc) != null ? _v : GeneratedSource, kind, element ); if (identifier4 === null) { continue; } else if (identifier4.kind === "Global") { builder.errors.push({ category: "Todo" /* Todo */, reason: "Expected reassignment of globals to enable forceTemporaries", loc: (_w = element.node.loc) != null ? _w : GeneratedSource }); continue; } properties.push({ kind: "ObjectProperty", type: "property", place: identifier4, key: loweredKey }); } else { const temp = buildTemporaryPlace( builder, (_x = element.node.loc) != null ? _x : GeneratedSource ); promoteTemporary(temp.identifier); properties.push({ kind: "ObjectProperty", type: "property", place: __spreadValues({}, temp), key: loweredKey }); followups.push({ place: temp, path: element }); } } } const temporary = lowerValueToTemporary(builder, { kind: "Destructure", lvalue: { kind, pattern: { kind: "ObjectPattern", properties } }, value, loc }); for (const { place, path } of followups) { lowerAssignment( builder, (_y = path.node.loc) != null ? _y : loc, kind, path, place, assignmentKind ); } return { kind: "LoadLocal", place: temporary, loc: value.loc }; } case "AssignmentPattern": { const lvalue = lvaluePath; const loc2 = (_z = lvalue.node.loc) != null ? _z : GeneratedSource; const temp = buildTemporaryPlace(builder, loc2); const testBlock = builder.reserve("value"); const continuationBlock = builder.reserve(builder.currentBlockKind()); const consequent = builder.enter("value", () => { const defaultValue = lowerReorderableExpression( builder, lvalue.get("right") ); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, temp) }, value: __spreadValues({}, defaultValue), type: null, loc: loc2 }); return { kind: "goto", variant: "Break" /* Break */, block: continuationBlock.id, id: makeInstructionId(0), loc: loc2 }; }); const alternate = builder.enter("value", () => { lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, temp) }, value: __spreadValues({}, value), type: null, loc: loc2 }); return { kind: "goto", variant: "Break" /* Break */, block: continuationBlock.id, id: makeInstructionId(0), loc: loc2 }; }); builder.terminateWithContinuation( { kind: "ternary", test: testBlock.id, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: loc2 }, testBlock ); const undef = lowerValueToTemporary(builder, { kind: "Primitive", value: void 0, loc: loc2 }); const test = lowerValueToTemporary(builder, { kind: "BinaryExpression", left: __spreadValues({}, value), operator: "===", right: __spreadValues({}, undef), loc: loc2 }); builder.terminateWithContinuation( { kind: "branch", test: __spreadValues({}, test), consequent, alternate, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: loc2 }, continuationBlock ); return lowerAssignment( builder, loc2, kind, lvalue.get("left"), temp, assignmentKind ); } default: { builder.errors.push({ reason: `(BuildHIR::lowerAssignment) Handle ${lvaluePath.type} assignments`, category: "Todo" /* Todo */, loc: (_A = lvaluePath.node.loc) != null ? _A : null, suggestions: null }); return { kind: "UnsupportedNode", node: lvalueNode, loc }; } } } function captureScopes({ from, to }) { let scopes = /* @__PURE__ */ new Set(); while (from) { scopes.add(from); if (from === to) { break; } from = from.parent; } return scopes; } function gatherCapturedContext(fn, componentScope) { const capturedIds = /* @__PURE__ */ new Map(); const pureScopes = captureScopes({ from: fn.scope.parent, to: componentScope }); function handleMaybeDependency(path) { var _a, _b; let baseIdentifier; if (path.isJSXOpeningElement()) { const name = path.get("name"); if (!(name.isJSXMemberExpression() || name.isJSXIdentifier())) { return; } let current = name; while (current.isJSXMemberExpression()) { current = current.get("object"); } (0, import_invariant2.default)( current.isJSXIdentifier(), "Invalid logic in gatherCapturedDeps" ); baseIdentifier = current; } else { baseIdentifier = path; } path.skip(); const binding = baseIdentifier.scope.getBinding(baseIdentifier.node.name); if (binding !== void 0 && pureScopes.has(binding.scope) && !capturedIds.has(binding.identifier)) { capturedIds.set( binding.identifier, (_b = (_a = path.node.loc) != null ? _a : binding.identifier.loc) != null ? _b : GeneratedSource ); } } fn.traverse({ TypeAnnotation(path) { path.skip(); }, TSTypeAnnotation(path) { path.skip(); }, TypeAlias(path) { path.skip(); }, TSTypeAliasDeclaration(path) { path.skip(); }, Expression(path) { if (path.isAssignmentExpression()) { const left = path.get("left"); if (left.isIdentifier()) { handleMaybeDependency(left); } return; } else if (path.isJSXElement()) { handleMaybeDependency(path.get("openingElement")); } else if (path.isIdentifier()) { handleMaybeDependency(path); } } }); return capturedIds; } function notNull(value) { return value !== null; } function lowerType(node) { switch (node.type) { case "GenericTypeAnnotation": { const id = node.id; if (id.type === "Identifier" && id.name === "Array") { return { kind: "Object", shapeId: BuiltInArrayId }; } return makeType(); } case "TSTypeReference": { const typeName = node.typeName; if (typeName.type === "Identifier" && typeName.name === "Array") { return { kind: "Object", shapeId: BuiltInArrayId }; } return makeType(); } case "ArrayTypeAnnotation": case "TSArrayType": { return { kind: "Object", shapeId: BuiltInArrayId }; } case "BooleanLiteralTypeAnnotation": case "BooleanTypeAnnotation": case "NullLiteralTypeAnnotation": case "NumberLiteralTypeAnnotation": case "NumberTypeAnnotation": case "StringLiteralTypeAnnotation": case "StringTypeAnnotation": case "TSBooleanKeyword": case "TSNullKeyword": case "TSNumberKeyword": case "TSStringKeyword": case "TSSymbolKeyword": case "TSUndefinedKeyword": case "TSVoidKeyword": case "VoidTypeAnnotation": { return { kind: "Primitive" }; } default: { return makeType(); } } } // src/HIR/BuildReactiveScopeTerminalsHIR.ts function buildReactiveScopeTerminalsHIR(fn) { const queuedRewrites = []; recursivelyTraverseItems( [...getScopes(fn)], (scope) => scope.range, { fallthroughs: /* @__PURE__ */ new Map(), rewrites: queuedRewrites, env: fn.env }, pushStartScopeTerminal, pushEndScopeTerminal ); const rewrittenFinalBlocks = /* @__PURE__ */ new Map(); const nextBlocks = /* @__PURE__ */ new Map(); queuedRewrites.reverse(); for (const [, block] of fn.body.blocks) { const context = { nextBlockId: block.id, rewrites: [], nextPreds: block.preds, instrSliceIdx: 0, source: block }; for (let i = 0; i < block.instructions.length + 1; i++) { const instrId = i < block.instructions.length ? block.instructions[i].id : block.terminal.id; let rewrite = queuedRewrites.at(-1); while (rewrite != null && rewrite.instrId <= instrId) { handleRewrite(rewrite, i, context); queuedRewrites.pop(); rewrite = queuedRewrites.at(-1); } } if (context.rewrites.length > 0) { const finalBlock = { id: context.nextBlockId, kind: block.kind, preds: context.nextPreds, terminal: block.terminal, instructions: block.instructions.slice(context.instrSliceIdx), phis: /* @__PURE__ */ new Set() }; context.rewrites.push(finalBlock); for (const b of context.rewrites) { nextBlocks.set(b.id, b); } rewrittenFinalBlocks.set(block.id, finalBlock.id); } else { nextBlocks.set(block.id, block); } } const originalBlocks = fn.body.blocks; fn.body.blocks = nextBlocks; for (const [, block] of originalBlocks) { for (const phi of block.phis) { for (const [originalId, value] of phi.operands) { const newId = rewrittenFinalBlocks.get(originalId); if (newId != null) { phi.operands.delete(originalId); phi.operands.set(newId, value); } } } } reversePostorderBlocks(fn.body); markPredecessors(fn.body); markInstructionIds(fn.body); fixScopeAndIdentifierRanges(fn.body); } function pushStartScopeTerminal(scope, context) { const blockId = context.env.nextBlockId; const fallthroughId = context.env.nextBlockId; context.rewrites.push({ kind: "StartScope", blockId, fallthroughId, instrId: scope.range.start, scope }); context.fallthroughs.set(scope.id, fallthroughId); } function pushEndScopeTerminal(scope, context) { const fallthroughId = context.fallthroughs.get(scope.id); CompilerError.invariant(fallthroughId != null, { reason: "Expected scope to exist", description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); context.rewrites.push({ kind: "EndScope", fallthroughId, instrId: scope.range.end }); } function handleRewrite(terminalInfo, idx, context) { const terminal = terminalInfo.kind === "StartScope" ? { kind: "scope", fallthrough: terminalInfo.fallthroughId, block: terminalInfo.blockId, scope: terminalInfo.scope, id: terminalInfo.instrId, loc: GeneratedSource } : { kind: "goto", variant: "Break" /* Break */, block: terminalInfo.fallthroughId, id: terminalInfo.instrId, loc: GeneratedSource }; const currBlockId = context.nextBlockId; context.rewrites.push({ kind: context.source.kind, id: currBlockId, instructions: context.source.instructions.slice(context.instrSliceIdx, idx), preds: context.nextPreds, // Only the first rewrite should reuse source block phis phis: context.rewrites.length === 0 ? context.source.phis : /* @__PURE__ */ new Set(), terminal }); context.nextPreds = /* @__PURE__ */ new Set([currBlockId]); context.nextBlockId = terminalInfo.kind === "StartScope" ? terminalInfo.blockId : terminalInfo.fallthroughId; context.instrSliceIdx = idx; } // src/HIR/Dominator.ts var import_pretty_format = __toESM(require_build()); function computePostDominatorTree(fn, options) { const graph = buildReverseGraph(fn, options.includeThrowsAsExitNode); const nodes = computeImmediateDominators(graph); if (!options.includeThrowsAsExitNode) { for (const [id] of fn.body.blocks) { if (!nodes.has(id)) { nodes.set(id, id); } } } return new PostDominator(graph.entry, nodes); } var _exit, _nodes; var PostDominator = class { constructor(exit, nodes) { __privateAdd(this, _exit); __privateAdd(this, _nodes); __privateSet(this, _exit, exit); __privateSet(this, _nodes, nodes); } // Returns the node representing normal exit from the function, ie return terminals. get exit() { return __privateGet(this, _exit); } /* * Returns the immediate dominator of the block with @param id if present. Returns null * if there is no immediate dominator (ie if the dominator is @param id itself). */ get(id) { const dominator = __privateGet(this, _nodes).get(id); CompilerError.invariant(dominator !== void 0, { reason: "Unknown node", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return dominator === id ? null : dominator; } debug() { const postDominators = /* @__PURE__ */ new Map(); for (const [key2, value] of __privateGet(this, _nodes)) { postDominators.set(`bb${key2}`, `bb${value}`); } return (0, import_pretty_format.default)({ exit: `bb${this.exit}`, postDominators }); } }; _exit = new WeakMap(); _nodes = new WeakMap(); function computeImmediateDominators(graph) { const nodes = /* @__PURE__ */ new Map(); nodes.set(graph.entry, graph.entry); let changed = true; while (changed) { changed = false; for (const [id, node] of graph.nodes) { if (node.id === graph.entry) { continue; } let newIdom = null; for (const pred of node.preds) { if (nodes.has(pred)) { newIdom = pred; break; } } CompilerError.invariant(newIdom !== null, { reason: `At least one predecessor must have been visited for block ${id}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); for (const pred of node.preds) { if (pred === newIdom) { continue; } const predDom = nodes.get(pred); if (predDom !== void 0) { newIdom = intersect(pred, newIdom, graph, nodes); } } if (nodes.get(id) !== newIdom) { nodes.set(id, newIdom); changed = true; } } } return nodes; } function intersect(a, b, graph, nodes) { let block1 = graph.nodes.get(a); let block2 = graph.nodes.get(b); while (block1 !== block2) { while (block1.index > block2.index) { const dom = nodes.get(block1.id); block1 = graph.nodes.get(dom); } while (block2.index > block1.index) { const dom = nodes.get(block2.id); block2 = graph.nodes.get(dom); } } return block1.id; } function buildReverseGraph(fn, includeThrowsAsExitNode) { const nodes = /* @__PURE__ */ new Map(); const exitId = fn.env.nextBlockId; const exit = { id: exitId, index: 0, preds: /* @__PURE__ */ new Set(), succs: /* @__PURE__ */ new Set() }; nodes.set(exitId, exit); for (const [id, block] of fn.body.blocks) { const node = { id, index: 0, preds: new Set(eachTerminalSuccessor(block.terminal)), succs: new Set(block.preds) }; if (block.terminal.kind === "return") { node.preds.add(exitId); exit.succs.add(id); } else if (block.terminal.kind === "throw" && includeThrowsAsExitNode) { node.preds.add(exitId); exit.succs.add(id); } nodes.set(id, node); } const visited = /* @__PURE__ */ new Set(); const postorder = []; function visit4(id) { if (visited.has(id)) { return; } visited.add(id); const node = nodes.get(id); for (const successor of node.succs) { visit4(successor); } postorder.push(id); } visit4(exitId); const rpo = { entry: exitId, nodes: /* @__PURE__ */ new Map() }; let index = 0; for (const id of postorder.reverse()) { const node = nodes.get(id); node.index = index++; rpo.nodes.set(id, node); } return rpo; } // ../../node_modules/zod-validation-error/v4/index.mjs function isZodErrorLike(err) { return err instanceof Object && "name" in err && (err.name === "ZodError" || err.name === "$ZodError") && "issues" in err && Array.isArray(err.issues); } var ZOD_VALIDATION_ERROR_NAME = "ZodValidationError"; var ValidationError = class extends Error { constructor(message, options) { super(message, options); __publicField(this, "name"); __publicField(this, "details"); this.name = ZOD_VALIDATION_ERROR_NAME; this.details = getIssuesFromErrorOptions(options); } toString() { return this.message; } }; function getIssuesFromErrorOptions(options) { if (options) { const cause = options.cause; if (isZodErrorLike(cause)) { return cause.issues; } } return []; } function stringifySymbol(symbol2) { var _a; return (_a = symbol2.description) != null ? _a : ""; } function isNonEmptyArray(value) { return value.length !== 0; } var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u; function joinPath(path) { if (path.length === 1) { let propertyKey = path[0]; if (typeof propertyKey === "symbol") { propertyKey = stringifySymbol(propertyKey); } return propertyKey.toString() || '""'; } return path.reduce((acc, propertyKey) => { if (typeof propertyKey === "number") { return acc + "[" + propertyKey.toString() + "]"; } if (typeof propertyKey === "symbol") { propertyKey = stringifySymbol(propertyKey); } if (propertyKey.includes('"')) { return acc + '["' + escapeQuotes(propertyKey) + '"]'; } if (!identifierRegex.test(propertyKey)) { return acc + '["' + propertyKey + '"]'; } const separator = acc.length === 0 ? "" : "."; return acc + separator + propertyKey; }, ""); } function escapeQuotes(str) { return str.replace(/"/g, '\\"'); } function titleCase(value) { if (value.length === 0) { return value; } return value.charAt(0).toUpperCase() + value.slice(1); } var defaultMessageBuilderOptions = { prefix: "Validation error", prefixSeparator: ": ", maxIssuesInMessage: 99, // I've got 99 problems but the b$tch ain't one unionSeparator: " or ", issueSeparator: "; ", includePath: true, forceTitleCase: true }; function createMessageBuilder(partialOptions = {}) { const options = __spreadValues(__spreadValues({}, defaultMessageBuilderOptions), partialOptions); return function messageBuilder(issues) { const message = issues.slice(0, options.maxIssuesInMessage).map((issue2) => mapIssue(issue2, options)).join(options.issueSeparator); return conditionallyPrefixMessage(message, options); }; } function mapIssue(issue2, options) { if (issue2.code === "invalid_union" && isNonEmptyArray(issue2.errors)) { const individualMessages = issue2.errors.map( (issues) => issues.map( (subIssue) => mapIssue( __spreadProps(__spreadValues({}, subIssue), { path: issue2.path.concat(subIssue.path) }), options ) ).join(options.issueSeparator) ); return Array.from(new Set(individualMessages)).join(options.unionSeparator); } const buf = []; if (options.forceTitleCase) { buf.push(titleCase(issue2.message)); } else { buf.push(issue2.message); } pathCondition: if (options.includePath && issue2.path !== void 0 && isNonEmptyArray(issue2.path)) { if (issue2.path.length === 1) { const identifier4 = issue2.path[0]; if (typeof identifier4 === "number") { buf.push(` at index ${identifier4}`); break pathCondition; } } buf.push(` at "${joinPath(issue2.path)}"`); } return buf.join(""); } function conditionallyPrefixMessage(message, options) { if (options.prefix != null) { if (message.length > 0) { return [options.prefix, message].join(options.prefixSeparator); } return options.prefix; } if (message.length > 0) { return message; } return defaultMessageBuilderOptions.prefix; } function fromZodError(zodError, options = {}) { if (!isZodErrorLike(zodError)) { throw new TypeError( `Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?` ); } return fromZodErrorWithoutRuntimeCheck(zodError, options); } function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) { const zodIssues = zodError.issues; let message; if (isNonEmptyArray(zodIssues)) { const messageBuilder = createMessageBuilderFromOptions(options); message = messageBuilder(zodIssues); } else { message = zodError.message; } return new ValidationError(message, { cause: zodError }); } function createMessageBuilderFromOptions(options) { if ("messageBuilder" in options) { return options.messageBuilder; } return createMessageBuilder(options); } var toValidationError = (options = {}) => (err) => { if (isZodErrorLike(err)) { return fromZodErrorWithoutRuntimeCheck(err, options); } if (err instanceof Error) { return new ValidationError(err.message, { cause: err }); } return new ValidationError("Unknown error"); }; function fromError(err, options = {}) { return toValidationError(options)(err); } // src/HIR/Globals.ts var DEFAULT_SHAPES = new Map(BUILTIN_SHAPES); var UNTYPED_GLOBALS = /* @__PURE__ */ new Set([ "Object", "Function", "RegExp", "Date", "Error", "TypeError", "RangeError", "ReferenceError", "SyntaxError", "URIError", "EvalError", "DataView", "Float32Array", "Float64Array", "Int8Array", "Int16Array", "Int32Array", "WeakMap", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "ArrayBuffer", "JSON", "console", "eval" ]); var TYPED_GLOBALS = [ [ "Object", addObject(DEFAULT_SHAPES, "Object", [ [ "keys", addFunction(DEFAULT_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }) ], [ /** * Object.fromEntries(iterable) * iterable: An iterable, such as an Array or Map, containing a list of * objects. Each object should have two properties. * Returns a new object whose properties are given by the entries of the * iterable. */ "fromEntries", addFunction(DEFAULT_SHAPES, [], { positionalParams: ["mutate?" /* ConditionallyMutate */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInObjectId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }) ], [ "entries", addFunction(DEFAULT_SHAPES, [], { positionalParams: ["capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */, aliasing: { receiver: "@receiver", params: ["@object"], rest: null, returns: "@returns", temporaries: [], effects: [ { kind: "Create", into: "@returns", reason: "known-return-signature" /* KnownReturnSignature */, value: "mutable" /* Mutable */ }, // Object values are captured into the return { kind: "Capture", from: "@object", into: "@returns" } ] } }) ], [ "keys", addFunction(DEFAULT_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */, aliasing: { receiver: "@receiver", params: ["@object"], rest: null, returns: "@returns", temporaries: [], effects: [ { kind: "Create", into: "@returns", reason: "known-return-signature" /* KnownReturnSignature */, value: "mutable" /* Mutable */ }, // Only keys are captured, and keys are immutable { kind: "ImmutableCapture", from: "@object", into: "@returns" } ] } }) ], [ "values", addFunction(DEFAULT_SHAPES, [], { positionalParams: ["capture" /* Capture */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */, aliasing: { receiver: "@receiver", params: ["@object"], rest: null, returns: "@returns", temporaries: [], effects: [ { kind: "Create", into: "@returns", reason: "known-return-signature" /* KnownReturnSignature */, value: "mutable" /* Mutable */ }, // Object values are captured into the return { kind: "Capture", from: "@object", into: "@returns" } ] } }) ] ]) ], [ "Array", addObject(DEFAULT_SHAPES, "Array", [ [ "isArray", // Array.isArray(value) addFunction(DEFAULT_SHAPES, [], { positionalParams: ["read" /* Read */], restParam: null, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], /* * https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.from * Array.from(arrayLike, optionalFn, optionalThis) * Note that the Effect of `arrayLike` is polymorphic i.e. * - Effect.read if * - it does not have an @iterator property and is array-like * (i.e. has a length property) * - it is an iterable object whose iterator does not mutate itself * - Effect.mutate if it is a self-mutative iterator (e.g. a generator * function) */ [ "from", addFunction(DEFAULT_SHAPES, [], { positionalParams: [ "mutate-iterator?" /* ConditionallyMutateIterator */, "mutate?" /* ConditionallyMutate */, "mutate?" /* ConditionallyMutate */ ], restParam: "read" /* Read */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }) ], [ "of", // Array.of(element0, ..., elementN) addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Object", shapeId: BuiltInArrayId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }) ] ]) ], [ "performance", addObject(DEFAULT_SHAPES, "performance", [ // Static methods (TODO) [ "now", // Date.now() addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Poly" }, // TODO: could be Primitive, but that would change existing compilation calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */, // same here impure: true, canonicalName: "performance.now" }) ] ]) ], [ "Date", addObject(DEFAULT_SHAPES, "Date", [ // Static methods (TODO) [ "now", // Date.now() addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Poly" }, // TODO: could be Primitive, but that would change existing compilation calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */, // same here impure: true, canonicalName: "Date.now" }) ] ]) ], [ "Math", addObject(DEFAULT_SHAPES, "Math", [ // Static properties (TODO) ["PI", { kind: "Primitive" }], // Static methods (TODO) [ "max", // Math.max(value0, ..., valueN) addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "min", // Math.min(value0, ..., valueN) addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "trunc", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "ceil", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "floor", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "pow", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "random", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Poly" }, // TODO: could be Primitive, but that would change existing compilation calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */, // same here impure: true, canonicalName: "Math.random" }) ] ]) ], ["Infinity", { kind: "Primitive" }], ["NaN", { kind: "Primitive" }], [ "console", addObject(DEFAULT_SHAPES, "console", [ [ "error", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "info", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "log", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "table", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "trace", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "warn", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ] ]) ], [ "Boolean", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "Number", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "String", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "parseInt", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "parseFloat", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "isNaN", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "isFinite", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "encodeURI", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "encodeURIComponent", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "decodeURI", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "decodeURIComponent", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, returnValueKind: "primitive" /* Primitive */ }) ], [ "Map", addFunction( DEFAULT_SHAPES, [], { positionalParams: ["mutate-iterator?" /* ConditionallyMutateIterator */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInMapId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }, null, true ) ], [ "Set", addFunction( DEFAULT_SHAPES, [], { positionalParams: ["mutate-iterator?" /* ConditionallyMutateIterator */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInSetId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }, null, true ) ], [ "WeakMap", addFunction( DEFAULT_SHAPES, [], { positionalParams: ["mutate-iterator?" /* ConditionallyMutateIterator */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInWeakMapId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }, null, true ) ], [ "WeakSet", addFunction( DEFAULT_SHAPES, [], { positionalParams: ["mutate-iterator?" /* ConditionallyMutateIterator */], restParam: null, returnType: { kind: "Object", shapeId: BuiltInWeakSetId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }, null, true ) ] // TODO: rest of Global objects ]; var REACT_APIS = [ [ "useContext", addHook( DEFAULT_SHAPES, { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, hookKind: "useContext", returnValueKind: "frozen" /* Frozen */, returnValueReason: "context" /* Context */ }, BuiltInUseContextHookId ) ], [ "useState", addHook(DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Object", shapeId: BuiltInUseStateId }, calleeEffect: "read" /* Read */, hookKind: "useState", returnValueKind: "frozen" /* Frozen */, returnValueReason: "state" /* State */ }) ], [ "useActionState", addHook(DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Object", shapeId: BuiltInUseActionStateId }, calleeEffect: "read" /* Read */, hookKind: "useActionState", returnValueKind: "frozen" /* Frozen */, returnValueReason: "state" /* State */ }) ], [ "useReducer", addHook(DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Object", shapeId: BuiltInUseReducerId }, calleeEffect: "read" /* Read */, hookKind: "useReducer", returnValueKind: "frozen" /* Frozen */, returnValueReason: "reducer-state" /* ReducerState */ }) ], [ "useRef", addHook(DEFAULT_SHAPES, { positionalParams: [], restParam: "capture" /* Capture */, returnType: { kind: "Object", shapeId: BuiltInUseRefId }, calleeEffect: "read" /* Read */, hookKind: "useRef", returnValueKind: "mutable" /* Mutable */ }) ], [ "useImperativeHandle", addHook(DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, hookKind: "useImperativeHandle", returnValueKind: "frozen" /* Frozen */ }) ], [ "useMemo", addHook(DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, hookKind: "useMemo", returnValueKind: "frozen" /* Frozen */ }) ], [ "useCallback", addHook(DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, hookKind: "useCallback", returnValueKind: "frozen" /* Frozen */ }) ], [ "useEffect", addHook( DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Primitive" }, calleeEffect: "read" /* Read */, hookKind: "useEffect", returnValueKind: "frozen" /* Frozen */, aliasing: { receiver: "@receiver", params: [], rest: "@rest", returns: "@returns", temporaries: ["@effect"], effects: [ // Freezes the function and deps { kind: "Freeze", value: "@rest", reason: "effect" /* Effect */ }, // Internally creates an effect object that captures the function and deps { kind: "Create", into: "@effect", value: "frozen" /* Frozen */, reason: "known-return-signature" /* KnownReturnSignature */ }, // The effect stores the function and dependencies { kind: "Capture", from: "@rest", into: "@effect" }, // Returns undefined { kind: "Create", into: "@returns", value: "primitive" /* Primitive */, reason: "known-return-signature" /* KnownReturnSignature */ } ] } }, BuiltInUseEffectHookId ) ], [ "useLayoutEffect", addHook( DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, hookKind: "useLayoutEffect", returnValueKind: "frozen" /* Frozen */ }, BuiltInUseLayoutEffectHookId ) ], [ "useInsertionEffect", addHook( DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, hookKind: "useInsertionEffect", returnValueKind: "frozen" /* Frozen */ }, BuiltInUseInsertionEffectHookId ) ], [ "useTransition", addHook(DEFAULT_SHAPES, { positionalParams: [], restParam: null, returnType: { kind: "Object", shapeId: BuiltInUseTransitionId }, calleeEffect: "read" /* Read */, hookKind: "useTransition", returnValueKind: "frozen" /* Frozen */ }) ], [ "use", addFunction( DEFAULT_SHAPES, [], { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, returnValueKind: "frozen" /* Frozen */ }, BuiltInUseOperatorId ) ], [ "fire", addFunction( DEFAULT_SHAPES, [], { positionalParams: [], restParam: null, returnType: { kind: "Function", return: { kind: "Poly" }, shapeId: BuiltInFireFunctionId, isConstructor: false }, calleeEffect: "read" /* Read */, returnValueKind: "frozen" /* Frozen */ }, BuiltInFireId ) ], [ "useEffectEvent", addHook( DEFAULT_SHAPES, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Function", return: { kind: "Poly" }, shapeId: BuiltinEffectEventId, isConstructor: false }, calleeEffect: "read" /* Read */, hookKind: "useEffectEvent", // Frozen because it should not mutate any locally-bound values returnValueKind: "frozen" /* Frozen */ }, BuiltInUseEffectEventId ) ], ["AUTODEPS", addObject(DEFAULT_SHAPES, BuiltInAutodepsId, [])] ]; TYPED_GLOBALS.push( [ "React", addObject(DEFAULT_SHAPES, null, [ ...REACT_APIS, [ "createElement", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, returnValueKind: "frozen" /* Frozen */ }) ], [ "cloneElement", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, returnValueKind: "frozen" /* Frozen */ }) ], [ "createRef", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "capture" /* Capture */, // createRef takes no paramters returnType: { kind: "Object", shapeId: BuiltInUseRefId }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */ }) ] ]) ], [ "_jsx", addFunction(DEFAULT_SHAPES, [], { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, returnValueKind: "frozen" /* Frozen */ }) ] ); var DEFAULT_GLOBALS = new Map(REACT_APIS); for (const name of UNTYPED_GLOBALS) { DEFAULT_GLOBALS.set(name, { kind: "Poly" }); } for (const [name, type_] of TYPED_GLOBALS) { DEFAULT_GLOBALS.set(name, type_); } DEFAULT_GLOBALS.set( "globalThis", addObject(DEFAULT_SHAPES, "globalThis", TYPED_GLOBALS) ); DEFAULT_GLOBALS.set( "global", addObject(DEFAULT_SHAPES, "global", TYPED_GLOBALS) ); function installTypeConfig(globals, shapes, typeConfig, moduleName, loc) { var _a, _b, _c, _d, _e, _f; switch (typeConfig.kind) { case "type": { switch (typeConfig.name) { case "Array": { return { kind: "Object", shapeId: BuiltInArrayId }; } case "MixedReadonly": { return { kind: "Object", shapeId: BuiltInMixedReadonlyId }; } case "Primitive": { return { kind: "Primitive" }; } case "Ref": { return { kind: "Object", shapeId: BuiltInUseRefId }; } case "Any": { return { kind: "Poly" }; } default: { assertExhaustive( typeConfig.name, `Unexpected type '${typeConfig.name}'` ); } } } case "function": { return addFunction(shapes, [], { positionalParams: typeConfig.positionalParams, restParam: typeConfig.restParam, calleeEffect: typeConfig.calleeEffect, returnType: installTypeConfig( globals, shapes, typeConfig.returnType, moduleName, loc ), returnValueKind: typeConfig.returnValueKind, noAlias: typeConfig.noAlias === true, mutableOnlyIfOperandsAreMutable: typeConfig.mutableOnlyIfOperandsAreMutable === true, aliasing: typeConfig.aliasing, knownIncompatible: (_a = typeConfig.knownIncompatible) != null ? _a : null }); } case "hook": { return addHook(shapes, { hookKind: "Custom", positionalParams: (_b = typeConfig.positionalParams) != null ? _b : [], restParam: (_c = typeConfig.restParam) != null ? _c : "freeze" /* Freeze */, calleeEffect: "read" /* Read */, returnType: installTypeConfig( globals, shapes, typeConfig.returnType, moduleName, loc ), returnValueKind: (_d = typeConfig.returnValueKind) != null ? _d : "frozen" /* Frozen */, noAlias: typeConfig.noAlias === true, aliasing: typeConfig.aliasing, knownIncompatible: (_e = typeConfig.knownIncompatible) != null ? _e : null }); } case "object": { return addObject( shapes, null, Object.entries((_f = typeConfig.properties) != null ? _f : {}).map(([key2, value]) => { var _a2; const type = installTypeConfig( globals, shapes, value, moduleName, loc ); const expectHook = isHookName(key2); let isHook2 = false; if (type.kind === "Function" && type.shapeId !== null) { const functionType = shapes.get(type.shapeId); if (((_a2 = functionType == null ? void 0 : functionType.functionType) == null ? void 0 : _a2.hookKind) !== null) { isHook2 = true; } } if (expectHook !== isHook2) { CompilerError.throwInvalidConfig({ reason: `Invalid type configuration for module`, description: `Expected type for object property '${key2}' from module '${moduleName}' ${expectHook ? "to be a hook" : "not to be a hook"} based on the property name`, loc }); } return [key2, type]; }) ); } default: { assertExhaustive( typeConfig, `Unexpected type kind '${typeConfig.kind}'` ); } } } function getReanimatedModuleType(registry2) { const frozenHooks = [ "useFrameCallback", "useAnimatedStyle", "useAnimatedProps", "useAnimatedScrollHandler", "useAnimatedReaction", "useWorkletCallback" ]; const reanimatedType = []; for (const hook of frozenHooks) { reanimatedType.push([ hook, addHook(registry2, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Poly" }, returnValueKind: "frozen" /* Frozen */, noAlias: true, calleeEffect: "read" /* Read */, hookKind: "Custom" }) ]); } const mutableHooks = ["useSharedValue", "useDerivedValue"]; for (const hook of mutableHooks) { reanimatedType.push([ hook, addHook(registry2, { positionalParams: [], restParam: "freeze" /* Freeze */, returnType: { kind: "Object", shapeId: ReanimatedSharedValueId }, returnValueKind: "mutable" /* Mutable */, noAlias: true, calleeEffect: "read" /* Read */, hookKind: "Custom" }) ]); } const funcs = [ "withTiming", "withSpring", "createAnimatedPropAdapter", "withDecay", "withRepeat", "runOnUI", "executeOnUIRuntimeSync" ]; for (const fn of funcs) { reanimatedType.push([ fn, addFunction(registry2, [], { positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "Poly" }, calleeEffect: "read" /* Read */, returnValueKind: "mutable" /* Mutable */, noAlias: true }) ]); } return addObject(registry2, null, reanimatedType); } // src/HIR/TypeSchema.ts var import_types = require("@babel/types"); var ObjectPropertiesSchema = external_exports.record( external_exports.string(), external_exports.lazy(() => TypeSchema) ).refine((record2) => { return Object.keys(record2).every( (key2) => key2 === "*" || key2 === "default" || (0, import_types.isValidIdentifier)(key2) ); }, 'Expected all "object" property names to be valid identifier, `*` to match any property, of `default` to define a module default export'); var ObjectTypeSchema = external_exports.object({ kind: external_exports.literal("object"), properties: ObjectPropertiesSchema.nullable() }); var LifetimeIdSchema = external_exports.string().refine((id) => id.startsWith("@"), { message: "Placeholder names must start with '@'" }); var FreezeEffectSchema = external_exports.object({ kind: external_exports.literal("Freeze"), value: LifetimeIdSchema, reason: ValueReasonSchema }); var MutateEffectSchema = external_exports.object({ kind: external_exports.literal("Mutate"), value: LifetimeIdSchema }); var MutateTransitiveConditionallySchema = external_exports.object({ kind: external_exports.literal("MutateTransitiveConditionally"), value: LifetimeIdSchema }); var CreateEffectSchema = external_exports.object({ kind: external_exports.literal("Create"), into: LifetimeIdSchema, value: ValueKindSchema, reason: ValueReasonSchema }); var AssignEffectSchema = external_exports.object({ kind: external_exports.literal("Assign"), from: LifetimeIdSchema, into: LifetimeIdSchema }); var AliasEffectSchema = external_exports.object({ kind: external_exports.literal("Alias"), from: LifetimeIdSchema, into: LifetimeIdSchema }); var ImmutableCaptureEffectSchema = external_exports.object({ kind: external_exports.literal("ImmutableCapture"), from: LifetimeIdSchema, into: LifetimeIdSchema }); var CaptureEffectSchema = external_exports.object({ kind: external_exports.literal("Capture"), from: LifetimeIdSchema, into: LifetimeIdSchema }); var CreateFromEffectSchema = external_exports.object({ kind: external_exports.literal("CreateFrom"), from: LifetimeIdSchema, into: LifetimeIdSchema }); var ApplyArgSchema = external_exports.union([ LifetimeIdSchema, external_exports.object({ kind: external_exports.literal("Spread"), place: LifetimeIdSchema }), external_exports.object({ kind: external_exports.literal("Hole") }) ]); var ApplyEffectSchema = external_exports.object({ kind: external_exports.literal("Apply"), receiver: LifetimeIdSchema, function: LifetimeIdSchema, mutatesFunction: external_exports.boolean(), args: external_exports.array(ApplyArgSchema), into: LifetimeIdSchema }); var ImpureEffectSchema = external_exports.object({ kind: external_exports.literal("Impure"), place: LifetimeIdSchema }); var AliasingEffectSchema = external_exports.union([ FreezeEffectSchema, CreateEffectSchema, CreateFromEffectSchema, AssignEffectSchema, AliasEffectSchema, CaptureEffectSchema, ImmutableCaptureEffectSchema, ImpureEffectSchema, MutateEffectSchema, MutateTransitiveConditionallySchema, ApplyEffectSchema ]); var AliasingSignatureSchema = external_exports.object({ receiver: LifetimeIdSchema, params: external_exports.array(LifetimeIdSchema), rest: LifetimeIdSchema.nullable(), returns: LifetimeIdSchema, effects: external_exports.array(AliasingEffectSchema), temporaries: external_exports.array(LifetimeIdSchema) }); var FunctionTypeSchema = external_exports.object({ kind: external_exports.literal("function"), positionalParams: external_exports.array(EffectSchema), restParam: EffectSchema.nullable(), calleeEffect: EffectSchema, returnType: external_exports.lazy(() => TypeSchema), returnValueKind: ValueKindSchema, noAlias: external_exports.boolean().nullable().optional(), mutableOnlyIfOperandsAreMutable: external_exports.boolean().nullable().optional(), impure: external_exports.boolean().nullable().optional(), canonicalName: external_exports.string().nullable().optional(), aliasing: AliasingSignatureSchema.nullable().optional(), knownIncompatible: external_exports.string().nullable().optional() }); var HookTypeSchema = external_exports.object({ kind: external_exports.literal("hook"), positionalParams: external_exports.array(EffectSchema).nullable().optional(), restParam: EffectSchema.nullable().optional(), returnType: external_exports.lazy(() => TypeSchema), returnValueKind: ValueKindSchema.nullable().optional(), noAlias: external_exports.boolean().nullable().optional(), aliasing: AliasingSignatureSchema.nullable().optional(), knownIncompatible: external_exports.string().nullable().optional() }); var BuiltInTypeSchema = external_exports.union([ external_exports.literal("Any"), external_exports.literal("Ref"), external_exports.literal("Array"), external_exports.literal("Primitive"), external_exports.literal("MixedReadonly") ]); var TypeReferenceSchema = external_exports.object({ kind: external_exports.literal("type"), name: BuiltInTypeSchema }); var TypeSchema = external_exports.union([ ObjectTypeSchema, FunctionTypeSchema, HookTypeSchema, TypeReferenceSchema ]); // src/Flood/TypeErrors.ts function unsupportedTypeAnnotation(desc, loc) { CompilerError.throwInvalidJS({ reason: `Typedchecker does not currently support type annotation: ${desc}`, loc }); } // src/Flood/Types.ts var opaqueLinearId = Symbol(); var opaqueTypeParameterId = Symbol(); function makeTypeParameterId(id) { CompilerError.invariant(id >= 0 && Number.isInteger(id), { reason: "Expected TypeParameterId to be a non-negative integer", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return id; } var opaqueNominalId = Symbol(); function makeNominalId(id) { return id; } var opaqueVariableId = Symbol(); var DUMMY_NOMINAL = makeNominalId(0); function convertFlowType(flowType, loc) { let nextGenericId = 0; function convertFlowTypeImpl(flowType2, loc2, genericEnv, platform, poly = null) { var _a, _b, _c; switch (flowType2.kind) { case "TypeApp": { if (flowType2.type.kind === "Def" && flowType2.type.def.kind === "Poly" && flowType2.type.def.t_out.kind === "Def" && flowType2.type.def.t_out.def.kind === "Type" && flowType2.type.def.t_out.def.type.kind === "Opaque" && flowType2.type.def.t_out.def.type.opaquetype.opaque_name === "Client" && flowType2.targs.length === 1) { return convertFlowTypeImpl( flowType2.targs[0], loc2, genericEnv, "client" ); } else if (flowType2.type.kind === "Def" && flowType2.type.def.kind === "Poly" && flowType2.type.def.t_out.kind === "Def" && flowType2.type.def.t_out.def.kind === "Type" && flowType2.type.def.t_out.def.type.kind === "Opaque" && flowType2.type.def.t_out.def.type.opaquetype.opaque_name === "Server" && flowType2.targs.length === 1) { return convertFlowTypeImpl( flowType2.targs[0], loc2, genericEnv, "server" ); } return Resolved.todo(platform); } case "Open": return Resolved.mixed(platform); case "Any": return Resolved.todo(platform); case "Annot": return convertFlowTypeImpl( flowType2.type, loc2, genericEnv, platform, poly ); case "Opaque": { if (flowType2.opaquetype.opaque_name === "Client" && flowType2.opaquetype.super_t != null) { return convertFlowTypeImpl( flowType2.opaquetype.super_t, loc2, genericEnv, "client" ); } if (flowType2.opaquetype.opaque_name === "Server" && flowType2.opaquetype.super_t != null) { return convertFlowTypeImpl( flowType2.opaquetype.super_t, loc2, genericEnv, "server" ); } const t6 = (_a = flowType2.opaquetype.underlying_t) != null ? _a : flowType2.opaquetype.super_t; if (t6 != null) { return convertFlowTypeImpl(t6, loc2, genericEnv, platform, poly); } else { return Resolved.todo(platform); } } case "Def": { switch (flowType2.def.kind) { case "EnumValue": return convertFlowTypeImpl( flowType2.def.enum_info.representation_t, loc2, genericEnv, platform, poly ); case "EnumObject": return Resolved.enum(platform); case "Empty": return Resolved.todo(platform); case "Instance": { const members = /* @__PURE__ */ new Map(); for (const key2 in flowType2.def.instance.inst.own_props) { const prop = flowType2.def.instance.inst.own_props[key2]; if (prop.kind === "Field") { members.set( key2, convertFlowTypeImpl(prop.type, loc2, genericEnv, platform) ); } else { CompilerError.invariant(false, { reason: `Unsupported property kind ${prop.kind}`, description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); } } return Resolved.class( (_b = flowType2.def.instance.inst.class_name) != null ? _b : "[anonymous class]", members, platform ); } case "Type": return convertFlowTypeImpl( flowType2.def.type, loc2, genericEnv, platform, poly ); case "NumGeneral": case "SingletonNum": return Resolved.number(platform); case "StrGeneral": case "SingletonStr": return Resolved.string(platform); case "BoolGeneral": case "SingletonBool": return Resolved.boolean(platform); case "Void": return Resolved.void(platform); case "Null": return Resolved.void(platform); case "Mixed": return Resolved.mixed(platform); case "Arr": { if (flowType2.def.arrtype.kind === "ArrayAT" || flowType2.def.arrtype.kind === "ROArrayAT") { return Resolved.array( convertFlowTypeImpl( flowType2.def.arrtype.elem_t, loc2, genericEnv, platform ), platform ); } else { return Resolved.tuple( DUMMY_NOMINAL, flowType2.def.arrtype.elements.map( (t6) => convertFlowTypeImpl(t6.t, loc2, genericEnv, platform) ), platform ); } } case "Obj": { const members = /* @__PURE__ */ new Map(); for (const key2 in flowType2.def.objtype.props) { const prop = flowType2.def.objtype.props[key2]; if (prop.kind === "Field") { members.set( key2, convertFlowTypeImpl(prop.type, loc2, genericEnv, platform) ); } else { CompilerError.invariant(false, { reason: `Unsupported property kind ${prop.kind}`, description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); } } return Resolved.object(DUMMY_NOMINAL, members, platform); } case "Class": { if (flowType2.def.type.kind === "ThisInstance") { const members = /* @__PURE__ */ new Map(); for (const key2 in flowType2.def.type.instance.inst.own_props) { const prop = flowType2.def.type.instance.inst.own_props[key2]; if (prop.kind === "Field") { members.set( key2, convertFlowTypeImpl(prop.type, loc2, genericEnv, platform) ); } else { CompilerError.invariant(false, { reason: `Unsupported property kind ${prop.kind}`, description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); } } return Resolved.class( (_c = flowType2.def.type.instance.inst.class_name) != null ? _c : "[anonymous class]", members, platform ); } CompilerError.invariant(false, { reason: `Unsupported class instance type ${flowType2.def.type.kind}`, description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); } case "Fun": return Resolved.function( poly, flowType2.def.funtype.params.map( (p) => convertFlowTypeImpl(p.type, loc2, genericEnv, platform) ), convertFlowTypeImpl( flowType2.def.funtype.return_t, loc2, genericEnv, platform ), platform ); case "Poly": { let newEnv = genericEnv; const poly2 = flowType2.def.tparams.map((p) => { const id = makeTypeParameterId(nextGenericId++); const bound = convertFlowTypeImpl(p.bound, loc2, newEnv, platform); newEnv = new Map(newEnv); newEnv.set(p.name, id); return { name: p.name, id, bound }; }); return convertFlowTypeImpl( flowType2.def.t_out, loc2, newEnv, platform, poly2 ); } case "ReactAbstractComponent": { const props = /* @__PURE__ */ new Map(); let children = null; const propsType = convertFlowTypeImpl( flowType2.def.config, loc2, genericEnv, platform ); if (propsType.type.kind === "Object") { propsType.type.members.forEach((v, k) => { if (k === "children") { children = v; } else { props.set(k, v); } }); } else { CompilerError.invariant(false, { reason: `Unsupported component props type ${propsType.type.kind}`, description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); } return Resolved.component(props, children, platform); } case "Renders": return Resolved.todo(platform); default: unsupportedTypeAnnotation("Renders", GeneratedSource); } } case "Generic": { const id = genericEnv.get(flowType2.name); if (id == null) { unsupportedTypeAnnotation(flowType2.name, GeneratedSource); } return Resolved.generic( id, platform, convertFlowTypeImpl(flowType2.bound, loc2, genericEnv, platform) ); } case "Union": { const members = flowType2.members.map( (t6) => convertFlowTypeImpl(t6, loc2, genericEnv, platform) ); if (members.length === 1) { return members[0]; } if (members[0].type.kind === "Number" || members[0].type.kind === "String" || members[0].type.kind === "Boolean") { const dupes = members.filter( (t6) => t6.type.kind === members[0].type.kind ); if (dupes.length === members.length) { return members[0]; } } if (members[0].type.kind === "Array" && (members[0].type.element.type.kind === "Number" || members[0].type.element.type.kind === "String" || members[0].type.element.type.kind === "Boolean")) { const first = members[0].type.element; const dupes = members.filter( (t6) => t6.type.kind === "Array" && t6.type.element.type.kind === first.type.kind ); if (dupes.length === members.length) { return members[0]; } } return Resolved.union(members, platform); } case "Eval": { if (flowType2.destructor.kind === "ReactDRO" || flowType2.destructor.kind === "ReactCheckComponentConfig") { return convertFlowTypeImpl( flowType2.type, loc2, genericEnv, platform, poly ); } unsupportedTypeAnnotation( `EvalT(${flowType2.destructor.kind})`, GeneratedSource ); } case "Optional": { return Resolved.union( [ convertFlowTypeImpl(flowType2.type, loc2, genericEnv, platform), Resolved.void(platform) ], platform ); } default: unsupportedTypeAnnotation(flowType2.kind, GeneratedSource); } } return convertFlowTypeImpl(flowType, loc, /* @__PURE__ */ new Map(), "shared"); } function serializeLoc(location) { return `${location.start.line}:${location.start.column}-${location.end.line}:${location.end.column}`; } function buildTypeEnvironment(flowOutput) { const result = /* @__PURE__ */ new Map(); for (const item of flowOutput) { const loc = { start: { line: item.loc.start.line, column: item.loc.start.column - 1, index: item.loc.start.index }, end: item.loc.end, filename: item.loc.filename, identifierName: item.loc.identifierName }; result.set(serializeLoc(loc), item.type); } return result; } var lastFlowSource = null; var lastFlowResult = null; var _nextNominalId, _nextTypeParameterId, _types, _bindings2, _generics, _flowTypes; var FlowTypeEnv = class { constructor() { this.moduleEnv = /* @__PURE__ */ new Map(); __privateAdd(this, _nextNominalId, 0); __privateAdd(this, _nextTypeParameterId, 0); __privateAdd(this, _types, /* @__PURE__ */ new Map()); __privateAdd(this, _bindings2, /* @__PURE__ */ new Map()); __privateAdd(this, _generics, []); __privateAdd(this, _flowTypes, /* @__PURE__ */ new Map()); } init(env, source2) { CompilerError.invariant(env.config.flowTypeProvider != null, { reason: "Expected flowDumpTypes to be defined in environment config", description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); let stdout; if (source2 === lastFlowSource) { stdout = lastFlowResult; } else { lastFlowSource = source2; lastFlowResult = env.config.flowTypeProvider(source2); stdout = lastFlowResult; } const flowTypes = buildTypeEnvironment(stdout); const resolvedFlowTypes = /* @__PURE__ */ new Map(); for (const [loc, type] of flowTypes) { if (typeof loc === "symbol") continue; resolvedFlowTypes.set(loc, convertFlowType(JSON.parse(type), loc)); } __privateSet(this, _flowTypes, resolvedFlowTypes); } setType(identifier4, type) { if (typeof identifier4.loc !== "symbol" && __privateGet(this, _flowTypes).has(serializeLoc(identifier4.loc))) { return; } __privateGet(this, _types).set(identifier4.id, type); } getType(identifier4) { const result = this.getTypeOrNull(identifier4); if (result == null) { throw new Error( `Type not found for ${identifier4.id}, ${typeof identifier4.loc === "symbol" ? "generated loc" : serializeLoc(identifier4.loc)}` ); } return result; } getTypeOrNull(identifier4) { var _a; const result = (_a = __privateGet(this, _types).get(identifier4.id)) != null ? _a : null; if (result == null && typeof identifier4.loc !== "symbol") { const flowType = __privateGet(this, _flowTypes).get(serializeLoc(identifier4.loc)); return flowType != null ? flowType : null; } return result; } getTypeByLoc(loc) { if (typeof loc === "symbol") { return null; } const flowType = __privateGet(this, _flowTypes).get(serializeLoc(loc)); return flowType != null ? flowType : null; } nextNominalId() { return makeNominalId(__privateWrapper(this, _nextNominalId)._++); } nextTypeParameterId() { return makeTypeParameterId(__privateWrapper(this, _nextTypeParameterId)._++); } addBinding(bindingIdentifier, type) { __privateGet(this, _bindings2).set(bindingIdentifier, type); } resolveBinding(bindingIdentifier) { var _a; return (_a = __privateGet(this, _bindings2).get(bindingIdentifier)) != null ? _a : null; } pushGeneric(name, generic) { __privateGet(this, _generics).unshift([name, generic]); } popGeneric(name) { for (let i = 0; i < __privateGet(this, _generics).length; i++) { if (__privateGet(this, _generics)[i][0] === name) { __privateGet(this, _generics).splice(i, 1); return; } } } /** * Look up bound polymorphic types * @param name * @returns */ getGeneric(name) { for (const [eltName, param] of __privateGet(this, _generics)) { if (name === eltName) { return param; } } return null; } }; _nextNominalId = new WeakMap(); _nextTypeParameterId = new WeakMap(); _types = new WeakMap(); _bindings2 = new WeakMap(); _generics = new WeakMap(); _flowTypes = new WeakMap(); var Primitives = { number(platform) { return { kind: "Concrete", type: { kind: "Number" }, platform }; }, string(platform) { return { kind: "Concrete", type: { kind: "String" }, platform }; }, boolean(platform) { return { kind: "Concrete", type: { kind: "Boolean" }, platform }; }, void(platform) { return { kind: "Concrete", type: { kind: "Void" }, platform }; }, mixed(platform) { return { kind: "Concrete", type: { kind: "Mixed" }, platform }; }, enum(platform) { return { kind: "Concrete", type: { kind: "Enum" }, platform }; }, todo(platform) { return { kind: "Concrete", type: { kind: "Mixed" }, platform }; } }; var Resolved = __spreadProps(__spreadValues({}, Primitives), { nullable(type, platform) { return { kind: "Concrete", type: { kind: "Nullable", type }, platform }; }, array(element, platform) { return { kind: "Concrete", type: { kind: "Array", element }, platform }; }, set(element, platform) { return { kind: "Concrete", type: { kind: "Set", element }, platform }; }, map(key2, value, platform) { return { kind: "Concrete", type: { kind: "Map", key: key2, value }, platform }; }, function(typeParameters, params, returnType, platform) { return { kind: "Concrete", type: { kind: "Function", typeParameters, params, returnType }, platform }; }, component(props, children, platform) { return { kind: "Concrete", type: { kind: "Component", props, children }, platform }; }, object(id, members, platform) { return { kind: "Concrete", type: { kind: "Object", id, members }, platform }; }, class(name, members, platform) { return { kind: "Concrete", type: { kind: "Instance", name, members }, platform }; }, tuple(id, members, platform) { return { kind: "Concrete", type: { kind: "Tuple", id, members }, platform }; }, generic(id, platform, bound = Primitives.mixed(platform)) { return { kind: "Concrete", type: { kind: "Generic", id, bound }, platform }; }, union(members, platform) { return { kind: "Concrete", type: { kind: "Union", members }, platform }; } }); // src/HIR/DefaultModuleTypeProvider.ts function defaultModuleTypeProvider(moduleName) { switch (moduleName) { case "react-hook-form": { return { kind: "object", properties: { useForm: { kind: "hook", returnType: { kind: "object", properties: { // Only the `watch()` function returned by react-hook-form's `useForm()` API is incompatible watch: { kind: "function", positionalParams: [], restParam: "read" /* Read */, calleeEffect: "read" /* Read */, returnType: { kind: "type", name: "Any" }, returnValueKind: "mutable" /* Mutable */, knownIncompatible: `React Hook Form's \`useForm()\` API returns a \`watch()\` function which cannot be memoized safely.` } } } } } }; } case "@tanstack/react-table": { return { kind: "object", properties: { /* * Many of the properties of `useReactTable()`'s return value are incompatible, so we mark the entire hook * as incompatible */ useReactTable: { kind: "hook", positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "type", name: "Any" }, knownIncompatible: `TanStack Table's \`useReactTable()\` API returns functions that cannot be memoized safely` } } }; } case "@tanstack/react-virtual": { return { kind: "object", properties: { /* * Many of the properties of `useVirtualizer()`'s return value are incompatible, so we mark the entire hook * as incompatible */ useVirtualizer: { kind: "hook", positionalParams: [], restParam: "read" /* Read */, returnType: { kind: "type", name: "Any" }, knownIncompatible: `TanStack Virtual's \`useVirtualizer()\` API returns functions that cannot be memoized safely` } } }; } } return null; } // src/HIR/Environment.ts var ReactElementSymbolSchema = external_exports.object({ elementSymbol: external_exports.union([ external_exports.literal("react.element"), external_exports.literal("react.transitional.element") ]), globalDevVar: external_exports.string() }); var ExternalFunctionSchema = external_exports.object({ // Source for the imported module that exports the `importSpecifierName` functions source: external_exports.string(), // Unique name for the feature flag test condition, eg `isForgetEnabled_ProjectName` importSpecifierName: external_exports.string() }); var InstrumentationSchema = external_exports.object({ fn: ExternalFunctionSchema, gating: ExternalFunctionSchema.nullable(), globalGating: external_exports.string().nullable() }).refine( (opts) => opts.gating != null || opts.globalGating != null, "Expected at least one of gating or globalGating" ); var USE_FIRE_FUNCTION_NAME = "useFire"; var EMIT_FREEZE_GLOBAL_GATING = "__DEV__"; var MacroMethodSchema = external_exports.union([ external_exports.object({ type: external_exports.literal("wildcard") }), external_exports.object({ type: external_exports.literal("name"), name: external_exports.string() }) ]); var MacroSchema = external_exports.union([ external_exports.string(), external_exports.tuple([external_exports.string(), external_exports.array(MacroMethodSchema)]) ]); var HookSchema = external_exports.object({ /* * The effect of arguments to this hook. Describes whether the hook may or may * not mutate arguments, etc. */ effectKind: external_exports.nativeEnum(Effect), /* * The kind of value returned by the hook. Allows indicating that a hook returns * a primitive or already-frozen value, which can allow more precise memoization * of callers. */ valueKind: external_exports.nativeEnum(ValueKind), /* * Specifies whether hook arguments may be aliased by other arguments or by the * return value of the function. Defaults to false. When enabled, this allows the * compiler to avoid memoizing arguments. */ noAlias: external_exports.boolean().default(false), /* * Specifies whether the hook returns data that is composed of: * - undefined * - null * - boolean * - number * - string * - arrays whose items are also transitiveMixed * - objects whose values are also transitiveMixed * * Many state management and data-fetching APIs return data that meets * this criteria since this is JSON + undefined. Forget can compile * hooks that return transitively mixed data more optimally because it * can make inferences about some method calls (especially array methods * like `data.items.map(...)` since these builtin types have few built-in * methods. */ transitiveMixedData: external_exports.boolean().default(false) }); var EnvironmentConfigSchema = external_exports.object({ customHooks: external_exports.map(external_exports.string(), HookSchema).default(/* @__PURE__ */ new Map()), /** * A function that, given the name of a module, can optionally return a description * of that module's type signature. */ moduleTypeProvider: external_exports.nullable(external_exports.any()).default(null), /** * A list of functions which the application compiles as macros, where * the compiler must ensure they are not compiled to rename the macro or separate the * "function" from its argument. * * For example, Meta has some APIs such as `featureflag("name-of-feature-flag")` which * are rewritten by a plugin. Assigning `featureflag` to a temporary would break the * plugin since it looks specifically for the name of the function being invoked, not * following aliases. */ customMacros: external_exports.nullable(external_exports.array(MacroSchema)).default(null), /** * Enable a check that resets the memoization cache when the source code of * the file changes. This is intended to support hot module reloading (HMR), * where the same runtime component instance will be reused across different * versions of the component source. * * When set to * - true: code for HMR support is always generated, regardless of NODE_ENV * or `globalThis.__DEV__` * - false: code for HMR support is not generated * - null: (default) code for HMR support is conditionally generated dependent * on `NODE_ENV` and `globalThis.__DEV__` at the time of compilation. */ enableResetCacheOnSourceFileChanges: external_exports.nullable(external_exports.boolean()).default(null), /** * Enable using information from existing useMemo/useCallback to understand when a value is done * being mutated. With this mode enabled, Forget will still discard the actual useMemo/useCallback * calls and may memoize slightly differently. However, it will assume that the values produced * are not subsequently modified, guaranteeing that the value will be memoized. * * By preserving guarantees about when values are memoized, this option preserves any existing * behavior that depends on referential equality in the original program. Notably, this preserves * existing effect behavior (how often effects fire) for effects that rely on referential equality. * * When disabled, Forget will not only prune useMemo and useCallback calls but also completely ignore * them, not using any information from them to guide compilation. Therefore, disabling this flag * will produce output that mimics the result from removing all memoization. * * Our recommendation is to first try running your application with this flag enabled, then attempt * to disable this flag and see what changes or breaks. This will mostly likely be effects that * depend on referential equality, which can be refactored (TODO guide for this). * * NOTE: this mode treats freeze as a transitive operation for function expressions. This means * that if a useEffect or useCallback references a function value, that function value will be * considered frozen, and in turn all of its referenced variables will be considered frozen as well. */ enablePreserveExistingMemoizationGuarantees: external_exports.boolean().default(true), /** * Validates that all useMemo/useCallback values are also memoized by Forget. This mode can be * used with or without @enablePreserveExistingMemoizationGuarantees. * * With enablePreserveExistingMemoizationGuarantees, this validation enables automatically and * verifies that Forget was able to preserve manual memoization semantics under that mode's * additional assumptions about the input. * * With enablePreserveExistingMemoizationGuarantees off, this validation ignores manual memoization * when determining program behavior, and only uses information from useMemo/useCallback to check * that the memoization was preserved. This can be useful for determining where referential equalities * may change under Forget. */ validatePreserveExistingMemoizationGuarantees: external_exports.boolean().default(true), /** * When this is true, rather than pruning existing manual memoization but ensuring or validating * that the memoized values remain memoized, the compiler will simply not prune existing calls to * useMemo/useCallback. */ enablePreserveExistingManualUseMemo: external_exports.boolean().default(false), // 🌲 enableForest: external_exports.boolean().default(false), /** * Enable use of type annotations in the source to drive type inference. By default * Forget attemps to infer types using only information that is guaranteed correct * given the source, and does not trust user-supplied type annotations. This mode * enables trusting user type annotations. */ enableUseTypeAnnotations: external_exports.boolean().default(false), /** * Allows specifying a function that can populate HIR with type information from * Flow */ flowTypeProvider: external_exports.nullable(external_exports.any()).default(null), /** * Enables inference of optional dependency chains. Without this flag * a property chain such as `props?.items?.foo` will infer as a dep on * just `props`. With this flag enabled, we'll infer that full path as * the dependency. */ enableOptionalDependencies: external_exports.boolean().default(true), enableFire: external_exports.boolean().default(false), enableNameAnonymousFunctions: external_exports.boolean().default(false), /** * Enables inference and auto-insertion of effect dependencies. Takes in an array of * configurable module and import pairs to allow for user-land experimentation. For example, * [ * { * module: 'react', * imported: 'useEffect', * autodepsIndex: 1, * },{ * module: 'MyExperimentalEffectHooks', * imported: 'useExperimentalEffect', * autodepsIndex: 2, * }, * ] * would insert dependencies for calls of `useEffect` imported from `react` and calls of * useExperimentalEffect` from `MyExperimentalEffectHooks`. * * `autodepsIndex` tells the compiler which index we expect the AUTODEPS to appear in. * With the configuration above, we'd insert dependencies for `useEffect` if it has two * arguments, and the second is AUTODEPS. * * Still experimental. */ inferEffectDependencies: external_exports.nullable( external_exports.array( external_exports.object({ function: ExternalFunctionSchema, autodepsIndex: external_exports.number().min(1, "autodepsIndex must be > 0") }) ) ).default(null), /** * Enables inlining ReactElement object literals in place of JSX * An alternative to the standard JSX transform which replaces JSX with React's jsxProd() runtime * Currently a prod-only optimization, requiring Fast JSX dependencies * * The symbol configuration is set for backwards compatability with pre-React 19 transforms */ inlineJsxTransform: ReactElementSymbolSchema.nullable().default(null), /* * Enable validation of hooks to partially check that the component honors the rules of hooks. * When disabled, the component is assumed to follow the rules (though the Babel plugin looks * for suppressions of the lint rule). */ validateHooksUsage: external_exports.boolean().default(true), // Validate that ref values (`ref.current`) are not accessed during render. validateRefAccessDuringRender: external_exports.boolean().default(true), /* * Validates that setState is not unconditionally called during render, as it can lead to * infinite loops. */ validateNoSetStateInRender: external_exports.boolean().default(true), /** * Validates that setState is not called synchronously within an effect (useEffect and friends). * Scheduling a setState (with an event listener, subscription, etc) is valid. */ validateNoSetStateInEffects: external_exports.boolean().default(false), /** * Validates that effects are not used to calculate derived data which could instead be computed * during render. */ validateNoDerivedComputationsInEffects: external_exports.boolean().default(false), /** * Validates against creating JSX within a try block and recommends using an error boundary * instead. */ validateNoJSXInTryStatements: external_exports.boolean().default(false), /** * Validates against dynamically creating components during render. */ validateStaticComponents: external_exports.boolean().default(false), /** * Validates that the dependencies of all effect hooks are memoized. This helps ensure * that Forget does not introduce infinite renders caused by a dependency changing, * triggering an effect, which triggers re-rendering, which causes a dependency to change, * triggering the effect, etc. * * Covers useEffect, useLayoutEffect, useInsertionEffect. */ validateMemoizedEffectDependencies: external_exports.boolean().default(false), /** * Validates that there are no capitalized calls other than those allowed by the allowlist. * Calls to capitalized functions are often functions that used to be components and may * have lingering hook calls, which makes those calls risky to memoize. * * You can specify a list of capitalized calls to allowlist using this option. React Compiler * always includes its known global functions, including common functions like Boolean and String, * in this allowlist. You can enable this validation with no additional allowlisted calls by setting * this option to the empty array. */ validateNoCapitalizedCalls: external_exports.nullable(external_exports.array(external_exports.string())).default(null), validateBlocklistedImports: external_exports.nullable(external_exports.array(external_exports.string())).default(null), /** * Validate against impure functions called during render */ validateNoImpureFunctionsInRender: external_exports.boolean().default(false), /** * Validate against passing mutable functions to hooks */ validateNoFreezingKnownMutableFunctions: external_exports.boolean().default(false), /* * When enabled, the compiler assumes that hooks follow the Rules of React: * - Hooks may memoize computation based on any of their parameters, thus * any arguments to a hook are assumed frozen after calling the hook. * - Hooks may memoize the result they return, thus the return value is * assumed frozen. */ enableAssumeHooksFollowRulesOfReact: external_exports.boolean().default(true), /** * When enabled, the compiler assumes that any values are not subsequently * modified after they are captured by a function passed to React. For example, * if a value `x` is referenced inside a function expression passed to `useEffect`, * then this flag will assume that `x` is not subusequently modified. */ enableTransitivelyFreezeFunctionExpressions: external_exports.boolean().default(true), /* * Enables codegen mutability debugging. This emits a dev-mode only to log mutations * to values that Forget assumes are immutable (for Forget compiled code). * For example: * emitFreeze: { * source: 'ReactForgetRuntime', * importSpecifierName: 'makeReadOnly', * } * * produces: * import {makeReadOnly} from 'ReactForgetRuntime'; * * function Component(props) { * if (c_0) { * // ... * $[0] = __DEV__ ? makeReadOnly(x) : x; * } else { * x = $[0]; * } * } */ enableEmitFreeze: ExternalFunctionSchema.nullable().default(null), enableEmitHookGuards: ExternalFunctionSchema.nullable().default(null), /** * Enable instruction reordering. See InstructionReordering.ts for the details * of the approach. */ enableInstructionReordering: external_exports.boolean().default(false), /** * Enables function outlinining, where anonymous functions that do not close over * local variables can be extracted into top-level helper functions. */ enableFunctionOutlining: external_exports.boolean().default(true), /** * If enabled, this will outline nested JSX into a separate component. * * This will enable the compiler to memoize the separate component, giving us * the same behavior as compiling _within_ the callback. * * ``` * function Component(countries, onDelete) { * const name = useFoo(); * return countries.map(() => { * return ( * * {name} * * * ); * }); * } * ``` * * will be transpiled to: * * ``` * function Component(countries, onDelete) { * const name = useFoo(); * return countries.map(() => { * return ( * * ); * }); * } * * function Temp({name, onDelete}) { * return ( * * {name} * * * ); * } * * Both, `Component` and `Temp` will then be memoized by the compiler. * * With this change, when `countries` is updated by adding one single value, * only the newly added value is re-rendered and not the entire list. */ enableJsxOutlining: external_exports.boolean().default(false), /* * Enables instrumentation codegen. This emits a dev-mode only call to an * instrumentation function, for components and hooks that Forget compiles. * For example: * instrumentForget: { * import: { * source: 'react-compiler-runtime', * importSpecifierName: 'useRenderCounter', * } * } * * produces: * import {useRenderCounter} from 'react-compiler-runtime'; * * function Component(props) { * if (__DEV__) { * useRenderCounter("Component", "/filepath/filename.js"); * } * // ... * } * */ enableEmitInstrumentForget: InstrumentationSchema.nullable().default(null), // Enable validation of mutable ranges assertValidMutableRanges: external_exports.boolean().default(false), /* * Enable emitting "change variables" which store the result of whether a particular * reactive scope dependency has changed since the scope was last executed. * * Ex: * ``` * const c_0 = $[0] !== input; // change variable * let output; * if (c_0) ... * ``` * * Defaults to false, where the comparison is inlined: * * ``` * let output; * if ($[0] !== input) ... * ``` */ enableChangeVariableCodegen: external_exports.boolean().default(false), /** * Enable emitting comments that explain Forget's output, and which * values are being checked and which values produced by each memo block. * * Intended for use in demo purposes (incl playground) */ enableMemoizationComments: external_exports.boolean().default(false), /** * [TESTING ONLY] Throw an unknown exception during compilation to * simulate unexpected exceptions e.g. errors from babel functions. */ throwUnknownException__testonly: external_exports.boolean().default(false), /** * Enables deps of a function epxression to be treated as conditional. This * makes sure we don't load a dep when it's a property (to check if it has * changed) and instead check the receiver. * * This makes sure we don't end up throwing when the reciver is null. Consider * this code: * * ``` * function getLength() { * return props.bar.length; * } * ``` * * It's only safe to memoize `getLength` against props, not props.bar, as * props.bar could be null when this `getLength` function is created. * * This does cause the memoization to now be coarse grained, which is * non-ideal. */ enableTreatFunctionDepsAsConditional: external_exports.boolean().default(false), /** * When true, always act as though the dependencies of a memoized value * have changed. This makes the compiler not actually perform any optimizations, * but is useful for debugging. Implicitly also sets * @enablePreserveExistingManualUseMemo, because otherwise memoization in the * original source will be disabled as well. */ disableMemoizationForDebugging: external_exports.boolean().default(false), /** * When true, rather using memoized values, the compiler will always re-compute * values, and then use a heuristic to compare the memoized value to the newly * computed one. This detects cases where rules of react violations may cause the * compiled code to behave differently than the original. */ enableChangeDetectionForDebugging: ExternalFunctionSchema.nullable().default(null), /** * The react native re-animated library uses custom Babel transforms that * requires the calls to library API remain unmodified. * * If this flag is turned on, the React compiler will use custom type * definitions for reanimated library to make it's Babel plugin work * with the compiler. */ enableCustomTypeDefinitionForReanimated: external_exports.boolean().default(false), /** * If specified, this value is used as a pattern for determing which global values should be * treated as hooks. The pattern should have a single capture group, which will be used as * the hook name for the purposes of resolving hook definitions (for builtin hooks)_. * * For example, by default `React$useState` would not be treated as a hook. By specifying * `hookPattern: 'React$(\w+)'`, the compiler will treat this value equivalently to `useState()`. * * This setting is intended for cases where Forget is compiling code that has been prebundled * and identifiers have been changed. */ hookPattern: external_exports.string().nullable().default(null), /** * If enabled, this will treat objects named as `ref` or if their names end with the substring `Ref`, * and contain a property named `current`, as React refs. * * ``` * const ref = useMyRef(); * const myRef = useMyRef2(); * useEffect(() => { * ref.current = ...; * myRef.current = ...; * }) * ``` * * Here the variables `ref` and `myRef` will be typed as Refs. */ enableTreatRefLikeIdentifiersAsRefs: external_exports.boolean().default(true), /** * Treat identifiers as SetState type if both * - they are named with a "set-" prefix * - they are called somewhere */ enableTreatSetIdentifiersAsStateSetters: external_exports.boolean().default(false), /* * If specified a value, the compiler lowers any calls to `useContext` to use * this value as the callee. * * A selector function is compiled and passed as an argument along with the * context to this function call. * * The compiler automatically figures out the keys by looking for the immediate * destructuring of the return value from the useContext call. In the future, * this can be extended to different kinds of context access like property * loads and accesses over multiple statements as well. * * ``` * // input * const {foo, bar} = useContext(MyContext); * * // output * const {foo, bar} = useCompiledContext(MyContext, (c) => [c.foo, c.bar]); * ``` */ lowerContextAccess: ExternalFunctionSchema.nullable().default(null), /** * If enabled, will validate useMemos that don't return any values: * * Valid: * useMemo(() => foo, [foo]); * useMemo(() => { return foo }, [foo]); * Invalid: * useMemo(() => { ... }, [...]); */ validateNoVoidUseMemo: external_exports.boolean().default(false), /** * Validates that Components/Hooks are always defined at module level. This prevents scope * reference errors that occur when the compiler attempts to optimize the nested component/hook * while its parent function remains uncompiled. */ validateNoDynamicallyCreatedComponentsOrHooks: external_exports.boolean().default(false), /** * When enabled, allows setState calls in effects when the value being set is * derived from a ref. This is useful for patterns where initial layout measurements * from refs need to be stored in state during mount. */ enableAllowSetStateFromRefsInEffects: external_exports.boolean().default(true) }); var _globals, _shapes, _moduleTypes, _nextIdentifer, _nextBlock, _nextScope, _scope, _outlinedFunctions, _contextIdentifiers, _hoistedIdentifiers, _flowTypeEnvironment, _Environment_instances, resolveModuleType_fn, isKnownReactModule_fn, getCustomHookType_fn; var Environment2 = class { constructor(scope, fnType, compilerMode, config2, contextIdentifiers, parentFunction, logger, filename, code, programContext) { __privateAdd(this, _Environment_instances); __privateAdd(this, _globals); __privateAdd(this, _shapes); __privateAdd(this, _moduleTypes, /* @__PURE__ */ new Map()); __privateAdd(this, _nextIdentifer, 0); __privateAdd(this, _nextBlock, 0); __privateAdd(this, _nextScope, 0); __privateAdd(this, _scope); __privateAdd(this, _outlinedFunctions, []); this.inferredEffectLocations = /* @__PURE__ */ new Set(); __privateAdd(this, _contextIdentifiers); __privateAdd(this, _hoistedIdentifiers); __privateAdd(this, _flowTypeEnvironment); __privateSet(this, _scope, scope); this.fnType = fnType; this.compilerMode = compilerMode; this.config = config2; this.filename = filename; this.code = code; this.logger = logger; this.programContext = programContext; __privateSet(this, _shapes, new Map(DEFAULT_SHAPES)); __privateSet(this, _globals, new Map(DEFAULT_GLOBALS)); this.hasFireRewrite = false; this.hasInferredEffect = false; if (config2.disableMemoizationForDebugging && config2.enableChangeDetectionForDebugging != null) { CompilerError.throwInvalidConfig({ reason: `Invalid environment config: the 'disableMemoizationForDebugging' and 'enableChangeDetectionForDebugging' options cannot be used together`, description: null, loc: null, suggestions: null }); } for (const [hookName, hook] of this.config.customHooks) { CompilerError.invariant(!__privateGet(this, _globals).has(hookName), { reason: `[Globals] Found existing definition in global registry for custom hook ${hookName}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); __privateGet(this, _globals).set( hookName, addHook(__privateGet(this, _shapes), { positionalParams: [], restParam: hook.effectKind, returnType: hook.transitiveMixedData ? { kind: "Object", shapeId: BuiltInMixedReadonlyId } : { kind: "Poly" }, returnValueKind: hook.valueKind, calleeEffect: "read" /* Read */, hookKind: "Custom", noAlias: hook.noAlias }) ); } if (config2.enableCustomTypeDefinitionForReanimated) { const reanimatedModuleType = getReanimatedModuleType(__privateGet(this, _shapes)); __privateGet(this, _moduleTypes).set(REANIMATED_MODULE_NAME, reanimatedModuleType); } this.parentFunction = parentFunction; __privateSet(this, _contextIdentifiers, contextIdentifiers); __privateSet(this, _hoistedIdentifiers, /* @__PURE__ */ new Set()); if (config2.flowTypeProvider != null) { __privateSet(this, _flowTypeEnvironment, new FlowTypeEnv()); CompilerError.invariant(code != null, { reason: "Expected Environment to be initialized with source code when a Flow type provider is specified", description: null, details: [ { kind: "error", loc: null, message: null } ] }); __privateGet(this, _flowTypeEnvironment).init(this, code); } else { __privateSet(this, _flowTypeEnvironment, null); } } get typeContext() { CompilerError.invariant(__privateGet(this, _flowTypeEnvironment) != null, { reason: "Flow type environment not initialized", description: null, details: [ { kind: "error", loc: null, message: null } ] }); return __privateGet(this, _flowTypeEnvironment); } get isInferredMemoEnabled() { return this.compilerMode !== "no_inferred_memo"; } get nextIdentifierId() { return makeIdentifierId(__privateWrapper(this, _nextIdentifer)._++); } get nextBlockId() { return makeBlockId(__privateWrapper(this, _nextBlock)._++); } get nextScopeId() { return makeScopeId(__privateWrapper(this, _nextScope)._++); } get scope() { return __privateGet(this, _scope); } logErrors(errors) { if (errors.isOk() || this.logger == null) { return; } for (const error45 of errors.unwrapErr().details) { this.logger.logEvent(this.filename, { kind: "CompileError", detail: error45, fnLoc: null }); } } isContextIdentifier(node) { return __privateGet(this, _contextIdentifiers).has(node); } isHoistedIdentifier(node) { return __privateGet(this, _hoistedIdentifiers).has(node); } generateGloballyUniqueIdentifierName(name) { const identifierNode = __privateGet(this, _scope).generateUidIdentifier(name != null ? name : void 0); return makeIdentifierName(identifierNode.name); } outlineFunction(fn, type) { __privateGet(this, _outlinedFunctions).push({ fn, type }); } getOutlinedFunctions() { return __privateGet(this, _outlinedFunctions); } getGlobalDeclaration(binding, loc) { var _a, _b, _c, _d; if (this.config.hookPattern != null) { const match = new RegExp(this.config.hookPattern).exec(binding.name); if (match != null && typeof match[1] === "string" && isHookName(match[1])) { const resolvedName = match[1]; return (_a = __privateGet(this, _globals).get(resolvedName)) != null ? _a : __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this); } } switch (binding.kind) { case "ModuleLocal": { return isHookName(binding.name) ? __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this) : null; } case "Global": { return (_b = __privateGet(this, _globals).get(binding.name)) != null ? _b : isHookName(binding.name) ? __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this) : null; } case "ImportSpecifier": { if (__privateMethod(this, _Environment_instances, isKnownReactModule_fn).call(this, binding.module)) { return (_c = __privateGet(this, _globals).get(binding.imported)) != null ? _c : isHookName(binding.imported) || isHookName(binding.name) ? __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this) : null; } else { const moduleType = __privateMethod(this, _Environment_instances, resolveModuleType_fn).call(this, binding.module, loc); if (moduleType !== null) { const importedType = this.getPropertyType( moduleType, binding.imported ); if (importedType != null) { const expectHook = isHookName(binding.imported); const isHook2 = getHookKindForType(this, importedType) != null; if (expectHook !== isHook2) { CompilerError.throwInvalidConfig({ reason: `Invalid type configuration for module`, description: `Expected type for \`import {${binding.imported}} from '${binding.module}'\` ${expectHook ? "to be a hook" : "not to be a hook"} based on the exported name`, loc }); } return importedType; } } return isHookName(binding.imported) || isHookName(binding.name) ? __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this) : null; } } case "ImportDefault": case "ImportNamespace": { if (__privateMethod(this, _Environment_instances, isKnownReactModule_fn).call(this, binding.module)) { return (_d = __privateGet(this, _globals).get(binding.name)) != null ? _d : isHookName(binding.name) ? __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this) : null; } else { const moduleType = __privateMethod(this, _Environment_instances, resolveModuleType_fn).call(this, binding.module, loc); if (moduleType !== null) { let importedType = null; if (binding.kind === "ImportDefault") { const defaultType = this.getPropertyType(moduleType, "default"); if (defaultType !== null) { importedType = defaultType; } } else { importedType = moduleType; } if (importedType !== null) { const expectHook = isHookName(binding.module); const isHook2 = getHookKindForType(this, importedType) != null; if (expectHook !== isHook2) { CompilerError.throwInvalidConfig({ reason: `Invalid type configuration for module`, description: `Expected type for \`import ... from '${binding.module}'\` ${expectHook ? "to be a hook" : "not to be a hook"} based on the module name`, loc }); } return importedType; } } return isHookName(binding.name) ? __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this) : null; } } } } getFallthroughPropertyType(receiver, _property2) { var _a; let shapeId = null; if (receiver.kind === "Object" || receiver.kind === "Function") { shapeId = receiver.shapeId; } if (shapeId !== null) { const shape = __privateGet(this, _shapes).get(shapeId); CompilerError.invariant(shape !== void 0, { reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return (_a = shape.properties.get("*")) != null ? _a : null; } return null; } getPropertyType(receiver, property) { var _a, _b, _c; let shapeId = null; if (receiver.kind === "Object" || receiver.kind === "Function") { shapeId = receiver.shapeId; } if (shapeId !== null) { const shape = __privateGet(this, _shapes).get(shapeId); CompilerError.invariant(shape !== void 0, { reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); if (typeof property === "string") { return (_b = (_a = shape.properties.get(property)) != null ? _a : shape.properties.get("*")) != null ? _b : isHookName(property) ? __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this) : null; } else { return (_c = shape.properties.get("*")) != null ? _c : null; } } else if (typeof property === "string" && isHookName(property)) { return __privateMethod(this, _Environment_instances, getCustomHookType_fn).call(this); } return null; } getFunctionSignature(type) { const { shapeId } = type; if (shapeId !== null) { const shape = __privateGet(this, _shapes).get(shapeId); CompilerError.invariant(shape !== void 0, { reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return shape.functionType; } return null; } addHoistedIdentifier(node) { __privateGet(this, _contextIdentifiers).add(node); __privateGet(this, _hoistedIdentifiers).add(node); } }; _globals = new WeakMap(); _shapes = new WeakMap(); _moduleTypes = new WeakMap(); _nextIdentifer = new WeakMap(); _nextBlock = new WeakMap(); _nextScope = new WeakMap(); _scope = new WeakMap(); _outlinedFunctions = new WeakMap(); _contextIdentifiers = new WeakMap(); _hoistedIdentifiers = new WeakMap(); _flowTypeEnvironment = new WeakMap(); _Environment_instances = new WeakSet(); resolveModuleType_fn = function(moduleName, loc) { var _a; let moduleType = __privateGet(this, _moduleTypes).get(moduleName); if (moduleType === void 0) { const moduleTypeProvider = (_a = this.config.moduleTypeProvider) != null ? _a : defaultModuleTypeProvider; if (moduleTypeProvider == null) { return null; } if (typeof moduleTypeProvider !== "function") { CompilerError.throwInvalidConfig({ reason: `Expected a function for \`moduleTypeProvider\``, loc }); } const unparsedModuleConfig = moduleTypeProvider(moduleName); if (unparsedModuleConfig != null) { const parsedModuleConfig = TypeSchema.safeParse(unparsedModuleConfig); if (!parsedModuleConfig.success) { CompilerError.throwInvalidConfig({ reason: `Could not parse module type, the configured \`moduleTypeProvider\` function returned an invalid module description`, description: parsedModuleConfig.error.toString(), loc }); } const moduleConfig = parsedModuleConfig.data; moduleType = installTypeConfig( __privateGet(this, _globals), __privateGet(this, _shapes), moduleConfig, moduleName, loc ); } else { moduleType = null; } __privateGet(this, _moduleTypes).set(moduleName, moduleType); } return moduleType; }; isKnownReactModule_fn = function(moduleName) { return moduleName.toLowerCase() === "react" || moduleName.toLowerCase() === "react-dom"; }; getCustomHookType_fn = function() { if (this.config.enableAssumeHooksFollowRulesOfReact) { return DefaultNonmutatingHook; } else { return DefaultMutatingHook; } }; Environment2.knownReactModules = ["react", "react-dom"]; var REANIMATED_MODULE_NAME = "react-native-reanimated"; function isHookName(name) { return /^use[A-Z0-9]/.test(name); } function parseEnvironmentConfig(partialConfig) { const config2 = EnvironmentConfigSchema.safeParse(partialConfig); if (config2.success) { return Ok(config2.data); } else { return Err(config2.error); } } function validateEnvironmentConfig(partialConfig) { const config2 = EnvironmentConfigSchema.safeParse(partialConfig); if (config2.success) { return config2.data; } CompilerError.throwInvalidConfig({ reason: "Could not validate environment config. Update React Compiler config to fix the error", description: `${fromZodError(config2.error)}`, loc: null, suggestions: null }); } function tryParseExternalFunction(maybeExternalFunction) { const externalFunction = ExternalFunctionSchema.safeParse( maybeExternalFunction ); if (externalFunction.success) { return externalFunction.data; } CompilerError.throwInvalidConfig({ reason: "Could not parse external function. Update React Compiler config to fix the error", description: `${fromZodError(externalFunction.error)}`, loc: null, suggestions: null }); } var DEFAULT_EXPORT = "default"; // src/HIR/MergeConsecutiveBlocks.ts function mergeConsecutiveBlocks(fn) { const merged = new MergedBlocks(); const fallthroughBlocks = /* @__PURE__ */ new Set(); for (const [, block] of fn.body.blocks) { const fallthrough = terminalFallthrough(block.terminal); if (fallthrough !== null) { fallthroughBlocks.add(fallthrough); } for (const instr of block.instructions) { if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { mergeConsecutiveBlocks(instr.value.loweredFunc.func); } } if ( // Can only merge blocks with a single predecessor block.preds.size !== 1 || // Value blocks cannot merge block.kind !== "block" || // Merging across fallthroughs could move the predecessor out of its block scope fallthroughBlocks.has(block.id) ) { continue; } const originalPredecessorId = Array.from(block.preds)[0]; const predecessorId = merged.get(originalPredecessorId); const predecessor = fn.body.blocks.get(predecessorId); CompilerError.invariant(predecessor !== void 0, { reason: `Expected predecessor ${predecessorId} to exist`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); if (predecessor.terminal.kind !== "goto" || predecessor.kind !== "block") { continue; } for (const phi of block.phis) { CompilerError.invariant(phi.operands.size === 1, { reason: `Found a block with a single predecessor but where a phi has multiple (${phi.operands.size}) operands`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); const operand = Array.from(phi.operands.values())[0]; const lvalue = { kind: "Identifier", identifier: phi.place.identifier, effect: "mutate?" /* ConditionallyMutate */, reactive: false, loc: GeneratedSource }; const instr = { id: predecessor.terminal.id, lvalue: __spreadValues({}, lvalue), value: { kind: "LoadLocal", place: __spreadValues({}, operand), loc: GeneratedSource }, effects: [{ kind: "Alias", from: __spreadValues({}, operand), into: __spreadValues({}, lvalue) }], loc: GeneratedSource }; predecessor.instructions.push(instr); } predecessor.instructions.push(...block.instructions); predecessor.terminal = block.terminal; merged.merge(block.id, predecessorId); fn.body.blocks.delete(block.id); } for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { for (const [predecessorId, operand] of phi.operands) { const mapped = merged.get(predecessorId); if (mapped !== predecessorId) { phi.operands.delete(predecessorId); phi.operands.set(mapped, operand); } } } } markPredecessors(fn.body); for (const [, { terminal }] of fn.body.blocks) { if (terminalHasFallthrough(terminal)) { terminal.fallthrough = merged.get(terminal.fallthrough); } } } var _map2; var MergedBlocks = class { constructor() { __privateAdd(this, _map2, /* @__PURE__ */ new Map()); } // Record that @param block was merged into @param into. merge(block, into) { const target = this.get(into); __privateGet(this, _map2).set(block, target); } /* * Get the id of the block that @param block has been merged into. * This is transitive, in the case that eg @param block was merged * into a block which later merged into another block. */ get(block) { var _a; let current = block; while (__privateGet(this, _map2).has(current)) { current = (_a = __privateGet(this, _map2).get(current)) != null ? _a : current; } return current; } }; _map2 = new WeakMap(); // src/Utils/DisjointSet.ts var _entries; var DisjointSet = class { constructor() { __privateAdd(this, _entries, /* @__PURE__ */ new Map()); } /* * Updates the graph to reflect that the given @param items form a set, * linking any previous sets that the items were part of into a single * set. */ union(items) { const first = items.shift(); CompilerError.invariant(first != null, { reason: "Expected set to be non-empty", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); let root2 = this.find(first); if (root2 == null) { root2 = first; __privateGet(this, _entries).set(first, first); } for (const item of items) { let itemParent = __privateGet(this, _entries).get(item); if (itemParent == null) { __privateGet(this, _entries).set(item, root2); continue; } else if (itemParent === root2) { continue; } else { let current = item; while (itemParent !== root2) { __privateGet(this, _entries).set(current, root2); current = itemParent; itemParent = __privateGet(this, _entries).get(current); } } } } /* * Finds the set to which the given @param item is associated, if @param item * is present in this set. If item is not present, returns null. * * Note that the returned value may be any item in the set to which the input * belongs: the only guarantee is that all items in a set will return the same * value in between calls to `union()`. */ find(item) { if (!__privateGet(this, _entries).has(item)) { return null; } const parent = __privateGet(this, _entries).get(item); if (parent === item) { return item; } const root2 = this.find(parent); __privateGet(this, _entries).set(item, root2); return root2; } has(item) { return __privateGet(this, _entries).has(item); } /* * Forces the set into canonical form, ie with all items pointing directly to * their root, and returns a Map representing the mapping of items to their roots. */ canonicalize() { const entries = /* @__PURE__ */ new Map(); for (const item of __privateGet(this, _entries).keys()) { const root2 = this.find(item); entries.set(item, root2); } return entries; } /* * Calls the provided callback once for each item in the disjoint set, * passing the @param item and the @param group to which it belongs. */ forEach(fn) { for (const item of __privateGet(this, _entries).keys()) { const group = this.find(item); fn(item, group); } } buildSets() { const ids = /* @__PURE__ */ new Map(); const sets = /* @__PURE__ */ new Map(); this.forEach((identifier4, groupIdentifier) => { let id = ids.get(groupIdentifier); if (id == null) { id = ids.size; ids.set(groupIdentifier, id); } let set2 = sets.get(id); if (set2 === void 0) { set2 = /* @__PURE__ */ new Set(); sets.set(id, set2); } set2.add(identifier4); }); return [...sets.values()]; } get size() { return __privateGet(this, _entries).size; } }; _entries = new WeakMap(); // src/ReactiveScopes/InferReactiveScopeVariables.ts function inferReactiveScopeVariables(fn) { var _a, _b; const scopeIdentifiers = findDisjointMutableValues(fn); const scopes = /* @__PURE__ */ new Map(); scopeIdentifiers.forEach((identifier4, groupIdentifier) => { let scope = scopes.get(groupIdentifier); if (scope === void 0) { scope = { id: fn.env.nextScopeId, range: identifier4.mutableRange, dependencies: /* @__PURE__ */ new Set(), declarations: /* @__PURE__ */ new Map(), reassignments: /* @__PURE__ */ new Set(), earlyReturnValue: null, merged: /* @__PURE__ */ new Set(), loc: identifier4.loc }; scopes.set(groupIdentifier, scope); } else { if (scope.range.start === 0) { scope.range.start = identifier4.mutableRange.start; } else if (identifier4.mutableRange.start !== 0) { scope.range.start = makeInstructionId( Math.min(scope.range.start, identifier4.mutableRange.start) ); } scope.range.end = makeInstructionId( Math.max(scope.range.end, identifier4.mutableRange.end) ); scope.loc = mergeLocation(scope.loc, identifier4.loc); } identifier4.scope = scope; identifier4.mutableRange = scope.range; }); let maxInstruction = 0; for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { maxInstruction = makeInstructionId(Math.max(maxInstruction, instr.id)); } maxInstruction = makeInstructionId( Math.max(maxInstruction, block.terminal.id) ); } for (const [, scope] of scopes) { if (scope.range.start === 0 || scope.range.end === 0 || maxInstruction === 0 || scope.range.end > maxInstruction + 1) { (_b = (_a = fn.env.logger) == null ? void 0 : _a.debugLogIRs) == null ? void 0 : _b.call(_a, { kind: "hir", name: "InferReactiveScopeVariables (invalid scope)", value: fn }); CompilerError.invariant(false, { reason: `Invalid mutable range for scope`, details: [ { kind: "error", loc: GeneratedSource, message: null } ], description: `Scope @${scope.id} has range [${scope.range.start}:${scope.range.end}] but the valid range is [1:${maxInstruction + 1}]` }); } } } function mergeLocation(l, r) { if (l === GeneratedSource) { return r; } else if (r === GeneratedSource) { return l; } else { return { filename: l.filename, identifierName: l.identifierName, start: { index: Math.min(l.start.index, r.start.index), line: Math.min(l.start.line, r.start.line), column: Math.min(l.start.column, r.start.column) }, end: { index: Math.max(l.end.index, r.end.index), line: Math.max(l.end.line, r.end.line), column: Math.max(l.end.column, r.end.column) } }; } } function isMutable2(instr, place) { return inRange(instr, place.identifier.mutableRange); } function inRange({ id }, range) { return id >= range.start && id < range.end; } function mayAllocate(_env4, instruction) { const { value } = instruction; switch (value.kind) { case "Destructure": { return doesPatternContainSpreadElement(value.lvalue.pattern); } case "PostfixUpdate": case "PrefixUpdate": case "Await": case "DeclareLocal": case "DeclareContext": case "StoreLocal": case "LoadGlobal": case "MetaProperty": case "TypeCastExpression": case "LoadLocal": case "LoadContext": case "StoreContext": case "PropertyDelete": case "ComputedLoad": case "ComputedDelete": case "JSXText": case "TemplateLiteral": case "Primitive": case "GetIterator": case "IteratorNext": case "NextPropertyOf": case "Debugger": case "StartMemoize": case "FinishMemoize": case "UnaryExpression": case "BinaryExpression": case "PropertyLoad": case "StoreGlobal": { return false; } case "TaggedTemplateExpression": case "CallExpression": case "MethodCall": { return instruction.lvalue.identifier.type.kind !== "Primitive"; } case "RegExpLiteral": case "PropertyStore": case "ComputedStore": case "ArrayExpression": case "JsxExpression": case "JsxFragment": case "NewExpression": case "ObjectExpression": case "UnsupportedNode": case "ObjectMethod": case "FunctionExpression": { return true; } default: { assertExhaustive( value, `Unexpected value kind \`${value.kind}\`` ); } } } function findDisjointMutableValues(fn) { var _a, _b; const scopeIdentifiers = new DisjointSet(); const declarations = /* @__PURE__ */ new Map(); function declareIdentifier(lvalue) { if (!declarations.has(lvalue.identifier.declarationId)) { declarations.set(lvalue.identifier.declarationId, lvalue.identifier); } } for (const [_, block] of fn.body.blocks) { for (const phi of block.phis) { if (phi.place.identifier.mutableRange.start + 1 !== phi.place.identifier.mutableRange.end && phi.place.identifier.mutableRange.end > ((_b = (_a = block.instructions.at(0)) == null ? void 0 : _a.id) != null ? _b : block.terminal.id)) { const operands = [phi.place.identifier]; const declaration = declarations.get( phi.place.identifier.declarationId ); if (declaration !== void 0) { operands.push(declaration); } for (const [_2, phiId] of phi.operands) { operands.push(phiId.identifier); } scopeIdentifiers.union(operands); } else if (fn.env.config.enableForest) { for (const [, phiId] of phi.operands) { scopeIdentifiers.union([phi.place.identifier, phiId.identifier]); } } } for (const instr of block.instructions) { const operands = []; const range = instr.lvalue.identifier.mutableRange; if (range.end > range.start + 1 || mayAllocate(fn.env, instr)) { operands.push(instr.lvalue.identifier); } if (instr.value.kind === "DeclareLocal" || instr.value.kind === "DeclareContext") { declareIdentifier(instr.value.lvalue.place); } else if (instr.value.kind === "StoreLocal" || instr.value.kind === "StoreContext") { declareIdentifier(instr.value.lvalue.place); if (instr.value.lvalue.place.identifier.mutableRange.end > instr.value.lvalue.place.identifier.mutableRange.start + 1) { operands.push(instr.value.lvalue.place.identifier); } if (isMutable2(instr, instr.value.value) && instr.value.value.identifier.mutableRange.start > 0) { operands.push(instr.value.value.identifier); } } else if (instr.value.kind === "Destructure") { for (const place of eachPatternOperand(instr.value.lvalue.pattern)) { declareIdentifier(place); if (place.identifier.mutableRange.end > place.identifier.mutableRange.start + 1) { operands.push(place.identifier); } } if (isMutable2(instr, instr.value.value) && instr.value.value.identifier.mutableRange.start > 0) { operands.push(instr.value.value.identifier); } } else if (instr.value.kind === "MethodCall") { for (const operand of eachInstructionOperand(instr)) { if (isMutable2(instr, operand) && /* * exclude global variables from being added to scopes, we can't recreate them! * TODO: improve handling of module-scoped variables and globals */ operand.identifier.mutableRange.start > 0) { operands.push(operand.identifier); } } operands.push(instr.value.property.identifier); } else { for (const operand of eachInstructionOperand(instr)) { if (isMutable2(instr, operand) && /* * exclude global variables from being added to scopes, we can't recreate them! * TODO: improve handling of module-scoped variables and globals */ operand.identifier.mutableRange.start > 0) { if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { if (operand.identifier.type.kind === "Primitive") { continue; } } operands.push(operand.identifier); } } } if (operands.length !== 0) { scopeIdentifiers.union(operands); } } } return scopeIdentifiers; } // src/HIR/MergeOverlappingReactiveScopesHIR.ts function mergeOverlappingReactiveScopesHIR(fn) { const scopesInfo = collectScopeInfo(fn); const joinedScopes = getOverlappingReactiveScopes(fn, scopesInfo); joinedScopes.forEach((scope, groupScope) => { if (scope !== groupScope) { groupScope.range.start = makeInstructionId( Math.min(groupScope.range.start, scope.range.start) ); groupScope.range.end = makeInstructionId( Math.max(groupScope.range.end, scope.range.end) ); } }); for (const [place, originalScope] of scopesInfo.placeScopes) { const nextScope = joinedScopes.find(originalScope); if (nextScope !== null && nextScope !== originalScope) { place.identifier.scope = nextScope; } } } function collectScopeInfo(fn) { const scopeStarts = /* @__PURE__ */ new Map(); const scopeEnds = /* @__PURE__ */ new Map(); const placeScopes = /* @__PURE__ */ new Map(); function collectPlaceScope(place) { const scope = place.identifier.scope; if (scope != null) { placeScopes.set(place, scope); if (scope.range.start !== scope.range.end) { getOrInsertDefault(scopeStarts, scope.range.start, /* @__PURE__ */ new Set()).add( scope ); getOrInsertDefault(scopeEnds, scope.range.end, /* @__PURE__ */ new Set()).add(scope); } } } for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { for (const operand of eachInstructionLValue(instr)) { collectPlaceScope(operand); } for (const operand of eachInstructionOperand(instr)) { collectPlaceScope(operand); } } for (const operand of eachTerminalOperand(block.terminal)) { collectPlaceScope(operand); } } return { scopeStarts: [...scopeStarts.entries()].map(([id, scopes]) => ({ id, scopes })).sort((a, b) => b.id - a.id), scopeEnds: [...scopeEnds.entries()].map(([id, scopes]) => ({ id, scopes })).sort((a, b) => b.id - a.id), placeScopes }; } function visitInstructionId(id, { scopeEnds, scopeStarts }, { activeScopes, joined }) { const scopeEndTop = scopeEnds.at(-1); if (scopeEndTop != null && scopeEndTop.id <= id) { scopeEnds.pop(); const scopesSortedStartDescending = [...scopeEndTop.scopes].sort( (a, b) => b.range.start - a.range.start ); for (const scope of scopesSortedStartDescending) { const idx = activeScopes.indexOf(scope); if (idx !== -1) { if (idx !== activeScopes.length - 1) { joined.union([scope, ...activeScopes.slice(idx + 1)]); } activeScopes.splice(idx, 1); } } } const scopeStartTop = scopeStarts.at(-1); if (scopeStartTop != null && scopeStartTop.id <= id) { scopeStarts.pop(); const scopesSortedEndDescending = [...scopeStartTop.scopes].sort( (a, b) => b.range.end - a.range.end ); activeScopes.push(...scopesSortedEndDescending); for (let i = 1; i < scopesSortedEndDescending.length; i++) { const prev = scopesSortedEndDescending[i - 1]; const curr = scopesSortedEndDescending[i]; if (prev.range.end === curr.range.end) { joined.union([prev, curr]); } } } } function visitPlace(id, place, { activeScopes, joined }) { const placeScope = getPlaceScope(id, place); if (placeScope != null && isMutable2({ id }, place)) { const placeScopeIdx = activeScopes.indexOf(placeScope); if (placeScopeIdx !== -1 && placeScopeIdx !== activeScopes.length - 1) { joined.union([placeScope, ...activeScopes.slice(placeScopeIdx + 1)]); } } } function getOverlappingReactiveScopes(fn, context) { const state = { joined: new DisjointSet(), activeScopes: [] }; for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { visitInstructionId(instr.id, context, state); for (const place of eachInstructionOperand(instr)) { if ((instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") && place.identifier.type.kind === "Primitive") { continue; } visitPlace(instr.id, place, state); } for (const place of eachInstructionLValue(instr)) { visitPlace(instr.id, place, state); } } visitInstructionId(block.terminal.id, context, state); for (const place of eachTerminalOperand(block.terminal)) { visitPlace(block.terminal.id, place, state); } } return state.joined; } // src/HIR/PruneUnusedLabelsHIR.ts function pruneUnusedLabelsHIR(fn) { var _a; const merged = []; const rewrites = /* @__PURE__ */ new Map(); for (const [blockId, block] of fn.body.blocks) { const terminal = block.terminal; if (terminal.kind === "label") { const { block: nextId, fallthrough: fallthroughId } = terminal; const next = fn.body.blocks.get(nextId); const fallthrough = fn.body.blocks.get(fallthroughId); if (next.terminal.kind === "goto" && next.terminal.variant === "Break" /* Break */ && next.terminal.block === fallthroughId) { if (next.kind === "block" && fallthrough.kind === "block") { merged.push({ label: blockId, next: nextId, fallthrough: fallthroughId }); } } } } for (const { label: originalLabelId, next: nextId, fallthrough: fallthroughId } of merged) { const labelId = (_a = rewrites.get(originalLabelId)) != null ? _a : originalLabelId; const label = fn.body.blocks.get(labelId); const next = fn.body.blocks.get(nextId); const fallthrough = fn.body.blocks.get(fallthroughId); CompilerError.invariant( next.phis.size === 0 && fallthrough.phis.size === 0, { reason: "Unexpected phis when merging label blocks", description: null, details: [ { kind: "error", loc: label.terminal.loc, message: null } ] } ); CompilerError.invariant( next.preds.size === 1 && fallthrough.preds.size === 1 && next.preds.has(originalLabelId) && fallthrough.preds.has(nextId), { reason: "Unexpected block predecessors when merging label blocks", description: null, details: [ { kind: "error", loc: label.terminal.loc, message: null } ] } ); label.instructions.push(...next.instructions, ...fallthrough.instructions); label.terminal = fallthrough.terminal; fn.body.blocks.delete(nextId); fn.body.blocks.delete(fallthroughId); rewrites.set(fallthroughId, labelId); } for (const [_, block] of fn.body.blocks) { for (const pred of block.preds) { const rewritten = rewrites.get(pred); if (rewritten != null) { block.preds.delete(pred); block.preds.add(rewritten); } } } } // src/Entrypoint/Program.ts var t4 = __toESM(require("@babel/types")); // src/Utils/ComponentDeclaration.ts function isComponentDeclaration(node) { return Object.prototype.hasOwnProperty.call(node, "__componentDeclaration"); } // src/Utils/HookDeclaration.ts function isHookDeclaration(node) { return Object.prototype.hasOwnProperty.call(node, "__hookDeclaration"); } // src/Entrypoint/Pipeline.ts var import_pretty_format3 = __toESM(require_build()); // src/HIR/FindContextIdentifiers.ts var DEFAULT_IDENTIFIER_INFO = { reassigned: false, reassignedByInnerFn: false, referencedByInnerFn: false }; var withFunctionScope = { enter: function(path, state) { state.currentFn.push(path); }, exit: function(_, state) { state.currentFn.pop(); } }; function findContextIdentifiers(func) { const state = { currentFn: [], identifiers: /* @__PURE__ */ new Map() }; func.traverse( { FunctionDeclaration: withFunctionScope, FunctionExpression: withFunctionScope, ArrowFunctionExpression: withFunctionScope, ObjectMethod: withFunctionScope, AssignmentExpression(path, state2) { var _a, _b; const left = path.get("left"); if (left.isLVal()) { const currentFn = (_a = state2.currentFn.at(-1)) != null ? _a : null; handleAssignment(currentFn, state2.identifiers, left); } else { CompilerError.throwTodo({ reason: `Unsupported syntax on the left side of an AssignmentExpression`, description: `Expected an LVal, got: ${left.type}`, loc: (_b = left.node.loc) != null ? _b : null }); } }, UpdateExpression(path, state2) { var _a; const argument = path.get("argument"); const currentFn = (_a = state2.currentFn.at(-1)) != null ? _a : null; if (argument.isLVal()) { handleAssignment(currentFn, state2.identifiers, argument); } }, Identifier(path, state2) { var _a; const currentFn = (_a = state2.currentFn.at(-1)) != null ? _a : null; if (path.isReferencedIdentifier()) { handleIdentifier(currentFn, state2.identifiers, path); } } }, state ); const result = /* @__PURE__ */ new Set(); for (const [id, info] of state.identifiers.entries()) { if (info.reassignedByInnerFn) { result.add(id); } else if (info.reassigned && info.referencedByInnerFn) { result.add(id); } } return result; } function handleIdentifier(currentFn, identifiers, path) { const name = path.node.name; const binding = path.scope.getBinding(name); if (binding == null) { return; } const identifier4 = getOrInsertDefault(identifiers, binding.identifier, __spreadValues({}, DEFAULT_IDENTIFIER_INFO)); if (currentFn != null) { const bindingAboveLambdaScope = currentFn.scope.parent.getBinding(name); if (binding === bindingAboveLambdaScope) { identifier4.referencedByInnerFn = true; } } } function handleAssignment(currentFn, identifiers, lvalPath) { var _a, _b, _c; const lvalNode = lvalPath.node; switch (lvalNode.type) { case "Identifier": { const path = lvalPath; const name = path.node.name; const binding = path.scope.getBinding(name); if (binding == null) { break; } const state = getOrInsertDefault(identifiers, binding.identifier, __spreadValues({}, DEFAULT_IDENTIFIER_INFO)); state.reassigned = true; if (currentFn != null) { const bindingAboveLambdaScope = currentFn.scope.parent.getBinding(name); if (binding === bindingAboveLambdaScope) { state.reassignedByInnerFn = true; } } break; } case "ArrayPattern": { const path = lvalPath; for (const element of path.get("elements")) { if (nonNull(element)) { handleAssignment(currentFn, identifiers, element); } } break; } case "ObjectPattern": { const path = lvalPath; for (const property of path.get("properties")) { if (property.isObjectProperty()) { const valuePath = property.get("value"); CompilerError.invariant(valuePath.isLVal(), { reason: `[FindContextIdentifiers] Expected object property value to be an LVal, got: ${valuePath.type}`, description: null, details: [ { kind: "error", loc: (_a = valuePath.node.loc) != null ? _a : GeneratedSource, message: null } ], suggestions: null }); handleAssignment(currentFn, identifiers, valuePath); } else { CompilerError.invariant(property.isRestElement(), { reason: `[FindContextIdentifiers] Invalid assumptions for babel types.`, description: null, details: [ { kind: "error", loc: (_b = property.node.loc) != null ? _b : GeneratedSource, message: null } ], suggestions: null }); handleAssignment(currentFn, identifiers, property); } } break; } case "AssignmentPattern": { const path = lvalPath; const left = path.get("left"); handleAssignment(currentFn, identifiers, left); break; } case "RestElement": { const path = lvalPath; handleAssignment(currentFn, identifiers, path.get("argument")); break; } case "MemberExpression": { break; } default: { CompilerError.throwTodo({ reason: `[FindContextIdentifiers] Cannot handle Object destructuring assignment target ${lvalNode.type}`, description: null, loc: (_c = lvalNode.loc) != null ? _c : GeneratedSource, suggestions: null }); } } } function nonNull(t6) { return t6.node != null; } // src/Optimization/ConstantPropagation.ts var import_types2 = require("@babel/types"); // src/SSA/EliminateRedundantPhi.ts var DEBUG = false; function eliminateRedundantPhi(fn, sharedRewrites) { const ir = fn.body; const rewrites = sharedRewrites != null ? sharedRewrites : /* @__PURE__ */ new Map(); let hasBackEdge2 = false; const visited = /* @__PURE__ */ new Set(); let size = rewrites.size; do { size = rewrites.size; for (const [blockId, block] of ir.blocks) { if (!hasBackEdge2) { for (const predId of block.preds) { if (!visited.has(predId)) { hasBackEdge2 = true; } } } visited.add(blockId); phis: for (const phi of block.phis) { phi.operands.forEach((place, _) => rewritePlace(place, rewrites)); let same = null; for (const [_, operand] of phi.operands) { if (same !== null && operand.identifier.id === same.id || operand.identifier.id === phi.place.identifier.id) { continue; } else if (same !== null) { continue phis; } else { same = operand.identifier; } } CompilerError.invariant(same !== null, { reason: "Expected phis to be non-empty", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); rewrites.set(phi.place.identifier, same); block.phis.delete(phi); } for (const instr of block.instructions) { for (const place of eachInstructionLValue(instr)) { rewritePlace(place, rewrites); } for (const place of eachInstructionOperand(instr)) { rewritePlace(place, rewrites); } if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { const { context } = instr.value.loweredFunc.func; for (const place of context) { rewritePlace(place, rewrites); } eliminateRedundantPhi(instr.value.loweredFunc.func, rewrites); } } const { terminal } = block; for (const place of eachTerminalOperand(terminal)) { rewritePlace(place, rewrites); } } } while (rewrites.size > size && hasBackEdge2); if (DEBUG) { for (const [, block] of ir.blocks) { for (const phi of block.phis) { CompilerError.invariant(!rewrites.has(phi.place.identifier), { reason: "[EliminateRedundantPhis]: rewrite not complete", description: null, details: [ { kind: "error", loc: phi.place.loc, message: null } ] }); for (const [, operand] of phi.operands) { CompilerError.invariant(!rewrites.has(operand.identifier), { reason: "[EliminateRedundantPhis]: rewrite not complete", description: null, details: [ { kind: "error", loc: phi.place.loc, message: null } ] }); } } } } } function rewritePlace(place, rewrites) { const rewrite = rewrites.get(place.identifier); if (rewrite != null) { place.identifier = rewrite; } } // src/SSA/EnterSSA.ts var _states, _current2, _blocks, _env2, _unknown2, _context2; var SSABuilder = class { constructor(env, blocks) { __privateAdd(this, _states, /* @__PURE__ */ new Map()); __privateAdd(this, _current2, null); this.unsealedPreds = /* @__PURE__ */ new Map(); __privateAdd(this, _blocks); __privateAdd(this, _env2); __privateAdd(this, _unknown2, /* @__PURE__ */ new Set()); __privateAdd(this, _context2, /* @__PURE__ */ new Set()); __privateSet(this, _blocks, new Map(blocks)); __privateSet(this, _env2, env); } get nextSsaId() { return __privateGet(this, _env2).nextIdentifierId; } defineFunction(func) { for (const [id, block] of func.body.blocks) { __privateGet(this, _blocks).set(id, block); } } enter(fn) { const current = __privateGet(this, _current2); fn(); __privateSet(this, _current2, current); } state() { CompilerError.invariant(__privateGet(this, _current2) !== null, { reason: "we need to be in a block to access state!", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return __privateGet(this, _states).get(__privateGet(this, _current2)); } makeId(oldId) { return { id: this.nextSsaId, declarationId: oldId.declarationId, name: oldId.name, mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, scope: null, // reset along w the mutable range type: makeType(), loc: oldId.loc }; } defineContext(oldPlace) { const newPlace = this.definePlace(oldPlace); __privateGet(this, _context2).add(oldPlace.identifier); return newPlace; } definePlace(oldPlace) { const oldId = oldPlace.identifier; if (__privateGet(this, _unknown2).has(oldId)) { CompilerError.throwTodo({ reason: `[hoisting] EnterSSA: Expected identifier to be defined before being used`, description: `Identifier ${printIdentifier(oldId)} is undefined`, loc: oldPlace.loc, suggestions: null }); } if (__privateGet(this, _context2).has(oldId)) { return this.getPlace(oldPlace); } const newId = this.makeId(oldId); this.state().defs.set(oldId, newId); return __spreadProps(__spreadValues({}, oldPlace), { identifier: newId }); } getPlace(oldPlace) { const newId = this.getIdAt(oldPlace, __privateGet(this, _current2).id); return __spreadProps(__spreadValues({}, oldPlace), { identifier: newId }); } getIdAt(oldPlace, blockId) { const block = __privateGet(this, _blocks).get(blockId); const state = __privateGet(this, _states).get(block); if (state.defs.has(oldPlace.identifier)) { return state.defs.get(oldPlace.identifier); } if (block.preds.size == 0) { __privateGet(this, _unknown2).add(oldPlace.identifier); return oldPlace.identifier; } if (this.unsealedPreds.get(block) > 0) { const newId2 = this.makeId(oldPlace.identifier); state.incompletePhis.push({ oldPlace, newPlace: __spreadProps(__spreadValues({}, oldPlace), { identifier: newId2 }) }); state.defs.set(oldPlace.identifier, newId2); return newId2; } if (block.preds.size == 1) { const [pred] = block.preds; const newId2 = this.getIdAt(oldPlace, pred); state.defs.set(oldPlace.identifier, newId2); return newId2; } const newId = this.makeId(oldPlace.identifier); state.defs.set(oldPlace.identifier, newId); return this.addPhi(block, oldPlace, __spreadProps(__spreadValues({}, oldPlace), { identifier: newId })); } addPhi(block, oldPlace, newPlace) { const predDefs = /* @__PURE__ */ new Map(); for (const predBlockId of block.preds) { const predId = this.getIdAt(oldPlace, predBlockId); predDefs.set(predBlockId, __spreadProps(__spreadValues({}, oldPlace), { identifier: predId })); } const phi = { kind: "Phi", place: newPlace, operands: predDefs }; block.phis.add(phi); return newPlace.identifier; } fixIncompletePhis(block) { const state = __privateGet(this, _states).get(block); for (const phi of state.incompletePhis) { this.addPhi(block, phi.oldPlace, phi.newPlace); } } startBlock(block) { __privateSet(this, _current2, block); __privateGet(this, _states).set(block, { defs: /* @__PURE__ */ new Map(), incompletePhis: [] }); } print() { var _a; const text = []; for (const [block, state] of __privateGet(this, _states)) { text.push(`bb${block.id}:`); for (const [oldId, newId] of state.defs) { text.push(` $${printIdentifier(oldId)}: $${printIdentifier(newId)}`); } for (const incompletePhi of state.incompletePhis) { text.push( ` iphi $${printPlace( incompletePhi.newPlace )} = $${printPlace(incompletePhi.oldPlace)}` ); } } text.push(`current block: bb${(_a = __privateGet(this, _current2)) == null ? void 0 : _a.id}`); console.log(text.join("\n")); } }; _states = new WeakMap(); _current2 = new WeakMap(); _blocks = new WeakMap(); _env2 = new WeakMap(); _unknown2 = new WeakMap(); _context2 = new WeakMap(); function enterSSA(func) { const builder = new SSABuilder(func.env, func.body.blocks); enterSSAImpl(func, builder, func.body.entry); } function enterSSAImpl(func, builder, rootEntry) { const visitedBlocks = /* @__PURE__ */ new Set(); for (const [blockId, block] of func.body.blocks) { CompilerError.invariant(!visitedBlocks.has(block), { reason: `found a cycle! visiting bb${block.id} again`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); visitedBlocks.add(block); builder.startBlock(block); if (blockId === rootEntry) { CompilerError.invariant(func.context.length === 0, { reason: `Expected function context to be empty for outer function declarations`, description: null, details: [ { kind: "error", loc: func.loc, message: null } ], suggestions: null }); func.params = func.params.map((param) => { if (param.kind === "Identifier") { return builder.definePlace(param); } else { return { kind: "Spread", place: builder.definePlace(param.place) }; } }); } for (const instr of block.instructions) { mapInstructionOperands(instr, (place) => builder.getPlace(place)); mapInstructionLValues(instr, (lvalue) => builder.definePlace(lvalue)); if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { const loweredFunc = instr.value.loweredFunc.func; const entry = loweredFunc.body.blocks.get(loweredFunc.body.entry); CompilerError.invariant(entry.preds.size === 0, { reason: "Expected function expression entry block to have zero predecessors", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); entry.preds.add(blockId); builder.defineFunction(loweredFunc); builder.enter(() => { loweredFunc.params = loweredFunc.params.map((param) => { if (param.kind === "Identifier") { return builder.definePlace(param); } else { return { kind: "Spread", place: builder.definePlace(param.place) }; } }); enterSSAImpl(loweredFunc, builder, rootEntry); }); entry.preds.clear(); } } mapTerminalOperands(block.terminal, (place) => builder.getPlace(place)); for (const outputId of eachTerminalSuccessor(block.terminal)) { const output = func.body.blocks.get(outputId); let count; if (builder.unsealedPreds.has(output)) { count = builder.unsealedPreds.get(output) - 1; } else { count = output.preds.size - 1; } builder.unsealedPreds.set(output, count); if (count === 0 && visitedBlocks.has(output)) { builder.fixIncompletePhis(output); } } } } // src/SSA/RewriteInstructionKindsBasedOnReassignment.ts function rewriteInstructionKindsBasedOnReassignment(fn) { const declarations = /* @__PURE__ */ new Map(); for (const param of fn.params) { let place = param.kind === "Identifier" ? param : param.place; if (place.identifier.name !== null) { declarations.set(place.identifier.declarationId, { kind: "Let" /* Let */, place }); } } for (const place of fn.context) { if (place.identifier.name !== null) { declarations.set(place.identifier.declarationId, { kind: "Let" /* Let */, place }); } } for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { const { value } = instr; switch (value.kind) { case "DeclareLocal": { const lvalue = value.lvalue; CompilerError.invariant( !declarations.has(lvalue.place.identifier.declarationId), { reason: `Expected variable not to be defined prior to declaration`, description: `${printPlace(lvalue.place)} was already defined`, details: [ { kind: "error", loc: lvalue.place.loc, message: null } ] } ); declarations.set(lvalue.place.identifier.declarationId, lvalue); break; } case "StoreLocal": { const lvalue = value.lvalue; if (lvalue.place.identifier.name !== null) { const declaration = declarations.get( lvalue.place.identifier.declarationId ); if (declaration === void 0) { CompilerError.invariant( !declarations.has(lvalue.place.identifier.declarationId), { reason: `Expected variable not to be defined prior to declaration`, description: `${printPlace(lvalue.place)} was already defined`, details: [ { kind: "error", loc: lvalue.place.loc, message: null } ] } ); declarations.set(lvalue.place.identifier.declarationId, lvalue); lvalue.kind = "Const" /* Const */; } else { declaration.kind = "Let" /* Let */; lvalue.kind = "Reassign" /* Reassign */; } } break; } case "Destructure": { const lvalue = value.lvalue; let kind = null; for (const place of eachPatternOperand(lvalue.pattern)) { if (place.identifier.name === null) { CompilerError.invariant( kind === null || kind === "Const" /* Const */, { reason: `Expected consistent kind for destructuring`, description: `other places were \`${kind}\` but '${printPlace( place )}' is const`, details: [ { kind: "error", loc: place.loc, message: "Expected consistent kind for destructuring" } ], suggestions: null } ); kind = "Const" /* Const */; } else { const declaration = declarations.get( place.identifier.declarationId ); if (declaration === void 0) { CompilerError.invariant(block.kind !== "value", { reason: `TODO: Handle reassignment in a value block where the original declaration was removed by dead code elimination (DCE)`, description: null, details: [ { kind: "error", loc: place.loc, message: null } ], suggestions: null }); declarations.set(place.identifier.declarationId, lvalue); CompilerError.invariant( kind === null || kind === "Const" /* Const */, { reason: `Expected consistent kind for destructuring`, description: `Other places were \`${kind}\` but '${printPlace( place )}' is const`, details: [ { kind: "error", loc: place.loc, message: "Expected consistent kind for destructuring" } ], suggestions: null } ); kind = "Const" /* Const */; } else { CompilerError.invariant( kind === null || kind === "Reassign" /* Reassign */, { reason: `Expected consistent kind for destructuring`, description: `Other places were \`${kind}\` but '${printPlace( place )}' is reassigned`, details: [ { kind: "error", loc: place.loc, message: "Expected consistent kind for destructuring" } ], suggestions: null } ); kind = "Reassign" /* Reassign */; declaration.kind = "Let" /* Let */; } } } CompilerError.invariant(kind !== null, { reason: "Expected at least one operand", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); lvalue.kind = kind; break; } case "PostfixUpdate": case "PrefixUpdate": { const lvalue = value.lvalue; const declaration = declarations.get(lvalue.identifier.declarationId); CompilerError.invariant(declaration !== void 0, { reason: `Expected variable to have been defined`, description: `No declaration for ${printPlace(lvalue)}`, details: [ { kind: "error", loc: lvalue.loc, message: null } ] }); declaration.kind = "Let" /* Let */; break; } } } } } // src/Optimization/ConstantPropagation.ts function constantPropagation(fn) { const constants = /* @__PURE__ */ new Map(); constantPropagationImpl(fn, constants); } function constantPropagationImpl(fn, constants) { while (true) { const haveTerminalsChanged = applyConstantPropagation(fn, constants); if (!haveTerminalsChanged) { break; } reversePostorderBlocks(fn.body); removeUnreachableForUpdates(fn.body); removeDeadDoWhileStatements(fn.body); removeUnnecessaryTryCatch(fn.body); markInstructionIds(fn.body); markPredecessors(fn.body); for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { for (const [predecessor] of phi.operands) { if (!block.preds.has(predecessor)) { phi.operands.delete(predecessor); } } } } eliminateRedundantPhi(fn); mergeConsecutiveBlocks(fn); assertConsistentIdentifiers(fn); assertTerminalSuccessorsExist(fn); } } function applyConstantPropagation(fn, constants) { let hasChanges = false; for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { let value = evaluatePhi(phi, constants); if (value !== null) { constants.set(phi.place.identifier.id, value); } } for (let i = 0; i < block.instructions.length; i++) { if (block.kind === "sequence" && i === block.instructions.length - 1) { continue; } const instr = block.instructions[i]; const value = evaluateInstruction(constants, instr); if (value !== null) { constants.set(instr.lvalue.identifier.id, value); } } const terminal = block.terminal; switch (terminal.kind) { case "if": { const testValue = read2(constants, terminal.test); if (testValue !== null && testValue.kind === "Primitive") { hasChanges = true; const targetBlockId = testValue.value ? terminal.consequent : terminal.alternate; block.terminal = { kind: "goto", variant: "Break" /* Break */, block: targetBlockId, id: terminal.id, loc: terminal.loc }; } break; } default: { } } } return hasChanges; } function evaluatePhi(phi, constants) { var _a; let value = null; for (const [, operand] of phi.operands) { const operandValue = (_a = constants.get(operand.identifier.id)) != null ? _a : null; if (operandValue === null) { return null; } if (value === null) { value = operandValue; continue; } if (operandValue.kind !== value.kind) { return null; } switch (operandValue.kind) { case "Primitive": { CompilerError.invariant(value.kind === "Primitive", { reason: "value kind expected to be Primitive", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); if (operandValue.value !== value.value) { return null; } break; } case "LoadGlobal": { CompilerError.invariant(value.kind === "LoadGlobal", { reason: "value kind expected to be LoadGlobal", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); if (operandValue.binding.name !== value.binding.name) { return null; } break; } default: return null; } } return value; } function evaluateInstruction(constants, instr) { const value = instr.value; switch (value.kind) { case "Primitive": { return value; } case "LoadGlobal": { return value; } case "ComputedLoad": { const property = read2(constants, value.property); if (property !== null && property.kind === "Primitive" && (typeof property.value === "string" && (0, import_types2.isValidIdentifier)(property.value) || typeof property.value === "number")) { const nextValue = { kind: "PropertyLoad", loc: value.loc, property: makePropertyLiteral(property.value), object: value.object }; instr.value = nextValue; } return null; } case "ComputedStore": { const property = read2(constants, value.property); if (property !== null && property.kind === "Primitive" && (typeof property.value === "string" && (0, import_types2.isValidIdentifier)(property.value) || typeof property.value === "number")) { const nextValue = { kind: "PropertyStore", loc: value.loc, property: makePropertyLiteral(property.value), object: value.object, value: value.value }; instr.value = nextValue; } return null; } case "PostfixUpdate": { const previous = read2(constants, value.value); if (previous !== null && previous.kind === "Primitive" && typeof previous.value === "number") { const next = value.operation === "++" ? previous.value + 1 : previous.value - 1; constants.set(value.lvalue.identifier.id, { kind: "Primitive", value: next, loc: value.loc }); return previous; } return null; } case "PrefixUpdate": { const previous = read2(constants, value.value); if (previous !== null && previous.kind === "Primitive" && typeof previous.value === "number") { const next = { kind: "Primitive", value: value.operation === "++" ? previous.value + 1 : previous.value - 1, loc: value.loc }; constants.set(value.lvalue.identifier.id, next); return next; } return null; } case "UnaryExpression": { switch (value.operator) { case "!": { const operand = read2(constants, value.value); if (operand !== null && operand.kind === "Primitive") { const result = { kind: "Primitive", value: !operand.value, loc: value.loc }; instr.value = result; return result; } return null; } case "-": { const operand = read2(constants, value.value); if (operand !== null && operand.kind === "Primitive" && typeof operand.value === "number") { const result = { kind: "Primitive", value: operand.value * -1, loc: value.loc }; instr.value = result; return result; } return null; } default: return null; } } case "BinaryExpression": { const lhsValue = read2(constants, value.left); const rhsValue = read2(constants, value.right); if (lhsValue !== null && rhsValue !== null && lhsValue.kind === "Primitive" && rhsValue.kind === "Primitive") { const lhs = lhsValue.value; const rhs = rhsValue.value; let result = null; switch (value.operator) { case "+": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs + rhs, loc: value.loc }; } else if (typeof lhs === "string" && typeof rhs === "string") { result = { kind: "Primitive", value: lhs + rhs, loc: value.loc }; } break; } case "-": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs - rhs, loc: value.loc }; } break; } case "*": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs * rhs, loc: value.loc }; } break; } case "/": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs / rhs, loc: value.loc }; } break; } case "|": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs | rhs, loc: value.loc }; } break; } case "&": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs & rhs, loc: value.loc }; } break; } case "^": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs ^ rhs, loc: value.loc }; } break; } case "<<": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs << rhs, loc: value.loc }; } break; } case ">>": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs >> rhs, loc: value.loc }; } break; } case ">>>": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs >>> rhs, loc: value.loc }; } break; } case "%": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs % rhs, loc: value.loc }; } break; } case "**": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: __pow(lhs, rhs), loc: value.loc }; } break; } case "<": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs < rhs, loc: value.loc }; } break; } case "<=": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs <= rhs, loc: value.loc }; } break; } case ">": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs > rhs, loc: value.loc }; } break; } case ">=": { if (typeof lhs === "number" && typeof rhs === "number") { result = { kind: "Primitive", value: lhs >= rhs, loc: value.loc }; } break; } case "==": { result = { kind: "Primitive", value: lhs == rhs, loc: value.loc }; break; } case "===": { result = { kind: "Primitive", value: lhs === rhs, loc: value.loc }; break; } case "!=": { result = { kind: "Primitive", value: lhs != rhs, loc: value.loc }; break; } case "!==": { result = { kind: "Primitive", value: lhs !== rhs, loc: value.loc }; break; } default: { break; } } if (result !== null) { instr.value = result; return result; } } return null; } case "PropertyLoad": { const objectValue = read2(constants, value.object); if (objectValue !== null) { if (objectValue.kind === "Primitive" && typeof objectValue.value === "string" && value.property === "length") { const result = { kind: "Primitive", value: objectValue.value.length, loc: value.loc }; instr.value = result; return result; } } return null; } case "TemplateLiteral": { if (value.subexprs.length === 0) { const result2 = { kind: "Primitive", value: value.quasis.map((q) => q.cooked).join(""), loc: value.loc }; instr.value = result2; return result2; } if (value.subexprs.length !== value.quasis.length - 1) { return null; } if (value.quasis.some((q) => q.cooked === void 0)) { return null; } let quasiIndex = 0; let resultString = value.quasis[quasiIndex].cooked; ++quasiIndex; for (const subExpr of value.subexprs) { const subExprValue = read2(constants, subExpr); if (!subExprValue || subExprValue.kind !== "Primitive") { return null; } const expressionValue = subExprValue.value; if (typeof expressionValue !== "number" && typeof expressionValue !== "string" && typeof expressionValue !== "boolean" && !(typeof expressionValue === "object" && expressionValue === null)) { return null; } const suffix = value.quasis[quasiIndex].cooked; ++quasiIndex; if (suffix === void 0) { return null; } resultString = resultString.concat(expressionValue, suffix); } const result = { kind: "Primitive", value: resultString, loc: value.loc }; instr.value = result; return result; } case "LoadLocal": { const placeValue = read2(constants, value.place); if (placeValue !== null) { instr.value = placeValue; } return placeValue; } case "StoreLocal": { const placeValue = read2(constants, value.value); if (placeValue !== null) { constants.set(value.lvalue.place.identifier.id, placeValue); } return placeValue; } case "ObjectMethod": case "FunctionExpression": { constantPropagationImpl(value.loweredFunc.func, constants); return null; } default: { return null; } } } function read2(constants, place) { var _a; return (_a = constants.get(place.identifier.id)) != null ? _a : null; } // src/Optimization/DeadCodeElimination.ts function deadCodeElimination(fn) { const state = findReferencedIdentifiers(fn); for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { if (!state.isIdOrNameUsed(phi.place.identifier)) { block.phis.delete(phi); } } retainWhere( block.instructions, (instr) => state.isIdOrNameUsed(instr.lvalue.identifier) ); for (let i = 0; i < block.instructions.length; i++) { const isBlockValue = block.kind !== "block" && i === block.instructions.length - 1; if (!isBlockValue) { rewriteInstruction(block.instructions[i], state); } } } retainWhere( fn.context, (contextVar) => state.isIdOrNameUsed(contextVar.identifier) ); } var State = class { constructor() { this.named = /* @__PURE__ */ new Set(); this.identifiers = /* @__PURE__ */ new Set(); } // Mark the identifier as being referenced (not dead code) reference(identifier4) { this.identifiers.add(identifier4.id); if (identifier4.name !== null) { this.named.add(identifier4.name.value); } } /* * Check if any version of the given identifier is used somewhere. * This checks both for usage of this specific identifer id (ssa id) * and (for named identifiers) for any usages of that identifier name. */ isIdOrNameUsed(identifier4) { return this.identifiers.has(identifier4.id) || identifier4.name !== null && this.named.has(identifier4.name.value); } /* * Like `used()`, but only checks for usages of this specific identifier id * (ssa id). */ isIdUsed(identifier4) { return this.identifiers.has(identifier4.id); } get count() { return this.identifiers.size; } }; function findReferencedIdentifiers(fn) { const hasLoop = hasBackEdge(fn); const reversedBlocks = [...fn.body.blocks.values()].reverse(); const state = new State(); let size = state.count; do { size = state.count; for (const block of reversedBlocks) { for (const operand of eachTerminalOperand(block.terminal)) { state.reference(operand.identifier); } for (let i = block.instructions.length - 1; i >= 0; i--) { const instr = block.instructions[i]; const isBlockValue = block.kind !== "block" && i === block.instructions.length - 1; if (isBlockValue) { state.reference(instr.lvalue.identifier); for (const place of eachInstructionValueOperand(instr.value)) { state.reference(place.identifier); } } else if (state.isIdOrNameUsed(instr.lvalue.identifier) || !pruneableValue(instr.value, state)) { state.reference(instr.lvalue.identifier); if (instr.value.kind === "StoreLocal") { if (instr.value.lvalue.kind === "Reassign" /* Reassign */ || state.isIdUsed(instr.value.lvalue.place.identifier)) { state.reference(instr.value.value.identifier); } } else { for (const operand of eachInstructionValueOperand(instr.value)) { state.reference(operand.identifier); } } } } for (const phi of block.phis) { if (state.isIdOrNameUsed(phi.place.identifier)) { for (const [_pred, operand] of phi.operands) { state.reference(operand.identifier); } } } } } while (state.count > size && hasLoop); return state; } function rewriteInstruction(instr, state) { if (instr.value.kind === "Destructure") { switch (instr.value.lvalue.pattern.kind) { case "ArrayPattern": { let lastEntryIndex = 0; const items = instr.value.lvalue.pattern.items; for (let i = 0; i < items.length; i++) { const item = items[i]; if (item.kind === "Identifier") { if (!state.isIdOrNameUsed(item.identifier)) { items[i] = { kind: "Hole" }; } else { lastEntryIndex = i; } } else if (item.kind === "Spread") { if (!state.isIdOrNameUsed(item.place.identifier)) { items[i] = { kind: "Hole" }; } else { lastEntryIndex = i; } } } items.length = lastEntryIndex + 1; break; } case "ObjectPattern": { let nextProperties = null; for (const property of instr.value.lvalue.pattern.properties) { if (property.kind === "ObjectProperty") { if (state.isIdOrNameUsed(property.place.identifier)) { nextProperties != null ? nextProperties : nextProperties = []; nextProperties.push(property); } } else { if (state.isIdOrNameUsed(property.place.identifier)) { nextProperties = null; break; } } } if (nextProperties !== null) { instr.value.lvalue.pattern.properties = nextProperties; } break; } default: { assertExhaustive( instr.value.lvalue.pattern, `Unexpected pattern kind '${instr.value.lvalue.pattern.kind}'` ); } } } else if (instr.value.kind === "StoreLocal") { if (instr.value.lvalue.kind !== "Reassign" /* Reassign */ && !state.isIdUsed(instr.value.lvalue.place.identifier)) { instr.value = { kind: "DeclareLocal", lvalue: instr.value.lvalue, type: instr.value.type, loc: instr.value.loc }; } } } function pruneableValue(value, state) { switch (value.kind) { case "DeclareLocal": { return !state.isIdOrNameUsed(value.lvalue.place.identifier); } case "StoreLocal": { if (value.lvalue.kind === "Reassign" /* Reassign */) { return !state.isIdUsed(value.lvalue.place.identifier); } return !state.isIdOrNameUsed(value.lvalue.place.identifier); } case "Destructure": { let isIdOrNameUsed = false; let isIdUsed = false; for (const place of eachPatternOperand(value.lvalue.pattern)) { if (state.isIdUsed(place.identifier)) { isIdOrNameUsed = true; isIdUsed = true; } else if (state.isIdOrNameUsed(place.identifier)) { isIdOrNameUsed = true; } } if (value.lvalue.kind === "Reassign" /* Reassign */) { return !isIdUsed; } else { return !isIdOrNameUsed; } } case "PostfixUpdate": case "PrefixUpdate": { return !state.isIdUsed(value.lvalue.identifier); } case "Debugger": { return false; } case "Await": case "CallExpression": case "ComputedDelete": case "ComputedStore": case "PropertyDelete": case "MethodCall": case "PropertyStore": case "StoreGlobal": { return false; } case "NewExpression": case "UnsupportedNode": case "TaggedTemplateExpression": { return false; } case "GetIterator": case "NextPropertyOf": case "IteratorNext": { return false; } case "LoadContext": case "DeclareContext": case "StoreContext": { return false; } case "StartMemoize": case "FinishMemoize": { return false; } case "RegExpLiteral": case "MetaProperty": case "LoadGlobal": case "ArrayExpression": case "BinaryExpression": case "ComputedLoad": case "ObjectMethod": case "FunctionExpression": case "LoadLocal": case "JsxExpression": case "JsxFragment": case "JSXText": case "ObjectExpression": case "Primitive": case "PropertyLoad": case "TemplateLiteral": case "TypeCastExpression": case "UnaryExpression": { return true; } default: { assertExhaustive( value, `Unexepcted value kind \`${value.kind}\`` ); } } } function hasBackEdge(fn) { return findBlocksWithBackEdges(fn).size > 0; } function findBlocksWithBackEdges(fn) { const visited = /* @__PURE__ */ new Set(); const blocks = /* @__PURE__ */ new Set(); for (const [blockId, block] of fn.body.blocks) { for (const predId of block.preds) { if (!visited.has(predId)) { blocks.add(blockId); } } visited.add(blockId); } return blocks; } // src/Optimization/PruneMaybeThrows.ts function pruneMaybeThrows(fn) { const terminalMapping = pruneMaybeThrowsImpl(fn); if (terminalMapping) { reversePostorderBlocks(fn.body); removeUnreachableForUpdates(fn.body); removeDeadDoWhileStatements(fn.body); removeUnnecessaryTryCatch(fn.body); markInstructionIds(fn.body); mergeConsecutiveBlocks(fn); for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { for (const [predecessor, operand] of phi.operands) { if (!block.preds.has(predecessor)) { const mappedTerminal = terminalMapping.get(predecessor); CompilerError.invariant(mappedTerminal != null, { reason: `Expected non-existing phi operand's predecessor to have been mapped to a new terminal`, details: [ { kind: "error", loc: GeneratedSource, message: null } ], description: `Could not find mapping for predecessor bb${predecessor} in block bb${block.id} for phi ${printPlace(phi.place)}`, suggestions: null }); phi.operands.delete(predecessor); phi.operands.set(mappedTerminal, operand); } } } } assertConsistentIdentifiers(fn); assertTerminalSuccessorsExist(fn); } } function pruneMaybeThrowsImpl(fn) { var _a; const terminalMapping = /* @__PURE__ */ new Map(); for (const [_, block] of fn.body.blocks) { const terminal = block.terminal; if (terminal.kind !== "maybe-throw") { continue; } const canThrow = block.instructions.some( (instr) => instructionMayThrow(instr) ); if (!canThrow) { const source2 = (_a = terminalMapping.get(block.id)) != null ? _a : block.id; terminalMapping.set(terminal.continuation, source2); block.terminal = { kind: "goto", block: terminal.continuation, variant: "Break" /* Break */, id: terminal.id, loc: terminal.loc }; } } return terminalMapping.size > 0 ? terminalMapping : null; } function instructionMayThrow(instr) { switch (instr.value.kind) { case "Primitive": case "ArrayExpression": case "ObjectExpression": { return false; } default: { return true; } } } // src/Optimization/InlineJsxTransform.ts function inlineJsxTransform(fn, inlineJsxTransformConfig) { var _a; const inlinedJsxDeclarations = /* @__PURE__ */ new Map(); for (const [_, currentBlock] of [...fn.body.blocks]) { let fallthroughBlockInstructions = null; const instructionCount = currentBlock.instructions.length; for (let i = 0; i < instructionCount; i++) { const instr = currentBlock.instructions[i]; if (currentBlock.kind === "value") { (_a = fn.env.logger) == null ? void 0 : _a.logEvent(fn.env.filename, { kind: "CompileDiagnostic", fnLoc: null, detail: { category: "Todo" /* Todo */, reason: "JSX Inlining is not supported on value blocks", loc: instr.loc } }); continue; } switch (instr.value.kind) { case "JsxExpression": case "JsxFragment": { const currentBlockInstructions = currentBlock.instructions.slice( 0, i ); const thenBlockInstructions = currentBlock.instructions.slice( i, i + 1 ); const elseBlockInstructions = []; fallthroughBlockInstructions != null ? fallthroughBlockInstructions : fallthroughBlockInstructions = currentBlock.instructions.slice( i + 1 ); const fallthroughBlockId = fn.env.nextBlockId; const fallthroughBlock = { kind: currentBlock.kind, id: fallthroughBlockId, instructions: fallthroughBlockInstructions, terminal: currentBlock.terminal, preds: /* @__PURE__ */ new Set(), phis: /* @__PURE__ */ new Set() }; const varPlace = createTemporaryPlace(fn.env, instr.value.loc); promoteTemporary(varPlace.identifier); const varLValuePlace = createTemporaryPlace(fn.env, instr.value.loc); const thenVarPlace = __spreadProps(__spreadValues({}, varPlace), { identifier: forkTemporaryIdentifier( fn.env.nextIdentifierId, varPlace.identifier ) }); const elseVarPlace = __spreadProps(__spreadValues({}, varPlace), { identifier: forkTemporaryIdentifier( fn.env.nextIdentifierId, varPlace.identifier ) }); const varInstruction = { id: makeInstructionId(0), lvalue: __spreadValues({}, varLValuePlace), value: { kind: "DeclareLocal", lvalue: { place: __spreadValues({}, varPlace), kind: "Let" /* Let */ }, type: null, loc: instr.value.loc }, effects: null, loc: instr.loc }; currentBlockInstructions.push(varInstruction); const devGlobalPlace = createTemporaryPlace(fn.env, instr.value.loc); const devGlobalInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, devGlobalPlace), { effect: "mutate" /* Mutate */ }), value: { kind: "LoadGlobal", binding: { kind: "Global", name: inlineJsxTransformConfig.globalDevVar }, loc: instr.value.loc }, effects: null, loc: instr.loc }; currentBlockInstructions.push(devGlobalInstruction); const thenBlockId = fn.env.nextBlockId; const elseBlockId = fn.env.nextBlockId; const ifTerminal = { kind: "if", test: __spreadProps(__spreadValues({}, devGlobalPlace), { effect: "read" /* Read */ }), consequent: thenBlockId, alternate: elseBlockId, fallthrough: fallthroughBlockId, loc: instr.loc, id: makeInstructionId(0) }; currentBlock.instructions = currentBlockInstructions; currentBlock.terminal = ifTerminal; const thenBlock = { id: thenBlockId, instructions: thenBlockInstructions, kind: "block", phis: /* @__PURE__ */ new Set(), preds: /* @__PURE__ */ new Set(), terminal: { kind: "goto", block: fallthroughBlockId, variant: "Break" /* Break */, id: makeInstructionId(0), loc: instr.loc } }; fn.body.blocks.set(thenBlockId, thenBlock); const resassignElsePlace = createTemporaryPlace( fn.env, instr.value.loc ); const reassignElseInstruction = { id: makeInstructionId(0), lvalue: __spreadValues({}, resassignElsePlace), value: { kind: "StoreLocal", lvalue: { place: elseVarPlace, kind: "Reassign" /* Reassign */ }, value: __spreadValues({}, instr.lvalue), type: null, loc: instr.value.loc }, effects: null, loc: instr.loc }; thenBlockInstructions.push(reassignElseInstruction); const elseBlockTerminal = { kind: "goto", block: fallthroughBlockId, variant: "Break" /* Break */, id: makeInstructionId(0), loc: instr.loc }; const elseBlock = { id: elseBlockId, instructions: elseBlockInstructions, kind: "block", phis: /* @__PURE__ */ new Set(), preds: /* @__PURE__ */ new Set(), terminal: elseBlockTerminal }; fn.body.blocks.set(elseBlockId, elseBlock); const { refProperty, keyProperty, propsProperty } = createPropsProperties( fn, instr, elseBlockInstructions, instr.value.kind === "JsxExpression" ? instr.value.props : [], instr.value.children ); const reactElementInstructionPlace = createTemporaryPlace( fn.env, instr.value.loc ); const reactElementInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, reactElementInstructionPlace), { effect: "store" /* Store */ }), value: { kind: "ObjectExpression", properties: [ createSymbolProperty( fn, instr, elseBlockInstructions, "$$typeof", inlineJsxTransformConfig.elementSymbol ), instr.value.kind === "JsxExpression" ? createTagProperty( fn, instr, elseBlockInstructions, instr.value.tag ) : createSymbolProperty( fn, instr, elseBlockInstructions, "type", "react.fragment" ), refProperty, keyProperty, propsProperty ], loc: instr.value.loc }, effects: null, loc: instr.loc }; elseBlockInstructions.push(reactElementInstruction); const reassignConditionalInstruction = { id: makeInstructionId(0), lvalue: __spreadValues({}, createTemporaryPlace(fn.env, instr.value.loc)), value: { kind: "StoreLocal", lvalue: { place: __spreadValues({}, elseVarPlace), kind: "Reassign" /* Reassign */ }, value: __spreadValues({}, reactElementInstruction.lvalue), type: null, loc: instr.value.loc }, effects: null, loc: instr.loc }; elseBlockInstructions.push(reassignConditionalInstruction); const operands = /* @__PURE__ */ new Map(); operands.set(thenBlockId, __spreadValues({}, elseVarPlace)); operands.set(elseBlockId, __spreadValues({}, thenVarPlace)); const phiIdentifier = forkTemporaryIdentifier( fn.env.nextIdentifierId, varPlace.identifier ); const phiPlace = __spreadProps(__spreadValues({}, createTemporaryPlace(fn.env, instr.value.loc)), { identifier: phiIdentifier }); const phis = /* @__PURE__ */ new Set([ { kind: "Phi", operands, place: phiPlace } ]); fallthroughBlock.phis = phis; fn.body.blocks.set(fallthroughBlockId, fallthroughBlock); inlinedJsxDeclarations.set(instr.lvalue.identifier.declarationId, { identifier: phiIdentifier, blockIdsToIgnore: /* @__PURE__ */ new Set([thenBlockId, elseBlockId]) }); break; } case "FunctionExpression": case "ObjectMethod": { inlineJsxTransform( instr.value.loweredFunc.func, inlineJsxTransformConfig ); break; } } } } for (const [blockId, block] of fn.body.blocks) { for (const instr of block.instructions) { mapInstructionOperands( instr, (place) => handlePlace(place, blockId, inlinedJsxDeclarations) ); mapInstructionLValues( instr, (lvalue) => handlelValue(lvalue, blockId, inlinedJsxDeclarations) ); mapInstructionValueOperands( instr.value, (place) => handlePlace(place, blockId, inlinedJsxDeclarations) ); } mapTerminalOperands( block.terminal, (place) => handlePlace(place, blockId, inlinedJsxDeclarations) ); if (block.terminal.kind === "scope") { const scope = block.terminal.scope; for (const dep of scope.dependencies) { dep.identifier = handleIdentifier2( dep.identifier, inlinedJsxDeclarations ); } for (const [origId, decl] of [...scope.declarations]) { const newDecl = handleIdentifier2( decl.identifier, inlinedJsxDeclarations ); if (newDecl.id !== origId) { scope.declarations.delete(origId); scope.declarations.set(decl.identifier.id, { identifier: newDecl, scope: decl.scope }); } } } } reversePostorderBlocks(fn.body); markPredecessors(fn.body); markInstructionIds(fn.body); fixScopeAndIdentifierRanges(fn.body); } function createSymbolProperty(fn, instr, nextInstructions, propertyName, symbolName) { const symbolPlace = createTemporaryPlace(fn.env, instr.value.loc); const symbolInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, symbolPlace), { effect: "mutate" /* Mutate */ }), value: { kind: "LoadGlobal", binding: { kind: "Global", name: "Symbol" }, loc: instr.value.loc }, effects: null, loc: instr.loc }; nextInstructions.push(symbolInstruction); const symbolForPlace = createTemporaryPlace(fn.env, instr.value.loc); const symbolForInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, symbolForPlace), { effect: "read" /* Read */ }), value: { kind: "PropertyLoad", object: __spreadValues({}, symbolInstruction.lvalue), property: makePropertyLiteral("for"), loc: instr.value.loc }, effects: null, loc: instr.loc }; nextInstructions.push(symbolForInstruction); const symbolValuePlace = createTemporaryPlace(fn.env, instr.value.loc); const symbolValueInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, symbolValuePlace), { effect: "mutate" /* Mutate */ }), value: { kind: "Primitive", value: symbolName, loc: instr.value.loc }, effects: null, loc: instr.loc }; nextInstructions.push(symbolValueInstruction); const $$typeofPlace = createTemporaryPlace(fn.env, instr.value.loc); const $$typeofInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, $$typeofPlace), { effect: "mutate" /* Mutate */ }), value: { kind: "MethodCall", receiver: symbolInstruction.lvalue, property: symbolForInstruction.lvalue, args: [symbolValueInstruction.lvalue], loc: instr.value.loc }, effects: null, loc: instr.loc }; const $$typeofProperty = { kind: "ObjectProperty", key: { name: propertyName, kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, $$typeofPlace), { effect: "capture" /* Capture */ }) }; nextInstructions.push($$typeofInstruction); return $$typeofProperty; } function createTagProperty(fn, instr, nextInstructions, componentTag) { let tagProperty; switch (componentTag.kind) { case "BuiltinTag": { const tagPropertyPlace = createTemporaryPlace(fn.env, instr.value.loc); const tagInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, tagPropertyPlace), { effect: "mutate" /* Mutate */ }), value: { kind: "Primitive", value: componentTag.name, loc: instr.value.loc }, effects: null, loc: instr.loc }; tagProperty = { kind: "ObjectProperty", key: { name: "type", kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, tagPropertyPlace), { effect: "capture" /* Capture */ }) }; nextInstructions.push(tagInstruction); break; } case "Identifier": { tagProperty = { kind: "ObjectProperty", key: { name: "type", kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, componentTag), { effect: "capture" /* Capture */ }) }; break; } } return tagProperty; } function createPropsProperties(fn, instr, nextInstructions, propAttributes, children) { let refProperty; let keyProperty; const props = []; const jsxAttributesWithoutKey = propAttributes.filter( (p) => p.kind === "JsxAttribute" && p.name !== "key" ); const jsxSpreadAttributes = propAttributes.filter( (p) => p.kind === "JsxSpreadAttribute" ); const spreadPropsOnly = jsxAttributesWithoutKey.length === 0 && jsxSpreadAttributes.length === 1; propAttributes.forEach((prop) => { switch (prop.kind) { case "JsxAttribute": { switch (prop.name) { case "key": { keyProperty = { kind: "ObjectProperty", key: { name: "key", kind: "string" }, type: "property", place: __spreadValues({}, prop.place) }; break; } case "ref": { refProperty = { kind: "ObjectProperty", key: { name: "ref", kind: "string" }, type: "property", place: __spreadValues({}, prop.place) }; const refPropProperty = { kind: "ObjectProperty", key: { name: "ref", kind: "string" }, type: "property", place: __spreadValues({}, prop.place) }; props.push(refPropProperty); break; } default: { const attributeProperty = { kind: "ObjectProperty", key: { name: prop.name, kind: "string" }, type: "property", place: __spreadValues({}, prop.place) }; props.push(attributeProperty); } } break; } case "JsxSpreadAttribute": { props.push({ kind: "Spread", place: __spreadValues({}, prop.argument) }); break; } } }); const propsPropertyPlace = createTemporaryPlace(fn.env, instr.value.loc); if (children) { let childrenPropProperty; if (children.length === 1) { childrenPropProperty = { kind: "ObjectProperty", key: { name: "children", kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, children[0]), { effect: "capture" /* Capture */ }) }; } else { const childrenPropPropertyPlace = createTemporaryPlace( fn.env, instr.value.loc ); const childrenPropInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, childrenPropPropertyPlace), { effect: "mutate" /* Mutate */ }), value: { kind: "ArrayExpression", elements: [...children], loc: instr.value.loc }, effects: null, loc: instr.loc }; nextInstructions.push(childrenPropInstruction); childrenPropProperty = { kind: "ObjectProperty", key: { name: "children", kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, childrenPropPropertyPlace), { effect: "capture" /* Capture */ }) }; } props.push(childrenPropProperty); } if (refProperty == null) { const refPropertyPlace = createTemporaryPlace(fn.env, instr.value.loc); const refInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, refPropertyPlace), { effect: "mutate" /* Mutate */ }), value: { kind: "Primitive", value: null, loc: instr.value.loc }, effects: null, loc: instr.loc }; refProperty = { kind: "ObjectProperty", key: { name: "ref", kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, refPropertyPlace), { effect: "capture" /* Capture */ }) }; nextInstructions.push(refInstruction); } if (keyProperty == null) { const keyPropertyPlace = createTemporaryPlace(fn.env, instr.value.loc); const keyInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, keyPropertyPlace), { effect: "mutate" /* Mutate */ }), value: { kind: "Primitive", value: null, loc: instr.value.loc }, effects: null, loc: instr.loc }; keyProperty = { kind: "ObjectProperty", key: { name: "key", kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, keyPropertyPlace), { effect: "capture" /* Capture */ }) }; nextInstructions.push(keyInstruction); } let propsProperty; if (spreadPropsOnly) { const spreadProp = jsxSpreadAttributes[0]; CompilerError.invariant(spreadProp.kind === "JsxSpreadAttribute", { reason: "Spread prop attribute must be of kind JSXSpreadAttribute", description: null, details: [ { kind: "error", loc: instr.loc, message: null } ] }); propsProperty = { kind: "ObjectProperty", key: { name: "props", kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, spreadProp.argument), { effect: "mutate" /* Mutate */ }) }; } else { const propsInstruction = { id: makeInstructionId(0), lvalue: __spreadProps(__spreadValues({}, propsPropertyPlace), { effect: "mutate" /* Mutate */ }), value: { kind: "ObjectExpression", properties: props, loc: instr.value.loc }, effects: null, loc: instr.loc }; propsProperty = { kind: "ObjectProperty", key: { name: "props", kind: "string" }, type: "property", place: __spreadProps(__spreadValues({}, propsPropertyPlace), { effect: "capture" /* Capture */ }) }; nextInstructions.push(propsInstruction); } return { refProperty, keyProperty, propsProperty }; } function handlePlace(place, blockId, inlinedJsxDeclarations) { const inlinedJsxDeclaration = inlinedJsxDeclarations.get( place.identifier.declarationId ); if (inlinedJsxDeclaration == null || inlinedJsxDeclaration.blockIdsToIgnore.has(blockId)) { return place; } return __spreadProps(__spreadValues({}, place), { identifier: inlinedJsxDeclaration.identifier }); } function handlelValue(lvalue, blockId, inlinedJsxDeclarations) { const inlinedJsxDeclaration = inlinedJsxDeclarations.get( lvalue.identifier.declarationId ); if (inlinedJsxDeclaration == null || inlinedJsxDeclaration.blockIdsToIgnore.has(blockId)) { return lvalue; } return __spreadProps(__spreadValues({}, lvalue), { identifier: inlinedJsxDeclaration.identifier }); } function handleIdentifier2(identifier4, inlinedJsxDeclarations) { const inlinedJsxDeclaration = inlinedJsxDeclarations.get( identifier4.declarationId ); return inlinedJsxDeclaration == null ? identifier4 : inlinedJsxDeclaration.identifier; } // src/ReactiveScopes/AlignObjectMethodScopes.ts function findScopesToMerge(fn) { const objectMethodDecls = /* @__PURE__ */ new Set(); const mergeScopesBuilder = new DisjointSet(); for (const [_, block] of fn.body.blocks) { for (const { lvalue, value } of block.instructions) { if (value.kind === "ObjectMethod") { objectMethodDecls.add(lvalue.identifier); } else if (value.kind === "ObjectExpression") { for (const operand of eachInstructionValueOperand(value)) { if (objectMethodDecls.has(operand.identifier)) { const operandScope = operand.identifier.scope; const lvalueScope = lvalue.identifier.scope; CompilerError.invariant( operandScope != null && lvalueScope != null, { reason: "Internal error: Expected all ObjectExpressions and ObjectMethods to have non-null scope.", description: null, suggestions: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] } ); mergeScopesBuilder.union([operandScope, lvalueScope]); } } } } } return mergeScopesBuilder; } function alignObjectMethodScopes(fn) { for (const [_, block] of fn.body.blocks) { for (const { value } of block.instructions) { if (value.kind === "ObjectMethod" || value.kind === "FunctionExpression") { alignObjectMethodScopes(value.loweredFunc.func); } } } const scopeGroupsMap = findScopesToMerge(fn).canonicalize(); for (const [scope, root2] of scopeGroupsMap) { if (scope !== root2) { root2.range.start = makeInstructionId( Math.min(scope.range.start, root2.range.start) ); root2.range.end = makeInstructionId( Math.max(scope.range.end, root2.range.end) ); } } for (const [_, block] of fn.body.blocks) { for (const { lvalue: { identifier: identifier4 } } of block.instructions) { if (identifier4.scope != null) { const root2 = scopeGroupsMap.get(identifier4.scope); if (root2 != null) { identifier4.scope = root2; } } } } } // src/ReactiveScopes/visitors.ts function visitReactiveFunction(fn, visitor, state) { visitor.visitBlock(fn.body, state); } var ReactiveFunctionVisitor = class { visitID(_id, _state) { } visitParam(_place, _state) { } visitLValue(_id, _lvalue, _state) { } visitPlace(_id, _place, _state) { } visitReactiveFunctionValue(_id, _dependencies2, _fn, _state) { } visitValue(id, value, state) { this.traverseValue(id, value, state); } traverseValue(id, value, state) { switch (value.kind) { case "OptionalExpression": { this.visitValue(id, value.value, state); break; } case "LogicalExpression": { this.visitValue(id, value.left, state); this.visitValue(id, value.right, state); break; } case "ConditionalExpression": { this.visitValue(id, value.test, state); this.visitValue(id, value.consequent, state); this.visitValue(id, value.alternate, state); break; } case "SequenceExpression": { for (const instr of value.instructions) { this.visitInstruction(instr, state); } this.visitValue(value.id, value.value, state); break; } default: { for (const place of eachInstructionValueOperand(value)) { this.visitPlace(id, place, state); } } } } visitInstruction(instruction, state) { this.traverseInstruction(instruction, state); } traverseInstruction(instruction, state) { this.visitID(instruction.id, state); for (const operand of eachInstructionLValue(instruction)) { this.visitLValue(instruction.id, operand, state); } this.visitValue(instruction.id, instruction.value, state); } visitTerminal(stmt, state) { this.traverseTerminal(stmt, state); } traverseTerminal(stmt, state) { const { terminal } = stmt; if (terminal.id !== null) { this.visitID(terminal.id, state); } switch (terminal.kind) { case "break": case "continue": { break; } case "return": { this.visitPlace(terminal.id, terminal.value, state); break; } case "throw": { this.visitPlace(terminal.id, terminal.value, state); break; } case "for": { this.visitValue(terminal.id, terminal.init, state); this.visitValue(terminal.id, terminal.test, state); this.visitBlock(terminal.loop, state); if (terminal.update !== null) { this.visitValue(terminal.id, terminal.update, state); } break; } case "for-of": { this.visitValue(terminal.id, terminal.init, state); this.visitValue(terminal.id, terminal.test, state); this.visitBlock(terminal.loop, state); break; } case "for-in": { this.visitValue(terminal.id, terminal.init, state); this.visitBlock(terminal.loop, state); break; } case "do-while": { this.visitBlock(terminal.loop, state); this.visitValue(terminal.id, terminal.test, state); break; } case "while": { this.visitValue(terminal.id, terminal.test, state); this.visitBlock(terminal.loop, state); break; } case "if": { this.visitPlace(terminal.id, terminal.test, state); this.visitBlock(terminal.consequent, state); if (terminal.alternate !== null) { this.visitBlock(terminal.alternate, state); } break; } case "switch": { this.visitPlace(terminal.id, terminal.test, state); for (const case_ of terminal.cases) { if (case_.test !== null) { this.visitPlace(terminal.id, case_.test, state); } if (case_.block !== void 0) { this.visitBlock(case_.block, state); } } break; } case "label": { this.visitBlock(terminal.block, state); break; } case "try": { this.visitBlock(terminal.block, state); this.visitBlock(terminal.handler, state); break; } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } visitScope(scope, state) { this.traverseScope(scope, state); } traverseScope(scope, state) { this.visitBlock(scope.instructions, state); } visitPrunedScope(scopeBlock, state) { this.traversePrunedScope(scopeBlock, state); } traversePrunedScope(scopeBlock, state) { this.visitBlock(scopeBlock.instructions, state); } visitBlock(block, state) { this.traverseBlock(block, state); } traverseBlock(block, state) { for (const instr of block) { switch (instr.kind) { case "instruction": { this.visitInstruction(instr.instruction, state); break; } case "scope": { this.visitScope(instr, state); break; } case "pruned-scope": { this.visitPrunedScope(instr, state); break; } case "terminal": { this.visitTerminal(instr, state); break; } default: { assertExhaustive( instr, `Unexpected instruction kind \`${instr.kind}\`` ); } } } } visitHirFunction(fn, state) { for (const param of fn.params) { const place = param.kind === "Identifier" ? param : param.place; this.visitParam(place, state); } for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { this.visitInstruction(instr, state); if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { this.visitHirFunction(instr.value.loweredFunc.func, state); } } for (const operand of eachTerminalOperand(block.terminal)) { this.visitPlace(block.terminal.id, operand, state); } } } }; var ReactiveFunctionTransform = class extends ReactiveFunctionVisitor { traverseBlock(block, state) { let nextBlock = null; for (let i = 0; i < block.length; i++) { const instr = block[i]; let transformed; switch (instr.kind) { case "instruction": { transformed = this.transformInstruction(instr.instruction, state); break; } case "scope": { transformed = this.transformScope(instr, state); break; } case "pruned-scope": { transformed = this.transformPrunedScope(instr, state); break; } case "terminal": { transformed = this.transformTerminal(instr, state); break; } default: { assertExhaustive( instr, `Unexpected instruction kind \`${instr.kind}\`` ); } } switch (transformed.kind) { case "keep": { if (nextBlock !== null) { nextBlock.push(instr); } break; } case "remove": { if (nextBlock === null) { nextBlock = block.slice(0, i); } break; } case "replace": { nextBlock != null ? nextBlock : nextBlock = block.slice(0, i); nextBlock.push(transformed.value); break; } case "replace-many": { nextBlock != null ? nextBlock : nextBlock = block.slice(0, i); nextBlock.push(...transformed.value); break; } } } if (nextBlock !== null) { block.length = 0; block.push(...nextBlock); } } transformInstruction(instruction, state) { this.visitInstruction(instruction, state); return { kind: "keep" }; } transformTerminal(stmt, state) { this.visitTerminal(stmt, state); return { kind: "keep" }; } transformScope(scope, state) { this.visitScope(scope, state); return { kind: "keep" }; } transformPrunedScope(scope, state) { this.visitPrunedScope(scope, state); return { kind: "keep" }; } transformValue(id, value, state) { this.visitValue(id, value, state); return { kind: "keep" }; } transformReactiveFunctionValue(id, dependencies, fn, state) { this.visitReactiveFunctionValue(id, dependencies, fn, state); return { kind: "keep" }; } traverseValue(id, value, state) { switch (value.kind) { case "OptionalExpression": { const nextValue = this.transformValue(id, value.value, state); if (nextValue.kind === "replace") { value.value = nextValue.value; } break; } case "LogicalExpression": { const left = this.transformValue(id, value.left, state); if (left.kind === "replace") { value.left = left.value; } const right = this.transformValue(id, value.right, state); if (right.kind === "replace") { value.right = right.value; } break; } case "ConditionalExpression": { const test = this.transformValue(id, value.test, state); if (test.kind === "replace") { value.test = test.value; } const consequent = this.transformValue(id, value.consequent, state); if (consequent.kind === "replace") { value.consequent = consequent.value; } const alternate = this.transformValue(id, value.alternate, state); if (alternate.kind === "replace") { value.alternate = alternate.value; } break; } case "SequenceExpression": { for (const instr of value.instructions) { this.visitInstruction(instr, state); } const nextValue = this.transformValue(value.id, value.value, state); if (nextValue.kind === "replace") { value.value = nextValue.value; } break; } default: { for (const place of eachInstructionValueOperand(value)) { this.visitPlace(id, place, state); } } } } traverseInstruction(instruction, state) { this.visitID(instruction.id, state); for (const operand of eachInstructionLValue(instruction)) { this.visitLValue(instruction.id, operand, state); } const nextValue = this.transformValue( instruction.id, instruction.value, state ); if (nextValue.kind === "replace") { instruction.value = nextValue.value; } } traverseTerminal(stmt, state) { const { terminal } = stmt; if (terminal.id !== null) { this.visitID(terminal.id, state); } switch (terminal.kind) { case "break": case "continue": { break; } case "return": { this.visitPlace(terminal.id, terminal.value, state); break; } case "throw": { this.visitPlace(terminal.id, terminal.value, state); break; } case "for": { const init = this.transformValue(terminal.id, terminal.init, state); if (init.kind === "replace") { terminal.init = init.value; } const test = this.transformValue(terminal.id, terminal.test, state); if (test.kind === "replace") { terminal.test = test.value; } if (terminal.update !== null) { const update2 = this.transformValue( terminal.id, terminal.update, state ); if (update2.kind === "replace") { terminal.update = update2.value; } } this.visitBlock(terminal.loop, state); break; } case "for-of": { const init = this.transformValue(terminal.id, terminal.init, state); if (init.kind === "replace") { terminal.init = init.value; } const test = this.transformValue(terminal.id, terminal.test, state); if (test.kind === "replace") { terminal.test = test.value; } this.visitBlock(terminal.loop, state); break; } case "for-in": { const init = this.transformValue(terminal.id, terminal.init, state); if (init.kind === "replace") { terminal.init = init.value; } this.visitBlock(terminal.loop, state); break; } case "do-while": { this.visitBlock(terminal.loop, state); const test = this.transformValue(terminal.id, terminal.test, state); if (test.kind === "replace") { terminal.test = test.value; } break; } case "while": { const test = this.transformValue(terminal.id, terminal.test, state); if (test.kind === "replace") { terminal.test = test.value; } this.visitBlock(terminal.loop, state); break; } case "if": { this.visitPlace(terminal.id, terminal.test, state); this.visitBlock(terminal.consequent, state); if (terminal.alternate !== null) { this.visitBlock(terminal.alternate, state); } break; } case "switch": { this.visitPlace(terminal.id, terminal.test, state); for (const case_ of terminal.cases) { if (case_.test !== null) { this.visitPlace(terminal.id, case_.test, state); } if (case_.block !== void 0) { this.visitBlock(case_.block, state); } } break; } case "label": { this.visitBlock(terminal.block, state); break; } case "try": { this.visitBlock(terminal.block, state); if (terminal.handlerBinding !== null) { this.visitPlace(terminal.id, terminal.handlerBinding, state); } this.visitBlock(terminal.handler, state); break; } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } }; function* eachReactiveValueOperand(instrValue) { switch (instrValue.kind) { case "OptionalExpression": { yield* __yieldStar(eachReactiveValueOperand(instrValue.value)); break; } case "LogicalExpression": { yield* __yieldStar(eachReactiveValueOperand(instrValue.left)); yield* __yieldStar(eachReactiveValueOperand(instrValue.right)); break; } case "SequenceExpression": { for (const instr of instrValue.instructions) { yield* __yieldStar(eachReactiveValueOperand(instr.value)); } yield* __yieldStar(eachReactiveValueOperand(instrValue.value)); break; } case "ConditionalExpression": { yield* __yieldStar(eachReactiveValueOperand(instrValue.test)); yield* __yieldStar(eachReactiveValueOperand(instrValue.consequent)); yield* __yieldStar(eachReactiveValueOperand(instrValue.alternate)); break; } default: { yield* __yieldStar(eachInstructionValueOperand(instrValue)); } } } // src/ReactiveScopes/AssertScopeInstructionsWithinScope.ts function assertScopeInstructionsWithinScopes(fn) { const existingScopes = /* @__PURE__ */ new Set(); visitReactiveFunction(fn, new FindAllScopesVisitor(), existingScopes); visitReactiveFunction( fn, new CheckInstructionsAgainstScopesVisitor(), existingScopes ); } var FindAllScopesVisitor = class extends ReactiveFunctionVisitor { visitScope(block, state) { this.traverseScope(block, state); state.add(block.scope.id); } }; var CheckInstructionsAgainstScopesVisitor = class extends ReactiveFunctionVisitor { constructor() { super(...arguments); this.activeScopes = /* @__PURE__ */ new Set(); } visitPlace(id, place, state) { const scope = getPlaceScope(id, place); if (scope !== null && // is there a scope for this at all, or did we end up pruning this scope? state.has(scope.id) && /* * if the scope exists somewhere, it must be active or else this is a straggler * instruction */ !this.activeScopes.has(scope.id)) { CompilerError.invariant(false, { reason: "Encountered an instruction that should be part of a scope, but where that scope has already completed", description: `Instruction [${id}] is part of scope @${scope.id}, but that scope has already completed`, details: [ { kind: "error", loc: place.loc, message: null } ], suggestions: null }); } } visitScope(block, state) { this.activeScopes.add(block.scope.id); this.traverseScope(block, state); this.activeScopes.delete(block.scope.id); } }; // src/ReactiveScopes/AssertWellFormedBreakTargets.ts function assertWellFormedBreakTargets(fn) { visitReactiveFunction(fn, new Visitor(), /* @__PURE__ */ new Set()); } var Visitor = class extends ReactiveFunctionVisitor { visitTerminal(stmt, seenLabels) { if (stmt.label != null) { seenLabels.add(stmt.label.id); } const terminal = stmt.terminal; if (terminal.kind === "break" || terminal.kind === "continue") { CompilerError.invariant(seenLabels.has(terminal.target), { reason: "Unexpected break to invalid label", description: null, details: [ { kind: "error", loc: stmt.terminal.loc, message: null } ] }); } } }; // src/ReactiveScopes/BuildReactiveFunction.ts function buildReactiveFunction(fn) { const cx = new Context(fn.body); const driver = new Driver(cx); const body = driver.traverseBlock(cx.block(fn.body.entry)); return { loc: fn.loc, id: fn.id, nameHint: fn.nameHint, params: fn.params, generator: fn.generator, async: fn.async, body, env: fn.env, directives: fn.directives }; } var Driver = class { constructor(cx) { this.cx = cx; } traverseBlock(block) { const blockValue = []; this.visitBlock(block, blockValue); return blockValue; } visitBlock(block, blockValue) { var _a; CompilerError.invariant(!this.cx.emitted.has(block.id), { reason: `Cannot emit the same block twice: bb${block.id}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); this.cx.emitted.add(block.id); for (const instruction of block.instructions) { blockValue.push({ kind: "instruction", instruction }); } const terminal = block.terminal; const scheduleIds = []; switch (terminal.kind) { case "return": { blockValue.push({ kind: "terminal", terminal: { kind: "return", loc: terminal.loc, value: terminal.value, id: terminal.id }, label: null }); break; } case "throw": { blockValue.push({ kind: "terminal", terminal: { kind: "throw", loc: terminal.loc, value: terminal.value, id: terminal.id }, label: null }); break; } case "if": { const fallthroughId = this.cx.reachable(terminal.fallthrough) && !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; const alternateId = terminal.alternate !== terminal.fallthrough ? terminal.alternate : null; if (fallthroughId !== null) { const scheduleId = this.cx.schedule(fallthroughId, "if"); scheduleIds.push(scheduleId); } let consequent = null; if (this.cx.isScheduled(terminal.consequent)) { CompilerError.invariant(false, { reason: `Unexpected 'if' where the consequent is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } else { consequent = this.traverseBlock( this.cx.ir.blocks.get(terminal.consequent) ); } let alternate = null; if (alternateId !== null) { if (this.cx.isScheduled(alternateId)) { CompilerError.invariant(false, { reason: `Unexpected 'if' where the alternate is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } else { alternate = this.traverseBlock(this.cx.ir.blocks.get(alternateId)); } } this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", terminal: { kind: "if", loc: terminal.loc, test: terminal.test, consequent: consequent != null ? consequent : this.emptyBlock(), alternate, id: terminal.id }, label: fallthroughId == null ? null : { id: fallthroughId, implicit: false } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "switch": { const fallthroughId = this.cx.reachable(terminal.fallthrough) && !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; if (fallthroughId !== null) { const scheduleId = this.cx.schedule(fallthroughId, "switch"); scheduleIds.push(scheduleId); } const cases = []; [...terminal.cases].reverse().forEach((case_, _index) => { const test = case_.test; let consequent; if (this.cx.isScheduled(case_.block)) { CompilerError.invariant(case_.block === terminal.fallthrough, { reason: `Unexpected 'switch' where a case is already scheduled and block is not the fallthrough`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); return; } else { consequent = this.traverseBlock( this.cx.ir.blocks.get(case_.block) ); const scheduleId = this.cx.schedule(case_.block, "case"); scheduleIds.push(scheduleId); } cases.push({ test, block: consequent }); }); cases.reverse(); this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", terminal: { kind: "switch", loc: terminal.loc, test: terminal.test, cases, id: terminal.id }, label: fallthroughId == null ? null : { id: fallthroughId, implicit: false } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "do-while": { const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; const loopId = !this.cx.isScheduled(terminal.loop) && terminal.loop !== terminal.fallthrough ? terminal.loop : null; const scheduleId = this.cx.scheduleLoop( terminal.fallthrough, terminal.test, terminal.loop ); scheduleIds.push(scheduleId); let loopBody; if (loopId) { loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); } else { CompilerError.invariant(false, { reason: `Unexpected 'do-while' where the loop is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } const testValue = this.visitValueBlock( terminal.test, terminal.loc ).value; this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", terminal: { kind: "do-while", loc: terminal.loc, test: testValue, loop: loopBody, id: terminal.id }, label: fallthroughId == null ? null : { id: fallthroughId, implicit: false } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "while": { const fallthroughId = this.cx.reachable(terminal.fallthrough) && !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; const loopId = !this.cx.isScheduled(terminal.loop) && terminal.loop !== terminal.fallthrough ? terminal.loop : null; const scheduleId = this.cx.scheduleLoop( terminal.fallthrough, terminal.test, terminal.loop ); scheduleIds.push(scheduleId); const testValue = this.visitValueBlock( terminal.test, terminal.loc ).value; let loopBody; if (loopId) { loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); } else { CompilerError.invariant(false, { reason: `Unexpected 'while' where the loop is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", terminal: { kind: "while", loc: terminal.loc, test: testValue, loop: loopBody, id: terminal.id }, label: fallthroughId == null ? null : { id: fallthroughId, implicit: false } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "for": { const loopId = !this.cx.isScheduled(terminal.loop) && terminal.loop !== terminal.fallthrough ? terminal.loop : null; const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; const scheduleId = this.cx.scheduleLoop( terminal.fallthrough, (_a = terminal.update) != null ? _a : terminal.test, terminal.loop ); scheduleIds.push(scheduleId); const init = this.visitValueBlock(terminal.init, terminal.loc); const initBlock = this.cx.ir.blocks.get(init.block); let initValue = init.value; if (initValue.kind === "SequenceExpression") { const last = initBlock.instructions.at(-1); initValue.instructions.push(last); initValue.value = { kind: "Primitive", value: void 0, loc: terminal.loc }; } else { initValue = { kind: "SequenceExpression", instructions: [initBlock.instructions.at(-1)], id: terminal.id, loc: terminal.loc, value: { kind: "Primitive", value: void 0, loc: terminal.loc } }; } const testValue = this.visitValueBlock( terminal.test, terminal.loc ).value; const updateValue = terminal.update !== null ? this.visitValueBlock(terminal.update, terminal.loc).value : null; let loopBody; if (loopId) { loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); } else { CompilerError.invariant(false, { reason: `Unexpected 'for' where the loop is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", terminal: { kind: "for", loc: terminal.loc, init: initValue, test: testValue, update: updateValue, loop: loopBody, id: terminal.id }, label: fallthroughId == null ? null : { id: fallthroughId, implicit: false } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "for-of": { const loopId = !this.cx.isScheduled(terminal.loop) && terminal.loop !== terminal.fallthrough ? terminal.loop : null; const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; const scheduleId = this.cx.scheduleLoop( terminal.fallthrough, terminal.init, terminal.loop ); scheduleIds.push(scheduleId); const init = this.visitValueBlock(terminal.init, terminal.loc); const initBlock = this.cx.ir.blocks.get(init.block); let initValue = init.value; if (initValue.kind === "SequenceExpression") { const last = initBlock.instructions.at(-1); initValue.instructions.push(last); initValue.value = { kind: "Primitive", value: void 0, loc: terminal.loc }; } else { initValue = { kind: "SequenceExpression", instructions: [initBlock.instructions.at(-1)], id: terminal.id, loc: terminal.loc, value: { kind: "Primitive", value: void 0, loc: terminal.loc } }; } const test = this.visitValueBlock(terminal.test, terminal.loc); const testBlock = this.cx.ir.blocks.get(test.block); let testValue = test.value; if (testValue.kind === "SequenceExpression") { const last = testBlock.instructions.at(-1); testValue.instructions.push(last); testValue.value = { kind: "Primitive", value: void 0, loc: terminal.loc }; } else { testValue = { kind: "SequenceExpression", instructions: [testBlock.instructions.at(-1)], id: terminal.id, loc: terminal.loc, value: { kind: "Primitive", value: void 0, loc: terminal.loc } }; } let loopBody; if (loopId) { loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); } else { CompilerError.invariant(false, { reason: `Unexpected 'for-of' where the loop is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", terminal: { kind: "for-of", loc: terminal.loc, init: initValue, test: testValue, loop: loopBody, id: terminal.id }, label: fallthroughId == null ? null : { id: fallthroughId, implicit: false } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "for-in": { const loopId = !this.cx.isScheduled(terminal.loop) && terminal.loop !== terminal.fallthrough ? terminal.loop : null; const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; const scheduleId = this.cx.scheduleLoop( terminal.fallthrough, terminal.init, terminal.loop ); scheduleIds.push(scheduleId); const init = this.visitValueBlock(terminal.init, terminal.loc); const initBlock = this.cx.ir.blocks.get(init.block); let initValue = init.value; if (initValue.kind === "SequenceExpression") { const last = initBlock.instructions.at(-1); initValue.instructions.push(last); initValue.value = { kind: "Primitive", value: void 0, loc: terminal.loc }; } else { initValue = { kind: "SequenceExpression", instructions: [initBlock.instructions.at(-1)], id: terminal.id, loc: terminal.loc, value: { kind: "Primitive", value: void 0, loc: terminal.loc } }; } let loopBody; if (loopId) { loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); } else { CompilerError.invariant(false, { reason: `Unexpected 'for-in' where the loop is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", terminal: { kind: "for-in", loc: terminal.loc, init: initValue, loop: loopBody, id: terminal.id }, label: fallthroughId == null ? null : { id: fallthroughId, implicit: false } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "branch": { let consequent = null; if (this.cx.isScheduled(terminal.consequent)) { const break_ = this.visitBreak( terminal.consequent, terminal.id, terminal.loc ); if (break_ !== null) { consequent = [break_]; } } else { consequent = this.traverseBlock( this.cx.ir.blocks.get(terminal.consequent) ); } let alternate = null; if (this.cx.isScheduled(terminal.alternate)) { CompilerError.invariant(false, { reason: `Unexpected 'branch' where the alternate is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } else { alternate = this.traverseBlock( this.cx.ir.blocks.get(terminal.alternate) ); } blockValue.push({ kind: "terminal", terminal: { kind: "if", loc: terminal.loc, test: terminal.test, consequent: consequent != null ? consequent : this.emptyBlock(), alternate, id: terminal.id }, label: null }); break; } case "label": { const fallthroughId = this.cx.reachable(terminal.fallthrough) && !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; if (fallthroughId !== null) { const scheduleId = this.cx.schedule(fallthroughId, "if"); scheduleIds.push(scheduleId); } let block2; if (this.cx.isScheduled(terminal.block)) { CompilerError.invariant(false, { reason: `Unexpected 'label' where the block is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } else { block2 = this.traverseBlock(this.cx.ir.blocks.get(terminal.block)); } this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", terminal: { kind: "label", loc: terminal.loc, block: block2, id: terminal.id }, label: fallthroughId == null ? null : { id: fallthroughId, implicit: false } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "sequence": case "optional": case "ternary": case "logical": { const fallthroughId = terminal.fallthrough !== null && !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; if (fallthroughId !== null) { const scheduleId = this.cx.schedule(fallthroughId, "if"); scheduleIds.push(scheduleId); } const { place, value } = this.visitValueBlockTerminal(terminal); this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "instruction", instruction: { id: terminal.id, lvalue: place, value, loc: terminal.loc } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "goto": { switch (terminal.variant) { case "Break" /* Break */: { const break_ = this.visitBreak( terminal.block, terminal.id, terminal.loc ); if (break_ !== null) { blockValue.push(break_); } break; } case "Continue" /* Continue */: { const continue_ = this.visitContinue( terminal.block, terminal.id, terminal.loc ); if (continue_ !== null) { blockValue.push(continue_); } break; } case "Try" /* Try */: { break; } default: { assertExhaustive( terminal.variant, `Unexpected goto variant \`${terminal.variant}\`` ); } } break; } case "maybe-throw": { if (!this.cx.isScheduled(terminal.continuation)) { this.visitBlock( this.cx.ir.blocks.get(terminal.continuation), blockValue ); } break; } case "try": { const fallthroughId = this.cx.reachable(terminal.fallthrough) && !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; if (fallthroughId !== null) { const scheduleId = this.cx.schedule(fallthroughId, "if"); scheduleIds.push(scheduleId); } this.cx.scheduleCatchHandler(terminal.handler); const block2 = this.traverseBlock( this.cx.ir.blocks.get(terminal.block) ); const handler = this.traverseBlock( this.cx.ir.blocks.get(terminal.handler) ); this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: "terminal", label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, terminal: { kind: "try", loc: terminal.loc, block: block2, handlerBinding: terminal.handlerBinding, handler, id: terminal.id } }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "pruned-scope": case "scope": { const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) ? terminal.fallthrough : null; if (fallthroughId !== null) { const scheduleId = this.cx.schedule(fallthroughId, "if"); scheduleIds.push(scheduleId); this.cx.scopeFallthroughs.add(fallthroughId); } let block2; if (this.cx.isScheduled(terminal.block)) { CompilerError.invariant(false, { reason: `Unexpected 'scope' where the block is already scheduled`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); } else { block2 = this.traverseBlock(this.cx.ir.blocks.get(terminal.block)); } this.cx.unscheduleAll(scheduleIds); blockValue.push({ kind: terminal.kind, instructions: block2, scope: terminal.scope }); if (fallthroughId !== null) { this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); } break; } case "unreachable": { break; } case "unsupported": { CompilerError.invariant(false, { reason: "Unexpected unsupported terminal", description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ], suggestions: null }); } default: { assertExhaustive(terminal, "Unexpected terminal"); } } } visitValueBlock(id, loc) { const defaultBlock = this.cx.ir.blocks.get(id); if (defaultBlock.terminal.kind === "branch") { const instructions = defaultBlock.instructions; if (instructions.length === 0) { return { block: defaultBlock.id, place: defaultBlock.terminal.test, value: { kind: "LoadLocal", place: defaultBlock.terminal.test, loc: defaultBlock.terminal.test.loc }, id: defaultBlock.terminal.id }; } else if (defaultBlock.instructions.length === 1) { const instr = defaultBlock.instructions[0]; CompilerError.invariant( instr.lvalue.identifier.id === defaultBlock.terminal.test.identifier.id, { reason: "Expected branch block to end in an instruction that sets the test value", description: null, details: [ { kind: "error", loc: instr.lvalue.loc, message: null } ], suggestions: null } ); return { block: defaultBlock.id, place: instr.lvalue, value: instr.value, id: instr.id }; } else { const instr = defaultBlock.instructions.at(-1); const sequence = { kind: "SequenceExpression", instructions: defaultBlock.instructions.slice(0, -1), id: instr.id, value: instr.value, loc }; return { block: defaultBlock.id, place: defaultBlock.terminal.test, value: sequence, id: defaultBlock.terminal.id }; } } else if (defaultBlock.terminal.kind === "goto") { const instructions = defaultBlock.instructions; if (instructions.length === 0) { CompilerError.invariant(false, { reason: "Expected goto value block to have at least one instruction", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); } else if (defaultBlock.instructions.length === 1) { const instr = defaultBlock.instructions[0]; let place = instr.lvalue; let value = instr.value; if ( /* * Value blocks generally end in a StoreLocal to assign the value of the * expression for this branch. These StoreLocal instructions can be pruned, * since we represent the value blocks as a compund value in ReactiveFunction * (no phis). However, it's also possible to have a value block that ends in * an AssignmentExpression, which we need to keep. So we only prune * StoreLocal for temporaries — any named/promoted values must be used * elsewhere and aren't safe to prune. */ value.kind === "StoreLocal" && value.lvalue.place.identifier.name === null ) { place = value.lvalue.place; value = { kind: "LoadLocal", place: value.value, loc: value.value.loc }; } return { block: defaultBlock.id, place, value, id: instr.id }; } else { const instr = defaultBlock.instructions.at(-1); let place = instr.lvalue; let value = instr.value; if ( /* * Value blocks generally end in a StoreLocal to assign the value of the * expression for this branch. These StoreLocal instructions can be pruned, * since we represent the value blocks as a compund value in ReactiveFunction * (no phis). However, it's also possible to have a value block that ends in * an AssignmentExpression, which we need to keep. So we only prune * StoreLocal for temporaries — any named/promoted values must be used * elsewhere and aren't safe to prune. */ value.kind === "StoreLocal" && value.lvalue.place.identifier.name === null ) { place = value.lvalue.place; value = { kind: "LoadLocal", place: value.value, loc: value.value.loc }; } const sequence = { kind: "SequenceExpression", instructions: defaultBlock.instructions.slice(0, -1), id: instr.id, value, loc }; return { block: defaultBlock.id, place, value: sequence, id: instr.id }; } } else { const init = this.visitValueBlockTerminal(defaultBlock.terminal); const final = this.visitValueBlock(init.fallthrough, loc); const sequence = { kind: "SequenceExpression", instructions: [ ...defaultBlock.instructions, { id: init.id, loc, lvalue: init.place, value: init.value } ], id: final.id, value: final.value, loc }; return { block: init.fallthrough, value: sequence, place: final.place, id: final.id }; } } visitValueBlockTerminal(terminal) { switch (terminal.kind) { case "sequence": { const block = this.visitValueBlock(terminal.block, terminal.loc); return { value: block.value, place: block.place, fallthrough: terminal.fallthrough, id: terminal.id }; } case "optional": { const test = this.visitValueBlock(terminal.test, terminal.loc); const testBlock = this.cx.ir.blocks.get(test.block); if (testBlock.terminal.kind !== "branch") { CompilerError.throwTodo({ reason: `Unexpected terminal kind \`${testBlock.terminal.kind}\` for optional test block`, description: null, loc: testBlock.terminal.loc, suggestions: null }); } const consequent = this.visitValueBlock( testBlock.terminal.consequent, terminal.loc ); const call = { kind: "SequenceExpression", instructions: [ { id: test.id, loc: testBlock.terminal.loc, lvalue: test.place, value: test.value } ], id: consequent.id, value: consequent.value, loc: terminal.loc }; return { place: __spreadValues({}, consequent.place), value: { kind: "OptionalExpression", optional: terminal.optional, value: call, id: terminal.id, loc: terminal.loc }, fallthrough: terminal.fallthrough, id: terminal.id }; } case "logical": { const test = this.visitValueBlock(terminal.test, terminal.loc); const testBlock = this.cx.ir.blocks.get(test.block); if (testBlock.terminal.kind !== "branch") { CompilerError.throwTodo({ reason: `Unexpected terminal kind \`${testBlock.terminal.kind}\` for logical test block`, description: null, loc: testBlock.terminal.loc, suggestions: null }); } const leftFinal = this.visitValueBlock( testBlock.terminal.consequent, terminal.loc ); const left = { kind: "SequenceExpression", instructions: [ { id: test.id, loc: terminal.loc, lvalue: test.place, value: test.value } ], id: leftFinal.id, value: leftFinal.value, loc: terminal.loc }; const right = this.visitValueBlock( testBlock.terminal.alternate, terminal.loc ); const value = { kind: "LogicalExpression", operator: terminal.operator, left, right: right.value, loc: terminal.loc }; return { place: __spreadValues({}, leftFinal.place), value, fallthrough: terminal.fallthrough, id: terminal.id }; } case "ternary": { const test = this.visitValueBlock(terminal.test, terminal.loc); const testBlock = this.cx.ir.blocks.get(test.block); if (testBlock.terminal.kind !== "branch") { CompilerError.throwTodo({ reason: `Unexpected terminal kind \`${testBlock.terminal.kind}\` for ternary test block`, description: null, loc: testBlock.terminal.loc, suggestions: null }); } const consequent = this.visitValueBlock( testBlock.terminal.consequent, terminal.loc ); const alternate = this.visitValueBlock( testBlock.terminal.alternate, terminal.loc ); const value = { kind: "ConditionalExpression", test: test.value, consequent: consequent.value, alternate: alternate.value, loc: terminal.loc }; return { place: __spreadValues({}, consequent.place), value, fallthrough: terminal.fallthrough, id: terminal.id }; } case "maybe-throw": { CompilerError.throwTodo({ reason: `Support value blocks (conditional, logical, optional chaining, etc) within a try/catch statement`, description: null, loc: terminal.loc, suggestions: null }); } case "label": { CompilerError.throwTodo({ reason: `Support labeled statements combined with value blocks (conditional, logical, optional chaining, etc)`, description: null, loc: terminal.loc, suggestions: null }); } default: { CompilerError.throwTodo({ reason: `Support \`${terminal.kind}\` as a value block terminal (conditional, logical, optional chaining, etc)`, description: null, loc: terminal.loc, suggestions: null }); } } } emptyBlock() { return []; } visitBreak(block, id, loc) { const target = this.cx.getBreakTarget(block); if (target === null) { CompilerError.invariant(false, { reason: "Expected a break target", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); } if (this.cx.scopeFallthroughs.has(target.block)) { CompilerError.invariant(target.type === "implicit", { reason: "Expected reactive scope to implicitly break to fallthrough", description: null, details: [ { kind: "error", loc, message: null } ] }); return null; } return { kind: "terminal", terminal: { kind: "break", loc, target: target.block, id, targetKind: target.type }, label: null }; } visitContinue(block, id, loc) { const target = this.cx.getContinueTarget(block); CompilerError.invariant(target !== null, { reason: `Expected continue target to be scheduled for bb${block}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); return { kind: "terminal", terminal: { kind: "continue", loc, target: target.block, id, targetKind: target.type }, label: null }; } }; var _nextScheduleId, _scheduled, _catchHandlers, _controlFlowStack; var Context = class { constructor(ir) { __privateAdd(this, _nextScheduleId, 0); /* * Used to track which blocks *have been* generated already in order to * abort if a block is generated a second time. This is an error catching * mechanism for debugging purposes, and is not used by the codegen algorithm * to drive decisions about how to emit blocks. */ this.emitted = /* @__PURE__ */ new Set(); this.scopeFallthroughs = /* @__PURE__ */ new Set(); /* * A set of blocks that are already scheduled to be emitted by eg a parent. * This allows child nodes to avoid re-emitting the same block and emit eg * a break instead. */ __privateAdd(this, _scheduled, /* @__PURE__ */ new Set()); __privateAdd(this, _catchHandlers, /* @__PURE__ */ new Set()); /* * Represents which control flow operations are currently in scope, with the innermost * scope last. Roughly speaking, the last ControlFlowTarget on the stack indicates where * control will implicitly transfer, such that gotos to that block can be elided. Gotos * targeting items higher up the stack may need labeled break or continue; see * getBreakTarget() and getContinueTarget() for more details. */ __privateAdd(this, _controlFlowStack, []); this.ir = ir; } block(id) { return this.ir.blocks.get(id); } scheduleCatchHandler(block) { __privateGet(this, _catchHandlers).add(block); } reachable(id) { const block = this.ir.blocks.get(id); return block.terminal.kind !== "unreachable"; } /* * Record that the given block will be emitted (eg by the codegen of a parent node) * so that child nodes can avoid re-emitting it. */ schedule(block, type) { const id = __privateWrapper(this, _nextScheduleId)._++; CompilerError.invariant(!__privateGet(this, _scheduled).has(block), { reason: `Break block is already scheduled: bb${block}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); __privateGet(this, _scheduled).add(block); __privateGet(this, _controlFlowStack).push({ block, id, type }); return id; } scheduleLoop(fallthroughBlock, continueBlock, loopBlock) { const id = __privateWrapper(this, _nextScheduleId)._++; const ownsBlock = !__privateGet(this, _scheduled).has(fallthroughBlock); __privateGet(this, _scheduled).add(fallthroughBlock); CompilerError.invariant(!__privateGet(this, _scheduled).has(continueBlock), { reason: `Continue block is already scheduled: bb${continueBlock}`, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); __privateGet(this, _scheduled).add(continueBlock); let ownsLoop = false; if (loopBlock !== null) { ownsLoop = !__privateGet(this, _scheduled).has(loopBlock); __privateGet(this, _scheduled).add(loopBlock); } __privateGet(this, _controlFlowStack).push({ block: fallthroughBlock, ownsBlock, id, type: "loop", continueBlock, loopBlock, ownsLoop }); return id; } // Removes a block that was scheduled; must be called after that block is emitted. unschedule(scheduleId) { const last = __privateGet(this, _controlFlowStack).pop(); CompilerError.invariant(last !== void 0 && last.id === scheduleId, { reason: "Can only unschedule the last target", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); if (last.type !== "loop" || last.ownsBlock !== null) { __privateGet(this, _scheduled).delete(last.block); } if (last.type === "loop") { __privateGet(this, _scheduled).delete(last.continueBlock); if (last.ownsLoop && last.loopBlock !== null) { __privateGet(this, _scheduled).delete(last.loopBlock); } } } /* * Helper to unschedule multiple scheduled blocks. The ids should be in * the order in which they were scheduled, ie most recently scheduled last. */ unscheduleAll(scheduleIds) { for (let i = scheduleIds.length - 1; i >= 0; i--) { this.unschedule(scheduleIds[i]); } } // Check if the given @param block is scheduled or not. isScheduled(block) { return __privateGet(this, _scheduled).has(block) || __privateGet(this, _catchHandlers).has(block); } /* * Given the current control flow stack, determines how a `break` to the given @param block * must be emitted. Returns as follows: * - 'implicit' if control would implicitly transfer to that block * - 'labeled' if a labeled break is required to transfer control to that block * - 'unlabeled' if an unlabeled break would transfer to that block * - null if there is no information for this block * * The returned 'block' value should be used as the label if necessary. */ getBreakTarget(block) { let hasPrecedingLoop = false; for (let i = __privateGet(this, _controlFlowStack).length - 1; i >= 0; i--) { const target = __privateGet(this, _controlFlowStack)[i]; if (target.block === block) { let type; if (target.type === "loop") { type = hasPrecedingLoop ? "labeled" : "unlabeled"; } else if (i === __privateGet(this, _controlFlowStack).length - 1) { type = "implicit"; } else { type = "labeled"; } return { block: target.block, type }; } hasPrecedingLoop || (hasPrecedingLoop = target.type === "loop"); } CompilerError.invariant(false, { reason: "Expected a break target", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); } /* * Given the current control flow stack, determines how a `continue` to the given @param block * must be emitted. Returns as follows: * - 'implicit' if control would implicitly continue to that block * - 'labeled' if a labeled continue is required to continue to that block * - 'unlabeled' if an unlabeled continue would transfer to that block * - null if there is no information for this block * * The returned 'block' value should be used as the label if necessary. */ getContinueTarget(block) { let hasPrecedingLoop = false; for (let i = __privateGet(this, _controlFlowStack).length - 1; i >= 0; i--) { const target = __privateGet(this, _controlFlowStack)[i]; if (target.type == "loop" && target.continueBlock === block) { let type; if (hasPrecedingLoop) { type = "labeled"; } else if (i === __privateGet(this, _controlFlowStack).length - 1) { type = "implicit"; } else { type = "unlabeled"; } return { block: target.block, type }; } hasPrecedingLoop || (hasPrecedingLoop = target.type === "loop"); } return null; } debugBreakTargets() { return __privateGet(this, _controlFlowStack).map((target) => __spreadValues({}, target)); } }; _nextScheduleId = new WeakMap(); _scheduled = new WeakMap(); _catchHandlers = new WeakMap(); _controlFlowStack = new WeakMap(); // src/ReactiveScopes/CodegenReactiveFunction.ts var t3 = __toESM(require("@babel/types")); var import_crypto = require("crypto"); // src/ReactiveScopes/MemoizeFbtAndMacroOperandsInSameScope.ts function memoizeFbtAndMacroOperandsInSameScope(fn) { var _a; const fbtMacroTags = /* @__PURE__ */ new Set([ ...Array.from(FBT_TAGS).map((tag) => [tag, []]), ...(_a = fn.env.config.customMacros) != null ? _a : [] ]); const fbtValues = /* @__PURE__ */ new Set(); const macroMethods = /* @__PURE__ */ new Map(); while (true) { let vsize = fbtValues.size; let msize = macroMethods.size; visit2(fn, fbtMacroTags, fbtValues, macroMethods); if (vsize === fbtValues.size && msize === macroMethods.size) { break; } } return fbtValues; } var FBT_TAGS = /* @__PURE__ */ new Set([ "fbt", "fbt:param", "fbs", "fbs:param" ]); var SINGLE_CHILD_FBT_TAGS = /* @__PURE__ */ new Set([ "fbt:param", "fbs:param" ]); function visit2(fn, fbtMacroTags, fbtValues, macroMethods) { for (const [, block] of fn.body.blocks) { for (const instruction of block.instructions) { const { lvalue, value } = instruction; if (lvalue === null) { continue; } if (value.kind === "Primitive" && typeof value.value === "string" && matchesExactTag(value.value, fbtMacroTags)) { fbtValues.add(lvalue.identifier.id); } else if (value.kind === "LoadGlobal" && matchesExactTag(value.binding.name, fbtMacroTags)) { fbtValues.add(lvalue.identifier.id); } else if (value.kind === "LoadGlobal" && matchTagRoot(value.binding.name, fbtMacroTags) !== null) { const methods = matchTagRoot(value.binding.name, fbtMacroTags); macroMethods.set(lvalue.identifier.id, methods); } else if (value.kind === "PropertyLoad" && macroMethods.has(value.object.identifier.id)) { const methods = macroMethods.get(value.object.identifier.id); const newMethods = []; for (const method of methods) { if (method.length > 0 && (method[0].type === "wildcard" || method[0].type === "name" && method[0].name === value.property)) { if (method.length > 1) { newMethods.push(method.slice(1)); } else { fbtValues.add(lvalue.identifier.id); } } } if (newMethods.length > 0) { macroMethods.set(lvalue.identifier.id, newMethods); } } else if (isFbtCallExpression(fbtValues, value)) { const fbtScope = lvalue.identifier.scope; if (fbtScope === null) { continue; } for (const operand of eachReactiveValueOperand(value)) { operand.identifier.scope = fbtScope; expandFbtScopeRange(fbtScope.range, operand.identifier.mutableRange); fbtValues.add(operand.identifier.id); } } else if (isFbtJsxExpression(fbtMacroTags, fbtValues, value) || isFbtJsxChild(fbtValues, lvalue, value)) { const fbtScope = lvalue.identifier.scope; if (fbtScope === null) { continue; } for (const operand of eachReactiveValueOperand(value)) { operand.identifier.scope = fbtScope; expandFbtScopeRange(fbtScope.range, operand.identifier.mutableRange); fbtValues.add(operand.identifier.id); } } else if (fbtValues.has(lvalue.identifier.id)) { const fbtScope = lvalue.identifier.scope; if (fbtScope === null) { return; } for (const operand of eachReactiveValueOperand(value)) { if (operand.identifier.name !== null && operand.identifier.name.kind === "named") { continue; } operand.identifier.scope = fbtScope; expandFbtScopeRange(fbtScope.range, operand.identifier.mutableRange); } } } } } function matchesExactTag(s, tags) { return Array.from(tags).some( (macro) => typeof macro === "string" ? s === macro : macro[1].length === 0 && macro[0] === s ); } function matchTagRoot(s, tags) { const methods = []; for (const macro of tags) { if (typeof macro === "string") { continue; } const [tag, rest] = macro; if (tag === s && rest.length > 0) { methods.push(rest); } } if (methods.length > 0) { return methods; } else { return null; } } function isFbtCallExpression(fbtValues, value) { return value.kind === "CallExpression" && fbtValues.has(value.callee.identifier.id) || value.kind === "MethodCall" && fbtValues.has(value.property.identifier.id); } function isFbtJsxExpression(fbtMacroTags, fbtValues, value) { return value.kind === "JsxExpression" && (value.tag.kind === "Identifier" && fbtValues.has(value.tag.identifier.id) || value.tag.kind === "BuiltinTag" && matchesExactTag(value.tag.name, fbtMacroTags)); } function isFbtJsxChild(fbtValues, lvalue, value) { return (value.kind === "JsxExpression" || value.kind === "JsxFragment") && lvalue !== null && fbtValues.has(lvalue.identifier.id); } function expandFbtScopeRange(fbtRange, extendWith) { if (extendWith.start !== 0) { fbtRange.start = makeInstructionId( Math.min(fbtRange.start, extendWith.start) ); } } // src/ReactiveScopes/CodegenReactiveFunction.ts var MEMO_CACHE_SENTINEL = "react.memo_cache_sentinel"; var EARLY_RETURN_SENTINEL = "react.early_return_sentinel"; function codegenFunction(fn, { uniqueIdentifiers, fbtOperands }) { var _a, _b, _c; const cx = new Context2( fn.env, (_a = fn.id) != null ? _a : "[[ anonymous ]]", uniqueIdentifiers, fbtOperands, null ); let fastRefreshState = null; if (fn.env.config.enableResetCacheOnSourceFileChanges && fn.env.code !== null) { const hash2 = (0, import_crypto.createHmac)("sha256", fn.env.code).digest("hex"); fastRefreshState = { cacheIndex: cx.nextCacheIndex, hash: hash2 }; } const compileResult = codegenReactiveFunction(cx, fn); if (compileResult.isErr()) { return compileResult; } const compiled = compileResult.unwrap(); const hookGuard = fn.env.config.enableEmitHookGuards; if (hookGuard != null && fn.env.isInferredMemoEnabled) { compiled.body = t3.blockStatement([ createHookGuard( hookGuard, fn.env.programContext, compiled.body.body, 0 /* PushHookGuard */, 1 /* PopHookGuard */ ) ]); } const cacheCount = compiled.memoSlotsUsed; if (cacheCount !== 0) { const preface = []; const useMemoCacheIdentifier = fn.env.programContext.addMemoCacheImport().name; preface.push( t3.variableDeclaration("const", [ t3.variableDeclarator( t3.identifier(cx.synthesizeName("$")), t3.callExpression(t3.identifier(useMemoCacheIdentifier), [ t3.numericLiteral(cacheCount) ]) ) ]) ); if (fastRefreshState !== null) { const index = cx.synthesizeName("$i"); preface.push( t3.ifStatement( t3.binaryExpression( "!==", t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.numericLiteral(fastRefreshState.cacheIndex), true ), t3.stringLiteral(fastRefreshState.hash) ), t3.blockStatement([ t3.forStatement( t3.variableDeclaration("let", [ t3.variableDeclarator(t3.identifier(index), t3.numericLiteral(0)) ]), t3.binaryExpression( "<", t3.identifier(index), t3.numericLiteral(cacheCount) ), t3.assignmentExpression( "+=", t3.identifier(index), t3.numericLiteral(1) ), t3.blockStatement([ t3.expressionStatement( t3.assignmentExpression( "=", t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.identifier(index), true ), t3.callExpression( t3.memberExpression( t3.identifier("Symbol"), t3.identifier("for") ), [t3.stringLiteral(MEMO_CACHE_SENTINEL)] ) ) ) ]) ), t3.expressionStatement( t3.assignmentExpression( "=", t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.numericLiteral(fastRefreshState.cacheIndex), true ), t3.stringLiteral(fastRefreshState.hash) ) ) ]) ) ); } compiled.body.body.unshift(...preface); } const emitInstrumentForget = fn.env.config.enableEmitInstrumentForget; if (emitInstrumentForget != null && fn.id != null && fn.env.isInferredMemoEnabled) { const gating = emitInstrumentForget.gating != null ? t3.identifier( fn.env.programContext.addImportSpecifier( emitInstrumentForget.gating ).name ) : null; const globalGating = emitInstrumentForget.globalGating != null ? t3.identifier(emitInstrumentForget.globalGating) : null; if (emitInstrumentForget.globalGating != null) { const assertResult = fn.env.programContext.assertGlobalBinding( emitInstrumentForget.globalGating ); if (assertResult.isErr()) { return assertResult; } } let ifTest; if (gating != null && globalGating != null) { ifTest = t3.logicalExpression("&&", globalGating, gating); } else if (gating != null) { ifTest = gating; } else { CompilerError.invariant(globalGating != null, { reason: "Bad config not caught! Expected at least one of gating or globalGating", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); ifTest = globalGating; } const instrumentFnIdentifier = fn.env.programContext.addImportSpecifier( emitInstrumentForget.fn ).name; const test = t3.ifStatement( ifTest, t3.expressionStatement( t3.callExpression(t3.identifier(instrumentFnIdentifier), [ t3.stringLiteral(fn.id), t3.stringLiteral((_b = fn.env.filename) != null ? _b : "") ]) ) ); compiled.body.body.unshift(test); } const outlined = []; for (const { fn: outlinedFunction, type } of cx.env.getOutlinedFunctions()) { const reactiveFunction = buildReactiveFunction(outlinedFunction); pruneUnusedLabels(reactiveFunction); pruneUnusedLValues(reactiveFunction); pruneHoistedContexts(reactiveFunction); const identifiers = renameVariables(reactiveFunction); const codegen = codegenReactiveFunction( new Context2( cx.env, (_c = reactiveFunction.id) != null ? _c : "[[ anonymous ]]", identifiers, cx.fbtOperands ), reactiveFunction ); if (codegen.isErr()) { return codegen; } outlined.push({ fn: codegen.unwrap(), type }); } compiled.outlined = outlined; return compileResult; } function codegenReactiveFunction(cx, fn) { for (const param of fn.params) { const place = param.kind === "Identifier" ? param : param.place; cx.temp.set(place.identifier.declarationId, null); cx.declare(place.identifier); } const params = fn.params.map((param) => convertParameter(param)); const body = codegenBlock(cx, fn.body); body.directives = fn.directives.map((d) => t3.directive(t3.directiveLiteral(d))); const statements = body.body; if (statements.length !== 0) { const last = statements[statements.length - 1]; if (last.type === "ReturnStatement" && last.argument == null) { statements.pop(); } } if (cx.errors.hasAnyErrors()) { return Err(cx.errors); } const countMemoBlockVisitor = new CountMemoBlockVisitor(fn.env); visitReactiveFunction(fn, countMemoBlockVisitor, void 0); return Ok({ type: "CodegenFunction", loc: fn.loc, id: fn.id !== null ? t3.identifier(fn.id) : null, nameHint: fn.nameHint, params, body, generator: fn.generator, async: fn.async, memoSlotsUsed: cx.nextCacheIndex, memoBlocks: countMemoBlockVisitor.memoBlocks, memoValues: countMemoBlockVisitor.memoValues, prunedMemoBlocks: countMemoBlockVisitor.prunedMemoBlocks, prunedMemoValues: countMemoBlockVisitor.prunedMemoValues, outlined: [], hasFireRewrite: fn.env.hasFireRewrite, hasInferredEffect: fn.env.hasInferredEffect, inferredEffectLocations: fn.env.inferredEffectLocations }); } var CountMemoBlockVisitor = class extends ReactiveFunctionVisitor { constructor(env) { super(); this.memoBlocks = 0; this.memoValues = 0; this.prunedMemoBlocks = 0; this.prunedMemoValues = 0; this.env = env; } visitScope(scopeBlock, state) { this.memoBlocks += 1; this.memoValues += scopeBlock.scope.declarations.size; this.traverseScope(scopeBlock, state); } visitPrunedScope(scopeBlock, state) { this.prunedMemoBlocks += 1; this.prunedMemoValues += scopeBlock.scope.declarations.size; this.traversePrunedScope(scopeBlock, state); } }; function convertParameter(param) { if (param.kind === "Identifier") { return convertIdentifier(param.identifier); } else { return t3.restElement(convertIdentifier(param.place.identifier)); } } var _nextCacheIndex, _declarations; var Context2 = class { constructor(env, fnName, uniqueIdentifiers, fbtOperands, temporaries = null) { __privateAdd(this, _nextCacheIndex, 0); /** * Tracks which named variables have been declared to dedupe declarations, * so this uses DeclarationId instead of IdentifierId */ __privateAdd(this, _declarations, /* @__PURE__ */ new Set()); this.errors = new CompilerError(); this.objectMethods = /* @__PURE__ */ new Map(); this.synthesizedNames = /* @__PURE__ */ new Map(); this.env = env; this.fnName = fnName; this.uniqueIdentifiers = uniqueIdentifiers; this.fbtOperands = fbtOperands; this.temp = temporaries !== null ? new Map(temporaries) : /* @__PURE__ */ new Map(); } get nextCacheIndex() { return __privateWrapper(this, _nextCacheIndex)._++; } declare(identifier4) { __privateGet(this, _declarations).add(identifier4.declarationId); } hasDeclared(identifier4) { return __privateGet(this, _declarations).has(identifier4.declarationId); } synthesizeName(name) { const previous = this.synthesizedNames.get(name); if (previous !== void 0) { return previous; } let validated = makeIdentifierName(name).value; let index = 0; while (this.uniqueIdentifiers.has(validated)) { validated = makeIdentifierName(`${name}${index++}`).value; } this.uniqueIdentifiers.add(validated); this.synthesizedNames.set(name, validated); return validated; } }; _nextCacheIndex = new WeakMap(); _declarations = new WeakMap(); function codegenBlock(cx, block) { const temp = new Map(cx.temp); const result = codegenBlockNoReset(cx, block); for (const [key2, value] of cx.temp) { if (!temp.has(key2)) { continue; } CompilerError.invariant(temp.get(key2) === value, { reason: "Expected temporary value to be unchanged", description: null, suggestions: null, details: [ { kind: "error", loc: null, message: null } ] }); } cx.temp = temp; return result; } function codegenBlockNoReset(cx, block) { const statements = []; for (const item of block) { switch (item.kind) { case "instruction": { const statement = codegenInstructionNullable(cx, item.instruction); if (statement !== null) { statements.push(statement); } break; } case "pruned-scope": { const scopeBlock = codegenBlockNoReset(cx, item.instructions); statements.push(...scopeBlock.body); break; } case "scope": { const temp = new Map(cx.temp); codegenReactiveScope(cx, statements, item.scope, item.instructions); cx.temp = temp; break; } case "terminal": { const statement = codegenTerminal(cx, item.terminal); if (statement === null) { break; } if (item.label !== null && !item.label.implicit) { const block2 = statement.type === "BlockStatement" && statement.body.length === 1 ? statement.body[0] : statement; statements.push( t3.labeledStatement( t3.identifier(codegenLabel(item.label.id)), block2 ) ); } else if (statement.type === "BlockStatement") { statements.push(...statement.body); } else { statements.push(statement); } break; } default: { assertExhaustive( item, `Unexpected item kind \`${item.kind}\`` ); } } } return t3.blockStatement(statements); } function wrapCacheDep(cx, value) { if (cx.env.config.enableEmitFreeze != null && cx.env.isInferredMemoEnabled) { const emitFreezeIdentifier = cx.env.programContext.addImportSpecifier( cx.env.config.enableEmitFreeze ).name; cx.env.programContext.assertGlobalBinding(EMIT_FREEZE_GLOBAL_GATING, cx.env.scope).unwrap(); return t3.conditionalExpression( t3.identifier(EMIT_FREEZE_GLOBAL_GATING), t3.callExpression(t3.identifier(emitFreezeIdentifier), [ value, t3.stringLiteral(cx.fnName) ]), value ); } else { return value; } } function codegenReactiveScope(cx, statements, scope, block) { const cacheStoreStatements = []; const cacheLoadStatements = []; const cacheLoads = []; const changeExpressions = []; const changeExpressionComments = []; const outputComments = []; for (const dep of [...scope.dependencies].sort(compareScopeDependency)) { const index = cx.nextCacheIndex; changeExpressionComments.push(printDependencyComment(dep)); const comparison = t3.binaryExpression( "!==", t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.numericLiteral(index), true ), codegenDependency(cx, dep) ); if (cx.env.config.enableChangeVariableCodegen) { const changeIdentifier = t3.identifier(cx.synthesizeName(`c_${index}`)); statements.push( t3.variableDeclaration("const", [ t3.variableDeclarator(changeIdentifier, comparison) ]) ); changeExpressions.push(changeIdentifier); } else { changeExpressions.push(comparison); } cacheStoreStatements.push( t3.expressionStatement( t3.assignmentExpression( "=", t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.numericLiteral(index), true ), codegenDependency(cx, dep) ) ) ); } let firstOutputIndex = null; for (const [, { identifier: identifier4 }] of [...scope.declarations].sort( ([, a], [, b]) => compareScopeDeclaration(a, b) )) { const index = cx.nextCacheIndex; if (firstOutputIndex === null) { firstOutputIndex = index; } CompilerError.invariant(identifier4.name != null, { reason: `Expected scope declaration identifier to be named`, description: `Declaration \`${printIdentifier( identifier4 )}\` is unnamed in scope @${scope.id}`, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); const name = convertIdentifier(identifier4); outputComments.push(name.name); if (!cx.hasDeclared(identifier4)) { statements.push( t3.variableDeclaration("let", [t3.variableDeclarator(name)]) ); } cacheLoads.push({ name, index, value: wrapCacheDep(cx, name) }); cx.declare(identifier4); } for (const reassignment of scope.reassignments) { const index = cx.nextCacheIndex; if (firstOutputIndex === null) { firstOutputIndex = index; } const name = convertIdentifier(reassignment); outputComments.push(name.name); cacheLoads.push({ name, index, value: wrapCacheDep(cx, name) }); } let testCondition = changeExpressions.reduce( (acc, ident) => { if (acc == null) { return ident; } return t3.logicalExpression("||", acc, ident); }, null ); if (testCondition === null) { CompilerError.invariant(firstOutputIndex !== null, { reason: `Expected scope to have at least one declaration`, description: `Scope '@${scope.id}' has no declarations`, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); testCondition = t3.binaryExpression( "===", t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.numericLiteral(firstOutputIndex), true ), t3.callExpression( t3.memberExpression(t3.identifier("Symbol"), t3.identifier("for")), [t3.stringLiteral(MEMO_CACHE_SENTINEL)] ) ); } if (cx.env.config.disableMemoizationForDebugging) { CompilerError.invariant( cx.env.config.enableChangeDetectionForDebugging == null, { reason: `Expected to not have both change detection enabled and memoization disabled`, description: `Incompatible config options`, details: [ { kind: "error", loc: null, message: null } ] } ); testCondition = t3.logicalExpression( "||", testCondition, t3.booleanLiteral(true) ); } let computationBlock = codegenBlock(cx, block); let memoStatement; const detectionFunction = cx.env.config.enableChangeDetectionForDebugging; if (detectionFunction != null && changeExpressions.length > 0) { const loc = typeof scope.loc === "symbol" ? "unknown location" : `(${scope.loc.start.line}:${scope.loc.end.line})`; const importedDetectionFunctionIdentifier = cx.env.programContext.addImportSpecifier(detectionFunction).name; const cacheLoadOldValueStatements = []; const changeDetectionStatements = []; const idempotenceDetectionStatements = []; for (const { name, index, value } of cacheLoads) { const loadName = cx.synthesizeName(`old$${name.name}`); const slot = t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.numericLiteral(index), true ); cacheStoreStatements.push( t3.expressionStatement(t3.assignmentExpression("=", slot, value)) ); cacheLoadOldValueStatements.push( t3.variableDeclaration("let", [ t3.variableDeclarator(t3.identifier(loadName), slot) ]) ); changeDetectionStatements.push( t3.expressionStatement( t3.callExpression(t3.identifier(importedDetectionFunctionIdentifier), [ t3.identifier(loadName), t3.cloneNode(name, true), t3.stringLiteral(name.name), t3.stringLiteral(cx.fnName), t3.stringLiteral("cached"), t3.stringLiteral(loc) ]) ) ); idempotenceDetectionStatements.push( t3.expressionStatement( t3.callExpression(t3.identifier(importedDetectionFunctionIdentifier), [ t3.cloneNode(slot, true), t3.cloneNode(name, true), t3.stringLiteral(name.name), t3.stringLiteral(cx.fnName), t3.stringLiteral("recomputed"), t3.stringLiteral(loc) ]) ) ); idempotenceDetectionStatements.push( t3.expressionStatement(t3.assignmentExpression("=", name, slot)) ); } const condition = cx.synthesizeName("condition"); const recomputationBlock = t3.cloneNode(computationBlock, true); memoStatement = t3.blockStatement([ ...computationBlock.body, t3.variableDeclaration("let", [ t3.variableDeclarator(t3.identifier(condition), testCondition) ]), t3.ifStatement( t3.unaryExpression("!", t3.identifier(condition)), t3.blockStatement([ ...cacheLoadOldValueStatements, ...changeDetectionStatements ]) ), ...cacheStoreStatements, t3.ifStatement( t3.identifier(condition), t3.blockStatement([ ...recomputationBlock.body, ...idempotenceDetectionStatements ]) ) ]); } else { for (const { name, index, value } of cacheLoads) { cacheStoreStatements.push( t3.expressionStatement( t3.assignmentExpression( "=", t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.numericLiteral(index), true ), value ) ) ); cacheLoadStatements.push( t3.expressionStatement( t3.assignmentExpression( "=", name, t3.memberExpression( t3.identifier(cx.synthesizeName("$")), t3.numericLiteral(index), true ) ) ) ); } computationBlock.body.push(...cacheStoreStatements); memoStatement = t3.ifStatement( testCondition, computationBlock, t3.blockStatement(cacheLoadStatements) ); } if (cx.env.config.enableMemoizationComments) { if (changeExpressionComments.length) { t3.addComment( memoStatement, "leading", ` check if ${printDelimitedCommentList( changeExpressionComments, "or" )} changed`, true ); t3.addComment( memoStatement, "leading", ` "useMemo" for ${printDelimitedCommentList(outputComments, "and")}:`, true ); } else { t3.addComment( memoStatement, "leading", " cache value with no dependencies", true ); t3.addComment( memoStatement, "leading", ` "useMemo" for ${printDelimitedCommentList(outputComments, "and")}:`, true ); } if (computationBlock.body.length > 0) { t3.addComment( computationBlock.body[0], "leading", ` Inputs changed, recompute`, true ); } if (cacheLoadStatements.length > 0) { t3.addComment( cacheLoadStatements[0], "leading", ` Inputs did not change, use cached value`, true ); } } statements.push(memoStatement); const earlyReturnValue = scope.earlyReturnValue; if (earlyReturnValue !== null) { CompilerError.invariant( earlyReturnValue.value.name !== null && earlyReturnValue.value.name.kind === "named", { reason: `Expected early return value to be promoted to a named variable`, description: null, details: [ { kind: "error", loc: earlyReturnValue.loc, message: null } ], suggestions: null } ); const name = earlyReturnValue.value.name.value; statements.push( t3.ifStatement( t3.binaryExpression( "!==", t3.identifier(name), t3.callExpression( t3.memberExpression(t3.identifier("Symbol"), t3.identifier("for")), [t3.stringLiteral(EARLY_RETURN_SENTINEL)] ) ), t3.blockStatement([t3.returnStatement(t3.identifier(name))]) ) ); } } function codegenTerminal(cx, terminal) { switch (terminal.kind) { case "break": { if (terminal.targetKind === "implicit") { return null; } return createBreakStatement( terminal.loc, terminal.targetKind === "labeled" ? t3.identifier(codegenLabel(terminal.target)) : null ); } case "continue": { if (terminal.targetKind === "implicit") { return null; } return createContinueStatement( terminal.loc, terminal.targetKind === "labeled" ? t3.identifier(codegenLabel(terminal.target)) : null ); } case "for": { return createForStatement( terminal.loc, codegenForInit(cx, terminal.init), codegenInstructionValueToExpression(cx, terminal.test), terminal.update !== null ? codegenInstructionValueToExpression(cx, terminal.update) : null, codegenBlock(cx, terminal.loop) ); } case "for-in": { CompilerError.invariant(terminal.init.kind === "SequenceExpression", { reason: `Expected a sequence expression init for for..in`, description: `Got \`${terminal.init.kind}\` expression instead`, details: [ { kind: "error", loc: terminal.init.loc, message: null } ], suggestions: null }); if (terminal.init.instructions.length !== 2) { CompilerError.throwTodo({ reason: "Support non-trivial for..in inits", description: null, loc: terminal.init.loc, suggestions: null }); } const iterableCollection = terminal.init.instructions[0]; const iterableItem = terminal.init.instructions[1]; let lval; switch (iterableItem.value.kind) { case "StoreLocal": { lval = codegenLValue(cx, iterableItem.value.lvalue.place); break; } case "Destructure": { lval = codegenLValue(cx, iterableItem.value.lvalue.pattern); break; } case "StoreContext": { CompilerError.throwTodo({ reason: "Support non-trivial for..in inits", description: null, loc: terminal.init.loc, suggestions: null }); } default: CompilerError.invariant(false, { reason: `Expected a StoreLocal or Destructure to be assigned to the collection`, description: `Found ${iterableItem.value.kind}`, details: [ { kind: "error", loc: iterableItem.value.loc, message: null } ], suggestions: null }); } let varDeclKind; switch (iterableItem.value.lvalue.kind) { case "Const" /* Const */: varDeclKind = "const"; break; case "Let" /* Let */: varDeclKind = "let"; break; case "Reassign" /* Reassign */: CompilerError.invariant(false, { reason: "Destructure should never be Reassign as it would be an Object/ArrayPattern", description: null, details: [ { kind: "error", loc: iterableItem.loc, message: null } ], suggestions: null }); case "Catch" /* Catch */: case "HoistedConst" /* HoistedConst */: case "HoistedLet" /* HoistedLet */: case "HoistedFunction" /* HoistedFunction */: case "Function" /* Function */: CompilerError.invariant(false, { reason: `Unexpected ${iterableItem.value.lvalue.kind} variable in for..in collection`, description: null, details: [ { kind: "error", loc: iterableItem.loc, message: null } ], suggestions: null }); default: assertExhaustive( iterableItem.value.lvalue.kind, `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}` ); } return createForInStatement( terminal.loc, /* * Special handling here since we only want the VariableDeclarators without any inits * This needs to be updated when we handle non-trivial ForOf inits */ createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ t3.variableDeclarator(lval, null) ]), codegenInstructionValueToExpression(cx, iterableCollection.value), codegenBlock(cx, terminal.loop) ); } case "for-of": { CompilerError.invariant( terminal.init.kind === "SequenceExpression" && terminal.init.instructions.length === 1 && terminal.init.instructions[0].value.kind === "GetIterator", { reason: `Expected a single-expression sequence expression init for for..of`, description: `Got \`${terminal.init.kind}\` expression instead`, details: [ { kind: "error", loc: terminal.init.loc, message: null } ], suggestions: null } ); const iterableCollection = terminal.init.instructions[0].value; CompilerError.invariant(terminal.test.kind === "SequenceExpression", { reason: `Expected a sequence expression test for for..of`, description: `Got \`${terminal.init.kind}\` expression instead`, details: [ { kind: "error", loc: terminal.test.loc, message: null } ], suggestions: null }); if (terminal.test.instructions.length !== 2) { CompilerError.throwTodo({ reason: "Support non-trivial for..of inits", description: null, loc: terminal.init.loc, suggestions: null }); } const iterableItem = terminal.test.instructions[1]; let lval; switch (iterableItem.value.kind) { case "StoreLocal": { lval = codegenLValue(cx, iterableItem.value.lvalue.place); break; } case "Destructure": { lval = codegenLValue(cx, iterableItem.value.lvalue.pattern); break; } case "StoreContext": { CompilerError.throwTodo({ reason: "Support non-trivial for..of inits", description: null, loc: terminal.init.loc, suggestions: null }); } default: CompilerError.invariant(false, { reason: `Expected a StoreLocal or Destructure to be assigned to the collection`, description: `Found ${iterableItem.value.kind}`, details: [ { kind: "error", loc: iterableItem.value.loc, message: null } ], suggestions: null }); } let varDeclKind; switch (iterableItem.value.lvalue.kind) { case "Const" /* Const */: varDeclKind = "const"; break; case "Let" /* Let */: varDeclKind = "let"; break; case "Reassign" /* Reassign */: case "Catch" /* Catch */: case "HoistedConst" /* HoistedConst */: case "HoistedLet" /* HoistedLet */: case "HoistedFunction" /* HoistedFunction */: case "Function" /* Function */: CompilerError.invariant(false, { reason: `Unexpected ${iterableItem.value.lvalue.kind} variable in for..of collection`, description: null, details: [ { kind: "error", loc: iterableItem.loc, message: null } ], suggestions: null }); default: assertExhaustive( iterableItem.value.lvalue.kind, `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}` ); } return createForOfStatement( terminal.loc, /* * Special handling here since we only want the VariableDeclarators without any inits * This needs to be updated when we handle non-trivial ForOf inits */ createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ t3.variableDeclarator(lval, null) ]), codegenInstructionValueToExpression(cx, iterableCollection), codegenBlock(cx, terminal.loop) ); } case "if": { const test = codegenPlaceToExpression(cx, terminal.test); const consequent = codegenBlock(cx, terminal.consequent); let alternate = null; if (terminal.alternate !== null) { const block = codegenBlock(cx, terminal.alternate); if (block.body.length !== 0) { alternate = block; } } return createIfStatement(terminal.loc, test, consequent, alternate); } case "return": { const value = codegenPlaceToExpression(cx, terminal.value); if (value.type === "Identifier" && value.name === "undefined") { return t3.returnStatement(); } return t3.returnStatement(value); } case "switch": { return createSwitchStatement( terminal.loc, codegenPlaceToExpression(cx, terminal.test), terminal.cases.map((case_) => { const test = case_.test !== null ? codegenPlaceToExpression(cx, case_.test) : null; const block = codegenBlock(cx, case_.block); return t3.switchCase(test, block.body.length === 0 ? [] : [block]); }) ); } case "throw": { return createThrowStatement( terminal.loc, codegenPlaceToExpression(cx, terminal.value) ); } case "do-while": { const test = codegenInstructionValueToExpression(cx, terminal.test); return createDoWhileStatement( terminal.loc, test, codegenBlock(cx, terminal.loop) ); } case "while": { const test = codegenInstructionValueToExpression(cx, terminal.test); return createWhileStatement( terminal.loc, test, codegenBlock(cx, terminal.loop) ); } case "label": { return codegenBlock(cx, terminal.block); } case "try": { let catchParam = null; if (terminal.handlerBinding !== null) { catchParam = convertIdentifier(terminal.handlerBinding.identifier); cx.temp.set(terminal.handlerBinding.identifier.declarationId, null); } return createTryStatement( terminal.loc, codegenBlock(cx, terminal.block), t3.catchClause(catchParam, codegenBlock(cx, terminal.handler)) ); } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } function codegenInstructionNullable(cx, instr) { if (instr.value.kind === "StoreLocal" || instr.value.kind === "StoreContext" || instr.value.kind === "Destructure" || instr.value.kind === "DeclareLocal" || instr.value.kind === "DeclareContext") { let kind = instr.value.lvalue.kind; let lvalue; let value; if (instr.value.kind === "StoreLocal") { kind = cx.hasDeclared(instr.value.lvalue.place.identifier) ? "Reassign" /* Reassign */ : kind; lvalue = instr.value.lvalue.place; value = codegenPlaceToExpression(cx, instr.value.value); } else if (instr.value.kind === "StoreContext") { lvalue = instr.value.lvalue.place; value = codegenPlaceToExpression(cx, instr.value.value); } else if (instr.value.kind === "DeclareLocal" || instr.value.kind === "DeclareContext") { if (cx.hasDeclared(instr.value.lvalue.place.identifier)) { return null; } kind = instr.value.lvalue.kind; lvalue = instr.value.lvalue.place; value = null; } else { lvalue = instr.value.lvalue.pattern; let hasReassign = false; let hasDeclaration = false; for (const place of eachPatternOperand(lvalue)) { if (kind !== "Reassign" /* Reassign */ && place.identifier.name === null) { cx.temp.set(place.identifier.declarationId, null); } const isDeclared = cx.hasDeclared(place.identifier); hasReassign || (hasReassign = isDeclared); hasDeclaration || (hasDeclaration = !isDeclared); } if (hasReassign && hasDeclaration) { CompilerError.invariant(false, { reason: "Encountered a destructuring operation where some identifiers are already declared (reassignments) but others are not (declarations)", description: null, details: [ { kind: "error", loc: instr.loc, message: null } ], suggestions: null }); } else if (hasReassign) { kind = "Reassign" /* Reassign */; } value = codegenPlaceToExpression(cx, instr.value.value); } switch (kind) { case "Const" /* Const */: { CompilerError.invariant(instr.lvalue === null, { reason: `Const declaration cannot be referenced as an expression`, description: null, details: [ { kind: "error", loc: instr.value.loc, message: `this is ${kind}` } ], suggestions: null }); return createVariableDeclaration(instr.loc, "const", [ t3.variableDeclarator(codegenLValue(cx, lvalue), value) ]); } case "Function" /* Function */: { CompilerError.invariant(instr.lvalue === null, { reason: `Function declaration cannot be referenced as an expression`, description: null, details: [ { kind: "error", loc: instr.value.loc, message: `this is ${kind}` } ], suggestions: null }); const genLvalue = codegenLValue(cx, lvalue); CompilerError.invariant(genLvalue.type === "Identifier", { reason: "Expected an identifier as a function declaration lvalue", description: null, details: [ { kind: "error", loc: instr.value.loc, message: null } ], suggestions: null }); CompilerError.invariant((value == null ? void 0 : value.type) === "FunctionExpression", { reason: "Expected a function as a function declaration value", description: `Got ${value == null ? String(value) : value.type} at ${printInstruction(instr)}`, details: [ { kind: "error", loc: instr.value.loc, message: null } ], suggestions: null }); return createFunctionDeclaration( instr.loc, genLvalue, value.params, value.body, value.generator, value.async ); } case "Let" /* Let */: { CompilerError.invariant(instr.lvalue === null, { reason: `Const declaration cannot be referenced as an expression`, description: null, details: [ { kind: "error", loc: instr.value.loc, message: "this is const" } ], suggestions: null }); return createVariableDeclaration(instr.loc, "let", [ t3.variableDeclarator(codegenLValue(cx, lvalue), value) ]); } case "Reassign" /* Reassign */: { CompilerError.invariant(value !== null, { reason: "Expected a value for reassignment", description: null, details: [ { kind: "error", loc: instr.value.loc, message: null } ], suggestions: null }); const expr = t3.assignmentExpression( "=", codegenLValue(cx, lvalue), value ); if (instr.lvalue !== null) { if (instr.value.kind !== "StoreContext") { cx.temp.set(instr.lvalue.identifier.declarationId, expr); return null; } else { const statement = codegenInstruction(cx, instr, expr); if (statement.type === "EmptyStatement") { return null; } return statement; } } else { return createExpressionStatement(instr.loc, expr); } } case "Catch" /* Catch */: { return t3.emptyStatement(); } case "HoistedLet" /* HoistedLet */: case "HoistedConst" /* HoistedConst */: case "HoistedFunction" /* HoistedFunction */: { CompilerError.invariant(false, { reason: `Expected ${kind} to have been pruned in PruneHoistedContexts`, description: null, details: [ { kind: "error", loc: instr.loc, message: null } ], suggestions: null }); } default: { assertExhaustive(kind, `Unexpected instruction kind \`${kind}\``); } } } else if (instr.value.kind === "StartMemoize" || instr.value.kind === "FinishMemoize") { return null; } else if (instr.value.kind === "Debugger") { return t3.debuggerStatement(); } else if (instr.value.kind === "ObjectMethod") { CompilerError.invariant(instr.lvalue, { reason: "Expected object methods to have a temp lvalue", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); cx.objectMethods.set(instr.lvalue.identifier.id, instr.value); return null; } else { const value = codegenInstructionValue(cx, instr.value); const statement = codegenInstruction(cx, instr, value); if (statement.type === "EmptyStatement") { return null; } return statement; } } function codegenForInit(cx, init) { if (init.kind === "SequenceExpression") { const body = codegenBlock( cx, init.instructions.map((instruction) => ({ kind: "instruction", instruction })) ).body; const declarators = []; let kind = "const"; body.forEach((instr) => { var _a; let top = void 0; if (instr.type === "ExpressionStatement" && instr.expression.type === "AssignmentExpression" && instr.expression.operator === "=" && instr.expression.left.type === "Identifier" && ((_a = top = declarators.at(-1)) == null ? void 0 : _a.id.type) === "Identifier" && (top == null ? void 0 : top.id.name) === instr.expression.left.name && (top == null ? void 0 : top.init) == null) { top.init = instr.expression.right; } else { CompilerError.invariant( instr.type === "VariableDeclaration" && (instr.kind === "let" || instr.kind === "const"), { reason: "Expected a variable declaration", details: [ { kind: "error", loc: init.loc, message: null } ], description: `Got ${instr.type}`, suggestions: null } ); if (instr.kind === "let") { kind = "let"; } declarators.push(...instr.declarations); } }); CompilerError.invariant(declarators.length > 0, { reason: "Expected a variable declaration", details: [ { kind: "error", loc: init.loc, message: null } ], description: null, suggestions: null }); return t3.variableDeclaration(kind, declarators); } else { return codegenInstructionValueToExpression(cx, init); } } function printDependencyComment(dependency) { const identifier4 = convertIdentifier(dependency.identifier); let name = identifier4.name; if (dependency.path !== null) { for (const path of dependency.path) { name += `.${path.property}`; } } return name; } function printDelimitedCommentList(items, finalCompletion) { if (items.length === 2) { return items.join(` ${finalCompletion} `); } else if (items.length <= 1) { return items.join(""); } let output = []; for (let i = 0; i < items.length; i++) { const item = items[i]; if (i < items.length - 2) { output.push(`${item}, `); } else if (i === items.length - 2) { output.push(`${item}, ${finalCompletion} `); } else { output.push(item); } } return output.join(""); } function codegenDependency(cx, dependency) { let object2 = convertIdentifier(dependency.identifier); if (dependency.path.length !== 0) { const hasOptional = dependency.path.some((path) => path.optional); for (const path of dependency.path) { const property = typeof path.property === "string" ? t3.identifier(path.property) : t3.numericLiteral(path.property); const isComputed = typeof path.property !== "string"; if (hasOptional) { object2 = t3.optionalMemberExpression( object2, property, isComputed, path.optional ); } else { object2 = t3.memberExpression(object2, property, isComputed); } } } return object2; } function withLoc(fn) { return (loc, ...args) => { const node = fn(...args); if (loc != null && loc != GeneratedSource) { node.loc = loc; } return node; }; } var createBinaryExpression = withLoc(t3.binaryExpression); var createExpressionStatement = withLoc(t3.expressionStatement); var _createLabelledStatement = withLoc(t3.labeledStatement); var createVariableDeclaration = withLoc(t3.variableDeclaration); var createFunctionDeclaration = withLoc(t3.functionDeclaration); var createWhileStatement = withLoc(t3.whileStatement); var createDoWhileStatement = withLoc(t3.doWhileStatement); var createSwitchStatement = withLoc(t3.switchStatement); var createIfStatement = withLoc(t3.ifStatement); var createForStatement = withLoc(t3.forStatement); var createForOfStatement = withLoc(t3.forOfStatement); var createForInStatement = withLoc(t3.forInStatement); var createTaggedTemplateExpression = withLoc(t3.taggedTemplateExpression); var createLogicalExpression = withLoc(t3.logicalExpression); var createSequenceExpression = withLoc(t3.sequenceExpression); var createConditionalExpression = withLoc(t3.conditionalExpression); var createTemplateLiteral = withLoc(t3.templateLiteral); var createJsxNamespacedName = withLoc(t3.jsxNamespacedName); var createJsxElement = withLoc(t3.jsxElement); var createJsxAttribute = withLoc(t3.jsxAttribute); var createJsxIdentifier = withLoc(t3.jsxIdentifier); var createJsxExpressionContainer = withLoc(t3.jsxExpressionContainer); var createJsxText = withLoc(t3.jsxText); var createJsxClosingElement = withLoc(t3.jsxClosingElement); var createJsxOpeningElement = withLoc(t3.jsxOpeningElement); var createStringLiteral = withLoc(t3.stringLiteral); var createThrowStatement = withLoc(t3.throwStatement); var createTryStatement = withLoc(t3.tryStatement); var createBreakStatement = withLoc(t3.breakStatement); var createContinueStatement = withLoc(t3.continueStatement); function createHookGuard(guard, context, stmts, before, after) { const guardFnName = context.addImportSpecifier(guard).name; function createHookGuardImpl(kind) { return t3.expressionStatement( t3.callExpression(t3.identifier(guardFnName), [t3.numericLiteral(kind)]) ); } return t3.tryStatement( t3.blockStatement([createHookGuardImpl(before), ...stmts]), null, t3.blockStatement([createHookGuardImpl(after)]) ); } function createCallExpression(env, callee, args, loc, isHook2) { const callExpr = t3.callExpression(callee, args); if (loc != null && loc != GeneratedSource) { callExpr.loc = loc; } const hookGuard = env.config.enableEmitHookGuards; if (hookGuard != null && isHook2 && env.isInferredMemoEnabled) { const iife = t3.functionExpression( null, [], t3.blockStatement([ createHookGuard( hookGuard, env.programContext, [t3.returnStatement(callExpr)], 2 /* AllowHook */, 3 /* DisallowHook */ ) ]) ); return t3.callExpression(iife, []); } else { return callExpr; } } function codegenLabel(id) { return `bb${id}`; } function codegenInstruction(cx, instr, value) { if (t3.isStatement(value)) { return value; } if (instr.lvalue === null) { return t3.expressionStatement(convertValueToExpression(value)); } if (instr.lvalue.identifier.name === null) { cx.temp.set(instr.lvalue.identifier.declarationId, value); return t3.emptyStatement(); } else { const expressionValue = convertValueToExpression(value); if (cx.hasDeclared(instr.lvalue.identifier)) { return createExpressionStatement( instr.loc, t3.assignmentExpression( "=", convertIdentifier(instr.lvalue.identifier), expressionValue ) ); } else { return createVariableDeclaration(instr.loc, "const", [ t3.variableDeclarator( convertIdentifier(instr.lvalue.identifier), expressionValue ) ]); } } } function convertValueToExpression(value) { if (value.type === "JSXText") { return createStringLiteral(value.loc, value.value); } return value; } function codegenInstructionValueToExpression(cx, instrValue) { const value = codegenInstructionValue(cx, instrValue); return convertValueToExpression(value); } function codegenInstructionValue(cx, instrValue) { var _a, _b, _c, _d, _e, _f, _g; let value; switch (instrValue.kind) { case "ArrayExpression": { const elements = instrValue.elements.map((element) => { if (element.kind === "Identifier") { return codegenPlaceToExpression(cx, element); } else if (element.kind === "Spread") { return t3.spreadElement(codegenPlaceToExpression(cx, element.place)); } else { return null; } }); value = t3.arrayExpression(elements); break; } case "BinaryExpression": { const left = codegenPlaceToExpression(cx, instrValue.left); const right = codegenPlaceToExpression(cx, instrValue.right); value = createBinaryExpression( instrValue.loc, instrValue.operator, left, right ); break; } case "UnaryExpression": { value = t3.unaryExpression( instrValue.operator, codegenPlaceToExpression(cx, instrValue.value) ); break; } case "Primitive": { value = codegenValue(cx, instrValue.loc, instrValue.value); break; } case "CallExpression": { if (cx.env.config.enableForest) { const callee2 = codegenPlaceToExpression(cx, instrValue.callee); const args2 = instrValue.args.map((arg) => codegenArgument(cx, arg)); value = t3.callExpression(callee2, args2); if (instrValue.typeArguments != null) { value.typeArguments = t3.typeParameterInstantiation( instrValue.typeArguments ); } break; } const isHook2 = getHookKind(cx.env, instrValue.callee.identifier) != null; const callee = codegenPlaceToExpression(cx, instrValue.callee); const args = instrValue.args.map((arg) => codegenArgument(cx, arg)); value = createCallExpression( cx.env, callee, args, instrValue.loc, isHook2 ); break; } case "OptionalExpression": { const optionalValue = codegenInstructionValueToExpression( cx, instrValue.value ); switch (optionalValue.type) { case "OptionalCallExpression": case "CallExpression": { CompilerError.invariant(t3.isExpression(optionalValue.callee), { reason: "v8 intrinsics are validated during lowering", description: null, details: [ { kind: "error", loc: (_a = optionalValue.callee.loc) != null ? _a : null, message: null } ], suggestions: null }); value = t3.optionalCallExpression( optionalValue.callee, optionalValue.arguments, instrValue.optional ); break; } case "OptionalMemberExpression": case "MemberExpression": { const property = optionalValue.property; CompilerError.invariant(t3.isExpression(property), { reason: "Private names are validated during lowering", description: null, details: [ { kind: "error", loc: (_b = property.loc) != null ? _b : null, message: null } ], suggestions: null }); value = t3.optionalMemberExpression( optionalValue.object, property, optionalValue.computed, instrValue.optional ); break; } default: { CompilerError.invariant(false, { reason: "Expected an optional value to resolve to a call expression or member expression", description: `Got a \`${optionalValue.type}\``, details: [ { kind: "error", loc: instrValue.loc, message: null } ], suggestions: null }); } } break; } case "MethodCall": { const isHook2 = getHookKind(cx.env, instrValue.property.identifier) != null; const memberExpr = codegenPlaceToExpression(cx, instrValue.property); CompilerError.invariant( t3.isMemberExpression(memberExpr) || t3.isOptionalMemberExpression(memberExpr), { reason: "[Codegen] Internal error: MethodCall::property must be an unpromoted + unmemoized MemberExpression", description: null, details: [ { kind: "error", loc: (_c = memberExpr.loc) != null ? _c : null, message: `Got: '${memberExpr.type}'` } ], suggestions: null } ); CompilerError.invariant( t3.isNodesEquivalent( memberExpr.object, codegenPlaceToExpression(cx, instrValue.receiver) ), { reason: "[Codegen] Internal error: Forget should always generate MethodCall::property as a MemberExpression of MethodCall::receiver", description: null, details: [ { kind: "error", loc: (_d = memberExpr.loc) != null ? _d : null, message: null } ], suggestions: null } ); const args = instrValue.args.map((arg) => codegenArgument(cx, arg)); value = createCallExpression( cx.env, memberExpr, args, instrValue.loc, isHook2 ); break; } case "NewExpression": { const callee = codegenPlaceToExpression(cx, instrValue.callee); const args = instrValue.args.map((arg) => codegenArgument(cx, arg)); value = t3.newExpression(callee, args); break; } case "ObjectExpression": { const properties = []; for (const property of instrValue.properties) { if (property.kind === "ObjectProperty") { const key2 = codegenObjectPropertyKey(cx, property.key); switch (property.type) { case "property": { const value2 = codegenPlaceToExpression(cx, property.place); properties.push( t3.objectProperty( key2, value2, property.key.kind === "computed", key2.type === "Identifier" && value2.type === "Identifier" && value2.name === key2.name ) ); break; } case "method": { const method = cx.objectMethods.get(property.place.identifier.id); CompilerError.invariant(method, { reason: "Expected ObjectMethod instruction", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); const loweredFunc = method.loweredFunc; const reactiveFunction = buildReactiveFunction(loweredFunc.func); pruneUnusedLabels(reactiveFunction); pruneUnusedLValues(reactiveFunction); const fn = codegenReactiveFunction( new Context2( cx.env, (_e = reactiveFunction.id) != null ? _e : "[[ anonymous ]]", cx.uniqueIdentifiers, cx.fbtOperands, cx.temp ), reactiveFunction ).unwrap(); const babelNode = t3.objectMethod( "method", key2, fn.params, fn.body, false ); babelNode.async = fn.async; babelNode.generator = fn.generator; properties.push(babelNode); break; } default: assertExhaustive( property.type, `Unexpected property type: ${property.type}` ); } } else { properties.push( t3.spreadElement(codegenPlaceToExpression(cx, property.place)) ); } } value = t3.objectExpression(properties); break; } case "JSXText": { value = createJsxText(instrValue.loc, instrValue.value); break; } case "JsxExpression": { const attributes = []; for (const attribute of instrValue.props) { attributes.push(codegenJsxAttribute(cx, attribute)); } let tagValue = instrValue.tag.kind === "Identifier" ? codegenPlaceToExpression(cx, instrValue.tag) : t3.stringLiteral(instrValue.tag.name); let tag; if (tagValue.type === "Identifier") { tag = createJsxIdentifier(instrValue.tag.loc, tagValue.name); } else if (tagValue.type === "MemberExpression") { tag = convertMemberExpressionToJsx(tagValue); } else { CompilerError.invariant(tagValue.type === "StringLiteral", { reason: `Expected JSX tag to be an identifier or string, got \`${tagValue.type}\``, description: null, details: [ { kind: "error", loc: (_f = tagValue.loc) != null ? _f : null, message: null } ], suggestions: null }); if (tagValue.value.indexOf(":") >= 0) { const [namespace, name] = tagValue.value.split(":", 2); tag = createJsxNamespacedName( instrValue.tag.loc, createJsxIdentifier(instrValue.tag.loc, namespace), createJsxIdentifier(instrValue.tag.loc, name) ); } else { tag = createJsxIdentifier(instrValue.loc, tagValue.value); } } let children; if (tagValue.type === "StringLiteral" && SINGLE_CHILD_FBT_TAGS.has(tagValue.value)) { CompilerError.invariant(instrValue.children != null, { details: [ { kind: "error", loc: instrValue.loc, message: null } ], reason: "Expected fbt element to have children", suggestions: null, description: null }); children = instrValue.children.map( (child) => codegenJsxFbtChildElement(cx, child) ); } else { children = instrValue.children !== null ? instrValue.children.map((child) => codegenJsxElement(cx, child)) : []; } value = createJsxElement( instrValue.loc, createJsxOpeningElement( instrValue.openingLoc, tag, attributes, instrValue.children === null ), instrValue.children !== null ? createJsxClosingElement(instrValue.closingLoc, tag) : null, children, instrValue.children === null ); break; } case "JsxFragment": { value = t3.jsxFragment( t3.jsxOpeningFragment(), t3.jsxClosingFragment(), instrValue.children.map((child) => codegenJsxElement(cx, child)) ); break; } case "UnsupportedNode": { const node = instrValue.node; if (!t3.isExpression(node)) { return node; } value = node; break; } case "PropertyStore": case "PropertyLoad": case "PropertyDelete": { let memberExpr; if (typeof instrValue.property === "string") { memberExpr = t3.memberExpression( codegenPlaceToExpression(cx, instrValue.object), t3.identifier(instrValue.property) ); } else { memberExpr = t3.memberExpression( codegenPlaceToExpression(cx, instrValue.object), t3.numericLiteral(instrValue.property), true ); } if (instrValue.kind === "PropertyStore") { value = t3.assignmentExpression( "=", memberExpr, codegenPlaceToExpression(cx, instrValue.value) ); } else if (instrValue.kind === "PropertyLoad") { value = memberExpr; } else { value = t3.unaryExpression("delete", memberExpr); } break; } case "ComputedStore": { value = t3.assignmentExpression( "=", t3.memberExpression( codegenPlaceToExpression(cx, instrValue.object), codegenPlaceToExpression(cx, instrValue.property), true ), codegenPlaceToExpression(cx, instrValue.value) ); break; } case "ComputedLoad": { const object2 = codegenPlaceToExpression(cx, instrValue.object); const property = codegenPlaceToExpression(cx, instrValue.property); value = t3.memberExpression(object2, property, true); break; } case "ComputedDelete": { value = t3.unaryExpression( "delete", t3.memberExpression( codegenPlaceToExpression(cx, instrValue.object), codegenPlaceToExpression(cx, instrValue.property), true ) ); break; } case "LoadLocal": case "LoadContext": { value = codegenPlaceToExpression(cx, instrValue.place); break; } case "FunctionExpression": { const loweredFunc = instrValue.loweredFunc.func; const reactiveFunction = buildReactiveFunction(loweredFunc); pruneUnusedLabels(reactiveFunction); pruneUnusedLValues(reactiveFunction); pruneHoistedContexts(reactiveFunction); const fn = codegenReactiveFunction( new Context2( cx.env, (_g = reactiveFunction.id) != null ? _g : "[[ anonymous ]]", cx.uniqueIdentifiers, cx.fbtOperands, cx.temp ), reactiveFunction ).unwrap(); if (instrValue.type === "ArrowFunctionExpression") { let body = fn.body; if (body.body.length === 1 && loweredFunc.directives.length == 0) { const stmt = body.body[0]; if (stmt.type === "ReturnStatement" && stmt.argument != null) { body = stmt.argument; } } value = t3.arrowFunctionExpression(fn.params, body, fn.async); } else { value = t3.functionExpression( instrValue.name != null ? t3.identifier(instrValue.name) : null, fn.params, fn.body, fn.generator, fn.async ); } if (cx.env.config.enableNameAnonymousFunctions && instrValue.name == null && instrValue.nameHint != null) { const name = instrValue.nameHint; value = t3.memberExpression( t3.objectExpression([t3.objectProperty(t3.stringLiteral(name), value)]), t3.stringLiteral(name), true, false ); } break; } case "TaggedTemplateExpression": { value = createTaggedTemplateExpression( instrValue.loc, codegenPlaceToExpression(cx, instrValue.tag), t3.templateLiteral([t3.templateElement(instrValue.value)], []) ); break; } case "TypeCastExpression": { if (t3.isTSType(instrValue.typeAnnotation)) { if (instrValue.typeAnnotationKind === "satisfies") { value = t3.tsSatisfiesExpression( codegenPlaceToExpression(cx, instrValue.value), instrValue.typeAnnotation ); } else { value = t3.tsAsExpression( codegenPlaceToExpression(cx, instrValue.value), instrValue.typeAnnotation ); } } else { value = t3.typeCastExpression( codegenPlaceToExpression(cx, instrValue.value), t3.typeAnnotation(instrValue.typeAnnotation) ); } break; } case "LogicalExpression": { value = createLogicalExpression( instrValue.loc, instrValue.operator, codegenInstructionValueToExpression(cx, instrValue.left), codegenInstructionValueToExpression(cx, instrValue.right) ); break; } case "ConditionalExpression": { value = createConditionalExpression( instrValue.loc, codegenInstructionValueToExpression(cx, instrValue.test), codegenInstructionValueToExpression(cx, instrValue.consequent), codegenInstructionValueToExpression(cx, instrValue.alternate) ); break; } case "SequenceExpression": { const body = codegenBlockNoReset( cx, instrValue.instructions.map((instruction) => ({ kind: "instruction", instruction })) ).body; const expressions = body.map((stmt) => { var _a2, _b2; if (stmt.type === "ExpressionStatement") { return stmt.expression; } else { if (t3.isVariableDeclaration(stmt)) { const declarator = stmt.declarations[0]; cx.errors.push({ reason: `(CodegenReactiveFunction::codegenInstructionValue) Cannot declare variables in a value block, tried to declare '${declarator.id.name}'`, category: "Todo" /* Todo */, loc: (_a2 = declarator.loc) != null ? _a2 : null, suggestions: null }); return t3.stringLiteral(`TODO handle ${declarator.id}`); } else { cx.errors.push({ reason: `(CodegenReactiveFunction::codegenInstructionValue) Handle conversion of ${stmt.type} to expression`, category: "Todo" /* Todo */, loc: (_b2 = stmt.loc) != null ? _b2 : null, suggestions: null }); return t3.stringLiteral(`TODO handle ${stmt.type}`); } } }); if (expressions.length === 0) { value = codegenInstructionValueToExpression(cx, instrValue.value); } else { value = createSequenceExpression(instrValue.loc, [ ...expressions, codegenInstructionValueToExpression(cx, instrValue.value) ]); } break; } case "TemplateLiteral": { value = createTemplateLiteral( instrValue.loc, instrValue.quasis.map((q) => t3.templateElement(q)), instrValue.subexprs.map((p) => codegenPlaceToExpression(cx, p)) ); break; } case "LoadGlobal": { value = t3.identifier(instrValue.binding.name); break; } case "RegExpLiteral": { value = t3.regExpLiteral(instrValue.pattern, instrValue.flags); break; } case "MetaProperty": { value = t3.metaProperty( t3.identifier(instrValue.meta), t3.identifier(instrValue.property) ); break; } case "Await": { value = t3.awaitExpression(codegenPlaceToExpression(cx, instrValue.value)); break; } case "GetIterator": { value = codegenPlaceToExpression(cx, instrValue.collection); break; } case "IteratorNext": { value = codegenPlaceToExpression(cx, instrValue.iterator); break; } case "NextPropertyOf": { value = codegenPlaceToExpression(cx, instrValue.value); break; } case "PostfixUpdate": { value = t3.updateExpression( instrValue.operation, codegenPlaceToExpression(cx, instrValue.lvalue), false ); break; } case "PrefixUpdate": { value = t3.updateExpression( instrValue.operation, codegenPlaceToExpression(cx, instrValue.lvalue), true ); break; } case "StoreLocal": { CompilerError.invariant( instrValue.lvalue.kind === "Reassign" /* Reassign */, { reason: `Unexpected StoreLocal in codegenInstructionValue`, description: null, details: [ { kind: "error", loc: instrValue.loc, message: null } ], suggestions: null } ); value = t3.assignmentExpression( "=", codegenLValue(cx, instrValue.lvalue.place), codegenPlaceToExpression(cx, instrValue.value) ); break; } case "StoreGlobal": { value = t3.assignmentExpression( "=", t3.identifier(instrValue.name), codegenPlaceToExpression(cx, instrValue.value) ); break; } case "StartMemoize": case "FinishMemoize": case "Debugger": case "DeclareLocal": case "DeclareContext": case "Destructure": case "ObjectMethod": case "StoreContext": { CompilerError.invariant(false, { reason: `Unexpected ${instrValue.kind} in codegenInstructionValue`, description: null, details: [ { kind: "error", loc: instrValue.loc, message: null } ], suggestions: null }); } default: { assertExhaustive( instrValue, `Unexpected instruction value kind \`${instrValue.kind}\`` ); } } if (instrValue.loc != null && instrValue.loc != GeneratedSource) { value.loc = instrValue.loc; } return value; } var STRING_REQUIRES_EXPR_CONTAINER_PATTERN = /[\u{0000}-\u{001F}\u{007F}\u{0080}-\u{FFFF}\u{010000}-\u{10FFFF}]|"|\\/u; function codegenJsxAttribute(cx, attribute) { switch (attribute.kind) { case "JsxAttribute": { let propName; if (attribute.name.indexOf(":") === -1) { propName = createJsxIdentifier(attribute.place.loc, attribute.name); } else { const [namespace, name] = attribute.name.split(":", 2); propName = createJsxNamespacedName( attribute.place.loc, createJsxIdentifier(attribute.place.loc, namespace), createJsxIdentifier(attribute.place.loc, name) ); } const innerValue = codegenPlaceToExpression(cx, attribute.place); let value; switch (innerValue.type) { case "StringLiteral": { value = innerValue; if (STRING_REQUIRES_EXPR_CONTAINER_PATTERN.test(value.value) && !cx.fbtOperands.has(attribute.place.identifier.id)) { value = createJsxExpressionContainer(value.loc, value); } break; } default: { value = createJsxExpressionContainer(attribute.place.loc, innerValue); break; } } return createJsxAttribute(attribute.place.loc, propName, value); } case "JsxSpreadAttribute": { return t3.jsxSpreadAttribute( codegenPlaceToExpression(cx, attribute.argument) ); } default: { assertExhaustive( attribute, `Unexpected attribute kind \`${attribute.kind}\`` ); } } } var JSX_TEXT_CHILD_REQUIRES_EXPR_CONTAINER_PATTERN = /[<>&{}]/; function codegenJsxElement(cx, place) { const value = codegenPlace(cx, place); switch (value.type) { case "JSXText": { if (JSX_TEXT_CHILD_REQUIRES_EXPR_CONTAINER_PATTERN.test(value.value)) { return createJsxExpressionContainer( place.loc, createStringLiteral(place.loc, value.value) ); } return createJsxText(place.loc, value.value); } case "JSXElement": case "JSXFragment": { return value; } default: { return createJsxExpressionContainer(place.loc, value); } } } function codegenJsxFbtChildElement(cx, place) { const value = codegenPlace(cx, place); switch (value.type) { // fbt:param only allows JSX element or expression container as children case "JSXText": case "JSXElement": { return value; } default: { return createJsxExpressionContainer(place.loc, value); } } } function convertMemberExpressionToJsx(expr) { var _a, _b; CompilerError.invariant(expr.property.type === "Identifier", { reason: "Expected JSX member expression property to be a string", description: null, details: [ { kind: "error", loc: (_a = expr.loc) != null ? _a : null, message: null } ], suggestions: null }); const property = t3.jsxIdentifier(expr.property.name); if (expr.object.type === "Identifier") { return t3.jsxMemberExpression(t3.jsxIdentifier(expr.object.name), property); } else { CompilerError.invariant(expr.object.type === "MemberExpression", { reason: "Expected JSX member expression to be an identifier or nested member expression", description: null, details: [ { kind: "error", loc: (_b = expr.object.loc) != null ? _b : null, message: null } ], suggestions: null }); const object2 = convertMemberExpressionToJsx(expr.object); return t3.jsxMemberExpression(object2, property); } } function codegenObjectPropertyKey(cx, key2) { switch (key2.kind) { case "string": { return t3.stringLiteral(key2.name); } case "identifier": { return t3.identifier(key2.name); } case "computed": { const expr = codegenPlace(cx, key2.name); CompilerError.invariant(t3.isExpression(expr), { reason: "Expected object property key to be an expression", description: null, details: [ { kind: "error", loc: key2.name.loc, message: null } ], suggestions: null }); return expr; } case "number": { return t3.numericLiteral(key2.name); } } } function codegenArrayPattern(cx, pattern) { const hasHoles = !pattern.items.every((e) => e.kind !== "Hole"); if (hasHoles) { const result = t3.arrayPattern([]); for (const item of pattern.items) { if (item.kind === "Hole") { result.elements.push(null); } else { result.elements.push(codegenLValue(cx, item)); } } return result; } else { return t3.arrayPattern( pattern.items.map((item) => { if (item.kind === "Hole") { return null; } return codegenLValue(cx, item); }) ); } } function codegenLValue(cx, pattern) { switch (pattern.kind) { case "ArrayPattern": { return codegenArrayPattern(cx, pattern); } case "ObjectPattern": { return t3.objectPattern( pattern.properties.map((property) => { if (property.kind === "ObjectProperty") { const key2 = codegenObjectPropertyKey(cx, property.key); const value = codegenLValue(cx, property.place); return t3.objectProperty( key2, value, property.key.kind === "computed", key2.type === "Identifier" && value.type === "Identifier" && value.name === key2.name ); } else { return t3.restElement(codegenLValue(cx, property.place)); } }) ); } case "Spread": { return t3.restElement(codegenLValue(cx, pattern.place)); } case "Identifier": { return convertIdentifier(pattern.identifier); } default: { assertExhaustive( pattern, `Unexpected pattern kind \`${pattern.kind}\`` ); } } } function codegenValue(cx, loc, value) { if (typeof value === "number") { if (value < 0) { return t3.unaryExpression("-", t3.numericLiteral(-value), false); } else { return t3.numericLiteral(value); } } else if (typeof value === "boolean") { return t3.booleanLiteral(value); } else if (typeof value === "string") { return createStringLiteral(loc, value); } else if (value === null) { return t3.nullLiteral(); } else if (value === void 0) { return t3.identifier("undefined"); } else { assertExhaustive(value, "Unexpected primitive value kind"); } } function codegenArgument(cx, arg) { if (arg.kind === "Identifier") { return codegenPlaceToExpression(cx, arg); } else { return t3.spreadElement(codegenPlaceToExpression(cx, arg.place)); } } function codegenPlaceToExpression(cx, place) { const value = codegenPlace(cx, place); return convertValueToExpression(value); } function codegenPlace(cx, place) { let tmp = cx.temp.get(place.identifier.declarationId); if (tmp != null) { return tmp; } CompilerError.invariant(place.identifier.name !== null || tmp !== void 0, { reason: `[Codegen] No value found for temporary`, description: `Value for '${printPlace( place )}' was not set in the codegen context`, details: [ { kind: "error", loc: place.loc, message: null } ], suggestions: null }); const identifier4 = convertIdentifier(place.identifier); identifier4.loc = place.loc; return identifier4; } function convertIdentifier(identifier4) { CompilerError.invariant( identifier4.name !== null && identifier4.name.kind === "named", { reason: `Expected temporaries to be promoted to named identifiers in an earlier pass`, details: [ { kind: "error", loc: GeneratedSource, message: null } ], description: `identifier ${identifier4.id} is unnamed`, suggestions: null } ); return t3.identifier(identifier4.name.value); } function compareScopeDependency(a, b) { var _a, _b; CompilerError.invariant( ((_a = a.identifier.name) == null ? void 0 : _a.kind) === "named" && ((_b = b.identifier.name) == null ? void 0 : _b.kind) === "named", { reason: "[Codegen] Expected named identifier for dependency", description: null, details: [ { kind: "error", loc: a.identifier.loc, message: null } ] } ); const aName = [ a.identifier.name.value, ...a.path.map((entry) => `${entry.optional ? "?" : ""}${entry.property}`) ].join("."); const bName = [ b.identifier.name.value, ...b.path.map((entry) => `${entry.optional ? "?" : ""}${entry.property}`) ].join("."); if (aName < bName) return -1; else if (aName > bName) return 1; else return 0; } function compareScopeDeclaration(a, b) { var _a, _b; CompilerError.invariant( ((_a = a.identifier.name) == null ? void 0 : _a.kind) === "named" && ((_b = b.identifier.name) == null ? void 0 : _b.kind) === "named", { reason: "[Codegen] Expected named identifier for declaration", description: null, details: [ { kind: "error", loc: a.identifier.loc, message: null } ] } ); const aName = a.identifier.name.value; const bName = b.identifier.name.value; if (aName < bName) return -1; else if (aName > bName) return 1; else return 0; } // src/ReactiveScopes/ExtractScopeDeclarationsFromDestructuring.ts function extractScopeDeclarationsFromDestructuring(fn) { const state = new State2(fn.env); for (const param of fn.params) { const place = param.kind === "Identifier" ? param : param.place; state.declared.add(place.identifier.declarationId); } visitReactiveFunction(fn, new Visitor2(), state); } var State2 = class { constructor(env) { /** * We need to track which program variables are already declared to convert * declarations into reassignments, so we use DeclarationId */ this.declared = /* @__PURE__ */ new Set(); this.env = env; } }; var Visitor2 = class extends ReactiveFunctionTransform { visitScope(scope, state) { for (const [, declaration] of scope.scope.declarations) { state.declared.add(declaration.identifier.declarationId); } this.traverseScope(scope, state); } transformInstruction(instruction, state) { this.visitInstruction(instruction, state); if (instruction.value.kind === "Destructure") { const transformed = transformDestructuring( state, instruction, instruction.value ); if (transformed) { return { kind: "replace-many", value: transformed.map((instruction2) => ({ kind: "instruction", instruction: instruction2 })) }; } } return { kind: "keep" }; } }; function transformDestructuring(state, instr, destructure2) { let reassigned = /* @__PURE__ */ new Set(); let hasDeclaration = false; for (const place of eachPatternOperand(destructure2.lvalue.pattern)) { const isDeclared = state.declared.has(place.identifier.declarationId); if (isDeclared) { reassigned.add(place.identifier.id); } hasDeclaration || (hasDeclaration = !isDeclared); } if (reassigned.size === 0 || !hasDeclaration) { return null; } const instructions = []; const renamed = /* @__PURE__ */ new Map(); mapPatternOperands(destructure2.lvalue.pattern, (place) => { if (!reassigned.has(place.identifier.id)) { return place; } const temporary = clonePlaceToTemporary(state.env, place); promoteTemporary(temporary.identifier); renamed.set(place, temporary); return temporary; }); instructions.push(instr); for (const [original, temporary] of renamed) { instructions.push({ id: instr.id, lvalue: null, value: { kind: "StoreLocal", lvalue: { kind: "Reassign" /* Reassign */, place: original }, value: temporary, type: null, loc: destructure2.loc }, loc: instr.loc }); } return instructions; } // src/ReactiveScopes/MergeReactiveScopesThatInvalidateTogether.ts function mergeReactiveScopesThatInvalidateTogether(fn) { const lastUsageVisitor = new FindLastUsageVisitor(); visitReactiveFunction(fn, lastUsageVisitor, void 0); visitReactiveFunction(fn, new Transform(lastUsageVisitor.lastUsage), null); } var DEBUG2 = false; function log(msg) { if (DEBUG2) { console.log(msg); } } var FindLastUsageVisitor = class extends ReactiveFunctionVisitor { constructor() { super(...arguments); /* * TODO LeaveSSA: use IdentifierId for more precise tracking * Using DeclarationId is necessary for compatible output but produces suboptimal results * in cases where a scope defines a variable, but that version is never read and always * overwritten later. * see reassignment-separate-scopes.js for example */ this.lastUsage = /* @__PURE__ */ new Map(); } visitPlace(id, place, _state) { const previousUsage = this.lastUsage.get(place.identifier.declarationId); const lastUsage = previousUsage !== void 0 ? makeInstructionId(Math.max(previousUsage, id)) : id; this.lastUsage.set(place.identifier.declarationId, lastUsage); } }; var Transform = class extends ReactiveFunctionTransform { constructor(lastUsage) { super(); this.temporaries = /* @__PURE__ */ new Map(); this.lastUsage = lastUsage; } transformScope(scopeBlock, state) { this.visitScope(scopeBlock, scopeBlock.scope.dependencies); if (state !== null && areEqualDependencies(state, scopeBlock.scope.dependencies)) { return { kind: "replace-many", value: scopeBlock.instructions }; } else { return { kind: "keep" }; } } visitBlock(block, state) { var _a; this.traverseBlock(block, state); let current = null; const merged = []; function reset() { CompilerError.invariant(current !== null, { reason: "MergeConsecutiveScopes: expected current scope to be non-null if reset()", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); if (current.to > current.from + 1) { merged.push(current); } current = null; } for (let i = 0; i < block.length; i++) { const instr = block[i]; switch (instr.kind) { case "terminal": { if (current !== null) { log( `Reset scope @${current.block.scope.id} from terminal [${instr.terminal.id}]` ); reset(); } break; } case "pruned-scope": { if (current !== null) { log( `Reset scope @${current.block.scope.id} from pruned scope @${instr.scope.id}` ); reset(); } break; } case "instruction": { switch (instr.instruction.value.kind) { case "BinaryExpression": case "ComputedLoad": case "JSXText": case "LoadGlobal": case "LoadLocal": case "Primitive": case "PropertyLoad": case "TemplateLiteral": case "UnaryExpression": { if (current !== null && instr.instruction.lvalue !== null) { current.lvalues.add( instr.instruction.lvalue.identifier.declarationId ); if (instr.instruction.value.kind === "LoadLocal") { this.temporaries.set( instr.instruction.lvalue.identifier.declarationId, instr.instruction.value.place.identifier.declarationId ); } } break; } case "StoreLocal": { if (current !== null) { if (instr.instruction.value.lvalue.kind === "Const" /* Const */) { for (const lvalue of eachInstructionLValue( instr.instruction )) { current.lvalues.add(lvalue.identifier.declarationId); } this.temporaries.set( instr.instruction.value.lvalue.place.identifier.declarationId, (_a = this.temporaries.get( instr.instruction.value.value.identifier.declarationId )) != null ? _a : instr.instruction.value.value.identifier.declarationId ); } else { log( `Reset scope @${current.block.scope.id} from StoreLocal in [${instr.instruction.id}]` ); reset(); } } break; } default: { if (current !== null) { log( `Reset scope @${current.block.scope.id} from instruction [${instr.instruction.id}]` ); reset(); } } } break; } case "scope": { if (current !== null && canMergeScopes(current.block, instr, this.temporaries) && areLValuesLastUsedByScope( instr.scope, current.lvalues, this.lastUsage )) { log( `Can merge scope @${current.block.scope.id} with @${instr.scope.id}` ); current.block.scope.range.end = makeInstructionId( Math.max(current.block.scope.range.end, instr.scope.range.end) ); for (const [key2, value] of instr.scope.declarations) { current.block.scope.declarations.set(key2, value); } updateScopeDeclarations(current.block.scope, this.lastUsage); current.to = i + 1; current.lvalues.clear(); if (!scopeIsEligibleForMerging(instr)) { log( ` but scope @${instr.scope.id} doesnt guaranteed invalidate so it cannot merge further` ); reset(); } } else { if (current !== null) { log( `Reset scope @${current.block.scope.id}, not mergeable with subsequent scope @${instr.scope.id}` ); reset(); } if (scopeIsEligibleForMerging(instr)) { current = { block: instr, from: i, to: i + 1, lvalues: /* @__PURE__ */ new Set() }; } else { log( `scope @${instr.scope.id} doesnt guaranteed invalidate so it cannot merge further` ); } } break; } default: { assertExhaustive( instr, `Unexpected instruction kind \`${instr.kind}\`` ); } } } if (current !== null) { reset(); } if (merged.length) { log(`merged ${merged.length} scopes:`); for (const entry of merged) { log( printReactiveScopeSummary(entry.block.scope) + ` from=${entry.from} to=${entry.to}` ); } } if (merged.length === 0) { return; } const nextInstructions = []; let index = 0; for (const entry of merged) { if (index < entry.from) { nextInstructions.push(...block.slice(index, entry.from)); index = entry.from; } const mergedScope = block[entry.from]; CompilerError.invariant(mergedScope.kind === "scope", { reason: "MergeConsecutiveScopes: Expected scope starting index to be a scope", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); nextInstructions.push(mergedScope); index++; while (index < entry.to) { const instr = block[index++]; if (instr.kind === "scope") { mergedScope.instructions.push(...instr.instructions); mergedScope.scope.merged.add(instr.scope.id); } else { mergedScope.instructions.push(instr); } } } while (index < block.length) { nextInstructions.push(block[index++]); } block.length = 0; block.push(...nextInstructions); } }; function updateScopeDeclarations(scope, lastUsage) { for (const [id, decl] of scope.declarations) { const lastUsedAt = lastUsage.get(decl.identifier.declarationId); if (lastUsedAt < scope.range.end) { scope.declarations.delete(id); } } } function areLValuesLastUsedByScope(scope, lvalues, lastUsage) { for (const lvalue of lvalues) { const lastUsedAt = lastUsage.get(lvalue); if (lastUsedAt >= scope.range.end) { log(` lvalue ${lvalue} used after scope @${scope.id}, cannot merge`); return false; } } return true; } function canMergeScopes(current, next, temporaries) { if (current.scope.reassignments.size !== 0 || next.scope.reassignments.size !== 0) { log(` cannot merge, has reassignments`); return false; } if (areEqualDependencies(current.scope.dependencies, next.scope.dependencies)) { log(` canMergeScopes: dependencies are equal`); return true; } if (areEqualDependencies( new Set( [...current.scope.declarations.values()].map((declaration) => ({ identifier: declaration.identifier, reactive: true, path: [] })) ), next.scope.dependencies ) || next.scope.dependencies.size !== 0 && [...next.scope.dependencies].every( (dep) => dep.path.length === 0 && isAlwaysInvalidatingType(dep.identifier.type) && Iterable_some( current.scope.declarations.values(), (decl) => decl.identifier.declarationId === dep.identifier.declarationId || decl.identifier.declarationId === temporaries.get(dep.identifier.declarationId) ) )) { log(` outputs of prev are input to current`); return true; } log(` cannot merge scopes:`); log( ` ${printReactiveScopeSummary(current.scope)} ${[...current.scope.declarations.values()].map((decl) => decl.identifier.declarationId)}` ); log( ` ${printReactiveScopeSummary(next.scope)} ${[...next.scope.dependencies].map((dep) => { var _a; return `${dep.identifier.declarationId} ${(_a = temporaries.get(dep.identifier.declarationId)) != null ? _a : dep.identifier.declarationId}`; })}` ); return false; } function isAlwaysInvalidatingType(type) { switch (type.kind) { case "Object": { switch (type.shapeId) { case BuiltInArrayId: case BuiltInObjectId: case BuiltInFunctionId: case BuiltInJsxId: { return true; } } break; } case "Function": { return true; } } return false; } function areEqualDependencies(a, b) { if (a.size !== b.size) { return false; } for (const aValue of a) { let found = false; for (const bValue of b) { if (aValue.identifier.declarationId === bValue.identifier.declarationId && areEqualPaths(aValue.path, bValue.path)) { found = true; break; } } if (!found) { return false; } } return true; } function scopeIsEligibleForMerging(scopeBlock) { if (scopeBlock.scope.dependencies.size === 0) { return true; } return [...scopeBlock.scope.declarations].some( ([, decl]) => isAlwaysInvalidatingType(decl.identifier.type) ); } // src/ReactiveScopes/PromoteUsedTemporaries.ts var PromoteTemporaries = class extends ReactiveFunctionVisitor { visitScope(scopeBlock, state) { for (const dep of scopeBlock.scope.dependencies) { const { identifier: identifier4 } = dep; if (identifier4.name == null) { promoteIdentifier(identifier4, state); } } for (const [, declaration] of scopeBlock.scope.declarations) { if (declaration.identifier.name == null) { promoteIdentifier(declaration.identifier, state); } } this.traverseScope(scopeBlock, state); } visitPrunedScope(scopeBlock, state) { var _a; for (const [, declaration] of scopeBlock.scope.declarations) { if (declaration.identifier.name == null && ((_a = state.pruned.get(declaration.identifier.declarationId)) == null ? void 0 : _a.usedOutsideScope) === true) { promoteIdentifier(declaration.identifier, state); } } this.traversePrunedScope(scopeBlock, state); } visitParam(place, state) { if (place.identifier.name === null) { promoteIdentifier(place.identifier, state); } } visitValue(id, value, state) { this.traverseValue(id, value, state); if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") { this.visitHirFunction(value.loweredFunc.func, state); } } visitReactiveFunctionValue(_id, _dependencies2, fn, state) { for (const operand of fn.params) { const place = operand.kind === "Identifier" ? operand : operand.place; if (place.identifier.name === null) { promoteIdentifier(place.identifier, state); } } visitReactiveFunction(fn, this, state); } }; var PromoteAllInstancedOfPromotedTemporaries = class extends ReactiveFunctionVisitor { visitPlace(_id, place, state) { if (place.identifier.name === null && state.promoted.has(place.identifier.declarationId)) { promoteIdentifier(place.identifier, state); } } visitLValue(_id, _lvalue, _state) { this.visitPlace(_id, _lvalue, _state); } traverseScopeIdentifiers(scope, state) { for (const [, decl] of scope.declarations) { if (decl.identifier.name === null && state.promoted.has(decl.identifier.declarationId)) { promoteIdentifier(decl.identifier, state); } } for (const dep of scope.dependencies) { if (dep.identifier.name === null && state.promoted.has(dep.identifier.declarationId)) { promoteIdentifier(dep.identifier, state); } } for (const reassignment of scope.reassignments) { if (reassignment.name === null && state.promoted.has(reassignment.declarationId)) { promoteIdentifier(reassignment, state); } } } visitScope(scope, state) { this.traverseScope(scope, state); this.traverseScopeIdentifiers(scope.scope, state); } visitPrunedScope(scopeBlock, state) { this.traversePrunedScope(scopeBlock, state); this.traverseScopeIdentifiers(scopeBlock.scope, state); } visitReactiveFunctionValue(_id, _dependencies2, fn, state) { visitReactiveFunction(fn, this, state); } }; var CollectPromotableTemporaries = class extends ReactiveFunctionVisitor { constructor() { super(...arguments); this.activeScopes = []; } visitPlace(_id, place, state) { if (this.activeScopes.length !== 0 && state.pruned.has(place.identifier.declarationId)) { const prunedPlace = state.pruned.get(place.identifier.declarationId); if (prunedPlace.activeScopes.indexOf(this.activeScopes.at(-1)) === -1) { prunedPlace.usedOutsideScope = true; } } } visitValue(id, value, state) { this.traverseValue(id, value, state); if (value.kind === "JsxExpression" && value.tag.kind === "Identifier") { state.tags.add(value.tag.identifier.declarationId); } } visitPrunedScope(scopeBlock, state) { for (const [_id, decl] of scopeBlock.scope.declarations) { state.pruned.set(decl.identifier.declarationId, { activeScopes: [...this.activeScopes], usedOutsideScope: false }); } this.visitBlock(scopeBlock.instructions, state); } visitScope(scopeBlock, state) { this.activeScopes.push(scopeBlock.scope.id); this.traverseScope(scopeBlock, state); this.activeScopes.pop(); } }; var _promotable, _consts, _globals2; var PromoteInterposedTemporaries = class extends ReactiveFunctionVisitor { /* * Unpromoted temporaries will be emitted at their use sites rather than as separate * declarations. However, this causes errors if an interposing temporary has been * promoted, or if an interposing instruction has had its lvalues deleted, because such * temporaries will be emitted as separate statements, which can effectively cause * code to be reordered, and when that code has side effects that changes program behavior. * This visitor promotes temporarties that have such interposing instructions to preserve * source ordering. */ constructor(promotable, params) { super(); __privateAdd(this, _promotable); __privateAdd(this, _consts, /* @__PURE__ */ new Set()); __privateAdd(this, _globals2, /* @__PURE__ */ new Set()); params.forEach((param) => { switch (param.kind) { case "Identifier": __privateGet(this, _consts).add(param.identifier.id); break; case "Spread": __privateGet(this, _consts).add(param.place.identifier.id); break; } }); __privateSet(this, _promotable, promotable); } visitPlace(_id, place, state) { const promo = state.get(place.identifier.id); if (promo) { const [identifier4, needsPromotion] = promo; if (needsPromotion && identifier4.name === null && !__privateGet(this, _consts).has(identifier4.id)) { promoteIdentifier(identifier4, __privateGet(this, _promotable)); } } } visitInstruction(instruction, state) { for (const lval of eachInstructionValueLValue(instruction.value)) { CompilerError.invariant(lval.identifier.name != null, { reason: "PromoteInterposedTemporaries: Assignment targets not expected to be temporaries", description: null, details: [ { kind: "error", loc: instruction.loc, message: null } ] }); } switch (instruction.value.kind) { case "CallExpression": case "MethodCall": case "Await": case "PropertyStore": case "PropertyDelete": case "ComputedStore": case "ComputedDelete": case "PostfixUpdate": case "PrefixUpdate": case "StoreLocal": case "StoreContext": case "StoreGlobal": case "Destructure": { let constStore = false; if ((instruction.value.kind === "StoreContext" || instruction.value.kind === "StoreLocal") && (instruction.value.lvalue.kind === "Const" || instruction.value.lvalue.kind === "HoistedConst")) { __privateGet(this, _consts).add(instruction.value.lvalue.place.identifier.id); constStore = true; } if (instruction.value.kind === "Destructure" && (instruction.value.lvalue.kind === "Const" || instruction.value.lvalue.kind === "HoistedConst")) { [...eachPatternOperand(instruction.value.lvalue.pattern)].forEach( (ident) => __privateGet(this, _consts).add(ident.identifier.id) ); constStore = true; } if (instruction.value.kind === "MethodCall") { __privateGet(this, _consts).add(instruction.value.property.identifier.id); } super.visitInstruction(instruction, state); if (!constStore && (instruction.lvalue == null || instruction.lvalue.identifier.name != null)) { for (const [key2, [ident, _]] of state.entries()) { state.set(key2, [ident, true]); } } if (instruction.lvalue && instruction.lvalue.identifier.name === null) { state.set(instruction.lvalue.identifier.id, [ instruction.lvalue.identifier, false ]); } break; } case "DeclareContext": case "DeclareLocal": { if (instruction.value.lvalue.kind === "Const" || instruction.value.lvalue.kind === "HoistedConst") { __privateGet(this, _consts).add(instruction.value.lvalue.place.identifier.id); } super.visitInstruction(instruction, state); break; } case "LoadContext": case "LoadLocal": { if (instruction.lvalue && instruction.lvalue.identifier.name === null) { if (__privateGet(this, _consts).has(instruction.value.place.identifier.id)) { __privateGet(this, _consts).add(instruction.lvalue.identifier.id); } state.set(instruction.lvalue.identifier.id, [ instruction.lvalue.identifier, false ]); } super.visitInstruction(instruction, state); break; } case "PropertyLoad": case "ComputedLoad": { if (instruction.lvalue) { if (__privateGet(this, _globals2).has(instruction.value.object.identifier.id)) { __privateGet(this, _globals2).add(instruction.lvalue.identifier.id); __privateGet(this, _consts).add(instruction.lvalue.identifier.id); } if (instruction.lvalue.identifier.name === null) { state.set(instruction.lvalue.identifier.id, [ instruction.lvalue.identifier, false ]); } } super.visitInstruction(instruction, state); break; } case "LoadGlobal": { instruction.lvalue && __privateGet(this, _globals2).add(instruction.lvalue.identifier.id); super.visitInstruction(instruction, state); break; } default: { super.visitInstruction(instruction, state); } } } }; _promotable = new WeakMap(); _consts = new WeakMap(); _globals2 = new WeakMap(); function promoteUsedTemporaries(fn) { const state = { tags: /* @__PURE__ */ new Set(), promoted: /* @__PURE__ */ new Set(), pruned: /* @__PURE__ */ new Map() }; visitReactiveFunction(fn, new CollectPromotableTemporaries(), state); for (const operand of fn.params) { const place = operand.kind === "Identifier" ? operand : operand.place; if (place.identifier.name === null) { promoteIdentifier(place.identifier, state); } } visitReactiveFunction(fn, new PromoteTemporaries(), state); visitReactiveFunction( fn, new PromoteInterposedTemporaries(state, fn.params), /* @__PURE__ */ new Map() ); visitReactiveFunction( fn, new PromoteAllInstancedOfPromotedTemporaries(), state ); } function promoteIdentifier(identifier4, state) { CompilerError.invariant(identifier4.name === null, { reason: "promoteTemporary: Expected to be called only for temporary variables", description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ], suggestions: null }); if (state.tags.has(identifier4.declarationId)) { promoteTemporaryJsxTag(identifier4); } else { promoteTemporary(identifier4); } state.promoted.add(identifier4.declarationId); } // src/ReactiveScopes/PropagateEarlyReturns.ts function propagateEarlyReturns(fn) { visitReactiveFunction(fn, new Transform2(fn.env), { withinReactiveScope: false, earlyReturnValue: null }); } var Transform2 = class extends ReactiveFunctionTransform { constructor(env) { super(); this.env = env; } visitScope(scopeBlock, parentState) { if (scopeBlock.scope.earlyReturnValue !== null) { return; } const innerState = { withinReactiveScope: true, earlyReturnValue: parentState.earlyReturnValue }; this.traverseScope(scopeBlock, innerState); const earlyReturnValue = innerState.earlyReturnValue; if (earlyReturnValue !== null) { if (!parentState.withinReactiveScope) { scopeBlock.scope.earlyReturnValue = earlyReturnValue; scopeBlock.scope.declarations.set(earlyReturnValue.value.id, { identifier: earlyReturnValue.value, scope: scopeBlock.scope }); const instructions = scopeBlock.instructions; const loc = earlyReturnValue.loc; const sentinelTemp = createTemporaryPlace(this.env, loc); const symbolTemp = createTemporaryPlace(this.env, loc); const forTemp = createTemporaryPlace(this.env, loc); const argTemp = createTemporaryPlace(this.env, loc); scopeBlock.instructions = [ { kind: "instruction", instruction: { id: makeInstructionId(0), loc, lvalue: __spreadValues({}, symbolTemp), value: { kind: "LoadGlobal", binding: { kind: "Global", name: "Symbol" }, loc } } }, { kind: "instruction", instruction: { id: makeInstructionId(0), loc, lvalue: __spreadValues({}, forTemp), value: { kind: "PropertyLoad", object: __spreadValues({}, symbolTemp), property: makePropertyLiteral("for"), loc } } }, { kind: "instruction", instruction: { id: makeInstructionId(0), loc, lvalue: __spreadValues({}, argTemp), value: { kind: "Primitive", value: EARLY_RETURN_SENTINEL, loc } } }, { kind: "instruction", instruction: { id: makeInstructionId(0), loc, lvalue: __spreadValues({}, sentinelTemp), value: { kind: "MethodCall", receiver: symbolTemp, property: forTemp, args: [argTemp], loc } } }, { kind: "instruction", instruction: { id: makeInstructionId(0), loc, lvalue: null, value: { kind: "StoreLocal", loc, type: null, lvalue: { kind: "Let" /* Let */, place: { kind: "Identifier", effect: "mutate?" /* ConditionallyMutate */, loc, reactive: true, identifier: earlyReturnValue.value } }, value: __spreadValues({}, sentinelTemp) } } }, { kind: "terminal", label: { id: earlyReturnValue.label, implicit: false }, terminal: { kind: "label", id: makeInstructionId(0), loc: GeneratedSource, block: instructions } } ]; } else { parentState.earlyReturnValue = earlyReturnValue; } } } transformTerminal(stmt, state) { if (state.withinReactiveScope && stmt.terminal.kind === "return") { const loc = stmt.terminal.value.loc; let earlyReturnValue; if (state.earlyReturnValue !== null) { earlyReturnValue = state.earlyReturnValue; } else { const identifier4 = createTemporaryPlace(this.env, loc).identifier; promoteTemporary(identifier4); earlyReturnValue = { label: this.env.nextBlockId, loc, value: identifier4 }; } state.earlyReturnValue = earlyReturnValue; return { kind: "replace-many", value: [ { kind: "instruction", instruction: { id: makeInstructionId(0), loc, lvalue: null, value: { kind: "StoreLocal", loc, type: null, lvalue: { kind: "Reassign" /* Reassign */, place: { kind: "Identifier", identifier: earlyReturnValue.value, effect: "capture" /* Capture */, loc, reactive: true } }, value: stmt.terminal.value } } }, { kind: "terminal", label: null, terminal: { kind: "break", id: makeInstructionId(0), loc, targetKind: "labeled", target: earlyReturnValue.label } } ] }; } this.traverseTerminal(stmt, state); return { kind: "keep" }; } }; // src/Utils/Stack.ts function empty() { return EMPTY; } var _value, _next; var _Node = class _Node { constructor(value, next = EMPTY) { __privateAdd(this, _value); __privateAdd(this, _next); __privateSet(this, _value, value); __privateSet(this, _next, next); } push(value) { return new _Node(value, this); } pop() { return __privateGet(this, _next); } find(fn) { return fn(__privateGet(this, _value)) ? true : __privateGet(this, _next).find(fn); } contains(value) { return value === __privateGet(this, _value) || __privateGet(this, _next) !== null && __privateGet(this, _next).contains(value); } each(fn) { fn(__privateGet(this, _value)); __privateGet(this, _next).each(fn); } get value() { return __privateGet(this, _value); } print(fn) { return fn(__privateGet(this, _value)) + __privateGet(this, _next).print(fn); } }; _value = new WeakMap(); _next = new WeakMap(); var Node = _Node; var Empty = class { push(value) { return new Node(value, this); } pop() { return this; } find(_fn) { return false; } contains(_value2) { return false; } each(_fn) { return; } get value() { return null; } print(_) { return ""; } }; var EMPTY = new Empty(); // src/ReactiveScopes/PruneHoistedContexts.ts function pruneHoistedContexts(fn) { visitReactiveFunction(fn, new Visitor3(), { activeScopes: empty(), uninitialized: /* @__PURE__ */ new Map() }); } var Visitor3 = class extends ReactiveFunctionTransform { visitScope(scope, state) { state.activeScopes = state.activeScopes.push( new Set(scope.scope.declarations.keys()) ); for (const decl of scope.scope.declarations.values()) { state.uninitialized.set(decl.identifier.id, { kind: "unknown-kind" }); } this.traverseScope(scope, state); state.activeScopes.pop(); for (const decl of scope.scope.declarations.values()) { state.uninitialized.delete(decl.identifier.id); } } visitPlace(_id, place, state) { const maybeHoistedFn = state.uninitialized.get(place.identifier.id); if ((maybeHoistedFn == null ? void 0 : maybeHoistedFn.kind) === "func" && maybeHoistedFn.definition !== place) { CompilerError.throwTodo({ reason: "[PruneHoistedContexts] Rewrite hoisted function references", loc: place.loc }); } } transformInstruction(instruction, state) { if (instruction.value.kind === "DeclareContext") { const maybeNonHoisted = convertHoistedLValueKind( instruction.value.lvalue.kind ); if (maybeNonHoisted != null) { if (maybeNonHoisted === "Function" /* Function */ && state.uninitialized.has(instruction.value.lvalue.place.identifier.id)) { state.uninitialized.set( instruction.value.lvalue.place.identifier.id, { kind: "func", definition: null } ); } return { kind: "remove" }; } } if (instruction.value.kind === "StoreContext" && instruction.value.lvalue.kind !== "Reassign" /* Reassign */) { const lvalueId = instruction.value.lvalue.place.identifier.id; const isDeclaredByScope = state.activeScopes.find( (scope) => scope.has(lvalueId) ); if (isDeclaredByScope) { if (instruction.value.lvalue.kind === "Let" /* Let */ || instruction.value.lvalue.kind === "Const" /* Const */) { instruction.value.lvalue.kind = "Reassign" /* Reassign */; } else if (instruction.value.lvalue.kind === "Function" /* Function */) { const maybeHoistedFn = state.uninitialized.get(lvalueId); if (maybeHoistedFn != null) { CompilerError.invariant(maybeHoistedFn.kind === "func", { reason: "[PruneHoistedContexts] Unexpected hoisted function", description: null, details: [ { kind: "error", loc: instruction.loc, message: null } ] }); maybeHoistedFn.definition = instruction.value.lvalue.place; state.uninitialized.delete(lvalueId); } } else { CompilerError.throwTodo({ reason: "[PruneHoistedContexts] Unexpected kind", description: `(${instruction.value.lvalue.kind})`, loc: instruction.loc }); } } } this.visitInstruction(instruction, state); return { kind: "keep" }; } }; // src/Inference/InferMutationAliasingEffects.ts var import_pretty_format2 = __toESM(require_build()); // src/Inference/AliasingEffects.ts function hashEffect(effect) { var _a; switch (effect.kind) { case "Apply": { return [ effect.kind, effect.receiver.identifier.id, effect.function.identifier.id, effect.mutatesFunction, effect.args.map((a) => { if (a.kind === "Hole") { return ""; } else if (a.kind === "Identifier") { return a.identifier.id; } else { return `...${a.place.identifier.id}`; } }).join(","), effect.into.identifier.id ].join(":"); } case "CreateFrom": case "ImmutableCapture": case "Assign": case "Alias": case "Capture": case "MaybeAlias": { return [ effect.kind, effect.from.identifier.id, effect.into.identifier.id ].join(":"); } case "Create": { return [ effect.kind, effect.into.identifier.id, effect.value, effect.reason ].join(":"); } case "Freeze": { return [effect.kind, effect.value.identifier.id, effect.reason].join(":"); } case "Impure": case "Render": { return [effect.kind, effect.place.identifier.id].join(":"); } case "MutateFrozen": case "MutateGlobal": { return [ effect.kind, effect.place.identifier.id, effect.error.severity, effect.error.reason, effect.error.description, printSourceLocation((_a = effect.error.primaryLocation()) != null ? _a : GeneratedSource) ].join(":"); } case "Mutate": case "MutateConditionally": case "MutateTransitive": case "MutateTransitiveConditionally": { return [effect.kind, effect.value.identifier.id].join(":"); } case "CreateFunction": { return [ effect.kind, effect.into.identifier.id, // return places are a unique way to identify functions themselves effect.function.loweredFunc.func.returns.identifier.id, effect.captures.map((p) => p.identifier.id).join(",") ].join(":"); } } } // src/Inference/InferMutationAliasingEffects.ts var DEBUG3 = false; function inferMutationAliasingEffects(fn, { isFunctionExpression } = { isFunctionExpression: false }) { const initialState = InferenceState.empty(fn.env, isFunctionExpression); const statesByBlock = /* @__PURE__ */ new Map(); for (const ref of fn.context) { const value = { kind: "ObjectExpression", properties: [], loc: ref.loc }; initialState.initialize(value, { kind: "context" /* Context */, reason: /* @__PURE__ */ new Set(["other" /* Other */]) }); initialState.define(ref, value); } const paramKind = isFunctionExpression ? { kind: "mutable" /* Mutable */, reason: /* @__PURE__ */ new Set(["other" /* Other */]) } : { kind: "frozen" /* Frozen */, reason: /* @__PURE__ */ new Set(["reactive-function-argument" /* ReactiveFunctionArgument */]) }; if (fn.fnType === "Component") { CompilerError.invariant(fn.params.length <= 2, { reason: "Expected React component to have not more than two parameters: one for props and for ref", description: null, details: [ { kind: "error", loc: fn.loc, message: null } ], suggestions: null }); const [props, ref] = fn.params; if (props != null) { inferParam(props, initialState, paramKind); } if (ref != null) { const place = ref.kind === "Identifier" ? ref : ref.place; const value = { kind: "ObjectExpression", properties: [], loc: place.loc }; initialState.initialize(value, { kind: "mutable" /* Mutable */, reason: /* @__PURE__ */ new Set(["other" /* Other */]) }); initialState.define(place, value); } } else { for (const param of fn.params) { inferParam(param, initialState, paramKind); } } const queuedStates = /* @__PURE__ */ new Map(); function queue(blockId, state) { var _a; let queuedState = queuedStates.get(blockId); if (queuedState != null) { state = (_a = queuedState.merge(state)) != null ? _a : queuedState; queuedStates.set(blockId, state); } else { const prevState = statesByBlock.get(blockId); const nextState = prevState != null ? prevState.merge(state) : state; if (nextState != null) { queuedStates.set(blockId, nextState); } } } queue(fn.body.entry, initialState); const hoistedContextDeclarations = findHoistedContextDeclarations(fn); const context = new Context3( isFunctionExpression, fn, hoistedContextDeclarations ); let iterationCount = 0; while (queuedStates.size !== 0) { iterationCount++; if (iterationCount > 100) { CompilerError.invariant(false, { reason: `[InferMutationAliasingEffects] Potential infinite loop`, description: `A value, temporary place, or effect was not cached properly`, details: [ { kind: "error", loc: fn.loc, message: null } ] }); } for (const [blockId, block] of fn.body.blocks) { const incomingState = queuedStates.get(blockId); queuedStates.delete(blockId); if (incomingState == null) { continue; } statesByBlock.set(blockId, incomingState); const state = incomingState.clone(); inferBlock(context, state, block); for (const nextBlockId of eachTerminalSuccessor(block.terminal)) { queue(nextBlockId, state); } } } return Ok(void 0); } function findHoistedContextDeclarations(fn) { const hoisted = /* @__PURE__ */ new Map(); function visit4(place) { if (hoisted.has(place.identifier.declarationId) && hoisted.get(place.identifier.declarationId) == null) { hoisted.set(place.identifier.declarationId, place); } } for (const block of fn.body.blocks.values()) { for (const instr of block.instructions) { if (instr.value.kind === "DeclareContext") { const kind = instr.value.lvalue.kind; if (kind == "HoistedConst" /* HoistedConst */ || kind == "HoistedFunction" /* HoistedFunction */ || kind == "HoistedLet" /* HoistedLet */) { hoisted.set(instr.value.lvalue.place.identifier.declarationId, null); } } else { for (const operand of eachInstructionValueOperand(instr.value)) { visit4(operand); } } } for (const operand of eachTerminalOperand(block.terminal)) { visit4(operand); } } return hoisted; } var Context3 = class { constructor(isFunctionExpression, fn, hoistedContextDeclarations) { this.internedEffects = /* @__PURE__ */ new Map(); this.instructionSignatureCache = /* @__PURE__ */ new Map(); this.effectInstructionValueCache = /* @__PURE__ */ new Map(); this.applySignatureCache = /* @__PURE__ */ new Map(); this.catchHandlers = /* @__PURE__ */ new Map(); this.functionSignatureCache = /* @__PURE__ */ new Map(); this.isFuctionExpression = isFunctionExpression; this.fn = fn; this.hoistedContextDeclarations = hoistedContextDeclarations; } cacheApplySignature(signature, effect, f) { const inner = getOrInsertDefault( this.applySignatureCache, signature, /* @__PURE__ */ new Map() ); return getOrInsertWith(inner, effect, f); } internEffect(effect) { const hash2 = hashEffect(effect); let interned = this.internedEffects.get(hash2); if (interned == null) { this.internedEffects.set(hash2, effect); interned = effect; } return interned; } }; function inferParam(param, initialState, paramKind) { const place = param.kind === "Identifier" ? param : param.place; const value = { kind: "Primitive", loc: place.loc, value: void 0 }; initialState.initialize(value, paramKind); initialState.define(place, value); } function inferBlock(context, state, block) { for (const phi of block.phis) { state.inferPhi(phi); } for (const instr of block.instructions) { let instructionSignature = context.instructionSignatureCache.get(instr); if (instructionSignature == null) { instructionSignature = computeSignatureForInstruction( context, state.env, instr ); context.instructionSignatureCache.set(instr, instructionSignature); } const effects = applySignature(context, state, instructionSignature, instr); instr.effects = effects; } const terminal = block.terminal; if (terminal.kind === "try" && terminal.handlerBinding != null) { context.catchHandlers.set(terminal.handler, terminal.handlerBinding); } else if (terminal.kind === "maybe-throw") { const handlerParam = context.catchHandlers.get(terminal.handler); if (handlerParam != null) { CompilerError.invariant(state.kind(handlerParam) != null, { reason: "Expected catch binding to be intialized with a DeclareLocal Catch instruction", description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); const effects = []; for (const instr of block.instructions) { if (instr.value.kind === "CallExpression" || instr.value.kind === "MethodCall") { state.appendAlias(handlerParam, instr.lvalue); const kind = state.kind(instr.lvalue).kind; if (kind === "mutable" /* Mutable */ || kind == "context" /* Context */) { effects.push( context.internEffect({ kind: "Alias", from: instr.lvalue, into: handlerParam }) ); } } } terminal.effects = effects.length !== 0 ? effects : null; } } else if (terminal.kind === "return") { if (!context.isFuctionExpression) { terminal.effects = [ context.internEffect({ kind: "Freeze", value: terminal.value, reason: "jsx-captured" /* JsxCaptured */ }) ]; } } } function applySignature(context, state, signature, instruction) { var _a, _b; const effects = []; if (instruction.value.kind === "FunctionExpression" || instruction.value.kind === "ObjectMethod") { const aliasingEffects = (_a = instruction.value.loweredFunc.func.aliasingEffects) != null ? _a : []; const context2 = new Set( instruction.value.loweredFunc.func.context.map((p) => p.identifier.id) ); for (const effect of aliasingEffects) { if (effect.kind === "Mutate" || effect.kind === "MutateTransitive") { if (!context2.has(effect.value.identifier.id)) { continue; } const value = state.kind(effect.value); switch (value.kind) { case "frozen" /* Frozen */: { const reason = getWriteErrorReason({ kind: value.kind, reason: value.reason }); const variable = effect.value.identifier.name !== null && effect.value.identifier.name.kind === "named" ? `\`${effect.value.identifier.name.value}\`` : "value"; const diagnostic = CompilerDiagnostic.create({ category: "Immutability" /* Immutability */, reason: "This value cannot be modified", description: reason }).withDetails({ kind: "error", loc: effect.value.loc, message: `${variable} cannot be modified` }); if (effect.kind === "Mutate" && ((_b = effect.reason) == null ? void 0 : _b.kind) === "AssignCurrentProperty") { diagnostic.withDetails({ kind: "hint", message: `Hint: If this value is a Ref (value returned by \`useRef()\`), rename the variable to end in "Ref".` }); } effects.push({ kind: "MutateFrozen", place: effect.value, error: diagnostic }); } } } } } const initialized = /* @__PURE__ */ new Set(); if (DEBUG3) { console.log(printInstruction(instruction)); } for (const effect of signature.effects) { applyEffect(context, state, effect, initialized, effects); } if (DEBUG3) { console.log( (0, import_pretty_format2.default)(state.debugAbstractValue(state.kind(instruction.lvalue))) ); console.log( effects.map((effect) => ` ${printAliasingEffect(effect)}`).join("\n") ); } if (!(state.isDefined(instruction.lvalue) && state.kind(instruction.lvalue))) { CompilerError.invariant(false, { reason: `Expected instruction lvalue to be initialized`, description: null, details: [ { kind: "error", loc: instruction.loc, message: null } ] }); } return effects.length !== 0 ? effects : null; } function applyEffect(context, state, _effect, initialized, effects) { var _a, _b, _c, _d, _e; const effect = context.internEffect(_effect); if (DEBUG3) { console.log(printAliasingEffect(effect)); } switch (effect.kind) { case "Freeze": { const didFreeze = state.freeze(effect.value, effect.reason); if (didFreeze) { effects.push(effect); } break; } case "Create": { CompilerError.invariant(!initialized.has(effect.into.identifier.id), { reason: `Cannot re-initialize variable within an instruction`, description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, details: [ { kind: "error", loc: effect.into.loc, message: null } ] }); initialized.add(effect.into.identifier.id); let value = context.effectInstructionValueCache.get(effect); if (value == null) { value = { kind: "ObjectExpression", properties: [], loc: effect.into.loc }; context.effectInstructionValueCache.set(effect, value); } state.initialize(value, { kind: effect.value, reason: /* @__PURE__ */ new Set([effect.reason]) }); state.define(effect.into, value); effects.push(effect); break; } case "ImmutableCapture": { const kind = state.kind(effect.from).kind; switch (kind) { case "global" /* Global */: case "primitive" /* Primitive */: { break; } default: { effects.push(effect); } } break; } case "CreateFrom": { CompilerError.invariant(!initialized.has(effect.into.identifier.id), { reason: `Cannot re-initialize variable within an instruction`, description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, details: [ { kind: "error", loc: effect.into.loc, message: null } ] }); initialized.add(effect.into.identifier.id); const fromValue = state.kind(effect.from); let value = context.effectInstructionValueCache.get(effect); if (value == null) { value = { kind: "ObjectExpression", properties: [], loc: effect.into.loc }; context.effectInstructionValueCache.set(effect, value); } state.initialize(value, { kind: fromValue.kind, reason: new Set(fromValue.reason) }); state.define(effect.into, value); switch (fromValue.kind) { case "primitive" /* Primitive */: case "global" /* Global */: { effects.push({ kind: "Create", value: fromValue.kind, into: effect.into, reason: (_a = [...fromValue.reason][0]) != null ? _a : "other" /* Other */ }); break; } case "frozen" /* Frozen */: { effects.push({ kind: "Create", value: fromValue.kind, into: effect.into, reason: (_b = [...fromValue.reason][0]) != null ? _b : "other" /* Other */ }); applyEffect( context, state, { kind: "ImmutableCapture", from: effect.from, into: effect.into }, initialized, effects ); break; } default: { effects.push(effect); } } break; } case "CreateFunction": { CompilerError.invariant(!initialized.has(effect.into.identifier.id), { reason: `Cannot re-initialize variable within an instruction`, description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, details: [ { kind: "error", loc: effect.into.loc, message: null } ] }); initialized.add(effect.into.identifier.id); effects.push(effect); const hasCaptures = effect.captures.some((capture) => { switch (state.kind(capture).kind) { case "context" /* Context */: case "mutable" /* Mutable */: { return true; } default: { return false; } } }); const hasTrackedSideEffects = (_c = effect.function.loweredFunc.func.aliasingEffects) == null ? void 0 : _c.some( (effect2) => ( // TODO; include "render" here? effect2.kind === "MutateFrozen" || effect2.kind === "MutateGlobal" || effect2.kind === "Impure" ) ); const capturesRef = effect.function.loweredFunc.func.context.some( (operand) => isRefOrRefValue(operand.identifier) ); const isMutable3 = hasCaptures || hasTrackedSideEffects || capturesRef; for (const operand of effect.function.loweredFunc.func.context) { if (operand.effect !== "capture" /* Capture */) { continue; } const kind = state.kind(operand).kind; if (kind === "primitive" /* Primitive */ || kind == "frozen" /* Frozen */ || kind == "global" /* Global */) { operand.effect = "read" /* Read */; } } state.initialize(effect.function, { kind: isMutable3 ? "mutable" /* Mutable */ : "frozen" /* Frozen */, reason: /* @__PURE__ */ new Set([]) }); state.define(effect.into, effect.function); for (const capture of effect.captures) { applyEffect( context, state, { kind: "Capture", from: capture, into: effect.into }, initialized, effects ); } break; } case "MaybeAlias": case "Alias": case "Capture": { CompilerError.invariant( effect.kind === "Capture" || effect.kind === "MaybeAlias" || initialized.has(effect.into.identifier.id), { reason: `Expected destination to already be initialized within this instruction`, description: `Destination ${printPlace(effect.into)} is not initialized in this instruction for effect ${printAliasingEffect(effect)}`, details: [ { kind: "error", loc: effect.into.loc, message: null } ] } ); const intoKind = state.kind(effect.into).kind; let destinationType = null; switch (intoKind) { case "context" /* Context */: { destinationType = "context"; break; } case "mutable" /* Mutable */: case "maybefrozen" /* MaybeFrozen */: { destinationType = "mutable"; break; } } const fromKind = state.kind(effect.from).kind; let sourceType = null; switch (fromKind) { case "context" /* Context */: { sourceType = "context"; break; } case "global" /* Global */: case "primitive" /* Primitive */: { break; } case "frozen" /* Frozen */: { sourceType = "frozen"; break; } default: { sourceType = "mutable"; break; } } if (sourceType === "frozen") { applyEffect( context, state, { kind: "ImmutableCapture", from: effect.from, into: effect.into }, initialized, effects ); } else if (sourceType === "mutable" && destinationType === "mutable" || effect.kind === "MaybeAlias") { effects.push(effect); } else if (sourceType === "context" && destinationType != null || sourceType === "mutable" && destinationType === "context") { applyEffect( context, state, { kind: "MaybeAlias", from: effect.from, into: effect.into }, initialized, effects ); } break; } case "Assign": { CompilerError.invariant(!initialized.has(effect.into.identifier.id), { reason: `Cannot re-initialize variable within an instruction`, description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, details: [ { kind: "error", loc: effect.into.loc, message: null } ] }); initialized.add(effect.into.identifier.id); const fromValue = state.kind(effect.from); const fromKind = fromValue.kind; switch (fromKind) { case "frozen" /* Frozen */: { applyEffect( context, state, { kind: "ImmutableCapture", from: effect.from, into: effect.into }, initialized, effects ); let value = context.effectInstructionValueCache.get(effect); if (value == null) { value = { kind: "Primitive", value: void 0, loc: effect.from.loc }; context.effectInstructionValueCache.set(effect, value); } state.initialize(value, { kind: fromKind, reason: new Set(fromValue.reason) }); state.define(effect.into, value); break; } case "global" /* Global */: case "primitive" /* Primitive */: { let value = context.effectInstructionValueCache.get(effect); if (value == null) { value = { kind: "Primitive", value: void 0, loc: effect.from.loc }; context.effectInstructionValueCache.set(effect, value); } state.initialize(value, { kind: fromKind, reason: new Set(fromValue.reason) }); state.define(effect.into, value); break; } default: { state.assign(effect.into, effect.from); effects.push(effect); break; } } break; } case "Apply": { const functionValues = state.values(effect.function); if (functionValues.length === 1 && functionValues[0].kind === "FunctionExpression" && functionValues[0].loweredFunc.func.aliasingEffects != null) { const functionExpr = functionValues[0]; let signature = context.functionSignatureCache.get(functionExpr); if (signature == null) { signature = buildSignatureFromFunctionExpression( state.env, functionExpr ); context.functionSignatureCache.set(functionExpr, signature); } if (DEBUG3) { console.log( `constructed alias signature: ${printAliasingSignature(signature)}` ); } const signatureEffects2 = context.cacheApplySignature( signature, effect, () => computeEffectsForSignature( state.env, signature, effect.into, effect.receiver, effect.args, functionExpr.loweredFunc.func.context, effect.loc ) ); if (signatureEffects2 != null) { applyEffect( context, state, { kind: "MutateTransitiveConditionally", value: effect.function }, initialized, effects ); for (const signatureEffect of signatureEffects2) { applyEffect(context, state, signatureEffect, initialized, effects); } break; } } let signatureEffects = null; if (((_d = effect.signature) == null ? void 0 : _d.aliasing) != null) { const signature = effect.signature.aliasing; signatureEffects = context.cacheApplySignature( effect.signature.aliasing, effect, () => computeEffectsForSignature( state.env, signature, effect.into, effect.receiver, effect.args, [], effect.loc ) ); } if (signatureEffects != null) { for (const signatureEffect of signatureEffects) { applyEffect(context, state, signatureEffect, initialized, effects); } } else if (effect.signature != null) { const legacyEffects = computeEffectsForLegacySignature( state, effect.signature, effect.into, effect.receiver, effect.args, effect.loc ); for (const legacyEffect of legacyEffects) { applyEffect(context, state, legacyEffect, initialized, effects); } } else { applyEffect( context, state, { kind: "Create", into: effect.into, value: "mutable" /* Mutable */, reason: "other" /* Other */ }, initialized, effects ); for (const arg of [effect.receiver, effect.function, ...effect.args]) { if (arg.kind === "Hole") { continue; } const operand = arg.kind === "Identifier" ? arg : arg.place; if (operand !== effect.function || effect.mutatesFunction) { applyEffect( context, state, { kind: "MutateTransitiveConditionally", value: operand }, initialized, effects ); } const mutateIterator = arg.kind === "Spread" ? conditionallyMutateIterator(operand) : null; if (mutateIterator) { applyEffect(context, state, mutateIterator, initialized, effects); } applyEffect( context, state, // OK: recording information flow { kind: "MaybeAlias", from: operand, into: effect.into }, initialized, effects ); for (const otherArg of [ effect.receiver, effect.function, ...effect.args ]) { if (otherArg.kind === "Hole") { continue; } const other = otherArg.kind === "Identifier" ? otherArg : otherArg.place; if (other === arg) { continue; } applyEffect( context, state, { /* * OK: a function might store one operand into another, * but it can't force one to alias another */ kind: "Capture", from: operand, into: other }, initialized, effects ); } } } break; } case "Mutate": case "MutateConditionally": case "MutateTransitive": case "MutateTransitiveConditionally": { const mutationKind = state.mutate(effect.kind, effect.value); if (mutationKind === "mutate") { effects.push(effect); } else if (mutationKind === "mutate-ref") { } else if (mutationKind !== "none" && (effect.kind === "Mutate" || effect.kind === "MutateTransitive")) { const value = state.kind(effect.value); if (DEBUG3) { console.log(`invalid mutation: ${printAliasingEffect(effect)}`); console.log((0, import_pretty_format2.default)(state.debugAbstractValue(value))); } if (mutationKind === "mutate-frozen" && context.hoistedContextDeclarations.has( effect.value.identifier.declarationId )) { const variable = effect.value.identifier.name !== null && effect.value.identifier.name.kind === "named" ? `\`${effect.value.identifier.name.value}\`` : null; const hoistedAccess = context.hoistedContextDeclarations.get( effect.value.identifier.declarationId ); const diagnostic = CompilerDiagnostic.create({ category: "Immutability" /* Immutability */, reason: "Cannot access variable before it is declared", description: `${variable != null ? variable : "This variable"} is accessed before it is declared, which prevents the earlier access from updating when this value changes over time` }); if (hoistedAccess != null && hoistedAccess.loc != effect.value.loc) { diagnostic.withDetails({ kind: "error", loc: hoistedAccess.loc, message: `${variable != null ? variable : "variable"} accessed before it is declared` }); } diagnostic.withDetails({ kind: "error", loc: effect.value.loc, message: `${variable != null ? variable : "variable"} is declared here` }); applyEffect( context, state, { kind: "MutateFrozen", place: effect.value, error: diagnostic }, initialized, effects ); } else { const reason = getWriteErrorReason({ kind: value.kind, reason: value.reason }); const variable = effect.value.identifier.name !== null && effect.value.identifier.name.kind === "named" ? `\`${effect.value.identifier.name.value}\`` : "value"; const diagnostic = CompilerDiagnostic.create({ category: "Immutability" /* Immutability */, reason: "This value cannot be modified", description: reason }).withDetails({ kind: "error", loc: effect.value.loc, message: `${variable} cannot be modified` }); if (effect.kind === "Mutate" && ((_e = effect.reason) == null ? void 0 : _e.kind) === "AssignCurrentProperty") { diagnostic.withDetails({ kind: "hint", message: `Hint: If this value is a Ref (value returned by \`useRef()\`), rename the variable to end in "Ref".` }); } applyEffect( context, state, { kind: value.kind === "frozen" /* Frozen */ ? "MutateFrozen" : "MutateGlobal", place: effect.value, error: diagnostic }, initialized, effects ); } } break; } case "Impure": case "Render": case "MutateFrozen": case "MutateGlobal": { effects.push(effect); break; } default: { assertExhaustive( effect, `Unexpected effect kind '${effect.kind}'` ); } } } var _isFunctionExpression, _values, _variables; var _InferenceState = class _InferenceState { constructor(env, isFunctionExpression, values, variables) { __privateAdd(this, _isFunctionExpression); // The kind of each value, based on its allocation site __privateAdd(this, _values); /* * The set of values pointed to by each identifier. This is a set * to accomodate phi points (where a variable may have different * values from different control flow paths). */ __privateAdd(this, _variables); this.env = env; __privateSet(this, _isFunctionExpression, isFunctionExpression); __privateSet(this, _values, values); __privateSet(this, _variables, variables); } static empty(env, isFunctionExpression) { return new _InferenceState(env, isFunctionExpression, /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()); } get isFunctionExpression() { return __privateGet(this, _isFunctionExpression); } // (Re)initializes a @param value with its default @param kind. initialize(value, kind) { CompilerError.invariant(value.kind !== "LoadLocal", { reason: "[InferMutationAliasingEffects] Expected all top-level identifiers to be defined as variables, not values", description: null, details: [ { kind: "error", loc: value.loc, message: null } ], suggestions: null }); __privateGet(this, _values).set(value, kind); } values(place) { const values = __privateGet(this, _variables).get(place.identifier.id); CompilerError.invariant(values != null, { reason: `[InferMutationAliasingEffects] Expected value kind to be initialized`, description: `${printPlace(place)}`, details: [ { kind: "error", loc: place.loc, message: "this is uninitialized" } ], suggestions: null }); return Array.from(values); } // Lookup the kind of the given @param value. kind(place) { const values = __privateGet(this, _variables).get(place.identifier.id); CompilerError.invariant(values != null, { reason: `[InferMutationAliasingEffects] Expected value kind to be initialized`, description: `${printPlace(place)}`, details: [ { kind: "error", loc: place.loc, message: "this is uninitialized" } ], suggestions: null }); let mergedKind = null; for (const value of values) { const kind = __privateGet(this, _values).get(value); mergedKind = mergedKind !== null ? mergeAbstractValues(mergedKind, kind) : kind; } CompilerError.invariant(mergedKind !== null, { reason: `[InferMutationAliasingEffects] Expected at least one value`, description: `No value found at \`${printPlace(place)}\``, details: [ { kind: "error", loc: place.loc, message: null } ], suggestions: null }); return mergedKind; } // Updates the value at @param place to point to the same value as @param value. assign(place, value) { const values = __privateGet(this, _variables).get(value.identifier.id); CompilerError.invariant(values != null, { reason: `[InferMutationAliasingEffects] Expected value for identifier to be initialized`, description: `${printIdentifier(value.identifier)}`, details: [ { kind: "error", loc: value.loc, message: "Expected value for identifier to be initialized" } ], suggestions: null }); __privateGet(this, _variables).set(place.identifier.id, new Set(values)); } appendAlias(place, value) { const values = __privateGet(this, _variables).get(value.identifier.id); CompilerError.invariant(values != null, { reason: `[InferMutationAliasingEffects] Expected value for identifier to be initialized`, description: `${printIdentifier(value.identifier)}`, details: [ { kind: "error", loc: value.loc, message: "Expected value for identifier to be initialized" } ], suggestions: null }); const prevValues = this.values(place); __privateGet(this, _variables).set( place.identifier.id, /* @__PURE__ */ new Set([...prevValues, ...values]) ); } // Defines (initializing or updating) a variable with a specific kind of value. define(place, value) { CompilerError.invariant(__privateGet(this, _values).has(value), { reason: `[InferMutationAliasingEffects] Expected value to be initialized`, description: printInstructionValue(value), details: [ { kind: "error", loc: value.loc, message: "Expected value for identifier to be initialized" } ], suggestions: null }); __privateGet(this, _variables).set(place.identifier.id, /* @__PURE__ */ new Set([value])); } isDefined(place) { return __privateGet(this, _variables).has(place.identifier.id); } /** * Marks @param place as transitively frozen. Returns true if the value was not * already frozen, false if the value is already frozen (or already known immutable). */ freeze(place, reason) { const value = this.kind(place); switch (value.kind) { case "context" /* Context */: case "mutable" /* Mutable */: case "maybefrozen" /* MaybeFrozen */: { const values = this.values(place); for (const instrValue of values) { this.freezeValue(instrValue, reason); } return true; } case "frozen" /* Frozen */: case "global" /* Global */: case "primitive" /* Primitive */: { return false; } default: { assertExhaustive( value.kind, `Unexpected value kind '${value.kind}'` ); } } } freezeValue(value, reason) { __privateGet(this, _values).set(value, { kind: "frozen" /* Frozen */, reason: /* @__PURE__ */ new Set([reason]) }); if (value.kind === "FunctionExpression" && (this.env.config.enablePreserveExistingMemoizationGuarantees || this.env.config.enableTransitivelyFreezeFunctionExpressions)) { for (const place of value.loweredFunc.func.context) { this.freeze(place, reason); } } } mutate(variant, place) { if (isRefOrRefValue(place.identifier)) { return "mutate-ref"; } const kind = this.kind(place).kind; switch (variant) { case "MutateConditionally": case "MutateTransitiveConditionally": { switch (kind) { case "mutable" /* Mutable */: case "context" /* Context */: { return "mutate"; } default: { return "none"; } } } case "Mutate": case "MutateTransitive": { switch (kind) { case "mutable" /* Mutable */: case "context" /* Context */: { return "mutate"; } case "primitive" /* Primitive */: { return "none"; } case "frozen" /* Frozen */: { return "mutate-frozen"; } case "global" /* Global */: { return "mutate-global"; } case "maybefrozen" /* MaybeFrozen */: { return "mutate-frozen"; } default: { assertExhaustive(kind, `Unexpected kind ${kind}`); } } } default: { assertExhaustive(variant, `Unexpected mutation variant ${variant}`); } } } /* * Combine the contents of @param this and @param other, returning a new * instance with the combined changes _if_ there are any changes, or * returning null if no changes would occur. Changes include: * - new entries in @param other that did not exist in @param this * - entries whose values differ in @param this and @param other, * and where joining the values produces a different value than * what was in @param this. * * Note that values are joined using a lattice operation to ensure * termination. */ merge(other) { let nextValues = null; let nextVariables = null; for (const [id, thisValue] of __privateGet(this, _values)) { const otherValue = __privateGet(other, _values).get(id); if (otherValue !== void 0) { const mergedValue = mergeAbstractValues(thisValue, otherValue); if (mergedValue !== thisValue) { nextValues = nextValues != null ? nextValues : new Map(__privateGet(this, _values)); nextValues.set(id, mergedValue); } } } for (const [id, otherValue] of __privateGet(other, _values)) { if (__privateGet(this, _values).has(id)) { continue; } nextValues = nextValues != null ? nextValues : new Map(__privateGet(this, _values)); nextValues.set(id, otherValue); } for (const [id, thisValues] of __privateGet(this, _variables)) { const otherValues = __privateGet(other, _variables).get(id); if (otherValues !== void 0) { let mergedValues = null; for (const otherValue of otherValues) { if (!thisValues.has(otherValue)) { mergedValues = mergedValues != null ? mergedValues : new Set(thisValues); mergedValues.add(otherValue); } } if (mergedValues !== null) { nextVariables = nextVariables != null ? nextVariables : new Map(__privateGet(this, _variables)); nextVariables.set(id, mergedValues); } } } for (const [id, otherValues] of __privateGet(other, _variables)) { if (__privateGet(this, _variables).has(id)) { continue; } nextVariables = nextVariables != null ? nextVariables : new Map(__privateGet(this, _variables)); nextVariables.set(id, new Set(otherValues)); } if (nextVariables === null && nextValues === null) { return null; } else { return new _InferenceState( this.env, __privateGet(this, _isFunctionExpression), nextValues != null ? nextValues : new Map(__privateGet(this, _values)), nextVariables != null ? nextVariables : new Map(__privateGet(this, _variables)) ); } } /* * Returns a copy of this state. * TODO: consider using persistent data structures to make * clone cheaper. */ clone() { return new _InferenceState( this.env, __privateGet(this, _isFunctionExpression), new Map(__privateGet(this, _values)), new Map(__privateGet(this, _variables)) ); } /* * For debugging purposes, dumps the state to a plain * object so that it can printed as JSON. */ debug() { const result = { values: {}, variables: {} }; const objects = /* @__PURE__ */ new Map(); function identify(value) { let id = objects.get(value); if (id == null) { id = objects.size; objects.set(value, id); } return id; } for (const [value, kind] of __privateGet(this, _values)) { const id = identify(value); result.values[id] = { abstract: this.debugAbstractValue(kind), value: printInstructionValue(value) }; } for (const [variable, values] of __privateGet(this, _variables)) { result.variables[`$${variable}`] = [...values].map(identify); } return result; } debugAbstractValue(value) { return { kind: value.kind, reason: [...value.reason] }; } inferPhi(phi) { const values = /* @__PURE__ */ new Set(); for (const [_, operand] of phi.operands) { const operandValues = __privateGet(this, _variables).get(operand.identifier.id); if (operandValues === void 0) continue; for (const v of operandValues) { values.add(v); } } if (values.size > 0) { __privateGet(this, _variables).set(phi.place.identifier.id, values); } } }; _isFunctionExpression = new WeakMap(); _values = new WeakMap(); _variables = new WeakMap(); var InferenceState = _InferenceState; function mergeAbstractValues(a, b) { const kind = mergeValueKinds(a.kind, b.kind); if (kind === a.kind && kind === b.kind && Set_isSuperset(a.reason, b.reason)) { return a; } const reason = new Set(a.reason); for (const r of b.reason) { reason.add(r); } return { kind, reason }; } function conditionallyMutateIterator(place) { if (!(isArrayType(place.identifier) || isSetType(place.identifier) || isMapType(place.identifier))) { return { kind: "MutateTransitiveConditionally", value: place }; } return null; } function computeSignatureForInstruction(context, env, instr) { const { lvalue, value } = instr; const effects = []; switch (value.kind) { case "ArrayExpression": { effects.push({ kind: "Create", into: lvalue, value: "mutable" /* Mutable */, reason: "other" /* Other */ }); for (const element of value.elements) { if (element.kind === "Identifier") { effects.push({ kind: "Capture", from: element, into: lvalue }); } else if (element.kind === "Spread") { const mutateIterator = conditionallyMutateIterator(element.place); if (mutateIterator != null) { effects.push(mutateIterator); } effects.push({ kind: "Capture", from: element.place, into: lvalue }); } else { continue; } } break; } case "ObjectExpression": { effects.push({ kind: "Create", into: lvalue, value: "mutable" /* Mutable */, reason: "other" /* Other */ }); for (const property of value.properties) { if (property.kind === "ObjectProperty") { effects.push({ kind: "Capture", from: property.place, into: lvalue }); } else { effects.push({ kind: "Capture", from: property.place, into: lvalue }); } } break; } case "Await": { effects.push({ kind: "Create", into: lvalue, value: "mutable" /* Mutable */, reason: "other" /* Other */ }); effects.push({ kind: "MutateTransitiveConditionally", value: value.value }); effects.push({ kind: "Capture", from: value.value, into: lvalue }); break; } case "NewExpression": case "CallExpression": case "MethodCall": { let callee; let receiver; let mutatesCallee; if (value.kind === "NewExpression") { callee = value.callee; receiver = value.callee; mutatesCallee = false; } else if (value.kind === "CallExpression") { callee = value.callee; receiver = value.callee; mutatesCallee = true; } else if (value.kind === "MethodCall") { callee = value.property; receiver = value.receiver; mutatesCallee = false; } else { assertExhaustive( value, `Unexpected value kind '${value.kind}'` ); } const signature = getFunctionCallSignature(env, callee.identifier.type); effects.push({ kind: "Apply", receiver, function: callee, mutatesFunction: mutatesCallee, args: value.args, into: lvalue, signature, loc: value.loc }); break; } case "PropertyDelete": case "ComputedDelete": { effects.push({ kind: "Create", into: lvalue, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); effects.push({ kind: "Mutate", value: value.object }); break; } case "PropertyLoad": case "ComputedLoad": { if (isPrimitiveType(lvalue.identifier)) { effects.push({ kind: "Create", into: lvalue, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); } else { effects.push({ kind: "CreateFrom", from: value.object, into: lvalue }); } break; } case "PropertyStore": case "ComputedStore": { const mutationReason = value.kind === "PropertyStore" && value.property === "current" && value.object.identifier.type.kind === "Type" ? { kind: "AssignCurrentProperty" } : null; effects.push({ kind: "Mutate", value: value.object, reason: mutationReason }); effects.push({ kind: "Capture", from: value.value, into: value.object }); effects.push({ kind: "Create", into: lvalue, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); break; } case "ObjectMethod": case "FunctionExpression": { effects.push({ kind: "CreateFunction", into: lvalue, function: value, captures: value.loweredFunc.func.context.filter( (operand) => operand.effect === "capture" /* Capture */ ) }); break; } case "GetIterator": { effects.push({ kind: "Create", into: lvalue, value: "mutable" /* Mutable */, reason: "other" /* Other */ }); if (isArrayType(value.collection.identifier) || isMapType(value.collection.identifier) || isSetType(value.collection.identifier)) { effects.push({ kind: "Capture", from: value.collection, into: lvalue }); } else { effects.push({ kind: "Alias", from: value.collection, into: lvalue }); effects.push({ kind: "MutateTransitiveConditionally", value: value.collection }); } break; } case "IteratorNext": { effects.push({ kind: "MutateConditionally", value: value.iterator }); effects.push({ kind: "CreateFrom", from: value.collection, into: lvalue }); break; } case "NextPropertyOf": { effects.push({ kind: "Create", into: lvalue, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); break; } case "JsxExpression": case "JsxFragment": { effects.push({ kind: "Create", into: lvalue, value: "frozen" /* Frozen */, reason: "jsx-captured" /* JsxCaptured */ }); for (const operand of eachInstructionValueOperand(value)) { effects.push({ kind: "Freeze", value: operand, reason: "jsx-captured" /* JsxCaptured */ }); effects.push({ kind: "Capture", from: operand, into: lvalue }); } if (value.kind === "JsxExpression") { if (value.tag.kind === "Identifier") { effects.push({ kind: "Render", place: value.tag }); } if (value.children != null) { for (const child of value.children) { effects.push({ kind: "Render", place: child }); } } for (const prop of value.props) { if (prop.kind === "JsxAttribute" && prop.place.identifier.type.kind === "Function" && (isJsxType(prop.place.identifier.type.return) || prop.place.identifier.type.return.kind === "Phi" && prop.place.identifier.type.return.operands.some( (operand) => isJsxType(operand) ))) { effects.push({ kind: "Render", place: prop.place }); } } } break; } case "DeclareLocal": { effects.push({ kind: "Create", into: value.lvalue.place, // TODO: what kind here??? value: "primitive" /* Primitive */, reason: "other" /* Other */ }); effects.push({ kind: "Create", into: lvalue, // TODO: what kind here??? value: "primitive" /* Primitive */, reason: "other" /* Other */ }); break; } case "Destructure": { for (const patternItem of eachPatternItem(value.lvalue.pattern)) { const place = patternItem.kind === "Identifier" ? patternItem : patternItem.place; if (isPrimitiveType(place.identifier)) { effects.push({ kind: "Create", into: place, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); } else if (patternItem.kind === "Identifier") { effects.push({ kind: "CreateFrom", from: value.value, into: place }); } else { effects.push({ kind: "Create", into: place, reason: "other" /* Other */, value: "mutable" /* Mutable */ }); effects.push({ kind: "Capture", from: value.value, into: place }); } } effects.push({ kind: "Assign", from: value.value, into: lvalue }); break; } case "LoadContext": { effects.push({ kind: "CreateFrom", from: value.place, into: lvalue }); break; } case "DeclareContext": { const kind = value.lvalue.kind; if (!context.hoistedContextDeclarations.has( value.lvalue.place.identifier.declarationId ) || kind === "HoistedConst" /* HoistedConst */ || kind === "HoistedFunction" /* HoistedFunction */ || kind === "HoistedLet" /* HoistedLet */) { effects.push({ kind: "Create", into: value.lvalue.place, value: "mutable" /* Mutable */, reason: "other" /* Other */ }); } else { effects.push({ kind: "Mutate", value: value.lvalue.place }); } effects.push({ kind: "Create", into: lvalue, // The result can't be referenced so this value doesn't matter value: "primitive" /* Primitive */, reason: "other" /* Other */ }); break; } case "StoreContext": { if (value.lvalue.kind === "Reassign" /* Reassign */ || context.hoistedContextDeclarations.has( value.lvalue.place.identifier.declarationId )) { effects.push({ kind: "Mutate", value: value.lvalue.place }); } else { effects.push({ kind: "Create", into: value.lvalue.place, value: "mutable" /* Mutable */, reason: "other" /* Other */ }); } effects.push({ kind: "Capture", from: value.value, into: value.lvalue.place }); effects.push({ kind: "Assign", from: value.value, into: lvalue }); break; } case "LoadLocal": { effects.push({ kind: "Assign", from: value.place, into: lvalue }); break; } case "StoreLocal": { effects.push({ kind: "Assign", from: value.value, into: value.lvalue.place }); effects.push({ kind: "Assign", from: value.value, into: lvalue }); break; } case "PostfixUpdate": case "PrefixUpdate": { effects.push({ kind: "Create", into: lvalue, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); effects.push({ kind: "Create", into: value.lvalue, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); break; } case "StoreGlobal": { const variable = `\`${value.name}\``; effects.push({ kind: "MutateGlobal", place: value.value, error: CompilerDiagnostic.create({ category: "Globals" /* Globals */, reason: "Cannot reassign variables declared outside of the component/hook", description: `Variable ${variable} is declared outside of the component/hook. Reassigning this value during render is a form of side effect, which can cause unpredictable behavior depending on when the component happens to re-render. If this variable is used in rendering, use useState instead. Otherwise, consider updating it in an effect. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)` }).withDetails({ kind: "error", loc: instr.loc, message: `${variable} cannot be reassigned` }) }); effects.push({ kind: "Assign", from: value.value, into: lvalue }); break; } case "TypeCastExpression": { effects.push({ kind: "Assign", from: value.value, into: lvalue }); break; } case "LoadGlobal": { effects.push({ kind: "Create", into: lvalue, value: "global" /* Global */, reason: "global" /* Global */ }); break; } case "StartMemoize": case "FinishMemoize": { if (env.config.enablePreserveExistingMemoizationGuarantees) { for (const operand of eachInstructionValueOperand(value)) { effects.push({ kind: "Freeze", value: operand, reason: "hook-captured" /* HookCaptured */ }); } } effects.push({ kind: "Create", into: lvalue, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); break; } case "TaggedTemplateExpression": case "BinaryExpression": case "Debugger": case "JSXText": case "MetaProperty": case "Primitive": case "RegExpLiteral": case "TemplateLiteral": case "UnaryExpression": case "UnsupportedNode": { effects.push({ kind: "Create", into: lvalue, value: "primitive" /* Primitive */, reason: "other" /* Other */ }); break; } } return { effects }; } function computeEffectsForLegacySignature(state, signature, lvalue, receiver, args, loc) { var _a, _b; const returnValueReason = (_a = signature.returnValueReason) != null ? _a : "other" /* Other */; const effects = []; effects.push({ kind: "Create", into: lvalue, value: signature.returnValueKind, reason: returnValueReason }); if (signature.impure && state.env.config.validateNoImpureFunctionsInRender) { effects.push({ kind: "Impure", place: receiver, error: CompilerDiagnostic.create({ category: "Purity" /* Purity */, reason: "Cannot call impure function during render", description: (signature.canonicalName != null ? `\`${signature.canonicalName}\` is an impure function. ` : "") + "Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent)" }).withDetails({ kind: "error", loc, message: "Cannot call impure function" }) }); } if (signature.knownIncompatible != null && state.env.isInferredMemoEnabled) { const errors = new CompilerError(); errors.pushDiagnostic( CompilerDiagnostic.create({ category: "IncompatibleLibrary" /* IncompatibleLibrary */, reason: "Use of incompatible library", description: [ "This API returns functions which cannot be memoized without leading to stale UI. To prevent this, by default React Compiler will skip memoizing this component/hook. However, you may see issues if values from this API are passed to other components/hooks that are memoized" ].join("") }).withDetails({ kind: "error", loc: receiver.loc, message: signature.knownIncompatible }) ); throw errors; } const stores = []; const captures = []; function visit4(place, effect) { switch (effect) { case "store" /* Store */: { effects.push({ kind: "Mutate", value: place }); stores.push(place); break; } case "capture" /* Capture */: { captures.push(place); break; } case "mutate?" /* ConditionallyMutate */: { effects.push({ kind: "MutateTransitiveConditionally", value: place }); break; } case "mutate-iterator?" /* ConditionallyMutateIterator */: { const mutateIterator = conditionallyMutateIterator(place); if (mutateIterator != null) { effects.push(mutateIterator); } effects.push({ kind: "Capture", from: place, into: lvalue }); break; } case "freeze" /* Freeze */: { effects.push({ kind: "Freeze", value: place, reason: returnValueReason }); break; } case "mutate" /* Mutate */: { effects.push({ kind: "MutateTransitive", value: place }); break; } case "read" /* Read */: { effects.push({ kind: "ImmutableCapture", from: place, into: lvalue }); break; } } } if (signature.mutableOnlyIfOperandsAreMutable && areArgumentsImmutableAndNonMutating(state, args)) { effects.push({ kind: "Alias", from: receiver, into: lvalue }); for (const arg of args) { if (arg.kind === "Hole") { continue; } const place = arg.kind === "Identifier" ? arg : arg.place; effects.push({ kind: "ImmutableCapture", from: place, into: lvalue }); } return effects; } if (signature.calleeEffect !== "capture" /* Capture */) { effects.push({ kind: "Alias", from: receiver, into: lvalue }); } visit4(receiver, signature.calleeEffect); for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg.kind === "Hole") { continue; } const place = arg.kind === "Identifier" ? arg : arg.place; const signatureEffect = arg.kind === "Identifier" && i < signature.positionalParams.length ? signature.positionalParams[i] : (_b = signature.restParam) != null ? _b : "mutate?" /* ConditionallyMutate */; const effect = getArgumentEffect(signatureEffect, arg); visit4(place, effect); } if (captures.length !== 0) { if (stores.length === 0) { for (const capture of captures) { effects.push({ kind: "Alias", from: capture, into: lvalue }); } } else { for (const capture of captures) { for (const store of stores) { effects.push({ kind: "Capture", from: capture, into: store }); } } } } return effects; } function areArgumentsImmutableAndNonMutating(state, args) { for (const arg of args) { if (arg.kind === "Hole") { continue; } if (arg.kind === "Identifier" && arg.identifier.type.kind === "Function") { const fnShape = state.env.getFunctionSignature(arg.identifier.type); if (fnShape != null) { return !fnShape.positionalParams.some(isKnownMutableEffect) && (fnShape.restParam == null || !isKnownMutableEffect(fnShape.restParam)); } } const place = arg.kind === "Identifier" ? arg : arg.place; const kind = state.kind(place).kind; switch (kind) { case "primitive" /* Primitive */: case "frozen" /* Frozen */: { break; } default: { return false; } } const values = state.values(place); for (const value of values) { if (value.kind === "FunctionExpression" && value.loweredFunc.func.params.some((param) => { const place2 = param.kind === "Identifier" ? param : param.place; const range = place2.identifier.mutableRange; return range.end > range.start + 1; })) { return false; } } } return true; } function computeEffectsForSignature(env, signature, lvalue, receiver, args, context = [], loc) { var _a, _b, _c, _d, _e, _f, _g; if ( // Not enough args signature.params.length > args.length || // Too many args and there is no rest param to hold them args.length > signature.params.length && signature.rest == null ) { return null; } const mutableSpreads = /* @__PURE__ */ new Set(); const substitutions = /* @__PURE__ */ new Map(); substitutions.set(signature.receiver, [receiver]); substitutions.set(signature.returns, [lvalue]); const params = signature.params; for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg.kind === "Hole") { continue; } else if (params == null || i >= params.length || arg.kind === "Spread") { if (signature.rest == null) { return null; } const place = arg.kind === "Identifier" ? arg : arg.place; getOrInsertWith(substitutions, signature.rest, () => []).push(place); if (arg.kind === "Spread") { const mutateIterator = conditionallyMutateIterator(arg.place); if (mutateIterator != null) { mutableSpreads.add(arg.place.identifier.id); } } } else { const param = params[i]; substitutions.set(param, [arg]); } } for (const operand of context) { substitutions.set(operand.identifier.id, [operand]); } const effects = []; for (const signatureTemporary of signature.temporaries) { const temp = createTemporaryPlace(env, receiver.loc); substitutions.set(signatureTemporary.identifier.id, [temp]); } for (const effect of signature.effects) { switch (effect.kind) { case "MaybeAlias": case "Assign": case "ImmutableCapture": case "Alias": case "CreateFrom": case "Capture": { const from = (_a = substitutions.get(effect.from.identifier.id)) != null ? _a : []; const to = (_b = substitutions.get(effect.into.identifier.id)) != null ? _b : []; for (const fromId of from) { for (const toId of to) { effects.push({ kind: effect.kind, from: fromId, into: toId }); } } break; } case "Impure": case "MutateFrozen": case "MutateGlobal": { const values = (_c = substitutions.get(effect.place.identifier.id)) != null ? _c : []; for (const value of values) { effects.push({ kind: effect.kind, place: value, error: effect.error }); } break; } case "Render": { const values = (_d = substitutions.get(effect.place.identifier.id)) != null ? _d : []; for (const value of values) { effects.push({ kind: effect.kind, place: value }); } break; } case "Mutate": case "MutateTransitive": case "MutateTransitiveConditionally": case "MutateConditionally": { const values = (_e = substitutions.get(effect.value.identifier.id)) != null ? _e : []; for (const id of values) { effects.push({ kind: effect.kind, value: id }); } break; } case "Freeze": { const values = (_f = substitutions.get(effect.value.identifier.id)) != null ? _f : []; for (const value of values) { if (mutableSpreads.has(value.identifier.id)) { CompilerError.throwTodo({ reason: "Support spread syntax for hook arguments", loc: value.loc }); } effects.push({ kind: "Freeze", value, reason: effect.reason }); } break; } case "Create": { const into = (_g = substitutions.get(effect.into.identifier.id)) != null ? _g : []; for (const value of into) { effects.push({ kind: "Create", into: value, value: effect.value, reason: effect.reason }); } break; } case "Apply": { const applyReceiver = substitutions.get(effect.receiver.identifier.id); if (applyReceiver == null || applyReceiver.length !== 1) { return null; } const applyFunction = substitutions.get(effect.function.identifier.id); if (applyFunction == null || applyFunction.length !== 1) { return null; } const applyInto = substitutions.get(effect.into.identifier.id); if (applyInto == null || applyInto.length !== 1) { return null; } const applyArgs = []; for (const arg of effect.args) { if (arg.kind === "Hole") { applyArgs.push(arg); } else if (arg.kind === "Identifier") { const applyArg = substitutions.get(arg.identifier.id); if (applyArg == null || applyArg.length !== 1) { return null; } applyArgs.push(applyArg[0]); } else { const applyArg = substitutions.get(arg.place.identifier.id); if (applyArg == null || applyArg.length !== 1) { return null; } applyArgs.push({ kind: "Spread", place: applyArg[0] }); } } effects.push({ kind: "Apply", mutatesFunction: effect.mutatesFunction, receiver: applyReceiver[0], args: applyArgs, function: applyFunction[0], into: applyInto[0], signature: effect.signature, loc }); break; } case "CreateFunction": { CompilerError.throwTodo({ reason: `Support CreateFrom effects in signatures`, loc: receiver.loc }); } default: { assertExhaustive( effect, `Unexpected effect kind '${effect.kind}'` ); } } } return effects; } function buildSignatureFromFunctionExpression(env, fn) { var _a; let rest = null; const params = []; for (const param of fn.loweredFunc.func.params) { if (param.kind === "Identifier") { params.push(param.identifier.id); } else { rest = param.place.identifier.id; } } return { receiver: makeIdentifierId(0), params, rest: rest != null ? rest : createTemporaryPlace(env, fn.loc).identifier.id, returns: fn.loweredFunc.func.returns.identifier.id, effects: (_a = fn.loweredFunc.func.aliasingEffects) != null ? _a : [], temporaries: [] }; } function getWriteErrorReason(abstractValue) { if (abstractValue.reason.has("global" /* Global */)) { return "Modifying a variable defined outside a component or hook is not allowed. Consider using an effect"; } else if (abstractValue.reason.has("jsx-captured" /* JsxCaptured */)) { return "Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX"; } else if (abstractValue.reason.has("context" /* Context */)) { return `Modifying a value returned from 'useContext()' is not allowed.`; } else if (abstractValue.reason.has("known-return-signature" /* KnownReturnSignature */)) { return "Modifying a value returned from a function whose return value should not be mutated"; } else if (abstractValue.reason.has("reactive-function-argument" /* ReactiveFunctionArgument */)) { return "Modifying component props or hook arguments is not allowed. Consider using a local variable instead"; } else if (abstractValue.reason.has("state" /* State */)) { return "Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead"; } else if (abstractValue.reason.has("reducer-state" /* ReducerState */)) { return "Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead"; } else if (abstractValue.reason.has("effect" /* Effect */)) { return "Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()"; } else if (abstractValue.reason.has("hook-captured" /* HookCaptured */)) { return "Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook"; } else if (abstractValue.reason.has("hook-return" /* HookReturn */)) { return "Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed"; } else { return "This modifies a variable that React considers immutable"; } } function getArgumentEffect(signatureEffect, arg) { if (signatureEffect != null) { if (arg.kind === "Identifier") { return signatureEffect; } else if (signatureEffect === "mutate" /* Mutate */ || signatureEffect === "mutate?" /* ConditionallyMutate */) { return signatureEffect; } else { if (signatureEffect === "freeze" /* Freeze */) { CompilerError.throwTodo({ reason: "Support spread syntax for hook arguments", loc: arg.place.loc }); } return "mutate-iterator?" /* ConditionallyMutateIterator */; } } else { return "mutate?" /* ConditionallyMutate */; } } function getFunctionCallSignature(env, type) { if (type.kind !== "Function") { return null; } return env.getFunctionSignature(type); } function isKnownMutableEffect(effect) { switch (effect) { case "store" /* Store */: case "mutate?" /* ConditionallyMutate */: case "mutate-iterator?" /* ConditionallyMutateIterator */: case "mutate" /* Mutate */: { return true; } case "" /* Unknown */: { CompilerError.invariant(false, { reason: "Unexpected unknown effect", description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ], suggestions: null }); } case "read" /* Read */: case "capture" /* Capture */: case "freeze" /* Freeze */: { return false; } default: { assertExhaustive(effect, `Unexpected effect \`${effect}\``); } } } function mergeValueKinds(a, b) { if (a === b) { return a; } else if (a === "maybefrozen" /* MaybeFrozen */ || b === "maybefrozen" /* MaybeFrozen */) { return "maybefrozen" /* MaybeFrozen */; } else if (a === "mutable" /* Mutable */ || b === "mutable" /* Mutable */) { if (a === "frozen" /* Frozen */ || b === "frozen" /* Frozen */) { return "maybefrozen" /* MaybeFrozen */; } else if (a === "context" /* Context */ || b === "context" /* Context */) { return "context" /* Context */; } else { return "mutable" /* Mutable */; } } else if (a === "context" /* Context */ || b === "context" /* Context */) { if (a === "frozen" /* Frozen */ || b === "frozen" /* Frozen */) { return "maybefrozen" /* MaybeFrozen */; } else { return "context" /* Context */; } } else if (a === "frozen" /* Frozen */ || b === "frozen" /* Frozen */) { return "frozen" /* Frozen */; } else if (a === "global" /* Global */ || b === "global" /* Global */) { return "global" /* Global */; } else { CompilerError.invariant( a === "primitive" /* Primitive */ && b == "primitive" /* Primitive */, { reason: `Unexpected value kind in mergeValues()`, description: `Found kinds ${a} and ${b}`, details: [ { kind: "error", loc: GeneratedSource, message: null } ] } ); return "primitive" /* Primitive */; } } // src/ReactiveScopes/PruneNonEscapingScopes.ts function pruneNonEscapingScopes(fn) { const state = new State3(fn.env); for (const param of fn.params) { if (param.kind === "Identifier") { state.declare(param.identifier.declarationId); } else { state.declare(param.place.identifier.declarationId); } } visitReactiveFunction(fn, new CollectDependenciesVisitor(fn.env, state), []); const memoized = computeMemoizedIdentifiers(state); visitReactiveFunction(fn, new PruneScopesTransform(), memoized); } function joinAliases(kind1, kind2) { if (kind1 === "Memoized" /* Memoized */ || kind2 === "Memoized" /* Memoized */) { return "Memoized" /* Memoized */; } else if (kind1 === "Conditional" /* Conditional */ || kind2 === "Conditional" /* Conditional */) { return "Conditional" /* Conditional */; } else if (kind1 === "Unmemoized" /* Unmemoized */ || kind2 === "Unmemoized" /* Unmemoized */) { return "Unmemoized" /* Unmemoized */; } else { return "Never" /* Never */; } } var State3 = class { constructor(env) { /* * Maps lvalues for LoadLocal to the identifier being loaded, to resolve indirections * in subsequent lvalues/rvalues. * * NOTE: this pass uses DeclarationId rather than IdentifierId because the pass is not * aware of control-flow, only data flow via mutation. Instead of precisely modeling * control flow, we analyze all values that may flow into a particular program variable, * and then whether that program variable may escape (if so, the values flowing in may * escape too). Thus we use DeclarationId to captures all values that may flow into * a particular program variable, regardless of control flow paths. * * In the future when we convert to HIR everywhere this pass can account for control * flow and use SSA ids. */ this.definitions = /* @__PURE__ */ new Map(); this.identifiers = /* @__PURE__ */ new Map(); this.scopes = /* @__PURE__ */ new Map(); this.escapingValues = /* @__PURE__ */ new Set(); this.env = env; } // Declare a new identifier, used for function id and params declare(id) { this.identifiers.set(id, { level: "Never" /* Never */, memoized: false, dependencies: /* @__PURE__ */ new Set(), scopes: /* @__PURE__ */ new Set(), seen: false }); } /* * Associates the identifier with its scope, if there is one and it is active for the given instruction id: * - Records the scope and its dependencies * - Associates the identifier with this scope */ visitOperand(id, place, identifier4) { const scope = getPlaceScope(id, place); if (scope !== null) { let node = this.scopes.get(scope.id); if (node === void 0) { node = { dependencies: [...scope.dependencies].map( (dep) => dep.identifier.declarationId ), seen: false }; this.scopes.set(scope.id, node); } const identifierNode = this.identifiers.get(identifier4); CompilerError.invariant(identifierNode !== void 0, { reason: "Expected identifier to be initialized", description: `[${id}] operand=${printPlace(place)} for identifier declaration ${identifier4}`, details: [ { kind: "error", loc: place.loc, message: null } ], suggestions: null }); identifierNode.scopes.add(scope.id); } } }; function computeMemoizedIdentifiers(state) { const memoized = /* @__PURE__ */ new Set(); function visit4(id, forceMemoize = false) { const node = state.identifiers.get(id); CompilerError.invariant(node !== void 0, { reason: `Expected a node for all identifiers, none found for \`${id}\``, description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); if (node.seen) { return node.memoized; } node.seen = true; node.memoized = false; let hasMemoizedDependency = false; for (const dep of node.dependencies) { const isDepMemoized = visit4(dep); hasMemoizedDependency || (hasMemoizedDependency = isDepMemoized); } if (node.level === "Memoized" /* Memoized */ || node.level === "Conditional" /* Conditional */ && (hasMemoizedDependency || forceMemoize) || node.level === "Unmemoized" /* Unmemoized */ && forceMemoize) { node.memoized = true; memoized.add(id); for (const scope of node.scopes) { forceMemoizeScopeDependencies(scope); } } return node.memoized; } function forceMemoizeScopeDependencies(id) { const node = state.scopes.get(id); CompilerError.invariant(node !== void 0, { reason: "Expected a node for all scopes", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); if (node.seen) { return; } node.seen = true; for (const dep of node.dependencies) { visit4(dep, true); } return; } for (const value of state.escapingValues) { visit4(value); } return memoized; } function computePatternLValues(pattern) { const lvalues = []; switch (pattern.kind) { case "ArrayPattern": { for (const item of pattern.items) { if (item.kind === "Identifier") { lvalues.push({ place: item, level: "Conditional" /* Conditional */ }); } else if (item.kind === "Spread") { lvalues.push({ place: item.place, level: "Memoized" /* Memoized */ }); } } break; } case "ObjectPattern": { for (const property of pattern.properties) { if (property.kind === "ObjectProperty") { lvalues.push({ place: property.place, level: "Conditional" /* Conditional */ }); } else { lvalues.push({ place: property.place, level: "Memoized" /* Memoized */ }); } } break; } default: { assertExhaustive( pattern, `Unexpected pattern kind \`${pattern.kind}\`` ); } } return lvalues; } var CollectDependenciesVisitor = class extends ReactiveFunctionVisitor { constructor(env, state) { super(); this.env = env; this.state = state; this.options = { memoizeJsxElements: !this.env.config.enableForest, forceMemoizePrimitives: this.env.config.enableForest || this.env.config.enablePreserveExistingMemoizationGuarantees }; } /* * Given a value, returns a description of how it should be memoized: * - lvalues: optional extra places that are lvalue-like in the sense of * aliasing the rvalues * - rvalues: places that are aliased by the instruction's lvalues. * - level: the level of memoization to apply to this value */ computeMemoizationInputs(value, lvalue) { const env = this.env; const options = this.options; switch (value.kind) { case "ConditionalExpression": { return { // Only need to memoize if the rvalues are memoized lvalues: lvalue !== null ? [{ place: lvalue, level: "Conditional" /* Conditional */ }] : [], rvalues: [ // Conditionals do not alias their test value. ...this.computeMemoizationInputs(value.consequent, null).rvalues, ...this.computeMemoizationInputs(value.alternate, null).rvalues ] }; } case "LogicalExpression": { return { // Only need to memoize if the rvalues are memoized lvalues: lvalue !== null ? [{ place: lvalue, level: "Conditional" /* Conditional */ }] : [], rvalues: [ ...this.computeMemoizationInputs(value.left, null).rvalues, ...this.computeMemoizationInputs(value.right, null).rvalues ] }; } case "SequenceExpression": { for (const instr of value.instructions) { this.visitValueForMemoization(instr.id, instr.value, instr.lvalue); } return { // Only need to memoize if the rvalues are memoized lvalues: lvalue !== null ? [{ place: lvalue, level: "Conditional" /* Conditional */ }] : [], /* * Only the final value of the sequence is a true rvalue: * values from the sequence's instructions are evaluated * as separate nodes */ rvalues: this.computeMemoizationInputs(value.value, null).rvalues }; } case "JsxExpression": { const operands = []; if (value.tag.kind === "Identifier") { operands.push(value.tag); } for (const prop of value.props) { if (prop.kind === "JsxAttribute") { operands.push(prop.place); } else { operands.push(prop.argument); } } if (value.children !== null) { for (const child of value.children) { operands.push(child); } } const level = options.memoizeJsxElements ? "Memoized" /* Memoized */ : "Unmemoized" /* Unmemoized */; return { /* * JSX elements themselves are not memoized unless forced to * avoid breaking downstream memoization */ lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], rvalues: operands }; } case "JsxFragment": { const level = options.memoizeJsxElements ? "Memoized" /* Memoized */ : "Unmemoized" /* Unmemoized */; return { /* * JSX elements themselves are not memoized unless forced to * avoid breaking downstream memoization */ lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], rvalues: value.children }; } case "NextPropertyOf": case "StartMemoize": case "FinishMemoize": case "Debugger": case "ComputedDelete": case "PropertyDelete": case "LoadGlobal": case "MetaProperty": case "TemplateLiteral": case "Primitive": case "JSXText": case "BinaryExpression": case "UnaryExpression": { if (options.forceMemoizePrimitives) { const level2 = "Conditional" /* Conditional */; return { lvalues: lvalue !== null ? [{ place: lvalue, level: level2 }] : [], rvalues: [...eachReactiveValueOperand(value)] }; } const level = "Never" /* Never */; return { // All of these instructions return a primitive value and never need to be memoized lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], rvalues: [] }; } case "Await": case "TypeCastExpression": { return { // Indirection for the inner value, memoized if the value is lvalues: lvalue !== null ? [{ place: lvalue, level: "Conditional" /* Conditional */ }] : [], rvalues: [value.value] }; } case "IteratorNext": { return { // Indirection for the inner value, memoized if the value is lvalues: lvalue !== null ? [{ place: lvalue, level: "Conditional" /* Conditional */ }] : [], rvalues: [value.iterator, value.collection] }; } case "GetIterator": { return { // Indirection for the inner value, memoized if the value is lvalues: lvalue !== null ? [{ place: lvalue, level: "Conditional" /* Conditional */ }] : [], rvalues: [value.collection] }; } case "LoadLocal": { return { // Indirection for the inner value, memoized if the value is lvalues: lvalue !== null ? [{ place: lvalue, level: "Conditional" /* Conditional */ }] : [], rvalues: [value.place] }; } case "LoadContext": { return { // Should never be pruned lvalues: lvalue !== null ? [{ place: lvalue, level: "Conditional" /* Conditional */ }] : [], rvalues: [value.place] }; } case "DeclareContext": { const lvalues = [ { place: value.lvalue.place, level: "Memoized" /* Memoized */ } ]; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Unmemoized" /* Unmemoized */ }); } return { lvalues, rvalues: [] }; } case "DeclareLocal": { const lvalues = [ { place: value.lvalue.place, level: "Unmemoized" /* Unmemoized */ } ]; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Unmemoized" /* Unmemoized */ }); } return { lvalues, rvalues: [] }; } case "PrefixUpdate": case "PostfixUpdate": { const lvalues = [ { place: value.lvalue, level: "Conditional" /* Conditional */ } ]; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Conditional" /* Conditional */ }); } return { // Indirection for the inner value, memoized if the value is lvalues, rvalues: [value.value] }; } case "StoreLocal": { const lvalues = [ { place: value.lvalue.place, level: "Conditional" /* Conditional */ } ]; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Conditional" /* Conditional */ }); } return { // Indirection for the inner value, memoized if the value is lvalues, rvalues: [value.value] }; } case "StoreContext": { const lvalues = [ { place: value.lvalue.place, level: "Memoized" /* Memoized */ } ]; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Conditional" /* Conditional */ }); } return { lvalues, rvalues: [value.value] }; } case "StoreGlobal": { const lvalues = []; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Unmemoized" /* Unmemoized */ }); } return { lvalues, rvalues: [value.value] }; } case "Destructure": { const lvalues = []; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Conditional" /* Conditional */ }); } lvalues.push(...computePatternLValues(value.lvalue.pattern)); return { lvalues, rvalues: [value.value] }; } case "ComputedLoad": case "PropertyLoad": { const level = "Conditional" /* Conditional */; return { // Indirection for the inner value, memoized if the value is lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], /* * Only the object is aliased to the result, and the result only needs to be * memoized if the object is */ rvalues: [value.object] }; } case "ComputedStore": { const lvalues = [ { place: value.object, level: "Conditional" /* Conditional */ } ]; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Conditional" /* Conditional */ }); } return { lvalues, rvalues: [value.value] }; } case "OptionalExpression": { const lvalues = []; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Conditional" /* Conditional */ }); } return { lvalues, rvalues: [ ...this.computeMemoizationInputs(value.value, null).rvalues ] }; } case "TaggedTemplateExpression": { const signature = getFunctionCallSignature( env, value.tag.identifier.type ); let lvalues = []; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Memoized" /* Memoized */ }); } if ((signature == null ? void 0 : signature.noAlias) === true) { return { lvalues, rvalues: [] }; } const operands = [...eachReactiveValueOperand(value)]; lvalues.push( ...operands.filter((operand) => isMutableEffect(operand.effect, operand.loc)).map((place) => ({ place, level: "Memoized" /* Memoized */ })) ); return { lvalues, rvalues: operands }; } case "CallExpression": { const signature = getFunctionCallSignature( env, value.callee.identifier.type ); let lvalues = []; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Memoized" /* Memoized */ }); } if ((signature == null ? void 0 : signature.noAlias) === true) { return { lvalues, rvalues: [] }; } const operands = [...eachReactiveValueOperand(value)]; lvalues.push( ...operands.filter((operand) => isMutableEffect(operand.effect, operand.loc)).map((place) => ({ place, level: "Memoized" /* Memoized */ })) ); return { lvalues, rvalues: operands }; } case "MethodCall": { const signature = getFunctionCallSignature( env, value.property.identifier.type ); let lvalues = []; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Memoized" /* Memoized */ }); } if ((signature == null ? void 0 : signature.noAlias) === true) { return { lvalues, rvalues: [] }; } const operands = [...eachReactiveValueOperand(value)]; lvalues.push( ...operands.filter((operand) => isMutableEffect(operand.effect, operand.loc)).map((place) => ({ place, level: "Memoized" /* Memoized */ })) ); return { lvalues, rvalues: operands }; } case "RegExpLiteral": case "ObjectMethod": case "FunctionExpression": case "ArrayExpression": case "NewExpression": case "ObjectExpression": case "PropertyStore": { const operands = [...eachReactiveValueOperand(value)]; const lvalues = operands.filter((operand) => isMutableEffect(operand.effect, operand.loc)).map((place) => ({ place, level: "Memoized" /* Memoized */ })); if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Memoized" /* Memoized */ }); } return { lvalues, rvalues: operands }; } case "UnsupportedNode": { const lvalues = []; if (lvalue !== null) { lvalues.push({ place: lvalue, level: "Never" /* Never */ }); } return { lvalues, rvalues: [] }; } default: { assertExhaustive( value, `Unexpected value kind \`${value.kind}\`` ); } } } visitValueForMemoization(id, value, lvalue) { var _a, _b, _c; const state = this.state; const aliasing = this.computeMemoizationInputs(value, lvalue); for (const operand of aliasing.rvalues) { const operandId = (_a = state.definitions.get(operand.identifier.declarationId)) != null ? _a : operand.identifier.declarationId; state.visitOperand(id, operand, operandId); } for (const { place: lvalue2, level } of aliasing.lvalues) { const lvalueId = (_b = state.definitions.get(lvalue2.identifier.declarationId)) != null ? _b : lvalue2.identifier.declarationId; let node = state.identifiers.get(lvalueId); if (node === void 0) { node = { level: "Never" /* Never */, memoized: false, dependencies: /* @__PURE__ */ new Set(), scopes: /* @__PURE__ */ new Set(), seen: false }; state.identifiers.set(lvalueId, node); } node.level = joinAliases(node.level, level); for (const operand of aliasing.rvalues) { const operandId = (_c = state.definitions.get(operand.identifier.declarationId)) != null ? _c : operand.identifier.declarationId; if (operandId === lvalueId) { continue; } node.dependencies.add(operandId); } state.visitOperand(id, lvalue2, lvalueId); } if (value.kind === "LoadLocal" && lvalue !== null) { state.definitions.set( lvalue.identifier.declarationId, value.place.identifier.declarationId ); } else if (value.kind === "CallExpression" || value.kind === "MethodCall") { let callee = value.kind === "CallExpression" ? value.callee : value.property; if (getHookKind(state.env, callee.identifier) != null) { const signature = getFunctionCallSignature( this.env, callee.identifier.type ); if (signature && signature.noAlias === true) { return; } for (const operand of value.args) { const place = operand.kind === "Spread" ? operand.place : operand; state.escapingValues.add(place.identifier.declarationId); } } } } visitInstruction(instruction, _scopes3) { this.visitValueForMemoization( instruction.id, instruction.value, instruction.lvalue ); } visitTerminal(stmt, scopes) { this.traverseTerminal(stmt, scopes); if (stmt.terminal.kind === "return") { this.state.escapingValues.add( stmt.terminal.value.identifier.declarationId ); const identifierNode = this.state.identifiers.get( stmt.terminal.value.identifier.declarationId ); CompilerError.invariant(identifierNode !== void 0, { reason: "Expected identifier to be initialized", description: null, details: [ { kind: "error", loc: stmt.terminal.loc, message: null } ], suggestions: null }); for (const scope of scopes) { identifierNode.scopes.add(scope.id); } } } visitScope(scope, scopes) { for (const reassignment of scope.scope.reassignments) { const identifierNode = this.state.identifiers.get( reassignment.declarationId ); CompilerError.invariant(identifierNode !== void 0, { reason: "Expected identifier to be initialized", description: null, details: [ { kind: "error", loc: reassignment.loc, message: null } ], suggestions: null }); for (const scope2 of scopes) { identifierNode.scopes.add(scope2.id); } identifierNode.scopes.add(scope.scope.id); } this.traverseScope(scope, [...scopes, scope.scope]); } }; var PruneScopesTransform = class extends ReactiveFunctionTransform { constructor() { super(...arguments); this.prunedScopes = /* @__PURE__ */ new Set(); /** * Track reassignments so we can correctly set `pruned` flags for * inlined useMemos. */ this.reassignments = /* @__PURE__ */ new Map(); } transformScope(scopeBlock, state) { this.visitScope(scopeBlock, state); if (scopeBlock.scope.declarations.size === 0 && scopeBlock.scope.reassignments.size === 0 || scopeBlock.scope.earlyReturnValue !== null) { return { kind: "keep" }; } const hasMemoizedOutput = Array.from(scopeBlock.scope.declarations.values()).some( (decl) => state.has(decl.identifier.declarationId) ) || Array.from(scopeBlock.scope.reassignments).some( (identifier4) => state.has(identifier4.declarationId) ); if (hasMemoizedOutput) { return { kind: "keep" }; } else { this.prunedScopes.add(scopeBlock.scope.id); return { kind: "replace-many", value: scopeBlock.instructions }; } } /** * If we pruned the scope for a non-escaping value, we know it doesn't * need to be memoized. Remove associated `Memoize` instructions so that * we don't report false positives on "missing" memoization of these values. */ transformInstruction(instruction, state) { var _a; this.traverseInstruction(instruction, state); const value = instruction.value; if (value.kind === "StoreLocal" && value.lvalue.kind === "Reassign") { const ids = getOrInsertDefault( this.reassignments, value.lvalue.place.identifier.declarationId, /* @__PURE__ */ new Set() ); ids.add(value.value.identifier); } else if (value.kind === "LoadLocal" && value.place.identifier.scope != null && instruction.lvalue != null && instruction.lvalue.identifier.scope == null) { const ids = getOrInsertDefault( this.reassignments, instruction.lvalue.identifier.declarationId, /* @__PURE__ */ new Set() ); ids.add(value.place.identifier); } else if (value.kind === "FinishMemoize") { let decls; if (value.decl.identifier.scope == null) { decls = (_a = this.reassignments.get(value.decl.identifier.declarationId)) != null ? _a : [ value.decl.identifier ]; } else { decls = [value.decl.identifier]; } if ([...decls].every( (decl) => decl.scope == null || this.prunedScopes.has(decl.scope.id) )) { value.pruned = true; } } return { kind: "keep" }; } }; // src/ReactiveScopes/CollectReactiveIdentifiers.ts var Visitor4 = class extends ReactiveFunctionVisitor { /* * Visitors don't visit lvalues as places by default, but we want to visit all places to * check for reactivity */ visitLValue(id, lvalue, state) { this.visitPlace(id, lvalue, state); } /* * This visitor only infers data dependencies and does not account for control dependencies * where a variable may be assigned a different value based on some conditional, eg via two * different paths of an if statement. */ visitPlace(_id, place, state) { if (place.reactive) { state.add(place.identifier.id); } } visitPrunedScope(scopeBlock, state) { this.traversePrunedScope(scopeBlock, state); for (const [id, decl] of scopeBlock.scope.declarations) { if (!isPrimitiveType(decl.identifier) && !isStableRefType(decl.identifier, state)) { state.add(id); } } } }; function isStableRefType(identifier4, reactiveIdentifiers) { return isUseRefType(identifier4) && !reactiveIdentifiers.has(identifier4.id); } function collectReactiveIdentifiers(fn) { const visitor = new Visitor4(); const state = /* @__PURE__ */ new Set(); visitReactiveFunction(fn, visitor, state); return state; } // src/ReactiveScopes/PruneNonReactiveDependencies.ts function pruneNonReactiveDependencies(fn) { const reactiveIdentifiers = collectReactiveIdentifiers(fn); visitReactiveFunction(fn, new Visitor5(), reactiveIdentifiers); } var Visitor5 = class extends ReactiveFunctionVisitor { visitInstruction(instruction, state) { this.traverseInstruction(instruction, state); const { lvalue, value } = instruction; switch (value.kind) { case "LoadLocal": { if (lvalue !== null && state.has(value.place.identifier.id)) { state.add(lvalue.identifier.id); } break; } case "StoreLocal": { if (state.has(value.value.identifier.id)) { state.add(value.lvalue.place.identifier.id); if (lvalue !== null) { state.add(lvalue.identifier.id); } } break; } case "Destructure": { if (state.has(value.value.identifier.id)) { for (const lvalue2 of eachPatternOperand(value.lvalue.pattern)) { if (isStableType(lvalue2.identifier)) { continue; } state.add(lvalue2.identifier.id); } if (lvalue !== null) { state.add(lvalue.identifier.id); } } break; } case "PropertyLoad": { if (lvalue !== null && state.has(value.object.identifier.id) && !isStableType(lvalue.identifier)) { state.add(lvalue.identifier.id); } break; } case "ComputedLoad": { if (lvalue !== null && (state.has(value.object.identifier.id) || state.has(value.property.identifier.id))) { state.add(lvalue.identifier.id); } break; } } } visitScope(scopeBlock, state) { this.traverseScope(scopeBlock, state); for (const dep of scopeBlock.scope.dependencies) { const isReactive = state.has(dep.identifier.id); if (!isReactive) { scopeBlock.scope.dependencies.delete(dep); } } if (scopeBlock.scope.dependencies.size !== 0) { for (const [, declaration] of scopeBlock.scope.declarations) { state.add(declaration.identifier.id); } for (const reassignment of scopeBlock.scope.reassignments) { state.add(reassignment.id); } } } }; // src/ReactiveScopes/PruneTemporaryLValues.ts function pruneUnusedLValues(fn) { const lvalues = /* @__PURE__ */ new Map(); visitReactiveFunction(fn, new Visitor6(), lvalues); for (const [, instr] of lvalues) { instr.lvalue = null; } } var Visitor6 = class extends ReactiveFunctionVisitor { visitPlace(id, place, state) { state.delete(place.identifier.declarationId); } visitInstruction(instruction, state) { this.traverseInstruction(instruction, state); if (instruction.lvalue !== null && instruction.lvalue.identifier.name === null) { state.set(instruction.lvalue.identifier.declarationId, instruction); } } }; // src/ReactiveScopes/PruneUnusedLabels.ts function pruneUnusedLabels(fn) { const labels = /* @__PURE__ */ new Set(); visitReactiveFunction(fn, new Transform3(), labels); } var Transform3 = class extends ReactiveFunctionTransform { transformTerminal(stmt, state) { this.traverseTerminal(stmt, state); const { terminal } = stmt; if ((terminal.kind === "break" || terminal.kind === "continue") && terminal.targetKind === "labeled") { state.add(terminal.target); } const isReachableLabel = stmt.label !== null && state.has(stmt.label.id); if (stmt.terminal.kind === "label" && !isReachableLabel) { const block = [...stmt.terminal.block]; const last = block.at(-1); if (last !== void 0 && last.kind === "terminal" && last.terminal.kind === "break" && last.terminal.target === null) { block.pop(); } return { kind: "replace-many", value: block }; } else { if (!isReachableLabel && stmt.label != null) { stmt.label.implicit = true; } return { kind: "keep" }; } } }; // src/ReactiveScopes/PruneUnusedScopes.ts function pruneUnusedScopes(fn) { visitReactiveFunction(fn, new Transform4(), { hasReturnStatement: false }); } var Transform4 = class extends ReactiveFunctionTransform { visitTerminal(stmt, state) { this.traverseTerminal(stmt, state); if (stmt.terminal.kind === "return") { state.hasReturnStatement = true; } } transformScope(scopeBlock, _state) { const scopeState = { hasReturnStatement: false }; this.visitScope(scopeBlock, scopeState); if (!scopeState.hasReturnStatement && scopeBlock.scope.reassignments.size === 0 && (scopeBlock.scope.declarations.size === 0 || /* * Can prune scopes where all declarations bubbled up from inner * scopes */ !hasOwnDeclaration(scopeBlock))) { return { kind: "replace", value: { kind: "pruned-scope", scope: scopeBlock.scope, instructions: scopeBlock.instructions } }; } else { return { kind: "keep" }; } } }; function hasOwnDeclaration(block) { for (const declaration of block.scope.declarations.values()) { if (declaration.scope.id === block.scope.id) { return true; } } return false; } // src/ReactiveScopes/CollectReferencedGlobals.ts function collectReferencedGlobals(fn) { const identifiers = /* @__PURE__ */ new Set(); visitReactiveFunction(fn, new Visitor7(), identifiers); return identifiers; } var Visitor7 = class extends ReactiveFunctionVisitor { visitValue(id, value, state) { this.traverseValue(id, value, state); if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") { this.visitHirFunction(value.loweredFunc.func, state); } else if (value.kind === "LoadGlobal") { state.add(value.binding.name); } } visitReactiveFunctionValue(_id, _dependencies2, fn, state) { visitReactiveFunction(fn, this, state); } }; // src/ReactiveScopes/RenameVariables.ts function renameVariables(fn) { const globals = collectReferencedGlobals(fn); const scopes = new Scopes(globals, fn.env.programContext); renameVariablesImpl(fn, new Visitor8(), scopes); return /* @__PURE__ */ new Set([...scopes.names, ...globals]); } function renameVariablesImpl(fn, visitor, scopes) { scopes.enter(() => { for (const param of fn.params) { if (param.kind === "Identifier") { scopes.visit(param.identifier); } else { scopes.visit(param.place.identifier); } } visitReactiveFunction(fn, visitor, scopes); }); } var Visitor8 = class extends ReactiveFunctionVisitor { visitParam(place, state) { state.visit(place.identifier); } visitLValue(_id, lvalue, state) { state.visit(lvalue.identifier); } visitPlace(id, place, state) { state.visit(place.identifier); } visitBlock(block, state) { state.enter(() => { this.traverseBlock(block, state); }); } visitPrunedScope(scopeBlock, state) { this.traverseBlock(scopeBlock.instructions, state); } visitScope(scope, state) { for (const [_, declaration] of scope.scope.declarations) { state.visit(declaration.identifier); } this.traverseScope(scope, state); } visitValue(id, value, state) { this.traverseValue(id, value, state); if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") { this.visitHirFunction(value.loweredFunc.func, state); } } visitReactiveFunctionValue(_id, _dependencies2, _fn, _state) { renameVariablesImpl(_fn, this, _state); } }; var _seen, _stack, _globals3, _programContext, _Scopes_instances, lookup_fn; var Scopes = class { constructor(globals, programContext) { __privateAdd(this, _Scopes_instances); __privateAdd(this, _seen, /* @__PURE__ */ new Map()); __privateAdd(this, _stack, [/* @__PURE__ */ new Map()]); __privateAdd(this, _globals3); __privateAdd(this, _programContext); this.names = /* @__PURE__ */ new Set(); __privateSet(this, _globals3, globals); __privateSet(this, _programContext, programContext); } visit(identifier4) { const originalName = identifier4.name; if (originalName === null) { return; } const mappedName = __privateGet(this, _seen).get(identifier4.declarationId); if (mappedName !== void 0) { identifier4.name = mappedName; return; } let name = originalName.value; let id = 0; if (isPromotedTemporary(originalName.value)) { name = `t${id++}`; } else if (isPromotedJsxTemporary(originalName.value)) { name = `T${id++}`; } while (__privateMethod(this, _Scopes_instances, lookup_fn).call(this, name) !== null || __privateGet(this, _globals3).has(name)) { if (isPromotedTemporary(originalName.value)) { name = `t${id++}`; } else if (isPromotedJsxTemporary(originalName.value)) { name = `T${id++}`; } else { name = `${originalName.value}$${id++}`; } } __privateGet(this, _programContext).addNewReference(name); const identifierName = makeIdentifierName(name); identifier4.name = identifierName; __privateGet(this, _seen).set(identifier4.declarationId, identifierName); __privateGet(this, _stack).at(-1).set(identifierName.value, identifier4.declarationId); this.names.add(identifierName.value); } enter(fn) { const next = /* @__PURE__ */ new Map(); __privateGet(this, _stack).push(next); fn(); const last = __privateGet(this, _stack).pop(); CompilerError.invariant(last === next, { reason: "Mismatch push/pop calls", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); } }; _seen = new WeakMap(); _stack = new WeakMap(); _globals3 = new WeakMap(); _programContext = new WeakMap(); _Scopes_instances = new WeakSet(); lookup_fn = function(name) { for (let i = __privateGet(this, _stack).length - 1; i >= 0; i--) { const scope = __privateGet(this, _stack)[i]; const entry = scope.get(name); if (entry !== void 0) { return entry; } } return null; }; // src/ReactiveScopes/StabilizeBlockIds.ts function stabilizeBlockIds(fn) { const referenced = /* @__PURE__ */ new Set(); visitReactiveFunction(fn, new CollectReferencedLabels(), referenced); const mappings = /* @__PURE__ */ new Map(); for (const blockId of referenced) { mappings.set(blockId, makeBlockId(mappings.size)); } visitReactiveFunction(fn, new RewriteBlockIds(), mappings); } var CollectReferencedLabels = class extends ReactiveFunctionVisitor { visitScope(scope, state) { const { earlyReturnValue } = scope.scope; if (earlyReturnValue != null) { state.add(earlyReturnValue.label); } this.traverseScope(scope, state); } visitTerminal(stmt, state) { if (stmt.label != null) { if (!stmt.label.implicit) { state.add(stmt.label.id); } } this.traverseTerminal(stmt, state); } }; var RewriteBlockIds = class extends ReactiveFunctionVisitor { visitScope(scope, state) { const { earlyReturnValue } = scope.scope; if (earlyReturnValue != null) { const rewrittenId = getOrInsertDefault( state, earlyReturnValue.label, state.size ); earlyReturnValue.label = makeBlockId(rewrittenId); } this.traverseScope(scope, state); } visitTerminal(stmt, state) { if (stmt.label != null) { const rewrittenId = getOrInsertDefault(state, stmt.label.id, state.size); stmt.label.id = makeBlockId(rewrittenId); } const terminal = stmt.terminal; if (terminal.kind === "break" || terminal.kind === "continue") { const rewrittenId = getOrInsertDefault( state, terminal.target, state.size ); terminal.target = makeBlockId(rewrittenId); } this.traverseTerminal(stmt, state); } }; // src/Inference/InferMutationAliasingRanges.ts function inferMutationAliasingRanges(fn, { isFunctionExpression }) { var _a, _b, _c, _d, _e, _f, _g; const functionEffects = []; const state = new AliasingState(); const pendingPhis = /* @__PURE__ */ new Map(); const mutations = []; const renders = []; let index = 0; const errors = new CompilerError(); for (const param of [...fn.params, ...fn.context, fn.returns]) { const place = param.kind === "Identifier" ? param : param.place; state.create(place, { kind: "Object" }); } const seenBlocks = /* @__PURE__ */ new Set(); for (const block of fn.body.blocks.values()) { for (const phi of block.phis) { state.create(phi.place, { kind: "Phi" }); for (const [pred, operand] of phi.operands) { if (!seenBlocks.has(pred)) { const blockPhis2 = getOrInsertWith( pendingPhis, pred, () => [] ); blockPhis2.push({ from: operand, into: phi.place, index: index++ }); } else { state.assign(index++, operand, phi.place); } } } seenBlocks.add(block.id); for (const instr of block.instructions) { if (instr.effects == null) continue; for (const effect of instr.effects) { if (effect.kind === "Create") { state.create(effect.into, { kind: "Object" }); } else if (effect.kind === "CreateFunction") { state.create(effect.into, { kind: "Function", function: effect.function.loweredFunc.func }); } else if (effect.kind === "CreateFrom") { state.createFrom(index++, effect.from, effect.into); } else if (effect.kind === "Assign") { if (!state.nodes.has(effect.into.identifier)) { state.create(effect.into, { kind: "Object" }); } state.assign(index++, effect.from, effect.into); } else if (effect.kind === "Alias") { state.assign(index++, effect.from, effect.into); } else if (effect.kind === "MaybeAlias") { state.maybeAlias(index++, effect.from, effect.into); } else if (effect.kind === "Capture") { state.capture(index++, effect.from, effect.into); } else if (effect.kind === "MutateTransitive" || effect.kind === "MutateTransitiveConditionally") { mutations.push({ index: index++, id: instr.id, transitive: true, kind: effect.kind === "MutateTransitive" ? 2 /* Definite */ : 1 /* Conditional */, reason: null, place: effect.value }); } else if (effect.kind === "Mutate" || effect.kind === "MutateConditionally") { mutations.push({ index: index++, id: instr.id, transitive: false, kind: effect.kind === "Mutate" ? 2 /* Definite */ : 1 /* Conditional */, reason: effect.kind === "Mutate" ? (_a = effect.reason) != null ? _a : null : null, place: effect.value }); } else if (effect.kind === "MutateFrozen" || effect.kind === "MutateGlobal" || effect.kind === "Impure") { errors.pushDiagnostic(effect.error); functionEffects.push(effect); } else if (effect.kind === "Render") { renders.push({ index: index++, place: effect.place }); functionEffects.push(effect); } } } const blockPhis = pendingPhis.get(block.id); if (blockPhis != null) { for (const { from, into, index: index2 } of blockPhis) { state.assign(index2, from, into); } } if (block.terminal.kind === "return") { state.assign(index++, block.terminal.value, fn.returns); } if ((block.terminal.kind === "maybe-throw" || block.terminal.kind === "return") && block.terminal.effects != null) { for (const effect of block.terminal.effects) { if (effect.kind === "Alias") { state.assign(index++, effect.from, effect.into); } else { CompilerError.invariant(effect.kind === "Freeze", { reason: `Unexpected '${effect.kind}' effect for MaybeThrow terminal`, description: null, details: [ { kind: "error", loc: block.terminal.loc, message: null } ] }); } } } } for (const mutation of mutations) { state.mutate( mutation.index, mutation.place.identifier, makeInstructionId(mutation.id + 1), mutation.transitive, mutation.kind, mutation.place.loc, mutation.reason, errors ); } for (const render of renders) { state.render(render.index, render.place.identifier, errors); } for (const param of [...fn.context, ...fn.params]) { const place = param.kind === "Identifier" ? param : param.place; const node = state.nodes.get(place.identifier); if (node == null) { continue; } let mutated = false; if (node.local != null) { if (node.local.kind === 1 /* Conditional */) { mutated = true; functionEffects.push({ kind: "MutateConditionally", value: __spreadProps(__spreadValues({}, place), { loc: node.local.loc }) }); } else if (node.local.kind === 2 /* Definite */) { mutated = true; functionEffects.push({ kind: "Mutate", value: __spreadProps(__spreadValues({}, place), { loc: node.local.loc }), reason: node.mutationReason }); } } if (node.transitive != null) { if (node.transitive.kind === 1 /* Conditional */) { mutated = true; functionEffects.push({ kind: "MutateTransitiveConditionally", value: __spreadProps(__spreadValues({}, place), { loc: node.transitive.loc }) }); } else if (node.transitive.kind === 2 /* Definite */) { mutated = true; functionEffects.push({ kind: "MutateTransitive", value: __spreadProps(__spreadValues({}, place), { loc: node.transitive.loc }) }); } } if (mutated) { place.effect = "capture" /* Capture */; } } for (const block of fn.body.blocks.values()) { for (const phi of block.phis) { phi.place.effect = "store" /* Store */; const isPhiMutatedAfterCreation = phi.place.identifier.mutableRange.end > ((_c = (_b = block.instructions.at(0)) == null ? void 0 : _b.id) != null ? _c : block.terminal.id); for (const operand of phi.operands.values()) { operand.effect = isPhiMutatedAfterCreation ? "capture" /* Capture */ : "read" /* Read */; } if (isPhiMutatedAfterCreation && phi.place.identifier.mutableRange.start === 0) { const firstInstructionIdOfBlock = (_e = (_d = block.instructions.at(0)) == null ? void 0 : _d.id) != null ? _e : block.terminal.id; phi.place.identifier.mutableRange.start = makeInstructionId( firstInstructionIdOfBlock - 1 ); } } for (const instr of block.instructions) { for (const lvalue of eachInstructionLValue(instr)) { lvalue.effect = "mutate?" /* ConditionallyMutate */; if (lvalue.identifier.mutableRange.start === 0) { lvalue.identifier.mutableRange.start = instr.id; } if (lvalue.identifier.mutableRange.end === 0) { lvalue.identifier.mutableRange.end = makeInstructionId( Math.max(instr.id + 1, lvalue.identifier.mutableRange.end) ); } } for (const operand of eachInstructionValueOperand(instr.value)) { operand.effect = "read" /* Read */; } if (instr.effects == null) { continue; } const operandEffects = /* @__PURE__ */ new Map(); for (const effect of instr.effects) { switch (effect.kind) { case "Assign": case "Alias": case "Capture": case "CreateFrom": case "MaybeAlias": { const isMutatedOrReassigned = effect.into.identifier.mutableRange.end > instr.id; if (isMutatedOrReassigned) { operandEffects.set(effect.from.identifier.id, "capture" /* Capture */); operandEffects.set(effect.into.identifier.id, "store" /* Store */); } else { operandEffects.set(effect.from.identifier.id, "read" /* Read */); operandEffects.set(effect.into.identifier.id, "store" /* Store */); } break; } case "CreateFunction": case "Create": { break; } case "Mutate": { operandEffects.set(effect.value.identifier.id, "store" /* Store */); break; } case "Apply": { CompilerError.invariant(false, { reason: `[AnalyzeFunctions] Expected Apply effects to be replaced with more precise effects`, description: null, details: [ { kind: "error", loc: effect.function.loc, message: null } ] }); } case "MutateTransitive": case "MutateConditionally": case "MutateTransitiveConditionally": { operandEffects.set( effect.value.identifier.id, "mutate?" /* ConditionallyMutate */ ); break; } case "Freeze": { operandEffects.set(effect.value.identifier.id, "freeze" /* Freeze */); break; } case "ImmutableCapture": { break; } case "Impure": case "Render": case "MutateFrozen": case "MutateGlobal": { break; } default: { assertExhaustive( effect, `Unexpected effect kind ${effect.kind}` ); } } } for (const lvalue of eachInstructionLValue(instr)) { const effect = (_f = operandEffects.get(lvalue.identifier.id)) != null ? _f : "mutate?" /* ConditionallyMutate */; lvalue.effect = effect; } for (const operand of eachInstructionValueOperand(instr.value)) { if (operand.identifier.mutableRange.end > instr.id && operand.identifier.mutableRange.start === 0) { operand.identifier.mutableRange.start = instr.id; } const effect = (_g = operandEffects.get(operand.identifier.id)) != null ? _g : "read" /* Read */; operand.effect = effect; } if (instr.value.kind === "StoreContext" && instr.value.value.identifier.mutableRange.end <= instr.id) { instr.value.value.identifier.mutableRange.end = makeInstructionId( instr.id + 1 ); } } if (block.terminal.kind === "return") { block.terminal.value.effect = isFunctionExpression ? "read" /* Read */ : "freeze" /* Freeze */; } else { for (const operand of eachTerminalOperand(block.terminal)) { operand.effect = "read" /* Read */; } } } const returns = fn.returns.identifier; functionEffects.push({ kind: "Create", into: fn.returns, value: isPrimitiveType(returns) ? "primitive" /* Primitive */ : isJsxType(returns.type) ? "frozen" /* Frozen */ : "mutable" /* Mutable */, reason: "known-return-signature" /* KnownReturnSignature */ }); const tracked = []; const ignoredErrors = new CompilerError(); for (const param of [...fn.params, ...fn.context, fn.returns]) { const place = param.kind === "Identifier" ? param : param.place; tracked.push(place); } for (const into of tracked) { const mutationIndex = index++; state.mutate( mutationIndex, into.identifier, null, true, 1 /* Conditional */, into.loc, null, ignoredErrors ); for (const from of tracked) { if (from.identifier.id === into.identifier.id || from.identifier.id === fn.returns.identifier.id) { continue; } const fromNode = state.nodes.get(from.identifier); CompilerError.invariant(fromNode != null, { reason: `Expected a node to exist for all parameters and context variables`, description: null, details: [ { kind: "error", loc: into.loc, message: null } ] }); if (fromNode.lastMutated === mutationIndex) { if (into.identifier.id === fn.returns.identifier.id) { functionEffects.push({ kind: "Alias", from, into }); } else { functionEffects.push({ kind: "Capture", from, into }); } } } } if (errors.hasAnyErrors() && !isFunctionExpression) { return Err(errors); } return Ok(functionEffects); } function appendFunctionErrors(errors, fn) { var _a; for (const effect of (_a = fn.aliasingEffects) != null ? _a : []) { switch (effect.kind) { case "Impure": case "MutateFrozen": case "MutateGlobal": { errors.pushDiagnostic(effect.error); break; } } } } var AliasingState = class { constructor() { this.nodes = /* @__PURE__ */ new Map(); } create(place, value) { this.nodes.set(place.identifier, { id: place.identifier, createdFrom: /* @__PURE__ */ new Map(), captures: /* @__PURE__ */ new Map(), aliases: /* @__PURE__ */ new Map(), maybeAliases: /* @__PURE__ */ new Map(), edges: [], transitive: null, local: null, lastMutated: 0, mutationReason: null, value }); } createFrom(index, from, into) { this.create(into, { kind: "Object" }); const fromNode = this.nodes.get(from.identifier); const toNode = this.nodes.get(into.identifier); if (fromNode == null || toNode == null) { return; } fromNode.edges.push({ index, node: into.identifier, kind: "alias" }); if (!toNode.createdFrom.has(from.identifier)) { toNode.createdFrom.set(from.identifier, index); } } capture(index, from, into) { const fromNode = this.nodes.get(from.identifier); const toNode = this.nodes.get(into.identifier); if (fromNode == null || toNode == null) { return; } fromNode.edges.push({ index, node: into.identifier, kind: "capture" }); if (!toNode.captures.has(from.identifier)) { toNode.captures.set(from.identifier, index); } } assign(index, from, into) { const fromNode = this.nodes.get(from.identifier); const toNode = this.nodes.get(into.identifier); if (fromNode == null || toNode == null) { return; } fromNode.edges.push({ index, node: into.identifier, kind: "alias" }); if (!toNode.aliases.has(from.identifier)) { toNode.aliases.set(from.identifier, index); } } maybeAlias(index, from, into) { const fromNode = this.nodes.get(from.identifier); const toNode = this.nodes.get(into.identifier); if (fromNode == null || toNode == null) { return; } fromNode.edges.push({ index, node: into.identifier, kind: "maybeAlias" }); if (!toNode.maybeAliases.has(from.identifier)) { toNode.maybeAliases.set(from.identifier, index); } } render(index, start, errors) { const seen = /* @__PURE__ */ new Set(); const queue = [start]; while (queue.length !== 0) { const current = queue.pop(); if (seen.has(current)) { continue; } seen.add(current); const node = this.nodes.get(current); if (node == null || node.transitive != null || node.local != null) { continue; } if (node.value.kind === "Function") { appendFunctionErrors(errors, node.value.function); } for (const [alias, when] of node.createdFrom) { if (when >= index) { continue; } queue.push(alias); } for (const [alias, when] of node.aliases) { if (when >= index) { continue; } queue.push(alias); } for (const [capture, when] of node.captures) { if (when >= index) { continue; } queue.push(capture); } } } mutate(index, start, end, transitive, startKind, loc, reason, errors) { var _a; const seen = /* @__PURE__ */ new Map(); const queue = [{ place: start, transitive, direction: "backwards", kind: startKind }]; while (queue.length !== 0) { const { place: current, transitive: transitive2, direction, kind } = queue.pop(); const previousKind = seen.get(current); if (previousKind != null && previousKind >= kind) { continue; } seen.set(current, kind); const node = this.nodes.get(current); if (node == null) { continue; } (_a = node.mutationReason) != null ? _a : node.mutationReason = reason; node.lastMutated = Math.max(node.lastMutated, index); if (end != null) { node.id.mutableRange.end = makeInstructionId( Math.max(node.id.mutableRange.end, end) ); } if (node.value.kind === "Function" && node.transitive == null && node.local == null) { appendFunctionErrors(errors, node.value.function); } if (transitive2) { if (node.transitive == null || node.transitive.kind < kind) { node.transitive = { kind, loc }; } } else { if (node.local == null || node.local.kind < kind) { node.local = { kind, loc }; } } for (const edge of node.edges) { if (edge.index >= index) { break; } queue.push({ place: edge.node, transitive: transitive2, direction: "forwards", // Traversing a maybeAlias edge always downgrades to conditional mutation kind: edge.kind === "maybeAlias" ? 1 /* Conditional */ : kind }); } for (const [alias, when] of node.createdFrom) { if (when >= index) { continue; } queue.push({ place: alias, transitive: true, direction: "backwards", kind }); } if (direction === "backwards" || node.value.kind !== "Phi") { for (const [alias, when] of node.aliases) { if (when >= index) { continue; } queue.push({ place: alias, transitive: transitive2, direction: "backwards", kind }); } for (const [alias, when] of node.maybeAliases) { if (when >= index) { continue; } queue.push({ place: alias, transitive: transitive2, direction: "backwards", kind: 1 /* Conditional */ }); } } if (transitive2) { for (const [capture, when] of node.captures) { if (when >= index) { continue; } queue.push({ place: capture, transitive: transitive2, direction: "backwards", kind }); } } } } }; // src/Inference/AnalyseFunctions.ts function analyseFunctions(func) { for (const [_, block] of func.body.blocks) { for (const instr of block.instructions) { switch (instr.value.kind) { case "ObjectMethod": case "FunctionExpression": { lowerWithMutationAliasing(instr.value.loweredFunc.func); for (const operand of instr.value.loweredFunc.func.context) { operand.identifier.mutableRange = { start: makeInstructionId(0), end: makeInstructionId(0) }; operand.identifier.scope = null; } break; } } } } } function lowerWithMutationAliasing(fn) { var _a, _b; analyseFunctions(fn); inferMutationAliasingEffects(fn, { isFunctionExpression: true }); deadCodeElimination(fn); const functionEffects = inferMutationAliasingRanges(fn, { isFunctionExpression: true }).unwrap(); rewriteInstructionKindsBasedOnReassignment(fn); inferReactiveScopeVariables(fn); fn.aliasingEffects = functionEffects; const capturedOrMutated = /* @__PURE__ */ new Set(); for (const effect of functionEffects) { switch (effect.kind) { case "Assign": case "Alias": case "Capture": case "CreateFrom": case "MaybeAlias": { capturedOrMutated.add(effect.from.identifier.id); break; } case "Apply": { CompilerError.invariant(false, { reason: `[AnalyzeFunctions] Expected Apply effects to be replaced with more precise effects`, description: null, details: [ { kind: "error", loc: effect.function.loc, message: null } ] }); } case "Mutate": case "MutateConditionally": case "MutateTransitive": case "MutateTransitiveConditionally": { capturedOrMutated.add(effect.value.identifier.id); break; } case "Impure": case "Render": case "MutateFrozen": case "MutateGlobal": case "CreateFunction": case "Create": case "Freeze": case "ImmutableCapture": { break; } default: { assertExhaustive( effect, `Unexpected effect kind ${effect.kind}` ); } } } for (const operand of fn.context) { if (capturedOrMutated.has(operand.identifier.id) || operand.effect === "capture" /* Capture */) { operand.effect = "capture" /* Capture */; } else { operand.effect = "read" /* Read */; } } (_b = (_a = fn.env.logger) == null ? void 0 : _a.debugLogIRs) == null ? void 0 : _b.call(_a, { kind: "hir", name: "AnalyseFunction (inner)", value: fn }); } // src/Inference/DropManualMemoization.ts function collectMaybeMemoDependencies(value, maybeDeps, optional2) { var _a; switch (value.kind) { case "LoadGlobal": { return { root: { kind: "Global", identifierName: value.binding.name }, path: [] }; } case "PropertyLoad": { const object2 = maybeDeps.get(value.object.identifier.id); if (object2 != null) { return { root: object2.root, // TODO: determine if the access is optional path: [...object2.path, { property: value.property, optional: optional2 }] }; } break; } case "LoadLocal": case "LoadContext": { const source2 = maybeDeps.get(value.place.identifier.id); if (source2 != null) { return source2; } else if (value.place.identifier.name != null && value.place.identifier.name.kind === "named") { return { root: { kind: "NamedLocal", value: __spreadValues({}, value.place) }, path: [] }; } break; } case "StoreLocal": { const lvalue = value.lvalue.place.identifier; const rvalue = value.value.identifier.id; const aliased = maybeDeps.get(rvalue); if (aliased != null && ((_a = lvalue.name) == null ? void 0 : _a.kind) !== "named") { maybeDeps.set(lvalue.id, aliased); return aliased; } break; } } return null; } function collectTemporaries(instr, env, sidemap) { const { value, lvalue } = instr; switch (value.kind) { case "FunctionExpression": { sidemap.functions.set( instr.lvalue.identifier.id, instr ); break; } case "LoadGlobal": { const global2 = env.getGlobalDeclaration(value.binding, value.loc); const hookKind = global2 !== null ? getHookKindForType(env, global2) : null; const lvalId = instr.lvalue.identifier.id; if (hookKind === "useMemo" || hookKind === "useCallback") { sidemap.manualMemos.set(lvalId, { kind: hookKind, loadInstr: instr }); } else if (value.binding.name === "React") { sidemap.react.add(lvalId); } break; } case "PropertyLoad": { if (sidemap.react.has(value.object.identifier.id)) { const property = value.property; if (property === "useMemo" || property === "useCallback") { sidemap.manualMemos.set(instr.lvalue.identifier.id, { kind: property, loadInstr: instr }); } } break; } case "ArrayExpression": { if (value.elements.every((e) => e.kind === "Identifier")) { sidemap.maybeDepsLists.set( instr.lvalue.identifier.id, value.elements ); } break; } } const maybeDep = collectMaybeMemoDependencies( value, sidemap.maybeDeps, sidemap.optionals.has(lvalue.identifier.id) ); if (maybeDep != null) { sidemap.maybeDeps.set(lvalue.identifier.id, maybeDep); } } function makeManualMemoizationMarkers(fnExpr, env, depsList, memoDecl, manualMemoId) { return [ { id: makeInstructionId(0), lvalue: createTemporaryPlace(env, fnExpr.loc), value: { kind: "StartMemoize", manualMemoId, /* * Use deps list from source instead of inferred deps * as dependencies */ deps: depsList, loc: fnExpr.loc }, effects: null, loc: fnExpr.loc }, { id: makeInstructionId(0), lvalue: createTemporaryPlace(env, fnExpr.loc), value: { kind: "FinishMemoize", manualMemoId, decl: __spreadValues({}, memoDecl), loc: fnExpr.loc }, effects: null, loc: fnExpr.loc } ]; } function getManualMemoizationReplacement(fn, loc, kind) { if (kind === "useMemo") { return { kind: "CallExpression", callee: fn, /* * Drop the args, including the deps array which DCE will remove * later. */ args: [], loc }; } else { return { kind: "LoadLocal", place: { kind: "Identifier", identifier: fn.identifier, effect: "" /* Unknown */, reactive: false, loc }, loc }; } } function extractManualMemoizationArgs(instr, kind, sidemap, errors) { const [fnPlace, depsListPlace] = instr.value.args; if (fnPlace == null) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "UseMemo" /* UseMemo */, reason: `Expected a callback function to be passed to ${kind}`, description: `Expected a callback function to be passed to ${kind}`, suggestions: null }).withDetails({ kind: "error", loc: instr.value.loc, message: `Expected a callback function to be passed to ${kind}` }) ); return { fnPlace: null, depsList: null }; } if (fnPlace.kind === "Spread" || (depsListPlace == null ? void 0 : depsListPlace.kind) === "Spread") { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "UseMemo" /* UseMemo */, reason: `Unexpected spread argument to ${kind}`, description: `Unexpected spread argument to ${kind}`, suggestions: null }).withDetails({ kind: "error", loc: instr.value.loc, message: `Unexpected spread argument to ${kind}` }) ); return { fnPlace: null, depsList: null }; } let depsList = null; if (depsListPlace != null) { const maybeDepsList = sidemap.maybeDepsLists.get( depsListPlace.identifier.id ); if (maybeDepsList == null) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "UseMemo" /* UseMemo */, reason: `Expected the dependency list for ${kind} to be an array literal`, description: `Expected the dependency list for ${kind} to be an array literal`, suggestions: null }).withDetails({ kind: "error", loc: depsListPlace.loc, message: `Expected the dependency list for ${kind} to be an array literal` }) ); return { fnPlace, depsList: null }; } depsList = []; for (const dep of maybeDepsList) { const maybeDep = sidemap.maybeDeps.get(dep.identifier.id); if (maybeDep == null) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "UseMemo" /* UseMemo */, reason: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)`, description: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)`, suggestions: null }).withDetails({ kind: "error", loc: dep.loc, message: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)` }) ); } else { depsList.push(maybeDep); } } } return { fnPlace, depsList }; } function dropManualMemoization(func) { var _a; const errors = new CompilerError(); const isValidationEnabled = func.env.config.validatePreserveExistingMemoizationGuarantees || func.env.config.validateNoSetStateInRender || func.env.config.enablePreserveExistingMemoizationGuarantees; const optionals = findOptionalPlaces(func); const sidemap = { functions: /* @__PURE__ */ new Map(), manualMemos: /* @__PURE__ */ new Map(), react: /* @__PURE__ */ new Set(), maybeDeps: /* @__PURE__ */ new Map(), maybeDepsLists: /* @__PURE__ */ new Map(), optionals }; let nextManualMemoId = 0; const queuedInserts = /* @__PURE__ */ new Map(); for (const [_, block] of func.body.blocks) { for (let i = 0; i < block.instructions.length; i++) { const instr = block.instructions[i]; if (instr.value.kind === "CallExpression" || instr.value.kind === "MethodCall") { const id = instr.value.kind === "CallExpression" ? instr.value.callee.identifier.id : instr.value.property.identifier.id; const manualMemo = sidemap.manualMemos.get(id); if (manualMemo != null) { const { fnPlace, depsList } = extractManualMemoizationArgs( instr, manualMemo.kind, sidemap, errors ); if (fnPlace == null) { continue; } if (func.env.config.validateNoVoidUseMemo && manualMemo.kind === "useMemo") { const funcToCheck = (_a = sidemap.functions.get( fnPlace.identifier.id )) == null ? void 0 : _a.value; if (funcToCheck !== void 0 && funcToCheck.loweredFunc.func) { if (!hasNonVoidReturn(funcToCheck.loweredFunc.func)) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "UseMemo" /* UseMemo */, reason: "useMemo() callbacks must return a value", description: `This ${manualMemo.loadInstr.value.kind === "PropertyLoad" ? "React.useMemo" : "useMemo"} callback doesn't return a value. useMemo is for computing and caching values, not for arbitrary side effects`, suggestions: null }).withDetails({ kind: "error", loc: instr.value.loc, message: "useMemo() callbacks must return a value" }) ); } } } instr.value = getManualMemoizationReplacement( fnPlace, instr.value.loc, manualMemo.kind ); if (isValidationEnabled) { if (!sidemap.functions.has(fnPlace.identifier.id)) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "UseMemo" /* UseMemo */, reason: `Expected the first argument to be an inline function expression`, description: `Expected the first argument to be an inline function expression`, suggestions: [] }).withDetails({ kind: "error", loc: fnPlace.loc, message: `Expected the first argument to be an inline function expression` }) ); continue; } const memoDecl = manualMemo.kind === "useMemo" ? instr.lvalue : { kind: "Identifier", identifier: fnPlace.identifier, effect: "" /* Unknown */, reactive: false, loc: fnPlace.loc }; const [startMarker, finishMarker] = makeManualMemoizationMarkers( fnPlace, func.env, depsList, memoDecl, nextManualMemoId++ ); queuedInserts.set(manualMemo.loadInstr.id, startMarker); queuedInserts.set(instr.id, finishMarker); } } } else { collectTemporaries(instr, func.env, sidemap); } } } if (queuedInserts.size > 0) { let hasChanges = false; for (const [_, block] of func.body.blocks) { let nextInstructions = null; for (let i = 0; i < block.instructions.length; i++) { const instr = block.instructions[i]; const insertInstr = queuedInserts.get(instr.id); if (insertInstr != null) { nextInstructions = nextInstructions != null ? nextInstructions : block.instructions.slice(0, i); nextInstructions.push(instr); nextInstructions.push(insertInstr); } else if (nextInstructions != null) { nextInstructions.push(instr); } } if (nextInstructions !== null) { block.instructions = nextInstructions; hasChanges = true; } } if (hasChanges) { markInstructionIds(func.body); } } return errors.asResult(); } function findOptionalPlaces(fn) { const optionals = /* @__PURE__ */ new Set(); for (const [, block] of fn.body.blocks) { if (block.terminal.kind === "optional" && block.terminal.optional) { const optionalTerminal = block.terminal; let testBlock = fn.body.blocks.get(block.terminal.test); loop: while (true) { const terminal = testBlock.terminal; switch (terminal.kind) { case "branch": { if (terminal.fallthrough === optionalTerminal.fallthrough) { const consequent = fn.body.blocks.get(terminal.consequent); const last = consequent.instructions.at(-1); if (last !== void 0 && last.value.kind === "StoreLocal") { optionals.add(last.value.value.identifier.id); } break loop; } else { testBlock = fn.body.blocks.get(terminal.fallthrough); } break; } case "optional": case "logical": case "sequence": case "ternary": { testBlock = fn.body.blocks.get(terminal.fallthrough); break; } default: { CompilerError.invariant(false, { reason: `Unexpected terminal in optional`, description: null, details: [ { kind: "error", loc: terminal.loc, message: `Unexpected ${terminal.kind} in optional` } ] }); } } } } } return optionals; } function hasNonVoidReturn(func) { for (const [, block] of func.body.blocks) { if (block.terminal.kind === "return") { if (block.terminal.returnVariant === "Explicit" || block.terminal.returnVariant === "Implicit") { return true; } } } return false; } // src/Inference/InferReactivePlaces.ts var StableSidemap = class { constructor(env) { this.map = /* @__PURE__ */ new Map(); this.env = env; } handleInstruction(instr) { const { value, lvalue } = instr; switch (value.kind) { case "CallExpression": case "MethodCall": { if (evaluatesToStableTypeOrContainer(this.env, instr)) { if (isStableType(lvalue.identifier)) { this.map.set(lvalue.identifier.id, { isStable: true }); } else { this.map.set(lvalue.identifier.id, { isStable: false }); } } break; } case "Destructure": case "PropertyLoad": { const source2 = value.kind === "Destructure" ? value.value.identifier.id : value.object.identifier.id; const entry = this.map.get(source2); if (entry) { for (const lvalue2 of eachInstructionLValue(instr)) { if (isStableTypeContainer(lvalue2.identifier)) { this.map.set(lvalue2.identifier.id, { isStable: false }); } else if (isStableType(lvalue2.identifier)) { this.map.set(lvalue2.identifier.id, { isStable: true }); } } } break; } case "StoreLocal": { const entry = this.map.get(value.value.identifier.id); if (entry) { this.map.set(lvalue.identifier.id, entry); this.map.set(value.lvalue.place.identifier.id, entry); } break; } case "LoadLocal": { const entry = this.map.get(value.place.identifier.id); if (entry) { this.map.set(lvalue.identifier.id, entry); } break; } } } isStable(id) { const entry = this.map.get(id); return entry != null ? entry.isStable : false; } }; function inferReactivePlaces(fn) { const reactiveIdentifiers = new ReactivityMap(findDisjointMutableValues(fn)); const stableIdentifierSources = new StableSidemap(fn.env); for (const param of fn.params) { const place = param.kind === "Identifier" ? param : param.place; reactiveIdentifiers.markReactive(place); } const postDominators = computePostDominatorTree(fn, { includeThrowsAsExitNode: false }); const postDominatorFrontierCache = /* @__PURE__ */ new Map(); function isReactiveControlledBlock(id) { let controlBlocks = postDominatorFrontierCache.get(id); if (controlBlocks === void 0) { controlBlocks = postDominatorFrontier(fn, postDominators, id); postDominatorFrontierCache.set(id, controlBlocks); } for (const blockId of controlBlocks) { const controlBlock = fn.body.blocks.get(blockId); switch (controlBlock.terminal.kind) { case "if": case "branch": { if (reactiveIdentifiers.isReactive(controlBlock.terminal.test)) { return true; } break; } case "switch": { if (reactiveIdentifiers.isReactive(controlBlock.terminal.test)) { return true; } for (const case_ of controlBlock.terminal.cases) { if (case_.test !== null && reactiveIdentifiers.isReactive(case_.test)) { return true; } } break; } } } return false; } do { for (const [, block] of fn.body.blocks) { let hasReactiveControl = isReactiveControlledBlock(block.id); for (const phi of block.phis) { if (reactiveIdentifiers.isReactive(phi.place)) { continue; } let isPhiReactive = false; for (const [, operand] of phi.operands) { if (reactiveIdentifiers.isReactive(operand)) { isPhiReactive = true; break; } } if (isPhiReactive) { reactiveIdentifiers.markReactive(phi.place); } else { for (const [pred] of phi.operands) { if (isReactiveControlledBlock(pred)) { reactiveIdentifiers.markReactive(phi.place); break; } } } } for (const instruction of block.instructions) { stableIdentifierSources.handleInstruction(instruction); const { value } = instruction; let hasReactiveInput = false; for (const operand of eachInstructionValueOperand(value)) { const reactive = reactiveIdentifiers.isReactive(operand); hasReactiveInput || (hasReactiveInput = reactive); } if (value.kind === "CallExpression" && (getHookKind(fn.env, value.callee.identifier) != null || isUseOperator(value.callee.identifier))) { hasReactiveInput = true; } else if (value.kind === "MethodCall" && (getHookKind(fn.env, value.property.identifier) != null || isUseOperator(value.property.identifier))) { hasReactiveInput = true; } if (hasReactiveInput) { for (const lvalue of eachInstructionLValue(instruction)) { if (stableIdentifierSources.isStable(lvalue.identifier.id)) { continue; } reactiveIdentifiers.markReactive(lvalue); } } if (hasReactiveInput || hasReactiveControl) { for (const operand of eachInstructionValueOperand(value)) { switch (operand.effect) { case "capture" /* Capture */: case "store" /* Store */: case "mutate?" /* ConditionallyMutate */: case "mutate-iterator?" /* ConditionallyMutateIterator */: case "mutate" /* Mutate */: { if (isMutable2(instruction, operand)) { reactiveIdentifiers.markReactive(operand); } break; } case "freeze" /* Freeze */: case "read" /* Read */: { break; } case "" /* Unknown */: { CompilerError.invariant(false, { reason: "Unexpected unknown effect", description: null, details: [ { kind: "error", loc: operand.loc, message: null } ], suggestions: null }); } default: { assertExhaustive( operand.effect, `Unexpected effect kind \`${operand.effect}\`` ); } } } } } for (const operand of eachTerminalOperand(block.terminal)) { reactiveIdentifiers.isReactive(operand); } } } while (reactiveIdentifiers.snapshot()); function propagateReactivityToInnerFunctions(fn2, isOutermost) { for (const [, block] of fn2.body.blocks) { for (const instr of block.instructions) { if (!isOutermost) { for (const operand of eachInstructionOperand(instr)) { reactiveIdentifiers.isReactive(operand); } } if (instr.value.kind === "ObjectMethod" || instr.value.kind === "FunctionExpression") { propagateReactivityToInnerFunctions( instr.value.loweredFunc.func, false ); } } if (!isOutermost) { for (const operand of eachTerminalOperand(block.terminal)) { reactiveIdentifiers.isReactive(operand); } } } } propagateReactivityToInnerFunctions(fn, true); } function postDominatorFrontier(fn, postDominators, targetId) { const visited = /* @__PURE__ */ new Set(); const frontier = /* @__PURE__ */ new Set(); const targetPostDominators = postDominatorsOf(fn, postDominators, targetId); for (const blockId of [...targetPostDominators, targetId]) { if (visited.has(blockId)) { continue; } visited.add(blockId); const block = fn.body.blocks.get(blockId); for (const pred of block.preds) { if (!targetPostDominators.has(pred)) { frontier.add(pred); } } } return frontier; } function postDominatorsOf(fn, postDominators, targetId) { var _a; const result = /* @__PURE__ */ new Set(); const visited = /* @__PURE__ */ new Set(); const queue = [targetId]; while (queue.length) { const currentId = queue.shift(); if (visited.has(currentId)) { continue; } visited.add(currentId); const current = fn.body.blocks.get(currentId); for (const pred of current.preds) { const predPostDominator = (_a = postDominators.get(pred)) != null ? _a : pred; if (predPostDominator === targetId || result.has(predPostDominator)) { result.add(pred); } queue.push(pred); } } return result; } var ReactivityMap = class { constructor(aliasedIdentifiers) { this.hasChanges = false; this.reactive = /* @__PURE__ */ new Set(); this.aliasedIdentifiers = aliasedIdentifiers; } isReactive(place) { var _a; const identifier4 = (_a = this.aliasedIdentifiers.find(place.identifier)) != null ? _a : place.identifier; const reactive = this.reactive.has(identifier4.id); if (reactive) { place.reactive = true; } return reactive; } markReactive(place) { var _a; place.reactive = true; const identifier4 = (_a = this.aliasedIdentifiers.find(place.identifier)) != null ? _a : place.identifier; if (!this.reactive.has(identifier4.id)) { this.hasChanges = true; this.reactive.add(identifier4.id); } } snapshot() { const hasChanges = this.hasChanges; this.hasChanges = false; return hasChanges; } }; // src/Inference/InlineImmediatelyInvokedFunctionExpressions.ts function inlineImmediatelyInvokedFunctionExpressions(fn) { const functions = /* @__PURE__ */ new Map(); const inlinedFunctions = /* @__PURE__ */ new Set(); const queue = Array.from(fn.body.blocks.values()); queue: for (const block of queue) { if (isStatementBlockKind(block.kind)) { for (let ii = 0; ii < block.instructions.length; ii++) { const instr = block.instructions[ii]; switch (instr.value.kind) { case "FunctionExpression": { if (instr.lvalue.identifier.name === null) { functions.set(instr.lvalue.identifier.id, instr.value); } break; } case "CallExpression": { if (instr.value.args.length !== 0) { continue; } const body = functions.get(instr.value.callee.identifier.id); if (body === void 0) { continue; } if (body.loweredFunc.func.params.length > 0 || body.loweredFunc.func.async || body.loweredFunc.func.generator) { continue; } inlinedFunctions.add(instr.value.callee.identifier.id); const continuationBlockId = fn.env.nextBlockId; const continuationBlock = { id: continuationBlockId, instructions: block.instructions.slice(ii + 1), kind: block.kind, phis: /* @__PURE__ */ new Set(), preds: /* @__PURE__ */ new Set(), terminal: block.terminal }; fn.body.blocks.set(continuationBlockId, continuationBlock); block.instructions.length = ii; if (hasSingleExitReturnTerminal(body.loweredFunc.func)) { block.terminal = { kind: "goto", block: body.loweredFunc.func.body.entry, id: block.terminal.id, loc: block.terminal.loc, variant: "Break" /* Break */ }; for (const block2 of body.loweredFunc.func.body.blocks.values()) { if (block2.terminal.kind === "return") { block2.instructions.push({ id: makeInstructionId(0), loc: block2.terminal.loc, lvalue: instr.lvalue, value: { kind: "LoadLocal", loc: block2.terminal.loc, place: block2.terminal.value }, effects: null }); block2.terminal = { kind: "goto", block: continuationBlockId, id: block2.terminal.id, loc: block2.terminal.loc, variant: "Break" /* Break */ }; } } for (const [id, block2] of body.loweredFunc.func.body.blocks) { block2.preds.clear(); fn.body.blocks.set(id, block2); } } else { const newTerminal = { block: body.loweredFunc.func.body.entry, id: makeInstructionId(0), kind: "label", fallthrough: continuationBlockId, loc: block.terminal.loc }; block.terminal = newTerminal; const result = instr.lvalue; declareTemporary(fn.env, block, result); if (result.identifier.name == null) { promoteTemporary(result.identifier); } for (const [id, block2] of body.loweredFunc.func.body.blocks) { block2.preds.clear(); rewriteBlock(fn.env, block2, continuationBlockId, result); fn.body.blocks.set(id, block2); } } queue.push(continuationBlock); continue queue; } default: { for (const place of eachInstructionValueOperand(instr.value)) { functions.delete(place.identifier.id); } } } } } } if (inlinedFunctions.size !== 0) { for (const block of fn.body.blocks.values()) { retainWhere( block.instructions, (instr) => !inlinedFunctions.has(instr.lvalue.identifier.id) ); } reversePostorderBlocks(fn.body); markInstructionIds(fn.body); markPredecessors(fn.body); mergeConsecutiveBlocks(fn); } } function hasSingleExitReturnTerminal(fn) { let hasReturn = false; let exitCount = 0; for (const [, block] of fn.body.blocks) { if (block.terminal.kind === "return" || block.terminal.kind === "throw") { hasReturn || (hasReturn = block.terminal.kind === "return"); exitCount++; } } return exitCount === 1 && hasReturn; } function rewriteBlock(env, block, returnTarget, returnValue) { const { terminal } = block; if (terminal.kind !== "return") { return; } block.instructions.push({ id: makeInstructionId(0), loc: terminal.loc, lvalue: createTemporaryPlace(env, terminal.loc), value: { kind: "StoreLocal", lvalue: { kind: "Reassign" /* Reassign */, place: __spreadValues({}, returnValue) }, value: terminal.value, type: null, loc: terminal.loc }, effects: null }); block.terminal = { kind: "goto", block: returnTarget, id: makeInstructionId(0), variant: "Break" /* Break */, loc: block.terminal.loc }; } function declareTemporary(env, block, result) { block.instructions.push({ id: makeInstructionId(0), loc: GeneratedSource, lvalue: createTemporaryPlace(env, result.loc), value: { kind: "DeclareLocal", lvalue: { place: result, kind: "Let" /* Let */ }, type: null, loc: result.loc }, effects: null }); } // src/HIR/CollectHoistablePropertyLoads.ts var DEBUG_PRINT = false; function collectHoistablePropertyLoads(fn, temporaries, hoistableFromOptionals) { const registry2 = new PropertyPathRegistry(); const knownImmutableIdentifiers = /* @__PURE__ */ new Set(); if (fn.fnType === "Component" || fn.fnType === "Hook") { for (const p of fn.params) { if (p.kind === "Identifier") { knownImmutableIdentifiers.add(p.identifier.id); } } } return collectHoistablePropertyLoadsImpl(fn, { temporaries, knownImmutableIdentifiers, hoistableFromOptionals, registry: registry2, nestedFnImmutableContext: null, assumedInvokedFns: fn.env.config.enableTreatFunctionDepsAsConditional ? /* @__PURE__ */ new Set() : getAssumedInvokedFunctions(fn) }); } function collectHoistablePropertyLoadsInInnerFn(fnInstr, temporaries, hoistableFromOptionals) { const fn = fnInstr.value.loweredFunc.func; const initialContext = { temporaries, knownImmutableIdentifiers: /* @__PURE__ */ new Set(), hoistableFromOptionals, registry: new PropertyPathRegistry(), nestedFnImmutableContext: null, assumedInvokedFns: fn.env.config.enableTreatFunctionDepsAsConditional ? /* @__PURE__ */ new Set() : getAssumedInvokedFunctions(fn) }; const nestedFnImmutableContext = new Set( fn.context.filter( (place) => isImmutableAtInstr(place.identifier, fnInstr.id, initialContext) ).map((place) => place.identifier.id) ); initialContext.nestedFnImmutableContext = nestedFnImmutableContext; return collectHoistablePropertyLoadsImpl(fn, initialContext); } function collectHoistablePropertyLoadsImpl(fn, context) { const nodes = collectNonNullsInBlocks(fn, context); propagateNonNull(fn, nodes, context.registry); if (DEBUG_PRINT) { console.log("(printing hoistable nodes in blocks)"); for (const [blockId, node] of nodes) { console.log( `bb${blockId}: ${[...node.assumedNonNullObjects].map((n) => printDependency(n.fullPath)).join(" ")}` ); } } return nodes; } function keyByScopeId(fn, source2) { const keyedByScopeId = /* @__PURE__ */ new Map(); for (const [_, block] of fn.body.blocks) { if (block.terminal.kind === "scope") { keyedByScopeId.set( block.terminal.scope.id, source2.get(block.terminal.block) ); } } return keyedByScopeId; } var PropertyPathRegistry = class _PropertyPathRegistry { constructor() { this.roots = /* @__PURE__ */ new Map(); } getOrCreateIdentifier(identifier4, reactive) { let rootNode = this.roots.get(identifier4.id); if (rootNode === void 0) { rootNode = { root: identifier4.id, properties: /* @__PURE__ */ new Map(), optionalProperties: /* @__PURE__ */ new Map(), fullPath: { identifier: identifier4, reactive, path: [] }, hasOptional: false, parent: null }; this.roots.set(identifier4.id, rootNode); } else { CompilerError.invariant(reactive === rootNode.fullPath.reactive, { reason: "[HoistablePropertyLoads] Found inconsistencies in `reactive` flag when deduping identifier reads within the same scope", description: null, details: [ { kind: "error", loc: identifier4.loc, message: null } ] }); } return rootNode; } static getOrCreatePropertyEntry(parent, entry) { const map2 = entry.optional ? parent.optionalProperties : parent.properties; let child = map2.get(entry.property); if (child == null) { child = { properties: /* @__PURE__ */ new Map(), optionalProperties: /* @__PURE__ */ new Map(), parent, fullPath: { identifier: parent.fullPath.identifier, reactive: parent.fullPath.reactive, path: parent.fullPath.path.concat(entry) }, hasOptional: parent.hasOptional || entry.optional }; map2.set(entry.property, child); } return child; } getOrCreateProperty(n) { let currNode = this.getOrCreateIdentifier(n.identifier, n.reactive); if (n.path.length === 0) { return currNode; } for (let i = 0; i < n.path.length - 1; i++) { currNode = _PropertyPathRegistry.getOrCreatePropertyEntry( currNode, n.path[i] ); } return _PropertyPathRegistry.getOrCreatePropertyEntry( currNode, n.path.at(-1) ); } }; function getMaybeNonNullInInstruction(instr, context) { var _a, _b, _c; let path = null; if (instr.kind === "PropertyLoad") { path = (_a = context.temporaries.get(instr.object.identifier.id)) != null ? _a : { identifier: instr.object.identifier, reactive: instr.object.reactive, path: [] }; } else if (instr.kind === "Destructure") { path = (_b = context.temporaries.get(instr.value.identifier.id)) != null ? _b : null; } else if (instr.kind === "ComputedLoad") { path = (_c = context.temporaries.get(instr.object.identifier.id)) != null ? _c : null; } return path != null ? context.registry.getOrCreateProperty(path) : null; } function isImmutableAtInstr(identifier4, instr, context) { if (context.nestedFnImmutableContext != null) { return context.nestedFnImmutableContext.has(identifier4.id); } else { const mutableAtInstr = identifier4.mutableRange.end > identifier4.mutableRange.start + 1 && identifier4.scope != null && inRange( { id: instr }, identifier4.scope.range ); return !mutableAtInstr || context.knownImmutableIdentifiers.has(identifier4.id); } } function collectNonNullsInBlocks(fn, context) { var _a; const knownNonNullIdentifiers = /* @__PURE__ */ new Set(); if (fn.fnType === "Component" && fn.params.length > 0 && fn.params[0].kind === "Identifier") { const identifier4 = fn.params[0].identifier; knownNonNullIdentifiers.add( context.registry.getOrCreateIdentifier(identifier4, true) ); } const nodes = /* @__PURE__ */ new Map(); for (const [_, block] of fn.body.blocks) { const assumedNonNullObjects = new Set( knownNonNullIdentifiers ); const maybeOptionalChain = context.hoistableFromOptionals.get(block.id); if (maybeOptionalChain != null) { assumedNonNullObjects.add( context.registry.getOrCreateProperty(maybeOptionalChain) ); } for (const instr of block.instructions) { const maybeNonNull = getMaybeNonNullInInstruction(instr.value, context); if (maybeNonNull != null && isImmutableAtInstr(maybeNonNull.fullPath.identifier, instr.id, context)) { assumedNonNullObjects.add(maybeNonNull); } if (instr.value.kind === "FunctionExpression") { const innerFn = instr.value.loweredFunc; if (context.assumedInvokedFns.has(innerFn)) { const innerHoistableMap = collectHoistablePropertyLoadsImpl( innerFn.func, __spreadProps(__spreadValues({}, context), { nestedFnImmutableContext: (_a = context.nestedFnImmutableContext) != null ? _a : new Set( innerFn.func.context.filter( (place) => isImmutableAtInstr(place.identifier, instr.id, context) ).map((place) => place.identifier.id) ) }) ); const innerHoistables = assertNonNull( innerHoistableMap.get(innerFn.func.body.entry) ); for (const entry of innerHoistables.assumedNonNullObjects) { assumedNonNullObjects.add(entry); } } } else if (fn.env.config.enablePreserveExistingMemoizationGuarantees && instr.value.kind === "StartMemoize" && instr.value.deps != null) { for (const dep of instr.value.deps) { if (dep.root.kind === "NamedLocal") { if (!isImmutableAtInstr(dep.root.value.identifier, instr.id, context)) { continue; } for (let i = 0; i < dep.path.length; i++) { const pathEntry = dep.path[i]; if (pathEntry.optional) { break; } const depNode = context.registry.getOrCreateProperty({ identifier: dep.root.value.identifier, path: dep.path.slice(0, i), reactive: dep.root.value.reactive }); assumedNonNullObjects.add(depNode); } } } } } nodes.set(block.id, { block, assumedNonNullObjects }); } return nodes; } function propagateNonNull(fn, nodes, registry2) { const blockSuccessors = /* @__PURE__ */ new Map(); const terminalPreds = /* @__PURE__ */ new Set(); for (const [blockId, block] of fn.body.blocks) { for (const pred of block.preds) { getOrInsertDefault(blockSuccessors, pred, /* @__PURE__ */ new Set()).add(blockId); } if (block.terminal.kind === "throw" || block.terminal.kind === "return") { terminalPreds.add(blockId); } } function recursivelyPropagateNonNull(nodeId, direction, traversalState2) { var _a; if (traversalState2.has(nodeId)) { return false; } traversalState2.set(nodeId, "active"); const node = nodes.get(nodeId); if (node == null) { CompilerError.invariant(false, { reason: `Bad node ${nodeId}, kind: ${direction}`, description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); } const neighbors = Array.from( direction === "backward" ? (_a = blockSuccessors.get(nodeId)) != null ? _a : [] : node.block.preds ); let changed2 = false; for (const pred of neighbors) { if (!traversalState2.has(pred)) { const neighborChanged = recursivelyPropagateNonNull( pred, direction, traversalState2 ); changed2 || (changed2 = neighborChanged); } } const neighborAccesses = Set_intersect( Array.from(neighbors).filter((n) => traversalState2.get(n) === "done").map((n) => assertNonNull(nodes.get(n)).assumedNonNullObjects) ); const prevObjects = assertNonNull(nodes.get(nodeId)).assumedNonNullObjects; const mergedObjects = Set_union(prevObjects, neighborAccesses); reduceMaybeOptionalChains(mergedObjects, registry2); assertNonNull(nodes.get(nodeId)).assumedNonNullObjects = mergedObjects; traversalState2.set(nodeId, "done"); changed2 || (changed2 = !Set_equal(prevObjects, mergedObjects)); return changed2; } const traversalState = /* @__PURE__ */ new Map(); const reversedBlocks = [...fn.body.blocks]; reversedBlocks.reverse(); let changed; let i = 0; do { CompilerError.invariant(i++ < 100, { reason: "[CollectHoistablePropertyLoads] fixed point iteration did not terminate after 100 loops", description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); changed = false; for (const [blockId] of fn.body.blocks) { const forwardChanged = recursivelyPropagateNonNull( blockId, "forward", traversalState ); changed || (changed = forwardChanged); } traversalState.clear(); for (const [blockId] of reversedBlocks) { const backwardChanged = recursivelyPropagateNonNull( blockId, "backward", traversalState ); changed || (changed = backwardChanged); } traversalState.clear(); } while (changed); } function assertNonNull(value, source2) { CompilerError.invariant(value != null, { reason: "Unexpected null", description: source2 != null ? `(from ${source2})` : null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); return value; } function reduceMaybeOptionalChains(nodes, registry2) { let optionalChainNodes = Set_filter(nodes, (n) => n.hasOptional); if (optionalChainNodes.size === 0) { return; } let changed; do { changed = false; for (const original of optionalChainNodes) { let { identifier: identifier4, path: origPath, reactive } = original.fullPath; let currNode = registry2.getOrCreateIdentifier( identifier4, reactive ); for (let i = 0; i < origPath.length; i++) { const entry = origPath[i]; const nextEntry = entry.optional && nodes.has(currNode) ? { property: entry.property, optional: false } : entry; currNode = PropertyPathRegistry.getOrCreatePropertyEntry( currNode, nextEntry ); } if (currNode !== original) { changed = true; optionalChainNodes.delete(original); optionalChainNodes.add(currNode); nodes.delete(original); nodes.add(currNode); } } } while (changed); } function getAssumedInvokedFunctions(fn, temporaries = /* @__PURE__ */ new Map()) { var _a; const hoistableFunctions = /* @__PURE__ */ new Set(); for (const block of fn.body.blocks.values()) { for (const { lvalue, value } of block.instructions) { if (value.kind === "FunctionExpression") { temporaries.set(lvalue.identifier.id, { fn: value.loweredFunc, mayInvoke: /* @__PURE__ */ new Set() }); } else if (value.kind === "StoreLocal") { const lvalue2 = value.lvalue.place.identifier; const maybeLoweredFunc = temporaries.get(value.value.identifier.id); if (maybeLoweredFunc != null) { temporaries.set(lvalue2.id, maybeLoweredFunc); } } else if (value.kind === "LoadLocal") { const maybeLoweredFunc = temporaries.get(value.place.identifier.id); if (maybeLoweredFunc != null) { temporaries.set(lvalue.identifier.id, maybeLoweredFunc); } } } } for (const block of fn.body.blocks.values()) { for (const { lvalue, value } of block.instructions) { if (value.kind === "CallExpression") { const callee = value.callee; const maybeHook = getHookKind(fn.env, callee.identifier); const maybeLoweredFunc = temporaries.get(callee.identifier.id); if (maybeLoweredFunc != null) { hoistableFunctions.add(maybeLoweredFunc.fn); } else if (maybeHook != null) { for (const arg of value.args) { if (arg.kind === "Identifier") { const maybeLoweredFunc2 = temporaries.get(arg.identifier.id); if (maybeLoweredFunc2 != null) { hoistableFunctions.add(maybeLoweredFunc2.fn); } } } } } else if (value.kind === "JsxExpression") { for (const attr of value.props) { if (attr.kind === "JsxSpreadAttribute") { continue; } const maybeLoweredFunc = temporaries.get(attr.place.identifier.id); if (maybeLoweredFunc != null) { hoistableFunctions.add(maybeLoweredFunc.fn); } } for (const child of (_a = value.children) != null ? _a : []) { const maybeLoweredFunc = temporaries.get(child.identifier.id); if (maybeLoweredFunc != null) { hoistableFunctions.add(maybeLoweredFunc.fn); } } } else if (value.kind === "FunctionExpression") { const loweredFunc = value.loweredFunc.func; const lambdasCalled = getAssumedInvokedFunctions( loweredFunc, temporaries ); const maybeLoweredFunc = temporaries.get(lvalue.identifier.id); if (maybeLoweredFunc != null) { for (const called of lambdasCalled) { maybeLoweredFunc.mayInvoke.add(called); } } } } if (block.terminal.kind === "return") { const maybeLoweredFunc = temporaries.get( block.terminal.value.identifier.id ); if (maybeLoweredFunc != null) { hoistableFunctions.add(maybeLoweredFunc.fn); } } } for (const [_, { fn: fn2, mayInvoke }] of temporaries) { if (hoistableFunctions.has(fn2)) { for (const called of mayInvoke) { hoistableFunctions.add(called); } } } return hoistableFunctions; } // src/HIR/CollectOptionalChainDependencies.ts function collectOptionalChainSidemap(fn) { const context = { currFn: fn, blocks: fn.body.blocks, seenOptionals: /* @__PURE__ */ new Set(), processedInstrsInOptional: /* @__PURE__ */ new Set(), temporariesReadInOptional: /* @__PURE__ */ new Map(), hoistableObjects: /* @__PURE__ */ new Map() }; traverseFunction(fn, context); return { temporariesReadInOptional: context.temporariesReadInOptional, processedInstrsInOptional: context.processedInstrsInOptional, hoistableObjects: context.hoistableObjects }; } function traverseFunction(fn, context) { for (const [_, block] of fn.body.blocks) { for (const instr of block.instructions) { if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { traverseFunction(instr.value.loweredFunc.func, __spreadProps(__spreadValues({}, context), { currFn: instr.value.loweredFunc.func, blocks: instr.value.loweredFunc.func.body.blocks })); } } if (block.terminal.kind === "optional" && !context.seenOptionals.has(block.id)) { traverseOptionalBlock( block, context, null ); } } } function matchOptionalTestBlock(terminal, blocks) { const consequentBlock = assertNonNull(blocks.get(terminal.consequent)); if (consequentBlock.instructions.length === 2 && consequentBlock.instructions[0].value.kind === "PropertyLoad" && consequentBlock.instructions[1].value.kind === "StoreLocal") { const propertyLoad = consequentBlock.instructions[0]; const storeLocal = consequentBlock.instructions[1].value; const storeLocalInstr = consequentBlock.instructions[1]; CompilerError.invariant( propertyLoad.value.object.identifier.id === terminal.test.identifier.id, { reason: "[OptionalChainDeps] Inconsistent optional chaining property load", description: `Test=${printIdentifier(terminal.test.identifier)} PropertyLoad base=${printIdentifier(propertyLoad.value.object.identifier)}`, details: [ { kind: "error", loc: propertyLoad.loc, message: null } ] } ); CompilerError.invariant( storeLocal.value.identifier.id === propertyLoad.lvalue.identifier.id, { reason: "[OptionalChainDeps] Unexpected storeLocal", description: null, details: [ { kind: "error", loc: propertyLoad.loc, message: null } ] } ); if (consequentBlock.terminal.kind !== "goto" || consequentBlock.terminal.variant !== "Break" /* Break */) { return null; } const alternate = assertNonNull(blocks.get(terminal.alternate)); CompilerError.invariant( alternate.instructions.length === 2 && alternate.instructions[0].value.kind === "Primitive" && alternate.instructions[1].value.kind === "StoreLocal", { reason: "Unexpected alternate structure", description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] } ); return { consequentId: storeLocal.lvalue.place.identifier.id, property: propertyLoad.value.property, propertyId: propertyLoad.lvalue.identifier.id, storeLocalInstr, consequentGoto: consequentBlock.terminal.block }; } return null; } function traverseOptionalBlock(optional2, context, outerAlternate) { context.seenOptionals.add(optional2.id); const maybeTest = context.blocks.get(optional2.terminal.test); let test; let baseObject; if (maybeTest.terminal.kind === "branch") { CompilerError.invariant(optional2.terminal.optional, { reason: "[OptionalChainDeps] Expect base case to be always optional", description: null, details: [ { kind: "error", loc: optional2.terminal.loc, message: null } ] }); if (maybeTest.instructions.length === 0 || maybeTest.instructions[0].value.kind !== "LoadLocal") { return null; } const path = []; for (let i = 1; i < maybeTest.instructions.length; i++) { const instrVal = maybeTest.instructions[i].value; const prevInstr = maybeTest.instructions[i - 1]; if (instrVal.kind === "PropertyLoad" && instrVal.object.identifier.id === prevInstr.lvalue.identifier.id) { path.push({ property: instrVal.property, optional: false }); } else { return null; } } CompilerError.invariant( maybeTest.terminal.test.identifier.id === maybeTest.instructions.at(-1).lvalue.identifier.id, { reason: "[OptionalChainDeps] Unexpected test expression", description: null, details: [ { kind: "error", loc: maybeTest.terminal.loc, message: null } ] } ); baseObject = { identifier: maybeTest.instructions[0].value.place.identifier, reactive: maybeTest.instructions[0].value.place.reactive, path }; test = maybeTest.terminal; } else if (maybeTest.terminal.kind === "optional") { const testBlock = context.blocks.get(maybeTest.terminal.fallthrough); if (testBlock.terminal.kind !== "branch") { CompilerError.throwTodo({ reason: `Unexpected terminal kind \`${testBlock.terminal.kind}\` for optional fallthrough block`, loc: maybeTest.terminal.loc }); } const innerOptional = traverseOptionalBlock( maybeTest, context, testBlock.terminal.alternate ); if (innerOptional == null) { return null; } if (testBlock.terminal.test.identifier.id !== innerOptional) { return null; } if (!optional2.terminal.optional) { context.hoistableObjects.set( optional2.id, assertNonNull(context.temporariesReadInOptional.get(innerOptional)) ); } baseObject = assertNonNull( context.temporariesReadInOptional.get(innerOptional) ); test = testBlock.terminal; } else { return null; } if (test.alternate === outerAlternate) { CompilerError.invariant(optional2.instructions.length === 0, { reason: "[OptionalChainDeps] Unexpected instructions an inner optional block. This indicates that the compiler may be incorrectly concatenating two unrelated optional chains", description: null, details: [ { kind: "error", loc: optional2.terminal.loc, message: null } ] }); } const matchConsequentResult = matchOptionalTestBlock(test, context.blocks); if (!matchConsequentResult) { return null; } CompilerError.invariant( matchConsequentResult.consequentGoto === optional2.terminal.fallthrough, { reason: "[OptionalChainDeps] Unexpected optional goto-fallthrough", description: `${matchConsequentResult.consequentGoto} != ${optional2.terminal.fallthrough}`, details: [ { kind: "error", loc: optional2.terminal.loc, message: null } ] } ); const load = { identifier: baseObject.identifier, reactive: baseObject.reactive, path: [ ...baseObject.path, { property: matchConsequentResult.property, optional: optional2.terminal.optional } ] }; context.processedInstrsInOptional.add(matchConsequentResult.storeLocalInstr); context.processedInstrsInOptional.add(test); context.temporariesReadInOptional.set( matchConsequentResult.consequentId, load ); context.temporariesReadInOptional.set(matchConsequentResult.propertyId, load); return matchConsequentResult.consequentId; } // src/HIR/DeriveMinimalDependenciesHIR.ts var _hoistableObjects, _deps, _ReactiveScopeDependencyTreeHIR_static, getOrCreateRoot_fn, debugImpl_fn; var _ReactiveScopeDependencyTreeHIR = class _ReactiveScopeDependencyTreeHIR { /** * @param hoistableObjects a set of paths from which we can safely evaluate * PropertyLoads. Note that we expect these to not contain duplicates (e.g. * both `a?.b` and `a.b`) only because CollectHoistablePropertyLoads merges * duplicates when traversing the CFG. */ constructor(hoistableObjects) { /** * Paths from which we can hoist PropertyLoads. If an `identifier`, * `identifier.path`, or `identifier?.path` is in this map, it is safe to * evaluate (non-optional) PropertyLoads from. */ __privateAdd(this, _hoistableObjects, /* @__PURE__ */ new Map()); __privateAdd(this, _deps, /* @__PURE__ */ new Map()); var _a, _b; for (const { path, identifier: identifier4, reactive } of hoistableObjects) { let currNode = __privateMethod(_a = _ReactiveScopeDependencyTreeHIR, _ReactiveScopeDependencyTreeHIR_static, getOrCreateRoot_fn).call(_a, identifier4, reactive, __privateGet(this, _hoistableObjects), path.length > 0 && path[0].optional ? "Optional" : "NonNull"); for (let i = 0; i < path.length; i++) { const prevAccessType = (_b = currNode.properties.get( path[i].property )) == null ? void 0 : _b.accessType; const accessType = i + 1 < path.length && path[i + 1].optional ? "Optional" : "NonNull"; CompilerError.invariant( prevAccessType == null || prevAccessType === accessType, { reason: "Conflicting access types", description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] } ); let nextNode = currNode.properties.get(path[i].property); if (nextNode == null) { nextNode = { properties: /* @__PURE__ */ new Map(), accessType }; currNode.properties.set(path[i].property, nextNode); } currNode = nextNode; } } } /** * Join a dependency with `#hoistableObjects` to record the hoistable * dependency. This effectively truncates @param dep to its maximal * safe-to-evaluate subpath */ addDependency(dep) { var _a; const { identifier: identifier4, reactive, path } = dep; let depCursor = __privateMethod(_a = _ReactiveScopeDependencyTreeHIR, _ReactiveScopeDependencyTreeHIR_static, getOrCreateRoot_fn).call(_a, identifier4, reactive, __privateGet(this, _deps), "UnconditionalAccess" /* UnconditionalAccess */); let hoistableCursor = __privateGet(this, _hoistableObjects).get(identifier4); for (const entry of path) { let nextHoistableCursor; let nextDepCursor; if (entry.optional) { if (hoistableCursor != null) { nextHoistableCursor = hoistableCursor == null ? void 0 : hoistableCursor.properties.get(entry.property); } let accessType; if (hoistableCursor != null && hoistableCursor.accessType === "NonNull") { accessType = "UnconditionalAccess" /* UnconditionalAccess */; } else { accessType = "OptionalAccess" /* OptionalAccess */; } nextDepCursor = makeOrMergeProperty( depCursor, entry.property, accessType ); } else if (hoistableCursor != null && hoistableCursor.accessType === "NonNull") { nextHoistableCursor = hoistableCursor.properties.get(entry.property); nextDepCursor = makeOrMergeProperty( depCursor, entry.property, "UnconditionalAccess" /* UnconditionalAccess */ ); } else { break; } depCursor = nextDepCursor; hoistableCursor = nextHoistableCursor; } depCursor.accessType = merge2( depCursor.accessType, "OptionalDependency" /* OptionalDependency */ ); } deriveMinimalDependencies() { const results = /* @__PURE__ */ new Set(); for (const [rootId, rootNode] of __privateGet(this, _deps).entries()) { collectMinimalDependenciesInSubtree( rootNode, rootNode.reactive, rootId, [], results ); } return results; } /* * Prints dependency tree to string for debugging. * @param includeAccesses * @returns string representation of DependencyTree */ printDeps(includeAccesses) { let res = []; for (const [rootId, rootNode] of __privateGet(this, _deps).entries()) { const rootResults = printSubtree(rootNode, includeAccesses).map( (result) => `${printIdentifier(rootId)}.${result}` ); res.push(rootResults); } return res.flat().join("\n"); } static debug(roots) { const buf = [`tree() [`]; for (const [rootId, rootNode] of roots) { buf.push(`${printIdentifier(rootId)} (${rootNode.accessType}):`); __privateMethod(this, _ReactiveScopeDependencyTreeHIR_static, debugImpl_fn).call(this, buf, rootNode, 1); } buf.push("]"); return buf.length > 2 ? buf.join("\n") : buf.join(""); } }; _hoistableObjects = new WeakMap(); _deps = new WeakMap(); _ReactiveScopeDependencyTreeHIR_static = new WeakSet(); getOrCreateRoot_fn = function(identifier4, reactive, roots, defaultAccessType) { let rootNode = roots.get(identifier4); if (rootNode === void 0) { rootNode = { properties: /* @__PURE__ */ new Map(), reactive, accessType: defaultAccessType }; roots.set(identifier4, rootNode); } else { CompilerError.invariant(reactive === rootNode.reactive, { reason: "[DeriveMinimalDependenciesHIR] Conflicting reactive root flag", description: `Identifier ${printIdentifier(identifier4)}`, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); } return rootNode; }; debugImpl_fn = function(buf, node, depth = 0) { for (const [property, childNode] of node.properties) { buf.push(`${" ".repeat(depth)}.${property} (${childNode.accessType}):`); __privateMethod(this, _ReactiveScopeDependencyTreeHIR_static, debugImpl_fn).call(this, buf, childNode, depth + 1); } }; __privateAdd(_ReactiveScopeDependencyTreeHIR, _ReactiveScopeDependencyTreeHIR_static); var ReactiveScopeDependencyTreeHIR = _ReactiveScopeDependencyTreeHIR; function isOptional(access) { return access === "OptionalAccess" /* OptionalAccess */ || access === "OptionalDependency" /* OptionalDependency */; } function isDependency(access) { return access === "OptionalDependency" /* OptionalDependency */ || access === "UnconditionalDependency" /* UnconditionalDependency */; } function merge2(access1, access2) { const resultIsUnconditional = !(isOptional(access1) && isOptional(access2)); const resultIsDependency = isDependency(access1) || isDependency(access2); if (resultIsUnconditional) { if (resultIsDependency) { return "UnconditionalDependency" /* UnconditionalDependency */; } else { return "UnconditionalAccess" /* UnconditionalAccess */; } } else { if (resultIsDependency) { return "OptionalDependency" /* OptionalDependency */; } else { return "OptionalAccess" /* OptionalAccess */; } } } function collectMinimalDependenciesInSubtree(node, reactive, rootIdentifier, path, results) { if (isDependency(node.accessType)) { results.add({ identifier: rootIdentifier, reactive, path }); } else { for (const [childName, childNode] of node.properties) { collectMinimalDependenciesInSubtree( childNode, reactive, rootIdentifier, [ ...path, { property: childName, optional: isOptional(childNode.accessType) } ], results ); } } } function printSubtree(node, includeAccesses) { const results = []; for (const [propertyName, propertyNode] of node.properties) { if (includeAccesses || isDependency(propertyNode.accessType)) { results.push(`${propertyName} (${propertyNode.accessType})`); } const propertyResults = printSubtree(propertyNode, includeAccesses); results.push(...propertyResults.map((result) => `${propertyName}.${result}`)); } return results; } function makeOrMergeProperty(node, property, accessType) { let child = node.properties.get(property); if (child == null) { child = { properties: /* @__PURE__ */ new Map(), accessType }; node.properties.set(property, child); } else { child.accessType = merge2(child.accessType, accessType); } return child; } // src/HIR/PropagateScopeDependenciesHIR.ts function propagateScopeDependenciesHIR(fn) { const usedOutsideDeclaringScope = findTemporariesUsedOutsideDeclaringScope(fn); const temporaries = collectTemporariesSidemap(fn, usedOutsideDeclaringScope); const { temporariesReadInOptional, processedInstrsInOptional, hoistableObjects } = collectOptionalChainSidemap(fn); const hoistablePropertyLoads = keyByScopeId( fn, collectHoistablePropertyLoads(fn, temporaries, hoistableObjects) ); const scopeDeps = collectDependencies( fn, usedOutsideDeclaringScope, new Map([...temporaries, ...temporariesReadInOptional]), processedInstrsInOptional ); for (const [scope, deps] of scopeDeps) { if (deps.length === 0) { continue; } const hoistables = hoistablePropertyLoads.get(scope.id); CompilerError.invariant(hoistables != null, { reason: "[PropagateScopeDependencies] Scope not found in tracked blocks", description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); const tree = new ReactiveScopeDependencyTreeHIR( [...hoistables.assumedNonNullObjects].map((o) => o.fullPath) ); for (const dep of deps) { tree.addDependency(__spreadValues({}, dep)); } const candidates = tree.deriveMinimalDependencies(); for (const candidateDep of candidates) { if (!Iterable_some( scope.dependencies, (existingDep) => existingDep.identifier.declarationId === candidateDep.identifier.declarationId && areEqualPaths(existingDep.path, candidateDep.path) )) scope.dependencies.add(candidateDep); } } } function findTemporariesUsedOutsideDeclaringScope(fn) { const declarations = /* @__PURE__ */ new Map(); const prunedScopes = /* @__PURE__ */ new Set(); const scopeTraversal = new ScopeBlockTraversal(); const usedOutsideDeclaringScope = /* @__PURE__ */ new Set(); function handlePlace2(place) { const declaringScope = declarations.get(place.identifier.declarationId); if (declaringScope != null && !scopeTraversal.isScopeActive(declaringScope) && !prunedScopes.has(declaringScope)) { usedOutsideDeclaringScope.add(place.identifier.declarationId); } } function handleInstruction2(instr) { const scope = scopeTraversal.currentScope; if (scope == null || prunedScopes.has(scope)) { return; } switch (instr.value.kind) { case "LoadLocal": case "LoadContext": case "PropertyLoad": { declarations.set(instr.lvalue.identifier.declarationId, scope); break; } default: { break; } } } for (const [blockId, block] of fn.body.blocks) { scopeTraversal.recordScopes(block); const scopeStartInfo = scopeTraversal.blockInfos.get(blockId); if ((scopeStartInfo == null ? void 0 : scopeStartInfo.kind) === "begin" && scopeStartInfo.pruned) { prunedScopes.add(scopeStartInfo.scope.id); } for (const instr of block.instructions) { for (const place of eachInstructionOperand(instr)) { handlePlace2(place); } handleInstruction2(instr); } for (const place of eachTerminalOperand(block.terminal)) { handlePlace2(place); } } return usedOutsideDeclaringScope; } function collectTemporariesSidemap(fn, usedOutsideDeclaringScope) { const temporaries = /* @__PURE__ */ new Map(); collectTemporariesSidemapImpl( fn, usedOutsideDeclaringScope, temporaries, null ); return temporaries; } function isLoadContextMutable(instrValue, id) { if (instrValue.kind === "LoadContext") { return instrValue.place.identifier.scope != null && id >= instrValue.place.identifier.scope.range.end; } return false; } function collectTemporariesSidemapImpl(fn, usedOutsideDeclaringScope, temporaries, innerFnContext) { for (const [_, block] of fn.body.blocks) { for (const { value, lvalue, id: origInstrId } of block.instructions) { const instrId = innerFnContext != null ? innerFnContext.instrId : origInstrId; const usedOutside = usedOutsideDeclaringScope.has( lvalue.identifier.declarationId ); if (value.kind === "PropertyLoad" && !usedOutside) { if (innerFnContext == null || temporaries.has(value.object.identifier.id)) { const property = getProperty( value.object, value.property, false, temporaries ); temporaries.set(lvalue.identifier.id, property); } } else if ((value.kind === "LoadLocal" || isLoadContextMutable(value, instrId)) && lvalue.identifier.name == null && value.place.identifier.name !== null && !usedOutside) { if (innerFnContext == null || fn.context.some( (context) => context.identifier.id === value.place.identifier.id )) { temporaries.set(lvalue.identifier.id, { identifier: value.place.identifier, reactive: value.place.reactive, path: [] }); } } else if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") { collectTemporariesSidemapImpl( value.loweredFunc.func, usedOutsideDeclaringScope, temporaries, innerFnContext != null ? innerFnContext : { instrId } ); } } } } function getProperty(object2, propertyName, optional2, temporaries) { const resolvedDependency = temporaries.get(object2.identifier.id); let property; if (resolvedDependency == null) { property = { identifier: object2.identifier, reactive: object2.reactive, path: [{ property: propertyName, optional: optional2 }] }; } else { property = { identifier: resolvedDependency.identifier, reactive: resolvedDependency.reactive, path: [...resolvedDependency.path, { property: propertyName, optional: optional2 }] }; } return property; } var _declarations2, _reassignments, _scopes2, _dependencies, _temporaries, _temporariesUsedOutsideScope, _processedInstrsInOptional, _innerFnContext, _DependencyCollectionContext_instances, checkValidDependency_fn, isScopeActive_fn; var DependencyCollectionContext = class { constructor(temporariesUsedOutsideScope, temporaries, processedInstrsInOptional) { __privateAdd(this, _DependencyCollectionContext_instances); __privateAdd(this, _declarations2, /* @__PURE__ */ new Map()); __privateAdd(this, _reassignments, /* @__PURE__ */ new Map()); __privateAdd(this, _scopes2, empty()); // Reactive dependencies used in the current reactive scope. __privateAdd(this, _dependencies, empty()); this.deps = /* @__PURE__ */ new Map(); __privateAdd(this, _temporaries); __privateAdd(this, _temporariesUsedOutsideScope); __privateAdd(this, _processedInstrsInOptional); /** * Tracks the traversal state. See Context.declare for explanation of why this * is needed. */ __privateAdd(this, _innerFnContext, null); __privateSet(this, _temporariesUsedOutsideScope, temporariesUsedOutsideScope); __privateSet(this, _temporaries, temporaries); __privateSet(this, _processedInstrsInOptional, processedInstrsInOptional); } enterScope(scope) { __privateSet(this, _dependencies, __privateGet(this, _dependencies).push([])); __privateSet(this, _scopes2, __privateGet(this, _scopes2).push(scope)); } exitScope(scope, pruned) { var _a; const scopedDependencies = __privateGet(this, _dependencies).value; CompilerError.invariant(scopedDependencies != null, { reason: "[PropagateScopeDeps]: Unexpected scope mismatch", description: null, details: [ { kind: "error", loc: scope.loc, message: null } ] }); __privateSet(this, _scopes2, __privateGet(this, _scopes2).pop()); __privateSet(this, _dependencies, __privateGet(this, _dependencies).pop()); for (const dep of scopedDependencies) { if (__privateMethod(this, _DependencyCollectionContext_instances, checkValidDependency_fn).call(this, dep)) { (_a = __privateGet(this, _dependencies).value) == null ? void 0 : _a.push(dep); } } if (!pruned) { this.deps.set(scope, scopedDependencies); } } isUsedOutsideDeclaringScope(place) { return __privateGet(this, _temporariesUsedOutsideScope).has( place.identifier.declarationId ); } /* * Records where a value was declared, and optionally, the scope where the * value originated from. This is later used to determine if a dependency * should be added to a scope; if the current scope we are visiting is the * same scope where the value originates, it can't be a dependency on itself. * * Note that we do not track declarations or reassignments within inner * functions for the following reasons: * - inner functions cannot be split by scope boundaries and are guaranteed * to consume their own declarations * - reassignments within inner functions are tracked as context variables, * which already have extended mutable ranges to account for reassignments * - *most importantly* it's currently simply incorrect to compare inner * function instruction ids (tracked by `decl`) with outer ones (as stored * by root identifier mutable ranges). */ declare(identifier4, decl) { if (__privateGet(this, _innerFnContext) != null) return; if (!__privateGet(this, _declarations2).has(identifier4.declarationId)) { __privateGet(this, _declarations2).set(identifier4.declarationId, decl); } __privateGet(this, _reassignments).set(identifier4, decl); } hasDeclared(identifier4) { return __privateGet(this, _declarations2).has(identifier4.declarationId); } get currentScope() { return __privateGet(this, _scopes2); } visitOperand(place) { var _a; this.visitDependency( (_a = __privateGet(this, _temporaries).get(place.identifier.id)) != null ? _a : { identifier: place.identifier, reactive: place.reactive, path: [] } ); } visitProperty(object2, property, optional2) { const nextDependency = getProperty( object2, property, optional2, __privateGet(this, _temporaries) ); this.visitDependency(nextDependency); } visitDependency(maybeDependency) { var _a; const originalDeclaration = __privateGet(this, _declarations2).get( maybeDependency.identifier.declarationId ); if (originalDeclaration !== void 0 && originalDeclaration.scope.value !== null) { originalDeclaration.scope.each((scope) => { if (!__privateMethod(this, _DependencyCollectionContext_instances, isScopeActive_fn).call(this, scope) && !Iterable_some( scope.declarations.values(), (decl) => decl.identifier.declarationId === maybeDependency.identifier.declarationId )) { scope.declarations.set(maybeDependency.identifier.id, { identifier: maybeDependency.identifier, scope: originalDeclaration.scope.value }); } }); } if (isUseRefType(maybeDependency.identifier) && ((_a = maybeDependency.path.at(0)) == null ? void 0 : _a.property) === "current") { maybeDependency = { identifier: maybeDependency.identifier, reactive: maybeDependency.reactive, path: [] }; } if (__privateMethod(this, _DependencyCollectionContext_instances, checkValidDependency_fn).call(this, maybeDependency)) { __privateGet(this, _dependencies).value.push(maybeDependency); } } /* * Record a variable that is declared in some other scope and that is being reassigned in the * current one as a {@link ReactiveScope.reassignments} */ visitReassignment(place) { const currentScope = this.currentScope.value; if (currentScope != null && !Iterable_some( currentScope.reassignments, (identifier4) => identifier4.declarationId === place.identifier.declarationId ) && __privateMethod(this, _DependencyCollectionContext_instances, checkValidDependency_fn).call(this, { identifier: place.identifier, reactive: place.reactive, path: [] })) { currentScope.reassignments.add(place.identifier); } } enterInnerFn(innerFn, cb) { var _a; const prevContext = __privateGet(this, _innerFnContext); __privateSet(this, _innerFnContext, (_a = __privateGet(this, _innerFnContext)) != null ? _a : { outerInstrId: innerFn.id }); const result = cb(); __privateSet(this, _innerFnContext, prevContext); return result; } /** * Skip dependencies that are subexpressions of other dependencies. e.g. if a * dependency is tracked in the temporaries sidemap, it can be added at * site-of-use */ isDeferredDependency(instr) { return __privateGet(this, _processedInstrsInOptional).has(instr.value) || instr.kind === 1 /* Instruction */ && __privateGet(this, _temporaries).has(instr.value.lvalue.identifier.id); } }; _declarations2 = new WeakMap(); _reassignments = new WeakMap(); _scopes2 = new WeakMap(); _dependencies = new WeakMap(); _temporaries = new WeakMap(); _temporariesUsedOutsideScope = new WeakMap(); _processedInstrsInOptional = new WeakMap(); _innerFnContext = new WeakMap(); _DependencyCollectionContext_instances = new WeakSet(); // Checks if identifier is a valid dependency in the current scope checkValidDependency_fn = function(maybeDependency) { var _a; if (isRefValueType(maybeDependency.identifier)) { return false; } if (isObjectMethodType(maybeDependency.identifier)) { return false; } const identifier4 = maybeDependency.identifier; const currentDeclaration = (_a = __privateGet(this, _reassignments).get(identifier4)) != null ? _a : __privateGet(this, _declarations2).get(identifier4.declarationId); const currentScope = this.currentScope.value; return currentScope != null && currentDeclaration !== void 0 && currentDeclaration.id < currentScope.range.start; }; isScopeActive_fn = function(scope) { if (__privateGet(this, _scopes2) === null) { return false; } return __privateGet(this, _scopes2).find((state) => state === scope); }; function handleInstruction(instr, context) { const { id, value, lvalue } = instr; context.declare(lvalue.identifier, { id, scope: context.currentScope }); if (context.isDeferredDependency({ kind: 1 /* Instruction */, value: instr })) { return; } if (value.kind === "PropertyLoad") { context.visitProperty(value.object, value.property, false); } else if (value.kind === "StoreLocal") { context.visitOperand(value.value); if (value.lvalue.kind === "Reassign" /* Reassign */) { context.visitReassignment(value.lvalue.place); } context.declare(value.lvalue.place.identifier, { id, scope: context.currentScope }); } else if (value.kind === "DeclareLocal" || value.kind === "DeclareContext") { if (convertHoistedLValueKind(value.lvalue.kind) === null) { context.declare(value.lvalue.place.identifier, { id, scope: context.currentScope }); } } else if (value.kind === "Destructure") { context.visitOperand(value.value); for (const place of eachPatternOperand(value.lvalue.pattern)) { if (value.lvalue.kind === "Reassign" /* Reassign */) { context.visitReassignment(place); } context.declare(place.identifier, { id, scope: context.currentScope }); } } else if (value.kind === "StoreContext") { if (!context.hasDeclared(value.lvalue.place.identifier) || value.lvalue.kind !== "Reassign" /* Reassign */) { context.declare(value.lvalue.place.identifier, { id, scope: context.currentScope }); } for (const operand of eachInstructionValueOperand(value)) { context.visitOperand(operand); } } else { for (const operand of eachInstructionValueOperand(value)) { context.visitOperand(operand); } } } function collectDependencies(fn, usedOutsideDeclaringScope, temporaries, processedInstrsInOptional) { const context = new DependencyCollectionContext( usedOutsideDeclaringScope, temporaries, processedInstrsInOptional ); for (const param of fn.params) { if (param.kind === "Identifier") { context.declare(param.identifier, { id: makeInstructionId(0), scope: empty() }); } else { context.declare(param.place.identifier, { id: makeInstructionId(0), scope: empty() }); } } const scopeTraversal = new ScopeBlockTraversal(); const handleFunction = (fn2) => { for (const [blockId, block] of fn2.body.blocks) { scopeTraversal.recordScopes(block); const scopeBlockInfo = scopeTraversal.blockInfos.get(blockId); if ((scopeBlockInfo == null ? void 0 : scopeBlockInfo.kind) === "begin") { context.enterScope(scopeBlockInfo.scope); } else if ((scopeBlockInfo == null ? void 0 : scopeBlockInfo.kind) === "end") { context.exitScope(scopeBlockInfo.scope, scopeBlockInfo.pruned); } for (const phi of block.phis) { for (const operand of phi.operands) { const maybeOptionalChain = temporaries.get(operand[1].identifier.id); if (maybeOptionalChain) { context.visitDependency(maybeOptionalChain); } } } for (const instr of block.instructions) { if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { context.declare(instr.lvalue.identifier, { id: instr.id, scope: context.currentScope }); const innerFn = instr.value.loweredFunc.func; context.enterInnerFn( instr, () => { handleFunction(innerFn); } ); } else { handleInstruction(instr, context); } } if (!context.isDeferredDependency({ kind: 2 /* Terminal */, value: block.terminal })) { for (const place of eachTerminalOperand(block.terminal)) { context.visitOperand(place); } } } }; handleFunction(fn); return context.deps; } // src/HIR/ScopeDependencyUtils.ts function buildDependencyInstructions(dep, env) { const builder = new HIRBuilder(env, { entryBlockKind: "value" }); let dependencyValue; if (dep.path.every((path) => !path.optional)) { dependencyValue = writeNonOptionalDependency(dep, env, builder); } else { dependencyValue = writeOptionalDependency(dep, builder, null); } const exitBlockId = builder.terminate( { kind: "unsupported", loc: GeneratedSource, id: makeInstructionId(0) }, null ); return { place: { kind: "Identifier", identifier: dependencyValue, effect: "freeze" /* Freeze */, reactive: dep.reactive, loc: GeneratedSource }, value: builder.build(), exitBlockId }; } function writeNonOptionalDependency(dep, env, builder) { const loc = dep.identifier.loc; let curr = makeTemporaryIdentifier(env.nextIdentifierId, loc); builder.push({ lvalue: { identifier: curr, kind: "Identifier", effect: "mutate" /* Mutate */, reactive: dep.reactive, loc }, value: { kind: "LoadLocal", place: { identifier: dep.identifier, kind: "Identifier", effect: "freeze" /* Freeze */, reactive: dep.reactive, loc }, loc }, id: makeInstructionId(1), loc, effects: null }); for (const path of dep.path) { const next = makeTemporaryIdentifier(env.nextIdentifierId, loc); builder.push({ lvalue: { identifier: next, kind: "Identifier", effect: "mutate" /* Mutate */, reactive: dep.reactive, loc }, value: { kind: "PropertyLoad", object: { identifier: curr, kind: "Identifier", effect: "freeze" /* Freeze */, reactive: dep.reactive, loc }, property: path.property, loc }, id: makeInstructionId(1), loc, effects: null }); curr = next; } return curr; } function writeOptionalDependency(dep, builder, parentAlternate) { const env = builder.environment; const dependencyValue = { kind: "Identifier", identifier: makeTemporaryIdentifier(env.nextIdentifierId, GeneratedSource), effect: "mutate" /* Mutate */, reactive: dep.reactive, loc: GeneratedSource }; const continuationBlock = builder.reserve(builder.currentBlockKind()); let alternate; if (parentAlternate != null) { alternate = parentAlternate; } else { alternate = builder.enter("value", () => { const temp = lowerValueToTemporary(builder, { kind: "Primitive", value: void 0, loc: GeneratedSource }); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, dependencyValue) }, value: __spreadValues({}, temp), type: null, loc: GeneratedSource }); return { kind: "goto", variant: "Break" /* Break */, block: continuationBlock.id, id: makeInstructionId(0), loc: GeneratedSource }; }); } const consequent = builder.reserve("value"); let testIdentifier = null; const testBlock = builder.enter("value", () => { const testDependency = __spreadProps(__spreadValues({}, dep), { path: dep.path.slice(0, dep.path.length - 1) }); const firstOptional = dep.path.findIndex((path) => path.optional); CompilerError.invariant(firstOptional !== -1, { reason: "[ScopeDependencyUtils] Internal invariant broken: expected optional path", description: null, details: [ { kind: "error", loc: dep.identifier.loc, message: null } ], suggestions: null }); if (firstOptional === dep.path.length - 1) { testIdentifier = writeNonOptionalDependency(testDependency, env, builder); } else { testIdentifier = writeOptionalDependency( testDependency, builder, alternate ); } return { kind: "branch", test: { identifier: testIdentifier, effect: "freeze" /* Freeze */, kind: "Identifier", loc: GeneratedSource, reactive: dep.reactive }, consequent: consequent.id, alternate, id: makeInstructionId(0), loc: GeneratedSource, fallthrough: continuationBlock.id }; }); builder.enterReserved(consequent, () => { CompilerError.invariant(testIdentifier !== null, { reason: "Satisfy type checker", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); lowerValueToTemporary(builder, { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, dependencyValue) }, value: lowerValueToTemporary(builder, { kind: "PropertyLoad", object: { identifier: testIdentifier, kind: "Identifier", effect: "freeze" /* Freeze */, reactive: dep.reactive, loc: GeneratedSource }, property: dep.path.at(-1).property, loc: GeneratedSource }), type: null, loc: GeneratedSource }); return { kind: "goto", variant: "Break" /* Break */, block: continuationBlock.id, id: makeInstructionId(0), loc: GeneratedSource }; }); builder.terminateWithContinuation( { kind: "optional", optional: dep.path.at(-1).optional, test: testBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0), loc: GeneratedSource }, continuationBlock ); return dependencyValue.identifier; } // src/Inference/InferEffectDependencies.ts function inferEffectDependencies(fn) { var _a, _b; const fnExpressions = /* @__PURE__ */ new Map(); const autodepFnConfigs = /* @__PURE__ */ new Map(); for (const effectTarget of fn.env.config.inferEffectDependencies) { const moduleTargets = getOrInsertWith( autodepFnConfigs, effectTarget.function.source, () => /* @__PURE__ */ new Map() ); moduleTargets.set( effectTarget.function.importSpecifierName, effectTarget.autodepsIndex ); } const autodepFnLoads = /* @__PURE__ */ new Map(); const autodepModuleLoads = /* @__PURE__ */ new Map(); const scopeInfos = /* @__PURE__ */ new Map(); const loadGlobals = /* @__PURE__ */ new Set(); const reactiveIds = inferReactiveIdentifiers(fn); const rewriteBlocks = []; for (const [, block] of fn.body.blocks) { if (block.terminal.kind === "scope") { const scopeBlock = fn.body.blocks.get(block.terminal.block); if (scopeBlock.instructions.length === 1 && scopeBlock.terminal.kind === "goto" && scopeBlock.terminal.block === block.terminal.fallthrough) { scopeInfos.set( block.terminal.scope.id, block.terminal.scope.dependencies ); } } const rewriteInstrs = []; for (const instr of block.instructions) { const { value, lvalue } = instr; if (value.kind === "FunctionExpression") { fnExpressions.set( lvalue.identifier.id, instr ); } else if (value.kind === "PropertyLoad") { if (typeof value.property === "string" && autodepModuleLoads.has(value.object.identifier.id)) { const moduleTargets = autodepModuleLoads.get( value.object.identifier.id ); const propertyName = value.property; const numRequiredArgs = moduleTargets.get(propertyName); if (numRequiredArgs != null) { autodepFnLoads.set(lvalue.identifier.id, numRequiredArgs); } } } else if (value.kind === "LoadGlobal") { loadGlobals.add(lvalue.identifier.id); if (value.binding.kind === "ImportNamespace") { const moduleTargets = autodepFnConfigs.get(value.binding.module); if (moduleTargets != null) { autodepModuleLoads.set(lvalue.identifier.id, moduleTargets); } } if (value.binding.kind === "ImportSpecifier" || value.binding.kind === "ImportDefault") { const moduleTargets = autodepFnConfigs.get(value.binding.module); if (moduleTargets != null) { const importSpecifierName = value.binding.kind === "ImportSpecifier" ? value.binding.imported : DEFAULT_EXPORT; const numRequiredArgs = moduleTargets.get(importSpecifierName); if (numRequiredArgs != null) { autodepFnLoads.set(lvalue.identifier.id, numRequiredArgs); } } } } else if (value.kind === "CallExpression" || value.kind === "MethodCall") { const callee = value.kind === "CallExpression" ? value.callee : value.property; const autodepsArgIndex = value.args.findIndex( (arg) => arg.kind === "Identifier" && arg.identifier.type.kind === "Object" && arg.identifier.type.shapeId === BuiltInAutodepsId ); const autodepsArgExpectedIndex = autodepFnLoads.get( callee.identifier.id ); if (value.args.length > 0 && autodepsArgExpectedIndex != null && autodepsArgIndex === autodepsArgExpectedIndex && autodepFnLoads.has(callee.identifier.id) && value.args[0].kind === "Identifier") { const effectDeps = []; const deps = { kind: "ArrayExpression", elements: effectDeps, loc: GeneratedSource }; const depsPlace = createTemporaryPlace(fn.env, GeneratedSource); depsPlace.effect = "read" /* Read */; const fnExpr = fnExpressions.get(value.args[0].identifier.id); if (fnExpr != null) { const scopeInfo = fnExpr.lvalue.identifier.scope != null ? scopeInfos.get(fnExpr.lvalue.identifier.scope.id) : null; let minimalDeps; if (scopeInfo != null) { minimalDeps = new Set(scopeInfo); } else { minimalDeps = inferMinimalDependencies(fnExpr); } const usedDeps = []; for (const maybeDep of minimalDeps) { if ((isUseRefType(maybeDep.identifier) || isSetStateType(maybeDep.identifier)) && !reactiveIds.has(maybeDep.identifier.id) || isFireFunctionType(maybeDep.identifier) || isEffectEventFunctionType(maybeDep.identifier)) { continue; } const dep = truncateDepAtCurrent(maybeDep); const { place, value: value2, exitBlockId } = buildDependencyInstructions( dep, fn.env ); rewriteInstrs.push({ kind: "block", location: instr.id, value: value2, exitBlockId }); effectDeps.push(place); usedDeps.push(dep); } const decorations = []; for (const loc of collectDepUsages(usedDeps, fnExpr.value)) { if (typeof loc === "symbol") { continue; } decorations.push(loc); } if (typeof value.loc !== "symbol") { (_a = fn.env.logger) == null ? void 0 : _a.logEvent(fn.env.filename, { kind: "AutoDepsDecorations", fnLoc: value.loc, decorations }); } rewriteInstrs.push({ kind: "instr", location: instr.id, value: { id: makeInstructionId(0), loc: GeneratedSource, lvalue: __spreadProps(__spreadValues({}, depsPlace), { effect: "mutate" /* Mutate */ }), value: deps, effects: null } }); value.args[autodepsArgIndex] = __spreadProps(__spreadValues({}, depsPlace), { effect: "freeze" /* Freeze */ }); fn.env.inferredEffectLocations.add(callee.loc); } else if (loadGlobals.has(value.args[0].identifier.id)) { rewriteInstrs.push({ kind: "instr", location: instr.id, value: { id: makeInstructionId(0), loc: GeneratedSource, lvalue: __spreadProps(__spreadValues({}, depsPlace), { effect: "mutate" /* Mutate */ }), value: deps, effects: null } }); value.args[autodepsArgIndex] = __spreadProps(__spreadValues({}, depsPlace), { effect: "freeze" /* Freeze */ }); fn.env.inferredEffectLocations.add(callee.loc); } } else if (value.args.length >= 2 && value.args.length - 1 === autodepFnLoads.get(callee.identifier.id) && value.args[0] != null && value.args[0].kind === "Identifier") { const penultimateArg = value.args[value.args.length - 2]; const depArrayArg = value.args[value.args.length - 1]; if (depArrayArg.kind !== "Spread" && penultimateArg.kind !== "Spread" && typeof depArrayArg.loc !== "symbol" && typeof penultimateArg.loc !== "symbol" && typeof value.loc !== "symbol") { (_b = fn.env.logger) == null ? void 0 : _b.logEvent(fn.env.filename, { kind: "AutoDepsEligible", fnLoc: value.loc, depArrayLoc: __spreadProps(__spreadValues({}, depArrayArg.loc), { start: penultimateArg.loc.end, end: depArrayArg.loc.end }) }); } } } } rewriteSplices(block, rewriteInstrs, rewriteBlocks); } if (rewriteBlocks.length > 0) { for (const block of rewriteBlocks) { fn.body.blocks.set(block.id, block); } reversePostorderBlocks(fn.body); markPredecessors(fn.body); markInstructionIds(fn.body); fixScopeAndIdentifierRanges(fn.body); deadCodeElimination(fn); fn.env.hasInferredEffect = true; } } function truncateDepAtCurrent(dep) { const idx = dep.path.findIndex((path) => path.property === "current"); if (idx === -1) { return dep; } else { return __spreadProps(__spreadValues({}, dep), { path: dep.path.slice(0, idx) }); } } function rewriteSplices(originalBlock, splices, rewriteBlocks) { if (splices.length === 0) { return; } const originalInstrs = originalBlock.instructions; let currBlock = __spreadProps(__spreadValues({}, originalBlock), { instructions: [] }); rewriteBlocks.push(currBlock); let cursor = 0; for (const rewrite of splices) { while (originalInstrs[cursor].id < rewrite.location) { CompilerError.invariant( originalInstrs[cursor].id < originalInstrs[cursor + 1].id, { reason: "[InferEffectDependencies] Internal invariant broken: expected block instructions to be sorted", description: null, details: [ { kind: "error", loc: originalInstrs[cursor].loc, message: null } ] } ); currBlock.instructions.push(originalInstrs[cursor]); cursor++; } CompilerError.invariant(originalInstrs[cursor].id === rewrite.location, { reason: "[InferEffectDependencies] Internal invariant broken: splice location not found", description: null, details: [ { kind: "error", loc: originalInstrs[cursor].loc, message: null } ] }); if (rewrite.kind === "instr") { currBlock.instructions.push(rewrite.value); } else if (rewrite.kind === "block") { const { entry, blocks } = rewrite.value; const entryBlock = blocks.get(entry); currBlock.instructions.push(...entryBlock.instructions); if (blocks.size > 1) { CompilerError.invariant( terminalFallthrough(entryBlock.terminal) === rewrite.exitBlockId, { reason: "[InferEffectDependencies] Internal invariant broken: expected entry block to have a fallthrough", description: null, details: [ { kind: "error", loc: entryBlock.terminal.loc, message: null } ] } ); const originalTerminal = currBlock.terminal; currBlock.terminal = entryBlock.terminal; for (const [id, block] of blocks) { if (id === entry) { continue; } if (id === rewrite.exitBlockId) { block.terminal = originalTerminal; currBlock = block; } rewriteBlocks.push(block); } } } } currBlock.instructions.push(...originalInstrs.slice(cursor)); } function inferReactiveIdentifiers(fn) { const reactiveIds = /* @__PURE__ */ new Set(); for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { for (const place of eachInstructionOperand(instr)) { if (place.reactive) { reactiveIds.add(place.identifier.id); } } } for (const place of eachTerminalOperand(block.terminal)) { if (place.reactive) { reactiveIds.add(place.identifier.id); } } } return reactiveIds; } function collectDepUsages(deps, fnExpr) { const identifiers = /* @__PURE__ */ new Map(); const loadedDeps = /* @__PURE__ */ new Set(); const sourceLocations = []; for (const dep of deps) { identifiers.set(dep.identifier.id, dep); } for (const [, block] of fnExpr.loweredFunc.func.body.blocks) { for (const instr of block.instructions) { if (instr.value.kind === "LoadLocal" && identifiers.has(instr.value.place.identifier.id)) { loadedDeps.add(instr.lvalue.identifier.id); } for (const place of eachInstructionOperand(instr)) { if (loadedDeps.has(place.identifier.id)) { sourceLocations.push(place.identifier.loc); } } } } return sourceLocations; } function inferMinimalDependencies(fnInstr) { const fn = fnInstr.value.loweredFunc.func; const temporaries = collectTemporariesSidemap(fn, /* @__PURE__ */ new Set()); const { hoistableObjects, processedInstrsInOptional, temporariesReadInOptional } = collectOptionalChainSidemap(fn); const hoistablePropertyLoads = collectHoistablePropertyLoadsInInnerFn( fnInstr, temporaries, hoistableObjects ); const hoistableToFnEntry = hoistablePropertyLoads.get(fn.body.entry); CompilerError.invariant(hoistableToFnEntry != null, { reason: "[InferEffectDependencies] Internal invariant broken: missing entry block", description: null, details: [ { kind: "error", loc: fnInstr.loc, message: null } ] }); const dependencies = inferDependencies( fnInstr, new Map([...temporaries, ...temporariesReadInOptional]), processedInstrsInOptional ); const tree = new ReactiveScopeDependencyTreeHIR( [...hoistableToFnEntry.assumedNonNullObjects].map((o) => o.fullPath) ); for (const dep of dependencies) { tree.addDependency(__spreadValues({}, dep)); } return tree.deriveMinimalDependencies(); } function inferDependencies(fnInstr, temporaries, processedInstrsInOptional) { const fn = fnInstr.value.loweredFunc.func; const context = new DependencyCollectionContext( /* @__PURE__ */ new Set(), temporaries, processedInstrsInOptional ); for (const dep of fn.context) { context.declare(dep.identifier, { id: makeInstructionId(0), scope: empty() }); } const placeholderScope = { id: makeScopeId(0), range: { start: fnInstr.id, end: makeInstructionId(fnInstr.id + 1) }, dependencies: /* @__PURE__ */ new Set(), reassignments: /* @__PURE__ */ new Set(), declarations: /* @__PURE__ */ new Map(), earlyReturnValue: null, merged: /* @__PURE__ */ new Set(), loc: GeneratedSource }; context.enterScope(placeholderScope); inferDependenciesInFn(fn, context, temporaries); context.exitScope(placeholderScope, false); const resultUnfiltered = context.deps.get(placeholderScope); CompilerError.invariant(resultUnfiltered != null, { reason: "[InferEffectDependencies] Internal invariant broken: missing scope dependencies", description: null, details: [ { kind: "error", loc: fn.loc, message: null } ] }); const fnContext = new Set(fn.context.map((dep) => dep.identifier.id)); const result = /* @__PURE__ */ new Set(); for (const dep of resultUnfiltered) { if (fnContext.has(dep.identifier.id)) { result.add(dep); } } return result; } function inferDependenciesInFn(fn, context, temporaries) { for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { for (const operand of phi.operands) { const maybeOptionalChain = temporaries.get(operand[1].identifier.id); if (maybeOptionalChain) { context.visitDependency(maybeOptionalChain); } } } for (const instr of block.instructions) { if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { context.declare(instr.lvalue.identifier, { id: instr.id, scope: context.currentScope }); const innerFn = instr.value.loweredFunc.func; context.enterInnerFn(instr, () => { inferDependenciesInFn(innerFn, context, temporaries); }); } else { handleInstruction(instr, context); } } } } // src/Optimization/InstructionReordering.ts function instructionReordering(fn) { var _a; const shared = /* @__PURE__ */ new Map(); const references = findReferencedRangeOfTemporaries(fn); for (const [, block] of fn.body.blocks) { reorderBlock(fn.env, block, shared, references); } CompilerError.invariant(shared.size === 0, { reason: `InstructionReordering: expected all reorderable nodes to have been emitted`, description: null, details: [ { kind: "error", loc: (_a = [...shared.values()].map((node) => { var _a2; return (_a2 = node.instruction) == null ? void 0 : _a2.loc; }).filter((loc) => loc != null)[0]) != null ? _a : GeneratedSource, message: null } ] }); markInstructionIds(fn.body); } var DEBUG4 = false; function findReferencedRangeOfTemporaries(fn) { const singleUseIdentifiers = /* @__PURE__ */ new Map(); const lastAssignments = /* @__PURE__ */ new Map(); function reference(instr, place, kind) { var _a; if (place.identifier.name !== null && place.identifier.name.kind === "named") { if (kind === 1 /* Write */) { const name = place.identifier.name.value; const previous = lastAssignments.get(name); if (previous === void 0) { lastAssignments.set(name, instr); } else { lastAssignments.set( name, makeInstructionId(Math.max(previous, instr)) ); } } return; } else if (kind === 0 /* Read */) { const previousCount = (_a = singleUseIdentifiers.get(place.identifier.id)) != null ? _a : 0; singleUseIdentifiers.set(place.identifier.id, previousCount + 1); } } for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { for (const operand of eachInstructionValueLValue(instr.value)) { reference(instr.id, operand, 0 /* Read */); } for (const lvalue of eachInstructionLValue(instr)) { reference(instr.id, lvalue, 1 /* Write */); } } for (const operand of eachTerminalOperand(block.terminal)) { reference(block.terminal.id, operand, 0 /* Read */); } } return { singleUseIdentifiers: new Set( [...singleUseIdentifiers].filter(([, count]) => count === 1).map(([id]) => id) ), lastAssignments }; } function reorderBlock(env, block, shared, references) { var _a, _b; const locals = /* @__PURE__ */ new Map(); const named = /* @__PURE__ */ new Map(); let previous = null; for (const instr of block.instructions) { const { lvalue, value } = instr; const reorderability = getReorderability(instr, references); const node = getOrInsertWith( locals, lvalue.identifier.id, () => ({ instruction: instr, dependencies: /* @__PURE__ */ new Set(), reorderability, depth: null }) ); if (reorderability === 1 /* Nonreorderable */) { if (previous !== null) { node.dependencies.add(previous); } previous = lvalue.identifier.id; } for (const operand of eachInstructionValueOperand(value)) { const { name, id } = operand.identifier; if (name !== null && name.kind === "named") { const previous2 = named.get(name.value); if (previous2 !== void 0) { node.dependencies.add(previous2); } named.set(name.value, lvalue.identifier.id); } else if (locals.has(id) || shared.has(id)) { node.dependencies.add(id); } } for (const lvalueOperand of eachInstructionValueLValue(value)) { const lvalueNode = getOrInsertWith( locals, lvalueOperand.identifier.id, () => ({ instruction: null, dependencies: /* @__PURE__ */ new Set(), depth: null }) ); lvalueNode.dependencies.add(lvalue.identifier.id); const name = lvalueOperand.identifier.name; if (name !== null && name.kind === "named") { const previous2 = named.get(name.value); if (previous2 !== void 0) { node.dependencies.add(previous2); } named.set(name.value, lvalue.identifier.id); } } } const nextInstructions = []; const seen = /* @__PURE__ */ new Set(); DEBUG4 && console.log(`bb${block.id}`); if (isExpressionBlockKind(block.kind)) { if (previous !== null) { DEBUG4 && console.log(`(last non-reorderable instruction)`); DEBUG4 && print(env, locals, shared, seen, previous); emit(env, locals, shared, nextInstructions, previous); } if (block.instructions.length !== 0) { DEBUG4 && console.log(`(block value)`); DEBUG4 && print( env, locals, shared, seen, block.instructions.at(-1).lvalue.identifier.id ); emit( env, locals, shared, nextInstructions, block.instructions.at(-1).lvalue.identifier.id ); } for (const operand of eachTerminalOperand(block.terminal)) { DEBUG4 && console.log(`(terminal operand)`); DEBUG4 && print(env, locals, shared, seen, operand.identifier.id); emit(env, locals, shared, nextInstructions, operand.identifier.id); } for (const [id, node] of locals) { if (node.instruction == null) { continue; } CompilerError.invariant( node.reorderability === 0 /* Reorderable */, { reason: `Expected all remaining instructions to be reorderable`, details: [ { kind: "error", loc: (_b = (_a = node.instruction) == null ? void 0 : _a.loc) != null ? _b : block.terminal.loc, message: null } ], description: node.instruction != null ? `Instruction [${node.instruction.id}] was not emitted yet but is not reorderable` : `Lvalue $${id} was not emitted yet but is not reorderable` } ); DEBUG4 && console.log(`save shared: $${id}`); shared.set(id, node); } } else { for (const operand of eachTerminalOperand(block.terminal)) { DEBUG4 && console.log(`(terminal operand)`); DEBUG4 && print(env, locals, shared, seen, operand.identifier.id); emit(env, locals, shared, nextInstructions, operand.identifier.id); } for (const id of Array.from(locals.keys()).reverse()) { const node = locals.get(id); if (node === void 0) { continue; } if (node.reorderability === 0 /* Reorderable */) { DEBUG4 && console.log(`save shared: $${id}`); shared.set(id, node); } else { DEBUG4 && console.log("leftover"); DEBUG4 && print(env, locals, shared, seen, id); emit(env, locals, shared, nextInstructions, id); } } } block.instructions = nextInstructions; DEBUG4 && console.log(); } function getDepth(env, nodes, id) { const node = nodes.get(id); if (node == null) { return 0; } if (node.depth != null) { return node.depth; } node.depth = 0; let depth = node.reorderability === 0 /* Reorderable */ ? 1 : 10; for (const dep of node.dependencies) { depth += getDepth(env, nodes, dep); } node.depth = depth; return depth; } function print(env, locals, shared, seen, id, depth = 0) { var _a; if (seen.has(id)) { DEBUG4 && console.log(`${"| ".repeat(depth)}$${id} `); return; } seen.add(id); const node = (_a = locals.get(id)) != null ? _a : shared.get(id); if (node == null) { return; } const deps = [...node.dependencies]; deps.sort((a, b) => { const aDepth = getDepth(env, locals, a); const bDepth = getDepth(env, locals, b); return bDepth - aDepth; }); for (const dep of deps) { print(env, locals, shared, seen, dep, depth + 1); } DEBUG4 && console.log( `${"| ".repeat(depth)}$${id} ${printNode(node)} deps=[${deps.map((x) => `$${x}`).join(", ")}] depth=${node.depth}` ); } function printNode(node) { const { instruction } = node; if (instruction === null) { return ""; } switch (instruction.value.kind) { case "FunctionExpression": case "ObjectMethod": { return `[${instruction.id}] ${instruction.value.kind}`; } default: { return printInstruction(instruction); } } } function emit(env, locals, shared, instructions, id) { var _a; const node = (_a = locals.get(id)) != null ? _a : shared.get(id); if (node == null) { return; } locals.delete(id); shared.delete(id); const deps = [...node.dependencies]; deps.sort((a, b) => { const aDepth = getDepth(env, locals, a); const bDepth = getDepth(env, locals, b); return bDepth - aDepth; }); for (const dep of deps) { emit(env, locals, shared, instructions, dep); } if (node.instruction !== null) { instructions.push(node.instruction); } } function getReorderability(instr, references) { switch (instr.value.kind) { case "JsxExpression": case "JsxFragment": case "JSXText": case "LoadGlobal": case "Primitive": case "TemplateLiteral": case "BinaryExpression": case "UnaryExpression": { return 0 /* Reorderable */; } case "LoadLocal": { const name = instr.value.place.identifier.name; if (name !== null && name.kind === "named") { const lastAssignment = references.lastAssignments.get(name.value); if (lastAssignment !== void 0 && lastAssignment < instr.id && references.singleUseIdentifiers.has(instr.lvalue.identifier.id)) { return 0 /* Reorderable */; } } return 1 /* Nonreorderable */; } default: { return 1 /* Nonreorderable */; } } } // src/ReactiveScopes/AlignMethodCallScopes.ts function alignMethodCallScopes(fn) { const scopeMapping = /* @__PURE__ */ new Map(); const mergedScopes = new DisjointSet(); for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { const { lvalue, value } = instr; if (value.kind === "MethodCall") { const lvalueScope = lvalue.identifier.scope; const propertyScope = value.property.identifier.scope; if (lvalueScope !== null) { if (propertyScope !== null) { mergedScopes.union([lvalueScope, propertyScope]); } else { scopeMapping.set(value.property.identifier.id, lvalueScope); } } else if (propertyScope !== null) { scopeMapping.set(value.property.identifier.id, null); } } else if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") { alignMethodCallScopes(value.loweredFunc.func); } } } mergedScopes.forEach((scope, root2) => { if (scope === root2) { return; } root2.range.start = makeInstructionId( Math.min(scope.range.start, root2.range.start) ); root2.range.end = makeInstructionId( Math.max(scope.range.end, root2.range.end) ); }); for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { const mappedScope = scopeMapping.get(instr.lvalue.identifier.id); if (mappedScope !== void 0) { instr.lvalue.identifier.scope = mappedScope; } else if (instr.lvalue.identifier.scope !== null) { const mergedScope = mergedScopes.find(instr.lvalue.identifier.scope); if (mergedScope != null) { instr.lvalue.identifier.scope = mergedScope; } } } } } // src/ReactiveScopes/AlignReactiveScopesToBlockScopesHIR.ts function alignReactiveScopesToBlockScopesHIR(fn) { var _a, _b, _c, _d, _e, _f, _g; const activeBlockFallthroughRanges = []; const activeScopes = /* @__PURE__ */ new Set(); const seen = /* @__PURE__ */ new Set(); const valueBlockNodes = /* @__PURE__ */ new Map(); const placeScopes = /* @__PURE__ */ new Map(); function recordPlace(id, place, node) { if (place.identifier.scope !== null) { placeScopes.set(place, place.identifier.scope); } const scope = getPlaceScope(id, place); if (scope == null) { return; } activeScopes.add(scope); node == null ? void 0 : node.children.push({ kind: "scope", scope, id }); if (seen.has(scope)) { return; } seen.add(scope); if (node != null && node.valueRange !== null) { scope.range.start = makeInstructionId( Math.min(node.valueRange.start, scope.range.start) ); scope.range.end = makeInstructionId( Math.max(node.valueRange.end, scope.range.end) ); } } for (const [, block] of fn.body.blocks) { const startingId = (_b = (_a = block.instructions[0]) == null ? void 0 : _a.id) != null ? _b : block.terminal.id; retainWhere_Set(activeScopes, (scope) => scope.range.end > startingId); const top = activeBlockFallthroughRanges.at(-1); if ((top == null ? void 0 : top.fallthrough) === block.id) { activeBlockFallthroughRanges.pop(); for (const scope of activeScopes) { scope.range.start = makeInstructionId( Math.min(scope.range.start, top.range.start) ); } } const { instructions, terminal } = block; const node = (_c = valueBlockNodes.get(block.id)) != null ? _c : null; for (const instr of instructions) { for (const lvalue of eachInstructionLValue(instr)) { recordPlace(instr.id, lvalue, node); } for (const operand of eachInstructionValueOperand(instr.value)) { recordPlace(instr.id, operand, node); } } for (const operand of eachTerminalOperand(terminal)) { recordPlace(terminal.id, operand, node); } const fallthrough = terminalFallthrough(terminal); if (fallthrough !== null && terminal.kind !== "branch") { const fallthroughBlock = fn.body.blocks.get(fallthrough); const nextId = (_e = (_d = fallthroughBlock.instructions[0]) == null ? void 0 : _d.id) != null ? _e : fallthroughBlock.terminal.id; for (const scope of activeScopes) { if (scope.range.end > terminal.id) { scope.range.end = makeInstructionId( Math.max(scope.range.end, nextId) ); } } activeBlockFallthroughRanges.push({ fallthrough, range: { start: terminal.id, end: nextId } }); CompilerError.invariant(!valueBlockNodes.has(fallthrough), { reason: "Expect hir blocks to have unique fallthroughs", description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); if (node != null) { valueBlockNodes.set(fallthrough, node); } } else if (terminal.kind === "goto") { const start = activeBlockFallthroughRanges.find( (range) => range.fallthrough === terminal.block ); if (start != null && start !== activeBlockFallthroughRanges.at(-1)) { const fallthroughBlock = fn.body.blocks.get(start.fallthrough); const firstId = (_g = (_f = fallthroughBlock.instructions[0]) == null ? void 0 : _f.id) != null ? _g : fallthroughBlock.terminal.id; for (const scope of activeScopes) { if (scope.range.end <= terminal.id) { continue; } scope.range.start = makeInstructionId( Math.min(start.range.start, scope.range.start) ); scope.range.end = makeInstructionId( Math.max(firstId, scope.range.end) ); } } } mapTerminalSuccessors(terminal, (successor) => { var _a2, _b2; if (valueBlockNodes.has(successor)) { return successor; } const successorBlock = fn.body.blocks.get(successor); if (successorBlock.kind === "block" || successorBlock.kind === "catch") { } else if (node == null || terminal.kind === "ternary" || terminal.kind === "logical" || terminal.kind === "optional") { let valueRange; if (node == null) { CompilerError.invariant(fallthrough !== null, { reason: `Expected a fallthrough for value block`, description: null, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); const fallthroughBlock = fn.body.blocks.get(fallthrough); const nextId = (_b2 = (_a2 = fallthroughBlock.instructions[0]) == null ? void 0 : _a2.id) != null ? _b2 : fallthroughBlock.terminal.id; valueRange = { start: terminal.id, end: nextId }; } else { valueRange = node.valueRange; } const childNode = { kind: "node", id: terminal.id, children: [], valueRange }; node == null ? void 0 : node.children.push(childNode); valueBlockNodes.set(successor, childNode); } else { valueBlockNodes.set(successor, node); } return successor; }); } } // src/ReactiveScopes/FlattenReactiveLoopsHIR.ts function flattenReactiveLoopsHIR(fn) { const activeLoops = Array(); for (const [, block] of fn.body.blocks) { retainWhere(activeLoops, (id) => id !== block.id); const { terminal } = block; switch (terminal.kind) { case "do-while": case "for": case "for-in": case "for-of": case "while": { activeLoops.push(terminal.fallthrough); break; } case "scope": { if (activeLoops.length !== 0) { block.terminal = { kind: "pruned-scope", block: terminal.block, fallthrough: terminal.fallthrough, id: terminal.id, loc: terminal.loc, scope: terminal.scope }; } break; } case "branch": case "goto": case "if": case "label": case "logical": case "maybe-throw": case "optional": case "pruned-scope": case "return": case "sequence": case "switch": case "ternary": case "throw": case "try": case "unreachable": case "unsupported": { break; } default: { assertExhaustive( terminal, `Unexpected terminal kind \`${terminal.kind}\`` ); } } } } // src/ReactiveScopes/FlattenScopesWithHooksOrUseHIR.ts function flattenScopesWithHooksOrUseHIR(fn) { const activeScopes = []; const prune = []; for (const [, block] of fn.body.blocks) { retainWhere(activeScopes, (current) => current.fallthrough !== block.id); for (const instr of block.instructions) { const { value } = instr; switch (value.kind) { case "MethodCall": case "CallExpression": { const callee = value.kind === "MethodCall" ? value.property : value.callee; if (getHookKind(fn.env, callee.identifier) != null || isUseOperator(callee.identifier)) { prune.push(...activeScopes.map((entry) => entry.block)); activeScopes.length = 0; } } } } if (block.terminal.kind === "scope") { activeScopes.push({ block: block.id, fallthrough: block.terminal.fallthrough }); } } for (const id of prune) { const block = fn.body.blocks.get(id); const terminal = block.terminal; CompilerError.invariant(terminal.kind === "scope", { reason: `Expected block to have a scope terminal`, description: `Expected block bb${block.id} to end in a scope terminal`, details: [ { kind: "error", loc: terminal.loc, message: null } ] }); const body = fn.body.blocks.get(terminal.block); if (body.instructions.length === 1 && body.terminal.kind === "goto" && body.terminal.block === terminal.fallthrough) { block.terminal = { kind: "label", block: terminal.block, fallthrough: terminal.fallthrough, id: terminal.id, loc: terminal.loc }; continue; } block.terminal = { kind: "pruned-scope", block: terminal.block, fallthrough: terminal.fallthrough, id: terminal.id, loc: terminal.loc, scope: terminal.scope }; } } // src/ReactiveScopes/PruneAlwaysInvalidatingScopes.ts function pruneAlwaysInvalidatingScopes(fn) { visitReactiveFunction(fn, new Transform5(), false); } var Transform5 = class extends ReactiveFunctionTransform { constructor() { super(...arguments); this.alwaysInvalidatingValues = /* @__PURE__ */ new Set(); this.unmemoizedValues = /* @__PURE__ */ new Set(); } transformInstruction(instruction, withinScope) { this.visitInstruction(instruction, withinScope); const { lvalue, value } = instruction; switch (value.kind) { case "ArrayExpression": case "ObjectExpression": case "JsxExpression": case "JsxFragment": case "NewExpression": { if (lvalue !== null) { this.alwaysInvalidatingValues.add(lvalue.identifier); if (!withinScope) { this.unmemoizedValues.add(lvalue.identifier); } } break; } case "StoreLocal": { if (this.alwaysInvalidatingValues.has(value.value.identifier)) { this.alwaysInvalidatingValues.add(value.lvalue.place.identifier); } if (this.unmemoizedValues.has(value.value.identifier)) { this.unmemoizedValues.add(value.lvalue.place.identifier); } break; } case "LoadLocal": { if (lvalue !== null && this.alwaysInvalidatingValues.has(value.place.identifier)) { this.alwaysInvalidatingValues.add(lvalue.identifier); } if (lvalue !== null && this.unmemoizedValues.has(value.place.identifier)) { this.unmemoizedValues.add(lvalue.identifier); } break; } } return { kind: "keep" }; } transformScope(scopeBlock, _withinScope) { this.visitScope(scopeBlock, true); for (const dep of scopeBlock.scope.dependencies) { if (this.unmemoizedValues.has(dep.identifier)) { for (const [_, decl] of scopeBlock.scope.declarations) { if (this.alwaysInvalidatingValues.has(decl.identifier)) { this.unmemoizedValues.add(decl.identifier); } } for (const identifier4 of scopeBlock.scope.reassignments) { if (this.alwaysInvalidatingValues.has(identifier4)) { this.unmemoizedValues.add(identifier4); } } return { kind: "replace", value: { kind: "pruned-scope", scope: scopeBlock.scope, instructions: scopeBlock.instructions } }; } } return { kind: "keep" }; } }; // src/ReactiveScopes/PruneInitializationDependencies.ts var Visitor9 = class extends ReactiveFunctionVisitor { constructor(env, aliases, paths) { super(); this.map = /* @__PURE__ */ new Map(); this.aliases = aliases; this.paths = paths; this.env = env; } join(values) { function join2(l, r) { if (l === "Update" || r === "Update") { return "Update"; } else if (l === "Create" || r === "Create") { return "Create"; } else if (l === "Unknown" || r === "Unknown") { return "Unknown"; } assertExhaustive(r, `Unhandled variable kind ${r}`); } return values.reduce(join2, "Unknown"); } isCreateOnlyHook(id) { return isUseStateType(id) || isUseRefType(id); } visitPlace(_, place, state) { var _a; this.map.set( place.identifier.id, this.join([state, (_a = this.map.get(place.identifier.id)) != null ? _a : "Unknown"]) ); } visitBlock(block, state) { super.visitBlock([...block].reverse(), state); } visitInstruction(instruction) { const state = this.join( [...eachInstructionLValue(instruction)].map( (operand) => { var _a; return (_a = this.map.get(operand.identifier.id)) != null ? _a : "Unknown"; } ) ); const visitCallOrMethodNonArgs = () => { switch (instruction.value.kind) { case "CallExpression": { this.visitPlace(instruction.id, instruction.value.callee, state); break; } case "MethodCall": { this.visitPlace(instruction.id, instruction.value.property, state); this.visitPlace(instruction.id, instruction.value.receiver, state); break; } } }; const isHook2 = () => { let callee = null; switch (instruction.value.kind) { case "CallExpression": { callee = instruction.value.callee.identifier; break; } case "MethodCall": { callee = instruction.value.property.identifier; break; } } return callee != null && getHookKind(this.env, callee) != null; }; switch (instruction.value.kind) { case "CallExpression": case "MethodCall": { if (instruction.lvalue && this.isCreateOnlyHook(instruction.lvalue.identifier)) { [...eachCallArgument(instruction.value.args)].forEach( (operand) => this.visitPlace(instruction.id, operand, "Create") ); visitCallOrMethodNonArgs(); } else { this.traverseInstruction(instruction, isHook2() ? "Update" : state); } break; } default: { this.traverseInstruction(instruction, state); } } } visitScope(scope) { const state = this.join( [ ...scope.scope.declarations.keys(), ...[...scope.scope.reassignments.values()].map((ident) => ident.id) ].map((id) => { var _a; return (_a = this.map.get(id)) != null ? _a : "Unknown"; }) ); super.visitScope(scope, state); [...scope.scope.dependencies].forEach((ident) => { var _a; let target = (_a = this.aliases.find(ident.identifier.id)) != null ? _a : ident.identifier.id; ident.path.forEach((token2) => { var _a2; target && (target = (_a2 = this.paths.get(target)) == null ? void 0 : _a2.get(token2.property)); }); if (target && this.map.get(target) === "Create") { scope.scope.dependencies.delete(ident); } }); } visitTerminal(stmt, state) { CompilerError.invariant(state !== "Create", { reason: "Visiting a terminal statement with state 'Create'", description: null, details: [ { kind: "error", loc: stmt.terminal.loc, message: null } ] }); super.visitTerminal(stmt, state); } visitReactiveFunctionValue(_id, _dependencies2, fn, state) { visitReactiveFunction(fn, this, state); } }; function pruneInitializationDependencies(fn) { const [aliases, paths] = getAliases(fn); visitReactiveFunction(fn, new Visitor9(fn.env, aliases, paths), "Update"); } function update(map2, key2, path, value) { var _a; const inner = (_a = map2.get(key2)) != null ? _a : /* @__PURE__ */ new Map(); inner.set(path, value); map2.set(key2, inner); } var AliasVisitor = class extends ReactiveFunctionVisitor { constructor() { super(...arguments); this.scopeIdentifiers = new DisjointSet(); this.scopePaths = /* @__PURE__ */ new Map(); } visitInstruction(instr) { if (instr.value.kind === "StoreLocal" || instr.value.kind === "StoreContext") { this.scopeIdentifiers.union([ instr.value.lvalue.place.identifier.id, instr.value.value.identifier.id ]); } else if (instr.value.kind === "LoadLocal" || instr.value.kind === "LoadContext") { instr.lvalue && this.scopeIdentifiers.union([ instr.lvalue.identifier.id, instr.value.place.identifier.id ]); } else if (instr.value.kind === "PropertyLoad") { instr.lvalue && update( this.scopePaths, instr.value.object.identifier.id, instr.value.property, instr.lvalue.identifier.id ); } else if (instr.value.kind === "PropertyStore") { update( this.scopePaths, instr.value.object.identifier.id, instr.value.property, instr.value.value.identifier.id ); } } }; function getAliases(fn) { var _a, _b; const visitor = new AliasVisitor(); visitReactiveFunction(fn, visitor, null); let disjoint = visitor.scopeIdentifiers; let scopePaths = /* @__PURE__ */ new Map(); for (const [key2, value] of visitor.scopePaths) { for (const [path, id] of value) { update( scopePaths, (_a = disjoint.find(key2)) != null ? _a : key2, path, (_b = disjoint.find(id)) != null ? _b : id ); } } return [disjoint, scopePaths]; } // src/TypeInference/InferTypes.ts function isPrimitiveBinaryOp(op) { switch (op) { case "+": case "-": case "/": case "%": case "*": case "**": case "&": case "|": case ">>": case "<<": case "^": case ">": case "<": case ">=": case "<=": case "|>": return true; default: return false; } } function inferTypes(func) { const unifier = new Unifier(func.env); for (const e of generate(func)) { unifier.unify(e.left, e.right); } apply(func, unifier); } function apply(func, unifier) { for (const [_, block] of func.body.blocks) { for (const phi of block.phis) { phi.place.identifier.type = unifier.get(phi.place.identifier.type); } for (const instr of block.instructions) { for (const operand of eachInstructionLValue(instr)) { operand.identifier.type = unifier.get(operand.identifier.type); } for (const place of eachInstructionOperand(instr)) { place.identifier.type = unifier.get(place.identifier.type); } const { lvalue, value } = instr; lvalue.identifier.type = unifier.get(lvalue.identifier.type); if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") { apply(value.loweredFunc.func, unifier); } } } const returns = func.returns.identifier; returns.type = unifier.get(returns.type); } function equation(left, right) { return { left, right }; } function* generate(func) { if (func.fnType === "Component") { const [props, ref] = func.params; if (props && props.kind === "Identifier") { yield equation(props.identifier.type, { kind: "Object", shapeId: BuiltInPropsId }); } if (ref && ref.kind === "Identifier") { yield equation(ref.identifier.type, { kind: "Object", shapeId: BuiltInUseRefId }); } } const names = /* @__PURE__ */ new Map(); const returnTypes = []; for (const [_, block] of func.body.blocks) { for (const phi of block.phis) { yield equation(phi.place.identifier.type, { kind: "Phi", operands: [...phi.operands.values()].map((id) => id.identifier.type) }); } for (const instr of block.instructions) { yield* __yieldStar(generateInstructionTypes(func.env, names, instr)); } const terminal = block.terminal; if (terminal.kind === "return") { returnTypes.push(terminal.value.identifier.type); } } if (returnTypes.length > 1) { yield equation(func.returns.identifier.type, { kind: "Phi", operands: returnTypes }); } else if (returnTypes.length === 1) { yield equation(func.returns.identifier.type, returnTypes[0]); } } function setName(names, id, name) { var _a; if (((_a = name.name) == null ? void 0 : _a.kind) === "named") { names.set(id, name.name.value); } } function getName(names, id) { var _a; return (_a = names.get(id)) != null ? _a : ""; } function* generateInstructionTypes(env, names, instr) { const { lvalue, value } = instr; const left = lvalue.identifier.type; switch (value.kind) { case "TemplateLiteral": case "JSXText": case "Primitive": { yield equation(left, { kind: "Primitive" }); break; } case "UnaryExpression": { yield equation(left, { kind: "Primitive" }); break; } case "LoadLocal": { setName(names, lvalue.identifier.id, value.place.identifier); yield equation(left, value.place.identifier.type); break; } // We intentionally do not infer types for most context variables case "DeclareContext": case "LoadContext": { break; } case "StoreContext": { if (value.lvalue.kind === "Const" /* Const */) { yield equation( value.lvalue.place.identifier.type, value.value.identifier.type ); } break; } case "StoreLocal": { if (env.config.enableUseTypeAnnotations) { yield equation( value.lvalue.place.identifier.type, value.value.identifier.type ); const valueType = value.type === null ? makeType() : lowerType(value.type); yield equation(valueType, value.lvalue.place.identifier.type); yield equation(left, valueType); } else { yield equation(left, value.value.identifier.type); yield equation( value.lvalue.place.identifier.type, value.value.identifier.type ); } break; } case "StoreGlobal": { yield equation(left, value.value.identifier.type); break; } case "BinaryExpression": { if (isPrimitiveBinaryOp(value.operator)) { yield equation(value.left.identifier.type, { kind: "Primitive" }); yield equation(value.right.identifier.type, { kind: "Primitive" }); } yield equation(left, { kind: "Primitive" }); break; } case "PostfixUpdate": case "PrefixUpdate": { yield equation(value.value.identifier.type, { kind: "Primitive" }); yield equation(value.lvalue.identifier.type, { kind: "Primitive" }); yield equation(left, { kind: "Primitive" }); break; } case "LoadGlobal": { const globalType = env.getGlobalDeclaration(value.binding, value.loc); if (globalType) { yield equation(left, globalType); } break; } case "CallExpression": { const returnType = makeType(); let shapeId = null; if (env.config.enableTreatSetIdentifiersAsStateSetters) { const name = getName(names, value.callee.identifier.id); if (name.startsWith("set")) { shapeId = BuiltInSetStateId; } } yield equation(value.callee.identifier.type, { kind: "Function", shapeId, return: returnType, isConstructor: false }); yield equation(left, returnType); break; } case "TaggedTemplateExpression": { const returnType = makeType(); yield equation(value.tag.identifier.type, { kind: "Function", shapeId: null, return: returnType, isConstructor: false }); yield equation(left, returnType); break; } case "ObjectExpression": { for (const property of value.properties) { if (property.kind === "ObjectProperty" && property.key.kind === "computed") { yield equation(property.key.name.identifier.type, { kind: "Primitive" }); } } yield equation(left, { kind: "Object", shapeId: BuiltInObjectId }); break; } case "ArrayExpression": { yield equation(left, { kind: "Object", shapeId: BuiltInArrayId }); break; } case "PropertyLoad": { yield equation(left, { kind: "Property", objectType: value.object.identifier.type, objectName: getName(names, value.object.identifier.id), propertyName: { kind: "literal", value: value.property } }); break; } case "ComputedLoad": { yield equation(left, { kind: "Property", objectType: value.object.identifier.type, objectName: getName(names, value.object.identifier.id), propertyName: { kind: "computed", value: value.property.identifier.type } }); break; } case "MethodCall": { const returnType = makeType(); yield equation(value.property.identifier.type, { kind: "Function", return: returnType, shapeId: null, isConstructor: false }); yield equation(left, returnType); break; } case "Destructure": { const pattern = value.lvalue.pattern; if (pattern.kind === "ArrayPattern") { for (let i = 0; i < pattern.items.length; i++) { const item = pattern.items[i]; if (item.kind === "Identifier") { const propertyName = String(i); yield equation(item.identifier.type, { kind: "Property", objectType: value.value.identifier.type, objectName: getName(names, value.value.identifier.id), propertyName: { kind: "literal", value: makePropertyLiteral(propertyName) } }); } else if (item.kind === "Spread") { yield equation(item.place.identifier.type, { kind: "Object", shapeId: BuiltInArrayId }); } else { break; } } } else { for (const property of pattern.properties) { if (property.kind === "ObjectProperty") { if (property.key.kind === "identifier" || property.key.kind === "string") { yield equation(property.place.identifier.type, { kind: "Property", objectType: value.value.identifier.type, objectName: getName(names, value.value.identifier.id), propertyName: { kind: "literal", value: makePropertyLiteral(property.key.name) } }); } } } } break; } case "TypeCastExpression": { if (env.config.enableUseTypeAnnotations) { yield equation(value.type, value.value.identifier.type); yield equation(left, value.type); } else { yield equation(left, value.value.identifier.type); } break; } case "PropertyDelete": case "ComputedDelete": { yield equation(left, { kind: "Primitive" }); break; } case "FunctionExpression": { yield* __yieldStar(generate(value.loweredFunc.func)); yield equation(left, { kind: "Function", shapeId: BuiltInFunctionId, return: value.loweredFunc.func.returns.identifier.type, isConstructor: false }); break; } case "NextPropertyOf": { yield equation(left, { kind: "Primitive" }); break; } case "ObjectMethod": { yield* __yieldStar(generate(value.loweredFunc.func)); yield equation(left, { kind: "ObjectMethod" }); break; } case "JsxExpression": case "JsxFragment": { if (env.config.enableTreatRefLikeIdentifiersAsRefs) { if (value.kind === "JsxExpression") { for (const prop of value.props) { if (prop.kind === "JsxAttribute" && prop.name === "ref") { yield equation(prop.place.identifier.type, { kind: "Object", shapeId: BuiltInUseRefId }); } } } } yield equation(left, { kind: "Object", shapeId: BuiltInJsxId }); break; } case "NewExpression": { const returnType = makeType(); yield equation(value.callee.identifier.type, { kind: "Function", return: returnType, shapeId: null, isConstructor: true }); yield equation(left, returnType); break; } case "PropertyStore": { yield equation( /** * Our property type declarations are best-effort and we haven't tested * using them to drive inference of rvalues from lvalues. We want to emit * a Property type in order to infer refs from `.current` accesses, but * stay conservative by not otherwise inferring anything about rvalues. * So we use a dummy type here. * * TODO: consider using the rvalue type here */ makeType(), // unify() only handles properties in the second position { kind: "Property", objectType: value.object.identifier.type, objectName: getName(names, value.object.identifier.id), propertyName: { kind: "literal", value: value.property } } ); break; } case "DeclareLocal": case "RegExpLiteral": case "MetaProperty": case "ComputedStore": case "Await": case "GetIterator": case "IteratorNext": case "UnsupportedNode": case "Debugger": case "FinishMemoize": case "StartMemoize": { break; } default: assertExhaustive( value, `Unhandled instruction value kind: ${value.kind}` ); } } var Unifier = class { constructor(env) { this.substitutions = /* @__PURE__ */ new Map(); this.env = env; } unify(tA, tB) { if (tB.kind === "Property") { if (this.env.config.enableTreatRefLikeIdentifiersAsRefs && isRefLikeName(tB)) { this.unify(tB.objectType, { kind: "Object", shapeId: BuiltInUseRefId }); this.unify(tA, { kind: "Object", shapeId: BuiltInRefValueId }); return; } const objectType = this.get(tB.objectType); const propertyType = tB.propertyName.kind === "literal" ? this.env.getPropertyType(objectType, tB.propertyName.value) : this.env.getFallthroughPropertyType( objectType, tB.propertyName.value ); if (propertyType !== null) { this.unify(tA, propertyType); } return; } if (typeEquals(tA, tB)) { return; } if (tA.kind === "Type") { this.bindVariableTo(tA, tB); return; } if (tB.kind === "Type") { this.bindVariableTo(tB, tA); return; } if (tB.kind === "Function" && tA.kind === "Function" && tA.isConstructor === tB.isConstructor) { this.unify(tA.return, tB.return); return; } } bindVariableTo(v, type) { if (type.kind === "Poly") { return; } if (this.substitutions.has(v.id)) { this.unify(this.substitutions.get(v.id), type); return; } if (type.kind === "Type" && this.substitutions.has(type.id)) { this.unify(v, this.substitutions.get(type.id)); return; } if (type.kind === "Phi") { CompilerError.invariant(type.operands.length > 0, { reason: "there should be at least one operand", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); let candidateType = null; for (const operand of type.operands) { const resolved = this.get(operand); if (candidateType === null) { candidateType = resolved; } else if (!typeEquals(resolved, candidateType)) { const unionType = tryUnionTypes(resolved, candidateType); if (unionType === null) { candidateType = null; break; } else { candidateType = unionType; } } } if (candidateType !== null) { this.unify(v, candidateType); return; } } if (this.occursCheck(v, type)) { const resolvedType = this.tryResolveType(v, type); if (resolvedType !== null) { this.substitutions.set(v.id, resolvedType); return; } throw new Error("cycle detected"); } this.substitutions.set(v.id, type); } tryResolveType(v, type) { switch (type.kind) { case "Phi": { const operands = []; for (const operand of type.operands) { if (operand.kind === "Type" && operand.id === v.id) { continue; } const resolved = this.tryResolveType(v, operand); if (resolved === null) { return null; } operands.push(resolved); } return { kind: "Phi", operands }; } case "Type": { const substitution = this.get(type); if (substitution !== type) { const resolved = this.tryResolveType(v, substitution); if (resolved !== null) { this.substitutions.set(type.id, resolved); } return resolved; } return type; } case "Property": { const objectType = this.tryResolveType(v, this.get(type.objectType)); if (objectType === null) { return null; } return { kind: "Property", objectName: type.objectName, objectType, propertyName: type.propertyName }; } case "Function": { const returnType = this.tryResolveType(v, this.get(type.return)); if (returnType === null) { return null; } return { kind: "Function", return: returnType, shapeId: type.shapeId, isConstructor: type.isConstructor }; } case "ObjectMethod": case "Object": case "Primitive": case "Poly": { return type; } default: { assertExhaustive(type, `Unexpected type kind '${type.kind}'`); } } } occursCheck(v, type) { if (typeEquals(v, type)) return true; if (type.kind === "Type" && this.substitutions.has(type.id)) { return this.occursCheck(v, this.substitutions.get(type.id)); } if (type.kind === "Phi") { return type.operands.some((o) => this.occursCheck(v, o)); } if (type.kind === "Function") { return this.occursCheck(v, type.return); } return false; } get(type) { if (type.kind === "Type") { if (this.substitutions.has(type.id)) { return this.get(this.substitutions.get(type.id)); } } if (type.kind === "Phi") { return { kind: "Phi", operands: type.operands.map((o) => this.get(o)) }; } if (type.kind === "Function") { return { kind: "Function", isConstructor: type.isConstructor, shapeId: type.shapeId, return: this.get(type.return) }; } return type; } }; var RefLikeNameRE = /^(?:[a-zA-Z$_][a-zA-Z$_0-9]*)Ref$|^ref$/; function isRefLikeName(t6) { return t6.propertyName.kind === "literal" && RefLikeNameRE.test(t6.objectName) && t6.propertyName.value === "current"; } function tryUnionTypes(ty1, ty2) { let readonlyType; let otherType; if (ty1.kind === "Object" && ty1.shapeId === BuiltInMixedReadonlyId) { readonlyType = ty1; otherType = ty2; } else if (ty2.kind === "Object" && ty2.shapeId === BuiltInMixedReadonlyId) { readonlyType = ty2; otherType = ty1; } else { return null; } if (otherType.kind === "Primitive") { return readonlyType; } else if (otherType.kind === "Object" && otherType.shapeId === BuiltInArrayId) { return otherType; } return null; } // src/Validation/ValidateContextVariableLValues.ts function validateContextVariableLValues(fn) { const identifierKinds = /* @__PURE__ */ new Map(); validateContextVariableLValuesImpl(fn, identifierKinds); } function validateContextVariableLValuesImpl(fn, identifierKinds) { for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { const { value } = instr; switch (value.kind) { case "DeclareContext": case "StoreContext": { visit3(identifierKinds, value.lvalue.place, "context"); break; } case "LoadContext": { visit3(identifierKinds, value.place, "context"); break; } case "StoreLocal": case "DeclareLocal": { visit3(identifierKinds, value.lvalue.place, "local"); break; } case "LoadLocal": { visit3(identifierKinds, value.place, "local"); break; } case "PostfixUpdate": case "PrefixUpdate": { visit3(identifierKinds, value.lvalue, "local"); break; } case "Destructure": { for (const lvalue of eachPatternOperand(value.lvalue.pattern)) { visit3(identifierKinds, lvalue, "destructure"); } break; } case "ObjectMethod": case "FunctionExpression": { validateContextVariableLValuesImpl( value.loweredFunc.func, identifierKinds ); break; } default: { for (const _ of eachInstructionValueLValue(value)) { CompilerError.throwTodo({ reason: "ValidateContextVariableLValues: unhandled instruction variant", loc: value.loc, description: `Handle '${value.kind} lvalues`, suggestions: null }); } } } } } } function visit3(identifiers, place, kind) { const prev = identifiers.get(place.identifier.id); if (prev !== void 0) { const wasContext = prev.kind === "context"; const isContext = kind === "context"; if (wasContext !== isContext) { if (prev.kind === "destructure" || kind === "destructure") { CompilerError.throwTodo({ reason: `Support destructuring of context variables`, loc: kind === "destructure" ? place.loc : prev.place.loc, description: null, suggestions: null }); } CompilerError.invariant(false, { reason: "Expected all references to a variable to be consistently local or context references", description: `Identifier ${printPlace( place )} is referenced as a ${kind} variable, but was previously referenced as a ${prev.kind} variable`, suggestions: null, details: [ { kind: "error", loc: place.loc, message: `this is ${prev.kind}` } ] }); } } identifiers.set(place.identifier.id, { place, kind }); } // src/HIR/ComputeUnconditionalBlocks.ts function computeUnconditionalBlocks(fn) { const unconditionalBlocks = /* @__PURE__ */ new Set(); const dominators = computePostDominatorTree(fn, { /* * Hooks must only be in a consistent order for executions that return normally, * so we opt-in to viewing throw as a non-exit node. */ includeThrowsAsExitNode: false }); const exit = dominators.exit; let current = fn.body.entry; while (current !== null && current !== exit) { CompilerError.invariant(!unconditionalBlocks.has(current), { reason: "Internal error: non-terminating loop in ComputeUnconditionalBlocks", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); unconditionalBlocks.add(current); current = dominators.get(current); } return unconditionalBlocks; } // src/Validation/ValidateHooksUsage.ts function joinKinds(a, b) { if (a === "Error" /* Error */ || b === "Error" /* Error */) { return "Error" /* Error */; } else if (a === "KnownHook" /* KnownHook */ || b === "KnownHook" /* KnownHook */) { return "KnownHook" /* KnownHook */; } else if (a === "PotentialHook" /* PotentialHook */ || b === "PotentialHook" /* PotentialHook */) { return "PotentialHook" /* PotentialHook */; } else if (a === "Global" /* Global */ || b === "Global" /* Global */) { return "Global" /* Global */; } else { return "Local" /* Local */; } } function validateHooksUsage(fn) { const unconditionalBlocks = computeUnconditionalBlocks(fn); const errors = new CompilerError(); const errorsByPlace = /* @__PURE__ */ new Map(); function recordError(loc, errorDetail) { if (typeof loc === "symbol") { errors.pushErrorDetail(errorDetail); } else { errorsByPlace.set(loc, errorDetail); } } function recordConditionalHookError(place) { setKind(place, "Error" /* Error */); const reason = "Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)"; const previousError = typeof place.loc !== "symbol" ? errorsByPlace.get(place.loc) : void 0; if (previousError === void 0 || previousError.reason !== reason) { recordError( place.loc, new CompilerErrorDetail({ category: "Hooks" /* Hooks */, description: null, reason, loc: place.loc, suggestions: null }) ); } } function recordInvalidHookUsageError(place) { const previousError = typeof place.loc !== "symbol" ? errorsByPlace.get(place.loc) : void 0; if (previousError === void 0) { recordError( place.loc, new CompilerErrorDetail({ category: "Hooks" /* Hooks */, description: null, reason: "Hooks may not be referenced as normal values, they must be called. See https://react.dev/reference/rules/react-calls-components-and-hooks#never-pass-around-hooks-as-regular-values", loc: place.loc, suggestions: null }) ); } } function recordDynamicHookUsageError(place) { const previousError = typeof place.loc !== "symbol" ? errorsByPlace.get(place.loc) : void 0; if (previousError === void 0) { recordError( place.loc, new CompilerErrorDetail({ category: "Hooks" /* Hooks */, description: null, reason: "Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks", loc: place.loc, suggestions: null }) ); } } const valueKinds = /* @__PURE__ */ new Map(); function getKindForPlace(place) { const knownKind = valueKinds.get(place.identifier.id); if (place.identifier.name !== null && isHookName(place.identifier.name.value)) { return joinKinds(knownKind != null ? knownKind : "Local" /* Local */, "PotentialHook" /* PotentialHook */); } else { return knownKind != null ? knownKind : "Local" /* Local */; } } function visitPlace2(place) { const kind = valueKinds.get(place.identifier.id); if (kind === "KnownHook" /* KnownHook */) { recordInvalidHookUsageError(place); } } function setKind(place, kind) { valueKinds.set(place.identifier.id, kind); } for (const param of fn.params) { const place = param.kind === "Identifier" ? param : param.place; const kind = getKindForPlace(place); setKind(place, kind); } for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { let kind = phi.place.identifier.name !== null && isHookName(phi.place.identifier.name.value) ? "PotentialHook" /* PotentialHook */ : "Local" /* Local */; for (const [, operand] of phi.operands) { const operandKind = valueKinds.get(operand.identifier.id); if (operandKind !== void 0) { kind = joinKinds(kind, operandKind); } } valueKinds.set(phi.place.identifier.id, kind); } for (const instr of block.instructions) { switch (instr.value.kind) { case "LoadGlobal": { if (getHookKind(fn.env, instr.lvalue.identifier) != null) { setKind(instr.lvalue, "KnownHook" /* KnownHook */); } else { setKind(instr.lvalue, "Global" /* Global */); } break; } case "LoadContext": case "LoadLocal": { visitPlace2(instr.value.place); const kind = getKindForPlace(instr.value.place); setKind(instr.lvalue, kind); break; } case "StoreLocal": case "StoreContext": { visitPlace2(instr.value.value); const kind = joinKinds( getKindForPlace(instr.value.value), getKindForPlace(instr.value.lvalue.place) ); setKind(instr.value.lvalue.place, kind); setKind(instr.lvalue, kind); break; } case "ComputedLoad": { visitPlace2(instr.value.object); const kind = getKindForPlace(instr.value.object); setKind(instr.lvalue, joinKinds(getKindForPlace(instr.lvalue), kind)); break; } case "PropertyLoad": { const objectKind = getKindForPlace(instr.value.object); const isHookProperty = typeof instr.value.property === "string" && isHookName(instr.value.property); let kind; switch (objectKind) { case "Error" /* Error */: { kind = "Error" /* Error */; break; } case "KnownHook" /* KnownHook */: { kind = isHookProperty ? "KnownHook" /* KnownHook */ : "Local" /* Local */; break; } case "PotentialHook" /* PotentialHook */: { kind = "PotentialHook" /* PotentialHook */; break; } case "Global" /* Global */: { kind = isHookProperty ? "KnownHook" /* KnownHook */ : "Global" /* Global */; break; } case "Local" /* Local */: { kind = isHookProperty ? "PotentialHook" /* PotentialHook */ : "Local" /* Local */; break; } default: { assertExhaustive(objectKind, `Unexpected kind \`${objectKind}\``); } } setKind(instr.lvalue, kind); break; } case "CallExpression": { const calleeKind = getKindForPlace(instr.value.callee); const isHookCallee = calleeKind === "KnownHook" /* KnownHook */ || calleeKind === "PotentialHook" /* PotentialHook */; if (isHookCallee && !unconditionalBlocks.has(block.id)) { recordConditionalHookError(instr.value.callee); } else if (calleeKind === "PotentialHook" /* PotentialHook */) { recordDynamicHookUsageError(instr.value.callee); } for (const operand of eachInstructionOperand(instr)) { if (operand === instr.value.callee) { continue; } visitPlace2(operand); } break; } case "MethodCall": { const calleeKind = getKindForPlace(instr.value.property); const isHookCallee = calleeKind === "KnownHook" /* KnownHook */ || calleeKind === "PotentialHook" /* PotentialHook */; if (isHookCallee && !unconditionalBlocks.has(block.id)) { recordConditionalHookError(instr.value.property); } else if (calleeKind === "PotentialHook" /* PotentialHook */) { recordDynamicHookUsageError(instr.value.property); } for (const operand of eachInstructionOperand(instr)) { if (operand === instr.value.property) { continue; } visitPlace2(operand); } break; } case "Destructure": { visitPlace2(instr.value.value); const objectKind = getKindForPlace(instr.value.value); for (const lvalue of eachInstructionLValue(instr)) { const isHookProperty = lvalue.identifier.name !== null && isHookName(lvalue.identifier.name.value); let kind; switch (objectKind) { case "Error" /* Error */: { kind = "Error" /* Error */; break; } case "KnownHook" /* KnownHook */: { kind = "KnownHook" /* KnownHook */; break; } case "PotentialHook" /* PotentialHook */: { kind = "PotentialHook" /* PotentialHook */; break; } case "Global" /* Global */: { kind = isHookProperty ? "KnownHook" /* KnownHook */ : "Global" /* Global */; break; } case "Local" /* Local */: { kind = isHookProperty ? "PotentialHook" /* PotentialHook */ : "Local" /* Local */; break; } default: { assertExhaustive( objectKind, `Unexpected kind \`${objectKind}\`` ); } } setKind(lvalue, kind); } break; } case "ObjectMethod": case "FunctionExpression": { visitFunctionExpression(errors, instr.value.loweredFunc.func); break; } default: { for (const operand of eachInstructionOperand(instr)) { visitPlace2(operand); } for (const lvalue of eachInstructionLValue(instr)) { const kind = getKindForPlace(lvalue); setKind(lvalue, kind); } } } } for (const operand of eachTerminalOperand(block.terminal)) { visitPlace2(operand); } } for (const [, error45] of errorsByPlace) { errors.pushErrorDetail(error45); } return errors.asResult(); } function visitFunctionExpression(errors, fn) { for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { switch (instr.value.kind) { case "ObjectMethod": case "FunctionExpression": { visitFunctionExpression(errors, instr.value.loweredFunc.func); break; } case "MethodCall": case "CallExpression": { const callee = instr.value.kind === "CallExpression" ? instr.value.callee : instr.value.property; const hookKind = getHookKind(fn.env, callee.identifier); if (hookKind != null) { errors.pushErrorDetail( new CompilerErrorDetail({ category: "Hooks" /* Hooks */, reason: "Hooks must be called at the top level in the body of a function component or custom hook, and may not be called within function expressions. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)", loc: callee.loc, description: `Cannot call ${hookKind === "Custom" ? "hook" : hookKind} within a function expression`, suggestions: null }) ); } break; } } } } } // src/Validation/ValidateMemoizedEffectDependencies.ts function validateMemoizedEffectDependencies(fn) { const errors = new CompilerError(); visitReactiveFunction(fn, new Visitor10(), errors); return errors.asResult(); } var Visitor10 = class extends ReactiveFunctionVisitor { constructor() { super(...arguments); this.scopes = /* @__PURE__ */ new Set(); } visitScope(scopeBlock, state) { this.traverseScope(scopeBlock, state); let areDependenciesMemoized = true; for (const dep of scopeBlock.scope.dependencies) { if (isUnmemoized(dep.identifier, this.scopes)) { areDependenciesMemoized = false; break; } } if (areDependenciesMemoized) { this.scopes.add(scopeBlock.scope.id); for (const id of scopeBlock.scope.merged) { this.scopes.add(id); } } } visitInstruction(instruction, state) { this.traverseInstruction(instruction, state); if (instruction.value.kind === "CallExpression" && isEffectHook(instruction.value.callee.identifier) && instruction.value.args.length >= 2) { const deps = instruction.value.args[1]; if (deps.kind === "Identifier" && /* * TODO: isMutable is not safe to call here as it relies on identifier mutableRange which is no longer valid at this point * in the pipeline */ (isMutable2(instruction, deps) || isUnmemoized(deps.identifier, this.scopes))) { state.push({ category: "EffectDependencies" /* EffectDependencies */, reason: "React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior", description: null, loc: typeof instruction.loc !== "symbol" ? instruction.loc : null, suggestions: null }); } } } }; function isUnmemoized(operand, scopes) { return operand.scope != null && !scopes.has(operand.scope.id); } function isEffectHook(identifier4) { return isUseEffectHookType(identifier4) || isUseLayoutEffectHookType(identifier4) || isUseInsertionEffectHookType(identifier4); } // src/Validation/ValidateNoCapitalizedCalls.ts function validateNoCapitalizedCalls(fn) { var _a; const envConfig = fn.env.config; const ALLOW_LIST = /* @__PURE__ */ new Set([ ...DEFAULT_GLOBALS.keys(), ...(_a = envConfig.validateNoCapitalizedCalls) != null ? _a : [] ]); const hookPattern = envConfig.hookPattern != null ? new RegExp(envConfig.hookPattern) : null; const isAllowed = (name) => { return ALLOW_LIST.has(name) || hookPattern != null && hookPattern.test(name); }; const errors = new CompilerError(); const capitalLoadGlobals = /* @__PURE__ */ new Map(); const capitalizedProperties = /* @__PURE__ */ new Map(); const reason = "Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config"; for (const [, block] of fn.body.blocks) { for (const { lvalue, value } of block.instructions) { switch (value.kind) { case "LoadGlobal": { if (value.binding.name != "" && /^[A-Z]/.test(value.binding.name) && // We don't want to flag CONSTANTS() !(value.binding.name.toUpperCase() === value.binding.name) && !isAllowed(value.binding.name)) { capitalLoadGlobals.set(lvalue.identifier.id, value.binding.name); } break; } case "CallExpression": { const calleeIdentifier = value.callee.identifier.id; const calleeName = capitalLoadGlobals.get(calleeIdentifier); if (calleeName != null) { CompilerError.throwInvalidReact({ category: "CapitalizedCalls" /* CapitalizedCalls */, reason, description: `${calleeName} may be a component`, loc: value.loc, suggestions: null }); } break; } case "PropertyLoad": { if (typeof value.property === "string" && /^[A-Z]/.test(value.property)) { capitalizedProperties.set(lvalue.identifier.id, value.property); } break; } case "MethodCall": { const propertyIdentifier = value.property.identifier.id; const propertyName = capitalizedProperties.get(propertyIdentifier); if (propertyName != null) { errors.push({ category: "CapitalizedCalls" /* CapitalizedCalls */, reason, description: `${propertyName} may be a component`, loc: value.loc, suggestions: null }); } break; } } } } return errors.asResult(); } // src/Validation/ValidateNoRefAccessInRender.ts var opaqueRefId = Symbol(); function makeRefId(id) { CompilerError.invariant(id >= 0 && Number.isInteger(id), { reason: "Expected identifier id to be a non-negative integer", description: null, suggestions: null, details: [ { kind: "error", loc: null, message: null } ] }); return id; } var _refId = 0; function nextRefId() { return makeRefId(_refId++); } var _changed, _data, _temporaries2; var Env = class { constructor() { __privateAdd(this, _changed, false); __privateAdd(this, _data, /* @__PURE__ */ new Map()); __privateAdd(this, _temporaries2, /* @__PURE__ */ new Map()); } lookup(place) { var _a; return (_a = __privateGet(this, _temporaries2).get(place.identifier.id)) != null ? _a : place; } define(place, value) { __privateGet(this, _temporaries2).set(place.identifier.id, value); } resetChanged() { __privateSet(this, _changed, false); } hasChanged() { return __privateGet(this, _changed); } get(key2) { var _a, _b; const operandId = (_b = (_a = __privateGet(this, _temporaries2).get(key2)) == null ? void 0 : _a.identifier.id) != null ? _b : key2; return __privateGet(this, _data).get(operandId); } set(key2, value) { var _a, _b; const operandId = (_b = (_a = __privateGet(this, _temporaries2).get(key2)) == null ? void 0 : _a.identifier.id) != null ? _b : key2; const cur = __privateGet(this, _data).get(operandId); const widenedValue = joinRefAccessTypes(value, cur != null ? cur : { kind: "None" }); if (!(cur == null && widenedValue.kind === "None") && (cur == null || !tyEqual(cur, widenedValue))) { __privateSet(this, _changed, true); } __privateGet(this, _data).set(operandId, widenedValue); return this; } }; _changed = new WeakMap(); _data = new WeakMap(); _temporaries2 = new WeakMap(); function validateNoRefAccessInRender(fn) { const env = new Env(); collectTemporariesSidemap2(fn, env); return validateNoRefAccessInRenderImpl(fn, env).map((_) => void 0); } function collectTemporariesSidemap2(fn, env) { for (const block of fn.body.blocks.values()) { for (const instr of block.instructions) { const { lvalue, value } = instr; switch (value.kind) { case "LoadLocal": { const temp = env.lookup(value.place); if (temp != null) { env.define(lvalue, temp); } break; } case "StoreLocal": { const temp = env.lookup(value.value); if (temp != null) { env.define(lvalue, temp); env.define(value.lvalue.place, temp); } break; } case "PropertyLoad": { if (isUseRefType(value.object.identifier) && value.property === "current") { continue; } const temp = env.lookup(value.object); if (temp != null) { env.define(lvalue, temp); } break; } } } } } function refTypeOfType(place) { if (isRefValueType(place.identifier)) { return { kind: "RefValue" }; } else if (isUseRefType(place.identifier)) { return { kind: "Ref", refId: nextRefId() }; } else { return { kind: "None" }; } } function tyEqual(a, b) { if (a.kind !== b.kind) { return false; } switch (a.kind) { case "None": return true; case "Ref": return true; case "Nullable": return true; case "Guard": CompilerError.invariant(b.kind === "Guard", { reason: "Expected ref value", description: null, details: [ { kind: "error", loc: null, message: null } ] }); return a.refId === b.refId; case "RefValue": CompilerError.invariant(b.kind === "RefValue", { reason: "Expected ref value", description: null, details: [ { kind: "error", loc: null, message: null } ] }); return a.loc == b.loc; case "Structure": { CompilerError.invariant(b.kind === "Structure", { reason: "Expected structure", description: null, details: [ { kind: "error", loc: null, message: null } ] }); const fnTypesEqual = a.fn === null && b.fn === null || a.fn !== null && b.fn !== null && a.fn.readRefEffect === b.fn.readRefEffect && tyEqual(a.fn.returnType, b.fn.returnType); return fnTypesEqual && (a.value === b.value || a.value !== null && b.value !== null && tyEqual(a.value, b.value)); } } } function joinRefAccessTypes(...types) { function joinRefAccessRefTypes(a, b) { if (a.kind === "RefValue") { if (b.kind === "RefValue" && a.refId === b.refId) { return a; } return { kind: "RefValue" }; } else if (b.kind === "RefValue") { return b; } else if (a.kind === "Ref" || b.kind === "Ref") { if (a.kind === "Ref" && b.kind === "Ref" && a.refId === b.refId) { return a; } return { kind: "Ref", refId: nextRefId() }; } else { CompilerError.invariant( a.kind === "Structure" && b.kind === "Structure", { reason: "Expected structure", description: null, details: [ { kind: "error", loc: null, message: null } ] } ); const fn = a.fn === null ? b.fn : b.fn === null ? a.fn : { readRefEffect: a.fn.readRefEffect || b.fn.readRefEffect, returnType: joinRefAccessTypes( a.fn.returnType, b.fn.returnType ) }; const value = a.value === null ? b.value : b.value === null ? a.value : joinRefAccessRefTypes(a.value, b.value); return { kind: "Structure", fn, value }; } } return types.reduce( (a, b) => { if (a.kind === "None") { return b; } else if (b.kind === "None") { return a; } else if (a.kind === "Guard") { if (b.kind === "Guard" && a.refId === b.refId) { return a; } else if (b.kind === "Nullable" || b.kind === "Guard") { return { kind: "None" }; } else { return b; } } else if (b.kind === "Guard") { if (a.kind === "Nullable") { return { kind: "None" }; } else { return b; } } else if (a.kind === "Nullable") { return b; } else if (b.kind === "Nullable") { return a; } else { return joinRefAccessRefTypes(a, b); } }, { kind: "None" } ); } function validateNoRefAccessInRenderImpl(fn, env) { var _a, _b, _c, _d, _e, _f, _g, _h, _i; let returnValues = []; let place; for (const param of fn.params) { if (param.kind === "Identifier") { place = param; } else { place = param.place; } const type = refTypeOfType(place); env.set(place.identifier.id, type); } const interpolatedAsJsx = /* @__PURE__ */ new Set(); for (const block of fn.body.blocks.values()) { for (const instr of block.instructions) { const { value } = instr; if (value.kind === "JsxExpression" || value.kind === "JsxFragment") { if (value.children != null) { for (const child of value.children) { interpolatedAsJsx.add(child.identifier.id); } } } } } for (let i = 0; (i == 0 || env.hasChanged()) && i < 10; i++) { env.resetChanged(); returnValues = []; const safeBlocks = []; const errors = new CompilerError(); for (const [, block] of fn.body.blocks) { retainWhere(safeBlocks, (entry) => entry.block !== block.id); for (const phi of block.phis) { env.set( phi.place.identifier.id, joinRefAccessTypes( ...Array(...phi.operands.values()).map( (operand) => { var _a2; return (_a2 = env.get(operand.identifier.id)) != null ? _a2 : { kind: "None" }; } ) ) ); } for (const instr of block.instructions) { switch (instr.value.kind) { case "JsxExpression": case "JsxFragment": { for (const operand of eachInstructionValueOperand(instr.value)) { validateNoDirectRefValueAccess(errors, operand, env); } break; } case "ComputedLoad": case "PropertyLoad": { if (instr.value.kind === "ComputedLoad") { validateNoDirectRefValueAccess(errors, instr.value.property, env); } const objType = env.get(instr.value.object.identifier.id); let lookupType = null; if ((objType == null ? void 0 : objType.kind) === "Structure") { lookupType = objType.value; } else if ((objType == null ? void 0 : objType.kind) === "Ref") { lookupType = { kind: "RefValue", loc: instr.loc, refId: objType.refId }; } env.set( instr.lvalue.identifier.id, lookupType != null ? lookupType : refTypeOfType(instr.lvalue) ); break; } case "TypeCastExpression": { env.set( instr.lvalue.identifier.id, (_a = env.get(instr.value.value.identifier.id)) != null ? _a : refTypeOfType(instr.lvalue) ); break; } case "LoadContext": case "LoadLocal": { env.set( instr.lvalue.identifier.id, (_b = env.get(instr.value.place.identifier.id)) != null ? _b : refTypeOfType(instr.lvalue) ); break; } case "StoreContext": case "StoreLocal": { env.set( instr.value.lvalue.place.identifier.id, (_c = env.get(instr.value.value.identifier.id)) != null ? _c : refTypeOfType(instr.value.lvalue.place) ); env.set( instr.lvalue.identifier.id, (_d = env.get(instr.value.value.identifier.id)) != null ? _d : refTypeOfType(instr.lvalue) ); break; } case "Destructure": { const objType = env.get(instr.value.value.identifier.id); let lookupType = null; if ((objType == null ? void 0 : objType.kind) === "Structure") { lookupType = objType.value; } env.set( instr.lvalue.identifier.id, lookupType != null ? lookupType : refTypeOfType(instr.lvalue) ); for (const lval of eachPatternOperand(instr.value.lvalue.pattern)) { env.set(lval.identifier.id, lookupType != null ? lookupType : refTypeOfType(lval)); } break; } case "ObjectMethod": case "FunctionExpression": { let returnType = { kind: "None" }; let readRefEffect = false; const result = validateNoRefAccessInRenderImpl( instr.value.loweredFunc.func, env ); if (result.isOk()) { returnType = result.unwrap(); } else if (result.isErr()) { readRefEffect = true; } env.set(instr.lvalue.identifier.id, { kind: "Structure", fn: { readRefEffect, returnType }, value: null }); break; } case "MethodCall": case "CallExpression": { const callee = instr.value.kind === "CallExpression" ? instr.value.callee : instr.value.property; const hookKind = getHookKindForType(fn.env, callee.identifier.type); let returnType = { kind: "None" }; const fnType = env.get(callee.identifier.id); let didError = false; if ((fnType == null ? void 0 : fnType.kind) === "Structure" && fnType.fn !== null) { returnType = fnType.fn.returnType; if (fnType.fn.readRefEffect) { didError = true; errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Refs" /* Refs */, reason: "Cannot access refs during render", description: ERROR_DESCRIPTION }).withDetails({ kind: "error", loc: callee.loc, message: `This function accesses a ref value` }) ); } } if (!didError) { const isRefLValue = isUseRefType(instr.lvalue.identifier); for (const operand of eachInstructionValueOperand(instr.value)) { if (isRefLValue || hookKind != null && hookKind !== "useState" && hookKind !== "useReducer") { validateNoDirectRefValueAccess(errors, operand, env); } else if (interpolatedAsJsx.has(instr.lvalue.identifier.id)) { validateNoRefValueAccess(errors, env, operand); } else { validateNoRefPassedToFunction( errors, env, operand, operand.loc ); } } } env.set(instr.lvalue.identifier.id, returnType); break; } case "ObjectExpression": case "ArrayExpression": { const types = []; for (const operand of eachInstructionValueOperand(instr.value)) { validateNoDirectRefValueAccess(errors, operand, env); types.push((_e = env.get(operand.identifier.id)) != null ? _e : { kind: "None" }); } const value = joinRefAccessTypes(...types); if (value.kind === "None" || value.kind === "Guard" || value.kind === "Nullable") { env.set(instr.lvalue.identifier.id, { kind: "None" }); } else { env.set(instr.lvalue.identifier.id, { kind: "Structure", value, fn: null }); } break; } case "PropertyDelete": case "PropertyStore": case "ComputedDelete": case "ComputedStore": { const target = env.get(instr.value.object.identifier.id); let safe = null; if (instr.value.kind === "PropertyStore" && target != null && target.kind === "Ref") { safe = safeBlocks.find((entry) => entry.ref === target.refId); } if (safe != null) { retainWhere(safeBlocks, (entry) => entry !== safe); } else { validateNoRefUpdate(errors, env, instr.value.object, instr.loc); } if (instr.value.kind === "ComputedDelete" || instr.value.kind === "ComputedStore") { validateNoRefValueAccess(errors, env, instr.value.property); } if (instr.value.kind === "ComputedStore" || instr.value.kind === "PropertyStore") { validateNoDirectRefValueAccess(errors, instr.value.value, env); const type = env.get(instr.value.value.identifier.id); if (type != null && type.kind === "Structure") { let objectType = type; if (target != null) { objectType = joinRefAccessTypes(objectType, target); } env.set(instr.value.object.identifier.id, objectType); } } break; } case "StartMemoize": case "FinishMemoize": break; case "LoadGlobal": { if (instr.value.binding.name === "undefined") { env.set(instr.lvalue.identifier.id, { kind: "Nullable" }); } break; } case "Primitive": { if (instr.value.value == null) { env.set(instr.lvalue.identifier.id, { kind: "Nullable" }); } break; } case "UnaryExpression": { if (instr.value.operator === "!") { const value = env.get(instr.value.value.identifier.id); const refId = (value == null ? void 0 : value.kind) === "RefValue" && value.refId != null ? value.refId : null; if (refId !== null) { env.set(instr.lvalue.identifier.id, { kind: "Guard", refId }); errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Refs" /* Refs */, reason: "Cannot access refs during render", description: ERROR_DESCRIPTION }).withDetails({ kind: "error", loc: instr.value.value.loc, message: `Cannot access ref value during render` }).withDetails({ kind: "hint", message: "To initialize a ref only once, check that the ref is null with the pattern `if (ref.current == null) { ref.current = ... }`" }) ); break; } } validateNoRefValueAccess(errors, env, instr.value.value); break; } case "BinaryExpression": { const left = env.get(instr.value.left.identifier.id); const right = env.get(instr.value.right.identifier.id); let nullish3 = false; let refId = null; if ((left == null ? void 0 : left.kind) === "RefValue" && left.refId != null) { refId = left.refId; } else if ((right == null ? void 0 : right.kind) === "RefValue" && right.refId != null) { refId = right.refId; } if ((left == null ? void 0 : left.kind) === "Nullable") { nullish3 = true; } else if ((right == null ? void 0 : right.kind) === "Nullable") { nullish3 = true; } if (refId !== null && nullish3) { env.set(instr.lvalue.identifier.id, { kind: "Guard", refId }); } else { for (const operand of eachInstructionValueOperand(instr.value)) { validateNoRefValueAccess(errors, env, operand); } } break; } default: { for (const operand of eachInstructionValueOperand(instr.value)) { validateNoRefValueAccess(errors, env, operand); } break; } } for (const operand of eachInstructionOperand(instr)) { guardCheck(errors, operand, env); } if (isUseRefType(instr.lvalue.identifier) && ((_f = env.get(instr.lvalue.identifier.id)) == null ? void 0 : _f.kind) !== "Ref") { env.set( instr.lvalue.identifier.id, joinRefAccessTypes( (_g = env.get(instr.lvalue.identifier.id)) != null ? _g : { kind: "None" }, { kind: "Ref", refId: nextRefId() } ) ); } if (isRefValueType(instr.lvalue.identifier) && ((_h = env.get(instr.lvalue.identifier.id)) == null ? void 0 : _h.kind) !== "RefValue") { env.set( instr.lvalue.identifier.id, joinRefAccessTypes( (_i = env.get(instr.lvalue.identifier.id)) != null ? _i : { kind: "None" }, { kind: "RefValue", loc: instr.loc } ) ); } } if (block.terminal.kind === "if") { const test = env.get(block.terminal.test.identifier.id); if ((test == null ? void 0 : test.kind) === "Guard" && safeBlocks.find((entry) => entry.ref === test.refId) == null) { safeBlocks.push({ block: block.terminal.fallthrough, ref: test.refId }); } } for (const operand of eachTerminalOperand(block.terminal)) { if (block.terminal.kind !== "return") { validateNoRefValueAccess(errors, env, operand); if (block.terminal.kind !== "if") { guardCheck(errors, operand, env); } } else { validateNoDirectRefValueAccess(errors, operand, env); guardCheck(errors, operand, env); returnValues.push(env.get(operand.identifier.id)); } } } if (errors.hasAnyErrors()) { return Err(errors); } } CompilerError.invariant(!env.hasChanged(), { reason: "Ref type environment did not converge", description: null, details: [ { kind: "error", loc: null, message: null } ] }); return Ok( joinRefAccessTypes( ...returnValues.filter((env2) => env2 !== void 0) ) ); } function destructure(type) { if ((type == null ? void 0 : type.kind) === "Structure" && type.value !== null) { return destructure(type.value); } return type; } function guardCheck(errors, operand, env) { var _a; if (((_a = env.get(operand.identifier.id)) == null ? void 0 : _a.kind) === "Guard") { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Refs" /* Refs */, reason: "Cannot access refs during render", description: ERROR_DESCRIPTION }).withDetails({ kind: "error", loc: operand.loc, message: `Cannot access ref value during render` }) ); } } function validateNoRefValueAccess(errors, env, operand) { var _a; const type = destructure(env.get(operand.identifier.id)); if ((type == null ? void 0 : type.kind) === "RefValue" || (type == null ? void 0 : type.kind) === "Structure" && ((_a = type.fn) == null ? void 0 : _a.readRefEffect)) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Refs" /* Refs */, reason: "Cannot access refs during render", description: ERROR_DESCRIPTION }).withDetails({ kind: "error", loc: type.kind === "RefValue" && type.loc || operand.loc, message: `Cannot access ref value during render` }) ); } } function validateNoRefPassedToFunction(errors, env, operand, loc) { var _a; const type = destructure(env.get(operand.identifier.id)); if ((type == null ? void 0 : type.kind) === "Ref" || (type == null ? void 0 : type.kind) === "RefValue" || (type == null ? void 0 : type.kind) === "Structure" && ((_a = type.fn) == null ? void 0 : _a.readRefEffect)) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Refs" /* Refs */, reason: "Cannot access refs during render", description: ERROR_DESCRIPTION }).withDetails({ kind: "error", loc: type.kind === "RefValue" && type.loc || loc, message: `Passing a ref to a function may read its value during render` }) ); } } function validateNoRefUpdate(errors, env, operand, loc) { const type = destructure(env.get(operand.identifier.id)); if ((type == null ? void 0 : type.kind) === "Ref" || (type == null ? void 0 : type.kind) === "RefValue") { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Refs" /* Refs */, reason: "Cannot access refs during render", description: ERROR_DESCRIPTION }).withDetails({ kind: "error", loc: type.kind === "RefValue" && type.loc || loc, message: `Cannot update ref during render` }) ); } } function validateNoDirectRefValueAccess(errors, operand, env) { var _a; const type = destructure(env.get(operand.identifier.id)); if ((type == null ? void 0 : type.kind) === "RefValue") { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Refs" /* Refs */, reason: "Cannot access refs during render", description: ERROR_DESCRIPTION }).withDetails({ kind: "error", loc: (_a = type.loc) != null ? _a : operand.loc, message: `Cannot access ref value during render` }) ); } } var ERROR_DESCRIPTION = "React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the `current` property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef)"; // src/Validation/ValidateNoSetStateInRender.ts function validateNoSetStateInRender(fn) { const unconditionalSetStateFunctions = /* @__PURE__ */ new Set(); return validateNoSetStateInRenderImpl(fn, unconditionalSetStateFunctions); } function validateNoSetStateInRenderImpl(fn, unconditionalSetStateFunctions) { const unconditionalBlocks = computeUnconditionalBlocks(fn); let activeManualMemoId = null; const errors = new CompilerError(); for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { switch (instr.value.kind) { case "LoadLocal": { if (unconditionalSetStateFunctions.has(instr.value.place.identifier.id)) { unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); } break; } case "StoreLocal": { if (unconditionalSetStateFunctions.has(instr.value.value.identifier.id)) { unconditionalSetStateFunctions.add( instr.value.lvalue.place.identifier.id ); unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); } break; } case "ObjectMethod": case "FunctionExpression": { if ( // faster-path to check if the function expression references a setState [...eachInstructionValueOperand(instr.value)].some( (operand) => isSetStateType(operand.identifier) || unconditionalSetStateFunctions.has(operand.identifier.id) ) && // if yes, does it unconditonally call it? validateNoSetStateInRenderImpl( instr.value.loweredFunc.func, unconditionalSetStateFunctions ).isErr() ) { unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); } break; } case "StartMemoize": { CompilerError.invariant(activeManualMemoId === null, { reason: "Unexpected nested StartMemoize instructions", description: null, details: [ { kind: "error", loc: instr.value.loc, message: null } ] }); activeManualMemoId = instr.value.manualMemoId; break; } case "FinishMemoize": { CompilerError.invariant( activeManualMemoId === instr.value.manualMemoId, { reason: "Expected FinishMemoize to align with previous StartMemoize instruction", description: null, details: [ { kind: "error", loc: instr.value.loc, message: null } ] } ); activeManualMemoId = null; break; } case "CallExpression": { const callee = instr.value.callee; if (isSetStateType(callee.identifier) || unconditionalSetStateFunctions.has(callee.identifier.id)) { if (activeManualMemoId !== null) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "RenderSetState" /* RenderSetState */, reason: "Calling setState from useMemo may trigger an infinite loop", description: "Each time the memo callback is evaluated it will change state. This can cause a memoization dependency to change, running the memo function again and causing an infinite loop. Instead of setting state in useMemo(), prefer deriving the value during render. (https://react.dev/reference/react/useState)", suggestions: null }).withDetails({ kind: "error", loc: callee.loc, message: "Found setState() within useMemo()" }) ); } else if (unconditionalBlocks.has(block.id)) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "RenderSetState" /* RenderSetState */, reason: "Calling setState during render may trigger an infinite loop", description: "Calling setState during render will trigger another render, and can lead to infinite loops. (https://react.dev/reference/react/useState)", suggestions: null }).withDetails({ kind: "error", loc: callee.loc, message: "Found setState() in render" }) ); } } break; } } } } return errors.asResult(); } // src/Validation/ValidatePreservedManualMemoization.ts function validatePreservedManualMemoization(fn) { const state = { errors: new CompilerError(), manualMemoState: null }; visitReactiveFunction(fn, new Visitor11(), state); return state.errors.asResult(); } var DEBUG5 = false; function prettyPrintScopeDependency(val) { var _a; let rootStr; if (((_a = val.identifier.name) == null ? void 0 : _a.kind) === "named") { rootStr = val.identifier.name.value; } else { rootStr = "[unnamed]"; } return `${rootStr}${val.path.map((v) => `${v.optional ? "?." : "."}${v.property}`).join("")}`; } function merge3(a, b) { return Math.max(a, b); } function getCompareDependencyResultDescription(result) { switch (result) { case 0 /* Ok */: return "Dependencies equal"; case 1 /* RootDifference */: case 2 /* PathDifference */: return "Inferred different dependency than source"; case 4 /* RefAccessDifference */: return "Differences in ref.current access"; case 3 /* Subpath */: return "Inferred less specific property than source"; } } function compareDeps(inferred, source2) { const rootsEqual = inferred.root.kind === "Global" && source2.root.kind === "Global" && inferred.root.identifierName === source2.root.identifierName || inferred.root.kind === "NamedLocal" && source2.root.kind === "NamedLocal" && inferred.root.value.identifier.id === source2.root.value.identifier.id; if (!rootsEqual) { return 1 /* RootDifference */; } let isSubpath = true; for (let i = 0; i < Math.min(inferred.path.length, source2.path.length); i++) { if (inferred.path[i].property !== source2.path[i].property) { isSubpath = false; break; } else if (inferred.path[i].optional !== source2.path[i].optional) { return 2 /* PathDifference */; } } if (isSubpath && (source2.path.length === inferred.path.length || inferred.path.length >= source2.path.length && !inferred.path.some((token2) => token2.property === "current"))) { return 0 /* Ok */; } else { if (isSubpath) { if (source2.path.some((token2) => token2.property === "current") || inferred.path.some((token2) => token2.property === "current")) { return 4 /* RefAccessDifference */; } else { return 3 /* Subpath */; } } else { return 2 /* PathDifference */; } } } function validateInferredDep(dep, temporaries, declsWithinMemoBlock, validDepsInMemoBlock, errorState, memoLocation) { var _a; let normalizedDep; const maybeNormalizedRoot = temporaries.get(dep.identifier.id); if (maybeNormalizedRoot != null) { normalizedDep = { root: maybeNormalizedRoot.root, path: [...maybeNormalizedRoot.path, ...dep.path] }; } else { CompilerError.invariant(((_a = dep.identifier.name) == null ? void 0 : _a.kind) === "named", { reason: "ValidatePreservedManualMemoization: expected scope dependency to be named", description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ], suggestions: null }); normalizedDep = { root: { kind: "NamedLocal", value: { kind: "Identifier", identifier: dep.identifier, loc: GeneratedSource, effect: "read" /* Read */, reactive: false } }, path: [...dep.path] }; } for (const decl of declsWithinMemoBlock) { if (normalizedDep.root.kind === "NamedLocal" && decl === normalizedDep.root.value.identifier.declarationId) { return; } } let errorDiagnostic = null; for (const originalDep of validDepsInMemoBlock) { const compareResult = compareDeps(normalizedDep, originalDep); if (compareResult === 0 /* Ok */) { return; } else { errorDiagnostic = merge3(errorDiagnostic != null ? errorDiagnostic : compareResult, compareResult); } } errorState.pushDiagnostic( CompilerDiagnostic.create({ category: "PreserveManualMemo" /* PreserveManualMemo */, reason: "Existing memoization could not be preserved", description: [ "React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. ", "The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. ", DEBUG5 || // If the dependency is a named variable then we can report it. Otherwise only print in debug mode dep.identifier.name != null && dep.identifier.name.kind === "named" ? `The inferred dependency was \`${prettyPrintScopeDependency( dep )}\`, but the source dependencies were [${validDepsInMemoBlock.map((dep2) => printManualMemoDependency(dep2, true)).join(", ")}]. ${errorDiagnostic ? getCompareDependencyResultDescription(errorDiagnostic) : "Inferred dependency not present in source"}` : "" ].join("").trim(), suggestions: null }).withDetails({ kind: "error", loc: memoLocation, message: "Could not preserve existing manual memoization" }) ); } var Visitor11 = class extends ReactiveFunctionVisitor { constructor() { super(...arguments); /** * Records all completed scopes (regardless of transitive memoization * of scope dependencies) * * Both @scopes and @prunedScopes are live sets. We rely on iterating * the reactive-ir in evaluation order, as they are used to determine * whether scope dependencies / declarations have completed mutation. */ this.scopes = /* @__PURE__ */ new Set(); this.prunedScopes = /* @__PURE__ */ new Set(); this.temporaries = /* @__PURE__ */ new Map(); } /** * Recursively visit values and instructions to collect declarations * and property loads. * @returns a @{ManualMemoDependency} representing the variable + * property reads represented by @value */ recordDepsInValue(value, state) { var _a, _b; switch (value.kind) { case "SequenceExpression": { for (const instr of value.instructions) { this.visitInstruction(instr, state); } this.recordDepsInValue(value.value, state); break; } case "OptionalExpression": { this.recordDepsInValue(value.value, state); break; } case "ConditionalExpression": { this.recordDepsInValue(value.test, state); this.recordDepsInValue(value.consequent, state); this.recordDepsInValue(value.alternate, state); break; } case "LogicalExpression": { this.recordDepsInValue(value.left, state); this.recordDepsInValue(value.right, state); break; } default: { collectMaybeMemoDependencies(value, this.temporaries, false); if (value.kind === "StoreLocal" || value.kind === "StoreContext" || value.kind === "Destructure") { for (const storeTarget of eachInstructionValueLValue(value)) { (_a = state.manualMemoState) == null ? void 0 : _a.decls.add( storeTarget.identifier.declarationId ); if (((_b = storeTarget.identifier.name) == null ? void 0 : _b.kind) === "named") { this.temporaries.set(storeTarget.identifier.id, { root: { kind: "NamedLocal", value: storeTarget }, path: [] }); } } } break; } } } recordTemporaries(instr, state) { var _a; const temporaries = this.temporaries; const { lvalue, value } = instr; const lvalId = lvalue == null ? void 0 : lvalue.identifier.id; if (lvalId != null && temporaries.has(lvalId)) { return; } const isNamedLocal = ((_a = lvalue == null ? void 0 : lvalue.identifier.name) == null ? void 0 : _a.kind) === "named"; if (lvalue !== null && isNamedLocal && state.manualMemoState != null) { state.manualMemoState.decls.add(lvalue.identifier.declarationId); } this.recordDepsInValue(value, state); if (lvalue != null) { temporaries.set(lvalue.identifier.id, { root: { kind: "NamedLocal", value: __spreadValues({}, lvalue) }, path: [] }); } } visitScope(scopeBlock, state) { this.traverseScope(scopeBlock, state); if (state.manualMemoState != null && state.manualMemoState.depsFromSource != null) { for (const dep of scopeBlock.scope.dependencies) { validateInferredDep( dep, this.temporaries, state.manualMemoState.decls, state.manualMemoState.depsFromSource, state.errors, state.manualMemoState.loc ); } } this.scopes.add(scopeBlock.scope.id); for (const id of scopeBlock.scope.merged) { this.scopes.add(id); } } visitPrunedScope(scopeBlock, state) { this.traversePrunedScope(scopeBlock, state); this.prunedScopes.add(scopeBlock.scope.id); } visitInstruction(instruction, state) { var _a, _b, _c; this.recordTemporaries(instruction, state); const value = instruction.value; if (value.kind === "StoreLocal" && value.lvalue.kind === "Reassign" && state.manualMemoState != null) { const ids = getOrInsertDefault( state.manualMemoState.reassignments, value.lvalue.place.identifier.declarationId, /* @__PURE__ */ new Set() ); ids.add(value.value.identifier); } if (value.kind === "LoadLocal" && value.place.identifier.scope != null && instruction.lvalue != null && instruction.lvalue.identifier.scope == null && state.manualMemoState != null) { const ids = getOrInsertDefault( state.manualMemoState.reassignments, instruction.lvalue.identifier.declarationId, /* @__PURE__ */ new Set() ); ids.add(value.place.identifier); } if (value.kind === "StartMemoize") { let depsFromSource = null; if (value.deps != null) { depsFromSource = value.deps; } CompilerError.invariant(state.manualMemoState == null, { reason: "Unexpected nested StartMemoize instructions", description: `Bad manual memoization ids: ${(_a = state.manualMemoState) == null ? void 0 : _a.manualMemoId}, ${value.manualMemoId}`, details: [ { kind: "error", loc: value.loc, message: null } ], suggestions: null }); state.manualMemoState = { loc: instruction.loc, decls: /* @__PURE__ */ new Set(), depsFromSource, manualMemoId: value.manualMemoId, reassignments: /* @__PURE__ */ new Map() }; for (const { identifier: identifier4, loc } of eachInstructionValueOperand( value )) { if (identifier4.scope != null && !this.scopes.has(identifier4.scope.id) && !this.prunedScopes.has(identifier4.scope.id)) { state.errors.pushDiagnostic( CompilerDiagnostic.create({ category: "PreserveManualMemo" /* PreserveManualMemo */, reason: "Existing memoization could not be preserved", description: [ "React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. ", "This dependency may be mutated later, which could cause the value to change unexpectedly" ].join("") }).withDetails({ kind: "error", loc, message: "This dependency may be modified later" }) ); } } } if (value.kind === "FinishMemoize") { CompilerError.invariant( state.manualMemoState != null && state.manualMemoState.manualMemoId === value.manualMemoId, { reason: "Unexpected mismatch between StartMemoize and FinishMemoize", description: `Encountered StartMemoize id=${(_b = state.manualMemoState) == null ? void 0 : _b.manualMemoId} followed by FinishMemoize id=${value.manualMemoId}`, details: [ { kind: "error", loc: value.loc, message: null } ], suggestions: null } ); const reassignments = state.manualMemoState.reassignments; state.manualMemoState = null; if (!value.pruned) { for (const { identifier: identifier4, loc } of eachInstructionValueOperand( value )) { let decls; if (identifier4.scope == null) { decls = (_c = reassignments.get(identifier4.declarationId)) != null ? _c : [identifier4]; } else { decls = [identifier4]; } for (const identifier5 of decls) { if (isUnmemoized2(identifier5, this.scopes)) { state.errors.pushDiagnostic( CompilerDiagnostic.create({ category: "PreserveManualMemo" /* PreserveManualMemo */, reason: "Existing memoization could not be preserved", description: [ "React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. This value was memoized in source but not in compilation output", DEBUG5 ? `${printIdentifier(identifier5)} was not memoized.` : "" ].join("").trim() }).withDetails({ kind: "error", loc, message: "Could not preserve existing memoization" }) ); } } } } } } }; function isUnmemoized2(operand, scopes) { return operand.scope != null && !scopes.has(operand.scope.id); } // src/Validation/ValidateUseMemo.ts function validateUseMemo(fn) { const errors = new CompilerError(); const useMemos = /* @__PURE__ */ new Set(); const react = /* @__PURE__ */ new Set(); const functions = /* @__PURE__ */ new Map(); for (const [, block] of fn.body.blocks) { for (const { lvalue, value } of block.instructions) { switch (value.kind) { case "LoadGlobal": { if (value.binding.name === "useMemo") { useMemos.add(lvalue.identifier.id); } else if (value.binding.name === "React") { react.add(lvalue.identifier.id); } break; } case "PropertyLoad": { if (react.has(value.object.identifier.id)) { if (value.property === "useMemo") { useMemos.add(lvalue.identifier.id); } } break; } case "FunctionExpression": { functions.set(lvalue.identifier.id, value); break; } case "MethodCall": case "CallExpression": { const callee = value.kind === "CallExpression" ? value.callee.identifier.id : value.property.identifier.id; const isUseMemo = useMemos.has(callee); if (!isUseMemo || value.args.length === 0) { continue; } const [arg] = value.args; if (arg.kind !== "Identifier") { continue; } const body = functions.get(arg.identifier.id); if (body === void 0) { continue; } if (body.loweredFunc.func.params.length > 0) { const firstParam = body.loweredFunc.func.params[0]; const loc = firstParam.kind === "Identifier" ? firstParam.loc : firstParam.place.loc; errors.pushDiagnostic( CompilerDiagnostic.create({ category: "UseMemo" /* UseMemo */, reason: "useMemo() callbacks may not accept parameters", description: "useMemo() callbacks are called by React to cache calculations across re-renders. They should not take parameters. Instead, directly reference the props, state, or local variables needed for the computation", suggestions: null }).withDetails({ kind: "error", loc, message: "Callbacks with parameters are not supported" }) ); } if (body.loweredFunc.func.async || body.loweredFunc.func.generator) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "UseMemo" /* UseMemo */, reason: "useMemo() callbacks may not be async or generator functions", description: "useMemo() callbacks are called once and must synchronously return a value", suggestions: null }).withDetails({ kind: "error", loc: body.loc, message: "Async and generator functions are not supported" }) ); } break; } } } } return errors.asResult(); } // src/Validation/ValidateLocalsNotReassignedAfterRender.ts function validateLocalsNotReassignedAfterRender(fn) { const contextVariables = /* @__PURE__ */ new Set(); const reassignment = getContextReassignment( fn, contextVariables, false, false ); if (reassignment !== null) { const errors = new CompilerError(); const variable = reassignment.identifier.name != null && reassignment.identifier.name.kind === "named" ? `\`${reassignment.identifier.name.value}\`` : "variable"; errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Immutability" /* Immutability */, reason: "Cannot reassign variable after render completes", description: `Reassigning ${variable} after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead` }).withDetails({ kind: "error", loc: reassignment.loc, message: `Cannot reassign ${variable} after render completes` }) ); throw errors; } } function getContextReassignment(fn, contextVariables, isFunctionExpression, isAsync) { const reassigningFunctions = /* @__PURE__ */ new Map(); for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { const { lvalue, value } = instr; switch (value.kind) { case "FunctionExpression": case "ObjectMethod": { let reassignment = getContextReassignment( value.loweredFunc.func, contextVariables, true, isAsync || value.loweredFunc.func.async ); if (reassignment === null) { for (const operand of eachInstructionValueOperand(value)) { const reassignmentFromOperand = reassigningFunctions.get( operand.identifier.id ); if (reassignmentFromOperand !== void 0) { reassignment = reassignmentFromOperand; break; } } } if (reassignment !== null) { if (isAsync || value.loweredFunc.func.async) { const errors = new CompilerError(); const variable = reassignment.identifier.name !== null && reassignment.identifier.name.kind === "named" ? `\`${reassignment.identifier.name.value}\`` : "variable"; errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Immutability" /* Immutability */, reason: "Cannot reassign variable in async function", description: "Reassigning a variable in an async function can cause inconsistent behavior on subsequent renders. Consider using state instead" }).withDetails({ kind: "error", loc: reassignment.loc, message: `Cannot reassign ${variable}` }) ); throw errors; } reassigningFunctions.set(lvalue.identifier.id, reassignment); } break; } case "StoreLocal": { const reassignment = reassigningFunctions.get( value.value.identifier.id ); if (reassignment !== void 0) { reassigningFunctions.set( value.lvalue.place.identifier.id, reassignment ); reassigningFunctions.set(lvalue.identifier.id, reassignment); } break; } case "LoadLocal": { const reassignment = reassigningFunctions.get( value.place.identifier.id ); if (reassignment !== void 0) { reassigningFunctions.set(lvalue.identifier.id, reassignment); } break; } case "DeclareContext": { if (!isFunctionExpression) { contextVariables.add(value.lvalue.place.identifier.id); } break; } case "StoreContext": { if (isFunctionExpression) { if (contextVariables.has(value.lvalue.place.identifier.id)) { return value.lvalue.place; } } else { contextVariables.add(value.lvalue.place.identifier.id); } const reassignment = reassigningFunctions.get( value.value.identifier.id ); if (reassignment !== void 0) { reassigningFunctions.set( value.lvalue.place.identifier.id, reassignment ); reassigningFunctions.set(lvalue.identifier.id, reassignment); } break; } default: { let operands = eachInstructionValueOperand(value); if (value.kind === "CallExpression") { const signature = getFunctionCallSignature( fn.env, value.callee.identifier.type ); if (signature == null ? void 0 : signature.noAlias) { operands = [value.callee]; } } else if (value.kind === "MethodCall") { const signature = getFunctionCallSignature( fn.env, value.property.identifier.type ); if (signature == null ? void 0 : signature.noAlias) { operands = [value.receiver, value.property]; } } else if (value.kind === "TaggedTemplateExpression") { const signature = getFunctionCallSignature( fn.env, value.tag.identifier.type ); if (signature == null ? void 0 : signature.noAlias) { operands = [value.tag]; } } for (const operand of operands) { CompilerError.invariant(operand.effect !== "" /* Unknown */, { reason: `Expected effects to be inferred prior to ValidateLocalsNotReassignedAfterRender`, description: null, details: [ { kind: "error", loc: operand.loc, message: "" } ] }); const reassignment = reassigningFunctions.get( operand.identifier.id ); if (reassignment !== void 0) { if (operand.effect === "freeze" /* Freeze */) { return reassignment; } else { for (const lval of eachInstructionLValue(instr)) { reassigningFunctions.set(lval.identifier.id, reassignment); } } } } break; } } } for (const operand of eachTerminalOperand(block.terminal)) { const reassignment = reassigningFunctions.get(operand.identifier.id); if (reassignment !== void 0) { return reassignment; } } } return null; } // src/Optimization/OutlineFunctions.ts function outlineFunctions(fn, fbtOperands) { var _a; for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { const { value, lvalue } = instr; if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") { outlineFunctions(value.loweredFunc.func, fbtOperands); } if (value.kind === "FunctionExpression" && value.loweredFunc.func.context.length === 0 && // TODO: handle outlining named functions value.loweredFunc.func.id === null && !fbtOperands.has(lvalue.identifier.id)) { const loweredFunc = value.loweredFunc.func; const id = fn.env.generateGloballyUniqueIdentifierName( (_a = loweredFunc.id) != null ? _a : loweredFunc.nameHint ); loweredFunc.id = id.value; fn.env.outlineFunction(loweredFunc, null); instr.value = { kind: "LoadGlobal", binding: { kind: "Global", name: id.value }, loc: value.loc }; } } } } // src/Optimization/LowerContextAccess.ts function lowerContextAccess(fn, loweredContextCalleeConfig) { const contextAccess = /* @__PURE__ */ new Map(); const contextKeys = /* @__PURE__ */ new Map(); for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { const { value, lvalue } = instr; if (value.kind === "CallExpression" && isUseContextHookType(value.callee.identifier)) { contextAccess.set(lvalue.identifier.id, value); continue; } if (value.kind !== "Destructure") { continue; } const destructureId = value.value.identifier.id; if (!contextAccess.has(destructureId)) { continue; } const keys = getContextKeys(value); if (keys === null) { return; } if (contextKeys.has(destructureId)) { return; } else { contextKeys.set(destructureId, keys); } } } let importLoweredContextCallee = null; if (contextAccess.size > 0 && contextKeys.size > 0) { for (const [, block] of fn.body.blocks) { let nextInstructions = null; for (let i = 0; i < block.instructions.length; i++) { const instr = block.instructions[i]; const { lvalue, value } = instr; if (value.kind === "CallExpression" && isUseContextHookType(value.callee.identifier) && contextKeys.has(lvalue.identifier.id)) { importLoweredContextCallee != null ? importLoweredContextCallee : importLoweredContextCallee = fn.env.programContext.addImportSpecifier( loweredContextCalleeConfig ); const loweredContextCalleeInstr = emitLoadLoweredContextCallee( fn.env, importLoweredContextCallee ); if (nextInstructions === null) { nextInstructions = block.instructions.slice(0, i); } nextInstructions.push(loweredContextCalleeInstr); const keys = contextKeys.get(lvalue.identifier.id); const selectorFnInstr = emitSelectorFn(fn.env, keys); nextInstructions.push(selectorFnInstr); const lowerContextCallId = loweredContextCalleeInstr.lvalue; value.callee = lowerContextCallId; const selectorFn = selectorFnInstr.lvalue; value.args.push(selectorFn); } if (nextInstructions) { nextInstructions.push(instr); } } if (nextInstructions) { block.instructions = nextInstructions; } } markInstructionIds(fn.body); inferTypes(fn); } } function emitLoadLoweredContextCallee(env, importedLowerContextCallee) { const loadGlobal = { kind: "LoadGlobal", binding: __spreadValues({}, importedLowerContextCallee), loc: GeneratedSource }; return { id: makeInstructionId(0), loc: GeneratedSource, lvalue: createTemporaryPlace(env, GeneratedSource), effects: null, value: loadGlobal }; } function getContextKeys(value) { const keys = []; const pattern = value.lvalue.pattern; switch (pattern.kind) { case "ArrayPattern": { return null; } case "ObjectPattern": { for (const place of pattern.properties) { if (place.kind !== "ObjectProperty" || place.type !== "property" || place.key.kind !== "identifier" || place.place.identifier.name === null || place.place.identifier.name.kind !== "named") { return null; } keys.push(place.key.name); } return keys; } } } function emitPropertyLoad(env, obj, property) { const loadObj = { kind: "LoadLocal", place: obj, loc: GeneratedSource }; const object2 = createTemporaryPlace(env, GeneratedSource); const loadLocalInstr = { lvalue: object2, value: loadObj, id: makeInstructionId(0), effects: null, loc: GeneratedSource }; const loadProp = { kind: "PropertyLoad", object: object2, property: makePropertyLiteral(property), loc: GeneratedSource }; const element = createTemporaryPlace(env, GeneratedSource); const loadPropInstr = { lvalue: element, value: loadProp, id: makeInstructionId(0), effects: null, loc: GeneratedSource }; return { instructions: [loadLocalInstr, loadPropInstr], element }; } function emitSelectorFn(env, keys) { const obj = createTemporaryPlace(env, GeneratedSource); promoteTemporary(obj.identifier); const instr = []; const elements = []; for (const key2 of keys) { const { instructions, element: prop } = emitPropertyLoad(env, obj, key2); instr.push(...instructions); elements.push(prop); } const arrayInstr = emitArrayInstr(elements, env); instr.push(arrayInstr); const block = { kind: "block", id: makeBlockId(0), instructions: instr, terminal: { id: makeInstructionId(0), kind: "return", returnVariant: "Explicit", loc: GeneratedSource, value: arrayInstr.lvalue, effects: null }, preds: /* @__PURE__ */ new Set(), phis: /* @__PURE__ */ new Set() }; const fn = { loc: GeneratedSource, id: null, nameHint: null, fnType: "Other", env, params: [obj], returnTypeAnnotation: null, returns: createTemporaryPlace(env, GeneratedSource), context: [], body: { entry: block.id, blocks: /* @__PURE__ */ new Map([[block.id, block]]) }, generator: false, async: false, directives: [], aliasingEffects: [] }; reversePostorderBlocks(fn.body); markInstructionIds(fn.body); enterSSA(fn); inferTypes(fn); const fnInstr = { id: makeInstructionId(0), value: { kind: "FunctionExpression", name: null, nameHint: null, loweredFunc: { func: fn }, type: "ArrowFunctionExpression", loc: GeneratedSource }, lvalue: createTemporaryPlace(env, GeneratedSource), effects: null, loc: GeneratedSource }; return fnInstr; } function emitArrayInstr(elements, env) { const array2 = { kind: "ArrayExpression", elements, loc: GeneratedSource }; const arrayLvalue = createTemporaryPlace(env, GeneratedSource); const arrayInstr = { id: makeInstructionId(0), value: array2, lvalue: arrayLvalue, effects: null, loc: GeneratedSource }; return arrayInstr; } // src/Validation/ValidateNoSetStateInEffects.ts function validateNoSetStateInEffects(fn, env) { const setStateFunctions = /* @__PURE__ */ new Map(); const errors = new CompilerError(); for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { switch (instr.value.kind) { case "LoadLocal": { if (setStateFunctions.has(instr.value.place.identifier.id)) { setStateFunctions.set( instr.lvalue.identifier.id, instr.value.place ); } break; } case "StoreLocal": { if (setStateFunctions.has(instr.value.value.identifier.id)) { setStateFunctions.set( instr.value.lvalue.place.identifier.id, instr.value.value ); setStateFunctions.set( instr.lvalue.identifier.id, instr.value.value ); } break; } case "FunctionExpression": { if ( // faster-path to check if the function expression references a setState [...eachInstructionValueOperand(instr.value)].some( (operand) => isSetStateType(operand.identifier) || setStateFunctions.has(operand.identifier.id) ) ) { const callee = getSetStateCall( instr.value.loweredFunc.func, setStateFunctions, env ); if (callee !== null) { setStateFunctions.set(instr.lvalue.identifier.id, callee); } } break; } case "MethodCall": case "CallExpression": { const callee = instr.value.kind === "MethodCall" ? instr.value.receiver : instr.value.callee; if (isUseEffectHookType(callee.identifier) || isUseLayoutEffectHookType(callee.identifier) || isUseInsertionEffectHookType(callee.identifier)) { const arg = instr.value.args[0]; if (arg !== void 0 && arg.kind === "Identifier") { const setState = setStateFunctions.get(arg.identifier.id); if (setState !== void 0) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "EffectSetState" /* EffectSetState */, reason: "Calling setState synchronously within an effect can trigger cascading renders", description: "Effects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect)", suggestions: null }).withDetails({ kind: "error", loc: setState.loc, message: "Avoid calling setState() directly within an effect" }) ); } } } break; } } } } return errors.asResult(); } function getSetStateCall(fn, setStateFunctions, env) { const refDerivedValues = /* @__PURE__ */ new Set(); const isDerivedFromRef = (place) => { return refDerivedValues.has(place.identifier.id) || isUseRefType(place.identifier) || isRefValueType(place.identifier); }; for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { if (env.config.enableAllowSetStateFromRefsInEffects) { const hasRefOperand = Iterable_some( eachInstructionValueOperand(instr.value), isDerivedFromRef ); if (hasRefOperand) { for (const lvalue of eachInstructionLValue(instr)) { refDerivedValues.add(lvalue.identifier.id); } } if (instr.value.kind === "PropertyLoad" && instr.value.property === "current" && (isUseRefType(instr.value.object.identifier) || isRefValueType(instr.value.object.identifier))) { refDerivedValues.add(instr.lvalue.identifier.id); } } switch (instr.value.kind) { case "LoadLocal": { if (setStateFunctions.has(instr.value.place.identifier.id)) { setStateFunctions.set( instr.lvalue.identifier.id, instr.value.place ); } break; } case "StoreLocal": { if (setStateFunctions.has(instr.value.value.identifier.id)) { setStateFunctions.set( instr.value.lvalue.place.identifier.id, instr.value.value ); setStateFunctions.set( instr.lvalue.identifier.id, instr.value.value ); } break; } case "CallExpression": { const callee = instr.value.callee; if (isSetStateType(callee.identifier) || setStateFunctions.has(callee.identifier.id)) { if (env.config.enableAllowSetStateFromRefsInEffects) { const arg = instr.value.args.at(0); if (arg !== void 0 && arg.kind === "Identifier" && refDerivedValues.has(arg.identifier.id)) { return null; } } return callee; } } } } } return null; } // src/Validation/ValidateNoJSXInTryStatement.ts function validateNoJSXInTryStatement(fn) { const activeTryBlocks = []; const errors = new CompilerError(); for (const [, block] of fn.body.blocks) { retainWhere(activeTryBlocks, (id) => id !== block.id); if (activeTryBlocks.length !== 0) { for (const instr of block.instructions) { const { value } = instr; switch (value.kind) { case "JsxExpression": case "JsxFragment": { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "ErrorBoundaries" /* ErrorBoundaries */, reason: "Avoid constructing JSX within try/catch", description: `React does not immediately render components when JSX is rendered, so any errors from this component will not be caught by the try/catch. To catch errors in rendering a given component, wrap that component in an error boundary. (https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)` }).withDetails({ kind: "error", loc: value.loc, message: "Avoid constructing JSX within try/catch" }) ); break; } } } } if (block.terminal.kind === "try") { activeTryBlocks.push(block.terminal.handler); } } return errors.asResult(); } // src/Optimization/OutlineJsx.ts var import_invariant3 = __toESM(require_invariant()); function outlineJSX(fn) { const outlinedFns = []; outlineJsxImpl(fn, outlinedFns); for (const outlinedFn of outlinedFns) { fn.env.outlineFunction(outlinedFn, "Component"); } } function outlineJsxImpl(fn, outlinedFns) { const globals = /* @__PURE__ */ new Map(); function processAndOutlineJSX(state, rewriteInstr) { if (state.jsx.length <= 1) { return; } const result = process2( fn, [...state.jsx].sort((a, b) => a.id - b.id), globals ); if (result) { outlinedFns.push(result.fn); rewriteInstr.set(state.jsx.at(0).id, result.instrs); } } for (const [, block] of fn.body.blocks) { const rewriteInstr = /* @__PURE__ */ new Map(); let state = { jsx: [], children: /* @__PURE__ */ new Set() }; for (let i = block.instructions.length - 1; i >= 0; i--) { const instr = block.instructions[i]; const { value, lvalue } = instr; switch (value.kind) { case "LoadGlobal": { globals.set(lvalue.identifier.id, instr); break; } case "FunctionExpression": { outlineJsxImpl(value.loweredFunc.func, outlinedFns); break; } case "JsxExpression": { if (!state.children.has(lvalue.identifier.id)) { processAndOutlineJSX(state, rewriteInstr); state = { jsx: [], children: /* @__PURE__ */ new Set() }; } state.jsx.push(instr); if (value.children) { for (const child of value.children) { state.children.add(child.identifier.id); } } break; } case "ArrayExpression": case "Await": case "BinaryExpression": case "CallExpression": case "ComputedDelete": case "ComputedLoad": case "ComputedStore": case "Debugger": case "DeclareContext": case "DeclareLocal": case "Destructure": case "FinishMemoize": case "GetIterator": case "IteratorNext": case "JSXText": case "JsxFragment": case "LoadContext": case "LoadLocal": case "MetaProperty": case "MethodCall": case "NewExpression": case "NextPropertyOf": case "ObjectExpression": case "ObjectMethod": case "PostfixUpdate": case "PrefixUpdate": case "Primitive": case "PropertyDelete": case "PropertyLoad": case "PropertyStore": case "RegExpLiteral": case "StartMemoize": case "StoreContext": case "StoreGlobal": case "StoreLocal": case "TaggedTemplateExpression": case "TemplateLiteral": case "TypeCastExpression": case "UnsupportedNode": case "UnaryExpression": { break; } default: { assertExhaustive(value, `Unexpected instruction: ${value}`); } } } processAndOutlineJSX(state, rewriteInstr); if (rewriteInstr.size > 0) { const newInstrs = []; for (let i = 0; i < block.instructions.length; i++) { const id = i + 1; if (rewriteInstr.has(id)) { const instrs = rewriteInstr.get(id); newInstrs.push(...instrs); } else { newInstrs.push(block.instructions[i]); } } block.instructions = newInstrs; } deadCodeElimination(fn); } } function process2(fn, jsx, globals) { if (fn.fnType === "Component") { return null; } const props = collectProps(fn.env, jsx); if (!props) return null; const outlinedTag = fn.env.generateGloballyUniqueIdentifierName(null).value; const newInstrs = emitOutlinedJsx(fn.env, jsx, props, outlinedTag); if (!newInstrs) return null; const outlinedFn = emitOutlinedFn(fn.env, jsx, props, globals); if (!outlinedFn) return null; outlinedFn.id = outlinedTag; return { instrs: newInstrs, fn: outlinedFn }; } function collectProps(env, instructions) { let id = 1; function generateName(oldName) { let newName = oldName; while (seen.has(newName)) { newName = `${oldName}${id++}`; } seen.add(newName); env.programContext.addNewReference(newName); return newName; } const attributes = []; const jsxIds = new Set(instructions.map((i) => i.lvalue.identifier.id)); const seen = /* @__PURE__ */ new Set(); for (const instr of instructions) { const { value } = instr; for (const at of value.props) { if (at.kind === "JsxSpreadAttribute") { return null; } if (at.kind === "JsxAttribute") { const newName = generateName(at.name); attributes.push({ originalName: at.name, newName, place: at.place }); } } if (value.children) { for (const child of value.children) { if (jsxIds.has(child.identifier.id)) { continue; } promoteTemporary(child.identifier); const newName = generateName("t"); attributes.push({ originalName: child.identifier.name.value, newName, place: child }); } } } return attributes; } function emitOutlinedJsx(env, instructions, outlinedProps, outlinedTag) { const props = outlinedProps.map((p) => ({ kind: "JsxAttribute", name: p.newName, place: p.place })); const loadJsx = { id: makeInstructionId(0), loc: GeneratedSource, lvalue: createTemporaryPlace(env, GeneratedSource), value: { kind: "LoadGlobal", binding: { kind: "ModuleLocal", name: outlinedTag }, loc: GeneratedSource }, effects: null }; promoteTemporaryJsxTag(loadJsx.lvalue.identifier); const jsxExpr = { id: makeInstructionId(0), loc: GeneratedSource, lvalue: instructions.at(-1).lvalue, value: { kind: "JsxExpression", tag: __spreadValues({}, loadJsx.lvalue), props, children: null, loc: GeneratedSource, openingLoc: GeneratedSource, closingLoc: GeneratedSource }, effects: null }; return [loadJsx, jsxExpr]; } function emitOutlinedFn(env, jsx, oldProps, globals) { const instructions = []; const oldToNewProps = createOldToNewPropsMapping(env, oldProps); const propsObj = createTemporaryPlace(env, GeneratedSource); promoteTemporary(propsObj.identifier); const destructurePropsInstr = emitDestructureProps( env, propsObj, oldToNewProps ); instructions.push(destructurePropsInstr); const updatedJsxInstructions = emitUpdatedJsx(jsx, oldToNewProps); const loadGlobalInstrs = emitLoadGlobals(jsx, globals); if (!loadGlobalInstrs) { return null; } instructions.push(...loadGlobalInstrs); instructions.push(...updatedJsxInstructions); const block = { kind: "block", id: makeBlockId(0), instructions, terminal: { id: makeInstructionId(0), kind: "return", returnVariant: "Explicit", loc: GeneratedSource, value: instructions.at(-1).lvalue, effects: null }, preds: /* @__PURE__ */ new Set(), phis: /* @__PURE__ */ new Set() }; const fn = { loc: GeneratedSource, id: null, nameHint: null, fnType: "Other", env, params: [propsObj], returnTypeAnnotation: null, returns: createTemporaryPlace(env, GeneratedSource), context: [], body: { entry: block.id, blocks: /* @__PURE__ */ new Map([[block.id, block]]) }, generator: false, async: false, directives: [], aliasingEffects: [] }; return fn; } function emitLoadGlobals(jsx, globals) { const instructions = []; for (const { value } of jsx) { if (value.tag.kind === "Identifier") { const loadGlobalInstr = globals.get(value.tag.identifier.id); if (!loadGlobalInstr) { return null; } instructions.push(loadGlobalInstr); } } return instructions; } function emitUpdatedJsx(jsx, oldToNewProps) { const newInstrs = []; const jsxIds = new Set(jsx.map((i) => i.lvalue.identifier.id)); for (const instr of jsx) { const { value } = instr; const newProps = []; for (const prop of value.props) { (0, import_invariant3.default)( prop.kind === "JsxAttribute", `Expected only attributes but found ${prop.kind}` ); if (prop.name === "key") { continue; } const newProp = oldToNewProps.get(prop.place.identifier.id); (0, import_invariant3.default)( newProp !== void 0, `Expected a new property for ${printIdentifier(prop.place.identifier)}` ); newProps.push({ kind: "JsxAttribute", name: newProp.originalName, place: newProp.place }); } let newChildren = null; if (value.children) { newChildren = []; for (const child of value.children) { if (jsxIds.has(child.identifier.id)) { newChildren.push(__spreadValues({}, child)); continue; } const newChild = oldToNewProps.get(child.identifier.id); (0, import_invariant3.default)( newChild !== void 0, `Expected a new prop for ${printIdentifier(child.identifier)}` ); newChildren.push(__spreadValues({}, newChild.place)); } } newInstrs.push(__spreadProps(__spreadValues({}, instr), { value: __spreadProps(__spreadValues({}, value), { props: newProps, children: newChildren }) })); } return newInstrs; } function createOldToNewPropsMapping(env, oldProps) { const oldToNewProps = /* @__PURE__ */ new Map(); for (const oldProp of oldProps) { if (oldProp.originalName === "key") { continue; } const newProp = __spreadProps(__spreadValues({}, oldProp), { place: createTemporaryPlace(env, GeneratedSource) }); newProp.place.identifier.name = makeIdentifierName(oldProp.newName); oldToNewProps.set(oldProp.place.identifier.id, newProp); } return oldToNewProps; } function emitDestructureProps(env, propsObj, oldToNewProps) { const properties = []; for (const [_, prop] of oldToNewProps) { properties.push({ kind: "ObjectProperty", key: { kind: "string", name: prop.newName }, type: "property", place: prop.place }); } const destructurePropsInstr = { id: makeInstructionId(0), lvalue: createTemporaryPlace(env, GeneratedSource), loc: GeneratedSource, value: { kind: "Destructure", lvalue: { pattern: { kind: "ObjectPattern", properties }, kind: "Let" /* Let */ }, loc: GeneratedSource, value: propsObj }, effects: null }; return destructurePropsInstr; } // src/Optimization/OptimizePropsMethodCalls.ts function optimizePropsMethodCalls(fn) { for (const [, block] of fn.body.blocks) { for (let i = 0; i < block.instructions.length; i++) { const instr = block.instructions[i]; if (instr.value.kind === "MethodCall" && isPropsType(instr.value.receiver.identifier)) { instr.value = { kind: "CallExpression", callee: instr.value.property, args: instr.value.args, loc: instr.value.loc }; } } } } // src/Transform/TransformFire.ts var CANNOT_COMPILE_FIRE = "Cannot compile `fire`"; function transformFire(fn) { const context = new Context4(fn.env); replaceFireFunctions(fn, context); if (!context.hasErrors()) { ensureNoMoreFireUses(fn, context); } context.throwIfErrorsFound(); } function replaceFireFunctions(fn, context) { let importedUseFire = null; let hasRewrite = false; for (const [, block] of fn.body.blocks) { const rewriteInstrs = /* @__PURE__ */ new Map(); const deleteInstrs = /* @__PURE__ */ new Set(); for (const instr of block.instructions) { const { value, lvalue } = instr; if (value.kind === "CallExpression" && isUseEffectHookType(value.callee.identifier) && value.args.length > 0 && value.args[0].kind === "Identifier") { const lambda = context.getFunctionExpression( value.args[0].identifier.id ); if (lambda != null) { const capturedCallees = visitFunctionExpressionAndPropagateFireDependencies( lambda, context, true ); const newInstrs = []; for (const [ fireCalleePlace, fireCalleeInfo ] of capturedCallees.entries()) { if (!context.hasCalleeWithInsertedFire(fireCalleePlace)) { context.addCalleeWithInsertedFire(fireCalleePlace); importedUseFire != null ? importedUseFire : importedUseFire = fn.env.programContext.addImportSpecifier({ source: fn.env.programContext.reactRuntimeModule, importSpecifierName: USE_FIRE_FUNCTION_NAME }); const loadUseFireInstr = makeLoadUseFireInstruction( fn.env, importedUseFire ); const loadFireCalleeInstr = makeLoadFireCalleeInstruction( fn.env, fireCalleeInfo.capturedCalleeIdentifier ); const callUseFireInstr = makeCallUseFireInstruction( fn.env, loadUseFireInstr.lvalue, loadFireCalleeInstr.lvalue ); const storeUseFireInstr = makeStoreUseFireInstruction( fn.env, callUseFireInstr.lvalue, fireCalleeInfo.fireFunctionBinding ); newInstrs.push( loadUseFireInstr, loadFireCalleeInstr, callUseFireInstr, storeUseFireInstr ); const loadUseEffectInstrId = context.getLoadGlobalInstrId( value.callee.identifier.id ); if (loadUseEffectInstrId == null) { context.pushError({ loc: value.loc, description: null, category: "Invariant" /* Invariant */, reason: "[InsertFire] No LoadGlobal found for useEffect call", suggestions: null }); continue; } rewriteInstrs.set(loadUseEffectInstrId, newInstrs); } } ensureNoRemainingCalleeCaptures( lambda.loweredFunc.func, context, capturedCallees ); if (value.args.length > 1 && value.args[1] != null && value.args[1].kind === "Identifier") { const depArray = value.args[1]; const depArrayExpression = context.getArrayExpression( depArray.identifier.id ); if (depArrayExpression != null) { for (const dependency of depArrayExpression.elements) { if (dependency.kind === "Identifier") { const loadOfDependency = context.getLoadLocalInstr( dependency.identifier.id ); if (loadOfDependency != null) { const replacedDepArrayItem = capturedCallees.get( loadOfDependency.place.identifier.id ); if (replacedDepArrayItem != null) { loadOfDependency.place = replacedDepArrayItem.fireFunctionBinding; } } } } } else { context.pushError({ loc: value.args[1].loc, description: "You must use an array literal for an effect dependency array when that effect uses `fire()`", category: "Fire" /* Fire */, reason: CANNOT_COMPILE_FIRE, suggestions: null }); } } else if (value.args.length > 1 && value.args[1].kind === "Spread") { context.pushError({ loc: value.args[1].place.loc, description: "You must use an array literal for an effect dependency array when that effect uses `fire()`", category: "Fire" /* Fire */, reason: CANNOT_COMPILE_FIRE, suggestions: null }); } } } else if (value.kind === "CallExpression" && value.callee.identifier.type.kind === "Function" && value.callee.identifier.type.shapeId === BuiltInFireId && context.inUseEffectLambda()) { if (value.args.length === 1 && value.args[0].kind === "Identifier") { const callExpr = context.getCallExpression( value.args[0].identifier.id ); if (callExpr != null) { const calleeId = callExpr.callee.identifier.id; const loadLocal = context.getLoadLocalInstr(calleeId); if (loadLocal == null) { context.pushError({ loc: value.loc, description: null, category: "Invariant" /* Invariant */, reason: "[InsertFire] No loadLocal found for fire call argument", suggestions: null }); continue; } const fireFunctionBinding = context.getOrGenerateFireFunctionBinding( loadLocal.place, value.loc ); loadLocal.place = __spreadValues({}, fireFunctionBinding); deleteInstrs.add(instr.id); } else { context.pushError({ loc: value.loc, description: "`fire()` can only receive a function call such as `fire(fn(a,b)). Method calls and other expressions are not allowed", category: "Fire" /* Fire */, reason: CANNOT_COMPILE_FIRE, suggestions: null }); } } else { let description = "fire() can only take in a single call expression as an argument"; if (value.args.length === 0) { description += " but received none"; } else if (value.args.length > 1) { description += " but received multiple arguments"; } else if (value.args[0].kind === "Spread") { description += " but received a spread argument"; } context.pushError({ loc: value.loc, description, category: "Fire" /* Fire */, reason: CANNOT_COMPILE_FIRE, suggestions: null }); } } else if (value.kind === "CallExpression") { context.addCallExpression(lvalue.identifier.id, value); } else if (value.kind === "FunctionExpression" && context.inUseEffectLambda()) { visitFunctionExpressionAndPropagateFireDependencies( value, context, false ); } else if (value.kind === "FunctionExpression") { context.addFunctionExpression(lvalue.identifier.id, value); } else if (value.kind === "LoadLocal") { context.addLoadLocalInstr(lvalue.identifier.id, value); } else if (value.kind === "LoadGlobal" && value.binding.kind === "ImportSpecifier" && value.binding.module === "react" && value.binding.imported === "fire" && context.inUseEffectLambda()) { deleteInstrs.add(instr.id); } else if (value.kind === "LoadGlobal") { context.addLoadGlobalInstrId(lvalue.identifier.id, instr.id); } else if (value.kind === "ArrayExpression") { context.addArrayExpression(lvalue.identifier.id, value); } } block.instructions = rewriteInstructions(rewriteInstrs, block.instructions); block.instructions = deleteInstructions(deleteInstrs, block.instructions); if (rewriteInstrs.size > 0 || deleteInstrs.size > 0) { hasRewrite = true; fn.env.hasFireRewrite = true; } } if (hasRewrite) { markInstructionIds(fn.body); } } function visitFunctionExpressionAndPropagateFireDependencies(fnExpr, context, enteringUseEffect) { let withScope = enteringUseEffect ? context.withUseEffectLambdaScope.bind(context) : context.withFunctionScope.bind(context); const calleesCapturedByFnExpression = withScope( () => replaceFireFunctions(fnExpr.loweredFunc.func, context) ); for (let contextIdx = 0; contextIdx < fnExpr.loweredFunc.func.context.length; contextIdx++) { const contextItem = fnExpr.loweredFunc.func.context[contextIdx]; const replacedCallee = calleesCapturedByFnExpression.get( contextItem.identifier.id ); if (replacedCallee != null) { fnExpr.loweredFunc.func.context[contextIdx] = __spreadValues({}, replacedCallee.fireFunctionBinding); } } context.mergeCalleesFromInnerScope(calleesCapturedByFnExpression); return calleesCapturedByFnExpression; } function* eachReachablePlace(fn) { for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { if (instr.value.kind === "FunctionExpression" || instr.value.kind === "ObjectMethod") { yield* __yieldStar(eachReachablePlace(instr.value.loweredFunc.func)); } else { yield* __yieldStar(eachInstructionOperand(instr)); } } } } function ensureNoRemainingCalleeCaptures(fn, context, capturedCallees) { var _a; for (const place of eachReachablePlace(fn)) { const calleeInfo = capturedCallees.get(place.identifier.id); if (calleeInfo != null) { const calleeName = ((_a = calleeInfo.capturedCalleeIdentifier.name) == null ? void 0 : _a.kind) === "named" ? calleeInfo.capturedCalleeIdentifier.name.value : ""; context.pushError({ loc: place.loc, description: `All uses of ${calleeName} must be either used with a fire() call in this effect or not used with a fire() call at all. ${calleeName} was used with fire() on line ${printSourceLocationLine(calleeInfo.fireLoc)} in this effect`, category: "Fire" /* Fire */, reason: CANNOT_COMPILE_FIRE, suggestions: null }); } } } function ensureNoMoreFireUses(fn, context) { for (const place of eachReachablePlace(fn)) { if (place.identifier.type.kind === "Function" && place.identifier.type.shapeId === BuiltInFireId) { context.pushError({ loc: place.identifier.loc, description: "Cannot use `fire` outside of a useEffect function", category: "Fire" /* Fire */, reason: CANNOT_COMPILE_FIRE, suggestions: null }); } } } function makeLoadUseFireInstruction(env, importedLoadUseFire) { const useFirePlace = createTemporaryPlace(env, GeneratedSource); useFirePlace.effect = "read" /* Read */; useFirePlace.identifier.type = DefaultNonmutatingHook; const instrValue = { kind: "LoadGlobal", binding: __spreadValues({}, importedLoadUseFire), loc: GeneratedSource }; return { id: makeInstructionId(0), value: instrValue, lvalue: __spreadValues({}, useFirePlace), loc: GeneratedSource, effects: null }; } function makeLoadFireCalleeInstruction(env, fireCalleeIdentifier) { const loadedFireCallee = createTemporaryPlace(env, GeneratedSource); const fireCallee = { kind: "Identifier", identifier: fireCalleeIdentifier, reactive: false, effect: "" /* Unknown */, loc: fireCalleeIdentifier.loc }; return { id: makeInstructionId(0), value: { kind: "LoadLocal", loc: GeneratedSource, place: __spreadValues({}, fireCallee) }, lvalue: __spreadValues({}, loadedFireCallee), loc: GeneratedSource, effects: null }; } function makeCallUseFireInstruction(env, useFirePlace, argPlace) { const useFireCallResultPlace = createTemporaryPlace(env, GeneratedSource); useFireCallResultPlace.effect = "read" /* Read */; const useFireCall = { kind: "CallExpression", callee: __spreadValues({}, useFirePlace), args: [argPlace], loc: GeneratedSource }; return { id: makeInstructionId(0), value: useFireCall, lvalue: __spreadValues({}, useFireCallResultPlace), loc: GeneratedSource, effects: null }; } function makeStoreUseFireInstruction(env, useFireCallResultPlace, fireFunctionBindingPlace) { promoteTemporary(fireFunctionBindingPlace.identifier); const fireFunctionBindingLValuePlace = createTemporaryPlace( env, GeneratedSource ); return { id: makeInstructionId(0), value: { kind: "StoreLocal", lvalue: { kind: "Const" /* Const */, place: __spreadValues({}, fireFunctionBindingPlace) }, value: __spreadValues({}, useFireCallResultPlace), type: null, loc: GeneratedSource }, lvalue: fireFunctionBindingLValuePlace, loc: GeneratedSource, effects: null }; } var _env3, _errors, _callExpressions, _functionExpressions, _loadLocals, _fireCalleesToFireFunctions, _calleesWithInsertedFire, _capturedCalleeIdentifierIds, _inUseEffectLambda, _loadGlobalInstructionIds, _arrayExpressions; var Context4 = class { constructor(env) { __privateAdd(this, _env3); __privateAdd(this, _errors, new CompilerError()); /* * Used to look up the call expression passed to a `fire(callExpr())`. Gives back * the `callExpr()`. */ __privateAdd(this, _callExpressions, /* @__PURE__ */ new Map()); /* * We keep track of function expressions so that we can traverse them when * we encounter a lambda passed to a useEffect call */ __privateAdd(this, _functionExpressions, /* @__PURE__ */ new Map()); /* * Mapping from lvalue ids to the LoadLocal for it. Allows us to replace dependency LoadLocals. */ __privateAdd(this, _loadLocals, /* @__PURE__ */ new Map()); /* * Maps all of the fire callees found in a component/hook to the generated fire function places * we create for them. Allows us to reuse already-inserted useFire results */ __privateAdd(this, _fireCalleesToFireFunctions, /* @__PURE__ */ new Map()); /* * The callees for which we have already created fire bindings. Used to skip inserting a new * useFire call for a fire callee if one has already been created. */ __privateAdd(this, _calleesWithInsertedFire, /* @__PURE__ */ new Set()); /* * A mapping from fire callees to the created fire function bindings that are reachable from this * scope. * * We additionally keep track of the captured callee identifier so that we can properly reference * it in the place where we LoadLocal the callee as an argument to useFire. */ __privateAdd(this, _capturedCalleeIdentifierIds, /* @__PURE__ */ new Map()); /* * We only transform fire calls if we're syntactically within a useEffect lambda (for now) */ __privateAdd(this, _inUseEffectLambda, false); /* * Mapping from useEffect callee identifier ids to the instruction id of the * load global instruction for the useEffect call. We use this to insert the * useFire calls before the useEffect call */ __privateAdd(this, _loadGlobalInstructionIds, /* @__PURE__ */ new Map()); /* * We keep track of array expressions so we can rewrite dependency arrays passed to useEffect * to use the fire functions */ __privateAdd(this, _arrayExpressions, /* @__PURE__ */ new Map()); __privateSet(this, _env3, env); } pushError(error45) { __privateGet(this, _errors).push(error45); } withFunctionScope(fn) { fn(); return __privateGet(this, _capturedCalleeIdentifierIds); } withUseEffectLambdaScope(fn) { const capturedCalleeIdentifierIds = __privateGet(this, _capturedCalleeIdentifierIds); const inUseEffectLambda = __privateGet(this, _inUseEffectLambda); __privateSet(this, _capturedCalleeIdentifierIds, /* @__PURE__ */ new Map()); __privateSet(this, _inUseEffectLambda, true); const resultCapturedCalleeIdentifierIds = this.withFunctionScope(fn); __privateSet(this, _capturedCalleeIdentifierIds, capturedCalleeIdentifierIds); __privateSet(this, _inUseEffectLambda, inUseEffectLambda); return resultCapturedCalleeIdentifierIds; } addCallExpression(id, callExpr) { __privateGet(this, _callExpressions).set(id, callExpr); } getCallExpression(id) { return __privateGet(this, _callExpressions).get(id); } addLoadLocalInstr(id, loadLocal) { __privateGet(this, _loadLocals).set(id, loadLocal); } getLoadLocalInstr(id) { return __privateGet(this, _loadLocals).get(id); } getOrGenerateFireFunctionBinding(callee, fireLoc) { const fireFunctionBinding = getOrInsertWith( __privateGet(this, _fireCalleesToFireFunctions), callee.identifier.id, () => createTemporaryPlace(__privateGet(this, _env3), GeneratedSource) ); fireFunctionBinding.identifier.type = { kind: "Function", shapeId: BuiltInFireFunctionId, return: { kind: "Poly" }, isConstructor: false }; __privateGet(this, _capturedCalleeIdentifierIds).set(callee.identifier.id, { fireFunctionBinding, capturedCalleeIdentifier: callee.identifier, fireLoc }); return fireFunctionBinding; } mergeCalleesFromInnerScope(innerCallees) { for (const [id, calleeInfo] of innerCallees.entries()) { __privateGet(this, _capturedCalleeIdentifierIds).set(id, calleeInfo); } } addCalleeWithInsertedFire(id) { __privateGet(this, _calleesWithInsertedFire).add(id); } hasCalleeWithInsertedFire(id) { return __privateGet(this, _calleesWithInsertedFire).has(id); } inUseEffectLambda() { return __privateGet(this, _inUseEffectLambda); } addFunctionExpression(id, fn) { __privateGet(this, _functionExpressions).set(id, fn); } getFunctionExpression(id) { return __privateGet(this, _functionExpressions).get(id); } addLoadGlobalInstrId(id, instrId) { __privateGet(this, _loadGlobalInstructionIds).set(id, instrId); } getLoadGlobalInstrId(id) { return __privateGet(this, _loadGlobalInstructionIds).get(id); } addArrayExpression(id, array2) { __privateGet(this, _arrayExpressions).set(id, array2); } getArrayExpression(id) { return __privateGet(this, _arrayExpressions).get(id); } hasErrors() { return __privateGet(this, _errors).hasAnyErrors(); } throwIfErrorsFound() { if (this.hasErrors()) throw __privateGet(this, _errors); } }; _env3 = new WeakMap(); _errors = new WeakMap(); _callExpressions = new WeakMap(); _functionExpressions = new WeakMap(); _loadLocals = new WeakMap(); _fireCalleesToFireFunctions = new WeakMap(); _calleesWithInsertedFire = new WeakMap(); _capturedCalleeIdentifierIds = new WeakMap(); _inUseEffectLambda = new WeakMap(); _loadGlobalInstructionIds = new WeakMap(); _arrayExpressions = new WeakMap(); function deleteInstructions(deleteInstrs, instructions) { if (deleteInstrs.size > 0) { const newInstrs = instructions.filter((instr) => !deleteInstrs.has(instr.id)); return newInstrs; } return instructions; } function rewriteInstructions(rewriteInstrs, instructions) { if (rewriteInstrs.size > 0) { const newInstrs = []; for (const instr of instructions) { const newInstrsAtId = rewriteInstrs.get(instr.id); if (newInstrsAtId != null) { newInstrs.push(...newInstrsAtId, instr); } else { newInstrs.push(instr); } } return newInstrs; } return instructions; } // src/Validation/ValidateNoImpureFunctionsInRender.ts function validateNoImpureFunctionsInRender(fn) { const errors = new CompilerError(); for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { const value = instr.value; if (value.kind === "MethodCall" || value.kind == "CallExpression") { const callee = value.kind === "MethodCall" ? value.property : value.callee; const signature = getFunctionCallSignature( fn.env, callee.identifier.type ); if (signature != null && signature.impure === true) { errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Purity" /* Purity */, reason: "Cannot call impure function during render", description: (signature.canonicalName != null ? `\`${signature.canonicalName}\` is an impure function. ` : "") + "Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent)", suggestions: null }).withDetails({ kind: "error", loc: callee.loc, message: "Cannot call impure function" }) ); } } } } return errors.asResult(); } // src/Validation/ValidateStaticComponents.ts function validateStaticComponents(fn) { const error45 = new CompilerError(); const knownDynamicComponents = /* @__PURE__ */ new Map(); for (const block of fn.body.blocks.values()) { phis: for (const phi of block.phis) { for (const operand of phi.operands.values()) { const loc = knownDynamicComponents.get(operand.identifier.id); if (loc != null) { knownDynamicComponents.set(phi.place.identifier.id, loc); continue phis; } } } for (const instr of block.instructions) { const { lvalue, value } = instr; switch (value.kind) { case "FunctionExpression": case "NewExpression": case "MethodCall": case "CallExpression": { knownDynamicComponents.set(lvalue.identifier.id, value.loc); break; } case "LoadLocal": { const loc = knownDynamicComponents.get(value.place.identifier.id); if (loc != null) { knownDynamicComponents.set(lvalue.identifier.id, loc); } break; } case "StoreLocal": { const loc = knownDynamicComponents.get(value.value.identifier.id); if (loc != null) { knownDynamicComponents.set(lvalue.identifier.id, loc); knownDynamicComponents.set(value.lvalue.place.identifier.id, loc); } break; } case "JsxExpression": { if (value.tag.kind === "Identifier") { const location = knownDynamicComponents.get( value.tag.identifier.id ); if (location != null) { error45.pushDiagnostic( CompilerDiagnostic.create({ category: "StaticComponents" /* StaticComponents */, reason: "Cannot create components during render", description: `Components created during render will reset their state each time they are created. Declare components outside of render` }).withDetails({ kind: "error", loc: value.tag.loc, message: "This component is created during render" }).withDetails({ kind: "error", loc: location, message: "The component is created during render here" }) ); } } } } } } return error45.asResult(); } // src/Validation/ValidateNoFreezingKnownMutableFunctions.ts function validateNoFreezingKnownMutableFunctions(fn) { const errors = new CompilerError(); const contextMutationEffects = /* @__PURE__ */ new Map(); function visitOperand(operand) { if (operand.effect === "freeze" /* Freeze */) { const effect = contextMutationEffects.get(operand.identifier.id); if (effect != null) { const place = effect.value; const variable = place != null && place.identifier.name != null && place.identifier.name.kind === "named" ? `\`${place.identifier.name.value}\`` : "a local variable"; errors.pushDiagnostic( CompilerDiagnostic.create({ category: "Immutability" /* Immutability */, reason: "Cannot modify local variables after render completes", description: `This argument is a function which may reassign or mutate ${variable} after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead` }).withDetails({ kind: "error", loc: operand.loc, message: `This function may (indirectly) reassign or modify ${variable} after render` }).withDetails({ kind: "error", loc: effect.value.loc, message: `This modifies ${variable}` }) ); } } } for (const block of fn.body.blocks.values()) { for (const instr of block.instructions) { const { lvalue, value } = instr; switch (value.kind) { case "LoadLocal": { const effect = contextMutationEffects.get(value.place.identifier.id); if (effect != null) { contextMutationEffects.set(lvalue.identifier.id, effect); } break; } case "StoreLocal": { const effect = contextMutationEffects.get(value.value.identifier.id); if (effect != null) { contextMutationEffects.set(lvalue.identifier.id, effect); contextMutationEffects.set( value.lvalue.place.identifier.id, effect ); } break; } case "FunctionExpression": { if (value.loweredFunc.func.aliasingEffects != null) { const context = new Set( value.loweredFunc.func.context.map((p) => p.identifier.id) ); effects: for (const effect of value.loweredFunc.func.aliasingEffects) { switch (effect.kind) { case "Mutate": case "MutateTransitive": { const knownMutation = contextMutationEffects.get( effect.value.identifier.id ); if (knownMutation != null) { contextMutationEffects.set( lvalue.identifier.id, knownMutation ); } else if (context.has(effect.value.identifier.id) && !isRefOrRefLikeMutableType(effect.value.identifier.type)) { contextMutationEffects.set(lvalue.identifier.id, effect); break effects; } break; } case "MutateConditionally": case "MutateTransitiveConditionally": { const knownMutation = contextMutationEffects.get( effect.value.identifier.id ); if (knownMutation != null) { contextMutationEffects.set( lvalue.identifier.id, knownMutation ); } break; } } } } break; } default: { for (const operand of eachInstructionValueOperand(value)) { visitOperand(operand); } } } } for (const operand of eachTerminalOperand(block.terminal)) { visitOperand(operand); } } return errors.asResult(); } // src/Validation/ValidateNoDerivedComputationsInEffects.ts function validateNoDerivedComputationsInEffects(fn) { const candidateDependencies = /* @__PURE__ */ new Map(); const functions = /* @__PURE__ */ new Map(); const locals = /* @__PURE__ */ new Map(); const errors = new CompilerError(); for (const block of fn.body.blocks.values()) { for (const instr of block.instructions) { const { lvalue, value } = instr; if (value.kind === "LoadLocal") { locals.set(lvalue.identifier.id, value.place.identifier.id); } else if (value.kind === "ArrayExpression") { candidateDependencies.set(lvalue.identifier.id, value); } else if (value.kind === "FunctionExpression") { functions.set(lvalue.identifier.id, value); } else if (value.kind === "CallExpression" || value.kind === "MethodCall") { const callee = value.kind === "CallExpression" ? value.callee : value.property; if (isUseEffectHookType(callee.identifier) && value.args.length === 2 && value.args[0].kind === "Identifier" && value.args[1].kind === "Identifier") { const effectFunction = functions.get(value.args[0].identifier.id); const deps = candidateDependencies.get(value.args[1].identifier.id); if (effectFunction != null && deps != null && deps.elements.length !== 0 && deps.elements.every((element) => element.kind === "Identifier")) { const dependencies = deps.elements.map((dep) => { var _a; CompilerError.invariant(dep.kind === "Identifier", { reason: `Dependency is checked as a place above`, description: null, details: [ { kind: "error", loc: value.loc, message: "this is checked as a place above" } ] }); return (_a = locals.get(dep.identifier.id)) != null ? _a : dep.identifier.id; }); validateEffect( effectFunction.loweredFunc.func, dependencies, errors ); } } } } } if (errors.hasAnyErrors()) { throw errors; } } function validateEffect(effectFunction, effectDeps, errors) { for (const operand of effectFunction.context) { if (isSetStateType(operand.identifier)) { continue; } else if (effectDeps.find((dep) => dep === operand.identifier.id) != null) { continue; } else { return; } } for (const dep of effectDeps) { if (effectFunction.context.find((operand) => operand.identifier.id === dep) == null) { return; } } const seenBlocks = /* @__PURE__ */ new Set(); const values = /* @__PURE__ */ new Map(); for (const dep of effectDeps) { values.set(dep, [dep]); } const setStateLocations = []; for (const block of effectFunction.body.blocks.values()) { for (const pred of block.preds) { if (!seenBlocks.has(pred)) { return; } } for (const phi of block.phis) { const aggregateDeps = /* @__PURE__ */ new Set(); for (const operand of phi.operands.values()) { const deps = values.get(operand.identifier.id); if (deps != null) { for (const dep of deps) { aggregateDeps.add(dep); } } } if (aggregateDeps.size !== 0) { values.set(phi.place.identifier.id, Array.from(aggregateDeps)); } } for (const instr of block.instructions) { switch (instr.value.kind) { case "Primitive": case "JSXText": case "LoadGlobal": { break; } case "LoadLocal": { const deps = values.get(instr.value.place.identifier.id); if (deps != null) { values.set(instr.lvalue.identifier.id, deps); } break; } case "ComputedLoad": case "PropertyLoad": case "BinaryExpression": case "TemplateLiteral": case "CallExpression": case "MethodCall": { const aggregateDeps = /* @__PURE__ */ new Set(); for (const operand of eachInstructionValueOperand(instr.value)) { const deps = values.get(operand.identifier.id); if (deps != null) { for (const dep of deps) { aggregateDeps.add(dep); } } } if (aggregateDeps.size !== 0) { values.set(instr.lvalue.identifier.id, Array.from(aggregateDeps)); } if (instr.value.kind === "CallExpression" && isSetStateType(instr.value.callee.identifier) && instr.value.args.length === 1 && instr.value.args[0].kind === "Identifier") { const deps = values.get(instr.value.args[0].identifier.id); if (deps != null && new Set(deps).size === effectDeps.length) { setStateLocations.push(instr.value.callee.loc); } else { return; } } break; } default: { return; } } } for (const operand of eachTerminalOperand(block.terminal)) { if (values.has(operand.identifier.id)) { return; } } seenBlocks.add(block.id); } for (const loc of setStateLocations) { errors.push({ category: "EffectDerivationsOfState" /* EffectDerivationsOfState */, reason: "Values derived from props and state should be calculated during render, not in an effect. (https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state)", description: null, loc, suggestions: null }); } } // src/Transform/NameAnonymousFunctions.ts function nameAnonymousFunctions(fn) { if (fn.id == null) { return; } const parentName = fn.id; const functions = nameAnonymousFunctionsImpl(fn); function visit4(node, prefix) { var _a, _b; if (node.generatedName != null && node.fn.nameHint == null) { const name = `${prefix}${node.generatedName}]`; node.fn.nameHint = name; node.fn.loweredFunc.func.nameHint = name; } const nextPrefix = `${prefix}${(_b = (_a = node.generatedName) != null ? _a : node.fn.name) != null ? _b : ""} > `; for (const inner of node.inner) { visit4(inner, nextPrefix); } } for (const node of functions) { visit4(node, `${parentName}[`); } } function nameAnonymousFunctionsImpl(fn) { var _a, _b; const functions = /* @__PURE__ */ new Map(); const names = /* @__PURE__ */ new Map(); const nodes = []; for (const block of fn.body.blocks.values()) { for (const instr of block.instructions) { const { lvalue, value } = instr; switch (value.kind) { case "LoadGlobal": { names.set(lvalue.identifier.id, value.binding.name); break; } case "LoadContext": case "LoadLocal": { const name = value.place.identifier.name; if (name != null && name.kind === "named") { names.set(lvalue.identifier.id, name.value); } const func = functions.get(value.place.identifier.id); if (func != null) { functions.set(lvalue.identifier.id, func); } break; } case "PropertyLoad": { const objectName = names.get(value.object.identifier.id); if (objectName != null) { names.set( lvalue.identifier.id, `${objectName}.${String(value.property)}` ); } break; } case "FunctionExpression": { const inner = nameAnonymousFunctionsImpl(value.loweredFunc.func); const node = { fn: value, generatedName: null, inner }; nodes.push(node); if (value.name == null) { functions.set(lvalue.identifier.id, node); } break; } case "StoreContext": case "StoreLocal": { const node = functions.get(value.value.identifier.id); const variableName = value.lvalue.place.identifier.name; if (node != null && node.generatedName == null && variableName != null && variableName.kind === "named") { node.generatedName = variableName.value; functions.delete(value.value.identifier.id); } break; } case "CallExpression": case "MethodCall": { const callee = value.kind === "MethodCall" ? value.property : value.callee; const hookKind = getHookKind(fn.env, callee.identifier); let calleeName = null; if (hookKind != null && hookKind !== "Custom") { calleeName = hookKind; } else { calleeName = (_a = names.get(callee.identifier.id)) != null ? _a : "(anonymous)"; } let fnArgCount = 0; for (const arg of value.args) { if (arg.kind === "Identifier" && functions.has(arg.identifier.id)) { fnArgCount++; } } for (let i = 0; i < value.args.length; i++) { const arg = value.args[i]; if (arg.kind === "Spread") { continue; } const node = functions.get(arg.identifier.id); if (node != null && node.generatedName == null) { const generatedName = fnArgCount > 1 ? `${calleeName}(arg${i})` : `${calleeName}()`; node.generatedName = generatedName; functions.delete(arg.identifier.id); } } break; } case "JsxExpression": { for (const attr of value.props) { if (attr.kind === "JsxSpreadAttribute") { continue; } const node = functions.get(attr.place.identifier.id); if (node != null && node.generatedName == null) { const elementName = value.tag.kind === "BuiltinTag" ? value.tag.name : (_b = names.get(value.tag.identifier.id)) != null ? _b : null; const propName = elementName == null ? attr.name : `<${elementName}>.${attr.name}`; node.generatedName = `${propName}`; functions.delete(attr.place.identifier.id); } } break; } } } } return nodes; } // src/Entrypoint/Pipeline.ts function run(func, config2, fnType, mode, programContext, logger, filename, code) { var _a, _b; const contextIdentifiers = findContextIdentifiers(func); const env = new Environment2( func.scope, fnType, mode, config2, contextIdentifiers, func, logger, filename, code, programContext ); (_b = (_a = env.logger) == null ? void 0 : _a.debugLogIRs) == null ? void 0 : _b.call(_a, { kind: "debug", name: "EnvironmentConfig", value: (0, import_pretty_format3.default)(env.config) }); return runWithEnvironment(func, env); } function runWithEnvironment(func, env) { const log2 = (value) => { var _a, _b; (_b = (_a = env.logger) == null ? void 0 : _a.debugLogIRs) == null ? void 0 : _b.call(_a, value); }; const hir = lower(func, env).unwrap(); log2({ kind: "hir", name: "HIR", value: hir }); pruneMaybeThrows(hir); log2({ kind: "hir", name: "PruneMaybeThrows", value: hir }); validateContextVariableLValues(hir); validateUseMemo(hir).unwrap(); if (env.isInferredMemoEnabled && !env.config.enablePreserveExistingManualUseMemo && !env.config.disableMemoizationForDebugging && !env.config.enableChangeDetectionForDebugging) { dropManualMemoization(hir).unwrap(); log2({ kind: "hir", name: "DropManualMemoization", value: hir }); } inlineImmediatelyInvokedFunctionExpressions(hir); log2({ kind: "hir", name: "InlineImmediatelyInvokedFunctionExpressions", value: hir }); mergeConsecutiveBlocks(hir); log2({ kind: "hir", name: "MergeConsecutiveBlocks", value: hir }); assertConsistentIdentifiers(hir); assertTerminalSuccessorsExist(hir); enterSSA(hir); log2({ kind: "hir", name: "SSA", value: hir }); eliminateRedundantPhi(hir); log2({ kind: "hir", name: "EliminateRedundantPhi", value: hir }); assertConsistentIdentifiers(hir); constantPropagation(hir); log2({ kind: "hir", name: "ConstantPropagation", value: hir }); inferTypes(hir); log2({ kind: "hir", name: "InferTypes", value: hir }); if (env.isInferredMemoEnabled) { if (env.config.validateHooksUsage) { validateHooksUsage(hir).unwrap(); } if (env.config.validateNoCapitalizedCalls) { validateNoCapitalizedCalls(hir).unwrap(); } } if (env.config.enableFire) { transformFire(hir); log2({ kind: "hir", name: "TransformFire", value: hir }); } if (env.config.lowerContextAccess) { lowerContextAccess(hir, env.config.lowerContextAccess); } optimizePropsMethodCalls(hir); log2({ kind: "hir", name: "OptimizePropsMethodCalls", value: hir }); analyseFunctions(hir); log2({ kind: "hir", name: "AnalyseFunctions", value: hir }); const mutabilityAliasingErrors = inferMutationAliasingEffects(hir); log2({ kind: "hir", name: "InferMutationAliasingEffects", value: hir }); if (env.isInferredMemoEnabled) { if (mutabilityAliasingErrors.isErr()) { throw mutabilityAliasingErrors.unwrapErr(); } } deadCodeElimination(hir); log2({ kind: "hir", name: "DeadCodeElimination", value: hir }); if (env.config.enableInstructionReordering) { instructionReordering(hir); log2({ kind: "hir", name: "InstructionReordering", value: hir }); } pruneMaybeThrows(hir); log2({ kind: "hir", name: "PruneMaybeThrows", value: hir }); const mutabilityAliasingRangeErrors = inferMutationAliasingRanges(hir, { isFunctionExpression: false }); log2({ kind: "hir", name: "InferMutationAliasingRanges", value: hir }); if (env.isInferredMemoEnabled) { if (mutabilityAliasingRangeErrors.isErr()) { throw mutabilityAliasingRangeErrors.unwrapErr(); } validateLocalsNotReassignedAfterRender(hir); } if (env.isInferredMemoEnabled) { if (env.config.assertValidMutableRanges) { assertValidMutableRanges(hir); } if (env.config.validateRefAccessDuringRender) { validateNoRefAccessInRender(hir).unwrap(); } if (env.config.validateNoSetStateInRender) { validateNoSetStateInRender(hir).unwrap(); } if (env.config.validateNoDerivedComputationsInEffects) { validateNoDerivedComputationsInEffects(hir); } if (env.config.validateNoSetStateInEffects) { env.logErrors(validateNoSetStateInEffects(hir, env)); } if (env.config.validateNoJSXInTryStatements) { env.logErrors(validateNoJSXInTryStatement(hir)); } if (env.config.validateNoImpureFunctionsInRender) { validateNoImpureFunctionsInRender(hir).unwrap(); } validateNoFreezingKnownMutableFunctions(hir).unwrap(); } inferReactivePlaces(hir); log2({ kind: "hir", name: "InferReactivePlaces", value: hir }); rewriteInstructionKindsBasedOnReassignment(hir); log2({ kind: "hir", name: "RewriteInstructionKindsBasedOnReassignment", value: hir }); if (env.isInferredMemoEnabled) { if (env.config.validateStaticComponents) { env.logErrors(validateStaticComponents(hir)); } inferReactiveScopeVariables(hir); log2({ kind: "hir", name: "InferReactiveScopeVariables", value: hir }); } const fbtOperands = memoizeFbtAndMacroOperandsInSameScope(hir); log2({ kind: "hir", name: "MemoizeFbtAndMacroOperandsInSameScope", value: hir }); if (env.config.enableJsxOutlining) { outlineJSX(hir); } if (env.config.enableNameAnonymousFunctions) { nameAnonymousFunctions(hir); log2({ kind: "hir", name: "NameAnonymousFunctions", value: hir }); } if (env.config.enableFunctionOutlining) { outlineFunctions(hir, fbtOperands); log2({ kind: "hir", name: "OutlineFunctions", value: hir }); } alignMethodCallScopes(hir); log2({ kind: "hir", name: "AlignMethodCallScopes", value: hir }); alignObjectMethodScopes(hir); log2({ kind: "hir", name: "AlignObjectMethodScopes", value: hir }); pruneUnusedLabelsHIR(hir); log2({ kind: "hir", name: "PruneUnusedLabelsHIR", value: hir }); alignReactiveScopesToBlockScopesHIR(hir); log2({ kind: "hir", name: "AlignReactiveScopesToBlockScopesHIR", value: hir }); mergeOverlappingReactiveScopesHIR(hir); log2({ kind: "hir", name: "MergeOverlappingReactiveScopesHIR", value: hir }); assertValidBlockNesting(hir); buildReactiveScopeTerminalsHIR(hir); log2({ kind: "hir", name: "BuildReactiveScopeTerminalsHIR", value: hir }); assertValidBlockNesting(hir); flattenReactiveLoopsHIR(hir); log2({ kind: "hir", name: "FlattenReactiveLoopsHIR", value: hir }); flattenScopesWithHooksOrUseHIR(hir); log2({ kind: "hir", name: "FlattenScopesWithHooksOrUseHIR", value: hir }); assertTerminalSuccessorsExist(hir); assertTerminalPredsExist(hir); propagateScopeDependenciesHIR(hir); log2({ kind: "hir", name: "PropagateScopeDependenciesHIR", value: hir }); if (env.config.inferEffectDependencies) { inferEffectDependencies(hir); log2({ kind: "hir", name: "InferEffectDependencies", value: hir }); } if (env.config.inlineJsxTransform) { inlineJsxTransform(hir, env.config.inlineJsxTransform); log2({ kind: "hir", name: "inlineJsxTransform", value: hir }); } const reactiveFunction = buildReactiveFunction(hir); log2({ kind: "reactive", name: "BuildReactiveFunction", value: reactiveFunction }); assertWellFormedBreakTargets(reactiveFunction); pruneUnusedLabels(reactiveFunction); log2({ kind: "reactive", name: "PruneUnusedLabels", value: reactiveFunction }); assertScopeInstructionsWithinScopes(reactiveFunction); pruneNonEscapingScopes(reactiveFunction); log2({ kind: "reactive", name: "PruneNonEscapingScopes", value: reactiveFunction }); pruneNonReactiveDependencies(reactiveFunction); log2({ kind: "reactive", name: "PruneNonReactiveDependencies", value: reactiveFunction }); pruneUnusedScopes(reactiveFunction); log2({ kind: "reactive", name: "PruneUnusedScopes", value: reactiveFunction }); mergeReactiveScopesThatInvalidateTogether(reactiveFunction); log2({ kind: "reactive", name: "MergeReactiveScopesThatInvalidateTogether", value: reactiveFunction }); pruneAlwaysInvalidatingScopes(reactiveFunction); log2({ kind: "reactive", name: "PruneAlwaysInvalidatingScopes", value: reactiveFunction }); if (env.config.enableChangeDetectionForDebugging != null) { pruneInitializationDependencies(reactiveFunction); log2({ kind: "reactive", name: "PruneInitializationDependencies", value: reactiveFunction }); } propagateEarlyReturns(reactiveFunction); log2({ kind: "reactive", name: "PropagateEarlyReturns", value: reactiveFunction }); pruneUnusedLValues(reactiveFunction); log2({ kind: "reactive", name: "PruneUnusedLValues", value: reactiveFunction }); promoteUsedTemporaries(reactiveFunction); log2({ kind: "reactive", name: "PromoteUsedTemporaries", value: reactiveFunction }); extractScopeDeclarationsFromDestructuring(reactiveFunction); log2({ kind: "reactive", name: "ExtractScopeDeclarationsFromDestructuring", value: reactiveFunction }); stabilizeBlockIds(reactiveFunction); log2({ kind: "reactive", name: "StabilizeBlockIds", value: reactiveFunction }); const uniqueIdentifiers = renameVariables(reactiveFunction); log2({ kind: "reactive", name: "RenameVariables", value: reactiveFunction }); pruneHoistedContexts(reactiveFunction); log2({ kind: "reactive", name: "PruneHoistedContexts", value: reactiveFunction }); if (env.config.validateMemoizedEffectDependencies) { validateMemoizedEffectDependencies(reactiveFunction).unwrap(); } if (env.config.enablePreserveExistingMemoizationGuarantees || env.config.validatePreserveExistingMemoizationGuarantees) { validatePreservedManualMemoization(reactiveFunction).unwrap(); } const ast = codegenFunction(reactiveFunction, { uniqueIdentifiers, fbtOperands }).unwrap(); log2({ kind: "ast", name: "Codegen", value: ast }); for (const outlined of ast.outlined) { log2({ kind: "ast", name: "Codegen (outlined)", value: outlined.fn }); } if (env.config.throwUnknownException__testonly) { throw new Error("unexpected error"); } return ast; } function compileFn(func, config2, fnType, mode, programContext, logger, filename, code) { return run( func, config2, fnType, mode, programContext, logger, filename, code ); } // src/Entrypoint/Suppression.ts function filterSuppressionsThatAffectFunction(suppressionRanges, fn) { const suppressionsInScope = []; const fnNode = fn.node; for (const suppressionRange of suppressionRanges) { if (suppressionRange.disableComment.start == null || fnNode.start == null || fnNode.end == null) { continue; } if (suppressionRange.disableComment.start > fnNode.start && // If there is no matching enable, the rest of the file has potential violations (suppressionRange.enableComment === null || suppressionRange.enableComment.end != null && suppressionRange.enableComment.end < fnNode.end)) { suppressionsInScope.push(suppressionRange); } if (suppressionRange.disableComment.start < fnNode.start && // If there is no matching enable, the rest of the file has potential violations (suppressionRange.enableComment === null || suppressionRange.enableComment.end != null && suppressionRange.enableComment.end > fnNode.end)) { suppressionsInScope.push(suppressionRange); } } return suppressionsInScope; } function findProgramSuppressions(programComments, ruleNames, flowSuppressions) { const suppressionRanges = []; let disableComment = null; let enableComment = null; let source2 = null; let disableNextLinePattern = null; let disablePattern = null; let enablePattern = null; if (ruleNames.length !== 0) { const rulePattern = `(${ruleNames.join("|")})`; disableNextLinePattern = new RegExp( `eslint-disable-next-line ${rulePattern}` ); disablePattern = new RegExp(`eslint-disable ${rulePattern}`); enablePattern = new RegExp(`eslint-enable ${rulePattern}`); } const flowSuppressionPattern = new RegExp( "\\$(FlowFixMe\\w*|FlowExpectedError|FlowIssue)\\[react\\-rule" ); for (const comment of programComments) { if (comment.start == null || comment.end == null) { continue; } if ( /* * If we're already within a CommentBlock, we should not restart the range prematurely for a * CommentLine within the block. */ disableComment == null && disableNextLinePattern != null && disableNextLinePattern.test(comment.value) ) { disableComment = comment; enableComment = comment; source2 = "Eslint"; } if (flowSuppressions && disableComment == null && flowSuppressionPattern.test(comment.value)) { disableComment = comment; enableComment = comment; source2 = "Flow"; } if (disablePattern != null && disablePattern.test(comment.value)) { disableComment = comment; source2 = "Eslint"; } if (enablePattern != null && enablePattern.test(comment.value) && source2 === "Eslint") { enableComment = comment; } if (disableComment != null && source2 != null) { suppressionRanges.push({ disableComment, enableComment, source: source2 }); disableComment = null; enableComment = null; source2 = null; } } return suppressionRanges; } function suppressionsToCompilerError(suppressionRanges) { var _a; CompilerError.invariant(suppressionRanges.length !== 0, { reason: `Expected at least suppression comment source range`, description: null, details: [ { kind: "error", loc: GeneratedSource, message: null } ] }); const error45 = new CompilerError(); for (const suppressionRange of suppressionRanges) { if (suppressionRange.disableComment.start == null || suppressionRange.disableComment.end == null) { continue; } let reason, suggestion; switch (suppressionRange.source) { case "Eslint": reason = "React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled"; suggestion = "Remove the ESLint suppression and address the React error"; break; case "Flow": reason = "React Compiler has skipped optimizing this component because one or more React rule violations were reported by Flow"; suggestion = "Remove the Flow suppression and address the React error"; break; default: assertExhaustive( suppressionRange.source, "Unhandled suppression source" ); } error45.pushDiagnostic( CompilerDiagnostic.create({ reason, description: `React Compiler only works when your components follow all the rules of React, disabling them may result in unexpected or incorrect behavior. Found suppression \`${suppressionRange.disableComment.value.trim()}\``, category: "Suppression" /* Suppression */, suggestions: [ { description: suggestion, range: [ suppressionRange.disableComment.start, suppressionRange.disableComment.end ], op: 2 /* Remove */ } ] }).withDetails({ kind: "error", loc: (_a = suppressionRange.disableComment.loc) != null ? _a : null, message: "Found React rule suppression" }) ); } return error45; } // src/Entrypoint/Program.ts var OPT_IN_DIRECTIVES = /* @__PURE__ */ new Set(["use forget", "use memo"]); var OPT_OUT_DIRECTIVES = /* @__PURE__ */ new Set(["use no forget", "use no memo"]); var DYNAMIC_GATING_DIRECTIVE = new RegExp("^use memo if\\(([^\\)]*)\\)$"); function tryFindDirectiveEnablingMemoization(directives, opts) { var _a, _b; const optIn = directives.find( (directive2) => OPT_IN_DIRECTIVES.has(directive2.value.value) ); if (optIn != null) { return Ok(optIn); } const dynamicGating = findDirectivesDynamicGating(directives, opts); if (dynamicGating.isOk()) { return Ok((_b = (_a = dynamicGating.unwrap()) == null ? void 0 : _a.directive) != null ? _b : null); } else { return Err(dynamicGating.unwrapErr()); } } function findDirectiveDisablingMemoization(directives, { customOptOutDirectives }) { var _a, _b; if (customOptOutDirectives != null) { return (_a = directives.find( (directive2) => customOptOutDirectives.indexOf(directive2.value.value) !== -1 )) != null ? _a : null; } return (_b = directives.find( (directive2) => OPT_OUT_DIRECTIVES.has(directive2.value.value) )) != null ? _b : null; } function findDirectivesDynamicGating(directives, opts) { var _a, _b; if (opts.dynamicGating === null) { return Ok(null); } const errors = new CompilerError(); const result = []; for (const directive2 of directives) { const maybeMatch = DYNAMIC_GATING_DIRECTIVE.exec(directive2.value.value); if (maybeMatch != null && maybeMatch[1] != null) { if (t4.isValidIdentifier(maybeMatch[1])) { result.push({ directive: directive2, match: maybeMatch[1] }); } else { errors.push({ reason: `Dynamic gating directive is not a valid JavaScript identifier`, description: `Found '${directive2.value.value}'`, category: "Gating" /* Gating */, loc: (_a = directive2.loc) != null ? _a : null, suggestions: null }); } } } if (errors.hasAnyErrors()) { return Err(errors); } else if (result.length > 1) { const error45 = new CompilerError(); error45.push({ reason: `Multiple dynamic gating directives found`, description: `Expected a single directive but found [${result.map((r) => r.directive.value.value).join(", ")}]`, category: "Gating" /* Gating */, loc: (_b = result[0].directive.loc) != null ? _b : null, suggestions: null }); return Err(error45); } else if (result.length === 1) { return Ok({ gating: { source: opts.dynamicGating.source, importSpecifierName: result[0].match }, directive: result[0].directive }); } else { return Ok(null); } } function isError(err) { return !(err instanceof CompilerError) || err.hasErrors(); } function isConfigError(err) { if (err instanceof CompilerError) { return err.details.some((detail) => detail.category === "Config" /* Config */); } return false; } function logError(err, context, fnLoc) { var _a, _b; if (context.opts.logger) { if (err instanceof CompilerError) { for (const detail of err.details) { context.opts.logger.logEvent(context.filename, { kind: "CompileError", fnLoc, detail }); } } else { let stringifiedError; if (err instanceof Error) { stringifiedError = (_a = err.stack) != null ? _a : err.message; } else { stringifiedError = (_b = err == null ? void 0 : err.toString()) != null ? _b : "[ null ]"; } context.opts.logger.logEvent(context.filename, { kind: "PipelineError", fnLoc, data: stringifiedError }); } } } function handleError(err, context, fnLoc) { logError(err, context, fnLoc); if (context.opts.panicThreshold === "all_errors" || context.opts.panicThreshold === "critical_errors" && isError(err) || isConfigError(err)) { throw err; } } function createNewFunctionNode(originalFn, compiledFn) { var _a, _b, _c; let transformedFn; switch (originalFn.node.type) { case "FunctionDeclaration": { const fn = { type: "FunctionDeclaration", id: compiledFn.id, loc: (_a = originalFn.node.loc) != null ? _a : null, async: compiledFn.async, generator: compiledFn.generator, params: compiledFn.params, body: compiledFn.body }; transformedFn = fn; break; } case "ArrowFunctionExpression": { const fn = { type: "ArrowFunctionExpression", loc: (_b = originalFn.node.loc) != null ? _b : null, async: compiledFn.async, generator: compiledFn.generator, params: compiledFn.params, expression: originalFn.node.expression, body: compiledFn.body }; transformedFn = fn; break; } case "FunctionExpression": { const fn = { type: "FunctionExpression", id: compiledFn.id, loc: (_c = originalFn.node.loc) != null ? _c : null, async: compiledFn.async, generator: compiledFn.generator, params: compiledFn.params, body: compiledFn.body }; transformedFn = fn; break; } default: { assertExhaustive( originalFn.node, `Creating unhandled function: ${originalFn.node}` ); } } return transformedFn; } function insertNewOutlinedFunctionNode(program, originalFn, compiledFn) { var _a, _b, _c; switch (originalFn.type) { case "FunctionDeclaration": { return originalFn.insertAfter( createNewFunctionNode(originalFn, compiledFn) )[0]; } /** * We can't just append the outlined function as a sibling of the original function if it is an * (Arrow)FunctionExpression parented by a VariableDeclaration, as this would cause its parent * to become a SequenceExpression instead which breaks a bunch of assumptions elsewhere in the * plugin. * * To get around this, we always synthesize a new FunctionDeclaration for the outlined function * and insert it as a true sibling to the original function. */ case "ArrowFunctionExpression": case "FunctionExpression": { const fn = { type: "FunctionDeclaration", id: compiledFn.id, loc: (_a = originalFn.node.loc) != null ? _a : null, async: compiledFn.async, generator: compiledFn.generator, params: compiledFn.params, body: compiledFn.body }; const insertedFuncDecl = program.pushContainer("body", [fn])[0]; CompilerError.invariant(insertedFuncDecl.isFunctionDeclaration(), { reason: "Expected inserted function declaration", description: `Got: ${insertedFuncDecl}`, details: [ { kind: "error", loc: (_c = (_b = insertedFuncDecl.node) == null ? void 0 : _b.loc) != null ? _c : null, message: null } ] }); return insertedFuncDecl; } default: { assertExhaustive( originalFn, `Inserting unhandled function: ${originalFn}` ); } } } var DEFAULT_ESLINT_SUPPRESSIONS = [ "react-hooks/exhaustive-deps", "react-hooks/rules-of-hooks" ]; function isFilePartOfSources(sources, filename) { if (typeof sources === "function") { return sources(filename); } for (const prefix of sources) { if (filename.indexOf(prefix) !== -1) { return true; } } return false; } function compileProgram(program, pass) { var _a; if (shouldSkipCompilation(program, pass)) { return null; } const restrictedImportsErr = validateRestrictedImports( program, pass.opts.environment ); if (restrictedImportsErr) { handleError(restrictedImportsErr, pass, null); return null; } const suppressions = findProgramSuppressions( pass.comments, (_a = pass.opts.eslintSuppressionRules) != null ? _a : DEFAULT_ESLINT_SUPPRESSIONS, pass.opts.flowSuppressions ); const programContext = new ProgramContext({ program, opts: pass.opts, filename: pass.filename, code: pass.code, suppressions, hasModuleScopeOptOut: findDirectiveDisablingMemoization(program.node.directives, pass.opts) != null }); const queue = findFunctionsToCompile( program, pass, programContext ); const compiledFns = []; while (queue.length !== 0) { const current = queue.shift(); const compiled = processFn(current.fn, current.fnType, programContext); if (compiled != null) { for (const outlined of compiled.outlined) { CompilerError.invariant(outlined.fn.outlined.length === 0, { reason: "Unexpected nested outlined functions", description: null, details: [ { kind: "error", loc: outlined.fn.loc, message: null } ] }); const fn = insertNewOutlinedFunctionNode( program, current.fn, outlined.fn ); fn.skip(); programContext.alreadyCompiled.add(fn.node); if (outlined.type !== null) { queue.push({ kind: "outlined", fn, fnType: outlined.type }); } } compiledFns.push({ kind: current.kind, originalFn: current.fn, compiledFn: compiled }); } } if (programContext.hasModuleScopeOptOut) { if (compiledFns.length > 0) { const error45 = new CompilerError(); error45.pushErrorDetail( new CompilerErrorDetail({ reason: "Unexpected compiled functions when module scope opt-out is present", category: "Invariant" /* Invariant */, loc: null }) ); handleError(error45, programContext, null); } return null; } applyCompiledFunctions(program, compiledFns, pass, programContext); return { retryErrors: programContext.retryErrors, inferredEffectLocations: programContext.inferredEffectLocations }; } function findFunctionsToCompile(program, pass, programContext) { var _a; const queue = []; const traverseFunction2 = (fn, pass2) => { if (pass2.opts.compilationMode === "all" && fn.scope.getProgramParent() !== fn.scope.parent) { return; } const fnType = getReactFunctionType(fn, pass2); if (pass2.opts.environment.validateNoDynamicallyCreatedComponentsOrHooks) { validateNoDynamicallyCreatedComponentsOrHooks(fn, pass2, programContext); } if (fnType === null || programContext.alreadyCompiled.has(fn.node)) { return; } programContext.alreadyCompiled.add(fn.node); fn.skip(); queue.push({ kind: "original", fn, fnType }); }; program.traverse( { ClassDeclaration(node) { node.skip(); }, ClassExpression(node) { node.skip(); }, FunctionDeclaration: traverseFunction2, FunctionExpression: traverseFunction2, ArrowFunctionExpression: traverseFunction2 }, __spreadProps(__spreadValues({}, pass), { opts: __spreadValues(__spreadValues({}, pass.opts), pass.opts), filename: (_a = pass.filename) != null ? _a : null }) ); return queue; } function processFn(fn, fnType, programContext) { var _a, _b, _c, _d, _e, _f, _g, _h; let directives; if (fn.node.body.type !== "BlockStatement") { directives = { optIn: null, optOut: null }; } else { const optIn = tryFindDirectiveEnablingMemoization( fn.node.body.directives, programContext.opts ); if (optIn.isErr()) { handleError(optIn.unwrapErr(), programContext, (_a = fn.node.loc) != null ? _a : null); return null; } directives = { optIn: optIn.unwrapOr(null), optOut: findDirectiveDisablingMemoization( fn.node.body.directives, programContext.opts ) }; } let compiledFn; const compileResult = tryCompileFunction(fn, fnType, programContext); if (compileResult.kind === "error") { if (directives.optOut != null) { logError(compileResult.error, programContext, (_b = fn.node.loc) != null ? _b : null); } else { handleError(compileResult.error, programContext, (_c = fn.node.loc) != null ? _c : null); } const retryResult = retryCompileFunction(fn, fnType, programContext); if (retryResult == null) { return null; } compiledFn = retryResult; } else { compiledFn = compileResult.compiledFn; } if (programContext.opts.ignoreUseNoForget === false && directives.optOut != null) { programContext.logEvent({ kind: "CompileSkip", fnLoc: (_d = fn.node.body.loc) != null ? _d : null, reason: `Skipped due to '${directives.optOut.value}' directive.`, loc: (_e = directives.optOut.loc) != null ? _e : null }); return null; } programContext.logEvent({ kind: "CompileSuccess", fnLoc: (_f = fn.node.loc) != null ? _f : null, fnName: (_h = (_g = compiledFn.id) == null ? void 0 : _g.name) != null ? _h : null, memoSlots: compiledFn.memoSlotsUsed, memoBlocks: compiledFn.memoBlocks, memoValues: compiledFn.memoValues, prunedMemoBlocks: compiledFn.prunedMemoBlocks, prunedMemoValues: compiledFn.prunedMemoValues }); if (programContext.hasModuleScopeOptOut) { return null; } else if (programContext.opts.noEmit) { for (const loc of compiledFn.inferredEffectLocations) { if (loc !== GeneratedSource) { programContext.inferredEffectLocations.add(loc); } } return null; } else if (programContext.opts.compilationMode === "annotation" && directives.optIn == null) { return null; } else { return compiledFn; } } function tryCompileFunction(fn, fnType, programContext) { const suppressionsInFunction = filterSuppressionsThatAffectFunction( programContext.suppressions, fn ); if (suppressionsInFunction.length > 0) { return { kind: "error", error: suppressionsToCompilerError(suppressionsInFunction) }; } try { return { kind: "compile", compiledFn: compileFn( fn, programContext.opts.environment, fnType, "all_features", programContext, programContext.opts.logger, programContext.filename, programContext.code ) }; } catch (err) { return { kind: "error", error: err }; } } function retryCompileFunction(fn, fnType, programContext) { const environment = programContext.opts.environment; if (!(environment.enableFire || environment.inferEffectDependencies != null)) { return null; } try { const retryResult = compileFn( fn, environment, fnType, "no_inferred_memo", programContext, programContext.opts.logger, programContext.filename, programContext.code ); if (!retryResult.hasFireRewrite && !retryResult.hasInferredEffect) { return null; } return retryResult; } catch (err) { if (err instanceof CompilerError) { programContext.retryErrors.push({ fn, error: err }); } return null; } } function applyCompiledFunctions(program, compiledFns, pass, programContext) { var _a, _b; let referencedBeforeDeclared = null; for (const result of compiledFns) { const { kind, originalFn, compiledFn } = result; const transformedFn = createNewFunctionNode(originalFn, compiledFn); programContext.alreadyCompiled.add(transformedFn); let dynamicGating = null; if (originalFn.node.body.type === "BlockStatement") { const result2 = findDirectivesDynamicGating( originalFn.node.body.directives, pass.opts ); if (result2.isOk()) { dynamicGating = (_b = (_a = result2.unwrap()) == null ? void 0 : _a.gating) != null ? _b : null; } } const functionGating = dynamicGating != null ? dynamicGating : pass.opts.gating; if (kind === "original" && functionGating != null) { referencedBeforeDeclared != null ? referencedBeforeDeclared : referencedBeforeDeclared = getFunctionReferencedBeforeDeclarationAtTopLevel(program, compiledFns); insertGatedFunctionDeclaration( originalFn, transformedFn, programContext, functionGating, referencedBeforeDeclared.has(result) ); } else { originalFn.replaceWith(transformedFn); } } if (compiledFns.length > 0) { addImportsToProgram(program, programContext); } } function shouldSkipCompilation(program, pass) { if (pass.opts.sources) { if (pass.filename === null) { const error45 = new CompilerError(); error45.pushErrorDetail( new CompilerErrorDetail({ reason: `Expected a filename but found none.`, description: "When the 'sources' config options is specified, the React compiler will only compile files with a name", category: "Config" /* Config */, loc: null }) ); handleError(error45, pass, null); return true; } if (!isFilePartOfSources(pass.opts.sources, pass.filename)) { return true; } } if (hasMemoCacheFunctionImport( program, getReactCompilerRuntimeModule(pass.opts.target) )) { return true; } return false; } function validateNoDynamicallyCreatedComponentsOrHooks(fn, pass, programContext) { const parentNameExpr = getFunctionName2(fn); const parentName = parentNameExpr !== null && parentNameExpr.isIdentifier() ? parentNameExpr.node.name : ""; const validateNestedFunction = (nestedFn) => { var _a, _b, _c, _d; if (nestedFn.node === fn.node || programContext.alreadyCompiled.has(nestedFn.node)) { return; } if (nestedFn.scope.getProgramParent() !== nestedFn.scope.parent) { const nestedFnType = getReactFunctionType(nestedFn, pass); const nestedFnNameExpr = getFunctionName2(nestedFn); const nestedName = nestedFnNameExpr !== null && nestedFnNameExpr.isIdentifier() ? nestedFnNameExpr.node.name : ""; if (nestedFnType === "Component" || nestedFnType === "Hook") { CompilerError.throwDiagnostic({ category: "Factories" /* Factories */, reason: `Components and hooks cannot be created dynamically`, description: `The function \`${nestedName}\` appears to be a React ${nestedFnType.toLowerCase()}, but it's defined inside \`${parentName}\`. Components and Hooks should always be declared at module scope`, details: [ { kind: "error", message: "this function dynamically created a component/hook", loc: (_b = (_a = parentNameExpr == null ? void 0 : parentNameExpr.node.loc) != null ? _a : fn.node.loc) != null ? _b : null }, { kind: "error", message: "the component is created here", loc: (_d = (_c = nestedFnNameExpr == null ? void 0 : nestedFnNameExpr.node.loc) != null ? _c : nestedFn.node.loc) != null ? _d : null } ] }); } } nestedFn.skip(); }; fn.traverse({ FunctionDeclaration: validateNestedFunction, FunctionExpression: validateNestedFunction, ArrowFunctionExpression: validateNestedFunction }); } function getReactFunctionType(fn, pass) { var _a, _b; const hookPattern = pass.opts.environment.hookPattern; if (fn.node.body.type === "BlockStatement") { const optInDirectives = tryFindDirectiveEnablingMemoization( fn.node.body.directives, pass.opts ); if (optInDirectives.unwrapOr(null) != null) { return (_a = getComponentOrHookLike(fn, hookPattern)) != null ? _a : "Other"; } } let componentSyntaxType = null; if (fn.isFunctionDeclaration()) { if (isComponentDeclaration(fn.node)) { componentSyntaxType = "Component"; } else if (isHookDeclaration(fn.node)) { componentSyntaxType = "Hook"; } } switch (pass.opts.compilationMode) { case "annotation": { return null; } case "infer": { return componentSyntaxType != null ? componentSyntaxType : getComponentOrHookLike(fn, hookPattern); } case "syntax": { return componentSyntaxType; } case "all": { return (_b = getComponentOrHookLike(fn, hookPattern)) != null ? _b : "Other"; } default: { assertExhaustive( pass.opts.compilationMode, `Unexpected compilationMode \`${pass.opts.compilationMode}\`` ); } } } function hasMemoCacheFunctionImport(program, moduleName) { let hasUseMemoCache = false; program.traverse({ ImportSpecifier(path) { const imported = path.get("imported"); let importedName = null; if (imported.isIdentifier()) { importedName = imported.node.name; } else if (imported.isStringLiteral()) { importedName = imported.node.value; } if (importedName === "c" && path.parentPath.isImportDeclaration() && path.parentPath.get("source").node.value === moduleName) { hasUseMemoCache = true; } } }); return hasUseMemoCache; } function isHookName2(s, hookPattern) { if (hookPattern !== null) { return new RegExp(hookPattern).test(s); } return /^use[A-Z0-9]/.test(s); } function isHook(path, hookPattern) { if (path.isIdentifier()) { return isHookName2(path.node.name, hookPattern); } else if (path.isMemberExpression() && !path.node.computed && isHook(path.get("property"), hookPattern)) { const obj = path.get("object").node; const isPascalCaseNameSpace = /^[A-Z].*/; return obj.type === "Identifier" && isPascalCaseNameSpace.test(obj.name); } else { return false; } } function isComponentName(path) { return path.isIdentifier() && /^[A-Z]/.test(path.node.name); } function isReactAPI(path, functionName) { const node = path.node; return node.type === "Identifier" && node.name === functionName || node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && node.property.name === functionName; } function isForwardRefCallback(path) { return !!(path.parentPath.isCallExpression() && path.parentPath.get("callee").isExpression() && isReactAPI(path.parentPath.get("callee"), "forwardRef")); } function isMemoCallback(path) { return path.parentPath.isCallExpression() && path.parentPath.get("callee").isExpression() && isReactAPI(path.parentPath.get("callee"), "memo"); } function isValidPropsAnnotation(annot) { if (annot == null) { return true; } else if (annot.type === "TSTypeAnnotation") { switch (annot.typeAnnotation.type) { case "TSArrayType": case "TSBigIntKeyword": case "TSBooleanKeyword": case "TSConstructorType": case "TSFunctionType": case "TSLiteralType": case "TSNeverKeyword": case "TSNumberKeyword": case "TSStringKeyword": case "TSSymbolKeyword": case "TSTupleType": return false; } return true; } else if (annot.type === "TypeAnnotation") { switch (annot.typeAnnotation.type) { case "ArrayTypeAnnotation": case "BooleanLiteralTypeAnnotation": case "BooleanTypeAnnotation": case "EmptyTypeAnnotation": case "FunctionTypeAnnotation": case "NumberLiteralTypeAnnotation": case "NumberTypeAnnotation": case "StringLiteralTypeAnnotation": case "StringTypeAnnotation": case "SymbolTypeAnnotation": case "ThisTypeAnnotation": case "TupleTypeAnnotation": return false; } return true; } else if (annot.type === "Noop") { return true; } else { assertExhaustive(annot, `Unexpected annotation node \`${annot}\``); } } function isValidComponentParams(params) { if (params.length === 0) { return true; } else if (params.length > 0 && params.length <= 2) { if (!isValidPropsAnnotation(params[0].node.typeAnnotation)) { return false; } if (params.length === 1) { return !params[0].isRestElement(); } else if (params[1].isIdentifier()) { const { name } = params[1].node; return name.includes("ref") || name.includes("Ref"); } else { return false; } } return false; } function getComponentOrHookLike(node, hookPattern) { const functionName = getFunctionName2(node); if (functionName !== null && isComponentName(functionName)) { let isComponent = callsHooksOrCreatesJsx(node, hookPattern) && isValidComponentParams(node.get("params")) && !returnsNonNode(node); return isComponent ? "Component" : null; } else if (functionName !== null && isHook(functionName, hookPattern)) { return callsHooksOrCreatesJsx(node, hookPattern) ? "Hook" : null; } if (node.isFunctionExpression() || node.isArrowFunctionExpression()) { if (isForwardRefCallback(node) || isMemoCallback(node)) { return callsHooksOrCreatesJsx(node, hookPattern) ? "Component" : null; } } return null; } function skipNestedFunctions(node) { return (fn) => { if (fn.node !== node.node) { fn.skip(); } }; } function callsHooksOrCreatesJsx(node, hookPattern) { let invokesHooks = false; let createsJsx = false; node.traverse({ JSX() { createsJsx = true; }, CallExpression(call) { const callee = call.get("callee"); if (callee.isExpression() && isHook(callee, hookPattern)) { invokesHooks = true; } }, ArrowFunctionExpression: skipNestedFunctions(node), FunctionExpression: skipNestedFunctions(node), FunctionDeclaration: skipNestedFunctions(node) }); return invokesHooks || createsJsx; } function isNonNode(node) { if (!node) { return true; } switch (node.type) { case "ObjectExpression": case "ArrowFunctionExpression": case "FunctionExpression": case "BigIntLiteral": case "ClassExpression": case "NewExpression": return true; } return false; } function returnsNonNode(node) { let returnsNonNode2 = false; if ( // node.traverse#ArrowFunctionExpression isn't called for the root node node.type === "ArrowFunctionExpression" && node.node.body.type !== "BlockStatement" ) { returnsNonNode2 = isNonNode(node.node.body); } node.traverse({ ReturnStatement(ret) { returnsNonNode2 = isNonNode(ret.node.argument); }, // Skip traversing all nested functions and their return statements ArrowFunctionExpression: skipNestedFunctions(node), FunctionExpression: skipNestedFunctions(node), FunctionDeclaration: skipNestedFunctions(node), ObjectMethod: (node2) => node2.skip() }); return returnsNonNode2; } function getFunctionName2(path) { if (path.isFunctionDeclaration()) { const id2 = path.get("id"); if (id2.isIdentifier()) { return id2; } return null; } let id = null; const parent = path.parentPath; if (parent.isVariableDeclarator() && parent.get("init").node === path.node) { id = parent.get("id"); } else if (parent.isAssignmentExpression() && parent.get("right").node === path.node && parent.get("operator") === "=") { id = parent.get("left"); } else if (parent.isProperty() && parent.get("value").node === path.node && !parent.get("computed") && parent.get("key").isLVal()) { id = parent.get("key"); } else if (parent.isAssignmentPattern() && parent.get("right").node === path.node && !parent.get("computed")) { id = parent.get("left"); } if (id !== null && (id.isIdentifier() || id.isMemberExpression())) { return id; } else { return null; } } function getFunctionReferencedBeforeDeclarationAtTopLevel(program, fns) { const fnNames = new Map( fns.map((fn) => [ getFunctionName2(fn.originalFn), fn ]).filter( (entry) => !!entry[0] && entry[0].isIdentifier() ).map((entry) => [entry[0].node.name, { id: entry[0].node, fn: entry[1] }]) ); const referencedBeforeDeclaration = /* @__PURE__ */ new Set(); program.traverse({ TypeAnnotation(path) { path.skip(); }, TSTypeAnnotation(path) { path.skip(); }, TypeAlias(path) { path.skip(); }, TSTypeAliasDeclaration(path) { path.skip(); }, Identifier(id) { const fn = fnNames.get(id.node.name); if (!fn) { return; } if (id.node === fn.id) { fnNames.delete(id.node.name); return; } const scope = id.scope.getFunctionParent(); if (scope === null && id.isReferencedIdentifier()) { referencedBeforeDeclaration.add(fn.fn); } } }); return referencedBeforeDeclaration; } function getReactCompilerRuntimeModule(target) { if (target === "19") { return "react/compiler-runtime"; } else if (target === "17" || target === "18") { return "react-compiler-runtime"; } else { CompilerError.invariant( target != null && target.kind === "donotuse_meta_internal" && typeof target.runtimeModule === "string", { reason: "Expected target to already be validated", description: null, details: [ { kind: "error", loc: null, message: null } ], suggestions: null } ); return target.runtimeModule; } } // src/Entrypoint/Imports.ts function validateRestrictedImports(path, { validateBlocklistedImports }) { if (validateBlocklistedImports == null || validateBlocklistedImports.length === 0) { return null; } const error45 = new CompilerError(); const restrictedImports = new Set(validateBlocklistedImports); path.traverse({ ImportDeclaration(importDeclPath) { var _a; if (restrictedImports.has(importDeclPath.node.source.value)) { error45.push({ category: "Todo" /* Todo */, reason: "Bailing out due to blocklisted import", description: `Import from module ${importDeclPath.node.source.value}`, loc: (_a = importDeclPath.node.loc) != null ? _a : null }); } } }); if (error45.hasAnyErrors()) { return error45; } else { return null; } } var ProgramContext = class { constructor({ program, suppressions, opts, filename, code, hasModuleScopeOptOut }) { /* * This is a hack to work around what seems to be a Babel bug. Babel doesn't * consistently respect the `skip()` function to avoid revisiting a node within * a pass, so we use this set to track nodes that we have compiled. */ this.alreadyCompiled = new (WeakSet != null ? WeakSet : Set)(); // known generated or referenced identifiers in the program this.knownReferencedNames = /* @__PURE__ */ new Set(); // generated imports this.imports = /* @__PURE__ */ new Map(); /** * Metadata from compilation */ this.retryErrors = []; this.inferredEffectLocations = /* @__PURE__ */ new Set(); this.scope = program.scope; this.opts = opts; this.filename = filename; this.code = code; this.reactRuntimeModule = getReactCompilerRuntimeModule(opts.target); this.suppressions = suppressions; this.hasModuleScopeOptOut = hasModuleScopeOptOut; } isHookName(name) { if (this.opts.environment.hookPattern == null) { return isHookName(name); } else { const match = new RegExp(this.opts.environment.hookPattern).exec(name); return match != null && typeof match[1] === "string" && isHookName(match[1]); } } hasReference(name) { return this.knownReferencedNames.has(name) || this.scope.hasBinding(name) || this.scope.hasGlobal(name) || this.scope.hasReference(name); } newUid(name) { let uid; if (this.isHookName(name)) { uid = name; let i = 0; while (this.hasReference(uid)) { this.knownReferencedNames.add(uid); uid = `${name}_${i++}`; } } else if (!this.hasReference(name)) { uid = name; } else { uid = this.scope.generateUid(name); } this.knownReferencedNames.add(uid); return uid; } addMemoCacheImport() { return this.addImportSpecifier( { source: this.reactRuntimeModule, importSpecifierName: "c" }, "_c" ); } /** * * @param externalFunction * @param nameHint if defined, will be used as the name of the import specifier * @returns */ addImportSpecifier({ source: module2, importSpecifierName: specifier }, nameHint) { var _a; const maybeBinding = (_a = this.imports.get(module2)) == null ? void 0 : _a.get(specifier); if (maybeBinding != null) { return __spreadValues({}, maybeBinding); } const binding = { kind: "ImportSpecifier", name: this.newUid(nameHint != null ? nameHint : specifier), module: module2, imported: specifier }; getOrInsertWith(this.imports, module2, () => /* @__PURE__ */ new Map()).set(specifier, __spreadValues({}, binding)); return binding; } addNewReference(name) { this.knownReferencedNames.add(name); } assertGlobalBinding(name, localScope) { var _a, _b; const scope = localScope != null ? localScope : this.scope; if (!scope.hasReference(name) && !scope.hasBinding(name)) { return Ok(void 0); } const error45 = new CompilerError(); error45.push({ category: "Todo" /* Todo */, reason: "Encountered conflicting global in generated program", description: `Conflict from local binding ${name}`, loc: (_b = (_a = scope.getBinding(name)) == null ? void 0 : _a.path.node.loc) != null ? _b : null, suggestions: null }); return Err(error45); } logEvent(event) { if (this.opts.logger != null) { this.opts.logger.logEvent(this.filename, event); } } }; function getExistingImports(program) { const existingImports = /* @__PURE__ */ new Map(); program.traverse({ ImportDeclaration(path) { if (isNonNamespacedImport(path)) { existingImports.set(path.node.source.value, path); } } }); return existingImports; } function addImportsToProgram(path, programContext) { const existingImports = getExistingImports(path); const stmts = []; const sortedModules = [...programContext.imports.entries()].sort( ([a], [b]) => a.localeCompare(b) ); for (const [moduleName, importsMap] of sortedModules) { for (const [specifierName, loweredImport] of importsMap) { CompilerError.invariant( path.scope.getBinding(loweredImport.name) == null, { reason: "Encountered conflicting import specifiers in generated program", description: `Conflict from import ${loweredImport.module}:(${loweredImport.imported} as ${loweredImport.name})`, details: [ { kind: "error", loc: GeneratedSource, message: null } ], suggestions: null } ); CompilerError.invariant( loweredImport.module === moduleName && loweredImport.imported === specifierName, { reason: "Found inconsistent import specifier. This is an internal bug.", description: `Expected import ${moduleName}:${specifierName} but found ${loweredImport.module}:${loweredImport.imported}`, details: [ { kind: "error", loc: GeneratedSource, message: null } ] } ); } const sortedImport = [ ...importsMap.values() ].sort(({ imported: a }, { imported: b }) => a.localeCompare(b)); const importSpecifiers = sortedImport.map((specifier) => { return t5.importSpecifier( t5.identifier(specifier.name), t5.identifier(specifier.imported) ); }); const maybeExistingImports = existingImports.get(moduleName); if (maybeExistingImports != null) { maybeExistingImports.pushContainer("specifiers", importSpecifiers); } else { if (path.node.sourceType === "module") { stmts.push( t5.importDeclaration(importSpecifiers, t5.stringLiteral(moduleName)) ); } else { stmts.push( t5.variableDeclaration("const", [ t5.variableDeclarator( t5.objectPattern( sortedImport.map((specifier) => { return t5.objectProperty( t5.identifier(specifier.imported), t5.identifier(specifier.name) ); }) ), t5.callExpression(t5.identifier("require"), [ t5.stringLiteral(moduleName) ]) ) ]) ); } } } path.unshiftContainer("body", stmts); } function isNonNamespacedImport(importDeclPath) { return importDeclPath.get("specifiers").every((specifier) => specifier.isImportSpecifier()) && importDeclPath.node.importKind !== "type" && importDeclPath.node.importKind !== "typeof"; } // src/Entrypoint/Options.ts var PanicThresholdOptionsSchema = external_exports.enum([ /* * Any errors will panic the compiler by throwing an exception, which will * bubble up to the nearest exception handler above the Forget transform. * If Forget is invoked through `BabelPluginReactCompiler`, this will at the least * skip Forget compilation for the rest of current file. */ "all_errors", /* * Panic by throwing an exception only on critical or unrecognized errors. * For all other errors, skip the erroring function without inserting * a Forget-compiled version (i.e. same behavior as noEmit). */ "critical_errors", // Never panic by throwing an exception. "none" ]); var DynamicGatingOptionsSchema = external_exports.object({ source: external_exports.string() }); var CustomOptOutDirectiveSchema = external_exports.nullable(external_exports.array(external_exports.string())).default(null); var CompilerReactTargetSchema = external_exports.union([ external_exports.literal("17"), external_exports.literal("18"), external_exports.literal("19"), /** * Used exclusively for Meta apps which are guaranteed to have compatible * react runtime and compiler versions. Note that only the FB-internal bundles * re-export useMemoCache (see * https://github.com/facebook/react/blob/5b0ef217ef32333a8e56f39be04327c89efa346f/packages/react/index.fb.js#L68-L70), * so this option is invalid / creates runtime errors for open-source users. */ external_exports.object({ kind: external_exports.literal("donotuse_meta_internal"), runtimeModule: external_exports.string().default("react") }) ]); var CompilationModeSchema = external_exports.enum([ /* * Compiles functions annotated with "use forget" or component/hook-like functions. * This latter includes: * * Components declared with component syntax. * * Functions which can be inferred to be a component or hook: * - Be named like a hook or component. This logic matches the ESLint rule. * - *and* create JSX and/or call a hook. This is an additional check to help prevent * false positives, since compilation has a greater impact than linting. * This is the default mode */ "infer", // Compile only components using Flow component syntax and hooks using hook syntax. "syntax", // Compile only functions which are explicitly annotated with "use forget" "annotation", // Compile all top-level functions "all" ]); var defaultOptions = { compilationMode: "infer", panicThreshold: "none", environment: parseEnvironmentConfig({}).unwrap(), logger: null, gating: null, noEmit: false, dynamicGating: null, eslintSuppressionRules: null, flowSuppressions: true, ignoreUseNoForget: false, sources: (filename) => { return filename.indexOf("node_modules") === -1; }, enableReanimatedCheck: true, customOptOutDirectives: null, target: "19" }; function parsePluginOptions(obj) { if (obj == null || typeof obj !== "object") { return defaultOptions; } const parsedOptions = /* @__PURE__ */ Object.create(null); for (let [key2, value] of Object.entries(obj)) { if (typeof value === "string") { value = value.toLowerCase(); } if (isCompilerFlag(key2)) { switch (key2) { case "environment": { const environmentResult = parseEnvironmentConfig(value); if (environmentResult.isErr()) { CompilerError.throwInvalidConfig({ reason: "Error in validating environment config. This is an advanced setting and not meant to be used directly", description: environmentResult.unwrapErr().toString(), suggestions: null, loc: null }); } parsedOptions[key2] = environmentResult.unwrap(); break; } case "target": { parsedOptions[key2] = parseTargetConfig(value); break; } case "gating": { if (value == null) { parsedOptions[key2] = null; } else { parsedOptions[key2] = tryParseExternalFunction(value); } break; } case "dynamicGating": { if (value == null) { parsedOptions[key2] = null; } else { const result = DynamicGatingOptionsSchema.safeParse(value); if (result.success) { parsedOptions[key2] = result.data; } else { CompilerError.throwInvalidConfig({ reason: "Could not parse dynamic gating. Update React Compiler config to fix the error", description: `${fromZodError(result.error)}`, loc: null, suggestions: null }); } } break; } case "customOptOutDirectives": { const result = CustomOptOutDirectiveSchema.safeParse(value); if (result.success) { parsedOptions[key2] = result.data; } else { CompilerError.throwInvalidConfig({ reason: "Could not parse custom opt out directives. Update React Compiler config to fix the error", description: `${fromZodError(result.error)}`, loc: null, suggestions: null }); } break; } default: { parsedOptions[key2] = value; } } } } return __spreadValues(__spreadValues({}, defaultOptions), parsedOptions); } function parseTargetConfig(value) { const parsed = CompilerReactTargetSchema.safeParse(value); if (parsed.success) { return parsed.data; } else { CompilerError.throwInvalidConfig({ reason: "Not a valid target", description: `${fromZodError(parsed.error)}`, suggestions: null, loc: null }); } } function isCompilerFlag(s) { return hasOwnProperty2(defaultOptions, s); } // src/Entrypoint/Reanimated.ts function hasModule(name) { if (typeof require === "undefined") { return false; } try { return !!require.resolve(name); } catch (error45) { if (error45.code === "MODULE_NOT_FOUND" && error45.message.indexOf(name) !== -1) { return false; } throw error45; } } function pipelineUsesReanimatedPlugin(plugins) { if (Array.isArray(plugins)) { for (const plugin of plugins) { if (hasOwnProperty2(plugin, "key")) { const key2 = plugin.key; if (typeof key2 === "string" && key2.indexOf("react-native-reanimated") !== -1) { return true; } } } } return hasModule("react-native-reanimated"); } function injectReanimatedFlag(options) { return __spreadProps(__spreadValues({}, options), { environment: __spreadProps(__spreadValues({}, options.environment), { enableCustomTypeDefinitionForReanimated: true }) }); } // src/Entrypoint/ValidateNoUntransformedReferences.ts function throwInvalidReact(options, { logger, filename }) { logger == null ? void 0 : logger.logEvent(filename, { kind: "CompileError", fnLoc: null, detail: new CompilerDiagnostic(options) }); CompilerError.throwDiagnostic(options); } function isAutodepsSigil(arg) { if (arg.isIdentifier() && arg.node.name === "AUTODEPS") { const binding = arg.scope.getBinding(arg.node.name); if (binding && binding.path.isImportSpecifier()) { const importSpecifier2 = binding.path.node; if (importSpecifier2.imported.type === "Identifier") { return importSpecifier2.imported.name === "AUTODEPS"; } } return false; } if (arg.isMemberExpression() && !arg.node.computed) { const object2 = arg.get("object"); const property = arg.get("property"); if (object2.isIdentifier() && object2.node.name === "React" && property.isIdentifier() && property.node.name === "AUTODEPS") { return true; } } return false; } function assertValidEffectImportReference(autodepsIndex, paths, context) { var _a; for (const path of paths) { const parent = path.parentPath; if (parent != null && parent.isCallExpression()) { const args = parent.get("arguments"); const maybeCalleeLoc = path.node.loc; const hasInferredEffect = maybeCalleeLoc != null && context.inferredEffectLocations.has(maybeCalleeLoc); const hasAutodepsArg = args.some(isAutodepsSigil); if (hasAutodepsArg && !hasInferredEffect) { const maybeErrorDiagnostic = matchCompilerDiagnostic( path, context.transformErrors ); throwInvalidReact( { category: "AutomaticEffectDependencies" /* AutomaticEffectDependencies */, reason: "Cannot infer dependencies of this effect. This will break your build!", description: "To resolve, either pass a dependency array or fix reported compiler bailout diagnostics" + (maybeErrorDiagnostic ? ` ${maybeErrorDiagnostic}` : ""), details: [ { kind: "error", message: "Cannot infer dependencies", loc: (_a = parent.node.loc) != null ? _a : GeneratedSource } ] }, context ); } } } } function assertValidFireImportReference(paths, context) { var _a; if (paths.length > 0) { const maybeErrorDiagnostic = matchCompilerDiagnostic( paths[0], context.transformErrors ); throwInvalidReact( { category: "Fire" /* Fire */, reason: "[Fire] Untransformed reference to compiler-required feature.", description: "Either remove this `fire` call or ensure it is successfully transformed by the compiler" + (maybeErrorDiagnostic != null ? ` ${maybeErrorDiagnostic}` : ""), details: [ { kind: "error", message: "Untransformed `fire` call", loc: (_a = paths[0].node.loc) != null ? _a : GeneratedSource } ] }, context ); } } function validateNoUntransformedReferences(path, filename, logger, env, compileResult) { const moduleLoadChecks = /* @__PURE__ */ new Map(); if (env.enableFire) { for (const module2 of Environment2.knownReactModules) { const react = getOrInsertWith(moduleLoadChecks, module2, () => /* @__PURE__ */ new Map()); react.set("fire", assertValidFireImportReference); } } if (env.inferEffectDependencies) { for (const { function: { source: source2, importSpecifierName }, autodepsIndex } of env.inferEffectDependencies) { const module2 = getOrInsertWith(moduleLoadChecks, source2, () => /* @__PURE__ */ new Map()); module2.set( importSpecifierName, assertValidEffectImportReference.bind(null, autodepsIndex) ); } } if (moduleLoadChecks.size > 0) { transformProgram(path, moduleLoadChecks, filename, logger, compileResult); } } function validateImportSpecifier(specifier, importSpecifierChecks, state) { var _a; const imported = specifier.get("imported"); const specifierName = imported.node.type === "Identifier" ? imported.node.name : imported.node.value; const checkFn = importSpecifierChecks.get(specifierName); if (checkFn == null) { return; } if (state.shouldInvalidateScopes) { state.shouldInvalidateScopes = false; state.program.scope.crawl(); } const local = specifier.get("local"); const binding = local.scope.getBinding(local.node.name); CompilerError.invariant(binding != null, { reason: "Expected binding to be found for import specifier", description: null, details: [ { kind: "error", loc: (_a = local.node.loc) != null ? _a : null, message: null } ] }); checkFn(binding.referencePaths, state); } function validateNamespacedImport(specifier, importSpecifierChecks, state) { var _a; if (state.shouldInvalidateScopes) { state.shouldInvalidateScopes = false; state.program.scope.crawl(); } const local = specifier.get("local"); const binding = local.scope.getBinding(local.node.name); const defaultCheckFn = importSpecifierChecks.get(DEFAULT_EXPORT); CompilerError.invariant(binding != null, { reason: "Expected binding to be found for import specifier", description: null, details: [ { kind: "error", loc: (_a = local.node.loc) != null ? _a : null, message: null } ] }); const filteredReferences = /* @__PURE__ */ new Map(); for (const reference of binding.referencePaths) { if (defaultCheckFn != null) { getOrInsertWith(filteredReferences, defaultCheckFn, () => []).push( reference ); } const parent = reference.parentPath; if (parent != null && parent.isMemberExpression() && parent.get("object") === reference) { if (parent.node.computed || parent.node.property.type !== "Identifier") { continue; } const checkFn = importSpecifierChecks.get(parent.node.property.name); if (checkFn != null) { getOrInsertWith(filteredReferences, checkFn, () => []).push(parent); } } } for (const [checkFn, references] of filteredReferences) { checkFn(references, state); } } function transformProgram(path, moduleLoadChecks, filename, logger, compileResult) { var _a, _b; const traversalState = { shouldInvalidateScopes: true, program: path, filename, logger, transformErrors: (_a = compileResult == null ? void 0 : compileResult.retryErrors) != null ? _a : [], inferredEffectLocations: (_b = compileResult == null ? void 0 : compileResult.inferredEffectLocations) != null ? _b : /* @__PURE__ */ new Set() }; path.traverse({ ImportDeclaration(path2) { const importSpecifierChecks = moduleLoadChecks.get( path2.node.source.value ); if (importSpecifierChecks == null) { return; } const specifiers = path2.get("specifiers"); for (const specifier of specifiers) { if (specifier.isImportSpecifier()) { validateImportSpecifier( specifier, importSpecifierChecks, traversalState ); } else { validateNamespacedImport( specifier, importSpecifierChecks, traversalState ); } } } }); } function matchCompilerDiagnostic(badReference, transformErrors) { for (const { fn, error: error45 } of transformErrors) { if (fn.isAncestor(badReference)) { return error45.toString(); } } return null; } // src/Babel/BabelPlugin.ts var ENABLE_REACT_COMPILER_TIMINGS = process.env["ENABLE_REACT_COMPILER_TIMINGS"] === "1"; function BabelPluginReactCompiler(_babel) { return { name: "react-forget", visitor: { /* * Note: Babel does some "smart" merging of visitors across plugins, so even if A is inserted * prior to B, if A does not have a Program visitor and B does, B will run first. We always * want Forget to run true to source as possible. */ Program: { enter(prog, pass) { var _a, _b, _c, _d; try { const filename = (_a = pass.filename) != null ? _a : "unknown"; if (ENABLE_REACT_COMPILER_TIMINGS === true) { performance.mark(`${filename}:start`, { detail: "BabelPlugin:Program:start" }); } let opts = parsePluginOptions(pass.opts); const isDev = typeof __DEV__ !== "undefined" && __DEV__ === true || process.env["NODE_ENV"] === "development"; if (opts.enableReanimatedCheck === true && pipelineUsesReanimatedPlugin(pass.file.opts.plugins)) { opts = injectReanimatedFlag(opts); } if (opts.environment.enableResetCacheOnSourceFileChanges !== false && isDev) { opts = __spreadProps(__spreadValues({}, opts), { environment: __spreadProps(__spreadValues({}, opts.environment), { enableResetCacheOnSourceFileChanges: true }) }); } const result = compileProgram(prog, { opts, filename: (_b = pass.filename) != null ? _b : null, comments: (_c = pass.file.ast.comments) != null ? _c : [], code: pass.file.code }); validateNoUntransformedReferences( prog, (_d = pass.filename) != null ? _d : null, opts.logger, opts.environment, result ); if (ENABLE_REACT_COMPILER_TIMINGS === true) { performance.mark(`${filename}:end`, { detail: "BabelPlugin:Program:end" }); } } catch (e) { if (e instanceof CompilerError) { throw e.withPrintedMessage(pass.file.code, { eslint: false }); } throw e; } }, exit(_, pass) { var _a; if (ENABLE_REACT_COMPILER_TIMINGS === true) { const filename = (_a = pass.filename) != null ? _a : "unknown"; const measurement = performance.measure(filename, { start: `${filename}:start`, end: `${filename}:end`, detail: "BabelPlugin:Program" }); if ("logger" in pass.opts && pass.opts.logger != null) { const logger = pass.opts.logger; logger.logEvent(filename, { kind: "Timing", measurement }); } } } } } }; } // src/Babel/RunReactCompilerBabelPlugin.ts function runBabelPluginReactCompiler(text, file2, language, options, includeAst = false) { const ast = BabelParser.parse(text, { sourceFilename: file2, plugins: [language, "jsx"], sourceType: "module" }); const result = (0, import_core8.transformFromAstSync)(ast, text, { ast: includeAst, filename: file2, highlightCode: false, retainLines: true, plugins: [ [BabelPluginReactCompiler, options], "babel-plugin-fbt", "babel-plugin-fbt-runtime" ], sourceType: "module", configFile: false, babelrc: false }); (0, import_invariant4.default)( (result == null ? void 0 : result.code) != null, `Expected BabelPluginReactForget to codegen successfully, got: ${result}` ); return result; } // src/Utils/TestUtils.ts function tryParseTestPragmaValue(val) { try { let parsedVal; const stringMatch = /^"([^"]*)"$/.exec(val); if (stringMatch && stringMatch.length > 1) { parsedVal = stringMatch[1]; } else { parsedVal = JSON.parse(val); } return Ok(parsedVal); } catch (e) { return Err(e); } } var testComplexConfigDefaults = { validateNoCapitalizedCalls: [], enableChangeDetectionForDebugging: { source: "react-compiler-runtime", importSpecifierName: "$structuralCheck" }, enableEmitFreeze: { source: "react-compiler-runtime", importSpecifierName: "makeReadOnly" }, enableEmitInstrumentForget: { fn: { source: "react-compiler-runtime", importSpecifierName: "useRenderCounter" }, gating: { source: "react-compiler-runtime", importSpecifierName: "shouldInstrument" }, globalGating: "DEV" }, enableEmitHookGuards: { source: "react-compiler-runtime", importSpecifierName: "$dispatcherGuard" }, inlineJsxTransform: { elementSymbol: "react.transitional.element", globalDevVar: "DEV" }, lowerContextAccess: { source: "react-compiler-runtime", importSpecifierName: "useContext_withSelector" }, inferEffectDependencies: [ { function: { source: "react", importSpecifierName: "useEffect" }, autodepsIndex: 1 }, { function: { source: "shared-runtime", importSpecifierName: "useSpecialEffect" }, autodepsIndex: 2 }, { function: { source: "useEffectWrapper", importSpecifierName: "default" }, autodepsIndex: 1 } ] }; function* splitPragma(pragma) { for (const entry of pragma.split("@")) { const keyVal = entry.trim(); const valIdx = keyVal.indexOf(":"); if (valIdx === -1) { yield { key: keyVal.split(" ", 1)[0], value: null }; } else { yield { key: keyVal.slice(0, valIdx), value: keyVal.slice(valIdx + 1) }; } } } function parseConfigPragmaEnvironmentForTest(pragma, defaultConfig) { EnvironmentConfigSchema.parse(defaultConfig); const maybeConfig = defaultConfig; for (const { key: key2, value: val } of splitPragma(pragma)) { if (!hasOwnProperty2(EnvironmentConfigSchema.shape, key2)) { continue; } const isSet = val == null || val === "true"; if (isSet && key2 in testComplexConfigDefaults) { maybeConfig[key2] = testComplexConfigDefaults[key2]; } else if (isSet) { maybeConfig[key2] = true; } else if (val === "false") { maybeConfig[key2] = false; } else if (val) { const parsedVal = tryParseTestPragmaValue(val).unwrap(); if (key2 === "customMacros" && typeof parsedVal === "string") { const valSplit = parsedVal.split("."); const props = []; for (const elt of valSplit.slice(1)) { if (elt === "*") { props.push({ type: "wildcard" }); } else if (elt.length > 0) { props.push({ type: "name", name: elt }); } } maybeConfig[key2] = [[valSplit[0], props]]; continue; } maybeConfig[key2] = parsedVal; } } const config2 = EnvironmentConfigSchema.safeParse(maybeConfig); if (config2.success) { if (config2.data.enableResetCacheOnSourceFileChanges == null) { config2.data.enableResetCacheOnSourceFileChanges = false; } return config2.data; } CompilerError.invariant(false, { reason: "Internal error, could not parse config from pragma string", description: `${fromZodError(config2.error)}`, details: [ { kind: "error", loc: null, message: null } ], suggestions: null }); } var testComplexPluginOptionDefaults = { gating: { source: "ReactForgetFeatureFlag", importSpecifierName: "isForgetEnabled_Fixtures" } }; function parseConfigPragmaForTests(pragma, defaults) { var _a; const environment = parseConfigPragmaEnvironmentForTest( pragma, (_a = defaults.environment) != null ? _a : {} ); const options = __spreadProps(__spreadValues({}, defaultOptions), { panicThreshold: "all_errors", compilationMode: defaults.compilationMode, environment }); for (const { key: key2, value: val } of splitPragma(pragma)) { if (!hasOwnProperty2(defaultOptions, key2)) { continue; } const isSet = val == null || val === "true"; if (isSet && key2 in testComplexPluginOptionDefaults) { options[key2] = testComplexPluginOptionDefaults[key2]; } else if (isSet) { options[key2] = true; } else if (val === "false") { options[key2] = false; } else if (val != null) { const parsedVal = tryParseTestPragmaValue(val).unwrap(); if (key2 === "target" && parsedVal === "donotuse_meta_internal") { options[key2] = { kind: parsedVal, runtimeModule: "react" }; } else { options[key2] = parsedVal; } } } return parsePluginOptions(options); } // src/index.ts var index_default = BabelPluginReactCompiler; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CompilerDiagnostic, CompilerError, CompilerErrorDetail, CompilerSuggestionOperation, Effect, ErrorCategory, ErrorSeverity, LintRules, OPT_IN_DIRECTIVES, OPT_OUT_DIRECTIVES, ProgramContext, ValueKind, ValueReason, compile, compileProgram, findDirectiveDisablingMemoization, findDirectiveEnablingMemoization, parseConfigPragmaForTests, parsePluginOptions, printFunctionWithOutlined, printHIR, printReactiveFunction, printReactiveFunctionWithOutlined, runBabelPluginReactCompiler, validateEnvironmentConfig }); /*! Bundled license information: react-is/cjs/react-is.production.min.js: (** @license React v16.13.1 * react-is.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) react-is/cjs/react-is.development.js: (** @license React v16.13.1 * react-is.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) */