@algolia/sitesearch
Version:
Opinionated site search modal for the web. Ships zero-build CDN bundles (JS + CSS) and a one-line init API. Powered by Algolia InstantSearch.
27,142 lines • 981 kB
JavaScript
//#region rolldown:runtime
var __create = Object.create;
var __defProp$1 = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn$1, res) => function() {
return fn$1 && (res = (0, fn$1[__getOwnPropNames(fn$1)[0]])(fn$1 = 0)), res;
};
var __commonJS = (cb, mod) => function() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export$1 = (target, all) => {
for (var name$2 in all) __defProp$1(target, name$2, {
get: all[name$2],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i$3 = 0, n$1 = keys.length, key; i$3 < n$1; i$3++) {
key = keys[i$3];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp$1(to, key, {
get: ((k$4) => from[k$4]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp$1(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
var __toCommonJS = (mod) => __copyProps(__defProp$1({}, "__esModule", { value: true }), mod);
//#endregion
//#region ../../node_modules/.bun/@algolia+requester-browser-xhr@5.40.0/node_modules/@algolia/requester-browser-xhr/dist/requester.xhr.js
function m$3() {
function r$2(t$2) {
return new Promise((s$2) => {
let e$2 = new XMLHttpRequest();
e$2.open(t$2.method, t$2.url, !0), Object.keys(t$2.headers).forEach((n$1) => e$2.setRequestHeader(n$1, t$2.headers[n$1]));
let i$3 = (n$1, a$2) => setTimeout(() => {
e$2.abort(), s$2({
status: 0,
content: a$2,
isTimedOut: !0
});
}, n$1), u$3 = i$3(t$2.connectTimeout, "Connection timeout"), o$3;
e$2.onreadystatechange = () => {
e$2.readyState > e$2.OPENED && o$3 === void 0 && (clearTimeout(u$3), o$3 = i$3(t$2.responseTimeout, "Socket timeout"));
}, e$2.onerror = () => {
e$2.status === 0 && (clearTimeout(u$3), clearTimeout(o$3), s$2({
content: e$2.responseText || "Network request failed",
status: e$2.status,
isTimedOut: !1
}));
}, e$2.onload = () => {
clearTimeout(u$3), clearTimeout(o$3), s$2({
content: e$2.responseText,
status: e$2.status,
isTimedOut: !1
});
}, e$2.send(t$2.data);
});
}
return { send: r$2 };
}
//#endregion
//#region ../../node_modules/.bun/@algolia+client-common@5.40.0/node_modules/@algolia/client-common/dist/common.js
function createBrowserLocalStorageCache(options) {
let storage;
const namespaceKey = `algolia-client-js-${options.key}`;
function getStorage() {
if (storage === void 0) storage = options.localStorage || window.localStorage;
return storage;
}
function getNamespace() {
return JSON.parse(getStorage().getItem(namespaceKey) || "{}");
}
function setNamespace(namespace) {
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
}
function removeOutdatedCacheItems() {
const timeToLive = options.timeToLive ? options.timeToLive * 1e3 : null;
const namespace = getNamespace();
const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => {
return cacheItem.timestamp !== void 0;
}));
setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
if (!timeToLive) return;
const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
const currentTimestamp = (/* @__PURE__ */ new Date()).getTime();
const isExpired$1 = cacheItem.timestamp + timeToLive < currentTimestamp;
return !isExpired$1;
}));
setNamespace(filteredNamespaceWithoutExpiredItems);
}
return {
get(key, defaultValue, events = { miss: () => Promise.resolve() }) {
return Promise.resolve().then(() => {
removeOutdatedCacheItems();
return getNamespace()[JSON.stringify(key)];
}).then((value) => {
return Promise.all([value ? value.value : defaultValue(), value !== void 0]);
}).then(([value, exists]) => {
return Promise.all([value, exists || events.miss(value)]);
}).then(([value]) => value);
},
set(key, value) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
namespace[JSON.stringify(key)] = {
timestamp: (/* @__PURE__ */ new Date()).getTime(),
value
};
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
return value;
});
},
delete(key) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
delete namespace[JSON.stringify(key)];
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
});
},
clear() {
return Promise.resolve().then(() => {
getStorage().removeItem(namespaceKey);
});
}
};
}
function createNullCache() {
return {
get(_key, defaultValue, events = { miss: () => Promise.resolve() }) {
const value = defaultValue();
return value.then((result) => Promise.all([result, events.miss(result)])).then(([result]) => result);
},
set(_key, value) {
return Promise.resolve(value);
},
delete(_key) {
return Promise.resolve();
},
clear() {
return Promise.resolve();
}
};
}
function createFallbackableCache(options) {
const caches = [...options.caches];
const current = caches.shift();
if (current === void 0) return createNullCache();
return {
get(key, defaultValue, events = { miss: () => Promise.resolve() }) {
return current.get(key, defaultValue, events).catch(() => {
return createFallbackableCache({ caches }).get(key, defaultValue, events);
});
},
set(key, value) {
return current.set(key, value).catch(() => {
return createFallbackableCache({ caches }).set(key, value);
});
},
delete(key) {
return current.delete(key).catch(() => {
return createFallbackableCache({ caches }).delete(key);
});
},
clear() {
return current.clear().catch(() => {
return createFallbackableCache({ caches }).clear();
});
}
};
}
function createMemoryCache(options = { serializable: true }) {
let cache = {};
return {
get(key, defaultValue, events = { miss: () => Promise.resolve() }) {
const keyAsString = JSON.stringify(key);
if (keyAsString in cache) return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
const promise = defaultValue();
return promise.then((value) => events.miss(value)).then(() => promise);
},
set(key, value) {
cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
return Promise.resolve(value);
},
delete(key) {
delete cache[JSON.stringify(key)];
return Promise.resolve();
},
clear() {
cache = {};
return Promise.resolve();
}
};
}
function createAlgoliaAgent(version$2) {
const algoliaAgent = {
value: `Algolia for JavaScript (${version$2})`,
add(options) {
const addedAlgoliaAgent = `; ${options.segment}${options.version !== void 0 ? ` (${options.version})` : ""}`;
if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
return algoliaAgent;
}
};
return algoliaAgent;
}
function createAuth(appId, apiKey, authMode = "WithinHeaders") {
const credentials = {
"x-algolia-api-key": apiKey,
"x-algolia-application-id": appId
};
return {
headers() {
return authMode === "WithinHeaders" ? credentials : {};
},
queryParameters() {
return authMode === "WithinQueryParameters" ? credentials : {};
}
};
}
function getAlgoliaAgent({ algoliaAgents, client, version: version$2 }) {
const defaultAlgoliaAgent = createAlgoliaAgent(version$2).add({
segment: client,
version: version$2
});
algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));
return defaultAlgoliaAgent;
}
function createNullLogger() {
return {
debug(_message, _args) {
return Promise.resolve();
},
info(_message, _args) {
return Promise.resolve();
},
error(_message, _args) {
return Promise.resolve();
}
};
}
var EXPIRATION_DELAY = 2 * 60 * 1e3;
function createStatefulHost(host, status = "up") {
const lastUpdate = Date.now();
function isUp() {
return status === "up" || Date.now() - lastUpdate > EXPIRATION_DELAY;
}
function isTimedOut() {
return status === "timed out" && Date.now() - lastUpdate <= EXPIRATION_DELAY;
}
return {
...host,
status,
lastUpdate,
isUp,
isTimedOut
};
}
var AlgoliaError = class extends Error {
name = "AlgoliaError";
constructor(message, name$2) {
super(message);
if (name$2) this.name = name$2;
}
};
var ErrorWithStackTrace = class extends AlgoliaError {
stackTrace;
constructor(message, stackTrace, name$2) {
super(message, name$2);
this.stackTrace = stackTrace;
}
};
var RetryError = class extends ErrorWithStackTrace {
constructor(stackTrace) {
super("Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support", stackTrace, "RetryError");
}
};
var ApiError = class extends ErrorWithStackTrace {
status;
constructor(message, status, stackTrace, name$2 = "ApiError") {
super(message, stackTrace, name$2);
this.status = status;
}
};
var DeserializationError = class extends AlgoliaError {
response;
constructor(message, response) {
super(message, "DeserializationError");
this.response = response;
}
};
var DetailedApiError = class extends ApiError {
error;
constructor(message, status, error, stackTrace) {
super(message, status, stackTrace, "DetailedApiError");
this.error = error;
}
};
function shuffle(array$1) {
const shuffledArray = array$1;
for (let c$2 = array$1.length - 1; c$2 > 0; c$2--) {
const b$3 = Math.floor(Math.random() * (c$2 + 1));
const a$2 = array$1[c$2];
shuffledArray[c$2] = array$1[b$3];
shuffledArray[b$3] = a$2;
}
return shuffledArray;
}
function serializeUrl(host, path, queryParameters) {
const queryParametersAsString = serializeQueryParameters$1(queryParameters);
let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ""}/${path.charAt(0) === "/" ? path.substring(1) : path}`;
if (queryParametersAsString.length) url += `?${queryParametersAsString}`;
return url;
}
function serializeQueryParameters$1(parameters) {
return Object.keys(parameters).filter((key) => parameters[key] !== void 0).sort().map((key) => `${key}=${encodeURIComponent(Object.prototype.toString.call(parameters[key]) === "[object Array]" ? parameters[key].join(",") : parameters[key]).replace(/\+/g, "%20")}`).join("&");
}
function serializeData(request, requestOptions) {
if (request.method === "GET" || request.data === void 0 && requestOptions.data === void 0) return void 0;
const data = Array.isArray(request.data) ? request.data : {
...request.data,
...requestOptions.data
};
return JSON.stringify(data);
}
function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
const headers = {
Accept: "application/json",
...baseHeaders,
...requestHeaders,
...requestOptionsHeaders
};
const serializedHeaders = {};
Object.keys(headers).forEach((header) => {
const value = headers[header];
serializedHeaders[header.toLowerCase()] = value;
});
return serializedHeaders;
}
function deserializeSuccess(response) {
try {
return JSON.parse(response.content);
} catch (e$2) {
throw new DeserializationError(e$2.message, response);
}
}
function deserializeFailure({ content, status }, stackFrame) {
try {
const parsed = JSON.parse(content);
if ("error" in parsed) return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
return new ApiError(parsed.message, status, stackFrame);
} catch {}
return new ApiError(content, status, stackFrame);
}
function isNetworkError({ isTimedOut, status }) {
return !isTimedOut && ~~status === 0;
}
function isRetryable({ isTimedOut, status }) {
return isTimedOut || isNetworkError({
isTimedOut,
status
}) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
}
function isSuccess({ status }) {
return ~~(status / 100) === 2;
}
function stackTraceWithoutCredentials(stackTrace) {
return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));
}
function stackFrameWithoutCredentials(stackFrame) {
const modifiedHeaders = stackFrame.request.headers["x-algolia-api-key"] ? { "x-algolia-api-key": "*****" } : {};
return {
...stackFrame,
request: {
...stackFrame.request,
headers: {
...stackFrame.request.headers,
...modifiedHeaders
}
}
};
}
function createTransporter({ hosts, hostsCache, baseHeaders, logger, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache }) {
async function createRetryableOptions(compatibleHosts) {
const statefulHosts = await Promise.all(compatibleHosts.map((compatibleHost) => {
return hostsCache.get(compatibleHost, () => {
return Promise.resolve(createStatefulHost(compatibleHost));
});
}));
const hostsUp = statefulHosts.filter((host) => host.isUp());
const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());
const hostsAvailable = [...hostsUp, ...hostsTimedOut];
const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
return {
hosts: compatibleHostsAvailable,
getTimeout(timeoutsCount, baseTimeout) {
const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
return timeoutMultiplier * baseTimeout;
}
};
}
async function retryableRequest(request, requestOptions, isRead = true) {
const stackTrace = [];
const data = serializeData(request, requestOptions);
const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
const dataQueryParameters = request.method === "GET" ? {
...request.data,
...requestOptions.data
} : {};
const queryParameters = {
...baseQueryParameters,
...request.queryParameters,
...dataQueryParameters
};
if (algoliaAgent.value) queryParameters["x-algolia-agent"] = algoliaAgent.value;
if (requestOptions && requestOptions.queryParameters) for (const key of Object.keys(requestOptions.queryParameters)) if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === "[object Object]") queryParameters[key] = requestOptions.queryParameters[key];
else queryParameters[key] = requestOptions.queryParameters[key].toString();
let timeoutsCount = 0;
const retry = async (retryableHosts, getTimeout) => {
const host = retryableHosts.pop();
if (host === void 0) throw new RetryError(stackTraceWithoutCredentials(stackTrace));
const timeout = {
...timeouts,
...requestOptions.timeouts
};
const payload = {
data,
headers,
method: request.method,
url: serializeUrl(host, request.path, queryParameters),
connectTimeout: getTimeout(timeoutsCount, timeout.connect),
responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
};
const pushToStackTrace = (response2) => {
const stackFrame = {
request: payload,
response: response2,
host,
triesLeft: retryableHosts.length
};
stackTrace.push(stackFrame);
return stackFrame;
};
const response = await requester.send(payload);
if (isRetryable(response)) {
const stackFrame = pushToStackTrace(response);
if (response.isTimedOut) timeoutsCount++;
logger.info("Retryable failure", stackFrameWithoutCredentials(stackFrame));
await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? "timed out" : "down"));
return retry(retryableHosts, getTimeout);
}
if (isSuccess(response)) return deserializeSuccess(response);
pushToStackTrace(response);
throw deserializeFailure(response, stackTrace);
};
const compatibleHosts = hosts.filter((host) => host.accept === "readWrite" || (isRead ? host.accept === "read" : host.accept === "write"));
const options = await createRetryableOptions(compatibleHosts);
return retry([...options.hosts].reverse(), options.getTimeout);
}
function createRequest(request, requestOptions = {}) {
const isRead = request.useReadTransporter || request.method === "GET";
if (!isRead) return retryableRequest(request, requestOptions, isRead);
const createRetryableRequest = () => {
return retryableRequest(request, requestOptions);
};
const cacheable = requestOptions.cacheable || request.cacheable;
if (cacheable !== true) return createRetryableRequest();
const key = {
request,
requestOptions,
transporter: {
queryParameters: baseQueryParameters,
headers: baseHeaders
}
};
return responsesCache.get(key, () => {
return requestsCache.get(key, () => requestsCache.set(key, createRetryableRequest()).then((response) => Promise.all([requestsCache.delete(key), response]), (err) => Promise.all([requestsCache.delete(key), Promise.reject(err)])).then(([_$3, response]) => response));
}, { miss: (response) => responsesCache.set(key, response) });
}
return {
hostsCache,
requester,
timeouts,
logger,
algoliaAgent,
baseHeaders,
baseQueryParameters,
hosts,
request: createRequest,
requestsCache,
responsesCache
};
}
//#endregion
//#region ../../node_modules/.bun/algoliasearch@5.40.0/node_modules/algoliasearch/dist/lite/builds/browser.js
var apiClientVersion = "5.40.0";
function getDefaultHosts(appId) {
return [{
url: `${appId}-dsn.algolia.net`,
accept: "read",
protocol: "https"
}, {
url: `${appId}.algolia.net`,
accept: "write",
protocol: "https"
}].concat(shuffle([
{
url: `${appId}-1.algolianet.com`,
accept: "readWrite",
protocol: "https"
},
{
url: `${appId}-2.algolianet.com`,
accept: "readWrite",
protocol: "https"
},
{
url: `${appId}-3.algolianet.com`,
accept: "readWrite",
protocol: "https"
}
]));
}
function createLiteClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents,...options }) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(appIdOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "Lite",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
appId: appIdOption,
apiKey: apiKeyOption,
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
get _ua() {
return transporter.algoliaAgent.value;
},
addAlgoliaAgent(segment, version$2) {
transporter.algoliaAgent.add({
segment,
version: version$2
});
},
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") transporter.baseHeaders["x-algolia-api-key"] = apiKey;
else transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
},
searchForHits(searchMethodParams, requestOptions) {
return this.search(searchMethodParams, requestOptions);
},
searchForFacets(searchMethodParams, requestOptions) {
return this.search(searchMethodParams, requestOptions);
},
customPost({ path, parameters, body }, requestOptions) {
if (!path) throw new Error("Parameter `path` is required when calling `customPost`.");
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
getRecommendations(getRecommendationsParams, requestOptions) {
if (getRecommendationsParams && Array.isArray(getRecommendationsParams)) {
const newSignatureRequest = { requests: getRecommendationsParams };
getRecommendationsParams = newSignatureRequest;
}
if (!getRecommendationsParams) throw new Error("Parameter `getRecommendationsParams` is required when calling `getRecommendations`.");
if (!getRecommendationsParams.requests) throw new Error("Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.");
const requestPath = "/1/indexes/*/recommendations";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: getRecommendationsParams,
useReadTransporter: true,
cacheable: true
};
return transporter.request(request, requestOptions);
},
search(searchMethodParams, requestOptions) {
if (searchMethodParams && Array.isArray(searchMethodParams)) {
const newSignatureRequest = { requests: searchMethodParams.map(({ params,...legacyRequest }) => {
if (legacyRequest.type === "facet") return {
...legacyRequest,
...params,
type: "facet"
};
return {
...legacyRequest,
...params,
facet: void 0,
maxFacetHits: void 0,
facetQuery: void 0
};
}) };
searchMethodParams = newSignatureRequest;
}
if (!searchMethodParams) throw new Error("Parameter `searchMethodParams` is required when calling `search`.");
if (!searchMethodParams.requests) throw new Error("Parameter `searchMethodParams.requests` is required when calling `search`.");
const requestPath = "/1/indexes/*/queries";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: searchMethodParams,
useReadTransporter: true,
cacheable: true
};
return transporter.request(request, requestOptions);
}
};
}
function liteClient(appId, apiKey, options) {
if (!appId || typeof appId !== "string") throw new Error("`appId` is missing.");
if (!apiKey || typeof apiKey !== "string") throw new Error("`apiKey` is missing.");
return createLiteClient({
appId,
apiKey,
timeouts: {
connect: 1e3,
read: 2e3,
write: 3e4
},
logger: createNullLogger(),
requester: m$3(),
algoliaAgents: [{ segment: "Browser" }],
authMode: "WithinQueryParameters",
responsesCache: createMemoryCache(),
requestsCache: createMemoryCache({ serializable: false }),
hostsCache: createFallbackableCache({ caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()] }),
...options
});
}
//#endregion
//#region ../../node_modules/.bun/preact@10.27.2/node_modules/preact/dist/preact.module.js
function d$2(n$1, l$2) {
for (var u$3 in l$2) n$1[u$3] = l$2[u$3];
return n$1;
}
function g$2(n$1) {
n$1 && n$1.parentNode && n$1.parentNode.removeChild(n$1);
}
function _$2(l$2, u$3, t$2) {
var i$3, r$2, o$3, e$2 = {};
for (o$3 in u$3) "key" == o$3 ? i$3 = u$3[o$3] : "ref" == o$3 ? r$2 = u$3[o$3] : e$2[o$3] = u$3[o$3];
if (arguments.length > 2 && (e$2.children = arguments.length > 3 ? n.call(arguments, 2) : t$2), "function" == typeof l$2 && null != l$2.defaultProps) for (o$3 in l$2.defaultProps) void 0 === e$2[o$3] && (e$2[o$3] = l$2.defaultProps[o$3]);
return m$2(l$2, e$2, i$3, r$2, null);
}
function m$2(n$1, t$2, i$3, r$2, o$3) {
var e$2 = {
type: n$1,
props: t$2,
key: i$3,
ref: r$2,
__k: null,
__: null,
__b: 0,
__e: null,
__c: null,
constructor: void 0,
__v: null == o$3 ? ++u$2 : o$3,
__i: -1,
__u: 0
};
return null == o$3 && null != l.vnode && l.vnode(e$2), e$2;
}
function b$1() {
return { current: null };
}
function k$1(n$1) {
return n$1.children;
}
function x$2(n$1, l$2) {
this.props = n$1, this.context = l$2;
}
function S$1(n$1, l$2) {
if (null == l$2) return n$1.__ ? S$1(n$1.__, n$1.__i + 1) : null;
for (var u$3; l$2 < n$1.__k.length; l$2++) if (null != (u$3 = n$1.__k[l$2]) && null != u$3.__e) return u$3.__e;
return "function" == typeof n$1.type ? S$1(n$1) : null;
}
function C$3(n$1) {
var l$2, u$3;
if (null != (n$1 = n$1.__) && null != n$1.__c) {
for (n$1.__e = n$1.__c.base = null, l$2 = 0; l$2 < n$1.__k.length; l$2++) if (null != (u$3 = n$1.__k[l$2]) && null != u$3.__e) {
n$1.__e = n$1.__c.base = u$3.__e;
break;
}
return C$3(n$1);
}
}
function M$2(n$1) {
(!n$1.__d && (n$1.__d = !0) && i$2.push(n$1) && !$$2.__r++ || r$1 != l.debounceRendering) && ((r$1 = l.debounceRendering) || o$2)($$2);
}
function $$2() {
for (var n$1, u$3, t$2, r$2, o$3, f$3, c$2, s$2 = 1; i$2.length;) i$2.length > s$2 && i$2.sort(e$1), n$1 = i$2.shift(), s$2 = i$2.length, n$1.__d && (t$2 = void 0, r$2 = void 0, o$3 = (r$2 = (u$3 = n$1).__v).__e, f$3 = [], c$2 = [], u$3.__P && ((t$2 = d$2({}, r$2)).__v = r$2.__v + 1, l.vnode && l.vnode(t$2), O$1(u$3.__P, t$2, r$2, u$3.__n, u$3.__P.namespaceURI, 32 & r$2.__u ? [o$3] : null, f$3, null == o$3 ? S$1(r$2) : o$3, !!(32 & r$2.__u), c$2), t$2.__v = r$2.__v, t$2.__.__k[t$2.__i] = t$2, N$2(f$3, t$2, c$2), r$2.__e = r$2.__ = null, t$2.__e != o$3 && C$3(t$2)));
$$2.__r = 0;
}
function I$2(n$1, l$2, u$3, t$2, i$3, r$2, o$3, e$2, f$3, c$2, s$2) {
var a$2, h$2, y$3, w$4, d$3, g$3, _$3, m$4 = t$2 && t$2.__k || v$2, b$3 = l$2.length;
for (f$3 = P$3(u$3, l$2, m$4, f$3, b$3), a$2 = 0; a$2 < b$3; a$2++) null != (y$3 = u$3.__k[a$2]) && (h$2 = -1 == y$3.__i ? p$1 : m$4[y$3.__i] || p$1, y$3.__i = a$2, g$3 = O$1(n$1, y$3, h$2, i$3, r$2, o$3, e$2, f$3, c$2, s$2), w$4 = y$3.__e, y$3.ref && h$2.ref != y$3.ref && (h$2.ref && B$3(h$2.ref, null, y$3), s$2.push(y$3.ref, y$3.__c || w$4, y$3)), null == d$3 && null != w$4 && (d$3 = w$4), (_$3 = !!(4 & y$3.__u)) || h$2.__k === y$3.__k ? f$3 = A$2(y$3, f$3, n$1, _$3) : "function" == typeof y$3.type && void 0 !== g$3 ? f$3 = g$3 : w$4 && (f$3 = w$4.nextSibling), y$3.__u &= -7);
return u$3.__e = d$3, f$3;
}
function P$3(n$1, l$2, u$3, t$2, i$3) {
var r$2, o$3, e$2, f$3, c$2, s$2 = u$3.length, a$2 = s$2, h$2 = 0;
for (n$1.__k = new Array(i$3), r$2 = 0; r$2 < i$3; r$2++) null != (o$3 = l$2[r$2]) && "boolean" != typeof o$3 && "function" != typeof o$3 ? (f$3 = r$2 + h$2, (o$3 = n$1.__k[r$2] = "string" == typeof o$3 || "number" == typeof o$3 || "bigint" == typeof o$3 || o$3.constructor == String ? m$2(null, o$3, null, null, null) : w$3(o$3) ? m$2(k$1, { children: o$3 }, null, null, null) : null == o$3.constructor && o$3.__b > 0 ? m$2(o$3.type, o$3.props, o$3.key, o$3.ref ? o$3.ref : null, o$3.__v) : o$3).__ = n$1, o$3.__b = n$1.__b + 1, e$2 = null, -1 != (c$2 = o$3.__i = L$2(o$3, u$3, f$3, a$2)) && (a$2--, (e$2 = u$3[c$2]) && (e$2.__u |= 2)), null == e$2 || null == e$2.__v ? (-1 == c$2 && (i$3 > s$2 ? h$2-- : i$3 < s$2 && h$2++), "function" != typeof o$3.type && (o$3.__u |= 4)) : c$2 != f$3 && (c$2 == f$3 - 1 ? h$2-- : c$2 == f$3 + 1 ? h$2++ : (c$2 > f$3 ? h$2-- : h$2++, o$3.__u |= 4))) : n$1.__k[r$2] = null;
if (a$2) for (r$2 = 0; r$2 < s$2; r$2++) null != (e$2 = u$3[r$2]) && 0 == (2 & e$2.__u) && (e$2.__e == t$2 && (t$2 = S$1(e$2)), D$3(e$2, e$2));
return t$2;
}
function A$2(n$1, l$2, u$3, t$2) {
var i$3, r$2;
if ("function" == typeof n$1.type) {
for (i$3 = n$1.__k, r$2 = 0; i$3 && r$2 < i$3.length; r$2++) i$3[r$2] && (i$3[r$2].__ = n$1, l$2 = A$2(i$3[r$2], l$2, u$3, t$2));
return l$2;
}
n$1.__e != l$2 && (t$2 && (l$2 && n$1.type && !l$2.parentNode && (l$2 = S$1(n$1)), u$3.insertBefore(n$1.__e, l$2 || null)), l$2 = n$1.__e);
do
l$2 = l$2 && l$2.nextSibling;
while (null != l$2 && 8 == l$2.nodeType);
return l$2;
}
function H(n$1, l$2) {
return l$2 = l$2 || [], null == n$1 || "boolean" == typeof n$1 || (w$3(n$1) ? n$1.some(function(n$2) {
H(n$2, l$2);
}) : l$2.push(n$1)), l$2;
}
function L$2(n$1, l$2, u$3, t$2) {
var i$3, r$2, o$3, e$2 = n$1.key, f$3 = n$1.type, c$2 = l$2[u$3], s$2 = null != c$2 && 0 == (2 & c$2.__u);
if (null === c$2 && null == n$1.key || s$2 && e$2 == c$2.key && f$3 == c$2.type) return u$3;
if (t$2 > (s$2 ? 1 : 0)) {
for (i$3 = u$3 - 1, r$2 = u$3 + 1; i$3 >= 0 || r$2 < l$2.length;) if (null != (c$2 = l$2[o$3 = i$3 >= 0 ? i$3-- : r$2++]) && 0 == (2 & c$2.__u) && e$2 == c$2.key && f$3 == c$2.type) return o$3;
}
return -1;
}
function T$3(n$1, l$2, u$3) {
"-" == l$2[0] ? n$1.setProperty(l$2, null == u$3 ? "" : u$3) : n$1[l$2] = null == u$3 ? "" : "number" != typeof u$3 || y$2.test(l$2) ? u$3 : u$3 + "px";
}
function j$3(n$1, l$2, u$3, t$2, i$3) {
var r$2, o$3;
n: if ("style" == l$2) if ("string" == typeof u$3) n$1.style.cssText = u$3;
else {
if ("string" == typeof t$2 && (n$1.style.cssText = t$2 = ""), t$2) for (l$2 in t$2) u$3 && l$2 in u$3 || T$3(n$1.style, l$2, "");
if (u$3) for (l$2 in u$3) t$2 && u$3[l$2] == t$2[l$2] || T$3(n$1.style, l$2, u$3[l$2]);
}
else if ("o" == l$2[0] && "n" == l$2[1]) r$2 = l$2 != (l$2 = l$2.replace(f$2, "$1")), o$3 = l$2.toLowerCase(), l$2 = o$3 in n$1 || "onFocusOut" == l$2 || "onFocusIn" == l$2 ? o$3.slice(2) : l$2.slice(2), n$1.l || (n$1.l = {}), n$1.l[l$2 + r$2] = u$3, u$3 ? t$2 ? u$3.u = t$2.u : (u$3.u = c$1, n$1.addEventListener(l$2, r$2 ? a$1 : s$1, r$2)) : n$1.removeEventListener(l$2, r$2 ? a$1 : s$1, r$2);
else {
if ("http://www.w3.org/2000/svg" == i$3) l$2 = l$2.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
else if ("width" != l$2 && "height" != l$2 && "href" != l$2 && "list" != l$2 && "form" != l$2 && "tabIndex" != l$2 && "download" != l$2 && "rowSpan" != l$2 && "colSpan" != l$2 && "role" != l$2 && "popover" != l$2 && l$2 in n$1) try {
n$1[l$2] = null == u$3 ? "" : u$3;
break n;
} catch (n$2) {}
"function" == typeof u$3 || (null == u$3 || !1 === u$3 && "-" != l$2[4] ? n$1.removeAttribute(l$2) : n$1.setAttribute(l$2, "popover" == l$2 && 1 == u$3 ? "" : u$3));
}
}
function F$3(n$1) {
return function(u$3) {
if (this.l) {
var t$2 = this.l[u$3.type + n$1];
if (null == u$3.t) u$3.t = c$1++;
else if (u$3.t < t$2.u) return;
return t$2(l.event ? l.event(u$3) : u$3);
}
};
}
function O$1(n$1, u$3, t$2, i$3, r$2, o$3, e$2, f$3, c$2, s$2) {
var a$2, h$2, p$2, v$3, y$3, _$3, m$4, b$3, S$2, C$4, M$3, $$3, P$4, A$3, H$2, L$3, T$4, j$4 = u$3.type;
if (null != u$3.constructor) return null;
128 & t$2.__u && (c$2 = !!(32 & t$2.__u), o$3 = [f$3 = u$3.__e = t$2.__e]), (a$2 = l.__b) && a$2(u$3);
n: if ("function" == typeof j$4) try {
if (b$3 = u$3.props, S$2 = "prototype" in j$4 && j$4.prototype.render, C$4 = (a$2 = j$4.contextType) && i$3[a$2.__c], M$3 = a$2 ? C$4 ? C$4.props.value : a$2.__ : i$3, t$2.__c ? m$4 = (h$2 = u$3.__c = t$2.__c).__ = h$2.__E : (S$2 ? u$3.__c = h$2 = new j$4(b$3, M$3) : (u$3.__c = h$2 = new x$2(b$3, M$3), h$2.constructor = j$4, h$2.render = E$2), C$4 && C$4.sub(h$2), h$2.props = b$3, h$2.state || (h$2.state = {}), h$2.context = M$3, h$2.__n = i$3, p$2 = h$2.__d = !0, h$2.__h = [], h$2._sb = []), S$2 && null == h$2.__s && (h$2.__s = h$2.state), S$2 && null != j$4.getDerivedStateFromProps && (h$2.__s == h$2.state && (h$2.__s = d$2({}, h$2.__s)), d$2(h$2.__s, j$4.getDerivedStateFromProps(b$3, h$2.__s))), v$3 = h$2.props, y$3 = h$2.state, h$2.__v = u$3, p$2) S$2 && null == j$4.getDerivedStateFromProps && null != h$2.componentWillMount && h$2.componentWillMount(), S$2 && null != h$2.componentDidMount && h$2.__h.push(h$2.componentDidMount);
else {
if (S$2 && null == j$4.getDerivedStateFromProps && b$3 !== v$3 && null != h$2.componentWillReceiveProps && h$2.componentWillReceiveProps(b$3, M$3), !h$2.__e && null != h$2.shouldComponentUpdate && !1 === h$2.shouldComponentUpdate(b$3, h$2.__s, M$3) || u$3.__v == t$2.__v) {
for (u$3.__v != t$2.__v && (h$2.props = b$3, h$2.state = h$2.__s, h$2.__d = !1), u$3.__e = t$2.__e, u$3.__k = t$2.__k, u$3.__k.some(function(n$2) {
n$2 && (n$2.__ = u$3);
}), $$3 = 0; $$3 < h$2._sb.length; $$3++) h$2.__h.push(h$2._sb[$$3]);
h$2._sb = [], h$2.__h.length && e$2.push(h$2);
break n;
}
null != h$2.componentWillUpdate && h$2.componentWillUpdate(b$3, h$2.__s, M$3), S$2 && null != h$2.componentDidUpdate && h$2.__h.push(function() {
h$2.componentDidUpdate(v$3, y$3, _$3);
});
}
if (h$2.context = M$3, h$2.props = b$3, h$2.__P = n$1, h$2.__e = !1, P$4 = l.__r, A$3 = 0, S$2) {
for (h$2.state = h$2.__s, h$2.__d = !1, P$4 && P$4(u$3), a$2 = h$2.render(h$2.props, h$2.state, h$2.context), H$2 = 0; H$2 < h$2._sb.length; H$2++) h$2.__h.push(h$2._sb[H$2]);
h$2._sb = [];
} else do
h$2.__d = !1, P$4 && P$4(u$3), a$2 = h$2.render(h$2.props, h$2.state, h$2.context), h$2.state = h$2.__s;
while (h$2.__d && ++A$3 < 25);
h$2.state = h$2.__s, null != h$2.getChildContext && (i$3 = d$2(d$2({}, i$3), h$2.getChildContext())), S$2 && !p$2 && null != h$2.getSnapshotBeforeUpdate && (_$3 = h$2.getSnapshotBeforeUpdate(v$3, y$3)), L$3 = a$2, null != a$2 && a$2.type === k$1 && null == a$2.key && (L$3 = V$2(a$2.props.children)), f$3 = I$2(n$1, w$3(L$3) ? L$3 : [L$3], u$3, t$2, i$3, r$2, o$3, e$2, f$3, c$2, s$2), h$2.base = u$3.__e, u$3.__u &= -161, h$2.__h.length && e$2.push(h$2), m$4 && (h$2.__E = h$2.__ = null);
} catch (n$2) {
if (u$3.__v = null, c$2 || null != o$3) if (n$2.then) {
for (u$3.__u |= c$2 ? 160 : 128; f$3 && 8 == f$3.nodeType && f$3.nextSibling;) f$3 = f$3.nextSibling;
o$3[o$3.indexOf(f$3)] = null, u$3.__e = f$3;
} else {
for (T$4 = o$3.length; T$4--;) g$2(o$3[T$4]);
z$3(u$3);
}
else u$3.__e = t$2.__e, u$3.__k = t$2.__k, n$2.then || z$3(u$3);
l.__e(n$2, u$3, t$2);
}
else null == o$3 && u$3.__v == t$2.__v ? (u$3.__k = t$2.__k, u$3.__e = t$2.__e) : f$3 = u$3.__e = q$3(t$2.__e, u$3, t$2, i$3, r$2, o$3, e$2, c$2, s$2);
return (a$2 = l.diffed) && a$2(u$3), 128 & u$3.__u ? void 0 : f$3;
}
function z$3(n$1) {
n$1 && n$1.__c && (n$1.__c.__e = !0), n$1 && n$1.__k && n$1.__k.forEach(z$3);
}
function N$2(n$1, u$3, t$2) {
for (var i$3 = 0; i$3 < t$2.length; i$3++) B$3(t$2[i$3], t$2[++i$3], t$2[++i$3]);
l.__c && l.__c(u$3, n$1), n$1.some(function(u$4) {
try {
n$1 = u$4.__h, u$4.__h = [], n$1.some(function(n$2) {
n$2.call(u$4);
});
} catch (n$2) {
l.__e(n$2, u$4.__v);
}
});
}
function V$2(n$1) {
return "object" != typeof n$1 || null == n$1 || n$1.__b && n$1.__b > 0 ? n$1 : w$3(n$1) ? n$1.map(V$2) : d$2({}, n$1);
}
function q$3(u$3, t$2, i$3, r$2, o$3, e$2, f$3, c$2, s$2) {
var a$2, h$2, v$3, y$3, d$3, _$3, m$4, b$3 = i$3.props, k$4 = t$2.props, x$4 = t$2.type;
if ("svg" == x$4 ? o$3 = "http://www.w3.org/2000/svg" : "math" == x$4 ? o$3 = "http://www.w3.org/1998/Math/MathML" : o$3 || (o$3 = "http://www.w3.org/1999/xhtml"), null != e$2) {
for (a$2 = 0; a$2 < e$2.length; a$2++) if ((d$3 = e$2[a$2]) && "setAttribute" in d$3 == !!x$4 && (x$4 ? d$3.localName == x$4 : 3 == d$3.nodeType)) {
u$3 = d$3, e$2[a$2] = null;
break;
}
}
if (null == u$3) {
if (null == x$4) return document.createTextNode(k$4);
u$3 = document.createElementNS(o$3, x$4, k$4.is && k$4), c$2 && (l.__m && l.__m(t$2, e$2), c$2 = !1), e$2 = null;
}
if (null == x$4) b$3 === k$4 || c$2 && u$3.data == k$4 || (u$3.data = k$4);
else {
if (e$2 = e$2 && n.call(u$3.childNodes), b$3 = i$3.props || p$1, !c$2 && null != e$2) for (b$3 = {}, a$2 = 0; a$2 < u$3.attributes.length; a$2++) b$3[(d$3 = u$3.attributes[a$2]).name] = d$3.value;
for (a$2 in b$3) if (d$3 = b$3[a$2], "children" == a$2);
else if ("dangerouslySetInnerHTML" == a$2) v$3 = d$3;
else if (!(a$2 in k$4)) {
if ("value" == a$2 && "defaultValue" in k$4 || "checked" == a$2 && "defaultChecked" in k$4) continue;
j$3(u$3, a$2, null, d$3, o$3);
}
for (a$2 in k$4) d$3 = k$4[a$2], "children" == a$2 ? y$3 = d$3 : "dangerouslySetInnerHTML" == a$2 ? h$2 = d$3 : "value" == a$2 ? _$3 = d$3 : "checked" == a$2 ? m$4 = d$3 : c$2 && "function" != typeof d$3 || b$3[a$2] === d$3 || j$3(u$3, a$2, d$3, b$3[a$2], o$3);
if (h$2) c$2 || v$3 && (h$2.__html == v$3.__html || h$2.__html == u$3.innerHTML) || (u$3.innerHTML = h$2.__html), t$2.__k = [];
else if (v$3 && (u$3.innerHTML = ""), I$2("template" == t$2.type ? u$3.content : u$3, w$3(y$3) ? y$3 : [y$3], t$2, i$3, r$2, "foreignObject" == x$4 ? "http://www.w3.org/1999/xhtml" : o$3, e$2, f$3, e$2 ? e$2[0] : i$3.__k && S$1(i$3, 0), c$2, s$2), null != e$2) for (a$2 = e$2.length; a$2--;) g$2(e$2[a$2]);
c$2 || (a$2 = "value", "progress" == x$4 && null == _$3 ? u$3.removeAttribute("value") : null != _$3 && (_$3 !== u$3[a$2] || "progress" == x$4 && !_$3 || "option" == x$4 && _$3 != b$3[a$2]) && j$3(u$3, a$2, _$3, b$3[a$2], o$3), a$2 = "checked", null != m$4 && m$4 != u$3[a$2] && j$3(u$3, a$2, m$4, b$3[a$2], o$3));
}
return u$3;
}
function B$3(n$1, u$3, t$2) {
try {
if ("function" == typeof n$1) {
var i$3 = "function" == typeof n$1.__u;
i$3 && n$1.__u(), i$3 && null == u$3 || (n$1.__u = n$1(u$3));
} else n$1.current = u$3;
} catch (n$2) {
l.__e(n$2, t$2);
}
}
function D$3(n$1, u$3, t$2) {
var i$3, r$2;
if (l.unmount && l.unmount(n$1), (i$3 = n$1.ref) && (i$3.current && i$3.current != n$1.__e || B$3(i$3, null, u$3)), null != (i$3 = n$1.__c)) {
if (i$3.componentWillUnmount) try {
i$3.componentWillUnmount();
} catch (n$2) {
l.__e(n$2, u$3);
}
i$3.base = i$3.__P = null;
}
if (i$3 = n$1.__k) for (r$2 = 0; r$2 < i$3.length; r$2++) i$3[r$2] && D$3(i$3[r$2], u$3, t$2 || "function" != typeof n$1.type);
t$2 || g$2(n$1.__e), n$1.__c = n$1.__ = n$1.__e = void 0;
}
function E$2(n$1, l$2, u$3) {
return this.constructor(n$1, u$3);
}
function G$1(u$3, t$2, i$3) {
var r$2, o$3, e$2, f$3;
t$2 == document && (t$2 = document.documentElement), l.__ && l.__(u$3, t$2), o$3 = (r$2 = "function" == typeof i$3) ? null : i$3 && i$3.__k || t$2.__k, e$2 = [], f$3 = [], O$1(t$2, u$3 = (!r$2 && i$3 || t$2).__k = _$2(k$1, null, [u$3]), o$3 || p$1, p$1, t$2.namespaceURI, !r$2 && i$3 ? [i$3] : o$3 ? null : t$2.firstChild ? n.call(t$2.childNodes) : null, e$2, !r$2 && i$3 ? i$3 : o$3 ? o$3.__e : t$2.firstChild, r$2, f$3), N$2(e$2, u$3, f$3);
}
function J$1(n$1, l$2) {
G$1(n$1, l$2, J$1);
}
function K$1(l$2, u$3, t$2) {
var i$3, r$2, o$3, e$2, f$3 = d$2({}, l$2.props);
for (o$3 in l$2.type && l$2.type.defaultProps && (e$2 = l$2.type.defaultProps), u$3) "key" == o$3 ? i$3 = u$3[o$3] : "ref" == o$3 ? r$2 = u$3[o$3] : f$3[o$3] = void 0 === u$3[o$3] && null != e$2 ? e$2[o$3] : u$3[o$3];
return arguments.length > 2 && (f$3.children = arguments.length > 3 ? n.call(arguments, 2) : t$2), m$2(l$2.type, f$3, i$3 || l$2.key, r$2 || l$2.ref, null);
}
function Q$1(n$1) {
function l$2(n$2) {
var u$3, t$2;
return this.getChildContext || (u$3 = new Set(), (t$2 = {})[l$2.__c] = this, this.getChildContext = function() {
return t$2;
}, this.componentWillUnmount = function() {
u$3 = null;
}, this.shouldComponentUpdate = function(n$3) {
this.props.value != n$3.value && u$3.forEach(function(n$4) {
n$4.__e = !0, M$2(n$4);
});
}, this.sub = function(n$3) {
u$3.add(n$3);
var l$3 = n$3.componentWillUnmount;
n$3.componentWillUnmount = function() {
u$3 && u$3.delete(n$3), l$3 && l$3.call(n$3);
};
}), n$2.children;
}
return l$2.__c = "__cC" + h$1++, l$2.__ = n$1, l$2.Provider = l$2.__l = (l$2.Consumer = function(n$2, l$3) {
return n$2.children(l$3);
}).contextType = l$2, l$2;
}
var n, l, u$2, t$1, i$2, r$1, o$2, e$1, f$2, c$1, s$1, a$1, h$1, p$1, v$2, y$2, w$3;
var init_preact_module = __esm({ "../../node_modules/.bun/preact@10.27.2/node_modules/preact/dist/preact.module.js"() {
p$1 = {}, v$2 = [], y$2 = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, w$3 = Array.isArray;
n = v$2.slice, l = { __e: function(n$1, l$2, u$3, t$2) {
for (var i$3, r$2, o$3; l$2 = l$2.__;) if ((i$3 = l$2.__c) && !i$3.__) try {
if ((r$2 = i$3.constructor) && null != r$2.getDerivedStateFromError && (i$3.setState(r$2.getDerivedStateFromError(n$1)), o$3 = i$3.__d), null != i$3.componentDidCatch && (i$3.componentDidCatch(n$1, t$2 || {}), o$3 = i$3.__d), o$3) return i$3.__E = i$3;
} catch (l$3) {
n$1 = l$3;
}
throw n$1;
} }, u$2 = 0, t$1 = function(n$1) {
return null != n$1 && null == n$1.constructor;
}, x$2.prototype.setState = function(n$1, l$2) {
var u$3;
u$3 = null != this.__s && this.__s != this.state ? this.__s : this.__s = d$2({}, this.state), "function" == typeof n$1 && (n$1 = n$1(d$2({}, u$3), this.props)), n$1 && d$2(u$3, n$1), null != n$1 && this.__v && (l$2 && this._sb.push(l$2), M$2(this));
}, x$2.prototype.forceUpdate = function(n$1) {
this.__v && (this.__e = !0, n$1 && this.__h.push(n$1), M$2(this));
}, x$2.prototype.render = k$1, i$2 = [], o$2 = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, e$1 = function(n$1, l$2) {
return n$1.__v.__b - l$2.__v.__b;
}, $$2.__r = 0, f$2 = /(PointerCapture)$|Capture$/i, c$1 = 0, s$1 = F$3(!1), a$1 = F$3(!0), h$1 = 0;
} });
//#endregion
//#region ../../node_modules/.bun/preact@10.27.2/node_modules/preact/hooks/dist/hooks.module.js
function p(n$1, t$2) {
c.__h && c.__h(r, n$1, o$1 || t$2), o$1 = 0;
var u$3 = r.__H || (r.__H = {
__: [],
__h: []
});
return n$1 >= u$3.__.length && u$3.__.push({}), u$3.__[n$1];
}
function d(n$1) {
return o$1 = 1, h(D$2, n$1);
}
function h(n$1, u$3, i$3) {
var o$3 = p(t++, 2);
if (o$3.t = n$1, !o$3.__c && (o$3.__ = [i$3 ? i$3(u$3) : D$2(void 0, u$3), function(n$2) {
var t$2 = o$3.__N ? o$3.__N[0] : o$3.__[0], r$2 = o$3.t(t$2, n$2);
t$2 !== r$2 && (o$3.__N = [r$2, o$3.__[1]], o$3.__c.setState({}));
}], o$3.__c = r, !r.__f)) {
var f$3 = function(n$2, t$2, r$2) {
if (!o$3.__c.__H) return !0;
var u$4 = o$3.__c.__H.__.filter(function(n$3) {
return !!n$3.__c;
});
if (u$4.every(function(n$3) {
return !n$3.__N;
})) return !c$2 || c$2.call(this, n$2, t$2, r$2);
var i$4 = o$3.__c.props !== n$2;
return u$4.forEach(function(n$3) {
if (n$3.__N) {
var t$3 = n$3.__[0];
n$3.__ = n$3.__N, n$3.__N = void 0, t$3 !== n$3.__[0] && (i$4 = !0);
}
}), c$2 && c$2.call(this, n$2, t$2, r$2) || i$4;
};
r.__f = !0;
var c$2 = r.shouldComponentUpdate, e$2 = r.componentWillUpdate;
r.componentWillUpdate = function(n$2, t$2, r$2) {
if (this.__e) {
var u$4 = c$2;
c$2 = void 0, f$3(n$2, t$2, r$2), c$2 = u$4;
}
e$2 && e$2.call(this, n$2, t$2, r$2);
}, r.shouldComponentUpdate = f$3;
}
return o$3.__N || o$3.__;
}
function y(n$1, u$3) {
var i$3 = p(t++, 3);
!c.__s && C$2(i$3.__H, u$3) && (i$3.__ = n$1, i$3.u = u$3, r.__H.__h.push(i$3));
}
function _(n$1, u$3) {
var i$3 = p(t++, 4);
!c.__s && C$2(i$3.__H, u$3) && (i$3.__ = n$1, i$3.u = u$3, r.__h.push(i$3));
}
function A(n$1) {
return o$1 = 5, T(function() {
return { current: n$1 };
}, []);
}
function F$1(n$1, t$2, r$2) {
o$1 = 6, _(function() {
if ("function" == typeof n$1) {
var r$3 = n$1(t$2());
return function() {
n$1(null), r$3 && "function" == typeof r$3 && r$3();
};
}
if (n$1) return n$1.current = t$2(), function() {
return n$1.current = null;
};
}, null == r$2 ? r$2 : r$2.concat(n$1));
}
function T(n$1, r$2) {
var u$3 = p(t++, 7);
return C$2(u$3.__H, r$2) && (u$3.__ = n$1(), u$3.__H = r$2, u$3.__h = n$1), u$3.__;
}
function q(n$1, t$2) {
return o$1 = 8, T(function() {
return n$1;
}, t$2);
}
function x$1(n$1) {
var u$3 = r.context[n$1.__c], i$3 = p(t++, 9);
return i$3.c = n$1, u$3 ? (i$3.__ ?? (i$3.__ = !0, u$3.sub(r)), u$3.props.value) : n$1.__;
}
function P$1(n$1, t$2) {
c.useDebugValue && c.useDebugValue(t$2 ? t$2(n$1) : n$1);
}
function b$2(n$1) {
var u$3 = p(t++, 10), i$3 = d();
return u$3.__ = n$1, r.componentDidCatch || (r.componentDidCatch = function(n$2, t$2) {
u$3.__ && u$3.__(n$2, t$2), i$3[1](n$2);
}), [i$3[0], function() {
i$3[1](void 0);
}];
}
function g() {
var n$1 = p(t++, 11);
if (!n$1.__) {
for (var u$3 = r.__v; null !== u$3 && !u$3.__m && null !== u$3.__;) u$3 = u$3.__;
var i$3 = u$3.__m || (u$3.__m = [0, 0]);
n$1.__ = "P" + i$3[0] + "-" + i$3[1]++;
}
return n$1.__;
}
function j$2() {
for (var n$1; n$1 = f$1.shift();) if (n$1.__P && n$1.__H) try {
n$1.__H.__h.forEach(z$2), n$1.__H.__h.forEach(B$2), n$1.__H.__h = [];
} catch (t$2) {
n$1.__H.__h = [], c.__e(t$2, n$1.__v);
}
}
function w$2(n$1) {
var t$2, r$2 = function() {
clearTimeout(u$3), k$3 && cancelAnimationFrame(t$2), setTimeout(n$1);
}, u$3 = setTimeout(r$2, 35);
k$3 && (t$2 = requestAnimationFrame(r$2));
}
function z$2(n$1) {
var t$2 = r, u$3 = n$1.__c;
"function" == typeof u$3 && (n$1.__c = void 0, u$3()), r = t$2;
}
function B$2(n$1) {
var t$2 = r;
n$1.__c = n$1.__(), r = t$2;
}
function C$2(n$1, t$2) {
return !n$1 || n$1.length !== t$2.length || t$2.some(function(t$3, r$2) {
return t$3 !== n$1[r$2];
});
}
function D$2(n$1, t$2) {
return "function" == typeof t$2 ? t$2(n$1) : t$2;
}
var t, r, u$1, i$1, o$1, f$1, c, e, a, v$1, l$1, m$1, s, k$3;
var init_hooks_module = __esm({ "../../node_modules/.bun/preact@10.27.2/node_modules/preact/hooks/dist/hooks.module.js"() {
init_preact_module();
o$1 = 0, f$1 = [], c = l, e = c.__b, a = c.__r, v$1 = c.diffed, l$1 = c.__c, m$1 = c.unmount, s = c.__;
c.__b = function(n$1) {
r = null, e && e(n$1);
}, c.__ = function(n$1, t$2) {
n$1 && t$2.__k && t$2.__k.__m && (n$1.__m = t$2.__k.__m), s && s(n$1, t$2);
}, c.__r = function(n$1) {
a && a(n$1), t = 0;
var i$3 = (r = n$1.__c).__H;
i$3 && (u$1 === r ? (i$3.__h = [], r.__h = [], i$3.__.forEach(function(n$2) {
n$2.__N && (n$2.__ = n$2.__N), n$2.u = n$2.__N = void 0;
})) : (i$3.__h.forEach(z$2), i$3.__h.forEach(B$2), i$3.__h = [], t = 0)), u$1 = r;
}, c.diffed = function(n$1) {
v$1 && v$1(n$1);
var t$2 = n$1.__c;
t$2 && t$2.__H && (t$2.__H.__h.length && (1 !== f$1.push(t$2) && i$1 === c.requestAnimationFrame || ((i$1 = c.requestAnimationFrame) || w$2)(j$2)), t$2.__H.__.forEach(function(n$2) {
n$2.u && (n$2.__H = n$2.u), n$2.u = void 0;
})), u$1 = r = null;
}, c.__c = function(n$1, t$2) {
t$2.some(function(n$2) {
try {
n$2.__h.forEach(z$2), n$2.__h = n$2.__h.filter(function(n$3) {
return !n$3.__ || B$2(n$3);
});
} catch (r$2) {
t$2.some(function(n$3) {
n$3.__h && (n$3.__h = []);
}), t$2 = [], c.__e(r$2, n$2.__v);
}
}), l$1 && l$1(n$1, t$2);
}, c.unmount = function(n$1) {
m$1 && m$1(n$1);
var t$2, r$2 = n$1.__c;
r$2 && r$2.__H && (r$2.__H.__.forEach(function(n$2) {
try {
z$2(n$2);
} catch (n$3) {
t$2 = n$3;
}
}), r$2.__H = void 0, t$2 && c.__e(t$2, r$2.__v));
};
k$3 = "function" == typeof requestAnimationFrame;
} });
//#endregion
//#region ../../node_modules/.bun/preact@10.27.2/node_modules/preact/compat/dist/compat.module.js
var compat_module_exports = {};
__export$1(compat_module_exports, {
Children: () => O,
Component: () => x$2,
Fragment: () => k$1,
PureComponent: () => N$1,
StrictMode: () => Cn,
Suspense: () => P$2,
SuspenseList: () => B$1,
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: () => hn,
cloneElement: () => _n,
createContext: () => Q$1,
createElement: () => _$2,
createFactory: () => dn,
createPortal: () => $,
createRef: () => b$1,
default: () => Rn,
findDOMNode: () => Sn,
flushSync: () => En,
forwardRef: () => D$1,
hydrate: () => tn,
isElement: () => xn,
isFragment: () => pn,
isMemo: () => yn,
isValidElement: () => mn,
lazy: () => z$1,
memo: () => M,
render: () => nn,
startTransition: () => R,
unmountComponentAtNode: () => bn,
unstable_batchedUpdates: () => gn,
useCallback: () => q,
useContext: () => x$1,
useDebugValue: () => P$1,
useDeferredValue: () => w$1,
useEffect: () => y,
useErrorBoundary: () => b$2,
useId: () => g,
useImperativeHandle: () => F$1,
useInsertionEffect: () => I$1,
useLayoutEffect: () => _,
useMemo: () => T,
useReducer: () => h,
useRef: () => A,
useState: () => d,
useSyncExternalStore: () => C$1,
useTransition: () => k$2,
version: () => vn
});
function g$1(n$1, t$2) {
for (var e$2 in t$2) n$1[e$2] = t$2[e$2];
return n$1;
}
function E$1(n$1, t$2) {
for (var e$2 in n$1) if ("__source" !== e$2 && !(e$2 in t$2)) return !0;
for (var r$2 in t$2) if ("__source" !== r$2 && n$1[r$2] !== t$2[r$2]) return !0;
return !1;
}
function C$1(n$1, t$2) {
var e$2 = t$2(), r$2 = d({ t: {
__: e$2,
u: t$2
} }), u$3 = r$2[0].t, o$3 = r$2[1];
return _(function() {
u$3.__ = e$2, u$3.u = t$2, x$3(u$3) && o$3({ t: u$3 });
}, [
n$1,
e$2,
t$2
]), y(function() {
return x$3(u$3) && o$3({ t: u$3 }), n$1(function() {
x$3(u$3) && o$3({ t: u$3 });
});
}, [n$1]), e$2;
}
function x$3(n$1) {
var t$2, e$2, r$2 = n$1.u, u$3 = n$1.__;
try {
var o$3 = r$2();
return !((t$2 = u$3) === (e$2 = o$3) && (0 !== t$2 || 1 / t$2 == 1 / e$2) || t$2 != t$2 && e$2 != e$2);
} catch (n$2) {
return !0;
}
}
function R(n$1) {
n$1();
}
function w$1(n$1) {
return n$1;
}
function k$2() {
return [!1, R];
}
function N$1(n$1, t$2) {
this.props = n$1, this.context = t$2;
}
function M(n$1, e$2) {
function r$2(n$2) {
var t$2 = this.props.ref, r$3 = t$2 == n$2.ref;
return !r$3 && t$2 && (t$2.call ? t$2(null) : t$2.current = null), e$2 ? !e$2(this.props, n$2) || !r$3 : E$1(this.props, n$2);
}
function u$3(e$3) {
return this.shouldComponentUpdate = r$2, _$2(n$1, e$3);
}
return u$3.displayName = "Memo(" + (n$1.displayName || n$1.name) + ")", u$3.prototype.isReactComponent = !0, u$3.__f = !0, u$3.type = n$1, u$3;
}
function D$1(n$1) {
function t$2(t$3) {
var e$2 = g$1({}, t$3);
return delete e$2.ref, n$1(e$2, t$3.ref || null);
}
return t$2.$$typeof = A$1, t$2.render = n$1, t$2.prototype.isReactComponent = t$2.__f = !0, t$2.displayName = "ForwardRef(" + (n$1.displayName || n$1.name) + ")", t$2;
}
function V$1(n$1, t$2, e$2) {
return n$1 && (n$1.__c && n$1.__c.__H && (n$1.__c.__H.__.forEach(function(n$2) {
"function" == typeof n$2.__c && n$2.__c();
}), n$1.__c.__H = null), null != (n$1 = g$1({}, n$1)).__c && (n$1.__c.__P === e$2 && (n$1.__c.__P = t$2), n$1.__c.__e = !0, n$1.__c = null), n$1.__k = n$1.__k && n$1.__k.map(function(n$2) {
return V$1(n$2, t$2, e$2);
})), n$1;
}
function W$1(n$1, t$2, e$2) {
return n$1 && e$2 && (n$1.__v = null, n$1.__k = n$1.__k && n$1.__k.map(function(n$2) {
return W$1(n$2, t$2, e$2);
}), n$1.__c && n$1.__c.__P === t$2 && (n$1.__e && e$2.appendChild(n$1.__e), n$1.__c.__e = !0, n$1.__c.__P = e$2)), n$1;
}
function P$2() {
this.__u = 0, this.o = null, this.__b = null;
}
function j$1(n$1) {
var t$2 = n$1.__.__c;
return t$2 && t$2.__a && t$2.__a(n$1);
}
function z$1(n$1) {
var e$2, r$2, u$3;
function o$3(o$4) {
if (e$2 || (e$2 = n$1()).then(function(n$2) {
r$2 = n$2.default || n$2;
}, function(n$2) {
u$3 = n$2;
}), u$3) throw u$3;
if (!r$2) throw e$2;
return _$2(r$2, o$4);
}
return o$3.displayName = "Lazy", o$3.__f = !0, o$3;
}
function B$1() {
this.i = null, this.l = null;
}
function Z(n$1) {
return this.getChildContext = function() {
return n$1.context;
}, n$1.children;
}
function Y(n$1) {
var e$2 = this, r$2 = n$1.h;
if (e$2.componentWillUnmount = function() {
G$1(null, e$2.v), e$2.v = null, e$2.h = null;
}, e$2.h && e$2.h !== r$2 && e$2.componentWillUnmount(), !e$2.v) {
for (var u$3 = e$2.__v; null !== u$3 && !u$3.__m && null !== u$3.__;) u$3 = u$3.__;
e$2.h = r$2, e$2.v = {
nodeType: 1,
parentNode: r$2,
childNodes: [],
__k: { __m: u$3.__m },
contains: function() {
return !0;
},
insertBefore: function(n$2, t$2) {
this.childNodes.push(n$2), e$2.h.insertBefore(n$2, t$2);
},
removeChild: function(n$2) {
this.childNodes.splice(this.childNodes.indexOf(n$2) >>> 1, 1), e$2.h.removeChild(n$2);
}
};
}
G$1(_$2(Z, { context: e$2.context }, n$1.__v), e$2.v);
}
function $(n$1, e$2) {
var r$2 = _$2(Y, {
__v: n$1,
h: e$2
});
return r$2.containerInfo = e$2, r$2;
}
function nn(n$1, t$2, e$2) {
return t$2.__k ?? (t$2.textContent = ""), G$1(n$1, t$2), "function" == typeof e$2 && e$2(), n$1 ? n$1.__c : null;
}
function tn(n$1, t$2, e$2) {
return J$1(n$1, t$2), "function" == typeof e$2 && e$2(), n$1 ? n$1.__c : null;
}
function rn() {}
function un() {
return this.cancelBubble;
}
function on() {
return this.defaultPrevented;
}
function dn(n$1) {
return _$2.bind(null, n$1);
}
function mn(n$1) {
return !!n$1 && n$1.$$typeof === q$2;
}
function pn(n$1) {
return mn(n$1) && n$1.type === k$1;
}
function yn(n$1) {
return !!n$1 && !!n$1.displayName && ("string" == typeof n$1.displayName || n$1.displayName instanceof String) && n$1.displayName.startsWith("Memo(");
}
function _n(n$1) {
return mn(n$1) ? K$1.apply(null, arguments) : n$1;
}
function bn(n$1) {
return !!n$1.__k && (G$1(null, n$1), !0);
}
function Sn(n$1) {
return n$1 && (n$1.base || 1 === n$1.nodeType && n$1) || null;
}
var I$1, T$2, A$1, L$1, O, F$2, U$1, H$1, q$2, G$2, J$2, K$2, Q$2, X$1, en, ln, cn, fn, an, sn, hn, vn, gn, En, Cn, xn, Rn;
var init_compat_module = __esm({ "../../node_modules/.bun/preact@10.27.2/node_modules/preact/compat/dist/compat.module.js"() {
init_preact_module();
init_hooks_module();
init_hooks_module();
I$1 = _;
(N$1.prototype = new x$2()).isPureReactComponent = !0, N$1.prototype.shouldComponentUpdate = function(n$1, t$2) {
return E$1(this.props, n$1) || E$1(this.state, t$2);
};
T$2 = l.__b;
l.__b = function(n$1) {
n$1.type && n$1.type.__f && n$1.ref && (n$1.props.ref = n$1.ref, n$1.ref = null), T$2 && T$2(n$1);
};
A$1 = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.forward_ref") || 3911;
L$1 = function(n$1, t$2) {
return null == n$1 ? null : H(H(n$1).map(t$2));
}, O = {
map: L$1,
forEach: L$1,
count: function(n$1) {
return n$1 ? H(n$1).length : 0;
},
only: function(n$1) {
var t$2 = H(n$1);
if (1 !== t$2.length) throw "Children.only";
return t$2[0];
},
toArray: H
}, F$2 = l.__e;
l.__e = function(n$1, t$2, e$2, r$2) {
if (n$1.then) {
for (var u$3, o$3 = t$2; o$3 = o$3.__;) if ((u$3 = o$3.__c) && u$3.__c) return t$2.__e ?? (t$2.__e = e$2.__e, t$2.__k = e$2.__k), u$3.__c(n$1, t$2);
}
F$2(n$1, t$2, e$2, r$2);
};
U$1 = l.unmount;
l.unmount = function(n$1) {
var t$2 = n$1.__c;
t$2 && t$2.__R && t$2.__R(), t$2 && 32 & n$1.__u && (n$1.type = null), U$1 && U$1(n$1);
}, (P$2.prototype = new x$2()).__c = function(n$1, t$2) {
var e$2 = t$2.__c, r$2 = this;
r$2.o ??= [], r$2.o.push(e$2);
var u$3 = j$1(r$2.__v), o$3 = !1, i$3 = function() {
o$3 || (o$3 = !0, e$2.__R = null, u$3 ? u$3(l$2) : l$2());
};
e$2.__R = i$3;
var l$2 = function() {
if (!--r$2.__u) {
if (r$2.state.__a) {
var n$2 = r$2.state.__a;
r$2.__v.__k[0] = W$1(n$2, n$2.__c.__P, n$2.__c.__O);
}
var t$3;
for (r$2.setState({ __a: r$2.__b = null }); t$3 = r$2.o.pop();) t$3.forceUpdate();
}
};
r$2.__u++ || 32 & t$2.__u || r$2.setState({ __a: r$2.__b = r$2.__v.__k[0] }), n$1.then(i$3, i$3);
}, P$2.prototype.componentWillUnmount = function() {
this.o = [];
}, P$2.prototype.render = function(n$1, e$2) {
if (this.__b) {
if (this.__v.__k) {
var r$2 = document.createElement("div"), o$3 = this.__v.__k[0].__c;
this.__v.__k[0] = V$1(this.__b, r$2, o$3.__O = o$3.__P);
}
this.__b = null;
}
var i$3 = e$2.__a && _$2(k$1, null, n$1.fallback);
return i$3 && (i$3.__u &= -33), [_$2(k$1, null, e$2.__a ? null : n$1.children), i$3];
};
H$1 = function(n$1, t$2, e$2) {
if (++e$2[1] === e$2[0] && n$1.l.delete(t$2), n$1.props.revealOrder && ("t" !== n$1.props.revealOrder[0] || !n$1.l.size)) for (e$2 = n$1.i; e$2;) {
for (; e$2.length > 3;) e$2.pop()();
if (e$2[1] < e$2[0]) break;
n$1.i = e$2 = e$2[2];
}
};
(B$1.prototype = new x$2()).__a = function(n$1) {
var t$2 = this, e$2 = j$1(t$2.__v), r$2 = t$2.l.get(n$1);
return r$2[0]++, function(u$3) {
var o$3 = function() {
t$2.props.revealOrder ? (r$2.push(u$3), H$1(t$2, n$1, r$2)) : u$3();
};
e$2 ? e$2(o$3) : o$3();
};
}, B$1.prototype.render = function(n$1) {
this.i = null, this.l = new Map();
var t$2 = H(n$1.children);
n$1.revealOrder && "b" === n$1.revealOrder[0] && t$2.reverse();
for (var e$2 = t$2.length; e$2--;) this.l.set(t$2[e$2], this.i = [
1,
0,
this.i
]);
return n$1.children;
}, B$1.prototype.componentDidUpdate = B$1.prototype.componentDidMount = function() {
var n$1 = this;
this.l.forEach(function(t$2, e$2) {
H$1(n$1, e$2, t$2);
});
};
q$2 = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103, G$2 = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/, J$2 = /^on(Ani|Tra|Tou|BeforeInp|Compo)/, K$2 = /[A-Z0-9]/g, Q$2 = "undefined" != typeof document, X$1 = function(n$1) {
return ("undefined" != typeof Symbol && "symbol" == typeof Symbol() ? /fil|che|rad/ : /fil|che|ra/).test(n$1);
};
x$2.prototype.isReactComponent = {}, [
"componentWillMount",
"componentWillReceiveProps",
"componentWillUpdate"
].forEach(function(t$2) {
Object.defineProperty(x$2.prototype, t$2, {
configurable: !0,
get: function() {
return this["UNSAFE_" + t$2];
},
set: function(n$1) {
Object.defineProperty(this, t$2, {
configurable: !0,
writable: !0,
value: n$1
});
}
});
});
en = l.event;
l.event = function(n$1) {
return en && (n$1 = en(n$1)), n$1.persist = rn, n$1.isPropagationStopped = un, n$1.isDefaultPrevented = on, n$1.nativeEvent = n$1;
};
cn = {
enumerable: !1,
configurable: !0,
get: function() {
return this.class;
}
}, fn = l.vnode;
l.vnode = function(n$1) {
"string" == typeof n$1.type && function(n$2) {
var t$2 = n$2.props, e$2 = n$2.type, u$3 = {}, o$3 = -1 === e$2.indexOf("-");
for (var i$3 in t$2) {
var l$2 = t$2[i$3];
if (!("value" === i$3 && "defaultValue" in t$2 && null == l$2 || Q$2 && "children" === i$3 && "noscript" === e$2 || "class" === i$3 || "className" === i$3)) {
var c$2 = i$3.toLowerCase();
"defaultValue" === i$3 && "value" in t$2 && null == t$2.value ? i$3 = "value" : "download" === i$3 && !0 === l$2 ? l$2 = "" : "translate" === c$2 && "no" === l$2 ? l$2 = !1 : "o" === c$2[0] && "n" === c$2[1] ? "ondoubleclick" === c$2 ? i$3 = "ondblclick" : "onchange" !== c$2 || "input" !== e$2 && "textarea" !== e$2 || X$1(t$2.type) ? "onfocus" === c$2 ? i$3 = "onfocusin" : "onblur" === c$2 ? i$3 = "onfocusout" : J$2.test(i$3) && (i$3 = c$2) : c$2 = i$3 = "oninput" : o$3 && G$2.test(i$3) ? i$3 = i$3.replace(K$2, "-$&").toLowerCase() : null === l$2 && (l$2 = void 0), "oninput" === c$2 && u$3[i$3 = c$2] && (i$3 = "oninputCapture"), u$3[i$3] = l$2;
}
}
"select" == e$2 && u$3.multiple && Array.isArray(u$3.value) && (u$3.value = H(t$2.children).forEach(function(n$3) {
n$3.props.selected = -1 != u$3.value.indexOf(n$3.props.value);
})), "select" == e$2 && null != u$3.defaultValue && (u$3.value = H(t$2.children).forEach(function(n$3) {
n$3.props.selected = u$3.multiple ? -1 != u$3.defaultValue.indexOf(n$3.props.value) : u$3.defaultValue == n$3.props.value;
})), t$2.class && !t$2.className ? (u$3.class = t$2.class, Object.defineProperty(u$3, "className", cn)) : (t$2.className && !t$2.class || t$2.class && t$2.className) && (u$3.class = u$3.className = t$2.className), n$2.props = u$3;
}(n$1), n$1.$$typeof = q$2, fn && fn(n$1);
};
an = l.__r;
l.__r = function(n$1) {
an && an(n$1), ln = n$1.__c;
};
sn = l.diffed;
l.diffed = function(n$1) {
sn && sn(n$1);
var t$2 = n$1.props, e$2 = n$1.__e;
null != e$2 && "textarea" === n$1.type && "value" in t$2 && t$2.value !== e$2.value && (e$2.value = null == t$2.value ? "" : t$2.value), ln = null;
};
hn = { ReactCurrentDispatcher: { current: {
readContext: function(n$1) {
return ln.__n[n$1.__c].props.value;
},
useCallback: q,
useContext: x$1,
useDebugValue: P$1,
useDeferredValue: w$1,
useEffect: y,
useId: g,
useImperativeHandle: F$1,
useInsertionEffect: I$1,
useLayoutEffect: _,
useMemo: T,
useReducer: h,
useRef: A,
useState: d,
useSyncExternalStore: C$1,
useTransition: k$2
} } }, vn = "18.3.1";
gn = function(n$1, t$2) {
return n$1(t$2);
}, En = function(n$1, t$2) {
return n$1(t$2);
}, Cn = k$1, xn = mn, Rn = {
useState: d,
useId: g,
useReducer: h,
useEffect: y,
useLayoutEffect: _,
useInsertionEffect: I$1,
useTransition: k$2,
useDeferredValue: w$1,
useSyncExternalStore: C$1,
startTransition: R,
useRef: A,
useImperativeHandle: F$1,
useMemo: T,
useCallback: q,
useContext: x$1,
useDebugValue: P$1,
version: "18.3.1",
Children: O,
render: nn,
hydrate: tn,
unmountComponentAtNode: bn,
createPortal: $,
createElement: _$2,
createContext: Q$1,
createFactory: dn,
cloneElement: _n,
createRef: b$1,
Fragment: k$1,
isValidElement: mn,
isElement: xn,
isFragment: pn,
isMemo: yn,
findDOMNode: Sn,
Component: x$2,
PureComponent: N$1,
memo: M,
forwardRef: D$1,
flushSync: En,
unstable_batchedUpdates: gn,
StrictMode: Cn,
Suspense: P$2,
SuspenseList: B$1,
lazy: z$1,
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: hn
};
} });
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/version.js
var version_default$1 = "7.16.3";
//#endregion
//#region ../../node_modules/.bun/@algolia+events@4.0.1/node_modules/@algolia/events/events.js
var require_events = __commonJS({ "../../node_modules/.bun/@algolia+events@4.0.1/node_modules/@algolia/events/events.js"(exports, module) {
function EventEmitter$3() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || void 0;
}
module.exports = EventEmitter$3;
EventEmitter$3.prototype._events = void 0;
EventEmitter$3.prototype._maxListeners = void 0;
EventEmitter$3.defaultMaxListeners = 10;
EventEmitter$3.prototype.setMaxListeners = function(n$1) {
if (!isNumber(n$1) || n$1 < 0 || isNaN(n$1)) throw TypeError("n must be a positive number");
this._maxListeners = n$1;
return this;
};
EventEmitter$3.prototype.emit = function(type) {
var er, handler, len, args, i$3, listeners;
if (!this._events) this._events = {};
if (type === "error") {
if (!this._events.error || isObject$1(this._events.error) && !this._events.error.length) {
er = arguments[1];
if (er instanceof Error) throw er;
else {
var err = new Error("Uncaught, unspecified \"error\" event. (" + er + ")");
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler)) return false;
if (isFunction(handler)) switch (arguments.length) {
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
else if (isObject$1(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i$3 = 0; i$3 < len; i$3++) listeners[i$3].apply(this, args);
}
return true;
};
EventEmitter$3.prototype.addListener = function(type, listener) {
var m$4;
if (!isFunction(listener)) throw TypeError("listener must be a function");
if (!this._events) this._events = {};
if (this._events.newListener) this.emit("newListener", type, isFunction(listener.listener) ? listener.listener : listener);
if (!this._events[type]) this._events[type] = listener;
else if (isObject$1(this._events[type])) this._events[type].push(listener);
else this._events[type] = [this._events[type], listener];
if (isObject$1(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) m$4 = this._maxListeners;
else m$4 = EventEmitter$3.defaultMaxListeners;
if (m$4 && m$4 > 0 && this._events[type].length > m$4) {
this._events[type].warned = true;
console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.", this._events[type].length);
if (typeof console.trace === "function") console.trace();
}
}
return this;
};
EventEmitter$3.prototype.on = EventEmitter$3.prototype.addListener;
EventEmitter$3.prototype.once = function(type, listener) {
if (!isFunction(listener)) throw TypeError("listener must be a function");
var fired = false;
function g$3() {
this.removeListener(type, g$3);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g$3.listener = listener;
this.on(type, g$3);
return this;
};
EventEmitter$3.prototype.removeListener = function(type, listener) {
var list, position, length, i$3;
if (!isFunction(listener)) throw TypeError("listener must be a function");
if (!this._events || !this._events[type]) return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener || isFunction(list.listener) && list.listener === listener) {
delete this._events[type];
if (this._events.removeListener) this.emit("removeListener", type, listener);
} else if (isObject$1(list)) {
for (i$3 = length; i$3-- > 0;) if (list[i$3] === listener || list[i$3].listener && list[i$3].listener === listener) {
position = i$3;
break;
}
if (position < 0) return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else list.splice(position, 1);
if (this._events.removeListener) this.emit("removeListener", type, listener);
}
return this;
};
EventEmitter$3.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events) return this;
if (!this._events.removeListener) {
if (arguments.length === 0) this._events = {};
else if (this._events[type]) delete this._events[type];
return this;
}
if (arguments.length === 0) {
for (key in this._events) {
if (key === "removeListener") continue;
this.removeAllListeners(key);
}
this.removeAllListeners("removeListener");
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) this.removeListener(type, listeners);
else if (listeners) while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]);
delete this._events[type];
return this;
};
EventEmitter$3.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type]) ret = [];
else if (isFunction(this._events[type])) ret = [this._events[type]];
else ret = this._events[type].slice();
return ret;
};
EventEmitter$3.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener)) return 1;
else if (evlistener) return evlistener.length;
}
return 0;
};
EventEmitter$3.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === "function";
}
function isNumber(arg) {
return typeof arg === "number";
}
function isObject$1(arg) {
return typeof arg === "object" && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/inherits.js
var require_inherits = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/inherits.js"(exports, module) {
function inherits$2(ctor, superCtor) {
ctor.prototype = Object.create(superCtor.prototype, { constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
} });
}
module.exports = inherits$2;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/DerivedHelper/index.js
var require_DerivedHelper = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/DerivedHelper/index.js"(exports, module) {
var EventEmitter$2 = require_events();
var inherits$1 = require_inherits();
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* @param {AlgoliaSearchHelper} mainHelper the main helper
* @param {function} fn the function to create the derived state for search
* @param {function} recommendFn the function to create the derived state for recommendations
*/
function DerivedHelper$1(mainHelper, fn$1, recommendFn) {
this.main = mainHelper;
this.fn = fn$1;
this.recommendFn = recommendFn;
this.lastResults = null;
this.lastRecommendResults = null;
}
inherits$1(DerivedHelper$1, EventEmitter$2);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper$1.prototype.detach = function() {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper$1.prototype.getModifiedState = function(parameters) {
return this.fn(parameters);
};
DerivedHelper$1.prototype.getModifiedRecommendState = function(parameters) {
return this.recommendFn(parameters);
};
module.exports = DerivedHelper$1;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/escapeFacetValue.js
var require_escapeFacetValue = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/escapeFacetValue.js"(exports, module) {
/**
* Replaces a leading - with \-
* @private
* @param {any} value the facet value to replace
* @returns {any} the escaped facet value or the value if it was not a string
*/
function escapeFacetValue$3(value) {
if (typeof value !== "string") return value;
return String(value).replace(/^-/, "\\-");
}
/**
* Replaces a leading \- with -
* @private
* @param {any} value the escaped facet value
* @returns {any} the unescaped facet value or the value if it was not a string
*/
function unescapeFacetValue$2(value) {
if (typeof value !== "string") return value;
return value.replace(/^\\-/, "-");
}
module.exports = {
escapeFacetValue: escapeFacetValue$3,
unescapeFacetValue: unescapeFacetValue$2
};
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/merge.js
var require_merge = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/merge.js"(exports, module) {
function clone$1(value) {
if (typeof value === "object" && value !== null) return _merge(Array.isArray(value) ? [] : {}, value);
return value;
}
function isObjectOrArrayOrFunction(value) {
return typeof value === "function" || Array.isArray(value) || Object.prototype.toString.call(value) === "[object Object]";
}
function _merge(target, source) {
if (target === source) return target;
for (var key in source) {
if (!Object.prototype.hasOwnProperty.call(source, key) || key === "__proto__" || key === "constructor") continue;
var sourceVal = source[key];
var targetVal = target[key];
if (typeof targetVal !== "undefined" && typeof sourceVal === "undefined") continue;
if (isObjectOrArrayOrFunction(targetVal) && isObjectOrArrayOrFunction(sourceVal)) target[key] = _merge(targetVal, sourceVal);
else target[key] = clone$1(sourceVal);
}
return target;
}
/**
* This method is like Object.assign, but recursively merges own and inherited
* enumerable keyed properties of source objects into the destination object.
*
* NOTE: this behaves like lodash/merge, but:
* - does mutate functions if they are a source
* - treats non-plain objects as plain
* - does not work for circular objects
* - treats sparse arrays as sparse
* - does not convert Array-like objects (Arguments, NodeLists, etc.) to arrays
*
* @param {Object} target The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
*/
function merge$5(target) {
if (!isObjectOrArrayOrFunction(target)) target = {};
for (var i$3 = 1, l$2 = arguments.length; i$3 < l$2; i$3++) {
var source = arguments[i$3];
if (isObjectOrArrayOrFunction(source)) _merge(target, source);
}
return target;
}
module.exports = merge$5;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/objectHasKeys.js
var require_objectHasKeys = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/objectHasKeys.js"(exports, module) {
function objectHasKeys$3(obj) {
return obj && Object.keys(obj).length > 0;
}
module.exports = objectHasKeys$3;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/omit.js
var require_omit = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/omit.js"(exports, module) {
function _objectWithoutPropertiesLoose$8(source, excluded) {
if (source === null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key;
var i$3;
for (i$3 = 0; i$3 < sourceKeys.length; i$3++) {
key = sourceKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
module.exports = _objectWithoutPropertiesLoose$8;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/RecommendParameters/index.js
var require_RecommendParameters = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/RecommendParameters/index.js"(exports, module) {
/**
* RecommendParameters is the data structure that contains all the information
* usable for getting recommendations from the Algolia API. It doesn't do the
* search itself, nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It
* will be provided when needed.
* @constructor
* @classdesc contains all the parameters for recommendations
* @param {RecommendParametersOptions} opts the options to create the object
*/
function RecommendParameters$2(opts) {
opts = opts || {};
this.params = opts.params || [];
}
RecommendParameters$2.prototype = {
constructor: RecommendParameters$2,
addParams: function(params) {
var newParams = this.params.slice();
newParams.push(params);
return new RecommendParameters$2({ params: newParams });
},
removeParams: function(id$1) {
return new RecommendParameters$2({ params: this.params.filter(function(param) {
return param.$$id !== id$1;
}) });
},
addFrequentlyBoughtTogether: function(params) {
return this.addParams(Object.assign({}, params, { model: "bought-together" }));
},
addRelatedProducts: function(params) {
return this.addParams(Object.assign({}, params, { model: "related-products" }));
},
addTrendingItems: function(params) {
return this.addParams(Object.assign({}, params, { model: "trending-items" }));
},
addTrendingFacets: function(params) {
return this.addParams(Object.assign({}, params, { model: "trending-facets" }));
},
addLookingSimilar: function(params) {
return this.addParams(Object.assign({}, params, { model: "looking-similar" }));
},
_buildQueries: function(indexName, cache) {
return this.params.filter(function(params) {
return cache[params.$$id] === void 0;
}).map(function(params) {
var query = Object.assign({}, params, {
indexName,
threshold: params.threshold || 0
});
delete query.$$id;
return query;
});
}
};
module.exports = RecommendParameters$2;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/RecommendResults/index.js
var require_RecommendResults = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/RecommendResults/index.js"(exports, module) {
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {RecommendParameters} state state that led to the response
* @param {Record<string,RecommendResultItem>} results the results from algolia client
**/
function RecommendResults$2(state, results) {
this._state = state;
this._rawResults = {};
var self = this;
state.params.forEach(function(param) {
var id$1 = param.$$id;
self[id$1] = results[id$1];
self._rawResults[id$1] = results[id$1];
});
}
RecommendResults$2.prototype = { constructor: RecommendResults$2 };
module.exports = RecommendResults$2;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/requestBuilder.js
var require_requestBuilder = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/requestBuilder.js"(exports, module) {
var merge$4 = require_merge();
function sortObject(obj) {
return Object.keys(obj).sort().reduce(function(acc, curr) {
acc[curr] = obj[curr];
return acc;
}, {});
}
var requestBuilder$1 = {
_getQueries: function getQueries(index$1, state) {
var queries = [];
queries.push({
indexName: index$1,
params: requestBuilder$1._getHitsSearchParams(state)
});
state.getRefinedDisjunctiveFacets().forEach(function(refinedFacet) {
queries.push({
indexName: index$1,
params: requestBuilder$1._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
state.getRefinedHierarchicalFacets().forEach(function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
var filtersMap = currentRefinement[0].split(separator).slice(0, -1).reduce(function createFiltersMap(map, segment, level) {
return map.concat({
attribute: hierarchicalFacet.attributes[level],
value: level === 0 ? segment : [map[map.length - 1].value, segment].join(separator)
});
}, []);
filtersMap.forEach(function(filter$1, level) {
var params = requestBuilder$1._getDisjunctiveFacetSearchParams(state, filter$1.attribute, level === 0);
function hasHierarchicalFacetFilter(value) {
return hierarchicalFacet.attributes.some(function(attribute) {
return attribute === value.split(":")[0];
});
}
var filteredFacetFilters = (params.facetFilters || []).reduce(function(acc, facetFilter) {
if (Array.isArray(facetFilter)) {
var filtered = facetFilter.filter(function(filterValue) {
return !hasHierarchicalFacetFilter(filterValue);
});
if (filtered.length > 0) acc.push(filtered);
}
if (typeof facetFilter === "string" && !hasHierarchicalFacetFilter(facetFilter)) acc.push(facetFilter);
return acc;
}, []);
var parent = filtersMap[level - 1];
if (level > 0) params.facetFilters = filteredFacetFilters.concat(parent.attribute + ":" + parent.value);
else if (filteredFacetFilters.length > 0) params.facetFilters = filteredFacetFilters;
else delete params.facetFilters;
queries.push({
indexName: index$1,
params
});
});
}
});
return queries;
},
_getCompositionQueries: function getQueries(state) {
return [{
compositionID: state.index,
requestBody: { params: requestBuilder$1._getCompositionHitsSearchParams(state) }
}];
},
_getHitsSearchParams: function(state) {
var facets = state.facets.concat(state.disjunctiveFacets).concat(requestBuilder$1._getHitsHierarchicalFacetsAttributes(state)).sort();
var facetFilters = requestBuilder$1._getFacetFilters(state);
var numericFilters = requestBuilder$1._getNumericFilters(state);
var tagFilters = requestBuilder$1._getTagFilters(state);
var additionalParams = {};
if (facets.length > 0) additionalParams.facets = facets.indexOf("*") > -1 ? ["*"] : facets;
if (tagFilters.length > 0) additionalParams.tagFilters = tagFilters;
if (facetFilters.length > 0) additionalParams.facetFilters = facetFilters;
if (numericFilters.length > 0) additionalParams.numericFilters = numericFilters;
return sortObject(merge$4({}, state.getQueryParams(), additionalParams));
},
_getCompositionHitsSearchParams: function(state) {
var facets = state.facets.concat(state.disjunctiveFacets.map(function(value) {
if (state.disjunctiveFacetsRefinements && state.disjunctiveFacetsRefinements[value] && state.disjunctiveFacetsRefinements[value].length > 0) return "disjunctive(" + value + ")";
return value;
})).concat(requestBuilder$1._getHitsHierarchicalFacetsAttributes(state)).sort();
var facetFilters = requestBuilder$1._getFacetFilters(state);
var numericFilters = requestBuilder$1._getNumericFilters(state);
var tagFilters = requestBuilder$1._getTagFilters(state);
var additionalParams = {};
if (facets.length > 0) additionalParams.facets = facets.indexOf("*") > -1 ? ["*"] : facets;
if (tagFilters.length > 0) additionalParams.tagFilters = tagFilters;
if (facetFilters.length > 0) additionalParams.facetFilters = facetFilters;
if (numericFilters.length > 0) additionalParams.numericFilters = numericFilters;
var params = state.getQueryParams();
delete params.highlightPreTag;
delete params.highlightPostTag;
delete params.index;
return sortObject(merge$4({}, params, additionalParams));
},
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder$1._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder$1._getNumericFilters(state, facet);
var tagFilters = requestBuilder$1._getTagFilters(state);
var additionalParams = {
hitsPerPage: 0,
page: 0,
analytics: false,
clickAnalytics: false
};
if (tagFilters.length > 0) additionalParams.tagFilters = tagFilters;
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) additionalParams.facets = requestBuilder$1._getDisjunctiveHierarchicalFacetAttribute(state, hierarchicalFacet, hierarchicalRootLevel);
else additionalParams.facets = facet;
if (numericFilters.length > 0) additionalParams.numericFilters = numericFilters;
if (facetFilters.length > 0) additionalParams.facetFilters = facetFilters;
return sortObject(merge$4({}, state.getQueryParams(), additionalParams));
},
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) return state.numericFilters;
var numericFilters = [];
Object.keys(state.numericRefinements).forEach(function(attribute) {
var operators = state.numericRefinements[attribute] || {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator] || [];
if (facetName !== attribute) values.forEach(function(value) {
if (Array.isArray(value)) {
var vs = value.map(function(v$3) {
return attribute + operator + v$3;
});
numericFilters.push(vs);
} else numericFilters.push(attribute + operator + value);
});
});
});
return numericFilters;
},
_getTagFilters: function(state) {
if (state.tagFilters) return state.tagFilters;
return state.tagRefinements.join(",");
},
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
var facetsRefinements = state.facetsRefinements || {};
Object.keys(facetsRefinements).sort().forEach(function(facetName) {
var facetValues = facetsRefinements[facetName] || [];
facetValues.slice().sort().forEach(function(facetValue) {
facetFilters.push(facetName + ":" + facetValue);
});
});
var facetsExcludes = state.facetsExcludes || {};
Object.keys(facetsExcludes).sort().forEach(function(facetName) {
var facetValues = facetsExcludes[facetName] || [];
facetValues.sort().forEach(function(facetValue) {
facetFilters.push(facetName + ":-" + facetValue);
});
});
var disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements || {};
Object.keys(disjunctiveFacetsRefinements).sort().forEach(function(facetName) {
var facetValues = disjunctiveFacetsRefinements[facetName] || [];
if (facetName === facet || !facetValues || facetValues.length === 0) return;
var orFilters = [];
facetValues.slice().sort().forEach(function(facetValue) {
orFilters.push(facetName + ":" + facetValue);
});
facetFilters.push(orFilters);
});
var hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements || {};
Object.keys(hierarchicalFacetsRefinements).sort().forEach(function(facetName) {
var facetValues = hierarchicalFacetsRefinements[facetName] || [];
var facetValue = facetValues[0];
if (facetValue === void 0) return;
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
if (facet === facetName) {
if (facetValue.indexOf(separator) === -1 || !rootPath && hierarchicalRootLevel === true || rootPath && rootPath.split(separator).length === facetValue.split(separator).length) return;
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) facetFilters.push([attributeToRefine + ":" + facetValue]);
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return state.hierarchicalFacets.reduce(function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) attributeIndex = rootPath.split(separator).length;
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || "";
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) {
var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state;
var searchForFacetSearchParameters = {
facetQuery: query,
facetName
};
if (typeof maxFacetHits === "number") searchForFacetSearchParameters.maxFacetHits = maxFacetHits;
return sortObject(merge$4({}, requestBuilder$1._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters));
}
};
module.exports = requestBuilder$1;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/defaultsPure.js
var require_defaultsPure = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/defaultsPure.js"(exports, module) {
module.exports = function defaultsPure$3() {
var sources = Array.prototype.slice.call(arguments);
return sources.reduceRight(function(acc, source) {
Object.keys(Object(source)).forEach(function(key) {
if (source[key] === void 0) return;
if (acc[key] !== void 0) delete acc[key];
acc[key] = source[key];
});
return acc;
}, {});
};
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/find.js
var require_find = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/find.js"(exports, module) {
module.exports = function find$6(array$1, comparator) {
if (!Array.isArray(array$1)) return void 0;
for (var i$3 = 0; i$3 < array$1.length; i$3++) if (comparator(array$1[i$3])) return array$1[i$3];
return void 0;
};
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/intersection.js
var require_intersection = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/intersection.js"(exports, module) {
function intersection$2(arr1, arr2) {
return arr1.filter(function(value, index$1) {
return arr2.indexOf(value) > -1 && arr1.indexOf(value) === index$1;
});
}
module.exports = intersection$2;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/valToNumber.js
var require_valToNumber = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/valToNumber.js"(exports, module) {
function valToNumber$1(v$3) {
if (typeof v$3 === "number") return v$3;
else if (typeof v$3 === "string") return parseFloat(v$3);
else if (Array.isArray(v$3)) return v$3.map(valToNumber$1);
throw new Error("The value should be a number, a parsable string or an array of those.");
}
module.exports = valToNumber$1;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/utils/isValidUserToken.js
var require_isValidUserToken = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/utils/isValidUserToken.js"(exports, module) {
module.exports = function isValidUserToken$1(userToken) {
if (userToken === null) return false;
return /^[a-zA-Z0-9_-]{1,64}$/.test(userToken);
};
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/SearchParameters/RefinementList.js
var require_RefinementList = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/SearchParameters/RefinementList.js"(exports, module) {
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var defaultsPure$2 = require_defaultsPure();
var objectHasKeys$2 = require_objectHasKeys();
var omit$3 = require_omit();
var lib = {
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) return refinementList;
var valueAsString = "" + value;
var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaultsPure$2(mod, refinementList);
},
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (value === void 0) return lib.clearRefinement(refinementList, function(v$3, f$3) {
return attribute === f$3;
});
var valueAsString = "" + value;
return lib.clearRefinement(refinementList, function(v$3, f$3) {
return attribute === f$3 && valueAsString === v$3;
});
},
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (value === void 0) throw new Error("toggleRefinement should be used with a value");
if (lib.isRefined(refinementList, attribute, value)) return lib.removeRefinement(refinementList, attribute, value);
return lib.addRefinement(refinementList, attribute, value);
},
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (attribute === void 0) {
if (!objectHasKeys$2(refinementList)) return refinementList;
return {};
} else if (typeof attribute === "string") return omit$3(refinementList, [attribute]);
else if (typeof attribute === "function") {
var hasChanged = false;
var newRefinementList = Object.keys(refinementList).reduce(function(memo, key) {
var values = refinementList[key] || [];
var facetList = values.filter(function(value) {
return !attribute(value, key, refinementType);
});
if (facetList.length !== values.length) hasChanged = true;
memo[key] = facetList;
return memo;
}, {});
if (hasChanged) return newRefinementList;
return refinementList;
}
return void 0;
},
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var containsRefinements = Boolean(refinementList[attribute]) && refinementList[attribute].length > 0;
if (refinementValue === void 0 || !containsRefinements) return containsRefinements;
var refinementValueAsString = "" + refinementValue;
return refinementList[attribute].indexOf(refinementValueAsString) !== -1;
}
};
module.exports = lib;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/SearchParameters/index.js
var require_SearchParameters = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/SearchParameters/index.js"(exports, module) {
var defaultsPure$1 = require_defaultsPure();
var find$5 = require_find();
var intersection$1 = require_intersection();
var merge$3 = require_merge();
var objectHasKeys$1 = require_objectHasKeys();
var omit$2 = require_omit();
var valToNumber = require_valToNumber();
var isValidUserToken = require_isValidUserToken();
var RefinementList = require_RefinementList();
/**
* isEqual, but only for numeric refinement values, possible values:
* - 5
* - [5]
* - [[5]]
* - [[5,5],[4]]
* @param {any} a numeric refinement value
* @param {any} b numeric refinement value
* @return {boolean} true if the values are equal
*/
function isEqualNumericRefinement(a$2, b$3) {
if (Array.isArray(a$2) && Array.isArray(b$3)) return a$2.length === b$3.length && a$2.every(function(el, i$3) {
return isEqualNumericRefinement(b$3[i$3], el);
});
return a$2 === b$3;
}
/**
* like _.find but using deep equality to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into (elements are base or array of base)
* @param {any} searchedValue the value we're looking for (base or array of base)
* @return {any} the searched value or undefined
*/
function findArray(array$1, searchedValue) {
return find$5(array$1, function(currentValue) {
return isEqualNumericRefinement(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters$2(newParameters) {
var params = newParameters ? SearchParameters$2._parseNumbers(newParameters) : {};
if (params.userToken !== void 0 && !isValidUserToken(params.userToken)) console.warn("[algoliasearch-helper] The `userToken` parameter is invalid. This can lead to wrong analytics.\n - Format: [a-zA-Z0-9_-]{1,64}");
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* separated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
var self = this;
Object.keys(params).forEach(function(paramName) {
var isKeyKnown = SearchParameters$2.PARAMETERS.indexOf(paramName) !== -1;
var isValueDefined = params[paramName] !== void 0;
if (!isKeyKnown && isValueDefined) self[paramName] = params[paramName];
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters$2.PARAMETERS = Object.keys(new SearchParameters$2());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters$2._parseNumbers = function(partialState) {
if (partialState instanceof SearchParameters$2) return partialState;
var numbers = {};
var numberKeys = [
"aroundPrecision",
"aroundRadius",
"getRankingInfo",
"minWordSizefor2Typos",
"minWordSizefor1Typo",
"page",
"maxValuesPerFacet",
"distinct",
"minimumAroundRadius",
"hitsPerPage",
"minProximity"
];
numberKeys.forEach(function(k$4) {
var value = partialState[k$4];
if (typeof value === "string") {
var parsedValue = parseFloat(value);
numbers[k$4] = isNaN(parsedValue) ? value : parsedValue;
}
});
if (Array.isArray(partialState.insideBoundingBox)) numbers.insideBoundingBox = partialState.insideBoundingBox.map(function(geoRect) {
if (Array.isArray(geoRect)) return geoRect.map(function(value) {
return parseFloat(value);
});
return geoRect;
});
if (partialState.numericRefinements) {
var numericRefinements = {};
Object.keys(partialState.numericRefinements).forEach(function(attribute) {
var operators = partialState.numericRefinements[attribute] || {};
numericRefinements[attribute] = {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator];
var parsedValues = values.map(function(v$3) {
if (Array.isArray(v$3)) return v$3.map(function(vPrime) {
if (typeof vPrime === "string") return parseFloat(vPrime);
return vPrime;
});
else if (typeof v$3 === "string") return parseFloat(v$3);
return v$3;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge$3(partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters$2.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters$2(newParameters);
var hierarchicalFacets = newParameters.hierarchicalFacets || [];
hierarchicalFacets.forEach(function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) instance = instance.clearRefinements(facet.name);
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters$2.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) return new Error("[Tags] Cannot switch from the managed tag API to the advanced API. It is probably an error, if it is really what you want, you should first clear the tags with clearTags method.");
if (currentState.tagRefinements.length > 0 && params.tagFilters) return new Error("[Tags] Cannot switch from the advanced tag API to the managed API. It is probably an error, if it is not, you should first clear the tags with clearTags method.");
if (currentState.numericFilters && params.numericRefinements && objectHasKeys$1(params.numericRefinements)) return new Error("[Numeric filters] Can't switch from the advanced to the managed API. It is probably an error, if this is really what you want, you have to first clear the numeric filters.");
if (objectHasKeys$1(currentState.numericRefinements) && params.numericFilters) return new Error("[Numeric filters] Can't switch from the managed API to the advanced. It is probably an error, if this is really what you want, you have to first clear the numeric filters.");
return null;
};
SearchParameters$2.prototype = {
constructor: SearchParameters$2,
clearRefinements: function clearRefinements(attribute) {
var patch = {
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: RefinementList.clearRefinement(this.facetsRefinements, attribute, "conjunctiveFacet"),
facetsExcludes: RefinementList.clearRefinement(this.facetsExcludes, attribute, "exclude"),
disjunctiveFacetsRefinements: RefinementList.clearRefinement(this.disjunctiveFacetsRefinements, attribute, "disjunctiveFacet"),
hierarchicalFacetsRefinements: RefinementList.clearRefinement(this.hierarchicalFacetsRefinements, attribute, "hierarchicalFacet")
};
if (patch.numericRefinements === this.numericRefinements && patch.facetsRefinements === this.facetsRefinements && patch.facetsExcludes === this.facetsExcludes && patch.disjunctiveFacetsRefinements === this.disjunctiveFacetsRefinements && patch.hierarchicalFacetsRefinements === this.hierarchicalFacetsRefinements) return this;
return this.setQueryParameters(patch);
},
clearTags: function clearTags() {
if (this.tagFilters === void 0 && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: void 0,
tagRefinements: []
});
},
setIndex: function setIndex(index$1) {
if (index$1 === this.index) return this;
return this.setQueryParameters({ index: index$1 });
},
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({ query: newQuery });
},
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({ page: newPage });
},
setFacets: function setFacets(facets) {
return this.setQueryParameters({ facets });
},
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({ disjunctiveFacets: facets });
},
setHitsPerPage: function setHitsPerPage(n$1) {
if (this.hitsPerPage === n$1) return this;
return this.setQueryParameters({ hitsPerPage: n$1 });
},
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({ typoTolerance });
},
addNumericRefinement: function(attribute, operator, value) {
var val = valToNumber(value);
if (this.isNumericRefined(attribute, operator, val)) return this;
var mod = merge$3({}, this.numericRefinements);
mod[attribute] = merge$3({}, mod[attribute]);
if (mod[attribute][operator]) {
mod[attribute][operator] = mod[attribute][operator].slice();
mod[attribute][operator].push(val);
} else mod[attribute][operator] = [val];
return this.setQueryParameters({ numericRefinements: mod });
},
getConjunctiveRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) return [];
return this.facetsRefinements[facetName] || [];
},
getDisjunctiveRefinements: function(facetName) {
if (!this.isDisjunctiveFacet(facetName)) return [];
return this.disjunctiveFacetsRefinements[facetName] || [];
},
getHierarchicalRefinement: function(facetName) {
return this.hierarchicalFacetsRefinements[facetName] || [];
},
getExcludeRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) return [];
return this.facetsExcludes[facetName] || [];
},
removeNumericRefinement: function(attribute, operator, number$2) {
var paramValue = number$2;
if (paramValue !== void 0) {
if (!this.isNumericRefined(attribute, operator, paramValue)) return this;
return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator && isEqualNumericRefinement(value.val, valToNumber(paramValue));
}) });
} else if (operator !== void 0) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
}) });
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
}) });
},
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (attribute === void 0) {
if (!objectHasKeys$1(this.numericRefinements)) return this.numericRefinements;
return {};
} else if (typeof attribute === "string") return omit$2(this.numericRefinements, [attribute]);
else if (typeof attribute === "function") {
var hasChanged = false;
var numericRefinements = this.numericRefinements;
var newNumericRefinements = Object.keys(numericRefinements).reduce(function(memo, key) {
var operators = numericRefinements[key];
var operatorList = {};
operators = operators || {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator] || [];
var outValues = [];
values.forEach(function(value) {
var predicateResult = attribute({
val: value,
op: operator
}, key, "numeric");
if (!predicateResult) outValues.push(value);
});
if (outValues.length !== values.length) hasChanged = true;
operatorList[operator] = outValues;
});
memo[key] = operatorList;
return memo;
}, {});
if (hasChanged) return newNumericRefinements;
return this.numericRefinements;
}
return void 0;
},
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) return this;
return this.setQueryParameters({ facets: this.facets.concat([facet]) });
},
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) return this;
return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) });
},
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) throw new Error("Cannot declare two hierarchical facets with the same name: `" + hierarchicalFacet.name + "`");
return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) });
},
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) throw new Error(facet + " is not defined in the facets attribute of the helper configuration");
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) });
},
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) throw new Error(facet + " is not defined in the facets attribute of the helper configuration");
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) });
},
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) throw new Error(facet + " is not defined in the disjunctiveFacets attribute of the helper configuration");
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement(this.disjunctiveFacetsRefinements, facet, value) });
},
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = { tagRefinements: this.tagRefinements.concat(tag) };
return this.setQueryParameters(modification);
},
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) return this;
return this.clearRefinements(facet).setQueryParameters({ facets: this.facets.filter(function(f$3) {
return f$3 !== facet;
}) });
},
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) return this;
return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.filter(function(f$3) {
return f$3 !== facet;
}) });
},
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) return this;
return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.filter(function(f$3) {
return f$3.name !== facet;
}) });
},
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) throw new Error(facet + " is not defined in the facets attribute of the helper configuration");
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) });
},
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) throw new Error(facet + " is not defined in the facets attribute of the helper configuration");
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) });
},
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) throw new Error(facet + " is not defined in the disjunctiveFacets attribute of the helper configuration");
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement(this.disjunctiveFacetsRefinements, facet, value) });
},
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = { tagRefinements: this.tagRefinements.filter(function(t$2) {
return t$2 !== tag;
}) };
return this.setQueryParameters(modification);
},
toggleRefinement: function toggleRefinement(facet, value) {
return this.toggleFacetRefinement(facet, value);
},
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) return this.toggleHierarchicalFacetRefinement(facet, value);
else if (this.isConjunctiveFacet(facet)) return this.toggleConjunctiveFacetRefinement(facet, value);
else if (this.isDisjunctiveFacet(facet)) return this.toggleDisjunctiveFacetRefinement(facet, value);
throw new Error("Cannot refine the undeclared facet " + facet + "; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets");
},
toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) throw new Error(facet + " is not defined in the facets attribute of the helper configuration");
return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) });
},
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) throw new Error(facet + " is not defined in the facets attribute of the helper configuration");
return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) });
},
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) throw new Error(facet + " is not defined in the disjunctiveFacets attribute of the helper configuration");
return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement(this.disjunctiveFacetsRefinements, facet, value) });
},
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) throw new Error(facet + " is not defined in the hierarchicalFacets attribute of the helper configuration");
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== void 0 && this.hierarchicalFacetsRefinements[facet].length > 0 && (this.hierarchicalFacetsRefinements[facet][0] === value || this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0);
if (upOneOrMultipleLevel) if (value.indexOf(separator) === -1) mod[facet] = [];
else mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
else mod[facet] = [value];
return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure$1(mod, this.hierarchicalFacetsRefinements) });
},
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) throw new Error(facet + " is already refined.");
if (!this.isHierarchicalFacet(facet)) throw new Error(facet + " is not defined in the hierarchicalFacets attribute of the helper configuration.");
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure$1(mod, this.hierarchicalFacetsRefinements) });
},
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) return this;
var mod = {};
mod[facet] = [];
return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure$1(mod, this.hierarchicalFacetsRefinements) });
},
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) return this.removeTagRefinement(tag);
return this.addTagRefinement(tag);
},
isDisjunctiveFacet: function(facet) {
return this.disjunctiveFacets.indexOf(facet) > -1;
},
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== void 0;
},
isConjunctiveFacet: function(facet) {
return this.facets.indexOf(facet) > -1;
},
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) return false;
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) return false;
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) return false;
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) return false;
var refinements = this.getHierarchicalRefinement(facet);
if (!value) return refinements.length > 0;
return refinements.indexOf(value) !== -1;
},
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (value === void 0 && operator === void 0) return Boolean(this.numericRefinements[attribute]);
var isOperatorDefined = this.numericRefinements[attribute] && this.numericRefinements[attribute][operator] !== void 0;
if (value === void 0 || !isOperatorDefined) return isOperatorDefined;
var parsedValue = valToNumber(value);
var isAttributeValueDefined = findArray(this.numericRefinements[attribute][operator], parsedValue) !== void 0;
return isOperatorDefined && isAttributeValueDefined;
},
isTagRefined: function isTagRefined(tag) {
return this.tagRefinements.indexOf(tag) !== -1;
},
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
var self = this;
var disjunctiveNumericRefinedFacets = intersection$1(Object.keys(this.numericRefinements).filter(function(facet) {
return Object.keys(self.numericRefinements[facet]).length > 0;
}), this.disjunctiveFacets);
return Object.keys(this.disjunctiveFacetsRefinements).filter(function(facet) {
return self.disjunctiveFacetsRefinements[facet].length > 0;
}).concat(disjunctiveNumericRefinedFacets).concat(this.getRefinedHierarchicalFacets()).sort();
},
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
var self = this;
return intersection$1(this.hierarchicalFacets.map(function(facet) {
return facet.name;
}), Object.keys(this.hierarchicalFacetsRefinements).filter(function(facet) {
return self.hierarchicalFacetsRefinements[facet].length > 0;
})).sort();
},
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return this.disjunctiveFacets.filter(function(f$3) {
return refinedFacets.indexOf(f$3) === -1;
});
},
managedParameters: [
"index",
"facets",
"disjunctiveFacets",
"facetsRefinements",
"hierarchicalFacets",
"facetsExcludes",
"disjunctiveFacetsRefinements",
"numericRefinements",
"tagRefinements",
"hierarchicalFacetsRefinements"
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
var self = this;
Object.keys(this).forEach(function(paramName) {
var paramValue = self[paramName];
if (managedParameters.indexOf(paramName) === -1 && paramValue !== void 0) queryParams[paramName] = paramValue;
});
return queryParams;
},
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters$2.validate(this, params);
if (error) throw error;
var self = this;
var nextWithNumbers = SearchParameters$2._parseNumbers(params);
var previousPlainObject = Object.keys(this).reduce(function(acc, key) {
acc[key] = self[key];
return acc;
}, {});
var nextPlainObject = Object.keys(nextWithNumbers).reduce(function(previous, key) {
var isPreviousValueDefined = previous[key] !== void 0;
var isNextValueDefined = nextWithNumbers[key] !== void 0;
if (isPreviousValueDefined && !isNextValueDefined) return omit$2(previous, [key]);
if (isNextValueDefined) previous[key] = nextWithNumbers[key];
return previous;
}, previousPlainObject);
return new this.constructor(nextPlainObject);
},
resetPage: function() {
if (this.page === void 0) return this;
return this.setPage(0);
},
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ["isRefined:desc", "name:asc"];
},
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || " > ";
},
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === "boolean") return hierarchicalFacet.showParentLevel;
return true;
},
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find$5(this.hierarchicalFacets, function(f$3) {
return f$3.name === hierarchicalFacetName;
});
},
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) return [];
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facetName));
var path = refinement.split(separator);
return path.map(function(part) {
return part.trim();
});
},
toString: function() {
return JSON.stringify(this, null, 2);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
module.exports = SearchParameters$2;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/compact.js
var require_compact = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/compact.js"(exports, module) {
module.exports = function compact$2(array$1) {
if (!Array.isArray(array$1)) return [];
return array$1.filter(Boolean);
};
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/findIndex.js
var require_findIndex = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/findIndex.js"(exports, module) {
module.exports = function find$6(array$1, comparator) {
if (!Array.isArray(array$1)) return -1;
for (var i$3 = 0; i$3 < array$1.length; i$3++) if (comparator(array$1[i$3])) return i$3;
return -1;
};
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/formatSort.js
var require_formatSort = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/formatSort.js"(exports, module) {
var find$4 = require_find();
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @param {string[]} [defaults] array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
module.exports = function formatSort$1(sortBy, defaults$2) {
var defaultInstructions = (defaults$2 || []).map(function(sort) {
return sort.split(":");
});
return sortBy.reduce(function preparePredicate(out, sort) {
var sortInstruction = sort.split(":");
var matchingDefault = find$4(defaultInstructions, function(defaultInstruction) {
return defaultInstruction[0] === sortInstruction[0];
});
if (sortInstruction.length > 1 || !matchingDefault) {
out[0].push(sortInstruction[0]);
out[1].push(sortInstruction[1]);
return out;
}
out[0].push(matchingDefault[0]);
out[1].push(matchingDefault[1]);
return out;
}, [[], []]);
};
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/mergeNumericMax.js
var require_mergeNumericMax = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/mergeNumericMax.js"(exports, module) {
function mergeNumericMax$1() {
var sources = Array.prototype.slice.call(arguments);
return sources.reduceRight(function(acc, source) {
Object.keys(Object(source)).forEach(function(key) {
var accValue = typeof acc[key] === "number" ? acc[key] : 0;
var sourceValue = source[key];
if (sourceValue === void 0) return;
if (sourceValue >= accValue) {
if (acc[key] !== void 0) delete acc[key];
acc[key] = sourceValue;
}
});
return acc;
}, {});
}
module.exports = mergeNumericMax$1;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/orderBy.js
var require_orderBy = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/orderBy.js"(exports, module) {
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== void 0;
var valIsNull = value === null;
var othIsDefined = other !== void 0;
var othIsNull = other === null;
if (!othIsNull && value > other || valIsNull && othIsDefined || !valIsDefined) return 1;
if (!valIsNull && value < other || othIsNull && valIsDefined || !othIsDefined) return -1;
}
return 0;
}
/**
* @param {Array<object>} collection object with keys in attributes
* @param {Array<string>} iteratees attributes
* @param {Array<string>} orders asc | desc
* @return {Array<object>} sorted collection
*/
function orderBy$2(collection, iteratees, orders) {
if (!Array.isArray(collection)) return [];
if (!Array.isArray(orders)) orders = [];
var result = collection.map(function(value, index$1) {
return {
criteria: iteratees.map(function(iteratee) {
return value[iteratee];
}),
index: index$1,
value
};
});
result.sort(function comparer(object$2, other) {
var index$1 = -1;
while (++index$1 < object$2.criteria.length) {
var res = compareAscending(object$2.criteria[index$1], other.criteria[index$1]);
if (res) {
if (index$1 >= orders.length) return res;
if (orders[index$1] === "desc") return -res;
return res;
}
}
return object$2.index - other.index;
});
return result.map(function(res) {
return res.value;
});
}
module.exports = orderBy$2;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/SearchResults/generate-hierarchical-tree.js
var require_generate_hierarchical_tree = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/SearchResults/generate-hierarchical-tree.js"(exports, module) {
module.exports = generateTrees;
var fv$1 = require_escapeFacetValue();
var find$3 = require_find();
var prepareHierarchicalFacetSortBy = require_formatSort();
var orderBy$1 = require_orderBy();
var escapeFacetValue$2 = fv$1.escapeFacetValue;
var unescapeFacetValue$1 = fv$1.unescapeFacetValue;
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || "";
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var rootExhaustive = hierarchicalFacetResult.every(function(facetResult) {
return facetResult.exhaustive;
});
var generateTreeFn = generateHierarchicalTree$1(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
return results.reduce(generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null,
isRefined: true,
path: null,
escapedValue: null,
exhaustive: rootExhaustive,
data: null
});
};
}
function generateHierarchicalTree$1(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
/**
* @type {object[]]} hierarchical data
*/
var data = parent && Array.isArray(parent.data) ? parent.data : [];
parent = find$3(data, function(subtree) {
return subtree.isRefined;
});
level++;
}
}
if (parent) {
var picked = Object.keys(hierarchicalFacetResult.data).map(function(facetValue) {
return [facetValue, hierarchicalFacetResult.data[facetValue]];
}).filter(function(tuple) {
var facetValue = tuple[0];
return onlyMatchingTree(facetValue, parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
});
parent.data = orderBy$1(picked.map(function(tuple) {
var facetValue = tuple[0];
var facetCount = tuple[1];
return format(facetCount, facetValue, hierarchicalSeparator, unescapeFacetValue$1(currentRefinement), hierarchicalFacetResult.exhaustive);
}), sortBy[0], sortBy[1]);
}
return hierarchicalTree;
};
}
function onlyMatchingTree(facetValue, parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) {
if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) return false;
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || currentRefinement.indexOf(facetValue) === 0 || facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
}
function format(facetCount, facetValue, hierarchicalSeparator, currentRefinement, exhaustive) {
var parts = facetValue.split(hierarchicalSeparator);
return {
name: parts[parts.length - 1].trim(),
path: facetValue,
escapedValue: escapeFacetValue$2(facetValue),
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
exhaustive,
data: null
};
}
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/SearchResults/index.js
var require_SearchResults = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/SearchResults/index.js"(exports, module) {
var compact$1 = require_compact();
var defaultsPure = require_defaultsPure();
var fv = require_escapeFacetValue();
var find$2 = require_find();
var findIndex$1 = require_findIndex();
var formatSort = require_formatSort();
var mergeNumericMax = require_mergeNumericMax();
var orderBy = require_orderBy();
var escapeFacetValue$1 = fv.escapeFacetValue;
var unescapeFacetValue = fv.unescapeFacetValue;
var generateHierarchicalTree = require_generate_hierarchical_tree();
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the faceting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objects matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} name the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric filters.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
/**
* Turn an array of attributes in an object of attributes with their position in the array as value
* @param {string[]} attributes the list of attributes in the record
* @return {object} the list of attributes indexed by attribute name
*/
function getIndices(attributes) {
var indices = {};
attributes.forEach(function(val, idx) {
indices[val] = idx;
});
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) dest.stats = facetStats[key];
}
/**
* @typedef {Object} HierarchicalFacet
* @property {string} name
* @property {string[]} attributes
*/
/**
* @param {HierarchicalFacet[]} hierarchicalFacets All hierarchical facets
* @param {string} hierarchicalAttributeName The name of the hierarchical attribute
* @return {HierarchicalFacet} The hierarchical facet matching the attribute name
*/
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find$2(hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) {
var facetNames = hierarchicalFacet.attributes || [];
return facetNames.indexOf(hierarchicalAttributeName) > -1;
});
}
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @param {object} options options to control results content
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
function SearchResults$2(state, results, options) {
var mainSubResponse = results[0] || {};
this._rawResults = results;
var self = this;
Object.keys(mainSubResponse).forEach(function(key) {
self[key] = mainSubResponse[key];
});
var opts = defaultsPure(options, { persistHierarchicalRootCount: false });
Object.keys(opts).forEach(function(key) {
self[key] = opts[key];
});
/**
* query used to generate the results
* @name query
* @member {string}
* @memberof SearchResults
* @instance
*/
/**
* The query as parsed by the engine given all the rules.
* @name parsedQuery
* @member {string}
* @memberof SearchResults
* @instance
*/
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: `full`, `partial` or `none`, depending on how the query terms match
* @name hits
* @member {object[]}
* @memberof SearchResults
* @instance
*/
/**
* index where the results come from
* @name index
* @member {string}
* @memberof SearchResults
* @instance
*/
/**
* number of hits per page requested
* @name hitsPerPage
* @member {number}
* @memberof SearchResults
* @instance
*/
/**
* total number of hits of this query on the index
* @name nbHits
* @member {number}
* @memberof SearchResults
* @instance
*/
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @name nbPages
* @member {number}
* @memberof SearchResults
* @instance
*/
/**
* current page
* @name page
* @member {number}
* @memberof SearchResults
* @instance
*/
/**
* The position if the position was guessed by IP.
* @name aroundLatLng
* @member {string}
* @memberof SearchResults
* @instance
* @example "48.8637,2.3615",
*/
/**
* The radius computed by Algolia.
* @name automaticRadius
* @member {string}
* @memberof SearchResults
* @instance
* @example "126792922",
*/
/**
* String identifying the server used to serve this request.
*
* getRankingInfo needs to be set to `true` for this to be returned
*
* @name serverUsed
* @member {string}
* @memberof SearchResults
* @instance
* @example "c7-use-2.algolia.net",
*/
/**
* Boolean that indicates if the computation of the counts did time out.
* @deprecated
* @name timeoutCounts
* @member {boolean}
* @memberof SearchResults
* @instance
*/
/**
* Boolean that indicates if the computation of the hits did time out.
* @deprecated
* @name timeoutHits
* @member {boolean}
* @memberof SearchResults
* @instance
*/
/**
* True if the counts of the facets is exhaustive
* @name exhaustiveFacetsCount
* @member {boolean}
* @memberof SearchResults
* @instance
*/
/**
* True if the number of hits is exhaustive
* @name exhaustiveNbHits
* @member {boolean}
* @memberof SearchResults
* @instance
*/
/**
* Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/).
* @name userData
* @member {object[]}
* @memberof SearchResults
* @instance
*/
/**
* queryID is the unique identifier of the query used to generate the current search results.
* This value is only available if the `clickAnalytics` search parameter is set to `true`.
* @name queryID
* @member {string}
* @memberof SearchResults
* @instance
*/
/**
* sum of the processing time of all the queries
* @name processingTimeMS
* @member {number}
* @memberof SearchResults
* @instance
*/
this.processingTimeMS = results.reduce(function(sum, result) {
return result.processingTimeMS === void 0 ? sum : sum + result.processingTimeMS;
}, 0);
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = state.hierarchicalFacets.map(function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var mainFacets = mainSubResponse.facets || {};
Object.keys(mainFacets).forEach(function(facetKey) {
var facetValueObject = mainFacets[facetKey];
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(state.hierarchicalFacets, facetKey);
if (hierarchicalFacet) {
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex$1(state.hierarchicalFacets, function(f$3) {
return f$3.name === hierarchicalFacet.name;
});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = state.disjunctiveFacets.indexOf(facetKey) !== -1;
var isFacetConjunctive = state.facets.indexOf(facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
this.hierarchicalFacets = compact$1(this.hierarchicalFacets);
disjunctiveFacets.forEach(function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var facets = result && result.facets ? result.facets : {};
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
Object.keys(facets).forEach(function(dfacet) {
var facetResults = facets[dfacet];
var position;
if (hierarchicalFacet) {
position = findIndex$1(state.hierarchicalFacets, function(f$3) {
return f$3.name === hierarchicalFacet.name;
});
var attributeIndex = findIndex$1(self.hierarchicalFacets[position], function(f$3) {
return f$3.attribute === dfacet;
});
if (attributeIndex === -1) return;
self.hierarchicalFacets[position][attributeIndex].data = self.persistHierarchicalRootCount ? mergeNumericMax(self.hierarchicalFacets[position][attributeIndex].data, facetResults) : defaultsPure(facetResults, self.hierarchicalFacets[position][attributeIndex].data);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: mergeNumericMax(dataFromMainRequest, facetResults),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) state.disjunctiveFacetsRefinements[dfacet].forEach(function(refinementValue) {
if (!self.disjunctiveFacets[position].data[refinementValue] && state.disjunctiveFacetsRefinements[dfacet].indexOf(unescapeFacetValue(refinementValue)) > -1) self.disjunctiveFacets[position].data[refinementValue] = 0;
});
}
});
nextDisjunctiveResult++;
});
state.getRefinedHierarchicalFacets().forEach(function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) return;
results.slice(nextDisjunctiveResult).forEach(function(result) {
var facets = result && result.facets ? result.facets : {};
Object.keys(facets).forEach(function(dfacet) {
var facetResults = facets[dfacet];
var position = findIndex$1(state.hierarchicalFacets, function(f$3) {
return f$3.name === hierarchicalFacet.name;
});
var attributeIndex = findIndex$1(self.hierarchicalFacets[position], function(f$3) {
return f$3.attribute === dfacet;
});
if (attributeIndex === -1) return;
var defaultData = {};
if (currentRefinement.length > 0 && !self.persistHierarchicalRootCount) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaultsPure(defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data);
});
nextDisjunctiveResult++;
});
});
Object.keys(state.facetsExcludes).forEach(function(facetName) {
var excludes = state.facetsExcludes[facetName];
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainFacets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
excludes.forEach(function(facetValue) {
self.facets[position] = self.facets[position] || { name: facetName };
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
/**
* @type {Array}
*/
this.hierarchicalFacets = this.hierarchicalFacets.map(generateHierarchicalTree(state));
/**
* @type {Array}
*/
this.facets = compact$1(this.facets);
/**
* @type {Array}
*/
this.disjunctiveFacets = compact$1(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the faceted attribute
* @return {SearchResults.Facet} the facet object
*/
SearchResults$2.prototype.getFacetByName = function(name$2) {
function predicate(facet) {
return facet.name === name$2;
}
return find$2(this.facets, predicate) || find$2(this.disjunctiveFacets, predicate) || find$2(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the faceted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
function predicate(facet$1) {
return facet$1.name === attribute;
}
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find$2(results.facets, predicate);
if (!facet) return [];
return Object.keys(facet.data).map(function(name$2) {
var value = escapeFacetValue$1(name$2);
return {
name: name$2,
escapedValue: value,
count: facet.data[name$2],
isRefined: results._state.isFacetRefined(attribute, value),
isExcluded: results._state.isExcludeRefined(attribute, name$2)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find$2(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return Object.keys(disjunctiveFacet.data).map(function(name$2) {
var value = escapeFacetValue$1(name$2);
return {
name: name$2,
escapedValue: value,
count: disjunctiveFacet.data[name$2],
isRefined: results._state.isDisjunctiveFacetRefined(attribute, value)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
var hierarchicalFacetValues = find$2(results.hierarchicalFacets, predicate);
if (!hierarchicalFacetValues) return hierarchicalFacetValues;
var hierarchicalFacet = results._state.getHierarchicalFacetByName(attribute);
var separator = results._state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = unescapeFacetValue(results._state.getHierarchicalRefinement(attribute)[0] || "");
if (currentRefinement.indexOf(hierarchicalFacet.rootPath) === 0) currentRefinement = currentRefinement.replace(hierarchicalFacet.rootPath + separator, "");
var currentRefinementSplit = currentRefinement.split(separator);
currentRefinementSplit.unshift(attribute);
setIsRefined(hierarchicalFacetValues, currentRefinementSplit, 0);
return hierarchicalFacetValues;
}
return void 0;
}
/**
* Set the isRefined of a hierarchical facet result based on the current state.
* @param {SearchResults.HierarchicalFacet} item Hierarchical facet to fix
* @param {string[]} currentRefinement array of parts of the current hierarchical refinement
* @param {number} depth recursion depth in the currentRefinement
* @return {undefined} function mutates the item
*/
function setIsRefined(item, currentRefinement, depth) {
item.isRefined = item.name === (currentRefinement[depth] && currentRefinement[depth].trim());
if (item.data) item.data.forEach(function(child) {
setIsRefined(child, currentRefinement, depth + 1);
});
}
/**
* Sort nodes of a hierarchical or disjunctive facet results
* @private
* @param {function} sortFn sort function to apply
* @param {HierarchicalFacet|Array} node node upon which we want to apply the sort
* @param {string[]} names attribute names
* @param {number} [level=0] current index in the names array
* @return {HierarchicalFacet|Array} sorted node
*/
function recSort(sortFn, node, names, level) {
level = level || 0;
if (Array.isArray(node)) return sortFn(node, names[level]);
if (!node.data || node.data.length === 0) return node;
var children = node.data.map(function(childNode) {
return recSort(sortFn, childNode, names, level + 1);
});
var sortedChildren = sortFn(children, names[level]);
var newNode = defaultsPure({ data: sortedChildren }, node);
return newNode;
}
SearchResults$2.DEFAULT_SORT = [
"isRefined:desc",
"count:desc",
"name:asc"
];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* @typedef FacetOrdering
* @type {Object}
* @property {string[]} [order]
* @property {'count' | 'alpha' | 'hidden'} [sortRemainingBy]
*/
/**
* Sorts facet arrays via their facet ordering
* @param {Array} facetValues the values
* @param {FacetOrdering} facetOrdering the ordering
* @returns {Array} the sorted facet values
*/
function sortViaFacetOrdering(facetValues, facetOrdering) {
var orderedFacets = [];
var remainingFacets = [];
var hide = facetOrdering.hide || [];
var order = facetOrdering.order || [];
/**
* an object with the keys being the values in order, the values their index:
* ['one', 'two'] -> { one: 0, two: 1 }
*/
var reverseOrder = order.reduce(function(acc, name$2, i$3) {
acc[name$2] = i$3;
return acc;
}, {});
facetValues.forEach(function(item) {
var name$2 = item.path || item.name;
var hidden = hide.indexOf(name$2) > -1;
if (!hidden && reverseOrder[name$2] !== void 0) orderedFacets[reverseOrder[name$2]] = item;
else if (!hidden) remainingFacets.push(item);
});
orderedFacets = orderedFacets.filter(function(facet) {
return facet;
});
var sortRemainingBy = facetOrdering.sortRemainingBy;
var ordering;
if (sortRemainingBy === "hidden") return orderedFacets;
else if (sortRemainingBy === "alpha") ordering = [["path", "name"], ["asc", "asc"]];
else ordering = [["count"], ["desc"]];
return orderedFacets.concat(orderBy(remainingFacets, ordering[0], ordering[1]));
}
/**
* @param {SearchResults} results the search results class
* @param {string} attribute the attribute to retrieve ordering of
* @returns {FacetOrdering | undefined} the facet ordering
*/
function getFacetOrdering(results, attribute) {
return results.renderingContent && results.renderingContent.facetOrdering && results.renderingContent.facetOrdering.values && results.renderingContent.facetOrdering.values[attribute];
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {boolean} [opts.facetOrdering]
* Force the use of facetOrdering from the result if a sortBy is present. If
* sortBy isn't present, facetOrdering will be used automatically.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet|undefined} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('result', function(event){
* //get values ordered only by name ascending using the string predicate
* event.results.getFacetValues('city', {sortBy: ['name:asc']});
* //get values ordered only by count ascending using a function
* event.results.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults$2.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) return void 0;
var options = defaultsPure(opts, {
sortBy: SearchResults$2.DEFAULT_SORT,
facetOrdering: !(opts && opts.sortBy)
});
var results = this;
var attributes;
if (Array.isArray(facetValues)) attributes = [attribute];
else {
var config$1 = results._state.getHierarchicalFacetByName(facetValues.name);
attributes = config$1.attributes;
}
return recSort(function(data, facetName) {
if (options.facetOrdering) {
var facetOrdering = getFacetOrdering(results, facetName);
if (facetOrdering) return sortViaFacetOrdering(data, facetOrdering);
}
if (Array.isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults$2.DEFAULT_SORT);
return orderBy(data, order[0], order[1]);
} else if (typeof options.sortBy === "function") return vanillaSortFn(options.sortBy, data);
throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function");
}, facetValues, attributes);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the faceted attribute
* @return {object} The stats of the facet
*/
SearchResults$2.prototype.getFacetStats = function(attribute) {
if (this._state.isConjunctiveFacet(attribute)) return getFacetStatsIfAvailable(this.facets, attribute);
else if (this._state.isDisjunctiveFacet(attribute)) return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
return void 0;
};
/**
* @typedef {Object} FacetListItem
* @property {string} name
*/
/**
* @param {FacetListItem[]} facetList (has more items, but enough for here)
* @param {string} facetName The attribute to look for
* @return {object|undefined} The stats of the facet
*/
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find$2(facetList, function(facet) {
return facet.name === facetName;
});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhaustiveness for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* Note that for a numeric refinement, results are grouped per operator, this
* means that it will return responses for operators which are empty.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults$2.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
Object.keys(state.facetsRefinements).forEach(function(attributeName) {
state.facetsRefinements[attributeName].forEach(function(name$2) {
res.push(getRefinement(state, "facet", attributeName, name$2, results.facets));
});
});
Object.keys(state.facetsExcludes).forEach(function(attributeName) {
state.facetsExcludes[attributeName].forEach(function(name$2) {
res.push(getRefinement(state, "exclude", attributeName, name$2, results.facets));
});
});
Object.keys(state.disjunctiveFacetsRefinements).forEach(function(attributeName) {
state.disjunctiveFacetsRefinements[attributeName].forEach(function(name$2) {
res.push(getRefinement(state, "disjunctive", attributeName, name$2, results.disjunctiveFacets));
});
});
Object.keys(state.hierarchicalFacetsRefinements).forEach(function(attributeName) {
state.hierarchicalFacetsRefinements[attributeName].forEach(function(name$2) {
res.push(getHierarchicalRefinement(state, attributeName, name$2, results.hierarchicalFacets));
});
});
Object.keys(state.numericRefinements).forEach(function(attributeName) {
var operators = state.numericRefinements[attributeName];
Object.keys(operators).forEach(function(operator) {
operators[operator].forEach(function(value) {
res.push({
type: "numeric",
attributeName,
name: value,
numericValue: value,
operator
});
});
});
});
state.tagRefinements.forEach(function(name$2) {
res.push({
type: "tag",
attributeName: "_tags",
name: name$2
});
});
return res;
};
/**
* @typedef {Object} Facet
* @property {string} name
* @property {Object} data
* @property {boolean} exhaustive
*/
/**
* @param {SearchParameters} state the current state
* @param {string} type the type of the refinement
* @param {string} attributeName The attribute of the facet
* @param {*} name The name of the facet
* @param {Facet[]} resultsFacets facets from the results
* @return {Refinement} the refinement
*/
function getRefinement(state, type, attributeName, name$2, resultsFacets) {
var facet = find$2(resultsFacets, function(f$3) {
return f$3.name === attributeName;
});
var count = facet && facet.data && facet.data[name$2] ? facet.data[name$2] : 0;
var exhaustive = facet && facet.exhaustive || false;
return {
type,
attributeName,
name: name$2,
count,
exhaustive
};
}
/**
* @param {SearchParameters} state the current state
* @param {string} attributeName the attribute of the hierarchical facet
* @param {string} name the name of the facet
* @param {Facet[]} resultsFacets facets from the results
* @return {HierarchicalFacet} the hierarchical facet
*/
function getHierarchicalRefinement(state, attributeName, name$2, resultsFacets) {
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var separator = state._getHierarchicalFacetSeparator(facetDeclaration);
var split$1 = name$2.split(separator);
var rootFacet = find$2(resultsFacets, function(facet$1) {
return facet$1.name === attributeName;
});
var facet = split$1.reduce(function(intermediateFacet, part) {
var newFacet = intermediateFacet && find$2(intermediateFacet.data, function(f$3) {
return f$3.name === part;
});
return newFacet !== void 0 ? newFacet : intermediateFacet;
}, rootFacet);
var count = facet && facet.count || 0;
var exhaustive = facet && facet.exhaustive || false;
var path = facet && facet.path || "";
return {
type: "hierarchical",
attributeName,
name: path,
count,
exhaustive
};
}
module.exports = SearchResults$2;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/flat.js
var require_flat = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/functions/flat.js"(exports, module) {
module.exports = function flat$1(arr) {
return arr.reduce(function(acc, val) {
return acc.concat(val);
}, []);
};
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/utils/sortAndMergeRecommendations.js
var require_sortAndMergeRecommendations = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/utils/sortAndMergeRecommendations.js"(exports, module) {
var find$1 = require_find();
var flat = require_flat();
function getAverageIndices(indexTracker, nrOfObjs) {
var avgIndices = [];
Object.keys(indexTracker).forEach(function(key) {
if (indexTracker[key].count < 2) indexTracker[key].indexSum += 100;
avgIndices.push({
objectID: key,
avgOfIndices: indexTracker[key].indexSum / nrOfObjs
});
});
return avgIndices.sort(function(a$2, b$3) {
return a$2.avgOfIndices > b$3.avgOfIndices ? 1 : -1;
});
}
function sortAndMergeRecommendations$1(objectIDs, results) {
var indexTracker = {};
results.forEach(function(hits) {
hits.forEach(function(hit, index$1) {
if (objectIDs.includes(hit.objectID)) return;
if (!indexTracker[hit.objectID]) indexTracker[hit.objectID] = {
indexSum: index$1,
count: 1
};
else indexTracker[hit.objectID] = {
indexSum: indexTracker[hit.objectID].indexSum + index$1,
count: indexTracker[hit.objectID].count + 1
};
});
});
var sortedAverageIndices = getAverageIndices(indexTracker, results.length);
var finalOrder = sortedAverageIndices.reduce(function(orderedHits, avgIndexRef) {
var result = find$1(flat(results), function(hit) {
return hit.objectID === avgIndexRef.objectID;
});
return result ? orderedHits.concat(result) : orderedHits;
}, []);
return finalOrder;
}
module.exports = sortAndMergeRecommendations$1;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/version.js
var require_version = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/version.js"(exports, module) {
module.exports = "3.26.0";
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/algoliasearch.helper.js
var require_algoliasearch_helper$1 = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/src/algoliasearch.helper.js"(exports, module) {
var EventEmitter$1 = require_events();
var DerivedHelper = require_DerivedHelper();
var escapeFacetValue = require_escapeFacetValue().escapeFacetValue;
var inherits = require_inherits();
var merge$2 = require_merge();
var objectHasKeys = require_objectHasKeys();
var omit$1 = require_omit();
var RecommendParameters$1 = require_RecommendParameters();
var RecommendResults$1 = require_RecommendResults();
var requestBuilder = require_requestBuilder();
var SearchParameters$1 = require_SearchParameters();
var SearchResults$1 = require_SearchResults();
var sortAndMergeRecommendations = require_sortAndMergeRecommendations();
var version$1 = require_version();
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {object} event
* @property {SearchParameters} event.state the current parameters with the latest changes applied
* @property {SearchResults} event.results the previous results received from Algolia. `null` before the first request
* @example
* helper.on('change', function(event) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search
* @property {SearchResults} event.results the results from the previous search. `null` if it is the first search.
* @example
* helper.on('search', function(event) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @property {string} event.facet the facet searched into
* @property {string} event.query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(event) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @example
* helper.on('searchOnce', function(event) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {object} event
* @property {SearchResults} event.results the results received from Algolia
* @property {SearchParameters} event.state the parameters used to query Algolia. Those might be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(event) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {object} event
* @property {Error} event.error the error returned by the Algolia.
* @example
* helper.on('error', function(event) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Event triggered when the queue of queries have been depleted (with any result or outdated queries)
* @event AlgoliaSearchHelper#event:searchQueueEmpty
* @example
* helper.on('searchQueueEmpty', function() {
* console.log('No more search pending');
* // This is received before the result event if we're not expecting new results
* });
*
* helper.search();
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
* @param {SearchResultsOptions|object} searchResultsOptions an object defining the options to use when creating the search results.
*/
function AlgoliaSearchHelper$1(client, index$1, options, searchResultsOptions) {
if (typeof client.addAlgoliaAgent === "function") client.addAlgoliaAgent("JS Helper (" + version$1 + ")");
this.setClient(client);
var opts = options || {};
opts.index = index$1;
this.state = SearchParameters$1.make(opts);
this.recommendState = new RecommendParameters$1({ params: opts.recommendState });
this.lastResults = null;
this.lastRecommendResults = null;
this._queryId = 0;
this._recommendQueryId = 0;
this._lastQueryIdReceived = -1;
this._lastRecommendQueryIdReceived = -1;
this.derivedHelpers = [];
this._currentNbQueries = 0;
this._currentNbRecommendQueries = 0;
this._searchResultsOptions = searchResultsOptions;
this._recommendCache = {};
}
inherits(AlgoliaSearchHelper$1, EventEmitter$1);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper$1.prototype.search = function() {
this._search({ onlyWithDerivedHelpers: false });
return this;
};
AlgoliaSearchHelper$1.prototype.searchOnlyWithDerivedHelpers = function() {
this._search({ onlyWithDerivedHelpers: true });
return this;
};
AlgoliaSearchHelper$1.prototype.searchWithComposition = function() {
this._runComposition({ onlyWithDerivedHelpers: true });
return this;
};
/**
* Sends the recommendation queries set in the state. When the method is
* called, it triggers a `fetch` event. The results will be available through
* the `result` event. If an error occurs, an `error` will be fired instead.
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires fetch
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper$1.prototype.recommend = function() {
this._recommend();
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper$1.prototype.getQuery = function() {
var state = this.state;
return requestBuilder._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [cb] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occurred it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper$1.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder._getQueries(tempState.index, tempState);
var self = this;
this._currentNbQueries++;
this.emit("searchOnce", { state: tempState });
if (cb) {
this.client.search(queries).then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit("searchQueueEmpty");
cb(null, new SearchResults$1(tempState, content.results), tempState);
}).catch(function(err) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit("searchQueueEmpty");
cb(err, null, tempState);
});
return void 0;
}
return this.client.search(queries).then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit("searchQueueEmpty");
return {
content: new SearchResults$1(tempState, content.results),
state: tempState,
_originalResponse: content
};
}, function(e$2) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit("searchQueueEmpty");
throw e$2;
});
};
/**
* Start the search for answers with the parameters set in the state.
* This method returns a promise.
* @param {Object} options - the options for answers API call
* @param {string[]} options.attributesForPrediction - Attributes to use for predictions. If empty, `searchableAttributes` is used instead.
* @param {string[]} options.queryLanguages - The languages in the query. Currently only supports ['en'].
* @param {number} options.nbHits - Maximum number of answers to retrieve from the Answers Engine. Cannot be greater than 1000.
*
* @return {promise} the answer results
* @deprecated answers is deprecated and will be replaced with new initiatives
*/
AlgoliaSearchHelper$1.prototype.findAnswers = function(options) {
console.warn("[algoliasearch-helper] answers is no longer supported");
var state = this.state;
var derivedHelper = this.derivedHelpers[0];
if (!derivedHelper) return Promise.resolve([]);
var derivedState = derivedHelper.getModifiedState(state);
var data = merge$2({
attributesForPrediction: options.attributesForPrediction,
nbHits: options.nbHits
}, { params: omit$1(requestBuilder._getHitsSearchParams(derivedState), [
"attributesToSnippet",
"hitsPerPage",
"restrictSearchableAttributes",
"snippetEllipsisText"
]) });
var errorMessage$1 = "search for answers was called, but this client does not have a function client.initIndex(index).findAnswers";
if (typeof this.client.initIndex !== "function") throw new Error(errorMessage$1);
var index$1 = this.client.initIndex(derivedState.index);
if (typeof index$1.findAnswers !== "function") throw new Error(errorMessage$1);
return index$1.findAnswers(derivedState.query, options.queryLanguages, data);
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurrence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {object}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query inside the engine
*/
/**
* Search for facet values based on an query and the name of a faceted attribute. This
* triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100
* @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes
* it in the generated query.
* @return {promise.<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper$1.prototype.searchForFacetValues = function(facet, query, maxFacetHits, userState) {
var clientHasSFFV = typeof this.client.searchForFacetValues === "function" && typeof this.client.searchForFacets !== "function";
var clientHasInitIndex = typeof this.client.initIndex === "function";
if (!clientHasSFFV && !clientHasInitIndex && typeof this.client.search !== "function") throw new Error("search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues");
var state = this.state.setQueryParameters(userState || {});
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, maxFacetHits, state);
this._currentNbQueries++;
var self = this;
var searchForFacetValuesPromise;
if (clientHasSFFV) searchForFacetValuesPromise = this.client.searchForFacetValues([{
indexName: state.index,
params: algoliaQuery
}]);
else if (clientHasInitIndex) searchForFacetValuesPromise = this.client.initIndex(state.index).searchForFacetValues(algoliaQuery);
else {
delete algoliaQuery.facetName;
searchForFacetValuesPromise = this.client.search([{
type: "facet",
facet,
indexName: state.index,
params: algoliaQuery
}]).then(function processResponse(response) {
return response.results[0];
});
}
this.emit("searchForFacetValues", {
state,
facet,
query
});
var hide = this.lastResults && this.lastResults.index === state.index && this.lastResults.renderingContent && this.lastResults.renderingContent.facetOrdering && this.lastResults.renderingContent.facetOrdering.values && this.lastResults.renderingContent.facetOrdering.values[facet] && this.lastResults.renderingContent.facetOrdering.values[facet].hide || [];
return searchForFacetValuesPromise.then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit("searchQueueEmpty");
content = Array.isArray(content) ? content[0] : content;
content.facetHits.forEach(function(f$3, i$3) {
if (hide.indexOf(f$3.value) > -1) {
content.facetHits.splice(i$3, 1);
return;
}
f$3.escapedValue = escapeFacetValue(f$3.value);
f$3.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f$3.escapedValue) : state.isFacetRefined(facet, f$3.escapedValue);
});
return content;
}, function(e$2) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit("searchQueueEmpty");
throw e$2;
});
};
/**
* Search for facet values using the Composition API & based on a query and the name of a faceted attribute.
* This triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100
* @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes
* it in the generated query.
* @return {promise.<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper$1.prototype.searchForCompositionFacetValues = function(facet, query, maxFacetHits, userState) {
if (typeof this.client.searchForFacetValues !== "function") throw new Error("search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues");
var state = this.state.setQueryParameters(userState || {});
var isDisjunctive = state.isDisjunctiveFacet(facet);
this._currentNbQueries++;
var self = this;
var searchForFacetValuesPromise;
searchForFacetValuesPromise = this.client.searchForFacetValues({
compositionID: state.index,
facetName: facet,
searchForFacetValuesRequest: { params: {
query,
maxFacetHits,
searchQuery: requestBuilder._getCompositionHitsSearchParams(state)
} }
});
this.emit("searchForFacetValues", {
state,
facet,
query
});
return searchForFacetValuesPromise.then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit("searchQueueEmpty");
content = content.results[0];
content.facetHits.forEach(function(f$3) {
f$3.escapedValue = escapeFacetValue(f$3.value);
f$3.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f$3.escapedValue) : state.isFacetRefined(facet, f$3.escapedValue);
});
return content;
}, function(e$2) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit("searchQueueEmpty");
throw e$2;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.setQuery = function(q$4) {
this._change({
state: this.state.resetPage().setQuery(q$4),
isPageReset: true
});
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper$1.prototype.clearRefinements = function(name$2) {
this._change({
state: this.state.resetPage().clearRefinements(name$2),
isPageReset: true
});
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.clearTags = function() {
this._change({
state: this.state.resetPage().clearTags(),
isPageReset: true
});
return this;
};
/**
* Adds a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().addDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper$1.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper$1.prototype.addHierarchicalFacetRefinement = function(facet, path) {
this._change({
state: this.state.resetPage().addHierarchicalFacetRefinement(facet, path),
isPageReset: true
});
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addNumericRefinement = function(attribute, operator, value) {
this._change({
state: this.state.resetPage().addNumericRefinement(attribute, operator, value),
isPageReset: true
});
return this;
};
/**
* Adds a filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().addFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper$1.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().addExcludeRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper$1.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addTag = function(tag) {
this._change({
state: this.state.resetPage().addTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Adds a "frequently bought together" recommendation query.
*
* @param {FrequentlyBoughtTogetherQuery} params the parameters for the recommendation
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addFrequentlyBoughtTogether = function(params) {
this._recommendChange({ state: this.recommendState.addFrequentlyBoughtTogether(params) });
return this;
};
/**
* Adds a "related products" recommendation query.
*
* @param {RelatedProductsQuery} params the parameters for the recommendation
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addRelatedProducts = function(params) {
this._recommendChange({ state: this.recommendState.addRelatedProducts(params) });
return this;
};
/**
* Adds a "trending items" recommendation query.
*
* @param {TrendingItemsQuery} params the parameters for the recommendation
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addTrendingItems = function(params) {
this._recommendChange({ state: this.recommendState.addTrendingItems(params) });
return this;
};
/**
* Adds a "trending facets" recommendation query.
*
* @param {TrendingFacetsQuery} params the parameters for the recommendation
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addTrendingFacets = function(params) {
this._recommendChange({ state: this.recommendState.addTrendingFacets(params) });
return this;
};
/**
* Adds a "looking similar" recommendation query.
*
* @param {LookingSimilarQuery} params the parameters for the recommendation
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.addLookingSimilar = function(params) {
this._recommendChange({ state: this.recommendState.addLookingSimilar(params) });
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optional, triggering different behavior:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeNumericRefinement = function(attribute, operator, value) {
this._change({
state: this.state.resetPage().removeNumericRefinement(attribute, operator, value),
isPageReset: true
});
return this;
};
/**
* Removes a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().removeDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper$1.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeHierarchicalFacetRefinement = function(facet) {
this._change({
state: this.state.resetPage().removeHierarchicalFacetRefinement(facet),
isPageReset: true
});
return this;
};
/**
* Removes a filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().removeFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper$1.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().removeExcludeRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper$1.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeTag = function(tag) {
this._change({
state: this.state.resetPage().removeTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Removes a "frequently bought together" recommendation query.
*
* @param {number} id identifier of the recommendation widget
* @returns {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeFrequentlyBoughtTogether = function(id$1) {
this._recommendChange({ state: this.recommendState.removeParams(id$1) });
return this;
};
/**
* Removes a "related products" recommendation query.
*
* @param {number} id identifier of the recommendation widget
* @returns {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeRelatedProducts = function(id$1) {
this._recommendChange({ state: this.recommendState.removeParams(id$1) });
return this;
};
/**
* Removes a "trending items" recommendation query.
*
* @param {number} id identifier of the recommendation widget
* @returns {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeTrendingItems = function(id$1) {
this._recommendChange({ state: this.recommendState.removeParams(id$1) });
return this;
};
/**
* Removes a "trending facets" recommendation query.
*
* @param {number} id identifier of the recommendation widget
* @returns {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeTrendingFacets = function(id$1) {
this._recommendChange({ state: this.recommendState.removeParams(id$1) });
return this;
};
/**
* Removes a "looking similar" recommendation query.
*
* @param {number} id identifier of the recommendation widget
* @returns {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.removeLookingSimilar = function(id$1) {
this._recommendChange({ state: this.recommendState.removeParams(id$1) });
return this;
};
/**
* Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.toggleFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().toggleExcludeFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper$1.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper$1.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.toggleFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().toggleFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper$1.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.toggleTag = function(tag) {
this._change({
state: this.state.resetPage().toggleTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper$1.prototype.nextPage = function() {
var page = this.state.page || 0;
return this.setPage(page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper$1.prototype.previousPage = function() {
var page = this.state.page || 0;
return this.setPage(page - 1);
};
/**
* @private
* @param {number} page The page number
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @chainable
* @fires change
*/
function setCurrentPage(page) {
if (page < 0) throw new Error("Page requested below 0.");
this._change({
state: this.state.setPage(page),
isPageReset: false
});
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.setIndex = function(name$2) {
this._change({
state: this.state.resetPage().setIndex(name$2),
isPageReset: true
});
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper$1.prototype.setQueryParameter = function(parameter, value) {
this._change({
state: this.state.resetPage().setQueryParameter(parameter, value),
isPageReset: true
});
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @fires change
* @chainable
*/
AlgoliaSearchHelper$1.prototype.setState = function(newState) {
this._change({
state: SearchParameters$1.make(newState),
isPageReset: false
});
return this;
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper$1.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters$1(newState);
return this;
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper$1.prototype.hasRefinements = function(attribute) {
if (objectHasKeys(this.state.getNumericRefinements(attribute))) return true;
else if (this.state.isConjunctiveFacet(attribute)) return this.state.isFacetRefined(attribute);
else if (this.state.isDisjunctiveFacet(attribute)) return this.state.isDisjunctiveFacetRefined(attribute);
else if (this.state.isHierarchicalFacet(attribute)) return this.state.isHierarchicalFacetRefined(attribute);
return false;
};
/**
* Check if a value is excluded for a specific faceted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper$1.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper$1.prototype.isDisjunctiveRefined = function(facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean} true if the tag is currently refined
*/
AlgoliaSearchHelper$1.prototype.hasTag = function(tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper$1.prototype.isTagRefined = function() {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string} name of the index
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper$1.prototype.getIndex = function() {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper$1.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper$1.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper$1.prototype.getTags = function() {
return this.state.tagRefinements;
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for faceting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper$1.prototype.getRefinements = function(facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
conjRefinements.forEach(function(r$2) {
refinements.push({
value: r$2,
type: "conjunctive"
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
excludeRefinements.forEach(function(r$2) {
refinements.push({
value: r$2,
type: "exclude"
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjunctiveRefinements = this.state.getDisjunctiveRefinements(facetName);
disjunctiveRefinements.forEach(function(r$2) {
refinements.push({
value: r$2,
type: "disjunctive"
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
Object.keys(numericRefinements).forEach(function(operator) {
var value = numericRefinements[operator];
refinements.push({
value,
operator,
type: "numeric"
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute attribute in the record
* @param {string} operator operator applied on the refined values
* @return {Array.<number|number[]>} refined values
*/
AlgoliaSearchHelper$1.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper$1.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
/**
* Perform the underlying queries
* @private
* @param {object} options options for the query
* @param {boolean} [options.onlyWithDerivedHelpers=false] if true, only the derived helpers will be queried
* @return {undefined} does not return anything
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper$1.prototype._search = function(options) {
var state = this.state;
var states = [];
var mainQueries = [];
if (!options.onlyWithDerivedHelpers) {
mainQueries = requestBuilder._getQueries(state.index, state);
states.push({
state,
queriesCount: mainQueries.length,
helper: this
});
this.emit("search", {
state,
results: this.lastResults
});
}
var derivedQueries = this.derivedHelpers.map(function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var derivedStateQueries = derivedState.index ? requestBuilder._getQueries(derivedState.index, derivedState) : [];
states.push({
state: derivedState,
queriesCount: derivedStateQueries.length,
helper: derivedHelper
});
derivedHelper.emit("search", {
state: derivedState,
results: derivedHelper.lastResults
});
return derivedStateQueries;
});
var queries = Array.prototype.concat.apply(mainQueries, derivedQueries);
var queryId = this._queryId++;
this._currentNbQueries++;
if (!queries.length) return Promise.resolve({ results: [] }).then(this._dispatchAlgoliaResponse.bind(this, states, queryId));
try {
this.client.search(queries).then(this._dispatchAlgoliaResponse.bind(this, states, queryId)).catch(this._dispatchAlgoliaError.bind(this, queryId));
} catch (error) {
this.emit("error", { error });
}
return void 0;
};
/**
* Perform the underlying queries
* @private
* @param {boolean} [options.onlyWithDerivedHelpers=false] if true, only the derived helpers will be queried
* @return {undefined} does not return anything
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper$1.prototype._runComposition = function() {
var state = this.state;
var states = [];
var mainQueries = [];
var derivedQueries = this.derivedHelpers.map(function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var derivedStateQueries = requestBuilder._getCompositionQueries(derivedState);
states.push({
state: derivedState,
queriesCount: derivedStateQueries.length,
helper: derivedHelper
});
derivedHelper.emit("search", {
state: derivedState,
results: derivedHelper.lastResults
});
return derivedStateQueries;
});
var queries = Array.prototype.concat.apply(mainQueries, derivedQueries);
var queryId = this._queryId++;
this._currentNbQueries++;
if (!queries.length) return Promise.resolve({ results: [] }).then(this._dispatchAlgoliaResponse.bind(this, states, queryId));
if (queries.length > 1) throw new Error("Only one query is allowed when using a composition.");
var query = queries[0];
try {
this.client.search(query).then(this._dispatchAlgoliaResponse.bind(this, states, queryId)).catch(this._dispatchAlgoliaError.bind(this, queryId));
} catch (error) {
this.emit("error", { error });
}
return void 0;
};
AlgoliaSearchHelper$1.prototype._recommend = function() {
var searchState = this.state;
var recommendState = this.recommendState;
var index$1 = this.getIndex();
var states = [{
state: recommendState,
index: index$1,
helper: this
}];
var ids = recommendState.params.map(function(param) {
return param.$$id;
});
this.emit("fetch", { recommend: {
state: recommendState,
results: this.lastRecommendResults
} });
var cache = this._recommendCache;
var derivedQueries = this.derivedHelpers.map(function(derivedHelper) {
var derivedIndex = derivedHelper.getModifiedState(searchState).index;
if (!derivedIndex) return [];
var derivedState = derivedHelper.getModifiedRecommendState(new RecommendParameters$1());
states.push({
state: derivedState,
index: derivedIndex,
helper: derivedHelper
});
ids = Array.prototype.concat.apply(ids, derivedState.params.map(function(param) {
return param.$$id;
}));
derivedHelper.emit("fetch", { recommend: {
state: derivedState,
results: derivedHelper.lastRecommendResults
} });
return derivedState._buildQueries(derivedIndex, cache);
});
var queries = Array.prototype.concat.apply(this.recommendState._buildQueries(index$1, cache), derivedQueries);
if (queries.length === 0) return;
if (queries.length > 0 && typeof this.client.getRecommendations === "undefined") {
console.warn("Please update algoliasearch/lite to the latest version in order to use recommend widgets.");
return;
}
var queryId = this._recommendQueryId++;
this._currentNbRecommendQueries++;
try {
this.client.getRecommendations(queries).then(this._dispatchRecommendResponse.bind(this, queryId, states, ids)).catch(this._dispatchRecommendError.bind(this, queryId));
} catch (error) {
this.emit("error", { error });
}
return;
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable object that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} states state used to generate the request
* @param {number} queryId id of the current request
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper$1.prototype._dispatchAlgoliaResponse = function(states, queryId, content) {
var self = this;
if (queryId < this._lastQueryIdReceived) return;
this._currentNbQueries -= queryId - this._lastQueryIdReceived;
this._lastQueryIdReceived = queryId;
if (this._currentNbQueries === 0) this.emit("searchQueueEmpty");
var results = content.results.slice();
var rawContent = Object.keys(content).reduce(function(value, key) {
if (key !== "results") value[key] = content[key];
return value;
}, {});
if (Object.keys(rawContent).length <= 0) rawContent = void 0;
states.forEach(function(s$2) {
var state = s$2.state;
var queriesCount = s$2.queriesCount;
var helper = s$2.helper;
var specificResults = results.splice(0, queriesCount);
if (!state.index) {
helper.emit("result", {
results: null,
state
});
return;
}
helper.lastResults = new SearchResults$1(state, specificResults, self._searchResultsOptions);
if (rawContent !== void 0) helper.lastResults._rawContent = rawContent;
helper.emit("result", {
results: helper.lastResults,
state
});
});
};
AlgoliaSearchHelper$1.prototype._dispatchRecommendResponse = function(queryId, states, ids, content) {
if (queryId < this._lastRecommendQueryIdReceived) return;
this._currentNbRecommendQueries -= queryId - this._lastRecommendQueryIdReceived;
this._lastRecommendQueryIdReceived = queryId;
if (this._currentNbRecommendQueries === 0) this.emit("recommendQueueEmpty");
var cache = this._recommendCache;
var idsMap = {};
ids.filter(function(id$1) {
return cache[id$1] === void 0;
}).forEach(function(id$1, index$1) {
if (!idsMap[id$1]) idsMap[id$1] = [];
idsMap[id$1].push(index$1);
});
Object.keys(idsMap).forEach(function(id$1) {
var indices = idsMap[id$1];
var firstResult = content.results[indices[0]];
if (indices.length === 1) {
cache[id$1] = firstResult;
return;
}
cache[id$1] = Object.assign({}, firstResult, { hits: sortAndMergeRecommendations(ids, indices.map(function(idx) {
return content.results[idx].hits;
})) });
});
var results = {};
ids.forEach(function(id$1) {
results[id$1] = cache[id$1];
});
states.forEach(function(s$2) {
var state = s$2.state;
var helper = s$2.helper;
if (!s$2.index) {
helper.emit("recommend:result", {
results: null,
state
});
return;
}
helper.lastRecommendResults = new RecommendResults$1(state, results);
helper.emit("recommend:result", { recommend: {
results: helper.lastRecommendResults,
state
} });
});
};
AlgoliaSearchHelper$1.prototype._dispatchAlgoliaError = function(queryId, error) {
if (queryId < this._lastQueryIdReceived) return;
this._currentNbQueries -= queryId - this._lastQueryIdReceived;
this._lastQueryIdReceived = queryId;
this.emit("error", { error });
if (this._currentNbQueries === 0) this.emit("searchQueueEmpty");
};
AlgoliaSearchHelper$1.prototype._dispatchRecommendError = function(queryId, error) {
if (queryId < this._lastRecommendQueryIdReceived) return;
this._currentNbRecommendQueries -= queryId - this._lastRecommendQueryIdReceived;
this._lastRecommendQueryIdReceived = queryId;
this.emit("error", { error });
if (this._currentNbRecommendQueries === 0) this.emit("recommendQueueEmpty");
};
AlgoliaSearchHelper$1.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean} true if there are refinements on this attribute
*/
AlgoliaSearchHelper$1.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper$1.prototype._change = function(event) {
var state = event.state;
var isPageReset = event.isPageReset;
if (state !== this.state) {
this.state = state;
this.emit("change", {
state: this.state,
results: this.lastResults,
isPageReset
});
}
};
AlgoliaSearchHelper$1.prototype._recommendChange = function(event) {
var state = event.state;
if (state !== this.recommendState) {
this.recommendState = state;
this.emit("recommend:change", {
search: {
results: this.lastResults,
state: this.state
},
recommend: {
results: this.lastRecommendResults,
state: this.recommendState
}
});
}
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
*/
AlgoliaSearchHelper$1.prototype.clearCache = function() {
if (this.client.clearCache) this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper} Method is chainable, it returns itself
*/
AlgoliaSearchHelper$1.prototype.setClient = function(newClient) {
if (this.client === newClient) return this;
if (typeof newClient.addAlgoliaAgent === "function") newClient.addAlgoliaAgent("JS Helper (" + version$1 + ")");
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch} the currently used client
*/
AlgoliaSearchHelper$1.prototype.getClient = function() {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `result` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @param {function} recommendFn RecommendParameters -> RecommendParameters
* @return {DerivedHelper} a new DerivedHelper
*/
AlgoliaSearchHelper$1.prototype.derive = function(fn$1, recommendFn) {
var derivedHelper = new DerivedHelper(this, fn$1, recommendFn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @param {DerivedHelper} derivedHelper the derived helper to detach
* @return {undefined} nothing is returned
* @throws Error
*/
AlgoliaSearchHelper$1.prototype.detachDerivedHelper = function(derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error("Derived helper already detached");
this.derivedHelpers.splice(pos, 1);
};
/**
* This method returns true if there is currently at least one on-going search.
* @return {boolean} true if there is a search pending
*/
AlgoliaSearchHelper$1.prototype.hasPendingRequests = function() {
return this._currentNbQueries > 0;
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the faceting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
module.exports = AlgoliaSearchHelper$1;
} });
//#endregion
//#region ../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/index.js
var require_algoliasearch_helper = __commonJS({ "../../node_modules/.bun/algoliasearch-helper@3.26.0+28b6629f675cd2d9/node_modules/algoliasearch-helper/index.js"(exports, module) {
var AlgoliaSearchHelper = require_algoliasearch_helper$1();
var RecommendParameters = require_RecommendParameters();
var RecommendResults = require_RecommendResults();
var SearchParameters = require_SearchParameters();
var SearchResults = require_SearchResults();
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(event) {
* console.log(event.results);
* });
* helper
* .toggleFacetRefinement('category', 'Movies & TV Shows')
* .toggleFacetRefinement('shipping', 'Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @param {SearchResultsOptions|object} searchResultsOptions an object defining the options to use when creating the search results.
* @return {AlgoliaSearchHelper} The helper instance
*/
function algoliasearchHelper$4(client, index$1, opts, searchResultsOptions) {
return new AlgoliaSearchHelper(client, index$1, opts, searchResultsOptions);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper$4.version = require_version();
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper$4.AlgoliaSearchHelper = AlgoliaSearchHelper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper$4.SearchParameters = SearchParameters;
/**
* Constructor for the object containing all the parameters for Recommend.
* @member module:algoliasearchHelper.RecommendParameters
* @type {RecommendParameters}
*/
algoliasearchHelper$4.RecommendParameters = RecommendParameters;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper$4.SearchResults = SearchResults;
/**
* Constructor for the object containing the results for Recommend.
* @member module:algoliasearchHelper.RecommendResults
* @type {RecommendResults}
*/
algoliasearchHelper$4.RecommendResults = RecommendResults;
module.exports = algoliasearchHelper$4;
} });
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/addWidgetId.js
var id = 0;
function addWidgetId(widget) {
if (widget.dependsOn !== "recommend") return;
widget.$$id = id++;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/noop.js
function noop$1() {}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/getObjectType.js
function getObjectType(object$2) {
return Object.prototype.toString.call(object$2).slice(8, -1);
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/checkRendering.js
function checkRendering(rendering, usage) {
if (rendering === void 0 || typeof rendering !== "function") throw new Error("The render function is not valid (received type ".concat(getObjectType(rendering), ").\n\n").concat(usage));
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/escape-html.js
/**
* This implementation is taken from Lodash implementation.
* See: https://github.com/lodash/lodash/blob/4.17.11-npm/escape.js
*/
var htmlEntities = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
};
var regexUnescapedHtml = /[&<>"']/g;
var regexHasUnescapedHtml = RegExp(regexUnescapedHtml.source);
/**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*/
function escape$1(value) {
return value && regexHasUnescapedHtml.test(value) ? value.replace(regexUnescapedHtml, function(character) {
return htmlEntities[character];
}) : value;
}
/**
* This implementation is taken from Lodash implementation.
* See: https://github.com/lodash/lodash/blob/4.17.11-npm/unescape.js
*/
var htmlCharacters = {
"&": "&",
"<": "<",
">": ">",
""": "\"",
"'": "'"
};
var regexEscapedHtml = /&(amp|quot|lt|gt|#39);/g;
var regexHasEscapedHtml = RegExp(regexEscapedHtml.source);
/**
* Converts the HTML entities "&", "<", ">", '"', and "'" in `string` to their
* characters.
*/
function unescape$1(value) {
return value && regexHasEscapedHtml.test(value) ? value.replace(regexEscapedHtml, function(character) {
return htmlCharacters[character];
}) : value;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/isPlainObject.js
function _typeof$25(o$3) {
"@babel/helpers - typeof";
return _typeof$25 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$25(o$3);
}
/**
* This implementation is taken from Lodash implementation.
* See: https://github.com/lodash/lodash/blob/master/isPlainObject.js
*/
function getTag(value) {
if (value === null) return value === void 0 ? "[object Undefined]" : "[object Null]";
return Object.prototype.toString.call(value);
}
function isObjectLike(value) {
return _typeof$25(value) === "object" && value !== null;
}
/**
* Checks if `value` is a plain object.
*
* A plain object is an object created by the `Object`
* constructor or with a `[[Prototype]]` of `null`.
*/
function isPlainObject$1(value) {
if (!isObjectLike(value) || getTag(value) !== "[object Object]") return false;
if (Object.getPrototypeOf(value) === null) return true;
var proto = value;
while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
return Object.getPrototypeOf(value) === proto;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/escape-highlight.js
function _typeof$24(o$3) {
"@babel/helpers - typeof";
return _typeof$24 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$24(o$3);
}
function _objectDestructuringEmpty(obj) {
if (obj == null) throw new TypeError("Cannot destructure " + obj);
}
function _extends$3() {
_extends$3 = Object.assign ? Object.assign.bind() : function(target) {
for (var i$3 = 1; i$3 < arguments.length; i$3++) {
var source = arguments[i$3];
for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
}
return target;
};
return _extends$3.apply(this, arguments);
}
function ownKeys$20(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$20(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$20(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$21(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$20(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$21(obj, key, value) {
key = _toPropertyKey$21(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$21(t$2) {
var i$3 = _toPrimitive$21(t$2, "string");
return "symbol" == _typeof$24(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$21(t$2, r$2) {
if ("object" != _typeof$24(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$24(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
var TAG_PLACEHOLDER = {
highlightPreTag: "__ais-highlight__",
highlightPostTag: "__/ais-highlight__"
};
var TAG_REPLACEMENT = {
highlightPreTag: "<mark>",
highlightPostTag: "</mark>"
};
function replaceTagsAndEscape(value) {
return escape$1(value).replace(new RegExp(TAG_PLACEHOLDER.highlightPreTag, "g"), TAG_REPLACEMENT.highlightPreTag).replace(new RegExp(TAG_PLACEHOLDER.highlightPostTag, "g"), TAG_REPLACEMENT.highlightPostTag);
}
function recursiveEscape(input) {
if (isPlainObject$1(input) && typeof input.value !== "string") return Object.keys(input).reduce(function(acc, key) {
return _objectSpread$20(_objectSpread$20({}, acc), {}, _defineProperty$21({}, key, recursiveEscape(input[key])));
}, {});
if (Array.isArray(input)) return input.map(recursiveEscape);
return _objectSpread$20(_objectSpread$20({}, input), {}, { value: replaceTagsAndEscape(input.value) });
}
function escapeHits(hits) {
if (hits.__escaped === void 0) {
hits = hits.map(function(_ref) {
var hit = _extends$3({}, (_objectDestructuringEmpty(_ref), _ref));
if (hit._highlightResult) hit._highlightResult = recursiveEscape(hit._highlightResult);
if (hit._snippetResult) hit._snippetResult = recursiveEscape(hit._snippetResult);
return hit;
});
hits.__escaped = true;
}
return hits;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/concatHighlightedParts.js
function concatHighlightedParts(parts) {
var highlightPreTag = TAG_REPLACEMENT.highlightPreTag, highlightPostTag = TAG_REPLACEMENT.highlightPostTag;
return parts.map(function(part) {
return part.isHighlighted ? highlightPreTag + part.value + highlightPostTag : part.value;
}).join("");
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/serializer.js
function serializePayload(payload) {
return btoa(encodeURIComponent(JSON.stringify(payload)));
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/createSendEventForHits.js
function ownKeys$19(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$19(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$19(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$20(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$19(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$20(obj, key, value) {
key = _toPropertyKey$20(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$20(t$2) {
var i$3 = _toPrimitive$20(t$2, "string");
return "symbol" == _typeof$23(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$20(t$2, r$2) {
if ("object" != _typeof$23(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$23(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function _slicedToArray$7(arr, i$3) {
return _arrayWithHoles$7(arr) || _iterableToArrayLimit$7(arr, i$3) || _unsupportedIterableToArray$8(arr, i$3) || _nonIterableRest$7();
}
function _nonIterableRest$7() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$8(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray$8(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray$8(o$3, minLen);
}
function _arrayLikeToArray$8(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
function _iterableToArrayLimit$7(r$2, l$2) {
var t$2 = null == r$2 ? null : "undefined" != typeof Symbol && r$2[Symbol.iterator] || r$2["@@iterator"];
if (null != t$2) {
var e$2, n$1, i$3, u$3, a$2 = [], f$3 = !0, o$3 = !1;
try {
if (i$3 = (t$2 = t$2.call(r$2)).next, 0 === l$2) {
if (Object(t$2) !== t$2) return;
f$3 = !1;
} else for (; !(f$3 = (e$2 = i$3.call(t$2)).done) && (a$2.push(e$2.value), a$2.length !== l$2); f$3 = !0);
} catch (r$3) {
o$3 = !0, n$1 = r$3;
} finally {
try {
if (!f$3 && null != t$2.return && (u$3 = t$2.return(), Object(u$3) !== u$3)) return;
} finally {
if (o$3) throw n$1;
}
}
return a$2;
}
}
function _arrayWithHoles$7(arr) {
if (Array.isArray(arr)) return arr;
}
function _typeof$23(o$3) {
"@babel/helpers - typeof";
return _typeof$23 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$23(o$3);
}
function chunk(arr) {
var chunkSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 20;
var chunks = [];
for (var i$3 = 0; i$3 < Math.ceil(arr.length / chunkSize); i$3++) chunks.push(arr.slice(i$3 * chunkSize, (i$3 + 1) * chunkSize));
return chunks;
}
function _buildEventPayloadsForHits(_ref) {
var helper = _ref.helper, widgetType = _ref.widgetType, methodName = _ref.methodName, args = _ref.args, instantSearchInstance = _ref.instantSearchInstance;
if (args.length === 1 && _typeof$23(args[0]) === "object") return [args[0]];
var _args$0$split = args[0].split(":"), _args$0$split2 = _slicedToArray$7(_args$0$split, 2), eventType = _args$0$split2[0], eventModifier = _args$0$split2[1];
var hits = args[1];
var eventName = args[2];
var additionalData = args[3] || {};
if (!hits) return [];
if ((eventType === "click" || eventType === "conversion") && !eventName) return [];
var hitsArray = Array.isArray(hits) ? hits : [hits];
if (hitsArray.length === 0) return [];
var queryID = hitsArray[0].__queryID;
var hitsChunks = chunk(hitsArray);
var objectIDsByChunk = hitsChunks.map(function(batch) {
return batch.map(function(hit) {
return hit.objectID;
});
});
var positionsByChunk = hitsChunks.map(function(batch) {
return batch.map(function(hit) {
return hit.__position;
});
});
if (eventType === "view") {
if (instantSearchInstance.status !== "idle") return [];
return hitsChunks.map(function(batch, i$3) {
var _helper$lastResults;
return {
insightsMethod: "viewedObjectIDs",
widgetType,
eventType,
payload: _objectSpread$19({
eventName: eventName || "Hits Viewed",
index: ((_helper$lastResults = helper.lastResults) === null || _helper$lastResults === void 0 ? void 0 : _helper$lastResults.index) || helper.state.index,
objectIDs: objectIDsByChunk[i$3]
}, additionalData),
hits: batch,
eventModifier
};
});
} else if (eventType === "click") return hitsChunks.map(function(batch, i$3) {
var _helper$lastResults2;
return {
insightsMethod: "clickedObjectIDsAfterSearch",
widgetType,
eventType,
payload: _objectSpread$19({
eventName: eventName || "Hit Clicked",
index: ((_helper$lastResults2 = helper.lastResults) === null || _helper$lastResults2 === void 0 ? void 0 : _helper$lastResults2.index) || helper.state.index,
queryID,
objectIDs: objectIDsByChunk[i$3],
positions: positionsByChunk[i$3]
}, additionalData),
hits: batch,
eventModifier
};
});
else if (eventType === "conversion") return hitsChunks.map(function(batch, i$3) {
var _helper$lastResults3;
return {
insightsMethod: "convertedObjectIDsAfterSearch",
widgetType,
eventType,
payload: _objectSpread$19({
eventName: eventName || "Hit Converted",
index: ((_helper$lastResults3 = helper.lastResults) === null || _helper$lastResults3 === void 0 ? void 0 : _helper$lastResults3.index) || helper.state.index,
queryID,
objectIDs: objectIDsByChunk[i$3]
}, additionalData),
hits: batch,
eventModifier
};
});
else return [];
}
function createSendEventForHits(_ref2) {
var instantSearchInstance = _ref2.instantSearchInstance, helper = _ref2.helper, widgetType = _ref2.widgetType;
var sentEvents = {};
var timer = void 0;
var sendEventForHits = function sendEventForHits$1() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
var payloads = _buildEventPayloadsForHits({
widgetType,
helper,
methodName: "sendEvent",
args,
instantSearchInstance
});
payloads.forEach(function(payload) {
if (payload.eventType === "click" && payload.eventModifier === "internal" && sentEvents[payload.eventType]) return;
sentEvents[payload.eventType] = true;
instantSearchInstance.sendEventToInsights(payload);
});
clearTimeout(timer);
timer = setTimeout(function() {
sentEvents = {};
}, 0);
};
return sendEventForHits;
}
function createBindEventForHits(_ref3) {
var helper = _ref3.helper, widgetType = _ref3.widgetType, instantSearchInstance = _ref3.instantSearchInstance;
var bindEventForHits = function bindEventForHits$1() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2];
var payloads = _buildEventPayloadsForHits({
widgetType,
helper,
methodName: "bindEvent",
args,
instantSearchInstance
});
return payloads.length ? "data-insights-event=".concat(serializePayload(payloads)) : "";
};
return bindEventForHits;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/isIndexWidget.js
function isIndexWidget(widget) {
return widget.$$type === "ais.index";
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/setIndexHelperState.js
function setIndexHelperState(finalUiState, indexWidget) {
var nextIndexUiState = finalUiState[indexWidget.getIndexId()] || {};
indexWidget.getHelper().setState(indexWidget.getWidgetSearchParameters(indexWidget.getHelper().state, { uiState: nextIndexUiState }));
indexWidget.getWidgets().filter(isIndexWidget).forEach(function(widget) {
return setIndexHelperState(finalUiState, widget);
});
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/defer.js
var nextMicroTask = Promise.resolve();
function defer(callback) {
var progress = null;
var cancelled = false;
var fn$1 = function fn$2() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
if (progress !== null) return;
progress = nextMicroTask.then(function() {
progress = null;
if (cancelled) {
cancelled = false;
return;
}
callback.apply(void 0, args);
});
};
fn$1.wait = function() {
if (progress === null) throw new Error("The deferred function should be called before calling `wait()`");
return progress;
};
fn$1.cancel = function() {
if (progress === null) return;
cancelled = true;
};
return fn$1;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/documentation.js
function createDocumentationLink(_ref) {
var name$2 = _ref.name, _ref$connector = _ref.connector, connector = _ref$connector === void 0 ? false : _ref$connector;
return [
"https://www.algolia.com/doc/api-reference/widgets/",
name$2,
"/js/",
connector ? "#connector" : ""
].join("");
}
function createDocumentationMessageGenerator() {
for (var _len = arguments.length, widgets = new Array(_len), _key = 0; _key < _len; _key++) widgets[_key] = arguments[_key];
var links = widgets.map(function(widget) {
return createDocumentationLink(widget);
}).join(", ");
return function(message) {
return [message, "See documentation: ".concat(links)].filter(Boolean).join("\n\n");
};
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/find.js
function find(items, predicate) {
var value;
for (var i$3 = 0; i$3 < items.length; i$3++) {
value = items[i$3];
if (predicate(value, i$3, items)) return value;
}
return void 0;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/findIndex.js
function findIndex(array$1, comparator) {
if (!Array.isArray(array$1)) return -1;
for (var i$3 = 0; i$3 < array$1.length; i$3++) if (comparator(array$1[i$3])) return i$3;
return -1;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/getAppIdAndApiKey.js
function getAppIdAndApiKey(searchClient) {
if (searchClient.appId && searchClient.apiKey) return [searchClient.appId, searchClient.apiKey];
else if (searchClient.transporter) {
var transporter = searchClient.transporter;
var headers = transporter.headers || transporter.baseHeaders;
var queryParameters = transporter.queryParameters || transporter.baseQueryParameters;
var APP_ID = "x-algolia-application-id";
var API_KEY = "x-algolia-api-key";
var appId = headers[APP_ID] || queryParameters[APP_ID];
var apiKey = headers[API_KEY] || queryParameters[API_KEY];
return [appId, apiKey];
} else return [searchClient.applicationID, searchClient.apiKey];
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/getHighlightedParts.js
function getHighlightedParts(highlightedValue) {
var highlightPostTag = TAG_REPLACEMENT.highlightPostTag, highlightPreTag = TAG_REPLACEMENT.highlightPreTag;
var splitByPreTag = highlightedValue.split(highlightPreTag);
var firstValue = splitByPreTag.shift();
var elements = !firstValue ? [] : [{
value: firstValue,
isHighlighted: false
}];
splitByPreTag.forEach(function(split$1) {
var splitByPostTag = split$1.split(highlightPostTag);
elements.push({
value: splitByPostTag[0],
isHighlighted: true
});
if (splitByPostTag[1] !== "") elements.push({
value: splitByPostTag[1],
isHighlighted: false
});
});
return elements;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/getHighlightFromSiblings.js
var hasAlphanumeric = new RegExp(/\w/i);
function getHighlightFromSiblings(parts, i$3) {
var _parts, _parts2;
var current = parts[i$3];
var isNextHighlighted = ((_parts = parts[i$3 + 1]) === null || _parts === void 0 ? void 0 : _parts.isHighlighted) || true;
var isPreviousHighlighted = ((_parts2 = parts[i$3 - 1]) === null || _parts2 === void 0 ? void 0 : _parts2.isHighlighted) || true;
if (!hasAlphanumeric.test(unescape$1(current.value)) && isPreviousHighlighted === isNextHighlighted) return isPreviousHighlighted;
return current.isHighlighted;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/getPropertyByPath.js
function getPropertyByPath(object$2, path) {
var parts = Array.isArray(path) ? path : path.split(".");
return parts.reduce(function(current, key) {
return current && current[key];
}, object$2);
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/hits-absolute-position.js
function _typeof$22(o$3) {
"@babel/helpers - typeof";
return _typeof$22 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$22(o$3);
}
function ownKeys$18(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$18(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$18(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$19(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$18(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$19(obj, key, value) {
key = _toPropertyKey$19(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$19(t$2) {
var i$3 = _toPrimitive$19(t$2, "string");
return "symbol" == _typeof$22(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$19(t$2, r$2) {
if ("object" != _typeof$22(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$22(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function addAbsolutePosition(hits, page, hitsPerPage) {
return hits.map(function(hit, idx) {
return _objectSpread$18(_objectSpread$18({}, hit), {}, { __position: hitsPerPage * page + idx + 1 });
});
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/hits-query-id.js
function _typeof$21(o$3) {
"@babel/helpers - typeof";
return _typeof$21 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$21(o$3);
}
function ownKeys$17(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$17(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$17(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$18(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$17(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$18(obj, key, value) {
key = _toPropertyKey$18(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$18(t$2) {
var i$3 = _toPrimitive$18(t$2, "string");
return "symbol" == _typeof$21(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$18(t$2, r$2) {
if ("object" != _typeof$21(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$21(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function addQueryID(hits, queryID) {
if (!queryID) return hits;
return hits.map(function(hit) {
return _objectSpread$17(_objectSpread$17({}, hit), {}, { __queryID: queryID });
});
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/hydrateRecommendCache.js
function _typeof$20(o$3) {
"@babel/helpers - typeof";
return _typeof$20 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$20(o$3);
}
function ownKeys$16(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$16(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$16(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$17(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$16(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$17(obj, key, value) {
key = _toPropertyKey$17(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$17(t$2) {
var i$3 = _toPrimitive$17(t$2, "string");
return "symbol" == _typeof$20(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$17(t$2, r$2) {
if ("object" != _typeof$20(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$20(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function hydrateRecommendCache(helper, initialResults) {
var recommendCache = Object.keys(initialResults).reduce(function(acc, indexName) {
var initialResult = initialResults[indexName];
if (initialResult.recommendResults) return _objectSpread$16(_objectSpread$16({}, acc), initialResult.recommendResults.results);
return acc;
}, {});
helper._recommendCache = recommendCache;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/hydrateSearchClient.js
function _typeof$19(o$3) {
"@babel/helpers - typeof";
return _typeof$19 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$19(o$3);
}
function _slicedToArray$6(arr, i$3) {
return _arrayWithHoles$6(arr) || _iterableToArrayLimit$6(arr, i$3) || _unsupportedIterableToArray$7(arr, i$3) || _nonIterableRest$6();
}
function _nonIterableRest$6() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$7(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray$7(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray$7(o$3, minLen);
}
function _arrayLikeToArray$7(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
function _iterableToArrayLimit$6(r$2, l$2) {
var t$2 = null == r$2 ? null : "undefined" != typeof Symbol && r$2[Symbol.iterator] || r$2["@@iterator"];
if (null != t$2) {
var e$2, n$1, i$3, u$3, a$2 = [], f$3 = !0, o$3 = !1;
try {
if (i$3 = (t$2 = t$2.call(r$2)).next, 0 === l$2) {
if (Object(t$2) !== t$2) return;
f$3 = !1;
} else for (; !(f$3 = (e$2 = i$3.call(t$2)).done) && (a$2.push(e$2.value), a$2.length !== l$2); f$3 = !0);
} catch (r$3) {
o$3 = !0, n$1 = r$3;
} finally {
try {
if (!f$3 && null != t$2.return && (u$3 = t$2.return(), Object(u$3) !== u$3)) return;
} finally {
if (o$3) throw n$1;
}
}
return a$2;
}
}
function _arrayWithHoles$6(arr) {
if (Array.isArray(arr)) return arr;
}
function ownKeys$15(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$15(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$15(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$16(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$15(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$16(obj, key, value) {
key = _toPropertyKey$16(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$16(t$2) {
var i$3 = _toPrimitive$16(t$2, "string");
return "symbol" == _typeof$19(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$16(t$2, r$2) {
if ("object" != _typeof$19(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$19(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function hydrateSearchClient(client, results) {
if (!results) return;
if ((!("transporter" in client) || client._cacheHydrated) && (!client._useCache || typeof client.addAlgoliaAgent !== "function")) return;
var cachedRequest = [Object.keys(results).reduce(function(acc, key) {
var _results$key = results[key], state = _results$key.state, requestParams = _results$key.requestParams, serverResults = _results$key.results;
var mappedResults = serverResults && state ? serverResults.map(function(result, idx) {
return _objectSpread$15({ indexName: state.index || result.index }, requestParams !== null && requestParams !== void 0 && requestParams[idx] || result.params ? { params: serializeQueryParameters((requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || deserializeQueryParameters(result.params)) } : {});
}) : [];
return acc.concat(mappedResults);
}, [])];
var cachedResults = Object.keys(results).reduce(function(acc, key) {
var res = results[key].results;
if (!res) return acc;
return acc.concat(res);
}, []);
if ("transporter" in client && !client._cacheHydrated) {
client._cacheHydrated = true;
var baseMethod = client.search.bind(client);
client.search = function(requests) {
for (var _len = arguments.length, methodArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) methodArgs[_key - 1] = arguments[_key];
var requestsWithSerializedParams = Array.isArray(requests) ? requests.map(function(request) {
return _objectSpread$15(_objectSpread$15({}, request), {}, { params: serializeQueryParameters(request.params) });
}) : serializeQueryParameters(requests.requestBody.params);
return client.transporter.responsesCache.get({
method: "search",
args: [requestsWithSerializedParams].concat(methodArgs)
}, function() {
return baseMethod.apply(void 0, [requests].concat(methodArgs));
});
};
client.transporter.responsesCache.set({
method: "search",
args: cachedRequest
}, { results: cachedResults });
}
if (!("transporter" in client)) {
var cacheKey = "/1/indexes/*/queries_body_".concat(JSON.stringify({ requests: cachedRequest }));
client.cache = _objectSpread$15(_objectSpread$15({}, client.cache), {}, _defineProperty$16({}, cacheKey, JSON.stringify({ results: Object.keys(results).map(function(key) {
return results[key].results;
}) })));
}
}
function deserializeQueryParameters(parameters) {
return parameters.split("&").reduce(function(acc, parameter) {
var _parameter$split = parameter.split("="), _parameter$split2 = _slicedToArray$6(_parameter$split, 2), key = _parameter$split2[0], value = _parameter$split2[1];
acc[key] = value ? decodeURIComponent(value) : "";
return acc;
}, {});
}
function serializeQueryParameters(parameters) {
var isObjectOrArray = function isObjectOrArray$1(value) {
return Object.prototype.toString.call(value) === "[object Object]" || Object.prototype.toString.call(value) === "[object Array]";
};
var encode$1 = function encode$2(format$1) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) args[_key2 - 1] = arguments[_key2];
var i$3 = 0;
return format$1.replace(/%s/g, function() {
return encodeURIComponent(args[i$3++]);
});
};
return Object.keys(parameters).map(function(key) {
return encode$1("%s=%s", key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]);
}).join("&");
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/isEqual.js
function isPrimitive(obj) {
return obj !== Object(obj);
}
function isEqual(first, second) {
if (first === second) return true;
if (isPrimitive(first) || isPrimitive(second) || typeof first === "function" || typeof second === "function") return first === second;
if (Object.keys(first).length !== Object.keys(second).length) return false;
for (var _i = 0, _Object$keys = Object.keys(first); _i < _Object$keys.length; _i++) {
var key = _Object$keys[_i];
if (!(key in second)) return false;
if (!isEqual(first[key], second[key])) return false;
}
return true;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/uniq.js
function uniq(array$1) {
return array$1.filter(function(value, index$1, self) {
return self.indexOf(value) === index$1;
});
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/mergeSearchParameters.js
function _typeof$18(o$3) {
"@babel/helpers - typeof";
return _typeof$18 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$18(o$3);
}
var _excluded$7 = [
"facets",
"disjunctiveFacets",
"facetsRefinements",
"facetsExcludes",
"disjunctiveFacetsRefinements",
"numericRefinements",
"tagRefinements",
"hierarchicalFacets",
"hierarchicalFacetsRefinements",
"ruleContexts"
];
function ownKeys$14(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$14(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$14(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$15(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$14(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$15(obj, key, value) {
key = _toPropertyKey$15(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$15(t$2) {
var i$3 = _toPrimitive$15(t$2, "string");
return "symbol" == _typeof$18(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$15(t$2, r$2) {
if ("object" != _typeof$18(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$18(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function _objectWithoutProperties$7(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose$7(source, excluded);
var key, i$3;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i$3 = 0; i$3 < sourceSymbolKeys.length; i$3++) {
key = sourceSymbolKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose$7(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i$3;
for (i$3 = 0; i$3 < sourceKeys.length; i$3++) {
key = sourceKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var mergeWithRest = function mergeWithRest$1(left, right) {
var facets = right.facets, disjunctiveFacets = right.disjunctiveFacets, facetsRefinements = right.facetsRefinements, facetsExcludes = right.facetsExcludes, disjunctiveFacetsRefinements = right.disjunctiveFacetsRefinements, numericRefinements = right.numericRefinements, tagRefinements = right.tagRefinements, hierarchicalFacets = right.hierarchicalFacets, hierarchicalFacetsRefinements = right.hierarchicalFacetsRefinements, ruleContexts = right.ruleContexts, rest = _objectWithoutProperties$7(right, _excluded$7);
return left.setQueryParameters(rest);
};
var mergeFacets = function mergeFacets$1(left, right) {
return right.facets.reduce(function(_$3, name$2) {
return _$3.addFacet(name$2);
}, left);
};
var mergeDisjunctiveFacets = function mergeDisjunctiveFacets$1(left, right) {
return right.disjunctiveFacets.reduce(function(_$3, name$2) {
return _$3.addDisjunctiveFacet(name$2);
}, left);
};
var mergeHierarchicalFacets = function mergeHierarchicalFacets$1(left, right) {
return left.setQueryParameters({ hierarchicalFacets: right.hierarchicalFacets.reduce(function(facets, facet) {
var index$1 = findIndex(facets, function(_$3) {
return _$3.name === facet.name;
});
if (index$1 === -1) return facets.concat(facet);
var nextFacets = facets.slice();
nextFacets.splice(index$1, 1, facet);
return nextFacets;
}, left.hierarchicalFacets) });
};
var mergeTagRefinements = function mergeTagRefinements$1(left, right) {
return right.tagRefinements.reduce(function(_$3, value) {
return _$3.addTagRefinement(value);
}, left);
};
var mergeFacetRefinements = function mergeFacetRefinements$1(left, right) {
return left.setQueryParameters({ facetsRefinements: _objectSpread$14(_objectSpread$14({}, left.facetsRefinements), right.facetsRefinements) });
};
var mergeFacetsExcludes = function mergeFacetsExcludes$1(left, right) {
return left.setQueryParameters({ facetsExcludes: _objectSpread$14(_objectSpread$14({}, left.facetsExcludes), right.facetsExcludes) });
};
var mergeDisjunctiveFacetsRefinements = function mergeDisjunctiveFacetsRefinements$1(left, right) {
return left.setQueryParameters({ disjunctiveFacetsRefinements: _objectSpread$14(_objectSpread$14({}, left.disjunctiveFacetsRefinements), right.disjunctiveFacetsRefinements) });
};
var mergeNumericRefinements = function mergeNumericRefinements$1(left, right) {
return left.setQueryParameters({ numericRefinements: _objectSpread$14(_objectSpread$14({}, left.numericRefinements), right.numericRefinements) });
};
var mergeHierarchicalFacetsRefinements = function mergeHierarchicalFacetsRefinements$1(left, right) {
return left.setQueryParameters({ hierarchicalFacetsRefinements: _objectSpread$14(_objectSpread$14({}, left.hierarchicalFacetsRefinements), right.hierarchicalFacetsRefinements) });
};
var mergeRuleContexts = function mergeRuleContexts$1(left, right) {
var ruleContexts = uniq([].concat(left.ruleContexts).concat(right.ruleContexts).filter(Boolean));
if (ruleContexts.length > 0) return left.setQueryParameters({ ruleContexts });
return left;
};
var mergeSearchParameters = function mergeSearchParameters$1() {
for (var _len = arguments.length, parameters = new Array(_len), _key = 0; _key < _len; _key++) parameters[_key] = arguments[_key];
return parameters.reduce(function(left, right) {
var hierarchicalFacetsRefinementsMerged = mergeHierarchicalFacetsRefinements(left, right);
var hierarchicalFacetsMerged = mergeHierarchicalFacets(hierarchicalFacetsRefinementsMerged, right);
var tagRefinementsMerged = mergeTagRefinements(hierarchicalFacetsMerged, right);
var numericRefinementsMerged = mergeNumericRefinements(tagRefinementsMerged, right);
var disjunctiveFacetsRefinementsMerged = mergeDisjunctiveFacetsRefinements(numericRefinementsMerged, right);
var facetsExcludesMerged = mergeFacetsExcludes(disjunctiveFacetsRefinementsMerged, right);
var facetRefinementsMerged = mergeFacetRefinements(facetsExcludesMerged, right);
var disjunctiveFacetsMerged = mergeDisjunctiveFacets(facetRefinementsMerged, right);
var ruleContextsMerged = mergeRuleContexts(disjunctiveFacetsMerged, right);
var facetsMerged = mergeFacets(ruleContextsMerged, right);
return mergeWithRest(facetsMerged, right);
});
};
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/render-args.js
function createInitArgs(instantSearchInstance, parent, uiState) {
var helper = parent.getHelper();
return {
uiState,
helper,
parent,
instantSearchInstance,
state: helper.state,
renderState: instantSearchInstance.renderState,
templatesConfig: instantSearchInstance.templatesConfig,
createURL: parent.createURL,
scopedResults: [],
searchMetadata: { isSearchStalled: instantSearchInstance.status === "stalled" },
status: instantSearchInstance.status,
error: instantSearchInstance.error
};
}
function createRenderArgs(instantSearchInstance, parent, widget) {
var results = parent.getResultsForWidget(widget);
var helper = parent.getHelper();
return {
helper,
parent,
instantSearchInstance,
results,
scopedResults: parent.getScopedResults(),
state: results && "_state" in results ? results._state : helper.state,
renderState: instantSearchInstance.renderState,
templatesConfig: instantSearchInstance.templatesConfig,
createURL: parent.createURL,
searchMetadata: { isSearchStalled: instantSearchInstance.status === "stalled" },
status: instantSearchInstance.status,
error: instantSearchInstance.error
};
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/resolveSearchParameters.js
function resolveSearchParameters(current) {
var parent = current.getParent();
var states = [current.getHelper().state];
while (parent !== null) {
states = [parent.getHelper().state].concat(states);
parent = parent.getParent();
}
return states;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/reverseHighlightedParts.js
function _typeof$17(o$3) {
"@babel/helpers - typeof";
return _typeof$17 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$17(o$3);
}
function ownKeys$13(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$13(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$13(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$14(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$13(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$14(obj, key, value) {
key = _toPropertyKey$14(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$14(t$2) {
var i$3 = _toPrimitive$14(t$2, "string");
return "symbol" == _typeof$17(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$14(t$2, r$2) {
if ("object" != _typeof$17(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$17(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function reverseHighlightedParts(parts) {
if (!parts.some(function(part) {
return part.isHighlighted;
})) return parts.map(function(part) {
return _objectSpread$13(_objectSpread$13({}, part), {}, { isHighlighted: false });
});
return parts.map(function(part, i$3) {
return _objectSpread$13(_objectSpread$13({}, part), {}, { isHighlighted: !getHighlightFromSiblings(parts, i$3) });
});
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/safelyRunOnBrowser.js
/**
* Runs code on browser environments safely.
*/
function safelyRunOnBrowser(callback) {
var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { fallback: function fallback$1() {
return void 0;
} }, fallback = _ref.fallback;
if (typeof window === "undefined") return fallback();
return callback({ window });
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/connectors/configure/connectConfigure.js
var import_algoliasearch_helper$3 = __toESM(require_algoliasearch_helper());
function _typeof$16(o$3) {
"@babel/helpers - typeof";
return _typeof$16 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$16(o$3);
}
function ownKeys$12(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$12(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$12(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$13(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$12(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$13(obj, key, value) {
key = _toPropertyKey$13(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$13(t$2) {
var i$3 = _toPrimitive$13(t$2, "string");
return "symbol" == _typeof$16(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$13(t$2, r$2) {
if ("object" != _typeof$16(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$16(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
/**
* Refine the given search parameters.
*/
var withUsage$4 = createDocumentationMessageGenerator({
name: "configure",
connector: true
});
function getInitialSearchParameters(state, widgetParams) {
return state.setQueryParameters(Object.keys(widgetParams.searchParameters).reduce(function(acc, key) {
return _objectSpread$12(_objectSpread$12({}, acc), {}, _defineProperty$13({}, key, void 0));
}, {}));
}
var connectConfigure = function connectConfigure$1() {
var renderFn = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : noop$1;
var unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop$1;
return function(widgetParams) {
if (!widgetParams || !isPlainObject$1(widgetParams.searchParameters)) throw new Error(withUsage$4("The `searchParameters` option expects an object."));
var connectorState = {};
function refine$1(helper) {
return function(searchParameters) {
var actualState = getInitialSearchParameters(helper.state, widgetParams);
var nextSearchParameters = mergeSearchParameters(actualState, new import_algoliasearch_helper$3.default.SearchParameters(searchParameters));
widgetParams.searchParameters = searchParameters;
helper.setState(nextSearchParameters).search();
};
}
return {
$$type: "ais.configure",
init: function init(initOptions) {
var instantSearchInstance = initOptions.instantSearchInstance;
renderFn(_objectSpread$12(_objectSpread$12({}, this.getWidgetRenderState(initOptions)), {}, { instantSearchInstance }), true);
},
render: function render(renderOptions) {
var instantSearchInstance = renderOptions.instantSearchInstance;
renderFn(_objectSpread$12(_objectSpread$12({}, this.getWidgetRenderState(renderOptions)), {}, { instantSearchInstance }), false);
},
dispose: function dispose(_ref) {
var state = _ref.state;
unmountFn();
return getInitialSearchParameters(state, widgetParams);
},
getRenderState: function getRenderState(renderState, renderOptions) {
var _renderState$configur;
var widgetRenderState = this.getWidgetRenderState(renderOptions);
return _objectSpread$12(_objectSpread$12({}, renderState), {}, { configure: _objectSpread$12(_objectSpread$12({}, widgetRenderState), {}, { widgetParams: _objectSpread$12(_objectSpread$12({}, widgetRenderState.widgetParams), {}, { searchParameters: mergeSearchParameters(new import_algoliasearch_helper$3.default.SearchParameters((_renderState$configur = renderState.configure) === null || _renderState$configur === void 0 ? void 0 : _renderState$configur.widgetParams.searchParameters), new import_algoliasearch_helper$3.default.SearchParameters(widgetRenderState.widgetParams.searchParameters)).getQueryParams() }) }) });
},
getWidgetRenderState: function getWidgetRenderState(_ref2) {
var helper = _ref2.helper;
if (!connectorState.refine) connectorState.refine = refine$1(helper);
return {
refine: connectorState.refine,
widgetParams
};
},
getWidgetSearchParameters: function getWidgetSearchParameters(state, _ref3) {
var uiState = _ref3.uiState;
return mergeSearchParameters(state, new import_algoliasearch_helper$3.default.SearchParameters(_objectSpread$12(_objectSpread$12({}, uiState.configure), widgetParams.searchParameters)));
},
getWidgetUiState: function getWidgetUiState(uiState) {
return _objectSpread$12(_objectSpread$12({}, uiState), {}, { configure: _objectSpread$12(_objectSpread$12({}, uiState.configure), widgetParams.searchParameters) });
}
};
};
};
var connectConfigure_default = connectConfigure;
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/dequal.js
function _typeof$15(o$3) {
"@babel/helpers - typeof";
return _typeof$15 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$15(o$3);
}
var has$3 = Object.prototype.hasOwnProperty;
function dequal(foo, bar, compare) {
if (compare !== null && compare !== void 0 && compare(foo, bar)) return true;
var ctor;
var len;
if (foo === bar) return true;
if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
if (ctor === Date) return foo.getTime() === bar.getTime();
if (ctor === RegExp) return foo.toString() === bar.toString();
if (ctor === Array) {
if ((len = foo.length) === bar.length) while (len-- && dequal(foo[len], bar[len], compare));
return len === -1;
}
if (!ctor || _typeof$15(foo) === "object") {
len = 0;
for (ctor in foo) {
if (has$3.call(foo, ctor) && ++len && !has$3.call(bar, ctor)) return false;
if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor], compare)) return false;
}
return Object.keys(bar).length === len;
}
}
return foo !== foo && bar !== bar;
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/createSearchResults.js
var import_algoliasearch_helper$2 = __toESM(require_algoliasearch_helper(), 1);
function createSearchResults(state) {
var _state$query, _state$page, _state$hitsPerPage;
return new import_algoliasearch_helper$2.default.SearchResults(state, [{
query: (_state$query = state.query) !== null && _state$query !== void 0 ? _state$query : "",
page: (_state$page = state.page) !== null && _state$page !== void 0 ? _state$page : 0,
hitsPerPage: (_state$hitsPerPage = state.hitsPerPage) !== null && _state$hitsPerPage !== void 0 ? _state$hitsPerPage : 20,
hits: [],
nbHits: 0,
nbPages: 0,
params: "",
exhaustiveNbHits: true,
exhaustiveFacetsCount: true,
processingTimeMS: 0,
index: state.index
}], { __isArtificial: true });
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/getIndexSearchResults.js
function _typeof$14(o$3) {
"@babel/helpers - typeof";
return _typeof$14 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$14(o$3);
}
function ownKeys$11(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$11(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$11(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$12(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$11(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$12(obj, key, value) {
key = _toPropertyKey$12(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$12(t$2) {
var i$3 = _toPrimitive$12(t$2, "string");
return "symbol" == _typeof$14(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$12(t$2, r$2) {
if ("object" != _typeof$14(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$14(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function getIndexSearchResults(indexWidget) {
var helper = indexWidget.getHelper();
var results = indexWidget.getResults() || createSearchResults(helper.state);
var scopedResults = indexWidget.getScopedResults().map(function(scopedResult) {
var fallbackResults = scopedResult.indexId === indexWidget.getIndexId() ? results : createSearchResults(scopedResult.helper.state);
return _objectSpread$11(_objectSpread$11({}, scopedResult), {}, { results: scopedResult.results || fallbackResults });
});
return {
results,
scopedResults,
recommendResults: helper.lastRecommendResults
};
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/IndexContext.js
init_compat_module();
var IndexContext = /* @__PURE__ */ Q$1(null);
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/invariant.js
/**
* Throws an error if the condition is not met.
*
* The error is exhaustive in development, and becomes generic in production.
*
* This is used to make development a better experience to provide guidance as
* to where the error comes from.
*/
function invariant(condition, message) {
if (condition) return;
throw new Error("Invariant failed");
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useIndexContext.js
init_compat_module();
function useIndexContext() {
var context = x$1(IndexContext);
invariant(context !== null, "The <Index> component must be used within <InstantSearch>.");
return context;
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/InstantSearchContext.js
init_compat_module();
var InstantSearchContext = /* @__PURE__ */ Q$1(null);
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useInstantSearchContext.js
init_compat_module();
function useInstantSearchContext() {
var search = x$1(InstantSearchContext);
invariant(search !== null, "Hooks must be used inside the <InstantSearch> component.\n\nThey are not compatible with the `react-instantsearch-core@6.x` and `react-instantsearch-dom` packages, so make sure to use the <InstantSearch> component from `react-instantsearch-core@7.x`.");
return search;
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/components/InstantSearchServerContext.js
init_compat_module();
var InstantSearchServerContext = /* @__PURE__ */ Q$1(null);
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useInstantSearchServerContext.js
init_compat_module();
function useInstantSearchServerContext() {
return x$1(InstantSearchServerContext);
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/InstantSearchSSRContext.js
init_compat_module();
var InstantSearchSSRContext = /* @__PURE__ */ Q$1(null);
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useInstantSearchSSRContext.js
init_compat_module();
function useInstantSearchSSRContext() {
return x$1(InstantSearchSSRContext);
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useStableValue.js
init_compat_module();
function _slicedToArray$5(arr, i$3) {
return _arrayWithHoles$5(arr) || _iterableToArrayLimit$5(arr, i$3) || _unsupportedIterableToArray$6(arr, i$3) || _nonIterableRest$5();
}
function _nonIterableRest$5() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$6(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray$6(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray$6(o$3, minLen);
}
function _arrayLikeToArray$6(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
function _iterableToArrayLimit$5(r$2, l$2) {
var t$2 = null == r$2 ? null : "undefined" != typeof Symbol && r$2[Symbol.iterator] || r$2["@@iterator"];
if (null != t$2) {
var e$2, n$1, i$3, u$3, a$2 = [], f$3 = !0, o$3 = !1;
try {
if (i$3 = (t$2 = t$2.call(r$2)).next, 0 === l$2) {
if (Object(t$2) !== t$2) return;
f$3 = !1;
} else for (; !(f$3 = (e$2 = i$3.call(t$2)).done) && (a$2.push(e$2.value), a$2.length !== l$2); f$3 = !0);
} catch (r$3) {
o$3 = !0, n$1 = r$3;
} finally {
try {
if (!f$3 && null != t$2.return && (u$3 = t$2.return(), Object(u$3) !== u$3)) return;
} finally {
if (o$3) throw n$1;
}
}
return a$2;
}
}
function _arrayWithHoles$5(arr) {
if (Array.isArray(arr)) return arr;
}
function useStableValue(value) {
var _useState = d(function() {
return value;
}), _useState2 = _slicedToArray$5(_useState, 2), stableValue = _useState2[0], setStableValue = _useState2[1];
if (!dequal(stableValue, value)) setStableValue(value);
return stableValue;
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/use.js
init_compat_module();
var useKey = "use";
var use = compat_module_exports[useKey];
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useIsomorphicLayoutEffect.js
init_compat_module();
/**
* `useLayoutEffect` that doesn't show a warning when server-side rendering.
*
* It uses `useEffect` on the server (no-op), and `useLayoutEffect` on the browser.
*/
var useIsomorphicLayoutEffect = typeof window !== "undefined" ? _ : y;
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/InstantSearchRSCContext.js
init_compat_module();
var InstantSearchRSCContext = /* @__PURE__ */ Q$1({
countRef: { current: 0 },
waitForResultsRef: null,
ignoreMultipleHooksWarning: false
});
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useRSCContext.js
init_compat_module();
function useRSCContext() {
return x$1(InstantSearchRSCContext);
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useWidget.js
init_compat_module();
function useWidget(_ref) {
var _waitForResultsRef$cu, _waitForResultsRef$cu2;
var widget = _ref.widget, parentIndex = _ref.parentIndex, props = _ref.props, shouldSsr = _ref.shouldSsr, skipSuspense = _ref.skipSuspense;
var _useRSCContext = useRSCContext(), waitForResultsRef = _useRSCContext.waitForResultsRef, countRef = _useRSCContext.countRef, ignoreMultipleHooksWarning = _useRSCContext.ignoreMultipleHooksWarning;
var prevPropsRef = A(props);
y(function() {
prevPropsRef.current = props;
}, [props]);
var prevWidgetRef = A(widget);
y(function() {
prevWidgetRef.current = widget;
}, [widget]);
var cleanupTimerRef = A(null);
var shouldAddWidgetEarly = shouldSsr && !parentIndex.getWidgets().includes(widget);
var search = useInstantSearchContext();
useIsomorphicLayoutEffect(function() {
var previousWidget = prevWidgetRef.current;
if (!cleanupTimerRef.current) {
if (!shouldSsr) parentIndex.addWidgets([widget]);
} else {
clearTimeout(cleanupTimerRef.current);
var arePropsEqual = dequal(props, prevPropsRef.current);
if (!arePropsEqual) {
parentIndex.removeWidgets([previousWidget]);
parentIndex.addWidgets([widget]);
}
}
return function() {
cleanupTimerRef.current = setTimeout(function() {
search._schedule(function() {
if (search._preventWidgetCleanup) return;
parentIndex.removeWidgets([previousWidget]);
});
});
};
}, [
parentIndex,
widget,
shouldSsr,
search,
props
]);
if (shouldAddWidgetEarly || (waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef$cu = waitForResultsRef.current) === null || _waitForResultsRef$cu === void 0 ? void 0 : _waitForResultsRef$cu.status) === "pending") parentIndex.addWidgets([widget]);
if (waitForResultsRef !== null && waitForResultsRef !== void 0 && waitForResultsRef.current && !skipSuspense) {
var _search$helper;
use(waitForResultsRef.current);
if (widget.$$type !== "ais.dynamicWidgets" && (_search$helper = search.helper) !== null && _search$helper !== void 0 && _search$helper.lastResults) use(waitForResultsRef.current);
}
if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef$cu2 = waitForResultsRef.current) === null || _waitForResultsRef$cu2 === void 0 ? void 0 : _waitForResultsRef$cu2.status) === "fulfilled") countRef.current += 1;
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/hooks/useConnector.js
init_compat_module();
function _typeof$13(o$3) {
"@babel/helpers - typeof";
return _typeof$13 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$13(o$3);
}
var _excluded$6 = ["skipSuspense"], _excluded2$1 = ["instantSearchInstance", "widgetParams"], _excluded3 = ["widgetParams"];
function _slicedToArray$4(arr, i$3) {
return _arrayWithHoles$4(arr) || _iterableToArrayLimit$4(arr, i$3) || _unsupportedIterableToArray$5(arr, i$3) || _nonIterableRest$4();
}
function _nonIterableRest$4() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$5(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray$5(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray$5(o$3, minLen);
}
function _arrayLikeToArray$5(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
function _iterableToArrayLimit$4(r$2, l$2) {
var t$2 = null == r$2 ? null : "undefined" != typeof Symbol && r$2[Symbol.iterator] || r$2["@@iterator"];
if (null != t$2) {
var e$2, n$1, i$3, u$3, a$2 = [], f$3 = !0, o$3 = !1;
try {
if (i$3 = (t$2 = t$2.call(r$2)).next, 0 === l$2) {
if (Object(t$2) !== t$2) return;
f$3 = !1;
} else for (; !(f$3 = (e$2 = i$3.call(t$2)).done) && (a$2.push(e$2.value), a$2.length !== l$2); f$3 = !0);
} catch (r$3) {
o$3 = !0, n$1 = r$3;
} finally {
try {
if (!f$3 && null != t$2.return && (u$3 = t$2.return(), Object(u$3) !== u$3)) return;
} finally {
if (o$3) throw n$1;
}
}
return a$2;
}
}
function _arrayWithHoles$4(arr) {
if (Array.isArray(arr)) return arr;
}
function ownKeys$10(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$10(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$10(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$11(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$10(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$11(obj, key, value) {
key = _toPropertyKey$11(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$11(t$2) {
var i$3 = _toPrimitive$11(t$2, "string");
return "symbol" == _typeof$13(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$11(t$2, r$2) {
if ("object" != _typeof$13(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$13(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function _objectWithoutProperties$6(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose$6(source, excluded);
var key, i$3;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i$3 = 0; i$3 < sourceSymbolKeys.length; i$3++) {
key = sourceSymbolKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose$6(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i$3;
for (i$3 = 0; i$3 < sourceKeys.length; i$3++) {
key = sourceKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function useConnector(connector) {
var props = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var _ref = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, _ref$skipSuspense = _ref.skipSuspense, skipSuspense = _ref$skipSuspense === void 0 ? false : _ref$skipSuspense, additionalWidgetProperties = _objectWithoutProperties$6(_ref, _excluded$6);
var serverContext = useInstantSearchServerContext();
var ssrContext = useInstantSearchSSRContext();
var search = useInstantSearchContext();
var parentIndex = useIndexContext();
var stableProps = useStableValue(props);
var stableAdditionalWidgetProperties = useStableValue(additionalWidgetProperties);
var shouldSetStateRef = A(true);
var previousRenderStateRef = A(null);
var previousStatusRef = A(search.status);
var widget = T(function() {
var createWidget = connector(function(connectorState, isFirstRender) {
if (isFirstRender) {
shouldSetStateRef.current = true;
return;
}
if (shouldSetStateRef.current) {
var instantSearchInstance = connectorState.instantSearchInstance, widgetParams = connectorState.widgetParams, renderState = _objectWithoutProperties$6(connectorState, _excluded2$1);
if (!dequal(renderState, previousRenderStateRef.current, function(a$2, b$3) {
return (a$2 === null || a$2 === void 0 ? void 0 : a$2.constructor) === Function && (b$3 === null || b$3 === void 0 ? void 0 : b$3.constructor) === Function;
}) || instantSearchInstance.status !== previousStatusRef.current) {
setState(renderState);
previousRenderStateRef.current = renderState;
previousStatusRef.current = instantSearchInstance.status;
}
}
}, function() {
shouldSetStateRef.current = false;
});
return _objectSpread$10(_objectSpread$10({}, createWidget(stableProps)), stableAdditionalWidgetProperties);
}, [
connector,
stableProps,
stableAdditionalWidgetProperties
]);
var _useState = d(function() {
if (widget.getWidgetRenderState) {
var _widget$getWidgetSear;
var helper = parentIndex.getHelper();
var uiState = parentIndex.getWidgetUiState({})[parentIndex.getIndexId()];
helper.state = ((_widget$getWidgetSear = widget.getWidgetSearchParameters) === null || _widget$getWidgetSear === void 0 ? void 0 : _widget$getWidgetSear.call(widget, helper.state, { uiState })) || helper.state;
var _getIndexSearchResult = getIndexSearchResults(parentIndex), results = _getIndexSearchResult.results, scopedResults = _getIndexSearchResult.scopedResults, recommendResults = _getIndexSearchResult.recommendResults;
var _widget$getWidgetRend = widget.getWidgetRenderState({
helper,
parent: parentIndex,
instantSearchInstance: search,
results: widget.dependsOn === "recommend" && recommendResults && ssrContext ? recommendResults[ssrContext.recommendIdx.current++] : results,
scopedResults,
state: helper.state,
renderState: search.renderState,
templatesConfig: search.templatesConfig,
createURL: parentIndex.createURL,
searchMetadata: { isSearchStalled: search.status === "stalled" },
status: search.status,
error: search.error
}), widgetParams = _widget$getWidgetRend.widgetParams, renderState = _objectWithoutProperties$6(_widget$getWidgetRend, _excluded3);
return renderState;
}
return {};
}), _useState2 = _slicedToArray$4(_useState, 2), state = _useState2[0], setState = _useState2[1];
useWidget({
widget,
parentIndex,
props: stableProps,
shouldSsr: Boolean(serverContext),
skipSuspense
});
return state;
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/connectors/useConfigure.js
function useConfigure(props, additionalWidgetProperties) {
return useConnector(connectConfigure_default, { searchParameters: props }, additionalWidgetProperties);
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/components/Configure.js
function _typeof$12(o$3) {
"@babel/helpers - typeof";
return _typeof$12 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$12(o$3);
}
function ownKeys$9(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$9(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$9(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$10(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$9(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$10(obj, key, value) {
key = _toPropertyKey$10(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$10(t$2) {
var i$3 = _toPrimitive$10(t$2, "string");
return "symbol" == _typeof$12(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$10(t$2, r$2) {
if ("object" != _typeof$12(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$12(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function Configure(props) {
useConfigure(_objectSpread$9({}, props), { $$widgetType: "ais.configure" });
return null;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/widgets/index/index.js
var import_algoliasearch_helper$1 = __toESM(require_algoliasearch_helper());
function _typeof$11(o$3) {
"@babel/helpers - typeof";
return _typeof$11 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$11(o$3);
}
var _excluded$5 = ["initialSearchParameters"], _excluded2 = ["initialRecommendParameters"];
function ownKeys$8(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$8(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$8(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$9(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$8(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$9(obj, key, value) {
key = _toPropertyKey$9(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$9(t$2) {
var i$3 = _toPrimitive$9(t$2, "string");
return "symbol" == _typeof$11(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$9(t$2, r$2) {
if ("object" != _typeof$11(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$11(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function _toConsumableArray$1(arr) {
return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$4(arr) || _nonIterableSpread$1();
}
function _nonIterableSpread$1() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$4(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray$4(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray$4(o$3, minLen);
}
function _iterableToArray$1(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles$1(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$4(arr);
}
function _arrayLikeToArray$4(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
function _objectWithoutProperties$5(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose$5(source, excluded);
var key, i$3;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i$3 = 0; i$3 < sourceSymbolKeys.length; i$3++) {
key = sourceSymbolKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose$5(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i$3;
for (i$3 = 0; i$3 < sourceKeys.length; i$3++) {
key = sourceKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var withUsage$3 = createDocumentationMessageGenerator({ name: "index-widget" });
/**
* This is the same content as helper._change / setState, but allowing for extra
* UiState to be synchronized.
* see: https://github.com/algolia/algoliasearch-helper-js/blob/6b835ffd07742f2d6b314022cce6848f5cfecd4a/src/algoliasearch.helper.js#L1311-L1324
*/
function privateHelperSetState(helper, _ref) {
var state = _ref.state, recommendState = _ref.recommendState, isPageReset = _ref.isPageReset, _uiState = _ref._uiState;
if (state !== helper.state) {
helper.state = state;
helper.emit("change", {
state: helper.state,
results: helper.lastResults,
isPageReset,
_uiState
});
}
if (recommendState !== helper.recommendState) helper.recommendState = recommendState;
}
function getLocalWidgetsUiState(widgets, widgetStateOptions) {
var initialUiState = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
return widgets.reduce(function(uiState, widget) {
if (isIndexWidget(widget)) return uiState;
if (!widget.getWidgetUiState && !widget.getWidgetState) return uiState;
if (widget.getWidgetUiState) return widget.getWidgetUiState(uiState, widgetStateOptions);
return widget.getWidgetState(uiState, widgetStateOptions);
}, initialUiState);
}
function getLocalWidgetsSearchParameters(widgets, widgetSearchParametersOptions) {
var initialSearchParameters = widgetSearchParametersOptions.initialSearchParameters, rest = _objectWithoutProperties$5(widgetSearchParametersOptions, _excluded$5);
return widgets.reduce(function(state, widget) {
if (!widget.getWidgetSearchParameters || isIndexWidget(widget)) return state;
if (widget.dependsOn === "search" && widget.getWidgetParameters) return widget.getWidgetParameters(state, rest);
return widget.getWidgetSearchParameters(state, rest);
}, initialSearchParameters);
}
function getLocalWidgetsRecommendParameters(widgets, widgetRecommendParametersOptions) {
var initialRecommendParameters = widgetRecommendParametersOptions.initialRecommendParameters, rest = _objectWithoutProperties$5(widgetRecommendParametersOptions, _excluded2);
return widgets.reduce(function(state, widget) {
if (!isIndexWidget(widget) && widget.dependsOn === "recommend" && widget.getWidgetParameters) return widget.getWidgetParameters(state, rest);
return state;
}, initialRecommendParameters);
}
function resetPageFromWidgets(widgets) {
var indexWidgets = widgets.filter(isIndexWidget);
if (indexWidgets.length === 0) return;
indexWidgets.forEach(function(widget) {
var widgetHelper = widget.getHelper();
privateHelperSetState(widgetHelper, {
state: widgetHelper.state.resetPage(),
recommendState: widgetHelper.recommendState,
isPageReset: true
});
resetPageFromWidgets(widget.getWidgets());
});
}
function resolveScopedResultsFromWidgets(widgets) {
var indexWidgets = widgets.filter(isIndexWidget);
return indexWidgets.reduce(function(scopedResults, current) {
return scopedResults.concat.apply(scopedResults, [{
indexId: current.getIndexId(),
results: current.getResults(),
helper: current.getHelper()
}].concat(_toConsumableArray$1(resolveScopedResultsFromWidgets(current.getWidgets()))));
}, []);
}
var index = function index$1(widgetParams) {
if (widgetParams === void 0 || widgetParams.indexName === void 0 && !widgetParams.EXPERIMENTAL_isolated) throw new Error(withUsage$3("The `indexName` option is required."));
var _widgetParams$indexNa = widgetParams.indexName, indexName = _widgetParams$indexNa === void 0 ? "" : _widgetParams$indexNa, _widgetParams$indexId = widgetParams.indexId, indexId = _widgetParams$indexId === void 0 ? indexName : _widgetParams$indexId, _widgetParams$EXPERIM = widgetParams.EXPERIMENTAL_isolated, isolated = _widgetParams$EXPERIM === void 0 ? false : _widgetParams$EXPERIM;
var localWidgets = [];
var localUiState = {};
var localInstantSearchInstance = null;
var localParent = null;
var helper = null;
var derivedHelper = null;
var lastValidSearchParameters = null;
var hasRecommendWidget = false;
var hasSearchWidget = false;
return {
$$type: "ais.index",
$$widgetType: "ais.index",
_isolated: isolated,
getIndexName: function getIndexName() {
return indexName;
},
getIndexId: function getIndexId() {
return indexId;
},
getHelper: function getHelper() {
return helper;
},
getResults: function getResults() {
var _derivedHelper;
if (!((_derivedHelper = derivedHelper) !== null && _derivedHelper !== void 0 && _derivedHelper.lastResults)) return null;
derivedHelper.lastResults._state = helper.state;
return derivedHelper.lastResults;
},
getResultsForWidget: function getResultsForWidget(widget) {
var _helper;
if (widget.dependsOn !== "recommend" || isIndexWidget(widget) || widget.$$id === void 0) return this.getResults();
if (!((_helper = helper) !== null && _helper !== void 0 && _helper.lastRecommendResults)) return null;
return helper.lastRecommendResults[widget.$$id];
},
getPreviousState: function getPreviousState() {
return lastValidSearchParameters;
},
getScopedResults: function getScopedResults() {
var widgetParent = this.getParent();
var widgetSiblings;
if (widgetParent) widgetSiblings = widgetParent.getWidgets();
else if (indexName.length === 0) widgetSiblings = this.getWidgets();
else widgetSiblings = [this];
return resolveScopedResultsFromWidgets(widgetSiblings);
},
getParent: function getParent() {
return isolated ? null : localParent;
},
createURL: function createURL(nextState) {
if (typeof nextState === "function") return localInstantSearchInstance._createURL(_defineProperty$9({}, indexId, nextState(localUiState)));
return localInstantSearchInstance._createURL(_defineProperty$9({}, indexId, getLocalWidgetsUiState(localWidgets, {
searchParameters: nextState,
helper
})));
},
getWidgets: function getWidgets() {
return localWidgets;
},
addWidgets: function addWidgets(widgets) {
var _this = this;
if (!Array.isArray(widgets)) throw new Error(withUsage$3("The `addWidgets` method expects an array of widgets."));
var flatWidgets = widgets.reduce(function(acc, w$4) {
return acc.concat(Array.isArray(w$4) ? w$4 : [w$4]);
}, []);
if (flatWidgets.some(function(widget) {
return typeof widget.init !== "function" && typeof widget.render !== "function";
})) throw new Error(withUsage$3("The widget definition expects a `render` and/or an `init` method."));
flatWidgets.forEach(function(widget) {
if (isIndexWidget(widget)) return;
if (localInstantSearchInstance && widget.dependsOn === "recommend") localInstantSearchInstance._hasRecommendWidget = true;
else if (localInstantSearchInstance) localInstantSearchInstance._hasSearchWidget = true;
else if (widget.dependsOn === "recommend") hasRecommendWidget = true;
else hasSearchWidget = true;
addWidgetId(widget);
});
localWidgets = localWidgets.concat(flatWidgets);
if (localInstantSearchInstance && Boolean(flatWidgets.length)) {
privateHelperSetState(helper, {
state: getLocalWidgetsSearchParameters(localWidgets, {
uiState: localUiState,
initialSearchParameters: helper.state
}),
recommendState: getLocalWidgetsRecommendParameters(localWidgets, {
uiState: localUiState,
initialRecommendParameters: helper.recommendState
}),
_uiState: localUiState
});
flatWidgets.forEach(function(widget) {
if (widget.getRenderState) {
var renderState = widget.getRenderState(localInstantSearchInstance.renderState[_this.getIndexId()] || {}, createInitArgs(localInstantSearchInstance, _this, localInstantSearchInstance._initialUiState));
storeRenderState({
renderState,
instantSearchInstance: localInstantSearchInstance,
parent: _this
});
}
});
flatWidgets.forEach(function(widget) {
if (widget.init) widget.init(createInitArgs(localInstantSearchInstance, _this, localInstantSearchInstance._initialUiState));
});
if (isolated) {
var _helper2;
(_helper2 = helper) === null || _helper2 === void 0 || _helper2.search();
} else localInstantSearchInstance.scheduleSearch();
}
return this;
},
removeWidgets: function removeWidgets(widgets) {
var _this2 = this;
if (!Array.isArray(widgets)) throw new Error(withUsage$3("The `removeWidgets` method expects an array of widgets."));
var flatWidgets = widgets.reduce(function(acc, w$4) {
return acc.concat(Array.isArray(w$4) ? w$4 : [w$4]);
}, []);
if (flatWidgets.some(function(widget) {
return typeof widget.dispose !== "function";
})) throw new Error(withUsage$3("The widget definition expects a `dispose` method."));
localWidgets = localWidgets.filter(function(widget) {
return flatWidgets.indexOf(widget) === -1;
});
localWidgets.forEach(function(widget) {
if (isIndexWidget(widget)) return;
if (localInstantSearchInstance && widget.dependsOn === "recommend") localInstantSearchInstance._hasRecommendWidget = true;
else if (localInstantSearchInstance) localInstantSearchInstance._hasSearchWidget = true;
else if (widget.dependsOn === "recommend") hasRecommendWidget = true;
else hasSearchWidget = true;
});
if (localInstantSearchInstance && Boolean(flatWidgets.length)) {
var _flatWidgets$reduce = flatWidgets.reduce(function(states, widget) {
var next = widget.dispose({
helper,
state: states.cleanedSearchState,
recommendState: states.cleanedRecommendState,
parent: _this2
});
if (next instanceof import_algoliasearch_helper$1.default.RecommendParameters) states.cleanedRecommendState = next;
else if (next) states.cleanedSearchState = next;
return states;
}, {
cleanedSearchState: helper.state,
cleanedRecommendState: helper.recommendState
}), cleanedSearchState = _flatWidgets$reduce.cleanedSearchState, cleanedRecommendState = _flatWidgets$reduce.cleanedRecommendState;
var newState = localInstantSearchInstance.future.preserveSharedStateOnUnmount ? getLocalWidgetsSearchParameters(localWidgets, {
uiState: localUiState,
initialSearchParameters: new import_algoliasearch_helper$1.default.SearchParameters({ index: this.getIndexName() })
}) : getLocalWidgetsSearchParameters(localWidgets, {
uiState: getLocalWidgetsUiState(localWidgets, {
searchParameters: cleanedSearchState,
helper
}),
initialSearchParameters: cleanedSearchState
});
localUiState = getLocalWidgetsUiState(localWidgets, {
searchParameters: newState,
helper
});
helper.setState(newState);
helper.recommendState = cleanedRecommendState;
if (localWidgets.length) if (isolated) {
var _helper3;
(_helper3 = helper) === null || _helper3 === void 0 || _helper3.search();
} else localInstantSearchInstance.scheduleSearch();
}
return this;
},
init: function init(_ref2) {
var _this3 = this, _instantSearchInstanc;
var instantSearchInstance = _ref2.instantSearchInstance, parent = _ref2.parent, uiState = _ref2.uiState;
if (helper !== null) return;
localInstantSearchInstance = instantSearchInstance;
localParent = parent;
localUiState = uiState[indexId] || {};
var mainHelper = instantSearchInstance.mainHelper;
var parameters = getLocalWidgetsSearchParameters(localWidgets, {
uiState: localUiState,
initialSearchParameters: new import_algoliasearch_helper$1.default.SearchParameters({ index: indexName })
});
var recommendParameters = getLocalWidgetsRecommendParameters(localWidgets, {
uiState: localUiState,
initialRecommendParameters: new import_algoliasearch_helper$1.default.RecommendParameters()
});
helper = (0, import_algoliasearch_helper$1.default)(mainHelper.getClient(), parameters.index, parameters);
helper.recommendState = recommendParameters;
helper.search = function() {
if (isolated) {
instantSearchInstance.status = "loading";
_this3.render({ instantSearchInstance });
return instantSearchInstance.compositionID ? helper.searchWithComposition() : helper.searchOnlyWithDerivedHelpers();
}
if (instantSearchInstance.onStateChange) {
instantSearchInstance.onStateChange({
uiState: instantSearchInstance.mainIndex.getWidgetUiState({}),
setUiState: function setUiState(nextState) {
return instantSearchInstance.setUiState(nextState, false);
}
});
return mainHelper;
}
return mainHelper.search();
};
helper.searchWithoutTriggeringOnStateChange = function() {
return mainHelper.search();
};
helper.searchForFacetValues = function(facetName, facetValue, maxFacetHits, userState) {
var state = helper.state.setQueryParameters(userState);
return mainHelper.searchForFacetValues(facetName, facetValue, maxFacetHits, state);
};
var isolatedHelper = indexName ? helper : (0, import_algoliasearch_helper$1.default)({}, "__empty_index__", {});
var derivingHelper = isolated ? isolatedHelper : nearestIsolatedHelper(parent, mainHelper);
derivedHelper = derivingHelper.derive(function() {
return mergeSearchParameters.apply(void 0, [mainHelper.state].concat(_toConsumableArray$1(resolveSearchParameters(_this3))));
}, function() {
return _this3.getHelper().recommendState;
});
var indexInitialResults = (_instantSearchInstanc = instantSearchInstance._initialResults) === null || _instantSearchInstanc === void 0 ? void 0 : _instantSearchInstanc[this.getIndexId()];
if (indexInitialResults !== null && indexInitialResults !== void 0 && indexInitialResults.results) {
var results = new import_algoliasearch_helper$1.default.SearchResults(new import_algoliasearch_helper$1.default.SearchParameters(indexInitialResults.state), indexInitialResults.results);
derivedHelper.lastResults = results;
helper.lastResults = results;
}
if (indexInitialResults !== null && indexInitialResults !== void 0 && indexInitialResults.recommendResults) {
var recommendResults = new import_algoliasearch_helper$1.default.RecommendResults(new import_algoliasearch_helper$1.default.RecommendParameters({ params: indexInitialResults.recommendResults.params }), indexInitialResults.recommendResults.results);
derivedHelper.lastRecommendResults = recommendResults;
helper.lastRecommendResults = recommendResults;
}
helper.on("change", function(_ref3) {
var isPageReset = _ref3.isPageReset;
if (isPageReset) resetPageFromWidgets(localWidgets);
});
derivedHelper.on("search", function() {
instantSearchInstance.scheduleStalledRender();
});
derivedHelper.on("result", function(_ref4) {
var results$1 = _ref4.results;
instantSearchInstance.scheduleRender();
helper.lastResults = results$1;
lastValidSearchParameters = results$1 === null || results$1 === void 0 ? void 0 : results$1._state;
});
derivedHelper.on("recommend:result", function(_ref5) {
var recommend = _ref5.recommend;
instantSearchInstance.scheduleRender();
helper.lastRecommendResults = recommend.results;
});
localWidgets.forEach(function(widget) {
if (widget.getRenderState) {
var renderState = widget.getRenderState(instantSearchInstance.renderState[_this3.getIndexId()] || {}, createInitArgs(instantSearchInstance, _this3, uiState));
storeRenderState({
renderState,
instantSearchInstance,
parent: _this3
});
}
});
localWidgets.forEach(function(widget) {
if (widget.init) widget.init(createInitArgs(instantSearchInstance, _this3, uiState));
});
helper.on("change", function(event) {
var state = event.state;
var _uiState = event._uiState;
localUiState = getLocalWidgetsUiState(localWidgets, {
searchParameters: state,
helper
}, _uiState || {});
if (!instantSearchInstance.onStateChange) instantSearchInstance.onInternalStateChange();
});
if (indexInitialResults) instantSearchInstance.scheduleRender();
if (hasRecommendWidget) instantSearchInstance._hasRecommendWidget = true;
if (hasSearchWidget) instantSearchInstance._hasSearchWidget = true;
},
render: function render(_ref6) {
var _derivedHelper2, _this4 = this;
var instantSearchInstance = _ref6.instantSearchInstance;
if (instantSearchInstance.status === "error" && !instantSearchInstance.mainHelper.hasPendingRequests() && lastValidSearchParameters) helper.setState(lastValidSearchParameters);
var widgetsToRender = this.getResults() || (_derivedHelper2 = derivedHelper) !== null && _derivedHelper2 !== void 0 && _derivedHelper2.lastRecommendResults || isolated && !indexName ? localWidgets : localWidgets.filter(isIndexWidget);
widgetsToRender = widgetsToRender.filter(function(widget) {
if (!widget.shouldRender) return true;
return widget.shouldRender({ instantSearchInstance });
});
widgetsToRender.forEach(function(widget) {
if (widget.getRenderState) {
var renderState = widget.getRenderState(instantSearchInstance.renderState[_this4.getIndexId()] || {}, createRenderArgs(instantSearchInstance, _this4, widget));
storeRenderState({
renderState,
instantSearchInstance,
parent: _this4
});
}
});
widgetsToRender.forEach(function(widget) {
if (widget.render) widget.render(createRenderArgs(instantSearchInstance, _this4, widget));
});
},
dispose: function dispose() {
var _this5 = this, _helper4, _derivedHelper3;
localWidgets.forEach(function(widget) {
if (widget.dispose && helper) widget.dispose({
helper,
state: helper.state,
recommendState: helper.recommendState,
parent: _this5
});
});
localInstantSearchInstance = null;
localParent = null;
(_helper4 = helper) === null || _helper4 === void 0 || _helper4.removeAllListeners();
helper = null;
(_derivedHelper3 = derivedHelper) === null || _derivedHelper3 === void 0 || _derivedHelper3.detach();
derivedHelper = null;
},
getWidgetUiState: function getWidgetUiState(uiState) {
return localWidgets.filter(isIndexWidget).filter(function(w$4) {
return !w$4._isolated;
}).reduce(function(previousUiState, innerIndex) {
return innerIndex.getWidgetUiState(previousUiState);
}, _objectSpread$8(_objectSpread$8({}, uiState), {}, _defineProperty$9({}, indexId, _objectSpread$8(_objectSpread$8({}, uiState[indexId]), localUiState))));
},
getWidgetState: function getWidgetState(uiState) {
return this.getWidgetUiState(uiState);
},
getWidgetSearchParameters: function getWidgetSearchParameters(searchParameters, _ref7) {
var uiState = _ref7.uiState;
return getLocalWidgetsSearchParameters(localWidgets, {
uiState,
initialSearchParameters: searchParameters
});
},
refreshUiState: function refreshUiState() {
localUiState = getLocalWidgetsUiState(localWidgets, {
searchParameters: this.getHelper().state,
helper: this.getHelper()
}, localUiState);
},
setIndexUiState: function setIndexUiState(indexUiState) {
var nextIndexUiState = typeof indexUiState === "function" ? indexUiState(localUiState) : indexUiState;
localInstantSearchInstance.setUiState(function(state) {
return _objectSpread$8(_objectSpread$8({}, state), {}, _defineProperty$9({}, indexId, nextIndexUiState));
});
}
};
};
var index_default = index;
function storeRenderState(_ref8) {
var renderState = _ref8.renderState, instantSearchInstance = _ref8.instantSearchInstance, parent = _ref8.parent;
var parentIndexName = parent ? parent.getIndexId() : instantSearchInstance.mainIndex.getIndexId();
instantSearchInstance.renderState = _objectSpread$8(_objectSpread$8({}, instantSearchInstance.renderState), {}, _defineProperty$9({}, parentIndexName, _objectSpread$8(_objectSpread$8({}, instantSearchInstance.renderState[parentIndexName]), renderState)));
}
/**
* Walk up the parent chain to find the closest isolated index, or fall back to mainHelper
*/
function nearestIsolatedHelper(current, mainHelper) {
while (current) {
if (current._isolated) return current.getHelper();
current = current.getParent();
}
return mainHelper;
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useForceUpdate.js
init_compat_module();
function _slicedToArray$3(arr, i$3) {
return _arrayWithHoles$3(arr) || _iterableToArrayLimit$3(arr, i$3) || _unsupportedIterableToArray$3(arr, i$3) || _nonIterableRest$3();
}
function _nonIterableRest$3() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$3(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray$3(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray$3(o$3, minLen);
}
function _arrayLikeToArray$3(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
function _iterableToArrayLimit$3(r$2, l$2) {
var t$2 = null == r$2 ? null : "undefined" != typeof Symbol && r$2[Symbol.iterator] || r$2["@@iterator"];
if (null != t$2) {
var e$2, n$1, i$3, u$3, a$2 = [], f$3 = !0, o$3 = !1;
try {
if (i$3 = (t$2 = t$2.call(r$2)).next, 0 === l$2) {
if (Object(t$2) !== t$2) return;
f$3 = !1;
} else for (; !(f$3 = (e$2 = i$3.call(t$2)).done) && (a$2.push(e$2.value), a$2.length !== l$2); f$3 = !0);
} catch (r$3) {
o$3 = !0, n$1 = r$3;
} finally {
try {
if (!f$3 && null != t$2.return && (u$3 = t$2.return(), Object(u$3) !== u$3)) return;
} finally {
if (o$3) throw n$1;
}
}
return a$2;
}
}
function _arrayWithHoles$3(arr) {
if (Array.isArray(arr)) return arr;
}
/**
* Forces a React update that triggers a rerender.
* @link https://reactjs.org/docs/hooks-faq.html#is-there-something-like-forceupdate
*/
function useForceUpdate() {
var _useReducer = h(function(x$4) {
return x$4 + 1;
}, 0), _useReducer2 = _slicedToArray$3(_useReducer, 2), forceUpdate = _useReducer2[1];
return forceUpdate;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/suit.js
var NAMESPACE = "ais";
var component = function component$1(componentName) {
return function() {
var _ref = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, descendantName = _ref.descendantName, modifierName = _ref.modifierName;
var descendent = descendantName ? "-".concat(descendantName) : "";
var modifier = modifierName ? "--".concat(modifierName) : "";
return "".concat(NAMESPACE, "-").concat(componentName).concat(descendent).concat(modifier);
};
};
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/helpers/highlight.js
var suit$3 = component("Highlight");
/**
* @deprecated use html tagged templates and the Highlight component instead
*/
function highlight(_ref) {
var attribute = _ref.attribute, _ref$highlightedTagNa = _ref.highlightedTagName, highlightedTagName = _ref$highlightedTagNa === void 0 ? "mark" : _ref$highlightedTagNa, hit = _ref.hit, _ref$cssClasses = _ref.cssClasses, cssClasses = _ref$cssClasses === void 0 ? {} : _ref$cssClasses;
var highlightAttributeResult = getPropertyByPath(hit._highlightResult, attribute);
var _ref2 = highlightAttributeResult || {}, _ref2$value = _ref2.value, attributeValue = _ref2$value === void 0 ? "" : _ref2$value;
var className = suit$3({ descendantName: "highlighted" }) + (cssClasses.highlighted ? " ".concat(cssClasses.highlighted) : "");
return attributeValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, "g"), "<".concat(highlightedTagName, " class=\"").concat(className, "\">")).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, "g"), "</".concat(highlightedTagName, ">"));
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/helpers/reverseHighlight.js
var suit$2 = component("ReverseHighlight");
/**
* @deprecated use html tagged templates and the ReverseHighlight component instead
*/
function reverseHighlight(_ref) {
var attribute = _ref.attribute, _ref$highlightedTagNa = _ref.highlightedTagName, highlightedTagName = _ref$highlightedTagNa === void 0 ? "mark" : _ref$highlightedTagNa, hit = _ref.hit, _ref$cssClasses = _ref.cssClasses, cssClasses = _ref$cssClasses === void 0 ? {} : _ref$cssClasses;
var highlightAttributeResult = getPropertyByPath(hit._highlightResult, attribute);
var _ref2 = highlightAttributeResult || {}, _ref2$value = _ref2.value, attributeValue = _ref2$value === void 0 ? "" : _ref2$value;
var className = suit$2({ descendantName: "highlighted" }) + (cssClasses.highlighted ? " ".concat(cssClasses.highlighted) : "");
var reverseHighlightedValue = concatHighlightedParts(reverseHighlightedParts(getHighlightedParts(attributeValue)));
return reverseHighlightedValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, "g"), "<".concat(highlightedTagName, " class=\"").concat(className, "\">")).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, "g"), "</".concat(highlightedTagName, ">"));
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/helpers/snippet.js
var suit$1 = component("Snippet");
/**
* @deprecated use html tagged templates and the Snippet component instead
*/
function snippet(_ref) {
var attribute = _ref.attribute, _ref$highlightedTagNa = _ref.highlightedTagName, highlightedTagName = _ref$highlightedTagNa === void 0 ? "mark" : _ref$highlightedTagNa, hit = _ref.hit, _ref$cssClasses = _ref.cssClasses, cssClasses = _ref$cssClasses === void 0 ? {} : _ref$cssClasses;
var snippetAttributeResult = getPropertyByPath(hit._snippetResult, attribute);
var _ref2 = snippetAttributeResult || {}, _ref2$value = _ref2.value, attributeValue = _ref2$value === void 0 ? "" : _ref2$value;
var className = suit$1({ descendantName: "highlighted" }) + (cssClasses.highlighted ? " ".concat(cssClasses.highlighted) : "");
return attributeValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, "g"), "<".concat(highlightedTagName, " class=\"").concat(className, "\">")).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, "g"), "</".concat(highlightedTagName, ">"));
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/helpers/reverseSnippet.js
var suit = component("ReverseSnippet");
/**
* @deprecated use html tagged templates and the ReverseSnippet component instead
*/
function reverseSnippet(_ref) {
var attribute = _ref.attribute, _ref$highlightedTagNa = _ref.highlightedTagName, highlightedTagName = _ref$highlightedTagNa === void 0 ? "mark" : _ref$highlightedTagNa, hit = _ref.hit, _ref$cssClasses = _ref.cssClasses, cssClasses = _ref$cssClasses === void 0 ? {} : _ref$cssClasses;
var snippetAttributeResult = getPropertyByPath(hit._snippetResult, attribute);
var _ref2 = snippetAttributeResult || {}, _ref2$value = _ref2.value, attributeValue = _ref2$value === void 0 ? "" : _ref2$value;
var className = suit({ descendantName: "highlighted" }) + (cssClasses.highlighted ? " ".concat(cssClasses.highlighted) : "");
var reverseHighlightedValue = concatHighlightedParts(reverseHighlightedParts(getHighlightedParts(attributeValue)));
return reverseHighlightedValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, "g"), "<".concat(highlightedTagName, " class=\"").concat(className, "\">")).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, "g"), "</".concat(highlightedTagName, ">"));
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/helpers/insights.js
function _typeof$10(o$3) {
"@babel/helpers - typeof";
return _typeof$10 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$10(o$3);
}
/** @deprecated use bindEvent instead */
function writeDataAttributes(_ref) {
var method = _ref.method, payload = _ref.payload;
if (_typeof$10(payload) !== "object") throw new Error("The insights helper expects the payload to be an object.");
var serializedPayload;
try {
serializedPayload = serializePayload(payload);
} catch (error) {
throw new Error("Could not JSON serialize the payload object.");
}
return "data-insights-method=\"".concat(method, "\" data-insights-payload=\"").concat(serializedPayload, "\"");
}
/**
* @deprecated This function will be still supported in 4.x releases, but not further. It is replaced by the `insights` middleware. For more information, visit https://www.algolia.com/doc/guides/getting-insights-and-analytics/search-analytics/click-through-and-conversions/how-to/send-click-and-conversion-events-with-instantsearch/js/
*/
function insights(method, payload) {
return writeDataAttributes({
method,
payload
});
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/helpers/get-insights-anonymous-user-token.js
function _typeof$9(o$3) {
"@babel/helpers - typeof";
return _typeof$9 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$9(o$3);
}
var ANONYMOUS_TOKEN_COOKIE_KEY = "_ALGOLIA";
function getCookie(name$2) {
if ((typeof document === "undefined" ? "undefined" : _typeof$9(document)) !== "object" || typeof document.cookie !== "string") return void 0;
var prefix = "".concat(name$2, "=");
var cookies = document.cookie.split(";");
for (var i$3 = 0; i$3 < cookies.length; i$3++) {
var cookie = cookies[i$3];
while (cookie.charAt(0) === " ") cookie = cookie.substring(1);
if (cookie.indexOf(prefix) === 0) return cookie.substring(prefix.length, cookie.length);
}
return void 0;
}
function getInsightsAnonymousUserTokenInternal() {
return getCookie(ANONYMOUS_TOKEN_COOKIE_KEY);
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/utils/uuid.js
/**
* Create UUID according to
* https://www.ietf.org/rfc/rfc4122.txt.
*
* @returns Generated UUID.
*/
function createUUID() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c$2) {
var r$2 = Math.random() * 16 | 0;
var v$3 = c$2 === "x" ? r$2 : r$2 & 3 | 8;
return v$3.toString(16);
});
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/middlewares/createInsightsMiddleware.js
function _typeof$8(o$3) {
"@babel/helpers - typeof";
return _typeof$8 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$8(o$3);
}
function ownKeys$7(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$7(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$7(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$8(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$7(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$8(obj, key, value) {
key = _toPropertyKey$8(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$8(t$2) {
var i$3 = _toPrimitive$8(t$2, "string");
return "symbol" == _typeof$8(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$8(t$2, r$2) {
if ("object" != _typeof$8(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$8(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function _slicedToArray$2(arr, i$3) {
return _arrayWithHoles$2(arr) || _iterableToArrayLimit$2(arr, i$3) || _unsupportedIterableToArray$2(arr, i$3) || _nonIterableRest$2();
}
function _nonIterableRest$2() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit$2(r$2, l$2) {
var t$2 = null == r$2 ? null : "undefined" != typeof Symbol && r$2[Symbol.iterator] || r$2["@@iterator"];
if (null != t$2) {
var e$2, n$1, i$3, u$3, a$2 = [], f$3 = !0, o$3 = !1;
try {
if (i$3 = (t$2 = t$2.call(r$2)).next, 0 === l$2) {
if (Object(t$2) !== t$2) return;
f$3 = !1;
} else for (; !(f$3 = (e$2 = i$3.call(t$2)).done) && (a$2.push(e$2.value), a$2.length !== l$2); f$3 = !0);
} catch (r$3) {
o$3 = !0, n$1 = r$3;
} finally {
try {
if (!f$3 && null != t$2.return && (u$3 = t$2.return(), Object(u$3) !== u$3)) return;
} finally {
if (o$3) throw n$1;
}
}
return a$2;
}
}
function _arrayWithHoles$2(arr) {
if (Array.isArray(arr)) return arr;
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$2(arr) || _nonIterableSpread();
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$2(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray$2(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray$2(o$3, minLen);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$2(arr);
}
function _arrayLikeToArray$2(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
var ALGOLIA_INSIGHTS_VERSION = "2.17.2";
var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
function createInsightsMiddleware() {
var props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
var _insightsClient = props.insightsClient, insightsInitParams = props.insightsInitParams, onEvent = props.onEvent, _props$$$internal = props.$$internal, $$internal = _props$$$internal === void 0 ? false : _props$$$internal, _props$$$automatic = props.$$automatic, $$automatic = _props$$$automatic === void 0 ? false : _props$$$automatic;
var potentialInsightsClient = _insightsClient;
if (!_insightsClient && _insightsClient !== null) safelyRunOnBrowser(function(_ref) {
var window$1 = _ref.window;
var pointer = window$1.AlgoliaAnalyticsObject || "aa";
if (typeof pointer === "string") potentialInsightsClient = window$1[pointer];
if (!potentialInsightsClient) {
window$1.AlgoliaAnalyticsObject = pointer;
if (!window$1[pointer]) {
window$1[pointer] = function() {
if (!window$1[pointer].queue) window$1[pointer].queue = [];
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
window$1[pointer].queue.push(args);
};
window$1[pointer].version = ALGOLIA_INSIGHTS_VERSION;
window$1[pointer].shouldAddScript = true;
}
potentialInsightsClient = window$1[pointer];
}
});
var insightsClient = potentialInsightsClient || noop$1;
return function(_ref2) {
var instantSearchInstance = _ref2.instantSearchInstance;
var existingInsightsMiddlewares = instantSearchInstance.middleware.filter(function(m$4) {
return m$4.instance.$$type === "ais.insights" && m$4.instance.$$internal;
}).map(function(m$4) {
return m$4.creator;
});
instantSearchInstance.unuse.apply(instantSearchInstance, _toConsumableArray(existingInsightsMiddlewares));
var _getAppIdAndApiKey = getAppIdAndApiKey(instantSearchInstance.client), _getAppIdAndApiKey2 = _slicedToArray$2(_getAppIdAndApiKey, 2), appId = _getAppIdAndApiKey2[0], apiKey = _getAppIdAndApiKey2[1];
var queuedInitParams = void 0;
var queuedUserToken = void 0;
var userTokenBeforeInit = void 0;
var queue = insightsClient.queue;
if (Array.isArray(queue)) {
var _map = ["setUserToken", "init"].map(function(key) {
var _ref3 = find(queue.slice().reverse(), function(_ref5) {
var _ref6 = _slicedToArray$2(_ref5, 1), method = _ref6[0];
return method === key;
}) || [], _ref4 = _slicedToArray$2(_ref3, 2), value = _ref4[1];
return value;
});
var _map2 = _slicedToArray$2(_map, 2);
queuedUserToken = _map2[0];
queuedInitParams = _map2[1];
}
insightsClient("getUserToken", null, function(_error$1, userToken) {
userTokenBeforeInit = normalizeUserToken(userToken);
});
if (insightsInitParams || !isModernInsightsClient(insightsClient)) insightsClient("init", _objectSpread$7({
appId,
apiKey,
partial: true
}, insightsInitParams));
var initialParameters;
var helper;
return {
$$type: "ais.insights",
$$internal,
$$automatic,
onStateChange: function onStateChange() {},
subscribe: function subscribe() {
if (!insightsClient.shouldAddScript) return;
var errorMessage$1 = "[insights middleware]: could not load search-insights.js. Please load it manually following https://alg.li/insights-init";
try {
var script = document.createElement("script");
script.async = true;
script.src = ALGOLIA_INSIGHTS_SRC;
script.onerror = function() {
instantSearchInstance.emit("error", new Error(errorMessage$1));
};
document.body.appendChild(script);
insightsClient.shouldAddScript = false;
} catch (cause) {
insightsClient.shouldAddScript = false;
instantSearchInstance.emit("error", new Error(errorMessage$1));
}
},
started: function started() {
insightsClient("addAlgoliaAgent", "insights-middleware");
helper = instantSearchInstance.mainHelper;
var queueAtStart = insightsClient.queue;
if (Array.isArray(queueAtStart)) {
var _map3 = ["setUserToken", "init"].map(function(key) {
var _ref7 = find(queueAtStart.slice().reverse(), function(_ref9) {
var _ref10 = _slicedToArray$2(_ref9, 1), method = _ref10[0];
return method === key;
}) || [], _ref8 = _slicedToArray$2(_ref7, 2), value = _ref8[1];
return value;
});
var _map4 = _slicedToArray$2(_map3, 2);
queuedUserToken = _map4[0];
queuedInitParams = _map4[1];
}
initialParameters = getInitialParameters(instantSearchInstance);
if (!$$automatic) helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread$7(_objectSpread$7({}, helper.state), {}, { clickAnalytics: true }));
if (!$$internal) instantSearchInstance.scheduleSearch();
var setUserTokenToSearch = function setUserTokenToSearch$1(userToken) {
var immediate = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var normalizedUserToken = normalizeUserToken(userToken);
if (!normalizedUserToken) return;
var existingToken = helper.state.userToken;
function applyToken() {
helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread$7(_objectSpread$7({}, helper.state), {}, { userToken: normalizedUserToken }));
if (existingToken && existingToken !== userToken) instantSearchInstance.scheduleSearch();
}
if (!immediate) setTimeout(applyToken, 0);
else applyToken();
};
function setUserToken(token$1) {
setUserTokenToSearch(token$1, true);
insightsClient("setUserToken", token$1);
}
var anonymousUserToken = void 0;
var anonymousTokenFromInsights = getInsightsAnonymousUserTokenInternal();
if (anonymousTokenFromInsights) anonymousUserToken = anonymousTokenFromInsights;
else {
var token = "anonymous-".concat(createUUID());
anonymousUserToken = token;
}
var userTokenFromInit;
var tokenFromSearchParameters = initialParameters.userToken;
if (insightsInitParams !== null && insightsInitParams !== void 0 && insightsInitParams.userToken) userTokenFromInit = insightsInitParams.userToken;
if (userTokenFromInit) setUserToken(userTokenFromInit);
else if (tokenFromSearchParameters) setUserToken(tokenFromSearchParameters);
else if (userTokenBeforeInit) setUserToken(userTokenBeforeInit);
else if (queuedUserToken) setUserToken(queuedUserToken);
else if (anonymousUserToken) {
var _queuedInitParams;
setUserToken(anonymousUserToken);
if (insightsInitParams !== null && insightsInitParams !== void 0 && insightsInitParams.useCookie || (_queuedInitParams = queuedInitParams) !== null && _queuedInitParams !== void 0 && _queuedInitParams.useCookie) {
var _queuedInitParams2;
saveTokenAsCookie(anonymousUserToken, (insightsInitParams === null || insightsInitParams === void 0 ? void 0 : insightsInitParams.cookieDuration) || ((_queuedInitParams2 = queuedInitParams) === null || _queuedInitParams2 === void 0 ? void 0 : _queuedInitParams2.cookieDuration));
}
}
insightsClient("onUserTokenChange", function(token$1) {
return setUserTokenToSearch(token$1, true);
}, { immediate: true });
var insightsClientWithLocalCredentials = insightsClient;
if (isModernInsightsClient(insightsClient)) insightsClientWithLocalCredentials = function insightsClientWithLocalCredentials$1(method, payload) {
var _getAppIdAndApiKey3 = getAppIdAndApiKey(instantSearchInstance.client), _getAppIdAndApiKey4 = _slicedToArray$2(_getAppIdAndApiKey3, 2), latestAppId = _getAppIdAndApiKey4[0], latestApiKey = _getAppIdAndApiKey4[1];
var extraParams = { headers: {
"X-Algolia-Application-Id": latestAppId,
"X-Algolia-API-Key": latestApiKey
} };
return insightsClient(method, payload, extraParams);
};
var viewedObjectIDs = new Set();
var lastQueryId;
instantSearchInstance.mainHelper.derivedHelpers[0].on("result", function(_ref11) {
var results = _ref11.results;
if (results && (!results.queryID || results.queryID !== lastQueryId)) {
lastQueryId = results.queryID;
viewedObjectIDs.clear();
}
});
instantSearchInstance.sendEventToInsights = function(event) {
if (onEvent) onEvent(event, insightsClientWithLocalCredentials);
else if (event.insightsMethod) {
if (event.insightsMethod === "viewedObjectIDs") {
var _payload = event.payload;
var difference = _payload.objectIDs.filter(function(objectID) {
return !viewedObjectIDs.has(objectID);
});
if (difference.length === 0) return;
difference.forEach(function(objectID) {
return viewedObjectIDs.add(objectID);
});
_payload.objectIDs = difference;
}
event.payload.algoliaSource = ["instantsearch"];
if ($$automatic) event.payload.algoliaSource.push("instantsearch-automatic");
if (event.eventModifier === "internal") event.payload.algoliaSource.push("instantsearch-internal");
insightsClientWithLocalCredentials(event.insightsMethod, event.payload);
}
};
},
unsubscribe: function unsubscribe() {
insightsClient("onUserTokenChange", void 0);
instantSearchInstance.sendEventToInsights = noop$1;
if (helper && initialParameters) {
helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread$7(_objectSpread$7({}, helper.state), initialParameters));
instantSearchInstance.scheduleSearch();
}
}
};
};
}
function getInitialParameters(instantSearchInstance) {
var _instantSearchInstanc, _instantSearchInstanc2;
var stateFromInitialResults = ((_instantSearchInstanc = instantSearchInstance._initialResults) === null || _instantSearchInstanc === void 0 ? void 0 : (_instantSearchInstanc2 = _instantSearchInstanc[instantSearchInstance.indexName]) === null || _instantSearchInstanc2 === void 0 ? void 0 : _instantSearchInstanc2.state) || {};
var stateFromHelper = instantSearchInstance.mainHelper.state;
return {
userToken: stateFromInitialResults.userToken || stateFromHelper.userToken,
clickAnalytics: stateFromInitialResults.clickAnalytics || stateFromHelper.clickAnalytics
};
}
function saveTokenAsCookie(token, cookieDuration) {
var MONTH = 30 * 24 * 60 * 60 * 1e3;
var d$3 = new Date();
d$3.setTime(d$3.getTime() + (cookieDuration || MONTH * 6));
var expires = "expires=".concat(d$3.toUTCString());
document.cookie = "_ALGOLIA=".concat(token, ";").concat(expires, ";path=/");
}
/**
* Determines if a given insights `client` supports the optional call to `init`
* and the ability to set credentials via extra parameters when sending events.
*/
function isModernInsightsClient(client) {
var _split$map = (client.version || "").split(".").map(Number), _split$map2 = _slicedToArray$2(_split$map, 2), major = _split$map2[0], minor = _split$map2[1];
var v3 = major >= 3;
var v2_6 = major === 2 && minor >= 6;
var v1_10 = major === 1 && minor >= 10;
return v3 || v2_6 || v1_10;
}
/**
* While `search-insights` supports both string and number user tokens,
* the Search API only accepts strings. This function normalizes the user token.
*/
function normalizeUserToken(userToken) {
if (!userToken) return void 0;
return typeof userToken === "number" ? userToken.toString() : userToken;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/middlewares/createMetadataMiddleware.js
function extractWidgetPayload(widgets, instantSearchInstance, payload) {
var initOptions = createInitArgs(instantSearchInstance, instantSearchInstance.mainIndex, instantSearchInstance._initialUiState);
widgets.forEach(function(widget) {
var widgetParams = {};
if (widget.getWidgetRenderState) {
var renderState = widget.getWidgetRenderState(initOptions);
if (renderState && renderState.widgetParams) widgetParams = renderState.widgetParams;
}
var params = Object.keys(widgetParams).filter(function(key) {
return widgetParams[key] !== void 0;
});
payload.widgets.push({
type: widget.$$type,
widgetType: widget.$$widgetType,
params
});
if (widget.$$type === "ais.index") extractWidgetPayload(widget.getWidgets(), instantSearchInstance, payload);
});
}
function isMetadataEnabled() {
return safelyRunOnBrowser(function(_ref) {
var _window$navigator, _window$navigator$use;
var window$1 = _ref.window;
return ((_window$navigator = window$1.navigator) === null || _window$navigator === void 0 ? void 0 : (_window$navigator$use = _window$navigator.userAgent) === null || _window$navigator$use === void 0 ? void 0 : _window$navigator$use.indexOf("Algolia Crawler")) > -1;
}, { fallback: function fallback() {
return false;
} });
}
/**
* Exposes the metadata of mounted widgets in a custom
* `<meta name="instantsearch:widgets" />` tag. The metadata per widget is:
* - applied parameters
* - widget name
* - connector name
*/
function createMetadataMiddleware() {
var _ref2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref2$$$internal = _ref2.$$internal, $$internal = _ref2$$$internal === void 0 ? false : _ref2$$$internal;
return function(_ref3) {
var instantSearchInstance = _ref3.instantSearchInstance;
var payload = { widgets: [] };
var payloadContainer = document.createElement("meta");
var refNode = document.querySelector("head");
payloadContainer.name = "instantsearch:widgets";
return {
$$type: "ais.metadata",
$$internal,
onStateChange: function onStateChange() {},
subscribe: function subscribe() {
setTimeout(function() {
var client = instantSearchInstance.client;
payload.ua = client.transporter && client.transporter.userAgent ? client.transporter.userAgent.value : client._ua;
extractWidgetPayload(instantSearchInstance.mainIndex.getWidgets(), instantSearchInstance, payload);
instantSearchInstance.middleware.forEach(function(middleware) {
return payload.widgets.push({
middleware: true,
type: middleware.instance.$$type,
internal: middleware.instance.$$internal
});
});
payloadContainer.content = JSON.stringify(payload);
refNode.appendChild(payloadContainer);
}, 0);
},
started: function started() {},
unsubscribe: function unsubscribe() {
payloadContainer.remove();
}
};
};
}
//#endregion
//#region ../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/formats.js
var require_formats = __commonJS({ "../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/formats.js"(exports, module) {
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
var Format = {
RFC1738: "RFC1738",
RFC3986: "RFC3986"
};
module.exports = {
"default": Format.RFC3986,
formatters: {
RFC1738: function(value) {
return replace.call(value, percentTwenties, "+");
},
RFC3986: function(value) {
return String(value);
}
},
RFC1738: Format.RFC1738,
RFC3986: Format.RFC3986
};
} });
//#endregion
//#region ../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/utils.js
var require_utils = __commonJS({ "../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/utils.js"(exports, module) {
var formats$2 = require_formats();
var has$2 = Object.prototype.hasOwnProperty;
var isArray$2 = Array.isArray;
var hexTable = function() {
var array$1 = [];
for (var i$3 = 0; i$3 < 256; ++i$3) array$1.push("%" + ((i$3 < 16 ? "0" : "") + i$3.toString(16)).toUpperCase());
return array$1;
}();
var compactQueue = function compactQueue$1(queue) {
while (queue.length > 1) {
var item = queue.pop();
var obj = item.obj[item.prop];
if (isArray$2(obj)) {
var compacted = [];
for (var j$4 = 0; j$4 < obj.length; ++j$4) if (typeof obj[j$4] !== "undefined") compacted.push(obj[j$4]);
item.obj[item.prop] = compacted;
}
}
};
var arrayToObject = function arrayToObject$1(source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i$3 = 0; i$3 < source.length; ++i$3) if (typeof source[i$3] !== "undefined") obj[i$3] = source[i$3];
return obj;
};
var merge$1 = function merge$6(target, source, options) {
if (!source) return target;
if (typeof source !== "object") {
if (isArray$2(target)) target.push(source);
else if (target && typeof target === "object") {
if (options && (options.plainObjects || options.allowPrototypes) || !has$2.call(Object.prototype, source)) target[source] = true;
} else return [target, source];
return target;
}
if (!target || typeof target !== "object") return [target].concat(source);
var mergeTarget = target;
if (isArray$2(target) && !isArray$2(source)) mergeTarget = arrayToObject(target, options);
if (isArray$2(target) && isArray$2(source)) {
source.forEach(function(item, i$3) {
if (has$2.call(target, i$3)) {
var targetItem = target[i$3];
if (targetItem && typeof targetItem === "object" && item && typeof item === "object") target[i$3] = merge$6(targetItem, item, options);
else target.push(item);
} else target[i$3] = item;
});
return target;
}
return Object.keys(source).reduce(function(acc, key) {
var value = source[key];
if (has$2.call(acc, key)) acc[key] = merge$6(acc[key], value, options);
else acc[key] = value;
return acc;
}, mergeTarget);
};
var assign = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function(acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
var decode$1 = function(str, decoder, charset) {
var strWithoutPlus = str.replace(/\+/g, " ");
if (charset === "iso-8859-1") return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
try {
return decodeURIComponent(strWithoutPlus);
} catch (e$2) {
return strWithoutPlus;
}
};
var encode = function encode$1(str, defaultEncoder, charset, kind, format$1) {
if (str.length === 0) return str;
var string$2 = str;
if (typeof str === "symbol") string$2 = Symbol.prototype.toString.call(str);
else if (typeof str !== "string") string$2 = String(str);
if (charset === "iso-8859-1") return escape(string$2).replace(/%u[0-9a-f]{4}/gi, function($0) {
return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
});
var out = "";
for (var i$3 = 0; i$3 < string$2.length; ++i$3) {
var c$2 = string$2.charCodeAt(i$3);
if (c$2 === 45 || c$2 === 46 || c$2 === 95 || c$2 === 126 || c$2 >= 48 && c$2 <= 57 || c$2 >= 65 && c$2 <= 90 || c$2 >= 97 && c$2 <= 122 || format$1 === formats$2.RFC1738 && (c$2 === 40 || c$2 === 41)) {
out += string$2.charAt(i$3);
continue;
}
if (c$2 < 128) {
out = out + hexTable[c$2];
continue;
}
if (c$2 < 2048) {
out = out + (hexTable[192 | c$2 >> 6] + hexTable[128 | c$2 & 63]);
continue;
}
if (c$2 < 55296 || c$2 >= 57344) {
out = out + (hexTable[224 | c$2 >> 12] + hexTable[128 | c$2 >> 6 & 63] + hexTable[128 | c$2 & 63]);
continue;
}
i$3 += 1;
c$2 = 65536 + ((c$2 & 1023) << 10 | string$2.charCodeAt(i$3) & 1023);
out += hexTable[240 | c$2 >> 18] + hexTable[128 | c$2 >> 12 & 63] + hexTable[128 | c$2 >> 6 & 63] + hexTable[128 | c$2 & 63];
}
return out;
};
var compact = function compact$2(value) {
var queue = [{
obj: { o: value },
prop: "o"
}];
var refs = [];
for (var i$3 = 0; i$3 < queue.length; ++i$3) {
var item = queue[i$3];
var obj = item.obj[item.prop];
var keys = Object.keys(obj);
for (var j$4 = 0; j$4 < keys.length; ++j$4) {
var key = keys[j$4];
var val = obj[key];
if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) {
queue.push({
obj,
prop: key
});
refs.push(val);
}
}
}
compactQueue(queue);
return value;
};
var isRegExp = function isRegExp$1(obj) {
return Object.prototype.toString.call(obj) === "[object RegExp]";
};
var isBuffer = function isBuffer$1(obj) {
if (!obj || typeof obj !== "object") return false;
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
var combine = function combine$1(a$2, b$3) {
return [].concat(a$2, b$3);
};
var maybeMap = function maybeMap$1(val, fn$1) {
if (isArray$2(val)) {
var mapped = [];
for (var i$3 = 0; i$3 < val.length; i$3 += 1) mapped.push(fn$1(val[i$3]));
return mapped;
}
return fn$1(val);
};
module.exports = {
arrayToObject,
assign,
combine,
compact,
decode: decode$1,
encode,
isBuffer,
isRegExp,
maybeMap,
merge: merge$1
};
} });
//#endregion
//#region ../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/stringify.js
var require_stringify = __commonJS({ "../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/stringify.js"(exports, module) {
var utils$1 = require_utils();
var formats$1 = require_formats();
var has$1 = Object.prototype.hasOwnProperty;
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + "[]";
},
comma: "comma",
indices: function indices(prefix, key) {
return prefix + "[" + key + "]";
},
repeat: function repeat(prefix) {
return prefix;
}
};
var isArray$1 = Array.isArray;
var split = String.prototype.split;
var push = Array.prototype.push;
var pushToArray = function(arr, valueOrArray) {
push.apply(arr, isArray$1(valueOrArray) ? valueOrArray : [valueOrArray]);
};
var toISO = Date.prototype.toISOString;
var defaultFormat = formats$1["default"];
var defaults$1 = {
addQueryPrefix: false,
allowDots: false,
charset: "utf-8",
charsetSentinel: false,
delimiter: "&",
encode: true,
encoder: utils$1.encode,
encodeValuesOnly: false,
format: defaultFormat,
formatter: formats$1.formatters[defaultFormat],
indices: false,
serializeDate: function serializeDate(date$2) {
return toISO.call(date$2);
},
skipNulls: false,
strictNullHandling: false
};
var isNonNullishPrimitive = function isNonNullishPrimitive$1(v$3) {
return typeof v$3 === "string" || typeof v$3 === "number" || typeof v$3 === "boolean" || typeof v$3 === "symbol" || typeof v$3 === "bigint";
};
var stringify$1 = function stringify$2(object$2, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter$1, sort, allowDots, serializeDate, format$1, formatter, encodeValuesOnly, charset) {
var obj = object$2;
if (typeof filter$1 === "function") obj = filter$1(prefix, obj);
else if (obj instanceof Date) obj = serializeDate(obj);
else if (generateArrayPrefix === "comma" && isArray$1(obj)) obj = utils$1.maybeMap(obj, function(value$1) {
if (value$1 instanceof Date) return serializeDate(value$1);
return value$1;
});
if (obj === null) {
if (strictNullHandling) return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder, charset, "key", format$1) : prefix;
obj = "";
}
if (isNonNullishPrimitive(obj) || utils$1.isBuffer(obj)) {
if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder, charset, "key", format$1);
if (generateArrayPrefix === "comma" && encodeValuesOnly) {
var valuesArray = split.call(String(obj), ",");
var valuesJoined = "";
for (var i$3 = 0; i$3 < valuesArray.length; ++i$3) valuesJoined += (i$3 === 0 ? "" : ",") + formatter(encoder(valuesArray[i$3], defaults$1.encoder, charset, "value", format$1));
return [formatter(keyValue) + "=" + valuesJoined];
}
return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults$1.encoder, charset, "value", format$1))];
}
return [formatter(prefix) + "=" + formatter(String(obj))];
}
var values = [];
if (typeof obj === "undefined") return values;
var objKeys;
if (generateArrayPrefix === "comma" && isArray$1(obj)) objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
else if (isArray$1(filter$1)) objKeys = filter$1;
else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var j$4 = 0; j$4 < objKeys.length; ++j$4) {
var key = objKeys[j$4];
var value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key];
if (skipNulls && value === null) continue;
var keyPrefix = isArray$1(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(prefix, key) : prefix : prefix + (allowDots ? "." + key : "[" + key + "]");
pushToArray(values, stringify$2(value, keyPrefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter$1, sort, allowDots, serializeDate, format$1, formatter, encodeValuesOnly, charset));
}
return values;
};
var normalizeStringifyOptions = function normalizeStringifyOptions$1(opts) {
if (!opts) return defaults$1;
if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") throw new TypeError("Encoder has to be a function.");
var charset = opts.charset || defaults$1.charset;
if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
var format$1 = formats$1["default"];
if (typeof opts.format !== "undefined") {
if (!has$1.call(formats$1.formatters, opts.format)) throw new TypeError("Unknown format option provided.");
format$1 = opts.format;
}
var formatter = formats$1.formatters[format$1];
var filter$1 = defaults$1.filter;
if (typeof opts.filter === "function" || isArray$1(opts.filter)) filter$1 = opts.filter;
return {
addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults$1.addQueryPrefix,
allowDots: typeof opts.allowDots === "undefined" ? defaults$1.allowDots : !!opts.allowDots,
charset,
charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults$1.charsetSentinel,
delimiter: typeof opts.delimiter === "undefined" ? defaults$1.delimiter : opts.delimiter,
encode: typeof opts.encode === "boolean" ? opts.encode : defaults$1.encode,
encoder: typeof opts.encoder === "function" ? opts.encoder : defaults$1.encoder,
encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults$1.encodeValuesOnly,
filter: filter$1,
format: format$1,
formatter,
serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults$1.serializeDate,
skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults$1.skipNulls,
sort: typeof opts.sort === "function" ? opts.sort : null,
strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults$1.strictNullHandling
};
};
module.exports = function(object$2, opts) {
var obj = object$2;
var options = normalizeStringifyOptions(opts);
var objKeys;
var filter$1;
if (typeof options.filter === "function") {
filter$1 = options.filter;
obj = filter$1("", obj);
} else if (isArray$1(options.filter)) {
filter$1 = options.filter;
objKeys = filter$1;
}
var keys = [];
if (typeof obj !== "object" || obj === null) return "";
var arrayFormat;
if (opts && opts.arrayFormat in arrayPrefixGenerators) arrayFormat = opts.arrayFormat;
else if (opts && "indices" in opts) arrayFormat = opts.indices ? "indices" : "repeat";
else arrayFormat = "indices";
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) objKeys = Object.keys(obj);
if (options.sort) objKeys.sort(options.sort);
for (var i$3 = 0; i$3 < objKeys.length; ++i$3) {
var key = objKeys[i$3];
if (options.skipNulls && obj[key] === null) continue;
pushToArray(keys, stringify$1(obj[key], key, generateArrayPrefix, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset));
}
var joined = keys.join(options.delimiter);
var prefix = options.addQueryPrefix === true ? "?" : "";
if (options.charsetSentinel) if (options.charset === "iso-8859-1") prefix += "utf8=%26%2310003%3B&";
else prefix += "utf8=%E2%9C%93&";
return joined.length > 0 ? prefix + joined : "";
};
} });
//#endregion
//#region ../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/parse.js
var require_parse = __commonJS({ "../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/parse.js"(exports, module) {
var utils = require_utils();
var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;
var defaults = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
charset: "utf-8",
charsetSentinel: false,
comma: false,
decoder: utils.decode,
delimiter: "&",
depth: 5,
ignoreQueryPrefix: false,
interpretNumericEntities: false,
parameterLimit: 1e3,
parseArrays: true,
plainObjects: false,
strictNullHandling: false
};
var interpretNumericEntities = function(str) {
return str.replace(/&#(\d+);/g, function($0, numberStr) {
return String.fromCharCode(parseInt(numberStr, 10));
});
};
var parseArrayValue = function(val, options) {
if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) return val.split(",");
return val;
};
var isoSentinel = "utf8=%26%2310003%3B";
var charsetSentinel = "utf8=%E2%9C%93";
var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str;
var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
var skipIndex = -1;
var i$3;
var charset = options.charset;
if (options.charsetSentinel) {
for (i$3 = 0; i$3 < parts.length; ++i$3) if (parts[i$3].indexOf("utf8=") === 0) {
if (parts[i$3] === charsetSentinel) charset = "utf-8";
else if (parts[i$3] === isoSentinel) charset = "iso-8859-1";
skipIndex = i$3;
i$3 = parts.length;
}
}
for (i$3 = 0; i$3 < parts.length; ++i$3) {
if (i$3 === skipIndex) continue;
var part = parts[i$3];
var bracketEqualsPos = part.indexOf("]=");
var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part, defaults.decoder, charset, "key");
val = options.strictNullHandling ? null : "";
} else {
key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key");
val = utils.maybeMap(parseArrayValue(part.slice(pos + 1), options), function(encodedVal) {
return options.decoder(encodedVal, defaults.decoder, charset, "value");
});
}
if (val && options.interpretNumericEntities && charset === "iso-8859-1") val = interpretNumericEntities(val);
if (part.indexOf("[]=") > -1) val = isArray(val) ? [val] : val;
if (has.call(obj, key)) obj[key] = utils.combine(obj[key], val);
else obj[key] = val;
}
return obj;
};
var parseObject = function(chain, val, options, valuesParsed) {
var leaf = valuesParsed ? val : parseArrayValue(val, options);
for (var i$3 = chain.length - 1; i$3 >= 0; --i$3) {
var obj;
var root = chain[i$3];
if (root === "[]" && options.parseArrays) obj = [].concat(leaf);
else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root;
var index$1 = parseInt(cleanRoot, 10);
if (!options.parseArrays && cleanRoot === "") obj = { 0: leaf };
else if (!isNaN(index$1) && root !== cleanRoot && String(index$1) === cleanRoot && index$1 >= 0 && options.parseArrays && index$1 <= options.arrayLimit) {
obj = [];
obj[index$1] = leaf;
} else if (cleanRoot !== "__proto__") obj[cleanRoot] = leaf;
}
leaf = obj;
}
return leaf;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
if (!givenKey) return;
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey;
var brackets = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
var segment = options.depth > 0 && brackets.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
var keys = [];
if (parent) {
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) return;
}
keys.push(parent);
}
var i$3 = 0;
while (options.depth > 0 && (segment = child.exec(key)) !== null && i$3 < options.depth) {
i$3 += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) return;
}
keys.push(segment[1]);
}
if (segment) keys.push("[" + key.slice(segment.index) + "]");
return parseObject(keys, val, options, valuesParsed);
};
var normalizeParseOptions = function normalizeParseOptions$1(opts) {
if (!opts) return defaults;
if (opts.decoder !== null && opts.decoder !== void 0 && typeof opts.decoder !== "function") throw new TypeError("Decoder has to be a function.");
if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset;
return {
allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots,
allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes,
arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit,
charset,
charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma,
decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder,
delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth,
ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit,
parseArrays: opts.parseArrays !== false,
plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects,
strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
};
};
module.exports = function(str, opts) {
var options = normalizeParseOptions(opts);
if (str === "" || str === null || typeof str === "undefined") return options.plainObjects ? Object.create(null) : {};
var tempObj = typeof str === "string" ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
var keys = Object.keys(tempObj);
for (var i$3 = 0; i$3 < keys.length; ++i$3) {
var key = keys[i$3];
var newObj = parseKeys(key, tempObj[key], options, typeof str === "string");
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
} });
//#endregion
//#region ../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/index.js
var require_lib = __commonJS({ "../../node_modules/.bun/qs@6.9.7/node_modules/qs/lib/index.js"(exports, module) {
var stringify = require_stringify();
var parse$2 = require_parse();
var formats = require_formats();
module.exports = {
formats,
parse: parse$2,
stringify
};
} });
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/routers/history.js
var import_lib = __toESM(require_lib());
function _typeof$7(o$3) {
"@babel/helpers - typeof";
return _typeof$7 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$7(o$3);
}
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties$1(target, props) {
for (var i$3 = 0; i$3 < props.length; i$3++) {
var descriptor = props[i$3];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey$7(descriptor.key), descriptor);
}
}
function _createClass$1(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
if (staticProps) _defineProperties$1(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _defineProperty$7(obj, key, value) {
key = _toPropertyKey$7(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$7(t$2) {
var i$3 = _toPrimitive$7(t$2, "string");
return "symbol" == _typeof$7(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$7(t$2, r$2) {
if ("object" != _typeof$7(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$7(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
var setWindowTitle = function setWindowTitle$1(title) {
if (title) window.document.title = title;
};
var BrowserHistory = /* @__PURE__ */ function() {
/**
* Initializes a new storage provider that syncs the search state to the URL
* using web APIs (`window.location.pushState` and `onpopstate` event).
*/
function BrowserHistory$1(_ref) {
var _this = this;
var windowTitle = _ref.windowTitle, _ref$writeDelay = _ref.writeDelay, writeDelay = _ref$writeDelay === void 0 ? 400 : _ref$writeDelay, createURL = _ref.createURL, parseURL = _ref.parseURL, getLocation = _ref.getLocation, start = _ref.start, dispose = _ref.dispose, push$1 = _ref.push, cleanUrlOnDispose = _ref.cleanUrlOnDispose;
_classCallCheck$1(this, BrowserHistory$1);
_defineProperty$7(this, "$$type", "ais.browser");
/**
* Transforms a UI state into a title for the page.
*/
_defineProperty$7(this, "windowTitle", void 0);
/**
* Time in milliseconds before performing a write in the history.
* It prevents from adding too many entries in the history and
* makes the back button more usable.
*
* @default 400
*/
_defineProperty$7(this, "writeDelay", void 0);
/**
* Creates a full URL based on the route state.
* The storage adaptor maps all syncable keys to the query string of the URL.
*/
_defineProperty$7(this, "_createURL", void 0);
/**
* Parses the URL into a route state.
* It should be symmetrical to `createURL`.
*/
_defineProperty$7(this, "parseURL", void 0);
/**
* Returns the location to store in the history.
* @default () => window.location
*/
_defineProperty$7(this, "getLocation", void 0);
_defineProperty$7(this, "writeTimer", void 0);
_defineProperty$7(this, "_onPopState", void 0);
/**
* Indicates if last action was back/forward in the browser.
*/
_defineProperty$7(this, "inPopState", false);
/**
* Indicates whether the history router is disposed or not.
*/
_defineProperty$7(this, "isDisposed", false);
/**
* Indicates the window.history.length before the last call to
* window.history.pushState (called in `write`).
* It allows to determine if a `pushState` has been triggered elsewhere,
* and thus to prevent the `write` method from calling `pushState`.
*/
_defineProperty$7(this, "latestAcknowledgedHistory", 0);
_defineProperty$7(this, "_start", void 0);
_defineProperty$7(this, "_dispose", void 0);
_defineProperty$7(this, "_push", void 0);
_defineProperty$7(this, "_cleanUrlOnDispose", void 0);
this.windowTitle = windowTitle;
this.writeTimer = void 0;
this.writeDelay = writeDelay;
this._createURL = createURL;
this.parseURL = parseURL;
this.getLocation = getLocation;
this._start = start;
this._dispose = dispose;
this._push = push$1;
this._cleanUrlOnDispose = typeof cleanUrlOnDispose === "undefined" ? true : cleanUrlOnDispose;
safelyRunOnBrowser(function(_ref2) {
var window$1 = _ref2.window;
var title = _this.windowTitle && _this.windowTitle(_this.read());
setWindowTitle(title);
_this.latestAcknowledgedHistory = window$1.history.length;
});
}
/**
* Reads the URL and returns a syncable UI search state.
*/
_createClass$1(BrowserHistory$1, [
{
key: "read",
value: function read() {
return this.parseURL({
qsModule: import_lib.default,
location: this.getLocation()
});
}
},
{
key: "write",
value: function write(routeState) {
var _this2 = this;
safelyRunOnBrowser(function(_ref3) {
var window$1 = _ref3.window;
var url = _this2.createURL(routeState);
var title = _this2.windowTitle && _this2.windowTitle(routeState);
if (_this2.writeTimer) clearTimeout(_this2.writeTimer);
_this2.writeTimer = setTimeout(function() {
setWindowTitle(title);
if (_this2.shouldWrite(url)) {
if (_this2._push) _this2._push(url);
else window$1.history.pushState(routeState, title || "", url);
_this2.latestAcknowledgedHistory = window$1.history.length;
}
_this2.inPopState = false;
_this2.writeTimer = void 0;
}, _this2.writeDelay);
});
}
},
{
key: "onUpdate",
value: function onUpdate(callback) {
var _this3 = this;
if (this._start) this._start(function() {
callback(_this3.read());
});
this._onPopState = function() {
if (_this3.writeTimer) {
clearTimeout(_this3.writeTimer);
_this3.writeTimer = void 0;
}
_this3.inPopState = true;
callback(_this3.read());
};
safelyRunOnBrowser(function(_ref4) {
var window$1 = _ref4.window;
window$1.addEventListener("popstate", _this3._onPopState);
});
}
},
{
key: "createURL",
value: function createURL(routeState) {
var url = this._createURL({
qsModule: import_lib.default,
routeState,
location: this.getLocation()
});
return url;
}
},
{
key: "dispose",
value: function dispose() {
var _this4 = this;
if (this._dispose) this._dispose();
this.isDisposed = true;
safelyRunOnBrowser(function(_ref5) {
var window$1 = _ref5.window;
if (_this4._onPopState) window$1.removeEventListener("popstate", _this4._onPopState);
});
if (this.writeTimer) clearTimeout(this.writeTimer);
if (this._cleanUrlOnDispose) this.write({});
}
},
{
key: "start",
value: function start() {
this.isDisposed = false;
}
},
{
key: "shouldWrite",
value: function shouldWrite(url) {
var _this5 = this;
return safelyRunOnBrowser(function(_ref6) {
var window$1 = _ref6.window;
if (_this5.isDisposed && !_this5._cleanUrlOnDispose) return false;
var lastPushWasByISAfterDispose = !(_this5.isDisposed && _this5.latestAcknowledgedHistory !== window$1.history.length);
return !_this5.inPopState && lastPushWasByISAfterDispose && url !== window$1.location.href;
});
}
}
]);
return BrowserHistory$1;
}();
function historyRouter() {
var _ref7 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref7$createURL = _ref7.createURL, createURL = _ref7$createURL === void 0 ? function(_ref8) {
var qsModule = _ref8.qsModule, routeState = _ref8.routeState, location = _ref8.location;
var protocol = location.protocol, hostname$1 = location.hostname, _location$port = location.port, port = _location$port === void 0 ? "" : _location$port, pathname = location.pathname, hash = location.hash;
var queryString = qsModule.stringify(routeState);
var portWithPrefix = port === "" ? "" : ":".concat(port);
if (!queryString) return "".concat(protocol, "//").concat(hostname$1).concat(portWithPrefix).concat(pathname).concat(hash);
return "".concat(protocol, "//").concat(hostname$1).concat(portWithPrefix).concat(pathname, "?").concat(queryString).concat(hash);
} : _ref7$createURL, _ref7$parseURL = _ref7.parseURL, parseURL = _ref7$parseURL === void 0 ? function(_ref9) {
var qsModule = _ref9.qsModule, location = _ref9.location;
return qsModule.parse(location.search.slice(1), { arrayLimit: 99 });
} : _ref7$parseURL, _ref7$writeDelay = _ref7.writeDelay, writeDelay = _ref7$writeDelay === void 0 ? 400 : _ref7$writeDelay, windowTitle = _ref7.windowTitle, _ref7$getLocation = _ref7.getLocation, getLocation = _ref7$getLocation === void 0 ? function() {
return safelyRunOnBrowser(function(_ref10) {
var window$1 = _ref10.window;
return window$1.location;
}, { fallback: function fallback() {
throw new Error("You need to provide `getLocation` to the `history` router in environments where `window` does not exist.");
} });
} : _ref7$getLocation, start = _ref7.start, dispose = _ref7.dispose, push$1 = _ref7.push, cleanUrlOnDispose = _ref7.cleanUrlOnDispose;
return new BrowserHistory({
createURL,
parseURL,
writeDelay,
windowTitle,
getLocation,
start,
dispose,
push: push$1,
cleanUrlOnDispose
});
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/stateMappings/simple.js
function _typeof$6(o$3) {
"@babel/helpers - typeof";
return _typeof$6 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$6(o$3);
}
var _excluded$4 = ["configure"];
function ownKeys$6(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$6(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$6(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$6(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$6(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$6(obj, key, value) {
key = _toPropertyKey$6(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$6(t$2) {
var i$3 = _toPrimitive$6(t$2, "string");
return "symbol" == _typeof$6(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$6(t$2, r$2) {
if ("object" != _typeof$6(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$6(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function _objectWithoutProperties$4(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose$4(source, excluded);
var key, i$3;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i$3 = 0; i$3 < sourceSymbolKeys.length; i$3++) {
key = sourceSymbolKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose$4(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i$3;
for (i$3 = 0; i$3 < sourceKeys.length; i$3++) {
key = sourceKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function getIndexStateWithoutConfigure(uiState) {
var configure = uiState.configure, trackedUiState = _objectWithoutProperties$4(uiState, _excluded$4);
return trackedUiState;
}
function simpleStateMapping() {
return {
$$type: "ais.simple",
stateToRoute: function stateToRoute(uiState) {
return Object.keys(uiState).reduce(function(state, indexId) {
return _objectSpread$6(_objectSpread$6({}, state), {}, _defineProperty$6({}, indexId, getIndexStateWithoutConfigure(uiState[indexId])));
}, {});
},
routeToState: function routeToState() {
var routeState = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
return Object.keys(routeState).reduce(function(state, indexId) {
return _objectSpread$6(_objectSpread$6({}, state), {}, _defineProperty$6({}, indexId, getIndexStateWithoutConfigure(routeState[indexId])));
}, {});
}
};
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/middlewares/createRouterMiddleware.js
function _typeof$5(o$3) {
"@babel/helpers - typeof";
return _typeof$5 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$5(o$3);
}
function ownKeys$5(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$5(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$5(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$5(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$5(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$5(obj, key, value) {
key = _toPropertyKey$5(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$5(t$2) {
var i$3 = _toPrimitive$5(t$2, "string");
return "symbol" == _typeof$5(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$5(t$2, r$2) {
if ("object" != _typeof$5(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$5(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
var createRouterMiddleware = function createRouterMiddleware$1() {
var props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
var _props$router = props.router, router = _props$router === void 0 ? historyRouter() : _props$router, _props$stateMapping = props.stateMapping, stateMapping = _props$stateMapping === void 0 ? simpleStateMapping() : _props$stateMapping, _props$$$internal = props.$$internal, $$internal = _props$$$internal === void 0 ? false : _props$$$internal;
return function(_ref) {
var instantSearchInstance = _ref.instantSearchInstance;
function topLevelCreateURL(nextState) {
var previousUiState = instantSearchInstance.mainIndex.getWidgets().length === 0 ? instantSearchInstance._initialUiState : instantSearchInstance.mainIndex.getWidgetUiState({});
var uiState = Object.keys(nextState).reduce(function(acc, indexId) {
return _objectSpread$5(_objectSpread$5({}, acc), {}, _defineProperty$5({}, indexId, nextState[indexId]));
}, previousUiState);
var route = stateMapping.stateToRoute(uiState);
return router.createURL(route);
}
instantSearchInstance._createURL = topLevelCreateURL;
var lastRouteState = void 0;
var initialUiState = instantSearchInstance._initialUiState;
return {
$$type: "ais.router({router:".concat(router.$$type || "__unknown__", ", stateMapping:").concat(stateMapping.$$type || "__unknown__", "})"),
$$internal,
onStateChange: function onStateChange(_ref2) {
var uiState = _ref2.uiState;
var routeState = stateMapping.stateToRoute(uiState);
if (lastRouteState === void 0 || !isEqual(lastRouteState, routeState)) {
router.write(routeState);
lastRouteState = routeState;
}
},
subscribe: function subscribe() {
instantSearchInstance._initialUiState = _objectSpread$5(_objectSpread$5({}, initialUiState), stateMapping.routeToState(router.read()));
router.onUpdate(function(route) {
if (instantSearchInstance.mainIndex.getWidgets().length > 0) instantSearchInstance.setUiState(stateMapping.routeToState(route));
});
},
started: function started() {
var _router$start;
(_router$start = router.start) === null || _router$start === void 0 || _router$start.call(router);
},
unsubscribe: function unsubscribe() {
router.dispose();
}
};
};
};
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/formatNumber.js
function formatNumber(value, numberLocale) {
return value.toLocaleString(numberLocale);
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/createHelpers.js
function _typeof$4(o$3) {
"@babel/helpers - typeof";
return _typeof$4 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$4(o$3);
}
function ownKeys$4(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$4(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$4(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$4(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$4(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$4(obj, key, value) {
key = _toPropertyKey$4(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$4(t$2) {
var i$3 = _toPrimitive$4(t$2, "string");
return "symbol" == _typeof$4(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$4(t$2, r$2) {
if ("object" != _typeof$4(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$4(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
function hoganHelpers(_ref) {
var numberLocale = _ref.numberLocale;
return {
formatNumber: function formatNumber$1(value, render) {
return formatNumber(Number(render(value)), numberLocale);
},
highlight: function highlight$1(options, render) {
try {
var highlightOptions = JSON.parse(options);
return render(highlight(_objectSpread$4(_objectSpread$4({}, highlightOptions), {}, { hit: this })));
} catch (error) {
throw new Error("\nThe highlight helper expects a JSON object of the format:\n{ \"attribute\": \"name\", \"highlightedTagName\": \"mark\" }");
}
},
reverseHighlight: function reverseHighlight$1(options, render) {
try {
var reverseHighlightOptions = JSON.parse(options);
return render(reverseHighlight(_objectSpread$4(_objectSpread$4({}, reverseHighlightOptions), {}, { hit: this })));
} catch (error) {
throw new Error("\n The reverseHighlight helper expects a JSON object of the format:\n { \"attribute\": \"name\", \"highlightedTagName\": \"mark\" }");
}
},
snippet: function snippet$1(options, render) {
try {
var snippetOptions = JSON.parse(options);
return render(snippet(_objectSpread$4(_objectSpread$4({}, snippetOptions), {}, { hit: this })));
} catch (error) {
throw new Error("\nThe snippet helper expects a JSON object of the format:\n{ \"attribute\": \"name\", \"highlightedTagName\": \"mark\" }");
}
},
reverseSnippet: function reverseSnippet$1(options, render) {
try {
var reverseSnippetOptions = JSON.parse(options);
return render(reverseSnippet(_objectSpread$4(_objectSpread$4({}, reverseSnippetOptions), {}, { hit: this })));
} catch (error) {
throw new Error("\n The reverseSnippet helper expects a JSON object of the format:\n { \"attribute\": \"name\", \"highlightedTagName\": \"mark\" }");
}
},
insights: function insights$1(options, render) {
try {
var _JSON$parse = JSON.parse(options), method = _JSON$parse.method, payload = _JSON$parse.payload;
return render(insights(method, _objectSpread$4({ objectIDs: [this.objectID] }, payload)));
} catch (error) {
throw new Error("\nThe insights helper expects a JSON object of the format:\n{ \"method\": \"method-name\", \"payload\": { \"eventName\": \"name of the event\" } }");
}
}
};
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/version.js
var version_default = "4.80.0";
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/lib/InstantSearch.js
var import_events = __toESM(require_events());
var import_algoliasearch_helper = __toESM(require_algoliasearch_helper());
function _typeof$3(o$3) {
"@babel/helpers - typeof";
return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$3(o$3);
}
function ownKeys$3(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$3(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$3(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$3(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$3(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i$3 = 0; i$3 < props.length; i$3++) {
var descriptor = props[i$3];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey$3(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o$3, p$2) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$1(o$4, p$3) {
o$4.__proto__ = p$3;
return o$4;
};
return _setPrototypeOf(o$3, p$2);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof$3(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e$2) {
return false;
}
}
function _getPrototypeOf(o$3) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf$1(o$4) {
return o$4.__proto__ || Object.getPrototypeOf(o$4);
};
return _getPrototypeOf(o$3);
}
function _defineProperty$3(obj, key, value) {
key = _toPropertyKey$3(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$3(t$2) {
var i$3 = _toPrimitive$3(t$2, "string");
return "symbol" == _typeof$3(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$3(t$2, r$2) {
if ("object" != _typeof$3(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$3(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
var withUsage$2 = createDocumentationMessageGenerator({ name: "instantsearch" });
function defaultCreateURL() {
return "#";
}
/**
* Global options for an InstantSearch instance.
*/
var INSTANTSEARCH_FUTURE_DEFAULTS = {
preserveSharedStateOnUnmount: false,
persistHierarchicalRootCount: false
};
/**
* The actual implementation of the InstantSearch. This is
* created using the `instantsearch` factory function.
* It emits the 'render' event every time a search is done
*/
var InstantSearch$1 = /* @__PURE__ */ function(_EventEmitter) {
_inherits(InstantSearch$2, _EventEmitter);
var _super = _createSuper(InstantSearch$2);
function InstantSearch$2(options) {
var _options$future2;
var _this;
_classCallCheck(this, InstantSearch$2);
_this = _super.call(this);
_defineProperty$3(_assertThisInitialized(_this), "client", void 0);
_defineProperty$3(_assertThisInitialized(_this), "indexName", void 0);
_defineProperty$3(_assertThisInitialized(_this), "compositionID", void 0);
_defineProperty$3(_assertThisInitialized(_this), "insightsClient", void 0);
_defineProperty$3(_assertThisInitialized(_this), "onStateChange", null);
_defineProperty$3(_assertThisInitialized(_this), "future", void 0);
_defineProperty$3(_assertThisInitialized(_this), "helper", void 0);
_defineProperty$3(_assertThisInitialized(_this), "mainHelper", void 0);
_defineProperty$3(_assertThisInitialized(_this), "mainIndex", void 0);
_defineProperty$3(_assertThisInitialized(_this), "started", void 0);
_defineProperty$3(_assertThisInitialized(_this), "templatesConfig", void 0);
_defineProperty$3(_assertThisInitialized(_this), "renderState", {});
_defineProperty$3(_assertThisInitialized(_this), "_stalledSearchDelay", void 0);
_defineProperty$3(_assertThisInitialized(_this), "_searchStalledTimer", void 0);
_defineProperty$3(_assertThisInitialized(_this), "_initialUiState", void 0);
_defineProperty$3(_assertThisInitialized(_this), "_initialResults", void 0);
_defineProperty$3(_assertThisInitialized(_this), "_manuallyResetScheduleSearch", false);
_defineProperty$3(_assertThisInitialized(_this), "_resetScheduleSearch", void 0);
_defineProperty$3(_assertThisInitialized(_this), "_createURL", void 0);
_defineProperty$3(_assertThisInitialized(_this), "_searchFunction", void 0);
_defineProperty$3(_assertThisInitialized(_this), "_mainHelperSearch", void 0);
_defineProperty$3(_assertThisInitialized(_this), "_hasSearchWidget", false);
_defineProperty$3(_assertThisInitialized(_this), "_hasRecommendWidget", false);
_defineProperty$3(_assertThisInitialized(_this), "_insights", void 0);
_defineProperty$3(_assertThisInitialized(_this), "middleware", []);
_defineProperty$3(_assertThisInitialized(_this), "sendEventToInsights", void 0);
/**
* The status of the search. Can be "idle", "loading", "stalled", or "error".
*/
_defineProperty$3(_assertThisInitialized(_this), "status", "idle");
/**
* The last returned error from the Search API.
* The error gets cleared when the next valid search response is rendered.
*/
_defineProperty$3(_assertThisInitialized(_this), "error", void 0);
_defineProperty$3(_assertThisInitialized(_this), "scheduleSearch", defer(function() {
if (_this.started) _this.mainHelper.search();
}));
_defineProperty$3(_assertThisInitialized(_this), "scheduleRender", defer(function() {
var _this$mainHelper;
var shouldResetStatus = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
if (!((_this$mainHelper = _this.mainHelper) !== null && _this$mainHelper !== void 0 && _this$mainHelper.hasPendingRequests())) {
clearTimeout(_this._searchStalledTimer);
_this._searchStalledTimer = null;
if (shouldResetStatus) {
_this.status = "idle";
_this.error = void 0;
}
}
_this.mainIndex.render({ instantSearchInstance: _assertThisInitialized(_this) });
_this.emit("render");
}));
_defineProperty$3(_assertThisInitialized(_this), "onInternalStateChange", defer(function() {
var nextUiState = _this.mainIndex.getWidgetUiState({});
_this.middleware.forEach(function(_ref) {
var instance = _ref.instance;
instance.onStateChange({ uiState: nextUiState });
});
}));
_this.setMaxListeners(100);
var _options$indexName = options.indexName, indexName = _options$indexName === void 0 ? "" : _options$indexName, compositionID = options.compositionID, numberLocale = options.numberLocale, _options$initialUiSta = options.initialUiState, initialUiState = _options$initialUiSta === void 0 ? {} : _options$initialUiSta, _options$routing = options.routing, routing = _options$routing === void 0 ? null : _options$routing, _options$insights = options.insights, insights$1 = _options$insights === void 0 ? void 0 : _options$insights, searchFunction = options.searchFunction, _options$stalledSearc = options.stalledSearchDelay, stalledSearchDelay = _options$stalledSearc === void 0 ? 200 : _options$stalledSearc, _options$searchClient = options.searchClient, searchClient = _options$searchClient === void 0 ? null : _options$searchClient, _options$insightsClie = options.insightsClient, insightsClient = _options$insightsClie === void 0 ? null : _options$insightsClie, _options$onStateChang = options.onStateChange, onStateChange = _options$onStateChang === void 0 ? null : _options$onStateChang, _options$future = options.future, future = _options$future === void 0 ? _objectSpread$3(_objectSpread$3({}, INSTANTSEARCH_FUTURE_DEFAULTS), options.future || {}) : _options$future;
if (searchClient === null) throw new Error(withUsage$2("The `searchClient` option is required."));
if (typeof searchClient.search !== "function") throw new Error("The `searchClient` must implement a `search` method.\n\nSee: https://www.algolia.com/doc/guides/building-search-ui/going-further/backend-search/in-depth/backend-instantsearch/js/");
if (typeof searchClient.addAlgoliaAgent === "function") searchClient.addAlgoliaAgent("instantsearch.js (".concat(version_default, ")"));
if (insightsClient && typeof insightsClient !== "function") throw new Error(withUsage$2("The `insightsClient` option should be a function."));
_this.client = searchClient;
_this.future = future;
_this.insightsClient = insightsClient;
_this.indexName = indexName;
_this.compositionID = compositionID;
_this.helper = null;
_this.mainHelper = null;
_this.mainIndex = index_default({ indexName: _this.compositionID || _this.indexName });
_this.onStateChange = onStateChange;
_this.started = false;
_this.templatesConfig = {
helpers: hoganHelpers({ numberLocale }),
compileOptions: {}
};
_this._stalledSearchDelay = stalledSearchDelay;
_this._searchStalledTimer = null;
_this._createURL = defaultCreateURL;
_this._initialUiState = initialUiState;
_this._initialResults = null;
_this._insights = insights$1;
if (searchFunction) _this._searchFunction = searchFunction;
_this.sendEventToInsights = noop$1;
if (routing) {
var routerOptions = typeof routing === "boolean" ? {} : routing;
routerOptions.$$internal = true;
_this.use(createRouterMiddleware(routerOptions));
}
if (insights$1) {
var insightsOptions = typeof insights$1 === "boolean" ? {} : insights$1;
insightsOptions.$$internal = true;
_this.use(createInsightsMiddleware(insightsOptions));
}
if (isMetadataEnabled()) _this.use(createMetadataMiddleware({ $$internal: true }));
return _this;
}
/**
* Hooks a middleware into the InstantSearch lifecycle.
*/
_createClass(InstantSearch$2, [
{
key: "_isSearchStalled",
get: function get() {
return this.status === "stalled";
}
},
{
key: "use",
value: function use$1() {
var _this2 = this;
for (var _len = arguments.length, middleware = new Array(_len), _key = 0; _key < _len; _key++) middleware[_key] = arguments[_key];
var newMiddlewareList = middleware.map(function(fn$1) {
var newMiddleware = _objectSpread$3({
$$type: "__unknown__",
$$internal: false,
subscribe: noop$1,
started: noop$1,
unsubscribe: noop$1,
onStateChange: noop$1
}, fn$1({ instantSearchInstance: _this2 }));
_this2.middleware.push({
creator: fn$1,
instance: newMiddleware
});
return newMiddleware;
});
if (this.started) newMiddlewareList.forEach(function(m$4) {
m$4.subscribe();
m$4.started();
});
return this;
}
},
{
key: "unuse",
value: function unuse() {
for (var _len2 = arguments.length, middlewareToUnuse = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) middlewareToUnuse[_key2] = arguments[_key2];
this.middleware.filter(function(m$4) {
return middlewareToUnuse.includes(m$4.creator);
}).forEach(function(m$4) {
return m$4.instance.unsubscribe();
});
this.middleware = this.middleware.filter(function(m$4) {
return !middlewareToUnuse.includes(m$4.creator);
});
return this;
}
},
{
key: "EXPERIMENTAL_use",
value: function EXPERIMENTAL_use() {
return this.use.apply(this, arguments);
}
},
{
key: "addWidget",
value: function addWidget(widget) {
return this.addWidgets([widget]);
}
},
{
key: "addWidgets",
value: function addWidgets(widgets) {
if (!Array.isArray(widgets)) throw new Error(withUsage$2("The `addWidgets` method expects an array of widgets. Please use `addWidget`."));
if (this.compositionID && widgets.some(function(w$4) {
return !Array.isArray(w$4) && isIndexWidget(w$4) && !w$4._isolated;
})) throw new Error(withUsage$2("The `index` widget cannot be used with a composition-based InstantSearch implementation."));
this.mainIndex.addWidgets(widgets);
return this;
}
},
{
key: "removeWidget",
value: function removeWidget(widget) {
return this.removeWidgets([widget]);
}
},
{
key: "removeWidgets",
value: function removeWidgets(widgets) {
if (!Array.isArray(widgets)) throw new Error(withUsage$2("The `removeWidgets` method expects an array of widgets. Please use `removeWidget`."));
this.mainIndex.removeWidgets(widgets);
return this;
}
},
{
key: "start",
value: function start() {
var _this3 = this;
if (this.started) throw new Error(withUsage$2("The `start` method has already been called once."));
var mainHelper = this.mainHelper || (0, import_algoliasearch_helper.default)(this.client, this.indexName, void 0, { persistHierarchicalRootCount: this.future.persistHierarchicalRootCount });
if (this.compositionID) mainHelper.searchForFacetValues = mainHelper.searchForCompositionFacetValues.bind(mainHelper);
mainHelper.search = function() {
_this3.status = "loading";
_this3.scheduleRender(false);
if (_this3._hasSearchWidget) if (_this3.compositionID) mainHelper.searchWithComposition();
else mainHelper.searchOnlyWithDerivedHelpers();
if (_this3._hasRecommendWidget) mainHelper.recommend();
return mainHelper;
};
if (this._searchFunction) {
var fakeClient = { search: function search() {
return new Promise(noop$1);
} };
this._mainHelperSearch = mainHelper.search.bind(mainHelper);
mainHelper.search = function() {
var mainIndexHelper = _this3.mainIndex.getHelper();
var searchFunctionHelper = (0, import_algoliasearch_helper.default)(fakeClient, mainIndexHelper.state.index, mainIndexHelper.state);
searchFunctionHelper.once("search", function(_ref2) {
var state = _ref2.state;
mainIndexHelper.overrideStateWithoutTriggeringChangeEvent(state);
_this3._mainHelperSearch();
});
searchFunctionHelper.on("change", function(_ref3) {
var state = _ref3.state;
mainIndexHelper.setState(state);
});
_this3._searchFunction(searchFunctionHelper);
return mainHelper;
};
}
mainHelper.on("error", function(_ref4) {
var error = _ref4.error;
if (!(error instanceof Error)) {
var err = error;
error = Object.keys(err).reduce(function(acc, key) {
acc[key] = err[key];
return acc;
}, new Error(err.message));
}
error.error = error;
_this3.error = error;
_this3.status = "error";
_this3.scheduleRender(false);
_this3.emit("error", error);
});
this.mainHelper = mainHelper;
this.middleware.forEach(function(_ref5) {
var instance = _ref5.instance;
instance.subscribe();
});
this.mainIndex.init({
instantSearchInstance: this,
parent: null,
uiState: this._initialUiState
});
if (this._initialResults) {
hydrateSearchClient(this.client, this._initialResults);
hydrateRecommendCache(this.mainHelper, this._initialResults);
var originalScheduleSearch = this.scheduleSearch;
this.scheduleSearch = defer(noop$1);
if (this._manuallyResetScheduleSearch) this._resetScheduleSearch = function() {
_this3.scheduleSearch = originalScheduleSearch;
};
else defer(function() {
_this3.scheduleSearch = originalScheduleSearch;
})();
} else if (this.mainIndex.getWidgets().length > 0) this.scheduleSearch();
this.helper = this.mainIndex.getHelper();
this.started = true;
this.middleware.forEach(function(_ref6) {
var instance = _ref6.instance;
instance.started();
});
if (typeof this._insights === "undefined") mainHelper.derivedHelpers[0].once("result", function() {
var hasAutomaticInsights = _this3.mainIndex.getScopedResults().some(function(_ref7) {
var results = _ref7.results;
return results === null || results === void 0 ? void 0 : results._automaticInsights;
});
if (hasAutomaticInsights) _this3.use(createInsightsMiddleware({
$$internal: true,
$$automatic: true
}));
});
}
},
{
key: "dispose",
value: function dispose() {
var _this$mainHelper2;
this.scheduleSearch.cancel();
this.scheduleRender.cancel();
clearTimeout(this._searchStalledTimer);
this.removeWidgets(this.mainIndex.getWidgets());
this.mainIndex.dispose();
this.started = false;
this.removeAllListeners();
(_this$mainHelper2 = this.mainHelper) === null || _this$mainHelper2 === void 0 || _this$mainHelper2.removeAllListeners();
this.mainHelper = null;
this.helper = null;
this.middleware.forEach(function(_ref8) {
var instance = _ref8.instance;
instance.unsubscribe();
});
}
},
{
key: "scheduleStalledRender",
value: function scheduleStalledRender() {
var _this4 = this;
if (!this._searchStalledTimer) this._searchStalledTimer = setTimeout(function() {
_this4.status = "stalled";
_this4.scheduleRender();
}, this._stalledSearchDelay);
}
},
{
key: "setUiState",
value: function setUiState(uiState) {
var _this5 = this;
var callOnStateChange = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
if (!this.mainHelper) throw new Error(withUsage$2("The `start` method needs to be called before `setUiState`."));
this.mainIndex.refreshUiState();
var nextUiState = typeof uiState === "function" ? uiState(this.mainIndex.getWidgetUiState({})) : uiState;
if (this.onStateChange && callOnStateChange) this.onStateChange({
uiState: nextUiState,
setUiState: function setUiState$1(finalUiState) {
setIndexHelperState(typeof finalUiState === "function" ? finalUiState(nextUiState) : finalUiState, _this5.mainIndex);
_this5.scheduleSearch();
_this5.onInternalStateChange();
}
});
else {
setIndexHelperState(nextUiState, this.mainIndex);
this.scheduleSearch();
this.onInternalStateChange();
}
}
},
{
key: "getUiState",
value: function getUiState() {
if (this.started) this.mainIndex.refreshUiState();
return this.mainIndex.getWidgetUiState({});
}
},
{
key: "createURL",
value: function createURL() {
var nextState = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
if (!this.started) throw new Error(withUsage$2("The `start` method needs to be called before `createURL`."));
return this._createURL(nextState);
}
},
{
key: "refresh",
value: function refresh() {
if (!this.mainHelper) throw new Error(withUsage$2("The `start` method needs to be called before `refresh`."));
this.mainHelper.clearCache().search();
}
}
]);
return InstantSearch$2;
}(import_events.default);
var InstantSearch_default = InstantSearch$1;
//#endregion
//#region ../../node_modules/.bun/use-sync-external-store@1.5.0+2f44e903108183df/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js
var require_use_sync_external_store_shim_production = __commonJS({ "../../node_modules/.bun/use-sync-external-store@1.5.0+2f44e903108183df/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js"(exports) {
var React = (init_compat_module(), __toCommonJS(compat_module_exports));
function is(x$4, y$3) {
return x$4 === y$3 && (0 !== x$4 || 1 / x$4 === 1 / y$3) || x$4 !== x$4 && y$3 !== y$3;
}
var objectIs = "function" === typeof Object.is ? Object.is : is, useState = React.useState, useEffect = React.useEffect, useLayoutEffect = React.useLayoutEffect, useDebugValue = React.useDebugValue;
function useSyncExternalStore$2(subscribe, getSnapshot) {
var value = getSnapshot(), _useState = useState({ inst: {
value,
getSnapshot
} }), inst = _useState[0].inst, forceUpdate = _useState[1];
useLayoutEffect(function() {
inst.value = value;
inst.getSnapshot = getSnapshot;
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
}, [
subscribe,
value,
getSnapshot
]);
useEffect(function() {
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
return subscribe(function() {
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
});
}, [subscribe]);
useDebugValue(value);
return value;
}
function checkIfSnapshotChanged(inst) {
var latestGetSnapshot = inst.getSnapshot;
inst = inst.value;
try {
var nextValue = latestGetSnapshot();
return !objectIs(inst, nextValue);
} catch (error) {
return !0;
}
}
function useSyncExternalStore$1(subscribe, getSnapshot) {
return getSnapshot();
}
var shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
exports.useSyncExternalStore = void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;
} });
//#endregion
//#region ../../node_modules/.bun/use-sync-external-store@1.5.0+2f44e903108183df/node_modules/use-sync-external-store/shim/index.js
var require_shim = __commonJS({ "../../node_modules/.bun/use-sync-external-store@1.5.0+2f44e903108183df/node_modules/use-sync-external-store/shim/index.js"(exports, module) {
module.exports = require_use_sync_external_store_shim_production();
} });
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useInstantSearchApi.js
init_compat_module();
var import_shim = __toESM(require_shim(), 1);
function _typeof$2(o$3) {
"@babel/helpers - typeof";
return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$2(o$3);
}
function ownKeys$2(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$2(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$2(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$2(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$2(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$2(obj, key, value) {
key = _toPropertyKey$2(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$2(t$2) {
var i$3 = _toPrimitive$2(t$2, "string");
return "symbol" == _typeof$2(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$2(t$2, r$2) {
if ("object" != _typeof$2(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$2(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
var defaultUserAgents = [
"react (".concat(vn, ")"),
"react-instantsearch (".concat(version_default$1, ")"),
"react-instantsearch-core (".concat(version_default$1, ")")
];
var serverUserAgent = "react-instantsearch-server (".concat(version_default$1, ")");
var nextUserAgent = function nextUserAgent$1(nextVersion) {
return nextVersion ? "next.js (".concat(nextVersion, ")") : null;
};
function useInstantSearchApi(props) {
var forceUpdate = useForceUpdate();
var serverContext = useInstantSearchServerContext();
var serverState = useInstantSearchSSRContext();
var _useRSCContext = useRSCContext(), waitForResultsRef = _useRSCContext.waitForResultsRef;
var initialResults = serverState === null || serverState === void 0 ? void 0 : serverState.initialResults;
var prevPropsRef = A(props);
var shouldRenderAtOnce = serverContext || initialResults || waitForResultsRef;
var searchRef = A(null);
if (serverState !== null && serverState !== void 0 && serverState.ssrSearchRef) searchRef = serverState.ssrSearchRef;
if (searchRef.current === null) {
var search = new InstantSearch_default(props);
search._schedule = function _schedule(cb) {
search._schedule.queue.push(cb);
clearTimeout(search._schedule.timer);
search._schedule.timer = setTimeout(function() {
search._schedule.queue.forEach(function(callback) {
callback();
});
search._schedule.queue = [];
}, 0);
};
search._schedule.queue = [];
if (shouldRenderAtOnce) {
search._initialResults = initialResults || {};
search._manuallyResetScheduleSearch = true;
}
addAlgoliaAgents(props.searchClient, [].concat(defaultUserAgents, [serverContext && serverUserAgent, nextUserAgent(getNextVersion())]));
if (shouldRenderAtOnce) search.start();
if (serverContext) serverContext.notifyServer({ search });
warnNextRouter(props.routing);
warnNextAppDir(Boolean(waitForResultsRef));
searchRef.current = search;
}
{
var _search = searchRef.current;
var prevProps = prevPropsRef.current;
if (prevProps.indexName !== props.indexName) {
_search.helper.setIndex(props.indexName || "").search();
prevPropsRef.current = props;
}
if (prevProps.searchClient !== props.searchClient) {
addAlgoliaAgents(props.searchClient, [].concat(defaultUserAgents, [serverContext && serverUserAgent]));
_search.mainHelper.setClient(props.searchClient).search();
prevPropsRef.current = props;
}
if (prevProps.onStateChange !== props.onStateChange) {
_search.onStateChange = props.onStateChange;
prevPropsRef.current = props;
}
if (prevProps.searchFunction !== props.searchFunction) {
_search._searchFunction = props.searchFunction;
prevPropsRef.current = props;
}
if (prevProps.stalledSearchDelay !== props.stalledSearchDelay) {
var _props$stalledSearchD;
_search._stalledSearchDelay = (_props$stalledSearchD = props.stalledSearchDelay) !== null && _props$stalledSearchD !== void 0 ? _props$stalledSearchD : 200;
prevPropsRef.current = props;
}
if (!dequal(prevProps.future, props.future)) {
_search.future = _objectSpread$2(_objectSpread$2({}, INSTANTSEARCH_FUTURE_DEFAULTS), props.future);
prevPropsRef.current = props;
}
}
var cleanupTimerRef = A(null);
var store = (0, import_shim.useSyncExternalStore)(q(function() {
var search$1 = searchRef.current;
if (cleanupTimerRef.current === null) {
if (!search$1.started) {
search$1.start();
forceUpdate();
}
} else {
clearTimeout(cleanupTimerRef.current);
search$1._preventWidgetCleanup = false;
}
return function() {
if (serverState !== null && serverState !== void 0 && serverState.ssrSearchRef) return;
function cleanup() {
search$1.dispose();
}
clearTimeout(search$1._schedule.timer);
cleanupTimerRef.current = setTimeout(cleanup);
search$1._preventWidgetCleanup = true;
};
}, [forceUpdate, serverState]), function() {
return searchRef.current;
}, function() {
return searchRef.current;
});
return store;
}
function addAlgoliaAgents(searchClient, userAgents) {
if (typeof searchClient.addAlgoliaAgent !== "function") return;
userAgents.filter(Boolean).forEach(function(userAgent) {
searchClient.addAlgoliaAgent(userAgent);
});
}
function warnNextRouter(routing) {
if (0) var _routing$router, isUsingNextRouter;
}
function warnNextAppDir(isRscContextDefined) {
var _next;
return;
}
/**
* Gets the version of Next.js if it is available in the `window` object,
* otherwise it returns the NEXT_RUNTIME environment variable (in SSR),
* which is either `nodejs` or `edge`.
*/
function getNextVersion() {
var _next2, _process$env;
return typeof window !== "undefined" && ((_next2 = window.next) === null || _next2 === void 0 ? void 0 : _next2.version) || (typeof process !== "undefined" ? (_process$env = process.env) === null || _process$env === void 0 ? void 0 : _process$env.NEXT_RUNTIME : void 0);
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/components/InstantSearch.js
init_compat_module();
var _excluded$3 = ["children"];
function _objectWithoutProperties$3(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose$3(source, excluded);
var key, i$3;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i$3 = 0; i$3 < sourceSymbolKeys.length; i$3++) {
key = sourceSymbolKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose$3(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i$3;
for (i$3 = 0; i$3 < sourceKeys.length; i$3++) {
key = sourceKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function InstantSearch(_ref) {
var children = _ref.children, props = _objectWithoutProperties$3(_ref, _excluded$3);
var search = useInstantSearchApi(props);
if (!search.started) return null;
return /* @__PURE__ */ Rn.createElement(InstantSearchContext.Provider, { value: search }, /* @__PURE__ */ Rn.createElement(IndexContext.Provider, { value: search.mainIndex }, children, /* @__PURE__ */ Rn.createElement(ResetScheduleSearch, { search })));
}
function ResetScheduleSearch(_ref2) {
var search = _ref2.search;
y(function() {
if (search._resetScheduleSearch) search._resetScheduleSearch();
}, [search]);
return null;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/connectors/hits/connectHits.js
function _typeof$1(o$3) {
"@babel/helpers - typeof";
return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof$1(o$3);
}
function ownKeys$1(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread$1(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys$1(Object(t$2), !0).forEach(function(r$3) {
_defineProperty$1(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys$1(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty$1(obj, key, value) {
key = _toPropertyKey$1(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey$1(t$2) {
var i$3 = _toPrimitive$1(t$2, "string");
return "symbol" == _typeof$1(i$3) ? i$3 : String(i$3);
}
function _toPrimitive$1(t$2, r$2) {
if ("object" != _typeof$1(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof$1(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
var withUsage$1 = createDocumentationMessageGenerator({
name: "hits",
connector: true
});
var connectHits_default = function connectHits(renderFn) {
var unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop$1;
checkRendering(renderFn, withUsage$1());
return function(widgetParams) {
var _ref = widgetParams || {}, _ref$escapeHTML = _ref.escapeHTML, escapeHTML = _ref$escapeHTML === void 0 ? true : _ref$escapeHTML, _ref$transformItems = _ref.transformItems, transformItems = _ref$transformItems === void 0 ? function(items) {
return items;
} : _ref$transformItems;
var sendEvent;
var bindEvent;
return {
$$type: "ais.hits",
init: function init(initOptions) {
renderFn(_objectSpread$1(_objectSpread$1({}, this.getWidgetRenderState(initOptions)), {}, { instantSearchInstance: initOptions.instantSearchInstance }), true);
},
render: function render(renderOptions) {
var renderState = this.getWidgetRenderState(renderOptions);
renderFn(_objectSpread$1(_objectSpread$1({}, renderState), {}, { instantSearchInstance: renderOptions.instantSearchInstance }), false);
renderState.sendEvent("view:internal", renderState.items);
},
getRenderState: function getRenderState(renderState, renderOptions) {
return _objectSpread$1(_objectSpread$1({}, renderState), {}, { hits: this.getWidgetRenderState(renderOptions) });
},
getWidgetRenderState: function getWidgetRenderState(_ref2) {
var _results$renderingCon, _results$renderingCon2, _results$renderingCon3;
var results = _ref2.results, helper = _ref2.helper, instantSearchInstance = _ref2.instantSearchInstance;
if (!sendEvent) sendEvent = createSendEventForHits({
instantSearchInstance,
helper,
widgetType: this.$$type
});
if (!bindEvent) bindEvent = createBindEventForHits({
helper,
widgetType: this.$$type,
instantSearchInstance
});
if (!results) return {
hits: [],
items: [],
results: void 0,
banner: void 0,
sendEvent,
bindEvent,
widgetParams
};
if (escapeHTML && results.hits.length > 0) results.hits = escapeHits(results.hits);
var hitsWithAbsolutePosition = addAbsolutePosition(results.hits, results.page, results.hitsPerPage);
var hitsWithAbsolutePositionAndQueryID = addQueryID(hitsWithAbsolutePosition, results.queryID);
var items = transformItems(hitsWithAbsolutePositionAndQueryID, { results });
var banner = (_results$renderingCon = results.renderingContent) === null || _results$renderingCon === void 0 ? void 0 : (_results$renderingCon2 = _results$renderingCon.widgets) === null || _results$renderingCon2 === void 0 ? void 0 : (_results$renderingCon3 = _results$renderingCon2.banners) === null || _results$renderingCon3 === void 0 ? void 0 : _results$renderingCon3[0];
return {
hits: items,
items,
results,
banner,
sendEvent,
bindEvent,
widgetParams
};
},
dispose: function dispose(_ref3) {
var state = _ref3.state;
unmountFn();
if (!escapeHTML) return state;
return state.setQueryParameters(Object.keys(TAG_PLACEHOLDER).reduce(function(acc, key) {
return _objectSpread$1(_objectSpread$1({}, acc), {}, _defineProperty$1({}, key, void 0));
}, {}));
},
getWidgetSearchParameters: function getWidgetSearchParameters(state, _uiState) {
if (!escapeHTML) return state;
return state.setQueryParameters(TAG_PLACEHOLDER);
}
};
};
};
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/connectors/useHits.js
function useHits(props, additionalWidgetProperties) {
return useConnector(connectHits_default, props, additionalWidgetProperties);
}
//#endregion
//#region ../../node_modules/.bun/instantsearch.js@4.80.0+28b6629f675cd2d9/node_modules/instantsearch.js/es/connectors/search-box/connectSearchBox.js
function _typeof(o$3) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$4) {
return typeof o$4;
} : function(o$4) {
return o$4 && "function" == typeof Symbol && o$4.constructor === Symbol && o$4 !== Symbol.prototype ? "symbol" : typeof o$4;
}, _typeof(o$3);
}
function ownKeys(e$2, r$2) {
var t$2 = Object.keys(e$2);
if (Object.getOwnPropertySymbols) {
var o$3 = Object.getOwnPropertySymbols(e$2);
r$2 && (o$3 = o$3.filter(function(r$3) {
return Object.getOwnPropertyDescriptor(e$2, r$3).enumerable;
})), t$2.push.apply(t$2, o$3);
}
return t$2;
}
function _objectSpread(e$2) {
for (var r$2 = 1; r$2 < arguments.length; r$2++) {
var t$2 = null != arguments[r$2] ? arguments[r$2] : {};
r$2 % 2 ? ownKeys(Object(t$2), !0).forEach(function(r$3) {
_defineProperty(e$2, r$3, t$2[r$3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e$2, Object.getOwnPropertyDescriptors(t$2)) : ownKeys(Object(t$2)).forEach(function(r$3) {
Object.defineProperty(e$2, r$3, Object.getOwnPropertyDescriptor(t$2, r$3));
});
}
return e$2;
}
function _defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey(t$2) {
var i$3 = _toPrimitive(t$2, "string");
return "symbol" == _typeof(i$3) ? i$3 : String(i$3);
}
function _toPrimitive(t$2, r$2) {
if ("object" != _typeof(t$2) || !t$2) return t$2;
var e$2 = t$2[Symbol.toPrimitive];
if (void 0 !== e$2) {
var i$3 = e$2.call(t$2, r$2 || "default");
if ("object" != _typeof(i$3)) return i$3;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r$2 ? String : Number)(t$2);
}
var withUsage = createDocumentationMessageGenerator({
name: "search-box",
connector: true
});
/**
* @typedef {Object} CustomSearchBoxWidgetParams
* @property {function(string, function(string))} [queryHook = undefined] A function that will be called every time
* a new value for the query is set. The first parameter is the query and the second is a
* function to actually trigger the search. The function takes the query as the parameter.
*
* This queryHook can be used to debounce the number of searches done from the searchBox.
*/
var defaultQueryHook = function defaultQueryHook$1(query, hook) {
return hook(query);
};
/**
* **SearchBox** connector provides the logic to build a widget that will let the user search for a query.
*
* The connector provides to the rendering: `refine()` to set the query. The behaviour of this function
* may be impacted by the `queryHook` widget parameter.
*/
var connectSearchBox = function connectSearchBox$1(renderFn) {
var unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop$1;
checkRendering(renderFn, withUsage());
return function(widgetParams) {
var _ref = widgetParams || {}, _ref$queryHook = _ref.queryHook, queryHook = _ref$queryHook === void 0 ? defaultQueryHook : _ref$queryHook;
var _refine$1;
var _clear;
return {
$$type: "ais.searchBox",
init: function init(initOptions) {
var instantSearchInstance = initOptions.instantSearchInstance;
renderFn(_objectSpread(_objectSpread({}, this.getWidgetRenderState(initOptions)), {}, { instantSearchInstance }), true);
},
render: function render(renderOptions) {
var instantSearchInstance = renderOptions.instantSearchInstance;
renderFn(_objectSpread(_objectSpread({}, this.getWidgetRenderState(renderOptions)), {}, { instantSearchInstance }), false);
},
dispose: function dispose(_ref2) {
var state = _ref2.state;
unmountFn();
return state.setQueryParameter("query", void 0);
},
getRenderState: function getRenderState(renderState, renderOptions) {
return _objectSpread(_objectSpread({}, renderState), {}, { searchBox: this.getWidgetRenderState(renderOptions) });
},
getWidgetRenderState: function getWidgetRenderState(_ref3) {
var helper = _ref3.helper, instantSearchInstance = _ref3.instantSearchInstance, state = _ref3.state;
if (!_refine$1) {
_refine$1 = function _refine$2(query) {
queryHook(query, function(q$4) {
return helper.setQuery(q$4).search();
});
};
_clear = function _clear$1() {
helper.setQuery("").search();
};
}
return {
query: state.query || "",
refine: _refine$1,
clear: _clear,
widgetParams,
isSearchStalled: instantSearchInstance.status === "stalled"
};
},
getWidgetUiState: function getWidgetUiState(uiState, _ref4) {
var searchParameters = _ref4.searchParameters;
var query = searchParameters.query || "";
if (query === "" || uiState && uiState.query === query) return uiState;
return _objectSpread(_objectSpread({}, uiState), {}, { query });
},
getWidgetSearchParameters: function getWidgetSearchParameters(searchParameters, _ref5) {
var uiState = _ref5.uiState;
return searchParameters.setQueryParameter("query", uiState.query || "");
}
};
};
};
var connectSearchBox_default = connectSearchBox;
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/connectors/useSearchBox.js
function useSearchBox(props, additionalWidgetProperties) {
return useConnector(connectSearchBox_default, props, additionalWidgetProperties);
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useSearchResults.js
init_compat_module();
function _slicedToArray$1(arr, i$3) {
return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i$3) || _unsupportedIterableToArray$1(arr, i$3) || _nonIterableRest$1();
}
function _nonIterableRest$1() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$1(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray$1(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray$1(o$3, minLen);
}
function _arrayLikeToArray$1(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
function _iterableToArrayLimit$1(r$2, l$2) {
var t$2 = null == r$2 ? null : "undefined" != typeof Symbol && r$2[Symbol.iterator] || r$2["@@iterator"];
if (null != t$2) {
var e$2, n$1, i$3, u$3, a$2 = [], f$3 = !0, o$3 = !1;
try {
if (i$3 = (t$2 = t$2.call(r$2)).next, 0 === l$2) {
if (Object(t$2) !== t$2) return;
f$3 = !1;
} else for (; !(f$3 = (e$2 = i$3.call(t$2)).done) && (a$2.push(e$2.value), a$2.length !== l$2); f$3 = !0);
} catch (r$3) {
o$3 = !0, n$1 = r$3;
} finally {
try {
if (!f$3 && null != t$2.return && (u$3 = t$2.return(), Object(u$3) !== u$3)) return;
} finally {
if (o$3) throw n$1;
}
}
return a$2;
}
}
function _arrayWithHoles$1(arr) {
if (Array.isArray(arr)) return arr;
}
function useSearchResults() {
var search = useInstantSearchContext();
var searchIndex = useIndexContext();
var _useState = d(function() {
var indexSearchResults = getIndexSearchResults(searchIndex);
return {
results: indexSearchResults.results,
scopedResults: indexSearchResults.scopedResults
};
}), _useState2 = _slicedToArray$1(_useState, 2), searchResults = _useState2[0], setSearchResults = _useState2[1];
y(function() {
function handleRender() {
var results = searchIndex.getResults();
if (results !== null) setSearchResults({
results,
scopedResults: searchIndex.getScopedResults()
});
else if (search.mainIndex.getIndexName().length === 0) {
var childIndex = search.mainIndex.getWidgets().find(isIndexWidget);
childIndex && setSearchResults({
results: getIndexSearchResults(searchIndex).results,
scopedResults: childIndex.getScopedResults()
});
}
}
search.addListener("render", handleRender);
handleRender();
return function() {
search.removeListener("render", handleRender);
};
}, [search, searchIndex]);
return searchResults;
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/lib/useSearchState.js
init_compat_module();
function _slicedToArray(arr, i$3) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i$3) || _unsupportedIterableToArray(arr, i$3) || _nonIterableRest();
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(o$3, minLen) {
if (!o$3) return;
if (typeof o$3 === "string") return _arrayLikeToArray(o$3, minLen);
var n$1 = Object.prototype.toString.call(o$3).slice(8, -1);
if (n$1 === "Object" && o$3.constructor) n$1 = o$3.constructor.name;
if (n$1 === "Map" || n$1 === "Set") return Array.from(o$3);
if (n$1 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n$1)) return _arrayLikeToArray(o$3, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i$3 = 0, arr2 = new Array(len); i$3 < len; i$3++) arr2[i$3] = arr[i$3];
return arr2;
}
function _iterableToArrayLimit(r$2, l$2) {
var t$2 = null == r$2 ? null : "undefined" != typeof Symbol && r$2[Symbol.iterator] || r$2["@@iterator"];
if (null != t$2) {
var e$2, n$1, i$3, u$3, a$2 = [], f$3 = !0, o$3 = !1;
try {
if (i$3 = (t$2 = t$2.call(r$2)).next, 0 === l$2) {
if (Object(t$2) !== t$2) return;
f$3 = !1;
} else for (; !(f$3 = (e$2 = i$3.call(t$2)).done) && (a$2.push(e$2.value), a$2.length !== l$2); f$3 = !0);
} catch (r$3) {
o$3 = !0, n$1 = r$3;
} finally {
try {
if (!f$3 && null != t$2.return && (u$3 = t$2.return(), Object(u$3) !== u$3)) return;
} finally {
if (o$3) throw n$1;
}
}
return a$2;
}
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function useSearchState$1() {
var search = useInstantSearchContext();
var searchIndex = useIndexContext();
var indexId = searchIndex.getIndexId();
var _useState = d(function() {
return search.getUiState();
}), _useState2 = _slicedToArray(_useState, 2), uiState = _useState2[0], setLocalUiState = _useState2[1];
var indexUiState = uiState[indexId];
var _useState3 = d(function() {
return search.renderState;
}), _useState4 = _slicedToArray(_useState3, 2), renderState = _useState4[0], setRenderState = _useState4[1];
var indexRenderState = renderState[indexId] || {};
var setUiState = q(function(nextUiState) {
search.setUiState(nextUiState);
}, [search]);
var setIndexUiState = q(function(nextIndexUiState) {
searchIndex.setIndexUiState(nextIndexUiState);
}, [searchIndex]);
y(function() {
function handleRender() {
setLocalUiState(search.getUiState());
setRenderState(search.renderState);
}
search.addListener("render", handleRender);
handleRender();
return function() {
search.removeListener("render", handleRender);
};
}, [search]);
return {
uiState,
setUiState,
indexUiState,
setIndexUiState,
renderState,
indexRenderState
};
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch-core@7.16.3+54ac7d07948769ad/node_modules/react-instantsearch-core/dist/es/hooks/useInstantSearch.js
init_compat_module();
function useInstantSearch() {
var _ref = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, catchError = _ref.catchError;
var search = useInstantSearchContext();
var _useSearchState = useSearchState$1(), uiState = _useSearchState.uiState, setUiState = _useSearchState.setUiState, indexUiState = _useSearchState.indexUiState, setIndexUiState = _useSearchState.setIndexUiState, renderState = _useSearchState.renderState, indexRenderState = _useSearchState.indexRenderState;
var _useSearchResults = useSearchResults(), results = _useSearchResults.results, scopedResults = _useSearchResults.scopedResults;
var addMiddlewares = q(function() {
for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) middlewares[_key] = arguments[_key];
search.use.apply(search, middlewares);
return function() {
search.unuse.apply(search, middlewares);
};
}, [search]);
var refresh = q(function() {
search.refresh();
}, [search]);
useIsomorphicLayoutEffect(function() {
if (catchError) {
var onError = function onError$1() {};
search.addListener("error", onError);
return function() {
return search.removeListener("error", onError);
};
}
return function() {};
}, [search, catchError]);
return {
results,
scopedResults,
uiState,
setUiState,
indexUiState,
setIndexUiState,
renderState,
indexRenderState,
addMiddlewares,
refresh,
status: search.status,
error: search.error
};
}
//#endregion
//#region ../../node_modules/.bun/@babel+runtime@7.28.4/node_modules/@babel/runtime/helpers/esm/extends.js
function _extends$2() {
return _extends$2 = Object.assign ? Object.assign.bind() : function(n$1) {
for (var e$2 = 1; e$2 < arguments.length; e$2++) {
var t$2 = arguments[e$2];
for (var r$2 in t$2) ({}).hasOwnProperty.call(t$2, r$2) && (n$1[r$2] = t$2[r$2]);
}
return n$1;
}, _extends$2.apply(null, arguments);
}
//#endregion
//#region ../../node_modules/.bun/@babel+runtime@7.28.4/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
function _objectWithoutPropertiesLoose$2(r$2, e$2) {
if (null == r$2) return {};
var t$2 = {};
for (var n$1 in r$2) if ({}.hasOwnProperty.call(r$2, n$1)) {
if (-1 !== e$2.indexOf(n$1)) continue;
t$2[n$1] = r$2[n$1];
}
return t$2;
}
//#endregion
//#region ../../node_modules/.bun/@babel+runtime@7.28.4/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
function _objectWithoutProperties$2(e$2, t$2) {
if (null == e$2) return {};
var o$3, r$2, i$3 = _objectWithoutPropertiesLoose$2(e$2, t$2);
if (Object.getOwnPropertySymbols) {
var n$1 = Object.getOwnPropertySymbols(e$2);
for (r$2 = 0; r$2 < n$1.length; r$2++) o$3 = n$1[r$2], -1 === t$2.indexOf(o$3) && {}.propertyIsEnumerable.call(e$2, o$3) && (i$3[o$3] = e$2[o$3]);
}
return i$3;
}
//#endregion
//#region ../../node_modules/.bun/instantsearch-ui-components@0.11.2/node_modules/instantsearch-ui-components/dist/es/lib/cx.js
function cx() {
for (var _len = arguments.length, classNames = new Array(_len), _key = 0; _key < _len; _key++) classNames[_key] = arguments[_key];
return classNames.reduce(function(acc, className) {
if (Array.isArray(className)) return acc.concat(className);
return acc.concat([className]);
}, []).filter(Boolean).join(" ");
}
//#endregion
//#region ../../node_modules/.bun/instantsearch-ui-components@0.11.2/node_modules/instantsearch-ui-components/dist/es/components/Highlight.js
var _excluded$2 = [
"parts",
"highlightedTagName",
"nonHighlightedTagName",
"separator",
"className",
"classNames"
];
function createHighlightPartComponent(_ref) {
var createElement = _ref.createElement;
return function HighlightPart(_ref2) {
var classNames = _ref2.classNames, children = _ref2.children, highlightedTagName = _ref2.highlightedTagName, isHighlighted = _ref2.isHighlighted, nonHighlightedTagName = _ref2.nonHighlightedTagName;
var TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName;
return createElement(TagName, { className: isHighlighted ? classNames.highlighted : classNames.nonHighlighted }, children);
};
}
function createHighlightComponent(_ref3) {
var createElement = _ref3.createElement, Fragment = _ref3.Fragment;
var HighlightPart = createHighlightPartComponent({
createElement,
Fragment
});
return function Highlight$2(userProps) {
var parts = userProps.parts, _userProps$highlighte = userProps.highlightedTagName, highlightedTagName = _userProps$highlighte === void 0 ? "mark" : _userProps$highlighte, _userProps$nonHighlig = userProps.nonHighlightedTagName, nonHighlightedTagName = _userProps$nonHighlig === void 0 ? "span" : _userProps$nonHighlig, _userProps$separator = userProps.separator, separator = _userProps$separator === void 0 ? ", " : _userProps$separator, className = userProps.className, _userProps$classNames = userProps.classNames, classNames = _userProps$classNames === void 0 ? {} : _userProps$classNames, props = _objectWithoutProperties$2(userProps, _excluded$2);
return createElement("span", _extends$2({}, props, { className: cx(classNames.root, className) }), parts.map(function(part, partIndex) {
var isLastPart = partIndex === parts.length - 1;
return createElement(Fragment, { key: partIndex }, part.map(function(subPart, subPartIndex) {
return createElement(HighlightPart, {
key: subPartIndex,
classNames,
highlightedTagName,
nonHighlightedTagName,
isHighlighted: subPart.isHighlighted
}, subPart.value);
}), !isLastPart && createElement("span", { className: classNames.separator }, separator));
}));
};
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch@7.16.3+630f27d9614c5721/node_modules/react-instantsearch/dist/es/ui/InternalHighlight.js
init_compat_module();
var InternalHighlight = createHighlightComponent({
createElement: _$2,
Fragment: k$1
});
//#endregion
//#region ../../node_modules/.bun/react-instantsearch@7.16.3+630f27d9614c5721/node_modules/react-instantsearch/dist/es/ui/Highlight.js
init_compat_module();
var _excluded$1 = ["classNames"];
function _extends$1() {
_extends$1 = Object.assign ? Object.assign.bind() : function(target) {
for (var i$3 = 1; i$3 < arguments.length; i$3++) {
var source = arguments[i$3];
for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
}
return target;
};
return _extends$1.apply(this, arguments);
}
function _objectWithoutProperties$1(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose$1(source, excluded);
var key, i$3;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i$3 = 0; i$3 < sourceSymbolKeys.length; i$3++) {
key = sourceSymbolKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i$3;
for (i$3 = 0; i$3 < sourceKeys.length; i$3++) {
key = sourceKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function Highlight$1(_ref) {
var _ref$classNames = _ref.classNames, classNames = _ref$classNames === void 0 ? {} : _ref$classNames, props = _objectWithoutProperties$1(_ref, _excluded$1);
return /* @__PURE__ */ Rn.createElement(InternalHighlight, _extends$1({ classNames: {
root: cx("ais-Highlight", classNames.root),
highlighted: cx("ais-Highlight-highlighted", classNames.highlighted),
nonHighlighted: cx("ais-Highlight-nonHighlighted", classNames.nonHighlighted),
separator: cx("ais-Highlight-separator", classNames.separator)
} }, props));
}
//#endregion
//#region ../../node_modules/.bun/react-instantsearch@7.16.3+630f27d9614c5721/node_modules/react-instantsearch/dist/es/widgets/Highlight.js
init_compat_module();
var _excluded = [
"hit",
"attribute",
"highlightedTagName",
"nonHighlightedTagName",
"separator"
];
function _extends() {
_extends = Object.assign ? Object.assign.bind() : function(target) {
for (var i$3 = 1; i$3 < arguments.length; i$3++) {
var source = arguments[i$3];
for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i$3;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i$3 = 0; i$3 < sourceSymbolKeys.length; i$3++) {
key = sourceSymbolKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i$3;
for (i$3 = 0; i$3 < sourceKeys.length; i$3++) {
key = sourceKeys[i$3];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function Highlight(_ref) {
var hit = _ref.hit, attribute = _ref.attribute, highlightedTagName = _ref.highlightedTagName, nonHighlightedTagName = _ref.nonHighlightedTagName, separator = _ref.separator, props = _objectWithoutProperties(_ref, _excluded);
var property = getPropertyByPath(hit._highlightResult, attribute) || [];
var properties = Array.isArray(property) ? property : [property];
var parts = properties.map(function(singleValue) {
return getHighlightedParts(unescape$1(singleValue.value || ""));
});
return /* @__PURE__ */ Rn.createElement(Highlight$1, _extends({}, props, {
parts,
highlightedTagName,
nonHighlightedTagName,
separator
}));
}
//#endregion
//#region src/components/types.ts
function toAttributePath(attribute) {
if (!attribute) return void 0;
return attribute.includes(".") ? attribute.split(".") : attribute;
}
/** Safely read a nested value from an object using a dotted path */
function getByPath(obj, path) {
if (!obj || !path) return void 0;
const parts = path.split(".");
let current = obj;
for (const part of parts) {
if (current == null || typeof current !== "object") return void 0;
const record$1 = current;
current = record$1[part];
}
return current;
}
//#endregion
//#region ../../node_modules/.bun/preact@10.27.2/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js
init_preact_module();
var o = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, f = 0, i = Array.isArray;
function u(e$2, t$2, n$1, o$3, i$3, u$3) {
t$2 || (t$2 = {});
var a$2, c$2, p$2 = t$2;
if ("ref" in p$2) for (c$2 in p$2 = {}, t$2) "ref" == c$2 ? a$2 = t$2[c$2] : p$2[c$2] = t$2[c$2];
var l$2 = {
type: e$2,
props: p$2,
key: n$1,
ref: a$2,
__k: null,
__: null,
__b: 0,
__e: null,
__c: null,
constructor: void 0,
__v: --f,
__i: -1,
__u: 0,
__source: i$3,
__self: u$3
};
if ("function" == typeof e$2 && (a$2 = e$2.defaultProps)) for (c$2 in a$2) void 0 === p$2[c$2] && (p$2[c$2] = a$2[c$2]);
return l.vnode && l.vnode(l$2), l$2;
}
//#endregion
//#region src/components/search/icons.tsx
const SearchIcon$1 = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
fill: color,
width: size,
height: size,
children: [/* @__PURE__ */ u("circle", {
cx: "11",
cy: "11",
r: "8",
stroke: color,
fill: "none",
strokeWidth: "1.4"
}), /* @__PURE__ */ u("path", {
d: "m21 21-4.3-4.3",
stroke: color,
fill: "none",
strokeLinecap: "round",
strokeLinejoin: "round"
})]
});
const CloseIcon$1 = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [
" ",
/* @__PURE__ */ u("path", { d: "M18 6 6 18" }),
/* @__PURE__ */ u("path", { d: "m6 6 12 12" })
]
});
const AlgoliaLogo$1 = ({ size = 150 }) => /* @__PURE__ */ u("svg", {
width: "80",
height: "24",
"aria-label": "Algolia",
role: "img",
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 2196.2 500",
style: { maxWidth: size },
children: [
/* @__PURE__ */ u("defs", { children: /* @__PURE__ */ u("style", { children: `.cls-1,.cls-2{fill:#003dff}.cls-2{fillRule:evenodd}` }) }),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1070.38,275.3V5.91c0-3.63-3.24-6.39-6.82-5.83l-50.46,7.94c-2.87,.45-4.99,2.93-4.99,5.84l.17,273.22c0,12.92,0,92.7,95.97,95.49,3.33,.1,6.09-2.58,6.09-5.91v-40.78c0-2.96-2.19-5.51-5.12-5.84-34.85-4.01-34.85-47.57-34.85-54.72Z"
}),
/* @__PURE__ */ u("rect", {
className: "cls-1",
x: "1845.88",
y: "104.73",
width: "62.58",
height: "277.9",
rx: "5.9",
ry: "5.9"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1851.78,71.38h50.77c3.26,0,5.9-2.64,5.9-5.9V5.9c0-3.62-3.24-6.39-6.82-5.83l-50.77,7.95c-2.87,.45-4.99,2.92-4.99,5.83v51.62c0,3.26,2.64,5.9,5.9,5.9Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1764.03,275.3V5.91c0-3.63-3.24-6.39-6.82-5.83l-50.46,7.94c-2.87,.45-4.99,2.93-4.99,5.84l.17,273.22c0,12.92,0,92.7,95.97,95.49,3.33,.1,6.09-2.58,6.09-5.91v-40.78c0-2.96-2.19-5.51-5.12-5.84-34.85-4.01-34.85-47.57-34.85-54.72Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1631.95,142.72c-11.14-12.25-24.83-21.65-40.78-28.31-15.92-6.53-33.26-9.85-52.07-9.85-18.78,0-36.15,3.17-51.92,9.85-15.59,6.66-29.29,16.05-40.76,28.31-11.47,12.23-20.38,26.87-26.76,44.03-6.38,17.17-9.24,37.37-9.24,58.36,0,20.99,3.19,36.87,9.55,54.21,6.38,17.32,15.14,32.11,26.45,44.36,11.29,12.23,24.83,21.62,40.6,28.46,15.77,6.83,40.12,10.33,52.4,10.48,12.25,0,36.78-3.82,52.7-10.48,15.92-6.68,29.46-16.23,40.78-28.46,11.29-12.25,20.05-27.04,26.25-44.36,6.22-17.34,9.24-33.22,9.24-54.21,0-20.99-3.34-41.19-10.03-58.36-6.38-17.17-15.14-31.8-26.43-44.03Zm-44.43,163.75c-11.47,15.75-27.56,23.7-48.09,23.7-20.55,0-36.63-7.8-48.1-23.7-11.47-15.75-17.21-34.01-17.21-61.2,0-26.89,5.59-49.14,17.06-64.87,11.45-15.75,27.54-23.52,48.07-23.52,20.55,0,36.63,7.78,48.09,23.52,11.47,15.57,17.36,37.98,17.36,64.87,0,27.19-5.72,45.3-17.19,61.2Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M894.42,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-14.52,22.58-22.99,49.63-22.99,78.73,0,44.89,20.13,84.92,51.59,111.1,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47,1.23,0,2.46-.03,3.68-.09,.36-.02,.71-.05,1.07-.07,.87-.05,1.75-.11,2.62-.2,.34-.03,.68-.08,1.02-.12,.91-.1,1.82-.21,2.73-.34,.21-.03,.42-.07,.63-.1,32.89-5.07,61.56-30.82,70.9-62.81v57.83c0,3.26,2.64,5.9,5.9,5.9h50.42c3.26,0,5.9-2.64,5.9-5.9V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,206.92c-12.2,10.16-27.97,13.98-44.84,15.12-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-42.24,0-77.12-35.89-77.12-79.37,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33v142.83Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M2133.97,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-14.52,22.58-22.99,49.63-22.99,78.73,0,44.89,20.13,84.92,51.59,111.1,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47,1.23,0,2.46-.03,3.68-.09,.36-.02,.71-.05,1.07-.07,.87-.05,1.75-.11,2.62-.2,.34-.03,.68-.08,1.02-.12,.91-.1,1.82-.21,2.73-.34,.21-.03,.42-.07,.63-.1,32.89-5.07,61.56-30.82,70.9-62.81v57.83c0,3.26,2.64,5.9,5.9,5.9h50.42c3.26,0,5.9-2.64,5.9-5.9V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,206.92c-12.2,10.16-27.97,13.98-44.84,15.12-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-42.24,0-77.12-35.89-77.12-79.37,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33v142.83Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1314.05,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-11.79,18.34-19.6,39.64-22.11,62.59-.58,5.3-.88,10.68-.88,16.14s.31,11.15,.93,16.59c4.28,38.09,23.14,71.61,50.66,94.52,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47h0c17.99,0,34.61-5.93,48.16-15.97,16.29-11.58,28.88-28.54,34.48-47.75v50.26h-.11v11.08c0,21.84-5.71,38.27-17.34,49.36-11.61,11.08-31.04,16.63-58.25,16.63-11.12,0-28.79-.59-46.6-2.41-2.83-.29-5.46,1.5-6.27,4.22l-12.78,43.11c-1.02,3.46,1.27,7.02,4.83,7.53,21.52,3.08,42.52,4.68,54.65,4.68,48.91,0,85.16-10.75,108.89-32.21,21.48-19.41,33.15-48.89,35.2-88.52V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,64.1s.65,139.13,0,143.36c-12.08,9.77-27.11,13.59-43.49,14.7-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-1.32,0-2.63-.03-3.94-.1-40.41-2.11-74.52-37.26-74.52-79.38,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-1",
d: "M249.83,0C113.3,0,2,110.09,.03,246.16c-2,138.19,110.12,252.7,248.33,253.5,42.68,.25,83.79-10.19,120.3-30.03,3.56-1.93,4.11-6.83,1.08-9.51l-23.38-20.72c-4.75-4.21-11.51-5.4-17.36-2.92-25.48,10.84-53.17,16.38-81.71,16.03-111.68-1.37-201.91-94.29-200.13-205.96,1.76-110.26,92-199.41,202.67-199.41h202.69V407.41l-115-102.18c-3.72-3.31-9.42-2.66-12.42,1.31-18.46,24.44-48.53,39.64-81.93,37.34-46.33-3.2-83.87-40.5-87.34-86.81-4.15-55.24,39.63-101.52,94-101.52,49.18,0,89.68,37.85,93.91,85.95,.38,4.28,2.31,8.27,5.52,11.12l29.95,26.55c3.4,3.01,8.79,1.17,9.63-3.3,2.16-11.55,2.92-23.58,2.07-35.92-4.82-70.34-61.8-126.93-132.17-131.26-80.68-4.97-148.13,58.14-150.27,137.25-2.09,77.1,61.08,143.56,138.19,145.26,32.19,.71,62.03-9.41,86.14-26.95l150.26,133.2c6.44,5.71,16.61,1.14,16.61-7.47V9.48C499.66,4.25,495.42,0,490.18,0H249.83Z"
})
]
});
//#endregion
//#region src/components/search/hits-list.tsx
init_compat_module();
const HitsList$1 = M(function HitsList$2({ hits, selectedIndex, attributes, onHoverIndex, hoverEnabled, sendEvent, openResultsInNewTab = true }) {
const [failedImages, setFailedImages] = d({});
const mapping = T(() => ({
primaryText: attributes?.primaryText,
secondaryText: attributes?.secondaryText,
tertiaryText: attributes?.tertiaryText,
url: attributes?.url,
image: attributes?.image
}), [attributes]);
if (!attributes || !mapping.primaryText) throw new Error("At least a primaryText is required to display results");
return /* @__PURE__ */ u(k$1, { children: hits.map((hit, idx) => {
const isSel = selectedIndex === idx;
const imageUrl = getByPath(hit, mapping.image);
const primaryVal = getByPath(hit, mapping.primaryText);
const url = getByPath(hit, mapping.url);
const hasImage = Boolean(imageUrl);
const isImageFailed = failedImages[hit.objectID] || !hasImage;
return /* @__PURE__ */ u("a", {
href: url ?? "#",
target: openResultsInNewTab && url ? "_blank" : void 0,
rel: openResultsInNewTab && url ? "noopener noreferrer" : void 0,
className: "ss-infinite-hits-item ss-infinite-hits-anchor",
role: "option",
"aria-selected": isSel,
onClick: () => {
sendEvent?.("click", hit, "Hit Clicked");
},
onMouseEnter: () => {
if (!hoverEnabled) return;
onHoverIndex?.(idx);
},
onMouseMove: () => {
if (!hoverEnabled) return;
onHoverIndex?.(idx);
},
children: [imageUrl ? /* @__PURE__ */ u("div", {
className: "ss-infinite-hits-item-image-container",
children: !isImageFailed ? /* @__PURE__ */ u("img", {
src: imageUrl,
alt: primaryVal || "",
className: "ss-infinite-hits-item-image",
onError: () => setFailedImages((prev) => ({
...prev,
[hit.objectID]: true
}))
}) : /* @__PURE__ */ u("div", {
className: "ss-infinite-hits-item-placeholder",
"aria-hidden": "true",
children: /* @__PURE__ */ u(SearchIcon$1, {})
})
}) : null, /* @__PURE__ */ u("div", {
className: "ss-infinite-hits-item-content",
children: [
/* @__PURE__ */ u("p", {
className: "ss-infinite-hits-item-title",
children: /* @__PURE__ */ u(Highlight, {
attribute: toAttributePath(mapping.primaryText),
hit
})
}),
mapping.secondaryText ? /* @__PURE__ */ u("p", {
className: "ss-infinite-hits-item-description",
children: /* @__PURE__ */ u(Highlight, {
attribute: toAttributePath(mapping.secondaryText),
hit
})
}) : null,
mapping.tertiaryText ? /* @__PURE__ */ u("p", {
className: "ss-infinite-hits-item-tertiary",
children: /* @__PURE__ */ u(Highlight, {
attribute: toAttributePath(mapping.tertiaryText),
hit
})
}) : null
]
})]
}, hit.objectID);
}) });
});
//#endregion
//#region src/components/search/search-input.tsx
init_compat_module();
const SearchInput$1 = M(function SearchInput$2(props) {
const { status } = useInstantSearch();
const { query, refine: refine$1 } = useSearchBox();
const isSearchStalled = status === "stalled";
function setQuery(newQuery) {
refine$1(newQuery);
}
const placeholder = props.placeholder;
return /* @__PURE__ */ u("search", {
className: props.className,
onSubmit: (event) => {
event.preventDefault();
event.stopPropagation();
},
onReset: (event) => {
event.preventDefault();
event.stopPropagation();
setQuery("");
if (props.inputRef.current) props.inputRef.current.focus();
},
children: [
/* @__PURE__ */ u("div", {
role: "button",
tabIndex: -1,
className: "ss-search-left-button",
"aria-label": "Search",
title: "Search",
children: /* @__PURE__ */ u(SearchIcon$1, {})
}),
/* @__PURE__ */ u("input", {
ref: props.inputRef,
autoComplete: "off",
autoCorrect: "off",
autoCapitalize: "off",
placeholder,
spellCheck: false,
maxLength: 512,
type: "search",
value: query || "",
onChange: (event) => {
setQuery(event.currentTarget.value);
},
onKeyDown: (e$2) => {
if (e$2.key === "ArrowDown") {
e$2.preventDefault();
props.onArrowDown?.();
return;
}
if (e$2.key === "ArrowUp") {
e$2.preventDefault();
props.onArrowUp?.();
return;
}
if (e$2.key === "Enter") {
e$2.preventDefault();
props.onEnter?.();
}
}
}),
/* @__PURE__ */ u("div", {
className: "ss-search-action-buttons-container",
children: [/* @__PURE__ */ u("button", {
type: "reset",
className: "ss-search-clear-button",
hidden: !query || query.length === 0 || isSearchStalled,
onClick: () => {
setQuery("");
if (props.inputRef.current) props.inputRef.current.focus();
},
children: "Clear"
}), /* @__PURE__ */ u("button", {
type: "button",
className: "ss-search-close-button",
onClick: props.onClose,
children: /* @__PURE__ */ u(CloseIcon$1, {})
})]
})
]
});
});
//#endregion
//#region src/components/search/useKeyboardNavigation.ts
init_compat_module();
function useKeyboardNavigation$1(hits, query, openResultsInNewTab = true) {
const [selectedIndex, setSelectedIndex] = d(0);
const [selectionOrigin, setSelectionOrigin] = d("init");
const totalItems = T(() => hits.length, [hits.length]);
const moveDown = q(() => {
setSelectedIndex((prev) => (prev + 1) % totalItems);
setSelectionOrigin("keyboard");
}, [totalItems]);
const moveUp = q(() => {
setSelectedIndex((prev) => (prev - 1 + totalItems) % totalItems);
setSelectionOrigin("keyboard");
}, [totalItems]);
const hoverIndex = q((index$1) => {
if (index$1 < 0 || index$1 >= totalItems) return;
setSelectedIndex(index$1);
setSelectionOrigin("pointer");
}, [totalItems]);
const activateSelection = q(() => {
const hit = hits[selectedIndex];
const url = typeof hit?.url === "string" ? hit.url : void 0;
if (url) {
if (openResultsInNewTab) window.open(url, "_blank", "noopener,noreferrer");
else window.location.assign(url);
return true;
}
return false;
}, [
selectedIndex,
hits,
openResultsInNewTab
]);
y(() => {
setSelectedIndex(0);
setSelectionOrigin("init");
}, [query]);
return {
selectedIndex,
moveDown,
moveUp,
activateSelection,
hoverIndex,
selectionOrigin
};
}
//#endregion
//#region src/components/search/search-button.tsx
init_compat_module();
const SearchButton$1 = ({ onClick, darkMode }) => {
const [modifierLabel, setModifierLabel] = d("⌘");
const [isModifierPressed, setIsModifierPressed] = d(false);
const [isKPressed, setIsKPressed] = d(false);
y(() => {
if (typeof navigator === "undefined") return;
const isMac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
setModifierLabel(isMac ? "⌘" : "Ctrl");
}, []);
y(() => {
const handleKeyDown = (event) => {
if (event.metaKey || event.ctrlKey) setIsModifierPressed(true);
if (event.key.toLowerCase() === "k") setIsKPressed(true);
};
const handleKeyUp = (event) => {
if (!event.metaKey && !event.ctrlKey) setIsModifierPressed(false);
if (event.key.toLowerCase() === "k") setIsKPressed(false);
};
const resetKeys = () => {
setIsModifierPressed(false);
setIsKPressed(false);
};
document.addEventListener("keydown", handleKeyDown);
document.addEventListener("keyup", handleKeyUp);
window.addEventListener("blur", resetKeys);
return () => {
document.removeEventListener("keydown", handleKeyDown);
document.removeEventListener("keyup", handleKeyUp);
window.removeEventListener("blur", resetKeys);
};
}, []);
return /* @__PURE__ */ u("button", {
className: `sitesearch-button${darkMode ? " dark" : ""}`,
type: "button",
onClick,
"aria-label": "Open search",
children: [
/* @__PURE__ */ u("span", {
className: "search-icon",
children: /* @__PURE__ */ u(SearchIcon$1, {})
}),
/* @__PURE__ */ u("span", {
className: "button-text",
children: "Search"
}),
/* @__PURE__ */ u("span", {
className: "keyboard-shortcut",
children: [/* @__PURE__ */ u("kbd", {
className: isModifierPressed ? "pressed" : "",
children: modifierLabel
}), /* @__PURE__ */ u("kbd", {
className: isKPressed ? "pressed" : "",
children: "K"
})]
})
]
});
};
//#endregion
//#region src/components/search/search-modal.tsx
init_compat_module();
const Modal$1 = ({ isOpen, onClose, children, isDark }) => {
y(() => {
const handleEscape = (event) => {
if (event.key === "Escape") onClose();
};
if (isOpen) {
document.addEventListener("keydown", handleEscape);
document.body.style.overflow = "hidden";
}
return () => {
document.removeEventListener("keydown", handleEscape);
document.body.style.overflow = "unset";
};
}, [isOpen, onClose]);
if (!isOpen) return null;
return $(/* @__PURE__ */ u("div", {
className: `modal-backdrop${isDark ? " dark" : ""}`,
onClick: onClose,
children: /* @__PURE__ */ u("div", {
className: `modal-content ss-exp${isDark ? " dark" : ""}`,
onClick: (e$2) => e$2.stopPropagation(),
children
})
}), document.body);
};
//#endregion
//#region src/components/search/useEffectiveDarkMode.ts
init_compat_module();
/**
* Computes effective dark mode with precedence:
* 1) explicit prop if provided
* 2) html element has class "dark"
* 3) prefers-color-scheme: dark
*/
function useEffectiveDarkMode$1(explicitDark) {
const initial = T(() => {
if (explicitDark !== void 0) return explicitDark;
if (typeof document !== "undefined") {
if (document.documentElement.classList.contains("dark")) return true;
}
if (typeof window !== "undefined" && typeof window.matchMedia === "function") return window.matchMedia("(prefers-color-scheme: dark)").matches;
return false;
}, [explicitDark]);
const [isDark, setIsDark] = d(initial);
y(() => {
if (explicitDark !== void 0) {
setIsDark(explicitDark);
return;
}
let disposed = false;
const recompute = () => {
if (disposed) return;
const htmlHasDark = document.documentElement.classList.contains("dark");
if (htmlHasDark) {
setIsDark(true);
return;
}
const prefers = window.matchMedia("(prefers-color-scheme: dark)").matches;
setIsDark(prefers);
};
const mo = new MutationObserver(() => recompute());
mo.observe(document.documentElement, {
attributes: true,
attributeFilter: ["class"]
});
const mql = window.matchMedia("(prefers-color-scheme: dark)");
const onChange = () => recompute();
if (typeof mql.addEventListener === "function") mql.addEventListener("change", onChange);
else if (typeof mql.addListener === "function") mql.addEventListener("change", onChange);
recompute();
return () => {
disposed = true;
mo.disconnect();
if (typeof mql.removeEventListener === "function") mql.removeEventListener("change", onChange);
else if (typeof mql.removeListener === "function") mql.removeEventListener("change", onChange);
};
}, [explicitDark]);
return isDark;
}
var useEffectiveDarkMode_default$1 = useEffectiveDarkMode$1;
//#endregion
//#region src/components/search/index.tsx
init_compat_module();
const SearchBox$1 = M(function SearchBox$2(props) {
return /* @__PURE__ */ u(SearchInput$1, {
className: props.className,
placeholder: props.placeholder,
inputRef: props.inputRef,
onClose: props.onClose || (() => {}),
onEnter: props.onEnter,
onArrowDown: props.onArrowDown,
onArrowUp: props.onArrowUp
});
});
const NoResults$1 = M(function NoResults$2({ query, onClear }) {
return /* @__PURE__ */ u("div", {
className: "ss-no-results",
children: [
/* @__PURE__ */ u("div", {
className: "ss-no-results-icon",
children: /* @__PURE__ */ u(SearchIcon$1, {})
}),
/* @__PURE__ */ u("p", {
className: "ss-no-results-title",
children: [
"No results for \"",
query,
"\""
]
}),
/* @__PURE__ */ u("p", {
className: "ss-no-results-subtitle",
children: "Try a different query"
}),
/* @__PURE__ */ u("div", {
className: "ss-no-results-actions",
children: /* @__PURE__ */ u("button", {
type: "button",
className: "ss-no-results-btn",
onClick: onClear,
children: "Clear query"
})
})
]
});
});
const ResultsPanel$1 = M(function ResultsPanel$2({ query, selectedIndex, config: config$1, onHoverIndex, scrollOnSelectionChange = true, sendEvent, openResultsInNewTab = true }) {
const { items } = useHits(config$1.transformItems ? { transformItems: config$1.transformItems } : {});
const containerRef = A(null);
const [hoverEnabled, setHoverEnabled] = d(false);
y(() => {
const container = containerRef.current;
if (!container) return;
setHoverEnabled(false);
const enable = () => setHoverEnabled(true);
container.addEventListener("pointermove", enable, { once: true });
return () => {
container.removeEventListener("pointermove", enable);
};
}, []);
y(() => {
if (!scrollOnSelectionChange) return;
const container = containerRef.current;
if (!container) return;
const selectedEl = container.querySelector("[aria-selected=\"true\"]");
if (!selectedEl) return;
const padding = 8;
const cRect = container.getBoundingClientRect();
const iRect = selectedEl.getBoundingClientRect();
if (iRect.top < cRect.top + padding) container.scrollTop -= cRect.top + padding - iRect.top;
else if (iRect.bottom > cRect.bottom - padding) container.scrollTop += iRect.bottom - (cRect.bottom - padding);
}, [
selectedIndex,
items.length,
scrollOnSelectionChange
]);
return /* @__PURE__ */ u(k$1, { children: /* @__PURE__ */ u("div", {
ref: containerRef,
className: "ss-hits-container",
role: "listbox",
children: /* @__PURE__ */ u(HitsList$1, {
hits: items,
query,
selectedIndex,
attributes: config$1.attributes,
onHoverIndex,
hoverEnabled,
sendEvent,
openResultsInNewTab
})
}) });
});
function SearchModal$1({ onClose, config: config$1 }) {
const { query, refine: refine$1 } = useSearchBox();
const inputRef = A(null);
const results = useInstantSearch();
const { items, sendEvent } = useHits(config$1.transformItems ? { transformItems: config$1.transformItems } : {});
y(() => {
const rafId = requestAnimationFrame(() => {
if (inputRef.current) inputRef.current.focus();
});
return () => cancelAnimationFrame(rafId);
}, []);
const noResults = results.results?.nbHits === 0;
const { selectedIndex, moveDown, moveUp, activateSelection, hoverIndex, selectionOrigin } = useKeyboardNavigation$1(items, query, config$1.openResultsInNewTab ?? true);
const handleActivateSelection = q(() => {
if (selectedIndex >= 0 && selectedIndex < items.length) {
const hit = items[selectedIndex];
if (hit) sendEvent?.("click", hit, "Hit Clicked");
}
if (activateSelection()) return true;
return false;
}, [
activateSelection,
selectedIndex,
items,
sendEvent
]);
const showResultsPanel = !noResults && !!query;
return /* @__PURE__ */ u(k$1, { children: [
/* @__PURE__ */ u(Configure, {
hitsPerPage: config$1.hitsPerPage || 8,
...config$1.searchParameters || {}
}),
/* @__PURE__ */ u("div", {
className: "search-panel",
children: [
/* @__PURE__ */ u(SearchBox$1, {
query,
placeholder: config$1.placeholder || "What are you looking for?",
className: "ss-searchbox-form",
refine: refine$1,
onClose,
onArrowDown: moveDown,
onArrowUp: moveUp,
inputRef,
onEnter: handleActivateSelection
}),
showResultsPanel && /* @__PURE__ */ u(ResultsPanel$1, {
inputRef,
query,
selectedIndex,
refine: refine$1,
config: config$1,
onHoverIndex: hoverIndex,
scrollOnSelectionChange: selectionOrigin !== "pointer",
sendEvent,
openResultsInNewTab: config$1.openResultsInNewTab
}),
noResults && query && /* @__PURE__ */ u(NoResults$1, {
query,
onClear: () => {
refine$1("");
if (inputRef.current) inputRef.current.focus();
}
})
]
}),
/* @__PURE__ */ u(Footer$1, {})
] });
}
const Footer$1 = M(function Footer$2() {
const basePoweredByUrl$1 = "https://www.algolia.com/developers?utm_medium=referral&utm_content=powered_by&utm_campaign=sitesearch";
const poweredByHref = typeof window !== "undefined" ? `${basePoweredByUrl$1}&utm_source=${encodeURIComponent(window.location.hostname)}` : basePoweredByUrl$1;
return /* @__PURE__ */ u("div", {
className: "ss-footer",
children: [/* @__PURE__ */ u("div", {
className: "ss-footer-left",
children: [/* @__PURE__ */ u("div", {
className: "ss-footer-kbd-group",
children: [/* @__PURE__ */ u("kbd", {
className: "ss-kbd",
children: /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
children: /* @__PURE__ */ u("path", {
fill: "currentColor",
d: "m6.8 13l2.9 2.9q.275.275.275.7t-.275.7t-.7.275t-.7-.275l-4.6-4.6q-.15-.15-.213-.325T3.426 12t.063-.375t.212-.325l4.6-4.6q.275-.275.7-.275t.7.275t.275.7t-.275.7L6.8 11H19V8q0-.425.288-.712T20 7t.713.288T21 8v3q0 .825-.587 1.413T19 13z"
})
})
}), /* @__PURE__ */ u("span", { children: "Open" })]
}), /* @__PURE__ */ u("div", {
className: "ss-footer-kbd-group",
children: [
/* @__PURE__ */ u("kbd", {
className: "ss-kbd",
children: /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
children: /* @__PURE__ */ u("path", {
fill: "currentColor",
d: "m11 7.825l-4.9 4.9q-.3.3-.7.288t-.7-.313q-.275-.3-.288-.7t.288-.7l6.6-6.6q.15-.15.325-.212T12 4.425t.375.063t.325.212l6.6 6.6q.275.275.275.688t-.275.712q-.3.3-.712.3t-.713-.3L13 7.825V19q0 .425-.288.713T12 20t-.712-.288T11 19z"
})
})
}),
/* @__PURE__ */ u("kbd", {
className: "ss-kbd",
children: /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
children: /* @__PURE__ */ u("path", {
fill: "currentColor",
d: "M11 16.175V5q0-.425.288-.712T12 4t.713.288T13 5v11.175l4.9-4.9q.3-.3.7-.288t.7.313q.275.3.287.7t-.287.7l-6.6 6.6q-.15.15-.325.213t-.375.062t-.375-.062t-.325-.213l-6.6-6.6q-.275-.275-.275-.687T4.7 11.3q.3-.3.713-.3t.712.3z"
})
})
}),
/* @__PURE__ */ u("span", { children: "Navigate" })
]
})]
}), /* @__PURE__ */ u("div", {
className: "ss-footer-right",
children: /* @__PURE__ */ u("a", {
className: "ss-footer-powered-by",
href: poweredByHref,
target: "_blank",
rel: "noopener noreferrer",
children: [/* @__PURE__ */ u("span", { children: "Powered by " }), /* @__PURE__ */ u(AlgoliaLogo$1, {})]
})
})]
});
});
function SearchExperience(config$1) {
const searchClient = liteClient(config$1.applicationId, config$1.apiKey);
searchClient.addAlgoliaAgent("algolia-sitesearch");
const [isModalOpen, setIsModalOpen] = d(false);
const isDark = useEffectiveDarkMode_default$1(config$1.darkMode);
const openModal = () => setIsModalOpen(true);
const closeModal = () => setIsModalOpen(false);
y(() => {
const handleKeyDown = (event) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault();
setIsModalOpen(true);
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, []);
const buttonProps = {
...config$1.buttonProps,
onClick: openModal
};
return /* @__PURE__ */ u(k$1, { children: [/* @__PURE__ */ u(SearchButton$1, {
...buttonProps,
darkMode: isDark,
children: config$1.buttonText
}), /* @__PURE__ */ u(Modal$1, {
isOpen: isModalOpen,
onClose: closeModal,
isDark,
children: /* @__PURE__ */ u(InstantSearch, {
searchClient,
indexName: config$1.indexName,
future: { preserveSharedStateOnUnmount: true },
insights: config$1.insights || true,
children: /* @__PURE__ */ u(SearchModal$1, {
onClose: closeModal,
config: config$1
})
})
})] });
}
//#endregion
//#region ../../node_modules/.bun/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
var marker$1 = "vercel.ai.error";
var symbol$1 = Symbol.for(marker$1);
var _a$1;
var _AISDKError = class _AISDKError$1 extends Error {
/**
* Creates an AI SDK Error.
*
* @param {Object} params - The parameters for creating the error.
* @param {string} params.name - The name of the error.
* @param {string} params.message - The error message.
* @param {unknown} [params.cause] - The underlying cause of the error.
*/
constructor({ name: name14$1, message, cause }) {
super(message);
this[_a$1] = true;
this.name = name14$1;
this.cause = cause;
}
/**
* Checks if the given error is an AI SDK Error.
* @param {unknown} error - The error to check.
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
*/
static isInstance(error) {
return _AISDKError$1.hasMarker(error, marker$1);
}
static hasMarker(error, marker15$1) {
const markerSymbol = Symbol.for(marker15$1);
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
}
};
_a$1 = symbol$1;
var AISDKError = _AISDKError;
var name$1 = "AI_APICallError";
var marker2$1 = `vercel.ai.error.${name$1}`;
var symbol2$1 = Symbol.for(marker2$1);
var _a2$1;
_a2$1 = symbol2$1;
var name2$1 = "AI_EmptyResponseBodyError";
var marker3$1 = `vercel.ai.error.${name2$1}`;
var symbol3$1 = Symbol.for(marker3$1);
var _a3$1;
_a3$1 = symbol3$1;
function getErrorMessage(error) {
if (error == null) return "unknown error";
if (typeof error === "string") return error;
if (error instanceof Error) return error.message;
return JSON.stringify(error);
}
var name3$1 = "AI_InvalidArgumentError";
var marker4$1 = `vercel.ai.error.${name3$1}`;
var symbol4$1 = Symbol.for(marker4$1);
var _a4$1;
var InvalidArgumentError = class extends AISDKError {
constructor({ message, cause, argument }) {
super({
name: name3$1,
message,
cause
});
this[_a4$1] = true;
this.argument = argument;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker4$1);
}
};
_a4$1 = symbol4$1;
var name4$1 = "AI_InvalidPromptError";
var marker5$1 = `vercel.ai.error.${name4$1}`;
var symbol5$1 = Symbol.for(marker5$1);
var _a5$1;
_a5$1 = symbol5$1;
var name5$1 = "AI_InvalidResponseDataError";
var marker6$1 = `vercel.ai.error.${name5$1}`;
var symbol6$1 = Symbol.for(marker6$1);
var _a6$1;
_a6$1 = symbol6$1;
var name6$1 = "AI_JSONParseError";
var marker7$1 = `vercel.ai.error.${name6$1}`;
var symbol7$1 = Symbol.for(marker7$1);
var _a7$1;
var JSONParseError = class extends AISDKError {
constructor({ text: text$1, cause }) {
super({
name: name6$1,
message: `JSON parsing failed: Text: ${text$1}.
Error message: ${getErrorMessage(cause)}`,
cause
});
this[_a7$1] = true;
this.text = text$1;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker7$1);
}
};
_a7$1 = symbol7$1;
var name7$1 = "AI_LoadAPIKeyError";
var marker8$1 = `vercel.ai.error.${name7$1}`;
var symbol8$1 = Symbol.for(marker8$1);
var _a8$1;
_a8$1 = symbol8$1;
var name8$1 = "AI_LoadSettingError";
var marker9$1 = `vercel.ai.error.${name8$1}`;
var symbol9$1 = Symbol.for(marker9$1);
var _a9$1;
_a9$1 = symbol9$1;
var name9$1 = "AI_NoContentGeneratedError";
var marker10$1 = `vercel.ai.error.${name9$1}`;
var symbol10$1 = Symbol.for(marker10$1);
var _a10$1;
_a10$1 = symbol10$1;
var name10$1 = "AI_NoSuchModelError";
var marker11$1 = `vercel.ai.error.${name10$1}`;
var symbol11$1 = Symbol.for(marker11$1);
var _a11$1;
_a11$1 = symbol11$1;
var name11$1 = "AI_TooManyEmbeddingValuesForCallError";
var marker12$1 = `vercel.ai.error.${name11$1}`;
var symbol12$1 = Symbol.for(marker12$1);
var _a12$1;
_a12$1 = symbol12$1;
var name12$1 = "AI_TypeValidationError";
var marker13$1 = `vercel.ai.error.${name12$1}`;
var symbol13$1 = Symbol.for(marker13$1);
var _a13$1;
var _TypeValidationError = class _TypeValidationError$1 extends AISDKError {
constructor({ value, cause }) {
super({
name: name12$1,
message: `Type validation failed: Value: ${JSON.stringify(value)}.
Error message: ${getErrorMessage(cause)}`,
cause
});
this[_a13$1] = true;
this.value = value;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker13$1);
}
/**
* Wraps an error into a TypeValidationError.
* If the cause is already a TypeValidationError with the same value, it returns the cause.
* Otherwise, it creates a new TypeValidationError.
*
* @param {Object} params - The parameters for wrapping the error.
* @param {unknown} params.value - The value that failed validation.
* @param {unknown} params.cause - The original error or cause of the validation failure.
* @returns {TypeValidationError} A TypeValidationError instance.
*/
static wrap({ value, cause }) {
return _TypeValidationError$1.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError$1({
value,
cause
});
}
};
_a13$1 = symbol13$1;
var TypeValidationError = _TypeValidationError;
var name13$1 = "AI_UnsupportedFunctionalityError";
var marker14$1 = `vercel.ai.error.${name13$1}`;
var symbol14$1 = Symbol.for(marker14$1);
var _a14$1;
_a14$1 = symbol14$1;
//#endregion
//#region ../../node_modules/.bun/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
var ParseError = class extends Error {
constructor(message, options) {
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
}
};
function noop(_arg) {}
function createParser(callbacks) {
if (typeof callbacks == "function") throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
let incompleteLine = "", isFirstChunk = !0, id$1, data = "", eventType = "";
function feed(newChunk) {
const chunk$1 = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk$1}`);
for (const line of complete) parseLine(line);
incompleteLine = incomplete, isFirstChunk = !1;
}
function parseLine(line) {
if (line === "") {
dispatchEvent();
return;
}
if (line.startsWith(":")) {
onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
return;
}
const fieldSeparatorIndex = line.indexOf(":");
if (fieldSeparatorIndex !== -1) {
const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
processField(field, value, line);
return;
}
processField(line, "", line);
}
function processField(field, value, line) {
switch (field) {
case "event":
eventType = value;
break;
case "data":
data = `${data}${value}
`;
break;
case "id":
id$1 = value.includes("\0") ? void 0 : value;
break;
case "retry":
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
type: "invalid-retry",
value,
line
}));
break;
default:
onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
type: "unknown-field",
field,
value,
line
}));
break;
}
}
function dispatchEvent() {
data.length > 0 && onEvent({
id: id$1,
event: eventType || void 0,
data: data.endsWith(`
`) ? data.slice(0, -1) : data
}), id$1 = void 0, data = "", eventType = "";
}
function reset(options = {}) {
incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id$1 = void 0, data = "", eventType = "", incompleteLine = "";
}
return {
feed,
reset
};
}
function splitLines(chunk$1) {
const lines = [];
let incompleteLine = "", searchIndex = 0;
for (; searchIndex < chunk$1.length;) {
const crIndex = chunk$1.indexOf("\r", searchIndex), lfIndex = chunk$1.indexOf(`
`, searchIndex);
let lineEnd = -1;
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk$1.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
incompleteLine = chunk$1.slice(searchIndex);
break;
} else {
const line = chunk$1.slice(searchIndex, lineEnd);
lines.push(line), searchIndex = lineEnd + 1, chunk$1[searchIndex - 1] === "\r" && chunk$1[searchIndex] === `
` && searchIndex++;
}
}
return [lines, incompleteLine];
}
//#endregion
//#region ../../node_modules/.bun/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js
var EventSourceParserStream = class extends TransformStream {
constructor({ onError, onRetry, onComment } = {}) {
let parser;
super({
start(controller) {
parser = createParser({
onEvent: (event) => {
controller.enqueue(event);
},
onError(error) {
onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
},
onRetry,
onComment
});
},
transform(chunk$1) {
parser.feed(chunk$1);
}
});
}
};
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/core.js
/** A special constant with type `never` */
const NEVER = Object.freeze({ status: "aborted" });
function $constructor(name$2, initializer$2, params) {
function init(inst, def) {
var _a$2;
Object.defineProperty(inst, "_zod", {
value: inst._zod ?? {},
enumerable: false
});
(_a$2 = inst._zod).traits ?? (_a$2.traits = new Set());
inst._zod.traits.add(name$2);
initializer$2(inst, def);
for (const k$4 in _$3.prototype) if (!(k$4 in inst)) Object.defineProperty(inst, k$4, { value: _$3.prototype[k$4].bind(inst) });
inst._zod.constr = _$3;
inst._zod.def = def;
}
const Parent = params?.Parent ?? Object;
class Definition extends Parent {}
Object.defineProperty(Definition, "name", { value: name$2 });
function _$3(def) {
var _a$2;
const inst = params?.Parent ? new Definition() : this;
init(inst, def);
(_a$2 = inst._zod).deferred ?? (_a$2.deferred = []);
for (const fn$1 of inst._zod.deferred) fn$1();
return inst;
}
Object.defineProperty(_$3, "init", { value: init });
Object.defineProperty(_$3, Symbol.hasInstance, { value: (inst) => {
if (params?.Parent && inst instanceof params.Parent) return true;
return inst?._zod?.traits?.has(name$2);
} });
Object.defineProperty(_$3, "name", { value: name$2 });
return _$3;
}
const $brand = Symbol("zod_brand");
var $ZodAsyncError = class extends Error {
constructor() {
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
}
};
const globalConfig = {};
function config(newConfig) {
if (newConfig) Object.assign(globalConfig, newConfig);
return globalConfig;
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/util.js
function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v$3) => typeof v$3 === "number");
const values = Object.entries(entries).filter(([k$4, _$3]) => numericValues.indexOf(+k$4) === -1).map(([_$3, v$3]) => v$3);
return values;
}
function jsonStringifyReplacer(_$3, value) {
if (typeof value === "bigint") return value.toString();
return value;
}
function cached(getter) {
const set = false;
return { get value() {
if (!set) {
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(source) {
const start = source.startsWith("^") ? 1 : 0;
const end = source.endsWith("$") ? source.length - 1 : source.length;
return source.slice(start, end);
}
function floatSafeRemainder$1(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / 10 ** decCount;
}
function defineLazy(object$2, key, getter) {
const set = false;
Object.defineProperty(object$2, key, {
get() {
if (!set) {
const value = getter();
object$2[key] = value;
return value;
}
throw new Error("cached value already set");
},
set(v$3) {
Object.defineProperty(object$2, key, { value: v$3 });
},
configurable: true
});
}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
function esc(str) {
return JSON.stringify(str);
}
const captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {};
function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
const allowsEval = cached(() => {
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
try {
const F$4 = Function;
new F$4("");
return true;
} catch (_$3) {
return false;
}
});
function isPlainObject(o$3) {
if (isObject(o$3) === false) return false;
const ctor = o$3.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;
}
const propertyKeyTypes = new Set([
"string",
"number",
"symbol"
]);
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params) {
const cl = new inst._zod.constr(def ?? inst._zod.def);
if (!def || 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?.message !== void 0) {
if (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 {
...params,
error: () => params.error
};
return params;
}
function optionalKeys(shape) {
return Object.keys(shape).filter((k$4) => {
return shape[k$4]._zod.optin === "optional" && shape[k$4]._zod.optout === "optional";
});
}
const 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]
};
function pick(schema, mask) {
const newShape = {};
const currDef = schema._zod.def;
for (const key in mask) {
if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
newShape[key] = currDef.shape[key];
}
return clone(schema, {
...schema._zod.def,
shape: newShape,
checks: []
});
}
function omit(schema, mask) {
const newShape = { ...schema._zod.def.shape };
const currDef = schema._zod.def;
for (const key in mask) {
if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
delete newShape[key];
}
return clone(schema, {
...schema._zod.def,
shape: newShape,
checks: []
});
}
function extend(schema, shape) {
if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
const def = {
...schema._zod.def,
get shape() {
const _shape = {
...schema._zod.def.shape,
...shape
};
assignProp(this, "shape", _shape);
return _shape;
},
checks: []
};
return clone(schema, def);
}
function merge(a$2, b$3) {
return clone(a$2, {
...a$2._zod.def,
get shape() {
const _shape = {
...a$2._zod.def.shape,
...b$3._zod.def.shape
};
assignProp(this, "shape", _shape);
return _shape;
},
catchall: b$3._zod.def.catchall,
checks: []
});
}
function partial(Class, schema, mask) {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) for (const key in mask) {
if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
shape[key] = Class ? new Class({
type: "optional",
innerType: oldShape[key]
}) : oldShape[key];
}
else for (const key in oldShape) shape[key] = Class ? new Class({
type: "optional",
innerType: oldShape[key]
}) : oldShape[key];
return clone(schema, {
...schema._zod.def,
shape,
checks: []
});
}
function required(Class, schema, mask) {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) for (const key in mask) {
if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key]
});
}
else for (const key in oldShape) shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key]
});
return clone(schema, {
...schema._zod.def,
shape,
checks: []
});
}
function aborted(x$4, startIndex = 0) {
for (let i$3 = startIndex; i$3 < x$4.issues.length; i$3++) if (x$4.issues[i$3]?.continue !== true) return true;
return false;
}
function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a$2;
(_a$2 = iss).path ?? (_a$2.path = []);
iss.path.unshift(path);
return iss;
});
}
function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config$1) {
const full = {
...iss,
path: iss.path ?? []
};
if (!iss.message) {
const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config$1.customError?.(iss)) ?? unwrapMessage(config$1.localeError?.(iss)) ?? "Invalid input";
full.message = message;
}
delete full.inst;
delete full.continue;
if (!ctx?.reportInput) delete full.input;
return full;
}
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 { ...iss };
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/errors.js
const initializer$1 = (inst, def) => {
inst.name = "$ZodError";
Object.defineProperty(inst, "_zod", {
value: inst._zod,
enumerable: false
});
Object.defineProperty(inst, "issues", {
value: def,
enumerable: false
});
Object.defineProperty(inst, "message", {
get() {
return JSON.stringify(def, jsonStringifyReplacer, 2);
},
enumerable: true
});
Object.defineProperty(inst, "toString", {
value: () => inst.message,
enumerable: false
});
};
const $ZodError = $constructor("$ZodError", initializer$1);
const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
function flattenError(error, mapper = (issue$1) => issue$1.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error.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(error, _mapper) {
const mapper = _mapper || function(issue$1) {
return issue$1.message;
};
const fieldErrors = { _errors: [] };
const processError = (error$1) => {
for (const issue$1 of error$1.issues) if (issue$1.code === "invalid_union" && issue$1.errors.length) issue$1.errors.map((issues) => processError({ issues }));
else if (issue$1.code === "invalid_key") processError({ issues: issue$1.issues });
else if (issue$1.code === "invalid_element") processError({ issues: issue$1.issues });
else if (issue$1.path.length === 0) fieldErrors._errors.push(mapper(issue$1));
else {
let curr = fieldErrors;
let i$3 = 0;
while (i$3 < issue$1.path.length) {
const el = issue$1.path[i$3];
const terminal = i$3 === issue$1.path.length - 1;
if (!terminal) curr[el] = curr[el] || { _errors: [] };
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue$1));
}
curr = curr[el];
i$3++;
}
}
};
processError(error);
return fieldErrors;
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/parse.js
const _parse$1 = (_Err) => (schema, value, _ctx, _params) => {
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$2 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
captureStackTrace(e$2, _params?.callee);
throw e$2;
}
return result.value;
};
const parse$1 = /* @__PURE__ */ _parse$1($ZodRealError);
const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
let result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) result = await result;
if (result.issues.length) {
const e$2 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
captureStackTrace(e$2, params?.callee);
throw e$2;
}
return result.value;
};
const parseAsync$1 = /* @__PURE__ */ _parseAsync($ZodRealError);
const _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? {
..._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 ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
} : {
success: true,
data: result.value
};
};
const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
let result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) result = await result;
return result.issues.length ? {
success: false,
error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
} : {
success: true,
data: result.value
};
};
const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/regexes.js
const cuid = /^[cC][^\s-]{8,}$/;
const cuid2 = /^[0-9a-z]+$/;
const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
const xid = /^[0-9a-vA-V]{20}$/;
const ksuid = /^[A-Za-z0-9]{27}$/;
const nanoid = /^[a-zA-Z0-9_-]{21}$/;
/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
const 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})$/;
/** Returns a regex for validating an RFC 4122 UUID.
*
* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
const uuid = (version$2) => {
if (!version$2) 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)$/;
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version$2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
/** Practical email validation */
const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
return new RegExp(_emoji$1, "u");
}
const 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])$/;
const ipv6 = /^(([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})$/;
const 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])$/;
const 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])$/;
const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
const base64url = /^[A-Za-z0-9_-]*$/;
const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
const 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])))`;
const date$1 = /* @__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$1(args) {
return new RegExp(`^${timeSource(args)}$`);
}
function datetime$1(args) {
const time$2 = timeSource({ precision: args.precision });
const opts = ["Z"];
if (args.local) opts.push("");
if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
const timeRegex$1 = `${time$2}(?:${opts.join("|")})`;
return new RegExp(`^${dateSource}T(?:${timeRegex$1})$`);
}
const string$1 = (params) => {
const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
return new RegExp(`^${regex}$`);
};
const integer = /^\d+$/;
const number$1 = /^-?\d+(?:\.\d+)?/i;
const boolean$1 = /true|false/i;
const _null$2 = /null/i;
const lowercase = /^[^A-Z]*$/;
const uppercase = /^[^a-z]*$/;
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/checks.js
const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
var _a$2;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a$2 = inst._zod).onattach ?? (_a$2.onattach = []);
});
const numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date"
};
const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? 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
});
};
});
const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? 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
});
};
});
const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.onattach.push((inst$1) => {
var _a$2;
(_a$2 = inst$1._zod.bag).multipleOf ?? (_a$2.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$1(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
});
};
});
const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
$ZodCheck.init(inst, def);
def.format = def.format || "float64";
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._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",
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
});
};
});
const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
var _a$2;
$ZodCheck.init(inst, def);
(_a$2 = inst._zod.def).when ?? (_a$2.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst$1) => {
const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
if (def.maximum < curr) inst$1._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
});
};
});
const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
var _a$2;
$ZodCheck.init(inst, def);
(_a$2 = inst._zod.def).when ?? (_a$2.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst$1) => {
const curr = inst$1._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
if (def.minimum > curr) inst$1._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
});
};
});
const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a$2;
$ZodCheck.init(inst, def);
(_a$2 = inst._zod.def).when ?? (_a$2.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._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({
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
});
};
});
const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
var _a$2, _b;
$ZodCheck.init(inst, def);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.format = def.format;
if (def.pattern) {
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(def.pattern);
}
});
if (def.pattern) (_a$2 = inst._zod).check ?? (_a$2.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def.format,
input: payload.value,
...def.pattern ? { pattern: def.pattern.toString() } : {},
inst,
continue: !def.abort
});
});
else (_b = inst._zod).check ?? (_b.check = () => {});
});
const $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
});
};
});
const $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = lowercase);
$ZodCheckStringFormat.init(inst, def);
});
const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = uppercase);
$ZodCheckStringFormat.init(inst, def);
});
const $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((inst$1) => {
const bag = inst$1._zod.bag;
bag.patterns ?? (bag.patterns = 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
});
};
});
const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.patterns ?? (bag.patterns = 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
});
};
});
const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.patterns ?? (bag.patterns = 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
});
};
});
const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/doc.js
var Doc = class {
constructor(args = []) {
this.content = [];
this.indent = 0;
if (this) this.args = args;
}
indented(fn$1) {
this.indent += 1;
fn$1(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$4) => x$4);
const minIndent = Math.min(...lines.map((x$4) => x$4.length - x$4.trimStart().length));
const dedented = lines.map((x$4) => x$4.slice(minIndent)).map((x$4) => " ".repeat(this.indent * 2) + x$4);
for (const line of dedented) this.content.push(line);
}
compile() {
const F$4 = Function;
const args = this?.args;
const content = this?.content ?? [``];
const lines = [...content.map((x$4) => ` ${x$4}`)];
return new F$4(...args, lines.join("\n"));
}
};
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/versions.js
const version = {
major: 4,
minor: 0,
patch: 0
};
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/schemas.js
const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
var _a$2;
inst ?? (inst = {});
inst._zod.def = def;
inst._zod.bag = inst._zod.bag || {};
inst._zod.version = version;
const checks = [...inst._zod.def.checks ?? []];
if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
for (const ch of checks) for (const fn$1 of ch._zod.onattach) fn$1(inst);
if (checks.length === 0) {
(_a$2 = inst._zod).deferred ?? (_a$2.deferred = []);
inst._zod.deferred?.push(() => {
inst._zod.run = inst._zod.parse;
});
} else {
const runChecks = (payload, checks$1, ctx) => {
let isAborted$1 = aborted(payload);
let asyncResult;
for (const ch of checks$1) {
if (ch._zod.def.when) {
const shouldRun = ch._zod.def.when(payload);
if (!shouldRun) continue;
} else if (isAborted$1) continue;
const currLen = payload.issues.length;
const _$3 = ch._zod.check(payload);
if (_$3 instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
if (asyncResult || _$3 instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
await _$3;
const nextLen = payload.issues.length;
if (nextLen === currLen) return;
if (!isAborted$1) isAborted$1 = aborted(payload, currLen);
});
else {
const nextLen = payload.issues.length;
if (nextLen === currLen) continue;
if (!isAborted$1) isAborted$1 = aborted(payload, currLen);
}
}
if (asyncResult) return asyncResult.then(() => {
return payload;
});
return payload;
};
inst._zod.run = (payload, ctx) => {
const result = inst._zod.parse(payload, ctx);
if (result instanceof Promise) {
if (ctx.async === false) throw new $ZodAsyncError();
return result.then((result$1) => runChecks(result$1, checks, ctx));
}
return runChecks(result, checks, ctx);
};
}
inst["~standard"] = {
validate: (value) => {
try {
const r$2 = safeParse$1(inst, value);
return r$2.success ? { value: r$2.data } : { issues: r$2.error?.issues };
} catch (_$3) {
return safeParseAsync$1(inst, value).then((r$2) => r$2.success ? { value: r$2.data } : { issues: r$2.error?.issues });
}
},
vendor: "zod",
version: 1
};
});
const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
inst._zod.parse = (payload, _$3) => {
if (def.coerce) try {
payload.value = String(payload.value);
} catch (_$4) {}
if (typeof payload.value === "string") return payload;
payload.issues.push({
expected: "string",
code: "invalid_type",
input: payload.value,
inst
});
return payload;
};
});
const $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
$ZodCheckStringFormat.init(inst, def);
$ZodString.init(inst, def);
});
const $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
def.pattern ?? (def.pattern = guid);
$ZodStringFormat.init(inst, def);
});
const $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
if (def.version) {
const versionMap = {
v1: 1,
v2: 2,
v3: 3,
v4: 4,
v5: 5,
v6: 6,
v7: 7,
v8: 8
};
const v$3 = versionMap[def.version];
if (v$3 === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
def.pattern ?? (def.pattern = uuid(v$3));
} else def.pattern ?? (def.pattern = uuid());
$ZodStringFormat.init(inst, def);
});
const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
def.pattern ?? (def.pattern = email);
$ZodStringFormat.init(inst, def);
});
const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
try {
const orig = payload.value;
const url = new URL(orig);
const href = url.href;
if (def.hostname) {
def.hostname.lastIndex = 0;
if (!def.hostname.test(url.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(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid protocol",
pattern: def.protocol.source,
input: payload.value,
inst,
continue: !def.abort
});
}
if (!orig.endsWith("/") && href.endsWith("/")) payload.value = href.slice(0, -1);
else payload.value = href;
return;
} catch (_$3) {
payload.issues.push({
code: "invalid_format",
format: "url",
input: payload.value,
inst,
continue: !def.abort
});
}
};
});
const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
def.pattern ?? (def.pattern = emoji());
$ZodStringFormat.init(inst, def);
});
const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
def.pattern ?? (def.pattern = nanoid);
$ZodStringFormat.init(inst, def);
});
const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
def.pattern ?? (def.pattern = cuid);
$ZodStringFormat.init(inst, def);
});
const $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
def.pattern ?? (def.pattern = cuid2);
$ZodStringFormat.init(inst, def);
});
const $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
def.pattern ?? (def.pattern = ulid);
$ZodStringFormat.init(inst, def);
});
const $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
def.pattern ?? (def.pattern = xid);
$ZodStringFormat.init(inst, def);
});
const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
def.pattern ?? (def.pattern = ksuid);
$ZodStringFormat.init(inst, def);
});
const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
def.pattern ?? (def.pattern = datetime$1(def));
$ZodStringFormat.init(inst, def);
});
const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
def.pattern ?? (def.pattern = date$1);
$ZodStringFormat.init(inst, def);
});
const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
def.pattern ?? (def.pattern = time$1(def));
$ZodStringFormat.init(inst, def);
});
const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
def.pattern ?? (def.pattern = duration$1);
$ZodStringFormat.init(inst, def);
});
const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
def.pattern ?? (def.pattern = ipv4);
$ZodStringFormat.init(inst, def);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.format = `ipv4`;
});
});
const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
def.pattern ?? (def.pattern = ipv6);
$ZodStringFormat.init(inst, def);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.format = `ipv6`;
});
inst._zod.check = (payload) => {
try {
new URL(`http://[${payload.value}]`);
} catch {
payload.issues.push({
code: "invalid_format",
format: "ipv6",
input: payload.value,
inst,
continue: !def.abort
});
}
};
});
const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
def.pattern ?? (def.pattern = cidrv4);
$ZodStringFormat.init(inst, def);
});
const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
def.pattern ?? (def.pattern = cidrv6);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
const [address, prefix] = payload.value.split("/");
try {
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 {
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 {
return false;
}
}
const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
def.pattern ?? (def.pattern = base64);
$ZodStringFormat.init(inst, def);
inst._zod.onattach.push((inst$1) => {
inst$1._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 base64$1 = data.replace(/[-_]/g, (c$2) => c$2 === "-" ? "+" : "/");
const padded = base64$1.padEnd(Math.ceil(base64$1.length / 4) * 4, "=");
return isValidBase64(padded);
}
const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
def.pattern ?? (def.pattern = base64url);
$ZodStringFormat.init(inst, def);
inst._zod.onattach.push((inst$1) => {
inst$1._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
});
};
});
const $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
def.pattern ?? (def.pattern = e164);
$ZodStringFormat.init(inst, def);
});
function isValidJWT$1(token, algorithm = null) {
try {
const tokensParts = token.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?.typ !== "JWT") return false;
if (!parsedHeader.alg) return false;
if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
return true;
} catch {
return false;
}
}
const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
if (isValidJWT$1(payload.value, def.alg)) return;
payload.issues.push({
code: "invalid_format",
format: "jwt",
input: payload.value,
inst,
continue: !def.abort
});
};
});
const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce) try {
payload.value = Number(payload.value);
} catch (_$3) {}
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({
expected: "number",
code: "invalid_type",
input,
inst,
...received ? { received } : {}
});
return payload;
};
});
const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
$ZodCheckNumberFormat.init(inst, def);
$ZodNumber.init(inst, def);
});
const $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = boolean$1;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce) try {
payload.value = Boolean(payload.value);
} catch (_$3) {}
const input = payload.value;
if (typeof input === "boolean") return payload;
payload.issues.push({
expected: "boolean",
code: "invalid_type",
input,
inst
});
return payload;
};
});
const $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = _null$2;
inst._zod.values = 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;
};
});
const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload) => payload;
});
const $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;
};
});
function handleArrayResult(result, final, index$1) {
if (result.issues.length) final.issues.push(...prefixIssues(index$1, result.issues));
final.value[index$1] = result.value;
}
const $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$3 = 0; i$3 < input.length; i$3++) {
const item = input[i$3];
const result = def.element._zod.run({
value: item,
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result$1) => handleArrayResult(result$1, payload, i$3)));
else handleArrayResult(result, payload, i$3);
}
if (proms.length) return Promise.all(proms).then(() => payload);
return payload;
};
});
function handleObjectResult(result, final, key) {
if (result.issues.length) final.issues.push(...prefixIssues(key, result.issues));
final.value[key] = result.value;
}
function handleOptionalObjectResult(result, final, key, input) {
if (result.issues.length) if (input[key] === void 0) if (key in input) final.value[key] = void 0;
else final.value[key] = result.value;
else final.issues.push(...prefixIssues(key, result.issues));
else if (result.value === void 0) {
if (key in input) final.value[key] = void 0;
} else final.value[key] = result.value;
}
const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
$ZodType.init(inst, def);
const _normalized = cached(() => {
const keys = Object.keys(def.shape);
for (const k$4 of keys) if (!(def.shape[k$4] instanceof $ZodType)) throw new Error(`Invalid element at key "${k$4}": expected a Zod schema`);
const okeys = optionalKeys(def.shape);
return {
shape: def.shape,
keys,
keySet: new Set(keys),
numKeys: keys.length,
optionalKeys: new Set(okeys)
};
});
defineLazy(inst._zod, "propValues", () => {
const shape = def.shape;
const propValues = {};
for (const key in shape) {
const field = shape[key]._zod;
if (field.values) {
propValues[key] ?? (propValues[key] = new Set());
for (const v$3 of field.values) propValues[key].add(v$3);
}
}
return propValues;
});
const generateFastpass = (shape) => {
const doc = new Doc([
"shape",
"payload",
"ctx"
]);
const normalized = _normalized.value;
const parseStr = (key) => {
const k$4 = esc(key);
return `shape[${k$4}]._zod.run({ value: input[${k$4}], issues: [] }, ctx)`;
};
doc.write(`const input = payload.value;`);
const ids = Object.create(null);
let counter = 0;
for (const key of normalized.keys) ids[key] = `key_${counter++}`;
doc.write(`const newResult = {}`);
for (const key of normalized.keys) if (normalized.optionalKeys.has(key)) {
const id$1 = ids[key];
doc.write(`const ${id$1} = ${parseStr(key)};`);
const k$4 = esc(key);
doc.write(`
if (${id$1}.issues.length) {
if (input[${k$4}] === undefined) {
if (${k$4} in input) {
newResult[${k$4}] = undefined;
}
} else {
payload.issues = payload.issues.concat(
${id$1}.issues.map((iss) => ({
...iss,
path: iss.path ? [${k$4}, ...iss.path] : [${k$4}],
}))
);
}
} else if (${id$1}.value === undefined) {
if (${k$4} in input) newResult[${k$4}] = undefined;
} else {
newResult[${k$4}] = ${id$1}.value;
}
`);
} else {
const id$1 = ids[key];
doc.write(`const ${id$1} = ${parseStr(key)};`);
doc.write(`
if (${id$1}.issues.length) payload.issues = payload.issues.concat(${id$1}.issues.map(iss => ({
...iss,
path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
})));`);
doc.write(`newResult[${esc(key)}] = ${id$1}.value`);
}
doc.write(`payload.value = newResult;`);
doc.write(`return payload;`);
const fn$1 = doc.compile();
return (payload, ctx) => fn$1(shape, payload, ctx);
};
let fastpass;
const isObject$2 = isObject;
const jit = !globalConfig.jitless;
const allowsEval$1 = allowsEval;
const fastEnabled = jit && allowsEval$1.value;
const catchall = def.catchall;
let value;
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
if (!isObject$2(input)) {
payload.issues.push({
expected: "object",
code: "invalid_type",
input,
inst
});
return payload;
}
const proms = [];
if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
if (!fastpass) fastpass = generateFastpass(def.shape);
payload = fastpass(payload, ctx);
} else {
payload.value = {};
const shape = value.shape;
for (const key of value.keys) {
const el = shape[key];
const r$2 = el._zod.run({
value: input[key],
issues: []
}, ctx);
const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
if (r$2 instanceof Promise) proms.push(r$2.then((r$3) => isOptional ? handleOptionalObjectResult(r$3, payload, key, input) : handleObjectResult(r$3, payload, key)));
else if (isOptional) handleOptionalObjectResult(r$2, payload, key, input);
else handleObjectResult(r$2, payload, key);
}
}
if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
const unrecognized = [];
const keySet = value.keySet;
const _catchall = catchall._zod;
const t$2 = _catchall.def.type;
for (const key of Object.keys(input)) {
if (keySet.has(key)) continue;
if (t$2 === "never") {
unrecognized.push(key);
continue;
}
const r$2 = _catchall.run({
value: input[key],
issues: []
}, ctx);
if (r$2 instanceof Promise) proms.push(r$2.then((r$3) => handleObjectResult(r$3, payload, key)));
else handleObjectResult(r$2, payload, key);
}
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;
});
};
});
function handleUnionResults(results, final, inst, ctx) {
for (const result of results) if (result.issues.length === 0) {
final.value = result.value;
return final;
}
final.issues.push({
code: "invalid_union",
input: final.value,
inst,
errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
});
return final;
}
const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "optin", () => def.options.some((o$3) => o$3._zod.optin === "optional") ? "optional" : void 0);
defineLazy(inst._zod, "optout", () => def.options.some((o$3) => o$3._zod.optout === "optional") ? "optional" : void 0);
defineLazy(inst._zod, "values", () => {
if (def.options.every((o$3) => o$3._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$3) => o$3._zod.pattern)) {
const patterns = def.options.map((o$3) => o$3._zod.pattern);
return new RegExp(`^(${patterns.map((p$2) => cleanRegex(p$2.source)).join("|")})$`);
}
return void 0;
});
inst._zod.parse = (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((results$1) => {
return handleUnionResults(results$1, payload, inst, ctx);
});
};
});
const $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$4, v$3] of Object.entries(pv)) {
if (!propValues[k$4]) propValues[k$4] = new Set();
for (const val of v$3) propValues[k$4].add(val);
}
}
return propValues;
});
const disc = cached(() => {
const opts = def.options;
const map = new Map();
for (const o$3 of opts) {
const values = o$3._zod.propValues[def.discriminator];
if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o$3)}"`);
for (const v$3 of values) {
if (map.has(v$3)) throw new Error(`Duplicate discriminator value "${String(v$3)}"`);
map.set(v$3, o$3);
}
}
return map;
});
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?.[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",
input,
path: [def.discriminator],
inst
});
return payload;
};
});
const $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(([left$1, right$1]) => {
return handleIntersectionResults(payload, left$1, right$1);
});
return handleIntersectionResults(payload, left, right);
};
});
function mergeValues$1(a$2, b$3) {
if (a$2 === b$3) return {
valid: true,
data: a$2
};
if (a$2 instanceof Date && b$3 instanceof Date && +a$2 === +b$3) return {
valid: true,
data: a$2
};
if (isPlainObject(a$2) && isPlainObject(b$3)) {
const bKeys = Object.keys(b$3);
const sharedKeys = Object.keys(a$2).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = {
...a$2,
...b$3
};
for (const key of sharedKeys) {
const sharedValue = mergeValues$1(a$2[key], b$3[key]);
if (!sharedValue.valid) return {
valid: false,
mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
};
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
}
if (Array.isArray(a$2) && Array.isArray(b$3)) {
if (a$2.length !== b$3.length) return {
valid: false,
mergeErrorPath: []
};
const newArray = [];
for (let index$1 = 0; index$1 < a$2.length; index$1++) {
const itemA = a$2[index$1];
const itemB = b$3[index$1];
const sharedValue = mergeValues$1(itemA, itemB);
if (!sharedValue.valid) return {
valid: false,
mergeErrorPath: [index$1, ...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$1(left.value, right.value);
if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
result.value = merged.data;
return result;
}
const $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 key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
const result = def.valueType._zod.run({
value: input[key],
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result$1) => {
if (result$1.issues.length) payload.issues.push(...prefixIssues(key, result$1.issues));
payload.value[key] = result$1.value;
}));
else {
if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
payload.value[key] = result.value;
}
}
let unrecognized;
for (const key in input) if (!values.has(key)) {
unrecognized = unrecognized ?? [];
unrecognized.push(key);
}
if (unrecognized && unrecognized.length > 0) payload.issues.push({
code: "unrecognized_keys",
input,
inst,
keys: unrecognized
});
} else {
payload.value = {};
for (const key of Reflect.ownKeys(input)) {
if (key === "__proto__") continue;
const keyResult = def.keyType._zod.run({
value: key,
issues: []
}, ctx);
if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
if (keyResult.issues.length) {
payload.issues.push({
origin: "record",
code: "invalid_key",
issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
input: key,
path: [key],
inst
});
payload.value[keyResult.value] = keyResult.value;
continue;
}
const result = def.valueType._zod.run({
value: input[key],
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result$1) => {
if (result$1.issues.length) payload.issues.push(...prefixIssues(key, result$1.issues));
payload.value[keyResult.value] = result$1.value;
}));
else {
if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
payload.value[keyResult.value] = result.value;
}
}
}
if (proms.length) return Promise.all(proms).then(() => payload);
return payload;
};
});
const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
$ZodType.init(inst, def);
const values = getEnumValues(def.entries);
inst._zod.values = new Set(values);
inst._zod.pattern = new RegExp(`^(${values.filter((k$4) => propertyKeyTypes.has(typeof k$4)).map((o$3) => typeof o$3 === "string" ? escapeRegex(o$3) : o$3.toString()).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,
input,
inst
});
return payload;
};
});
const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.values = new Set(def.values);
inst._zod.pattern = new RegExp(`^(${def.values.map((o$3) => typeof o$3 === "string" ? escapeRegex(o$3) : o$3 ? o$3.toString() : String(o$3)).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;
};
});
const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, _ctx) => {
const _out = def.transform(payload.value, payload);
if (_ctx.async) {
const output = _out instanceof Promise ? _out : Promise.resolve(_out);
return output.then((output$1) => {
payload.value = output$1;
return payload;
});
}
if (_out instanceof Promise) throw new $ZodAsyncError();
payload.value = _out;
return payload;
};
});
const $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 ? 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") return def.innerType._zod.run(payload, ctx);
if (payload.value === void 0) return payload;
return def.innerType._zod.run(payload, ctx);
};
});
const $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 ? 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);
};
});
const $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 (payload.value === void 0) {
payload.value = def.defaultValue;
/**
* $ZodDefault always returns the default value immediately.
* It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
return payload;
}
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result$1) => handleDefaultResult(result$1, def));
return handleDefaultResult(result, def);
};
});
function handleDefaultResult(payload, def) {
if (payload.value === void 0) payload.value = def.defaultValue;
return payload;
}
const $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 (payload.value === void 0) payload.value = def.defaultValue;
return def.innerType._zod.run(payload, ctx);
};
});
const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "values", () => {
const v$3 = def.innerType._zod.values;
return v$3 ? new Set([...v$3].filter((x$4) => x$4 !== void 0)) : void 0;
});
inst._zod.parse = (payload, ctx) => {
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result$1) => handleNonOptionalResult(result$1, 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;
}
const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result$1) => {
payload.value = result$1.value;
if (result$1.issues.length) {
payload.value = def.catchValue({
...payload,
error: { issues: result$1.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({
...payload,
error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
input: payload.value
});
payload.issues = [];
}
return payload;
};
});
const $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);
inst._zod.parse = (payload, ctx) => {
const left = def.in._zod.run(payload, ctx);
if (left instanceof Promise) return left.then((left$1) => handlePipeResult(left$1, def, ctx));
return handlePipeResult(left, def, ctx);
};
});
function handlePipeResult(left, def, ctx) {
if (aborted(left)) return left;
return def.out._zod.run({
value: left.value,
issues: left.issues
}, ctx);
}
const $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) => {
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;
}
const $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", () => inst._zod.innerType._zod.optin);
defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout);
inst._zod.parse = (payload, ctx) => {
const inner = inst._zod.innerType;
return inner._zod.run(payload, ctx);
};
});
const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
$ZodCheck.init(inst, def);
$ZodType.init(inst, def);
inst._zod.parse = (payload, _$3) => {
return payload;
};
inst._zod.check = (payload) => {
const input = payload.value;
const r$2 = def.fn(input);
if (r$2 instanceof Promise) return r$2.then((r$3) => handleRefineResult(r$3, payload, input, inst));
handleRefineResult(r$2, payload, input, inst);
return;
};
});
function handleRefineResult(result, payload, input, inst) {
if (!result) {
const _iss = {
code: "custom",
input,
inst,
path: [...inst._zod.def.path ?? []],
continue: !inst._zod.def.abort
};
if (inst._zod.def.params) _iss.params = inst._zod.def.params;
payload.issues.push(issue(_iss));
}
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/registries.js
const $output = Symbol("ZodOutput");
const $input = Symbol("ZodInput");
var $ZodRegistry = class {
constructor() {
this._map = new Map();
this._idmap = 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 = new Map();
this._idmap = 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) {
const p$2 = schema._zod.parent;
if (p$2) {
const pm = { ...this.get(p$2) ?? {} };
delete pm.id;
return {
...pm,
...this._map.get(schema)
};
}
return this._map.get(schema);
}
has(schema) {
return this._map.has(schema);
}
};
function registry() {
return new $ZodRegistry();
}
const globalRegistry = /* @__PURE__ */ registry();
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/api.js
function _string(Class, params) {
return new Class({
type: "string",
...normalizeParams(params)
});
}
function _email(Class, params) {
return new Class({
type: "string",
format: "email",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _guid(Class, params) {
return new Class({
type: "string",
format: "guid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _uuid(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _uuidv4(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v4",
...normalizeParams(params)
});
}
function _uuidv6(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v6",
...normalizeParams(params)
});
}
function _uuidv7(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v7",
...normalizeParams(params)
});
}
function _url(Class, params) {
return new Class({
type: "string",
format: "url",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _emoji(Class, params) {
return new Class({
type: "string",
format: "emoji",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _nanoid(Class, params) {
return new Class({
type: "string",
format: "nanoid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cuid(Class, params) {
return new Class({
type: "string",
format: "cuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cuid2(Class, params) {
return new Class({
type: "string",
format: "cuid2",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ulid(Class, params) {
return new Class({
type: "string",
format: "ulid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _xid(Class, params) {
return new Class({
type: "string",
format: "xid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ksuid(Class, params) {
return new Class({
type: "string",
format: "ksuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ipv4(Class, params) {
return new Class({
type: "string",
format: "ipv4",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ipv6(Class, params) {
return new Class({
type: "string",
format: "ipv6",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cidrv4(Class, params) {
return new Class({
type: "string",
format: "cidrv4",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cidrv6(Class, params) {
return new Class({
type: "string",
format: "cidrv6",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _base64(Class, params) {
return new Class({
type: "string",
format: "base64",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _base64url(Class, params) {
return new Class({
type: "string",
format: "base64url",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _e164(Class, params) {
return new Class({
type: "string",
format: "e164",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _jwt(Class, params) {
return new Class({
type: "string",
format: "jwt",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _isoDateTime(Class, params) {
return new Class({
type: "string",
format: "datetime",
check: "string_format",
offset: false,
local: false,
precision: null,
...normalizeParams(params)
});
}
function _isoDate(Class, params) {
return new Class({
type: "string",
format: "date",
check: "string_format",
...normalizeParams(params)
});
}
function _isoTime(Class, params) {
return new Class({
type: "string",
format: "time",
check: "string_format",
precision: null,
...normalizeParams(params)
});
}
function _isoDuration(Class, params) {
return new Class({
type: "string",
format: "duration",
check: "string_format",
...normalizeParams(params)
});
}
function _number(Class, params) {
return new Class({
type: "number",
checks: [],
...normalizeParams(params)
});
}
function _int(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "safeint",
...normalizeParams(params)
});
}
function _boolean(Class, params) {
return new Class({
type: "boolean",
...normalizeParams(params)
});
}
function _null$1(Class, params) {
return new Class({
type: "null",
...normalizeParams(params)
});
}
function _unknown(Class) {
return new Class({ type: "unknown" });
}
function _never(Class, params) {
return new Class({
type: "never",
...normalizeParams(params)
});
}
function _lt(value, params) {
return new $ZodCheckLessThan({
check: "less_than",
...normalizeParams(params),
value,
inclusive: false
});
}
function _lte(value, params) {
return new $ZodCheckLessThan({
check: "less_than",
...normalizeParams(params),
value,
inclusive: true
});
}
function _gt(value, params) {
return new $ZodCheckGreaterThan({
check: "greater_than",
...normalizeParams(params),
value,
inclusive: false
});
}
function _gte(value, params) {
return new $ZodCheckGreaterThan({
check: "greater_than",
...normalizeParams(params),
value,
inclusive: true
});
}
function _multipleOf(value, params) {
return new $ZodCheckMultipleOf({
check: "multiple_of",
...normalizeParams(params),
value
});
}
function _maxLength(maximum, params) {
const ch = new $ZodCheckMaxLength({
check: "max_length",
...normalizeParams(params),
maximum
});
return ch;
}
function _minLength(minimum, params) {
return new $ZodCheckMinLength({
check: "min_length",
...normalizeParams(params),
minimum
});
}
function _length(length, params) {
return new $ZodCheckLengthEquals({
check: "length_equals",
...normalizeParams(params),
length
});
}
function _regex(pattern, params) {
return new $ZodCheckRegex({
check: "string_format",
format: "regex",
...normalizeParams(params),
pattern
});
}
function _lowercase(params) {
return new $ZodCheckLowerCase({
check: "string_format",
format: "lowercase",
...normalizeParams(params)
});
}
function _uppercase(params) {
return new $ZodCheckUpperCase({
check: "string_format",
format: "uppercase",
...normalizeParams(params)
});
}
function _includes(includes, params) {
return new $ZodCheckIncludes({
check: "string_format",
format: "includes",
...normalizeParams(params),
includes
});
}
function _startsWith(prefix, params) {
return new $ZodCheckStartsWith({
check: "string_format",
format: "starts_with",
...normalizeParams(params),
prefix
});
}
function _endsWith(suffix, params) {
return new $ZodCheckEndsWith({
check: "string_format",
format: "ends_with",
...normalizeParams(params),
suffix
});
}
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(Class, element, params) {
return new Class({
type: "array",
element,
...normalizeParams(params)
});
}
function _custom(Class, fn$1, _params) {
const norm = normalizeParams(_params);
norm.abort ?? (norm.abort = true);
const schema = new Class({
type: "custom",
check: "custom",
fn: fn$1,
...norm
});
return schema;
}
function _refine(Class, fn$1, _params) {
const schema = new Class({
type: "custom",
check: "custom",
fn: fn$1,
...normalizeParams(_params)
});
return schema;
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/to-json-schema.js
var JSONSchemaGenerator = class {
constructor(params) {
this.counter = 0;
this.metadataRegistry = params?.metadata ?? globalRegistry;
this.target = params?.target ?? "draft-2020-12";
this.unrepresentable = params?.unrepresentable ?? "throw";
this.override = params?.override ?? (() => {});
this.io = params?.io ?? "output";
this.seen = new Map();
}
process(schema, _params = {
path: [],
schemaPath: []
}) {
var _a$2;
const def = schema._zod.def;
const formatMap = {
guid: "uuid",
url: "uri",
datetime: "date-time",
json_string: "json-string",
regex: ""
};
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 = schema._zod.toJSONSchema?.();
if (overrideSchema) result.schema = overrideSchema;
else {
const params = {
..._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 json = _json;
json.type = "string";
const { minimum, maximum, format: format$1, patterns, contentEncoding } = schema._zod.bag;
if (typeof minimum === "number") json.minLength = minimum;
if (typeof maximum === "number") json.maxLength = maximum;
if (format$1) {
json.format = formatMap[format$1] ?? format$1;
if (json.format === "") delete json.format;
}
if (contentEncoding) json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
const regexes = [...patterns];
if (regexes.length === 1) json.pattern = regexes[0].source;
else if (regexes.length > 1) result.schema.allOf = [...regexes.map((regex) => ({
...this.target === "draft-7" ? { type: "string" } : {},
pattern: regex.source
}))];
}
break;
}
case "number": {
const json = _json;
const { minimum, maximum, format: format$1, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
if (typeof format$1 === "string" && format$1.includes("int")) json.type = "integer";
else json.type = "number";
if (typeof exclusiveMinimum === "number") json.exclusiveMinimum = exclusiveMinimum;
if (typeof minimum === "number") {
json.minimum = minimum;
if (typeof exclusiveMinimum === "number") if (exclusiveMinimum >= minimum) delete json.minimum;
else delete json.exclusiveMinimum;
}
if (typeof exclusiveMaximum === "number") json.exclusiveMaximum = exclusiveMaximum;
if (typeof maximum === "number") {
json.maximum = maximum;
if (typeof exclusiveMaximum === "number") if (exclusiveMaximum <= maximum) delete json.maximum;
else delete json.exclusiveMaximum;
}
if (typeof multipleOf === "number") json.multipleOf = multipleOf;
break;
}
case "boolean": {
const json = _json;
json.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": {
_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 json = _json;
const { minimum, maximum } = schema._zod.bag;
if (typeof minimum === "number") json.minItems = minimum;
if (typeof maximum === "number") json.maxItems = maximum;
json.type = "array";
json.items = this.process(def.element, {
...params,
path: [...params.path, "items"]
});
break;
}
case "object": {
const json = _json;
json.type = "object";
json.properties = {};
const shape = def.shape;
for (const key in shape) json.properties[key] = this.process(shape[key], {
...params,
path: [
...params.path,
"properties",
key
]
});
const allKeys = new Set(Object.keys(shape));
const requiredKeys = new Set([...allKeys].filter((key) => {
const v$3 = def.shape[key]._zod;
if (this.io === "input") return v$3.optin === void 0;
else return v$3.optout === void 0;
}));
if (requiredKeys.size > 0) json.required = Array.from(requiredKeys);
if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
else if (!def.catchall) {
if (this.io === "output") json.additionalProperties = false;
} else if (def.catchall) json.additionalProperties = this.process(def.catchall, {
...params,
path: [...params.path, "additionalProperties"]
});
break;
}
case "union": {
const json = _json;
json.anyOf = def.options.map((x$4, i$3) => this.process(x$4, {
...params,
path: [
...params.path,
"anyOf",
i$3
]
}));
break;
}
case "intersection": {
const json = _json;
const a$2 = this.process(def.left, {
...params,
path: [
...params.path,
"allOf",
0
]
});
const b$3 = this.process(def.right, {
...params,
path: [
...params.path,
"allOf",
1
]
});
const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
const allOf = [...isSimpleIntersection(a$2) ? a$2.allOf : [a$2], ...isSimpleIntersection(b$3) ? b$3.allOf : [b$3]];
json.allOf = allOf;
break;
}
case "tuple": {
const json = _json;
json.type = "array";
const prefixItems = def.items.map((x$4, i$3) => this.process(x$4, {
...params,
path: [
...params.path,
"prefixItems",
i$3
]
}));
if (this.target === "draft-2020-12") json.prefixItems = prefixItems;
else json.items = prefixItems;
if (def.rest) {
const rest = this.process(def.rest, {
...params,
path: [...params.path, "items"]
});
if (this.target === "draft-2020-12") json.items = rest;
else json.additionalItems = rest;
}
if (def.rest) json.items = this.process(def.rest, {
...params,
path: [...params.path, "items"]
});
const { minimum, maximum } = schema._zod.bag;
if (typeof minimum === "number") json.minItems = minimum;
if (typeof maximum === "number") json.maxItems = maximum;
break;
}
case "record": {
const json = _json;
json.type = "object";
json.propertyNames = this.process(def.keyType, {
...params,
path: [...params.path, "propertyNames"]
});
json.additionalProperties = this.process(def.valueType, {
...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 json = _json;
const values = getEnumValues(def.entries);
if (values.every((v$3) => typeof v$3 === "number")) json.type = "number";
if (values.every((v$3) => typeof v$3 === "string")) json.type = "string";
json.enum = values;
break;
}
case "literal": {
const json = _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 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];
json.type = val === null ? "null" : typeof val;
json.const = val;
} else {
if (vals.every((v$3) => typeof v$3 === "number")) json.type = "number";
if (vals.every((v$3) => typeof v$3 === "string")) json.type = "string";
if (vals.every((v$3) => typeof v$3 === "boolean")) json.type = "string";
if (vals.every((v$3) => v$3 === null)) json.type = "null";
json.enum = vals;
}
break;
}
case "file": {
const json = _json;
const file = {
type: "string",
format: "binary",
contentEncoding: "binary"
};
const { minimum, maximum, mime } = schema._zod.bag;
if (minimum !== void 0) file.minLength = minimum;
if (maximum !== void 0) file.maxLength = maximum;
if (mime) if (mime.length === 1) {
file.contentMediaType = mime[0];
Object.assign(json, file);
} else json.anyOf = mime.map((m$4) => {
const mFile = {
...file,
contentMediaType: m$4
};
return mFile;
});
else Object.assign(json, file);
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);
_json.anyOf = [inner, { type: "null" }];
break;
}
case "nonoptional": {
this.process(def.innerType, params);
result.ref = def.innerType;
break;
}
case "success": {
const json = _json;
json.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 {
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 json = _json;
const pattern = schema._zod.pattern;
if (!pattern) throw new Error("Pattern not found in template literal");
json.type = "string";
json.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;
}
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;
}
default: {}
}
}
}
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) (_a$2 = result.schema).default ?? (_a$2.default = result.schema._prefault);
delete result.schema._prefault;
const _result = this.seen.get(schema);
return _result.schema;
}
emit(schema, _params) {
const params = {
cycles: _params?.cycles ?? "ref",
reused: _params?.reused ?? "inline",
external: _params?.external ?? void 0
};
const root = this.seen.get(schema);
if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
const makeURI = (entry) => {
const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
if (params.external) {
const externalId = params.external.registry.get(entry[0])?.id;
const uriGenerator = params.external.uri ?? ((id$2) => id$2);
if (externalId) return { ref: uriGenerator(externalId) };
const id$1 = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
entry[1].defId = id$1;
return {
defId: id$1,
ref: `${uriGenerator("__shared")}#/${defsSegment}/${id$1}`
};
}
if (entry[1] === root) return { ref: "#" };
const uriPrefix = `#`;
const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
const defId = entry[1].schema.id ?? `__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 = { ...seen.schema };
if (defId) seen.defId = defId;
const schema$1 = seen.schema;
for (const key in schema$1) delete schema$1[key];
schema$1.$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: #/${seen.cycle?.join("/")}/<root>
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 = params.external.registry.get(entry[0])?.id;
if (schema !== entry[0] && ext) {
extractToDef(entry);
continue;
}
}
const id$1 = this.metadataRegistry.get(entry[0])?.id;
if (id$1) {
extractToDef(entry);
continue;
}
if (seen.cycle) {
extractToDef(entry);
continue;
}
if (seen.count > 1) {
if (params.reused === "ref") {
extractToDef(entry);
continue;
}
}
}
const flattenRef = (zodSchema$1, params$1) => {
const seen = this.seen.get(zodSchema$1);
const schema$1 = seen.def ?? seen.schema;
const _cached = { ...schema$1 };
if (seen.ref === null) return;
const ref = seen.ref;
seen.ref = null;
if (ref) {
flattenRef(ref, params$1);
const refSchema = this.seen.get(ref).schema;
if (refSchema.$ref && params$1.target === "draft-7") {
schema$1.allOf = schema$1.allOf ?? [];
schema$1.allOf.push(refSchema);
} else {
Object.assign(schema$1, refSchema);
Object.assign(schema$1, _cached);
}
}
if (!seen.isParent) this.override({
zodSchema: zodSchema$1,
jsonSchema: schema$1,
path: seen.path ?? []
});
};
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 console.warn(`Invalid target: ${this.target}`);
if (params.external?.uri) {
const id$1 = params.external.registry.get(schema)?.id;
if (!id$1) throw new Error("Schema is missing an `id` property");
result.$id = params.external.uri(id$1);
}
Object.assign(result, root.def);
const defs = params.external?.defs ?? {};
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 gen$1 = new JSONSchemaGenerator(_params);
const defs = {};
for (const entry of input._idmap.entries()) {
const [_$3, schema] = entry;
gen$1.process(schema);
}
const schemas = {};
const external = {
registry: input,
uri: _params?.uri,
defs
};
for (const entry of input._idmap.entries()) {
const [key, schema] = entry;
schemas[key] = gen$1.emit(schema, {
..._params,
external
});
}
if (Object.keys(defs).length > 0) {
const defsSegment = gen$1.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 ?? { seen: 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 key in def.shape) if (isTransforming(def.shape[key], 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);
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;
default:
}
throw new Error(`Unknown schema type: ${def.type}`);
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/classic/iso.js
const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
$ZodISODateTime.init(inst, def);
ZodStringFormat.init(inst, def);
});
function datetime(params) {
return _isoDateTime(ZodISODateTime, params);
}
const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
$ZodISODate.init(inst, def);
ZodStringFormat.init(inst, def);
});
function date(params) {
return _isoDate(ZodISODate, params);
}
const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
$ZodISOTime.init(inst, def);
ZodStringFormat.init(inst, def);
});
function time(params) {
return _isoTime(ZodISOTime, params);
}
const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
$ZodISODuration.init(inst, def);
ZodStringFormat.init(inst, def);
});
function duration(params) {
return _isoDuration(ZodISODuration, params);
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/classic/errors.js
const initializer = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
Object.defineProperties(inst, {
format: { value: (mapper) => formatError(inst, mapper) },
flatten: { value: (mapper) => flattenError(inst, mapper) },
addIssue: { value: (issue$1) => inst.issues.push(issue$1) },
addIssues: { value: (issues$1) => inst.issues.push(...issues$1) },
isEmpty: { get() {
return inst.issues.length === 0;
} }
});
};
const ZodError$1 = $constructor("ZodError", initializer);
const ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/classic/parse.js
const parse = /* @__PURE__ */ _parse$1(ZodRealError);
const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/classic/schemas.js
const ZodType$1 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
$ZodType.init(inst, def);
inst.def = def;
Object.defineProperty(inst, "_def", { value: def });
inst.check = (...checks) => {
return inst.clone({
...def,
checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
check: ch,
def: { check: "custom" },
onattach: []
} } : ch)]
});
};
inst.clone = (def$1, params) => clone(inst, def$1, params);
inst.brand = () => inst;
inst.register = (reg, meta) => {
reg.add(inst, meta);
return inst;
};
inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
inst.safeParse = (data, params) => safeParse(inst, data, params);
inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
inst.spa = inst.safeParseAsync;
inst.refine = (check$1, params) => inst.check(refine(check$1, params));
inst.superRefine = (refinement) => inst.check(superRefine(refinement));
inst.overwrite = (fn$1) => inst.check(_overwrite(fn$1));
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 = (def$1) => _default(inst, def$1);
inst.prefault = (def$1) => prefault(inst, def$1);
inst.catch = (params) => _catch(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() {
return globalRegistry.get(inst)?.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;
});
/** @internal */
const _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
$ZodString.init(inst, def);
ZodType$1.init(inst, def);
const bag = inst._zod.bag;
inst.format = bag.format ?? null;
inst.minLength = bag.minimum ?? null;
inst.maxLength = bag.maximum ?? 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());
});
const ZodString$1 = /* @__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(_emoji(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(datetime(params));
inst.date = (params) => inst.check(date(params));
inst.time = (params) => inst.check(time(params));
inst.duration = (params) => inst.check(duration(params));
});
function string(params) {
return _string(ZodString$1, params);
}
const ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
$ZodStringFormat.init(inst, def);
_ZodString.init(inst, def);
});
const ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
$ZodEmail.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
$ZodGUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
$ZodUUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
$ZodURL.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
$ZodEmoji.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
$ZodNanoID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
$ZodCUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
$ZodCUID2.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
$ZodULID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
$ZodXID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
$ZodKSUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
$ZodIPv4.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
$ZodIPv6.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
$ZodCIDRv4.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
$ZodCIDRv6.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
$ZodBase64.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
$ZodBase64URL.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
$ZodE164.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
$ZodJWT.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodNumber$1 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
$ZodNumber.init(inst, def);
ZodType$1.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 = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
inst.isFinite = true;
inst.format = bag.format ?? null;
});
function number(params) {
return _number(ZodNumber$1, params);
}
const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
$ZodNumberFormat.init(inst, def);
ZodNumber$1.init(inst, def);
});
function int(params) {
return _int(ZodNumberFormat, params);
}
const ZodBoolean$1 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
$ZodBoolean.init(inst, def);
ZodType$1.init(inst, def);
});
function boolean(params) {
return _boolean(ZodBoolean$1, params);
}
const ZodNull$1 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
$ZodNull.init(inst, def);
ZodType$1.init(inst, def);
});
function _null(params) {
return _null$1(ZodNull$1, params);
}
const ZodUnknown$1 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
$ZodUnknown.init(inst, def);
ZodType$1.init(inst, def);
});
function unknown() {
return _unknown(ZodUnknown$1);
}
const ZodNever$1 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
$ZodNever.init(inst, def);
ZodType$1.init(inst, def);
});
function never(params) {
return _never(ZodNever$1, params);
}
const ZodArray$1 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
$ZodArray.init(inst, def);
ZodType$1.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$1, element, params);
}
const ZodObject$1 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
$ZodObject.init(inst, def);
ZodType$1.init(inst, def);
defineLazy(inst, "shape", () => def.shape);
inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
inst.catchall = (catchall) => inst.clone({
...inst._zod.def,
catchall
});
inst.passthrough = () => inst.clone({
...inst._zod.def,
catchall: unknown()
});
inst.loose = () => inst.clone({
...inst._zod.def,
catchall: unknown()
});
inst.strict = () => inst.clone({
...inst._zod.def,
catchall: never()
});
inst.strip = () => inst.clone({
...inst._zod.def,
catchall: void 0
});
inst.extend = (incoming) => {
return extend(inst, incoming);
};
inst.merge = (other) => merge(inst, other);
inst.pick = (mask) => pick(inst, mask);
inst.omit = (mask) => omit(inst, mask);
inst.partial = (...args) => partial(ZodOptional$1, inst, args[0]);
inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
});
function object$1(shape, params) {
const def = {
type: "object",
get shape() {
assignProp(this, "shape", { ...shape });
return this.shape;
},
...normalizeParams(params)
};
return new ZodObject$1(def);
}
function strictObject(shape, params) {
return new ZodObject$1({
type: "object",
get shape() {
assignProp(this, "shape", { ...shape });
return this.shape;
},
catchall: never(),
...normalizeParams(params)
});
}
const ZodUnion$1 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
$ZodUnion.init(inst, def);
ZodType$1.init(inst, def);
inst.options = def.options;
});
function union(options, params) {
return new ZodUnion$1({
type: "union",
options,
...normalizeParams(params)
});
}
const ZodDiscriminatedUnion$1 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
ZodUnion$1.init(inst, def);
$ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator, options, params) {
return new ZodDiscriminatedUnion$1({
type: "union",
options,
discriminator,
...normalizeParams(params)
});
}
const ZodIntersection$1 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
$ZodIntersection.init(inst, def);
ZodType$1.init(inst, def);
});
function intersection(left, right) {
return new ZodIntersection$1({
type: "intersection",
left,
right
});
}
const ZodRecord$1 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
$ZodRecord.init(inst, def);
ZodType$1.init(inst, def);
inst.keyType = def.keyType;
inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
return new ZodRecord$1({
type: "record",
keyType,
valueType,
...normalizeParams(params)
});
}
const ZodEnum$1 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
$ZodEnum.init(inst, def);
ZodType$1.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$1({
...def,
checks: [],
...normalizeParams(params),
entries: newEntries
});
};
inst.exclude = (values, params) => {
const newEntries = { ...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$1({
...def,
checks: [],
...normalizeParams(params),
entries: newEntries
});
};
});
function _enum(values, params) {
const entries = Array.isArray(values) ? Object.fromEntries(values.map((v$3) => [v$3, v$3])) : values;
return new ZodEnum$1({
type: "enum",
entries,
...normalizeParams(params)
});
}
const ZodLiteral$1 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
$ZodLiteral.init(inst, def);
ZodType$1.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 literal(value, params) {
return new ZodLiteral$1({
type: "literal",
values: Array.isArray(value) ? value : [value],
...normalizeParams(params)
});
}
const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
$ZodTransform.init(inst, def);
ZodType$1.init(inst, def);
inst._zod.parse = (payload, _ctx) => {
payload.addIssue = (issue$1) => {
if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def));
else {
const _issue = issue$1;
if (_issue.fatal) _issue.continue = false;
_issue.code ?? (_issue.code = "custom");
_issue.input ?? (_issue.input = payload.value);
_issue.inst ?? (_issue.inst = inst);
_issue.continue ?? (_issue.continue = true);
payload.issues.push(issue(_issue));
}
};
const output = def.transform(payload.value, payload);
if (output instanceof Promise) return output.then((output$1) => {
payload.value = output$1;
return payload;
});
payload.value = output;
return payload;
};
});
function transform(fn$1) {
return new ZodTransform({
type: "transform",
transform: fn$1
});
}
const ZodOptional$1 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
$ZodOptional.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
return new ZodOptional$1({
type: "optional",
innerType
});
}
const ZodNullable$1 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
$ZodNullable.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
return new ZodNullable$1({
type: "nullable",
innerType
});
}
const ZodDefault$1 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
$ZodDefault.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
inst.removeDefault = inst.unwrap;
});
function _default(innerType, defaultValue) {
return new ZodDefault$1({
type: "default",
innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : defaultValue;
}
});
}
const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
$ZodPrefault.init(inst, def);
ZodType$1.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() : defaultValue;
}
});
}
const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
$ZodNonOptional.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
return new ZodNonOptional({
type: "nonoptional",
innerType,
...normalizeParams(params)
});
}
const ZodCatch$1 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
$ZodCatch.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
inst.removeCatch = inst.unwrap;
});
function _catch(innerType, catchValue) {
return new ZodCatch$1({
type: "catch",
innerType,
catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
});
}
const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
$ZodPipe.init(inst, def);
ZodType$1.init(inst, def);
inst.in = def.in;
inst.out = def.out;
});
function pipe(in_, out) {
return new ZodPipe({
type: "pipe",
in: in_,
out
});
}
const ZodReadonly$1 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
$ZodReadonly.init(inst, def);
ZodType$1.init(inst, def);
});
function readonly(innerType) {
return new ZodReadonly$1({
type: "readonly",
innerType
});
}
const ZodLazy$1 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => {
$ZodLazy.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.getter();
});
function lazy(getter) {
return new ZodLazy$1({
type: "lazy",
getter
});
}
const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
$ZodCustom.init(inst, def);
ZodType$1.init(inst, def);
});
function check(fn$1) {
const ch = new $ZodCheck({ check: "custom" });
ch._zod.check = fn$1;
return ch;
}
function custom(fn$1, _params) {
return _custom(ZodCustom, fn$1 ?? (() => true), _params);
}
function refine(fn$1, _params = {}) {
return _refine(ZodCustom, fn$1, _params);
}
function superRefine(fn$1) {
const ch = check((payload) => {
payload.addIssue = (issue$1) => {
if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
else {
const _issue = issue$1;
if (_issue.fatal) _issue.continue = false;
_issue.code ?? (_issue.code = "custom");
_issue.input ?? (_issue.input = payload.value);
_issue.inst ?? (_issue.inst = ch);
_issue.continue ?? (_issue.continue = !ch._zod.def.abort);
payload.issues.push(issue(_issue));
}
};
return fn$1(payload.value, payload);
});
return ch;
}
function _instanceof(cls, params = { error: `Input not instance of ${cls.name}` }) {
const inst = new ZodCustom({
type: "custom",
check: "custom",
fn: (data) => data instanceof cls,
abort: true,
...normalizeParams(params)
});
inst._zod.bag.Class = cls;
return inst;
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/util.js
var util;
(function(util$1) {
util$1.assertEqual = (_$3) => {};
function assertIs(_arg) {}
util$1.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util$1.assertNever = assertNever;
util$1.arrayToEnum = (items) => {
const obj = {};
for (const item of items) obj[item] = item;
return obj;
};
util$1.getValidEnumValues = (obj) => {
const validKeys = util$1.objectKeys(obj).filter((k$4) => typeof obj[obj[k$4]] !== "number");
const filtered = {};
for (const k$4 of validKeys) filtered[k$4] = obj[k$4];
return util$1.objectValues(filtered);
};
util$1.objectValues = (obj) => {
return util$1.objectKeys(obj).map(function(e$2) {
return obj[e$2];
});
};
util$1.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object$2) => {
const keys = [];
for (const key in object$2) if (Object.prototype.hasOwnProperty.call(object$2, key)) keys.push(key);
return keys;
};
util$1.find = (arr, checker) => {
for (const item of arr) if (checker(item)) return item;
return void 0;
};
util$1.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array$1, separator = " | ") {
return array$1.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util$1.joinValues = joinValues;
util$1.jsonStringifyReplacer = (_$3, value) => {
if (typeof value === "bigint") return value.toString();
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil$1) {
objectUtil$1.mergeShapes = (first, second) => {
return {
...first,
...second
};
};
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
const getParsedType = (data) => {
const t$2 = typeof data;
switch (t$2) {
case "undefined": return ZodParsedType.undefined;
case "string": return ZodParsedType.string;
case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean": return ZodParsedType.boolean;
case "function": return ZodParsedType.function;
case "bigint": return ZodParsedType.bigint;
case "symbol": return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) return ZodParsedType.array;
if (data === null) return ZodParsedType.null;
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") return ZodParsedType.promise;
if (typeof Map !== "undefined" && data instanceof Map) return ZodParsedType.map;
if (typeof Set !== "undefined" && data instanceof Set) return ZodParsedType.set;
if (typeof Date !== "undefined" && data instanceof Date) return ZodParsedType.date;
return ZodParsedType.object;
default: return ZodParsedType.unknown;
}
};
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/ZodError.js
const ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var ZodError = class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
else this.__proto__ = actualProto;
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue$1) {
return issue$1.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue$1 of error.issues) if (issue$1.code === "invalid_union") issue$1.unionErrors.map(processError);
else if (issue$1.code === "invalid_return_type") processError(issue$1.returnTypeError);
else if (issue$1.code === "invalid_arguments") processError(issue$1.argumentsError);
else if (issue$1.path.length === 0) fieldErrors._errors.push(mapper(issue$1));
else {
let curr = fieldErrors;
let i$3 = 0;
while (i$3 < issue$1.path.length) {
const el = issue$1.path[i$3];
const terminal = i$3 === issue$1.path.length - 1;
if (!terminal) curr[el] = curr[el] || { _errors: [] };
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue$1));
}
curr = curr[el];
i$3++;
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue$1) => issue$1.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) if (sub.path.length > 0) {
const firstEl = sub.path[0];
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else formErrors.push(mapper(sub));
return {
formErrors,
fieldErrors
};
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/locales/en.js
const errorMap = (issue$1, _ctx) => {
let message;
switch (issue$1.code) {
case ZodIssueCode.invalid_type:
if (issue$1.received === ZodParsedType.undefined) message = "Required";
else message = `Expected ${issue$1.expected}, received ${issue$1.received}`;
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue$1.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue$1.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue$1.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue$1.options)}, received '${issue$1.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue$1.validation === "object") if ("includes" in issue$1.validation) {
message = `Invalid input: must include "${issue$1.validation.includes}"`;
if (typeof issue$1.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue$1.validation.position}`;
} else if ("startsWith" in issue$1.validation) message = `Invalid input: must start with "${issue$1.validation.startsWith}"`;
else if ("endsWith" in issue$1.validation) message = `Invalid input: must end with "${issue$1.validation.endsWith}"`;
else util.assertNever(issue$1.validation);
else if (issue$1.validation !== "regex") message = `Invalid ${issue$1.validation}`;
else message = "Invalid";
break;
case ZodIssueCode.too_small:
if (issue$1.type === "array") message = `Array must contain ${issue$1.exact ? "exactly" : issue$1.inclusive ? `at least` : `more than`} ${issue$1.minimum} element(s)`;
else if (issue$1.type === "string") message = `String must contain ${issue$1.exact ? "exactly" : issue$1.inclusive ? `at least` : `over`} ${issue$1.minimum} character(s)`;
else if (issue$1.type === "number") message = `Number must be ${issue$1.exact ? `exactly equal to ` : issue$1.inclusive ? `greater than or equal to ` : `greater than `}${issue$1.minimum}`;
else if (issue$1.type === "bigint") message = `Number must be ${issue$1.exact ? `exactly equal to ` : issue$1.inclusive ? `greater than or equal to ` : `greater than `}${issue$1.minimum}`;
else if (issue$1.type === "date") message = `Date must be ${issue$1.exact ? `exactly equal to ` : issue$1.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue$1.minimum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue$1.type === "array") message = `Array must contain ${issue$1.exact ? `exactly` : issue$1.inclusive ? `at most` : `less than`} ${issue$1.maximum} element(s)`;
else if (issue$1.type === "string") message = `String must contain ${issue$1.exact ? `exactly` : issue$1.inclusive ? `at most` : `under`} ${issue$1.maximum} character(s)`;
else if (issue$1.type === "number") message = `Number must be ${issue$1.exact ? `exactly` : issue$1.inclusive ? `less than or equal to` : `less than`} ${issue$1.maximum}`;
else if (issue$1.type === "bigint") message = `BigInt must be ${issue$1.exact ? `exactly` : issue$1.inclusive ? `less than or equal to` : `less than`} ${issue$1.maximum}`;
else if (issue$1.type === "date") message = `Date must be ${issue$1.exact ? `exactly` : issue$1.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue$1.maximum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue$1.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue$1);
}
return { message };
};
var en_default = errorMap;
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/errors.js
let overrideErrorMap = en_default;
function getErrorMap() {
return overrideErrorMap;
}
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
const makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0) return {
...issueData,
path: fullPath,
message: issueData.message
};
let errorMessage$1 = "";
const maps = errorMaps.filter((m$4) => !!m$4).slice().reverse();
for (const map of maps) errorMessage$1 = map(fullIssue, {
data,
defaultError: errorMessage$1
}).message;
return {
...issueData,
path: fullPath,
message: errorMessage$1
};
};
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue$1 = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === en_default ? void 0 : en_default
].filter((x$4) => !!x$4)
});
ctx.common.issues.push(issue$1);
}
var ParseStatus = class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid") this.value = "dirty";
}
abort() {
if (this.value !== "aborted") this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s$2 of results) {
if (s$2.status === "aborted") return INVALID;
if (s$2.status === "dirty") status.dirty();
arrayValue.push(s$2.value);
}
return {
status: status.value,
value: arrayValue
};
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted") return INVALID;
if (value.status === "aborted") return INVALID;
if (key.status === "dirty") status.dirty();
if (value.status === "dirty") status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
}
return {
status: status.value,
value: finalObject
};
}
};
const INVALID = Object.freeze({ status: "aborted" });
const DIRTY = (value) => ({
status: "dirty",
value
});
const OK = (value) => ({
status: "valid",
value
});
const isAborted = (x$4) => x$4.status === "aborted";
const isDirty = (x$4) => x$4.status === "dirty";
const isValid = (x$4) => x$4.status === "valid";
const isAsync = (x$4) => typeof Promise !== "undefined" && x$4 instanceof Promise;
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil$1) {
errorUtil$1.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil$1.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));
//#endregion
//#region ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/types.js
var ParseInputLazyPath = class {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
else this._cachedPath.push(...this._path, this._key);
return this._cachedPath;
}
};
const handleResult = (ctx, result) => {
if (isValid(result)) return {
success: true,
data: result.value
};
else {
if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
return {
success: false,
get error() {
if (this._error) return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params) return {};
const { errorMap: errorMap$1, invalid_type_error, required_error, description } = params;
if (errorMap$1 && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
if (errorMap$1) return {
errorMap: errorMap$1,
description
};
const customMap = (iss, ctx) => {
const { message } = params;
if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError };
if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError };
if (iss.code !== "invalid_type") return { message: ctx.defaultError };
return { message: message ?? invalid_type_error ?? ctx.defaultError };
};
return {
errorMap: customMap,
description
};
}
var ZodType = class {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) throw new Error("Synchronous parse encountered promise.");
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success) return result.data;
throw result.error;
}
safeParse(data, params) {
const ctx = {
common: {
issues: [],
async: params?.async ?? false,
contextualErrorMap: params?.errorMap
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({
data,
path: ctx.path,
parent: ctx
});
return handleResult(ctx, result);
}
"~validate"(data) {
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
if (!this["~standard"].async) try {
const result = this._parseSync({
data,
path: [],
parent: ctx
});
return isValid(result) ? { value: result.value } : { issues: ctx.common.issues };
} catch (err) {
if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
ctx.common = {
issues: [],
async: true
};
}
return this._parseAsync({
data,
path: [],
parent: ctx
}).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues });
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success) return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params?.errorMap,
async: true
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({
data,
path: ctx.path,
parent: ctx
});
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check$1, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") return { message };
else if (typeof message === "function") return message(val);
else return message;
};
return this._refinement((val, ctx) => {
const result = check$1(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data) => {
if (!data) {
setError();
return false;
} else return true;
});
if (!result) {
setError();
return false;
} else return true;
});
}
refinement(check$1, refinementData) {
return this._refinement((val, ctx) => {
if (!check$1(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else return true;
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: {
type: "refinement",
refinement
}
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
/** Alias of safeParseAsync */
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform$1) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: {
type: "transform",
transform: transform$1
}
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex$1;
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = `[0-5]\\d`;
if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version$2) {
if ((version$2 === "v4" || !version$2) && ipv4Regex.test(ip)) return true;
if ((version$2 === "v6" || !version$2) && ipv6Regex.test(ip)) return true;
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt)) return false;
try {
const [header] = jwt.split(".");
if (!header) return false;
const base64$1 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64$1));
if (typeof decoded !== "object" || decoded === null) return false;
if ("typ" in decoded && decoded?.typ !== "JWT") return false;
if (!decoded.alg) return false;
if (alg && decoded.alg !== alg) return false;
return true;
} catch {
return false;
}
}
function isValidCidr(ip, version$2) {
if ((version$2 === "v4" || !version$2) && ipv4CidrRegex.test(ip)) return true;
if ((version$2 === "v6" || !version$2) && ipv6CidrRegex.test(ip)) return true;
return false;
}
var ZodString = class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = String(input.data);
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx$1.parsedType
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check$1 of this._def.checks) if (check$1.kind === "min") {
if (input.data.length < check$1.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check$1.value,
type: "string",
inclusive: true,
exact: false,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "max") {
if (input.data.length > check$1.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check$1.value,
type: "string",
inclusive: true,
exact: false,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "length") {
const tooBig = input.data.length > check$1.value;
const tooSmall = input.data.length < check$1.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check$1.value,
type: "string",
inclusive: true,
exact: true,
message: check$1.message
});
else if (tooSmall) addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check$1.value,
type: "string",
inclusive: true,
exact: true,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "emoji") {
if (!emojiRegex$1) emojiRegex$1 = new RegExp(_emojiRegex, "u");
if (!emojiRegex$1.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "url") try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
else if (check$1.kind === "regex") {
check$1.regex.lastIndex = 0;
const testResult = check$1.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "trim") input.data = input.data.trim();
else if (check$1.kind === "includes") {
if (!input.data.includes(check$1.value, check$1.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: {
includes: check$1.value,
position: check$1.position
},
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "toLowerCase") input.data = input.data.toLowerCase();
else if (check$1.kind === "toUpperCase") input.data = input.data.toUpperCase();
else if (check$1.kind === "startsWith") {
if (!input.data.startsWith(check$1.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check$1.value },
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "endsWith") {
if (!input.data.endsWith(check$1.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check$1.value },
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "datetime") {
const regex = datetimeRegex(check$1);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "time") {
const regex = timeRegex(check$1);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "ip") {
if (!isValidIP(input.data, check$1.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "jwt") {
if (!isValidJWT(input.data, check$1.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "cidr") {
if (!isValidCidr(input.data, check$1.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check$1.message
});
status.dirty();
}
} else util.assertNever(check$1);
return {
status: status.value,
value: input.data
};
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_addCheck(check$1) {
return new ZodString({
...this._def,
checks: [...this._def.checks, check$1]
});
}
email(message) {
return this._addCheck({
kind: "email",
...errorUtil.errToObj(message)
});
}
url(message) {
return this._addCheck({
kind: "url",
...errorUtil.errToObj(message)
});
}
emoji(message) {
return this._addCheck({
kind: "emoji",
...errorUtil.errToObj(message)
});
}
uuid(message) {
return this._addCheck({
kind: "uuid",
...errorUtil.errToObj(message)
});
}
nanoid(message) {
return this._addCheck({
kind: "nanoid",
...errorUtil.errToObj(message)
});
}
cuid(message) {
return this._addCheck({
kind: "cuid",
...errorUtil.errToObj(message)
});
}
cuid2(message) {
return this._addCheck({
kind: "cuid2",
...errorUtil.errToObj(message)
});
}
ulid(message) {
return this._addCheck({
kind: "ulid",
...errorUtil.errToObj(message)
});
}
base64(message) {
return this._addCheck({
kind: "base64",
...errorUtil.errToObj(message)
});
}
base64url(message) {
return this._addCheck({
kind: "base64url",
...errorUtil.errToObj(message)
});
}
jwt(options) {
return this._addCheck({
kind: "jwt",
...errorUtil.errToObj(options)
});
}
ip(options) {
return this._addCheck({
kind: "ip",
...errorUtil.errToObj(options)
});
}
cidr(options) {
return this._addCheck({
kind: "cidr",
...errorUtil.errToObj(options)
});
}
datetime(options) {
if (typeof options === "string") return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
return this._addCheck({
kind: "datetime",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
offset: options?.offset ?? false,
local: options?.local ?? false,
...errorUtil.errToObj(options?.message)
});
}
date(message) {
return this._addCheck({
kind: "date",
message
});
}
time(options) {
if (typeof options === "string") return this._addCheck({
kind: "time",
precision: null,
message: options
});
return this._addCheck({
kind: "time",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
...errorUtil.errToObj(options?.message)
});
}
duration(message) {
return this._addCheck({
kind: "duration",
...errorUtil.errToObj(message)
});
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options?.position,
...errorUtil.errToObj(options?.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
/**
* Equivalent to `.min(1)`
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
};
ZodString.create = (params) => {
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / 10 ** decCount;
}
var ZodNumber = class ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) input.data = Number(input.data);
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx$1.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check$1 of this._def.checks) if (check$1.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "min") {
const tooSmall = check$1.inclusive ? input.data < check$1.value : input.data <= check$1.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check$1.value,
type: "number",
inclusive: check$1.inclusive,
exact: false,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "max") {
const tooBig = check$1.inclusive ? input.data > check$1.value : input.data >= check$1.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check$1.value,
type: "number",
inclusive: check$1.inclusive,
exact: false,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check$1.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check$1.value,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check$1.message
});
status.dirty();
}
} else util.assertNever(check$1);
return {
status: status.value,
value: input.data
};
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, {
kind,
value,
inclusive,
message: errorUtil.toString(message)
}]
});
}
_addCheck(check$1) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, check$1]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
else if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
var ZodBigInt = class ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) try {
input.data = BigInt(input.data);
} catch {
return this._getInvalidInput(input);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) return this._getInvalidInput(input);
let ctx = void 0;
const status = new ParseStatus();
for (const check$1 of this._def.checks) if (check$1.kind === "min") {
const tooSmall = check$1.inclusive ? input.data < check$1.value : input.data <= check$1.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check$1.value,
inclusive: check$1.inclusive,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "max") {
const tooBig = check$1.inclusive ? input.data > check$1.value : input.data >= check$1.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check$1.value,
inclusive: check$1.inclusive,
message: check$1.message
});
status.dirty();
}
} else if (check$1.kind === "multipleOf") {
if (input.data % check$1.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check$1.value,
message: check$1.message
});
status.dirty();
}
} else util.assertNever(check$1);
return {
status: status.value,
value: input.data
};
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, {
kind,
value,
inclusive,
message: errorUtil.toString(message)
}]
});
}
_addCheck(check$1) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, check$1]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
};
ZodBigInt.create = (params) => {
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = Boolean(input.data);
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
var ZodDate = class ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = new Date(input.data);
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx$1.parsedType
});
return INVALID;
}
if (Number.isNaN(input.data.getTime())) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, { code: ZodIssueCode.invalid_date });
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check$1 of this._def.checks) if (check$1.kind === "min") {
if (input.data.getTime() < check$1.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check$1.message,
inclusive: true,
exact: false,
minimum: check$1.value,
type: "date"
});
status.dirty();
}
} else if (check$1.kind === "max") {
if (input.data.getTime() > check$1.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check$1.message,
inclusive: true,
exact: false,
maximum: check$1.value,
type: "date"
});
status.dirty();
}
} else util.assertNever(check$1);
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check$1) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check$1]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: params?.coerce || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
var ZodSymbol = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
var ZodUndefined = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
var ZodNull = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
var ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
var ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
var ZodVoid = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
var ZodArray = class ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) return Promise.all([...ctx.data].map((item, i$3) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i$3));
})).then((result$1) => {
return ParseStatus.mergeArray(status, result$1);
});
const result = [...ctx.data].map((item, i$3) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i$3));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: {
value: minLength,
message: errorUtil.toString(message)
}
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: {
value: maxLength,
message: errorUtil.toString(message)
}
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: {
value: len,
message: errorUtil.toString(message)
}
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape
});
} else if (schema instanceof ZodArray) return new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
});
else if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap()));
else if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap()));
else if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
else return schema;
}
var ZodObject = class ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
/**
* @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
* If you want to pass through unknown properties, use `.passthrough()` instead.
*/
this.nonstrict = this.passthrough;
/**
* @deprecated Use `.extend` instead
* */
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null) return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
this._cached = {
shape,
keys
};
return this._cached;
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx$1.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key);
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({
key: {
status: "valid",
value: key
},
value: {
status: "valid",
value: ctx.data[key]
}
});
else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
else return ParseStatus.mergeObjectSync(status, pairs);
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? { errorMap: (issue$1, ctx) => {
const defaultError = this._def.errorMap?.(issue$1, ctx).message ?? ctx.defaultError;
if (issue$1.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError };
return { message: defaultError };
} } : {}
});
}
strip() {
return new ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
extend(augmentation) {
return new ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
const merged = new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
setKey(key, schema) {
return this.augment({ [key]: schema });
}
catchall(index$1) {
return new ZodObject({
...this._def,
catchall: index$1
});
}
pick(mask) {
const shape = {};
for (const key of util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
return new ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
for (const key of util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key];
return new ZodObject({
...this._def,
shape: () => shape
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) newShape[key] = fieldSchema;
else newShape[key] = fieldSchema.optional();
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key];
else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) newField = newField._def.innerType;
newShape[key] = newField;
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
var ZodUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) if (result.result.status === "valid") return result.result;
for (const result of results) if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") return result;
else if (result.status === "dirty" && !dirty) dirty = {
result,
ctx: childCtx
};
if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues$1) => new ZodError(issues$1));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types, params) => {
return new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
const getDiscriminator = (type) => {
if (type instanceof ZodLazy) return getDiscriminator(type.schema);
else if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
else if (type instanceof ZodLiteral) return [type.value];
else if (type instanceof ZodEnum) return type.options;
else if (type instanceof ZodNativeEnum) return util.objectValues(type.enum);
else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
else if (type instanceof ZodUndefined) return [void 0];
else if (type instanceof ZodNull) return [null];
else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())];
else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())];
else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
else return [];
};
var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
else return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = new Map();
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
for (const value of discriminatorValues) {
if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
};
function mergeValues(a$2, b$3) {
const aType = getParsedType(a$2);
const bType = getParsedType(b$3);
if (a$2 === b$3) return {
valid: true,
data: a$2
};
else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b$3);
const sharedKeys = util.objectKeys(a$2).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = {
...a$2,
...b$3
};
for (const key of sharedKeys) {
const sharedValue = mergeValues(a$2[key], b$3[key]);
if (!sharedValue.valid) return { valid: false };
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a$2.length !== b$3.length) return { valid: false };
const newArray = [];
for (let index$1 = 0; index$1 < a$2.length; index$1++) {
const itemA = a$2[index$1];
const itemB = b$3[index$1];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) return { valid: false };
newArray.push(sharedValue.data);
}
return {
valid: true,
data: newArray
};
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a$2 === +b$3) return {
valid: true,
data: a$2
};
else return { valid: false };
}
var ZodIntersection = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID;
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types });
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty();
return {
status: status.value,
value: merged.data
};
};
if (ctx.common.async) return Promise.all([this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})]).then(([left, right]) => handleParsed(left, right));
else return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
};
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
var ZodTuple = class ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema) return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x$4) => !!x$4);
if (ctx.common.async) return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
else return ParseStatus.mergeArray(status, items);
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest
});
}
};
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
var ZodRecord = class ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs);
else return ParseStatus.mergeObjectSync(status, pairs);
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) return new ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
};
var ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index$1) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index$1, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index$1, "value"]))
};
});
if (ctx.common.async) {
const finalMap = new Map();
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") return INVALID;
if (key.status === "dirty" || value.status === "dirty") status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
});
} else {
const finalMap = new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") return INVALID;
if (key.status === "dirty" || value.status === "dirty") status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
var ZodSet = class ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements$1) {
const parsedSet = new Set();
for (const element of elements$1) {
if (element.status === "aborted") return INVALID;
if (element.status === "dirty") status.dirty();
parsedSet.add(element.value);
}
return {
status: status.value,
value: parsedSet
};
}
const elements = [...ctx.data.values()].map((item, i$3) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i$3)));
if (ctx.common.async) return Promise.all(elements).then((elements$1) => finalizeSet(elements$1));
else return finalizeSet(elements);
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: {
value: minSize,
message: errorUtil.toString(message)
}
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: {
value: maxSize,
message: errorUtil.toString(message)
}
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
var ZodFunction = class ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
en_default
].filter((x$4) => !!x$4),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
en_default
].filter((x$4) => !!x$4),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn$1 = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me$1 = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me$1._def.args.parseAsync(args, params).catch((e$2) => {
error.addIssue(makeArgsIssue(args, e$2));
throw error;
});
const result = await Reflect.apply(fn$1, this, parsedArgs);
const parsedReturns = await me$1._def.returns._def.type.parseAsync(result, params).catch((e$2) => {
error.addIssue(makeReturnsIssue(result, e$2));
throw error;
});
return parsedReturns;
});
} else {
const me$1 = this;
return OK(function(...args) {
const parsedArgs = me$1._def.args.safeParse(args, params);
if (!parsedArgs.success) throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
const result = Reflect.apply(fn$1, this, parsedArgs.data);
const parsedReturns = me$1._def.returns.safeParse(result, params);
if (!parsedReturns.success) throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
};
var ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return {
status: "valid",
value: input.data
};
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
var ZodEnum = class ZodEnum extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) this._cache = new Set(this._def.values);
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
extract(values, newDef = this._def) {
return ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) this._cache = new Set(util.getValidEnumValues(this._def.values));
if (!this._cache.has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
var ZodEffects = class extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) status.abort();
else status.dirty();
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) return Promise.resolve(processed).then(async (processed$1) => {
if (status.value === "aborted") return INVALID;
const result = await this._def.schema._parseAsync({
data: processed$1,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted") return INVALID;
if (result.status === "dirty") return DIRTY(result.value);
if (status.value === "dirty") return DIRTY(result.value);
return result;
});
else {
if (status.value === "aborted") return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted") return INVALID;
if (result.status === "dirty") return DIRTY(result.value);
if (status.value === "dirty") return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) return Promise.resolve(result);
if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted") return INVALID;
if (inner.status === "dirty") status.dirty();
executeRefinement(inner.value);
return {
status: status.value,
value: inner.value
};
} else return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((inner) => {
if (inner.status === "aborted") return INVALID;
if (inner.status === "dirty") status.dirty();
return executeRefinement(inner.value).then(() => {
return {
status: status.value,
value: inner.value
};
});
});
}
if (effect.type === "transform") if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base)) return INVALID;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
return {
status: status.value,
value: result
};
} else return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((base) => {
if (!isValid(base)) return INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
status: status.value,
value: result
}));
});
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: {
type: "preprocess",
transform: preprocess
},
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
var ZodOptional = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) return OK(void 0);
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
var ZodNullable = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) return OK(null);
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
var ZodDefault = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) data = this._def.defaultValue();
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
var ZodCatch = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: { ...newCtx }
});
if (isAsync(result)) return result.then((result$1) => {
return {
status: "valid",
value: result$1.status === "valid" ? result$1.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
else return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
var ZodNaN = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return {
status: "valid",
value: input.data
};
}
};
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
const BRAND = Symbol("zod_brand");
var ZodBranded = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
var ZodPipeline = class ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted") return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted") return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
static create(a$2, b$3) {
return new ZodPipeline({
in: a$2,
out: b$3,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
};
var ZodReadonly = class extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid(data)) data.value = Object.freeze(data.value);
return data;
};
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
const late = { object: ZodObject.lazycreate };
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind$1) {
ZodFirstPartyTypeKind$1["ZodString"] = "ZodString";
ZodFirstPartyTypeKind$1["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind$1["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind$1["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind$1["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind$1["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind$1["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind$1["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind$1["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind$1["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind$1["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind$1["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind$1["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind$1["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind$1["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind$1["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind$1["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind$1["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind$1["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind$1["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind$1["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind$1["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind$1["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind$1["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind$1["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind$1["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind$1["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind$1["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind$1["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind$1["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind$1["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind$1["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind$1["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind$1["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind$1["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind$1["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const stringType = ZodString.create;
const numberType = ZodNumber.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt.create;
const booleanType = ZodBoolean.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown.create;
const neverType = ZodNever.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = ZodObject.create;
const strictObjectType = ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
const intersectionType = ZodIntersection.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
//#endregion
//#region ../../node_modules/.bun/@ai-sdk+provider-utils@3.0.19+27912429049419a2/node_modules/@ai-sdk/provider-utils/dist/index.mjs
var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
const generator = () => {
const alphabetLength = alphabet.length;
const chars = new Array(size);
for (let i$3 = 0; i$3 < size; i$3++) chars[i$3] = alphabet[Math.random() * alphabetLength | 0];
return chars.join("");
};
if (prefix == null) return generator;
if (alphabet.includes(separator)) throw new InvalidArgumentError({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
return () => `${prefix}${separator}${generator()}`;
};
var generateId = createIdGenerator();
function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
var _a$2, _b, _c;
if (globalThisAny.window) return `runtime/browser`;
if ((_a$2 = globalThisAny.navigator) == null ? void 0 : _a$2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
if ((_c = (_b = globalThisAny.process) == null ? void 0 : _b.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
if (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`;
return "runtime/unknown";
}
function normalizeHeaders(headers) {
if (headers == null) return {};
const normalized = {};
if (headers instanceof Headers) headers.forEach((value, key) => {
normalized[key.toLowerCase()] = value;
});
else {
if (!Array.isArray(headers)) headers = Object.entries(headers);
for (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;
}
return normalized;
}
function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
const normalizedHeaders = new Headers(normalizeHeaders(headers));
const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
return Object.fromEntries(normalizedHeaders.entries());
}
var suspectProtoRx = /"__proto__"\s*:/;
var suspectConstructorRx = /"constructor"\s*:/;
function _parse(text$1) {
const obj = JSON.parse(text$1);
if (obj === null || typeof obj !== "object") return obj;
if (suspectProtoRx.test(text$1) === false && suspectConstructorRx.test(text$1) === false) return obj;
return filter(obj);
}
function filter(obj) {
let next = [obj];
while (next.length) {
const nodes = next;
next = [];
for (const node of nodes) {
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) throw new SyntaxError("Object contains forbidden prototype property");
if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) throw new SyntaxError("Object contains forbidden prototype property");
for (const key in node) {
const value = node[key];
if (value && typeof value === "object") next.push(value);
}
}
}
return obj;
}
function secureJsonParse(text$1) {
const { stackTraceLimit } = Error;
try {
Error.stackTraceLimit = 0;
} catch (e$2) {
return _parse(text$1);
}
try {
return _parse(text$1);
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
}
var validatorSymbol = Symbol.for("vercel.ai.validator");
function validator(validate) {
return {
[validatorSymbol]: true,
validate
};
}
function isValidator(value) {
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
}
function lazyValidator(createValidator) {
let validator2;
return () => {
if (validator2 == null) validator2 = createValidator();
return validator2;
};
}
function asValidator(value) {
return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
}
function standardSchemaValidator(standardSchema) {
return validator(async (value) => {
const result = await standardSchema["~standard"].validate(value);
return result.issues == null ? {
success: true,
value: result.value
} : {
success: false,
error: new TypeValidationError({
value,
cause: result.issues
})
};
});
}
async function validateTypes({ value, schema }) {
const result = await safeValidateTypes({
value,
schema
});
if (!result.success) throw TypeValidationError.wrap({
value,
cause: result.error
});
return result.value;
}
async function safeValidateTypes({ value, schema }) {
const validator2 = asValidator(schema);
try {
if (validator2.validate == null) return {
success: true,
value,
rawValue: value
};
const result = await validator2.validate(value);
if (result.success) return {
success: true,
value: result.value,
rawValue: value
};
return {
success: false,
error: TypeValidationError.wrap({
value,
cause: result.error
}),
rawValue: value
};
} catch (error) {
return {
success: false,
error: TypeValidationError.wrap({
value,
cause: error
}),
rawValue: value
};
}
}
async function safeParseJSON({ text: text$1, schema }) {
try {
const value = secureJsonParse(text$1);
if (schema == null) return {
success: true,
value,
rawValue: value
};
return await safeValidateTypes({
value,
schema
});
} catch (error) {
return {
success: false,
error: JSONParseError.isInstance(error) ? error : new JSONParseError({
text: text$1,
cause: error
}),
rawValue: void 0
};
}
}
function parseJsonEventStream({ stream, schema }) {
return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new TransformStream({ async transform({ data }, controller) {
if (data === "[DONE]") return;
controller.enqueue(await safeParseJSON({
text: data,
schema
}));
} }));
}
async function resolve(value) {
if (typeof value === "function") value = value();
return Promise.resolve(value);
}
function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
if (jsonSchema2.type === "object") {
jsonSchema2.additionalProperties = false;
const properties = jsonSchema2.properties;
if (properties != null) for (const property in properties) properties[property] = addAdditionalPropertiesToJsonSchema(properties[property]);
}
if (jsonSchema2.type === "array" && jsonSchema2.items != null) if (Array.isArray(jsonSchema2.items)) jsonSchema2.items = jsonSchema2.items.map((item) => addAdditionalPropertiesToJsonSchema(item));
else jsonSchema2.items = addAdditionalPropertiesToJsonSchema(jsonSchema2.items);
return jsonSchema2;
}
var getRelativePath = (pathA, pathB) => {
let i$3 = 0;
for (; i$3 < pathA.length && i$3 < pathB.length; i$3++) if (pathA[i$3] !== pathB[i$3]) break;
return [(pathA.length - i$3).toString(), ...pathB.slice(i$3)].join("/");
};
var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions = {
name: void 0,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
strictUnions: false,
definitions: {},
errorMessages: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
var getDefaultOptions = (options) => typeof options === "string" ? {
...defaultOptions,
name: options
} : {
...defaultOptions,
...options
};
function parseAnyDef() {
return {};
}
function parseArrayDef(def, refs) {
var _a$2, _b, _c;
const res = { type: "array" };
if (((_a$2 = def.type) == null ? void 0 : _a$2._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
if (def.minLength) res.minItems = def.minLength.value;
if (def.maxLength) res.maxItems = def.maxLength.value;
if (def.exactLength) {
res.minItems = def.exactLength.value;
res.maxItems = def.exactLength.value;
}
return res;
}
function parseBigintDef(def) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks) return res;
for (const check$1 of def.checks) switch (check$1.kind) {
case "min":
if (check$1.inclusive) res.minimum = check$1.value;
else res.exclusiveMinimum = check$1.value;
break;
case "max":
if (check$1.inclusive) res.maximum = check$1.value;
else res.exclusiveMaximum = check$1.value;
break;
case "multipleOf":
res.multipleOf = check$1.value;
break;
}
return res;
}
function parseBooleanDef() {
return { type: "boolean" };
}
function parseBrandedDef(_def, refs) {
return parseDef(_def.type._def, refs);
}
var parseCatchDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
function parseDateDef(def, refs, overrideDateStrategy) {
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
if (Array.isArray(strategy)) return { anyOf: strategy.map((item, i$3) => parseDateDef(def, refs, item)) };
switch (strategy) {
case "string":
case "format:date-time": return {
type: "string",
format: "date-time"
};
case "format:date": return {
type: "string",
format: "date"
};
case "integer": return integerDateParser(def);
}
}
var integerDateParser = (def) => {
const res = {
type: "integer",
format: "unix-time"
};
for (const check$1 of def.checks) switch (check$1.kind) {
case "min":
res.minimum = check$1.value;
break;
case "max":
res.maximum = check$1.value;
break;
}
return res;
};
function parseDefaultDef(_def, refs) {
return {
...parseDef(_def.innerType._def, refs),
default: _def.defaultValue()
};
}
function parseEffectsDef(_def, refs) {
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
}
function parseEnumDef(def) {
return {
type: "string",
enum: Array.from(def.values)
};
}
var isJsonSchema7AllOfType = (type) => {
if ("type" in type && type.type === "string") return false;
return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
const allOf = [parseDef(def.left._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
}), parseDef(def.right._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"1"
]
})].filter((x$4) => !!x$4);
const mergedAllOf = [];
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType(schema)) mergedAllOf.push(...schema.allOf);
else {
let nestedSchema = schema;
if ("additionalProperties" in schema && schema.additionalProperties === false) {
const { additionalProperties,...rest } = schema;
nestedSchema = rest;
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
}
function parseLiteralDef(def) {
const parsedType = typeof def.value;
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" };
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value
};
}
var emojiRegex = void 0;
var zodPatterns = {
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
emoji: () => {
if (emojiRegex === void 0) emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
return emojiRegex;
},
uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
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])$/,
ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/,
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef(def, refs) {
const res = { type: "string" };
if (def.checks) for (const check$1 of def.checks) switch (check$1.kind) {
case "min":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check$1.value) : check$1.value;
break;
case "max":
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check$1.value) : check$1.value;
break;
case "email":
switch (refs.emailStrategy) {
case "format:email":
addFormat(res, "email", check$1.message, refs);
break;
case "format:idn-email":
addFormat(res, "idn-email", check$1.message, refs);
break;
case "pattern:zod":
addPattern(res, zodPatterns.email, check$1.message, refs);
break;
}
break;
case "url":
addFormat(res, "uri", check$1.message, refs);
break;
case "uuid":
addFormat(res, "uuid", check$1.message, refs);
break;
case "regex":
addPattern(res, check$1.regex, check$1.message, refs);
break;
case "cuid":
addPattern(res, zodPatterns.cuid, check$1.message, refs);
break;
case "cuid2":
addPattern(res, zodPatterns.cuid2, check$1.message, refs);
break;
case "startsWith":
addPattern(res, RegExp(`^${escapeLiteralCheckValue(check$1.value, refs)}`), check$1.message, refs);
break;
case "endsWith":
addPattern(res, RegExp(`${escapeLiteralCheckValue(check$1.value, refs)}$`), check$1.message, refs);
break;
case "datetime":
addFormat(res, "date-time", check$1.message, refs);
break;
case "date":
addFormat(res, "date", check$1.message, refs);
break;
case "time":
addFormat(res, "time", check$1.message, refs);
break;
case "duration":
addFormat(res, "duration", check$1.message, refs);
break;
case "length":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check$1.value) : check$1.value;
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check$1.value) : check$1.value;
break;
case "includes": {
addPattern(res, RegExp(escapeLiteralCheckValue(check$1.value, refs)), check$1.message, refs);
break;
}
case "ip": {
if (check$1.version !== "v6") addFormat(res, "ipv4", check$1.message, refs);
if (check$1.version !== "v4") addFormat(res, "ipv6", check$1.message, refs);
break;
}
case "base64url":
addPattern(res, zodPatterns.base64url, check$1.message, refs);
break;
case "jwt":
addPattern(res, zodPatterns.jwt, check$1.message, refs);
break;
case "cidr": {
if (check$1.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check$1.message, refs);
if (check$1.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check$1.message, refs);
break;
}
case "emoji":
addPattern(res, zodPatterns.emoji(), check$1.message, refs);
break;
case "ulid": {
addPattern(res, zodPatterns.ulid, check$1.message, refs);
break;
}
case "base64": {
switch (refs.base64Strategy) {
case "format:binary": {
addFormat(res, "binary", check$1.message, refs);
break;
}
case "contentEncoding:base64": {
res.contentEncoding = "base64";
break;
}
case "pattern:zod": {
addPattern(res, zodPatterns.base64, check$1.message, refs);
break;
}
}
break;
}
case "nanoid": addPattern(res, zodPatterns.nanoid, check$1.message, refs);
case "toLowerCase":
case "toUpperCase":
case "trim": break;
default:
}
return res;
}
function escapeLiteralCheckValue(literal$1, refs) {
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal$1) : literal$1;
}
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(source) {
let result = "";
for (let i$3 = 0; i$3 < source.length; i$3++) {
if (!ALPHA_NUMERIC.has(source[i$3])) result += "\\";
result += source[i$3];
}
return result;
}
function addFormat(schema, value, message, refs) {
var _a$2;
if (schema.format || ((_a$2 = schema.anyOf) == null ? void 0 : _a$2.some((x$4) => x$4.format))) {
if (!schema.anyOf) schema.anyOf = [];
if (schema.format) {
schema.anyOf.push({ format: schema.format });
delete schema.format;
}
schema.anyOf.push({
format: value,
...message && refs.errorMessages && { errorMessage: { format: message } }
});
} else schema.format = value;
}
function addPattern(schema, regex, message, refs) {
var _a$2;
if (schema.pattern || ((_a$2 = schema.allOf) == null ? void 0 : _a$2.some((x$4) => x$4.pattern))) {
if (!schema.allOf) schema.allOf = [];
if (schema.pattern) {
schema.allOf.push({ pattern: schema.pattern });
delete schema.pattern;
}
schema.allOf.push({
pattern: stringifyRegExpWithFlags(regex, refs),
...message && refs.errorMessages && { errorMessage: { pattern: message } }
});
} else schema.pattern = stringifyRegExpWithFlags(regex, refs);
}
function stringifyRegExpWithFlags(regex, refs) {
var _a$2;
if (!refs.applyRegexFlags || !regex.flags) return regex.source;
const flags = {
i: regex.flags.includes("i"),
m: regex.flags.includes("m"),
s: regex.flags.includes("s")
};
const source = flags.i ? regex.source.toLowerCase() : regex.source;
let pattern = "";
let isEscaped = false;
let inCharGroup = false;
let inCharRange = false;
for (let i$3 = 0; i$3 < source.length; i$3++) {
if (isEscaped) {
pattern += source[i$3];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i$3].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i$3];
pattern += `${source[i$3 - 2]}-${source[i$3]}`.toUpperCase();
inCharRange = false;
} else if (source[i$3 + 1] === "-" && ((_a$2 = source[i$3 + 2]) == null ? void 0 : _a$2.match(/[a-z]/))) {
pattern += source[i$3];
inCharRange = true;
} else pattern += `${source[i$3]}${source[i$3].toUpperCase()}`;
continue;
}
} else if (source[i$3].match(/[a-z]/)) {
pattern += `[${source[i$3]}${source[i$3].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i$3] === "^") {
pattern += `(^|(?<=[\r
]))`;
continue;
} else if (source[i$3] === "$") {
pattern += `($|(?=[\r
]))`;
continue;
}
}
if (flags.s && source[i$3] === ".") {
pattern += inCharGroup ? `${source[i$3]}\r
` : `[${source[i$3]}\r
]`;
continue;
}
pattern += source[i$3];
if (source[i$3] === "\\") isEscaped = true;
else if (inCharGroup && source[i$3] === "]") inCharGroup = false;
else if (!inCharGroup && source[i$3] === "[") inCharGroup = true;
}
try {
new RegExp(pattern);
} catch (e$2) {
console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
return regex.source;
}
return pattern;
}
function parseRecordDef(def, refs) {
var _a$2, _b, _c, _d, _e$1, _f;
const schema = {
type: "object",
additionalProperties: (_a$2 = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
})) != null ? _a$2 : refs.allowedAdditionalProperties
};
if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
const { type,...keyType } = parseStringDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) return {
...schema,
propertyNames: { enum: def.keyType._def.values }
};
else if (((_e$1 = def.keyType) == null ? void 0 : _e$1._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
const { type,...keyType } = parseBrandedDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
}
return schema;
}
function parseMapDef(def, refs) {
if (refs.mapStrategy === "record") return parseRecordDef(def, refs);
const keys = parseDef(def.keyType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"0"
]
}) || parseAnyDef();
const values = parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"1"
]
}) || parseAnyDef();
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [keys, values],
minItems: 2,
maxItems: 2
}
};
}
function parseNativeEnumDef(def) {
const object$2 = def.values;
const actualKeys = Object.keys(def.values).filter((key) => {
return typeof object$2[object$2[key]] !== "number";
});
const actualValues = actualKeys.map((key) => object$2[key]);
const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
return {
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
enum: actualValues
};
}
function parseNeverDef() {
return { not: parseAnyDef() };
}
function parseNullDef() {
return { type: "null" };
}
var primitiveMappings = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null"
};
function parseUnionDef(def, refs) {
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
if (options.every((x$4) => x$4._def.typeName in primitiveMappings && (!x$4._def.checks || !x$4._def.checks.length))) {
const types = options.reduce((types2, x$4) => {
const type = primitiveMappings[x$4._def.typeName];
return type && !types2.includes(type) ? [...types2, type] : types2;
}, []);
return { type: types.length > 1 ? types : types[0] };
} else if (options.every((x$4) => x$4._def.typeName === "ZodLiteral" && !x$4.description)) {
const types = options.reduce((acc, x$4) => {
const type = typeof x$4._def.value;
switch (type) {
case "string":
case "number":
case "boolean": return [...acc, type];
case "bigint": return [...acc, "integer"];
case "object": if (x$4._def.value === null) return [...acc, "null"];
case "symbol":
case "undefined":
case "function":
default: return acc;
}
}, []);
if (types.length === options.length) {
const uniqueTypes = types.filter((x$4, i$3, a$2) => a$2.indexOf(x$4) === i$3);
return {
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
enum: options.reduce((acc, x$4) => {
return acc.includes(x$4._def.value) ? acc : [...acc, x$4._def.value];
}, [])
};
}
} else if (options.every((x$4) => x$4._def.typeName === "ZodEnum")) return {
type: "string",
enum: options.reduce((acc, x$4) => [...acc, ...x$4._def.values.filter((x2) => !acc.includes(x2))], [])
};
return asAnyOf(def, refs);
}
var asAnyOf = (def, refs) => {
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x$4, i$3) => parseDef(x$4._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
`${i$3}`
]
})).filter((x$4) => !!x$4 && (!refs.strictUnions || typeof x$4 === "object" && Object.keys(x$4).length > 0));
return anyOf.length ? { anyOf } : void 0;
};
function parseNullableDef(def, refs) {
if ([
"ZodString",
"ZodNumber",
"ZodBigInt",
"ZodBoolean",
"ZodNull"
].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { type: [primitiveMappings[def.innerType._def.typeName], "null"] };
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"0"
]
});
return base && { anyOf: [base, { type: "null" }] };
}
function parseNumberDef(def) {
const res = { type: "number" };
if (!def.checks) return res;
for (const check$1 of def.checks) switch (check$1.kind) {
case "int":
res.type = "integer";
break;
case "min":
if (check$1.inclusive) res.minimum = check$1.value;
else res.exclusiveMinimum = check$1.value;
break;
case "max":
if (check$1.inclusive) res.maximum = check$1.value;
else res.exclusiveMaximum = check$1.value;
break;
case "multipleOf":
res.multipleOf = check$1.value;
break;
}
return res;
}
function parseObjectDef(def, refs) {
const result = {
type: "object",
properties: {}
};
const required$1 = [];
const shape = def.shape();
for (const propName in shape) {
let propDef = shape[propName];
if (propDef === void 0 || propDef._def === void 0) continue;
const propOptional = safeIsOptional(propDef);
const parsedDef = parseDef(propDef._def, {
...refs,
currentPath: [
...refs.currentPath,
"properties",
propName
],
propertyPath: [
...refs.currentPath,
"properties",
propName
]
});
if (parsedDef === void 0) continue;
result.properties[propName] = parsedDef;
if (!propOptional) required$1.push(propName);
}
if (required$1.length) result.required = required$1;
const additionalProperties = decideAdditionalProperties(def, refs);
if (additionalProperties !== void 0) result.additionalProperties = additionalProperties;
return result;
}
function decideAdditionalProperties(def, refs) {
if (def.catchall._def.typeName !== "ZodNever") return parseDef(def.catchall._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
});
switch (def.unknownKeys) {
case "passthrough": return refs.allowedAdditionalProperties;
case "strict": return refs.rejectedAdditionalProperties;
case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
}
}
function safeIsOptional(schema) {
try {
return schema.isOptional();
} catch (e$2) {
return true;
}
}
var parseOptionalDef = (def, refs) => {
var _a$2;
if (refs.currentPath.toString() === ((_a$2 = refs.propertyPath) == null ? void 0 : _a$2.toString())) return parseDef(def.innerType._def, refs);
const innerSchema = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"1"
]
});
return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
};
var parsePipelineDef = (def, refs) => {
if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs);
else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs);
const a$2 = parseDef(def.in._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
});
const b$3 = parseDef(def.out._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
a$2 ? "1" : "0"
]
});
return { allOf: [a$2, b$3].filter((x$4) => x$4 !== void 0) };
};
function parsePromiseDef(def, refs) {
return parseDef(def.type._def, refs);
}
function parseSetDef(def, refs) {
const items = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
const schema = {
type: "array",
uniqueItems: true,
items
};
if (def.minSize) schema.minItems = def.minSize.value;
if (def.maxSize) schema.maxItems = def.maxSize.value;
return schema;
}
function parseTupleDef(def, refs) {
if (def.rest) return {
type: "array",
minItems: def.items.length,
items: def.items.map((x$4, i$3) => parseDef(x$4._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i$3}`
]
})).reduce((acc, x$4) => x$4 === void 0 ? acc : [...acc, x$4], []),
additionalItems: parseDef(def.rest._def, {
...refs,
currentPath: [...refs.currentPath, "additionalItems"]
})
};
else return {
type: "array",
minItems: def.items.length,
maxItems: def.items.length,
items: def.items.map((x$4, i$3) => parseDef(x$4._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i$3}`
]
})).reduce((acc, x$4) => x$4 === void 0 ? acc : [...acc, x$4], [])
};
}
function parseUndefinedDef() {
return { not: parseAnyDef() };
}
function parseUnknownDef() {
return parseAnyDef();
}
var parseReadonlyDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
var selectParser = (def, typeName, refs) => {
switch (typeName) {
case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);
case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def);
case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);
case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def);
case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();
case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);
case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef();
case ZodFirstPartyTypeKind.ZodNull: return parseNullDef();
case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);
case ZodFirstPartyTypeKind.ZodUnion:
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);
case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);
case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);
case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);
case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def);
case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);
case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);
case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);
case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);
case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);
case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);
case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);
case ZodFirstPartyTypeKind.ZodNaN:
case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef();
case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);
case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef();
case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef();
case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);
case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);
case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);
case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);
case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);
case ZodFirstPartyTypeKind.ZodFunction:
case ZodFirstPartyTypeKind.ZodVoid:
case ZodFirstPartyTypeKind.ZodSymbol: return void 0;
default: return /* @__PURE__ */ ((_$3) => void 0)(typeName);
}
};
function parseDef(def, refs, forceResolution = false) {
var _a$2;
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = (_a$2 = refs.override) == null ? void 0 : _a$2.call(refs, def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride) return overrideResult;
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref(seenItem, refs);
if (seenSchema !== void 0) return seenSchema;
}
const newItem = {
def,
path: refs.currentPath,
jsonSchema: void 0
};
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
if (jsonSchema2) addMeta(def, refs, jsonSchema2);
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
newItem.jsonSchema = jsonSchema2;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema2;
return jsonSchema2;
}
var get$ref = (item, refs) => {
switch (refs.$refStrategy) {
case "root": return { $ref: item.path.join("/") };
case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) };
case "none":
case "seen": {
if (item.path.length < refs.currentPath.length && item.path.every((value, index$1) => refs.currentPath[index$1] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return parseAnyDef();
}
return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
}
}
};
var addMeta = (def, refs, jsonSchema2) => {
if (def.description) jsonSchema2.description = def.description;
return jsonSchema2;
};
var getRefs = (options) => {
const _options = getDefaultOptions(options);
const currentPath = _options.name !== void 0 ? [
..._options.basePath,
_options.definitionPath,
_options.name
] : _options.basePath;
return {
..._options,
currentPath,
propertyPath: void 0,
seen: new Map(Object.entries(_options.definitions).map(([name$2, def]) => [def._def, {
def: def._def,
path: [
..._options.basePath,
_options.definitionPath,
name$2
],
jsonSchema: void 0
}]))
};
};
var zodToJsonSchema = (schema, options) => {
var _a$2;
const refs = getRefs(options);
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2$2, schema2]) => {
var _a2$2;
return {
...acc,
[name2$2]: (_a2$2 = parseDef(schema2._def, {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name2$2
]
}, true)) != null ? _a2$2 : parseAnyDef()
};
}, {}) : void 0;
const name$2 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
const main = (_a$2 = parseDef(schema._def, name$2 === void 0 ? refs : {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name$2
]
}, false)) != null ? _a$2 : parseAnyDef();
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
if (title !== void 0) main.title = title;
const combined = name$2 === void 0 ? definitions ? {
...main,
[refs.definitionPath]: definitions
} : main : {
$ref: [
...refs.$refStrategy === "relative" ? [] : refs.basePath,
refs.definitionPath,
name$2
].join("/"),
[refs.definitionPath]: {
...definitions,
[name$2]: main
}
};
combined.$schema = "http://json-schema.org/draft-07/schema#";
return combined;
};
var zod_to_json_schema_default = zodToJsonSchema;
function zod3Schema(zodSchema2, options) {
var _a$2;
const useReferences = (_a$2 = options == null ? void 0 : options.useReferences) != null ? _a$2 : false;
return jsonSchema(() => zod_to_json_schema_default(zodSchema2, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => {
const result = await zodSchema2.safeParseAsync(value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function zod4Schema(zodSchema2, options) {
var _a$2;
const useReferences = (_a$2 = options == null ? void 0 : options.useReferences) != null ? _a$2 : false;
return jsonSchema(() => addAdditionalPropertiesToJsonSchema(toJSONSchema(zodSchema2, {
target: "draft-7",
io: "input",
reused: useReferences ? "ref" : "inline"
})), { validate: async (value) => {
const result = await safeParseAsync(zodSchema2, value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function isZod4Schema(zodSchema2) {
return "_zod" in zodSchema2;
}
function zodSchema(zodSchema2, options) {
if (isZod4Schema(zodSchema2)) return zod4Schema(zodSchema2, options);
else return zod3Schema(zodSchema2, options);
}
var schemaSymbol = Symbol.for("vercel.ai.schema");
function jsonSchema(jsonSchema2, { validate } = {}) {
return {
[schemaSymbol]: true,
_type: void 0,
[validatorSymbol]: true,
get jsonSchema() {
if (typeof jsonSchema2 === "function") jsonSchema2 = jsonSchema2();
return jsonSchema2;
},
validate
};
}
function isSchema(value) {
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
}
function asSchema(schema) {
return schema == null ? jsonSchema({
properties: {},
additionalProperties: false
}) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
}
var { btoa: btoa$1, atob: atob$1 } = globalThis;
//#endregion
//#region ../../node_modules/.bun/ai@5.0.115+27912429049419a2/node_modules/ai/dist/index.mjs
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name16 in all) __defProp(target, name16, {
get: all[name16],
enumerable: true
});
};
var name = "AI_NoOutputSpecifiedError";
var marker = `vercel.ai.error.${name}`;
var symbol = Symbol.for(marker);
var _a;
_a = symbol;
var name2 = "AI_InvalidArgumentError";
var marker2 = `vercel.ai.error.${name2}`;
var symbol2 = Symbol.for(marker2);
var _a2;
_a2 = symbol2;
var name3 = "AI_InvalidStreamPartError";
var marker3 = `vercel.ai.error.${name3}`;
var symbol3 = Symbol.for(marker3);
var _a3;
_a3 = symbol3;
var name4 = "AI_InvalidToolInputError";
var marker4 = `vercel.ai.error.${name4}`;
var symbol4 = Symbol.for(marker4);
var _a4;
_a4 = symbol4;
var name5 = "AI_NoImageGeneratedError";
var marker5 = `vercel.ai.error.${name5}`;
var symbol5 = Symbol.for(marker5);
var _a5;
_a5 = symbol5;
var name6 = "AI_NoObjectGeneratedError";
var marker6 = `vercel.ai.error.${name6}`;
var symbol6 = Symbol.for(marker6);
var _a6;
var NoObjectGeneratedError = class extends AISDKError {
constructor({ message = "No object generated.", cause, text: text2, response, usage, finishReason }) {
super({
name: name6,
message,
cause
});
this[_a6] = true;
this.text = text2;
this.response = response;
this.usage = usage;
this.finishReason = finishReason;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker6);
}
};
_a6 = symbol6;
var name7 = "AI_NoOutputGeneratedError";
var marker7 = `vercel.ai.error.${name7}`;
var symbol7 = Symbol.for(marker7);
var _a7;
_a7 = symbol7;
var name8 = "AI_NoSuchToolError";
var marker8 = `vercel.ai.error.${name8}`;
var symbol8 = Symbol.for(marker8);
var _a8;
_a8 = symbol8;
var name9 = "AI_ToolCallRepairError";
var marker9 = `vercel.ai.error.${name9}`;
var symbol9 = Symbol.for(marker9);
var _a9;
_a9 = symbol9;
var name10 = "AI_InvalidDataContentError";
var marker10 = `vercel.ai.error.${name10}`;
var symbol10 = Symbol.for(marker10);
var _a10;
_a10 = symbol10;
var name11 = "AI_InvalidMessageRoleError";
var marker11 = `vercel.ai.error.${name11}`;
var symbol11 = Symbol.for(marker11);
var _a11;
_a11 = symbol11;
var name12 = "AI_MessageConversionError";
var marker12 = `vercel.ai.error.${name12}`;
var symbol12 = Symbol.for(marker12);
var _a12;
_a12 = symbol12;
var name13 = "AI_DownloadError";
var marker13 = `vercel.ai.error.${name13}`;
var symbol13 = Symbol.for(marker13);
var _a13;
_a13 = symbol13;
var name14 = "AI_RetryError";
var marker14 = `vercel.ai.error.${name14}`;
var symbol14 = Symbol.for(marker14);
var _a14;
_a14 = symbol14;
var VERSION = "5.0.115";
var dataContentSchema = union([
string(),
_instanceof(Uint8Array),
_instanceof(ArrayBuffer),
custom((value) => {
var _a16, _b;
return (_b = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b : false;
}, { message: "Must be a Buffer" })
]);
var jsonValueSchema = lazy(() => union([
_null(),
string(),
number(),
boolean(),
record(string(), jsonValueSchema),
array(jsonValueSchema)
]));
var providerMetadataSchema = record(string(), record(string(), jsonValueSchema));
var textPartSchema = object$1({
type: literal("text"),
text: string(),
providerOptions: providerMetadataSchema.optional()
});
var imagePartSchema = object$1({
type: literal("image"),
image: union([dataContentSchema, _instanceof(URL)]),
mediaType: string().optional(),
providerOptions: providerMetadataSchema.optional()
});
var filePartSchema = object$1({
type: literal("file"),
data: union([dataContentSchema, _instanceof(URL)]),
filename: string().optional(),
mediaType: string(),
providerOptions: providerMetadataSchema.optional()
});
var reasoningPartSchema = object$1({
type: literal("reasoning"),
text: string(),
providerOptions: providerMetadataSchema.optional()
});
var toolCallPartSchema = object$1({
type: literal("tool-call"),
toolCallId: string(),
toolName: string(),
input: unknown(),
providerOptions: providerMetadataSchema.optional(),
providerExecuted: boolean().optional()
});
var outputSchema = discriminatedUnion("type", [
object$1({
type: literal("text"),
value: string()
}),
object$1({
type: literal("json"),
value: jsonValueSchema
}),
object$1({
type: literal("error-text"),
value: string()
}),
object$1({
type: literal("error-json"),
value: jsonValueSchema
}),
object$1({
type: literal("content"),
value: array(union([object$1({
type: literal("text"),
text: string()
}), object$1({
type: literal("media"),
data: string(),
mediaType: string()
})]))
})
]);
var toolResultPartSchema = object$1({
type: literal("tool-result"),
toolCallId: string(),
toolName: string(),
output: outputSchema,
providerOptions: providerMetadataSchema.optional()
});
var systemModelMessageSchema = object$1({
role: literal("system"),
content: string(),
providerOptions: providerMetadataSchema.optional()
});
var userModelMessageSchema = object$1({
role: literal("user"),
content: union([string(), array(union([
textPartSchema,
imagePartSchema,
filePartSchema
]))]),
providerOptions: providerMetadataSchema.optional()
});
var assistantModelMessageSchema = object$1({
role: literal("assistant"),
content: union([string(), array(union([
textPartSchema,
filePartSchema,
reasoningPartSchema,
toolCallPartSchema,
toolResultPartSchema
]))]),
providerOptions: providerMetadataSchema.optional()
});
var toolModelMessageSchema = object$1({
role: literal("tool"),
content: array(toolResultPartSchema),
providerOptions: providerMetadataSchema.optional()
});
var modelMessageSchema = union([
systemModelMessageSchema,
userModelMessageSchema,
assistantModelMessageSchema,
toolModelMessageSchema
]);
var originalGenerateId = createIdGenerator({
prefix: "aitxt",
size: 24
});
var uiMessageChunkSchema = lazyValidator(() => zodSchema(union([
strictObject({
type: literal("text-start"),
id: string(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: literal("text-delta"),
id: string(),
delta: string(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: literal("text-end"),
id: string(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: literal("error"),
errorText: string()
}),
strictObject({
type: literal("tool-input-start"),
toolCallId: string(),
toolName: string(),
providerExecuted: boolean().optional(),
dynamic: boolean().optional()
}),
strictObject({
type: literal("tool-input-delta"),
toolCallId: string(),
inputTextDelta: string()
}),
strictObject({
type: literal("tool-input-available"),
toolCallId: string(),
toolName: string(),
input: unknown(),
providerExecuted: boolean().optional(),
providerMetadata: providerMetadataSchema.optional(),
dynamic: boolean().optional()
}),
strictObject({
type: literal("tool-input-error"),
toolCallId: string(),
toolName: string(),
input: unknown(),
providerExecuted: boolean().optional(),
providerMetadata: providerMetadataSchema.optional(),
dynamic: boolean().optional(),
errorText: string()
}),
strictObject({
type: literal("tool-output-available"),
toolCallId: string(),
output: unknown(),
providerExecuted: boolean().optional(),
dynamic: boolean().optional(),
preliminary: boolean().optional()
}),
strictObject({
type: literal("tool-output-error"),
toolCallId: string(),
errorText: string(),
providerExecuted: boolean().optional(),
dynamic: boolean().optional()
}),
strictObject({
type: literal("reasoning-start"),
id: string(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: literal("reasoning-delta"),
id: string(),
delta: string(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: literal("reasoning-end"),
id: string(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: literal("source-url"),
sourceId: string(),
url: string(),
title: string().optional(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: literal("source-document"),
sourceId: string(),
mediaType: string(),
title: string(),
filename: string().optional(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: literal("file"),
url: string(),
mediaType: string(),
providerMetadata: providerMetadataSchema.optional()
}),
strictObject({
type: custom((value) => typeof value === "string" && value.startsWith("data-"), { message: "Type must start with \"data-\"" }),
id: string().optional(),
data: unknown(),
transient: boolean().optional()
}),
strictObject({ type: literal("start-step") }),
strictObject({ type: literal("finish-step") }),
strictObject({
type: literal("start"),
messageId: string().optional(),
messageMetadata: unknown().optional()
}),
strictObject({
type: literal("finish"),
finishReason: _enum([
"stop",
"length",
"content-filter",
"tool-calls",
"error",
"other",
"unknown"
]).optional(),
messageMetadata: unknown().optional()
}),
strictObject({ type: literal("abort") }),
strictObject({
type: literal("message-metadata"),
messageMetadata: unknown()
})
])));
function isDataUIMessageChunk(chunk$1) {
return chunk$1.type.startsWith("data-");
}
function mergeObjects(base, overrides) {
if (base === void 0 && overrides === void 0) return void 0;
if (base === void 0) return overrides;
if (overrides === void 0) return base;
const result = { ...base };
for (const key in overrides) if (Object.prototype.hasOwnProperty.call(overrides, key)) {
const overridesValue = overrides[key];
if (overridesValue === void 0) continue;
const baseValue = key in base ? base[key] : void 0;
const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
if (isSourceObject && isTargetObject) result[key] = mergeObjects(baseValue, overridesValue);
else result[key] = overridesValue;
}
return result;
}
function fixJson(input) {
const stack = ["ROOT"];
let lastValidIndex = -1;
let literalStart = null;
function processValueStart(char, i$3, swapState) {
switch (char) {
case "\"": {
lastValidIndex = i$3;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_STRING");
break;
}
case "f":
case "t":
case "n": {
lastValidIndex = i$3;
literalStart = i$3;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_LITERAL");
break;
}
case "-": {
stack.pop();
stack.push(swapState);
stack.push("INSIDE_NUMBER");
break;
}
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": {
lastValidIndex = i$3;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_NUMBER");
break;
}
case "{": {
lastValidIndex = i$3;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_OBJECT_START");
break;
}
case "[": {
lastValidIndex = i$3;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_ARRAY_START");
break;
}
}
}
function processAfterObjectValue(char, i$3) {
switch (char) {
case ",": {
stack.pop();
stack.push("INSIDE_OBJECT_AFTER_COMMA");
break;
}
case "}": {
lastValidIndex = i$3;
stack.pop();
break;
}
}
}
function processAfterArrayValue(char, i$3) {
switch (char) {
case ",": {
stack.pop();
stack.push("INSIDE_ARRAY_AFTER_COMMA");
break;
}
case "]": {
lastValidIndex = i$3;
stack.pop();
break;
}
}
}
for (let i$3 = 0; i$3 < input.length; i$3++) {
const char = input[i$3];
const currentState = stack[stack.length - 1];
switch (currentState) {
case "ROOT":
processValueStart(char, i$3, "FINISH");
break;
case "INSIDE_OBJECT_START": {
switch (char) {
case "\"": {
stack.pop();
stack.push("INSIDE_OBJECT_KEY");
break;
}
case "}": {
lastValidIndex = i$3;
stack.pop();
break;
}
}
break;
}
case "INSIDE_OBJECT_AFTER_COMMA": {
switch (char) {
case "\"": {
stack.pop();
stack.push("INSIDE_OBJECT_KEY");
break;
}
}
break;
}
case "INSIDE_OBJECT_KEY": {
switch (char) {
case "\"": {
stack.pop();
stack.push("INSIDE_OBJECT_AFTER_KEY");
break;
}
}
break;
}
case "INSIDE_OBJECT_AFTER_KEY": {
switch (char) {
case ":": {
stack.pop();
stack.push("INSIDE_OBJECT_BEFORE_VALUE");
break;
}
}
break;
}
case "INSIDE_OBJECT_BEFORE_VALUE": {
processValueStart(char, i$3, "INSIDE_OBJECT_AFTER_VALUE");
break;
}
case "INSIDE_OBJECT_AFTER_VALUE": {
processAfterObjectValue(char, i$3);
break;
}
case "INSIDE_STRING": {
switch (char) {
case "\"": {
stack.pop();
lastValidIndex = i$3;
break;
}
case "\\": {
stack.push("INSIDE_STRING_ESCAPE");
break;
}
default: lastValidIndex = i$3;
}
break;
}
case "INSIDE_ARRAY_START": {
switch (char) {
case "]": {
lastValidIndex = i$3;
stack.pop();
break;
}
default: {
lastValidIndex = i$3;
processValueStart(char, i$3, "INSIDE_ARRAY_AFTER_VALUE");
break;
}
}
break;
}
case "INSIDE_ARRAY_AFTER_VALUE": {
switch (char) {
case ",": {
stack.pop();
stack.push("INSIDE_ARRAY_AFTER_COMMA");
break;
}
case "]": {
lastValidIndex = i$3;
stack.pop();
break;
}
default: {
lastValidIndex = i$3;
break;
}
}
break;
}
case "INSIDE_ARRAY_AFTER_COMMA": {
processValueStart(char, i$3, "INSIDE_ARRAY_AFTER_VALUE");
break;
}
case "INSIDE_STRING_ESCAPE": {
stack.pop();
lastValidIndex = i$3;
break;
}
case "INSIDE_NUMBER": {
switch (char) {
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": {
lastValidIndex = i$3;
break;
}
case "e":
case "E":
case "-":
case ".": break;
case ",": {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i$3);
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i$3);
break;
}
case "}": {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i$3);
break;
}
case "]": {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i$3);
break;
}
default: {
stack.pop();
break;
}
}
break;
}
case "INSIDE_LITERAL": {
const partialLiteral = input.substring(literalStart, i$3 + 1);
if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i$3);
else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i$3);
} else lastValidIndex = i$3;
break;
}
}
}
let result = input.slice(0, lastValidIndex + 1);
for (let i$3 = stack.length - 1; i$3 >= 0; i$3--) {
const state = stack[i$3];
switch (state) {
case "INSIDE_STRING": {
result += "\"";
break;
}
case "INSIDE_OBJECT_KEY":
case "INSIDE_OBJECT_AFTER_KEY":
case "INSIDE_OBJECT_AFTER_COMMA":
case "INSIDE_OBJECT_START":
case "INSIDE_OBJECT_BEFORE_VALUE":
case "INSIDE_OBJECT_AFTER_VALUE": {
result += "}";
break;
}
case "INSIDE_ARRAY_START":
case "INSIDE_ARRAY_AFTER_COMMA":
case "INSIDE_ARRAY_AFTER_VALUE": {
result += "]";
break;
}
case "INSIDE_LITERAL": {
const partialLiteral = input.substring(literalStart, input.length);
if ("true".startsWith(partialLiteral)) result += "true".slice(partialLiteral.length);
else if ("false".startsWith(partialLiteral)) result += "false".slice(partialLiteral.length);
else if ("null".startsWith(partialLiteral)) result += "null".slice(partialLiteral.length);
}
}
}
return result;
}
async function parsePartialJson(jsonText) {
if (jsonText === void 0) return {
value: void 0,
state: "undefined-input"
};
let result = await safeParseJSON({ text: jsonText });
if (result.success) return {
value: result.value,
state: "successful-parse"
};
result = await safeParseJSON({ text: fixJson(jsonText) });
if (result.success) return {
value: result.value,
state: "repaired-parse"
};
return {
value: void 0,
state: "failed-parse"
};
}
function isToolUIPart(part) {
return part.type.startsWith("tool-");
}
function isDynamicToolUIPart(part) {
return part.type === "dynamic-tool";
}
function isToolOrDynamicToolUIPart(part) {
return isToolUIPart(part) || isDynamicToolUIPart(part);
}
function getToolName(part) {
return part.type.split("-").slice(1).join("-");
}
function createStreamingUIMessageState({ lastMessage, messageId }) {
return {
message: (lastMessage == null ? void 0 : lastMessage.role) === "assistant" ? lastMessage : {
id: messageId,
metadata: void 0,
role: "assistant",
parts: []
},
activeTextParts: {},
activeReasoningParts: {},
partialToolCalls: {}
};
}
function processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas, runUpdateMessageJob, onError, onToolCall, onData }) {
return stream.pipeThrough(new TransformStream({ async transform(chunk$1, controller) {
await runUpdateMessageJob(async ({ state, write }) => {
var _a16, _b, _c, _d;
function getToolInvocation(toolCallId) {
const toolInvocations = state.message.parts.filter(isToolUIPart);
const toolInvocation = toolInvocations.find((invocation) => invocation.toolCallId === toolCallId);
if (toolInvocation == null) throw new Error("tool-output-error must be preceded by a tool-input-available");
return toolInvocation;
}
function getDynamicToolInvocation(toolCallId) {
const toolInvocations = state.message.parts.filter((part) => part.type === "dynamic-tool");
const toolInvocation = toolInvocations.find((invocation) => invocation.toolCallId === toolCallId);
if (toolInvocation == null) throw new Error("tool-output-error must be preceded by a tool-input-available");
return toolInvocation;
}
function updateToolPart(options) {
var _a17;
const part = state.message.parts.find((part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId);
const anyOptions = options;
const anyPart = part;
if (part != null) {
part.state = options.state;
anyPart.input = anyOptions.input;
anyPart.output = anyOptions.output;
anyPart.errorText = anyOptions.errorText;
anyPart.rawInput = anyOptions.rawInput;
anyPart.preliminary = anyOptions.preliminary;
anyPart.providerExecuted = (_a17 = anyOptions.providerExecuted) != null ? _a17 : part.providerExecuted;
if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
} else state.message.parts.push({
type: `tool-${options.toolName}`,
toolCallId: options.toolCallId,
state: options.state,
input: anyOptions.input,
output: anyOptions.output,
rawInput: anyOptions.rawInput,
errorText: anyOptions.errorText,
providerExecuted: anyOptions.providerExecuted,
preliminary: anyOptions.preliminary,
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
});
}
function updateDynamicToolPart(options) {
var _a17, _b2;
const part = state.message.parts.find((part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId);
const anyOptions = options;
const anyPart = part;
if (part != null) {
part.state = options.state;
anyPart.toolName = options.toolName;
anyPart.input = anyOptions.input;
anyPart.output = anyOptions.output;
anyPart.errorText = anyOptions.errorText;
anyPart.rawInput = (_a17 = anyOptions.rawInput) != null ? _a17 : anyPart.rawInput;
anyPart.preliminary = anyOptions.preliminary;
anyPart.providerExecuted = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;
if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
} else state.message.parts.push({
type: "dynamic-tool",
toolName: options.toolName,
toolCallId: options.toolCallId,
state: options.state,
input: anyOptions.input,
output: anyOptions.output,
errorText: anyOptions.errorText,
preliminary: anyOptions.preliminary,
providerExecuted: anyOptions.providerExecuted,
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
});
}
async function updateMessageMetadata(metadata) {
if (metadata != null) {
const mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;
if (messageMetadataSchema != null) await validateTypes({
value: mergedMetadata,
schema: messageMetadataSchema
});
state.message.metadata = mergedMetadata;
}
}
switch (chunk$1.type) {
case "text-start": {
const textPart = {
type: "text",
text: "",
providerMetadata: chunk$1.providerMetadata,
state: "streaming"
};
state.activeTextParts[chunk$1.id] = textPart;
state.message.parts.push(textPart);
write();
break;
}
case "text-delta": {
const textPart = state.activeTextParts[chunk$1.id];
textPart.text += chunk$1.delta;
textPart.providerMetadata = (_a16 = chunk$1.providerMetadata) != null ? _a16 : textPart.providerMetadata;
write();
break;
}
case "text-end": {
const textPart = state.activeTextParts[chunk$1.id];
textPart.state = "done";
textPart.providerMetadata = (_b = chunk$1.providerMetadata) != null ? _b : textPart.providerMetadata;
delete state.activeTextParts[chunk$1.id];
write();
break;
}
case "reasoning-start": {
const reasoningPart = {
type: "reasoning",
text: "",
providerMetadata: chunk$1.providerMetadata,
state: "streaming"
};
state.activeReasoningParts[chunk$1.id] = reasoningPart;
state.message.parts.push(reasoningPart);
write();
break;
}
case "reasoning-delta": {
const reasoningPart = state.activeReasoningParts[chunk$1.id];
reasoningPart.text += chunk$1.delta;
reasoningPart.providerMetadata = (_c = chunk$1.providerMetadata) != null ? _c : reasoningPart.providerMetadata;
write();
break;
}
case "reasoning-end": {
const reasoningPart = state.activeReasoningParts[chunk$1.id];
reasoningPart.providerMetadata = (_d = chunk$1.providerMetadata) != null ? _d : reasoningPart.providerMetadata;
reasoningPart.state = "done";
delete state.activeReasoningParts[chunk$1.id];
write();
break;
}
case "file": {
state.message.parts.push({
type: "file",
mediaType: chunk$1.mediaType,
url: chunk$1.url
});
write();
break;
}
case "source-url": {
state.message.parts.push({
type: "source-url",
sourceId: chunk$1.sourceId,
url: chunk$1.url,
title: chunk$1.title,
providerMetadata: chunk$1.providerMetadata
});
write();
break;
}
case "source-document": {
state.message.parts.push({
type: "source-document",
sourceId: chunk$1.sourceId,
mediaType: chunk$1.mediaType,
title: chunk$1.title,
filename: chunk$1.filename,
providerMetadata: chunk$1.providerMetadata
});
write();
break;
}
case "tool-input-start": {
const toolInvocations = state.message.parts.filter(isToolUIPart);
state.partialToolCalls[chunk$1.toolCallId] = {
text: "",
toolName: chunk$1.toolName,
index: toolInvocations.length,
dynamic: chunk$1.dynamic
};
if (chunk$1.dynamic) updateDynamicToolPart({
toolCallId: chunk$1.toolCallId,
toolName: chunk$1.toolName,
state: "input-streaming",
input: void 0,
providerExecuted: chunk$1.providerExecuted
});
else updateToolPart({
toolCallId: chunk$1.toolCallId,
toolName: chunk$1.toolName,
state: "input-streaming",
input: void 0,
providerExecuted: chunk$1.providerExecuted
});
write();
break;
}
case "tool-input-delta": {
const partialToolCall = state.partialToolCalls[chunk$1.toolCallId];
partialToolCall.text += chunk$1.inputTextDelta;
const { value: partialArgs } = await parsePartialJson(partialToolCall.text);
if (partialToolCall.dynamic) updateDynamicToolPart({
toolCallId: chunk$1.toolCallId,
toolName: partialToolCall.toolName,
state: "input-streaming",
input: partialArgs
});
else updateToolPart({
toolCallId: chunk$1.toolCallId,
toolName: partialToolCall.toolName,
state: "input-streaming",
input: partialArgs
});
write();
break;
}
case "tool-input-available": {
if (chunk$1.dynamic) updateDynamicToolPart({
toolCallId: chunk$1.toolCallId,
toolName: chunk$1.toolName,
state: "input-available",
input: chunk$1.input,
providerExecuted: chunk$1.providerExecuted,
providerMetadata: chunk$1.providerMetadata
});
else updateToolPart({
toolCallId: chunk$1.toolCallId,
toolName: chunk$1.toolName,
state: "input-available",
input: chunk$1.input,
providerExecuted: chunk$1.providerExecuted,
providerMetadata: chunk$1.providerMetadata
});
write();
if (onToolCall && !chunk$1.providerExecuted) await onToolCall({ toolCall: chunk$1 });
break;
}
case "tool-input-error": {
if (chunk$1.dynamic) updateDynamicToolPart({
toolCallId: chunk$1.toolCallId,
toolName: chunk$1.toolName,
state: "output-error",
input: chunk$1.input,
errorText: chunk$1.errorText,
providerExecuted: chunk$1.providerExecuted,
providerMetadata: chunk$1.providerMetadata
});
else updateToolPart({
toolCallId: chunk$1.toolCallId,
toolName: chunk$1.toolName,
state: "output-error",
input: void 0,
rawInput: chunk$1.input,
errorText: chunk$1.errorText,
providerExecuted: chunk$1.providerExecuted,
providerMetadata: chunk$1.providerMetadata
});
write();
break;
}
case "tool-output-available": {
if (chunk$1.dynamic) {
const toolInvocation = getDynamicToolInvocation(chunk$1.toolCallId);
updateDynamicToolPart({
toolCallId: chunk$1.toolCallId,
toolName: toolInvocation.toolName,
state: "output-available",
input: toolInvocation.input,
output: chunk$1.output,
preliminary: chunk$1.preliminary
});
} else {
const toolInvocation = getToolInvocation(chunk$1.toolCallId);
updateToolPart({
toolCallId: chunk$1.toolCallId,
toolName: getToolName(toolInvocation),
state: "output-available",
input: toolInvocation.input,
output: chunk$1.output,
providerExecuted: chunk$1.providerExecuted,
preliminary: chunk$1.preliminary
});
}
write();
break;
}
case "tool-output-error": {
if (chunk$1.dynamic) {
const toolInvocation = getDynamicToolInvocation(chunk$1.toolCallId);
updateDynamicToolPart({
toolCallId: chunk$1.toolCallId,
toolName: toolInvocation.toolName,
state: "output-error",
input: toolInvocation.input,
errorText: chunk$1.errorText,
providerExecuted: chunk$1.providerExecuted
});
} else {
const toolInvocation = getToolInvocation(chunk$1.toolCallId);
updateToolPart({
toolCallId: chunk$1.toolCallId,
toolName: getToolName(toolInvocation),
state: "output-error",
input: toolInvocation.input,
rawInput: toolInvocation.rawInput,
errorText: chunk$1.errorText,
providerExecuted: chunk$1.providerExecuted
});
}
write();
break;
}
case "start-step": {
state.message.parts.push({ type: "step-start" });
break;
}
case "finish-step": {
state.activeTextParts = {};
state.activeReasoningParts = {};
break;
}
case "start": {
if (chunk$1.messageId != null) state.message.id = chunk$1.messageId;
await updateMessageMetadata(chunk$1.messageMetadata);
if (chunk$1.messageId != null || chunk$1.messageMetadata != null) write();
break;
}
case "finish": {
if (chunk$1.finishReason != null) state.finishReason = chunk$1.finishReason;
await updateMessageMetadata(chunk$1.messageMetadata);
if (chunk$1.messageMetadata != null) write();
break;
}
case "message-metadata": {
await updateMessageMetadata(chunk$1.messageMetadata);
if (chunk$1.messageMetadata != null) write();
break;
}
case "error": {
onError == null || onError(new Error(chunk$1.errorText));
break;
}
default: if (isDataUIMessageChunk(chunk$1)) {
if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk$1.type]) != null) await validateTypes({
value: chunk$1.data,
schema: dataPartSchemas[chunk$1.type]
});
const dataChunk = chunk$1;
if (dataChunk.transient) {
onData == null || onData(dataChunk);
break;
}
const existingUIPart = dataChunk.id != null ? state.message.parts.find((chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id) : void 0;
if (existingUIPart != null) existingUIPart.data = dataChunk.data;
else state.message.parts.push(dataChunk);
onData == null || onData(dataChunk);
write();
}
}
controller.enqueue(chunk$1);
});
} }));
}
async function consumeStream({ stream, onError }) {
const reader = stream.getReader();
try {
while (true) {
const { done } = await reader.read();
if (done) break;
}
} catch (error) {
onError == null || onError(error);
} finally {
reader.releaseLock();
}
}
var originalGenerateId2 = createIdGenerator({
prefix: "aitxt",
size: 24
});
var originalGenerateId3 = createIdGenerator({
prefix: "aiobj",
size: 24
});
var SerialJobExecutor = class {
constructor() {
this.queue = [];
this.isProcessing = false;
}
async processQueue() {
if (this.isProcessing) return;
this.isProcessing = true;
while (this.queue.length > 0) {
await this.queue[0]();
this.queue.shift();
}
this.isProcessing = false;
}
async run(job) {
return new Promise((resolve2, reject) => {
this.queue.push(async () => {
try {
await job();
resolve2();
} catch (error) {
reject(error);
}
});
this.processQueue();
});
}
};
var originalGenerateId4 = createIdGenerator({
prefix: "aiobj",
size: 24
});
var output_exports = {};
__export(output_exports, {
object: () => object,
text: () => text
});
var text = () => ({
type: "text",
responseFormat: { type: "text" },
async parsePartial({ text: text2 }) {
return { partial: text2 };
},
async parseOutput({ text: text2 }) {
return text2;
}
});
var object = ({ schema: inputSchema }) => {
const schema = asSchema(inputSchema);
return {
type: "object",
responseFormat: {
type: "json",
schema: schema.jsonSchema
},
async parsePartial({ text: text2 }) {
const result = await parsePartialJson(text2);
switch (result.state) {
case "failed-parse":
case "undefined-input": return void 0;
case "repaired-parse":
case "successful-parse": return { partial: result.value };
default: {
const _exhaustiveCheck = result.state;
throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
}
}
},
async parseOutput({ text: text2 }, context) {
const parseResult = await safeParseJSON({ text: text2 });
if (!parseResult.success) throw new NoObjectGeneratedError({
message: "No object generated: could not parse the response.",
cause: parseResult.error,
text: text2,
response: context.response,
usage: context.usage,
finishReason: context.finishReason
});
const validationResult = await safeValidateTypes({
value: parseResult.value,
schema
});
if (!validationResult.success) throw new NoObjectGeneratedError({
message: "No object generated: response did not match schema.",
cause: validationResult.error,
text: text2,
response: context.response,
usage: context.usage,
finishReason: context.finishReason
});
return validationResult.value;
}
};
};
var name15 = "AI_NoSuchProviderError";
var marker15 = `vercel.ai.error.${name15}`;
var symbol15 = Symbol.for(marker15);
var _a15;
_a15 = symbol15;
async function convertFileListToFileUIParts(files) {
if (files == null) return [];
if (!globalThis.FileList || !(files instanceof globalThis.FileList)) throw new Error("FileList is not supported in the current environment");
return Promise.all(Array.from(files).map(async (file) => {
const { name: name16, type } = file;
const dataUrl = await new Promise((resolve2, reject) => {
const reader = new FileReader();
reader.onload = (readerEvent) => {
var _a16;
resolve2((_a16 = readerEvent.target) == null ? void 0 : _a16.result);
};
reader.onerror = (error) => reject(error);
reader.readAsDataURL(file);
});
return {
type: "file",
mediaType: type,
filename: name16,
url: dataUrl
};
}));
}
var HttpChatTransport = class {
constructor({ api = "/api/chat", credentials, headers, body, fetch: fetch2, prepareSendMessagesRequest, prepareReconnectToStreamRequest }) {
this.api = api;
this.credentials = credentials;
this.headers = headers;
this.body = body;
this.fetch = fetch2;
this.prepareSendMessagesRequest = prepareSendMessagesRequest;
this.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;
}
async sendMessages({ abortSignal,...options }) {
var _a16, _b, _c, _d, _e$1;
const resolvedBody = await resolve(this.body);
const resolvedHeaders = await resolve(this.headers);
const resolvedCredentials = await resolve(this.credentials);
const baseHeaders = {
...normalizeHeaders(resolvedHeaders),
...normalizeHeaders(options.headers)
};
const preparedRequest = await ((_a16 = this.prepareSendMessagesRequest) == null ? void 0 : _a16.call(this, {
api: this.api,
id: options.chatId,
messages: options.messages,
body: {
...resolvedBody,
...options.body
},
headers: baseHeaders,
credentials: resolvedCredentials,
requestMetadata: options.metadata,
trigger: options.trigger,
messageId: options.messageId
}));
const api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : this.api;
const headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;
const body = (preparedRequest == null ? void 0 : preparedRequest.body) !== void 0 ? preparedRequest.body : {
...resolvedBody,
...options.body,
id: options.chatId,
messages: options.messages,
trigger: options.trigger,
messageId: options.messageId
};
const credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;
const fetch2 = (_d = this.fetch) != null ? _d : globalThis.fetch;
const response = await fetch2(api, {
method: "POST",
headers: withUserAgentSuffix({
"Content-Type": "application/json",
...headers
}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),
body: JSON.stringify(body),
credentials,
signal: abortSignal
});
if (!response.ok) throw new Error((_e$1 = await response.text()) != null ? _e$1 : "Failed to fetch the chat response.");
if (!response.body) throw new Error("The response body is empty.");
return this.processResponseStream(response.body);
}
async reconnectToStream(options) {
var _a16, _b, _c, _d, _e$1;
const resolvedBody = await resolve(this.body);
const resolvedHeaders = await resolve(this.headers);
const resolvedCredentials = await resolve(this.credentials);
const baseHeaders = {
...normalizeHeaders(resolvedHeaders),
...normalizeHeaders(options.headers)
};
const preparedRequest = await ((_a16 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a16.call(this, {
api: this.api,
id: options.chatId,
body: {
...resolvedBody,
...options.body
},
headers: baseHeaders,
credentials: resolvedCredentials,
requestMetadata: options.metadata
}));
const api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : `${this.api}/${options.chatId}/stream`;
const headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;
const credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;
const fetch2 = (_d = this.fetch) != null ? _d : globalThis.fetch;
const response = await fetch2(api, {
method: "GET",
headers: withUserAgentSuffix(headers, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),
credentials
});
if (response.status === 204) return null;
if (!response.ok) throw new Error((_e$1 = await response.text()) != null ? _e$1 : "Failed to fetch the chat response.");
if (!response.body) throw new Error("The response body is empty.");
return this.processResponseStream(response.body);
}
};
var DefaultChatTransport = class extends HttpChatTransport {
constructor(options = {}) {
super(options);
}
processResponseStream(stream) {
return parseJsonEventStream({
stream,
schema: uiMessageChunkSchema
}).pipeThrough(new TransformStream({ async transform(chunk$1, controller) {
if (!chunk$1.success) throw chunk$1.error;
controller.enqueue(chunk$1.value);
} }));
}
};
var AbstractChat = class {
constructor({ generateId: generateId3 = generateId, id: id$1 = generateId3(), transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {
this.activeResponse = void 0;
this.jobExecutor = new SerialJobExecutor();
/**
* Appends or replaces a user message to the chat list. This triggers the API call to fetch
* the assistant's response.
*
* If a messageId is provided, the message will be replaced.
*/
this.sendMessage = async (message, options) => {
var _a16, _b, _c, _d;
if (message == null) {
await this.makeRequest({
trigger: "submit-message",
messageId: (_a16 = this.lastMessage) == null ? void 0 : _a16.id,
...options
});
return;
}
let uiMessage;
if ("text" in message || "files" in message) {
const fileParts = Array.isArray(message.files) ? message.files : await convertFileListToFileUIParts(message.files);
uiMessage = { parts: [...fileParts, ..."text" in message && message.text != null ? [{
type: "text",
text: message.text
}] : []] };
} else uiMessage = message;
if (message.messageId != null) {
const messageIndex = this.state.messages.findIndex((m$4) => m$4.id === message.messageId);
if (messageIndex === -1) throw new Error(`message with id ${message.messageId} not found`);
if (this.state.messages[messageIndex].role !== "user") throw new Error(`message with id ${message.messageId} is not a user message`);
this.state.messages = this.state.messages.slice(0, messageIndex + 1);
this.state.replaceMessage(messageIndex, {
...uiMessage,
id: message.messageId,
role: (_b = uiMessage.role) != null ? _b : "user",
metadata: message.metadata
});
} else this.state.pushMessage({
...uiMessage,
id: (_c = uiMessage.id) != null ? _c : this.generateId(),
role: (_d = uiMessage.role) != null ? _d : "user",
metadata: message.metadata
});
await this.makeRequest({
trigger: "submit-message",
messageId: message.messageId,
...options
});
};
/**
* Regenerate the assistant message with the provided message id.
* If no message id is provided, the last assistant message will be regenerated.
*/
this.regenerate = async ({ messageId,...options } = {}) => {
const messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);
if (messageIndex === -1) throw new Error(`message ${messageId} not found`);
this.state.messages = this.state.messages.slice(0, this.messages[messageIndex].role === "assistant" ? messageIndex : messageIndex + 1);
await this.makeRequest({
trigger: "regenerate-message",
messageId,
...options
});
};
/**
* Attempt to resume an ongoing streaming response.
*/
this.resumeStream = async (options = {}) => {
await this.makeRequest({
trigger: "resume-stream",
...options
});
};
/**
* Clear the error state and set the status to ready if the chat is in an error state.
*/
this.clearError = () => {
if (this.status === "error") {
this.state.error = void 0;
this.setStatus({ status: "ready" });
}
};
this.addToolOutput = async ({ state: state$1 = "output-available", tool: tool2, toolCallId, output, errorText }) => this.jobExecutor.run(async () => {
var _a16, _b;
const messages = this.state.messages;
const lastMessage = messages[messages.length - 1];
this.state.replaceMessage(messages.length - 1, {
...lastMessage,
parts: lastMessage.parts.map((part) => isToolOrDynamicToolUIPart(part) && part.toolCallId === toolCallId ? {
...part,
state: state$1,
output,
errorText
} : part)
});
if (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map((part) => isToolOrDynamicToolUIPart(part) && part.toolCallId === toolCallId ? {
...part,
state: state$1,
output,
errorText
} : part);
if (this.status !== "streaming" && this.status !== "submitted" && ((_a16 = this.sendAutomaticallyWhen) == null ? void 0 : _a16.call(this, { messages: this.state.messages }))) this.makeRequest({
trigger: "submit-message",
messageId: (_b = this.lastMessage) == null ? void 0 : _b.id
});
});
/** @deprecated Use addToolOutput */
this.addToolResult = this.addToolOutput;
/**
* Abort the current request immediately, keep the generated tokens if any.
*/
this.stop = async () => {
var _a16;
if (this.status !== "streaming" && this.status !== "submitted") return;
if ((_a16 = this.activeResponse) == null ? void 0 : _a16.abortController) this.activeResponse.abortController.abort();
};
this.id = id$1;
this.transport = transport;
this.generateId = generateId3;
this.messageMetadataSchema = messageMetadataSchema;
this.dataPartSchemas = dataPartSchemas;
this.state = state;
this.onError = onError;
this.onToolCall = onToolCall;
this.onFinish = onFinish;
this.onData = onData;
this.sendAutomaticallyWhen = sendAutomaticallyWhen;
}
/**
* Hook status:
*
* - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
* - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
* - `ready`: The full response has been received and processed; a new user message can be submitted.
* - `error`: An error occurred during the API request, preventing successful completion.
*/
get status() {
return this.state.status;
}
setStatus({ status, error }) {
if (this.status === status) return;
this.state.status = status;
this.state.error = error;
}
get error() {
return this.state.error;
}
get messages() {
return this.state.messages;
}
get lastMessage() {
return this.state.messages[this.state.messages.length - 1];
}
set messages(messages) {
this.state.messages = messages;
}
async makeRequest({ trigger, metadata, headers, body, messageId }) {
var _a16, _b, _c, _d;
this.setStatus({
status: "submitted",
error: void 0
});
const lastMessage = this.lastMessage;
let isAbort = false;
let isDisconnect = false;
let isError = false;
try {
const activeResponse = {
state: createStreamingUIMessageState({
lastMessage: this.state.snapshot(lastMessage),
messageId: this.generateId()
}),
abortController: new AbortController()
};
activeResponse.abortController.signal.addEventListener("abort", () => {
isAbort = true;
});
this.activeResponse = activeResponse;
let stream;
if (trigger === "resume-stream") {
const reconnect = await this.transport.reconnectToStream({
chatId: this.id,
metadata,
headers,
body
});
if (reconnect == null) {
this.setStatus({ status: "ready" });
return;
}
stream = reconnect;
} else stream = await this.transport.sendMessages({
chatId: this.id,
messages: this.state.messages,
abortSignal: activeResponse.abortController.signal,
metadata,
headers,
body,
trigger,
messageId
});
const runUpdateMessageJob = (job) => this.jobExecutor.run(() => job({
state: activeResponse.state,
write: () => {
var _a17;
this.setStatus({ status: "streaming" });
const replaceLastMessage = activeResponse.state.message.id === ((_a17 = this.lastMessage) == null ? void 0 : _a17.id);
if (replaceLastMessage) this.state.replaceMessage(this.state.messages.length - 1, activeResponse.state.message);
else this.state.pushMessage(activeResponse.state.message);
}
}));
await consumeStream({
stream: processUIMessageStream({
stream,
onToolCall: this.onToolCall,
onData: this.onData,
messageMetadataSchema: this.messageMetadataSchema,
dataPartSchemas: this.dataPartSchemas,
runUpdateMessageJob,
onError: (error) => {
throw error;
}
}),
onError: (error) => {
throw error;
}
});
this.setStatus({ status: "ready" });
} catch (err) {
if (isAbort || err.name === "AbortError") {
isAbort = true;
this.setStatus({ status: "ready" });
return null;
}
isError = true;
if (err instanceof TypeError && (err.message.toLowerCase().includes("fetch") || err.message.toLowerCase().includes("network"))) isDisconnect = true;
if (this.onError && err instanceof Error) this.onError(err);
this.setStatus({
status: "error",
error: err
});
} finally {
try {
(_b = this.onFinish) == null || _b.call(this, {
message: this.activeResponse.state.message,
messages: this.state.messages,
isAbort,
isDisconnect,
isError,
finishReason: (_a16 = this.activeResponse) == null ? void 0 : _a16.state.finishReason
});
} catch (err) {
console.error(err);
}
this.activeResponse = void 0;
}
if (((_c = this.sendAutomaticallyWhen) == null ? void 0 : _c.call(this, { messages: this.state.messages })) && !isError) await this.makeRequest({
trigger: "submit-message",
messageId: (_d = this.lastMessage) == null ? void 0 : _d.id,
metadata,
headers,
body
});
}
};
function lastAssistantMessageIsCompleteWithToolCalls({ messages }) {
const message = messages[messages.length - 1];
if (!message) return false;
if (message.role !== "assistant") return false;
const lastStepStartIndex = message.parts.reduce((lastIndex, part, index$1) => {
return part.type === "step-start" ? index$1 : lastIndex;
}, -1);
const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolOrDynamicToolUIPart).filter((part) => !part.providerExecuted);
return lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => part.state === "output-available" || part.state === "output-error");
}
var uiMessagesSchema = lazyValidator(() => zodSchema(array(object$1({
id: string(),
role: _enum([
"system",
"user",
"assistant"
]),
metadata: unknown().optional(),
parts: array(union([
object$1({
type: literal("text"),
text: string(),
state: _enum(["streaming", "done"]).optional(),
providerMetadata: providerMetadataSchema.optional()
}),
object$1({
type: literal("reasoning"),
text: string(),
state: _enum(["streaming", "done"]).optional(),
providerMetadata: providerMetadataSchema.optional()
}),
object$1({
type: literal("source-url"),
sourceId: string(),
url: string(),
title: string().optional(),
providerMetadata: providerMetadataSchema.optional()
}),
object$1({
type: literal("source-document"),
sourceId: string(),
mediaType: string(),
title: string(),
filename: string().optional(),
providerMetadata: providerMetadataSchema.optional()
}),
object$1({
type: literal("file"),
mediaType: string(),
filename: string().optional(),
url: string(),
providerMetadata: providerMetadataSchema.optional()
}),
object$1({ type: literal("step-start") }),
object$1({
type: string().startsWith("data-"),
id: string().optional(),
data: unknown()
}),
object$1({
type: literal("dynamic-tool"),
toolName: string(),
toolCallId: string(),
state: literal("input-streaming"),
input: unknown().optional(),
providerExecuted: boolean().optional(),
output: never().optional(),
errorText: never().optional()
}),
object$1({
type: literal("dynamic-tool"),
toolName: string(),
toolCallId: string(),
state: literal("input-available"),
input: unknown(),
providerExecuted: boolean().optional(),
output: never().optional(),
errorText: never().optional(),
callProviderMetadata: providerMetadataSchema.optional()
}),
object$1({
type: literal("dynamic-tool"),
toolName: string(),
toolCallId: string(),
state: literal("output-available"),
input: unknown(),
providerExecuted: boolean().optional(),
output: unknown(),
errorText: never().optional(),
callProviderMetadata: providerMetadataSchema.optional(),
preliminary: boolean().optional()
}),
object$1({
type: literal("dynamic-tool"),
toolName: string(),
toolCallId: string(),
state: literal("output-error"),
input: unknown(),
providerExecuted: boolean().optional(),
output: never().optional(),
errorText: string(),
callProviderMetadata: providerMetadataSchema.optional()
}),
object$1({
type: string().startsWith("tool-"),
toolCallId: string(),
state: literal("input-streaming"),
providerExecuted: boolean().optional(),
input: unknown().optional(),
output: never().optional(),
errorText: never().optional(),
approval: never().optional()
}),
object$1({
type: string().startsWith("tool-"),
toolCallId: string(),
state: literal("input-available"),
providerExecuted: boolean().optional(),
input: unknown(),
output: never().optional(),
errorText: never().optional(),
callProviderMetadata: providerMetadataSchema.optional(),
approval: never().optional()
}),
object$1({
type: string().startsWith("tool-"),
toolCallId: string(),
state: literal("approval-requested"),
input: unknown(),
providerExecuted: boolean().optional(),
output: never().optional(),
errorText: never().optional(),
callProviderMetadata: providerMetadataSchema.optional(),
approval: object$1({
id: string(),
approved: never().optional(),
reason: never().optional()
})
}),
object$1({
type: string().startsWith("tool-"),
toolCallId: string(),
state: literal("approval-responded"),
input: unknown(),
providerExecuted: boolean().optional(),
output: never().optional(),
errorText: never().optional(),
callProviderMetadata: providerMetadataSchema.optional(),
approval: object$1({
id: string(),
approved: boolean(),
reason: string().optional()
})
}),
object$1({
type: string().startsWith("tool-"),
toolCallId: string(),
state: literal("output-available"),
providerExecuted: boolean().optional(),
input: unknown(),
output: unknown(),
errorText: never().optional(),
callProviderMetadata: providerMetadataSchema.optional(),
preliminary: boolean().optional(),
approval: object$1({
id: string(),
approved: literal(true),
reason: string().optional()
}).optional()
}),
object$1({
type: string().startsWith("tool-"),
toolCallId: string(),
state: literal("output-error"),
providerExecuted: boolean().optional(),
input: unknown(),
output: never().optional(),
errorText: string(),
callProviderMetadata: providerMetadataSchema.optional(),
approval: object$1({
id: string(),
approved: literal(true),
reason: string().optional()
}).optional()
}),
object$1({
type: string().startsWith("tool-"),
toolCallId: string(),
state: literal("output-denied"),
providerExecuted: boolean().optional(),
input: unknown(),
output: never().optional(),
errorText: never().optional(),
callProviderMetadata: providerMetadataSchema.optional(),
approval: object$1({
id: string(),
approved: literal(false),
reason: string().optional()
})
})
])).nonempty("Message must contain at least one part")
})).nonempty("Messages array must not be empty")));
//#endregion
//#region ../../node_modules/.bun/throttleit@2.1.0/node_modules/throttleit/index.js
var require_throttleit = __commonJS({ "../../node_modules/.bun/throttleit@2.1.0/node_modules/throttleit/index.js"(exports, module) {
function throttle$1(function_, wait) {
if (typeof function_ !== "function") throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof function_}\`.`);
let timeoutId;
let lastCallTime = 0;
return function throttled(...arguments_) {
clearTimeout(timeoutId);
const now = Date.now();
const timeSinceLastCall = now - lastCallTime;
const delayForNextCall = wait - timeSinceLastCall;
if (delayForNextCall <= 0) {
lastCallTime = now;
function_.apply(this, arguments_);
} else timeoutId = setTimeout(() => {
lastCallTime = Date.now();
function_.apply(this, arguments_);
}, delayForNextCall);
};
}
module.exports = throttle$1;
} });
//#endregion
//#region ../../node_modules/.bun/@ai-sdk+react@2.0.117+4a32f864abb19720/node_modules/@ai-sdk/react/dist/index.mjs
init_compat_module();
var import_throttleit = __toESM(require_throttleit(), 1);
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj)) throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj)) throw 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);
return value;
};
function throttle(fn$1, waitMs) {
return waitMs != null ? (0, import_throttleit.default)(fn$1, waitMs) : fn$1;
}
var _messages, _status, _error, _messagesCallbacks, _statusCallbacks, _errorCallbacks, _callMessagesCallbacks, _callStatusCallbacks, _callErrorCallbacks;
var ReactChatState = class {
constructor(initialMessages = []) {
__privateAdd(this, _messages, void 0);
__privateAdd(this, _status, "ready");
__privateAdd(this, _error, void 0);
__privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
__privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
__privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
this.pushMessage = (message) => {
__privateSet(this, _messages, __privateGet(this, _messages).concat(message));
__privateGet(this, _callMessagesCallbacks).call(this);
};
this.popMessage = () => {
__privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
__privateGet(this, _callMessagesCallbacks).call(this);
};
this.replaceMessage = (index$1, message) => {
__privateSet(this, _messages, [
...__privateGet(this, _messages).slice(0, index$1),
this.snapshot(message),
...__privateGet(this, _messages).slice(index$1 + 1)
]);
__privateGet(this, _callMessagesCallbacks).call(this);
};
this.snapshot = (value) => structuredClone(value);
this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
__privateGet(this, _messagesCallbacks).add(callback);
return () => {
__privateGet(this, _messagesCallbacks).delete(callback);
};
};
this["~registerStatusCallback"] = (onChange) => {
__privateGet(this, _statusCallbacks).add(onChange);
return () => {
__privateGet(this, _statusCallbacks).delete(onChange);
};
};
this["~registerErrorCallback"] = (onChange) => {
__privateGet(this, _errorCallbacks).add(onChange);
return () => {
__privateGet(this, _errorCallbacks).delete(onChange);
};
};
__privateAdd(this, _callMessagesCallbacks, () => {
__privateGet(this, _messagesCallbacks).forEach((callback) => callback());
});
__privateAdd(this, _callStatusCallbacks, () => {
__privateGet(this, _statusCallbacks).forEach((callback) => callback());
});
__privateAdd(this, _callErrorCallbacks, () => {
__privateGet(this, _errorCallbacks).forEach((callback) => callback());
});
__privateSet(this, _messages, initialMessages);
}
get status() {
return __privateGet(this, _status);
}
set status(newStatus) {
__privateSet(this, _status, newStatus);
__privateGet(this, _callStatusCallbacks).call(this);
}
get error() {
return __privateGet(this, _error);
}
set error(newError) {
__privateSet(this, _error, newError);
__privateGet(this, _callErrorCallbacks).call(this);
}
get messages() {
return __privateGet(this, _messages);
}
set messages(newMessages) {
__privateSet(this, _messages, [...newMessages]);
__privateGet(this, _callMessagesCallbacks).call(this);
}
};
_messages = new WeakMap();
_status = new WeakMap();
_error = new WeakMap();
_messagesCallbacks = new WeakMap();
_statusCallbacks = new WeakMap();
_errorCallbacks = new WeakMap();
_callMessagesCallbacks = new WeakMap();
_callStatusCallbacks = new WeakMap();
_callErrorCallbacks = new WeakMap();
var _state;
var Chat = class extends AbstractChat {
constructor({ messages,...init }) {
const state = new ReactChatState(messages);
super({
...init,
state
});
__privateAdd(this, _state, void 0);
this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
__privateSet(this, _state, state);
}
};
_state = new WeakMap();
function useChat({ experimental_throttle: throttleWaitMs, resume = false,...options } = {}) {
const chatRef = A("chat" in options ? options.chat : new Chat(options));
const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && chatRef.current.id !== options.id;
if (shouldRecreateChat) chatRef.current = "chat" in options ? options.chat : new Chat(options);
const subscribeToMessages = q((update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs), [throttleWaitMs, chatRef.current.id]);
const messages = C$1(subscribeToMessages, () => chatRef.current.messages, () => chatRef.current.messages);
const status = C$1(chatRef.current["~registerStatusCallback"], () => chatRef.current.status, () => chatRef.current.status);
const error = C$1(chatRef.current["~registerErrorCallback"], () => chatRef.current.error, () => chatRef.current.error);
const setMessages = q((messagesParam) => {
if (typeof messagesParam === "function") messagesParam = messagesParam(chatRef.current.messages);
chatRef.current.messages = messagesParam;
}, [chatRef]);
y(() => {
if (resume) chatRef.current.resumeStream();
}, [resume, chatRef]);
return {
id: chatRef.current.id,
messages,
setMessages,
sendMessage: chatRef.current.sendMessage,
regenerate: chatRef.current.regenerate,
clearError: chatRef.current.clearError,
stop: chatRef.current.stop,
error,
resumeStream: chatRef.current.resumeStream,
status,
addToolResult: chatRef.current.addToolOutput,
addToolOutput: chatRef.current.addToolOutput
};
}
//#endregion
//#region src/components/search-askai/error-utils.tsx
/**
* Ask AI / Agent Studio error helpers: thread depth (AI-217) and Agent Studio
* cost controls (tokens, steps, rate limits, domain allowlisting), aligned with
* DocSearch `utils/askAiBlockingMatchers` + `utils/ai` behavior.
*/
const AGENT_STUDIO_PROMPT_BLOCKING_CODES = new Set([
"AI-203",
"AI-205",
"AI-224",
"AI-225"
]);
const TOKEN_OUTPUT_LIMIT_FALLBACK = "Could not complete response due to token output limits";
function errorMessage(error) {
if (error == null) return "";
if (error instanceof Error) {
let msg = error.message ?? "";
const cause = error.cause;
if (cause instanceof Error) {
const c$2 = cause.message ?? "";
if (c$2 && !msg.includes(c$2)) msg = msg ? `${msg} ${c$2}` : c$2;
} else if (typeof cause === "string" && cause && !msg.includes(cause)) msg = msg ? `${msg} ${cause}` : cause;
return msg;
}
if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message;
return "";
}
function readAgentStudioJsonStringField(o$3, key) {
for (const [k$4, v$3] of Object.entries(o$3)) if (k$4.toLowerCase() === key.toLowerCase() && typeof v$3 === "string" && v$3.trim() !== "") return v$3.trim();
return void 0;
}
function extractAiErrorCodeFromMessage(message) {
const direct = /\b(AI-\d{3})\b/i.exec(message);
if (direct) return direct[1].toUpperCase();
try {
const parsed = JSON.parse(message);
const c$2 = parsed.code ?? parsed.errorCode;
if (typeof c$2 === "string" && /AI-\d{3}/i.test(c$2)) return c$2.trim().toUpperCase();
} catch {}
return void 0;
}
function threadDepthFromPlainText(message) {
if (!message) return false;
if (message.toUpperCase().includes("AI-217")) return true;
return /conversation\s+depth/i.test(message);
}
function messageLooksLikeThreadDepth(message) {
if (threadDepthFromPlainText(message)) return true;
try {
const parsed = JSON.parse(message);
const code = parsed.code ?? parsed.errorCode;
if (typeof code === "string" && code.toUpperCase() === "AI-217") return true;
const nested = typeof parsed.message === "string" ? parsed.message : "";
return threadDepthFromPlainText(nested);
} catch {
return false;
}
}
/**
* Whether the error is thread depth exceeded (AI-217), including JSON-shaped Agent Studio payloads in `message`.
*/
function isThreadDepthError(error) {
return messageLooksLikeThreadDepth(errorMessage(error));
}
function matchesRequestBlockedForThisDomainMessage(normalizedMessage) {
return /\brequest blocked for this domain\b/.test(normalizedMessage) || /\bblocked for this domain\b/.test(normalizedMessage);
}
function matchesAgentStudioMaxStepsMessage(normalizedMessage) {
const m$4 = normalizedMessage;
return /\bstep limit\b/.test(m$4) || /\bmax steps\b/.test(m$4) || /\bmax step\b/.test(m$4) || /\bmaximum steps\b/.test(m$4) || /\bmaximum step\b/.test(m$4) || /\bmax agent steps\b/.test(m$4) || /\bmax agent step\b/.test(m$4) || /\bmaximum agent steps\b/.test(m$4) || /\bmaximum agent step\b/.test(m$4) || /\bmax steps per completion\b/.test(m$4) || /\bsteps per completion limit\b/.test(m$4);
}
function matchesAgentStudioRateLimitMessage(normalizedMessage) {
return /\b429\b/.test(normalizedMessage) || /\brate\s*limit/i.test(normalizedMessage) || /\btoo\s+many\s+attempts\b/.test(normalizedMessage) || /\btoo_many_requests\b/.test(normalizedMessage);
}
function matchesAgentStudioTokenOutputLimitPlainMessage(message) {
return /\bTokenOutputLimitError\b/i.test(message);
}
function matchesAgentStudioWhitelistOrNotAllowedDomainPlainMessage(normalizedMessage) {
return /\bwhitelist(ed)?\b/.test(normalizedMessage) || /\bnot\s+allowed\s+for\s+this\s+domain\b/.test(normalizedMessage);
}
function matchesAgentStudioContextOrTokenLimitsPlainMessage(normalizedMessage) {
const m$4 = normalizedMessage;
return /\bcontext\s+length\b/.test(m$4) || /\bmax tokens\b/.test(m$4) || /\bmax token\b/.test(m$4) || /\bmaximum tokens\b/.test(m$4) || /\bmaximum token\b/.test(m$4) || /\btoken\s+limit\b/.test(m$4) || /\btoken\s+output\b/.test(m$4) || /\boutput\s+limits?\b/.test(m$4);
}
function jsonMessageIsRequestBlockedForDomain(parsed) {
const msg = readAgentStudioJsonStringField(parsed, "message") ?? "";
return matchesRequestBlockedForThisDomainMessage(msg.toLowerCase());
}
function jsonPayloadImpliesCostControlExcludingRequestBlockedDomainMessage(parsed) {
const type = typeof parsed.type === "string" ? parsed.type : "";
if (/tokenoutput|outputlimit|steplimit|maxstep|ratelimit|domainnotallowed/i.test(type)) return true;
const errCode = readAgentStudioJsonStringField(parsed, "error") ?? "";
if (errCode.toUpperCase() === "TOO_MANY_REQUESTS") return true;
if (/token output|output limits|token limits|rate limit|whitelist|step limit|max steps|could not complete response due to token/i.test(errCode)) return true;
const msg = readAgentStudioJsonStringField(parsed, "message") ?? "";
if (/rate limit exceeded|retry after \d+/i.test(msg)) return true;
if (/whitelist/i.test(msg)) return true;
const lower = msg.toLowerCase();
const notAllowedAt = lower.indexOf("not allowed");
if (notAllowedAt !== -1 && lower.indexOf("domain", notAllowedAt) !== -1) return true;
return false;
}
function buildBlockingContext(rawMessage) {
const message = rawMessage;
const messageLower = message.toLowerCase();
let parsedJson = null;
try {
const p$2 = JSON.parse(message);
if (p$2 && typeof p$2 === "object" && !Array.isArray(p$2)) parsedJson = p$2;
} catch {}
return {
message,
messageLower,
parsedJson,
extractedCodeUpper: extractAiErrorCodeFromMessage(message)
};
}
const agentStudioPromptBlockingMatchers = [
{ matches: (c$2) => typeof c$2.extractedCodeUpper === "string" && AGENT_STUDIO_PROMPT_BLOCKING_CODES.has(c$2.extractedCodeUpper) },
{
matches: (c$2) => c$2.parsedJson !== null && jsonMessageIsRequestBlockedForDomain(c$2.parsedJson),
showNewConversationLink: false
},
{ matches: (c$2) => c$2.parsedJson !== null && jsonPayloadImpliesCostControlExcludingRequestBlockedDomainMessage(c$2.parsedJson) },
{
matches: (c$2) => matchesAgentStudioTokenOutputLimitPlainMessage(c$2.message),
showNewConversationLink: false
},
{ matches: (c$2) => matchesAgentStudioRateLimitMessage(c$2.messageLower) },
{
matches: (c$2) => matchesRequestBlockedForThisDomainMessage(c$2.messageLower),
showNewConversationLink: false
},
{ matches: (c$2) => matchesAgentStudioWhitelistOrNotAllowedDomainPlainMessage(c$2.messageLower) },
{ matches: (c$2) => matchesAgentStudioContextOrTokenLimitsPlainMessage(c$2.messageLower) },
{ matches: (c$2) => matchesAgentStudioMaxStepsMessage(c$2.messageLower) }
];
function resolveAgentStudioPromptBlocking(rawMessage) {
const ctx = buildBlockingContext(rawMessage);
const matched = agentStudioPromptBlockingMatchers.filter((m$4) => m$4.matches(ctx));
if (matched.length === 0) return {
blocking: false,
showNewConversationLink: true
};
const showNewConversationLink = matched.every((m$4) => m$4.showNewConversationLink !== false);
return {
blocking: true,
showNewConversationLink
};
}
function messageLooksLikeAgentStudioCostControl(rawMessage) {
return resolveAgentStudioPromptBlocking(rawMessage).blocking;
}
/**
* Whether further prompts should be blocked: thread depth (any backend) or Agent Studio cost controls.
*/
function isAskAiPromptBlockingError(error, agentStudio = false) {
if (error == null) return false;
if (isThreadDepthError(error)) return true;
if (!agentStudio) return false;
return messageLooksLikeAgentStudioCostControl(errorMessage(error));
}
/**
* Agent Studio stream hit the completion token ceiling (`TokenOutputLimitError`).
*/
function isAgentStudioTokenOutputLimitError(error) {
const msg = errorMessage(error);
if (/TokenOutputLimitError/i.test(msg)) return true;
if (/could not complete response due to token output limits/i.test(msg)) return true;
try {
const p$2 = JSON.parse(msg);
if (typeof p$2.type === "string" && /^TokenOutputLimitError$/i.test(p$2.type.trim())) return true;
if (typeof p$2.error === "string" && /token output limits/i.test(p$2.error)) return true;
} catch {}
return false;
}
/**
* Whether the blocking banner should include “Start a new conversation … to continue”.
*/
function showAskAiBlockingBannerNewConversationLink(error, agentStudio = false) {
if (error == null) return true;
if (isAgentStudioTokenOutputLimitError(error)) return false;
if (isThreadDepthError(error)) return true;
if (!agentStudio) return true;
return resolveAgentStudioPromptBlocking(errorMessage(error)).showNewConversationLink;
}
function stripTrailingAiCodeSuffix(message) {
return message.replace(/\s*\(AI-\d{3}\)\s*$/i, "").trim();
}
function looksLikeJsonObjectString(s$2) {
const t$2 = s$2.trim();
return t$2.startsWith("{") && t$2.endsWith("}");
}
/**
* Pulls `message` or `error` from Agent Studio JSON payloads, including double-encoded JSON
* and objects serialized with escaped quotes (`{\"error\": \"...\"}`).
*/
function extractAgentStudioErrorFieldMessage(raw) {
let s$2 = raw.trim();
if (!s$2) return void 0;
let iterations = 0;
while (iterations < 10) {
iterations += 1;
try {
const v$3 = JSON.parse(s$2);
if (typeof v$3 === "string") {
const next = v$3.trim();
if (!next) return void 0;
s$2 = next;
} else if (v$3 && typeof v$3 === "object" && !Array.isArray(v$3)) {
const o$3 = v$3;
const msg = readAgentStudioJsonStringField(o$3, "message");
if (msg) return msg;
const err = readAgentStudioJsonStringField(o$3, "error");
if (err) return err;
return void 0;
} else return void 0;
} catch {
if (/\\"/.test(s$2)) s$2 = s$2.replace(/\\"/g, "\"").replace(/\\\\/g, "\\").trim();
else {
const mMsg = /"message"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(s$2);
if (mMsg?.[1]) return mMsg[1].replace(/\\"/g, "\"").replace(/\\\\/g, "\\").trim();
const mErr = /"error"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(s$2);
if (mErr?.[1]) return mErr[1].replace(/\\"/g, "\"").replace(/\\\\/g, "\\").trim();
return void 0;
}
}
}
return void 0;
}
/**
* “Request blocked for this domain” (Agent Studio origin allowlist), including nested JSON `message`.
*/
function isRequestBlockedForDomainAskAiError(error) {
if (error == null) return false;
const raw = errorMessage(error);
const lower = raw.toLowerCase();
if (matchesRequestBlockedForThisDomainMessage(lower)) return true;
const extracted = extractAgentStudioErrorFieldMessage(raw.trim());
if (extracted && matchesRequestBlockedForThisDomainMessage(extracted.toLowerCase())) return true;
try {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
if (jsonMessageIsRequestBlockedForDomain(parsed)) return true;
}
} catch {}
return false;
}
function getAskAiPromptBlockingUserFacingMessage(error) {
if (error == null) return void 0;
const raw = errorMessage(error);
const extracted = extractAgentStudioErrorFieldMessage(raw);
if (extracted) return extracted;
const stripped = stripTrailingAiCodeSuffix(raw.trim());
return stripped !== "" ? stripped : void 0;
}
/**
* Primary line for the blocking banner (parsed API text when possible).
*/
function promptBlockingBannerMessage(error, agentStudio = false) {
if (!isAskAiPromptBlockingError(error, agentStudio)) return void 0;
if (isAgentStudioTokenOutputLimitError(error)) {
const m$4 = getAskAiPromptBlockingUserFacingMessage(error);
if (m$4 && !looksLikeJsonObjectString(m$4)) return m$4;
return TOKEN_OUTPUT_LIMIT_FALLBACK;
}
return getAskAiPromptBlockingUserFacingMessage(error);
}
/**
* Whether to omit the shell chat field (modal search bar, sidepanel compose, etc.).
* The banner can show token-limit copy while {@link showAskAiBlockingBannerNewConversationLink}
* stays true (generic “context / token” matchers), so we also key off the resolved banner text.
* Max-steps / per-completion limits use the same pattern (API copy may not flip the “new chat” heuristic).
*/
function shouldHideAskAiShellChatInput(error, agentStudio) {
if (!agentStudio) return false;
if (!isAskAiPromptBlockingError(error, agentStudio)) return false;
const rawLower = errorMessage(error).toLowerCase();
if (matchesAgentStudioMaxStepsMessage(rawLower)) return true;
if (isAgentStudioTokenOutputLimitError(error)) return true;
const banner = promptBlockingBannerMessage(error, agentStudio);
if (banner && /could not complete response due to token output limits/i.test(banner)) return true;
if (banner && matchesAgentStudioMaxStepsMessage(banner.toLowerCase())) return true;
return !showAskAiBlockingBannerNewConversationLink(error, agentStudio);
}
/**
* Banner when the conversation cannot accept further prompts (thread depth or Agent Studio limits).
*/
const ThreadDepthErrorBanner = ({ onNewChat, detailMessage, showNewConversationLink = true }) => /* @__PURE__ */ u("div", {
className: "ss-thread-depth-error-banner",
children: [detailMessage ? /* @__PURE__ */ u("p", {
className: "ss-thread-depth-error-detail",
children: detailMessage
}) : null, showNewConversationLink ? /* @__PURE__ */ u("p", {
className: "ss-thread-depth-error-main",
children: [
onNewChat ? /* @__PURE__ */ u("button", {
type: "button",
className: "ss-thread-depth-error-link",
onClick: onNewChat,
children: "Start a new conversation"
}) : /* @__PURE__ */ u("span", {
className: "ss-thread-depth-error-cta",
children: "Start a new conversation"
}),
" ",
"to continue."
]
}) : null]
});
//#endregion
//#region src/components/search-askai/askai.ts
init_compat_module();
const BASE_ASKAI_URL = "https://askai.algolia.com";
const agentStudioBaseUrl = (appId) => `https://${appId}.algolia.net/agent-studio/1`;
/**
* Resolves the chat API URL for the given config.
* When agentStudio is true, uses Agent Studio completions endpoint.
*/
function getChatApiUrl(config$1) {
if (config$1.agentStudio) return `${agentStudioBaseUrl(config$1.applicationId)}/agents/${config$1.assistantId}/completions?stream=true&compatibilityMode=ai-sdk-5`;
return `${BASE_ASKAI_URL}/chat`;
}
function useAskai(config$1) {
if (!config$1) throw new Error("config is required for useAskai");
const [chatId, setChatId] = d(() => generateId());
const transport = T(() => {
return new DefaultChatTransport({
api: getChatApiUrl(config$1),
headers: async () => {
if (config$1.agentStudio) return {
"x-algolia-api-key": config$1.apiKey,
"x-algolia-application-id": config$1.applicationId
};
const token = await getValidToken({ assistantId: config$1.assistantId });
return {
"x-algolia-api-key": config$1.apiKey,
"x-algolia-application-id": config$1.applicationId,
"x-algolia-index-name": config$1.indexName,
"x-algolia-assistant-id": config$1.assistantId,
"x-ai-sdk-version": "v5",
authorization: `TOKEN ${token}`
};
}
});
}, [
config$1.apiKey,
config$1.applicationId,
config$1.indexName,
config$1.assistantId,
config$1.agentStudio,
config$1
]);
const chat = useChat({
id: chatId,
transport,
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls
});
const chatRef = A(chat);
chatRef.current = chat;
const startNewConversation = q(() => {
chatRef.current.stop();
chatRef.current.clearError();
setChatId(generateId());
}, []);
const isGenerating = chat.status === "submitted" || chat.status === "streaming";
const agentStudioEnabled = Boolean(config$1.agentStudio);
/** Agent Studio cost controls (tokens, steps, rate limit, domain). */
const promptBlockingError = T(() => chat.status === "error" && isAskAiPromptBlockingError(chat.error, agentStudioEnabled), [
chat.status,
chat.error,
agentStudioEnabled
]);
/**
* Banner and input lock: thread depth only after at least one assistant reply;
* other blocks (e.g. rate limit on first turn) show immediately.
*/
const showPromptBlockingError = T(() => promptBlockingError && (isThreadDepthError(chat.error) ? chat.messages.some((m$4) => m$4.role === "assistant") : true), [
promptBlockingError,
chat.error,
chat.messages
]);
return {
...chat,
startNewConversation,
isGenerating,
promptBlockingError,
showPromptBlockingError
};
}
const TOKEN_KEY = "askai_token";
const decode = (token) => {
const [b64] = token.split(".");
return JSON.parse(atob(b64));
};
const isExpired = (token) => {
if (!token) return true;
try {
const { exp } = decode(token);
return Date.now() / 1e3 > exp - 30;
} catch {
return true;
}
};
let inflight = null;
const getValidToken = async ({ assistantId }) => {
const cached$1 = sessionStorage.getItem(TOKEN_KEY);
if (!isExpired(cached$1)) return cached$1;
if (!inflight) inflight = fetch(`${BASE_ASKAI_URL}/chat/token`, {
method: "POST",
headers: {
"x-algolia-assistant-id": assistantId,
"content-type": "application/json"
}
}).then((r$2) => r$2.json()).then(({ token }) => {
sessionStorage.setItem(TOKEN_KEY, token);
return token;
}).finally(() => {
inflight = null;
});
return inflight;
};
const postAgentStudioFeedback = ({ agentId, vote, messageId, appId, apiKey }) => {
const headers = new Headers();
headers.set("x-algolia-application-id", appId);
headers.set("x-algolia-api-key", apiKey);
headers.set("content-type", "application/json");
const baseUrl = `${agentStudioBaseUrl(appId)}/feedback`;
return fetch(baseUrl, {
method: "POST",
body: JSON.stringify({
messageId,
agentId,
vote
}),
headers
});
};
const postFeedback = async ({ assistantId, thumbs, messageId, appId }) => {
const headers = new Headers();
headers.set("x-algolia-assistant-id", assistantId);
headers.set("content-type", "application/json");
const token = await getValidToken({ assistantId });
headers.set("authorization", `TOKEN ${token}`);
return fetch(`${BASE_ASKAI_URL}/chat/feedback`, {
method: "POST",
body: JSON.stringify({
appId,
messageId,
thumbs
}),
headers
});
};
//#endregion
//#region src/components/search-askai/icons.tsx
const LikeIcon = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/* @__PURE__ */ u("path", { d: "M7 10v12" }), /* @__PURE__ */ u("path", { d: "M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z" })]
});
const DislikeIcon = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/* @__PURE__ */ u("path", { d: "M17 14V2" }), /* @__PURE__ */ u("path", { d: "M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z" })]
});
const CopyIcon = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/* @__PURE__ */ u("rect", {
width: "14",
height: "14",
x: "8",
y: "8",
rx: "2",
ry: "2"
}), /* @__PURE__ */ u("path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" })]
});
const SparklesIcon = ({ size = 24, className, gradientIdSuffix = "" }) => {
const g$3 = (base) => `${base}${gradientIdSuffix}`;
return /* @__PURE__ */ u("svg", {
width: size,
height: size,
viewBox: "0 0 16 16",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
className,
"aria-hidden": true,
children: [
/* @__PURE__ */ u("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M8 1.5a.5.5 0 0 1 .475.344L9.75 5.719a.833.833 0 0 0 .53.531l3.876 1.275a.5.5 0 0 1 0 .95L10.281 9.75a.833.833 0 0 0-.531.53l-1.275 3.876a.5.5 0 0 1-.95 0L6.25 10.281a.833.833 0 0 0-.53-.531L1.843 8.475a.5.5 0 0 1 0-.95L5.719 6.25a.833.833 0 0 0 .531-.53l1.275-3.876A.5.5 0 0 1 8 1.5Zm-.8 4.532A1.833 1.833 0 0 1 6.032 7.2L3.6 8l2.432.8A1.833 1.833 0 0 1 7.2 9.968L8 12.4l.8-2.432A1.833 1.833 0 0 1 9.968 8.8L12.4 8l-2.432-.8A1.833 1.833 0 0 1 8.8 6.032L8 3.6l-.8 2.432Z",
fill: `url(#${g$3("8aa5f4b5___a")})`
}),
/* @__PURE__ */ u("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M3.333 1.5a.5.5 0 0 1 .5.5v2.667a.5.5 0 1 1-1 0V2a.5.5 0 0 1 .5-.5Z",
fill: `url(#${g$3("8aa5f4b5___b")})`
}),
/* @__PURE__ */ u("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M12.667 10.833a.5.5 0 0 1 .5.5V14a.5.5 0 0 1-1 0v-2.667a.5.5 0 0 1 .5-.5Z",
fill: `url(#${g$3("8aa5f4b5___c")})`
}),
/* @__PURE__ */ u("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M1.5 3.333a.5.5 0 0 1 .5-.5h2.667a.5.5 0 0 1 0 1H2a.5.5 0 0 1-.5-.5Z",
fill: `url(#${g$3("8aa5f4b5___d")})`
}),
/* @__PURE__ */ u("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M10.833 12.667a.5.5 0 0 1 .5-.5H14a.5.5 0 1 1 0 1h-2.667a.5.5 0 0 1-.5-.5Z",
fill: `url(#${g$3("8aa5f4b5___e")})`
}),
/* @__PURE__ */ u("defs", { children: [
/* @__PURE__ */ u("linearGradient", {
id: g$3("8aa5f4b5___a"),
x1: "15.03",
y1: "8",
x2: "2.03",
y2: "8",
gradientUnits: "userSpaceOnUse",
children: [/* @__PURE__ */ u("stop", {
offset: "0.15",
stopColor: "#8E00FC"
}), /* @__PURE__ */ u("stop", {
offset: "1",
stopColor: "#003DFF"
})]
}),
/* @__PURE__ */ u("linearGradient", {
id: g$3("8aa5f4b5___b"),
x1: "15.03",
y1: "8",
x2: "2.03",
y2: "8",
gradientUnits: "userSpaceOnUse",
children: [/* @__PURE__ */ u("stop", {
offset: "0.15",
stopColor: "#8E00FC"
}), /* @__PURE__ */ u("stop", {
offset: "1",
stopColor: "#003DFF"
})]
}),
/* @__PURE__ */ u("linearGradient", {
id: g$3("8aa5f4b5___c"),
x1: "15.03",
y1: "8",
x2: "2.03",
y2: "8",
gradientUnits: "userSpaceOnUse",
children: [/* @__PURE__ */ u("stop", {
offset: "0.15",
stopColor: "#8E00FC"
}), /* @__PURE__ */ u("stop", {
offset: "1",
stopColor: "#003DFF"
})]
}),
/* @__PURE__ */ u("linearGradient", {
id: g$3("8aa5f4b5___d"),
x1: "15.03",
y1: "8",
x2: "2.03",
y2: "8",
gradientUnits: "userSpaceOnUse",
children: [/* @__PURE__ */ u("stop", {
offset: "0.15",
stopColor: "#8E00FC"
}), /* @__PURE__ */ u("stop", {
offset: "1",
stopColor: "#003DFF"
})]
}),
/* @__PURE__ */ u("linearGradient", {
id: g$3("8aa5f4b5___e"),
x1: "15.03",
y1: "8",
x2: "2.03",
y2: "8",
gradientUnits: "userSpaceOnUse",
children: [/* @__PURE__ */ u("stop", {
offset: "0.15",
stopColor: "#8E00FC"
}), /* @__PURE__ */ u("stop", {
offset: "1",
stopColor: "#003DFF"
})]
})
] })
]
});
};
const SearchIcon = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
fill: color,
width: size,
height: size,
children: [/* @__PURE__ */ u("circle", {
cx: "11",
cy: "11",
r: "8",
stroke: color,
fill: "none",
strokeWidth: "1.4"
}), /* @__PURE__ */ u("path", {
d: "m21 21-4.3-4.3",
stroke: color,
fill: "none",
strokeLinecap: "round",
strokeLinejoin: "round"
})]
});
const ArrowLeftIcon = ({ size = 24, color = "currentColor", className }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
fill: color,
width: size,
height: size,
className,
children: /* @__PURE__ */ u("path", {
fill: color,
d: "M20 11v2H8l5.5 5.5l-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5L8 11z"
})
});
const CloseIcon = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [
" ",
/* @__PURE__ */ u("path", { d: "M18 6 6 18" }),
/* @__PURE__ */ u("path", { d: "m6 6 12 12" })
]
});
const AlgoliaLogo = ({ size = 150 }) => /* @__PURE__ */ u("svg", {
width: "80",
height: "24",
"aria-label": "Algolia",
role: "img",
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 2196.2 500",
style: { maxWidth: size },
children: [
/* @__PURE__ */ u("defs", { children: /* @__PURE__ */ u("style", { children: `.cls-1,.cls-2{fill:#003dff}.cls-2{fillRule:evenodd}` }) }),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1070.38,275.3V5.91c0-3.63-3.24-6.39-6.82-5.83l-50.46,7.94c-2.87,.45-4.99,2.93-4.99,5.84l.17,273.22c0,12.92,0,92.7,95.97,95.49,3.33,.1,6.09-2.58,6.09-5.91v-40.78c0-2.96-2.19-5.51-5.12-5.84-34.85-4.01-34.85-47.57-34.85-54.72Z"
}),
/* @__PURE__ */ u("rect", {
className: "cls-1",
x: "1845.88",
y: "104.73",
width: "62.58",
height: "277.9",
rx: "5.9",
ry: "5.9"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1851.78,71.38h50.77c3.26,0,5.9-2.64,5.9-5.9V5.9c0-3.62-3.24-6.39-6.82-5.83l-50.77,7.95c-2.87,.45-4.99,2.92-4.99,5.83v51.62c0,3.26,2.64,5.9,5.9,5.9Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1764.03,275.3V5.91c0-3.63-3.24-6.39-6.82-5.83l-50.46,7.94c-2.87,.45-4.99,2.93-4.99,5.84l.17,273.22c0,12.92,0,92.7,95.97,95.49,3.33,.1,6.09-2.58,6.09-5.91v-40.78c0-2.96-2.19-5.51-5.12-5.84-34.85-4.01-34.85-47.57-34.85-54.72Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1631.95,142.72c-11.14-12.25-24.83-21.65-40.78-28.31-15.92-6.53-33.26-9.85-52.07-9.85-18.78,0-36.15,3.17-51.92,9.85-15.59,6.66-29.29,16.05-40.76,28.31-11.47,12.23-20.38,26.87-26.76,44.03-6.38,17.17-9.24,37.37-9.24,58.36,0,20.99,3.19,36.87,9.55,54.21,6.38,17.32,15.14,32.11,26.45,44.36,11.29,12.23,24.83,21.62,40.6,28.46,15.77,6.83,40.12,10.33,52.4,10.48,12.25,0,36.78-3.82,52.7-10.48,15.92-6.68,29.46-16.23,40.78-28.46,11.29-12.25,20.05-27.04,26.25-44.36,6.22-17.34,9.24-33.22,9.24-54.21,0-20.99-3.34-41.19-10.03-58.36-6.38-17.17-15.14-31.8-26.43-44.03Zm-44.43,163.75c-11.47,15.75-27.56,23.7-48.09,23.7-20.55,0-36.63-7.8-48.1-23.7-11.47-15.75-17.21-34.01-17.21-61.2,0-26.89,5.59-49.14,17.06-64.87,11.45-15.75,27.54-23.52,48.07-23.52,20.55,0,36.63,7.78,48.09,23.52,11.47,15.57,17.36,37.98,17.36,64.87,0,27.19-5.72,45.3-17.19,61.2Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M894.42,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-14.52,22.58-22.99,49.63-22.99,78.73,0,44.89,20.13,84.92,51.59,111.1,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47,1.23,0,2.46-.03,3.68-.09,.36-.02,.71-.05,1.07-.07,.87-.05,1.75-.11,2.62-.2,.34-.03,.68-.08,1.02-.12,.91-.1,1.82-.21,2.73-.34,.21-.03,.42-.07,.63-.1,32.89-5.07,61.56-30.82,70.9-62.81v57.83c0,3.26,2.64,5.9,5.9,5.9h50.42c3.26,0,5.9-2.64,5.9-5.9V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,206.92c-12.2,10.16-27.97,13.98-44.84,15.12-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-42.24,0-77.12-35.89-77.12-79.37,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33v142.83Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M2133.97,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-14.52,22.58-22.99,49.63-22.99,78.73,0,44.89,20.13,84.92,51.59,111.1,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47,1.23,0,2.46-.03,3.68-.09,.36-.02,.71-.05,1.07-.07,.87-.05,1.75-.11,2.62-.2,.34-.03,.68-.08,1.02-.12,.91-.1,1.82-.21,2.73-.34,.21-.03,.42-.07,.63-.1,32.89-5.07,61.56-30.82,70.9-62.81v57.83c0,3.26,2.64,5.9,5.9,5.9h50.42c3.26,0,5.9-2.64,5.9-5.9V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,206.92c-12.2,10.16-27.97,13.98-44.84,15.12-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-42.24,0-77.12-35.89-77.12-79.37,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33v142.83Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-2",
d: "M1314.05,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-11.79,18.34-19.6,39.64-22.11,62.59-.58,5.3-.88,10.68-.88,16.14s.31,11.15,.93,16.59c4.28,38.09,23.14,71.61,50.66,94.52,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47h0c17.99,0,34.61-5.93,48.16-15.97,16.29-11.58,28.88-28.54,34.48-47.75v50.26h-.11v11.08c0,21.84-5.71,38.27-17.34,49.36-11.61,11.08-31.04,16.63-58.25,16.63-11.12,0-28.79-.59-46.6-2.41-2.83-.29-5.46,1.5-6.27,4.22l-12.78,43.11c-1.02,3.46,1.27,7.02,4.83,7.53,21.52,3.08,42.52,4.68,54.65,4.68,48.91,0,85.16-10.75,108.89-32.21,21.48-19.41,33.15-48.89,35.2-88.52V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,64.1s.65,139.13,0,143.36c-12.08,9.77-27.11,13.59-43.49,14.7-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-1.32,0-2.63-.03-3.94-.1-40.41-2.11-74.52-37.26-74.52-79.38,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33Z"
}),
/* @__PURE__ */ u("path", {
className: "cls-1",
d: "M249.83,0C113.3,0,2,110.09,.03,246.16c-2,138.19,110.12,252.7,248.33,253.5,42.68,.25,83.79-10.19,120.3-30.03,3.56-1.93,4.11-6.83,1.08-9.51l-23.38-20.72c-4.75-4.21-11.51-5.4-17.36-2.92-25.48,10.84-53.17,16.38-81.71,16.03-111.68-1.37-201.91-94.29-200.13-205.96,1.76-110.26,92-199.41,202.67-199.41h202.69V407.41l-115-102.18c-3.72-3.31-9.42-2.66-12.42,1.31-18.46,24.44-48.53,39.64-81.93,37.34-46.33-3.2-83.87-40.5-87.34-86.81-4.15-55.24,39.63-101.52,94-101.52,49.18,0,89.68,37.85,93.91,85.95,.38,4.28,2.31,8.27,5.52,11.12l29.95,26.55c3.4,3.01,8.79,1.17,9.63-3.3,2.16-11.55,2.92-23.58,2.07-35.92-4.82-70.34-61.8-126.93-132.17-131.26-80.68-4.97-148.13,58.14-150.27,137.25-2.09,77.1,61.08,143.56,138.19,145.26,32.19,.71,62.03-9.41,86.14-26.95l150.26,133.2c6.44,5.71,16.61,1.14,16.61-7.47V9.48C499.66,4.25,495.42,0,490.18,0H249.83Z"
})
]
});
const BrainIcon = ({ size = 20, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 20 20",
children: /* @__PURE__ */ u("path", {
fill: color,
d: "m14.878.282l.348 1.071a2.2 2.2 0 0 0 1.399 1.397l1.071.348l.021.006a.423.423 0 0 1 0 .798l-1.071.348a2.2 2.2 0 0 0-1.399 1.397l-.348 1.07a.423.423 0 0 1-.798 0l-.349-1.07a2.2 2.2 0 0 0-.532-.867a2.2 2.2 0 0 0-.866-.536l-1.071-.348a.423.423 0 0 1 0-.798l1.071-.348a2.2 2.2 0 0 0 1.377-1.397l.348-1.07a.423.423 0 0 1 .799 0m4.905 7.931l-.766-.248a1.58 1.58 0 0 1-.998-.999l-.25-.764a.302.302 0 0 0-.57 0l-.248.764a1.58 1.58 0 0 1-.984.999l-.765.248a.303.303 0 0 0 0 .57l.765.249a1.58 1.58 0 0 1 1 1.002l.248.764a.302.302 0 0 0 .57 0l.249-.764a1.58 1.58 0 0 1 .999-.999l.765-.248a.303.303 0 0 0 0-.57zM16.97 11.89a1.46 1.46 0 0 0 1.013.038q.016.158.016.32a3.25 3.25 0 0 1-2.575 3.178l-.037.185A2.973 2.973 0 0 1 10 16.678a2.973 2.973 0 0 1-5.388-1.068l-.037-.185a3.248 3.248 0 0 1-.77-6.088A2.5 2.5 0 0 1 3 7.5v-.198a2.7 2.7 0 0 1 2.169-2.646l.406-.08l.125-.628a2.423 2.423 0 0 1 4.3-1a2.4 2.4 0 0 1 .293-.318l-.033.045c-.17.24-.26.52-.26.821s.09.581.26.821q.104.147.24.265v10.445a1.973 1.973 0 0 0 3.907.387l.103-.512a.5.5 0 0 1 .392-.392l.291-.059a2.25 2.25 0 0 0 1.778-2.562M9.5 15.027V4.423a1.423 1.423 0 0 0-2.819-.279l-.19.954a.5.5 0 0 1-.393.392l-.733.147A1.7 1.7 0 0 0 4 7.302V7.5A1.5 1.5 0 0 0 5.5 9a.5.5 0 0 1 0 1h-.252a2.248 2.248 0 0 0-.441 4.451l.291.059a.5.5 0 0 1 .392.392l.103.512a1.973 1.973 0 0 0 3.907-.387"
})
});
const CheckIcon = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: /* @__PURE__ */ u("path", { d: "M20 6 9 17l-5-5" })
});
const SquarePenIcon = ({ size = 24, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/* @__PURE__ */ u("path", { d: "M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" }), /* @__PURE__ */ u("path", { d: "M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z" })]
});
const ChatSubmitIcon = ({ size = 22, color = "currentColor" }) => /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: "2.25",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/* @__PURE__ */ u("path", { d: "m5 12 7-7 7 7" }), /* @__PURE__ */ u("path", { d: "M12 19V5" })]
});
//#endregion
//#region ../../node_modules/.bun/marked@16.4.0/node_modules/marked/lib/marked.esm.js
/**
* marked v16.4.0 - a markdown parser
* Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed)
* https://github.com/markedjs/marked
*/
/**
* DO NOT EDIT THIS FILE
* The code in this file is generated from files in ./src/
*/
function L() {
return {
async: !1,
breaks: !1,
extensions: null,
gfm: !0,
hooks: null,
pedantic: !1,
renderer: null,
silent: !1,
tokenizer: null,
walkTokens: null
};
}
var T$1 = L();
function G(u$3) {
T$1 = u$3;
}
var I = { exec: () => null };
function d$1(u$3, e$2 = "") {
let t$2 = typeof u$3 == "string" ? u$3 : u$3.source, n$1 = {
replace: (r$2, i$3) => {
let s$2 = typeof i$3 == "string" ? i$3 : i$3.source;
return s$2 = s$2.replace(m.caret, "$1"), t$2 = t$2.replace(r$2, s$2), n$1;
},
getRegex: () => new RegExp(t$2, e$2)
};
return n$1;
}
var m = {
codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm,
outputLinkReplace: /\\([\[\]])/g,
indentCodeCompensation: /^(\s+)(?:```)/,
beginningSpace: /^\s+/,
endingHash: /#$/,
startingSpaceChar: /^ /,
endingSpaceChar: / $/,
nonSpaceChar: /[^ ]/,
newLineCharGlobal: /\n/g,
tabCharGlobal: /\t/g,
multipleSpaceGlobal: /\s+/g,
blankLine: /^[ \t]*$/,
doubleBlankLine: /\n[ \t]*\n[ \t]*$/,
blockquoteStart: /^ {0,3}>/,
blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g,
blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm,
listReplaceTabs: /^\t+/,
listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,
listIsTask: /^\[[ xX]\] /,
listReplaceTask: /^\[[ xX]\] +/,
anyLine: /\n.*\n/,
hrefBrackets: /^<(.*)>$/,
tableDelimiter: /[:|]/,
tableAlignChars: /^\||\| *$/g,
tableRowBlankLine: /\n[ \t]*$/,
tableAlignRight: /^ *-+: *$/,
tableAlignCenter: /^ *:-+: *$/,
tableAlignLeft: /^ *:-+ *$/,
startATag: /^<a /i,
endATag: /^<\/a>/i,
startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i,
endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i,
startAngleBracket: /^</,
endAngleBracket: />$/,
pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/,
unicodeAlphaNumeric: /[\p{L}\p{N}]/u,
escapeTest: /[&<>"']/,
escapeReplace: /[&<>"']/g,
escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,
caret: /(^|[^\[])\^/g,
percentDecode: /%25/g,
findPipe: /\|/g,
splitPipe: / \|/,
slashPipe: /\\\|/g,
carriageReturn: /\r\n|\r/g,
spaceLine: /^ +$/gm,
notSpaceStart: /^\S*/,
endingNewline: /\n$/,
listItemRegex: (u$3) => new RegExp(`^( {0,3}${u$3})((?:[ ][^\\n]*)?(?:\\n|$))`),
nextBulletRegex: (u$3) => new RegExp(`^ {0,${Math.min(3, u$3 - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),
hrRegex: (u$3) => new RegExp(`^ {0,${Math.min(3, u$3 - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),
fencesBeginRegex: (u$3) => new RegExp(`^ {0,${Math.min(3, u$3 - 1)}}(?:\`\`\`|~~~)`),
headingBeginRegex: (u$3) => new RegExp(`^ {0,${Math.min(3, u$3 - 1)}}#`),
htmlBeginRegex: (u$3) => new RegExp(`^ {0,${Math.min(3, u$3 - 1)}}<(?:[a-z].*>|!--)`, "i")
}, be = /^(?:[ \t]*(?:\n|$))+/, Re = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/, Te = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/, E = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/, Oe = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, F = /(?:[*+-]|\d{1,9}[.)])/, ie = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/, oe = d$1(ie).replace(/bull/g, F).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex(), we = d$1(ie).replace(/bull/g, F).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(), j = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/, ye = /^[^\n]+/, Q = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/, Pe = d$1(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", Q).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(), Se = d$1(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, F).getRegex(), v = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul", U = /<!--(?:-?>|[\s\S]*?(?:-->|$))/, $e = d$1("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))", "i").replace("comment", U).replace("tag", v).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(), ae = d$1(j).replace("hr", E).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex(), _e = d$1(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", ae).getRegex(), K = {
blockquote: _e,
code: Re,
def: Pe,
fences: Te,
heading: Oe,
hr: E,
html: $e,
lheading: oe,
list: Se,
newline: be,
paragraph: ae,
table: I,
text: ye
}, re = d$1("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", E).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3} )[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex(), Le = {
...K,
lheading: we,
table: re,
paragraph: d$1(j).replace("hr", E).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", re).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex()
}, Me = {
...K,
html: d$1(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", U).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
heading: /^(#{1,6})(.*)(?:\n+|$)/,
fences: I,
lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
paragraph: d$1(j).replace("hr", E).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", oe).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
}, ze = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, Ae = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, le = /^( {2,}|\\)\n(?!\s*$)/, Ie = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/, D = /[\p{P}\p{S}]/u, W = /[\s\p{P}\p{S}]/u, ue = /[^\s\p{P}\p{S}]/u, Ee = d$1(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, W).getRegex(), pe = /(?!~)[\p{P}\p{S}]/u, Ce = /(?!~)[\s\p{P}\p{S}]/u, Be = /(?:[^\s\p{P}\p{S}]|~)/u, qe = /\[(?:[^\[\]`]|`[^`]*?`)*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)|`[^`]*?`|<(?! )[^<>]*?>/g, ce = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/, ve = d$1(ce, "u").replace(/punct/g, D).getRegex(), De = d$1(ce, "u").replace(/punct/g, pe).getRegex(), he = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)", He = d$1(he, "gu").replace(/notPunctSpace/g, ue).replace(/punctSpace/g, W).replace(/punct/g, D).getRegex(), Ze = d$1(he, "gu").replace(/notPunctSpace/g, Be).replace(/punctSpace/g, Ce).replace(/punct/g, pe).getRegex(), Ge = d$1("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, ue).replace(/punctSpace/g, W).replace(/punct/g, D).getRegex(), Ne = d$1(/\\(punct)/, "gu").replace(/punct/g, D).getRegex(), Fe = d$1(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[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])?)+(?![-_])/).getRegex(), je = d$1(U).replace("(?:-->|$)", "-->").getRegex(), Qe = d$1("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", je).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(), q$1 = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/, Ue = d$1(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", q$1).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(), de = d$1(/^!?\[(label)\]\[(ref)\]/).replace("label", q$1).replace("ref", Q).getRegex(), ke = d$1(/^!?\[(ref)\](?:\[\])?/).replace("ref", Q).getRegex(), Ke = d$1("reflink|nolink(?!\\()", "g").replace("reflink", de).replace("nolink", ke).getRegex(), se = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/, X = {
_backpedal: I,
anyPunctuation: Ne,
autolink: Fe,
blockSkip: qe,
br: le,
code: Ae,
del: I,
emStrongLDelim: ve,
emStrongRDelimAst: He,
emStrongRDelimUnd: Ge,
escape: ze,
link: Ue,
nolink: ke,
punctuation: Ee,
reflink: de,
reflinkSearch: Ke,
tag: Qe,
text: Ie,
url: I
}, We = {
...X,
link: d$1(/^!?\[(label)\]\((.*?)\)/).replace("label", q$1).getRegex(),
reflink: d$1(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", q$1).getRegex()
}, N = {
...X,
emStrongRDelimAst: Ze,
emStrongLDelim: De,
url: d$1(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", se).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
_backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,
text: d$1(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol", se).getRegex()
}, Xe = {
...N,
br: d$1(le).replace("{2,}", "*").getRegex(),
text: d$1(N.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
}, C = {
normal: K,
gfm: Le,
pedantic: Me
}, M$1 = {
normal: X,
gfm: N,
breaks: Xe,
pedantic: We
};
var Je = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
}, ge = (u$3) => Je[u$3];
function w(u$3, e$2) {
if (e$2) {
if (m.escapeTest.test(u$3)) return u$3.replace(m.escapeReplace, ge);
} else if (m.escapeTestNoEncode.test(u$3)) return u$3.replace(m.escapeReplaceNoEncode, ge);
return u$3;
}
function J(u$3) {
try {
u$3 = encodeURI(u$3).replace(m.percentDecode, "%");
} catch {
return null;
}
return u$3;
}
function V(u$3, e$2) {
let t$2 = u$3.replace(m.findPipe, (i$3, s$2, o$3) => {
let a$2 = !1, l$2 = s$2;
for (; --l$2 >= 0 && o$3[l$2] === "\\";) a$2 = !a$2;
return a$2 ? "|" : " |";
}), n$1 = t$2.split(m.splitPipe), r$2 = 0;
if (n$1[0].trim() || n$1.shift(), n$1.length > 0 && !n$1.at(-1)?.trim() && n$1.pop(), e$2) if (n$1.length > e$2) n$1.splice(e$2);
else for (; n$1.length < e$2;) n$1.push("");
for (; r$2 < n$1.length; r$2++) n$1[r$2] = n$1[r$2].trim().replace(m.slashPipe, "|");
return n$1;
}
function z(u$3, e$2, t$2) {
let n$1 = u$3.length;
if (n$1 === 0) return "";
let r$2 = 0;
for (; r$2 < n$1;) {
let i$3 = u$3.charAt(n$1 - r$2 - 1);
if (i$3 === e$2 && !t$2) r$2++;
else if (i$3 !== e$2 && t$2) r$2++;
else break;
}
return u$3.slice(0, n$1 - r$2);
}
function fe(u$3, e$2) {
if (u$3.indexOf(e$2[1]) === -1) return -1;
let t$2 = 0;
for (let n$1 = 0; n$1 < u$3.length; n$1++) if (u$3[n$1] === "\\") n$1++;
else if (u$3[n$1] === e$2[0]) t$2++;
else if (u$3[n$1] === e$2[1] && (t$2--, t$2 < 0)) return n$1;
return t$2 > 0 ? -2 : -1;
}
function me(u$3, e$2, t$2, n$1, r$2) {
let i$3 = e$2.href, s$2 = e$2.title || null, o$3 = u$3[1].replace(r$2.other.outputLinkReplace, "$1");
n$1.state.inLink = !0;
let a$2 = {
type: u$3[0].charAt(0) === "!" ? "image" : "link",
raw: t$2,
href: i$3,
title: s$2,
text: o$3,
tokens: n$1.inlineTokens(o$3)
};
return n$1.state.inLink = !1, a$2;
}
function Ve(u$3, e$2, t$2) {
let n$1 = u$3.match(t$2.other.indentCodeCompensation);
if (n$1 === null) return e$2;
let r$2 = n$1[1];
return e$2.split(`
`).map((i$3) => {
let s$2 = i$3.match(t$2.other.beginningSpace);
if (s$2 === null) return i$3;
let [o$3] = s$2;
return o$3.length >= r$2.length ? i$3.slice(r$2.length) : i$3;
}).join(`
`);
}
var y$1 = class {
options;
rules;
lexer;
constructor(e$2) {
this.options = e$2 || T$1;
}
space(e$2) {
let t$2 = this.rules.block.newline.exec(e$2);
if (t$2 && t$2[0].length > 0) return {
type: "space",
raw: t$2[0]
};
}
code(e$2) {
let t$2 = this.rules.block.code.exec(e$2);
if (t$2) {
let n$1 = t$2[0].replace(this.rules.other.codeRemoveIndent, "");
return {
type: "code",
raw: t$2[0],
codeBlockStyle: "indented",
text: this.options.pedantic ? n$1 : z(n$1, `
`)
};
}
}
fences(e$2) {
let t$2 = this.rules.block.fences.exec(e$2);
if (t$2) {
let n$1 = t$2[0], r$2 = Ve(n$1, t$2[3] || "", this.rules);
return {
type: "code",
raw: n$1,
lang: t$2[2] ? t$2[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t$2[2],
text: r$2
};
}
}
heading(e$2) {
let t$2 = this.rules.block.heading.exec(e$2);
if (t$2) {
let n$1 = t$2[2].trim();
if (this.rules.other.endingHash.test(n$1)) {
let r$2 = z(n$1, "#");
(this.options.pedantic || !r$2 || this.rules.other.endingSpaceChar.test(r$2)) && (n$1 = r$2.trim());
}
return {
type: "heading",
raw: t$2[0],
depth: t$2[1].length,
text: n$1,
tokens: this.lexer.inline(n$1)
};
}
}
hr(e$2) {
let t$2 = this.rules.block.hr.exec(e$2);
if (t$2) return {
type: "hr",
raw: z(t$2[0], `
`)
};
}
blockquote(e$2) {
let t$2 = this.rules.block.blockquote.exec(e$2);
if (t$2) {
let n$1 = z(t$2[0], `
`).split(`
`), r$2 = "", i$3 = "", s$2 = [];
for (; n$1.length > 0;) {
let o$3 = !1, a$2 = [], l$2;
for (l$2 = 0; l$2 < n$1.length; l$2++) if (this.rules.other.blockquoteStart.test(n$1[l$2])) a$2.push(n$1[l$2]), o$3 = !0;
else if (!o$3) a$2.push(n$1[l$2]);
else break;
n$1 = n$1.slice(l$2);
let c$2 = a$2.join(`
`), p$2 = c$2.replace(this.rules.other.blockquoteSetextReplace, `
$1`).replace(this.rules.other.blockquoteSetextReplace2, "");
r$2 = r$2 ? `${r$2}
${c$2}` : c$2, i$3 = i$3 ? `${i$3}
${p$2}` : p$2;
let g$3 = this.lexer.state.top;
if (this.lexer.state.top = !0, this.lexer.blockTokens(p$2, s$2, !0), this.lexer.state.top = g$3, n$1.length === 0) break;
let h$2 = s$2.at(-1);
if (h$2?.type === "code") break;
if (h$2?.type === "blockquote") {
let R$1 = h$2, f$3 = R$1.raw + `
` + n$1.join(`
`), O$2 = this.blockquote(f$3);
s$2[s$2.length - 1] = O$2, r$2 = r$2.substring(0, r$2.length - R$1.raw.length) + O$2.raw, i$3 = i$3.substring(0, i$3.length - R$1.text.length) + O$2.text;
break;
} else if (h$2?.type === "list") {
let R$1 = h$2, f$3 = R$1.raw + `
` + n$1.join(`
`), O$2 = this.list(f$3);
s$2[s$2.length - 1] = O$2, r$2 = r$2.substring(0, r$2.length - h$2.raw.length) + O$2.raw, i$3 = i$3.substring(0, i$3.length - R$1.raw.length) + O$2.raw, n$1 = f$3.substring(s$2.at(-1).raw.length).split(`
`);
continue;
}
}
return {
type: "blockquote",
raw: r$2,
tokens: s$2,
text: i$3
};
}
}
list(e$2) {
let t$2 = this.rules.block.list.exec(e$2);
if (t$2) {
let n$1 = t$2[1].trim(), r$2 = n$1.length > 1, i$3 = {
type: "list",
raw: "",
ordered: r$2,
start: r$2 ? +n$1.slice(0, -1) : "",
loose: !1,
items: []
};
n$1 = r$2 ? `\\d{1,9}\\${n$1.slice(-1)}` : `\\${n$1}`, this.options.pedantic && (n$1 = r$2 ? n$1 : "[*+-]");
let s$2 = this.rules.other.listItemRegex(n$1), o$3 = !1;
for (; e$2;) {
let l$2 = !1, c$2 = "", p$2 = "";
if (!(t$2 = s$2.exec(e$2)) || this.rules.block.hr.test(e$2)) break;
c$2 = t$2[0], e$2 = e$2.substring(c$2.length);
let g$3 = t$2[2].split(`
`, 1)[0].replace(this.rules.other.listReplaceTabs, (H$2) => " ".repeat(3 * H$2.length)), h$2 = e$2.split(`
`, 1)[0], R$1 = !g$3.trim(), f$3 = 0;
if (this.options.pedantic ? (f$3 = 2, p$2 = g$3.trimStart()) : R$1 ? f$3 = t$2[1].length + 1 : (f$3 = t$2[2].search(this.rules.other.nonSpaceChar), f$3 = f$3 > 4 ? 1 : f$3, p$2 = g$3.slice(f$3), f$3 += t$2[1].length), R$1 && this.rules.other.blankLine.test(h$2) && (c$2 += h$2 + `
`, e$2 = e$2.substring(h$2.length + 1), l$2 = !0), !l$2) {
let H$2 = this.rules.other.nextBulletRegex(f$3), ee = this.rules.other.hrRegex(f$3), te = this.rules.other.fencesBeginRegex(f$3), ne = this.rules.other.headingBeginRegex(f$3), xe = this.rules.other.htmlBeginRegex(f$3);
for (; e$2;) {
let Z$1 = e$2.split(`
`, 1)[0], A$3;
if (h$2 = Z$1, this.options.pedantic ? (h$2 = h$2.replace(this.rules.other.listReplaceNesting, " "), A$3 = h$2) : A$3 = h$2.replace(this.rules.other.tabCharGlobal, " "), te.test(h$2) || ne.test(h$2) || xe.test(h$2) || H$2.test(h$2) || ee.test(h$2)) break;
if (A$3.search(this.rules.other.nonSpaceChar) >= f$3 || !h$2.trim()) p$2 += `
` + A$3.slice(f$3);
else {
if (R$1 || g$3.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4 || te.test(g$3) || ne.test(g$3) || ee.test(g$3)) break;
p$2 += `
` + h$2;
}
!R$1 && !h$2.trim() && (R$1 = !0), c$2 += Z$1 + `
`, e$2 = e$2.substring(Z$1.length + 1), g$3 = A$3.slice(f$3);
}
}
i$3.loose || (o$3 ? i$3.loose = !0 : this.rules.other.doubleBlankLine.test(c$2) && (o$3 = !0));
let O$2 = null, Y$1;
this.options.gfm && (O$2 = this.rules.other.listIsTask.exec(p$2), O$2 && (Y$1 = O$2[0] !== "[ ] ", p$2 = p$2.replace(this.rules.other.listReplaceTask, ""))), i$3.items.push({
type: "list_item",
raw: c$2,
task: !!O$2,
checked: Y$1,
loose: !1,
text: p$2,
tokens: []
}), i$3.raw += c$2;
}
let a$2 = i$3.items.at(-1);
if (a$2) a$2.raw = a$2.raw.trimEnd(), a$2.text = a$2.text.trimEnd();
else return;
i$3.raw = i$3.raw.trimEnd();
for (let l$2 = 0; l$2 < i$3.items.length; l$2++) if (this.lexer.state.top = !1, i$3.items[l$2].tokens = this.lexer.blockTokens(i$3.items[l$2].text, []), !i$3.loose) {
let c$2 = i$3.items[l$2].tokens.filter((g$3) => g$3.type === "space"), p$2 = c$2.length > 0 && c$2.some((g$3) => this.rules.other.anyLine.test(g$3.raw));
i$3.loose = p$2;
}
if (i$3.loose) for (let l$2 = 0; l$2 < i$3.items.length; l$2++) i$3.items[l$2].loose = !0;
return i$3;
}
}
html(e$2) {
let t$2 = this.rules.block.html.exec(e$2);
if (t$2) return {
type: "html",
block: !0,
raw: t$2[0],
pre: t$2[1] === "pre" || t$2[1] === "script" || t$2[1] === "style",
text: t$2[0]
};
}
def(e$2) {
let t$2 = this.rules.block.def.exec(e$2);
if (t$2) {
let n$1 = t$2[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), r$2 = t$2[2] ? t$2[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", i$3 = t$2[3] ? t$2[3].substring(1, t$2[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t$2[3];
return {
type: "def",
tag: n$1,
raw: t$2[0],
href: r$2,
title: i$3
};
}
}
table(e$2) {
let t$2 = this.rules.block.table.exec(e$2);
if (!t$2 || !this.rules.other.tableDelimiter.test(t$2[2])) return;
let n$1 = V(t$2[1]), r$2 = t$2[2].replace(this.rules.other.tableAlignChars, "").split("|"), i$3 = t$2[3]?.trim() ? t$2[3].replace(this.rules.other.tableRowBlankLine, "").split(`
`) : [], s$2 = {
type: "table",
raw: t$2[0],
header: [],
align: [],
rows: []
};
if (n$1.length === r$2.length) {
for (let o$3 of r$2) this.rules.other.tableAlignRight.test(o$3) ? s$2.align.push("right") : this.rules.other.tableAlignCenter.test(o$3) ? s$2.align.push("center") : this.rules.other.tableAlignLeft.test(o$3) ? s$2.align.push("left") : s$2.align.push(null);
for (let o$3 = 0; o$3 < n$1.length; o$3++) s$2.header.push({
text: n$1[o$3],
tokens: this.lexer.inline(n$1[o$3]),
header: !0,
align: s$2.align[o$3]
});
for (let o$3 of i$3) s$2.rows.push(V(o$3, s$2.header.length).map((a$2, l$2) => ({
text: a$2,
tokens: this.lexer.inline(a$2),
header: !1,
align: s$2.align[l$2]
})));
return s$2;
}
}
lheading(e$2) {
let t$2 = this.rules.block.lheading.exec(e$2);
if (t$2) return {
type: "heading",
raw: t$2[0],
depth: t$2[2].charAt(0) === "=" ? 1 : 2,
text: t$2[1],
tokens: this.lexer.inline(t$2[1])
};
}
paragraph(e$2) {
let t$2 = this.rules.block.paragraph.exec(e$2);
if (t$2) {
let n$1 = t$2[1].charAt(t$2[1].length - 1) === `
` ? t$2[1].slice(0, -1) : t$2[1];
return {
type: "paragraph",
raw: t$2[0],
text: n$1,
tokens: this.lexer.inline(n$1)
};
}
}
text(e$2) {
let t$2 = this.rules.block.text.exec(e$2);
if (t$2) return {
type: "text",
raw: t$2[0],
text: t$2[0],
tokens: this.lexer.inline(t$2[0])
};
}
escape(e$2) {
let t$2 = this.rules.inline.escape.exec(e$2);
if (t$2) return {
type: "escape",
raw: t$2[0],
text: t$2[1]
};
}
tag(e$2) {
let t$2 = this.rules.inline.tag.exec(e$2);
if (t$2) return !this.lexer.state.inLink && this.rules.other.startATag.test(t$2[0]) ? this.lexer.state.inLink = !0 : this.lexer.state.inLink && this.rules.other.endATag.test(t$2[0]) && (this.lexer.state.inLink = !1), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t$2[0]) ? this.lexer.state.inRawBlock = !0 : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t$2[0]) && (this.lexer.state.inRawBlock = !1), {
type: "html",
raw: t$2[0],
inLink: this.lexer.state.inLink,
inRawBlock: this.lexer.state.inRawBlock,
block: !1,
text: t$2[0]
};
}
link(e$2) {
let t$2 = this.rules.inline.link.exec(e$2);
if (t$2) {
let n$1 = t$2[2].trim();
if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n$1)) {
if (!this.rules.other.endAngleBracket.test(n$1)) return;
let s$2 = z(n$1.slice(0, -1), "\\");
if ((n$1.length - s$2.length) % 2 === 0) return;
} else {
let s$2 = fe(t$2[2], "()");
if (s$2 === -2) return;
if (s$2 > -1) {
let a$2 = (t$2[0].indexOf("!") === 0 ? 5 : 4) + t$2[1].length + s$2;
t$2[2] = t$2[2].substring(0, s$2), t$2[0] = t$2[0].substring(0, a$2).trim(), t$2[3] = "";
}
}
let r$2 = t$2[2], i$3 = "";
if (this.options.pedantic) {
let s$2 = this.rules.other.pedanticHrefTitle.exec(r$2);
s$2 && (r$2 = s$2[1], i$3 = s$2[3]);
} else i$3 = t$2[3] ? t$2[3].slice(1, -1) : "";
return r$2 = r$2.trim(), this.rules.other.startAngleBracket.test(r$2) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n$1) ? r$2 = r$2.slice(1) : r$2 = r$2.slice(1, -1)), me(t$2, {
href: r$2 && r$2.replace(this.rules.inline.anyPunctuation, "$1"),
title: i$3 && i$3.replace(this.rules.inline.anyPunctuation, "$1")
}, t$2[0], this.lexer, this.rules);
}
}
reflink(e$2, t$2) {
let n$1;
if ((n$1 = this.rules.inline.reflink.exec(e$2)) || (n$1 = this.rules.inline.nolink.exec(e$2))) {
let r$2 = (n$1[2] || n$1[1]).replace(this.rules.other.multipleSpaceGlobal, " "), i$3 = t$2[r$2.toLowerCase()];
if (!i$3) {
let s$2 = n$1[0].charAt(0);
return {
type: "text",
raw: s$2,
text: s$2
};
}
return me(n$1, i$3, n$1[0], this.lexer, this.rules);
}
}
emStrong(e$2, t$2, n$1 = "") {
let r$2 = this.rules.inline.emStrongLDelim.exec(e$2);
if (!r$2 || r$2[3] && n$1.match(this.rules.other.unicodeAlphaNumeric)) return;
if (!(r$2[1] || r$2[2] || "") || !n$1 || this.rules.inline.punctuation.exec(n$1)) {
let s$2 = [...r$2[0]].length - 1, o$3, a$2, l$2 = s$2, c$2 = 0, p$2 = r$2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
for (p$2.lastIndex = 0, t$2 = t$2.slice(-1 * e$2.length + s$2); (r$2 = p$2.exec(t$2)) != null;) {
if (o$3 = r$2[1] || r$2[2] || r$2[3] || r$2[4] || r$2[5] || r$2[6], !o$3) continue;
if (a$2 = [...o$3].length, r$2[3] || r$2[4]) {
l$2 += a$2;
continue;
} else if ((r$2[5] || r$2[6]) && s$2 % 3 && !((s$2 + a$2) % 3)) {
c$2 += a$2;
continue;
}
if (l$2 -= a$2, l$2 > 0) continue;
a$2 = Math.min(a$2, a$2 + l$2 + c$2);
let g$3 = [...r$2[0]][0].length, h$2 = e$2.slice(0, s$2 + r$2.index + g$3 + a$2);
if (Math.min(s$2, a$2) % 2) {
let f$3 = h$2.slice(1, -1);
return {
type: "em",
raw: h$2,
text: f$3,
tokens: this.lexer.inlineTokens(f$3)
};
}
let R$1 = h$2.slice(2, -2);
return {
type: "strong",
raw: h$2,
text: R$1,
tokens: this.lexer.inlineTokens(R$1)
};
}
}
}
codespan(e$2) {
let t$2 = this.rules.inline.code.exec(e$2);
if (t$2) {
let n$1 = t$2[2].replace(this.rules.other.newLineCharGlobal, " "), r$2 = this.rules.other.nonSpaceChar.test(n$1), i$3 = this.rules.other.startingSpaceChar.test(n$1) && this.rules.other.endingSpaceChar.test(n$1);
return r$2 && i$3 && (n$1 = n$1.substring(1, n$1.length - 1)), {
type: "codespan",
raw: t$2[0],
text: n$1
};
}
}
br(e$2) {
let t$2 = this.rules.inline.br.exec(e$2);
if (t$2) return {
type: "br",
raw: t$2[0]
};
}
del(e$2) {
let t$2 = this.rules.inline.del.exec(e$2);
if (t$2) return {
type: "del",
raw: t$2[0],
text: t$2[2],
tokens: this.lexer.inlineTokens(t$2[2])
};
}
autolink(e$2) {
let t$2 = this.rules.inline.autolink.exec(e$2);
if (t$2) {
let n$1, r$2;
return t$2[2] === "@" ? (n$1 = t$2[1], r$2 = "mailto:" + n$1) : (n$1 = t$2[1], r$2 = n$1), {
type: "link",
raw: t$2[0],
text: n$1,
href: r$2,
tokens: [{
type: "text",
raw: n$1,
text: n$1
}]
};
}
}
url(e$2) {
let t$2;
if (t$2 = this.rules.inline.url.exec(e$2)) {
let n$1, r$2;
if (t$2[2] === "@") n$1 = t$2[0], r$2 = "mailto:" + n$1;
else {
let i$3;
do
i$3 = t$2[0], t$2[0] = this.rules.inline._backpedal.exec(t$2[0])?.[0] ?? "";
while (i$3 !== t$2[0]);
n$1 = t$2[0], t$2[1] === "www." ? r$2 = "http://" + t$2[0] : r$2 = t$2[0];
}
return {
type: "link",
raw: t$2[0],
text: n$1,
href: r$2,
tokens: [{
type: "text",
raw: n$1,
text: n$1
}]
};
}
}
inlineText(e$2) {
let t$2 = this.rules.inline.text.exec(e$2);
if (t$2) {
let n$1 = this.lexer.state.inRawBlock;
return {
type: "text",
raw: t$2[0],
text: t$2[0],
escaped: n$1
};
}
}
};
var x = class u$3 {
tokens;
options;
state;
tokenizer;
inlineQueue;
constructor(e$2) {
this.tokens = [], this.tokens.links = Object.create(null), this.options = e$2 || T$1, this.options.tokenizer = this.options.tokenizer || new y$1(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = {
inLink: !1,
inRawBlock: !1,
top: !0
};
let t$2 = {
other: m,
block: C.normal,
inline: M$1.normal
};
this.options.pedantic ? (t$2.block = C.pedantic, t$2.inline = M$1.pedantic) : this.options.gfm && (t$2.block = C.gfm, this.options.breaks ? t$2.inline = M$1.breaks : t$2.inline = M$1.gfm), this.tokenizer.rules = t$2;
}
static get rules() {
return {
block: C,
inline: M$1
};
}
static lex(e$2, t$2) {
return new u$3(t$2).lex(e$2);
}
static lexInline(e$2, t$2) {
return new u$3(t$2).inlineTokens(e$2);
}
lex(e$2) {
e$2 = e$2.replace(m.carriageReturn, `
`), this.blockTokens(e$2, this.tokens);
for (let t$2 = 0; t$2 < this.inlineQueue.length; t$2++) {
let n$1 = this.inlineQueue[t$2];
this.inlineTokens(n$1.src, n$1.tokens);
}
return this.inlineQueue = [], this.tokens;
}
blockTokens(e$2, t$2 = [], n$1 = !1) {
for (this.options.pedantic && (e$2 = e$2.replace(m.tabCharGlobal, " ").replace(m.spaceLine, "")); e$2;) {
let r$2;
if (this.options.extensions?.block?.some((s$2) => (r$2 = s$2.call({ lexer: this }, e$2, t$2)) ? (e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2), !0) : !1)) continue;
if (r$2 = this.tokenizer.space(e$2)) {
e$2 = e$2.substring(r$2.raw.length);
let s$2 = t$2.at(-1);
r$2.raw.length === 1 && s$2 !== void 0 ? s$2.raw += `
` : t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.code(e$2)) {
e$2 = e$2.substring(r$2.raw.length);
let s$2 = t$2.at(-1);
s$2?.type === "paragraph" || s$2?.type === "text" ? (s$2.raw += (s$2.raw.endsWith(`
`) ? "" : `
`) + r$2.raw, s$2.text += `
` + r$2.text, this.inlineQueue.at(-1).src = s$2.text) : t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.fences(e$2)) {
e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.heading(e$2)) {
e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.hr(e$2)) {
e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.blockquote(e$2)) {
e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.list(e$2)) {
e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.html(e$2)) {
e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.def(e$2)) {
e$2 = e$2.substring(r$2.raw.length);
let s$2 = t$2.at(-1);
s$2?.type === "paragraph" || s$2?.type === "text" ? (s$2.raw += (s$2.raw.endsWith(`
`) ? "" : `
`) + r$2.raw, s$2.text += `
` + r$2.raw, this.inlineQueue.at(-1).src = s$2.text) : this.tokens.links[r$2.tag] || (this.tokens.links[r$2.tag] = {
href: r$2.href,
title: r$2.title
}, t$2.push(r$2));
continue;
}
if (r$2 = this.tokenizer.table(e$2)) {
e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2);
continue;
}
if (r$2 = this.tokenizer.lheading(e$2)) {
e$2 = e$2.substring(r$2.raw.length), t$2.push(r$2);
continue;
}
let i$3 = e$2;
if (this.options.extensions?.startBlock) {
let s$2 = Infinity, o$3 = e$2.slice(1), a$2;
this.options.extensions.startBlock.forEach((l$2) => {
a$2 = l$2.call({ lexer: this }, o$3), typeof a$2 == "number" && a$2 >= 0 && (s$2 = Math.min(s$2, a$2));
}), s$2 < Infinity && s$2 >= 0 && (i$3 = e$2.substring(0, s$2 + 1));
}
if (this.state.top && (r$2 = this.tokenizer.paragraph(i$3))) {
let s$2 = t$2.at(-1);
n$1 && s$2?.type === "paragraph" ? (s$2.raw += (s$2.raw.endsWith(`
`) ? "" : `
`) + r$2.raw, s$2.text += `
` + r$2.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s$2.text) : t$2.push(r$2), n$1 = i$3.length !== e$2.length, e$2 = e$2.substring(r$2.raw.length);
continue;
}
if (r$2 = this.tokenizer.text(e$2)) {
e$2 = e$2.substring(r$2.raw.length);
let s$2 = t$2.at(-1);
s$2?.type === "text" ? (s$2.raw += (s$2.raw.endsWith(`
`) ? "" : `
`) + r$2.raw, s$2.text += `
` + r$2.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s$2.text) : t$2.push(r$2);
continue;
}
if (e$2) {
let s$2 = "Infinite loop on byte: " + e$2.charCodeAt(0);
if (this.options.silent) {
console.error(s$2);
break;
} else throw new Error(s$2);
}
}
return this.state.top = !0, t$2;
}
inline(e$2, t$2 = []) {
return this.inlineQueue.push({
src: e$2,
tokens: t$2
}), t$2;
}
inlineTokens(e$2, t$2 = []) {
let n$1 = e$2, r$2 = null;
if (this.tokens.links) {
let o$3 = Object.keys(this.tokens.links);
if (o$3.length > 0) for (; (r$2 = this.tokenizer.rules.inline.reflinkSearch.exec(n$1)) != null;) o$3.includes(r$2[0].slice(r$2[0].lastIndexOf("[") + 1, -1)) && (n$1 = n$1.slice(0, r$2.index) + "[" + "a".repeat(r$2[0].length - 2) + "]" + n$1.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex));
}
for (; (r$2 = this.tokenizer.rules.inline.anyPunctuation.exec(n$1)) != null;) n$1 = n$1.slice(0, r$2.index) + "++" + n$1.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
for (; (r$2 = this.tokenizer.rules.inline.blockSkip.exec(n$1)) != null;) n$1 = n$1.slice(0, r$2.index) + "[" + "a".repeat(r$2[0].length - 2) + "]" + n$1.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
n$1 = this.options.hooks?.emStrongMask?.call({ lexer: this }, n$1) ?? n$1;
let i$3 = !1, s$2 = "";
for (; e$2;) {
i$3 || (s$2 = ""), i$3 = !1;
let o$3;
if (this.options.extensions?.inline?.some((l$2) => (o$3 = l$2.call({ lexer: this }, e$2, t$2)) ? (e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3), !0) : !1)) continue;
if (o$3 = this.tokenizer.escape(e$2)) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
if (o$3 = this.tokenizer.tag(e$2)) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
if (o$3 = this.tokenizer.link(e$2)) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
if (o$3 = this.tokenizer.reflink(e$2, this.tokens.links)) {
e$2 = e$2.substring(o$3.raw.length);
let l$2 = t$2.at(-1);
o$3.type === "text" && l$2?.type === "text" ? (l$2.raw += o$3.raw, l$2.text += o$3.text) : t$2.push(o$3);
continue;
}
if (o$3 = this.tokenizer.emStrong(e$2, n$1, s$2)) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
if (o$3 = this.tokenizer.codespan(e$2)) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
if (o$3 = this.tokenizer.br(e$2)) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
if (o$3 = this.tokenizer.del(e$2)) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
if (o$3 = this.tokenizer.autolink(e$2)) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
if (!this.state.inLink && (o$3 = this.tokenizer.url(e$2))) {
e$2 = e$2.substring(o$3.raw.length), t$2.push(o$3);
continue;
}
let a$2 = e$2;
if (this.options.extensions?.startInline) {
let l$2 = Infinity, c$2 = e$2.slice(1), p$2;
this.options.extensions.startInline.forEach((g$3) => {
p$2 = g$3.call({ lexer: this }, c$2), typeof p$2 == "number" && p$2 >= 0 && (l$2 = Math.min(l$2, p$2));
}), l$2 < Infinity && l$2 >= 0 && (a$2 = e$2.substring(0, l$2 + 1));
}
if (o$3 = this.tokenizer.inlineText(a$2)) {
e$2 = e$2.substring(o$3.raw.length), o$3.raw.slice(-1) !== "_" && (s$2 = o$3.raw.slice(-1)), i$3 = !0;
let l$2 = t$2.at(-1);
l$2?.type === "text" ? (l$2.raw += o$3.raw, l$2.text += o$3.text) : t$2.push(o$3);
continue;
}
if (e$2) {
let l$2 = "Infinite loop on byte: " + e$2.charCodeAt(0);
if (this.options.silent) {
console.error(l$2);
break;
} else throw new Error(l$2);
}
}
return t$2;
}
};
var P = class {
options;
parser;
constructor(e$2) {
this.options = e$2 || T$1;
}
space(e$2) {
return "";
}
code({ text: e$2, lang: t$2, escaped: n$1 }) {
let r$2 = (t$2 || "").match(m.notSpaceStart)?.[0], i$3 = e$2.replace(m.endingNewline, "") + `
`;
return r$2 ? "<pre><code class=\"language-" + w(r$2) + "\">" + (n$1 ? i$3 : w(i$3, !0)) + `</code></pre>
` : "<pre><code>" + (n$1 ? i$3 : w(i$3, !0)) + `</code></pre>
`;
}
blockquote({ tokens: e$2 }) {
return `<blockquote>
${this.parser.parse(e$2)}</blockquote>
`;
}
html({ text: e$2 }) {
return e$2;
}
def(e$2) {
return "";
}
heading({ tokens: e$2, depth: t$2 }) {
return `<h${t$2}>${this.parser.parseInline(e$2)}</h${t$2}>
`;
}
hr(e$2) {
return `<hr>
`;
}
list(e$2) {
let t$2 = e$2.ordered, n$1 = e$2.start, r$2 = "";
for (let o$3 = 0; o$3 < e$2.items.length; o$3++) {
let a$2 = e$2.items[o$3];
r$2 += this.listitem(a$2);
}
let i$3 = t$2 ? "ol" : "ul", s$2 = t$2 && n$1 !== 1 ? " start=\"" + n$1 + "\"" : "";
return "<" + i$3 + s$2 + `>
` + r$2 + "</" + i$3 + `>
`;
}
listitem(e$2) {
let t$2 = "";
if (e$2.task) {
let n$1 = this.checkbox({ checked: !!e$2.checked });
e$2.loose ? e$2.tokens[0]?.type === "paragraph" ? (e$2.tokens[0].text = n$1 + " " + e$2.tokens[0].text, e$2.tokens[0].tokens && e$2.tokens[0].tokens.length > 0 && e$2.tokens[0].tokens[0].type === "text" && (e$2.tokens[0].tokens[0].text = n$1 + " " + w(e$2.tokens[0].tokens[0].text), e$2.tokens[0].tokens[0].escaped = !0)) : e$2.tokens.unshift({
type: "text",
raw: n$1 + " ",
text: n$1 + " ",
escaped: !0
}) : t$2 += n$1 + " ";
}
return t$2 += this.parser.parse(e$2.tokens, !!e$2.loose), `<li>${t$2}</li>
`;
}
checkbox({ checked: e$2 }) {
return "<input " + (e$2 ? "checked=\"\" " : "") + "disabled=\"\" type=\"checkbox\">";
}
paragraph({ tokens: e$2 }) {
return `<p>${this.parser.parseInline(e$2)}</p>
`;
}
table(e$2) {
let t$2 = "", n$1 = "";
for (let i$3 = 0; i$3 < e$2.header.length; i$3++) n$1 += this.tablecell(e$2.header[i$3]);
t$2 += this.tablerow({ text: n$1 });
let r$2 = "";
for (let i$3 = 0; i$3 < e$2.rows.length; i$3++) {
let s$2 = e$2.rows[i$3];
n$1 = "";
for (let o$3 = 0; o$3 < s$2.length; o$3++) n$1 += this.tablecell(s$2[o$3]);
r$2 += this.tablerow({ text: n$1 });
}
return r$2 && (r$2 = `<tbody>${r$2}</tbody>`), `<table>
<thead>
` + t$2 + `</thead>
` + r$2 + `</table>
`;
}
tablerow({ text: e$2 }) {
return `<tr>
${e$2}</tr>
`;
}
tablecell(e$2) {
let t$2 = this.parser.parseInline(e$2.tokens), n$1 = e$2.header ? "th" : "td";
return (e$2.align ? `<${n$1} align="${e$2.align}">` : `<${n$1}>`) + t$2 + `</${n$1}>
`;
}
strong({ tokens: e$2 }) {
return `<strong>${this.parser.parseInline(e$2)}</strong>`;
}
em({ tokens: e$2 }) {
return `<em>${this.parser.parseInline(e$2)}</em>`;
}
codespan({ text: e$2 }) {
return `<code>${w(e$2, !0)}</code>`;
}
br(e$2) {
return "<br>";
}
del({ tokens: e$2 }) {
return `<del>${this.parser.parseInline(e$2)}</del>`;
}
link({ href: e$2, title: t$2, tokens: n$1 }) {
let r$2 = this.parser.parseInline(n$1), i$3 = J(e$2);
if (i$3 === null) return r$2;
e$2 = i$3;
let s$2 = "<a href=\"" + e$2 + "\"";
return t$2 && (s$2 += " title=\"" + w(t$2) + "\""), s$2 += ">" + r$2 + "</a>", s$2;
}
image({ href: e$2, title: t$2, text: n$1, tokens: r$2 }) {
r$2 && (n$1 = this.parser.parseInline(r$2, this.parser.textRenderer));
let i$3 = J(e$2);
if (i$3 === null) return w(n$1);
e$2 = i$3;
let s$2 = `<img src="${e$2}" alt="${n$1}"`;
return t$2 && (s$2 += ` title="${w(t$2)}"`), s$2 += ">", s$2;
}
text(e$2) {
return "tokens" in e$2 && e$2.tokens ? this.parser.parseInline(e$2.tokens) : "escaped" in e$2 && e$2.escaped ? e$2.text : w(e$2.text);
}
};
var $$1 = class {
strong({ text: e$2 }) {
return e$2;
}
em({ text: e$2 }) {
return e$2;
}
codespan({ text: e$2 }) {
return e$2;
}
del({ text: e$2 }) {
return e$2;
}
html({ text: e$2 }) {
return e$2;
}
text({ text: e$2 }) {
return e$2;
}
link({ text: e$2 }) {
return "" + e$2;
}
image({ text: e$2 }) {
return "" + e$2;
}
br() {
return "";
}
};
var b = class u$3 {
options;
renderer;
textRenderer;
constructor(e$2) {
this.options = e$2 || T$1, this.options.renderer = this.options.renderer || new P(), this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new $$1();
}
static parse(e$2, t$2) {
return new u$3(t$2).parse(e$2);
}
static parseInline(e$2, t$2) {
return new u$3(t$2).parseInline(e$2);
}
parse(e$2, t$2 = !0) {
let n$1 = "";
for (let r$2 = 0; r$2 < e$2.length; r$2++) {
let i$3 = e$2[r$2];
if (this.options.extensions?.renderers?.[i$3.type]) {
let o$3 = i$3, a$2 = this.options.extensions.renderers[o$3.type].call({ parser: this }, o$3);
if (a$2 !== !1 || ![
"space",
"hr",
"heading",
"code",
"table",
"blockquote",
"list",
"html",
"def",
"paragraph",
"text"
].includes(o$3.type)) {
n$1 += a$2 || "";
continue;
}
}
let s$2 = i$3;
switch (s$2.type) {
case "space": {
n$1 += this.renderer.space(s$2);
continue;
}
case "hr": {
n$1 += this.renderer.hr(s$2);
continue;
}
case "heading": {
n$1 += this.renderer.heading(s$2);
continue;
}
case "code": {
n$1 += this.renderer.code(s$2);
continue;
}
case "table": {
n$1 += this.renderer.table(s$2);
continue;
}
case "blockquote": {
n$1 += this.renderer.blockquote(s$2);
continue;
}
case "list": {
n$1 += this.renderer.list(s$2);
continue;
}
case "html": {
n$1 += this.renderer.html(s$2);
continue;
}
case "def": {
n$1 += this.renderer.def(s$2);
continue;
}
case "paragraph": {
n$1 += this.renderer.paragraph(s$2);
continue;
}
case "text": {
let o$3 = s$2, a$2 = this.renderer.text(o$3);
for (; r$2 + 1 < e$2.length && e$2[r$2 + 1].type === "text";) o$3 = e$2[++r$2], a$2 += `
` + this.renderer.text(o$3);
t$2 ? n$1 += this.renderer.paragraph({
type: "paragraph",
raw: a$2,
text: a$2,
tokens: [{
type: "text",
raw: a$2,
text: a$2,
escaped: !0
}]
}) : n$1 += a$2;
continue;
}
default: {
let o$3 = "Token with \"" + s$2.type + "\" type was not found.";
if (this.options.silent) return console.error(o$3), "";
throw new Error(o$3);
}
}
}
return n$1;
}
parseInline(e$2, t$2 = this.renderer) {
let n$1 = "";
for (let r$2 = 0; r$2 < e$2.length; r$2++) {
let i$3 = e$2[r$2];
if (this.options.extensions?.renderers?.[i$3.type]) {
let o$3 = this.options.extensions.renderers[i$3.type].call({ parser: this }, i$3);
if (o$3 !== !1 || ![
"escape",
"html",
"link",
"image",
"strong",
"em",
"codespan",
"br",
"del",
"text"
].includes(i$3.type)) {
n$1 += o$3 || "";
continue;
}
}
let s$2 = i$3;
switch (s$2.type) {
case "escape": {
n$1 += t$2.text(s$2);
break;
}
case "html": {
n$1 += t$2.html(s$2);
break;
}
case "link": {
n$1 += t$2.link(s$2);
break;
}
case "image": {
n$1 += t$2.image(s$2);
break;
}
case "strong": {
n$1 += t$2.strong(s$2);
break;
}
case "em": {
n$1 += t$2.em(s$2);
break;
}
case "codespan": {
n$1 += t$2.codespan(s$2);
break;
}
case "br": {
n$1 += t$2.br(s$2);
break;
}
case "del": {
n$1 += t$2.del(s$2);
break;
}
case "text": {
n$1 += t$2.text(s$2);
break;
}
default: {
let o$3 = "Token with \"" + s$2.type + "\" type was not found.";
if (this.options.silent) return console.error(o$3), "";
throw new Error(o$3);
}
}
}
return n$1;
}
};
var S = class {
options;
block;
constructor(e$2) {
this.options = e$2 || T$1;
}
static passThroughHooks = new Set([
"preprocess",
"postprocess",
"processAllTokens",
"emStrongMask"
]);
static passThroughHooksRespectAsync = new Set([
"preprocess",
"postprocess",
"processAllTokens"
]);
preprocess(e$2) {
return e$2;
}
postprocess(e$2) {
return e$2;
}
processAllTokens(e$2) {
return e$2;
}
emStrongMask(e$2) {
return e$2;
}
provideLexer() {
return this.block ? x.lex : x.lexInline;
}
provideParser() {
return this.block ? b.parse : b.parseInline;
}
};
var B = class {
defaults = L();
options = this.setOptions;
parse = this.parseMarkdown(!0);
parseInline = this.parseMarkdown(!1);
Parser = b;
Renderer = P;
TextRenderer = $$1;
Lexer = x;
Tokenizer = y$1;
Hooks = S;
constructor(...e$2) {
this.use(...e$2);
}
walkTokens(e$2, t$2) {
let n$1 = [];
for (let r$2 of e$2) switch (n$1 = n$1.concat(t$2.call(this, r$2)), r$2.type) {
case "table": {
let i$3 = r$2;
for (let s$2 of i$3.header) n$1 = n$1.concat(this.walkTokens(s$2.tokens, t$2));
for (let s$2 of i$3.rows) for (let o$3 of s$2) n$1 = n$1.concat(this.walkTokens(o$3.tokens, t$2));
break;
}
case "list": {
let i$3 = r$2;
n$1 = n$1.concat(this.walkTokens(i$3.items, t$2));
break;
}
default: {
let i$3 = r$2;
this.defaults.extensions?.childTokens?.[i$3.type] ? this.defaults.extensions.childTokens[i$3.type].forEach((s$2) => {
let o$3 = i$3[s$2].flat(Infinity);
n$1 = n$1.concat(this.walkTokens(o$3, t$2));
}) : i$3.tokens && (n$1 = n$1.concat(this.walkTokens(i$3.tokens, t$2)));
}
}
return n$1;
}
use(...e$2) {
let t$2 = this.defaults.extensions || {
renderers: {},
childTokens: {}
};
return e$2.forEach((n$1) => {
let r$2 = { ...n$1 };
if (r$2.async = this.defaults.async || r$2.async || !1, n$1.extensions && (n$1.extensions.forEach((i$3) => {
if (!i$3.name) throw new Error("extension name required");
if ("renderer" in i$3) {
let s$2 = t$2.renderers[i$3.name];
s$2 ? t$2.renderers[i$3.name] = function(...o$3) {
let a$2 = i$3.renderer.apply(this, o$3);
return a$2 === !1 && (a$2 = s$2.apply(this, o$3)), a$2;
} : t$2.renderers[i$3.name] = i$3.renderer;
}
if ("tokenizer" in i$3) {
if (!i$3.level || i$3.level !== "block" && i$3.level !== "inline") throw new Error("extension level must be 'block' or 'inline'");
let s$2 = t$2[i$3.level];
s$2 ? s$2.unshift(i$3.tokenizer) : t$2[i$3.level] = [i$3.tokenizer], i$3.start && (i$3.level === "block" ? t$2.startBlock ? t$2.startBlock.push(i$3.start) : t$2.startBlock = [i$3.start] : i$3.level === "inline" && (t$2.startInline ? t$2.startInline.push(i$3.start) : t$2.startInline = [i$3.start]));
}
"childTokens" in i$3 && i$3.childTokens && (t$2.childTokens[i$3.name] = i$3.childTokens);
}), r$2.extensions = t$2), n$1.renderer) {
let i$3 = this.defaults.renderer || new P(this.defaults);
for (let s$2 in n$1.renderer) {
if (!(s$2 in i$3)) throw new Error(`renderer '${s$2}' does not exist`);
if (["options", "parser"].includes(s$2)) continue;
let o$3 = s$2, a$2 = n$1.renderer[o$3], l$2 = i$3[o$3];
i$3[o$3] = (...c$2) => {
let p$2 = a$2.apply(i$3, c$2);
return p$2 === !1 && (p$2 = l$2.apply(i$3, c$2)), p$2 || "";
};
}
r$2.renderer = i$3;
}
if (n$1.tokenizer) {
let i$3 = this.defaults.tokenizer || new y$1(this.defaults);
for (let s$2 in n$1.tokenizer) {
if (!(s$2 in i$3)) throw new Error(`tokenizer '${s$2}' does not exist`);
if ([
"options",
"rules",
"lexer"
].includes(s$2)) continue;
let o$3 = s$2, a$2 = n$1.tokenizer[o$3], l$2 = i$3[o$3];
i$3[o$3] = (...c$2) => {
let p$2 = a$2.apply(i$3, c$2);
return p$2 === !1 && (p$2 = l$2.apply(i$3, c$2)), p$2;
};
}
r$2.tokenizer = i$3;
}
if (n$1.hooks) {
let i$3 = this.defaults.hooks || new S();
for (let s$2 in n$1.hooks) {
if (!(s$2 in i$3)) throw new Error(`hook '${s$2}' does not exist`);
if (["options", "block"].includes(s$2)) continue;
let o$3 = s$2, a$2 = n$1.hooks[o$3], l$2 = i$3[o$3];
S.passThroughHooks.has(s$2) ? i$3[o$3] = (c$2) => {
if (this.defaults.async && S.passThroughHooksRespectAsync.has(s$2)) return (async () => {
let g$3 = await a$2.call(i$3, c$2);
return l$2.call(i$3, g$3);
})();
let p$2 = a$2.call(i$3, c$2);
return l$2.call(i$3, p$2);
} : i$3[o$3] = (...c$2) => {
if (this.defaults.async) return (async () => {
let g$3 = await a$2.apply(i$3, c$2);
return g$3 === !1 && (g$3 = await l$2.apply(i$3, c$2)), g$3;
})();
let p$2 = a$2.apply(i$3, c$2);
return p$2 === !1 && (p$2 = l$2.apply(i$3, c$2)), p$2;
};
}
r$2.hooks = i$3;
}
if (n$1.walkTokens) {
let i$3 = this.defaults.walkTokens, s$2 = n$1.walkTokens;
r$2.walkTokens = function(o$3) {
let a$2 = [];
return a$2.push(s$2.call(this, o$3)), i$3 && (a$2 = a$2.concat(i$3.call(this, o$3))), a$2;
};
}
this.defaults = {
...this.defaults,
...r$2
};
}), this;
}
setOptions(e$2) {
return this.defaults = {
...this.defaults,
...e$2
}, this;
}
lexer(e$2, t$2) {
return x.lex(e$2, t$2 ?? this.defaults);
}
parser(e$2, t$2) {
return b.parse(e$2, t$2 ?? this.defaults);
}
parseMarkdown(e$2) {
return (n$1, r$2) => {
let i$3 = { ...r$2 }, s$2 = {
...this.defaults,
...i$3
}, o$3 = this.onError(!!s$2.silent, !!s$2.async);
if (this.defaults.async === !0 && i$3.async === !1) return o$3(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
if (typeof n$1 > "u" || n$1 === null) return o$3(new Error("marked(): input parameter is undefined or null"));
if (typeof n$1 != "string") return o$3(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n$1) + ", string expected"));
if (s$2.hooks && (s$2.hooks.options = s$2, s$2.hooks.block = e$2), s$2.async) return (async () => {
let a$2 = s$2.hooks ? await s$2.hooks.preprocess(n$1) : n$1, c$2 = await (s$2.hooks ? await s$2.hooks.provideLexer() : e$2 ? x.lex : x.lexInline)(a$2, s$2), p$2 = s$2.hooks ? await s$2.hooks.processAllTokens(c$2) : c$2;
s$2.walkTokens && await Promise.all(this.walkTokens(p$2, s$2.walkTokens));
let h$2 = await (s$2.hooks ? await s$2.hooks.provideParser() : e$2 ? b.parse : b.parseInline)(p$2, s$2);
return s$2.hooks ? await s$2.hooks.postprocess(h$2) : h$2;
})().catch(o$3);
try {
s$2.hooks && (n$1 = s$2.hooks.preprocess(n$1));
let l$2 = (s$2.hooks ? s$2.hooks.provideLexer() : e$2 ? x.lex : x.lexInline)(n$1, s$2);
s$2.hooks && (l$2 = s$2.hooks.processAllTokens(l$2)), s$2.walkTokens && this.walkTokens(l$2, s$2.walkTokens);
let p$2 = (s$2.hooks ? s$2.hooks.provideParser() : e$2 ? b.parse : b.parseInline)(l$2, s$2);
return s$2.hooks && (p$2 = s$2.hooks.postprocess(p$2)), p$2;
} catch (a$2) {
return o$3(a$2);
}
};
}
onError(e$2, t$2) {
return (n$1) => {
if (n$1.message += `
Please report this to https://github.com/markedjs/marked.`, e$2) {
let r$2 = "<p>An error occurred:</p><pre>" + w(n$1.message + "", !0) + "</pre>";
return t$2 ? Promise.resolve(r$2) : r$2;
}
if (t$2) return Promise.reject(n$1);
throw n$1;
};
}
};
var _$1 = new B();
function k(u$3, e$2) {
return _$1.parse(u$3, e$2);
}
k.options = k.setOptions = function(u$3) {
return _$1.setOptions(u$3), k.defaults = _$1.defaults, G(k.defaults), k;
};
k.getDefaults = L;
k.defaults = T$1;
k.use = function(...u$3) {
return _$1.use(...u$3), k.defaults = _$1.defaults, G(k.defaults), k;
};
k.walkTokens = function(u$3, e$2) {
return _$1.walkTokens(u$3, e$2);
};
k.parseInline = _$1.parseInline;
k.Parser = b;
k.parser = b.parse;
k.Renderer = P;
k.TextRenderer = $$1;
k.Lexer = x;
k.lexer = x.lex;
k.Tokenizer = y$1;
k.Hooks = S;
k.parse = k;
var Ht = k.options, Zt = k.setOptions, Gt = k.use, Nt = k.walkTokens, Ft = k.parseInline, jt = k, Qt = b.parse, Ut = x.lex;
//#endregion
//#region src/components/search-askai/utils/sanitize.ts
/** Escapes HTML special characters for safe interpolation into HTML strings. */
function escapeHtml(unsafe) {
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
function decodeUrlForSchemeCheck(value) {
let current = value;
for (let i$3 = 0; i$3 < 3; i$3 += 1) try {
const decoded = decodeURIComponent(current);
if (decoded === current) break;
current = decoded;
} catch {
break;
}
return current;
}
function stripControlsAndWhitespace(value) {
let result = "";
for (let i$3 = 0; i$3 < value.length; i$3 += 1) {
const code = value.charCodeAt(i$3);
if (code > 32 && code !== 127) result += value.charAt(i$3);
}
return result;
}
/**
* Returns a URL safe for href/src, or '' if unsafe.
* Does not HTML-escape — callers building HTML strings must escape separately.
*/
function sanitizeUrl(url) {
if (!url) return "";
const trimmed = url.trim();
if (!trimmed) return "";
const normalized = stripControlsAndWhitespace(decodeUrlForSchemeCheck(trimmed)).replace(/\\/g, "/");
if (!normalized) return "";
if (normalized.startsWith("//")) return "";
if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(normalized)) return trimmed;
try {
const parsed = new URL(normalized);
if (parsed.protocol === "http:" || parsed.protocol === "https:" || parsed.protocol === "mailto:") return trimmed;
} catch {
return "";
}
return "";
}
//#endregion
//#region src/components/search-askai/utils/markdown.ts
/** Replace unpaired UTF-16 surrogates (common in crawled index text). */
function replaceUnpairedSurrogates(value) {
return value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
}
function toMarkdownString(value) {
if (typeof value !== "string") return "";
return replaceUnpairedSurrogates(value);
}
function safeEncodeURIComponent(value) {
const sanitized = replaceUnpairedSurrogates(value);
try {
return encodeURIComponent(sanitized);
} catch {
return "";
}
}
const renderer = new k.Renderer();
renderer.code = ({ text: text$1, lang = "", escaped }) => {
const safeLang = /^[a-zA-Z0-9_-]+$/.test(lang) ? lang : "";
const languageClass = safeLang ? `language-${safeLang}` : "";
const safeCode = escaped ? text$1 : escapeHtml(text$1);
const encodedCode = safeEncodeURIComponent(text$1);
const copyIconAsHtml = [
"<svg class=\"ss-markdown-copy-icon\" width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">",
"<rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect>",
"<path d=\"m5 15-4-4 4-4\"></path>",
"</svg>"
].join("");
const checkIconAsHtml = [
"<svg class=\"ss-markdown-check-icon\" width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">",
"<polyline points=\"20,6 9,17 4,12\"></polyline>",
"</svg>"
].join("");
return [
"<div class=\"ss-markdown-code-snippet\">",
"<button class=\"ss-markdown-copy-button\" data-code=\"" + encodedCode + "\" aria-label=\"Copy code to clipboard\" title=\"Copy code\">",
copyIconAsHtml,
checkIconAsHtml,
"<span class=\"ss-markdown-copy-label\">Copy</span>",
"</button>",
"<pre><code class=\"" + languageClass + "\">" + safeCode + "</code></pre>",
"</div>"
].join("");
};
renderer.link = ({ href, title, text: text$1 }) => {
const safeHref = escapeHtml(sanitizeUrl(href));
const textEscaped = escapeHtml(text$1);
if (!safeHref) return textEscaped;
const titleAttr = title ? " title=\"" + escapeHtml(title) + "\"" : "";
return "<a href=\"" + safeHref + "\" target=\"_blank\" rel=\"noopener noreferrer\"" + titleAttr + ">" + textEscaped + "</a>";
};
renderer.image = ({ href, title, text: text$1 }) => {
const safeHref = escapeHtml(sanitizeUrl(href));
if (!safeHref) return escapeHtml(text$1);
const titleAttr = title ? " title=\"" + escapeHtml(title) + "\"" : "";
return "<img src=\"" + safeHref + "\" alt=\"" + escapeHtml(text$1) + "\"" + titleAttr + " />";
};
renderer.html = ({ text: text$1 }) => escapeHtml(text$1);
/** Parses markdown into HTML safe for `dangerouslySetInnerHTML`. */
function parseMarkdownToSafeHtml(content) {
const source = toMarkdownString(content);
try {
return k.parse(source, {
gfm: true,
breaks: true,
renderer
});
} catch (error) {
console.error("Error parsing markdown:", error);
return escapeHtml(source);
}
}
//#endregion
//#region src/components/search-askai/markdown.tsx
init_compat_module();
const MemoizedMarkdown = M(function MemoizedMarkdown$1({ children, className = "" }) {
const containerRef = A(null);
const html = T(() => parseMarkdownToSafeHtml(children), [children]);
y(() => {
const container = containerRef.current;
if (!container) return;
const handleCopyClick = async (event) => {
const target = event.target;
const button = target.closest(".ss-markdown-copy-button");
if (!button) return;
event.preventDefault();
event.stopPropagation();
const encodedCode = button.getAttribute("data-code");
if (!encodedCode) return;
try {
const code = decodeURIComponent(encodedCode);
await navigator.clipboard.writeText(code);
button.classList.add("ss-markdown-copied");
setTimeout(() => {
button.classList.remove("ss-markdown-copied");
}, 2e3);
} catch (error) {
console.error("Failed to copy code:", error);
}
};
container.addEventListener("click", handleCopyClick);
return () => {
container.removeEventListener("click", handleCopyClick);
};
}, [html]);
return /* @__PURE__ */ u("div", {
ref: containerRef,
className: `ss-markdown-content ${className}`.trim(),
dangerouslySetInnerHTML: { __html: html }
});
});
//#endregion
//#region src/components/search-askai/chat.tsx
init_compat_module();
function useClipboard() {
const copyText = q(async (text$1) => {
try {
await navigator.clipboard.writeText(text$1);
} catch {}
}, []);
return { copyText };
}
const ChatWidget = M(function ChatWidget$1({ messages, error, isGenerating, onCopy, onThumbsUp, onThumbsDown, applicationId, apiKey, assistantId, agentStudio, suggestedQuestions, onSuggestedQuestionClick, onNewChat, showPromptBlockingError = false, threadDepthBannerInChat = true, showAiDisclaimer = true, newestExchangeFirst = true }) {
const { copyText } = useClipboard();
const chatScrollRef = A(null);
/** When false, user has scrolled away from the bottom; avoid snapping on updates. */
const stickChatToBottomRef = A(true);
const [copiedExchangeId, setCopiedExchangeId] = d(null);
const copyResetTimeoutRef = A(null);
const [acknowledgedExchangeIds, setAcknowledgedExchangeIds] = d(new Set());
const [submittingExchangeId, setSubmittingExchangeId] = d(null);
const handleFeedback = async (exchange, vote) => {
if (!exchange.assistantMessage) return;
const customHandler = vote === 1 ? onThumbsUp : onThumbsDown;
try {
setSubmittingExchangeId(exchange.id);
if (customHandler) await customHandler(exchange.userMessage.id);
else if (agentStudio) {
if (apiKey) await postAgentStudioFeedback({
agentId: assistantId,
vote,
messageId: exchange.assistantMessage.id,
appId: applicationId,
apiKey
});
} else await postFeedback({
assistantId,
appId: applicationId,
messageId: exchange.userMessage.id,
thumbs: vote
});
setAcknowledgedExchangeIds((prev) => {
const next = new Set(prev);
next.add(exchange.id);
return next;
});
} catch {} finally {
setSubmittingExchangeId(null);
}
};
const exchanges = T(() => {
const grouped = [];
for (let i$3 = 0; i$3 < messages.length; i$3++) {
const current = messages.at(i$3);
if (!current) continue;
if (current.role === "user") {
const userMessage = current;
const nextMessage = messages.at(i$3 + 1);
if (nextMessage?.role === "assistant") {
grouped.push({
id: userMessage.id,
userMessage,
assistantMessage: nextMessage
});
i$3++;
} else grouped.push({
id: userMessage.id,
userMessage,
assistantMessage: null
});
}
}
return grouped;
}, [messages]);
const orderedExchanges = T(() => newestExchangeFirst ? [...exchanges].reverse() : exchanges, [exchanges, newestExchangeFirst]);
const updateStickToBottomFromScroll = q(() => {
if (newestExchangeFirst) return;
const root = chatScrollRef.current;
if (!root) return;
const thresholdPx = 80;
const dist = root.scrollHeight - root.scrollTop - root.clientHeight;
stickChatToBottomRef.current = dist < thresholdPx;
}, [newestExchangeFirst]);
_(() => {
if (newestExchangeFirst) return;
const root = chatScrollRef.current;
if (!root) return;
if (stickChatToBottomRef.current) root.scrollTop = root.scrollHeight;
updateStickToBottomFromScroll();
}, [
newestExchangeFirst,
messages,
isGenerating,
orderedExchanges.length,
updateStickToBottomFromScroll
]);
y(() => {
return () => {
if (copyResetTimeoutRef.current) window.clearTimeout(copyResetTimeoutRef.current);
};
}, []);
return /* @__PURE__ */ u("div", {
className: "ss-chat-root",
ref: chatScrollRef,
onScroll: updateStickToBottomFromScroll,
children: /* @__PURE__ */ u("div", {
className: "ss-qa-list",
children: [
exchanges.length === 0 ? /* @__PURE__ */ u("div", {
className: "ss-chat-welcome",
children: [
/* @__PURE__ */ u("h2", {
className: "ss-chat-welcome-title",
children: "How can I help you today?"
}),
/* @__PURE__ */ u("p", {
className: "ss-chat-welcome-subtitle",
children: "I search through your content to help you find answers to your questions, fast."
}),
suggestedQuestions && suggestedQuestions.length > 0 ? /* @__PURE__ */ u("div", {
className: "ss-suggested-questions",
children: suggestedQuestions.map((question) => /* @__PURE__ */ u("button", {
type: "button",
className: "ss-suggested-question-btn",
disabled: isGenerating,
onClick: () => {
if (isGenerating) return;
onSuggestedQuestionClick?.(question.question);
},
children: question.question
}, question.objectID))
}) : null
]
}) : null,
threadDepthBannerInChat && showPromptBlockingError ? /* @__PURE__ */ u(ThreadDepthErrorBanner, {
onNewChat,
detailMessage: promptBlockingBannerMessage(error, agentStudio),
showNewConversationLink: showAskAiBlockingBannerNewConversationLink(error, agentStudio)
}) : null,
showAiDisclaimer ? /* @__PURE__ */ u("p", {
className: "ss-hint",
children: "Answers are generated with AI which can make mistakes."
}) : null,
error && !isAskAiPromptBlockingError(error, Boolean(agentStudio)) && /* @__PURE__ */ u("div", {
className: "ss-error-banner",
children: error.message
}),
orderedExchanges.map((exchange, index$1) => {
const isLastExchange = newestExchangeFirst ? index$1 === 0 : index$1 === orderedExchanges.length - 1;
return /* @__PURE__ */ u("article", {
className: "ss-qa-card",
children: [
/* @__PURE__ */ u("div", {
className: "ss-qa-header",
children: /* @__PURE__ */ u("div", {
className: "ss-qa-question",
children: exchange.userMessage.parts.map((part, index$2) => part.type === "text" ? /* @__PURE__ */ u("span", { children: typeof part.text === "string" ? part.text : "" }, index$2) : null)
})
}),
/* @__PURE__ */ u("div", {
className: "ss-qa-answer",
children: /* @__PURE__ */ u("div", {
className: "ss-qa-answer-content",
children: exchange.assistantMessage ? /* @__PURE__ */ u("div", {
className: "ss-qa-markdown",
children: exchange.assistantMessage.parts.map((part, index$2) => {
if (typeof part === "string") return /* @__PURE__ */ u("p", { children: part }, `${index$2}`);
if (part.type === "text") {
const text$1 = typeof part.text === "string" ? part.text : "";
return /* @__PURE__ */ u(MemoizedMarkdown, { children: text$1 }, `${index$2}`);
} else if (part.type === "reasoning" && part.state === "streaming") return /* @__PURE__ */ u("p", {
className: "ss-tool-info",
children: [
/* @__PURE__ */ u(BrainIcon, {}),
" ",
/* @__PURE__ */ u("span", {
className: "ss-shimmer-text",
children: "Reasoning..."
})
]
}, `${index$2}`);
else if (part.type === "tool-searchIndex") if (part.state === "input-streaming") return /* @__PURE__ */ u("p", {
className: "ss-tool-info",
children: [
/* @__PURE__ */ u(SearchIcon, { size: 18 }),
" ",
/* @__PURE__ */ u("span", {
className: "ss-shimmer-text",
children: "Searching..."
})
]
}, `${index$2}`);
else if (part.state === "input-available") return /* @__PURE__ */ u("p", {
className: "ss-tool-info",
children: [
/* @__PURE__ */ u(SearchIcon, { size: 18 }),
" ",
/* @__PURE__ */ u("span", {
className: "ss-shimmer-text",
children: [
"Looking for",
" ",
/* @__PURE__ */ u("mark", { children: [
"\"",
part.input?.query || "",
"\""
] })
]
})
]
}, `${index$2}`);
else if (part.state === "output-available") return /* @__PURE__ */ u("p", {
className: "ss-tool-info",
children: [
/* @__PURE__ */ u(SearchIcon, { size: 18 }),
" ",
/* @__PURE__ */ u("span", { children: [
"Searched for",
" ",
/* @__PURE__ */ u("mark", { children: [
"\"",
part.output?.query,
"\""
] }),
" ",
"found",
" ",
Array.isArray(part.output?.hits) ? part.output.hits.length : "no",
" ",
"results"
] })
]
}, `${index$2}`);
else if (part.state === "output-error") return /* @__PURE__ */ u("p", {
className: "ss-tool-info",
children: part.errorText
}, `${index$2}`);
else return null;
else return null;
})
}) : /* @__PURE__ */ u("div", {
className: "ss-qa-markdown ss-qa-generating ss-shimmer-text",
children: isGenerating && isLastExchange ? "Thinking..." : ""
})
})
}),
/* @__PURE__ */ u("div", {
className: "ss-qa-actions",
children: [exchange.assistantMessage && !isGenerating ? acknowledgedExchangeIds.has(exchange.id) ? /* @__PURE__ */ u("span", {
className: "ss-qa-feedback-ack ss-fade",
children: "Thanks for your feedback!"
}) : submittingExchangeId === exchange.id ? /* @__PURE__ */ u("span", {
className: "ss-qa-feedback-ack ss-shimmer-text",
children: "Submitting..."
}) : /* @__PURE__ */ u("div", {
className: "ss-qa-actions-group",
children: [/* @__PURE__ */ u("button", {
type: "button",
title: "Like",
"aria-label": "Like",
className: "ss-qa-action-btn",
disabled: !exchange.assistantMessage || submittingExchangeId === exchange.id,
onClick: () => handleFeedback(exchange, 1),
children: /* @__PURE__ */ u(LikeIcon, { size: 18 })
}), /* @__PURE__ */ u("button", {
type: "button",
title: "Dislike",
"aria-label": "Dislike",
className: "ss-qa-action-btn",
disabled: !exchange.assistantMessage || submittingExchangeId === exchange.id,
onClick: () => handleFeedback(exchange, 0),
children: /* @__PURE__ */ u(DislikeIcon, { size: 18 })
})]
}) : null, /* @__PURE__ */ u("button", {
type: "button",
className: `ss-qa-action-btn ${copiedExchangeId === exchange.id ? "is-copied" : ""}`,
"aria-label": copiedExchangeId === exchange.id ? "Copied" : "Copy answer",
title: copiedExchangeId === exchange.id ? "Copied" : "Copy answer",
disabled: !exchange.assistantMessage || copiedExchangeId === exchange.id,
onClick: async () => {
const parts = exchange.assistantMessage?.parts ?? [];
const textContent = parts.flatMap((part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []).join("").trim();
if (!textContent) return;
try {
if (onCopy) await onCopy(textContent);
else await copyText(textContent);
setCopiedExchangeId(exchange.id);
if (copyResetTimeoutRef.current) window.clearTimeout(copyResetTimeoutRef.current);
copyResetTimeoutRef.current = window.setTimeout(() => {
setCopiedExchangeId(null);
}, 1500);
} catch {}
},
children: copiedExchangeId === exchange.id ? /* @__PURE__ */ u(CheckIcon, { size: 18 }) : /* @__PURE__ */ u(CopyIcon, { size: 18 })
})]
})
]
}, exchange.id);
})
]
})
});
});
//#endregion
//#region src/components/search-askai/hits-list.tsx
init_compat_module();
const HitsActions = M(function HitsActions$1({ query, isSelected, onAskAI, onHoverIndex, hoverEnabled }) {
return /* @__PURE__ */ u("div", {
className: "ss-infinite-hits-list",
children: /* @__PURE__ */ u("article", {
onClick: onAskAI,
className: "ss-infinite-hits-item ss-ask-ai-btn",
"aria-label": "Ask AI",
title: "Ask AI",
role: "option",
"aria-selected": isSelected,
onMouseEnter: () => {
if (!hoverEnabled) return;
onHoverIndex?.(0);
},
onMouseMove: () => {
if (!hoverEnabled) return;
onHoverIndex?.(0);
},
children: [/* @__PURE__ */ u(SparklesIcon, {}), /* @__PURE__ */ u("p", {
className: "ss-infinite-hits-item-title",
children: ["Ask AI: ", /* @__PURE__ */ u("span", {
className: "ais-Highlight-highlighted",
children: [
"\"",
query,
"\""
]
})]
})]
})
});
});
const HitsList = M(function HitsList$2({ hits, query, selectedIndex, onAskAI, attributes, onHoverIndex, hoverEnabled, sendEvent, openResultsInNewTab = true }) {
const mapping = T(() => ({
primaryText: attributes?.primaryText || "title",
secondaryText: attributes?.secondaryText || "description",
tertiaryText: attributes?.tertiaryText,
url: attributes?.url || "url",
image: attributes?.image
}), [attributes]);
const [failedImages, setFailedImages] = d({});
return /* @__PURE__ */ u(k$1, { children: [/* @__PURE__ */ u(HitsActions, {
query,
isSelected: selectedIndex === 0,
onAskAI,
onHoverIndex,
hoverEnabled
}), hits.map((hit, idx) => {
const isSel = selectedIndex === idx + 1;
const primaryVal = getByPath(hit, mapping.primaryText);
const url = getByPath(hit, mapping.url);
const imageUrl = getByPath(hit, mapping.image);
const hasImage = Boolean(imageUrl);
const isImageFailed = failedImages[hit.objectID] || !hasImage;
return /* @__PURE__ */ u("a", {
href: url ?? "#",
target: openResultsInNewTab ? "_blank" : void 0,
rel: openResultsInNewTab ? "noopener noreferrer" : void 0,
className: "ss-infinite-hits-item ss-infinite-hits-anchor",
role: "option",
"aria-selected": isSel,
onClick: () => {
sendEvent?.("click", hit, "Hit Clicked");
},
onMouseEnter: () => {
if (!hoverEnabled) return;
onHoverIndex?.(idx + 1);
},
onMouseMove: () => {
if (!hoverEnabled) return;
onHoverIndex?.(idx + 1);
},
children: [imageUrl ? /* @__PURE__ */ u("div", {
className: "ss-infinite-hits-item-image-container",
children: !isImageFailed ? /* @__PURE__ */ u("img", {
src: imageUrl,
alt: primaryVal,
className: "ss-infinite-hits-item-image",
onError: () => setFailedImages((prev) => ({
...prev,
[hit.objectID]: true
}))
}) : /* @__PURE__ */ u("div", {
className: "ss-infinite-hits-item-placeholder",
"aria-hidden": "true",
children: /* @__PURE__ */ u(SearchIcon, {})
})
}) : null, /* @__PURE__ */ u("div", {
className: "ss-infinite-hits-item-content",
children: [
/* @__PURE__ */ u("p", {
className: "ss-infinite-hits-item-title",
children: /* @__PURE__ */ u(Highlight, {
attribute: toAttributePath(mapping.primaryText),
hit
})
}),
mapping.secondaryText ? /* @__PURE__ */ u("p", {
className: "ss-infinite-hits-item-description",
children: /* @__PURE__ */ u(Highlight, {
attribute: toAttributePath(mapping.secondaryText),
hit
})
}) : null,
mapping.tertiaryText ? /* @__PURE__ */ u("p", {
className: "ss-infinite-hits-item-description",
children: /* @__PURE__ */ u(Highlight, {
attribute: toAttributePath(mapping.tertiaryText),
hit
})
}) : null
]
})]
}, hit.objectID);
})] });
});
//#endregion
//#region src/components/search-askai/search-input.tsx
init_compat_module();
const SearchLeftButton = M(function SearchLeftButton$1({ showChat, setShowChat }) {
if (showChat) return /* @__PURE__ */ u("button", {
type: "button",
onClick: () => setShowChat(false),
className: "ss-search-left-button",
"aria-label": "Back to search",
title: "Back to search",
children: /* @__PURE__ */ u(ArrowLeftIcon, {})
});
return /* @__PURE__ */ u("div", {
role: "button",
tabIndex: -1,
className: "ss-search-left-button",
"aria-label": "Search",
title: "Search",
children: /* @__PURE__ */ u(SearchIcon, {})
});
});
const SearchInput = M(function SearchInput$2(props) {
const { status } = useInstantSearch();
const { query, refine: refine$1 } = useSearchBox();
const [chatInput, setChatInput] = d("");
const isSearchStalled = status === "stalled";
function setQuery(newQuery) {
if (props.showChat) setChatInput(newQuery);
else refine$1(newQuery);
}
y(() => {
if (props.showChat) setChatInput("");
}, [props.showChat]);
const domainBlocked = isRequestBlockedForDomainAskAiError(props.error);
const placeholder = props.isPromptBlockingError && domainBlocked ? "" : props.isPromptBlockingError && !domainBlocked ? "Conversation limit reached" : props.isGenerating ? "Answering..." : props.showChat ? "Ask AI anything" : props.placeholder;
const hideChatInput = Boolean(props.showChat && props.hideChatInput);
const currentValue = props.showChat ? chatInput : query || "";
const isInputDisabled = props.isGenerating || props.isPromptBlockingError;
const formClassName = [
props.className,
props.showChat ? "ss-searchbox-form--chat" : "",
hideChatInput ? "ss-searchbox-form--chat-no-input" : ""
].filter(Boolean).join(" ");
return /* @__PURE__ */ u("search", {
className: formClassName,
onSubmit: (event) => {
event.preventDefault();
event.stopPropagation();
},
onReset: (event) => {
event.preventDefault();
event.stopPropagation();
setQuery("");
if (props.inputRef.current) props.inputRef.current.focus();
},
children: [
/* @__PURE__ */ u(SearchLeftButton, {
showChat: props.showChat,
setShowChat: props.setShowChat
}),
!hideChatInput ? /* @__PURE__ */ u("input", {
ref: props.inputRef,
autoComplete: "off",
autoCorrect: "off",
autoCapitalize: "off",
placeholder,
spellCheck: false,
maxLength: 512,
type: "search",
value: currentValue,
disabled: isInputDisabled,
onChange: (event) => {
setQuery(event.currentTarget.value);
},
onKeyDown: (e$2) => {
if (isInputDisabled) {
e$2.preventDefault();
return;
}
if (e$2.key === "ArrowDown") {
e$2.preventDefault();
props.onArrowDown?.();
return;
}
if (e$2.key === "ArrowUp") {
e$2.preventDefault();
props.onArrowUp?.();
return;
}
if (e$2.key === "Enter") {
e$2.preventDefault();
const valueAtEnter = props.showChat ? chatInput : query || "";
if (props.onEnter?.(valueAtEnter)) {
if (props.showChat) setChatInput("");
else setQuery("");
return;
}
const trimmed = valueAtEnter.trim();
if (trimmed) props.setShowChat(true);
}
}
}) : props.isPromptBlockingError && !domainBlocked ? /* @__PURE__ */ u("p", {
className: "ss-search-chat-blocking-placeholder",
children: placeholder
}) : null,
/* @__PURE__ */ u("div", {
className: "ss-search-action-buttons-container",
children: [
/* @__PURE__ */ u("button", {
type: "reset",
className: "ss-search-clear-button",
hidden: !currentValue || currentValue.length === 0 || isSearchStalled,
onClick: () => {
setQuery("");
if (props.inputRef.current) props.inputRef.current.focus();
},
children: "Clear"
}),
props.showChat ? /* @__PURE__ */ u("button", {
type: "button",
className: "ss-search-new-chat-button",
disabled: props.isGenerating && !props.isPromptBlockingError,
title: props.isPromptBlockingError ? "Start a new conversation" : "New conversation",
"aria-label": props.isPromptBlockingError ? "Start a new conversation" : "New conversation",
onClick: () => {
setChatInput("");
props.onNewChat?.();
},
children: /* @__PURE__ */ u(SquarePenIcon, { size: 18 })
}) : null,
/* @__PURE__ */ u("button", {
type: "button",
className: "ss-search-close-button",
onClick: props.onClose,
children: /* @__PURE__ */ u(CloseIcon, {})
})
]
})
]
});
});
//#endregion
//#region src/components/search-askai/useKeyboardNavigation.ts
init_compat_module();
function useKeyboardNavigation(showChat, hits, query, openResultsInNewTab = true) {
const [selectedIndex, setSelectedIndex] = d(0);
const [selectionOrigin, setSelectionOrigin] = d("init");
const totalItems = T(() => hits.length + 1, [hits.length]);
const moveDown = q(() => {
if (showChat || totalItems === 0) return;
setSelectedIndex((prev) => (prev + 1) % totalItems);
setSelectionOrigin("keyboard");
}, [showChat, totalItems]);
const moveUp = q(() => {
if (showChat || totalItems === 0) return;
setSelectedIndex((prev) => (prev - 1 + totalItems) % totalItems);
setSelectionOrigin("keyboard");
}, [showChat, totalItems]);
const hoverIndex = q((index$1) => {
if (showChat || index$1 < 0 || index$1 >= totalItems) return;
setSelectedIndex(index$1);
setSelectionOrigin("pointer");
}, [showChat, totalItems]);
const activateSelection = q(() => {
if (showChat) return false;
if (selectedIndex === 0) return true;
if (selectedIndex > 0) {
const hit = hits[selectedIndex - 1];
const url = typeof hit?.url === "string" ? hit.url : void 0;
if (url) {
if (openResultsInNewTab) window.open(url, "_blank", "noopener,noreferrer");
else window.location.assign(url);
return true;
}
}
return false;
}, [
showChat,
selectedIndex,
hits,
openResultsInNewTab
]);
y(() => {
setSelectedIndex(0);
setSelectionOrigin("init");
}, [query, showChat]);
return {
selectedIndex,
moveDown,
moveUp,
activateSelection,
hoverIndex,
selectionOrigin
};
}
//#endregion
//#region src/components/search-askai/useSearchState.ts
init_compat_module();
function useSearchState() {
const [showChat, setShowChat] = d(false);
const handleShowChat = q((show) => {
setShowChat(show);
}, []);
return {
showChat,
setShowChat,
handleShowChat
};
}
//#endregion
//#region src/components/search-askai/search-button.tsx
init_compat_module();
const SearchButton = ({ onClick, darkMode }) => {
const [modifierLabel, setModifierLabel] = d("⌘");
const [isModifierPressed, setIsModifierPressed] = d(false);
const [isKPressed, setIsKPressed] = d(false);
y(() => {
if (typeof navigator === "undefined") return;
const isMac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
setModifierLabel(isMac ? "⌘" : "Ctrl");
}, []);
y(() => {
const handleKeyDown = (event) => {
if (event.metaKey || event.ctrlKey) setIsModifierPressed(true);
if (event.key.toLowerCase() === "k") setIsKPressed(true);
};
const handleKeyUp = (event) => {
if (!event.metaKey && !event.ctrlKey) setIsModifierPressed(false);
if (event.key.toLowerCase() === "k") setIsKPressed(false);
};
const resetKeys = () => {
setIsModifierPressed(false);
setIsKPressed(false);
};
document.addEventListener("keydown", handleKeyDown);
document.addEventListener("keyup", handleKeyUp);
window.addEventListener("blur", resetKeys);
return () => {
document.removeEventListener("keydown", handleKeyDown);
document.removeEventListener("keyup", handleKeyUp);
window.removeEventListener("blur", resetKeys);
};
}, []);
return /* @__PURE__ */ u("button", {
className: `sitesearch-button-aa${darkMode ? " dark" : ""}`,
type: "button",
onClick,
"aria-label": "Open search",
children: [
/* @__PURE__ */ u("span", {
className: "search-icon",
children: /* @__PURE__ */ u(SearchIcon, {})
}),
/* @__PURE__ */ u("span", {
className: "button-text",
children: "Search"
}),
/* @__PURE__ */ u("span", {
className: "keyboard-shortcut",
children: [/* @__PURE__ */ u("kbd", {
className: isModifierPressed ? "pressed" : "",
children: modifierLabel
}), /* @__PURE__ */ u("kbd", {
className: isKPressed ? "pressed" : "",
children: "K"
})]
})
]
});
};
//#endregion
//#region src/components/search-askai/search-modal.tsx
init_compat_module();
const Modal = ({ isOpen, onClose, children, isDark }) => {
y(() => {
const handleEscape = (event) => {
if (event.key === "Escape") onClose();
};
if (isOpen) {
document.addEventListener("keydown", handleEscape);
document.body.style.overflow = "hidden";
}
return () => {
document.removeEventListener("keydown", handleEscape);
document.body.style.overflow = "unset";
};
}, [isOpen, onClose]);
if (!isOpen) return null;
return $(/* @__PURE__ */ u("div", {
className: `modal-backdrop-askai${isDark ? " dark" : ""}`,
onClick: onClose,
children: /* @__PURE__ */ u("div", {
className: `modal-content-askai ssask-exp${isDark ? " dark" : ""}`,
onClick: (e$2) => e$2.stopPropagation(),
children
})
}), document.body);
};
//#endregion
//#region src/components/search-askai/use-suggested-questions.ts
init_compat_module();
const SUGGESTED_QUETIONS_INDEX_NAME = "algolia_ask_ai_suggested_questions";
const useSuggestedQuestions = ({ assistantId, suggestedQuestionsEnabled = false, searchClient, isOpen = false }) => {
const [suggestedQuestions, setSuggestedQuestions] = d([]);
const hasFetchedRef = A(false);
y(() => {
if (hasFetchedRef.current || !isOpen) return;
const getSuggestedQuestions = async () => {
if (!suggestedQuestionsEnabled || !assistantId || assistantId === "") return;
try {
const { results } = await searchClient.search({ requests: [{
indexName: SUGGESTED_QUETIONS_INDEX_NAME,
filters: `state:published AND assistantId:${assistantId}`,
hitsPerPage: 3
}] });
const result = results[0];
setSuggestedQuestions(result.hits);
hasFetchedRef.current = true;
} catch (error) {
console.error("Failed to fetch suggested questions:", error);
}
};
getSuggestedQuestions();
}, [
suggestedQuestionsEnabled,
assistantId,
isOpen,
searchClient
]);
return suggestedQuestions;
};
//#endregion
//#region src/components/search-askai/useEffectiveDarkMode.ts
init_compat_module();
/**
* Computes effective dark mode with precedence:
* 1) explicit prop if provided
* 2) html element has class "dark"
* 3) prefers-color-scheme: dark
*/
function useEffectiveDarkMode(explicitDark) {
const initial = T(() => {
if (explicitDark !== void 0) return explicitDark;
if (typeof document !== "undefined") {
if (document.documentElement.classList.contains("dark")) return true;
}
if (typeof window !== "undefined" && typeof window.matchMedia === "function") return window.matchMedia("(prefers-color-scheme: dark)").matches;
return false;
}, [explicitDark]);
const [isDark, setIsDark] = d(initial);
y(() => {
if (explicitDark !== void 0) {
setIsDark(explicitDark);
return;
}
let disposed = false;
const recompute = () => {
if (disposed) return;
const htmlHasDark = document.documentElement.classList.contains("dark");
if (htmlHasDark) {
setIsDark(true);
return;
}
const prefers = window.matchMedia("(prefers-color-scheme: dark)").matches;
setIsDark(prefers);
};
const mo = new MutationObserver(() => recompute());
mo.observe(document.documentElement, {
attributes: true,
attributeFilter: ["class"]
});
const mql = window.matchMedia("(prefers-color-scheme: dark)");
const onChange = () => recompute();
if (typeof mql.addEventListener === "function") mql.addEventListener("change", onChange);
else if (typeof mql.addListener === "function") mql.addListener(onChange);
recompute();
return () => {
disposed = true;
mo.disconnect();
if (typeof mql.removeEventListener === "function") mql.removeEventListener("change", onChange);
else if (typeof mql.removeListener === "function") mql.removeListener(onChange);
};
}, [explicitDark]);
return isDark;
}
var useEffectiveDarkMode_default = useEffectiveDarkMode;
//#endregion
//#region src/components/search-askai/index.tsx
init_compat_module();
const SearchBox = M(function SearchBox$2(props) {
return /* @__PURE__ */ u(SearchInput, {
className: props.className,
placeholder: props.placeholder,
showChat: props.showChat,
isGenerating: props.isGenerating,
isPromptBlockingError: props.isPromptBlockingError,
hideChatInput: props.hideChatInput,
error: props.error,
inputRef: props.inputRef,
setShowChat: props.setShowChat,
onClose: props.onClose || (() => {}),
onArrowDown: props.onArrowDown,
onArrowUp: props.onArrowUp,
onEnter: props.onEnter,
onNewChat: props.onNewChat
});
});
const NoResults = M(function NoResults$2({ query, onAskAI, onClear }) {
return /* @__PURE__ */ u("div", {
className: "ss-no-results",
children: [
/* @__PURE__ */ u("div", {
className: "ss-no-results-icon",
children: /* @__PURE__ */ u(SearchIcon, {})
}),
/* @__PURE__ */ u("p", {
className: "ss-no-results-title",
children: [
"No results for \"",
query,
"\""
]
}),
/* @__PURE__ */ u("p", {
className: "ss-no-results-subtitle",
children: "Try a different query or ask AI to help."
}),
/* @__PURE__ */ u("div", {
className: "ss-no-results-actions",
children: [/* @__PURE__ */ u("button", {
type: "button",
className: "ss-no-results-btn",
onClick: onAskAI,
children: [/* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
children: [/* @__PURE__ */ u("title", { children: "Ask AI" }), /* @__PURE__ */ u("path", {
fill: "currentColor",
d: "m6.8 13l2.9 2.9q.275.275.275.7t-.275.7t-.7.275t-.7-.275l-4.6-4.6q-.15-.15-.213-.325T3.426 12t.063-.375t.212-.325l4.6-4.6q.275-.275.7-.275t.7.275t.275.7t-.275.7L6.8 11H19V8q0-.425.288-.712T20 7t.713.288T21 8v3q0 .825-.587 1.413T19 13z"
})]
}), "Ask AI"]
}), /* @__PURE__ */ u("button", {
type: "button",
className: "ss-no-results-btn",
onClick: onClear,
children: "Clear"
})]
})
]
});
});
const ResultsPanel = M(function ResultsPanel$2({ showChat, inputRef, setShowChat, query, selectedIndex, refine: refine$1, config: config$1, messages, error, isGenerating, sendMessage, onHoverIndex, scrollOnSelectionChange = true, sendEvent, suggestedQuestions, onNewChat, showPromptBlockingError, openResultsInNewTab = true }) {
const { items } = useHits(config$1.transformItems ? { transformItems: config$1.transformItems } : {});
const containerRef = A(null);
const [hoverEnabled, setHoverEnabled] = d(false);
y(() => {
if (showChat) return;
const container = containerRef.current;
if (!container) return;
setHoverEnabled(false);
const enable = () => setHoverEnabled(true);
container.addEventListener("pointermove", enable, { once: true });
return () => {
container.removeEventListener("pointermove", enable);
};
}, [showChat]);
y(() => {
if (showChat || !scrollOnSelectionChange) return;
const container = containerRef.current;
if (!container) return;
const selectedEl = container.querySelector("[aria-selected=\"true\"]");
if (!selectedEl) return;
const padding = 8;
const cRect = container.getBoundingClientRect();
const iRect = selectedEl.getBoundingClientRect();
if (iRect.top < cRect.top + padding) container.scrollTop -= cRect.top + padding - iRect.top;
else if (iRect.bottom > cRect.bottom - padding) container.scrollTop += iRect.bottom - (cRect.bottom - padding);
}, [
selectedIndex,
showChat,
items.length,
scrollOnSelectionChange
]);
const lastSentRef = A(null);
y(() => {
if (!showChat) return;
const trimmed = (query ?? "").trim();
if (!trimmed) return;
if (lastSentRef.current === trimmed) return;
refine$1("");
if (inputRef.current) inputRef.current.focus();
sendMessage({ text: trimmed });
lastSentRef.current = trimmed;
}, [
showChat,
query,
inputRef,
sendMessage,
refine$1
]);
y(() => {
if (messages.length === 0) lastSentRef.current = null;
}, [messages]);
const handleSuggestedQuestionClick = q((question) => {
const trimmed = question.trim();
if (!trimmed || isGenerating) return;
sendMessage({ text: trimmed });
}, [isGenerating, sendMessage]);
if (showChat) return /* @__PURE__ */ u(ChatWidget, {
messages,
error,
isGenerating,
applicationId: config$1.applicationId,
apiKey: config$1.apiKey,
assistantId: config$1.assistantId,
agentStudio: config$1.agentStudio,
suggestedQuestions,
onSuggestedQuestionClick: handleSuggestedQuestionClick,
onNewChat,
showPromptBlockingError
});
return /* @__PURE__ */ u(k$1, { children: /* @__PURE__ */ u("div", {
ref: containerRef,
className: "ss-hits-container",
role: "listbox",
children: /* @__PURE__ */ u(HitsList, {
hits: items,
query,
selectedIndex,
onAskAI: () => setShowChat(true),
attributes: config$1.attributes,
onHoverIndex,
hoverEnabled,
sendEvent,
openResultsInNewTab
})
}) });
});
function SearchModal({ onClose, config: config$1 }) {
const { query, refine: refine$1 } = useSearchBox();
const inputRef = A(null);
const results = useInstantSearch();
const { items, sendEvent } = useHits(config$1.transformItems ? { transformItems: config$1.transformItems } : {});
const { showChat, setShowChat, handleShowChat } = useSearchState();
y(() => {
const rafId = requestAnimationFrame(() => {
if (inputRef.current) inputRef.current.focus();
});
return () => cancelAnimationFrame(rafId);
}, []);
const { messages, error, isGenerating, sendMessage, startNewConversation, promptBlockingError, showPromptBlockingError } = useAskai({
applicationId: config$1.applicationId,
apiKey: config$1.apiKey,
indexName: config$1.indexName,
assistantId: config$1.assistantId,
agentStudio: config$1.agentStudio
});
const suggestedQuestionsClient = T(() => {
const client = liteClient(config$1.applicationId, config$1.apiKey);
client.addAlgoliaAgent("algolia-sitesearch");
return client;
}, [config$1.applicationId, config$1.apiKey]);
const suggestedQuestions = useSuggestedQuestions({
searchClient: suggestedQuestionsClient,
assistantId: config$1.assistantId,
suggestedQuestionsEnabled: config$1.suggestedQuestionsEnabled ?? false,
isOpen: showChat
});
/** Agent Studio: hide chat field for token output, domain-blocked-style blocks, etc. */
const hideModalChatInput = T(() => showChat && showPromptBlockingError && shouldHideAskAiShellChatInput(error, Boolean(config$1.agentStudio)), [
showChat,
showPromptBlockingError,
error,
config$1.agentStudio
]);
const noResults = results.results?.nbHits === 0;
const { selectedIndex, moveDown, moveUp, activateSelection, hoverIndex, selectionOrigin } = useKeyboardNavigation(showChat, items, query, config$1.openResultsInNewTab ?? true);
const handleActivateSelection = q(() => {
if (selectedIndex > 0) {
const hit = items[selectedIndex - 1];
if (hit) sendEvent?.("click", hit, "Hit Clicked");
}
if (activateSelection()) {
if (selectedIndex === 0) handleShowChat(true);
return true;
}
return false;
}, [
activateSelection,
selectedIndex,
handleShowChat,
items,
sendEvent
]);
const showResultsPanel = !noResults && !!query || showChat;
const handleNewChat = q(() => {
startNewConversation();
setShowChat(true);
refine$1("");
if (inputRef.current) inputRef.current.focus();
}, [
startNewConversation,
setShowChat,
refine$1
]);
/** Leaving chat while prompts are blocked: reset thread so Ask AI works again without closing the modal. */
const handleSetShowChat = q((v$3) => {
if (!v$3 && promptBlockingError) startNewConversation();
setShowChat(v$3);
}, [
setShowChat,
promptBlockingError,
startNewConversation
]);
return /* @__PURE__ */ u(k$1, { children: [
/* @__PURE__ */ u(Configure, {
hitsPerPage: config$1.hitsPerPage || 8,
...config$1.searchParameters || {}
}),
/* @__PURE__ */ u("div", {
className: "search-panel",
children: [
/* @__PURE__ */ u(SearchBox, {
query,
placeholder: config$1.placeholder || "What are you looking for?",
className: "ss-searchbox-form",
refine: refine$1,
showChat,
isGenerating,
isPromptBlockingError: showPromptBlockingError,
hideChatInput: hideModalChatInput,
error,
setShowChat: handleSetShowChat,
onClose,
onArrowDown: moveDown,
onArrowUp: moveUp,
onEnter: (value) => {
const trimmed = (value ?? "").trim();
if (showChat && trimmed) {
refine$1(trimmed);
return true;
}
return handleActivateSelection();
},
inputRef,
onNewChat: handleNewChat
}),
showResultsPanel && /* @__PURE__ */ u(ResultsPanel, {
showChat,
inputRef,
setShowChat: handleSetShowChat,
query,
selectedIndex,
refine: refine$1,
config: config$1,
messages,
error,
isGenerating,
sendMessage,
onHoverIndex: hoverIndex,
scrollOnSelectionChange: selectionOrigin !== "pointer",
sendEvent,
suggestedQuestions,
onNewChat: handleNewChat,
showPromptBlockingError,
openResultsInNewTab: config$1.openResultsInNewTab
}),
noResults && query && !showChat && /* @__PURE__ */ u(NoResults, {
query,
onAskAI: () => {
setShowChat(true);
},
onClear: () => {
refine$1("");
if (inputRef.current) inputRef.current.focus();
}
})
]
}),
/* @__PURE__ */ u(Footer, { showChat })
] });
}
const Footer = M(function Footer$2({ showChat }) {
const basePoweredByUrl$1 = "https://www.algolia.com/developers?utm_medium=referral&utm_content=powered_by&utm_campaign=sitesearch";
const poweredByHref = typeof window !== "undefined" ? `${basePoweredByUrl$1}&utm_source=${encodeURIComponent(window.location.hostname)}` : basePoweredByUrl$1;
return /* @__PURE__ */ u("div", {
className: "ss-footer",
children: [/* @__PURE__ */ u("div", {
className: "ss-footer-left",
children: [/* @__PURE__ */ u("div", {
className: "ss-footer-kbd-group",
children: [/* @__PURE__ */ u("kbd", {
className: "ss-kbd",
children: /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
children: /* @__PURE__ */ u("path", {
fill: "currentColor",
d: "m6.8 13l2.9 2.9q.275.275.275.7t-.275.7t-.7.275t-.7-.275l-4.6-4.6q-.15-.15-.213-.325T3.426 12t.063-.375t.212-.325l4.6-4.6q.275-.275.7-.275t.7.275t.275.7t-.275.7L6.8 11H19V8q0-.425.288-.712T20 7t.713.288T21 8v3q0 .825-.587 1.413T19 13z"
})
})
}), /* @__PURE__ */ u("span", { children: showChat ? "Ask question" : "Open" })]
}), /* @__PURE__ */ u("div", {
className: "ss-footer-kbd-group",
children: [
/* @__PURE__ */ u("kbd", {
className: "ss-kbd",
children: /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
children: /* @__PURE__ */ u("path", {
fill: "currentColor",
d: "m11 7.825l-4.9 4.9q-.3.3-.7.288t-.7-.313q-.275-.3-.288-.7t.288-.7l6.6-6.6q.15-.15.325-.212T12 4.425t.375.063t.325.212l6.6 6.6q.275.275.275.688t-.275.712q-.3.3-.712.3t-.713-.3L13 7.825V19q0 .425-.288.713T12 20t-.712-.288T11 19z"
})
})
}),
/* @__PURE__ */ u("kbd", {
className: "ss-kbd",
children: /* @__PURE__ */ u("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
children: /* @__PURE__ */ u("path", {
fill: "currentColor",
d: "M11 16.175V5q0-.425.288-.712T12 4t.713.288T13 5v11.175l4.9-4.9q.3-.3.7-.288t.7.313q.275.3.287.7t-.287.7l-6.6 6.6q-.15.15-.325.213t-.375.062t-.375-.062t-.325-.213l-6.6-6.6q-.275-.275-.275-.687T4.7 11.3q.3-.3.713-.3t.712.3z"
})
})
}),
/* @__PURE__ */ u("span", { children: "Navigate" })
]
})]
}), /* @__PURE__ */ u("div", {
className: "ss-footer-right",
children: /* @__PURE__ */ u("a", {
className: "ss-footer-powered-by",
href: poweredByHref,
target: "_blank",
rel: "noopener noreferrer",
children: [/* @__PURE__ */ u("span", { children: "Powered by " }), /* @__PURE__ */ u(AlgoliaLogo, {})]
})
})]
});
});
function SearchExperience$1(config$1) {
const searchClient = liteClient(config$1.applicationId, config$1.apiKey);
searchClient.addAlgoliaAgent("algolia-sitesearch");
const [isModalOpen, setIsModalOpen] = d(false);
const isDark = useEffectiveDarkMode_default(config$1.darkMode);
const openModal = () => setIsModalOpen(true);
const closeModal = () => setIsModalOpen(false);
y(() => {
const handleKeyDown = (event) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault();
setIsModalOpen(true);
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, []);
const buttonProps = {
...config$1.buttonProps,
onClick: openModal
};
return /* @__PURE__ */ u(k$1, { children: [/* @__PURE__ */ u(SearchButton, {
...buttonProps,
darkMode: isDark,
children: config$1.buttonText
}), /* @__PURE__ */ u(Modal, {
isOpen: isModalOpen,
onClose: closeModal,
isDark,
children: /* @__PURE__ */ u(InstantSearch, {
searchClient,
indexName: config$1.indexName,
future: { preserveSharedStateOnUnmount: true },
insights: config$1.insights || true,
children: /* @__PURE__ */ u(SearchModal, {
onClose: closeModal,
config: config$1
})
})
})] });
}
//#endregion
//#region src/components/sidepanel-askai/index.tsx
init_compat_module();
const basePoweredByUrl = "https://www.algolia.com/?utm_medium=website&utm_source=sitesearch&utm_campaign=poweredby";
const SidepanelInner = M(function SidepanelInner$1({ config: config$1, onClose }) {
const inputRef = A(null);
const [input, setInput] = d("");
const poweredByHref = T(() => typeof window !== "undefined" ? `${basePoweredByUrl}&utm_source=${encodeURIComponent(window.location.hostname)}` : basePoweredByUrl, []);
const { messages, error, isGenerating, sendMessage, startNewConversation, showPromptBlockingError } = useAskai({
applicationId: config$1.applicationId,
apiKey: config$1.apiKey,
indexName: config$1.indexName,
assistantId: config$1.assistantId,
agentStudio: config$1.agentStudio
});
const suggestedQuestionsClient = T(() => {
const client = liteClient(config$1.applicationId, config$1.apiKey);
client.addAlgoliaAgent("algolia-sitesearch");
return client;
}, [config$1.applicationId, config$1.apiKey]);
const suggestedQuestions = useSuggestedQuestions({
searchClient: suggestedQuestionsClient,
assistantId: config$1.assistantId,
suggestedQuestionsEnabled: config$1.suggestedQuestionsEnabled ?? false,
isOpen: true
});
const handleSuggestedQuestionClick = q((question) => {
const trimmed = question.trim();
if (!trimmed || isGenerating) return;
sendMessage({ text: trimmed });
}, [isGenerating, sendMessage]);
const handleNewChat = q(() => {
startNewConversation();
setInput("");
requestAnimationFrame(() => inputRef.current?.focus());
}, [startNewConversation]);
/** Agent Studio: hide compose for thread depth, token output, domain-blocked-style blocks, etc. */
const hideSidepanelCompose = T(() => showPromptBlockingError && (shouldHideAskAiShellChatInput(error, Boolean(config$1.agentStudio)) || Boolean(config$1.agentStudio) && isThreadDepthError(error)), [
showPromptBlockingError,
error,
config$1.agentStudio
]);
const domainBlocked = isRequestBlockedForDomainAskAiError(error);
const placeholder = showPromptBlockingError && domainBlocked ? "" : showPromptBlockingError && !domainBlocked ? "Conversation limit reached" : isGenerating ? "Answering..." : config$1.placeholder ?? "Ask AI anything";
const submit = q(() => {
const trimmed = input.trim();
if (!trimmed || isGenerating || showPromptBlockingError) return;
sendMessage({ text: trimmed });
setInput("");
}, [
input,
isGenerating,
showPromptBlockingError,
sendMessage
]);
y(() => {
const onKey = (e$2) => {
if (e$2.key === "Escape") {
e$2.preventDefault();
onClose();
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [onClose]);
y(() => {
requestAnimationFrame(() => inputRef.current?.focus());
}, []);
return /* @__PURE__ */ u("div", {
className: "ss-sidepanel-inner",
children: [
/* @__PURE__ */ u("header", {
className: "ss-sidepanel-header",
children: [/* @__PURE__ */ u("div", {
className: "ss-sidepanel-title-group",
children: [/* @__PURE__ */ u(SparklesIcon, {
size: 20,
gradientIdSuffix: "-sp-hdr",
className: "ss-sidepanel-title-sparkle"
}), /* @__PURE__ */ u("h2", {
className: "ss-sidepanel-title",
children: "Ask AI"
})]
}), /* @__PURE__ */ u("div", {
className: "ss-sidepanel-header-actions",
children: [/* @__PURE__ */ u("button", {
type: "button",
className: "ss-search-new-chat-button",
disabled: isGenerating && !showPromptBlockingError,
title: showPromptBlockingError ? "Start a new conversation" : "New conversation",
"aria-label": showPromptBlockingError ? "Start a new conversation" : "New conversation",
onClick: handleNewChat,
children: /* @__PURE__ */ u(SquarePenIcon, { size: 18 })
}), /* @__PURE__ */ u("button", {
type: "button",
className: "ss-search-close-button",
onClick: onClose,
"aria-label": "Close panel",
title: "Close",
children: /* @__PURE__ */ u(CloseIcon, {})
})]
})]
}),
/* @__PURE__ */ u("div", {
className: "ss-sidepanel-body",
children: /* @__PURE__ */ u(ChatWidget, {
messages,
error,
isGenerating,
applicationId: config$1.applicationId,
apiKey: config$1.apiKey,
assistantId: config$1.assistantId,
agentStudio: config$1.agentStudio,
suggestedQuestions,
onSuggestedQuestionClick: handleSuggestedQuestionClick,
onNewChat: handleNewChat,
showPromptBlockingError,
threadDepthBannerInChat: false,
showAiDisclaimer: false,
newestExchangeFirst: false
})
}),
/* @__PURE__ */ u("div", {
className: "ss-sidepanel-compose-stack",
children: [showPromptBlockingError ? /* @__PURE__ */ u("div", {
className: "ss-sidepanel-thread-depth-banner",
children: /* @__PURE__ */ u(ThreadDepthErrorBanner, {
onNewChat: handleNewChat,
detailMessage: promptBlockingBannerMessage(error, config$1.agentStudio),
showNewConversationLink: showAskAiBlockingBannerNewConversationLink(error, Boolean(config$1.agentStudio))
})
}) : null, /* @__PURE__ */ u("footer", {
className: "ss-sidepanel-footer",
children: [
!hideSidepanelCompose ? /* @__PURE__ */ u("search", {
className: "ss-searchbox-form ss-searchbox-form--chat ss-sidepanel-compose-form",
onSubmit: (e$2) => {
e$2.preventDefault();
submit();
},
children: [/* @__PURE__ */ u("input", {
ref: inputRef,
autoComplete: "off",
autoCorrect: "off",
autoCapitalize: "off",
spellCheck: false,
maxLength: 512,
type: "search",
placeholder,
value: input,
disabled: isGenerating || showPromptBlockingError,
onChange: (e$2) => setInput(e$2.currentTarget.value),
onKeyDown: (e$2) => {
if (e$2.key === "Enter") {
e$2.preventDefault();
submit();
}
}
}), /* @__PURE__ */ u("button", {
type: "submit",
className: "ss-search-submit-chat-button",
disabled: isGenerating || showPromptBlockingError || !input.trim(),
title: "Send message",
"aria-label": "Send message",
children: /* @__PURE__ */ u(ChatSubmitIcon, { size: 22 })
})]
}) : null,
/* @__PURE__ */ u("div", {
className: "ss-sidepanel-ai-notice",
children: /* @__PURE__ */ u("p", {
className: "ss-sidepanel-ai-notice-text",
children: "Answers are generated with AI which can make mistakes."
})
}),
/* @__PURE__ */ u("div", {
className: "ss-sidepanel-powered-by",
children: /* @__PURE__ */ u("a", {
className: "ss-sidepanel-powered-by-link",
href: poweredByHref,
target: "_blank",
rel: "noopener noreferrer",
children: [/* @__PURE__ */ u("span", {
className: "ss-sidepanel-powered-by-label",
children: "Powered by "
}), /* @__PURE__ */ u(AlgoliaLogo, { size: 80 })]
})
})
]
})]
})
]
});
});
function SidepanelAskAIExperience(config$1) {
const [open, setOpen] = d(false);
const isDark = useEffectiveDarkMode_default(config$1.darkMode);
const triggerPosition = config$1.triggerPosition ?? "fixed";
return /* @__PURE__ */ u("div", {
className: `ssask-exp ss-sidepanel-root ss-sidepanel-root--${triggerPosition}${isDark ? " dark" : ""}`,
children: [/* @__PURE__ */ u("button", {
type: "button",
className: "ss-sidepanel-trigger",
onClick: () => setOpen(true),
"aria-expanded": open,
"aria-haspopup": "dialog",
children: [/* @__PURE__ */ u(SparklesIcon, { size: 18 }), /* @__PURE__ */ u("span", { children: config$1.buttonText ?? "Ask AI" })]
}), open && typeof document !== "undefined" && $(/* @__PURE__ */ u(k$1, { children: [/* @__PURE__ */ u("button", {
type: "button",
className: "ss-sidepanel-backdrop",
"aria-label": "Close panel",
onClick: () => setOpen(false)
}), /* @__PURE__ */ u("div", {
className: `ss-sidepanel-panel ssask-exp${isDark ? " dark" : ""}`,
role: "dialog",
"aria-modal": "true",
children: /* @__PURE__ */ u(SidepanelInner, {
config: config$1,
onClose: () => setOpen(false)
})
})] }), document.body)]
});
}
//#endregion
export { SearchExperience as Search, SearchExperience$1 as SearchWithAskAI, SidepanelAskAIExperience as SidepanelAskAI };