@marketrix.ai/widget 3.8.473 → 3.8.475
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/components/blocks/WidgetFab.d.ts +1 -1
- package/dist/src/components/views/ChatView.d.ts +2 -2
- package/dist/src/context/sseReducer.d.ts +0 -6
- package/dist/src/hooks/useDragSnap.d.ts +2 -2
- package/dist/src/hooks/useScreenShare.d.ts +3 -3
- package/dist/src/index.d.ts +10 -4
- package/dist/src/services/ShowModeService.d.ts +1 -1
- package/dist/src/services/StorageService.d.ts +0 -1
- package/dist/src/services/StreamClient.d.ts +1 -0
- package/dist/src/types/index.d.ts +9 -14
- package/dist/src/utils/chat.d.ts +1 -2
- package/dist/src/utils/validation.d.ts +2 -0
- package/dist/widget.mjs +57 -58
- package/package.json +3 -2
- package/dist/widget.mjs.map +0 -1
package/dist/widget.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"widget.mjs","names":["#cleanup","#next","#isDone","#isExecuteComplete","isObject","isObject","toStandardHeaders","isObject","#serialize","#deserialize","F","_a","_zodDesc","util.jsonStringifyReplacer","initializer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodError","safeParse","errors.$ZodRealError","safeParseAsync","email","_emoji","date","string","number","boolean","util.nullish","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.codePointLength","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","content","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","util.hide","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.nanoidOfLength","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","regexes.base64url","regexes.e164","regexes.number","regexes.boolean","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.parsedType","util.stringifyPrimitive","util.joinValues","_a","util.normalizeParams","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","regexes.number","regexes.integer","core.formatError","core.flattenError","util.jsonStringifyReplacer","encode","en","core.memoizer","util.mergeDefs","core.clone","checks.overwrite","util.hide","core.standardProps","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","number","core._number","core._int","processors.booleanProcessor","core._boolean","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.dateProcessor","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.recordProcessor","record","processors.enumProcessor","processors.literalProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","core.util.constantCatch","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine","core._coercedNumber","schemas.ZodNumber","core._coercedDate","schemas.ZodDate","ownerDocument","contains","isElement","isShadowRoot","isHTMLElement","getComputedStyle","React","React","React","React","_formatErrorMessage","React","ownerWindow","React","isHTMLElement","React","React","_formatErrorMessage","Button","React","_formatErrorMessage","React","EMPTY","platform.os.android","platform.env.jsdom","isHTMLElement","React","platform.screenReader.voiceOver","platform.engine.webkit","getComputedStyle","getComputedStyle","isHTMLElement","React","React","ownerWindow","React","isHTMLElement","REASONS.focusOut","platform.engine.webkit","outsidePress","React","REASONS.triggerPress","escapeKey","REASONS.escapeKey","platform.engine.webkit","isHTMLElement","getComputedStyle","REASONS.outsidePress","React","React","selectors","React","React","React","REASONS.none","React","_formatErrorMessage","ownerWindow","platform.engine.webkit","platform.os.ios","React","REASONS.imperativeAction"],"sources":["../node_modules/@orpc/shared/dist/index.mjs","../node_modules/@orpc/client/dist/shared/client.CZlviB0y.mjs","../node_modules/@orpc/standard-server/dist/index.mjs","../node_modules/@orpc/client/dist/shared/client.BLtwTQUg.mjs","../node_modules/@orpc/client/dist/index.mjs","../node_modules/@orpc/standard-server-fetch/dist/index.mjs","../node_modules/@orpc/client/dist/shared/client.BtiuJPEa.mjs","../node_modules/@orpc/client/dist/adapters/fetch/index.mjs","../node_modules/zod/v4/core/util.js","../node_modules/zod/v4/core/core.js","../node_modules/zod/v4/core/errors.js","../node_modules/zod/v4/core/parse.js","../node_modules/zod/v4/core/regexes.js","../node_modules/zod/v4/core/checks.js","../node_modules/zod/v4/core/doc.js","../node_modules/zod/v4/core/versions.js","../node_modules/zod/v4/core/schemas.js","../node_modules/zod/v4/core/memoizer.js","../node_modules/zod/v4/locales/en.js","../node_modules/zod/v4/core/registries.js","../node_modules/zod/v4/core/api.js","../node_modules/zod/v4/core/to-json-schema.js","../node_modules/zod/v4/core/json-schema-processors.js","../node_modules/zod/v4/classic/errors.js","../node_modules/zod/v4/classic/parse.js","../node_modules/zod/v4/classic/schemas.js","../node_modules/zod/v4/classic/coerce.js","../src/sdk/contracts/common.ts","../src/sdk/contracts/entities.ts","../src/sdk/index.ts","../src/services/StorageService.ts","../src/services/ChatSessionManager.ts","../node_modules/@rrweb/record/dist/record.js","../src/services/RrwebSessionRecorder.ts","../src/services/StreamClient.ts","../src/services/WidgetService.ts","../src/assets/marketrix-icon.svg","../src/design-system/shadows.ts","../src/design-system/component-tokens.ts","../src/design-system/layers.ts","../node_modules/tailwind-merge/dist/bundle-mjs.mjs","../src/lib/utils.ts","../src/components/base/layoutProps.ts","../src/components/base/Avatar.tsx","../node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","../node_modules/@base-ui/utils/safeReact.mjs","../node_modules/@base-ui/utils/useRefWithInit.mjs","../node_modules/@base-ui/utils/useStableCallback.mjs","../node_modules/@base-ui/utils/useIsoLayoutEffect.mjs","../node_modules/@base-ui/utils/mergeObjects.mjs","../node_modules/@base-ui/react/merge-props/mergeProps.mjs","../node_modules/@base-ui/utils/formatErrorMessage.mjs","../node_modules/@base-ui/react/internals/composite/root/CompositeRootContext.mjs","../node_modules/@base-ui/react/utils/useFocusableWhenDisabled.mjs","../node_modules/@base-ui/utils/owner.mjs","../node_modules/@base-ui/react/utils/dispatchClickWithModifiers.mjs","../node_modules/@base-ui/react/internals/use-button/useButton.mjs","../node_modules/@base-ui/utils/useMergedRefs.mjs","../node_modules/@base-ui/utils/reactVersion.mjs","../node_modules/@base-ui/utils/getReactElementRef.mjs","../node_modules/@base-ui/utils/empty.mjs","../node_modules/@base-ui/react/internals/getStateAttributesProps.mjs","../node_modules/@base-ui/react/utils/resolveClassName.mjs","../node_modules/@base-ui/react/utils/resolveStyle.mjs","../node_modules/@base-ui/react/internals/useRenderElement.mjs","../node_modules/@base-ui/react/button/Button.mjs","../src/components/base/Button.tsx","../src/components/base/Surface.tsx","../src/components/base/Flex.tsx","../src/components/base/icons.ts","../src/components/base/Icon.tsx","../src/components/base/IconButton.tsx","../src/components/base/Stack.tsx","../src/components/base/Text.tsx","../src/components/blocks/NotificationToast.tsx","../src/services/ChatService.ts","../src/services/ApiService.ts","../src/utils/chat.ts","../src/utils/dom.ts","../src/services/DomService.ts","../src/services/ScreenShareService.ts","../src/services/ShowModeService.ts","../src/services/BrowserToolService.ts","../src/context/sseReducer.ts","../src/context/UIStateContext.tsx","../src/context/ChatContext.tsx","../src/context/WidgetProviders.tsx","../src/utils/color.ts","../src/design-system/semantic-tokens.ts","../src/hooks/useScrollLock.ts","../src/hooks/useWidget.ts","../src/utils/widgetPositioning.ts","../src/components/base/ErrorBoundary.tsx","../src/hooks/useDragSnap.ts","../src/components/blocks/WidgetFab.tsx","../src/hooks/useFocusTrap.ts","../src/hooks/useResize.ts","../src/components/blocks/HeaderBar.tsx","../src/hooks/useScreenShare.ts","../src/components/blocks/ChatInput.tsx","../node_modules/@base-ui/react/dialog/root/DialogRootContext.mjs","../node_modules/@base-ui/react/internals/stateAttributesMapping.mjs","../node_modules/@base-ui/react/utils/popupStateMapping.mjs","../node_modules/@base-ui/react/dialog/backdrop/DialogBackdrop.mjs","../node_modules/@base-ui/react/internals/reason-parts.mjs","../node_modules/@base-ui/react/internals/createBaseUIEventDetails.mjs","../node_modules/@base-ui/utils/useId.mjs","../node_modules/@base-ui/react/internals/useBaseUiId.mjs","../node_modules/@base-ui/react/dialog/description/DialogDescription.mjs","../node_modules/@base-ui/utils/useOnMount.mjs","../node_modules/@base-ui/utils/useTimeout.mjs","../node_modules/@base-ui/utils/platform/shared.mjs","../node_modules/@base-ui/utils/platform/os.mjs","../node_modules/@base-ui/utils/platform/engine.mjs","../node_modules/@base-ui/utils/platform/screen-reader.mjs","../node_modules/@base-ui/utils/platform/env.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/event.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/constants.mjs","../node_modules/@base-ui/react/internals/shadowDom.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/element.mjs","../node_modules/@base-ui/utils/addEventListener.mjs","../node_modules/@base-ui/utils/mergeCleanups.mjs","../node_modules/@base-ui/utils/useValueAsRef.mjs","../node_modules/@base-ui/utils/useAnimationFrame.mjs","../node_modules/@base-ui/utils/visuallyHidden.mjs","../node_modules/@base-ui/react/utils/FocusGuard.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/composite.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/tabbable.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/nodes.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/createAttribute.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/enqueueFocus.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/markOthers.mjs","../node_modules/@base-ui/react/internals/constants.mjs","../node_modules/@base-ui/react/floating-ui-react/components/FloatingPortal.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/createEventEmitter.mjs","../node_modules/@base-ui/react/floating-ui-react/components/FloatingTree.mjs","../node_modules/@base-ui/react/utils/resolveRef.mjs","../node_modules/@base-ui/react/floating-ui-react/components/FloatingFocusManager.mjs","../node_modules/@base-ui/react/floating-ui-react/hooks/useDismiss.mjs","../src/react19.ts","../node_modules/@base-ui/utils/fastHooks.mjs","../node_modules/@base-ui/utils/store/useStore.mjs","../node_modules/@base-ui/utils/store/Store.mjs","../node_modules/@base-ui/utils/store/ReactStore.mjs","../node_modules/@base-ui/react/floating-ui-react/components/FloatingRootStore.mjs","../node_modules/@base-ui/react/floating-ui-react/hooks/useSyncedFloatingRootContext.mjs","../node_modules/@base-ui/react/internals/useTransitionStatus.mjs","../node_modules/@base-ui/react/internals/useAnimationsFinished.mjs","../node_modules/@base-ui/react/internals/useOpenChangeComplete.mjs","../node_modules/@base-ui/react/utils/popups/popupStoreUtils.mjs","../node_modules/@base-ui/react/utils/popups/popupTriggerMap.mjs","../node_modules/@base-ui/react/floating-ui-react/utils/getEmptyRootContext.mjs","../node_modules/@base-ui/react/utils/popups/store.mjs","../node_modules/@base-ui/react/dialog/portal/DialogPortalContext.mjs","../node_modules/@base-ui/react/internals/composite/composite.mjs","../node_modules/@base-ui/react/dialog/utils/stateAttributesMapping.mjs","../node_modules/@base-ui/react/dialog/popup/DialogPopup.mjs","../node_modules/@base-ui/utils/inertValue.mjs","../node_modules/@base-ui/react/utils/InternalBackdrop.mjs","../node_modules/@base-ui/react/dialog/portal/DialogPortal.mjs","../node_modules/@base-ui/utils/useScrollLock.mjs","../node_modules/@base-ui/react/dialog/root/useDialogRoot.mjs","../node_modules/@base-ui/react/dialog/store/DialogStore.mjs","../node_modules/@base-ui/react/dialog/root/useRenderDialogRoot.mjs","../node_modules/@base-ui/react/dialog/root/DialogRoot.mjs","../node_modules/@base-ui/react/dialog/title/DialogTitle.mjs","../src/components/blocks/WidgetDialog.tsx","../src/components/base/Spinner.tsx","../src/components/chat/ThinkingIndicator.tsx","../src/components/chat/MessageContent.tsx","../src/components/chat/TaskStatusIcon.tsx","../src/components/chat/VideoStreamDisplay.tsx","../src/components/chat/MessageItem.tsx","../src/components/chat/MessageList.tsx","../src/components/views/ChatView.tsx","../src/utils/suggestedActions.ts","../src/components/chat/SuggestedActions.tsx","../src/components/views/HomeView.tsx","../src/components/navigation/ResizeHandles.tsx","../src/components/navigation/ShellTabBar.tsx","../src/components/navigation/MessengerShell.tsx","../src/components/WidgetRoot.tsx","../src/utils/validation.ts","../src/utils/bootstrap.tsx","../src/index.tsx"],"sourcesContent":["export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';\n\nfunction resolveMaybeOptionalOptions(rest) {\n return rest[0] ?? {};\n}\n\nfunction toArray(value) {\n return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];\n}\nfunction splitInHalf(arr) {\n const half = Math.ceil(arr.length / 2);\n return [arr.slice(0, half), arr.slice(half)];\n}\n\nfunction readAsBuffer(source) {\n if (typeof source.bytes === \"function\") {\n return source.bytes();\n }\n return source.arrayBuffer();\n}\n\nconst ORPC_NAME = \"orpc\";\nconst ORPC_SHARED_PACKAGE_NAME = \"@orpc/shared\";\nconst ORPC_SHARED_PACKAGE_VERSION = \"1.15.0\";\n\nclass AbortError extends Error {\n constructor(...rest) {\n super(...rest);\n this.name = \"AbortError\";\n }\n}\n\nfunction once(fn) {\n let cached;\n return () => {\n if (cached) {\n return cached.result;\n }\n const result = fn();\n cached = { result };\n return result;\n };\n}\nfunction sequential(fn) {\n let lastOperationPromise = Promise.resolve();\n return (...args) => {\n return lastOperationPromise = lastOperationPromise.catch(() => {\n }).then(() => {\n return fn(...args);\n });\n };\n}\nfunction defer(callback) {\n if (typeof setTimeout === \"function\") {\n setTimeout(callback, 0);\n } else {\n Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));\n }\n}\n\nconst SPAN_ERROR_STATUS = 2;\nconst GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;\nfunction setGlobalOtelConfig(config) {\n globalThis[GLOBAL_OTEL_CONFIG_KEY] = config;\n}\nfunction getGlobalOtelConfig() {\n return globalThis[GLOBAL_OTEL_CONFIG_KEY];\n}\nfunction startSpan(name, options = {}, context) {\n const tracer = getGlobalOtelConfig()?.tracer;\n return tracer?.startSpan(name, options, context);\n}\nfunction setSpanError(span, error, options = {}) {\n if (!span) {\n return;\n }\n const exception = toOtelException(error);\n span.recordException(exception);\n if (!options.signal?.aborted || options.signal.reason !== error) {\n span.setStatus({\n code: SPAN_ERROR_STATUS,\n message: exception.message\n });\n }\n}\nfunction setSpanAttribute(span, key, value) {\n if (!span || value === void 0) {\n return;\n }\n span.setAttribute(key, value);\n}\nfunction toOtelException(error) {\n if (error instanceof Error) {\n const exception = {\n message: error.message,\n name: error.name,\n stack: error.stack\n };\n if (\"code\" in error && (typeof error.code === \"string\" || typeof error.code === \"number\")) {\n exception.code = error.code;\n }\n return exception;\n }\n return { message: String(error) };\n}\nfunction toSpanAttributeValue(data) {\n if (data === void 0) {\n return \"undefined\";\n }\n try {\n return JSON.stringify(data, (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n if (value instanceof Map || value instanceof Set) {\n return Array.from(value);\n }\n return value;\n });\n } catch {\n return String(data);\n }\n}\nasync function runWithSpan({ name, context, ...options }, fn) {\n const tracer = getGlobalOtelConfig()?.tracer;\n if (!tracer) {\n return fn();\n }\n const callback = async (span) => {\n try {\n return await fn(span);\n } catch (e) {\n setSpanError(span, e, options);\n throw e;\n } finally {\n span.end();\n }\n };\n if (context) {\n return tracer.startActiveSpan(name, options, context, callback);\n } else {\n return tracer.startActiveSpan(name, options, callback);\n }\n}\nasync function runInSpanContext(span, fn) {\n const otelConfig = getGlobalOtelConfig();\n if (!span || !otelConfig) {\n return fn();\n }\n const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);\n return otelConfig.context.with(ctx, fn);\n}\n\nclass AsyncIdQueue {\n openIds = /* @__PURE__ */ new Set();\n queues = /* @__PURE__ */ new Map();\n waiters = /* @__PURE__ */ new Map();\n get length() {\n return this.openIds.size;\n }\n get waiterIds() {\n return Array.from(this.waiters.keys());\n }\n hasBufferedItems(id) {\n return Boolean(this.queues.get(id)?.length);\n }\n open(id) {\n this.openIds.add(id);\n }\n isOpen(id) {\n return this.openIds.has(id);\n }\n push(id, item) {\n this.assertOpen(id);\n const pending = this.waiters.get(id);\n if (pending?.length) {\n pending.shift()[0](item);\n if (pending.length === 0) {\n this.waiters.delete(id);\n }\n } else {\n const items = this.queues.get(id);\n if (items) {\n items.push(item);\n } else {\n this.queues.set(id, [item]);\n }\n }\n }\n async pull(id) {\n this.assertOpen(id);\n const items = this.queues.get(id);\n if (items?.length) {\n const item = items.shift();\n if (items.length === 0) {\n this.queues.delete(id);\n }\n return item;\n }\n return new Promise((resolve, reject) => {\n const waitingPulls = this.waiters.get(id);\n const pending = [resolve, reject];\n if (waitingPulls) {\n waitingPulls.push(pending);\n } else {\n this.waiters.set(id, [pending]);\n }\n });\n }\n close({ id, reason } = {}) {\n if (id === void 0) {\n this.waiters.forEach((pendingPulls, id2) => {\n const error2 = reason ?? new AbortError(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`);\n pendingPulls.forEach(([, reject]) => reject(error2));\n });\n this.waiters.clear();\n this.openIds.clear();\n this.queues.clear();\n return;\n }\n const error = reason ?? new AbortError(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`);\n this.waiters.get(id)?.forEach(([, reject]) => reject(error));\n this.waiters.delete(id);\n this.openIds.delete(id);\n this.queues.delete(id);\n }\n assertOpen(id) {\n if (!this.isOpen(id)) {\n throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);\n }\n }\n}\n\nfunction isAsyncIteratorObject(maybe) {\n if (!maybe || typeof maybe !== \"object\") {\n return false;\n }\n return \"next\" in maybe && typeof maybe.next === \"function\" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === \"function\";\n}\nconst fallbackAsyncDisposeSymbol = Symbol.for(\"asyncDispose\");\nconst asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;\nclass AsyncIteratorClass {\n #isDone = false;\n #isExecuteComplete = false;\n #cleanup;\n #next;\n constructor(next, cleanup) {\n this.#cleanup = cleanup;\n this.#next = sequential(async () => {\n if (this.#isDone) {\n return { done: true, value: void 0 };\n }\n try {\n const result = await next();\n if (result.done) {\n this.#isDone = true;\n }\n return result;\n } catch (err) {\n this.#isDone = true;\n throw err;\n } finally {\n if (this.#isDone && !this.#isExecuteComplete) {\n this.#isExecuteComplete = true;\n await this.#cleanup(\"next\");\n }\n }\n });\n }\n next() {\n return this.#next();\n }\n async return(value) {\n this.#isDone = true;\n if (!this.#isExecuteComplete) {\n this.#isExecuteComplete = true;\n await this.#cleanup(\"return\");\n }\n return { done: true, value };\n }\n async throw(err) {\n this.#isDone = true;\n if (!this.#isExecuteComplete) {\n this.#isExecuteComplete = true;\n await this.#cleanup(\"throw\");\n }\n throw err;\n }\n /**\n * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')\n */\n async [asyncDisposeSymbol]() {\n this.#isDone = true;\n if (!this.#isExecuteComplete) {\n this.#isExecuteComplete = true;\n await this.#cleanup(\"dispose\");\n }\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n}\nfunction replicateAsyncIterator(source, count) {\n const queue = new AsyncIdQueue();\n const ids = Array.from({ length: count }, (_, i) => i.toString());\n let isSourceFinished = false;\n const start = once(async () => {\n try {\n while (true) {\n const item = await source.next();\n ids.forEach((id) => {\n if (queue.isOpen(id)) {\n queue.push(id, { next: item });\n }\n });\n if (item.done) {\n break;\n }\n }\n } catch (error) {\n ids.forEach((id) => {\n if (queue.isOpen(id)) {\n queue.push(id, { error });\n }\n });\n } finally {\n isSourceFinished = true;\n }\n });\n const replicated = ids.map((id) => {\n queue.open(id);\n return new AsyncIteratorClass(\n async () => {\n start();\n const item = await queue.pull(id);\n if (item.next) {\n return item.next;\n }\n throw item.error;\n },\n async (reason) => {\n queue.close({ id });\n if (reason !== \"next\" && !queue.length && !isSourceFinished) {\n isSourceFinished = true;\n await source?.return?.();\n }\n }\n );\n });\n return replicated;\n}\nfunction asyncIteratorWithSpan({ name, ...options }, iterator) {\n let span;\n return new AsyncIteratorClass(\n async () => {\n span ??= startSpan(name);\n try {\n const result = await runInSpanContext(span, () => iterator.next());\n span?.addEvent(result.done ? \"completed\" : \"yielded\");\n return result;\n } catch (err) {\n setSpanError(span, err, options);\n throw err;\n }\n },\n async (reason) => {\n try {\n if (reason !== \"next\") {\n await runInSpanContext(span, () => iterator.return?.());\n }\n } catch (err) {\n setSpanError(span, err, options);\n throw err;\n } finally {\n span?.end();\n }\n }\n );\n}\n\nclass EventPublisher {\n #listenersMap = /* @__PURE__ */ new Map();\n #maxBufferedEvents;\n constructor(options = {}) {\n this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;\n }\n get size() {\n return this.#listenersMap.size;\n }\n /**\n * Emits an event and delivers the payload to all subscribed listeners.\n */\n publish(event, payload) {\n const listeners = this.#listenersMap.get(event);\n if (!listeners) {\n return;\n }\n for (const listener of listeners) {\n listener(payload);\n }\n }\n subscribe(event, listenerOrOptions) {\n if (typeof listenerOrOptions === \"function\") {\n let listeners = this.#listenersMap.get(event);\n if (!listeners) {\n this.#listenersMap.set(event, listeners = []);\n }\n listeners.push(listenerOrOptions);\n return once(() => {\n listeners.splice(listeners.indexOf(listenerOrOptions), 1);\n if (listeners.length === 0) {\n this.#listenersMap.delete(event);\n }\n });\n }\n const signal = listenerOrOptions?.signal;\n const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;\n signal?.throwIfAborted();\n const bufferedEvents = [];\n const pullResolvers = [];\n const unsubscribe = this.subscribe(event, (payload) => {\n const resolver = pullResolvers.shift();\n if (resolver) {\n resolver[0]({ done: false, value: payload });\n } else {\n bufferedEvents.push(payload);\n if (bufferedEvents.length > maxBufferedEvents) {\n bufferedEvents.shift();\n }\n }\n });\n const abortListener = (event2) => {\n unsubscribe();\n pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));\n pullResolvers.length = 0;\n bufferedEvents.length = 0;\n };\n signal?.addEventListener(\"abort\", abortListener, { once: true });\n return new AsyncIteratorClass(async () => {\n if (signal?.aborted) {\n throw signal.reason;\n }\n if (bufferedEvents.length > 0) {\n return { done: false, value: bufferedEvents.shift() };\n }\n return new Promise((resolve, reject) => {\n pullResolvers.push([resolve, reject]);\n });\n }, async () => {\n unsubscribe();\n signal?.removeEventListener(\"abort\", abortListener);\n pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));\n pullResolvers.length = 0;\n bufferedEvents.length = 0;\n });\n }\n}\n\nclass SequentialIdGenerator {\n index = BigInt(1);\n generate() {\n const id = this.index.toString(36);\n this.index++;\n return id;\n }\n}\nfunction compareSequentialIds(a, b) {\n if (a.length !== b.length) {\n return a.length - b.length;\n }\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction onStart(callback) {\n return async (options, ...rest) => {\n await callback(options, ...rest);\n return await options.next();\n };\n}\nfunction onSuccess(callback) {\n return async (options, ...rest) => {\n const result = await options.next();\n await callback(result, options, ...rest);\n return result;\n };\n}\nfunction onError(callback) {\n return async (options, ...rest) => {\n try {\n return await options.next();\n } catch (error) {\n await callback(error, options, ...rest);\n throw error;\n }\n };\n}\nfunction onFinish(callback) {\n let state;\n return async (options, ...rest) => {\n try {\n const result = await options.next();\n state = [null, result, true];\n return result;\n } catch (error) {\n state = [error, void 0, false];\n throw error;\n } finally {\n await callback(state, options, ...rest);\n }\n };\n}\nfunction intercept(interceptors, options, main) {\n const next = (options2, index) => {\n const interceptor = interceptors[index];\n if (!interceptor) {\n return main(options2);\n }\n return interceptor({\n ...options2,\n next: (newOptions = options2) => next(newOptions, index + 1)\n });\n };\n return next(options, 0);\n}\n\nfunction parseEmptyableJSON(text) {\n if (!text) {\n return void 0;\n }\n return JSON.parse(text);\n}\nfunction stringifyJSON(value) {\n return JSON.stringify(value);\n}\n\nfunction logError(error) {\n if (typeof console === \"object\" && typeof console.error === \"function\") {\n console.error(error);\n }\n}\n\nfunction findDeepMatches(check, payload, segments = [], maps = [], values = []) {\n if (check(payload)) {\n maps.push(segments);\n values.push(payload);\n } else if (Array.isArray(payload)) {\n payload.forEach((v, i) => {\n findDeepMatches(check, v, [...segments, i], maps, values);\n });\n } else if (isObject(payload)) {\n for (const key in payload) {\n findDeepMatches(check, payload[key], [...segments, key], maps, values);\n }\n }\n return { maps, values };\n}\nfunction getConstructor(value) {\n if (!isTypescriptObject(value)) {\n return null;\n }\n return Object.getPrototypeOf(value)?.constructor;\n}\nfunction isObject(value) {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || !proto || !proto.constructor;\n}\nfunction isTypescriptObject(value) {\n return !!value && (typeof value === \"object\" || typeof value === \"function\");\n}\nfunction clone(value) {\n if (Array.isArray(value)) {\n return value.map(clone);\n }\n if (isObject(value)) {\n const result = {};\n for (const key in value) {\n result[key] = clone(value[key]);\n }\n for (const sym of Object.getOwnPropertySymbols(value)) {\n result[sym] = clone(value[sym]);\n }\n return result;\n }\n return value;\n}\nfunction get(object, path) {\n let current = object;\n for (const key of path) {\n if (!isTypescriptObject(current)) {\n return void 0;\n }\n current = current[key];\n }\n return current;\n}\nfunction isPropertyKey(value) {\n const type = typeof value;\n return type === \"string\" || type === \"number\" || type === \"symbol\";\n}\nconst NullProtoObj = /* @__PURE__ */ (() => {\n const e = function() {\n };\n e.prototype = /* @__PURE__ */ Object.create(null);\n Object.freeze(e.prototype);\n return e;\n})();\n\nfunction value(value2, ...args) {\n if (typeof value2 === \"function\") {\n return value2(...args);\n }\n return value2;\n}\nfunction fallback(value2, fallback2) {\n return value2 === void 0 ? fallback2 : value2;\n}\n\nfunction preventNativeAwait(target) {\n return new Proxy(target, {\n get(target2, prop, receiver) {\n const value2 = Reflect.get(target2, prop, receiver);\n if (prop !== \"then\" || typeof value2 !== \"function\") {\n return value2;\n }\n return new Proxy(value2, {\n apply(targetFn, thisArg, args) {\n if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) {\n return Reflect.apply(targetFn, thisArg, args);\n }\n let shouldOmit = true;\n args[0].call(thisArg, preventNativeAwait(new Proxy(target2, {\n get: (target3, prop2, receiver2) => {\n if (shouldOmit && prop2 === \"then\") {\n shouldOmit = false;\n return void 0;\n }\n return Reflect.get(target3, prop2, receiver2);\n }\n })));\n }\n });\n }\n });\n}\nconst NATIVE_FUNCTION_REGEX = /^\\s*function\\s*\\(\\)\\s*\\{\\s*\\[native code\\]\\s*\\}\\s*$/;\nfunction isNativeFunction(fn) {\n return typeof fn === \"function\" && NATIVE_FUNCTION_REGEX.test(fn.toString());\n}\nfunction overlayProxy(target, partial) {\n const proxy = new Proxy(typeof target === \"function\" ? partial : target, {\n get(_, prop) {\n const targetValue = prop in partial ? partial : value(target);\n const v = Reflect.get(targetValue, prop);\n return typeof v === \"function\" ? v.bind(targetValue) : v;\n },\n has(_, prop) {\n return Reflect.has(partial, prop) || Reflect.has(value(target), prop);\n }\n });\n return proxy;\n}\n\nfunction streamToAsyncIteratorClass(stream) {\n const reader = stream.getReader();\n return new AsyncIteratorClass(\n async () => {\n return reader.read();\n },\n async () => {\n await reader.cancel();\n }\n );\n}\nfunction asyncIteratorToStream(iterator) {\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await iterator.next();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n },\n async cancel() {\n await iterator.return?.();\n }\n });\n}\nfunction asyncIteratorToUnproxiedDataStream(iterator) {\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await iterator.next();\n if (done) {\n controller.close();\n } else {\n const unproxied = isObject(value) ? { ...value } : Array.isArray(value) ? value.map((i) => i) : value;\n controller.enqueue(unproxied);\n }\n },\n async cancel() {\n await iterator.return?.();\n }\n });\n}\n\nfunction tryDecodeURIComponent(value) {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nexport { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, asyncIteratorWithSpan, clone, compareSequentialIds, defer, fallback, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, logError, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };\n","import { resolveMaybeOptionalOptions, getConstructor, isObject } from '@orpc/shared';\n\nconst ORPC_CLIENT_PACKAGE_NAME = \"@orpc/client\";\nconst ORPC_CLIENT_PACKAGE_VERSION = \"1.15.0\";\nconst RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([\n /**\n * Commonly used by libraries to bind functions to a specific `this`\n * context.\n */\n \"bind\",\n /**\n * Commonly accessed during primitive conversion, inspection, and logging.\n */\n \"valueOf\",\n /**\n * Commonly accessed during string conversion, inspection, and logging.\n */\n \"toString\",\n /**\n * Commonly accessed by serializers such as `JSON.stringify`.\n */\n \"toJSON\"\n]);\n\nconst COMMON_ORPC_ERROR_DEFS = {\n BAD_REQUEST: {\n status: 400,\n message: \"Bad Request\"\n },\n UNAUTHORIZED: {\n status: 401,\n message: \"Unauthorized\"\n },\n FORBIDDEN: {\n status: 403,\n message: \"Forbidden\"\n },\n NOT_FOUND: {\n status: 404,\n message: \"Not Found\"\n },\n METHOD_NOT_SUPPORTED: {\n status: 405,\n message: \"Method Not Supported\"\n },\n NOT_ACCEPTABLE: {\n status: 406,\n message: \"Not Acceptable\"\n },\n TIMEOUT: {\n status: 408,\n message: \"Request Timeout\"\n },\n CONFLICT: {\n status: 409,\n message: \"Conflict\"\n },\n PRECONDITION_FAILED: {\n status: 412,\n message: \"Precondition Failed\"\n },\n PAYLOAD_TOO_LARGE: {\n status: 413,\n message: \"Payload Too Large\"\n },\n UNSUPPORTED_MEDIA_TYPE: {\n status: 415,\n message: \"Unsupported Media Type\"\n },\n UNPROCESSABLE_CONTENT: {\n status: 422,\n message: \"Unprocessable Content\"\n },\n TOO_MANY_REQUESTS: {\n status: 429,\n message: \"Too Many Requests\"\n },\n CLIENT_CLOSED_REQUEST: {\n status: 499,\n message: \"Client Closed Request\"\n },\n INTERNAL_SERVER_ERROR: {\n status: 500,\n message: \"Internal Server Error\"\n },\n NOT_IMPLEMENTED: {\n status: 501,\n message: \"Not Implemented\"\n },\n BAD_GATEWAY: {\n status: 502,\n message: \"Bad Gateway\"\n },\n SERVICE_UNAVAILABLE: {\n status: 503,\n message: \"Service Unavailable\"\n },\n GATEWAY_TIMEOUT: {\n status: 504,\n message: \"Gateway Timeout\"\n }\n};\nfunction fallbackORPCErrorStatus(code, status) {\n return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;\n}\nfunction fallbackORPCErrorMessage(code, message) {\n return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;\n}\nlet globalORPCErrorConstructors;\nclass ORPCError extends Error {\n defined;\n code;\n status;\n data;\n static {\n const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(`__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`);\n void (globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet());\n globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];\n globalORPCErrorConstructors.add(ORPCError);\n }\n constructor(code, ...rest) {\n const options = resolveMaybeOptionalOptions(rest);\n if (options.status !== void 0 && !isORPCErrorStatus(options.status)) {\n throw new Error(\"[ORPCError] Invalid error status code.\");\n }\n const message = fallbackORPCErrorMessage(code, options.message);\n super(message, options);\n this.code = code;\n this.status = fallbackORPCErrorStatus(code, options.status);\n this.defined = options.defined ?? false;\n this.data = options.data;\n }\n toJSON() {\n return {\n defined: this.defined,\n code: this.code,\n status: this.status,\n message: this.message,\n data: this.data\n };\n }\n /**\n * Workaround for Next.js where different contexts use separate\n * dependency graphs, causing multiple ORPCError constructors existing and breaking\n * `instanceof` checks across contexts.\n *\n * This is particularly problematic with \"Optimized SSR\", where orpc-client\n * executes in one context but is invoked from another. When an error is thrown\n * in the execution context, `instanceof ORPCError` checks fail in the\n * invocation context due to separate class constructors.\n *\n * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.\n */\n static [Symbol.hasInstance](instance) {\n if (globalORPCErrorConstructors.has(this)) {\n const constructor = getConstructor(instance);\n if (constructor && globalORPCErrorConstructors.has(constructor)) {\n return true;\n }\n }\n return super[Symbol.hasInstance](instance);\n }\n}\nfunction isDefinedError(error) {\n return error instanceof ORPCError && error.defined;\n}\nfunction toORPCError(error) {\n return error instanceof ORPCError ? error : new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Internal server error\",\n cause: error\n });\n}\nfunction isORPCErrorStatus(status) {\n return status < 200 || status >= 400;\n}\nfunction isORPCErrorJson(json) {\n if (!isObject(json)) {\n return false;\n }\n const validKeys = [\"defined\", \"code\", \"status\", \"message\", \"data\"];\n if (Object.keys(json).some((k) => !validKeys.includes(k))) {\n return false;\n }\n return \"defined\" in json && typeof json.defined === \"boolean\" && \"code\" in json && typeof json.code === \"string\" && \"status\" in json && typeof json.status === \"number\" && isORPCErrorStatus(json.status) && \"message\" in json && typeof json.message === \"string\";\n}\nfunction createORPCErrorFromJson(json, options = {}) {\n return new ORPCError(json.code, {\n ...options,\n ...json\n });\n}\n\nexport { COMMON_ORPC_ERROR_DEFS as C, ORPC_CLIENT_PACKAGE_NAME as O, RECURSIVE_CLIENT_UNWRAP_KEYS as R, ORPC_CLIENT_PACKAGE_VERSION as a, fallbackORPCErrorMessage as b, ORPCError as c, isORPCErrorStatus as d, isORPCErrorJson as e, fallbackORPCErrorStatus as f, createORPCErrorFromJson as g, isDefinedError as i, toORPCError as t };\n","import { isTypescriptObject, AsyncIteratorClass, tryDecodeURIComponent, toArray, once, isAsyncIteratorObject, replicateAsyncIterator } from '@orpc/shared';\n\nclass EventEncoderError extends TypeError {\n}\nclass EventDecoderError extends TypeError {\n}\nclass ErrorEvent extends Error {\n data;\n constructor(options) {\n super(options?.message ?? \"An error event was received\", options);\n this.data = options?.data;\n }\n}\n\nconst LINE_ENDING_REGEX$1 = /\\r\\n|\\r(?!\\n)|\\n/;\nconst MESSAGE_DELIMITER_REGEX = /(?:\\r\\n|\\r(?!\\n)|\\n){2}/;\nconst MESSAGE_DELIMITER_GLOBAL_REGEX = /(?:\\r\\n|\\r(?!\\n)|\\n){2}/g;\nconst CR = 13;\nconst LF = 10;\nconst SPACE = 32;\nfunction decodeEventMessage(encoded) {\n const message = {\n data: void 0,\n event: void 0,\n id: void 0,\n retry: void 0,\n comments: []\n };\n for (const line of encoded.split(LINE_ENDING_REGEX$1)) {\n if (line === \"\") {\n continue;\n }\n const index = line.indexOf(\":\");\n const value = index === -1 ? \"\" : line.slice(line.charCodeAt(index + 1) === SPACE ? index + 2 : index + 1);\n if (index === 0) {\n message.comments.push(value);\n continue;\n }\n switch (index === -1 ? line : line.slice(0, index)) {\n case \"data\":\n message.data = message.data === void 0 ? value : `${message.data}\n${value}`;\n break;\n case \"event\":\n message.event = value;\n break;\n case \"id\":\n message.id = value;\n break;\n case \"retry\": {\n const maybeInteger = Number.parseInt(value, 10);\n if (maybeInteger >= 0 && maybeInteger.toString() === value) {\n message.retry = maybeInteger;\n }\n break;\n }\n }\n }\n return message;\n}\nclass EventDecoder {\n constructor(options = {}) {\n this.options = options;\n }\n pending = [];\n // Last up-to-3 characters of the pending buffer, prefixed to the next chunk\n // so a delimiter straddling the boundary is still found.\n tail = \"\";\n // Set when a chunk-ending '\\r' was already consumed as a line ending, so a\n // leading '\\n' in the next chunk is the second half of that CRLF pair.\n discardLeadingLF = false;\n feed(chunk) {\n if (chunk === \"\") {\n return;\n }\n if (this.discardLeadingLF) {\n this.discardLeadingLF = false;\n if (chunk.charCodeAt(0) === LF) {\n chunk = chunk.slice(1);\n if (chunk === \"\") {\n return;\n }\n }\n }\n const scan = this.tail + chunk;\n if (!MESSAGE_DELIMITER_REGEX.test(scan)) {\n this.pending.push(chunk);\n this.tail = scan.slice(-3);\n return;\n }\n this.pending.push(chunk);\n const buffered = this.pending.length === 1 ? chunk : this.pending.join(\"\");\n const offset = buffered.length - scan.length;\n const parts = [];\n let start = 0;\n for (const match of scan.matchAll(MESSAGE_DELIMITER_GLOBAL_REGEX)) {\n parts.push(buffered.slice(start, offset + match.index));\n start = offset + match.index + match[0].length;\n }\n const incomplete = buffered.slice(start);\n this.pending.length = 0;\n this.tail = incomplete.slice(-3);\n if (incomplete === \"\") {\n this.discardLeadingLF = chunk.charCodeAt(chunk.length - 1) === CR;\n } else {\n this.pending.push(incomplete);\n }\n for (const encoded of parts) {\n const message = decodeEventMessage(encoded);\n if (this.options.onEvent) {\n this.options.onEvent(message);\n }\n }\n }\n end() {\n if (this.pending.length !== 0) {\n throw new EventDecoderError(\"Event Iterator ended before complete\");\n }\n }\n}\nclass EventDecoderStream extends TransformStream {\n constructor() {\n let decoder;\n super({\n start(controller) {\n decoder = new EventDecoder({\n onEvent: (event) => {\n controller.enqueue(event);\n }\n });\n },\n transform(chunk) {\n decoder.feed(chunk);\n },\n flush() {\n decoder.end();\n }\n });\n }\n}\n\nconst LINE_ENDING_REGEX = /\\r\\n|[\\n\\r]/;\nconst LINE_ENDING_GLOBAL_REGEX = /\\r\\n|[\\n\\r]/g;\nfunction containsLineBreak(value) {\n return LINE_ENDING_REGEX.test(value);\n}\nfunction assertEventId(id) {\n if (containsLineBreak(id)) {\n throw new EventEncoderError(\"Event's id must not contain a carriage return or newline character\");\n }\n}\nfunction assertEventName(event) {\n if (containsLineBreak(event)) {\n throw new EventEncoderError(\"Event's event must not contain a carriage return or newline character\");\n }\n}\nfunction assertEventRetry(retry) {\n if (!Number.isInteger(retry) || retry < 0) {\n throw new EventEncoderError(\"Event's retry must be a integer and >= 0\");\n }\n}\nfunction assertEventComment(comment) {\n if (containsLineBreak(comment)) {\n throw new EventEncoderError(\"Event's comment must not contain a carriage return or newline character\");\n }\n}\nfunction encodeEventData(data) {\n if (data === void 0) {\n return \"\";\n }\n return `data: ${data.replace(LINE_ENDING_GLOBAL_REGEX, \"\\ndata: \")}\n`;\n}\nfunction encodeEventComments(comments) {\n let output = \"\";\n for (const comment of comments ?? []) {\n assertEventComment(comment);\n output += `: ${comment}\n`;\n }\n return output;\n}\nfunction encodeEventMessage(message) {\n let output = \"\";\n output += encodeEventComments(message.comments);\n if (message.event !== void 0) {\n assertEventName(message.event);\n output += `event: ${message.event}\n`;\n }\n if (message.retry !== void 0) {\n assertEventRetry(message.retry);\n output += `retry: ${message.retry}\n`;\n }\n if (message.id !== void 0) {\n assertEventId(message.id);\n output += `id: ${message.id}\n`;\n }\n output += encodeEventData(message.data);\n output += \"\\n\";\n return output;\n}\n\nconst EVENT_SOURCE_META_SYMBOL = Symbol(\"ORPC_EVENT_SOURCE_META\");\nfunction withEventMeta(container, meta) {\n if (meta.id === void 0 && meta.retry === void 0 && !meta.comments?.length) {\n return container;\n }\n if (meta.id !== void 0) {\n assertEventId(meta.id);\n }\n if (meta.retry !== void 0) {\n assertEventRetry(meta.retry);\n }\n if (meta.comments !== void 0) {\n for (const comment of meta.comments) {\n assertEventComment(comment);\n }\n }\n return new Proxy(container, {\n get(target, prop, receiver) {\n if (prop === EVENT_SOURCE_META_SYMBOL) {\n return meta;\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n}\nfunction getEventMeta(container) {\n return isTypescriptObject(container) ? Reflect.get(container, EVENT_SOURCE_META_SYMBOL) : void 0;\n}\n\nclass HibernationEventIterator extends AsyncIteratorClass {\n /**\n * this property is not transferred to the client, so it should be optional for type safety\n */\n hibernationCallback;\n constructor(hibernationCallback) {\n super(async () => {\n throw new Error(\"Cannot iterate over hibernating iterator directly\");\n }, async (reason) => {\n if (reason !== \"next\") {\n throw new Error(\"Cannot cleanup hibernating iterator directly\");\n }\n });\n this.hibernationCallback = hibernationCallback;\n }\n}\n\nfunction generateContentDisposition(filename, disposition = \"inline\") {\n const encodedFileName = filename.replace(/[^\\x20-\\x7E]/g, \"_\").replace(/\"/g, '\\\\\"');\n const encodedFilenameStar = encodeURIComponent(filename).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(Number.parseInt(hex, 16)));\n return `${disposition}; filename=\"${encodedFileName}\"; filename*=utf-8''${encodedFilenameStar}`;\n}\nfunction getFilenameFromContentDisposition(contentDisposition) {\n const encodedFilenameStarMatch = contentDisposition.match(/filename\\*=(UTF-8'')?([^;]*)/i);\n if (encodedFilenameStarMatch && typeof encodedFilenameStarMatch[2] === \"string\") {\n return tryDecodeURIComponent(encodedFilenameStarMatch[2]);\n }\n const encodedFilenameMatch = contentDisposition.match(/filename=\"((?:\\\\\"|[^\"])*)\"/i);\n if (encodedFilenameMatch && typeof encodedFilenameMatch[1] === \"string\") {\n return encodedFilenameMatch[1].replace(/\\\\\"/g, '\"');\n }\n}\nfunction mergeStandardHeaders(a, b) {\n const merged = { ...a };\n for (const key in b) {\n if (Array.isArray(b[key])) {\n merged[key] = [...toArray(merged[key]), ...b[key]];\n } else if (b[key] !== void 0) {\n if (Array.isArray(merged[key])) {\n merged[key] = [...merged[key], b[key]];\n } else if (merged[key] !== void 0) {\n merged[key] = [merged[key], b[key]];\n } else {\n merged[key] = b[key];\n }\n }\n }\n return merged;\n}\nfunction flattenHeader(header) {\n if (typeof header === \"string\" || header === void 0) {\n return header;\n }\n if (header.length === 0) {\n return void 0;\n }\n return header.join(\", \");\n}\nfunction replicateStandardLazyResponse(response, count) {\n const replicated = [];\n let bodyPromise;\n let replicatedAsyncIteratorObjects;\n for (let i = 0; i < count; i++) {\n replicated.push({\n ...response,\n body: once(async () => {\n const body = await (bodyPromise ??= response.body());\n if (!isAsyncIteratorObject(body)) {\n return body;\n }\n replicatedAsyncIteratorObjects ??= replicateAsyncIterator(body, count);\n return replicatedAsyncIteratorObjects.shift();\n })\n });\n }\n return replicated;\n}\nfunction isEventIteratorHeaders(headers) {\n return Boolean(flattenHeader(headers[\"content-type\"])?.startsWith(\"text/event-stream\") && flattenHeader(headers[\"content-disposition\"]) === void 0);\n}\n\nexport { ErrorEvent, EventDecoder, EventDecoderError, EventDecoderStream, EventEncoderError, HibernationEventIterator, assertEventComment, assertEventId, assertEventName, assertEventRetry, decodeEventMessage, encodeEventComments, encodeEventData, encodeEventMessage, flattenHeader, generateContentDisposition, getEventMeta, getFilenameFromContentDisposition, isEventIteratorHeaders, mergeStandardHeaders, replicateStandardLazyResponse, withEventMeta };\n","import { AsyncIteratorClass, isTypescriptObject } from '@orpc/shared';\nimport { getEventMeta, withEventMeta } from '@orpc/standard-server';\n\nfunction mapEventIterator(iterator, maps) {\n const mapError = async (error) => {\n let mappedError = await maps.error(error);\n if (mappedError !== error) {\n const meta = getEventMeta(error);\n if (meta && isTypescriptObject(mappedError)) {\n mappedError = withEventMeta(mappedError, meta);\n }\n }\n return mappedError;\n };\n return new AsyncIteratorClass(async () => {\n const { done, value } = await (async () => {\n try {\n return await iterator.next();\n } catch (error) {\n throw await mapError(error);\n }\n })();\n let mappedValue = await maps.value(value, done);\n if (mappedValue !== value) {\n const meta = getEventMeta(value);\n if (meta && isTypescriptObject(mappedValue)) {\n mappedValue = withEventMeta(mappedValue, meta);\n }\n }\n return { done, value: mappedValue };\n }, async () => {\n try {\n await iterator.return?.();\n } catch (error) {\n throw await mapError(error);\n }\n });\n}\n\nexport { mapEventIterator as m };\n","import { preventNativeAwait, isTypescriptObject } from '@orpc/shared';\nexport { AsyncIteratorClass, EventPublisher, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@orpc/shared';\nimport { i as isDefinedError, R as RECURSIVE_CLIENT_UNWRAP_KEYS } from './shared/client.CZlviB0y.mjs';\nexport { C as COMMON_ORPC_ERROR_DEFS, c as ORPCError, O as ORPC_CLIENT_PACKAGE_NAME, a as ORPC_CLIENT_PACKAGE_VERSION, g as createORPCErrorFromJson, b as fallbackORPCErrorMessage, f as fallbackORPCErrorStatus, e as isORPCErrorJson, d as isORPCErrorStatus, t as toORPCError } from './shared/client.CZlviB0y.mjs';\nexport { m as mapEventIterator } from './shared/client.BLtwTQUg.mjs';\nexport { ErrorEvent, getEventMeta, withEventMeta } from '@orpc/standard-server';\n\nasync function safe(promise) {\n try {\n const output = await promise;\n return Object.assign(\n [null, output, false, true],\n { error: null, data: output, isDefined: false, isSuccess: true }\n );\n } catch (e) {\n const error = e;\n if (isDefinedError(error)) {\n return Object.assign(\n [error, void 0, true, false],\n { error, data: void 0, isDefined: true, isSuccess: false }\n );\n }\n return Object.assign(\n [error, void 0, false, false],\n { error, data: void 0, isDefined: false, isSuccess: false }\n );\n }\n}\nfunction resolveFriendlyClientOptions(options) {\n return {\n ...options,\n context: options.context ?? {}\n // Context only optional if all fields are optional\n };\n}\nfunction consumeEventIterator(iterator, options) {\n void (async () => {\n let onFinishState;\n try {\n const resolvedIterator = await iterator;\n while (true) {\n const { done, value } = await resolvedIterator.next();\n if (done) {\n const realValue = value;\n onFinishState = [null, realValue, true];\n options.onSuccess?.(realValue);\n break;\n }\n options.onEvent(value);\n }\n } catch (error) {\n onFinishState = [error, void 0, false];\n if (!options.onError && !options.onFinish) {\n throw error;\n }\n options.onError?.(error);\n } finally {\n options.onFinish?.(onFinishState);\n }\n })();\n return async () => {\n await (await iterator)?.return?.();\n };\n}\n\nfunction createORPCClient(link, options = {}) {\n const path = options.path ?? [];\n const procedureClient = async (...[input, options2 = {}]) => {\n return await link.call(path, input, resolveFriendlyClientOptions(options2));\n };\n const recursive = new Proxy(procedureClient, {\n get(target, key) {\n if (typeof key !== \"string\" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(key)) {\n return Reflect.get(target, key);\n }\n return createORPCClient(link, {\n ...options,\n path: [...path, key]\n });\n }\n });\n return preventNativeAwait(recursive);\n}\n\nfunction createSafeClient(client) {\n const proxy = new Proxy((...args) => safe(client(...args)), {\n get(target, prop, receiver) {\n if (typeof prop !== \"string\" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {\n return Reflect.get(target, prop);\n }\n const value = Reflect.get(client, prop, receiver);\n if (!isTypescriptObject(value)) {\n return value;\n }\n return createSafeClient(value);\n }\n });\n return proxy;\n}\n\nclass DynamicLink {\n constructor(linkResolver) {\n this.linkResolver = linkResolver;\n }\n async call(path, input, options) {\n const resolvedLink = await this.linkResolver(options, path, input);\n const output = await resolvedLink.call(path, input, options);\n return output;\n }\n}\n\nexport { DynamicLink, RECURSIVE_CLIENT_UNWRAP_KEYS, consumeEventIterator, createORPCClient, createSafeClient, isDefinedError, resolveFriendlyClientOptions, safe };\n","import { AsyncIteratorClass, startSpan, runInSpanContext, AbortError, parseEmptyableJSON, isTypescriptObject, setSpanError, stringifyJSON, runWithSpan, isAsyncIteratorObject, once } from '@orpc/shared';\nimport { EventDecoderStream, withEventMeta, ErrorEvent, encodeEventMessage, getEventMeta, getFilenameFromContentDisposition, generateContentDisposition } from '@orpc/standard-server';\n\nfunction toEventIterator(stream, options = {}) {\n const eventStream = stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());\n const reader = eventStream?.getReader();\n let span;\n let isCancelled = false;\n return new AsyncIteratorClass(async () => {\n span ??= startSpan(\"consume_event_iterator_stream\");\n try {\n while (true) {\n if (reader === void 0) {\n return { done: true, value: void 0 };\n }\n const { done, value } = await runInSpanContext(span, () => reader.read());\n if (done) {\n if (isCancelled) {\n throw new AbortError(\"Stream was cancelled\");\n }\n return { done: true, value: void 0 };\n }\n switch (value.event) {\n case \"message\": {\n let message = parseEmptyableJSON(value.data);\n if (isTypescriptObject(message)) {\n message = withEventMeta(message, value);\n }\n span?.addEvent(\"message\");\n return { done: false, value: message };\n }\n case \"error\": {\n let error = new ErrorEvent({\n data: parseEmptyableJSON(value.data)\n });\n error = withEventMeta(error, value);\n span?.addEvent(\"error\");\n throw error;\n }\n case \"done\": {\n let done2 = parseEmptyableJSON(value.data);\n if (isTypescriptObject(done2)) {\n done2 = withEventMeta(done2, value);\n }\n span?.addEvent(\"done\");\n return { done: true, value: done2 };\n }\n default: {\n span?.addEvent(\"maybe_keepalive\");\n }\n }\n }\n } catch (e) {\n if (!(e instanceof ErrorEvent)) {\n setSpanError(span, e, options);\n }\n throw e;\n }\n }, async (reason) => {\n try {\n if (reason !== \"next\") {\n isCancelled = true;\n span?.addEvent(\"cancelled\");\n }\n await runInSpanContext(span, () => reader?.cancel());\n } catch (e) {\n setSpanError(span, e, options);\n throw e;\n } finally {\n span?.end();\n }\n });\n}\nfunction toEventStream(iterator, options = {}) {\n const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;\n const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;\n const keepAliveComment = options.eventIteratorKeepAliveComment ?? \"\";\n const initialCommentEnabled = options.eventIteratorInitialCommentEnabled ?? true;\n const initialComment = options.eventIteratorInitialComment ?? \"\";\n let cancelled = false;\n let timeout;\n let span;\n const stream = new ReadableStream({\n start(controller) {\n span = startSpan(\"stream_event_iterator\");\n if (initialCommentEnabled) {\n controller.enqueue(encodeEventMessage({\n comments: [initialComment]\n }));\n }\n },\n async pull(controller) {\n try {\n if (keepAliveEnabled) {\n timeout = setInterval(() => {\n controller.enqueue(encodeEventMessage({\n comments: [keepAliveComment]\n }));\n span?.addEvent(\"keepalive\");\n }, keepAliveInterval);\n }\n const value = await runInSpanContext(span, () => iterator.next());\n clearInterval(timeout);\n if (cancelled) {\n return;\n }\n const meta = getEventMeta(value.value);\n if (!value.done || value.value !== void 0 || meta !== void 0) {\n const event = value.done ? \"done\" : \"message\";\n controller.enqueue(encodeEventMessage({\n ...meta,\n event,\n data: stringifyJSON(value.value)\n }));\n span?.addEvent(event);\n }\n if (value.done) {\n controller.close();\n span?.end();\n }\n } catch (err) {\n clearInterval(timeout);\n if (cancelled) {\n return;\n }\n if (err instanceof ErrorEvent) {\n controller.enqueue(encodeEventMessage({\n ...getEventMeta(err),\n event: \"error\",\n data: stringifyJSON(err.data)\n }));\n span?.addEvent(\"error\");\n controller.close();\n } else {\n setSpanError(span, err);\n controller.error(err);\n }\n span?.end();\n }\n },\n async cancel() {\n try {\n cancelled = true;\n clearInterval(timeout);\n span?.addEvent(\"cancelled\");\n await runInSpanContext(span, () => iterator.return?.());\n } catch (e) {\n setSpanError(span, e);\n throw e;\n } finally {\n span?.end();\n }\n }\n }).pipeThrough(new TextEncoderStream());\n return stream;\n}\n\nfunction toStandardBody(re, options = {}) {\n return runWithSpan(\n { name: \"parse_standard_body\", signal: options.signal },\n async () => {\n const contentDisposition = re.headers.get(\"content-disposition\");\n if (typeof contentDisposition === \"string\") {\n const fileName = getFilenameFromContentDisposition(contentDisposition) ?? \"blob\";\n const blob2 = await re.blob();\n return new File([blob2], fileName, {\n type: blob2.type\n });\n }\n const contentType = re.headers.get(\"content-type\");\n if (!contentType || contentType.startsWith(\"application/json\")) {\n const text = await re.text();\n return parseEmptyableJSON(text);\n }\n if (contentType.startsWith(\"multipart/form-data\")) {\n return await re.formData();\n }\n if (contentType.startsWith(\"application/x-www-form-urlencoded\")) {\n const text = await re.text();\n return new URLSearchParams(text);\n }\n if (contentType.startsWith(\"text/event-stream\")) {\n return toEventIterator(re.body, options);\n }\n if (contentType.startsWith(\"text/plain\")) {\n return await re.text();\n }\n const blob = await re.blob();\n return new File([blob], \"blob\", {\n type: blob.type\n });\n }\n );\n}\nfunction toFetchBody(body, headers, options = {}) {\n if (body instanceof ReadableStream) {\n return body;\n }\n const currentContentDisposition = headers.get(\"content-disposition\");\n headers.delete(\"content-type\");\n headers.delete(\"content-disposition\");\n if (body === void 0) {\n return void 0;\n }\n if (body instanceof Blob) {\n headers.set(\"content-type\", body.type);\n headers.set(\"content-length\", body.size.toString());\n headers.set(\n \"content-disposition\",\n currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : \"blob\")\n );\n return body;\n }\n if (body instanceof FormData) {\n return body;\n }\n if (body instanceof URLSearchParams) {\n return body;\n }\n if (isAsyncIteratorObject(body)) {\n headers.set(\"content-type\", \"text/event-stream\");\n return toEventStream(body, options);\n }\n headers.set(\"content-type\", \"application/json\");\n return stringifyJSON(body);\n}\n\nfunction toStandardHeaders(headers, standardHeaders = {}) {\n headers.forEach((value, key) => {\n if (Array.isArray(standardHeaders[key])) {\n standardHeaders[key].push(value);\n } else if (standardHeaders[key] !== void 0) {\n standardHeaders[key] = [standardHeaders[key], value];\n } else {\n standardHeaders[key] = value;\n }\n });\n return standardHeaders;\n}\nfunction toFetchHeaders(headers, fetchHeaders = new Headers()) {\n for (const [key, value] of Object.entries(headers)) {\n if (Array.isArray(value)) {\n for (const v of value) {\n fetchHeaders.append(key, v);\n }\n } else if (value !== void 0) {\n fetchHeaders.append(key, value);\n }\n }\n return fetchHeaders;\n}\n\nfunction toStandardLazyRequest(request) {\n return {\n url: new URL(request.url),\n signal: request.signal,\n method: request.method,\n body: once(() => toStandardBody(request, { signal: request.signal })),\n get headers() {\n const headers = toStandardHeaders(request.headers);\n Object.defineProperty(this, \"headers\", { value: headers, writable: true });\n return headers;\n },\n set headers(value) {\n Object.defineProperty(this, \"headers\", { value, writable: true });\n }\n };\n}\nfunction toFetchRequest(request, options = {}) {\n const headers = toFetchHeaders(request.headers);\n const body = toFetchBody(request.body, headers, options);\n return new Request(request.url, {\n signal: request.signal,\n method: request.method,\n headers,\n body\n });\n}\n\nfunction toFetchResponse(response, options = {}) {\n const headers = toFetchHeaders(response.headers);\n const body = toFetchBody(response.body, headers, options);\n return new Response(body, { headers, status: response.status });\n}\nfunction toStandardLazyResponse(response, options = {}) {\n return {\n body: once(() => toStandardBody(response, options)),\n status: response.status,\n get headers() {\n const headers = toStandardHeaders(response.headers);\n Object.defineProperty(this, \"headers\", { value: headers, writable: true });\n return headers;\n },\n set headers(value) {\n Object.defineProperty(this, \"headers\", { value, writable: true });\n }\n };\n}\n\nexport { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };\n","import { toArray, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, intercept, getGlobalOtelConfig, isObject, value, stringifyJSON } from '@orpc/shared';\nimport { mergeStandardHeaders, ErrorEvent } from '@orpc/standard-server';\nimport { C as COMMON_ORPC_ERROR_DEFS, d as isORPCErrorStatus, e as isORPCErrorJson, g as createORPCErrorFromJson, c as ORPCError, t as toORPCError } from './client.CZlviB0y.mjs';\nimport { toStandardHeaders as toStandardHeaders$1 } from '@orpc/standard-server-fetch';\nimport { m as mapEventIterator } from './client.BLtwTQUg.mjs';\n\nclass CompositeStandardLinkPlugin {\n plugins;\n constructor(plugins = []) {\n this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n }\n init(options) {\n for (const plugin of this.plugins) {\n plugin.init?.(options);\n }\n }\n}\n\nclass StandardLink {\n constructor(codec, sender, options = {}) {\n this.codec = codec;\n this.sender = sender;\n const plugin = new CompositeStandardLinkPlugin(options.plugins);\n plugin.init(options);\n this.interceptors = toArray(options.interceptors);\n this.clientInterceptors = toArray(options.clientInterceptors);\n }\n interceptors;\n clientInterceptors;\n call(path, input, options) {\n return runWithSpan(\n { name: `${ORPC_NAME}.${path.join(\"/\")}`, signal: options.signal },\n (span) => {\n span?.setAttribute(\"rpc.system\", ORPC_NAME);\n span?.setAttribute(\"rpc.method\", path.join(\".\"));\n if (isAsyncIteratorObject(input)) {\n input = asyncIteratorWithSpan(\n { name: \"consume_event_iterator_input\", signal: options.signal },\n input\n );\n }\n return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => {\n const otelConfig = getGlobalOtelConfig();\n let otelContext;\n const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;\n if (currentSpan && otelConfig) {\n otelContext = otelConfig?.trace.setSpan(otelConfig.context.active(), currentSpan);\n }\n const request = await runWithSpan(\n { name: \"encode_request\", context: otelContext },\n () => this.codec.encode(path2, input2, options2)\n );\n const response = await intercept(\n this.clientInterceptors,\n { ...options2, input: input2, path: path2, request },\n ({ input: input3, path: path3, request: request2, ...options3 }) => {\n return runWithSpan(\n { name: \"send_request\", signal: options3.signal, context: otelContext },\n () => this.sender.call(request2, options3, path3, input3)\n );\n }\n );\n const output = await runWithSpan(\n { name: \"decode_response\", context: otelContext },\n () => this.codec.decode(response, options2, path2, input2)\n );\n if (isAsyncIteratorObject(output)) {\n return asyncIteratorWithSpan(\n { name: \"consume_event_iterator_output\", signal: options2.signal },\n output\n );\n }\n return output;\n });\n }\n );\n }\n}\n\nconst STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {\n BIGINT: 0,\n DATE: 1,\n NAN: 2,\n UNDEFINED: 3,\n URL: 4,\n REGEXP: 5,\n SET: 6,\n MAP: 7\n};\nclass StandardRPCJsonSerializer {\n customSerializers;\n constructor(options = {}) {\n this.customSerializers = options.customJsonSerializers ?? [];\n if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {\n throw new Error(\"Custom serializer type must be unique.\");\n }\n }\n serialize(data, segments = [], meta = [], maps = [], blobs = []) {\n for (const custom of this.customSerializers) {\n if (custom.condition(data)) {\n const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);\n meta.push([custom.type, ...segments]);\n return result;\n }\n }\n if (data instanceof Blob) {\n maps.push(segments);\n blobs.push(data);\n return [data, meta, maps, blobs];\n }\n if (typeof data === \"bigint\") {\n meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);\n return [data.toString(), meta, maps, blobs];\n }\n if (data instanceof Date) {\n meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);\n if (Number.isNaN(data.getTime())) {\n return [null, meta, maps, blobs];\n }\n return [data.toISOString(), meta, maps, blobs];\n }\n if (Number.isNaN(data)) {\n meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);\n return [null, meta, maps, blobs];\n }\n if (data instanceof URL) {\n meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);\n return [data.toString(), meta, maps, blobs];\n }\n if (data instanceof RegExp) {\n meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);\n return [data.toString(), meta, maps, blobs];\n }\n if (data instanceof Set) {\n const result = this.serialize(Array.from(data), segments, meta, maps, blobs);\n meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);\n return result;\n }\n if (data instanceof Map) {\n const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);\n meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);\n return result;\n }\n if (Array.isArray(data)) {\n const json = data.map((v, i) => {\n if (v === void 0) {\n meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);\n return null;\n }\n return this.serialize(v, [...segments, i], meta, maps, blobs)[0];\n });\n return [json, meta, maps, blobs];\n }\n if (isObject(data)) {\n const json = {};\n for (const k in data) {\n if (k === \"toJSON\" && typeof data[k] === \"function\") {\n continue;\n }\n json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];\n }\n return [json, meta, maps, blobs];\n }\n return [data, meta, maps, blobs];\n }\n deserialize(json, meta, maps, getBlob) {\n const ref = { data: json };\n if (maps && getBlob) {\n maps.forEach((segments, i) => {\n let currentRef = ref;\n let preSegment = \"data\";\n segments.forEach((segment) => {\n currentRef = currentRef[preSegment];\n preSegment = segment;\n if (!Object.hasOwn(currentRef, preSegment)) {\n throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${preSegment}`);\n }\n });\n currentRef[preSegment] = getBlob(i);\n });\n }\n for (const item of meta) {\n const type = item[0];\n let currentRef = ref;\n let preSegment = \"data\";\n for (let i = 1; i < item.length; i++) {\n currentRef = currentRef[preSegment];\n preSegment = item[i];\n if (!Object.hasOwn(currentRef, preSegment)) {\n throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${preSegment}`);\n }\n }\n for (const custom of this.customSerializers) {\n if (custom.type === type) {\n currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);\n break;\n }\n }\n switch (type) {\n case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:\n currentRef[preSegment] = BigInt(currentRef[preSegment]);\n break;\n case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:\n currentRef[preSegment] = new Date(currentRef[preSegment] ?? \"Invalid Date\");\n break;\n case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:\n currentRef[preSegment] = Number.NaN;\n break;\n case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:\n currentRef[preSegment] = void 0;\n break;\n case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:\n currentRef[preSegment] = new URL(currentRef[preSegment]);\n break;\n case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {\n const [, pattern, flags] = currentRef[preSegment].match(/^\\/(.*)\\/([a-z]*)$/);\n currentRef[preSegment] = new RegExp(pattern, flags);\n break;\n }\n case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:\n currentRef[preSegment] = new Set(currentRef[preSegment]);\n break;\n case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:\n currentRef[preSegment] = new Map(currentRef[preSegment]);\n break;\n }\n }\n return ref.data;\n }\n}\n\nfunction toHttpPath(path) {\n return `/${path.map(encodeURIComponent).join(\"/\")}`;\n}\nfunction toStandardHeaders(headers) {\n if (typeof headers.forEach === \"function\") {\n return toStandardHeaders$1(headers);\n }\n return headers;\n}\nfunction getMalformedResponseErrorCode(status) {\n return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? \"MALFORMED_ORPC_ERROR_RESPONSE\";\n}\n\nclass StandardRPCLinkCodec {\n constructor(serializer, options) {\n this.serializer = serializer;\n this.baseUrl = options.url;\n this.maxUrlLength = options.maxUrlLength ?? 2083;\n this.fallbackMethod = options.fallbackMethod ?? \"POST\";\n this.expectedMethod = options.method ?? this.fallbackMethod;\n this.headers = options.headers ?? {};\n }\n baseUrl;\n maxUrlLength;\n fallbackMethod;\n expectedMethod;\n headers;\n async encode(path, input, options) {\n let headers = toStandardHeaders(await value(this.headers, options, path, input));\n if (options.lastEventId !== void 0) {\n headers = mergeStandardHeaders(headers, { \"last-event-id\": options.lastEventId });\n }\n const expectedMethod = await value(this.expectedMethod, options, path, input);\n const baseUrl = await value(this.baseUrl, options, path, input);\n const url = new URL(baseUrl);\n url.pathname = `${url.pathname.replace(/\\/$/, \"\")}${toHttpPath(path)}`;\n const serialized = this.serializer.serialize(input);\n if (expectedMethod === \"GET\" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {\n const maxUrlLength = await value(this.maxUrlLength, options, path, input);\n const getUrl = new URL(url);\n getUrl.searchParams.append(\"data\", stringifyJSON(serialized));\n if (getUrl.toString().length <= maxUrlLength) {\n return {\n body: void 0,\n method: expectedMethod,\n headers,\n url: getUrl,\n signal: options.signal\n };\n }\n }\n return {\n url,\n method: expectedMethod === \"GET\" ? this.fallbackMethod : expectedMethod,\n headers,\n body: serialized,\n signal: options.signal\n };\n }\n async decode(response) {\n const isOk = !isORPCErrorStatus(response.status);\n const deserialized = await (async () => {\n let isBodyOk = false;\n try {\n const body = await response.body();\n isBodyOk = true;\n return this.serializer.deserialize(body);\n } catch (error) {\n if (!isBodyOk) {\n throw new Error(\"Cannot parse response body, please check the response body and content-type.\", {\n cause: error\n });\n }\n throw new Error(\"Invalid RPC response format.\", {\n cause: error\n });\n }\n })();\n if (!isOk) {\n if (isORPCErrorJson(deserialized)) {\n throw createORPCErrorFromJson(deserialized);\n }\n throw new ORPCError(getMalformedResponseErrorCode(response.status), {\n status: response.status,\n data: { ...response, body: deserialized }\n });\n }\n return deserialized;\n }\n}\n\nclass StandardRPCSerializer {\n constructor(jsonSerializer) {\n this.jsonSerializer = jsonSerializer;\n }\n serialize(data) {\n if (isAsyncIteratorObject(data)) {\n return mapEventIterator(data, {\n value: async (value) => this.#serialize(value, false),\n error: async (e) => {\n return new ErrorEvent({\n data: this.#serialize(toORPCError(e).toJSON(), false),\n cause: e\n });\n }\n });\n }\n return this.#serialize(data, true);\n }\n #serialize(data, enableFormData) {\n const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);\n const meta = meta_.length === 0 ? void 0 : meta_;\n if (!enableFormData || blobs.length === 0) {\n return {\n json,\n meta\n };\n }\n const form = new FormData();\n form.set(\"data\", stringifyJSON({ json, meta, maps }));\n blobs.forEach((blob, i) => {\n form.set(i.toString(), blob);\n });\n return form;\n }\n deserialize(data) {\n if (isAsyncIteratorObject(data)) {\n return mapEventIterator(data, {\n value: async (value) => this.#deserialize(value),\n error: async (e) => {\n if (!(e instanceof ErrorEvent)) {\n return e;\n }\n const deserialized = this.#deserialize(e.data);\n if (isORPCErrorJson(deserialized)) {\n return createORPCErrorFromJson(deserialized, { cause: e });\n }\n return new ErrorEvent({\n data: deserialized,\n cause: e\n });\n }\n });\n }\n return this.#deserialize(data);\n }\n #deserialize(data) {\n if (data === void 0) {\n return void 0;\n }\n if (!(data instanceof FormData)) {\n return this.jsonSerializer.deserialize(data.json, data.meta ?? []);\n }\n const serialized = JSON.parse(data.get(\"data\"));\n return this.jsonSerializer.deserialize(\n serialized.json,\n serialized.meta ?? [],\n serialized.maps,\n (i) => data.get(i.toString())\n );\n }\n}\n\nclass StandardRPCLink extends StandardLink {\n constructor(linkClient, options) {\n const jsonSerializer = new StandardRPCJsonSerializer(options);\n const serializer = new StandardRPCSerializer(jsonSerializer);\n const linkCodec = new StandardRPCLinkCodec(serializer, options);\n super(linkCodec, linkClient, options);\n }\n}\n\nexport { CompositeStandardLinkPlugin as C, StandardLink as S, STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as a, StandardRPCJsonSerializer as b, StandardRPCLink as c, StandardRPCLinkCodec as d, StandardRPCSerializer as e, toStandardHeaders as f, getMalformedResponseErrorCode as g, toHttpPath as t };\n","import { toArray, intercept } from '@orpc/shared';\nimport { toFetchRequest, toStandardLazyResponse } from '@orpc/standard-server-fetch';\nimport { C as CompositeStandardLinkPlugin, c as StandardRPCLink } from '../../shared/client.BtiuJPEa.mjs';\nimport '@orpc/standard-server';\nimport '../../shared/client.CZlviB0y.mjs';\nimport '../../shared/client.BLtwTQUg.mjs';\n\nclass CompositeLinkFetchPlugin extends CompositeStandardLinkPlugin {\n initRuntimeAdapter(options) {\n for (const plugin of this.plugins) {\n plugin.initRuntimeAdapter?.(options);\n }\n }\n}\n\nclass LinkFetchClient {\n fetch;\n toFetchRequestOptions;\n adapterInterceptors;\n constructor(options) {\n const plugin = new CompositeLinkFetchPlugin(options.plugins);\n plugin.initRuntimeAdapter(options);\n this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.toFetchRequestOptions = options;\n this.adapterInterceptors = toArray(options.adapterInterceptors);\n }\n async call(standardRequest, options, path, input) {\n const request = toFetchRequest(standardRequest, this.toFetchRequestOptions);\n const fetchResponse = await intercept(\n this.adapterInterceptors,\n { ...options, request, path, input, init: { redirect: \"manual\" } },\n ({ request: request2, path: path2, input: input2, init, ...options2 }) => this.fetch(request2, init, options2, path2, input2)\n );\n const lazyResponse = toStandardLazyResponse(fetchResponse, { signal: request.signal });\n return lazyResponse;\n }\n}\n\nclass RPCLink extends StandardRPCLink {\n constructor(options) {\n const linkClient = new LinkFetchClient(options);\n super(linkClient, options);\n }\n}\n\nexport { LinkFetchClient, RPCLink };\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (!mask[key])\n continue;\n assignProp(newShape, key, currDef.shape[key]);\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.prototype.hasOwnProperty.call(oldShape, key)) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n // the spread copies symbol keys; `for...in` would not reach them\n for (const key of Reflect.ownKeys(oldShape)) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.prototype.hasOwnProperty.call(shape, key)) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key of Reflect.ownKeys(oldShape)) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _zodDesc = { value: undefined, enumerable: false };\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n _zodDesc.value = inst._zod;\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slots; a retained `value` pins the last error's issues.\n _zodDesc.value = undefined;\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined && validator(value) !== COMPILE_INVALID)\n return true;\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport 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})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match.\nconst _emoji = `^[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport 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])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport 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])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\nconst 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])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n","export const version = {\n major: 4,\n minor: 5,\n patch: 4,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\nconst toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues };\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n try {\n return toStandardResult(safeParse(inst, value));\n }\n catch (_) {\n return safeParseAsync(inst, value).then(toStandardResult);\n }\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL constructor rejected the input. */\nexport const URL_UNPARSEABLE = 2;\n/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = parseURLObject(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema\n if (def.local || def.precision === -1) {\n inst._zod.bag.laxFormat = true;\n inst._zod.onattach.push((s) => {\n s._zod.bag.laxFormat = true;\n });\n }\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n try {\n // @ts-ignore\n new URL(`http://[${value}]`);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = +digits[--length];\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n for (const key in input) {\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\n// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed.\nconst propShapes = new WeakMap();\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n propShapes.set(def, sh);\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n propShapes.set(def, newSh);\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.allKeys) {\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // Prefixes in place, like util.prefixIssues does for every interpreted path.\n const prefixStr = (id, k) => `\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n \n if (${id}.value === undefined) {\n if (${isPresent}) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option of `union` whose discriminator claims `value`. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = new Map();\n const { options, discriminator } = internals.def;\n for (const option of options) {\n // First declaration wins, matching the order the parse path resolves a duplicate in.\n for (const v of option._zod.propValues?.[discriminator] ?? [])\n if (!map.has(v))\n map.set(v, option);\n }\n internals.bag.optionsMap = map;\n }\n return map.get(value);\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = propShapes.get(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n const patternValues = values.filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n inst._zod.pattern = new RegExp(def.values.length\n ? `^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * 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. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","export class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return true;\n stack.add(inst);\n let result = false;\n const check = (child) => {\n if (!result && child?._zod && isRecursive(child, stack))\n result = true;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n for (const key of Reflect.ownKeys(def.shape))\n check(def.shape[key]);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // reading `_zod.innerType` resolves the getter once and caches it\n case \"lazy\":\n check(inst._zod.innerType);\n break;\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n recursive.set(inst, result);\n return result;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n return isRecursive(inst, new Set());\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new Map();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n isRecursiveInst = isRecursive(inst, new Set());\n if (!isRecursiveInst) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n }\n const input = payload.value;\n if (input === null || typeof input !== \"object\")\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new Map(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new Set());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && value !== null && typeof value === \"object\" && backEdges.has(value);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n credit_card: \"credit card number\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape) {\n return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: \"property\", property, schema }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n assignProps(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"catch\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, process, } from \"./to-json-schema.js\";\nimport { assignProp, getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns];\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (typeof multipleOf === \"number\") {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n if (Number.isFinite(multipleOf) && multipleOf !== 0)\n json.multipleOf = Math.abs(multipleOf);\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`);\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const field = def.shape[key];\n if (ctx.io === \"input\") {\n return inputOptin(field) === undefined;\n }\n else {\n return field._zod.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, pattern.source, valueSchema);\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n assignProp(schemas, key, finalize(ctx, schema));\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n}, {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n}, {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n}, {\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n}, {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n return this.clone({ ...this._zod.def, catchall: catchall });\n },\n passthrough() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n loose() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n strict() {\n return this.clone({ ...this._zod.def, catchall: never() });\n },\n strip() {\n return this.clone({ ...this._zod.def, catchall: undefined });\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\n },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","import { z } from 'zod';\n\nexport const EntityStatusSchema = z.enum(['created', 'active', 'suspended']);\nexport type EntityStatus = z.infer<typeof EntityStatusSchema>;\n\nexport const BaseEntitySchema = z.object({\n id: z.number().optional(),\n created_at: z.coerce.date().optional(),\n updated_at: z.coerce.date().optional(),\n});\n\nexport const ByIdSchema = z.object({ id: z.coerce.number() });\nexport const BySlugSchema = z.object({ slug: z.string() });\nexport const ByWidgetIdSchema = z.object({ widget_id: z.coerce.number() });\nexport const BySimulationIdSchema = z.object({ simulation_id: z.coerce.number() });\nexport const ByApplicationIdSchema = z.object({ application_id: z.coerce.number() });\nexport const ByUserIdSchema = z.object({ user_id: z.coerce.number() });\n\nexport const PaginationSchema = z.object({\n limit: z.coerce.number().optional().default(50),\n offset: z.coerce.number().optional().default(0),\n});\n\ntype StripDefault<T> = T extends z.ZodDefault<infer Inner> ? Inner : T;\n\n/**\n * The ONE way to build a PATCH schema from an entity/input schema. Zod's `.partial()` makes every\n * field optional but does NOT stop a `.default(...)` field from being backfilled when omitted — an\n * update caller who sends only `{ title }` gets `options: []`/`config: {}` re-applied by parsing, so a\n * `field !== undefined` merge guard downstream never sees the omission and silently wipes the column.\n * This strips each field's default before making it optional, so \"not sent\" really does parse to\n * `undefined`.\n */\nexport function partialPatch<Shape extends z.ZodRawShape>(\n schema: z.ZodObject<Shape>,\n): z.ZodObject<{ [K in keyof Shape]: z.ZodOptional<StripDefault<Shape[K]>> }> {\n const stripped = Object.fromEntries(\n Object.entries(schema.shape).map(([key, field]) => {\n const base = field as z.ZodTypeAny;\n const unwrapped = base instanceof z.ZodDefault ? (base.removeDefault() as z.ZodTypeAny) : base;\n return [key, unwrapped.optional()];\n }),\n );\n return z.object(stripped) as unknown as z.ZodObject<{ [K in keyof Shape]: z.ZodOptional<StripDefault<Shape[K]>> }>;\n}\n\n// NOT z.coerce.boolean() — that's Boolean(val), so `?enabled=false` would coerce true.\nexport const booleanQueryParam = z\n .union([z.boolean(), z.string()])\n .transform(val => (typeof val === 'boolean' ? val : val === 'true' ? true : val === 'false' ? false : undefined))\n .optional();\n\nexport const paginatedListOf = <T extends z.ZodType>(schema: T) =>\n z.object({\n items: z.array(schema),\n total: z.number(),\n limit: z.number(),\n offset: z.number(),\n });\n\n// Bounded results (scoped to a parent entity) — no limit/offset.\nexport const listOf = <T extends z.ZodType>(schema: T) =>\n z.object({\n items: z.array(schema),\n count: z.number(),\n });\n\nexport const SuccessSchema = z.object({ success: z.literal(true) });\nexport const SuccessWithMessageSchema = SuccessSchema.extend({ message: z.string() });\n\n// One browser_op invocation recorded inside a SimulationStep's action.\nexport const ToolCallRecordSchema = z.object({\n name: z.string().min(1),\n params: z.record(z.string(), z.unknown()).default({}),\n result: z.record(z.string(), z.unknown()).default({}),\n});\n\n// Shared by workspace update + slack-test so both 400 on the same malformed input.\nexport const SlackWebhookUrlSchema = z.url().refine(u => /^https:\\/\\/hooks\\.slack\\.com\\//.test(u), {\n message: 'Slack webhook URL must start with https://hooks.slack.com/',\n});\n\nexport const GraphEdgeSchema = z\n .object({\n start: z.string(),\n end: z.string(),\n action: z.string(),\n })\n .passthrough();\nexport type GraphEdgeData = z.infer<typeof GraphEdgeSchema>;\n\nexport const GraphSectionSchema = z\n .object({\n id: z.string(),\n label: z.string(),\n purpose: z.string(),\n elements: z.array(z.record(z.string(), z.unknown())).default([]),\n bbox: z.record(z.string(), z.unknown()).default({}),\n screenshot: z.string().default(''),\n embedding: z.array(z.number()).nullish(),\n })\n .passthrough();\n\n// Unique page state observed during simulation; matches agent's PageNode (knowledge/graph.py).\n// passthrough() because the agent model may evolve faster than this schema.\nexport const GraphNodeSchema = z\n .object({\n id: z.string(),\n title: z.string(),\n url: z.string(),\n summary: z.string().default(''),\n screenshot: z.string().default(''),\n sections: z.array(GraphSectionSchema).default([]),\n sequence_ids: z.array(z.number()).default([]),\n embedding: z.array(z.number()).nullish(),\n })\n .passthrough();\nexport type GraphNodeData = z.infer<typeof GraphNodeSchema>;\n\nexport const GraphSchema = z.object({\n nodes: z.array(GraphNodeSchema),\n edges: z.array(GraphEdgeSchema),\n});\nexport type GraphData = z.infer<typeof GraphSchema>;\n\nexport const NotificationResolvedReasonSchema = z.enum(['answered', 'dismissed', 'cancelled']);\nexport type NotificationResolvedReason = z.infer<typeof NotificationResolvedReasonSchema>;\n\n/** Every live-progress stream the api opens. The app keys `useAgentProgress` on these, so a kind it\n * cannot name is a generator whose progress never renders. */\nexport const AGENT_PROGRESS_KINDS = [\n 'study_plan',\n 'qa_generate_journeys',\n 'qa_prefill_values',\n 'persona_generate',\n 'persona_from_description',\n 'persona_autocomplete',\n] as const;\nexport const AgentProgressKindSchema = z.enum(AGENT_PROGRESS_KINDS);\nexport type AgentProgressKind = z.infer<typeof AgentProgressKindSchema>;\n","import { z } from 'zod';\n\nimport { BaseEntitySchema, EntityStatusSchema } from './common';\nexport const WorkspacePackageSchema = z.enum(['free', 'startup', 'growth', 'enterprise']);\n\nexport const ApplicationTypeSchema = z.enum(['app', 'website']);\n\nexport type ApplicationType = z.infer<typeof ApplicationTypeSchema>;\n\nexport const WidgetTypeSchema = z.enum(['widget']);\n\nexport type WidgetType = z.infer<typeof WidgetTypeSchema>;\n\nexport const InstructionTypeSchema = z.enum(['tell', 'show', 'do']);\n\nexport type InstructionType = z.infer<typeof InstructionTypeSchema>;\n\nconst AuthMethodSchema = z.enum(['password', 'oauth']);\n\n// Users don't have plans — plans belong to workspaces (via the workspace_plan table).\n/**\n * The workspace role vocabulary — `admin` administers, `member` does not. One spelling everywhere:\n * DB enum, this contract, the dashboard, and the WorkOS role slug. Declared here (not `workspace.ts`)\n * because `UserEntitySchema` needs it and `workspace.ts` already imports from this file.\n */\nexport const WorkspaceMemberRoleSchema = z.enum(['admin', 'member']);\nexport type WorkspaceMemberRole = z.infer<typeof WorkspaceMemberRoleSchema>;\n\nexport const UserEntitySchema = BaseEntitySchema.extend({\n is_super: z.boolean(),\n status: EntityStatusSchema,\n email: z.email(),\n external_id: z.string().nullish(),\n first_name: z.string().nullish(),\n last_name: z.string().nullish(),\n password: z.string().nullish(),\n image_url: z.string().nullish(),\n last_login_at: z.coerce.date().nullish(),\n auth_method: AuthMethodSchema.nullish(),\n // Present only when the user was looked up THROUGH a workspace (`userSearch` with a workspace_id) —\n // a role is a property of the membership, not of the person, so a user read on its own has none.\n workspace_role: WorkspaceMemberRoleSchema.nullish(),\n});\n\nexport type UserData = z.infer<typeof UserEntitySchema>;\n\n// package and ending_date come from the workspace_plan table (joined on fetch), NOT the workspace row.\nexport const WorkspaceEntitySchema = BaseEntitySchema.extend({\n name: z.string(),\n slug: z.string(),\n status: EntityStatusSchema,\n package: WorkspacePackageSchema,\n ending_date: z.coerce.date().nullish(),\n external_workspace_id: z.string().nullish(),\n // Read-only flag derived from `slack_webhook_url`'s presence. The URL itself\n // is a secret and is never returned to clients — only this boolean is.\n slack_webhook_configured: z.boolean().optional(),\n notify_all_members_on_question: z.boolean().optional(),\n});\n\nexport type WorkspaceData = z.infer<typeof WorkspaceEntitySchema>;\n\nexport const ApplicationEntitySchema = BaseEntitySchema.extend({\n workspace_id: z.number(),\n name: z.string(),\n slug: z.string(),\n type: ApplicationTypeSchema,\n url: z.string(),\n username: z.string().nullish(),\n password: z.string().nullish(),\n allowed_domains: z.array(z.string()).default([]),\n});\n\nexport type ApplicationData = z.infer<typeof ApplicationEntitySchema>;\n\n/** Used for all API responses; password is write-only and never returned to clients. */\nexport const ApplicationReadSchema = ApplicationEntitySchema.omit({ password: true });\n\nexport type ApplicationReadData = z.infer<typeof ApplicationReadSchema>;\n\nexport const WidgetChipSchema = z.object({\n chip_mode: InstructionTypeSchema,\n chip_text: z.string(),\n});\n\nexport type WidgetChip = z.infer<typeof WidgetChipSchema>;\n\nexport const WidgetSettingsDataSchema = z.object({\n widget_enabled: z.boolean(),\n // The widget reads this only as `!== 'default'` (greeting toast) and `=== 'hidden'`; the retired\n // `compact`/`full` rendered identically to `default`, so db-V246 folds them onto it.\n widget_appearance: z.enum(['default', 'hidden']),\n widget_position: z.enum(['bottom_left', 'bottom_right', 'top_left', 'top_right']),\n widget_header: z.string(),\n widget_body: z.string(),\n widget_greeting: z.string(),\n widget_greeting_toast: z.boolean(),\n widget_recording: z.boolean(),\n widget_feature_tell: z.boolean(),\n widget_feature_show: z.boolean(),\n widget_feature_do: z.boolean(),\n widget_background_color: z.string(),\n widget_text_color: z.string(),\n widget_border_color: z.string(),\n widget_accent_color: z.string(),\n widget_secondary_color: z.string(),\n widget_border_radius: z.string(),\n widget_font_size: z.string(),\n widget_width: z.string(),\n widget_height: z.string(),\n widget_animation_duration: z.string(),\n widget_fade_duration: z.string(),\n widget_chips: z.array(WidgetChipSchema),\n});\n\nexport type WidgetSettingsData = z.infer<typeof WidgetSettingsDataSchema>;\n\n// The widget renders these from its own constants, so a write is a no-op; they stay in the read shape\n// because published bundles safeParse them out of widgetDefaultGet.\nexport const WIDGET_RENDER_CONSTANTS = [\n 'widget_border_radius',\n 'widget_font_size',\n 'widget_animation_duration',\n 'widget_fade_duration',\n] as const;\n\nexport const WidgetSettingsWriteSchema = WidgetSettingsDataSchema.omit({\n widget_border_radius: true,\n widget_font_size: true,\n widget_animation_duration: true,\n widget_fade_duration: true,\n});\nexport type WidgetSettingsWriteData = z.infer<typeof WidgetSettingsWriteSchema>;\n\nexport const WidgetEntitySchema = BaseEntitySchema.extend({\n application_id: z.number(),\n type: WidgetTypeSchema,\n settings: WidgetSettingsDataSchema,\n status: EntityStatusSchema,\n marketrix_id: z.string(),\n marketrix_key: z.string(),\n snippet: z.string().nullish(),\n});\n\nexport type WidgetData = z.infer<typeof WidgetEntitySchema>;\n\nexport const ActivityLogTypeSchema = z.enum([\n 'user_login',\n 'url_visit',\n 'update_workspace',\n 'create_user',\n 'update_user',\n 'delete_user',\n 'create_application',\n 'update_application',\n 'delete_application',\n 'create_widget',\n 'update_widget',\n 'delete_widget',\n 'create_knowledge',\n 'update_knowledge',\n 'delete_knowledge',\n // Exactly two membership verbs: someone REQUESTS membership, an admin INVITES them — no approving;\n // a request is answered with a WorkOS invitation or not at all, and it still must be accepted.\n 'request_membership',\n 'invite_user',\n // Workspace + subscription lifecycle — the transparency record a customer reads in settings, so\n // SYSTEM actions (Stripe webhooks) write these too with `user_id: null` rather than a fabricated admin.\n 'create_workspace',\n 'trial_started',\n 'trial_ending_soon',\n 'trial_ended',\n 'subscription_created',\n 'subscription_canceled',\n 'plan_changed',\n 'payment_succeeded',\n 'payment_failed',\n 'widget_question',\n 'qa_run_started',\n 'start_simulation',\n 'create_workflow',\n 'update_workflow',\n 'delete_workflow',\n 'toggle_workflow',\n 'slack_command',\n 'create_form',\n 'update_form',\n 'delete_form',\n 'duplicate_form',\n 'publish_form',\n 'unpublish_form',\n 'archive_form',\n 'submit_form_response',\n 'delete_form_response',\n]);\n\nexport type ActivityLogType = z.infer<typeof ActivityLogTypeSchema>;\n\nexport const ActivityLogMetadataSchema = z\n .object({\n details: z.string().optional(),\n id: z.number().optional(),\n type: z.string().optional(),\n name: z.string().optional(),\n target_user_id: z.number().optional(),\n target_user_email: z.string().optional(),\n reason: z.string().optional(),\n ip_address: z.string().optional(),\n user_agent: z.string().optional(),\n widget_type: z.string().optional(),\n created_by: z.number().optional(),\n })\n .passthrough();\n\nexport const ActivityLogEntitySchema = BaseEntitySchema.extend({\n workspace_id: z.number(),\n user_id: z.number().nullable(),\n type: ActivityLogTypeSchema,\n metadata: ActivityLogMetadataSchema.optional(),\n});\n\nexport type ActivityLogData = z.infer<typeof ActivityLogEntitySchema>;\n\nexport const ActivityLogCreateSchema = ActivityLogEntitySchema.partial().extend({\n type: ActivityLogTypeSchema,\n});\n","import { createORPCClient } from '@orpc/client';\nimport { RPCLink } from '@orpc/client/fetch';\nimport type { ContractRouterClient } from '@orpc/contract';\n\nimport type { widgetContract } from './contract';\n\nfunction createClient(apiUrl: string): ContractRouterClient<typeof widgetContract> {\n return createORPCClient(new RPCLink({ url: apiUrl }));\n}\n\nlet currentApiUrl = '';\nlet client = createClient('');\n\n/** Must be called before any SDK operation — the widget has no baked-in API host. */\nexport const configureSdk = (apiUrl: string) => {\n if (!apiUrl?.trim()) throw new Error('API URL is required for SDK configuration');\n\n if (apiUrl !== currentApiUrl) {\n console.log(`[SDK] Reconfiguring API URL to: ${apiUrl}`);\n currentApiUrl = apiUrl;\n client = createClient(apiUrl);\n }\n};\n\nexport const sdk = new Proxy({} as ContractRouterClient<typeof widgetContract>, {\n get(_target, prop) {\n return client[prop as keyof typeof client];\n },\n});\n\nexport { WidgetSettingsDataSchema } from './contracts/entities';\nexport { WidgetEventSchema } from './contracts/widget';\n\nexport type { InstructionType, WidgetData, WidgetSettingsData } from './contracts/entities';\n\nexport type { WidgetCommand, WidgetEvent } from './contracts/widget';\n\n// Type-only: the oRPC client builds requests from the proxied path, so the contract value never ships.\nexport type { widgetContract } from './contract';\n","import type { ChatMessage, InstructionType, MarketrixConfig } from '../types';\n\nconst STORAGE_KEY = 'marketrix_chat_context';\nconst CONTEXT_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport type StoredMessage = Omit<ChatMessage, 'videoStream' | 'timestamp'> & { timestamp: string };\n\nexport interface ChatSnapshot {\n messages: ChatMessage[];\n isTaskRunning: boolean;\n currentMode: InstructionType;\n isOpen: boolean;\n}\n\nexport type CredentialedConfig = MarketrixConfig & { mtxId: string; mtxKey: string };\n\nexport type MarketrixChatContext = Omit<ChatSnapshot, 'messages'> & {\n chat_id: string | null;\n messages: StoredMessage[];\n config: MarketrixConfig | null;\n timestamp: number;\n};\n\nconst DEFAULT_CONTEXT: MarketrixChatContext = {\n chat_id: null,\n messages: [],\n isTaskRunning: false,\n currentMode: 'tell',\n isOpen: false,\n config: null,\n timestamp: 0,\n};\n\n// A host page can deny storage outright (third-party cookies off, sandboxed iframe), where even reading throws.\nexport function readLocal(key: string): string | null {\n try {\n return typeof localStorage === 'undefined' ? null : localStorage.getItem(key);\n } catch (error) {\n console.warn('[StorageService] localStorage is unreadable:', error);\n return null;\n }\n}\n\nexport function writeLocal(key: string, value: string): void {\n try {\n if (typeof localStorage !== 'undefined') localStorage.setItem(key, value);\n } catch (error) {\n console.warn('[StorageService] localStorage is unwritable:', error);\n }\n}\n\n// Merged over the defaults so a payload written by an older widget version reads as incomplete, not corrupt.\nfunction loadContext(): MarketrixChatContext {\n const stored = readLocal(STORAGE_KEY);\n if (!stored) return { ...DEFAULT_CONTEXT };\n try {\n const parsed = { ...DEFAULT_CONTEXT, ...(JSON.parse(stored) as Partial<MarketrixChatContext>) };\n if (Date.now() - parsed.timestamp <= CONTEXT_EXPIRY_MS) return parsed;\n } catch (error) {\n console.warn('[StorageService] Failed to parse the stored context:', error);\n }\n return { ...DEFAULT_CONTEXT };\n}\n\nclass StorageService {\n private context = loadContext();\n\n getContext(): MarketrixChatContext {\n return this.context;\n }\n\n updateContext(updates: Partial<MarketrixChatContext>): void {\n this.context = { ...this.context, ...updates, timestamp: Date.now() };\n writeLocal(STORAGE_KEY, JSON.stringify(this.context));\n }\n\n getChatId(): string | null {\n return this.context.chat_id;\n }\n\n setChatId(chatId: string): void {\n this.updateContext({ chat_id: chatId });\n }\n\n getCredentialedConfig(): CredentialedConfig | null {\n const { config } = this.context;\n return config?.mtxId && config.mtxKey ? (config as CredentialedConfig) : null;\n }\n\n setConfig(config: CredentialedConfig): void {\n this.updateContext({ config });\n }\n}\n\nexport const storageService = new StorageService();\n","import { sdk } from '../sdk';\nimport { storageService } from './StorageService';\n\nclass ChatSessionManager {\n private creation: Promise<string> | null = null;\n\n /** Promise-based lock: concurrent callers all await the same creation. */\n async getOrCreateChatId(): Promise<string> {\n const stored = storageService.getChatId();\n if (stored) return stored;\n\n this.creation ??= this.createChatId().finally(() => {\n this.creation = null;\n });\n return this.creation;\n }\n\n private async createChatId(): Promise<string> {\n const chatId = await sdk.chatCreate(undefined);\n if (!chatId) throw new Error('API returned empty chat ID');\n storageService.setChatId(chatId);\n console.info('[ChatSessionManager] Created chat ID:', chatId);\n return chatId;\n }\n}\n\nexport const chatSessionManager = new ChatSessionManager();\n","var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar _a;\nvar EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n EventType2[EventType2[\"Asset\"] = 7] = \"Asset\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => {\n MediaInteractions2[MediaInteractions2[\"Play\"] = 0] = \"Play\";\n MediaInteractions2[MediaInteractions2[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions2[MediaInteractions2[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions2[MediaInteractions2[\"VolumeChange\"] = 3] = \"VolumeChange\";\n MediaInteractions2[MediaInteractions2[\"RateChange\"] = 4] = \"RateChange\";\n return MediaInteractions2;\n})(MediaInteractions || {});\nvar NodeType = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n return NodeType2;\n})(NodeType || {});\nconst testableAccessors = {\n Node: [\n \"childNodes\",\n \"parentNode\",\n \"parentElement\",\n \"textContent\",\n \"ownerDocument\"\n ],\n ShadowRoot: [\"host\", \"styleSheets\"],\n Element: [\"shadowRoot\", \"querySelector\", \"querySelectorAll\"],\n MutationObserver: []\n};\nconst testableMethods = {\n Node: [\"contains\", \"getRootNode\"],\n ShadowRoot: [\"getSelection\"],\n Element: [],\n MutationObserver: [\"constructor\"]\n};\nconst untaintedBasePrototype = {};\nconst untaintedBaseIframeCleanup = {};\nconst isAngularZonePresent = () => {\n return !!globalThis.Zone;\n};\nfunction getUntaintedPrototype(key) {\n if (untaintedBasePrototype[key])\n return untaintedBasePrototype[key];\n const defaultObj = globalThis[key];\n const defaultPrototype = defaultObj.prototype;\n const accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;\n const isUntaintedAccessors = Boolean(\n accessorNames && // @ts-expect-error 2345\n accessorNames.every(\n (accessor) => {\n var _a2, _b;\n return Boolean(\n (_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes(\"[native code]\")\n );\n }\n )\n );\n const methodNames = key in testableMethods ? testableMethods[key] : void 0;\n const isUntaintedMethods = Boolean(\n methodNames && methodNames.every(\n // @ts-expect-error 2345\n (method) => {\n var _a2;\n return typeof defaultPrototype[method] === \"function\" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes(\"[native code]\"));\n }\n )\n );\n if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent()) {\n untaintedBasePrototype[key] = defaultObj.prototype;\n return defaultObj.prototype;\n }\n try {\n const iframeEl = document.createElement(\"iframe\");\n iframeEl.style.display = \"none\";\n document.body.appendChild(iframeEl);\n const win = iframeEl.contentWindow;\n if (!win) return defaultObj.prototype;\n const untaintedObject = win[key].prototype;\n if (!untaintedObject) {\n iframeEl.remove();\n return defaultPrototype;\n }\n const ua = navigator.userAgent;\n if (ua.includes(\"Safari\") && !ua.includes(\"Chrome\")) {\n iframeEl.classList.add(\"rr-block\");\n iframeEl.setAttribute(\"__rrwebUntaintedMutationObserver\", \"\");\n untaintedBaseIframeCleanup[key] = () => iframeEl.remove();\n } else {\n iframeEl.remove();\n }\n return untaintedBasePrototype[key] = untaintedObject;\n } catch {\n return defaultPrototype;\n }\n}\nconst untaintedAccessorCache = {};\nfunction getUntaintedAccessor(key, instance, accessor) {\n var _a2;\n const cacheKey = `${key}.${String(accessor)}`;\n if (untaintedAccessorCache[cacheKey])\n return untaintedAccessorCache[cacheKey].call(\n instance\n );\n const untaintedPrototype = getUntaintedPrototype(key);\n const untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(\n untaintedPrototype,\n accessor\n )) == null ? void 0 : _a2.get;\n if (!untaintedAccessor) return instance[accessor];\n untaintedAccessorCache[cacheKey] = untaintedAccessor;\n return untaintedAccessor.call(instance);\n}\nconst untaintedMethodCache = {};\nfunction getUntaintedMethod(key, instance, method) {\n const cacheKey = `${key}.${String(method)}`;\n if (untaintedMethodCache[cacheKey])\n return untaintedMethodCache[cacheKey].bind(\n instance\n );\n const untaintedPrototype = getUntaintedPrototype(key);\n const untaintedMethod = untaintedPrototype[method];\n if (typeof untaintedMethod !== \"function\") return instance[method];\n untaintedMethodCache[cacheKey] = untaintedMethod;\n return untaintedMethod.bind(instance);\n}\nfunction ownerDocument(n) {\n return getUntaintedAccessor(\"Node\", n, \"ownerDocument\");\n}\nfunction childNodes(n) {\n return getUntaintedAccessor(\"Node\", n, \"childNodes\");\n}\nfunction parentNode(n) {\n return getUntaintedAccessor(\"Node\", n, \"parentNode\");\n}\nfunction parentElement(n) {\n return getUntaintedAccessor(\"Node\", n, \"parentElement\");\n}\nfunction textContent(n) {\n return getUntaintedAccessor(\"Node\", n, \"textContent\");\n}\nfunction contains(n, other) {\n return getUntaintedMethod(\"Node\", n, \"contains\")(other);\n}\nfunction getRootNode(n) {\n return getUntaintedMethod(\"Node\", n, \"getRootNode\")();\n}\nfunction host(n) {\n if (!n || !(\"host\" in n)) return null;\n return getUntaintedAccessor(\"ShadowRoot\", n, \"host\");\n}\nfunction styleSheets(n) {\n return n.styleSheets;\n}\nfunction shadowRoot(n) {\n if (!n || !(\"shadowRoot\" in n)) return null;\n return getUntaintedAccessor(\"Element\", n, \"shadowRoot\");\n}\nfunction querySelector(n, selectors) {\n return getUntaintedAccessor(\"Element\", n, \"querySelector\")(selectors);\n}\nfunction querySelectorAll(n, selectors) {\n return getUntaintedAccessor(\"Element\", n, \"querySelectorAll\")(selectors);\n}\nfunction mutationObserverCtor() {\n return [\n getUntaintedPrototype(\"MutationObserver\").constructor,\n untaintedBaseIframeCleanup[\"MutationObserver\"] ?? (() => {\n })\n ];\n}\nlet nowTimestamp = Date.now;\nif (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {\n nowTimestamp = () => (/* @__PURE__ */ new Date()).getTime();\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => {\n };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === \"function\") {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original\n }\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n } catch {\n return () => {\n };\n }\n}\nconst index = {\n ownerDocument,\n childNodes,\n parentNode,\n parentElement,\n textContent,\n contains,\n getRootNode,\n host,\n styleSheets,\n shadowRoot,\n querySelector,\n querySelectorAll,\n nowTimestamp,\n mutationObserverCtor,\n patch\n};\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const hostEl = (\n // anchor and textarea elements also have a `host` property\n // but only shadow roots have a `mode` property\n n && \"host\" in n && \"mode\" in n && index.host(n) || null\n );\n return Boolean(\n hostEl && \"shadowRoot\" in hostEl && index.shadowRoot(hostEl) === n\n );\n}\nfunction isNativeShadowDom(shadowRoot2) {\n return Object.prototype.toString.call(shadowRoot2) === \"[object ShadowRoot]\";\n}\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\n if (cssText.includes(\" background-clip: text;\") && !cssText.includes(\" -webkit-background-clip: text;\")) {\n cssText = cssText.replace(\n /\\sbackground-clip:\\s*text;/g,\n \" -webkit-background-clip: text; background-clip: text;\"\n );\n }\n return cssText;\n}\nfunction escapeImportStatement(rule) {\n const { cssText } = rule;\n if (cssText.split('\"').length < 3) return cssText;\n const statement = [\"@import\", `url(${JSON.stringify(rule.href)})`];\n if (rule.layerName === \"\") {\n statement.push(`layer`);\n } else if (rule.layerName) {\n statement.push(`layer(${rule.layerName})`);\n }\n if (rule.supportsText) {\n statement.push(`supports(${rule.supportsText})`);\n }\n if (rule.media.length) {\n statement.push(rule.media.mediaText);\n }\n return statement.join(\" \") + \";\";\n}\nfunction stringifyStylesheet(s) {\n try {\n const rules = s.rules || s.cssRules;\n if (!rules) {\n return null;\n }\n let sheetHref = s.href;\n if (!sheetHref && s.ownerNode) {\n sheetHref = s.ownerNode.baseURI;\n }\n const stringifiedRules = Array.from(\n rules,\n (rule) => stringifyRule(rule, sheetHref)\n ).join(\"\");\n return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);\n } catch (error) {\n return null;\n }\n}\nfunction stringifyRule(rule, sheetHref) {\n if (isCSSImportRule(rule)) {\n let importStringified;\n try {\n importStringified = // for same-origin stylesheets,\n // we can access the imported stylesheet rules directly\n stringifyStylesheet(rule.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement\n escapeImportStatement(rule);\n } catch (error) {\n importStringified = rule.cssText;\n }\n if (rule.styleSheet.href) {\n return absolutifyURLs(importStringified, rule.styleSheet.href);\n }\n return importStringified;\n } else {\n let ruleStringified = rule.cssText;\n if (isCSSStyleRule(rule) && rule.selectorText.includes(\":\")) {\n ruleStringified = fixSafariColons(ruleStringified);\n }\n if (sheetHref) {\n return absolutifyURLs(ruleStringified, sheetHref);\n }\n return ruleStringified;\n }\n}\nfunction fixSafariColons(cssStringified) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, \"$1\\\\$2\");\n}\nfunction isCSSImportRule(rule) {\n return \"styleSheet\" in rule;\n}\nfunction isCSSStyleRule(rule) {\n return \"selectorText\" in rule;\n}\nclass Mirror {\n constructor() {\n __publicField(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n __publicField(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n }\n getId(n) {\n var _a2;\n if (!n) return -1;\n const id = (_a2 = this.getMeta(n)) == null ? void 0 : _a2.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n) {\n return this.nodeMetaMap.get(n) || null;\n }\n // removes the node from idNodeMap\n // doesn't remove the node from nodeMetaMap\n removeNodeFromMap(n) {\n const id = this.getId(n);\n this.idNodeMap.delete(id);\n if (n.childNodes) {\n n.childNodes.forEach(\n (childNode) => this.removeNodeFromMap(childNode)\n );\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n);\n this.nodeMetaMap.set(n, meta);\n }\n replace(id, n) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta) this.nodeMetaMap.set(n, meta);\n }\n this.idNodeMap.set(id, n);\n }\n reset() {\n this.idNodeMap = /* @__PURE__ */ new Map();\n this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n }\n}\nfunction createMirror() {\n return new Mirror();\n}\nfunction maskInputValue({\n element,\n maskInputOptions,\n tagName,\n type,\n value,\n maskInputFn\n}) {\n let text = value || \"\";\n const actualType = type && toLowerCase(type);\n if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {\n if (maskInputFn) {\n text = maskInputFn(text, element);\n } else {\n text = \"*\".repeat(text.length);\n }\n }\n return text;\n}\nfunction toLowerCase(str) {\n return str.toLowerCase();\n}\nconst ORIGINAL_ATTRIBUTE_NAME = \"__rrweb_original__\";\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;\n const pixelBuffer = new Uint32Array(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n originalGetImageData.call(\n ctx,\n x,\n y,\n Math.min(chunkSize, canvas.width - x),\n Math.min(chunkSize, canvas.height - y)\n ).data.buffer\n );\n if (pixelBuffer.some((pixel) => pixel !== 0)) return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute(\"data-rr-is-password\") ? \"password\" : type ? (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n toLowerCase(type)\n ) : null;\n}\nfunction extractFileExtension(path, baseURL) {\n let url;\n try {\n url = new URL(path, baseURL ?? window.location.href);\n } catch (err) {\n return null;\n }\n const regex = /\\.([0-9a-z]+)(?:$)/i;\n const match = url.pathname.match(regex);\n return (match == null ? void 0 : match[1]) ?? null;\n}\nfunction extractOrigin(url) {\n let origin = \"\";\n if (url.indexOf(\"//\") > -1) {\n origin = url.split(\"/\").slice(0, 3).join(\"/\");\n } else {\n origin = url.split(\"/\")[0];\n }\n origin = origin.split(\"?\")[0];\n return origin;\n}\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absolutifyURLs(cssText, href) {\n return (cssText || \"\").replace(\n URL_IN_CSS_REF,\n (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || \"\";\n if (!filePath) {\n return origin;\n }\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === \"/\") {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const filePathNoHash = filePath.split(\"#\")[0];\n const maybeHash = filePath.substring(filePathNoHash.length);\n const stack = href.split(\"#\")[0].split(\"/\");\n const parts = filePathNoHash.split(\"/\");\n stack.pop();\n for (const part of parts) {\n if (part === \".\") {\n continue;\n } else if (part === \"..\") {\n stack.pop();\n } else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join(\"/\")}${maybeHash}${maybeQuote})`;\n }\n );\n}\nfunction normalizeCssString(cssText, _testNoPxNorm = false) {\n if (_testNoPxNorm) {\n return cssText.replace(/(\\/\\*[^*]*\\*\\/)|[\\s;]/g, \"\");\n } else {\n return cssText.replace(/(\\/\\*[^*]*\\*\\/)|[\\s;]/g, \"\").replace(/0px/g, \"0\");\n }\n}\nfunction splitCssText(cssText, style, _testNoPxNorm = false) {\n const childNodes2 = Array.from(style.childNodes);\n const splits = [];\n let iterCount = 0;\n if (childNodes2.length > 1 && cssText && typeof cssText === \"string\") {\n let cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);\n const normFactor = cssTextNorm.length / cssText.length;\n for (let i = 1; i < childNodes2.length; i++) {\n if (childNodes2[i].textContent && typeof childNodes2[i].textContent === \"string\") {\n const textContentNorm = normalizeCssString(\n childNodes2[i].textContent,\n _testNoPxNorm\n );\n const jLimit = 100;\n let j = 3;\n for (; j < textContentNorm.length; j++) {\n if (\n // keep consuming css identifiers (to get a decent chunk more quickly)\n textContentNorm[j].match(/[a-zA-Z0-9]/) || // substring needs to be unique to this section\n textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1\n ) {\n continue;\n }\n break;\n }\n for (; j < textContentNorm.length; j++) {\n let startSubstring = textContentNorm.substring(0, j);\n let cssNormSplits = cssTextNorm.split(startSubstring);\n let splitNorm = -1;\n if (cssNormSplits.length === 2) {\n splitNorm = cssNormSplits[0].length;\n } else if (cssNormSplits.length > 2 && cssNormSplits[0] === \"\" && childNodes2[i - 1].textContent !== \"\") {\n splitNorm = cssTextNorm.indexOf(startSubstring, 1);\n } else if (cssNormSplits.length === 1) {\n startSubstring = startSubstring.substring(\n 0,\n startSubstring.length - 1\n );\n cssNormSplits = cssTextNorm.split(startSubstring);\n if (cssNormSplits.length <= 1) {\n splits.push(cssText);\n return splits;\n }\n j = jLimit + 1;\n } else if (j === textContentNorm.length - 1) {\n splitNorm = cssTextNorm.indexOf(startSubstring);\n }\n if (cssNormSplits.length >= 2 && j > jLimit) {\n const prevTextContent = childNodes2[i - 1].textContent;\n if (prevTextContent && typeof prevTextContent === \"string\") {\n const prevMinLength = normalizeCssString(prevTextContent).length;\n splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);\n }\n if (splitNorm === -1) {\n splitNorm = cssNormSplits[0].length;\n }\n }\n if (splitNorm !== -1) {\n let k = Math.floor(splitNorm / normFactor);\n for (; k > 0 && k < cssText.length; ) {\n iterCount += 1;\n if (iterCount > 50 * childNodes2.length) {\n splits.push(cssText);\n return splits;\n }\n const normPart = normalizeCssString(\n cssText.substring(0, k),\n _testNoPxNorm\n );\n if (normPart.length === splitNorm) {\n splits.push(cssText.substring(0, k));\n cssText = cssText.substring(k);\n cssTextNorm = cssTextNorm.substring(splitNorm);\n break;\n } else if (normPart.length < splitNorm) {\n k += Math.max(\n 1,\n Math.floor((splitNorm - normPart.length) / normFactor)\n );\n } else {\n k -= Math.max(\n 1,\n Math.floor((normPart.length - splitNorm) * normFactor)\n );\n }\n }\n break;\n }\n }\n }\n }\n }\n splits.push(cssText);\n return splits;\n}\nfunction markCssSplits(cssText, style) {\n return splitCssText(cssText, style).join(\"/* rr_split */\");\n}\nlet _id = 1;\nconst tagNameRegex = new RegExp(\"[^a-z0-9-_:]\");\nconst IGNORED_NODE = -2;\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return \"form\";\n }\n const processedTagName = toLowerCase(element.tagName);\n if (tagNameRegex.test(processedTagName)) {\n return \"div\";\n }\n return processedTagName;\n}\nlet canvasService;\nlet canvasCtx;\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === \"\") {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars2;\n const match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars2 = match[0];\n pos += chars2.length;\n return chars2;\n }\n return \"\";\n }\n const output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === \",\") {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n } else {\n let descriptorsStr = \"\";\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n const c = attributeValue.charAt(pos);\n if (c === \"\") {\n output.push((url + descriptorsStr).trim());\n break;\n } else if (!inParens) {\n if (c === \",\") {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n } else if (c === \"(\") {\n inParens = true;\n }\n } else {\n if (c === \")\") {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(\", \");\n}\nconst cachedDocument = /* @__PURE__ */ new WeakMap();\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === \"\") {\n return attributeValue;\n }\n return getHref(doc, attributeValue);\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === \"svg\" || el.ownerSVGElement);\n}\nfunction getHref(doc, customHref) {\n let a = cachedDocument.get(doc);\n if (!a) {\n a = doc.createElement(\"a\");\n cachedDocument.set(doc, a);\n }\n if (!customHref) {\n customHref = \"\";\n } else if (customHref.startsWith(\"blob:\") || customHref.startsWith(\"data:\")) {\n return customHref;\n }\n a.setAttribute(\"href\", customHref);\n return a.href;\n}\nfunction transformAttribute(doc, tagName, name, value) {\n if (!value) {\n return value;\n }\n if (name === \"src\" || name === \"href\" && !(tagName === \"use\" && value[0] === \"#\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"xlink:href\" && value[0] !== \"#\") {\n return absoluteToDoc(doc, value);\n } else if (name === \"background\" && [\"table\", \"td\", \"th\"].includes(tagName)) {\n return absoluteToDoc(doc, value);\n } else if (name === \"srcset\") {\n return getAbsoluteSrcsetString(doc, value);\n } else if (name === \"style\") {\n return absolutifyURLs(value, getHref(doc));\n } else if (tagName === \"object\" && name === \"data\") {\n return absoluteToDoc(doc, value);\n }\n return value;\n}\nfunction ignoreAttribute(tagName, name, _value) {\n return [\"video\", \"audio\"].includes(tagName) && name === \"autoplay\";\n}\nfunction _isBlockedElement(element, blockClass, blockSelector) {\n try {\n if (typeof blockClass === \"string\") {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n } else {\n for (let eIndex = element.classList.length; eIndex--; ) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n } catch (e) {\n }\n return false;\n}\nfunction classMatchesRegex(node, regex, checkAncestors) {\n if (!node) return false;\n if (node.nodeType !== node.ELEMENT_NODE) {\n if (!checkAncestors) return false;\n return classMatchesRegex(index.parentNode(node), regex, checkAncestors);\n }\n for (let eIndex = node.classList.length; eIndex--; ) {\n const className = node.classList[eIndex];\n if (regex.test(className)) {\n return true;\n }\n }\n if (!checkAncestors) return false;\n return classMatchesRegex(index.parentNode(node), regex, checkAncestors);\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, checkAncestors) {\n let el;\n if (isElement(node)) {\n el = node;\n if (!index.childNodes(el).length) {\n return false;\n }\n } else if (index.parentElement(node) === null) {\n return false;\n } else {\n el = index.parentElement(node);\n }\n try {\n if (typeof maskTextClass === \"string\") {\n if (checkAncestors) {\n if (el.closest(`.${maskTextClass}`)) return true;\n } else {\n if (el.classList.contains(maskTextClass)) return true;\n }\n } else {\n if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;\n }\n if (maskTextSelector) {\n if (checkAncestors) {\n if (el.closest(maskTextSelector)) return true;\n } else {\n if (el.matches(maskTextSelector)) return true;\n }\n }\n } catch (e) {\n }\n return false;\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n } catch (error) {\n return;\n }\n if (readyState !== \"complete\") {\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener(\"load\", () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = \"about:blank\";\n if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === \"\") {\n setTimeout(listener, 0);\n return iframeEl.addEventListener(\"load\", listener);\n }\n iframeEl.addEventListener(\"load\", listener);\n}\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\n let fired = false;\n let styleSheetLoaded;\n try {\n styleSheetLoaded = link.sheet;\n } catch (error) {\n return;\n }\n if (styleSheetLoaded) return;\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, styleSheetLoadTimeout);\n link.addEventListener(\"load\", () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n}\nfunction serializeNode(n, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n inlineStylesheet,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n cssCaptured = false\n } = options;\n const rootId = getRootId(doc, mirror2);\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== \"CSS1Compat\") {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode\n // probably \"BackCompat\"\n };\n } else {\n return {\n type: NodeType.Document,\n childNodes: []\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId\n };\n case n.ELEMENT_NODE:\n return serializeElementNode(n, {\n doc,\n blockClass,\n blockSelector,\n inlineStylesheet,\n maskInputOptions,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n rootId\n });\n case n.TEXT_NODE:\n return serializeTextNode(n, {\n doc,\n needsMask,\n maskTextFn,\n rootId,\n cssCaptured\n });\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: \"\",\n rootId\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: index.textContent(n) || \"\",\n rootId\n };\n default:\n return false;\n }\n}\nfunction getRootId(doc, mirror2) {\n if (!mirror2.hasNode(doc)) return void 0;\n const docId = mirror2.getId(doc);\n return docId === 1 ? void 0 : docId;\n}\nfunction serializeTextNode(n, options) {\n const { needsMask, maskTextFn, rootId, cssCaptured } = options;\n const parent = index.parentNode(n);\n const parentTagName = parent && parent.tagName;\n let textContent2 = \"\";\n const isStyle = parentTagName === \"STYLE\" ? true : void 0;\n const isScript = parentTagName === \"SCRIPT\" ? true : void 0;\n if (isScript) {\n textContent2 = \"SCRIPT_PLACEHOLDER\";\n } else if (!cssCaptured) {\n textContent2 = index.textContent(n);\n if (isStyle && textContent2) {\n textContent2 = absolutifyURLs(textContent2, getHref(options.doc));\n }\n }\n if (!isStyle && !isScript && textContent2 && needsMask) {\n textContent2 = maskTextFn ? maskTextFn(textContent2, index.parentElement(n)) : textContent2.replace(/[\\S]/g, \"*\");\n }\n return {\n type: NodeType.Text,\n textContent: textContent2 || \"\",\n rootId\n };\n}\nfunction serializeElementNode(n, options) {\n const {\n doc,\n blockClass,\n blockSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n rootId\n } = options;\n const needBlock = _isBlockedElement(n, blockClass, blockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n const len = n.attributes.length;\n for (let i = 0; i < len; i++) {\n const attr = n.attributes[i];\n if (!ignoreAttribute(tagName, attr.name, attr.value)) {\n attributes[attr.name] = transformAttribute(\n doc,\n tagName,\n toLowerCase(attr.name),\n attr.value\n );\n }\n }\n if (tagName === \"link\" && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\n return s.href === n.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = stringifyStylesheet(stylesheet);\n }\n if (cssText) {\n delete attributes.rel;\n delete attributes.href;\n attributes._cssText = cssText;\n }\n }\n if (tagName === \"style\" && n.sheet) {\n let cssText = stringifyStylesheet(\n n.sheet\n );\n if (cssText) {\n if (n.childNodes.length > 1) {\n cssText = markCssSplits(cssText, n);\n }\n attributes._cssText = cssText;\n }\n }\n if ([\"input\", \"textarea\", \"select\"].includes(tagName)) {\n const value = n.value;\n const checked = n.checked;\n if (attributes.type !== \"radio\" && attributes.type !== \"checkbox\" && attributes.type !== \"submit\" && attributes.type !== \"button\" && value) {\n attributes.value = maskInputValue({\n element: n,\n type: getInputType(n),\n tagName,\n value,\n maskInputOptions,\n maskInputFn\n });\n } else if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === \"option\") {\n if (n.selected && !maskInputOptions[\"select\"]) {\n attributes.selected = true;\n } else {\n delete attributes.selected;\n }\n }\n if (tagName === \"dialog\" && n.open) {\n attributes.rr_open_mode = n.matches(\"dialog:modal\") ? \"modal\" : \"non-modal\";\n }\n if (tagName === \"canvas\" && recordCanvas) {\n if (n.__context === \"2d\") {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n }\n } else if (!(\"__context\" in n)) {\n const canvasDataURL = n.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n const blankCanvas = doc.createElement(\"canvas\");\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === \"img\" && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement(\"canvas\");\n canvasCtx = canvasService.getContext(\"2d\");\n }\n const image = n;\n const imageSrc = image.currentSrc || image.getAttribute(\"src\") || \"<unknown-src>\";\n const priorCrossOrigin = image.crossOrigin;\n const recordInlineImage = () => {\n image.removeEventListener(\"load\", recordInlineImage);\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n } catch (err) {\n if (image.crossOrigin !== \"anonymous\") {\n image.crossOrigin = \"anonymous\";\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n return;\n } else {\n console.warn(\n `Cannot inline img src=${imageSrc}! Error: ${err}`\n );\n }\n }\n if (image.crossOrigin === \"anonymous\") {\n priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute(\"crossorigin\");\n }\n };\n if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n }\n if ([\"audio\", \"video\"].includes(tagName)) {\n const mediaAttributes = attributes;\n mediaAttributes.rr_mediaState = n.paused ? \"paused\" : \"played\";\n mediaAttributes.rr_mediaCurrentTime = n.currentTime;\n mediaAttributes.rr_mediaPlaybackRate = n.playbackRate;\n mediaAttributes.rr_mediaMuted = n.muted;\n mediaAttributes.rr_mediaLoop = n.loop;\n mediaAttributes.rr_mediaVolume = n.volume;\n }\n if (!newlyAddedElement) {\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`\n };\n }\n if (tagName === \"iframe\" && !keepIframeSrcFn(attributes.src)) {\n if (!n.contentDocument) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n let isCustomElement;\n try {\n if (customElements.get(tagName)) isCustomElement = true;\n } catch (e) {\n }\n return {\n type: NodeType.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || void 0,\n needBlock,\n rootId,\n isCustom: isCustomElement\n };\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === void 0 || maybeAttr === null) {\n return \"\";\n } else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMDefaults(_slimDOMOptions) {\n if (_slimDOMOptions === true || _slimDOMOptions === \"all\") {\n return {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n // the following are off for slimDOMOptions === true,\n // as they destroy some (hidden) info:\n headMetaAuthorship: _slimDOMOptions === \"all\",\n headMetaDescKeywords: _slimDOMOptions === \"all\",\n headTitleMutations: _slimDOMOptions === \"all\"\n };\n } else if (_slimDOMOptions) {\n return _slimDOMOptions;\n }\n return {};\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n } else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script && // script tag\n (sn.tagName === \"script\" || // (module)preload link\n sn.tagName === \"link\" && (sn.attributes.rel === \"preload\" && sn.attributes.as === \"script\" || sn.attributes.rel === \"modulepreload\") || // prefetch link\n sn.tagName === \"link\" && sn.attributes.rel === \"prefetch\" && typeof sn.attributes.href === \"string\" && extractFileExtension(sn.attributes.href) === \"js\")) {\n return true;\n } else if (slimDOMOptions.headFavicon && (sn.tagName === \"link\" && sn.attributes.rel === \"shortcut icon\" || sn.tagName === \"meta\" && (lowerIfExists(sn.attributes.name).match(\n /^msapplication-tile(image|color)$/\n ) || lowerIfExists(sn.attributes.name) === \"application-name\" || lowerIfExists(sn.attributes.rel) === \"icon\" || lowerIfExists(sn.attributes.rel) === \"apple-touch-icon\" || lowerIfExists(sn.attributes.rel) === \"shortcut icon\"))) {\n return true;\n } else if (sn.tagName === \"meta\") {\n if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === \"pinterest\")) {\n return true;\n } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === \"robots\" || lowerIfExists(sn.attributes.name) === \"googlebot\" || lowerIfExists(sn.attributes.name) === \"bingbot\")) {\n return true;\n } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes[\"http-equiv\"] !== void 0) {\n return true;\n } else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === \"author\" || lowerIfExists(sn.attributes.name) === \"generator\" || lowerIfExists(sn.attributes.name) === \"framework\" || lowerIfExists(sn.attributes.name) === \"publisher\" || lowerIfExists(sn.attributes.name) === \"progid\" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n } else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === \"google-site-verification\" || lowerIfExists(sn.attributes.name) === \"yandex-verification\" || lowerIfExists(sn.attributes.name) === \"csrf-token\" || lowerIfExists(sn.attributes.name) === \"p:domain_verify\" || lowerIfExists(sn.attributes.name) === \"verify-v1\" || lowerIfExists(sn.attributes.name) === \"verification\" || lowerIfExists(sn.attributes.name) === \"shopify-checkout-api-token\")) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n skipChild = false,\n inlineStylesheet = true,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions = {},\n inlineImages = false,\n recordCanvas = false,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout = 5e3,\n onStylesheetLoad,\n stylesheetLoadTimeout = 5e3,\n keepIframeSrcFn = () => false,\n newlyAddedElement = false,\n cssCaptured = false\n } = options;\n let { needsMask } = options;\n let { preserveWhiteSpace = true } = options;\n if (!needsMask) {\n const checkAncestors = needsMask === void 0;\n needsMask = needMaskingText(\n n,\n maskTextClass,\n maskTextSelector,\n checkAncestors\n );\n }\n const _serializedNode = serializeNode(n, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n cssCaptured\n });\n if (!_serializedNode) {\n console.warn(n, \"not serialized\");\n return null;\n }\n let id;\n if (mirror2.hasNode(n)) {\n id = mirror2.getId(n);\n } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType.Text && !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, \"\").length) {\n id = IGNORED_NODE;\n } else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n mirror2.add(n, serializedNode);\n if (id === IGNORED_NODE) {\n return null;\n }\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n const shadowRootEl = index.shadowRoot(n);\n if (shadowRootEl && isNativeShadowDom(shadowRootEl))\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType.Document || serializedNode.type === NodeType.Element) && recordChild) {\n if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType.Element && serializedNode.tagName === \"head\") {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n cssCaptured: false\n };\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"textarea\" && serializedNode.attributes.value !== void 0) ;\n else {\n if (serializedNode.type === NodeType.Element && serializedNode.attributes._cssText !== void 0 && typeof serializedNode.attributes._cssText === \"string\") {\n bypassOptions.cssCaptured = true;\n }\n for (const childN of Array.from(index.childNodes(n))) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n let shadowRootEl = null;\n if (isElement(n) && (shadowRootEl = index.shadowRoot(n))) {\n for (const childN of Array.from(index.childNodes(shadowRootEl))) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n isNativeShadowDom(shadowRootEl) && (serializedChildNode.isShadow = true);\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n const parent = index.parentNode(n);\n if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"iframe\") {\n onceIframeLoaded(\n n,\n () => {\n const iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn\n });\n if (serializedIframeNode) {\n onIframeLoad(\n n,\n serializedIframeNode\n );\n }\n }\n },\n iframeLoadTimeout\n );\n }\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"link\" && typeof serializedNode.attributes.rel === \"string\" && (serializedNode.attributes.rel === \"stylesheet\" || serializedNode.attributes.rel === \"preload\" && typeof serializedNode.attributes.href === \"string\" && extractFileExtension(serializedNode.attributes.href) === \"css\")) {\n onceStylesheetLoaded(\n n,\n () => {\n if (onStylesheetLoad) {\n const serializedLinkNode = serializeNodeWithId(n, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn\n });\n if (serializedLinkNode) {\n onStylesheetLoad(\n n,\n serializedLinkNode\n );\n }\n }\n },\n stylesheetLoadTimeout\n );\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n const {\n mirror: mirror2 = new Mirror(),\n blockClass = \"rr-block\",\n blockSelector = null,\n maskTextClass = \"rr-mask\",\n maskTextSelector = null,\n inlineStylesheet = true,\n inlineImages = false,\n recordCanvas = false,\n maskAllInputs = false,\n maskTextFn,\n maskInputFn,\n slimDOM = false,\n dataURLOptions,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn = () => false\n } = options;\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true\n } : maskAllInputs === false ? {\n password: true\n } : maskAllInputs;\n const slimDOMOptions = slimDOMDefaults(slimDOM);\n return serializeNodeWithId(n, {\n doc: n,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n newlyAddedElement: false\n });\n}\nclass BaseRRNode {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n constructor(..._args) {\n __publicField(this, \"parentElement\", null);\n __publicField(this, \"parentNode\", null);\n __publicField(this, \"ownerDocument\");\n __publicField(this, \"firstChild\", null);\n __publicField(this, \"lastChild\", null);\n __publicField(this, \"previousSibling\", null);\n __publicField(this, \"nextSibling\", null);\n __publicField(this, \"ELEMENT_NODE\", 1);\n __publicField(this, \"TEXT_NODE\", 3);\n // corresponding nodeType value of standard HTML Node\n __publicField(this, \"nodeType\");\n __publicField(this, \"nodeName\");\n __publicField(this, \"RRNodeType\");\n }\n get childNodes() {\n const childNodes2 = [];\n let childIterator = this.firstChild;\n while (childIterator) {\n childNodes2.push(childIterator);\n childIterator = childIterator.nextSibling;\n }\n return childNodes2;\n }\n contains(node) {\n if (!(node instanceof BaseRRNode)) return false;\n else if (node.ownerDocument !== this.ownerDocument) return false;\n else if (node === this) return true;\n while (node.parentNode) {\n if (node.parentNode === this) return true;\n node = node.parentNode;\n }\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n appendChild(_newChild) {\n throw new Error(\n `RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n insertBefore(_newChild, _refChild) {\n throw new Error(\n `RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n removeChild(_node) {\n throw new Error(\n `RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n toString() {\n return \"RRNode\";\n }\n}\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = \"Please stop import mirror directly. Instead of that,\\r\\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\\r\\nor you can use record.mirror to access the mirror instance during recording.\";\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n};\nif (typeof window !== \"undefined\" && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === \"map\") {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n}\nfunction throttle(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function(...args) {\n const now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n const remaining = wait - (now - previous);\n const context = this;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(\n target,\n key,\n isRevoked ? d : {\n set(value) {\n setTimeout(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n }\n }\n );\n return () => hookSetter(target, key, original || {}, true);\n}\nfunction getWindowScroll(win) {\n var _a2, _b, _c, _d;\n const doc = win.document;\n return {\n left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc.documentElement.scrollLeft || (doc == null ? void 0 : doc.body) && ((_a2 = index.parentElement(doc.body)) == null ? void 0 : _a2.scrollLeft) || ((_b = doc == null ? void 0 : doc.body) == null ? void 0 : _b.scrollLeft) || 0,\n top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : (doc == null ? void 0 : doc.documentElement.scrollTop) || (doc == null ? void 0 : doc.body) && ((_c = index.parentElement(doc.body)) == null ? void 0 : _c.scrollTop) || ((_d = doc == null ? void 0 : doc.body) == null ? void 0 : _d.scrollTop) || 0\n };\n}\nfunction getWindowHeight() {\n return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;\n}\nfunction getWindowWidth() {\n return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;\n}\nfunction closestElementOfNode(node) {\n if (!node) {\n return null;\n }\n const el = node.nodeType === node.ELEMENT_NODE ? node : index.parentElement(node);\n return el;\n}\nfunction isBlocked(node, blockClass, blockSelector, checkAncestors) {\n if (!node) {\n return false;\n }\n const el = closestElementOfNode(node);\n if (!el) {\n return false;\n }\n try {\n if (typeof blockClass === \"string\") {\n if (el.classList.contains(blockClass)) return true;\n if (checkAncestors && el.closest(\".\" + blockClass) !== null) return true;\n } else {\n if (classMatchesRegex(el, blockClass, checkAncestors)) return true;\n }\n } catch (e) {\n }\n if (blockSelector) {\n if (el.matches(blockSelector)) return true;\n if (checkAncestors && el.closest(blockSelector) !== null) return true;\n }\n return false;\n}\nfunction isSerialized(n, mirror2) {\n return mirror2.getId(n) !== -1;\n}\nfunction isIgnored(n, mirror2, slimDOMOptions) {\n if (n.tagName === \"TITLE\" && slimDOMOptions.headTitleMutations) {\n return true;\n }\n return mirror2.getId(n) === IGNORED_NODE;\n}\nfunction isAncestorRemoved(target, mirror2) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror2.getId(target);\n if (!mirror2.has(id)) {\n return true;\n }\n const parent = index.parentNode(target);\n if (parent && parent.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!parent) {\n return true;\n }\n return isAncestorRemoved(parent, mirror2);\n}\nfunction legacy_isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n if (\"NodeList\" in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype.forEach;\n }\n if (\"DOMTokenList\" in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype.forEach;\n }\n}\nfunction isSerializedIframe(n, mirror2) {\n return Boolean(n.nodeName === \"IFRAME\" && mirror2.getMeta(n));\n}\nfunction isSerializedStylesheet(n, mirror2) {\n return Boolean(\n n.nodeName === \"LINK\" && n.nodeType === n.ELEMENT_NODE && n.getAttribute && n.getAttribute(\"rel\") === \"stylesheet\" && mirror2.getMeta(n)\n );\n}\nfunction hasShadowRoot(n) {\n if (!n) return false;\n if (n instanceof BaseRRNode && \"shadowRoot\" in n) {\n return Boolean(n.shadowRoot);\n }\n return Boolean(index.shadowRoot(n));\n}\nclass StyleSheetMirror {\n constructor() {\n __publicField(this, \"id\", 1);\n __publicField(this, \"styleIDMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"idStyleMap\", /* @__PURE__ */ new Map());\n }\n getId(stylesheet) {\n return this.styleIDMap.get(stylesheet) ?? -1;\n }\n has(stylesheet) {\n return this.styleIDMap.has(stylesheet);\n }\n /**\n * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.\n */\n add(stylesheet, id) {\n if (this.has(stylesheet)) return this.getId(stylesheet);\n let newId;\n if (id === void 0) {\n newId = this.id++;\n } else newId = id;\n this.styleIDMap.set(stylesheet, newId);\n this.idStyleMap.set(newId, stylesheet);\n return newId;\n }\n getStyle(id) {\n return this.idStyleMap.get(id) || null;\n }\n reset() {\n this.styleIDMap = /* @__PURE__ */ new WeakMap();\n this.idStyleMap = /* @__PURE__ */ new Map();\n this.id = 1;\n }\n generateId() {\n return this.id++;\n }\n}\nfunction getShadowHost(n) {\n var _a2;\n let shadowHost = null;\n if (\"getRootNode\" in n && ((_a2 = index.getRootNode(n)) == null ? void 0 : _a2.nodeType) === Node.DOCUMENT_FRAGMENT_NODE && index.host(index.getRootNode(n)))\n shadowHost = index.host(index.getRootNode(n));\n return shadowHost;\n}\nfunction getRootShadowHost(n) {\n let rootShadowHost = n;\n let shadowHost;\n while (shadowHost = getShadowHost(rootShadowHost))\n rootShadowHost = shadowHost;\n return rootShadowHost;\n}\nfunction shadowHostInDom(n) {\n const doc = index.ownerDocument(n);\n if (!doc) return false;\n const shadowHost = getRootShadowHost(n);\n return index.contains(doc, shadowHost);\n}\nfunction inDom(n) {\n const doc = index.ownerDocument(n);\n if (!doc) return false;\n return index.contains(doc, n) || shadowHostInDom(n);\n}\nfunction isNodeInLinkedList(n) {\n return \"__ln\" in n;\n}\nclass DoubleLinkedList {\n constructor() {\n __publicField(this, \"length\", 0);\n __publicField(this, \"head\", null);\n __publicField(this, \"tail\", null);\n }\n get(position) {\n if (position >= this.length) {\n throw new Error(\"Position outside of list range\");\n }\n let current = this.head;\n for (let index2 = 0; index2 < position; index2++) {\n current = (current == null ? void 0 : current.next) || null;\n }\n return current;\n }\n addNode(n) {\n const node = {\n value: n,\n previous: null,\n next: null\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n const current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n } else if (n.nextSibling && isNodeInLinkedList(n.nextSibling) && n.nextSibling.__ln.previous) {\n const current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n } else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n if (node.next === null) {\n this.tail = node;\n }\n this.length++;\n }\n removeNode(n) {\n const current = n.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n } else {\n this.tail = null;\n }\n } else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n } else {\n this.tail = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nclass MutationBuffer {\n constructor() {\n __publicField(this, \"frozen\", false);\n __publicField(this, \"locked\", false);\n __publicField(this, \"texts\", []);\n __publicField(this, \"attributes\", []);\n __publicField(this, \"attributeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"removes\", []);\n __publicField(this, \"mapRemoves\", []);\n __publicField(this, \"movedMap\", {});\n /**\n * the browser MutationObserver emits multiple mutations after\n * a delay for performance reasons, making tracing added nodes hard\n * in our `processMutations` callback function.\n * For example, if we append an element el_1 into body, and then append\n * another element el_2 into el_1, these two mutations may be passed to the\n * callback function together when the two operations were done.\n * Generally we need to trace child nodes of newly added nodes, but in this\n * case if we count el_2 as el_1's child node in the first mutation record,\n * then we will count el_2 again in the second mutation record which was\n * duplicated.\n * To avoid of duplicate counting added nodes, we use a Set to store\n * added nodes and its child nodes during iterate mutation records. Then\n * collect added nodes from the Set which have no duplicate copy. But\n * this also causes newly added nodes will not be serialized with id ASAP,\n * which means all the id related calculation should be lazy too.\n */\n __publicField(this, \"addedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"movedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"droppedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"removesSubTreeCache\", /* @__PURE__ */ new Set());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"blockClass\");\n __publicField(this, \"blockSelector\");\n __publicField(this, \"maskTextClass\");\n __publicField(this, \"maskTextSelector\");\n __publicField(this, \"inlineStylesheet\");\n __publicField(this, \"maskInputOptions\");\n __publicField(this, \"maskTextFn\");\n __publicField(this, \"maskInputFn\");\n __publicField(this, \"keepIframeSrcFn\");\n __publicField(this, \"recordCanvas\");\n __publicField(this, \"inlineImages\");\n __publicField(this, \"slimDOMOptions\");\n __publicField(this, \"dataURLOptions\");\n __publicField(this, \"doc\");\n __publicField(this, \"mirror\");\n __publicField(this, \"iframeManager\");\n __publicField(this, \"stylesheetManager\");\n __publicField(this, \"shadowDomManager\");\n __publicField(this, \"canvasManager\");\n __publicField(this, \"processedNodeManager\");\n __publicField(this, \"unattachedDoc\");\n __publicField(this, \"processMutations\", (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n });\n __publicField(this, \"emit\", () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addedIds = /* @__PURE__ */ new Set();\n const addList = new DoubleLinkedList();\n const getNextId = (n) => {\n let ns = n;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n) => {\n const parent = index.parentNode(n);\n if (!parent || !inDom(n)) {\n return;\n }\n let cssCaptured = false;\n if (n.nodeType === Node.TEXT_NODE) {\n const parentTag = parent.tagName;\n if (parentTag === \"TEXTAREA\") {\n return;\n } else if (parentTag === \"STYLE\" && this.addedSet.has(parent)) {\n cssCaptured = true;\n }\n }\n const parentId = isShadowRoot(parent) ? this.mirror.getId(getShadowHost(n)) : this.mirror.getId(parent);\n const nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n const sn = serializeNodeWithId(n, {\n doc: this.doc,\n mirror: this.mirror,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n maskTextClass: this.maskTextClass,\n maskTextSelector: this.maskTextSelector,\n skipChild: true,\n newlyAddedElement: true,\n inlineStylesheet: this.inlineStylesheet,\n maskInputOptions: this.maskInputOptions,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n dataURLOptions: this.dataURLOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isSerializedIframe(currentN, this.mirror)) {\n this.iframeManager.addIframe(currentN);\n }\n if (isSerializedStylesheet(currentN, this.mirror)) {\n this.stylesheetManager.trackLinkElement(\n currentN\n );\n }\n if (hasShadowRoot(n)) {\n this.shadowDomManager.addShadowRoot(index.shadowRoot(n), this.doc);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n this.iframeManager.attachIframe(iframe, childSn);\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n onStylesheetLoad: (link, childSn) => {\n this.stylesheetManager.attachLinkElement(link, childSn);\n },\n cssCaptured\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn\n });\n addedIds.add(sn.id);\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n of this.movedSet) {\n if (isParentRemoved(this.removesSubTreeCache, n, this.mirror) && !this.movedSet.has(index.parentNode(n))) {\n continue;\n }\n pushAdd(n);\n }\n for (const n of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n) && !isParentRemoved(this.removesSubTreeCache, n, this.mirror)) {\n pushAdd(n);\n } else if (isAncestorInSet(this.movedSet, n)) {\n pushAdd(n);\n } else {\n this.droppedSet.add(n);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(index.parentNode(candidate.value));\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n let tailNode = addList.tail;\n while (tailNode) {\n const _node = tailNode;\n tailNode = tailNode.previous;\n if (_node) {\n const parentId = this.mirror.getId(index.parentNode(_node.value));\n const nextId = getNextId(_node.value);\n if (nextId === -1) continue;\n else if (parentId !== -1) {\n node = _node;\n break;\n } else {\n const unhandledNode = _node.value;\n const parent = index.parentNode(unhandledNode);\n if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n const shadowHost = index.host(parent);\n const parentId2 = this.mirror.getId(shadowHost);\n if (parentId2 !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts.map((text) => {\n const n = text.node;\n const parent = index.parentNode(n);\n if (parent && parent.tagName === \"TEXTAREA\") {\n this.genTextAreaValueMutation(parent);\n }\n return {\n id: this.mirror.getId(n),\n value: text.value\n };\n }).filter((text) => !addedIds.has(text.id)).filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes.map((attribute) => {\n const { attributes } = attribute;\n if (typeof attributes.style === \"string\") {\n const diffAsStr = JSON.stringify(attribute.styleDiff);\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\n if (diffAsStr.length < attributes.style.length) {\n if ((diffAsStr + unchangedAsStr).split(\"var(\").length === attributes.style.split(\"var(\").length) {\n attributes.style = attribute.styleDiff;\n }\n }\n }\n return {\n id: this.mirror.getId(attribute.node),\n attributes\n };\n }).filter((attribute) => !addedIds.has(attribute.id)).filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds\n };\n if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.attributeMap = /* @__PURE__ */ new WeakMap();\n this.removes = [];\n this.addedSet = /* @__PURE__ */ new Set();\n this.movedSet = /* @__PURE__ */ new Set();\n this.droppedSet = /* @__PURE__ */ new Set();\n this.removesSubTreeCache = /* @__PURE__ */ new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n });\n __publicField(this, \"genTextAreaValueMutation\", (textarea) => {\n let item = this.attributeMap.get(textarea);\n if (!item) {\n item = {\n node: textarea,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {}\n };\n this.attributes.push(item);\n this.attributeMap.set(textarea, item);\n }\n const value = Array.from(\n index.childNodes(textarea),\n (cn) => index.textContent(cn) || \"\"\n ).join(\"\");\n item.attributes.value = maskInputValue({\n element: textarea,\n maskInputOptions: this.maskInputOptions,\n tagName: textarea.tagName,\n type: getInputType(textarea),\n value,\n maskInputFn: this.maskInputFn\n });\n });\n __publicField(this, \"processMutation\", (m) => {\n if (isIgnored(m.target, this.mirror, this.slimDOMOptions)) {\n return;\n }\n switch (m.type) {\n case \"characterData\": {\n const value = index.textContent(m.target);\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) && value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(\n m.target,\n this.maskTextClass,\n this.maskTextSelector,\n true\n // checkAncestors\n ) && value ? this.maskTextFn ? this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\\S]/g, \"*\") : value,\n node: m.target\n });\n }\n break;\n }\n case \"attributes\": {\n const target = m.target;\n let attributeName = m.attributeName;\n let value = m.target.getAttribute(attributeName);\n if (attributeName === \"value\") {\n const type = getInputType(target);\n value = maskInputValue({\n element: target,\n maskInputOptions: this.maskInputOptions,\n tagName: target.tagName,\n type,\n value,\n maskInputFn: this.maskInputFn\n });\n }\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || value === m.oldValue) {\n return;\n }\n let item = this.attributeMap.get(m.target);\n if (target.tagName === \"IFRAME\" && attributeName === \"src\" && !this.keepIframeSrcFn(value)) {\n if (!target.contentDocument) {\n attributeName = \"rr_src\";\n } else {\n return;\n }\n }\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {}\n };\n this.attributes.push(item);\n this.attributeMap.set(m.target, item);\n }\n if (attributeName === \"type\" && target.tagName === \"INPUT\" && (m.oldValue || \"\").toLowerCase() === \"password\") {\n target.setAttribute(\"data-rr-is-password\", \"true\");\n }\n if (!ignoreAttribute(target.tagName, attributeName)) {\n item.attributes[attributeName] = transformAttribute(\n this.doc,\n toLowerCase(target.tagName),\n toLowerCase(attributeName),\n value\n );\n if (attributeName === \"style\") {\n if (!this.unattachedDoc) {\n try {\n this.unattachedDoc = document.implementation.createHTMLDocument();\n } catch (e) {\n this.unattachedDoc = this.doc;\n }\n }\n const old = this.unattachedDoc.createElement(\"span\");\n if (m.oldValue) {\n old.setAttribute(\"style\", m.oldValue);\n }\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === \"\") {\n item.styleDiff[pname] = newValue;\n } else {\n item.styleDiff[pname] = [newValue, newPriority];\n }\n } else {\n item._unchangedStyles[pname] = [newValue, newPriority];\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === \"\") {\n item.styleDiff[pname] = false;\n }\n }\n } else if (attributeName === \"open\" && target.tagName === \"DIALOG\") {\n if (target.matches(\"dialog:modal\")) {\n item.attributes[\"rr_open_mode\"] = \"modal\";\n } else {\n item.attributes[\"rr_open_mode\"] = \"non-modal\";\n }\n }\n }\n break;\n }\n case \"childList\": {\n if (isBlocked(m.target, this.blockClass, this.blockSelector, true))\n return;\n if (m.target.tagName === \"TEXTAREA\") {\n this.genTextAreaValueMutation(m.target);\n return;\n }\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n m.removedNodes.forEach((n) => {\n const nodeId = this.mirror.getId(n);\n const parentId = isShadowRoot(m.target) ? this.mirror.getId(index.host(m.target)) : this.mirror.getId(m.target);\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || isIgnored(n, this.mirror, this.slimDOMOptions) || !isSerialized(n, this.mirror)) {\n return;\n }\n if (this.addedSet.has(n)) {\n deepDelete(this.addedSet, n);\n this.droppedSet.add(n);\n } else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n) && this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n);\n } else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0\n });\n processRemoves(n, this.removesSubTreeCache);\n }\n this.mapRemoves.push(n);\n });\n break;\n }\n }\n });\n /**\n * Make sure you check if `n`'s parent is blocked before calling this function\n * */\n __publicField(this, \"genAdds\", (n, target) => {\n if (this.processedNodeManager.inOtherBuffer(n, this)) return;\n if (this.addedSet.has(n) || this.movedSet.has(n)) return;\n if (this.mirror.hasNode(n)) {\n if (isIgnored(n, this.mirror, this.slimDOMOptions)) {\n return;\n }\n this.movedSet.add(n);\n let targetId = null;\n if (target && this.mirror.hasNode(target)) {\n targetId = this.mirror.getId(target);\n }\n if (targetId && targetId !== -1) {\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\n }\n } else {\n this.addedSet.add(n);\n this.droppedSet.delete(n);\n }\n if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {\n index.childNodes(n).forEach((childN) => this.genAdds(childN));\n if (hasShadowRoot(n)) {\n index.childNodes(index.shadowRoot(n)).forEach((childN) => {\n this.processedNodeManager.add(childN, this);\n this.genAdds(childN, n);\n });\n }\n }\n });\n }\n init(options) {\n [\n \"mutationCb\",\n \"blockClass\",\n \"blockSelector\",\n \"maskTextClass\",\n \"maskTextSelector\",\n \"inlineStylesheet\",\n \"maskInputOptions\",\n \"maskTextFn\",\n \"maskInputFn\",\n \"keepIframeSrcFn\",\n \"recordCanvas\",\n \"inlineImages\",\n \"slimDOMOptions\",\n \"dataURLOptions\",\n \"doc\",\n \"mirror\",\n \"iframeManager\",\n \"stylesheetManager\",\n \"shadowDomManager\",\n \"canvasManager\",\n \"processedNodeManager\"\n ].forEach((key) => {\n this[key] = options[key];\n });\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.canvasManager.reset();\n }\n}\nfunction deepDelete(addsSet, n) {\n addsSet.delete(n);\n index.childNodes(n).forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction processRemoves(n, cache) {\n const queue = [n];\n while (queue.length) {\n const next = queue.pop();\n if (cache.has(next)) continue;\n cache.add(next);\n index.childNodes(next).forEach((n2) => queue.push(n2));\n }\n return;\n}\nfunction isParentRemoved(removes, n, mirror2) {\n if (removes.size === 0) return false;\n return _isParentRemoved(removes, n);\n}\nfunction _isParentRemoved(removes, n, _mirror2) {\n const node = index.parentNode(n);\n if (!node) return false;\n return removes.has(node);\n}\nfunction isAncestorInSet(set, n) {\n if (set.size === 0) return false;\n return _isAncestorInSet(set, n);\n}\nfunction _isAncestorInSet(set, n) {\n const parent = index.parentNode(n);\n if (!parent) {\n return false;\n }\n if (set.has(parent)) {\n return true;\n }\n return _isAncestorInSet(set, parent);\n}\nlet errorHandler;\nfunction registerErrorHandler(handler) {\n errorHandler = handler;\n}\nfunction unregisterErrorHandler() {\n errorHandler = void 0;\n}\nconst callbackWrapper = (cb) => {\n if (!errorHandler) {\n return cb;\n }\n const rrwebWrapped = (...rest) => {\n try {\n return cb(...rest);\n } catch (error) {\n if (errorHandler && errorHandler(error) === true) {\n return;\n }\n throw error;\n }\n };\n return rrwebWrapped;\n};\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if (\"composedPath\" in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n } else if (\"path\" in event && event.path.length) {\n return event.path[0];\n }\n } catch {\n }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n const [ObserverCtor, iframeCleanup] = mutationObserverCtor();\n const observer = new ObserverCtor(\n callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer))\n );\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true\n });\n return [observer, iframeCleanup];\n}\nfunction initMoveObserver({\n mousemoveCb,\n sampling,\n doc,\n mirror: mirror2\n}) {\n if (sampling.mousemove === false) {\n return () => {\n };\n }\n const threshold = typeof sampling.mousemove === \"number\" ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === \"number\" ? sampling.mousemoveCallback : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle(\n callbackWrapper(\n (source) => {\n const totalOffset = Date.now() - timeBaseline;\n mousemoveCb(\n positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }),\n source\n );\n positions = [];\n timeBaseline = null;\n }\n ),\n callbackThreshold\n );\n const updatePosition = callbackWrapper(\n throttle(\n callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;\n if (!timeBaseline) {\n timeBaseline = nowTimestamp();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror2.getId(target),\n timeOffset: nowTimestamp() - timeBaseline\n });\n wrappedCb(\n typeof DragEvent !== \"undefined\" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove\n );\n }),\n threshold,\n {\n trailing: false\n }\n )\n );\n const handlers = [\n on(\"mousemove\", updatePosition, doc),\n on(\"touchmove\", updatePosition, doc),\n on(\"drag\", updatePosition, doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({\n mouseInteractionCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n sampling\n}) {\n if (sampling.mouseInteraction === false) {\n return () => {\n };\n }\n const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;\n const handlers = [];\n let currentPointerType = null;\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n let pointerType = null;\n let thisEventKey = eventKey;\n if (\"pointerType\" in event) {\n switch (event.pointerType) {\n case \"mouse\":\n pointerType = PointerTypes.Mouse;\n break;\n case \"touch\":\n pointerType = PointerTypes.Touch;\n break;\n case \"pen\":\n pointerType = PointerTypes.Pen;\n break;\n }\n if (pointerType === PointerTypes.Touch) {\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\n thisEventKey = \"TouchStart\";\n } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\n thisEventKey = \"TouchEnd\";\n }\n } else if (pointerType === PointerTypes.Pen) ;\n } else if (legacy_isTouchEvent(event)) {\n pointerType = PointerTypes.Touch;\n }\n if (pointerType !== null) {\n currentPointerType = pointerType;\n if (thisEventKey.startsWith(\"Touch\") && pointerType === PointerTypes.Touch || thisEventKey.startsWith(\"Mouse\") && pointerType === PointerTypes.Mouse) {\n pointerType = null;\n }\n } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n pointerType = currentPointerType;\n currentPointerType = null;\n }\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n const id = mirror2.getId(target);\n const { clientX, clientY } = e;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[thisEventKey],\n id,\n x: clientX,\n y: clientY,\n ...pointerType !== null && { pointerType }\n });\n };\n };\n Object.keys(MouseInteractions).filter(\n (key) => Number.isNaN(Number(key)) && !key.endsWith(\"_Departed\") && disableMap[key] !== false\n ).forEach((eventKey) => {\n let eventName = toLowerCase(eventKey);\n const handler = getHandler(eventKey);\n if (window.PointerEvent) {\n switch (MouseInteractions[eventKey]) {\n case MouseInteractions.MouseDown:\n case MouseInteractions.MouseUp:\n eventName = eventName.replace(\n \"mouse\",\n \"pointer\"\n );\n break;\n case MouseInteractions.TouchStart:\n case MouseInteractions.TouchEnd:\n return;\n }\n }\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({\n scrollCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n sampling\n}) {\n const updatePosition = callbackWrapper(\n throttle(\n callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n if (!target || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n const id = mirror2.getId(target);\n if (target === doc && doc.defaultView) {\n const scrollLeftTop = getWindowScroll(doc.defaultView);\n scrollCb({\n id,\n x: scrollLeftTop.left,\n y: scrollLeftTop.top\n });\n } else {\n scrollCb({\n id,\n x: target.scrollLeft,\n y: target.scrollTop\n });\n }\n }),\n sampling.scroll || 100\n )\n );\n return on(\"scroll\", updatePosition, doc);\n}\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = callbackWrapper(\n throttle(\n callbackWrapper(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n viewportResizeCb({\n width: Number(width),\n height: Number(height)\n });\n lastH = height;\n lastW = width;\n }\n }),\n 200\n )\n );\n return on(\"resize\", updateDimension, win);\n}\nconst INPUT_TAGS = [\"INPUT\", \"TEXTAREA\", \"SELECT\"];\nconst lastInputValueMap = /* @__PURE__ */ new WeakMap();\nfunction initInputObserver({\n inputCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n ignoreClass,\n ignoreSelector,\n maskInputOptions,\n maskInputFn,\n sampling,\n userTriggeredOnInput\n}) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const userTriggered = event.isTrusted;\n const tagName = target && target.tagName;\n if (target && tagName === \"OPTION\") {\n target = index.parentElement(target);\n }\n if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) {\n return;\n }\n let text = target.value;\n let isChecked = false;\n const type = getInputType(target) || \"\";\n if (type === \"radio\" || type === \"checkbox\") {\n isChecked = target.checked;\n } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {\n text = maskInputValue({\n element: target,\n maskInputOptions,\n tagName,\n type,\n value: text,\n maskInputFn\n });\n }\n cbWithDedup(\n target,\n userTriggeredOnInput ? { text, isChecked, userTriggered } : { text, isChecked }\n );\n const name = target.name;\n if (type === \"radio\" && name && isChecked) {\n doc.querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`).forEach((el) => {\n if (el !== target) {\n const text2 = el.value;\n cbWithDedup(\n el,\n userTriggeredOnInput ? { text: text2, isChecked: !isChecked, userTriggered: false } : { text: text2, isChecked: !isChecked }\n );\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue || lastInputValue.text !== v.text || lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n const id = mirror2.getId(target);\n callbackWrapper(inputCb)({\n ...v,\n id\n });\n }\n }\n const events = sampling.input === \"last\" ? [\"change\"] : [\"input\", \"change\"];\n const handlers = events.map(\n (eventName) => on(eventName, callbackWrapper(eventHandler), doc)\n );\n const currentWindow = doc.defaultView;\n if (!currentWindow) {\n return () => {\n handlers.forEach((h) => h());\n };\n }\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(\n currentWindow.HTMLInputElement.prototype,\n \"value\"\n );\n const hookProperties = [\n [currentWindow.HTMLInputElement.prototype, \"value\"],\n [currentWindow.HTMLInputElement.prototype, \"checked\"],\n [currentWindow.HTMLSelectElement.prototype, \"value\"],\n [currentWindow.HTMLTextAreaElement.prototype, \"value\"],\n // Some UI library use selectedIndex to set select value\n [currentWindow.HTMLSelectElement.prototype, \"selectedIndex\"],\n [currentWindow.HTMLOptionElement.prototype, \"selected\"]\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(\n ...hookProperties.map(\n (p) => hookSetter(\n p[0],\n p[1],\n {\n set() {\n callbackWrapper(eventHandler)({\n target: this,\n isTrusted: false\n // userTriggered to false as this could well be programmatic\n });\n }\n },\n false,\n currentWindow\n )\n )\n );\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if (hasNestedCSSRule(\"CSSGroupingRule\") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule(\"CSSMediaRule\") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule(\"CSSSupportsRule\") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule(\"CSSConditionRule\") && childRule.parentRule instanceof CSSConditionRule) {\n const rules = Array.from(\n childRule.parentRule.cssRules\n );\n const index2 = rules.indexOf(childRule);\n pos.unshift(index2);\n return recurse(childRule.parentRule, pos);\n } else if (childRule.parentStyleSheet) {\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\n const index2 = rules.indexOf(childRule);\n pos.unshift(index2);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction getIdAndStyleId(sheet, mirror2, styleMirror) {\n let id, styleId;\n if (!sheet) return {};\n if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);\n else styleId = styleMirror.getId(sheet);\n return {\n styleId,\n id\n };\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => {\n };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [{ rule, index: index2 }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2 = this.cssRules.length) {\n const rule = `${selector} { ${styleBlock} }`;\n return win.CSSStyleSheet.prototype.insertRule.apply(this, [rule, index2]);\n };\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [{ index: index2 }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n win.CSSStyleSheet.prototype.removeRule = function(index2) {\n return win.CSSStyleSheet.prototype.deleteRule.apply(this, [index2]);\n };\n let replace;\n if (win.CSSStyleSheet.prototype.replace) {\n replace = win.CSSStyleSheet.prototype.replace;\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replace: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n let replaceSync;\n if (win.CSSStyleSheet.prototype.replaceSync) {\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replaceSync: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule(\"CSSGroupingRule\")) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n } else {\n if (canMonkeyPatchNestedCSSRule(\"CSSMediaRule\")) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSConditionRule\")) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSSupportsRule\")) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n insertRule: type.prototype.insertRule,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n deleteRule: type.prototype.deleteRule\n };\n type.prototype.insertRule = new Proxy(\n unmodifiedFunctions[typeKey].insertRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index2 || 0\n // defaults to 0\n ]\n }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n type.prototype.deleteRule = new Proxy(\n unmodifiedFunctions[typeKey].deleteRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index2] }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n replace && (win.CSSStyleSheet.prototype.replace = replace);\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initAdoptedStyleSheetObserver({\n mirror: mirror2,\n stylesheetManager\n}, host2) {\n var _a2, _b, _c;\n let hostId = null;\n if (host2.nodeName === \"#document\") hostId = mirror2.getId(host2);\n else hostId = mirror2.getId(index.host(host2));\n const patchTarget = host2.nodeName === \"#document\" ? (_a2 = host2.defaultView) == null ? void 0 : _a2.Document : (_c = (_b = host2.ownerDocument) == null ? void 0 : _b.defaultView) == null ? void 0 : _c.ShadowRoot;\n const originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(\n patchTarget == null ? void 0 : patchTarget.prototype,\n \"adoptedStyleSheets\"\n ) : void 0;\n if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor)\n return () => {\n };\n Object.defineProperty(host2, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get() {\n var _a3;\n return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);\n },\n set(sheets) {\n var _a3;\n const result = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);\n if (hostId !== null && hostId !== -1) {\n try {\n stylesheetManager.adoptStyleSheets(sheets, hostId);\n } catch (e) {\n }\n }\n return result;\n }\n });\n return callbackWrapper(() => {\n Object.defineProperty(host2, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n get: originalPropertyDescriptor.get,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n set: originalPropertyDescriptor.set\n });\n });\n}\nfunction initStyleDeclarationObserver({\n styleDeclarationCb,\n mirror: mirror2,\n ignoreCSSAttributes,\n stylesheetManager\n}, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n var _a2;\n const [property, value, priority] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return setProperty.apply(thisArg, [property, value, priority]);\n }\n const { id, styleId } = getIdAndStyleId(\n (_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n set: {\n property,\n value,\n priority\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n var _a2;\n const [property] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return removeProperty.apply(thisArg, [property]);\n }\n const { id, styleId } = getIdAndStyleId(\n (_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n remove: {\n property\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({\n mediaInteractionCb,\n blockClass,\n blockSelector,\n mirror: mirror2,\n sampling,\n doc\n}) {\n const handler = callbackWrapper(\n (type) => throttle(\n callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n const { currentTime, volume, muted, playbackRate, loop } = target;\n mediaInteractionCb({\n type,\n id: mirror2.getId(target),\n currentTime,\n volume,\n muted,\n playbackRate,\n loop\n });\n }),\n sampling.media || 500\n )\n );\n const handlers = [\n on(\"play\", handler(MediaInteractions.Play), doc),\n on(\"pause\", handler(MediaInteractions.Pause), doc),\n on(\"seeked\", handler(MediaInteractions.Seeked), doc),\n on(\"volumechange\", handler(MediaInteractions.VolumeChange), doc),\n on(\"ratechange\", handler(MediaInteractions.RateChange), doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => {\n };\n }\n const handlers = [];\n const fontMap = /* @__PURE__ */ new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace(family, source, descriptors) {\n const fontFace = new originalFontFace(family, source, descriptors);\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== \"string\",\n descriptors,\n fontSource: typeof source === \"string\" ? source : JSON.stringify(Array.from(new Uint8Array(source)))\n });\n return fontFace;\n };\n const restoreHandler = patch(\n doc.fonts,\n \"add\",\n function(original) {\n return function(fontFace) {\n setTimeout(\n callbackWrapper(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }),\n 0\n );\n return original.apply(this, [fontFace]);\n };\n }\n );\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initSelectionObserver(param) {\n const { doc, mirror: mirror2, blockClass, blockSelector, selectionCb } = param;\n let collapsed = true;\n const updateSelection = callbackWrapper(() => {\n const selection = doc.getSelection();\n if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;\n collapsed = selection.isCollapsed || false;\n const ranges = [];\n const count = selection.rangeCount || 0;\n for (let i = 0; i < count; i++) {\n const range = selection.getRangeAt(i);\n const { startContainer, startOffset, endContainer, endOffset } = range;\n const blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);\n if (blocked) continue;\n ranges.push({\n start: mirror2.getId(startContainer),\n startOffset,\n end: mirror2.getId(endContainer),\n endOffset\n });\n }\n selectionCb({ ranges });\n });\n updateSelection();\n return on(\"selectionchange\", updateSelection);\n}\nfunction initCustomElementObserver({\n doc,\n customElementCb\n}) {\n const win = doc.defaultView;\n if (!win || !win.customElements) return () => {\n };\n const restoreHandler = patch(\n win.customElements,\n \"define\",\n function(original) {\n return function(name, constructor, options) {\n try {\n customElementCb({\n define: {\n name\n }\n });\n } catch (e) {\n console.warn(`Custom element callback failed for ${name}`);\n }\n return original.apply(this, [name, constructor, options]);\n };\n }\n );\n return restoreHandler;\n}\nfunction mergeHooks(o, hooks) {\n const {\n mutationCb,\n mousemoveCb,\n mouseInteractionCb,\n scrollCb,\n viewportResizeCb,\n inputCb,\n mediaInteractionCb,\n styleSheetRuleCb,\n styleDeclarationCb,\n canvasMutationCb,\n fontCb,\n selectionCb,\n customElementCb\n } = o;\n o.mutationCb = (...p) => {\n if (hooks.mutation) {\n hooks.mutation(...p);\n }\n mutationCb(...p);\n };\n o.mousemoveCb = (...p) => {\n if (hooks.mousemove) {\n hooks.mousemove(...p);\n }\n mousemoveCb(...p);\n };\n o.mouseInteractionCb = (...p) => {\n if (hooks.mouseInteraction) {\n hooks.mouseInteraction(...p);\n }\n mouseInteractionCb(...p);\n };\n o.scrollCb = (...p) => {\n if (hooks.scroll) {\n hooks.scroll(...p);\n }\n scrollCb(...p);\n };\n o.viewportResizeCb = (...p) => {\n if (hooks.viewportResize) {\n hooks.viewportResize(...p);\n }\n viewportResizeCb(...p);\n };\n o.inputCb = (...p) => {\n if (hooks.input) {\n hooks.input(...p);\n }\n inputCb(...p);\n };\n o.mediaInteractionCb = (...p) => {\n if (hooks.mediaInteaction) {\n hooks.mediaInteaction(...p);\n }\n mediaInteractionCb(...p);\n };\n o.styleSheetRuleCb = (...p) => {\n if (hooks.styleSheetRule) {\n hooks.styleSheetRule(...p);\n }\n styleSheetRuleCb(...p);\n };\n o.styleDeclarationCb = (...p) => {\n if (hooks.styleDeclaration) {\n hooks.styleDeclaration(...p);\n }\n styleDeclarationCb(...p);\n };\n o.canvasMutationCb = (...p) => {\n if (hooks.canvasMutation) {\n hooks.canvasMutation(...p);\n }\n canvasMutationCb(...p);\n };\n o.fontCb = (...p) => {\n if (hooks.font) {\n hooks.font(...p);\n }\n fontCb(...p);\n };\n o.selectionCb = (...p) => {\n if (hooks.selection) {\n hooks.selection(...p);\n }\n selectionCb(...p);\n };\n o.customElementCb = (...c) => {\n if (hooks.customElement) {\n hooks.customElement(...c);\n }\n customElementCb(...c);\n };\n}\nfunction initObservers(o, hooks = {}) {\n const currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return () => {\n };\n }\n mergeHooks(o, hooks);\n let mutationObserver;\n let cleanupMutationIframe = () => {\n };\n if (o.recordDOM) {\n [mutationObserver, cleanupMutationIframe] = initMutationObserver(o, o.doc);\n }\n const mousemoveHandler = initMoveObserver(o);\n const mouseInteractionHandler = initMouseInteractionObserver(o);\n const scrollHandler = initScrollObserver(o);\n const viewportResizeHandler = initViewportResizeObserver(o, {\n win: currentWindow\n });\n const inputHandler = initInputObserver(o);\n const mediaInteractionHandler = initMediaInteractionObserver(o);\n let styleSheetObserver = () => {\n };\n let adoptedStyleSheetObserver = () => {\n };\n let styleDeclarationObserver = () => {\n };\n let fontObserver = () => {\n };\n if (o.recordDOM) {\n styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\n styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow\n });\n if (o.collectFonts) {\n fontObserver = initFontObserver(o);\n }\n }\n const selectionObserver = initSelectionObserver(o);\n const customElementObserver = initCustomElementObserver(o);\n const pluginHandlers = [];\n for (const plugin of o.plugins) {\n pluginHandlers.push(\n plugin.observer(plugin.callback, currentWindow, plugin.options)\n );\n }\n return callbackWrapper(() => {\n mutationBuffers.forEach((b) => b.reset());\n mutationObserver == null ? void 0 : mutationObserver.disconnect();\n cleanupMutationIframe();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n styleSheetObserver();\n adoptedStyleSheetObserver();\n styleDeclarationObserver();\n fontObserver();\n selectionObserver();\n customElementObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== \"undefined\";\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(\n typeof window[prop] !== \"undefined\" && // Note: Generally, this check _shouldn't_ be necessary\n // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here\n window[prop].prototype && \"insertRule\" in window[prop].prototype && \"deleteRule\" in window[prop].prototype\n );\n}\nclass CrossOriginIframeMirror {\n constructor(generateIdFn) {\n __publicField(this, \"iframeIdToRemoteIdMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"iframeRemoteIdToIdMap\", /* @__PURE__ */ new WeakMap());\n this.generateIdFn = generateIdFn;\n }\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n let id = idToRemoteIdMap.get(remoteId);\n if (!id) {\n id = this.generateIdFn();\n idToRemoteIdMap.set(remoteId, id);\n remoteIdToIdMap.set(id, remoteId);\n }\n return id;\n }\n getIds(iframe, remoteId) {\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return remoteId.map(\n (id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap)\n );\n }\n getRemoteId(iframe, id, map) {\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n if (typeof id !== \"number\") return id;\n const remoteId = remoteIdToIdMap.get(id);\n if (!remoteId) return -1;\n return remoteId;\n }\n getRemoteIds(iframe, ids) {\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n }\n reset(iframe) {\n if (!iframe) {\n this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();\n this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();\n return;\n }\n this.iframeIdToRemoteIdMap.delete(iframe);\n this.iframeRemoteIdToIdMap.delete(iframe);\n }\n getIdToRemoteIdMap(iframe) {\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n if (!idToRemoteIdMap) {\n idToRemoteIdMap = /* @__PURE__ */ new Map();\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n }\n return idToRemoteIdMap;\n }\n getRemoteIdToIdMap(iframe) {\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n if (!remoteIdToIdMap) {\n remoteIdToIdMap = /* @__PURE__ */ new Map();\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n }\n return remoteIdToIdMap;\n }\n}\nclass IframeManager {\n constructor(options) {\n __publicField(this, \"iframes\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"crossOriginIframeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"crossOriginIframeMirror\", new CrossOriginIframeMirror(genId));\n __publicField(this, \"crossOriginIframeStyleMirror\");\n __publicField(this, \"crossOriginIframeRootIdMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"mirror\");\n __publicField(this, \"mutationCb\");\n __publicField(this, \"wrappedEmit\");\n __publicField(this, \"loadListener\");\n __publicField(this, \"stylesheetManager\");\n __publicField(this, \"recordCrossOriginIframes\");\n this.mutationCb = options.mutationCb;\n this.wrappedEmit = options.wrappedEmit;\n this.stylesheetManager = options.stylesheetManager;\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(\n this.stylesheetManager.styleMirror.generateId.bind(\n this.stylesheetManager.styleMirror\n )\n );\n this.mirror = options.mirror;\n if (this.recordCrossOriginIframes) {\n window.addEventListener(\"message\", this.handleMessage.bind(this));\n }\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n if (iframeEl.contentWindow)\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n attachIframe(iframeEl, childSn) {\n var _a2, _b;\n this.mutationCb({\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: childSn\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n });\n if (this.recordCrossOriginIframes)\n (_a2 = iframeEl.contentWindow) == null ? void 0 : _a2.addEventListener(\n \"message\",\n this.handleMessage.bind(this)\n );\n (_b = this.loadListener) == null ? void 0 : _b.call(this, iframeEl);\n if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0)\n this.stylesheetManager.adoptStyleSheets(\n iframeEl.contentDocument.adoptedStyleSheets,\n this.mirror.getId(iframeEl.contentDocument)\n );\n }\n handleMessage(message) {\n const crossOriginMessageEvent = message;\n if (crossOriginMessageEvent.data.type !== \"rrweb\" || // To filter out the rrweb messages which are forwarded by some sites.\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\n return;\n const iframeSourceWindow = message.source;\n if (!iframeSourceWindow) return;\n const iframeEl = this.crossOriginIframeMap.get(message.source);\n if (!iframeEl) return;\n const transformedEvent = this.transformCrossOriginEvent(\n iframeEl,\n crossOriginMessageEvent.data.event\n );\n if (transformedEvent)\n this.wrappedEmit(\n transformedEvent,\n crossOriginMessageEvent.data.isCheckout\n );\n }\n transformCrossOriginEvent(iframeEl, e) {\n var _a2;\n switch (e.type) {\n case EventType.FullSnapshot: {\n this.crossOriginIframeMirror.reset(iframeEl);\n this.crossOriginIframeStyleMirror.reset(iframeEl);\n this.replaceIdOnNode(e.data.node, iframeEl);\n const rootId = e.data.node.id;\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n this.patchRootIdOnNode(e.data.node, rootId);\n return {\n timestamp: e.timestamp,\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: e.data.node\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n }\n };\n }\n case EventType.Meta:\n case EventType.Load:\n case EventType.DomContentLoaded: {\n return false;\n }\n case EventType.Plugin: {\n return e;\n }\n case EventType.Custom: {\n this.replaceIds(\n e.data.payload,\n iframeEl,\n [\"id\", \"parentId\", \"previousId\", \"nextId\"]\n );\n return e;\n }\n case EventType.IncrementalSnapshot: {\n switch (e.data.source) {\n case IncrementalSource.Mutation: {\n e.data.adds.forEach((n) => {\n this.replaceIds(n, iframeEl, [\n \"parentId\",\n \"nextId\",\n \"previousId\"\n ]);\n this.replaceIdOnNode(n.node, iframeEl);\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n rootId && this.patchRootIdOnNode(n.node, rootId);\n });\n e.data.removes.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"parentId\", \"id\"]);\n });\n e.data.attributes.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"id\"]);\n });\n e.data.texts.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"id\"]);\n });\n return e;\n }\n case IncrementalSource.Drag:\n case IncrementalSource.TouchMove:\n case IncrementalSource.MouseMove: {\n e.data.positions.forEach((p) => {\n this.replaceIds(p, iframeEl, [\"id\"]);\n });\n return e;\n }\n case IncrementalSource.ViewportResize: {\n return false;\n }\n case IncrementalSource.MediaInteraction:\n case IncrementalSource.MouseInteraction:\n case IncrementalSource.Scroll:\n case IncrementalSource.CanvasMutation:\n case IncrementalSource.Input: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n return e;\n }\n case IncrementalSource.StyleSheetRule:\n case IncrementalSource.StyleDeclaration: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e.data, iframeEl, [\"styleId\"]);\n return e;\n }\n case IncrementalSource.Font: {\n return e;\n }\n case IncrementalSource.Selection: {\n e.data.ranges.forEach((range) => {\n this.replaceIds(range, iframeEl, [\"start\", \"end\"]);\n });\n return e;\n }\n case IncrementalSource.AdoptedStyleSheet: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e.data, iframeEl, [\"styleIds\"]);\n (_a2 = e.data.styles) == null ? void 0 : _a2.forEach((style) => {\n this.replaceStyleIds(style, iframeEl, [\"styleId\"]);\n });\n return e;\n }\n }\n }\n }\n return false;\n }\n replace(iframeMirror, obj, iframeEl, keys) {\n for (const key of keys) {\n if (!Array.isArray(obj[key]) && typeof obj[key] !== \"number\") continue;\n if (Array.isArray(obj[key])) {\n obj[key] = iframeMirror.getIds(\n iframeEl,\n obj[key]\n );\n } else {\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\n }\n }\n return obj;\n }\n replaceIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n }\n replaceStyleIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n }\n replaceIdOnNode(node, iframeEl) {\n this.replaceIds(node, iframeEl, [\"id\", \"rootId\"]);\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.replaceIdOnNode(child, iframeEl);\n });\n }\n }\n patchRootIdOnNode(node, rootId) {\n if (node.type !== NodeType.Document && !node.rootId) node.rootId = rootId;\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.patchRootIdOnNode(child, rootId);\n });\n }\n }\n}\nclass ShadowDomManager {\n constructor(options) {\n __publicField(this, \"shadowDoms\", /* @__PURE__ */ new WeakSet());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"scrollCb\");\n __publicField(this, \"bypassOptions\");\n __publicField(this, \"mirror\");\n __publicField(this, \"restoreHandlers\", []);\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n this.init();\n }\n init() {\n this.reset();\n this.patchAttachShadow(Element, document);\n }\n addShadowRoot(shadowRoot2, doc) {\n if (!isNativeShadowDom(shadowRoot2)) return;\n if (this.shadowDoms.has(shadowRoot2)) return;\n this.shadowDoms.add(shadowRoot2);\n const [observer] = initMutationObserver(\n {\n ...this.bypassOptions,\n doc,\n mutationCb: this.mutationCb,\n mirror: this.mirror,\n shadowDomManager: this\n },\n shadowRoot2\n );\n this.restoreHandlers.push(() => observer.disconnect());\n this.restoreHandlers.push(\n initScrollObserver({\n ...this.bypassOptions,\n scrollCb: this.scrollCb,\n // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813\n // scroll is not allowed to pass the boundary, so we need to listen the shadow document\n doc: shadowRoot2,\n mirror: this.mirror\n })\n );\n setTimeout(() => {\n if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0)\n this.bypassOptions.stylesheetManager.adoptStyleSheets(\n shadowRoot2.adoptedStyleSheets,\n this.mirror.getId(index.host(shadowRoot2))\n );\n this.restoreHandlers.push(\n initAdoptedStyleSheetObserver(\n {\n mirror: this.mirror,\n stylesheetManager: this.bypassOptions.stylesheetManager\n },\n shadowRoot2\n )\n );\n }, 0);\n }\n /**\n * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.\n */\n observeAttachShadow(iframeElement) {\n if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;\n this.patchAttachShadow(\n iframeElement.contentWindow.Element,\n iframeElement.contentDocument\n );\n }\n /**\n * Patch 'attachShadow' to observe newly added shadow doms.\n */\n patchAttachShadow(element, doc) {\n const manager = this;\n this.restoreHandlers.push(\n patch(\n element.prototype,\n \"attachShadow\",\n function(original) {\n return function(option) {\n const sRoot = original.call(this, option);\n const shadowRootEl = index.shadowRoot(this);\n if (shadowRootEl && inDom(this))\n manager.addShadowRoot(shadowRootEl, doc);\n return sRoot;\n };\n }\n )\n );\n }\n reset() {\n this.restoreHandlers.forEach((handler) => {\n try {\n handler();\n } catch (e) {\n }\n });\n this.restoreHandlers = [];\n this.shadowDoms = /* @__PURE__ */ new WeakSet();\n }\n}\nvar chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nvar lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = \"\";\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + \"=\";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + \"==\";\n }\n return base64;\n};\nconst canvasVarMap = /* @__PURE__ */ new Map();\nfunction variableListFor(ctx, ctor) {\n let contextMap = canvasVarMap.get(ctx);\n if (!contextMap) {\n contextMap = /* @__PURE__ */ new Map();\n canvasVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nconst saveWebGLVar = (value, win, ctx) => {\n if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === \"object\"))\n return;\n const name = value.constructor.name;\n const list = variableListFor(ctx, name);\n let index2 = list.indexOf(value);\n if (index2 === -1) {\n index2 = list.length;\n list.push(value);\n }\n return index2;\n};\nfunction serializeArg(value, win, ctx) {\n if (value instanceof Array) {\n return value.map((arg) => serializeArg(arg, win, ctx));\n } else if (value === null) {\n return value;\n } else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [Object.values(value)]\n };\n } else if (\n // SharedArrayBuffer disabled on most browsers due to spectre.\n // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer\n // value instanceof SharedArrayBuffer ||\n value instanceof ArrayBuffer\n ) {\n const name = value.constructor.name;\n const base64 = encode(value);\n return {\n rr_type: name,\n base64\n };\n } else if (value instanceof DataView) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.buffer, win, ctx),\n value.byteOffset,\n value.byteLength\n ]\n };\n } else if (value instanceof HTMLImageElement) {\n const name = value.constructor.name;\n const { src } = value;\n return {\n rr_type: name,\n src\n };\n } else if (value instanceof HTMLCanvasElement) {\n const name = \"HTMLImageElement\";\n const src = value.toDataURL();\n return {\n rr_type: name,\n src\n };\n } else if (value instanceof ImageData) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [serializeArg(value.data, win, ctx), value.width, value.height]\n };\n } else if (isInstanceOfWebGLObject(value, win) || typeof value === \"object\") {\n const name = value.constructor.name;\n const index2 = saveWebGLVar(value, win, ctx);\n return {\n rr_type: name,\n index: index2\n };\n }\n return value;\n}\nconst serializeArgs = (args, win, ctx) => {\n return args.map((arg) => serializeArg(arg, win, ctx));\n};\nconst isInstanceOfWebGLObject = (value, win) => {\n const webGLConstructorNames = [\n \"WebGLActiveInfo\",\n \"WebGLBuffer\",\n \"WebGLFramebuffer\",\n \"WebGLProgram\",\n \"WebGLRenderbuffer\",\n \"WebGLShader\",\n \"WebGLShaderPrecisionFormat\",\n \"WebGLTexture\",\n \"WebGLUniformLocation\",\n \"WebGLVertexArrayObject\",\n // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.\n \"WebGLVertexArrayObjectOES\"\n ];\n const supportedWebGLConstructorNames = webGLConstructorNames.filter(\n (name) => typeof win[name] === \"function\"\n );\n return Boolean(\n supportedWebGLConstructorNames.find(\n (name) => value instanceof win[name]\n )\n );\n};\nfunction initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {\n const handlers = [];\n const props2D = Object.getOwnPropertyNames(\n win.CanvasRenderingContext2D.prototype\n );\n for (const prop of props2D) {\n try {\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== \"function\") {\n continue;\n }\n const restoreHandler = patch(\n win.CanvasRenderingContext2D.prototype,\n prop,\n function(original) {\n return function(...args) {\n if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {\n setTimeout(() => {\n const recordArgs = serializeArgs(args, win, this);\n cb(this.canvas, {\n type: CanvasContext[\"2D\"],\n property: prop,\n args: recordArgs\n });\n }, 0);\n }\n return original.apply(this, args);\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n const hookHandler = hookSetter(\n win.CanvasRenderingContext2D.prototype,\n prop,\n {\n set(v) {\n cb(this.canvas, {\n type: CanvasContext[\"2D\"],\n property: prop,\n args: [v],\n setter: true\n });\n }\n }\n );\n handlers.push(hookHandler);\n }\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nfunction getNormalizedContextName(contextType) {\n return contextType === \"experimental-webgl\" ? \"webgl\" : contextType;\n}\nfunction initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {\n const handlers = [];\n try {\n const restoreHandler = patch(\n win.HTMLCanvasElement.prototype,\n \"getContext\",\n function(original) {\n return function(contextType, ...args) {\n if (!isBlocked(this, blockClass, blockSelector, true)) {\n const ctxName = getNormalizedContextName(contextType);\n if (!(\"__context\" in this)) this.__context = ctxName;\n if (setPreserveDrawingBufferToTrue && [\"webgl\", \"webgl2\"].includes(ctxName)) {\n if (args[0] && typeof args[0] === \"object\") {\n const contextAttributes = args[0];\n if (!contextAttributes.preserveDrawingBuffer) {\n contextAttributes.preserveDrawingBuffer = true;\n }\n } else {\n args.splice(0, 1, {\n preserveDrawingBuffer: true\n });\n }\n }\n }\n return original.apply(this, [contextType, ...args]);\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n console.error(\"failed to patch HTMLCanvasElement.prototype.getContext\");\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nfunction patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win) {\n const handlers = [];\n const props = Object.getOwnPropertyNames(prototype);\n for (const prop of props) {\n if (\n //prop.startsWith('get') || // e.g. getProgramParameter, but too risky\n [\n \"isContextLost\",\n \"canvas\",\n \"drawingBufferWidth\",\n \"drawingBufferHeight\"\n ].includes(prop)\n ) {\n continue;\n }\n try {\n if (typeof prototype[prop] !== \"function\") {\n continue;\n }\n const restoreHandler = patch(\n prototype,\n prop,\n function(original) {\n return function(...args) {\n const result = original.apply(this, args);\n saveWebGLVar(result, win, this);\n if (\"tagName\" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {\n const recordArgs = serializeArgs(args, win, this);\n const mutation = {\n type,\n property: prop,\n args: recordArgs\n };\n cb(this.canvas, mutation);\n }\n return result;\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n const hookHandler = hookSetter(prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type,\n property: prop,\n args: [v],\n setter: true\n });\n }\n });\n handlers.push(hookHandler);\n }\n }\n return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector) {\n const handlers = [];\n if (typeof win.WebGLRenderingContext !== \"undefined\") {\n handlers.push(\n ...patchGLPrototype(\n win.WebGLRenderingContext.prototype,\n CanvasContext.WebGL,\n cb,\n blockClass,\n blockSelector,\n win\n )\n );\n }\n if (typeof win.WebGL2RenderingContext !== \"undefined\") {\n handlers.push(\n ...patchGLPrototype(\n win.WebGL2RenderingContext.prototype,\n CanvasContext.WebGL2,\n cb,\n blockClass,\n blockSelector,\n win\n )\n );\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nconst jsContent = '(function() {\\n \"use strict\";\\n var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\\n var lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\\n for (var i = 0; i < chars.length; i++) {\\n lookup[chars.charCodeAt(i)] = i;\\n }\\n var encode = function(arraybuffer) {\\n var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = \"\";\\n for (i2 = 0; i2 < len; i2 += 3) {\\n base64 += chars[bytes[i2] >> 2];\\n base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\\n base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\\n base64 += chars[bytes[i2 + 2] & 63];\\n }\\n if (len % 3 === 2) {\\n base64 = base64.substring(0, base64.length - 1) + \"=\";\\n } else if (len % 3 === 1) {\\n base64 = base64.substring(0, base64.length - 2) + \"==\";\\n }\\n return base64;\\n };\\n const lastBlobMap = /* @__PURE__ */ new Map();\\n const transparentBlobMap = /* @__PURE__ */ new Map();\\n async function getTransparentBlobFor(width, height, dataURLOptions) {\\n const id = `${width}-${height}`;\\n if (\"OffscreenCanvas\" in globalThis) {\\n if (transparentBlobMap.has(id)) return transparentBlobMap.get(id);\\n const offscreen = new OffscreenCanvas(width, height);\\n offscreen.getContext(\"2d\");\\n const blob = await offscreen.convertToBlob(dataURLOptions);\\n const arrayBuffer = await blob.arrayBuffer();\\n const base64 = encode(arrayBuffer);\\n transparentBlobMap.set(id, base64);\\n return base64;\\n } else {\\n return \"\";\\n }\\n }\\n const worker = self;\\n worker.onmessage = async function(e) {\\n if (\"OffscreenCanvas\" in globalThis) {\\n const { id, bitmap, width, height, dataURLOptions } = e.data;\\n const transparentBase64 = getTransparentBlobFor(\\n width,\\n height,\\n dataURLOptions\\n );\\n const offscreen = new OffscreenCanvas(width, height);\\n const ctx = offscreen.getContext(\"2d\");\\n ctx.drawImage(bitmap, 0, 0);\\n bitmap.close();\\n const blob = await offscreen.convertToBlob(dataURLOptions);\\n const type = blob.type;\\n const arrayBuffer = await blob.arrayBuffer();\\n const base64 = encode(arrayBuffer);\\n if (!lastBlobMap.has(id) && await transparentBase64 === base64) {\\n lastBlobMap.set(id, base64);\\n return worker.postMessage({ id });\\n }\\n if (lastBlobMap.get(id) === base64) return worker.postMessage({ id });\\n worker.postMessage({\\n id,\\n type,\\n base64,\\n width,\\n height\\n });\\n lastBlobMap.set(id, base64);\\n } else {\\n return worker.postMessage({ id: e.data.id });\\n }\\n };\\n})();\\n//# sourceMappingURL=image-bitmap-data-url-worker-IJpC7g_b.js.map\\n';\nconst blob = typeof self !== \"undefined\" && self.Blob && new Blob([jsContent], { type: \"text/javascript;charset=utf-8\" });\nfunction WorkerWrapper(options) {\n let objURL;\n try {\n objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);\n if (!objURL) throw \"\";\n const worker = new Worker(objURL, {\n name: options == null ? void 0 : options.name\n });\n worker.addEventListener(\"error\", () => {\n (self.URL || self.webkitURL).revokeObjectURL(objURL);\n });\n return worker;\n } catch (e) {\n return new Worker(\n \"data:text/javascript;charset=utf-8,\" + encodeURIComponent(jsContent),\n {\n name: options == null ? void 0 : options.name\n }\n );\n } finally {\n objURL && (self.URL || self.webkitURL).revokeObjectURL(objURL);\n }\n}\nclass CanvasManager {\n constructor(options) {\n __publicField(this, \"pendingCanvasMutations\", /* @__PURE__ */ new Map());\n __publicField(this, \"rafStamps\", { latestId: 0, invokeId: null });\n __publicField(this, \"mirror\");\n __publicField(this, \"mutationCb\");\n __publicField(this, \"resetObservers\");\n __publicField(this, \"frozen\", false);\n __publicField(this, \"locked\", false);\n __publicField(this, \"processMutation\", (target, mutation) => {\n const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId;\n if (newFrame || !this.rafStamps.invokeId)\n this.rafStamps.invokeId = this.rafStamps.latestId;\n if (!this.pendingCanvasMutations.has(target)) {\n this.pendingCanvasMutations.set(target, []);\n }\n this.pendingCanvasMutations.get(target).push(mutation);\n });\n const {\n sampling = \"all\",\n win,\n blockClass,\n blockSelector,\n recordCanvas,\n dataURLOptions\n } = options;\n this.mutationCb = options.mutationCb;\n this.mirror = options.mirror;\n if (recordCanvas && sampling === \"all\")\n this.initCanvasMutationObserver(win, blockClass, blockSelector);\n if (recordCanvas && typeof sampling === \"number\")\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {\n dataURLOptions\n });\n }\n reset() {\n this.pendingCanvasMutations.clear();\n this.resetObservers && this.resetObservers();\n }\n freeze() {\n this.frozen = true;\n }\n unfreeze() {\n this.frozen = false;\n }\n lock() {\n this.locked = true;\n }\n unlock() {\n this.locked = false;\n }\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {\n const canvasContextReset = initCanvasContextObserver(\n win,\n blockClass,\n blockSelector,\n true\n );\n const snapshotInProgressMap = /* @__PURE__ */ new Map();\n const worker = new WorkerWrapper();\n worker.onmessage = (e) => {\n const { id } = e.data;\n snapshotInProgressMap.set(id, false);\n if (!(\"base64\" in e.data)) return;\n const { base64, type, width, height } = e.data;\n this.mutationCb({\n id,\n type: CanvasContext[\"2D\"],\n commands: [\n {\n property: \"clearRect\",\n // wipe canvas\n args: [0, 0, width, height]\n },\n {\n property: \"drawImage\",\n // draws (semi-transparent) image\n args: [\n {\n rr_type: \"ImageBitmap\",\n args: [\n {\n rr_type: \"Blob\",\n data: [{ rr_type: \"ArrayBuffer\", base64 }],\n type\n }\n ]\n },\n 0,\n 0\n ]\n }\n ]\n });\n };\n const timeBetweenSnapshots = 1e3 / fps;\n let lastSnapshotTime = 0;\n let rafId;\n const getCanvas = () => {\n const matchedCanvas = [];\n win.document.querySelectorAll(\"canvas\").forEach((canvas) => {\n if (!isBlocked(canvas, blockClass, blockSelector, true)) {\n matchedCanvas.push(canvas);\n }\n });\n return matchedCanvas;\n };\n const takeCanvasSnapshots = (timestamp) => {\n if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n return;\n }\n lastSnapshotTime = timestamp;\n getCanvas().forEach(async (canvas) => {\n var _a2;\n const id = this.mirror.getId(canvas);\n if (snapshotInProgressMap.get(id)) return;\n if (canvas.width === 0 || canvas.height === 0) return;\n snapshotInProgressMap.set(id, true);\n if ([\"webgl\", \"webgl2\"].includes(canvas.__context)) {\n const context = canvas.getContext(canvas.__context);\n if (((_a2 = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _a2.preserveDrawingBuffer) === false) {\n context.clear(context.COLOR_BUFFER_BIT);\n }\n }\n const bitmap = await createImageBitmap(canvas);\n worker.postMessage(\n {\n id,\n bitmap,\n width: canvas.width,\n height: canvas.height,\n dataURLOptions: options.dataURLOptions\n },\n [bitmap]\n );\n });\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n };\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n this.resetObservers = () => {\n canvasContextReset();\n cancelAnimationFrame(rafId);\n };\n }\n initCanvasMutationObserver(win, blockClass, blockSelector) {\n this.startRAFTimestamping();\n this.startPendingCanvasMutationFlusher();\n const canvasContextReset = initCanvasContextObserver(\n win,\n blockClass,\n blockSelector,\n false\n );\n const canvas2DReset = initCanvas2DMutationObserver(\n this.processMutation.bind(this),\n win,\n blockClass,\n blockSelector\n );\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(\n this.processMutation.bind(this),\n win,\n blockClass,\n blockSelector\n );\n this.resetObservers = () => {\n canvasContextReset();\n canvas2DReset();\n canvasWebGL1and2Reset();\n };\n }\n startPendingCanvasMutationFlusher() {\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n startRAFTimestamping() {\n const setLatestRAFTimestamp = (timestamp) => {\n this.rafStamps.latestId = timestamp;\n requestAnimationFrame(setLatestRAFTimestamp);\n };\n requestAnimationFrame(setLatestRAFTimestamp);\n }\n flushPendingCanvasMutations() {\n this.pendingCanvasMutations.forEach(\n (_values, canvas) => {\n const id = this.mirror.getId(canvas);\n this.flushPendingCanvasMutationFor(canvas, id);\n }\n );\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n flushPendingCanvasMutationFor(canvas, id) {\n if (this.frozen || this.locked) {\n return;\n }\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\n if (!valuesWithType || id === -1) return;\n const values = valuesWithType.map((value) => {\n const { type: type2, ...rest } = value;\n return rest;\n });\n const { type } = valuesWithType[0];\n this.mutationCb({ id, type, commands: values });\n this.pendingCanvasMutations.delete(canvas);\n }\n}\nclass StylesheetManager {\n constructor(options) {\n __publicField(this, \"trackedLinkElements\", /* @__PURE__ */ new WeakSet());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"adoptedStyleSheetCb\");\n __publicField(this, \"styleMirror\", new StyleSheetMirror());\n this.mutationCb = options.mutationCb;\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n }\n attachLinkElement(linkEl, childSn) {\n if (\"_cssText\" in childSn.attributes)\n this.mutationCb({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: childSn.id,\n attributes: childSn.attributes\n }\n ]\n });\n this.trackLinkElement(linkEl);\n }\n trackLinkElement(linkEl) {\n if (this.trackedLinkElements.has(linkEl)) return;\n this.trackedLinkElements.add(linkEl);\n this.trackStylesheetInLinkElement(linkEl);\n }\n adoptStyleSheets(sheets, hostId) {\n if (sheets.length === 0) return;\n const adoptedStyleSheetData = {\n id: hostId,\n styleIds: []\n };\n const styles = [];\n for (const sheet of sheets) {\n let styleId;\n if (!this.styleMirror.has(sheet)) {\n styleId = this.styleMirror.add(sheet);\n styles.push({\n styleId,\n rules: Array.from(sheet.rules || CSSRule, (r, index2) => ({\n rule: stringifyRule(r, sheet.href),\n index: index2\n }))\n });\n } else styleId = this.styleMirror.getId(sheet);\n adoptedStyleSheetData.styleIds.push(styleId);\n }\n if (styles.length > 0) adoptedStyleSheetData.styles = styles;\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\n }\n reset() {\n this.styleMirror.reset();\n this.trackedLinkElements = /* @__PURE__ */ new WeakSet();\n }\n // TODO: take snapshot on stylesheet reload by applying event listener\n trackStylesheetInLinkElement(_linkEl) {\n }\n}\nclass ProcessedNodeManager {\n constructor() {\n __publicField(this, \"nodeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"active\", false);\n }\n inOtherBuffer(node, thisBuffer) {\n const buffers = this.nodeMap.get(node);\n return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer);\n }\n add(node, buffer) {\n if (!this.active) {\n this.active = true;\n requestAnimationFrame(() => {\n this.nodeMap = /* @__PURE__ */ new WeakMap();\n this.active = false;\n });\n }\n this.nodeMap.set(node, (this.nodeMap.get(node) || /* @__PURE__ */ new Set()).add(buffer));\n }\n destroy() {\n }\n}\nlet wrappedEmit;\nlet takeFullSnapshot;\nlet canvasManager;\nlet recording = false;\ntry {\n if (Array.from([1], (x) => x * 2)[0] !== 2) {\n const cleanFrame = document.createElement(\"iframe\");\n document.body.appendChild(cleanFrame);\n Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;\n document.body.removeChild(cleanFrame);\n }\n} catch (err) {\n console.debug(\"Unable to override Array.from\", err);\n}\nconst mirror = createMirror();\nfunction record(options = {}) {\n const {\n emit,\n checkoutEveryNms,\n checkoutEveryNth,\n blockClass = \"rr-block\",\n blockSelector = null,\n ignoreClass = \"rr-ignore\",\n ignoreSelector = null,\n maskTextClass = \"rr-mask\",\n maskTextSelector = null,\n inlineStylesheet = true,\n maskAllInputs,\n maskInputOptions: _maskInputOptions,\n slimDOMOptions: _slimDOMOptions,\n maskInputFn,\n maskTextFn,\n hooks,\n packFn,\n sampling = {},\n dataURLOptions = {},\n mousemoveWait,\n recordDOM = true,\n recordCanvas = false,\n recordCrossOriginIframes = false,\n recordAfter = options.recordAfter === \"DOMContentLoaded\" ? options.recordAfter : \"load\",\n userTriggeredOnInput = false,\n collectFonts = false,\n inlineImages = false,\n plugins,\n keepIframeSrcFn = () => false,\n ignoreCSSAttributes = /* @__PURE__ */ new Set([]),\n errorHandler: errorHandler2\n } = options;\n registerErrorHandler(errorHandler2);\n const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;\n let passEmitsToParent = false;\n if (!inEmittingFrame) {\n try {\n if (window.parent.document) {\n passEmitsToParent = false;\n }\n } catch (e) {\n passEmitsToParent = true;\n }\n }\n if (inEmittingFrame && !emit) {\n throw new Error(\"emit function is required\");\n }\n if (!inEmittingFrame && !passEmitsToParent) {\n return () => {\n };\n }\n if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {\n sampling.mousemove = mousemoveWait;\n }\n mirror.reset();\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true\n } : _maskInputOptions !== void 0 ? _maskInputOptions : { password: true };\n const slimDOMOptions = slimDOMDefaults(_slimDOMOptions);\n polyfill();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const eventProcessor = (e) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n if (packFn && // Disable packing events which will be emitted to parent frames.\n !passEmitsToParent) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = (r, isCheckout) => {\n var _a2;\n const e = r;\n e.timestamp = nowTimestamp();\n if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e.type !== EventType.FullSnapshot && !(e.type === EventType.IncrementalSnapshot && e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n if (inEmittingFrame) {\n emit == null ? void 0 : emit(eventProcessor(e), isCheckout);\n } else if (passEmitsToParent) {\n const message = {\n type: \"rrweb\",\n event: eventProcessor(e),\n origin: window.location.origin,\n isCheckout\n };\n window.parent.postMessage(message, \"*\");\n }\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n } else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation && e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms && e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\n const wrappedMutationEmit = (m) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n ...m\n }\n });\n };\n const wrappedScrollEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Scroll,\n ...p\n }\n });\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p\n }\n });\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.AdoptedStyleSheet,\n ...a\n }\n });\n const stylesheetManager = new StylesheetManager({\n mutationCb: wrappedMutationEmit,\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit\n });\n const iframeManager = new IframeManager({\n mirror,\n mutationCb: wrappedMutationEmit,\n stylesheetManager,\n recordCrossOriginIframes,\n wrappedEmit\n });\n for (const plugin of plugins || []) {\n if (plugin.getMirror)\n plugin.getMirror({\n nodeMirror: mirror,\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror\n });\n }\n const processedNodeManager = new ProcessedNodeManager();\n canvasManager = new CanvasManager({\n recordCanvas,\n mutationCb: wrappedCanvasMutationEmit,\n win: window,\n blockClass,\n blockSelector,\n mirror,\n sampling: sampling.canvas,\n dataURLOptions\n });\n const shadowDomManager = new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n dataURLOptions,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n stylesheetManager,\n canvasManager,\n keepIframeSrcFn,\n processedNodeManager\n },\n mirror\n });\n takeFullSnapshot = (isCheckout = false) => {\n if (!recordDOM) {\n return;\n }\n wrappedEmit(\n {\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight()\n }\n },\n isCheckout\n );\n stylesheetManager.reset();\n shadowDomManager.init();\n mutationBuffers.forEach((buf) => buf.lock());\n const node = snapshot(document, {\n mirror,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n inlineStylesheet,\n maskAllInputs: maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOM: slimDOMOptions,\n dataURLOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n) => {\n if (isSerializedIframe(n, mirror)) {\n iframeManager.addIframe(n);\n }\n if (isSerializedStylesheet(n, mirror)) {\n stylesheetManager.trackLinkElement(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(index.shadowRoot(n), document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n shadowDomManager.observeAttachShadow(iframe);\n },\n onStylesheetLoad: (linkEl, childSn) => {\n stylesheetManager.attachLinkElement(linkEl, childSn);\n },\n keepIframeSrcFn\n });\n if (!node) {\n return console.warn(\"Failed to snapshot the document\");\n }\n wrappedEmit(\n {\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: getWindowScroll(window)\n }\n },\n isCheckout\n );\n mutationBuffers.forEach((buf) => buf.unlock());\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n stylesheetManager.adoptStyleSheets(\n document.adoptedStyleSheets,\n mirror.getId(document)\n );\n };\n try {\n const handlers = [];\n const observe = (doc) => {\n var _a2;\n return callbackWrapper(initObservers)(\n {\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions\n }\n }),\n mouseInteractionCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MouseInteraction,\n ...d\n }\n }),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.ViewportResize,\n ...d\n }\n }),\n inputCb: (v) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Input,\n ...v\n }\n }),\n mediaInteractionCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MediaInteraction,\n ...p\n }\n }),\n styleSheetRuleCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleSheetRule,\n ...r\n }\n }),\n styleDeclarationCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleDeclaration,\n ...r\n }\n }),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Font,\n ...p\n }\n }),\n selectionCb: (p) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Selection,\n ...p\n }\n });\n },\n customElementCb: (c) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CustomElement,\n ...c\n }\n });\n },\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskTextClass,\n maskTextSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordDOM,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskInputFn,\n maskTextFn,\n keepIframeSrcFn,\n blockSelector,\n slimDOMOptions,\n dataURLOptions,\n mirror,\n iframeManager,\n stylesheetManager,\n shadowDomManager,\n processedNodeManager,\n canvasManager,\n ignoreCSSAttributes,\n plugins: ((_a2 = plugins == null ? void 0 : plugins.filter((p) => p.observer)) == null ? void 0 : _a2.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload\n }\n })\n }))) || []\n },\n hooks\n );\n };\n iframeManager.addLoadListener((iframeEl) => {\n try {\n handlers.push(observe(iframeEl.contentDocument));\n } catch (error) {\n console.warn(error);\n }\n });\n const init = () => {\n takeFullSnapshot();\n handlers.push(observe(document));\n recording = true;\n };\n if ([\"interactive\", \"complete\"].includes(document.readyState)) {\n init();\n } else {\n handlers.push(\n on(\"DOMContentLoaded\", () => {\n wrappedEmit({\n type: EventType.DomContentLoaded,\n data: {}\n });\n if (recordAfter === \"DOMContentLoaded\") init();\n })\n );\n handlers.push(\n on(\n \"load\",\n () => {\n wrappedEmit({\n type: EventType.Load,\n data: {}\n });\n if (recordAfter === \"load\") init();\n },\n window\n )\n );\n }\n return () => {\n handlers.forEach((handler) => {\n try {\n handler();\n } catch (error) {\n const msg = String(error).toLowerCase();\n if (!msg.includes(\"cross-origin\")) {\n console.warn(error);\n }\n }\n });\n processedNodeManager.destroy();\n recording = false;\n unregisterErrorHandler();\n };\n } catch (error) {\n console.warn(error);\n }\n}\nrecord.addCustomEvent = (tag, payload) => {\n if (!recording) {\n throw new Error(\"please add custom event after start recording\");\n }\n wrappedEmit({\n type: EventType.Custom,\n data: {\n tag,\n payload\n }\n });\n};\nrecord.freezePage = () => {\n mutationBuffers.forEach((buf) => buf.freeze());\n};\nrecord.takeFullSnapshot = (isCheckout) => {\n if (!recording) {\n throw new Error(\"please take full snapshot after start recording\");\n }\n takeFullSnapshot(isCheckout);\n};\nrecord.mirror = mirror;\nexport {\n record\n};\n//# sourceMappingURL=record.js.map\n","import { record } from '@rrweb/record';\nimport type { eventWithTime } from '@rrweb/types';\n\nimport { sdk } from '../sdk';\n\nconst FLUSH_INTERVAL_MS = 500;\nconst MAX_BUFFERED_EVENTS = 20_000;\n\nexport class RrwebSessionRecorder {\n private events: eventWithTime[] = [];\n private readonly sessionId = globalThis.crypto.randomUUID();\n private stopRecording: ReturnType<typeof record> | null = null;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private flushPromise = Promise.resolve();\n private stopped = false;\n\n constructor(\n private readonly chatId: string,\n private readonly applicationId: number,\n ) {}\n\n async start(): Promise<void> {\n if (this.stopRecording || this.stopped) return;\n await sdk.widgetMessagePost({\n chat_id: this.chatId,\n command: {\n type: 'rrweb/metadata',\n rrweb_session_id: this.sessionId,\n chat_id: this.chatId,\n application_id: this.applicationId,\n url: window.location.href,\n user_agent: navigator.userAgent,\n timestamp: Date.now(),\n viewport: { width: window.innerWidth, height: window.innerHeight },\n },\n });\n if (this.stopped) return;\n this.stopRecording = record({\n emit: event => this.buffer(event as eventWithTime),\n maskAllInputs: true,\n // Regex, not a plain string: a bare 'mtx-*' would REPLACE rrweb's rr-* defaults and un-block elements a customer blocks with .rr-block.\n maskTextClass: /^(rr-mask|mtx-mask)$/,\n blockClass: /^(rr-block|mtx-block)$/,\n });\n }\n\n stop(): void {\n this.stopped = true;\n this.stopRecording?.();\n this.stopRecording = null;\n if (this.flushTimer) clearTimeout(this.flushTimer);\n this.flushTimer = null;\n void this.flush();\n }\n\n private buffer(event: eventWithTime): void {\n this.events.push(event);\n if (!this.flushTimer) this.flushTimer = setTimeout(() => void this.flush(), FLUSH_INTERVAL_MS);\n }\n\n private flush(): Promise<void> {\n this.flushPromise = this.flushPromise.then(async () => {\n if (this.flushTimer) clearTimeout(this.flushTimer);\n this.flushTimer = null;\n const events = this.events.splice(0);\n if (!events.length) return;\n try {\n await sdk.widgetMessagePost({\n chat_id: this.chatId,\n command: { type: 'rrweb/events', rrweb_session_id: this.sessionId, events },\n });\n } catch (error) {\n this.events = events.concat(this.events).slice(0, MAX_BUFFERED_EVENTS);\n console.error('Failed to record session events:', error);\n }\n });\n return this.flushPromise;\n }\n}\n","import { sdk, type WidgetCommand, type WidgetEvent } from '../sdk';\nimport { storageService } from './StorageService';\n\n// `open` is the transport, `registered` is the chat: only the latter can carry a reply, which is why\n// `isConnected` reads `registered` and nothing waits on `open`.\ntype StreamStatus = 'disconnected' | 'connecting' | 'open' | 'registered' | 'error';\n\n/** The stream has stopped retrying, so nothing further will arrive for anything still in flight. */\nexport class StreamGaveUpError extends Error {}\n\nexport interface StreamClientCallbacks {\n onMessage?: (event: WidgetEvent) => void;\n onError?: (error: Error) => void;\n}\n\nexport class StreamClient {\n private static instance: StreamClient | null = null;\n private abortController: AbortController | null = null;\n private chatId: string | null = null;\n private status: StreamStatus = 'disconnected';\n private callbacks: Set<StreamClientCallbacks> = new Set();\n private tornDown = false;\n private credentialRejected = false;\n private reconnectAttempts = 0;\n private readonly maxReconnectAttempts = 10;\n private reconnectDelay = 1000;\n private readonly maxReconnectDelay = 30000;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private connectionId = 0;\n // Per-tab identity: tabs share the localStorage chat_id, so the server keys SSE by (chat_id, tab_id) to stop tabs evicting each other's stream.\n private readonly tabId = globalThis.crypto.randomUUID();\n private registrationWaiters = new Set<{ resolve: () => void; reject: (error: Error) => void }>();\n\n private constructor() {}\n\n static getInstance(): StreamClient {\n if (!StreamClient.instance) {\n StreamClient.instance = new StreamClient();\n }\n return StreamClient.instance;\n }\n\n addCallbacks(callbacks: StreamClientCallbacks): void {\n this.callbacks.add(callbacks);\n }\n\n removeCallbacks(callbacks: StreamClientCallbacks): void {\n this.callbacks.delete(callbacks);\n }\n\n isConnected(): boolean {\n return this.status === 'registered';\n }\n\n private reconnectSuppressed(): boolean {\n return this.tornDown || this.credentialRejected;\n }\n\n /** Whether a user-driven retry can achieve anything: there is a chat to rejoin and nothing has\n * suppressed reconnection. */\n canReconnect(): boolean {\n return this.chatId !== null && !this.reconnectSuppressed() && !this.isConnected();\n }\n\n /** The user asked to retry. `scheduleReconnect` gives up permanently at `maxReconnectAttempts` and only\n * `registered` resets the counters, so without this reset the widget's Retry button had nothing it\n * could do — which is why it was wired to plain dismiss. */\n reconnectNow(): void {\n if (!this.canReconnect() || this.chatId === null) return;\n this.clearReconnectTimer();\n this.reconnectAttempts = 0;\n this.reconnectDelay = 1000;\n this.connect(this.chatId).catch(console.error);\n }\n\n async waitUntilRegistered(): Promise<void> {\n if (this.isConnected()) return;\n if (this.credentialRejected) {\n throw new StreamGaveUpError('Chat is unavailable — the widget credentials were rejected.');\n }\n await new Promise<void>((resolve, reject) => this.registrationWaiters.add({ resolve, reject }));\n }\n\n async connect(chatId: string): Promise<void> {\n if (this.credentialRejected) return;\n this.tornDown = false;\n\n if (\n this.chatId === chatId &&\n (this.status === 'connecting' || this.status === 'open' || this.status === 'registered')\n ) {\n return;\n }\n\n if (this.abortController) {\n this.abortController.abort();\n this.abortController = null;\n }\n\n this.chatId = chatId;\n this.status = 'connecting';\n const myConnectionId = ++this.connectionId;\n\n this.abortController = new AbortController();\n const signal = this.abortController.signal;\n\n try {\n // Read at connect time, not captured at init: a reconnect after updateMarketrixConfig must use the current credentials.\n const credentials = storageService.getCredentialedConfig();\n const iterator = await sdk.widgetStream(\n {\n chat_id: chatId,\n tab_id: this.tabId,\n ...(credentials && { marketrix_id: credentials.mtxId, marketrix_key: credentials.mtxKey }),\n },\n { signal },\n );\n\n this.status = 'open';\n // Reconnect counters reset only on `registered` (handleMessage); resetting here would defeat the max-attempts cap if registration never lands and the stream flaps open→closed.\n\n this.consumeEvents(iterator, myConnectionId);\n } catch (error) {\n if (!signal.aborted) {\n console.error('[StreamClient] Connection failed:', error);\n this.status = 'error';\n this.notifyError(new Error('Stream connection failed'));\n this.scheduleReconnect();\n }\n }\n }\n\n private async consumeEvents(iterator: AsyncIterable<WidgetEvent>, connectionId: number): Promise<void> {\n let stale = false;\n try {\n for await (const event of iterator) {\n if (this.connectionId !== connectionId) {\n stale = true;\n break;\n }\n this.handleMessage(event);\n }\n } catch (error) {\n if (this.connectionId !== connectionId) {\n stale = true;\n } else if (!this.reconnectSuppressed()) {\n console.warn('[StreamClient] Stream error:', error);\n this.status = 'error';\n }\n } finally {\n if (!stale && this.connectionId === connectionId && !this.reconnectSuppressed()) {\n this.status = 'disconnected';\n this.scheduleReconnect();\n }\n }\n }\n\n disconnect(): void {\n this.tornDown = true;\n this.credentialRejected = false;\n this.clearReconnectTimer();\n if (this.abortController) {\n this.abortController.abort();\n this.abortController = null;\n }\n this.status = 'disconnected';\n this.chatId = null;\n this.settleWaiters(new Error('Stream disconnected before registration'));\n }\n\n send(command: WidgetCommand): Promise<void> {\n if (!this.chatId) {\n return Promise.reject(new Error('No active chat'));\n }\n return sdk\n .widgetMessagePost({\n chat_id: this.chatId,\n tab_id: this.tabId,\n command,\n })\n .then(() => {})\n .catch(err => {\n this.notifyError(new Error(`Failed to send message: ${String(err)}`));\n throw err;\n });\n }\n\n private notifyError(error: Error): void {\n this.callbacks.forEach(cb => cb.onError?.(error));\n }\n\n private settleWaiters(error: Error): void {\n for (const waiter of this.registrationWaiters) waiter.reject(error);\n this.registrationWaiters.clear();\n }\n\n private giveUp(message: string): void {\n const error = new StreamGaveUpError(message);\n this.notifyError(error);\n this.settleWaiters(error);\n }\n\n private handleMessage(event: WidgetEvent): void {\n if (this.reconnectSuppressed()) return;\n if (event.type === 'heartbeat') return;\n\n if (event.type === 'registered') {\n if (event.chat_id === this.chatId) {\n console.log('[StreamClient] Successfully registered with server');\n this.status = 'registered';\n this.reconnectAttempts = 0;\n this.reconnectDelay = 1000;\n for (const waiter of this.registrationWaiters) waiter.resolve();\n this.registrationWaiters.clear();\n }\n }\n\n if (event.type === 'chat/error' && event.request_id === 'auth') {\n console.error('[StreamClient] Authentication failed — will not reconnect');\n this.credentialRejected = true;\n // The event is ALSO handed to the reducer below, where `chat/error` settles the message whose id is\n // the request id — and no message is ever id 'auth', so the branch matched nothing and the widget\n // went permanently silent with no toast, no bubble and (console being dropped by terser) no trace.\n this.giveUp('Chat is unavailable — the widget credentials were rejected.');\n }\n\n this.callbacks.forEach(cb => cb.onMessage?.(event));\n }\n\n private scheduleReconnect(): void {\n if (this.reconnectAttempts >= this.maxReconnectAttempts) {\n // What the visitor on a customer's page reads, so it names the state and the way out rather than the counter.\n this.giveUp('Could not reconnect to the assistant. Try again.');\n return;\n }\n this.clearReconnectTimer();\n this.reconnectAttempts++;\n const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), this.maxReconnectDelay);\n console.log(\n `[StreamClient] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`,\n );\n this.reconnectTimer = setTimeout(() => {\n if (!this.reconnectSuppressed() && this.chatId) {\n this.connect(this.chatId).catch(console.error);\n }\n }, delay);\n }\n\n private clearReconnectTimer(): void {\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n }\n}\n","import { sdk, type WidgetData, type WidgetSettingsData, WidgetSettingsDataSchema } from '../sdk';\nimport type { MarketrixConfig } from '../types';\nimport type { CredentialedConfig } from './StorageService';\n\nexport function createConfigFromSettings(\n widgetSettings: WidgetSettingsData,\n baseConfig: Partial<MarketrixConfig> = {},\n): MarketrixConfig {\n return {\n ...baseConfig,\n ...widgetSettings,\n } as MarketrixConfig;\n}\n\n/** Per-tenant scope for browser-local keys: the credential id, else the application id. */\nexport function tenantScope(config: MarketrixConfig): string {\n return config.mtxId ?? (config.mtxApp != null ? String(config.mtxApp) : 'default');\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : typeof error === 'string' ? error : 'Unknown error';\n}\n\nfunction withCause(message: string, cause: unknown): Error {\n const error = new Error(message);\n (error as Error & { cause: unknown }).cause = cause;\n return error;\n}\n\nfunction widgetSearchError(error: unknown, config: MarketrixConfig): Error {\n const message = errorMessage(error);\n if (\n message.includes('Failed to fetch') ||\n message.includes('ERR_CONNECTION_REFUSED') ||\n message.includes('NetworkError') ||\n message.includes('Network request failed')\n ) {\n return withCause(\n `Cannot connect to API server. Please ensure the API server is running at ${config.mtxApiHost || 'configured API server'}. Error: ${message}`,\n error,\n );\n }\n return withCause(`Widget validation failed: ${message}`, error);\n}\n\nexport async function loadWidgetConfig(config: MarketrixConfig): Promise<CredentialedConfig> {\n const { mtxId, mtxKey } = config;\n if (!mtxId || !mtxKey) {\n throw new Error('Please provide mtxId + mtxKey');\n }\n\n let widgets: WidgetData[];\n try {\n ({ items: widgets } = await sdk.widgetSearch({ marketrix_id: mtxId, marketrix_key: mtxKey }));\n } catch (error) {\n throw widgetSearchError(error, config);\n }\n\n if (!widgets.length) {\n throw new Error('Widget not found or invalid credentials');\n }\n\n const activeWidget = widgets.find(widget => widget.status === 'active');\n if (!activeWidget) {\n const statuses = widgets.map(widget => widget.status).join(', ');\n throw new Error(\n `Found widget(s) but none are active. Current status(es): ${statuses}. Please activate the widget in the dashboard.`,\n );\n }\n\n if (!activeWidget.application_id) {\n throw new Error('Widget missing application_id');\n }\n\n try {\n await sdk.applicationGet({ application_id: activeWidget.application_id });\n } catch (error) {\n throw withCause(`Failed to validate application: ${errorMessage(error)}`, error);\n }\n\n let defaults: WidgetSettingsData;\n try {\n defaults = await sdk.widgetDefaultGet({ type: 'widget' });\n } catch (error) {\n throw withCause(`Failed to fetch widget settings from API: ${errorMessage(error)}`, error);\n }\n\n const parsedSettings = WidgetSettingsDataSchema.safeParse({ ...defaults, ...activeWidget.settings });\n if (!parsedSettings.success) {\n const fields = [...new Set(parsedSettings.error.issues.map(issue => issue.path.join('.') || 'settings'))];\n throw new Error(`Widget settings are invalid: ${fields.join(', ')}`);\n }\n\n return {\n ...createConfigFromSettings(parsedSettings.data, config),\n mtxId,\n mtxKey,\n mtxApp: activeWidget.application_id,\n };\n}\n","export default \"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20viewBox='0%200%20361%20360'%3e%3cdefs%3e%3cstyle%3e%20.st0%20{%20display:%20none;%20fill:%20none;%20stroke:%20%23cdc9c2;%20stroke-width:%201.3px;%20}%20.st1%20{%20fill:%20%23fff;%20}%20.st2,%20.st3%20{%20fill:%20%237cffa6;%20}%20.st3%20{%20stroke:%20%237cffa6;%20stroke-width:%20.38px;%20}%20.st4%20{%20fill:%20%23101828;%20}%20%3c/style%3e%3c/defs%3e%3crect%20class='st4'%20x='.5'%20width='360'%20height='360'/%3e%3cpath%20class='st2'%20d='M83.37,209.58c15.35,0,27.8-12.45,27.8-27.8s-12.44-27.79-27.8-27.79-27.8,12.44-27.8,27.79,12.44,27.8,27.8,27.8Z'/%3e%3cpath%20class='st1'%20d='M85.86,68.28l152.45,223.44h67.29l-70.62-113.77,68.13-109.67h-67.29l-41.12,65.31-41.54-65.31h-67.29Z'/%3e%3cpath%20class='st3'%20d='M176.61,249.83l-35.08-51-57.82,92.71h66.85l26.05-41.7Z'/%3e%3crect%20class='st0'%20x='1.25'%20y='.65'%20width='358.7'%20height='358.7'%20rx='43.35'%20ry='43.35'/%3e%3c/svg%3e\"","export const SHADOW = {\n none: 'none',\n card: '0 1px 4px rgba(0,0,0,0.1)',\n section: '0 2px 8px rgba(0,0,0,0.06)',\n panel: '0 12px 40px rgba(0,0,0,0.16), 0 4px 12px rgba(0,0,0,0.08)',\n fab: '0 2px 8px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.04)',\n button: '0 4px 6px -1px rgba(0,0,0,0.1)',\n} as const;\n\nexport type ShadowToken = keyof typeof SHADOW;\n","import type { CSSProperties } from 'react';\n\nimport { SHADOW, type ShadowToken } from './shadows';\n\nexport type RadiusToken = 'none' | 'sm' | 'md' | 'lg' | 'xl' | 'theme' | 'pill' | 'circle';\nexport type TextTone = 'default' | 'muted' | 'faint' | 'primary' | 'inherit';\nexport type TextLeading = 'tight' | 'snug' | 'normal' | 'relaxed';\nexport type NotificationTone = 'info' | 'error' | 'neutral';\n\nexport const radiusClasses: Record<RadiusToken, string> = {\n none: 'rounded-none',\n sm: 'rounded-sm',\n md: 'rounded-md',\n lg: 'rounded-lg',\n xl: 'rounded-xl',\n theme: 'rounded-[var(--radius)]',\n pill: 'rounded-full',\n circle: 'rounded-full',\n};\n\nexport const textToneClasses: Record<TextTone, string> = {\n default: 'text-foreground',\n muted: 'text-foreground-muted',\n faint: 'text-foreground-faint',\n primary: 'text-primary',\n inherit: 'text-inherit',\n};\n\nexport const textLeadingClasses: Record<TextLeading, string> = {\n tight: 'leading-tight',\n snug: 'leading-snug',\n normal: 'leading-normal',\n relaxed: 'leading-relaxed',\n};\n\nexport const TAB_BAR_HEIGHT = 48;\n\nexport const notificationToneStyles: Record<\n NotificationTone,\n {\n background: string;\n border: string;\n titleColor: string;\n bodyColor: string;\n closeColor: string;\n actionBackground: string;\n }\n> = {\n info: {\n background: '#f0f9ff',\n border: '1px solid #bae6fd',\n titleColor: '#0c4a6e',\n bodyColor: '#0369a1',\n closeColor: '#7dd3fc',\n actionBackground: '#e0f2fe',\n },\n error: {\n background: '#fef2f2',\n border: '1px solid #fecaca',\n titleColor: '#b91c1c',\n bodyColor: '#b91c1c',\n closeColor: '#f87171',\n actionBackground: '#fee2e2',\n },\n neutral: {\n background: 'rgba(255, 255, 255, 0.95)',\n border: '1px solid rgba(255, 255, 255, 0.2)',\n titleColor: '#1f2937',\n bodyColor: '#1f2937',\n closeColor: '#6b7280',\n actionBackground: 'transparent',\n },\n};\n\nexport function getElevationStyle(token?: ShadowToken | null): CSSProperties | undefined {\n if (!token || token === 'none') {\n return undefined;\n }\n\n return { boxShadow: SHADOW[token] };\n}\n","export type LayerTokens = {\n screenEdgeGlow: number;\n panel: number;\n dialog: number;\n toast: number;\n};\n\nconst WIDGET_LAYER_BASE = 2147483001;\n\nexport const LAYER_TOKENS: LayerTokens = {\n screenEdgeGlow: WIDGET_LAYER_BASE,\n panel: WIDGET_LAYER_BASE + 1,\n dialog: WIDGET_LAYER_BASE + 2,\n toast: WIDGET_LAYER_BASE + 3,\n};\n","/**\n * Concatenates two arrays faster than the array spread operator.\n */\nconst concatArrays = (array1, array2) => {\n // Pre-allocate for better V8 optimization\n const combinedArray = new Array(array1.length + array2.length);\n for (let i = 0; i < array1.length; i++) {\n combinedArray[i] = array1[i];\n }\n for (let i = 0; i < array2.length; i++) {\n combinedArray[array1.length + i] = array2[i];\n }\n return combinedArray;\n};\n\n// Factory function ensures consistent object shapes\nconst createClassValidatorObject = (classGroupId, validator) => ({\n classGroupId,\n validator\n});\n// Factory ensures consistent ClassPartObject shape\nconst createClassPartObject = (nextPart = new Map(), validators = null, classGroupId) => ({\n nextPart,\n validators,\n classGroupId\n});\nconst CLASS_PART_SEPARATOR = '-';\nconst EMPTY_CONFLICTS = [];\n// I use two dots here because one dot is used as prefix for class groups in plugins\nconst ARBITRARY_PROPERTY_PREFIX = 'arbitrary..';\nconst createClassGroupUtils = config => {\n const classMap = createClassMap(config);\n const {\n conflictingClassGroups,\n conflictingClassGroupModifiers\n } = config;\n const getClassGroupId = className => {\n if (className.startsWith('[') && className.endsWith(']')) {\n return getGroupIdForArbitraryProperty(className);\n }\n const classParts = className.split(CLASS_PART_SEPARATOR);\n // Classes like `-inset-1` produce an empty string as first classPart. We assume that classes for negative values are used correctly and skip it.\n const startIndex = classParts[0] === '' && classParts.length > 1 ? 1 : 0;\n return getGroupRecursive(classParts, startIndex, classMap);\n };\n const getConflictingClassGroupIds = (classGroupId, hasPostfixModifier) => {\n if (hasPostfixModifier) {\n const modifierConflicts = conflictingClassGroupModifiers[classGroupId];\n const baseConflicts = conflictingClassGroups[classGroupId];\n if (modifierConflicts) {\n if (baseConflicts) {\n // Merge base conflicts with modifier conflicts\n return concatArrays(baseConflicts, modifierConflicts);\n }\n // Only modifier conflicts\n return modifierConflicts;\n }\n // Fall back to without postfix if no modifier conflicts\n return baseConflicts || EMPTY_CONFLICTS;\n }\n return conflictingClassGroups[classGroupId] || EMPTY_CONFLICTS;\n };\n return {\n getClassGroupId,\n getConflictingClassGroupIds\n };\n};\nconst getGroupRecursive = (classParts, startIndex, classPartObject) => {\n const classPathsLength = classParts.length - startIndex;\n if (classPathsLength === 0) {\n return classPartObject.classGroupId;\n }\n const currentClassPart = classParts[startIndex];\n const nextClassPartObject = classPartObject.nextPart.get(currentClassPart);\n if (nextClassPartObject) {\n const result = getGroupRecursive(classParts, startIndex + 1, nextClassPartObject);\n if (result) return result;\n }\n const validators = classPartObject.validators;\n if (validators === null) {\n return undefined;\n }\n // Build classRest string efficiently by joining from startIndex onwards\n const classRest = startIndex === 0 ? classParts.join(CLASS_PART_SEPARATOR) : classParts.slice(startIndex).join(CLASS_PART_SEPARATOR);\n const validatorsLength = validators.length;\n for (let i = 0; i < validatorsLength; i++) {\n const validatorObj = validators[i];\n if (validatorObj.validator(classRest)) {\n return validatorObj.classGroupId;\n }\n }\n return undefined;\n};\n/**\n * Get the class group ID for an arbitrary property.\n *\n * @param className - The class name to get the group ID for. Is expected to be string starting with `[` and ending with `]`.\n */\nconst getGroupIdForArbitraryProperty = className => className.slice(1, -1).indexOf(':') === -1 ? undefined : (() => {\n const content = className.slice(1, -1);\n const colonIndex = content.indexOf(':');\n const property = content.slice(0, colonIndex);\n return property ? ARBITRARY_PROPERTY_PREFIX + property : undefined;\n})();\n/**\n * Exported for testing only\n */\nconst createClassMap = config => {\n const {\n theme,\n classGroups\n } = config;\n return processClassGroups(classGroups, theme);\n};\n// Split into separate functions to maintain monomorphic call sites\nconst processClassGroups = (classGroups, theme) => {\n const classMap = createClassPartObject();\n for (const classGroupId in classGroups) {\n const group = classGroups[classGroupId];\n processClassesRecursively(group, classMap, classGroupId, theme);\n }\n return classMap;\n};\nconst processClassesRecursively = (classGroup, classPartObject, classGroupId, theme) => {\n const len = classGroup.length;\n for (let i = 0; i < len; i++) {\n const classDefinition = classGroup[i];\n processClassDefinition(classDefinition, classPartObject, classGroupId, theme);\n }\n};\n// Split into separate functions for each type to maintain monomorphic call sites\nconst processClassDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n if (typeof classDefinition === 'string') {\n processStringDefinition(classDefinition, classPartObject, classGroupId);\n return;\n }\n if (typeof classDefinition === 'function') {\n processFunctionDefinition(classDefinition, classPartObject, classGroupId, theme);\n return;\n }\n processObjectDefinition(classDefinition, classPartObject, classGroupId, theme);\n};\nconst processStringDefinition = (classDefinition, classPartObject, classGroupId) => {\n const classPartObjectToEdit = classDefinition === '' ? classPartObject : getPart(classPartObject, classDefinition);\n classPartObjectToEdit.classGroupId = classGroupId;\n};\nconst processFunctionDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n if (isThemeGetter(classDefinition)) {\n processClassesRecursively(classDefinition(theme), classPartObject, classGroupId, theme);\n return;\n }\n if (classPartObject.validators === null) {\n classPartObject.validators = [];\n }\n classPartObject.validators.push(createClassValidatorObject(classGroupId, classDefinition));\n};\nconst processObjectDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n const entries = Object.entries(classDefinition);\n const len = entries.length;\n for (let i = 0; i < len; i++) {\n const [key, value] = entries[i];\n processClassesRecursively(value, getPart(classPartObject, key), classGroupId, theme);\n }\n};\nconst getPart = (classPartObject, path) => {\n let current = classPartObject;\n const parts = path.split(CLASS_PART_SEPARATOR);\n const len = parts.length;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n let next = current.nextPart.get(part);\n if (!next) {\n next = createClassPartObject();\n current.nextPart.set(part, next);\n }\n current = next;\n }\n return current;\n};\n// Type guard maintains monomorphic check\nconst isThemeGetter = func => 'isThemeGetter' in func && func.isThemeGetter === true;\n\n// LRU cache implementation using plain objects for simplicity\nconst createLruCache = maxCacheSize => {\n if (maxCacheSize < 1) {\n return {\n get: () => undefined,\n set: () => {}\n };\n }\n let cacheSize = 0;\n let cache = Object.create(null);\n let previousCache = Object.create(null);\n const update = (key, value) => {\n cache[key] = value;\n cacheSize++;\n if (cacheSize > maxCacheSize) {\n cacheSize = 0;\n previousCache = cache;\n cache = Object.create(null);\n }\n };\n return {\n get(key) {\n let value = cache[key];\n if (value !== undefined) {\n return value;\n }\n if ((value = previousCache[key]) !== undefined) {\n update(key, value);\n return value;\n }\n },\n set(key, value) {\n if (key in cache) {\n cache[key] = value;\n } else {\n update(key, value);\n }\n }\n };\n};\nconst IMPORTANT_MODIFIER = '!';\nconst MODIFIER_SEPARATOR = ':';\nconst EMPTY_MODIFIERS = [];\n// Pre-allocated result object shape for consistency\nconst createResultObject = (modifiers, hasImportantModifier, baseClassName, maybePostfixModifierPosition, isExternal) => ({\n modifiers,\n hasImportantModifier,\n baseClassName,\n maybePostfixModifierPosition,\n isExternal\n});\nconst createParseClassName = config => {\n const {\n prefix,\n experimentalParseClassName\n } = config;\n /**\n * Parse class name into parts.\n *\n * Inspired by `splitAtTopLevelOnly` used in Tailwind CSS\n * @see https://github.com/tailwindlabs/tailwindcss/blob/v3.2.2/src/util/splitAtTopLevelOnly.js\n */\n let parseClassName = className => {\n // Use simple array with push for better performance\n const modifiers = [];\n let bracketDepth = 0;\n let parenDepth = 0;\n let modifierStart = 0;\n let postfixModifierPosition;\n const len = className.length;\n for (let index = 0; index < len; index++) {\n const currentCharacter = className[index];\n if (bracketDepth === 0 && parenDepth === 0) {\n if (currentCharacter === MODIFIER_SEPARATOR) {\n modifiers.push(className.slice(modifierStart, index));\n modifierStart = index + 1;\n continue;\n }\n if (currentCharacter === '/') {\n postfixModifierPosition = index;\n continue;\n }\n }\n if (currentCharacter === '[') bracketDepth++;else if (currentCharacter === ']') bracketDepth--;else if (currentCharacter === '(') parenDepth++;else if (currentCharacter === ')') parenDepth--;\n }\n const baseClassNameWithImportantModifier = modifiers.length === 0 ? className : className.slice(modifierStart);\n // Inline important modifier check\n let baseClassName = baseClassNameWithImportantModifier;\n let hasImportantModifier = false;\n if (baseClassNameWithImportantModifier.endsWith(IMPORTANT_MODIFIER)) {\n baseClassName = baseClassNameWithImportantModifier.slice(0, -1);\n hasImportantModifier = true;\n } else if (\n /**\n * In Tailwind CSS v3 the important modifier was at the start of the base class name. This is still supported for legacy reasons.\n * @see https://github.com/dcastil/tailwind-merge/issues/513#issuecomment-2614029864\n */\n baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER)) {\n baseClassName = baseClassNameWithImportantModifier.slice(1);\n hasImportantModifier = true;\n }\n const maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : undefined;\n return createResultObject(modifiers, hasImportantModifier, baseClassName, maybePostfixModifierPosition);\n };\n if (prefix) {\n const fullPrefix = prefix + MODIFIER_SEPARATOR;\n const parseClassNameOriginal = parseClassName;\n parseClassName = className => className.startsWith(fullPrefix) ? parseClassNameOriginal(className.slice(fullPrefix.length)) : createResultObject(EMPTY_MODIFIERS, false, className, undefined, true);\n }\n if (experimentalParseClassName) {\n const parseClassNameOriginal = parseClassName;\n parseClassName = className => experimentalParseClassName({\n className,\n parseClassName: parseClassNameOriginal\n });\n }\n return parseClassName;\n};\n\n/**\n * Sorts modifiers according to following schema:\n * - Predefined modifiers are sorted alphabetically\n * - When an arbitrary variant appears, it must be preserved which modifiers are before and after it\n */\nconst createSortModifiers = config => {\n // Pre-compute weights for all known modifiers for O(1) comparison\n const modifierWeights = new Map();\n // Assign weights to sensitive modifiers (highest priority, but preserve order)\n config.orderSensitiveModifiers.forEach((mod, index) => {\n modifierWeights.set(mod, 1000000 + index); // High weights for sensitive mods\n });\n return modifiers => {\n const result = [];\n let currentSegment = [];\n // Process modifiers in one pass\n for (let i = 0; i < modifiers.length; i++) {\n const modifier = modifiers[i];\n // Check if modifier is sensitive (starts with '[' or in orderSensitiveModifiers)\n const isArbitrary = modifier[0] === '[';\n const isOrderSensitive = modifierWeights.has(modifier);\n if (isArbitrary || isOrderSensitive) {\n // Sort and flush current segment alphabetically\n if (currentSegment.length > 0) {\n currentSegment.sort();\n result.push(...currentSegment);\n currentSegment = [];\n }\n result.push(modifier);\n } else {\n // Regular modifier - add to current segment for batch sorting\n currentSegment.push(modifier);\n }\n }\n // Sort and add any remaining segment items\n if (currentSegment.length > 0) {\n currentSegment.sort();\n result.push(...currentSegment);\n }\n return result;\n };\n};\nconst createConfigUtils = config => ({\n cache: createLruCache(config.cacheSize),\n parseClassName: createParseClassName(config),\n sortModifiers: createSortModifiers(config),\n postfixLookupClassGroupIds: createPostfixLookupClassGroupIds(config),\n ...createClassGroupUtils(config)\n});\nconst createPostfixLookupClassGroupIds = config => {\n const lookup = Object.create(null);\n const classGroupIds = config.postfixLookupClassGroups;\n if (classGroupIds) {\n for (let i = 0; i < classGroupIds.length; i++) {\n lookup[classGroupIds[i]] = true;\n }\n }\n return lookup;\n};\nconst SPLIT_CLASSES_REGEX = /\\s+/;\nconst mergeClassList = (classList, configUtils) => {\n const {\n parseClassName,\n getClassGroupId,\n getConflictingClassGroupIds,\n sortModifiers,\n postfixLookupClassGroupIds\n } = configUtils;\n /**\n * Set of classGroupIds in following format:\n * `{importantModifier}{variantModifiers}{classGroupId}`\n * @example 'float'\n * @example 'hover:focus:bg-color'\n * @example 'md:!pr'\n */\n const classGroupsInConflict = [];\n const classNames = classList.trim().split(SPLIT_CLASSES_REGEX);\n let result = '';\n for (let index = classNames.length - 1; index >= 0; index -= 1) {\n const originalClassName = classNames[index];\n const {\n isExternal,\n modifiers,\n hasImportantModifier,\n baseClassName,\n maybePostfixModifierPosition\n } = parseClassName(originalClassName);\n if (isExternal) {\n result = originalClassName + (result.length > 0 ? ' ' + result : result);\n continue;\n }\n let hasPostfixModifier = !!maybePostfixModifierPosition;\n let classGroupId;\n if (hasPostfixModifier) {\n const baseClassNameWithoutPostfix = baseClassName.substring(0, maybePostfixModifierPosition);\n classGroupId = getClassGroupId(baseClassNameWithoutPostfix);\n const classGroupIdWithPostfix = classGroupId && postfixLookupClassGroupIds[classGroupId] ? getClassGroupId(baseClassName) : undefined;\n if (classGroupIdWithPostfix && classGroupIdWithPostfix !== classGroupId) {\n classGroupId = classGroupIdWithPostfix;\n hasPostfixModifier = false;\n }\n } else {\n classGroupId = getClassGroupId(baseClassName);\n }\n if (!classGroupId) {\n if (!hasPostfixModifier) {\n // Not a Tailwind class\n result = originalClassName + (result.length > 0 ? ' ' + result : result);\n continue;\n }\n classGroupId = getClassGroupId(baseClassName);\n if (!classGroupId) {\n // Not a Tailwind class\n result = originalClassName + (result.length > 0 ? ' ' + result : result);\n continue;\n }\n hasPostfixModifier = false;\n }\n // Fast path: skip sorting for empty or single modifier\n const variantModifier = modifiers.length === 0 ? '' : modifiers.length === 1 ? modifiers[0] : sortModifiers(modifiers).join(':');\n const modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier;\n const classId = modifierId + classGroupId;\n if (classGroupsInConflict.indexOf(classId) > -1) {\n // Tailwind class omitted due to conflict\n continue;\n }\n classGroupsInConflict.push(classId);\n const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier);\n for (let i = 0; i < conflictGroups.length; ++i) {\n const group = conflictGroups[i];\n classGroupsInConflict.push(modifierId + group);\n }\n // Tailwind class not in conflict\n result = originalClassName + (result.length > 0 ? ' ' + result : result);\n }\n return result;\n};\n\n/**\n * The code in this file is copied from https://github.com/lukeed/clsx and modified to suit the needs of tailwind-merge better.\n *\n * Specifically:\n * - Runtime code from https://github.com/lukeed/clsx/blob/v1.2.1/src/index.js\n * - TypeScript types from https://github.com/lukeed/clsx/blob/v1.2.1/clsx.d.ts\n *\n * Original code has MIT license: Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n */\nconst twJoin = (...classLists) => {\n let index = 0;\n let argument;\n let resolvedValue;\n let string = '';\n while (index < classLists.length) {\n if (argument = classLists[index++]) {\n if (resolvedValue = toValue(argument)) {\n string && (string += ' ');\n string += resolvedValue;\n }\n }\n }\n return string;\n};\nconst toValue = mix => {\n // Fast path for strings\n if (typeof mix === 'string') {\n return mix;\n }\n let resolvedValue;\n let string = '';\n for (let k = 0; k < mix.length; k++) {\n if (mix[k]) {\n if (resolvedValue = toValue(mix[k])) {\n string && (string += ' ');\n string += resolvedValue;\n }\n }\n }\n return string;\n};\nconst createTailwindMerge = (createConfigFirst, ...createConfigRest) => {\n let configUtils;\n let cacheGet;\n let cacheSet;\n let functionToCall;\n const initTailwindMerge = classList => {\n const config = createConfigRest.reduce((previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig), createConfigFirst());\n configUtils = createConfigUtils(config);\n cacheGet = configUtils.cache.get;\n cacheSet = configUtils.cache.set;\n functionToCall = tailwindMerge;\n return tailwindMerge(classList);\n };\n const tailwindMerge = classList => {\n const cachedResult = cacheGet(classList);\n if (cachedResult) {\n return cachedResult;\n }\n const result = mergeClassList(classList, configUtils);\n cacheSet(classList, result);\n return result;\n };\n functionToCall = initTailwindMerge;\n return (...args) => functionToCall(twJoin(...args));\n};\nconst fallbackThemeArr = [];\nconst fromTheme = key => {\n const themeGetter = theme => theme[key] || fallbackThemeArr;\n themeGetter.isThemeGetter = true;\n return themeGetter;\n};\nconst arbitraryValueRegex = /^\\[(?:(\\w[\\w-]*):)?(.+)\\]$/i;\nconst arbitraryVariableRegex = /^\\((?:(\\w[\\w-]*):)?(.+)\\)$/i;\nconst fractionRegex = /^\\d+(?:\\.\\d+)?\\/\\d+(?:\\.\\d+)?$/;\nconst tshirtUnitRegex = /^(\\d+(\\.\\d+)?)?(xs|sm|md|lg|xl)$/;\nconst lengthUnitRegex = /\\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\\b(calc|min|max|clamp)\\(.+\\)|^0$/;\nconst colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\\(.+\\)$/;\n// Shadow always begins with x and y offset separated by underscore optionally prepended by inset\nconst shadowRegex = /^(inset_)?-?((\\d+)?\\.?(\\d+)[a-z]+|0)_-?((\\d+)?\\.?(\\d+)[a-z]+|0)/;\nconst imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\\(.+\\)$/;\nconst isFraction = value => fractionRegex.test(value);\nconst isNumber = value => !!value && !Number.isNaN(Number(value));\nconst isInteger = value => !!value && Number.isInteger(Number(value));\nconst isPercent = value => value.endsWith('%') && isNumber(value.slice(0, -1));\nconst isTshirtSize = value => tshirtUnitRegex.test(value);\nconst isAny = () => true;\nconst isLengthOnly = value =>\n// `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.\n// For example, `hsl(0 0% 0%)` would be classified as a length without this check.\n// I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.\nlengthUnitRegex.test(value) && !colorFunctionRegex.test(value);\nconst isNever = () => false;\nconst isShadow = value => shadowRegex.test(value);\nconst isImage = value => imageRegex.test(value);\nconst isAnyNonArbitrary = value => !isArbitraryValue(value) && !isArbitraryVariable(value);\nconst isNamedContainerQuery = value => value.startsWith('@container') && (value[10] === '/' && value[11] !== undefined || value[11] === 's' && value[16] !== undefined && value.startsWith('-size/', 10) || value[11] === 'n' && value[18] !== undefined && value.startsWith('-normal/', 10));\nconst isArbitrarySize = value => getIsArbitraryValue(value, isLabelSize, isNever);\nconst isArbitraryValue = value => arbitraryValueRegex.test(value);\nconst isArbitraryLength = value => getIsArbitraryValue(value, isLabelLength, isLengthOnly);\nconst isArbitraryNumber = value => getIsArbitraryValue(value, isLabelNumber, isNumber);\nconst isArbitraryWeight = value => getIsArbitraryValue(value, isLabelWeight, isAny);\nconst isArbitraryFamilyName = value => getIsArbitraryValue(value, isLabelFamilyName, isNever);\nconst isArbitraryPosition = value => getIsArbitraryValue(value, isLabelPosition, isNever);\nconst isArbitraryImage = value => getIsArbitraryValue(value, isLabelImage, isImage);\nconst isArbitraryShadow = value => getIsArbitraryValue(value, isLabelShadow, isShadow);\nconst isArbitraryVariable = value => arbitraryVariableRegex.test(value);\nconst isArbitraryVariableLength = value => getIsArbitraryVariable(value, isLabelLength);\nconst isArbitraryVariableFamilyName = value => getIsArbitraryVariable(value, isLabelFamilyName);\nconst isArbitraryVariablePosition = value => getIsArbitraryVariable(value, isLabelPosition);\nconst isArbitraryVariableSize = value => getIsArbitraryVariable(value, isLabelSize);\nconst isArbitraryVariableImage = value => getIsArbitraryVariable(value, isLabelImage);\nconst isArbitraryVariableShadow = value => getIsArbitraryVariable(value, isLabelShadow, true);\nconst isArbitraryVariableWeight = value => getIsArbitraryVariable(value, isLabelWeight, true);\n// Helpers\nconst getIsArbitraryValue = (value, testLabel, testValue) => {\n const result = arbitraryValueRegex.exec(value);\n if (result) {\n if (result[1]) {\n return testLabel(result[1]);\n }\n return testValue(result[2]);\n }\n return false;\n};\nconst getIsArbitraryVariable = (value, testLabel, shouldMatchNoLabel = false) => {\n const result = arbitraryVariableRegex.exec(value);\n if (result) {\n if (result[1]) {\n return testLabel(result[1]);\n }\n return shouldMatchNoLabel;\n }\n return false;\n};\n// Labels\nconst isLabelPosition = label => label === 'position' || label === 'percentage';\nconst isLabelImage = label => label === 'image' || label === 'url';\nconst isLabelSize = label => label === 'length' || label === 'size' || label === 'bg-size';\nconst isLabelLength = label => label === 'length';\nconst isLabelNumber = label => label === 'number';\nconst isLabelFamilyName = label => label === 'family-name';\nconst isLabelWeight = label => label === 'number' || label === 'weight';\nconst isLabelShadow = label => label === 'shadow';\nconst validators = /*#__PURE__*/Object.defineProperty({\n __proto__: null,\n isAny,\n isAnyNonArbitrary,\n isArbitraryFamilyName,\n isArbitraryImage,\n isArbitraryLength,\n isArbitraryNumber,\n isArbitraryPosition,\n isArbitraryShadow,\n isArbitrarySize,\n isArbitraryValue,\n isArbitraryVariable,\n isArbitraryVariableFamilyName,\n isArbitraryVariableImage,\n isArbitraryVariableLength,\n isArbitraryVariablePosition,\n isArbitraryVariableShadow,\n isArbitraryVariableSize,\n isArbitraryVariableWeight,\n isArbitraryWeight,\n isFraction,\n isInteger,\n isNamedContainerQuery,\n isNumber,\n isPercent,\n isTshirtSize\n}, Symbol.toStringTag, {\n value: 'Module'\n});\nconst getDefaultConfig = () => {\n /**\n * Theme getters for theme variable namespaces\n * @see https://tailwindcss.com/docs/theme#theme-variable-namespaces\n */\n /***/\n const themeColor = fromTheme('color');\n const themeFont = fromTheme('font');\n const themeText = fromTheme('text');\n const themeFontWeight = fromTheme('font-weight');\n const themeTracking = fromTheme('tracking');\n const themeLeading = fromTheme('leading');\n const themeBreakpoint = fromTheme('breakpoint');\n const themeContainer = fromTheme('container');\n const themeSpacing = fromTheme('spacing');\n const themeRadius = fromTheme('radius');\n const themeShadow = fromTheme('shadow');\n const themeInsetShadow = fromTheme('inset-shadow');\n const themeTextShadow = fromTheme('text-shadow');\n const themeDropShadow = fromTheme('drop-shadow');\n const themeBlur = fromTheme('blur');\n const themePerspective = fromTheme('perspective');\n const themeAspect = fromTheme('aspect');\n const themeEase = fromTheme('ease');\n const themeAnimate = fromTheme('animate');\n /**\n * Helpers to avoid repeating the same scales\n *\n * We use functions that create a new array every time they're called instead of static arrays.\n * This ensures that users who modify any scale by mutating the array (e.g. with `array.push(element)`) don't accidentally mutate arrays in other parts of the config.\n */\n /***/\n const scaleBreak = () => ['auto', 'avoid', 'all', 'avoid-page', 'page', 'left', 'right', 'column'];\n const scalePosition = () => ['center', 'top', 'bottom', 'left', 'right', 'top-left',\n // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n 'left-top', 'top-right',\n // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n 'right-top', 'bottom-right',\n // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n 'right-bottom', 'bottom-left',\n // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n 'left-bottom'];\n const scalePositionWithArbitrary = () => [...scalePosition(), isArbitraryVariable, isArbitraryValue];\n const scaleOverflow = () => ['auto', 'hidden', 'clip', 'visible', 'scroll'];\n const scaleOverscroll = () => ['auto', 'contain', 'none'];\n const scaleUnambiguousSpacing = () => [isArbitraryVariable, isArbitraryValue, themeSpacing];\n const scaleInset = () => [isFraction, 'full', 'auto', ...scaleUnambiguousSpacing()];\n const scaleGridTemplateColsRows = () => [isInteger, 'none', 'subgrid', isArbitraryVariable, isArbitraryValue];\n const scaleGridColRowStartAndEnd = () => ['auto', {\n span: ['full', isInteger, isArbitraryVariable, isArbitraryValue]\n }, isInteger, isArbitraryVariable, isArbitraryValue];\n const scaleGridColRowStartOrEnd = () => [isInteger, 'auto', isArbitraryVariable, isArbitraryValue];\n const scaleGridAutoColsRows = () => ['auto', 'min', 'max', 'fr', isArbitraryVariable, isArbitraryValue];\n const scaleAlignPrimaryAxis = () => ['start', 'end', 'center', 'between', 'around', 'evenly', 'stretch', 'baseline', 'center-safe', 'end-safe'];\n const scaleAlignSecondaryAxis = () => ['start', 'end', 'center', 'stretch', 'center-safe', 'end-safe'];\n const scaleMargin = () => ['auto', ...scaleUnambiguousSpacing()];\n const scaleSizing = () => [isFraction, 'auto', 'full', 'dvw', 'dvh', 'lvw', 'lvh', 'svw', 'svh', 'min', 'max', 'fit', ...scaleUnambiguousSpacing()];\n const scaleSizingInline = () => [isFraction, 'screen', 'full', 'dvw', 'lvw', 'svw', 'min', 'max', 'fit', ...scaleUnambiguousSpacing()];\n const scaleSizingBlock = () => [isFraction, 'screen', 'full', 'lh', 'dvh', 'lvh', 'svh', 'min', 'max', 'fit', ...scaleUnambiguousSpacing()];\n const scaleColor = () => [themeColor, isArbitraryVariable, isArbitraryValue];\n const scaleBgPosition = () => [...scalePosition(), isArbitraryVariablePosition, isArbitraryPosition, {\n position: [isArbitraryVariable, isArbitraryValue]\n }];\n const scaleBgRepeat = () => ['no-repeat', {\n repeat: ['', 'x', 'y', 'space', 'round']\n }];\n const scaleBgSize = () => ['auto', 'cover', 'contain', isArbitraryVariableSize, isArbitrarySize, {\n size: [isArbitraryVariable, isArbitraryValue]\n }];\n const scaleGradientStopPosition = () => [isPercent, isArbitraryVariableLength, isArbitraryLength];\n const scaleRadius = () => [\n // Deprecated since Tailwind CSS v4.0.0\n '', 'none', 'full', themeRadius, isArbitraryVariable, isArbitraryValue];\n const scaleBorderWidth = () => ['', isNumber, isArbitraryVariableLength, isArbitraryLength];\n const scaleLineStyle = () => ['solid', 'dashed', 'dotted', 'double'];\n const scaleBlendMode = () => ['normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'];\n const scaleMaskImagePosition = () => [isNumber, isPercent, isArbitraryVariablePosition, isArbitraryPosition];\n const scaleBlur = () => [\n // Deprecated since Tailwind CSS v4.0.0\n '', 'none', themeBlur, isArbitraryVariable, isArbitraryValue];\n const scaleRotate = () => ['none', isNumber, isArbitraryVariable, isArbitraryValue];\n const scaleScale = () => ['none', isNumber, isArbitraryVariable, isArbitraryValue];\n const scaleSkew = () => [isNumber, isArbitraryVariable, isArbitraryValue];\n const scaleTranslate = () => [isFraction, 'full', ...scaleUnambiguousSpacing()];\n return {\n cacheSize: 500,\n theme: {\n animate: ['spin', 'ping', 'pulse', 'bounce'],\n aspect: ['video'],\n blur: [isTshirtSize],\n breakpoint: [isTshirtSize],\n color: [isAny],\n container: [isTshirtSize],\n 'drop-shadow': [isTshirtSize],\n ease: ['in', 'out', 'in-out'],\n font: [isAnyNonArbitrary],\n 'font-weight': ['thin', 'extralight', 'light', 'normal', 'medium', 'semibold', 'bold', 'extrabold', 'black'],\n 'inset-shadow': [isTshirtSize],\n leading: ['none', 'tight', 'snug', 'normal', 'relaxed', 'loose'],\n perspective: ['dramatic', 'near', 'normal', 'midrange', 'distant', 'none'],\n radius: [isTshirtSize],\n shadow: [isTshirtSize],\n spacing: ['px', isNumber],\n text: [isTshirtSize],\n 'text-shadow': [isTshirtSize],\n tracking: ['tighter', 'tight', 'normal', 'wide', 'wider', 'widest']\n },\n classGroups: {\n // --------------\n // --- Layout ---\n // --------------\n /**\n * Aspect Ratio\n * @see https://tailwindcss.com/docs/aspect-ratio\n */\n aspect: [{\n aspect: ['auto', 'square', isFraction, isArbitraryValue, isArbitraryVariable, themeAspect]\n }],\n /**\n * Container\n * @see https://tailwindcss.com/docs/container\n * @deprecated since Tailwind CSS v4.0.0\n */\n container: ['container'],\n /**\n * Container Type\n * @see https://tailwindcss.com/docs/responsive-design#container-queries\n */\n 'container-type': [{\n '@container': ['', 'normal', 'size', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Container Name\n * @see https://tailwindcss.com/docs/responsive-design#named-containers\n */\n 'container-named': [isNamedContainerQuery],\n /**\n * Columns\n * @see https://tailwindcss.com/docs/columns\n */\n columns: [{\n columns: [isNumber, isArbitraryValue, isArbitraryVariable, themeContainer]\n }],\n /**\n * Break After\n * @see https://tailwindcss.com/docs/break-after\n */\n 'break-after': [{\n 'break-after': scaleBreak()\n }],\n /**\n * Break Before\n * @see https://tailwindcss.com/docs/break-before\n */\n 'break-before': [{\n 'break-before': scaleBreak()\n }],\n /**\n * Break Inside\n * @see https://tailwindcss.com/docs/break-inside\n */\n 'break-inside': [{\n 'break-inside': ['auto', 'avoid', 'avoid-page', 'avoid-column']\n }],\n /**\n * Box Decoration Break\n * @see https://tailwindcss.com/docs/box-decoration-break\n */\n 'box-decoration': [{\n 'box-decoration': ['slice', 'clone']\n }],\n /**\n * Box Sizing\n * @see https://tailwindcss.com/docs/box-sizing\n */\n box: [{\n box: ['border', 'content']\n }],\n /**\n * Display\n * @see https://tailwindcss.com/docs/display\n */\n display: ['block', 'inline-block', 'inline', 'flex', 'inline-flex', 'table', 'inline-table', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row-group', 'table-row', 'flow-root', 'grid', 'inline-grid', 'contents', 'list-item', 'hidden'],\n /**\n * Screen Reader Only\n * @see https://tailwindcss.com/docs/display#screen-reader-only\n */\n sr: ['sr-only', 'not-sr-only'],\n /**\n * Floats\n * @see https://tailwindcss.com/docs/float\n */\n float: [{\n float: ['right', 'left', 'none', 'start', 'end']\n }],\n /**\n * Clear\n * @see https://tailwindcss.com/docs/clear\n */\n clear: [{\n clear: ['left', 'right', 'both', 'none', 'start', 'end']\n }],\n /**\n * Isolation\n * @see https://tailwindcss.com/docs/isolation\n */\n isolation: ['isolate', 'isolation-auto'],\n /**\n * Object Fit\n * @see https://tailwindcss.com/docs/object-fit\n */\n 'object-fit': [{\n object: ['contain', 'cover', 'fill', 'none', 'scale-down']\n }],\n /**\n * Object Position\n * @see https://tailwindcss.com/docs/object-position\n */\n 'object-position': [{\n object: scalePositionWithArbitrary()\n }],\n /**\n * Overflow\n * @see https://tailwindcss.com/docs/overflow\n */\n overflow: [{\n overflow: scaleOverflow()\n }],\n /**\n * Overflow X\n * @see https://tailwindcss.com/docs/overflow\n */\n 'overflow-x': [{\n 'overflow-x': scaleOverflow()\n }],\n /**\n * Overflow Y\n * @see https://tailwindcss.com/docs/overflow\n */\n 'overflow-y': [{\n 'overflow-y': scaleOverflow()\n }],\n /**\n * Overscroll Behavior\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n overscroll: [{\n overscroll: scaleOverscroll()\n }],\n /**\n * Overscroll Behavior X\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n 'overscroll-x': [{\n 'overscroll-x': scaleOverscroll()\n }],\n /**\n * Overscroll Behavior Y\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n 'overscroll-y': [{\n 'overscroll-y': scaleOverscroll()\n }],\n /**\n * Position\n * @see https://tailwindcss.com/docs/position\n */\n position: ['static', 'fixed', 'absolute', 'relative', 'sticky'],\n /**\n * Inset\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n inset: [{\n inset: scaleInset()\n }],\n /**\n * Inset Inline\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-x': [{\n 'inset-x': scaleInset()\n }],\n /**\n * Inset Block\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-y': [{\n 'inset-y': scaleInset()\n }],\n /**\n * Inset Inline Start\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n * @todo class group will be renamed to `inset-s` in next major release\n */\n start: [{\n 'inset-s': scaleInset(),\n /**\n * @deprecated since Tailwind CSS v4.2.0 in favor of `inset-s-*` utilities.\n * @see https://github.com/tailwindlabs/tailwindcss/pull/19613\n */\n start: scaleInset()\n }],\n /**\n * Inset Inline End\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n * @todo class group will be renamed to `inset-e` in next major release\n */\n end: [{\n 'inset-e': scaleInset(),\n /**\n * @deprecated since Tailwind CSS v4.2.0 in favor of `inset-e-*` utilities.\n * @see https://github.com/tailwindlabs/tailwindcss/pull/19613\n */\n end: scaleInset()\n }],\n /**\n * Inset Block Start\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-bs': [{\n 'inset-bs': scaleInset()\n }],\n /**\n * Inset Block End\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-be': [{\n 'inset-be': scaleInset()\n }],\n /**\n * Top\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n top: [{\n top: scaleInset()\n }],\n /**\n * Right\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n right: [{\n right: scaleInset()\n }],\n /**\n * Bottom\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n bottom: [{\n bottom: scaleInset()\n }],\n /**\n * Left\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n left: [{\n left: scaleInset()\n }],\n /**\n * Visibility\n * @see https://tailwindcss.com/docs/visibility\n */\n visibility: ['visible', 'invisible', 'collapse'],\n /**\n * Z-Index\n * @see https://tailwindcss.com/docs/z-index\n */\n z: [{\n z: [isInteger, 'auto', isArbitraryVariable, isArbitraryValue]\n }],\n // ------------------------\n // --- Flexbox and Grid ---\n // ------------------------\n /**\n * Flex Basis\n * @see https://tailwindcss.com/docs/flex-basis\n */\n basis: [{\n basis: [isFraction, 'full', 'auto', themeContainer, ...scaleUnambiguousSpacing()]\n }],\n /**\n * Flex Direction\n * @see https://tailwindcss.com/docs/flex-direction\n */\n 'flex-direction': [{\n flex: ['row', 'row-reverse', 'col', 'col-reverse']\n }],\n /**\n * Flex Wrap\n * @see https://tailwindcss.com/docs/flex-wrap\n */\n 'flex-wrap': [{\n flex: ['nowrap', 'wrap', 'wrap-reverse']\n }],\n /**\n * Flex\n * @see https://tailwindcss.com/docs/flex\n */\n flex: [{\n flex: [isNumber, isFraction, 'auto', 'initial', 'none', isArbitraryValue]\n }],\n /**\n * Flex Grow\n * @see https://tailwindcss.com/docs/flex-grow\n */\n grow: [{\n grow: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Flex Shrink\n * @see https://tailwindcss.com/docs/flex-shrink\n */\n shrink: [{\n shrink: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Order\n * @see https://tailwindcss.com/docs/order\n */\n order: [{\n order: [isInteger, 'first', 'last', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Grid Template Columns\n * @see https://tailwindcss.com/docs/grid-template-columns\n */\n 'grid-cols': [{\n 'grid-cols': scaleGridTemplateColsRows()\n }],\n /**\n * Grid Column Start / End\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-start-end': [{\n col: scaleGridColRowStartAndEnd()\n }],\n /**\n * Grid Column Start\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-start': [{\n 'col-start': scaleGridColRowStartOrEnd()\n }],\n /**\n * Grid Column End\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-end': [{\n 'col-end': scaleGridColRowStartOrEnd()\n }],\n /**\n * Grid Template Rows\n * @see https://tailwindcss.com/docs/grid-template-rows\n */\n 'grid-rows': [{\n 'grid-rows': scaleGridTemplateColsRows()\n }],\n /**\n * Grid Row Start / End\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-start-end': [{\n row: scaleGridColRowStartAndEnd()\n }],\n /**\n * Grid Row Start\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-start': [{\n 'row-start': scaleGridColRowStartOrEnd()\n }],\n /**\n * Grid Row End\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-end': [{\n 'row-end': scaleGridColRowStartOrEnd()\n }],\n /**\n * Grid Auto Flow\n * @see https://tailwindcss.com/docs/grid-auto-flow\n */\n 'grid-flow': [{\n 'grid-flow': ['row', 'col', 'dense', 'row-dense', 'col-dense']\n }],\n /**\n * Grid Auto Columns\n * @see https://tailwindcss.com/docs/grid-auto-columns\n */\n 'auto-cols': [{\n 'auto-cols': scaleGridAutoColsRows()\n }],\n /**\n * Grid Auto Rows\n * @see https://tailwindcss.com/docs/grid-auto-rows\n */\n 'auto-rows': [{\n 'auto-rows': scaleGridAutoColsRows()\n }],\n /**\n * Gap\n * @see https://tailwindcss.com/docs/gap\n */\n gap: [{\n gap: scaleUnambiguousSpacing()\n }],\n /**\n * Gap X\n * @see https://tailwindcss.com/docs/gap\n */\n 'gap-x': [{\n 'gap-x': scaleUnambiguousSpacing()\n }],\n /**\n * Gap Y\n * @see https://tailwindcss.com/docs/gap\n */\n 'gap-y': [{\n 'gap-y': scaleUnambiguousSpacing()\n }],\n /**\n * Justify Content\n * @see https://tailwindcss.com/docs/justify-content\n */\n 'justify-content': [{\n justify: [...scaleAlignPrimaryAxis(), 'normal']\n }],\n /**\n * Justify Items\n * @see https://tailwindcss.com/docs/justify-items\n */\n 'justify-items': [{\n 'justify-items': [...scaleAlignSecondaryAxis(), 'normal']\n }],\n /**\n * Justify Self\n * @see https://tailwindcss.com/docs/justify-self\n */\n 'justify-self': [{\n 'justify-self': ['auto', ...scaleAlignSecondaryAxis()]\n }],\n /**\n * Align Content\n * @see https://tailwindcss.com/docs/align-content\n */\n 'align-content': [{\n content: ['normal', ...scaleAlignPrimaryAxis()]\n }],\n /**\n * Align Items\n * @see https://tailwindcss.com/docs/align-items\n */\n 'align-items': [{\n items: [...scaleAlignSecondaryAxis(), {\n baseline: ['', 'last']\n }]\n }],\n /**\n * Align Self\n * @see https://tailwindcss.com/docs/align-self\n */\n 'align-self': [{\n self: ['auto', ...scaleAlignSecondaryAxis(), {\n baseline: ['', 'last']\n }]\n }],\n /**\n * Place Content\n * @see https://tailwindcss.com/docs/place-content\n */\n 'place-content': [{\n 'place-content': scaleAlignPrimaryAxis()\n }],\n /**\n * Place Items\n * @see https://tailwindcss.com/docs/place-items\n */\n 'place-items': [{\n 'place-items': [...scaleAlignSecondaryAxis(), 'baseline']\n }],\n /**\n * Place Self\n * @see https://tailwindcss.com/docs/place-self\n */\n 'place-self': [{\n 'place-self': ['auto', ...scaleAlignSecondaryAxis()]\n }],\n // Spacing\n /**\n * Padding\n * @see https://tailwindcss.com/docs/padding\n */\n p: [{\n p: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Inline\n * @see https://tailwindcss.com/docs/padding\n */\n px: [{\n px: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Block\n * @see https://tailwindcss.com/docs/padding\n */\n py: [{\n py: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Inline Start\n * @see https://tailwindcss.com/docs/padding\n */\n ps: [{\n ps: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Inline End\n * @see https://tailwindcss.com/docs/padding\n */\n pe: [{\n pe: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Block Start\n * @see https://tailwindcss.com/docs/padding\n */\n pbs: [{\n pbs: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Block End\n * @see https://tailwindcss.com/docs/padding\n */\n pbe: [{\n pbe: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Top\n * @see https://tailwindcss.com/docs/padding\n */\n pt: [{\n pt: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Right\n * @see https://tailwindcss.com/docs/padding\n */\n pr: [{\n pr: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Bottom\n * @see https://tailwindcss.com/docs/padding\n */\n pb: [{\n pb: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Left\n * @see https://tailwindcss.com/docs/padding\n */\n pl: [{\n pl: scaleUnambiguousSpacing()\n }],\n /**\n * Margin\n * @see https://tailwindcss.com/docs/margin\n */\n m: [{\n m: scaleMargin()\n }],\n /**\n * Margin Inline\n * @see https://tailwindcss.com/docs/margin\n */\n mx: [{\n mx: scaleMargin()\n }],\n /**\n * Margin Block\n * @see https://tailwindcss.com/docs/margin\n */\n my: [{\n my: scaleMargin()\n }],\n /**\n * Margin Inline Start\n * @see https://tailwindcss.com/docs/margin\n */\n ms: [{\n ms: scaleMargin()\n }],\n /**\n * Margin Inline End\n * @see https://tailwindcss.com/docs/margin\n */\n me: [{\n me: scaleMargin()\n }],\n /**\n * Margin Block Start\n * @see https://tailwindcss.com/docs/margin\n */\n mbs: [{\n mbs: scaleMargin()\n }],\n /**\n * Margin Block End\n * @see https://tailwindcss.com/docs/margin\n */\n mbe: [{\n mbe: scaleMargin()\n }],\n /**\n * Margin Top\n * @see https://tailwindcss.com/docs/margin\n */\n mt: [{\n mt: scaleMargin()\n }],\n /**\n * Margin Right\n * @see https://tailwindcss.com/docs/margin\n */\n mr: [{\n mr: scaleMargin()\n }],\n /**\n * Margin Bottom\n * @see https://tailwindcss.com/docs/margin\n */\n mb: [{\n mb: scaleMargin()\n }],\n /**\n * Margin Left\n * @see https://tailwindcss.com/docs/margin\n */\n ml: [{\n ml: scaleMargin()\n }],\n /**\n * Space Between X\n * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n */\n 'space-x': [{\n 'space-x': scaleUnambiguousSpacing()\n }],\n /**\n * Space Between X Reverse\n * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n */\n 'space-x-reverse': ['space-x-reverse'],\n /**\n * Space Between Y\n * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n */\n 'space-y': [{\n 'space-y': scaleUnambiguousSpacing()\n }],\n /**\n * Space Between Y Reverse\n * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n */\n 'space-y-reverse': ['space-y-reverse'],\n // --------------\n // --- Sizing ---\n // --------------\n /**\n * Size\n * @see https://tailwindcss.com/docs/width#setting-both-width-and-height\n */\n size: [{\n size: scaleSizing()\n }],\n /**\n * Inline Size\n * @see https://tailwindcss.com/docs/width\n */\n 'inline-size': [{\n inline: ['auto', ...scaleSizingInline()]\n }],\n /**\n * Min-Inline Size\n * @see https://tailwindcss.com/docs/min-width\n */\n 'min-inline-size': [{\n 'min-inline': ['auto', ...scaleSizingInline()]\n }],\n /**\n * Max-Inline Size\n * @see https://tailwindcss.com/docs/max-width\n */\n 'max-inline-size': [{\n 'max-inline': ['none', ...scaleSizingInline()]\n }],\n /**\n * Block Size\n * @see https://tailwindcss.com/docs/height\n */\n 'block-size': [{\n block: ['auto', ...scaleSizingBlock()]\n }],\n /**\n * Min-Block Size\n * @see https://tailwindcss.com/docs/min-height\n */\n 'min-block-size': [{\n 'min-block': ['auto', ...scaleSizingBlock()]\n }],\n /**\n * Max-Block Size\n * @see https://tailwindcss.com/docs/max-height\n */\n 'max-block-size': [{\n 'max-block': ['none', ...scaleSizingBlock()]\n }],\n /**\n * Width\n * @see https://tailwindcss.com/docs/width\n */\n w: [{\n w: [themeContainer, 'screen', ...scaleSizing()]\n }],\n /**\n * Min-Width\n * @see https://tailwindcss.com/docs/min-width\n */\n 'min-w': [{\n 'min-w': [themeContainer, 'screen', /** Deprecated. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n 'none', ...scaleSizing()]\n }],\n /**\n * Max-Width\n * @see https://tailwindcss.com/docs/max-width\n */\n 'max-w': [{\n 'max-w': [themeContainer, 'screen', 'none', /** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n 'prose', /** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n {\n screen: [themeBreakpoint]\n }, ...scaleSizing()]\n }],\n /**\n * Height\n * @see https://tailwindcss.com/docs/height\n */\n h: [{\n h: ['screen', 'lh', ...scaleSizing()]\n }],\n /**\n * Min-Height\n * @see https://tailwindcss.com/docs/min-height\n */\n 'min-h': [{\n 'min-h': ['screen', 'lh', 'none', ...scaleSizing()]\n }],\n /**\n * Max-Height\n * @see https://tailwindcss.com/docs/max-height\n */\n 'max-h': [{\n 'max-h': ['screen', 'lh', ...scaleSizing()]\n }],\n // ------------------\n // --- Typography ---\n // ------------------\n /**\n * Font Size\n * @see https://tailwindcss.com/docs/font-size\n */\n 'font-size': [{\n text: ['base', themeText, isArbitraryVariableLength, isArbitraryLength]\n }],\n /**\n * Font Smoothing\n * @see https://tailwindcss.com/docs/font-smoothing\n */\n 'font-smoothing': ['antialiased', 'subpixel-antialiased'],\n /**\n * Font Style\n * @see https://tailwindcss.com/docs/font-style\n */\n 'font-style': ['italic', 'not-italic'],\n /**\n * Font Weight\n * @see https://tailwindcss.com/docs/font-weight\n */\n 'font-weight': [{\n font: [themeFontWeight, isArbitraryVariableWeight, isArbitraryWeight]\n }],\n /**\n * Font Stretch\n * @see https://tailwindcss.com/docs/font-stretch\n */\n 'font-stretch': [{\n 'font-stretch': ['ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded', isPercent, isArbitraryValue]\n }],\n /**\n * Font Family\n * @see https://tailwindcss.com/docs/font-family\n */\n 'font-family': [{\n font: [isArbitraryVariableFamilyName, isArbitraryFamilyName, themeFont]\n }],\n /**\n * Font Feature Settings\n * @see https://tailwindcss.com/docs/font-feature-settings\n */\n 'font-features': [{\n 'font-features': [isArbitraryValue]\n }],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-normal': ['normal-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-ordinal': ['ordinal'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-slashed-zero': ['slashed-zero'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-figure': ['lining-nums', 'oldstyle-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-spacing': ['proportional-nums', 'tabular-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-fraction': ['diagonal-fractions', 'stacked-fractions'],\n /**\n * Letter Spacing\n * @see https://tailwindcss.com/docs/letter-spacing\n */\n tracking: [{\n tracking: [themeTracking, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Line Clamp\n * @see https://tailwindcss.com/docs/line-clamp\n */\n 'line-clamp': [{\n 'line-clamp': [isNumber, 'none', isArbitraryVariable, isArbitraryNumber]\n }],\n /**\n * Line Height\n * @see https://tailwindcss.com/docs/line-height\n */\n leading: [{\n leading: [/** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n themeLeading, ...scaleUnambiguousSpacing()]\n }],\n /**\n * List Style Image\n * @see https://tailwindcss.com/docs/list-style-image\n */\n 'list-image': [{\n 'list-image': ['none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * List Style Position\n * @see https://tailwindcss.com/docs/list-style-position\n */\n 'list-style-position': [{\n list: ['inside', 'outside']\n }],\n /**\n * List Style Type\n * @see https://tailwindcss.com/docs/list-style-type\n */\n 'list-style-type': [{\n list: ['disc', 'decimal', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Text Alignment\n * @see https://tailwindcss.com/docs/text-align\n */\n 'text-alignment': [{\n text: ['left', 'center', 'right', 'justify', 'start', 'end']\n }],\n /**\n * Placeholder Color\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://v3.tailwindcss.com/docs/placeholder-color\n */\n 'placeholder-color': [{\n placeholder: scaleColor()\n }],\n /**\n * Text Color\n * @see https://tailwindcss.com/docs/text-color\n */\n 'text-color': [{\n text: scaleColor()\n }],\n /**\n * Text Decoration\n * @see https://tailwindcss.com/docs/text-decoration\n */\n 'text-decoration': ['underline', 'overline', 'line-through', 'no-underline'],\n /**\n * Text Decoration Style\n * @see https://tailwindcss.com/docs/text-decoration-style\n */\n 'text-decoration-style': [{\n decoration: [...scaleLineStyle(), 'wavy']\n }],\n /**\n * Text Decoration Thickness\n * @see https://tailwindcss.com/docs/text-decoration-thickness\n */\n 'text-decoration-thickness': [{\n decoration: [isNumber, 'from-font', 'auto', isArbitraryVariable, isArbitraryLength]\n }],\n /**\n * Text Decoration Color\n * @see https://tailwindcss.com/docs/text-decoration-color\n */\n 'text-decoration-color': [{\n decoration: scaleColor()\n }],\n /**\n * Text Underline Offset\n * @see https://tailwindcss.com/docs/text-underline-offset\n */\n 'underline-offset': [{\n 'underline-offset': [isNumber, 'auto', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Text Transform\n * @see https://tailwindcss.com/docs/text-transform\n */\n 'text-transform': ['uppercase', 'lowercase', 'capitalize', 'normal-case'],\n /**\n * Text Overflow\n * @see https://tailwindcss.com/docs/text-overflow\n */\n 'text-overflow': ['truncate', 'text-ellipsis', 'text-clip'],\n /**\n * Text Wrap\n * @see https://tailwindcss.com/docs/text-wrap\n */\n 'text-wrap': [{\n text: ['wrap', 'nowrap', 'balance', 'pretty']\n }],\n /**\n * Text Indent\n * @see https://tailwindcss.com/docs/text-indent\n */\n indent: [{\n indent: scaleUnambiguousSpacing()\n }],\n /**\n * Tab Size\n * @see https://tailwindcss.com/docs/tab-size\n */\n 'tab-size': [{\n tab: [isInteger, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Vertical Alignment\n * @see https://tailwindcss.com/docs/vertical-align\n */\n 'vertical-align': [{\n align: ['baseline', 'top', 'middle', 'bottom', 'text-top', 'text-bottom', 'sub', 'super', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Whitespace\n * @see https://tailwindcss.com/docs/whitespace\n */\n whitespace: [{\n whitespace: ['normal', 'nowrap', 'pre', 'pre-line', 'pre-wrap', 'break-spaces']\n }],\n /**\n * Word Break\n * @see https://tailwindcss.com/docs/word-break\n */\n break: [{\n break: ['normal', 'words', 'all', 'keep']\n }],\n /**\n * Overflow Wrap\n * @see https://tailwindcss.com/docs/overflow-wrap\n */\n wrap: [{\n wrap: ['break-word', 'anywhere', 'normal']\n }],\n /**\n * Hyphens\n * @see https://tailwindcss.com/docs/hyphens\n */\n hyphens: [{\n hyphens: ['none', 'manual', 'auto']\n }],\n /**\n * Content\n * @see https://tailwindcss.com/docs/content\n */\n content: [{\n content: ['none', isArbitraryVariable, isArbitraryValue]\n }],\n // -------------------\n // --- Backgrounds ---\n // -------------------\n /**\n * Background Attachment\n * @see https://tailwindcss.com/docs/background-attachment\n */\n 'bg-attachment': [{\n bg: ['fixed', 'local', 'scroll']\n }],\n /**\n * Background Clip\n * @see https://tailwindcss.com/docs/background-clip\n */\n 'bg-clip': [{\n 'bg-clip': ['border', 'padding', 'content', 'text']\n }],\n /**\n * Background Origin\n * @see https://tailwindcss.com/docs/background-origin\n */\n 'bg-origin': [{\n 'bg-origin': ['border', 'padding', 'content']\n }],\n /**\n * Background Position\n * @see https://tailwindcss.com/docs/background-position\n */\n 'bg-position': [{\n bg: scaleBgPosition()\n }],\n /**\n * Background Repeat\n * @see https://tailwindcss.com/docs/background-repeat\n */\n 'bg-repeat': [{\n bg: scaleBgRepeat()\n }],\n /**\n * Background Size\n * @see https://tailwindcss.com/docs/background-size\n */\n 'bg-size': [{\n bg: scaleBgSize()\n }],\n /**\n * Background Image\n * @see https://tailwindcss.com/docs/background-image\n */\n 'bg-image': [{\n bg: ['none', {\n linear: [{\n to: ['t', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl']\n }, isInteger, isArbitraryVariable, isArbitraryValue],\n radial: ['', isArbitraryVariable, isArbitraryValue],\n conic: [isInteger, isArbitraryVariable, isArbitraryValue]\n }, isArbitraryVariableImage, isArbitraryImage]\n }],\n /**\n * Background Color\n * @see https://tailwindcss.com/docs/background-color\n */\n 'bg-color': [{\n bg: scaleColor()\n }],\n /**\n * Gradient Color Stops From Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-from-pos': [{\n from: scaleGradientStopPosition()\n }],\n /**\n * Gradient Color Stops Via Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-via-pos': [{\n via: scaleGradientStopPosition()\n }],\n /**\n * Gradient Color Stops To Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-to-pos': [{\n to: scaleGradientStopPosition()\n }],\n /**\n * Gradient Color Stops From\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-from': [{\n from: scaleColor()\n }],\n /**\n * Gradient Color Stops Via\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-via': [{\n via: scaleColor()\n }],\n /**\n * Gradient Color Stops To\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-to': [{\n to: scaleColor()\n }],\n // ---------------\n // --- Borders ---\n // ---------------\n /**\n * Border Radius\n * @see https://tailwindcss.com/docs/border-radius\n */\n rounded: [{\n rounded: scaleRadius()\n }],\n /**\n * Border Radius Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-s': [{\n 'rounded-s': scaleRadius()\n }],\n /**\n * Border Radius End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-e': [{\n 'rounded-e': scaleRadius()\n }],\n /**\n * Border Radius Top\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-t': [{\n 'rounded-t': scaleRadius()\n }],\n /**\n * Border Radius Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-r': [{\n 'rounded-r': scaleRadius()\n }],\n /**\n * Border Radius Bottom\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-b': [{\n 'rounded-b': scaleRadius()\n }],\n /**\n * Border Radius Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-l': [{\n 'rounded-l': scaleRadius()\n }],\n /**\n * Border Radius Start Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-ss': [{\n 'rounded-ss': scaleRadius()\n }],\n /**\n * Border Radius Start End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-se': [{\n 'rounded-se': scaleRadius()\n }],\n /**\n * Border Radius End End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-ee': [{\n 'rounded-ee': scaleRadius()\n }],\n /**\n * Border Radius End Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-es': [{\n 'rounded-es': scaleRadius()\n }],\n /**\n * Border Radius Top Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-tl': [{\n 'rounded-tl': scaleRadius()\n }],\n /**\n * Border Radius Top Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-tr': [{\n 'rounded-tr': scaleRadius()\n }],\n /**\n * Border Radius Bottom Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-br': [{\n 'rounded-br': scaleRadius()\n }],\n /**\n * Border Radius Bottom Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-bl': [{\n 'rounded-bl': scaleRadius()\n }],\n /**\n * Border Width\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w': [{\n border: scaleBorderWidth()\n }],\n /**\n * Border Width Inline\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-x': [{\n 'border-x': scaleBorderWidth()\n }],\n /**\n * Border Width Block\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-y': [{\n 'border-y': scaleBorderWidth()\n }],\n /**\n * Border Width Inline Start\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-s': [{\n 'border-s': scaleBorderWidth()\n }],\n /**\n * Border Width Inline End\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-e': [{\n 'border-e': scaleBorderWidth()\n }],\n /**\n * Border Width Block Start\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-bs': [{\n 'border-bs': scaleBorderWidth()\n }],\n /**\n * Border Width Block End\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-be': [{\n 'border-be': scaleBorderWidth()\n }],\n /**\n * Border Width Top\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-t': [{\n 'border-t': scaleBorderWidth()\n }],\n /**\n * Border Width Right\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-r': [{\n 'border-r': scaleBorderWidth()\n }],\n /**\n * Border Width Bottom\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-b': [{\n 'border-b': scaleBorderWidth()\n }],\n /**\n * Border Width Left\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-l': [{\n 'border-l': scaleBorderWidth()\n }],\n /**\n * Divide Width X\n * @see https://tailwindcss.com/docs/border-width#between-children\n */\n 'divide-x': [{\n 'divide-x': scaleBorderWidth()\n }],\n /**\n * Divide Width X Reverse\n * @see https://tailwindcss.com/docs/border-width#between-children\n */\n 'divide-x-reverse': ['divide-x-reverse'],\n /**\n * Divide Width Y\n * @see https://tailwindcss.com/docs/border-width#between-children\n */\n 'divide-y': [{\n 'divide-y': scaleBorderWidth()\n }],\n /**\n * Divide Width Y Reverse\n * @see https://tailwindcss.com/docs/border-width#between-children\n */\n 'divide-y-reverse': ['divide-y-reverse'],\n /**\n * Border Style\n * @see https://tailwindcss.com/docs/border-style\n */\n 'border-style': [{\n border: [...scaleLineStyle(), 'hidden', 'none']\n }],\n /**\n * Divide Style\n * @see https://tailwindcss.com/docs/border-style#setting-the-divider-style\n */\n 'divide-style': [{\n divide: [...scaleLineStyle(), 'hidden', 'none']\n }],\n /**\n * Border Color\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color': [{\n border: scaleColor()\n }],\n /**\n * Border Color Inline\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-x': [{\n 'border-x': scaleColor()\n }],\n /**\n * Border Color Block\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-y': [{\n 'border-y': scaleColor()\n }],\n /**\n * Border Color Inline Start\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-s': [{\n 'border-s': scaleColor()\n }],\n /**\n * Border Color Inline End\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-e': [{\n 'border-e': scaleColor()\n }],\n /**\n * Border Color Block Start\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-bs': [{\n 'border-bs': scaleColor()\n }],\n /**\n * Border Color Block End\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-be': [{\n 'border-be': scaleColor()\n }],\n /**\n * Border Color Top\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-t': [{\n 'border-t': scaleColor()\n }],\n /**\n * Border Color Right\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-r': [{\n 'border-r': scaleColor()\n }],\n /**\n * Border Color Bottom\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-b': [{\n 'border-b': scaleColor()\n }],\n /**\n * Border Color Left\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-l': [{\n 'border-l': scaleColor()\n }],\n /**\n * Divide Color\n * @see https://tailwindcss.com/docs/divide-color\n */\n 'divide-color': [{\n divide: scaleColor()\n }],\n /**\n * Outline Style\n * @see https://tailwindcss.com/docs/outline-style\n */\n 'outline-style': [{\n outline: [...scaleLineStyle(), 'none', 'hidden']\n }],\n /**\n * Outline Offset\n * @see https://tailwindcss.com/docs/outline-offset\n */\n 'outline-offset': [{\n 'outline-offset': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Outline Width\n * @see https://tailwindcss.com/docs/outline-width\n */\n 'outline-w': [{\n outline: ['', isNumber, isArbitraryVariableLength, isArbitraryLength]\n }],\n /**\n * Outline Color\n * @see https://tailwindcss.com/docs/outline-color\n */\n 'outline-color': [{\n outline: scaleColor()\n }],\n // ---------------\n // --- Effects ---\n // ---------------\n /**\n * Box Shadow\n * @see https://tailwindcss.com/docs/box-shadow\n */\n shadow: [{\n shadow: [\n // Deprecated since Tailwind CSS v4.0.0\n '', 'none', themeShadow, isArbitraryVariableShadow, isArbitraryShadow]\n }],\n /**\n * Box Shadow Color\n * @see https://tailwindcss.com/docs/box-shadow#setting-the-shadow-color\n */\n 'shadow-color': [{\n shadow: scaleColor()\n }],\n /**\n * Inset Box Shadow\n * @see https://tailwindcss.com/docs/box-shadow#adding-an-inset-shadow\n */\n 'inset-shadow': [{\n 'inset-shadow': ['none', themeInsetShadow, isArbitraryVariableShadow, isArbitraryShadow]\n }],\n /**\n * Inset Box Shadow Color\n * @see https://tailwindcss.com/docs/box-shadow#setting-the-inset-shadow-color\n */\n 'inset-shadow-color': [{\n 'inset-shadow': scaleColor()\n }],\n /**\n * Ring Width\n * @see https://tailwindcss.com/docs/box-shadow#adding-a-ring\n */\n 'ring-w': [{\n ring: scaleBorderWidth()\n }],\n /**\n * Ring Width Inset\n * @see https://v3.tailwindcss.com/docs/ring-width#inset-rings\n * @deprecated since Tailwind CSS v4.0.0\n * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n */\n 'ring-w-inset': ['ring-inset'],\n /**\n * Ring Color\n * @see https://tailwindcss.com/docs/box-shadow#setting-the-ring-color\n */\n 'ring-color': [{\n ring: scaleColor()\n }],\n /**\n * Ring Offset Width\n * @see https://v3.tailwindcss.com/docs/ring-offset-width\n * @deprecated since Tailwind CSS v4.0.0\n * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n */\n 'ring-offset-w': [{\n 'ring-offset': [isNumber, isArbitraryLength]\n }],\n /**\n * Ring Offset Color\n * @see https://v3.tailwindcss.com/docs/ring-offset-color\n * @deprecated since Tailwind CSS v4.0.0\n * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n */\n 'ring-offset-color': [{\n 'ring-offset': scaleColor()\n }],\n /**\n * Inset Ring Width\n * @see https://tailwindcss.com/docs/box-shadow#adding-an-inset-ring\n */\n 'inset-ring-w': [{\n 'inset-ring': scaleBorderWidth()\n }],\n /**\n * Inset Ring Color\n * @see https://tailwindcss.com/docs/box-shadow#setting-the-inset-ring-color\n */\n 'inset-ring-color': [{\n 'inset-ring': scaleColor()\n }],\n /**\n * Text Shadow\n * @see https://tailwindcss.com/docs/text-shadow\n */\n 'text-shadow': [{\n 'text-shadow': ['none', themeTextShadow, isArbitraryVariableShadow, isArbitraryShadow]\n }],\n /**\n * Text Shadow Color\n * @see https://tailwindcss.com/docs/text-shadow#setting-the-shadow-color\n */\n 'text-shadow-color': [{\n 'text-shadow': scaleColor()\n }],\n /**\n * Opacity\n * @see https://tailwindcss.com/docs/opacity\n */\n opacity: [{\n opacity: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Mix Blend Mode\n * @see https://tailwindcss.com/docs/mix-blend-mode\n */\n 'mix-blend': [{\n 'mix-blend': [...scaleBlendMode(), 'plus-darker', 'plus-lighter']\n }],\n /**\n * Background Blend Mode\n * @see https://tailwindcss.com/docs/background-blend-mode\n */\n 'bg-blend': [{\n 'bg-blend': scaleBlendMode()\n }],\n /**\n * Mask Clip\n * @see https://tailwindcss.com/docs/mask-clip\n */\n 'mask-clip': [{\n 'mask-clip': ['border', 'padding', 'content', 'fill', 'stroke', 'view']\n }, 'mask-no-clip'],\n /**\n * Mask Composite\n * @see https://tailwindcss.com/docs/mask-composite\n */\n 'mask-composite': [{\n mask: ['add', 'subtract', 'intersect', 'exclude']\n }],\n /**\n * Mask Image\n * @see https://tailwindcss.com/docs/mask-image\n */\n 'mask-image-linear-pos': [{\n 'mask-linear': [isNumber]\n }],\n 'mask-image-linear-from-pos': [{\n 'mask-linear-from': scaleMaskImagePosition()\n }],\n 'mask-image-linear-to-pos': [{\n 'mask-linear-to': scaleMaskImagePosition()\n }],\n 'mask-image-linear-from-color': [{\n 'mask-linear-from': scaleColor()\n }],\n 'mask-image-linear-to-color': [{\n 'mask-linear-to': scaleColor()\n }],\n 'mask-image-t-from-pos': [{\n 'mask-t-from': scaleMaskImagePosition()\n }],\n 'mask-image-t-to-pos': [{\n 'mask-t-to': scaleMaskImagePosition()\n }],\n 'mask-image-t-from-color': [{\n 'mask-t-from': scaleColor()\n }],\n 'mask-image-t-to-color': [{\n 'mask-t-to': scaleColor()\n }],\n 'mask-image-r-from-pos': [{\n 'mask-r-from': scaleMaskImagePosition()\n }],\n 'mask-image-r-to-pos': [{\n 'mask-r-to': scaleMaskImagePosition()\n }],\n 'mask-image-r-from-color': [{\n 'mask-r-from': scaleColor()\n }],\n 'mask-image-r-to-color': [{\n 'mask-r-to': scaleColor()\n }],\n 'mask-image-b-from-pos': [{\n 'mask-b-from': scaleMaskImagePosition()\n }],\n 'mask-image-b-to-pos': [{\n 'mask-b-to': scaleMaskImagePosition()\n }],\n 'mask-image-b-from-color': [{\n 'mask-b-from': scaleColor()\n }],\n 'mask-image-b-to-color': [{\n 'mask-b-to': scaleColor()\n }],\n 'mask-image-l-from-pos': [{\n 'mask-l-from': scaleMaskImagePosition()\n }],\n 'mask-image-l-to-pos': [{\n 'mask-l-to': scaleMaskImagePosition()\n }],\n 'mask-image-l-from-color': [{\n 'mask-l-from': scaleColor()\n }],\n 'mask-image-l-to-color': [{\n 'mask-l-to': scaleColor()\n }],\n 'mask-image-x-from-pos': [{\n 'mask-x-from': scaleMaskImagePosition()\n }],\n 'mask-image-x-to-pos': [{\n 'mask-x-to': scaleMaskImagePosition()\n }],\n 'mask-image-x-from-color': [{\n 'mask-x-from': scaleColor()\n }],\n 'mask-image-x-to-color': [{\n 'mask-x-to': scaleColor()\n }],\n 'mask-image-y-from-pos': [{\n 'mask-y-from': scaleMaskImagePosition()\n }],\n 'mask-image-y-to-pos': [{\n 'mask-y-to': scaleMaskImagePosition()\n }],\n 'mask-image-y-from-color': [{\n 'mask-y-from': scaleColor()\n }],\n 'mask-image-y-to-color': [{\n 'mask-y-to': scaleColor()\n }],\n 'mask-image-radial': [{\n 'mask-radial': [isArbitraryVariable, isArbitraryValue]\n }],\n 'mask-image-radial-from-pos': [{\n 'mask-radial-from': scaleMaskImagePosition()\n }],\n 'mask-image-radial-to-pos': [{\n 'mask-radial-to': scaleMaskImagePosition()\n }],\n 'mask-image-radial-from-color': [{\n 'mask-radial-from': scaleColor()\n }],\n 'mask-image-radial-to-color': [{\n 'mask-radial-to': scaleColor()\n }],\n 'mask-image-radial-shape': [{\n 'mask-radial': ['circle', 'ellipse']\n }],\n 'mask-image-radial-size': [{\n 'mask-radial': [{\n closest: ['side', 'corner'],\n farthest: ['side', 'corner']\n }]\n }],\n 'mask-image-radial-pos': [{\n 'mask-radial-at': scalePosition()\n }],\n 'mask-image-conic-pos': [{\n 'mask-conic': [isNumber]\n }],\n 'mask-image-conic-from-pos': [{\n 'mask-conic-from': scaleMaskImagePosition()\n }],\n 'mask-image-conic-to-pos': [{\n 'mask-conic-to': scaleMaskImagePosition()\n }],\n 'mask-image-conic-from-color': [{\n 'mask-conic-from': scaleColor()\n }],\n 'mask-image-conic-to-color': [{\n 'mask-conic-to': scaleColor()\n }],\n /**\n * Mask Mode\n * @see https://tailwindcss.com/docs/mask-mode\n */\n 'mask-mode': [{\n mask: ['alpha', 'luminance', 'match']\n }],\n /**\n * Mask Origin\n * @see https://tailwindcss.com/docs/mask-origin\n */\n 'mask-origin': [{\n 'mask-origin': ['border', 'padding', 'content', 'fill', 'stroke', 'view']\n }],\n /**\n * Mask Position\n * @see https://tailwindcss.com/docs/mask-position\n */\n 'mask-position': [{\n mask: scaleBgPosition()\n }],\n /**\n * Mask Repeat\n * @see https://tailwindcss.com/docs/mask-repeat\n */\n 'mask-repeat': [{\n mask: scaleBgRepeat()\n }],\n /**\n * Mask Size\n * @see https://tailwindcss.com/docs/mask-size\n */\n 'mask-size': [{\n mask: scaleBgSize()\n }],\n /**\n * Mask Type\n * @see https://tailwindcss.com/docs/mask-type\n */\n 'mask-type': [{\n 'mask-type': ['alpha', 'luminance']\n }],\n /**\n * Mask Image\n * @see https://tailwindcss.com/docs/mask-image\n */\n 'mask-image': [{\n mask: ['none', isArbitraryVariable, isArbitraryValue]\n }],\n // ---------------\n // --- Filters ---\n // ---------------\n /**\n * Filter\n * @see https://tailwindcss.com/docs/filter\n */\n filter: [{\n filter: [\n // Deprecated since Tailwind CSS v3.0.0\n '', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Blur\n * @see https://tailwindcss.com/docs/blur\n */\n blur: [{\n blur: scaleBlur()\n }],\n /**\n * Brightness\n * @see https://tailwindcss.com/docs/brightness\n */\n brightness: [{\n brightness: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Contrast\n * @see https://tailwindcss.com/docs/contrast\n */\n contrast: [{\n contrast: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Drop Shadow\n * @see https://tailwindcss.com/docs/drop-shadow\n */\n 'drop-shadow': [{\n 'drop-shadow': [\n // Deprecated since Tailwind CSS v4.0.0\n '', 'none', themeDropShadow, isArbitraryVariableShadow, isArbitraryShadow]\n }],\n /**\n * Drop Shadow Color\n * @see https://tailwindcss.com/docs/filter-drop-shadow#setting-the-shadow-color\n */\n 'drop-shadow-color': [{\n 'drop-shadow': scaleColor()\n }],\n /**\n * Grayscale\n * @see https://tailwindcss.com/docs/grayscale\n */\n grayscale: [{\n grayscale: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Hue Rotate\n * @see https://tailwindcss.com/docs/hue-rotate\n */\n 'hue-rotate': [{\n 'hue-rotate': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Invert\n * @see https://tailwindcss.com/docs/invert\n */\n invert: [{\n invert: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Saturate\n * @see https://tailwindcss.com/docs/saturate\n */\n saturate: [{\n saturate: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Sepia\n * @see https://tailwindcss.com/docs/sepia\n */\n sepia: [{\n sepia: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Filter\n * @see https://tailwindcss.com/docs/backdrop-filter\n */\n 'backdrop-filter': [{\n 'backdrop-filter': [\n // Deprecated since Tailwind CSS v3.0.0\n '', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Blur\n * @see https://tailwindcss.com/docs/backdrop-blur\n */\n 'backdrop-blur': [{\n 'backdrop-blur': scaleBlur()\n }],\n /**\n * Backdrop Brightness\n * @see https://tailwindcss.com/docs/backdrop-brightness\n */\n 'backdrop-brightness': [{\n 'backdrop-brightness': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Contrast\n * @see https://tailwindcss.com/docs/backdrop-contrast\n */\n 'backdrop-contrast': [{\n 'backdrop-contrast': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Grayscale\n * @see https://tailwindcss.com/docs/backdrop-grayscale\n */\n 'backdrop-grayscale': [{\n 'backdrop-grayscale': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Hue Rotate\n * @see https://tailwindcss.com/docs/backdrop-hue-rotate\n */\n 'backdrop-hue-rotate': [{\n 'backdrop-hue-rotate': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Invert\n * @see https://tailwindcss.com/docs/backdrop-invert\n */\n 'backdrop-invert': [{\n 'backdrop-invert': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Opacity\n * @see https://tailwindcss.com/docs/backdrop-opacity\n */\n 'backdrop-opacity': [{\n 'backdrop-opacity': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Saturate\n * @see https://tailwindcss.com/docs/backdrop-saturate\n */\n 'backdrop-saturate': [{\n 'backdrop-saturate': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Sepia\n * @see https://tailwindcss.com/docs/backdrop-sepia\n */\n 'backdrop-sepia': [{\n 'backdrop-sepia': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n // --------------\n // --- Tables ---\n // --------------\n /**\n * Border Collapse\n * @see https://tailwindcss.com/docs/border-collapse\n */\n 'border-collapse': [{\n border: ['collapse', 'separate']\n }],\n /**\n * Border Spacing\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing': [{\n 'border-spacing': scaleUnambiguousSpacing()\n }],\n /**\n * Border Spacing X\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing-x': [{\n 'border-spacing-x': scaleUnambiguousSpacing()\n }],\n /**\n * Border Spacing Y\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing-y': [{\n 'border-spacing-y': scaleUnambiguousSpacing()\n }],\n /**\n * Table Layout\n * @see https://tailwindcss.com/docs/table-layout\n */\n 'table-layout': [{\n table: ['auto', 'fixed']\n }],\n /**\n * Caption Side\n * @see https://tailwindcss.com/docs/caption-side\n */\n caption: [{\n caption: ['top', 'bottom']\n }],\n // ---------------------------------\n // --- Transitions and Animation ---\n // ---------------------------------\n /**\n * Transition Property\n * @see https://tailwindcss.com/docs/transition-property\n */\n transition: [{\n transition: ['', 'all', 'colors', 'opacity', 'shadow', 'transform', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Transition Behavior\n * @see https://tailwindcss.com/docs/transition-behavior\n */\n 'transition-behavior': [{\n transition: ['normal', 'discrete']\n }],\n /**\n * Transition Duration\n * @see https://tailwindcss.com/docs/transition-duration\n */\n duration: [{\n duration: [isNumber, 'initial', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Transition Timing Function\n * @see https://tailwindcss.com/docs/transition-timing-function\n */\n ease: [{\n ease: ['linear', 'initial', themeEase, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Transition Delay\n * @see https://tailwindcss.com/docs/transition-delay\n */\n delay: [{\n delay: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Animation\n * @see https://tailwindcss.com/docs/animation\n */\n animate: [{\n animate: ['none', themeAnimate, isArbitraryVariable, isArbitraryValue]\n }],\n // ------------------\n // --- Transforms ---\n // ------------------\n /**\n * Backface Visibility\n * @see https://tailwindcss.com/docs/backface-visibility\n */\n backface: [{\n backface: ['hidden', 'visible']\n }],\n /**\n * Perspective\n * @see https://tailwindcss.com/docs/perspective\n */\n perspective: [{\n perspective: [themePerspective, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Perspective Origin\n * @see https://tailwindcss.com/docs/perspective-origin\n */\n 'perspective-origin': [{\n 'perspective-origin': scalePositionWithArbitrary()\n }],\n /**\n * Rotate\n * @see https://tailwindcss.com/docs/rotate\n */\n rotate: [{\n rotate: scaleRotate()\n }],\n /**\n * Rotate X\n * @see https://tailwindcss.com/docs/rotate\n */\n 'rotate-x': [{\n 'rotate-x': scaleRotate()\n }],\n /**\n * Rotate Y\n * @see https://tailwindcss.com/docs/rotate\n */\n 'rotate-y': [{\n 'rotate-y': scaleRotate()\n }],\n /**\n * Rotate Z\n * @see https://tailwindcss.com/docs/rotate\n */\n 'rotate-z': [{\n 'rotate-z': scaleRotate()\n }],\n /**\n * Scale\n * @see https://tailwindcss.com/docs/scale\n */\n scale: [{\n scale: scaleScale()\n }],\n /**\n * Scale X\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-x': [{\n 'scale-x': scaleScale()\n }],\n /**\n * Scale Y\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-y': [{\n 'scale-y': scaleScale()\n }],\n /**\n * Scale Z\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-z': [{\n 'scale-z': scaleScale()\n }],\n /**\n * Scale 3D\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-3d': ['scale-3d'],\n /**\n * Skew\n * @see https://tailwindcss.com/docs/skew\n */\n skew: [{\n skew: scaleSkew()\n }],\n /**\n * Skew X\n * @see https://tailwindcss.com/docs/skew\n */\n 'skew-x': [{\n 'skew-x': scaleSkew()\n }],\n /**\n * Skew Y\n * @see https://tailwindcss.com/docs/skew\n */\n 'skew-y': [{\n 'skew-y': scaleSkew()\n }],\n /**\n * Transform\n * @see https://tailwindcss.com/docs/transform\n */\n transform: [{\n transform: [isArbitraryVariable, isArbitraryValue, '', 'none', 'gpu', 'cpu']\n }],\n /**\n * Transform Origin\n * @see https://tailwindcss.com/docs/transform-origin\n */\n 'transform-origin': [{\n origin: scalePositionWithArbitrary()\n }],\n /**\n * Transform Style\n * @see https://tailwindcss.com/docs/transform-style\n */\n 'transform-style': [{\n transform: ['3d', 'flat']\n }],\n /**\n * Translate\n * @see https://tailwindcss.com/docs/translate\n */\n translate: [{\n translate: scaleTranslate()\n }],\n /**\n * Translate X\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-x': [{\n 'translate-x': scaleTranslate()\n }],\n /**\n * Translate Y\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-y': [{\n 'translate-y': scaleTranslate()\n }],\n /**\n * Translate Z\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-z': [{\n 'translate-z': scaleTranslate()\n }],\n /**\n * Translate None\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-none': ['translate-none'],\n /**\n * Zoom\n * @see https://tailwindcss.com/docs/zoom\n */\n zoom: [{\n zoom: [isInteger, isArbitraryVariable, isArbitraryValue]\n }],\n // ---------------------\n // --- Interactivity ---\n // ---------------------\n /**\n * Accent Color\n * @see https://tailwindcss.com/docs/accent-color\n */\n accent: [{\n accent: scaleColor()\n }],\n /**\n * Appearance\n * @see https://tailwindcss.com/docs/appearance\n */\n appearance: [{\n appearance: ['none', 'auto']\n }],\n /**\n * Caret Color\n * @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities\n */\n 'caret-color': [{\n caret: scaleColor()\n }],\n /**\n * Color Scheme\n * @see https://tailwindcss.com/docs/color-scheme\n */\n 'color-scheme': [{\n scheme: ['normal', 'dark', 'light', 'light-dark', 'only-dark', 'only-light']\n }],\n /**\n * Cursor\n * @see https://tailwindcss.com/docs/cursor\n */\n cursor: [{\n cursor: ['auto', 'default', 'pointer', 'wait', 'text', 'move', 'help', 'not-allowed', 'none', 'context-menu', 'progress', 'cell', 'crosshair', 'vertical-text', 'alias', 'copy', 'no-drop', 'grab', 'grabbing', 'all-scroll', 'col-resize', 'row-resize', 'n-resize', 'e-resize', 's-resize', 'w-resize', 'ne-resize', 'nw-resize', 'se-resize', 'sw-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'zoom-in', 'zoom-out', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Field Sizing\n * @see https://tailwindcss.com/docs/field-sizing\n */\n 'field-sizing': [{\n 'field-sizing': ['fixed', 'content']\n }],\n /**\n * Pointer Events\n * @see https://tailwindcss.com/docs/pointer-events\n */\n 'pointer-events': [{\n 'pointer-events': ['auto', 'none']\n }],\n /**\n * Resize\n * @see https://tailwindcss.com/docs/resize\n */\n resize: [{\n resize: ['none', '', 'y', 'x']\n }],\n /**\n * Scroll Behavior\n * @see https://tailwindcss.com/docs/scroll-behavior\n */\n 'scroll-behavior': [{\n scroll: ['auto', 'smooth']\n }],\n /**\n * Scrollbar Thumb Color\n * @see https://tailwindcss.com/docs/scrollbar-color\n */\n 'scrollbar-thumb-color': [{\n 'scrollbar-thumb': scaleColor()\n }],\n /**\n * Scrollbar Track Color\n * @see https://tailwindcss.com/docs/scrollbar-color\n */\n 'scrollbar-track-color': [{\n 'scrollbar-track': scaleColor()\n }],\n /**\n * Scrollbar Gutter\n * @see https://tailwindcss.com/docs/scrollbar-gutter\n */\n 'scrollbar-gutter': [{\n 'scrollbar-gutter': ['auto', 'stable', 'both']\n }],\n /**\n * Scrollbar Width\n * @see https://tailwindcss.com/docs/scrollbar-width\n */\n 'scrollbar-w': [{\n scrollbar: ['auto', 'thin', 'none']\n }],\n /**\n * Scroll Margin\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-m': [{\n 'scroll-m': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Inline\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mx': [{\n 'scroll-mx': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Block\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-my': [{\n 'scroll-my': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Inline Start\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-ms': [{\n 'scroll-ms': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Inline End\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-me': [{\n 'scroll-me': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Block Start\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mbs': [{\n 'scroll-mbs': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Block End\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mbe': [{\n 'scroll-mbe': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Top\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mt': [{\n 'scroll-mt': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Right\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mr': [{\n 'scroll-mr': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Bottom\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mb': [{\n 'scroll-mb': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Left\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-ml': [{\n 'scroll-ml': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-p': [{\n 'scroll-p': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Inline\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-px': [{\n 'scroll-px': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Block\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-py': [{\n 'scroll-py': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Inline Start\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-ps': [{\n 'scroll-ps': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Inline End\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pe': [{\n 'scroll-pe': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Block Start\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pbs': [{\n 'scroll-pbs': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Block End\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pbe': [{\n 'scroll-pbe': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Top\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pt': [{\n 'scroll-pt': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Right\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pr': [{\n 'scroll-pr': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Bottom\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pb': [{\n 'scroll-pb': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Left\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pl': [{\n 'scroll-pl': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Snap Align\n * @see https://tailwindcss.com/docs/scroll-snap-align\n */\n 'snap-align': [{\n snap: ['start', 'end', 'center', 'align-none']\n }],\n /**\n * Scroll Snap Stop\n * @see https://tailwindcss.com/docs/scroll-snap-stop\n */\n 'snap-stop': [{\n snap: ['normal', 'always']\n }],\n /**\n * Scroll Snap Type\n * @see https://tailwindcss.com/docs/scroll-snap-type\n */\n 'snap-type': [{\n snap: ['none', 'x', 'y', 'both']\n }],\n /**\n * Scroll Snap Type Strictness\n * @see https://tailwindcss.com/docs/scroll-snap-type\n */\n 'snap-strictness': [{\n snap: ['mandatory', 'proximity']\n }],\n /**\n * Touch Action\n * @see https://tailwindcss.com/docs/touch-action\n */\n touch: [{\n touch: ['auto', 'none', 'manipulation']\n }],\n /**\n * Touch Action X\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-x': [{\n 'touch-pan': ['x', 'left', 'right']\n }],\n /**\n * Touch Action Y\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-y': [{\n 'touch-pan': ['y', 'up', 'down']\n }],\n /**\n * Touch Action Pinch Zoom\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-pz': ['touch-pinch-zoom'],\n /**\n * User Select\n * @see https://tailwindcss.com/docs/user-select\n */\n select: [{\n select: ['none', 'text', 'all', 'auto']\n }],\n /**\n * Will Change\n * @see https://tailwindcss.com/docs/will-change\n */\n 'will-change': [{\n 'will-change': ['auto', 'scroll', 'contents', 'transform', isArbitraryVariable, isArbitraryValue]\n }],\n // -----------\n // --- SVG ---\n // -----------\n /**\n * Fill\n * @see https://tailwindcss.com/docs/fill\n */\n fill: [{\n fill: ['none', ...scaleColor()]\n }],\n /**\n * Stroke Width\n * @see https://tailwindcss.com/docs/stroke-width\n */\n 'stroke-w': [{\n stroke: [isNumber, isArbitraryVariableLength, isArbitraryLength, isArbitraryNumber]\n }],\n /**\n * Stroke\n * @see https://tailwindcss.com/docs/stroke\n */\n stroke: [{\n stroke: ['none', ...scaleColor()]\n }],\n // ---------------------\n // --- Accessibility ---\n // ---------------------\n /**\n * Forced Color Adjust\n * @see https://tailwindcss.com/docs/forced-color-adjust\n */\n 'forced-color-adjust': [{\n 'forced-color-adjust': ['auto', 'none']\n }]\n },\n conflictingClassGroups: {\n 'container-named': ['container-type'],\n overflow: ['overflow-x', 'overflow-y'],\n overscroll: ['overscroll-x', 'overscroll-y'],\n inset: ['inset-x', 'inset-y', 'inset-bs', 'inset-be', 'start', 'end', 'top', 'right', 'bottom', 'left'],\n 'inset-x': ['right', 'left'],\n 'inset-y': ['top', 'bottom'],\n flex: ['basis', 'grow', 'shrink'],\n gap: ['gap-x', 'gap-y'],\n p: ['px', 'py', 'ps', 'pe', 'pbs', 'pbe', 'pt', 'pr', 'pb', 'pl'],\n px: ['pr', 'pl'],\n py: ['pt', 'pb'],\n m: ['mx', 'my', 'ms', 'me', 'mbs', 'mbe', 'mt', 'mr', 'mb', 'ml'],\n mx: ['mr', 'ml'],\n my: ['mt', 'mb'],\n size: ['w', 'h'],\n 'font-size': ['leading'],\n 'fvn-normal': ['fvn-ordinal', 'fvn-slashed-zero', 'fvn-figure', 'fvn-spacing', 'fvn-fraction'],\n 'fvn-ordinal': ['fvn-normal'],\n 'fvn-slashed-zero': ['fvn-normal'],\n 'fvn-figure': ['fvn-normal'],\n 'fvn-spacing': ['fvn-normal'],\n 'fvn-fraction': ['fvn-normal'],\n 'line-clamp': ['display', 'overflow'],\n rounded: ['rounded-s', 'rounded-e', 'rounded-t', 'rounded-r', 'rounded-b', 'rounded-l', 'rounded-ss', 'rounded-se', 'rounded-ee', 'rounded-es', 'rounded-tl', 'rounded-tr', 'rounded-br', 'rounded-bl'],\n 'rounded-s': ['rounded-ss', 'rounded-es'],\n 'rounded-e': ['rounded-se', 'rounded-ee'],\n 'rounded-t': ['rounded-tl', 'rounded-tr'],\n 'rounded-r': ['rounded-tr', 'rounded-br'],\n 'rounded-b': ['rounded-br', 'rounded-bl'],\n 'rounded-l': ['rounded-tl', 'rounded-bl'],\n 'border-spacing': ['border-spacing-x', 'border-spacing-y'],\n 'border-w': ['border-w-x', 'border-w-y', 'border-w-s', 'border-w-e', 'border-w-bs', 'border-w-be', 'border-w-t', 'border-w-r', 'border-w-b', 'border-w-l'],\n 'border-w-x': ['border-w-r', 'border-w-l'],\n 'border-w-y': ['border-w-t', 'border-w-b'],\n 'border-color': ['border-color-x', 'border-color-y', 'border-color-s', 'border-color-e', 'border-color-bs', 'border-color-be', 'border-color-t', 'border-color-r', 'border-color-b', 'border-color-l'],\n 'border-color-x': ['border-color-r', 'border-color-l'],\n 'border-color-y': ['border-color-t', 'border-color-b'],\n translate: ['translate-x', 'translate-y', 'translate-none'],\n 'translate-none': ['translate', 'translate-x', 'translate-y', 'translate-z'],\n 'scroll-m': ['scroll-mx', 'scroll-my', 'scroll-ms', 'scroll-me', 'scroll-mbs', 'scroll-mbe', 'scroll-mt', 'scroll-mr', 'scroll-mb', 'scroll-ml'],\n 'scroll-mx': ['scroll-mr', 'scroll-ml'],\n 'scroll-my': ['scroll-mt', 'scroll-mb'],\n 'scroll-p': ['scroll-px', 'scroll-py', 'scroll-ps', 'scroll-pe', 'scroll-pbs', 'scroll-pbe', 'scroll-pt', 'scroll-pr', 'scroll-pb', 'scroll-pl'],\n 'scroll-px': ['scroll-pr', 'scroll-pl'],\n 'scroll-py': ['scroll-pt', 'scroll-pb'],\n touch: ['touch-x', 'touch-y', 'touch-pz'],\n 'touch-x': ['touch'],\n 'touch-y': ['touch'],\n 'touch-pz': ['touch']\n },\n conflictingClassGroupModifiers: {\n 'font-size': ['leading']\n },\n postfixLookupClassGroups: ['container-type'],\n orderSensitiveModifiers: ['*', '**', 'after', 'backdrop', 'before', 'details-content', 'file', 'first-letter', 'first-line', 'marker', 'placeholder', 'selection']\n };\n};\n\n/**\n * @param baseConfig Config where other config will be merged into. This object will be mutated.\n * @param configExtension Partial config to merge into the `baseConfig`.\n */\nconst mergeConfigs = (baseConfig, {\n cacheSize,\n prefix,\n experimentalParseClassName,\n extend = {},\n override = {}\n}) => {\n overrideProperty(baseConfig, 'cacheSize', cacheSize);\n overrideProperty(baseConfig, 'prefix', prefix);\n overrideProperty(baseConfig, 'experimentalParseClassName', experimentalParseClassName);\n overrideConfigProperties(baseConfig.theme, override.theme);\n overrideConfigProperties(baseConfig.classGroups, override.classGroups);\n overrideConfigProperties(baseConfig.conflictingClassGroups, override.conflictingClassGroups);\n overrideConfigProperties(baseConfig.conflictingClassGroupModifiers, override.conflictingClassGroupModifiers);\n overrideProperty(baseConfig, 'postfixLookupClassGroups', override.postfixLookupClassGroups);\n overrideProperty(baseConfig, 'orderSensitiveModifiers', override.orderSensitiveModifiers);\n mergeConfigProperties(baseConfig.theme, extend.theme);\n mergeConfigProperties(baseConfig.classGroups, extend.classGroups);\n mergeConfigProperties(baseConfig.conflictingClassGroups, extend.conflictingClassGroups);\n mergeConfigProperties(baseConfig.conflictingClassGroupModifiers, extend.conflictingClassGroupModifiers);\n mergeArrayProperties(baseConfig, extend, 'postfixLookupClassGroups');\n mergeArrayProperties(baseConfig, extend, 'orderSensitiveModifiers');\n return baseConfig;\n};\nconst overrideProperty = (baseObject, overrideKey, overrideValue) => {\n if (overrideValue !== undefined) {\n baseObject[overrideKey] = overrideValue;\n }\n};\nconst overrideConfigProperties = (baseObject, overrideObject) => {\n if (overrideObject) {\n for (const key in overrideObject) {\n overrideProperty(baseObject, key, overrideObject[key]);\n }\n }\n};\nconst mergeConfigProperties = (baseObject, mergeObject) => {\n if (mergeObject) {\n for (const key in mergeObject) {\n mergeArrayProperties(baseObject, mergeObject, key);\n }\n }\n};\nconst mergeArrayProperties = (baseObject, mergeObject, key) => {\n const mergeValue = mergeObject[key];\n if (mergeValue !== undefined) {\n baseObject[key] = baseObject[key] ? baseObject[key].concat(mergeValue) : mergeValue;\n }\n};\nconst extendTailwindMerge = (configExtension, ...createConfig) => typeof configExtension === 'function' ? createTailwindMerge(getDefaultConfig, configExtension, ...createConfig) : createTailwindMerge(() => mergeConfigs(getDefaultConfig(), configExtension), ...createConfig);\nconst twMerge = /*#__PURE__*/createTailwindMerge(getDefaultConfig);\nexport { createTailwindMerge, extendTailwindMerge, fromTheme, getDefaultConfig, mergeConfigs, twJoin, twMerge, validators };\n//# sourceMappingURL=bundle-mjs.mjs.map\n","import { twMerge } from 'tailwind-merge';\n\ntype ClassValue = string | undefined | null | false;\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(inputs.filter(Boolean).join(' '));\n}\n","import type { CSSProperties, ElementType } from 'react';\n\nimport { radiusClasses } from '../../design-system/component-tokens';\n\nexport type SpacingToken = 'none' | '2xs' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';\n\nexport const SPACING_SCALE: Record<SpacingToken, string> = {\n none: '0',\n '2xs': '0.5',\n xs: '1',\n sm: '1.5',\n md: '2',\n lg: '3',\n xl: '4',\n '2xl': '6',\n};\n\nconst alignClasses = {\n start: 'items-start',\n center: 'items-center',\n end: 'items-end',\n stretch: 'items-stretch',\n baseline: 'items-baseline',\n} as const;\n\nconst justifyClasses = {\n start: 'justify-start',\n center: 'justify-center',\n end: 'justify-end',\n between: 'justify-between',\n around: 'justify-around',\n} as const;\n\nconst overflowClasses = {\n hidden: 'overflow-hidden',\n auto: 'overflow-auto',\n visible: 'overflow-visible',\n scroll: 'overflow-scroll',\n} as const;\n\nconst overflowYClasses = { hidden: 'overflow-y-hidden', auto: 'overflow-y-auto' } as const;\nconst widthClasses = { full: 'w-full', auto: 'w-auto' } as const;\nconst heightClasses = { full: 'h-full', auto: 'h-auto' } as const;\nconst borderSideClasses = { top: 'border-t', bottom: 'border-b', left: 'border-l', right: 'border-r' } as const;\n\nexport interface LayoutProps {\n padding?: SpacingToken;\n paddingX?: SpacingToken;\n paddingY?: SpacingToken;\n paddingTop?: SpacingToken;\n paddingBottom?: SpacingToken;\n gap?: SpacingToken;\n\n align?: keyof typeof alignClasses;\n justify?: keyof typeof justifyClasses;\n grow?: boolean;\n shrink?: boolean;\n\n position?: 'relative' | 'absolute' | 'fixed' | 'sticky';\n inset?: SpacingToken | '0';\n\n overflow?: keyof typeof overflowClasses;\n overflowY?: keyof typeof overflowYClasses;\n width?: keyof typeof widthClasses;\n height?: keyof typeof heightClasses;\n minWidth?: '0';\n\n border?: boolean | keyof typeof borderSideClasses;\n rounded?: boolean | 'none' | 'sm' | 'full' | 'lg' | 'theme' | 'md' | 'xl' | 'pill' | 'circle';\n\n animate?: 'spin' | 'ping' | 'pulse' | 'fadeIn' | 'none';\n hidden?: boolean;\n\n as?: ElementType;\n style?: CSSProperties;\n}\n\nconst LAYOUT_KEYS = new Set<keyof LayoutProps>([\n 'padding',\n 'paddingX',\n 'paddingY',\n 'paddingTop',\n 'paddingBottom',\n 'gap',\n 'align',\n 'justify',\n 'grow',\n 'shrink',\n 'position',\n 'inset',\n 'overflow',\n 'overflowY',\n 'width',\n 'height',\n 'minWidth',\n 'border',\n 'rounded',\n 'animate',\n 'hidden',\n 'as',\n 'style',\n]);\n\nexport function resolveLayoutClasses(props: LayoutProps): string {\n const classes: string[] = [];\n\n if (props.padding !== undefined) classes.push(`p-${SPACING_SCALE[props.padding]}`);\n if (props.paddingX !== undefined) classes.push(`px-${SPACING_SCALE[props.paddingX]}`);\n if (props.paddingY !== undefined) classes.push(`py-${SPACING_SCALE[props.paddingY]}`);\n if (props.paddingTop !== undefined) classes.push(`pt-${SPACING_SCALE[props.paddingTop]}`);\n if (props.paddingBottom !== undefined) classes.push(`pb-${SPACING_SCALE[props.paddingBottom]}`);\n if (props.gap !== undefined) classes.push(`gap-${SPACING_SCALE[props.gap]}`);\n\n if (props.align !== undefined) classes.push(alignClasses[props.align]);\n if (props.justify !== undefined) classes.push(justifyClasses[props.justify]);\n if (props.grow === true) classes.push('flex-1');\n if (props.shrink === false) classes.push('flex-shrink-0');\n\n if (props.position !== undefined) classes.push(props.position);\n if (props.inset !== undefined) {\n classes.push(props.inset === '0' ? 'inset-0' : `inset-${SPACING_SCALE[props.inset]}`);\n }\n\n if (props.overflow !== undefined) classes.push(overflowClasses[props.overflow]);\n if (props.overflowY !== undefined) classes.push(overflowYClasses[props.overflowY]);\n if (props.width !== undefined) classes.push(widthClasses[props.width]);\n if (props.height !== undefined) classes.push(heightClasses[props.height]);\n if (props.minWidth === '0') classes.push('min-w-0');\n\n if (props.border !== undefined && props.border !== false) {\n if (props.border === true) {\n classes.push('border', 'border-border');\n } else {\n classes.push(borderSideClasses[props.border], 'border-border');\n }\n }\n if (props.rounded !== undefined && props.rounded !== false) {\n if (props.rounded === true) {\n classes.push(radiusClasses.theme);\n } else if (props.rounded === 'full') {\n classes.push(radiusClasses.pill);\n } else {\n classes.push(radiusClasses[props.rounded]);\n }\n }\n\n if (props.animate !== undefined && props.animate !== 'none') {\n const animateMap: Record<string, string> = {\n spin: 'animate-spin',\n ping: 'animate-ping',\n pulse: 'animate-pulse',\n fadeIn: 'animate-fade-in',\n };\n classes.push(animateMap[props.animate]);\n }\n if (props.hidden === true) classes.push('hidden');\n\n return classes.join(' ');\n}\n\nexport function stripLayoutProps<T extends LayoutProps>(props: T): Omit<T, keyof LayoutProps> {\n const result: Record<string, unknown> = {};\n for (const key in props) {\n if (!LAYOUT_KEYS.has(key as keyof LayoutProps)) {\n result[key] = props[key];\n }\n }\n return result as Omit<T, keyof LayoutProps>;\n}\n","import type { ComponentPropsWithRef } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { getElevationStyle, type RadiusToken } from '../../design-system/component-tokens';\nimport type { ShadowToken } from '../../design-system/shadows';\nimport { resolveLayoutClasses } from './layoutProps';\n\ntype AvatarSize = 'sm' | 'md' | 'lg';\n\nexport interface AvatarProps extends Omit<ComponentPropsWithRef<'img'>, 'size'> {\n src: string;\n alt: string;\n elevation?: ShadowToken;\n fit?: 'contain' | 'cover';\n size?: AvatarSize | number;\n rounded?: boolean | 'full' | 'theme' | RadiusToken;\n}\n\nconst sizeStyles: Record<AvatarSize, string> = {\n sm: 'w-5 h-5',\n md: 'w-8 h-8',\n lg: 'w-12 h-12',\n};\n\nexport function Avatar(props: AvatarProps) {\n const { src, alt, elevation, fit = 'contain', size = 'md', rounded, className, style, ref, ...imgProps } = props;\n const isPreset = typeof size === 'string';\n const sizeClass = isPreset ? sizeStyles[size] : undefined;\n const sizeStyle = !isPreset ? { width: size, height: size, ...style } : style;\n const roundedClass = resolveLayoutClasses({ rounded });\n\n return (\n <img\n {...imgProps}\n ref={ref}\n alt={alt}\n className={cn(\n 'flex-shrink-0',\n fit === 'contain' ? 'object-contain' : 'object-cover',\n sizeClass,\n roundedClass,\n className,\n )}\n src={src}\n style={{ ...getElevationStyle(elevation), ...sizeStyle }}\n />\n );\n}\n","function hasWindow() {\n return typeof window !== 'undefined';\n}\nfunction getNodeName(node) {\n if (isNode(node)) {\n return (node.nodeName || '').toLowerCase();\n }\n // Mocked nodes in testing environments may not be instances of Node. By\n // returning `#document` an infinite loop won't occur.\n // https://github.com/floating-ui/floating-ui/issues/2317\n return '#document';\n}\nfunction getWindow(node) {\n var _node$ownerDocument;\n return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n var _ref;\n return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n if (!hasWindow() || typeof ShadowRoot === 'undefined') {\n return false;\n }\n return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nfunction isOverflowElement(element) {\n const {\n overflow,\n overflowX,\n overflowY,\n display\n } = getComputedStyle(element);\n return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== 'inline' && display !== 'contents';\n}\nfunction isTableElement(element) {\n return /^(table|td|th)$/.test(getNodeName(element));\n}\nfunction isTopLayer(element) {\n try {\n if (element.matches(':popover-open')) {\n return true;\n }\n } catch (_e) {\n // no-op\n }\n try {\n return element.matches(':modal');\n } catch (_e) {\n return false;\n }\n}\nconst willChangeRe = /transform|translate|scale|rotate|perspective|filter/;\nconst containRe = /paint|layout|strict|content/;\nconst isNotNone = value => !!value && value !== 'none';\nlet isWebKitValue;\nfunction isContainingBlock(elementOrCss) {\n const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n // https://drafts.csswg.org/css-transforms-2/#individual-transforms\n return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || '') || containRe.test(css.contain || '');\n}\nfunction getContainingBlock(element) {\n let currentNode = getParentNode(element);\n while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n if (isContainingBlock(currentNode)) {\n return currentNode;\n } else if (isTopLayer(currentNode)) {\n return null;\n }\n currentNode = getParentNode(currentNode);\n }\n return null;\n}\nfunction isWebKit() {\n if (isWebKitValue == null) {\n isWebKitValue = typeof CSS !== 'undefined' && CSS.supports && CSS.supports('-webkit-backdrop-filter', 'none');\n }\n return isWebKitValue;\n}\nfunction isLastTraversableNode(node) {\n return /^(html|body|#document)$/.test(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n if (isElement(element)) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n }\n return {\n scrollLeft: element.scrollX,\n scrollTop: element.scrollY\n };\n}\nfunction getParentNode(node) {\n if (getNodeName(node) === 'html') {\n return node;\n }\n const result =\n // Step into the shadow DOM of the parent of a slotted node.\n node.assignedSlot ||\n // DOM Element detected.\n node.parentNode ||\n // ShadowRoot detected.\n isShadowRoot(node) && node.host ||\n // Fallback.\n getDocumentElement(node);\n return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n const parentNode = getParentNode(node);\n if (isLastTraversableNode(parentNode)) {\n return (node.ownerDocument || node).body;\n }\n if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n return parentNode;\n }\n return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n var _node$ownerDocument2;\n if (list === void 0) {\n list = [];\n }\n if (traverseIframes === void 0) {\n traverseIframes = true;\n }\n const scrollableAncestor = getNearestOverflowAncestor(node);\n const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n const win = getWindow(scrollableAncestor);\n if (isBody) {\n const frameElement = getFrameElement(win);\n return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);\n } else {\n return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n }\n}\nfunction getFrameElement(win) {\n return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getFrameElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isTopLayer, isWebKit };\n","import * as React from 'react';\n\n/**\n * A clone of the React namespace for reading APIs that may be missing in older\n * supported React versions. Bundlers can rewrite direct `React.someNewApi`\n * reads into named imports, which breaks React 17. Reading from this cloned\n * object keeps those lookups optional.\n *\n * @see https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379\n */\nexport const SafeReact = {\n ...React\n};","'use client';\n\nimport * as React from 'react';\nconst UNINITIALIZED = {};\n\n/**\n * A React.useRef() that is initialized with a function. Note that it accepts an optional\n * initialization argument, so the initialization function doesn't need to be an inline closure.\n *\n * @usage\n * const ref = useRefWithInit(sortColumns, columns)\n */\n\nexport function useRefWithInit(init, initArg) {\n const ref = React.useRef(UNINITIALIZED);\n if (ref.current === UNINITIALIZED) {\n ref.current = init(initArg);\n }\n return ref;\n}","'use client';\n\nimport { SafeReact } from \"./safeReact.mjs\";\nimport { useRefWithInit } from \"./useRefWithInit.mjs\";\nconst useInsertionEffect = SafeReact.useInsertionEffect;\nconst useSafeInsertionEffect =\n// React 17 doesn't have useInsertionEffect.\nuseInsertionEffect &&\n// Preact replaces useInsertionEffect with useLayoutEffect and fires too late.\nuseInsertionEffect !== SafeReact.useLayoutEffect ? useInsertionEffect : fn => fn();\n/**\n * Stabilizes the function passed so it's always the same between renders.\n *\n * The function becomes non-reactive to any values it captures.\n * It can safely be passed as a dependency of `React.useMemo` and `React.useEffect` without re-triggering them if its captured values change.\n *\n * The function must only be called inside effects and event handlers, never during render (which throws an error).\n *\n * This hook is a more permissive version of React 19.2's `React.useEffectEvent` in that it can be passed through contexts and called in event handler props, not just effects.\n */\nexport function useStableCallback(callback) {\n const stable = useRefWithInit(createStableCallback).current;\n stable.next = callback;\n useSafeInsertionEffect(stable.effect);\n return stable.trampoline;\n}\nfunction createStableCallback() {\n const stable = {\n next: undefined,\n callback: assertNotCalled,\n trampoline: (...args) => stable.callback?.(...args),\n effect: () => {\n stable.callback = stable.next;\n }\n };\n return stable;\n}\nfunction assertNotCalled() {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: fix mui/no-guarded-throw\n // eslint-disable-next-line mui/no-guarded-throw\n throw /* minify-error-disabled */new Error('Base UI: Cannot call an event handler while rendering.');\n }\n}","'use client';\n\nimport * as React from 'react';\nconst noop = () => {};\nexport const useIsoLayoutEffect = typeof document !== 'undefined' ? React.useLayoutEffect : noop;","export function mergeObjects(a, b) {\n if (a && !b) {\n return a;\n }\n if (!a && b) {\n return b;\n }\n if (a || b) {\n return {\n ...a,\n ...b\n };\n }\n return undefined;\n}","import { mergeObjects } from '@base-ui/utils/mergeObjects';\nconst EMPTY_PROPS = {};\n\n/* eslint-disable id-denylist */\n/**\n * Merges multiple sets of React props. It follows the Object.assign pattern where the rightmost object's fields overwrite\n * the conflicting ones from others. This doesn't apply to event handlers, `className` and `style` props.\n *\n * Event handlers are merged and called in right-to-left order (rightmost handler executes first, leftmost last).\n * For React synthetic events, the rightmost handler can prevent prior (left-positioned) handlers from executing\n * by calling `event.preventBaseUIHandler()`. For non-synthetic events (custom events with primitive/object values),\n * all handlers always execute without prevention capability.\n *\n * The `className` prop is merged by concatenating classes in right-to-left order (rightmost class appears first in the string).\n * The `style` prop is merged with rightmost styles overwriting the prior ones.\n *\n * Props can either be provided as objects or as functions that take the previous props as an argument.\n * The function will receive the merged props up to that point (going from left to right):\n * so in the case of `(obj1, obj2, fn, obj3)`, `fn` will receive the merged props of `obj1` and `obj2`.\n * The function is responsible for chaining event handlers if needed (that is, we don't run the merge logic).\n *\n * Event handlers returned by the functions are not automatically prevented when `preventBaseUIHandler` is called.\n * They must check `event.baseUIHandlerPrevented` themselves and bail out if it's true.\n *\n * @important **`ref` is not merged.**\n * @param a Props object to merge.\n * @param b Props object to merge. The function will overwrite conflicting props from `a`.\n * @param c Props object to merge. The function will overwrite conflicting props from previous parameters.\n * @param d Props object to merge. The function will overwrite conflicting props from previous parameters.\n * @param e Props object to merge. The function will overwrite conflicting props from previous parameters.\n * @returns The merged props.\n * @public\n */\n\nexport function mergeProps(a, b, c, d, e) {\n if (!c && !d && !e && !a) {\n return createInitialMergedProps(b);\n }\n\n // We need to mutably own `merged`.\n let merged = createInitialMergedProps(a);\n if (b) {\n merged = mergeInto(merged, b);\n }\n if (c) {\n merged = mergeInto(merged, c);\n }\n if (d) {\n merged = mergeInto(merged, d);\n }\n if (e) {\n merged = mergeInto(merged, e);\n }\n return merged;\n}\n/* eslint-enable id-denylist */\n\n/**\n * Merges an arbitrary number of React props using the same logic as {@link mergeProps}.\n * This function accepts an array of props instead of individual arguments.\n *\n * This has slightly lower performance than {@link mergeProps} due to accepting an array\n * instead of a fixed number of arguments. Prefer {@link mergeProps} when merging 5 or\n * fewer prop sets for better performance.\n *\n * @param props Array of props to merge.\n * @returns The merged props.\n * @see mergeProps\n * @public\n */\nexport function mergePropsN(props) {\n if (props.length === 0) {\n return EMPTY_PROPS;\n }\n if (props.length === 1) {\n return createInitialMergedProps(props[0]);\n }\n\n // We need to mutably own `merged`.\n let merged = createInitialMergedProps(props[0]);\n for (let i = 1; i < props.length; i += 1) {\n merged = mergeInto(merged, props[i]);\n }\n return merged;\n}\nfunction createInitialMergedProps(inputProps) {\n if (isPropsGetter(inputProps)) {\n // Getter-returned handlers intentionally keep their existing semantics.\n return {\n ...resolvePropsGetter(inputProps, EMPTY_PROPS)\n };\n }\n return copyInitialProps(inputProps);\n}\nfunction mergeInto(merged, inputProps) {\n if (isPropsGetter(inputProps)) {\n return resolvePropsGetter(inputProps, merged);\n }\n return mutablyMergeInto(merged, inputProps);\n}\nfunction copyInitialProps(inputProps) {\n const copiedProps = {\n ...inputProps\n };\n\n // `copiedProps` is our fresh own-object copy, so iterating with `for...in` is safe here.\n // eslint-disable-next-line guard-for-in\n for (const propName in copiedProps) {\n const propValue = copiedProps[propName];\n if (isEventHandler(propName, propValue)) {\n copiedProps[propName] = wrapEventHandler(propValue);\n }\n }\n return copiedProps;\n}\n\n/**\n * Merges two sets of props. In case of conflicts, the external props take precedence.\n */\nfunction mutablyMergeInto(mergedProps, externalProps) {\n if (!externalProps) {\n return mergedProps;\n }\n\n // eslint-disable-next-line guard-for-in\n for (const propName in externalProps) {\n const externalPropValue = externalProps[propName];\n switch (propName) {\n case 'style':\n {\n mergedProps[propName] = mergeObjects(mergedProps.style, externalPropValue);\n break;\n }\n case 'className':\n {\n mergedProps[propName] = mergeClassNames(mergedProps.className, externalPropValue);\n break;\n }\n default:\n {\n if (isEventHandler(propName, externalPropValue)) {\n mergedProps[propName] = mergeEventHandlers(mergedProps[propName], externalPropValue);\n } else {\n mergedProps[propName] = externalPropValue;\n }\n }\n }\n }\n return mergedProps;\n}\nfunction isEventHandler(key, value) {\n // This approach is more efficient than using a regex.\n const code0 = key.charCodeAt(0);\n const code1 = key.charCodeAt(1);\n const code2 = key.charCodeAt(2);\n return code0 === 111 /* o */ && code1 === 110 /* n */ && code2 >= 65 /* A */ && code2 <= 90 /* Z */ && (typeof value === 'function' || typeof value === 'undefined');\n}\nfunction isPropsGetter(inputProps) {\n return typeof inputProps === 'function';\n}\nfunction resolvePropsGetter(inputProps, previousProps) {\n if (isPropsGetter(inputProps)) {\n return inputProps(previousProps);\n }\n return inputProps ?? EMPTY_PROPS;\n}\nfunction mergeEventHandlers(ourHandler, theirHandler) {\n if (!theirHandler) {\n return ourHandler;\n }\n if (!ourHandler) {\n return wrapEventHandler(theirHandler);\n }\n return (...args) => {\n const event = args[0];\n if (isSyntheticEvent(event)) {\n const baseUIEvent = event;\n makeEventPreventable(baseUIEvent);\n const result = theirHandler(...args);\n if (!baseUIEvent.baseUIHandlerPrevented) {\n ourHandler?.(...args);\n }\n return result;\n }\n const result = theirHandler(...args);\n ourHandler?.(...args);\n return result;\n };\n}\nfunction wrapEventHandler(handler) {\n if (!handler) {\n return handler;\n }\n return (...args) => {\n const event = args[0];\n if (isSyntheticEvent(event)) {\n makeEventPreventable(event);\n }\n return handler(...args);\n };\n}\nexport function makeEventPreventable(event) {\n event.preventBaseUIHandler = () => {\n event.baseUIHandlerPrevented = true;\n };\n return event;\n}\nexport function mergeClassNames(ourClassName, theirClassName) {\n if (theirClassName) {\n if (ourClassName) {\n // eslint-disable-next-line prefer-template\n return theirClassName + ' ' + ourClassName;\n }\n return theirClassName;\n }\n return ourClassName;\n}\nfunction isSyntheticEvent(event) {\n return event != null && typeof event === 'object' && 'nativeEvent' in event;\n}","/**\n * Creates a formatErrorMessage function with a custom URL and prefix.\n * @param baseUrl - The base URL for the error page (e.g., 'https://base-ui.com/production-error')\n * @param prefix - The prefix for the error message (e.g., 'Base UI')\n * @returns A function that formats error messages with the given URL and prefix\n */\nexport function createFormatErrorMessage(baseUrl, prefix) {\n return function formatErrorMessage(code, ...args) {\n const url = new URL(baseUrl);\n url.searchParams.set('code', code.toString());\n args.forEach(arg => url.searchParams.append('args[]', arg));\n return `${prefix} error #${code}; visit ${url} for the full message.`;\n };\n}\n\n/**\n * WARNING: Don't import this directly. It's imported by the code generated by\n * `@mui/internal-babel-plugin-minify-errors`. Make sure to always use string literals in `Error`\n * constructors to ensure the plugin works as expected. Supported patterns include:\n * throw new Error('My message');\n * throw new Error(`My message: ${foo}`);\n * throw new Error(`My message: ${foo}` + 'another string');\n * ...\n */\nconst formatErrorMessage = createFormatErrorMessage('https://base-ui.com/production-error', 'Base UI');\nexport default formatErrorMessage;","'use client';\n\nimport _formatErrorMessage from \"@base-ui/utils/formatErrorMessage\";\nimport * as React from 'react';\nexport const CompositeRootContext = /*#__PURE__*/React.createContext(undefined);\nif (process.env.NODE_ENV !== \"production\") CompositeRootContext.displayName = \"CompositeRootContext\";\nexport function useCompositeRootContext(optional = false) {\n const context = React.useContext(CompositeRootContext);\n if (context === undefined && !optional) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'Base UI: CompositeRootContext is missing. Composite parts must be placed within <Composite.Root>.' : _formatErrorMessage(16));\n }\n return context;\n}","'use client';\n\nimport * as React from 'react';\nexport function useFocusableWhenDisabled(parameters) {\n const {\n focusableWhenDisabled,\n disabled,\n composite = false,\n tabIndex: tabIndexProp = 0,\n isNativeButton\n } = parameters;\n const isFocusableComposite = composite && focusableWhenDisabled !== false;\n const isNonFocusableComposite = composite && focusableWhenDisabled === false;\n\n // we can't explicitly assign `undefined` to any of these props because it\n // would otherwise prevent subsequently merged props from setting them\n const props = React.useMemo(() => {\n const additionalProps = {\n // allow Tabbing away from focusableWhenDisabled elements\n onKeyDown(event) {\n if (disabled && focusableWhenDisabled && event.key !== 'Tab') {\n event.preventDefault();\n }\n }\n };\n if (!composite) {\n additionalProps.tabIndex = tabIndexProp;\n if (!isNativeButton && disabled) {\n additionalProps.tabIndex = focusableWhenDisabled ? tabIndexProp : -1;\n }\n }\n if (isNativeButton && (focusableWhenDisabled || isFocusableComposite) || !isNativeButton && disabled) {\n additionalProps['aria-disabled'] = disabled;\n }\n if (isNativeButton && (!focusableWhenDisabled || isNonFocusableComposite)) {\n additionalProps.disabled = disabled;\n }\n return additionalProps;\n }, [composite, disabled, focusableWhenDisabled, isFocusableComposite, isNonFocusableComposite, isNativeButton, tabIndexProp]);\n return {\n props\n };\n}","export { getWindow as ownerWindow } from '@floating-ui/utils/dom';\nexport function ownerDocument(node) {\n return node?.ownerDocument || document;\n}","import { ownerWindow } from '@base-ui/utils/owner';\n/**\n * Dispatches a constructed click on the target so it carries the source event's\n * modifier state, which `click()` always reports as unpressed. Like `click()`,\n * the untrusted click still runs native activation behavior (form submission,\n * link navigation).\n * `detail` defaults to 0 (the native convention for keyboard-generated clicks);\n * pass `detail: 1` when the click represents a mouse gesture so consumers keying\n * off `detail === 0` don't classify it as a keyboard activation.\n */\nexport function dispatchClickWithModifiers(target, sourceEvent, {\n detail = 0\n} = {}) {\n target.dispatchEvent(new (ownerWindow(target).PointerEvent)('click', {\n bubbles: true,\n cancelable: true,\n composed: true,\n detail,\n shiftKey: sourceEvent.shiftKey,\n ctrlKey: sourceEvent.ctrlKey,\n altKey: sourceEvent.altKey,\n metaKey: sourceEvent.metaKey\n }));\n}","'use client';\n\nimport * as React from 'react';\nimport { isHTMLElement } from '@floating-ui/utils/dom';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { error } from '@base-ui/utils/error';\nimport { SafeReact } from '@base-ui/utils/safeReact';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { makeEventPreventable, mergeProps } from \"../../merge-props/index.mjs\";\nimport { useCompositeRootContext } from \"../composite/root/CompositeRootContext.mjs\";\nimport { useFocusableWhenDisabled } from \"../../utils/useFocusableWhenDisabled.mjs\";\nimport { dispatchClickWithModifiers } from \"../../utils/dispatchClickWithModifiers.mjs\";\nexport function useButton(parameters = {}) {\n const {\n disabled = false,\n focusableWhenDisabled,\n tabIndex = 0,\n native: isNativeButton = true,\n composite: compositeProp\n } = parameters;\n const elementRef = React.useRef(null);\n const compositeRootContext = useCompositeRootContext(true);\n const isCompositeItem = compositeProp ?? compositeRootContext !== undefined;\n const {\n props: focusableWhenDisabledProps\n } = useFocusableWhenDisabled({\n focusableWhenDisabled,\n disabled,\n composite: isCompositeItem,\n tabIndex,\n isNativeButton\n });\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(() => {\n if (!elementRef.current) {\n return;\n }\n const isButtonTag = isButtonElement(elementRef.current);\n if (isNativeButton) {\n if (!isButtonTag) {\n const ownerStackMessage = SafeReact.captureOwnerStack?.() || '';\n const message = 'A component that acts as a button expected a native <button> because the ' + '`nativeButton` prop is true. Rendering a non-<button> removes native button ' + 'semantics, which can impact forms and accessibility. Use a real <button> in the ' + '`render` prop, or set `nativeButton` to `false`.';\n error(`${message}${ownerStackMessage}`);\n }\n } else if (isButtonTag) {\n const ownerStackMessage = SafeReact.captureOwnerStack?.() || '';\n const message = 'A component that acts as a button expected a non-<button> because the `nativeButton` ' + 'prop is false. Rendering a <button> keeps native behavior while Base UI applies ' + 'non-native attributes and handlers, which can add unintended extra attributes (such ' + 'as `role` or `aria-disabled`). Use a non-<button> in the `render` prop, or set ' + '`nativeButton` to `true`.';\n error(`${message}${ownerStackMessage}`);\n }\n }, [isNativeButton]);\n }\n\n // handles a disabled composite button rendering another button, e.g.\n // <Toolbar.Button disabled render={<Menu.Trigger />} />\n // the `disabled` prop needs to pass through 2 `useButton`s then finally\n // delete the `disabled` attribute from DOM\n const updateDisabled = React.useCallback(() => {\n const element = elementRef.current;\n if (!isButtonElement(element)) {\n return;\n }\n if (isCompositeItem && disabled && focusableWhenDisabledProps.disabled === undefined && element.disabled) {\n element.disabled = false;\n }\n }, [disabled, focusableWhenDisabledProps.disabled, isCompositeItem]);\n useIsoLayoutEffect(updateDisabled, [updateDisabled]);\n const getButtonProps = React.useCallback((externalProps = {}) => {\n const {\n onClick: externalOnClick,\n onMouseDown: externalOnMouseDown,\n onKeyUp: externalOnKeyUp,\n onKeyDown: externalOnKeyDown,\n onPointerDown: externalOnPointerDown,\n ...otherExternalProps\n } = externalProps;\n return mergeProps({\n onClick(event) {\n if (disabled) {\n event.preventDefault();\n return;\n }\n externalOnClick?.(event);\n },\n onMouseDown(event) {\n if (!disabled) {\n externalOnMouseDown?.(event);\n }\n },\n onKeyDown(event) {\n if (disabled) {\n return;\n }\n makeEventPreventable(event);\n externalOnKeyDown?.(event);\n if (event.baseUIHandlerPrevented) {\n return;\n }\n const isCurrentTarget = event.target === event.currentTarget;\n const currentTarget = event.currentTarget;\n const isButton = isButtonElement(currentTarget);\n const isLink = !isNativeButton && isValidLinkElement(currentTarget);\n const shouldClick = isCurrentTarget && (isNativeButton ? isButton : !isLink);\n const isEnterKey = event.key === 'Enter';\n const isSpaceKey = event.key === ' ';\n const role = currentTarget.getAttribute('role');\n const isTextNavigationRole = role?.startsWith('menuitem') || role === 'option' || role === 'gridcell';\n if (isCurrentTarget && isCompositeItem && isSpaceKey) {\n if (event.defaultPrevented && isTextNavigationRole) {\n return;\n }\n event.preventDefault();\n\n // Only a native-mode item that isn't a real <button> is excluded.\n if (!isNativeButton || isButton) {\n event.preventBaseUIHandler();\n dispatchClickWithModifiers(currentTarget, event);\n }\n return;\n }\n\n // Keyboard accessibility for native and non-native elements.\n if (!shouldClick || isNativeButton || !isSpaceKey && !isEnterKey) {\n // Space activates links on keyup (`role=\"button\"` semantics, matching the\n // composite path); prevent the page scroll Space would otherwise trigger.\n // Enter is left to the browser's native link activation.\n if (isCurrentTarget && isLink && isSpaceKey) {\n event.preventDefault();\n }\n return;\n }\n\n // Match native buttons: preventing the keydown's default cancels activation.\n if (event.defaultPrevented) {\n return;\n }\n event.preventDefault();\n if (isEnterKey) {\n event.preventBaseUIHandler();\n dispatchClickWithModifiers(currentTarget, event);\n }\n },\n onKeyUp(event) {\n if (disabled) {\n return;\n }\n\n // calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed\n // https://codesandbox.io/p/sandbox/button-keyup-preventdefault-dn7f0\n makeEventPreventable(event);\n externalOnKeyUp?.(event);\n if (event.target === event.currentTarget && isNativeButton && isCompositeItem && isButtonElement(event.currentTarget) && event.key === ' ') {\n event.preventDefault();\n return;\n }\n if (event.baseUIHandlerPrevented) {\n return;\n }\n\n // Keyboard accessibility for non interactive elements.\n // Match native buttons: preventing the keyup's default cancels Space activation.\n // Limitation: unlike a native <button>, a prevented *keydown* cannot cancel the\n // activation — no state is kept between keydown and keyup, so we can't tell\n // whether the keydown was prevented or even happened on this element.\n if (event.target === event.currentTarget && !isNativeButton && !isCompositeItem && !event.defaultPrevented && event.key === ' ') {\n event.preventBaseUIHandler();\n dispatchClickWithModifiers(event.currentTarget, event);\n }\n },\n onPointerDown(event) {\n if (disabled) {\n event.preventDefault();\n return;\n }\n externalOnPointerDown?.(event);\n }\n }, isNativeButton ? {\n type: 'button'\n } : {\n role: 'button'\n }, focusableWhenDisabledProps, otherExternalProps);\n }, [disabled, focusableWhenDisabledProps, isCompositeItem, isNativeButton]);\n const buttonRef = useStableCallback(element => {\n elementRef.current = element;\n updateDisabled();\n });\n return {\n getButtonProps,\n buttonRef\n };\n}\nfunction isButtonElement(elem) {\n return isHTMLElement(elem) && elem.tagName === 'BUTTON';\n}\nfunction isValidLinkElement(elem) {\n return isHTMLElement(elem) && elem.tagName === 'A' && Boolean(elem.href);\n}","import { useRefWithInit } from \"./useRefWithInit.mjs\";\n\n/**\n * Merges refs into a single memoized callback ref or `null`.\n * This makes sure multiple refs are updated together and have the same value.\n *\n * This function accepts up to four refs. If you need to merge more, or have an unspecified number of refs to merge,\n * use `useMergedRefsN` instead.\n */\n\nexport function useMergedRefs(a, b, c, d) {\n const forkRef = useRefWithInit(createForkRef).current;\n if (didChange(forkRef, a, b, c, d)) {\n update(forkRef, [a, b, c, d]);\n }\n return forkRef.callback;\n}\n\n/**\n * Merges an array of refs into a single memoized callback ref or `null`.\n *\n * If you need to merge a fixed number (up to four) of refs, use `useMergedRefs` instead for better performance.\n */\nexport function useMergedRefsN(refs) {\n const forkRef = useRefWithInit(createForkRef).current;\n if (didChangeN(forkRef, refs)) {\n update(forkRef, refs);\n }\n return forkRef.callback;\n}\nfunction createForkRef() {\n return {\n callback: null,\n cleanup: null,\n refs: []\n };\n}\nfunction didChange(forkRef, a, b, c, d) {\n // prettier-ignore\n return forkRef.refs[0] !== a || forkRef.refs[1] !== b || forkRef.refs[2] !== c || forkRef.refs[3] !== d;\n}\nfunction didChangeN(forkRef, newRefs) {\n return forkRef.refs.length !== newRefs.length || forkRef.refs.some((ref, index) => ref !== newRefs[index]);\n}\nfunction update(forkRef, refs) {\n forkRef.refs = refs;\n if (refs.every(ref => ref == null)) {\n forkRef.callback = null;\n return;\n }\n forkRef.callback = instance => {\n if (forkRef.cleanup) {\n forkRef.cleanup();\n forkRef.cleanup = null;\n }\n if (instance != null) {\n const cleanupCallbacks = Array(refs.length).fill(null);\n for (let i = 0; i < refs.length; i += 1) {\n const ref = refs[i];\n if (ref == null) {\n continue;\n }\n switch (typeof ref) {\n case 'function':\n {\n const refCleanup = ref(instance);\n if (typeof refCleanup === 'function') {\n cleanupCallbacks[i] = refCleanup;\n }\n break;\n }\n case 'object':\n {\n ref.current = instance;\n break;\n }\n default:\n }\n }\n forkRef.cleanup = () => {\n for (let i = 0; i < refs.length; i += 1) {\n const ref = refs[i];\n if (ref == null) {\n continue;\n }\n switch (typeof ref) {\n case 'function':\n {\n const cleanupCallback = cleanupCallbacks[i];\n if (typeof cleanupCallback === 'function') {\n cleanupCallback();\n } else {\n // Legacy ref with no attach-time cleanup: detach by calling it with `null`.\n // It returns nothing; React 19 cleanups are handled in the branch above.\n void ref(null);\n }\n break;\n }\n case 'object':\n {\n ref.current = null;\n break;\n }\n default:\n }\n }\n };\n }\n };\n}","import * as React from 'react';\nconst majorVersion = parseInt(React.version, 10);\nexport function isReactVersionAtLeast(reactVersionToCheck) {\n return majorVersion >= reactVersionToCheck;\n}","import * as React from 'react';\nimport { isReactVersionAtLeast } from \"./reactVersion.mjs\";\n\n/**\n * Extracts the `ref` from a React element, handling different React versions.\n */\nexport function getReactElementRef(element) {\n if (! /*#__PURE__*/React.isValidElement(element)) {\n return null;\n }\n const reactElement = element;\n const propsWithRef = reactElement.props;\n return (isReactVersionAtLeast(19) ? propsWithRef?.ref : reactElement.ref) ?? null;\n}","export function NOOP() {}\nexport const EMPTY_ARRAY = Object.freeze([]);\nexport const EMPTY_OBJECT = Object.freeze({});","export function getStateAttributesProps(state, customMapping) {\n const props = {};\n\n /* eslint-disable-next-line guard-for-in */\n for (const key in state) {\n const value = state[key];\n if (customMapping?.hasOwnProperty(key)) {\n const customProps = customMapping[key](value);\n if (customProps != null) {\n Object.assign(props, customProps);\n }\n continue;\n }\n if (value === true) {\n props[`data-${key.toLowerCase()}`] = '';\n } else if (value) {\n props[`data-${key.toLowerCase()}`] = value.toString();\n }\n }\n return props;\n}","/**\n * If the provided className is a string, it will be returned as is.\n * Otherwise, the function will call the className function with the state as the first argument.\n *\n * @param className\n * @param state\n */\nexport function resolveClassName(className, state) {\n return typeof className === 'function' ? className(state) : className;\n}","/**\n * If the provided style is an object, it will be returned as is.\n * Otherwise, the function will call the style function with the state as the first argument.\n *\n * @param style\n * @param state\n */\nexport function resolveStyle(style, state) {\n return typeof style === 'function' ? style(state) : style;\n}","import _formatErrorMessage from \"@base-ui/utils/formatErrorMessage\";\nimport * as React from 'react';\nimport { useMergedRefs, useMergedRefsN } from '@base-ui/utils/useMergedRefs';\nimport { getReactElementRef } from '@base-ui/utils/getReactElementRef';\nimport { mergeObjects } from '@base-ui/utils/mergeObjects';\nimport { warn } from '@base-ui/utils/warn';\nimport { EMPTY_OBJECT } from '@base-ui/utils/empty';\nimport { getStateAttributesProps } from \"./getStateAttributesProps.mjs\";\nimport { resolveClassName } from \"../utils/resolveClassName.mjs\";\nimport { resolveStyle } from \"../utils/resolveStyle.mjs\";\nimport { mergeProps, mergePropsN, mergeClassNames } from \"../merge-props/index.mjs\";\nimport { createElement as _createElement } from \"react\";\n/**\n * Renders a Base UI element.\n *\n * @param element The default HTML element to render. Can be overridden by the `render` prop.\n * @param componentProps An object containing the `render` and `className` props to be used for element customization. Other props are ignored.\n * @param params Additional parameters for rendering the element.\n */\nexport function useRenderElement(element, componentProps, params = {}) {\n const renderProp = componentProps.render;\n const outProps = useRenderElementProps(componentProps, params);\n if (params.enabled === false) {\n return null;\n }\n const state = params.state ?? EMPTY_OBJECT;\n return evaluateRenderProp(element, renderProp, outProps, state);\n}\n\n/**\n * Computes render element final props.\n */\nfunction useRenderElementProps(componentProps, params = {}) {\n const {\n className: classNameProp,\n style: styleProp,\n render: renderProp\n } = componentProps;\n const {\n state = EMPTY_OBJECT,\n ref,\n props,\n stateAttributesMapping,\n enabled = true\n } = params;\n const className = enabled ? resolveClassName(classNameProp, state) : undefined;\n const style = enabled ? resolveStyle(styleProp, state) : undefined;\n const stateProps = enabled ? getStateAttributesProps(state, stateAttributesMapping) : EMPTY_OBJECT;\n const resolvedProps = enabled && props ? resolveRenderFunctionProps(props) : undefined;\n\n // Ensure outProps is always a new mutable object when enabled, never EMPTY_OBJECT.\n // This prevents potential TypeError when setting ref, className, or style properties,\n // since EMPTY_OBJECT is frozen and mutations would fail in strict mode.\n const outProps = enabled ? mergeObjects(stateProps, resolvedProps) ?? {} : EMPTY_OBJECT;\n\n // SAFETY: The `useMergedRefs` functions use a single hook to store the same value,\n // switching between them at runtime is safe. If this assertion fails, React will\n // throw at runtime anyway.\n // This also skips the `useMergedRefs` call on the server, which is fine because\n // refs are not used on the server side.\n /* eslint-disable react-hooks/rules-of-hooks */\n if (typeof document !== 'undefined') {\n if (!enabled) {\n // Called only to keep the hook order stable when disabled; the merged ref is unused.\n void useMergedRefs(null, null);\n } else if (Array.isArray(ref)) {\n outProps.ref = useMergedRefsN([outProps.ref, getReactElementRef(renderProp), ...ref]);\n } else {\n outProps.ref = useMergedRefs(outProps.ref, getReactElementRef(renderProp), ref);\n }\n }\n if (!enabled) {\n return EMPTY_OBJECT;\n }\n if (className !== undefined) {\n outProps.className = mergeClassNames(outProps.className, className);\n }\n if (style !== undefined) {\n outProps.style = mergeObjects(outProps.style, style);\n }\n return outProps;\n}\nfunction resolveRenderFunctionProps(props) {\n if (Array.isArray(props)) {\n return mergePropsN(props);\n }\n return mergeProps(undefined, props);\n}\n\n// The symbol React uses internally for lazy components\n// https://github.com/react/react/blob/a0566250b210499b4c5677f5ac2eedbd71d51a1b/packages/shared/ReactSymbols.js#L31\n//\n// TODO delete once https://github.com/react/react/issues/32392 is fixed\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy');\nconst COMPONENT_IDENTIFIER_PATTERN = /^[A-Z][A-Za-z0-9$]*$/;\nconst LOWERCASE_CHARACTER_PATTERN = /[a-z]/;\nfunction evaluateRenderProp(element, render, props, state) {\n if (render) {\n if (typeof render === 'function') {\n if (process.env.NODE_ENV !== 'production') {\n warnIfRenderPropLooksLikeComponent(render);\n }\n return render(props, state);\n }\n const mergedProps = mergeProps(props, render.props);\n mergedProps.ref = props.ref;\n let newElement = render;\n // Workaround for https://github.com/react/react/issues/32392\n // This works because the toArray() logic unwrap lazy element type in\n // https://github.com/react/react/blob/a0566250b210499b4c5677f5ac2eedbd71d51a1b/packages/react/src/ReactChildren.js#L186\n if (newElement?.$$typeof === REACT_LAZY_TYPE) {\n const children = React.Children.toArray(render);\n newElement = children[0];\n }\n\n // There is a high number of indirections, the error message thrown by React.cloneElement() is\n // hard to use for developers, this logic provides a better context.\n //\n // Our general guideline is to never change the control flow depending on the environment.\n // However, React.cloneElement() throws if React.isValidElement() is false,\n // so we can throw before with custom message.\n if (process.env.NODE_ENV !== 'production') {\n if (! /*#__PURE__*/React.isValidElement(newElement)) {\n // TODO: fix mui/no-guarded-throw\n // eslint-disable-next-line mui/no-guarded-throw\n throw new Error(['Base UI: The `render` prop was provided an invalid React element as `React.isValidElement(render)` is `false`.', 'A valid React element must be provided to the `render` prop because it is cloned with props to replace the default element.', 'https://base-ui.com/r/invalid-render-prop'].join('\\n'));\n }\n }\n return /*#__PURE__*/React.cloneElement(newElement, mergedProps);\n }\n if (element) {\n if (typeof element === 'string') {\n return renderTag(element, props);\n }\n }\n // Unreachable, but the typings on `useRenderElement` need to be reworked\n // to annotate it correctly.\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'Base UI: Render element or function are not defined.' : _formatErrorMessage(8));\n}\nfunction warnIfRenderPropLooksLikeComponent(renderFn) {\n const functionName = renderFn.name;\n if (functionName.length === 0) {\n return;\n }\n if (!COMPONENT_IDENTIFIER_PATTERN.test(functionName)) {\n return;\n }\n if (!LOWERCASE_CHARACTER_PATTERN.test(functionName)) {\n return;\n }\n warn(`The \\`render\\` prop received a function named \\`${functionName}\\` that starts with an uppercase letter.`, 'This usually means a React component was passed directly as `render={Component}`.', 'Base UI calls `render` as a plain function, which can break the Rules of Hooks during reconciliation.', 'If this is an intentional render callback, rename it to start with a lowercase letter.', 'Use `render={<Component />}` or `render={(props) => <Component {...props} />}` instead.', 'https://base-ui.com/r/invalid-render-prop');\n}\nfunction renderTag(Tag, props) {\n if (Tag === 'button') {\n return /*#__PURE__*/_createElement(\"button\", {\n type: \"button\",\n ...props,\n key: props.key\n });\n }\n if (Tag === 'img') {\n return /*#__PURE__*/_createElement(\"img\", {\n alt: \"\",\n ...props,\n key: props.key\n });\n }\n return /*#__PURE__*/React.createElement(Tag, props);\n}","'use client';\n\nimport * as React from 'react';\nimport { useButton } from \"../internals/use-button/useButton.mjs\";\nimport { useRenderElement } from \"../internals/useRenderElement.mjs\";\n/**\n * A button component that can be used to trigger actions.\n * Renders a `<button>` element.\n *\n * Documentation: [Base UI Button](https://base-ui.com/react/components/button)\n */\nexport const Button = /*#__PURE__*/React.forwardRef(function Button(componentProps, forwardedRef) {\n const {\n render,\n className,\n disabled = false,\n focusableWhenDisabled = false,\n nativeButton = true,\n style,\n ...elementProps\n } = componentProps;\n const {\n getButtonProps,\n buttonRef\n } = useButton({\n disabled,\n focusableWhenDisabled,\n native: nativeButton\n });\n const state = {\n disabled\n };\n return useRenderElement('button', componentProps, {\n state,\n ref: [forwardedRef, buttonRef],\n props: [elementProps, getButtonProps]\n });\n});\nif (process.env.NODE_ENV !== \"production\") Button.displayName = \"Button\";","import { Button as BaseButton } from '@base-ui/react/button';\nimport type { ComponentPropsWithRef } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { getElevationStyle, radiusClasses } from '../../design-system/component-tokens';\nimport type { ShadowToken } from '../../design-system/shadows';\n\ntype ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'bare' | 'chip' | 'tab';\ntype ButtonSize = 'sm' | 'md';\ntype ButtonShape = 'default' | 'theme' | 'pill';\n\nexport interface ButtonProps extends ComponentPropsWithRef<'button'> {\n active?: boolean;\n elevation?: ShadowToken;\n size?: ButtonSize;\n shape?: ButtonShape;\n stacked?: boolean;\n variant?: ButtonVariant;\n full?: boolean;\n}\n\nconst variantStyles: Record<ButtonVariant, string> = {\n primary: 'bg-primary text-primary-foreground border-transparent hover:bg-primary/90',\n secondary: 'bg-secondary text-secondary-foreground border-transparent hover:bg-secondary/80',\n ghost: 'bg-transparent text-foreground border-border hover:bg-border',\n bare: 'bg-transparent text-inherit border-transparent hover:bg-transparent p-0 min-h-0',\n chip: 'bg-secondary-bg text-foreground border-transparent hover:bg-primary hover:text-primary-foreground hover:border-primary',\n tab: 'bg-transparent text-foreground-muted border-transparent hover:text-foreground hover:bg-transparent p-0 min-h-0',\n};\n\nconst sizeStyles: Record<ButtonSize, string> = {\n sm: 'px-2 py-1 text-xs min-h-7',\n md: 'px-4 py-2 text-sm min-h-9',\n};\n\nconst shapeClasses: Record<ButtonShape, string> = {\n default: 'rounded-lg',\n theme: radiusClasses.theme,\n pill: radiusClasses.pill,\n};\n\nexport function Button({\n active = false,\n className,\n disabled,\n elevation,\n full,\n shape = 'default',\n size = 'md',\n stacked = false,\n type = 'button',\n variant = 'primary',\n style,\n ref,\n ...props\n}: ButtonProps) {\n const hasChrome = !['bare', 'tab'].includes(variant);\n\n return (\n <BaseButton\n {...props}\n ref={ref}\n className={cn(\n 'inline-flex items-center justify-center gap-2 font-medium cursor-pointer transition-all focus-visible:outline-2 focus-visible:outline-ring focus-visible:outline-offset-2',\n hasChrome && 'border',\n shapeClasses[shape],\n variantStyles[variant],\n variant !== 'bare' && variant !== 'tab' && sizeStyles[size],\n stacked && 'flex-col gap-0.5',\n variant === 'tab' && 'h-full min-w-0 flex-1',\n active && variant === 'tab' && 'text-primary font-semibold',\n disabled && 'opacity-50 cursor-not-allowed pointer-events-none',\n full && 'w-full',\n className,\n )}\n data-disabled={disabled ? 'true' : 'false'}\n data-size={size}\n data-variant={variant}\n disabled={disabled}\n style={{ ...getElevationStyle(elevation), ...style }}\n type={type}\n />\n );\n}\n","import { type ElementType, forwardRef } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { getElevationStyle } from '../../design-system/component-tokens';\nimport type { ShadowToken } from '../../design-system/shadows';\nimport { type LayoutProps, resolveLayoutClasses, stripLayoutProps } from './layoutProps';\n\nexport type SurfaceBackground = 'default' | 'card';\nexport type SurfacePadding = 'none' | 'card' | 'toast';\n\nexport interface SurfaceProps extends LayoutProps, Omit<React.HTMLAttributes<HTMLElement>, 'className'> {\n as?: ElementType;\n background?: SurfaceBackground;\n elevation?: ShadowToken;\n paddingPreset?: SurfacePadding;\n /** @internal blocks/ only */\n className?: string;\n}\n\nexport const backgroundClasses: Record<SurfaceBackground, string> = {\n default: '',\n card: 'bg-card text-card-foreground',\n};\n\nexport const paddingPresetClasses: Record<SurfacePadding, string> = {\n none: '',\n card: 'px-3 py-2',\n toast: 'py-2 pl-2 pr-3',\n};\n\nexport const Surface = forwardRef<HTMLElement, SurfaceProps>(function Surface(props, ref) {\n const {\n as: Component = 'div',\n background = 'default',\n className,\n elevation,\n paddingPreset = 'none',\n style,\n ...rest\n } = props;\n const layoutClasses = resolveLayoutClasses(props);\n const domProps = stripLayoutProps(rest);\n\n return (\n <Component\n {...domProps}\n ref={ref}\n className={cn(backgroundClasses[background], paddingPresetClasses[paddingPreset], layoutClasses, className)}\n style={{ ...getElevationStyle(elevation), ...style }}\n />\n );\n});\n","import { forwardRef, type ReactNode } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { Surface, type SurfaceProps } from './Surface';\n\nexport interface FlexProps extends SurfaceProps {\n direction?: 'row' | 'column';\n children?: ReactNode;\n}\n\nexport const Flex = forwardRef<HTMLElement, FlexProps>(function Flex(props, ref) {\n const { className, direction, ...rest } = props;\n return <Surface {...rest} ref={ref} className={cn('flex', direction === 'column' && 'flex-col', className)} />;\n});\n","export interface IconPath {\n d: string;\n fill?: string;\n stroke?: string;\n strokeWidth?: number | string;\n strokeLinecap?: 'butt' | 'round' | 'square';\n strokeLinejoin?: 'miter' | 'round' | 'bevel';\n strokeMiterlimit?: number | string;\n fillRule?: 'nonzero' | 'evenodd';\n clipRule?: 'nonzero' | 'evenodd';\n}\n\nexport interface IconData {\n viewBox: string;\n paths: IconPath[];\n}\n\n/** Icon.tsx resolves an absent `fill` to 'none' whenever a stroke is set, so a stroked path omits it. */\nconst stroked = (d: string, strokeWidth = 2): IconPath => ({\n d,\n stroke: 'currentColor',\n strokeWidth,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n});\n\nexport const icons = {\n checkCircle: {\n viewBox: '0 0 512 512',\n paths: [\n {\n d: 'M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z',\n fill: 'currentColor',\n },\n ],\n },\n\n circle: {\n viewBox: '0 0 512 512',\n paths: [\n {\n d: 'M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z',\n fill: 'currentColor',\n },\n ],\n },\n\n exclamationCircle: {\n viewBox: '0 0 512 512',\n paths: [\n {\n d: 'M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z',\n fill: 'currentColor',\n },\n ],\n },\n\n arrowUp: {\n viewBox: '0 0 448 512',\n paths: [\n {\n d: 'M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z',\n fill: 'currentColor',\n },\n ],\n },\n\n arrowDown: {\n viewBox: '0 0 448 512',\n paths: [\n {\n d: 'M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z',\n fill: 'currentColor',\n },\n ],\n },\n\n chatBubble: {\n viewBox: '0 0 512 512',\n paths: [\n {\n d: 'M87.48 380c1.2-4.38-1.43-10.47-3.94-14.86a42.63 42.63 0 0 0-2.54-3.8 199.81 199.81 0 0 1-33-110C47.64 139.09 140.72 48 255.82 48 356.2 48 440 117.54 459.57 209.85a199 199 0 0 1 4.43 41.64c0 112.41-89.49 204.93-204.59 204.93-18.31 0-43-4.6-56.47-8.37s-26.92-8.77-30.39-10.11a31.14 31.14 0 0 0-11.13-2.07 30.7 30.7 0 0 0-12.08 2.43L81.5 462.78a15.92 15.92 0 0 1-4.66 1.22 9.61 9.61 0 0 1-9.58-9.74 15.85 15.85 0 0 1 .6-3.29z',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 32,\n strokeLinecap: 'round',\n },\n { d: 'M160 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0', fill: 'currentColor' },\n { d: 'M256 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0', fill: 'currentColor' },\n { d: 'M352 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0', fill: 'currentColor' },\n ],\n },\n\n stop: {\n viewBox: '0 0 512 512',\n paths: [\n {\n d: 'M392 432H120a40 40 0 0 1-40-40V120a40 40 0 0 1 40-40h272a40 40 0 0 1 40 40v272a40 40 0 0 1-40 40z',\n fill: 'currentColor',\n },\n ],\n },\n\n mousePointerClick: {\n viewBox: '0 0 24 24',\n paths: [\n stroked('M14 4.1 12 6'),\n stroked('m5.1 8-2.9-.8'),\n stroked('m6 12-1.9 2'),\n stroked('M7.2 2.2 8 5.1'),\n stroked(\n 'M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z',\n ),\n ],\n },\n\n ticktick: {\n viewBox: '0 0 24 24',\n paths: [\n {\n d: 'M12 0C5.383 0 0 5.383 0 12s5.383 12 12 12 12-5.383 12-12h-2.7c0 5.128-4.172 9.3-9.3 9.3-5.128 0-9.3-4.172-9.3-9.3 0-5.128 4.172-9.3 9.3-9.3V0Zm7.4 2.583-7.505 9.371L8.388 9.08l-2.002 2.436 4.741 3.888a1.573 1.573 0 0 0 2.231-.233l8.504-10.617L19.4 2.583Z',\n fill: 'currentColor',\n },\n ],\n },\n\n home: {\n viewBox: '0 0 24 24',\n paths: [\n stroked(\n 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6',\n ),\n ],\n },\n\n chat: {\n viewBox: '0 0 24 24',\n paths: [\n stroked(\n 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z',\n ),\n ],\n },\n\n send: {\n viewBox: '0 0 24 24',\n paths: [stroked('M5 12h14m-7-7l7 7-7 7')],\n },\n\n closeSmall: {\n viewBox: '0 0 12 12',\n paths: [stroked('M9 3L3 9M3 3l6 6', 1.5)],\n },\n\n close: {\n viewBox: '0 0 20 20',\n paths: [\n {\n d: 'M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z',\n fill: 'currentColor',\n fillRule: 'evenodd',\n clipRule: 'evenodd',\n },\n ],\n },\n\n chevronDown: {\n viewBox: '0 0 24 24',\n paths: [stroked('M19 9l-7 7-7-7', 2.5)],\n },\n\n screenShare: {\n viewBox: '0 0 24 24',\n paths: [\n stroked(\n 'M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z',\n ),\n ],\n },\n\n alertCircle: {\n viewBox: '0 0 24 24',\n paths: [stroked('M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z')],\n },\n} as const satisfies Record<string, IconData>;\n\nexport type IconName = keyof typeof icons;\n","import type { ComponentPropsWithRef } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { type IconData, type IconName, icons } from './icons';\n\nexport interface IconProps extends ComponentPropsWithRef<'svg'> {\n name: IconName;\n size?: number;\n /** @internal blocks/ only */\n className?: string;\n}\n\nexport function Icon({ name, size = 16, className, ref, ...props }: IconProps) {\n const icon = icons[name] as IconData | undefined;\n if (!icon) return null;\n\n return (\n <svg\n {...props}\n ref={ref}\n aria-hidden='true'\n className={cn('inline-block flex-shrink-0', className)}\n fill='none'\n height={size}\n viewBox={icon.viewBox}\n width={size}\n xmlns='http://www.w3.org/2000/svg'\n >\n {icon.paths.map((p, i) => (\n <path\n key={i}\n clipRule={p.clipRule}\n d={p.d}\n fill={p.fill ?? (p.stroke ? 'none' : 'currentColor')}\n fillRule={p.fillRule}\n stroke={p.stroke}\n strokeLinecap={p.strokeLinecap}\n strokeLinejoin={p.strokeLinejoin}\n strokeMiterlimit={p.strokeMiterlimit}\n strokeWidth={p.strokeWidth}\n />\n ))}\n </svg>\n );\n}\n","import type { ComponentPropsWithRef } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { radiusClasses, type TextTone, textToneClasses } from '../../design-system/component-tokens';\n\ntype IconButtonVariant = 'primary' | 'secondary' | 'ghost';\ntype IconButtonSize = 'xs' | 'sm';\n\nexport interface IconButtonProps extends ComponentPropsWithRef<'button'> {\n variant?: IconButtonVariant;\n size?: IconButtonSize;\n tone?: TextTone;\n label: string;\n /** @internal blocks/ only */\n className?: string;\n}\n\nconst variantStyles: Record<IconButtonVariant, string> = {\n primary: 'bg-primary text-primary-foreground hover:bg-primary-hover',\n secondary: 'bg-secondary-bg text-foreground hover:bg-secondary-hover',\n ghost: 'bg-transparent text-foreground opacity-60 hover:opacity-100',\n};\n\nconst sizeStyles: Record<IconButtonSize, string> = {\n xs: 'w-5 h-5 min-w-5',\n sm: 'w-7 h-7 min-w-7',\n};\n\nexport function IconButton({\n variant = 'ghost',\n size = 'sm',\n tone,\n label,\n disabled,\n className: userClassName,\n children,\n style,\n ref,\n ...props\n}: IconButtonProps) {\n return (\n <button\n {...props}\n ref={ref}\n type='button'\n disabled={disabled}\n aria-label={label}\n className={cn(\n 'inline-flex items-center justify-center flex-shrink-0 border-none cursor-pointer transition-all',\n radiusClasses.circle,\n variantStyles[variant],\n tone && textToneClasses[tone],\n sizeStyles[size],\n disabled && 'opacity-50 cursor-not-allowed pointer-events-none',\n userClassName,\n )}\n style={style}\n >\n {children}\n </button>\n );\n}\n","import { forwardRef } from 'react';\n\nimport { Flex, type FlexProps } from './Flex';\n\nexport type StackProps = Omit<FlexProps, 'direction'>;\n\nexport const Stack = forwardRef<HTMLElement, StackProps>(function Stack(props, ref) {\n return <Flex {...props} ref={ref} direction='column' />;\n});\n","import type { ElementType, Ref } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport {\n type TextLeading,\n textLeadingClasses,\n type TextTone,\n textToneClasses,\n} from '../../design-system/component-tokens';\n\ntype TextVariant = 'default' | 'muted' | 'faint';\ntype TextSize = 'xxs' | 'xs' | 'sm' | 'lg';\ntype TextWeight = 'normal' | 'medium' | 'semibold';\ntype TextAlign = 'center' | 'right';\n\nexport interface TextProps extends React.HTMLAttributes<HTMLElement> {\n as?: ElementType;\n block?: boolean;\n inheritColor?: boolean;\n italic?: boolean;\n leading?: TextLeading;\n variant?: TextVariant;\n size?: TextSize;\n weight?: TextWeight;\n truncate?: boolean;\n align?: TextAlign;\n /** @internal blocks/ only */\n className?: string;\n ref?: Ref<HTMLElement>;\n}\n\nconst sizeStyles: Record<TextSize, string> = {\n xxs: 'text-[10px]',\n xs: 'text-xs',\n sm: 'text-sm',\n lg: 'text-lg',\n};\n\nconst weightStyles: Record<TextWeight, string> = {\n normal: 'font-normal',\n medium: 'font-medium',\n semibold: 'font-semibold',\n};\n\nconst alignStyles: Record<TextAlign, string> = {\n center: 'text-center',\n right: 'text-right',\n};\n\nexport function Text({\n as: Component = 'span',\n block = false,\n inheritColor = false,\n italic = false,\n leading,\n variant = 'default',\n size,\n weight,\n truncate,\n align,\n className,\n ref,\n style,\n ...props\n}: TextProps) {\n const resolvedTone: TextTone = inheritColor ? 'inherit' : variant;\n\n return (\n <Component\n {...props}\n ref={ref}\n className={cn(\n textToneClasses[resolvedTone],\n size && sizeStyles[size],\n weight && weightStyles[weight],\n align && alignStyles[align],\n leading && textLeadingClasses[leading],\n block && 'block',\n italic && 'italic',\n truncate && 'truncate',\n className,\n )}\n style={style}\n />\n );\n}\n","import React, { useCallback, useEffect, useState } from 'react';\n\nimport MarketrixIcon from '../../assets/marketrix-icon.svg';\nimport { type NotificationTone, notificationToneStyles } from '../../design-system/component-tokens';\nimport { LAYER_TOKENS } from '../../design-system/layers';\nimport { Avatar } from '../base/Avatar';\nimport { Button } from '../base/Button';\nimport { Flex } from '../base/Flex';\nimport { Icon } from '../base/Icon';\nimport { IconButton } from '../base/IconButton';\nimport { Stack } from '../base/Stack';\nimport { Surface } from '../base/Surface';\nimport { Text } from '../base/Text';\n\nconst AUTO_DISMISS_MS = 8000;\n\nexport interface NotificationToastProps {\n tone: NotificationTone;\n title: string;\n body?: string;\n onDismiss: () => void;\n onRetry?: () => void;\n position?: 'bottom-center' | 'above-fab';\n}\n\nexport const NotificationToast: React.FC<NotificationToastProps> = ({\n tone,\n title,\n body,\n onDismiss,\n onRetry,\n position = 'bottom-center',\n}) => {\n const [isExiting, setIsExiting] = useState(false);\n\n const dismiss = useCallback(() => {\n setIsExiting(true);\n setTimeout(onDismiss, 300);\n }, [onDismiss]);\n\n // Only the greeting toast times out; error and neutral stay until dismissed.\n useEffect(() => {\n if (tone !== 'info') return;\n const timer = setTimeout(dismiss, AUTO_DISMISS_MS);\n return () => clearTimeout(timer);\n }, [tone, dismiss]);\n\n const colors = notificationToneStyles[tone];\n\n return (\n <Surface\n position='fixed'\n animate={isExiting ? 'none' : 'fadeIn'}\n style={{\n zIndex: LAYER_TOKENS.toast,\n maxWidth: '420px',\n opacity: isExiting ? 0 : 1,\n transition: 'opacity 0.3s ease-out',\n bottom: position === 'above-fab' ? '90px' : '20px',\n left: '50%',\n transform: 'translateX(-50%)',\n }}\n >\n <Flex\n align='center'\n gap='md'\n rounded='pill'\n paddingPreset='toast'\n elevation='panel'\n style={{\n backgroundColor: colors.background,\n border: colors.border,\n }}\n >\n <Avatar src={MarketrixIcon} alt='' size={28} rounded='full' />\n\n <Stack grow minWidth='0'>\n <Text\n as='span'\n block\n inheritColor\n weight='medium'\n style={{\n fontSize: '13px',\n color: colors.titleColor,\n whiteSpace: onRetry ? 'normal' : 'nowrap',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n }}\n >\n {title}\n </Text>\n {body && (\n <Text\n as='span'\n block\n inheritColor\n style={{\n fontSize: '12px',\n color: colors.bodyColor,\n opacity: 0.8,\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n }}\n >\n {body}\n </Text>\n )}\n </Stack>\n\n {onRetry && (\n <Button\n type='button'\n variant='ghost'\n shape='pill'\n size='sm'\n onClick={() => {\n onRetry();\n dismiss();\n }}\n style={{\n color: colors.titleColor,\n backgroundColor: colors.actionBackground,\n border: colors.border,\n }}\n aria-label='Retry'\n >\n Retry\n </Button>\n )}\n\n <IconButton\n label='Dismiss'\n onClick={e => {\n e.stopPropagation();\n dismiss();\n }}\n size='xs'\n tone='inherit'\n style={{\n color: colors.closeColor,\n padding: '2px',\n }}\n >\n <Icon name='closeSmall' size={12} />\n </IconButton>\n </Flex>\n </Surface>\n );\n};\n","import type { ChatMessage, InstructionType } from '../types';\nimport { type ChatSnapshot, storageService, type StoredMessage } from './StorageService';\n\nfunction reviveMessage(msg: StoredMessage): ChatMessage {\n const parts = [...msg.parts];\n const text = msg.content.trim();\n if (parts.length === 0 && text) parts.push({ type: 'text', content: text });\n return { ...msg, timestamp: new Date(msg.timestamp), parts };\n}\n\nfunction serializeMessage({ videoStream, ...msg }: ChatMessage): StoredMessage {\n const timestamp = msg.timestamp.toISOString();\n if (!videoStream) return { ...msg, timestamp };\n const content = 'Screenshare ended';\n return { ...msg, timestamp, content, isSystemMessage: true, parts: [{ type: 'text', content }] };\n}\n\nexport class ChatService {\n restore(): ChatSnapshot {\n const { chat_id: _chatId, config: _config, timestamp: _timestamp, messages, ...rest } = storageService.getContext();\n return { ...rest, messages: messages.map(reviveMessage) };\n }\n\n persist(snapshot: ChatSnapshot): void {\n storageService.updateContext({ ...snapshot, messages: snapshot.messages.map(serializeMessage) });\n }\n}\n\nexport const chatService = new ChatService();\n\nfunction createMessage(\n idPrefix: string,\n sender: 'user' | 'agent',\n content: string,\n extra: Partial<ChatMessage> = {},\n): ChatMessage {\n return {\n id: `${idPrefix}-${Date.now()}`,\n content,\n sender,\n timestamp: new Date(),\n parts: content ? [{ type: 'text', content }] : [],\n ...extra,\n };\n}\n\nexport const createUserMessage = (content: string, mode?: InstructionType, idPrefix = 'user-message'): ChatMessage =>\n createMessage(idPrefix, 'user', content.trim(), { mode });\n\nexport const createAgentMessage = (content: string): ChatMessage =>\n createMessage('agent-message', 'agent', content.trim());\n\nexport const createSystemMessage = (\n content: string,\n mode: InstructionType,\n sender: 'user' | 'agent',\n idPrefix: string,\n): ChatMessage => createMessage(idPrefix, sender, content, { mode, isSystemMessage: true });\n\nexport const createScreenAccessRequestMessage = (mode?: InstructionType): ChatMessage =>\n createMessage('screen-access-request', 'agent', 'Can I take a look at your screen?', {\n mode,\n isScreenAccessRequest: true,\n });\n\nexport const createScreenshareMessage = (stream: MediaStream, mode: InstructionType = 'show'): ChatMessage =>\n createMessage('screenshare', 'user', '', { mode, videoStream: stream });\n","import { type InstructionType, sdk, type WidgetCommand } from '../sdk';\nimport { chatSessionManager } from './ChatSessionManager';\nimport { type CredentialedConfig, storageService } from './StorageService';\nimport { StreamClient } from './StreamClient';\n\nfunction logWidgetQuestion(config: CredentialedConfig, question: string, mode: InstructionType): void {\n const metadata: Record<string, unknown> = {\n question,\n mode,\n chat_id: storageService.getChatId(),\n timestamp: new Date().toISOString(),\n marketrix_id: config.mtxId,\n marketrix_key: config.mtxKey,\n };\n\n if (config.userId) metadata.user_id = config.userId;\n\n sdk\n .activityLogCreate({ type: 'widget_question', metadata })\n .catch((error: unknown) => console.warn('[API Service] Failed to log widget question:', error));\n}\n\n/** The reply does not come back from here — it arrives asynchronously as a chat/response event on the stream. */\nexport async function messageDispatch(\n config: CredentialedConfig,\n message: string,\n mode: InstructionType,\n requestId: string,\n): Promise<void> {\n const chatId = await chatSessionManager.getOrCreateChatId();\n logWidgetQuestion(config, message, mode);\n\n const command: WidgetCommand = { type: `chat/${mode}`, request_id: requestId, content: message };\n\n const streamClient = StreamClient.getInstance();\n await streamClient.connect(chatId);\n await streamClient.waitUntilRegistered();\n await streamClient.send(command);\n}\n","import type { ChatMessage, InstructionType, MessagePart } from '../types';\n\nconst MODE_DISPLAY_NAMES: Record<InstructionType, string> = { show: 'Show', tell: 'Tell', do: 'Do' };\n\nexport const getModeDisplayName = (mode: InstructionType): string => MODE_DISPLAY_NAMES[mode];\n\nexport const formatMessageTime = (date: Date | undefined): string =>\n (date ?? new Date()).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });\n\nexport interface FindMessageOptions {\n messages: ChatMessage[];\n isTaskRunning: boolean;\n currentMode: InstructionType;\n}\n\nfunction lastIndexWhere<T>(items: T[], matches: (item: T) => boolean): number {\n for (let i = items.length - 1; i >= 0; i--) {\n if (matches(items[i])) return i;\n }\n return -1;\n}\n\n/** Ranked predicates: the first rank matching anything wins, and within it the newest message. */\nexport function findMessageForProgress({\n messages,\n isTaskRunning,\n currentMode,\n}: FindMessageOptions): { index: number; message: ChatMessage } | null {\n const isAgentReply = (msg: ChatMessage) =>\n msg.sender === 'agent' && !msg.isSystemMessage && !msg.isScreenAccessRequest;\n // Lenient on placeholders with an undefined mode — tool calls can race ahead of the mode being set.\n const modeMatches = (msg: ChatMessage) =>\n msg.isPlaceholder ? msg.mode === undefined || msg.mode === currentMode : msg.mode === currentMode;\n\n const ranked: Array<(msg: ChatMessage) => boolean> = [];\n if (isTaskRunning && (currentMode === 'show' || currentMode === 'do')) {\n ranked.push(\n msg => isAgentReply(msg) && modeMatches(msg) && !!msg.isPlaceholder,\n msg => isAgentReply(msg) && modeMatches(msg),\n );\n }\n // Tool calls can arrive before isTaskRunning flips true, so always fall back to a mode-agnostic match.\n ranked.push(msg => isAgentReply(msg) && !!msg.isPlaceholder, isAgentReply);\n\n for (const matches of ranked) {\n const index = lastIndexWhere(messages, matches);\n if (index >= 0) return { index, message: messages[index] };\n }\n\n console.warn('[MessageFinder] No message found for progress update', {\n totalMessages: messages.length,\n isTaskRunning,\n currentMode,\n });\n return null;\n}\n\n// In `show` mode these pause for the user to act (DOM-mutating tools, minus `scroll`); also the highlight set in BrowserToolService.\nexport const WAIT_FOR_USER_TOOLS = new Set(['click_element', 'type_text', 'select_dropdown_option', 'send_keys']);\n\n// \"Cancelled by cleanup\" is expected internal chatter users shouldn't see.\nconst filterCancellationText = (content: string): string => content.replace(/\\(?cancelled by cleanup\\)?/gi, '').trim();\n\nconst isOpenProgress = (part: MessagePart): boolean => part.type === 'progress' && part.status === 'in_progress';\n\nfunction patchPart(message: ChatMessage, index: number, patch: Partial<MessagePart>): ChatMessage {\n if (index < 0) return message;\n const parts = [...message.parts];\n parts[index] = { ...parts[index], ...patch };\n return { ...message, parts };\n}\n\nconst openLineFor = (message: ChatMessage, browserToolName: string): number =>\n message.parts.findIndex(part => isOpenProgress(part) && part.browserToolName === browserToolName);\n\nexport function addProgressLine(message: ChatMessage, browserToolName: string, explanation: string): ChatMessage {\n const content = filterCancellationText(explanation);\n const open = openLineFor(message, browserToolName);\n if (open >= 0) return patchPart(message, open, { content });\n return {\n ...message,\n parts: [...message.parts, { type: 'progress', content, status: 'in_progress', browserToolName }],\n };\n}\n\nexport const markProgressLineComplete = (message: ChatMessage, browserToolName: string): ChatMessage =>\n patchPart(message, openLineFor(message, browserToolName), { status: 'completed' });\n\nexport function markProgressLineFailed(message: ChatMessage, browserToolName: string, error: string): ChatMessage {\n const index = openLineFor(message, browserToolName);\n if (index < 0) return message;\n\n const content = filterCancellationText(message.parts[index].content);\n const cleanedError = filterCancellationText(error);\n return patchPart(message, index, {\n status: 'failed',\n content: cleanedError ? `${content} (${cleanedError})` : content,\n });\n}\n\n/** Tool id -> the phrase shown in the activity log. Also the allowlist of tools the agent may call. */\nexport const BROWSER_TOOLS = new Map<string, string>([\n ['navigate', 'Navigating'],\n ['search', 'Searching'],\n ['click_element', 'Clicking element'],\n ['type_text', 'Typing text'],\n ['scroll', 'Scrolling'],\n ['scroll_to_text', 'Scrolling to text'],\n ['send_keys', 'Pressing key'],\n ['extract', 'Extracting content'],\n ['get_dropdown_options', 'Reading dropdown options'],\n ['select_dropdown_option', 'Selecting option'],\n ['go_back', 'Going back'],\n ['wait', 'Waiting'],\n ['close_tab', 'Closing tab'],\n ['done', 'Done'],\n ['get_html', 'Reading the page'],\n ['get_screenshot', 'Taking screenshot'],\n]);\n\n// ChatContext rejects a tool/call whose name is not in BROWSER_TOOLS before the reducer sees it.\nexport const getFriendlyToolName = (browserToolName: string): string =>\n BROWSER_TOOLS.get(browserToolName) ?? browserToolName;\n","export const WIDGET_SHADOW_HOST_CLASS = 'marketrix-widget-container';\n\nconst INTERACTIVE_ROLES = new Set(['button', 'link', 'textbox', 'checkbox', 'radio', 'switch', 'tab', 'menuitem']);\n\nfunction isInteractiveKind(el: Element): boolean {\n const tag = el.tagName.toLowerCase();\n return (\n tag === 'button' ||\n tag === 'input' ||\n tag === 'textarea' ||\n tag === 'select' ||\n (tag === 'a' && el.hasAttribute('href')) ||\n INTERACTIVE_ROLES.has(el.getAttribute('role') ?? '') ||\n el.getAttribute('contenteditable') === 'true' ||\n el.hasAttribute('onclick') ||\n parseInt(el.getAttribute('tabindex') ?? '-1', 10) >= 0\n );\n}\n\n/** Walks element → parentElement, crossing each shadow boundary at its host. */\nfunction* ancestry(el: Element): Generator<Element> {\n let node: Element | null = el;\n while (node) {\n yield node;\n const root = node.getRootNode();\n node = node.parentElement ?? (root instanceof ShadowRoot ? root.host : null);\n }\n}\n\nexport function isInteractable(el: Element | null): boolean {\n if (!(el instanceof Element)) return false;\n\n // One net, because the host page owns this DOM and may have patched anything on it; an indexing pass must not throw.\n try {\n if (!isInteractiveKind(el)) return false;\n if ((el as HTMLButtonElement).disabled === true) return false;\n if (el.getAttribute('aria-disabled') === 'true') return false;\n\n for (const node of ancestry(el)) {\n if (node instanceof HTMLElement && node.inert) return false;\n }\n\n const style = window.getComputedStyle(el);\n // Only display:none and pointer-events:none disqualify — not opacity/visibility, which user interaction can reveal (expanding sections, modals).\n if (style.display === 'none' || style.pointerEvents === 'none') return false;\n\n const rect = el.getBoundingClientRect();\n // No off-screen and no occlusion check: both can be scrolled to or dismissed, so the element stays indexable.\n if (rect.width <= 0 || rect.height <= 0) return false;\n\n for (const parent of ancestry(el)) {\n if (parent !== el) {\n const clip = window.getComputedStyle(parent).overflow;\n if (clip === 'hidden' || clip === 'clip') {\n const pr = parent.getBoundingClientRect();\n if (rect.right < pr.left || rect.left > pr.right || rect.bottom < pr.top || rect.top > pr.bottom)\n return false;\n }\n if (parent === document.body) break;\n }\n }\n\n // A zero-size shadow host hides everything inside it.\n for (let root = el.getRootNode(); root instanceof ShadowRoot; root = root.host.getRootNode()) {\n const hostRect = root.host.getBoundingClientRect();\n if (hostRect.width <= 0 || hostRect.height <= 0) return false;\n }\n\n return true;\n } catch (error) {\n console.error('[isInteractable] Unexpected error:', error);\n return false;\n }\n}\n","import { isInteractable, WIDGET_SHADOW_HOST_CLASS } from '../utils/dom';\n\n// The agent addresses elements by index, so an index must not survive the element changing underneath it: the node\n// object stays the same across a re-render while its attributes are rewritten.\nconst IDENTITY_ATTRIBUTES = ['id', 'type', 'role', 'aria-label', 'name', 'href'] as const;\n\ninterface IndexedElement {\n element: HTMLElement;\n selector: string;\n identity: Array<string | null>;\n}\n\nexport interface ValidatedElementResult {\n element: HTMLElement | null;\n error?: string;\n}\n\nexport class DomService {\n private index: Map<number, IndexedElement> = new Map();\n private elementToSequence: WeakMap<Element, number> = new WeakMap();\n\n private generateAnchoredSelector(element: Element): string {\n const path: string[] = [];\n let current: Element = element;\n\n while (current !== document.body) {\n const idSelector = current.id ? `#${CSS.escape(current.id)}` : '';\n if (idSelector && document.querySelectorAll(idSelector).length === 1) {\n path.unshift(idSelector);\n return path.join(' > ');\n }\n\n const parent = current.parentElement;\n if (!parent) break;\n\n const tagName = current.tagName;\n const siblings = Array.from(parent.children).filter(child => child.tagName === tagName);\n const position = siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(current) + 1})` : '';\n\n path.unshift(tagName.toLowerCase() + position);\n current = parent;\n }\n\n return ['body', ...path].join(' > ');\n }\n\n private staleReason(entry: IndexedElement): string | null {\n if (!document.contains(entry.element)) return 'no longer exists';\n const changed = IDENTITY_ATTRIBUTES.some(\n (attribute, i) => entry.element.getAttribute(attribute) !== entry.identity[i],\n );\n return changed ? 'has changed' : null;\n }\n\n private indexInteractableElements(): void {\n this.clearIndex();\n\n const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, {\n acceptNode: (node: Node) => {\n if (node instanceof HTMLElement) {\n if (node.offsetParent === null && node.tagName !== 'BODY') {\n const style = window.getComputedStyle(node);\n const isFixedOrSticky = style.position === 'fixed' || style.position === 'sticky';\n const isDisplayNone = style.display === 'none';\n\n if (isDisplayNone) return NodeFilter.FILTER_REJECT;\n\n if (!isFixedOrSticky) {\n let parent = node.parentElement;\n let insideFixedParent = false;\n\n while (parent && parent !== document.body) {\n const parentStyle = window.getComputedStyle(parent);\n if (parentStyle.position === 'fixed' || parentStyle.position === 'sticky') {\n insideFixedParent = true;\n break;\n }\n parent = parent.parentElement;\n }\n\n if (!insideFixedParent) return NodeFilter.FILTER_REJECT;\n }\n }\n }\n return NodeFilter.FILTER_ACCEPT;\n },\n });\n\n let node: Node | null = walker.nextNode();\n let sequenceNumber = 0;\n\n while (node) {\n const element = node instanceof HTMLElement ? node : null;\n if (element) {\n const semantic = element.matches('a[href], button, input, textarea, select, [role=\"button\"]');\n const visuallyClickable =\n element.classList.contains('cursor-pointer') || element.classList.contains('clickable');\n const hasClickHandler = typeof element.onclick === 'function';\n\n if (semantic || visuallyClickable || hasClickHandler || isInteractable(element)) {\n this.index.set(sequenceNumber, {\n element,\n selector: this.generateAnchoredSelector(element),\n identity: IDENTITY_ATTRIBUTES.map(attribute => element.getAttribute(attribute)),\n });\n this.elementToSequence.set(element, sequenceNumber);\n sequenceNumber++;\n }\n }\n\n node = walker.nextNode();\n }\n\n console.log(`[DomService] Indexed ${sequenceNumber} elements`);\n }\n\n /** `data-id` is the whole contract: the agent parses the snapshot for `[data-id]` and reads nothing else off it. */\n reindexAndSnapshot(): string {\n this.indexInteractableElements();\n\n const clone = document.documentElement.cloneNode(true) as Element;\n\n // Match into the clone by selector — a synced two-tree walk breaks on modals and fixed elements.\n for (const [index, { selector }] of this.index.entries()) {\n try {\n clone.querySelector(selector)?.setAttribute('data-id', index.toString());\n } catch (e) {\n // A host tag name that is not a valid selector token makes querySelector throw; that element just goes unindexed.\n console.warn(`[DomService] Failed to tag index ${index}:`, e);\n }\n }\n\n return clone.outerHTML;\n }\n\n getSequenceForElement(element: Element): number | undefined {\n return this.elementToSequence.get(element);\n }\n\n private clearIndex(): void {\n this.index.clear();\n this.elementToSequence = new WeakMap();\n }\n\n checkElementInteractable(element: HTMLElement, index: number): string | null {\n if (!document.body.contains(element)) {\n return `ELEMENT_NOT_INTERACTABLE: Element ${index} is not in the DOM`;\n }\n\n const style = window.getComputedStyle(element);\n if (style.display === 'none') {\n return `ELEMENT_NOT_INTERACTABLE: Element ${index} has display:none`;\n }\n if (style.visibility === 'hidden') {\n return `ELEMENT_NOT_INTERACTABLE: Element ${index} has visibility:hidden`;\n }\n if (parseFloat(style.opacity) === 0) {\n return `ELEMENT_NOT_INTERACTABLE: Element ${index} has opacity:0`;\n }\n\n const rect = element.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) {\n return `ELEMENT_NOT_INTERACTABLE: Element ${index} has zero dimensions`;\n }\n\n const centerX = rect.left + rect.width / 2;\n const centerY = rect.top + rect.height / 2;\n const topElement = document.elementFromPoint(centerX, centerY);\n\n if (topElement && topElement !== element && !element.contains(topElement)) {\n const isMarketrixUI = topElement.closest(\n `#marketrix-show-highlight, #marketrix-show-popup, .${WIDGET_SHADOW_HOST_CLASS}`,\n );\n if (!isMarketrixUI) {\n const tagName = topElement.tagName.toLowerCase();\n const obscurerInfo = topElement.className ? `${tagName}.${topElement.className.split(' ')[0]}` : tagName;\n return (\n `ELEMENT_OBSCURED: Element ${index} is covered by ${obscurerInfo}. ` +\n `The obscuring element may be a modal or overlay that needs to be dismissed first.`\n );\n }\n }\n\n return null;\n }\n\n getValidatedElement(index: number): ValidatedElementResult {\n const entry = this.index.get(index);\n if (!entry) {\n return { element: null, error: `Element ${index} not found` };\n }\n\n const stale = this.staleReason(entry);\n if (stale) {\n return {\n element: null,\n error: `DOM_CHANGED: Element at index ${index} ${stale}. Call get_html to get updated indices.`,\n };\n }\n\n const interactError = this.checkElementInteractable(entry.element, index);\n if (interactError) {\n return { element: null, error: interactError };\n }\n\n return { element: entry.element };\n }\n}\n\nexport const domService = new DomService();\n","import { storageService } from './StorageService';\n\nlet activeStream: MediaStream | null = null;\n\nfunction getLiveStream(): MediaStream | null {\n if (activeStream?.active && activeStream.getVideoTracks()[0]?.readyState === 'live') {\n return activeStream;\n }\n activeStream = null;\n return null;\n}\n\nexport async function startScreenShare(): Promise<MediaStream> {\n if (storageService.getContext().config?.use_screenshare === false) {\n throw new Error('Screen sharing is disabled for this widget');\n }\n\n const liveStream = getLiveStream();\n if (liveStream) return liveStream;\n\n const stream = await navigator.mediaDevices.getDisplayMedia({\n video: true,\n audio: false,\n preferCurrentTab: true,\n } as DisplayMediaStreamOptions);\n\n if (!stream || stream.getVideoTracks().length === 0) {\n throw new Error('Screen sharing permission denied or no video track available');\n }\n\n activeStream = stream;\n\n stream.getVideoTracks()[0].addEventListener('ended', () => {\n activeStream = null;\n });\n\n return stream;\n}\n\nexport function stopScreenShare(): void {\n if (activeStream) {\n activeStream.getTracks().forEach(track => track.stop());\n activeStream = null;\n }\n}\n\nexport function isScreenSharing(): boolean {\n return getLiveStream() !== null;\n}\n","import { domService } from './DomService';\n\nexport interface ShowModeOptions {\n element: HTMLElement;\n explanation: string;\n browserToolName: string;\n isClickAction?: boolean;\n}\n\n// scroll is capture-phase so the highlight tracks a scrolling container, not just the window.\nconst REPOSITION_EVENTS = ['scroll', 'resize', 'touchmove', 'wheel'] as const;\n\nconst POPUP_WIDTH_PX = 320;\n// Painted once at create time — reposition only writes top/left, so scrolling cannot grow the style attribute.\nconst POPUP_CHROME_CSS = `position: fixed; width: ${POPUP_WIDTH_PX}px; background: white; border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 2147483646; padding: 16px;`;\n\nexport class ShowModeService {\n private currentPopup: HTMLElement | null = null;\n private currentHighlight: HTMLElement | null = null;\n private currentElement: HTMLElement | null = null;\n private currentOptions: ShowModeOptions | null = null;\n private currentPromise: Promise<void> | null = null;\n private resolvePromise: (() => void) | null = null;\n private rejectPromise: ((reason?: unknown) => void) | null = null;\n private clickHandler: ((e: MouseEvent) => void) | null = null;\n private scrollHandler: (() => void) | null = null;\n private visibilityCheckInterval: ReturnType<typeof setInterval> | null = null;\n\n async showToolAction(options: ShowModeOptions): Promise<void> {\n const { element, explanation, isClickAction = false, browserToolName } = options;\n\n if (\n this.currentOptions?.element === element &&\n this.currentOptions.explanation === explanation &&\n this.currentOptions.browserToolName === browserToolName &&\n this.currentPromise\n ) {\n console.log('[ShowModeService] Duplicate tool action detected, returning existing promise');\n return this.currentPromise;\n }\n\n this.cleanup();\n this.currentOptions = options;\n this.currentElement = element;\n\n element.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' });\n\n this.createHighlight(element);\n this.createPopup(explanation, isClickAction);\n this.setupPositionUpdates();\n this.setupVisibilityMonitoring();\n\n if (isClickAction) {\n // Highlight uses pointer-events:none so the click reaches the element; we capture it on document first.\n this.setupClickHandler();\n }\n\n this.currentPromise = new Promise<void>((resolve, reject) => {\n this.resolvePromise = resolve;\n this.rejectPromise = reject;\n });\n\n return this.currentPromise;\n }\n\n cleanup(): void {\n this.takeSettlers().reject?.(new Error('Cancelled by cleanup'));\n\n if (this.clickHandler) {\n document.removeEventListener('click', this.clickHandler, { capture: true });\n this.clickHandler = null;\n }\n if (this.scrollHandler) {\n for (const event of REPOSITION_EVENTS) {\n window.removeEventListener(event, this.scrollHandler, { capture: true });\n }\n this.scrollHandler = null;\n }\n\n if (this.visibilityCheckInterval) {\n clearInterval(this.visibilityCheckInterval);\n this.visibilityCheckInterval = null;\n }\n\n this.currentPopup?.remove();\n this.currentHighlight?.remove();\n // A node whose cleanup was interrupted outlives its handle.\n document.getElementById('marketrix-show-popup')?.remove();\n document.getElementById('marketrix-show-highlight')?.remove();\n\n this.currentPopup = null;\n this.currentHighlight = null;\n this.currentElement = null;\n this.currentOptions = null;\n this.currentPromise = null;\n }\n\n private completeAction(): void {\n this.takeSettlers().resolve?.();\n this.cleanup();\n }\n\n /** Detach both settlers before calling one — the click handler, the Continue button and the two watchdogs race. */\n private takeSettlers(): { resolve: (() => void) | null; reject: ((reason?: unknown) => void) | null } {\n const settlers = { resolve: this.resolvePromise, reject: this.rejectPromise };\n this.resolvePromise = null;\n this.rejectPromise = null;\n return settlers;\n }\n\n private createHighlight(element: HTMLElement): void {\n const rect = element.getBoundingClientRect();\n const highlight = document.createElement('div');\n highlight.id = 'marketrix-show-highlight';\n highlight.style.cssText = `\n position: fixed;\n top: ${rect.top}px;\n left: ${rect.left}px;\n width: ${rect.width}px;\n height: ${rect.height}px;\n border: 3px solid #3b82f6;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2), 0 0 20px rgba(59, 130, 246, 0.4);\n z-index: 2147483645;\n pointer-events: none;\n transition: none;\n `;\n document.body.appendChild(highlight);\n this.currentHighlight = highlight;\n }\n\n private createPopup(explanation: string, isClickAction: boolean): void {\n const popup = document.createElement('div');\n popup.id = 'marketrix-show-popup';\n\n const content = isClickAction\n ? `<div style=\"font-weight: 500; color: #1f2937; font-size: 12px;\">${this.escapeHtml(explanation)}</div>`\n : `<div style=\"margin-bottom: 12px; font-weight: 500; color: #1f2937; font-size: 12px;\">${this.escapeHtml(explanation)}</div>\n <div style=\"display: flex; gap: 8px; justify-content: flex-end;\">\n <button id=\"marketrix-show-continue\" style=\"\n background: #3b82f6; color: white; border: none; border-radius: 6px;\n padding: 8px 16px; font-size: 12px; font-weight: 500; cursor: pointer;\n \">Continue</button>\n </div>`;\n\n popup.innerHTML = content;\n popup.style.cssText = POPUP_CHROME_CSS;\n document.body.appendChild(popup);\n this.currentPopup = popup;\n\n if (!isClickAction) {\n this.setupContinueButton(popup);\n }\n\n this.updatePopupPosition();\n }\n\n private setupPositionUpdates(): void {\n this.scrollHandler = () => {\n if (!this.currentElement || !this.currentHighlight) return;\n const rect = this.currentElement.getBoundingClientRect();\n Object.assign(this.currentHighlight.style, {\n top: `${rect.top}px`,\n left: `${rect.left}px`,\n width: `${rect.width}px`,\n height: `${rect.height}px`,\n });\n this.updatePopupPosition();\n };\n\n for (const event of REPOSITION_EVENTS) {\n window.addEventListener(event, this.scrollHandler, { capture: true, passive: true });\n }\n }\n\n private updatePopupPosition(): void {\n if (!this.currentPopup || !this.currentElement) return;\n\n const rect = this.currentElement.getBoundingClientRect();\n const popupHeight = 120; // Approx height\n const spacing = 20;\n const padding = 10;\n\n const elementCenterX = rect.left + rect.width / 2;\n const elementCenterY = rect.top + rect.height / 2;\n\n // Right, left, above, below — first that fits the viewport wins.\n const positions = [\n { left: rect.right + spacing, top: elementCenterY - popupHeight / 2 },\n { left: rect.left - POPUP_WIDTH_PX - spacing, top: elementCenterY - popupHeight / 2 },\n { left: elementCenterX - POPUP_WIDTH_PX / 2, top: rect.top - popupHeight - spacing },\n { left: elementCenterX - POPUP_WIDTH_PX / 2, top: rect.bottom + spacing },\n ];\n\n let bestPos = positions[0];\n for (const pos of positions) {\n if (\n pos.left >= padding &&\n pos.left + POPUP_WIDTH_PX <= window.innerWidth - padding &&\n pos.top >= padding &&\n pos.top + popupHeight <= window.innerHeight - padding\n ) {\n bestPos = pos;\n break;\n }\n }\n\n this.currentPopup.style.left = `${Math.max(padding, Math.min(bestPos.left, window.innerWidth - POPUP_WIDTH_PX - padding))}px`;\n this.currentPopup.style.top = `${Math.max(padding, Math.min(bestPos.top, window.innerHeight - popupHeight - padding))}px`;\n }\n\n private setupClickHandler(): void {\n this.clickHandler = (e: MouseEvent) => {\n if (!this.currentElement || !this.resolvePromise) return;\n\n // composedPath sees through Shadow DOM retargeting and bubbling.\n const path = e.composedPath();\n const isClickOnElement = path.includes(this.currentElement);\n\n if (isClickOnElement) {\n // Intercept so navigation/action doesn't fire before we process the tool result.\n e.preventDefault();\n e.stopPropagation();\n\n this.completeAction();\n }\n };\n\n document.addEventListener('click', this.clickHandler, { capture: true });\n }\n\n private setupContinueButton(popup: HTMLElement): void {\n window.requestAnimationFrame(() => {\n popup.querySelector('#marketrix-show-continue')?.addEventListener('click', e => {\n e.stopPropagation();\n this.completeAction();\n });\n });\n }\n\n /** checkElementInteractable's first test is `document.body.contains`, so this one watchdog also covers removal. */\n private setupVisibilityMonitoring(): void {\n this.visibilityCheckInterval = setInterval(() => {\n const element = this.currentElement;\n if (!element) return;\n const rect = element.getBoundingClientRect();\n if (rect.bottom < 0 || rect.top > window.innerHeight || rect.right < 0 || rect.left > window.innerWidth) {\n this.failWithElementGone('The highlighted element scrolled out of view');\n return;\n }\n const index = domService.getSequenceForElement(element) ?? -1;\n const error = domService.checkElementInteractable(element, index);\n if (error) this.failWithElementGone(error);\n }, 200);\n }\n\n private failWithElementGone(reason: string): void {\n this.takeSettlers().reject?.(new Error(`ELEMENT_GONE: ${reason}`));\n this.cleanup();\n }\n\n private escapeHtml(text: string): string {\n const div = document.createElement('div');\n div.textContent = text;\n return div.innerHTML;\n }\n}\n\nexport const showModeService = new ShowModeService();\n","import { WAIT_FOR_USER_TOOLS } from '../utils/chat';\nimport { domService } from './DomService';\nimport { startScreenShare } from './ScreenShareService';\nimport { showModeService } from './ShowModeService';\n\nexport interface TextData {\n text: string;\n}\n\nexport interface ExtractData {\n title: string;\n url: string;\n text: string;\n links: Array<{ text: string; href: string | null }>;\n}\n\nexport interface DropdownOptionsData {\n options: Array<{ value: string; text: string }>;\n}\n\nexport interface ToolExecutionResult<T = TextData> {\n success: boolean;\n data: T;\n error?: string;\n afterResponseAttempt?: () => void;\n}\n\n/** One shape for every widget tool's arguments: the wire carries a bare JSON object, so nothing is\n * guaranteed present and each handler guards the fields it needs. */\ninterface ToolArgs {\n clear?: boolean;\n direction?: 'up' | 'down' | 'left' | 'right';\n engine?: 'duckduckgo' | 'google' | 'bing';\n extract_links?: boolean;\n index?: number;\n keys?: string;\n message?: string;\n new_tab?: boolean;\n option?: string;\n query?: string;\n seconds?: number;\n text?: string;\n url?: string;\n}\n\nconst ok = (text: string): ToolExecutionResult => ({ success: true, data: { text } });\nconst okData = <T>(data: T): ToolExecutionResult<T> => ({ success: true, data });\nconst fail = (error: string): ToolExecutionResult => ({ success: false, data: { text: '' }, error });\nconst failOptions = (error: string): ToolExecutionResult<DropdownOptionsData> => ({\n success: false,\n data: { options: [] },\n error,\n});\n\nconst SCREENSHOT_FRAME_TIMEOUT_MS = 5000;\n\nfunction firstFrame(video: HTMLVideoElement, timeoutMs: number): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error('Screen capture produced no frame')), timeoutMs);\n video.onloadeddata = () => {\n clearTimeout(timer);\n resolve();\n };\n video.onerror = () => {\n clearTimeout(timer);\n reject(new Error('Screen capture failed'));\n };\n });\n}\n\nconst TAB_ORDER_SELECTOR =\n 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])';\n\nexport class BrowserToolService {\n async executeTool(\n browserToolName: string,\n args: Record<string, unknown>,\n mode: string = 'do',\n explanation: string = '',\n ): Promise<ToolExecutionResult<unknown>> {\n const toolArgs = args as ToolArgs;\n try {\n console.log(`[BrowserToolService] Executing ${browserToolName} (mode: ${mode})`);\n\n if (mode === 'show' && WAIT_FOR_USER_TOOLS.has(browserToolName)) {\n const index = toolArgs.index;\n if (index !== undefined) {\n const { element, error } = domService.getValidatedElement(index);\n if (!element) return fail(error || `Element ${index} not found`);\n\n await showModeService.showToolAction({\n element,\n explanation: explanation || `Execute ${browserToolName}`,\n browserToolName,\n isClickAction: browserToolName === 'click_element',\n });\n }\n }\n\n switch (browserToolName) {\n case 'navigate':\n return this.navigate(toolArgs);\n case 'search':\n return this.search(toolArgs);\n case 'click_element':\n return await this.clickElement(toolArgs);\n case 'type_text':\n return this.typeText(toolArgs);\n case 'scroll':\n return this.scroll(toolArgs);\n case 'scroll_to_text':\n return this.scrollToText(toolArgs);\n case 'extract':\n return this.extract(toolArgs);\n case 'go_back':\n return this.goBack();\n case 'wait':\n return await this.wait(toolArgs);\n case 'select_dropdown_option':\n return this.selectDropdownOption(toolArgs);\n case 'get_dropdown_options':\n return this.getDropdownOptions(toolArgs);\n case 'send_keys':\n return this.sendKeys(toolArgs);\n case 'close_tab':\n return this.closeTab();\n case 'done':\n return this.done(toolArgs);\n case 'get_html':\n return this.getHtml();\n case 'get_screenshot':\n return await this.getScreenshot();\n default:\n return fail(`Unknown tool: ${browserToolName}`);\n }\n } catch (error) {\n return fail(error instanceof Error ? error.message : String(error));\n }\n }\n\n private navigate(args: ToolArgs): ToolExecutionResult {\n if (!args.url) return fail('URL is required');\n\n if (args.new_tab) {\n return window.open(args.url, '_blank')\n ? ok(`Opened ${args.url} in new tab`)\n : fail('The browser blocked opening a new tab');\n }\n const url = args.url;\n return {\n ...ok(`Navigating to ${url}`),\n afterResponseAttempt: () => {\n window.location.href = url;\n },\n };\n }\n\n private search(args: ToolArgs): ToolExecutionResult {\n if (!args.query) return fail('Query is required');\n\n const engine = args.engine || 'duckduckgo';\n const encoded = encodeURIComponent(args.query);\n let url = `https://duckduckgo.com/?q=${encoded}`;\n\n if (engine === 'google') url = `https://www.google.com/search?q=${encoded}`;\n if (engine === 'bing') url = `https://www.bing.com/search?q=${encoded}`;\n\n return {\n ...ok(`Searching for \"${args.query}\" on ${engine}`),\n afterResponseAttempt: () => {\n window.location.href = url;\n },\n };\n }\n\n private async clickElement(args: ToolArgs): Promise<ToolExecutionResult> {\n if (args.index === undefined) return fail('Index required');\n\n const { element, error } = domService.getValidatedElement(args.index);\n if (!element) return fail(error || `Element ${args.index} not found`);\n\n element.scrollIntoView({ behavior: 'smooth', block: 'center' });\n await new Promise(resolve => setTimeout(resolve, 100));\n\n return { ...ok(`Clicked element ${args.index}`), afterResponseAttempt: () => element.click() };\n }\n\n private typeText(args: ToolArgs): ToolExecutionResult {\n if (args.index === undefined || args.text === undefined) return fail('Index and text required');\n\n const clear = args.clear !== false;\n\n const { element, error } = domService.getValidatedElement(args.index);\n if (!element) return fail(error || `Element ${args.index} not found`);\n\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n element.focus();\n this.setNativeValue(element, clear ? args.text : element.value + args.text);\n\n element.dispatchEvent(\n new InputEvent('input', { bubbles: true, cancelable: true, inputType: 'insertText', data: args.text }),\n );\n element.dispatchEvent(new Event('change', { bubbles: true }));\n // Some frameworks need blur to trigger validation\n element.dispatchEvent(new Event('blur', { bubbles: true }));\n } else if (element.isContentEditable) {\n element.focus();\n const selection = window.getSelection();\n if (clear) selection?.selectAllChildren(element);\n else selection?.collapse(element, element.childNodes.length);\n\n if (!document.execCommand('insertText', false, args.text)) {\n return fail(`Could not insert text into element ${args.index}`);\n }\n } else if ('value' in element) {\n try {\n (element as HTMLInputElement).value = args.text;\n element.dispatchEvent(new Event('input', { bubbles: true }));\n element.dispatchEvent(new Event('change', { bubbles: true }));\n } catch (e) {\n return fail(`Failed to set value on element: ${e instanceof Error ? e.message : String(e)}`);\n }\n } else {\n try {\n element.textContent = args.text;\n element.dispatchEvent(new Event('input', { bubbles: true }));\n } catch (e) {\n return fail(`Failed to set textContent: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n return ok(`Typed text into element ${args.index}`);\n }\n\n private scroll(args: ToolArgs): ToolExecutionResult {\n const amount = window.innerHeight * 0.8;\n\n switch (args.direction) {\n case 'down':\n window.scrollBy({ top: amount, behavior: 'smooth' });\n break;\n case 'up':\n window.scrollBy({ top: -amount, behavior: 'smooth' });\n break;\n case 'left':\n window.scrollBy({ left: -amount, behavior: 'smooth' });\n break;\n case 'right':\n window.scrollBy({ left: amount, behavior: 'smooth' });\n break;\n default:\n return fail('Invalid direction');\n }\n return ok(`Scrolled ${args.direction}`);\n }\n\n private scrollToText(args: ToolArgs): ToolExecutionResult {\n if (!args.text) return fail('Text required');\n\n const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);\n let node: Node | null;\n while ((node = walker.nextNode())) {\n if (node.textContent?.includes(args.text) && node.parentElement) {\n node.parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });\n return ok(`Scrolled to \"${args.text}\"`);\n }\n }\n return fail(`Text \"${args.text}\" not found`);\n }\n\n private extract(args: ToolArgs): ToolExecutionResult<ExtractData> {\n const includeLinks = args.extract_links !== false;\n const extractResult: ExtractData = {\n title: document.title,\n url: window.location.href,\n text: document.body.innerText.slice(0, 10000),\n links: includeLinks\n ? Array.from(document.querySelectorAll('a[href]'))\n .slice(0, 100)\n .map(a => ({\n text: a.textContent?.trim() || '',\n href: a.getAttribute('href'),\n }))\n : [],\n };\n return okData(extractResult);\n }\n\n private goBack(): ToolExecutionResult {\n if (window.history.length <= 1) return fail('No history');\n return { ...ok('Navigated back'), afterResponseAttempt: () => window.history.back() };\n }\n\n private async wait({ seconds }: ToolArgs): Promise<ToolExecutionResult> {\n if (seconds === undefined) return fail('Seconds required');\n await new Promise(resolve => setTimeout(resolve, seconds * 1000));\n return ok(`Waited ${seconds}s`);\n }\n\n private selectDropdownOption(args: ToolArgs): ToolExecutionResult {\n if (args.index === undefined || !args.option) return fail('Index/Option required');\n\n const { element, error } = domService.getValidatedElement(args.index);\n if (!element) return fail(error || `Select ${args.index} not found`);\n\n if (!(element instanceof HTMLSelectElement)) {\n return fail(`Element ${args.index} is not a select element`);\n }\n\n const opt = Array.from(element.options).find(o => o.value === args.option || o.text === args.option);\n if (!opt) return fail(`Option ${args.option} not found`);\n\n element.value = opt.value;\n element.dispatchEvent(new Event('change', { bubbles: true }));\n\n return ok(`Selected ${args.option}`);\n }\n\n private getDropdownOptions(args: ToolArgs): ToolExecutionResult<DropdownOptionsData> {\n const index = args.index;\n if (index === undefined) return failOptions('Index required');\n\n const { element, error } = domService.getValidatedElement(index);\n if (!element) return failOptions(error || `Select ${index} not found`);\n\n if (!(element instanceof HTMLSelectElement)) {\n return failOptions(`Element ${index} is not a select element`);\n }\n\n const options = Array.from(element.options).map(o => ({ value: o.value, text: o.text }));\n return okData({ options });\n }\n\n private sendKeys(args: ToolArgs): ToolExecutionResult {\n if (args.index === undefined || !args.keys) return fail('Index/Keys required');\n\n const { element, error } = domService.getValidatedElement(args.index);\n if (!element) return fail(error || `Element ${args.index} not found`);\n\n element.focus();\n element.dispatchEvent(new KeyboardEvent('keydown', { key: args.keys, bubbles: true, cancelable: true }));\n element.dispatchEvent(new KeyboardEvent('keyup', { key: args.keys, bubbles: true, cancelable: true }));\n\n const actionResult = this.simulateKeyAction(element, args.keys);\n\n return ok(actionResult || `Sent keys ${args.keys}`);\n }\n\n /** Programmatic KeyboardEvents aren't \"trusted\", so manually reproduce each key's expected behavior. */\n private simulateKeyAction(element: HTMLElement, key: string): string | null {\n switch (key) {\n case 'Tab':\n case 'Shift+Tab': {\n const step = key === 'Tab' ? 1 : -1;\n const focusables = Array.from(document.querySelectorAll<HTMLElement>(TAB_ORDER_SELECTOR)).filter(\n el => el.offsetParent !== null,\n );\n const currentIndex = focusables.indexOf(element);\n const next = currentIndex === -1 ? undefined : focusables[currentIndex + step];\n if (!next) return `${key}: no ${step > 0 ? 'next' : 'previous'} focusable element`;\n next.focus();\n return `${key}: moved focus to ${next.tagName.toLowerCase()}${next.id ? `#${next.id}` : ''}`;\n }\n\n case 'Enter': {\n if (element instanceof HTMLButtonElement || element.getAttribute('role') === 'button') {\n element.click();\n return 'Enter: clicked button';\n }\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n const form = element.closest('form');\n if (form) {\n const submitBtn = form.querySelector<HTMLButtonElement>('button[type=\"submit\"], input[type=\"submit\"]');\n if (submitBtn) {\n submitBtn.click();\n return 'Enter: clicked form submit button';\n } else {\n form.requestSubmit();\n return 'Enter: submitted form';\n }\n }\n }\n if (element instanceof HTMLAnchorElement) {\n element.click();\n return 'Enter: clicked link';\n }\n return 'Enter: dispatched event';\n }\n\n case 'Escape': {\n element.blur();\n // Dispatch to document too, for modal close handlers.\n document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));\n return 'Escape: blurred element and dispatched to document';\n }\n\n case ' ':\n case 'Space': {\n if (element instanceof HTMLInputElement && (element.type === 'checkbox' || element.type === 'radio')) {\n element.click();\n return `Space: toggled ${element.type}`;\n }\n if (element instanceof HTMLButtonElement || element.getAttribute('role') === 'button') {\n element.click();\n return 'Space: clicked button';\n }\n return 'Space: dispatched event';\n }\n\n case 'ArrowDown': {\n if (element instanceof HTMLSelectElement) {\n const currentIdx = element.selectedIndex;\n if (currentIdx < element.options.length - 1) {\n element.selectedIndex = currentIdx + 1;\n element.dispatchEvent(new Event('change', { bubbles: true }));\n return `ArrowDown: selected \"${element.options[element.selectedIndex].text}\"`;\n }\n return 'ArrowDown: already at last option';\n }\n return 'ArrowDown: dispatched event';\n }\n\n case 'ArrowUp': {\n if (element instanceof HTMLSelectElement) {\n const currentIdx = element.selectedIndex;\n if (currentIdx > 0) {\n element.selectedIndex = currentIdx - 1;\n element.dispatchEvent(new Event('change', { bubbles: true }));\n return `ArrowUp: selected \"${element.options[element.selectedIndex].text}\"`;\n }\n return 'ArrowUp: already at first option';\n }\n return 'ArrowUp: dispatched event';\n }\n\n case 'Home': {\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n element.setSelectionRange(0, 0);\n return 'Home: moved cursor to start';\n }\n return 'Home: dispatched event';\n }\n\n case 'End': {\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n const len = element.value.length;\n element.setSelectionRange(len, len);\n return 'End: moved cursor to end';\n }\n return 'End: dispatched event';\n }\n\n case 'Backspace': {\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n const value = element.value;\n\n if (!value || value.length === 0) {\n return 'Backspace: input is empty, nothing to delete';\n }\n\n const start: number = element.selectionStart ?? value.length;\n const end: number = element.selectionEnd ?? value.length;\n\n let newValue: string;\n let newCursorPos: number;\n\n if (start === end && start > 0) {\n newValue = value.slice(0, start - 1) + value.slice(end);\n newCursorPos = start - 1;\n } else if (start !== end) {\n newValue = value.slice(0, start) + value.slice(end);\n newCursorPos = start;\n } else {\n return 'Backspace: cursor at start, nothing to delete';\n }\n\n this.setValueAndCaret(element, newValue, newCursorPos);\n\n return `Backspace: deleted character, value is now \"${newValue}\"`;\n }\n return 'Backspace: dispatched event';\n }\n\n case 'Delete': {\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n const start = element.selectionStart || 0;\n const end = element.selectionEnd || 0;\n const value = element.value;\n\n let newValue: string;\n\n if (start === end && start < value.length) {\n newValue = value.slice(0, start) + value.slice(end + 1);\n } else if (start !== end) {\n newValue = value.slice(0, start) + value.slice(end);\n } else {\n return 'Delete: cursor at end, nothing to delete';\n }\n\n this.setValueAndCaret(element, newValue, start);\n\n return `Delete: deleted character, value is now \"${newValue}\"`;\n }\n return 'Delete: dispatched event';\n }\n\n default:\n // The caller already dispatched the generic key events.\n return null;\n }\n }\n\n /** Native value setter so React/Vue controlled inputs pick up the change. */\n private setNativeValue(el: HTMLInputElement | HTMLTextAreaElement, value: string): void {\n const setter = Object.getOwnPropertyDescriptor(\n el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype,\n 'value',\n )?.set;\n if (setter) setter.call(el, value);\n else el.value = value;\n }\n\n private setValueAndCaret(el: HTMLInputElement | HTMLTextAreaElement, value: string, caret: number): void {\n this.setNativeValue(el, value);\n el.dispatchEvent(new Event('input', { bubbles: true }));\n el.dispatchEvent(new Event('change', { bubbles: true }));\n el.setSelectionRange(caret, caret);\n }\n\n private closeTab(): ToolExecutionResult {\n window.close();\n return window.closed ? ok('Tab closed') : fail('The browser refused to close a tab this script did not open');\n }\n\n private done(args: ToolArgs): ToolExecutionResult {\n return ok(args.message || 'Task ended');\n }\n\n private getHtml(): ToolExecutionResult {\n try {\n const html = domService.reindexAndSnapshot();\n return ok(html);\n } catch (error) {\n return fail(String(error));\n }\n }\n\n private async getScreenshot(): Promise<ToolExecutionResult> {\n const video = document.createElement('video');\n try {\n video.srcObject = await startScreenShare();\n video.autoplay = true;\n video.style.display = 'none';\n document.body.appendChild(video);\n\n await firstFrame(video, SCREENSHOT_FRAME_TIMEOUT_MS);\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d');\n ctx?.drawImage(video, 0, 0);\n\n // Keep the stream alive — the agent usually requests a screenshot then keeps going; startScreenShare handles reuse.\n return ok(canvas.toDataURL('image/jpeg', 0.75));\n } catch (error) {\n return fail(String(error));\n } finally {\n video.remove();\n }\n }\n}\n\nexport const browserToolService = new BrowserToolService();\n","import type { WidgetEvent } from '../sdk';\nimport type { ChatMessage, InstructionType, MessagePart } from '../types';\nimport {\n addProgressLine,\n findMessageForProgress,\n getFriendlyToolName,\n markProgressLineComplete,\n markProgressLineFailed,\n WAIT_FOR_USER_TOOLS,\n} from '../utils/chat';\n\nexport interface TaskState {\n isTaskRunning: boolean;\n}\n\nexport interface SseState {\n messages: ChatMessage[];\n task: TaskState;\n}\n\nexport interface SseEffect {\n type: 'executeTool';\n toolCallId: string;\n tool: string;\n args: Record<string, unknown>;\n mode: InstructionType;\n explanation: string;\n}\n\nexport interface ReduceResult {\n state: SseState;\n effects: SseEffect[];\n}\n\nconst noChange = (state: SseState): ReduceResult => ({ state, effects: [] });\n\ntype ProgressStatus = 'in_progress' | 'completed' | 'failed';\n\nfunction applyProgress(\n messages: ChatMessage[],\n isTaskRunning: boolean,\n currentMode: InstructionType,\n browserToolName: string,\n explanation: string,\n status: ProgressStatus,\n error?: string,\n): ChatMessage[] {\n const found = findMessageForProgress({ messages, isTaskRunning, currentMode });\n if (!found) return messages;\n\n let updatedMsg = found.message;\n // `done` carries no progress line of its own — it only ends the run.\n if (status === 'failed') {\n updatedMsg = markProgressLineFailed(updatedMsg, browserToolName, error || '');\n } else if (browserToolName !== 'done') {\n updatedMsg =\n status === 'in_progress'\n ? addProgressLine(updatedMsg, browserToolName, explanation || getFriendlyToolName(browserToolName))\n : markProgressLineComplete(updatedMsg, browserToolName);\n }\n\n if (isTaskRunning && (currentMode === 'show' || currentMode === 'do')) {\n // In show mode a DOM-mutating tool parks the spinner on \"your turn\" until the user acts.\n const waiting = status === 'in_progress' && currentMode === 'show' && WAIT_FOR_USER_TOOLS.has(browserToolName);\n updatedMsg = { ...updatedMsg, placeholderState: waiting ? 'waiting-for-user' : 'thinking' };\n }\n\n const next = [...messages];\n next[found.index] = updatedMsg;\n return next;\n}\n\nexport function reduceToolProgress(\n state: SseState,\n browserToolName: string,\n explanation: string,\n status: ProgressStatus,\n currentMode: InstructionType,\n error?: string,\n): SseState {\n return {\n ...state,\n messages: applyProgress(\n state.messages,\n state.task.isTaskRunning,\n currentMode,\n browserToolName,\n explanation,\n status,\n error,\n ),\n };\n}\n\n// The composer is disabled while any message is still a placeholder, so a bubble nothing will write to\n// again has to stop being one — `has_question` most of all, where the agent asks for an answer the\n// visitor could not then type.\nconst settled = (msg: ChatMessage): ChatMessage => ({ ...msg, isPlaceholder: false });\n\n/** The four terminal/pause transitions all stamp the progress message and clear the task; only the stamp differs. */\nfunction stampProgressMessage(\n state: SseState,\n currentMode: InstructionType,\n stamp: (msg: ChatMessage) => ChatMessage,\n): SseState {\n const found = findMessageForProgress({\n messages: state.messages,\n isTaskRunning: state.task.isTaskRunning,\n currentMode,\n });\n const messages = [...state.messages];\n if (found) messages[found.index] = settled(stamp(found.message));\n return { messages, task: { isTaskRunning: false } };\n}\n\nexport function reduceToolDone(state: SseState, currentMode: InstructionType): SseState {\n return stampProgressMessage(state, currentMode, msg => ({ ...msg, taskStatus: 'done' }));\n}\n\nexport function reduceStop(state: SseState, currentMode: InstructionType): SseState {\n return stampProgressMessage(state, currentMode, msg => ({ ...msg, taskStatus: 'stopped' }));\n}\n\nconst TASK_STATUS = { completed: 'done', failed: 'failed', stopped: 'stopped' } as const;\n\n// The terminal set, read off the map that stamps it — `has_question` is a pause and `running` stamps\n// nothing, so a fourth terminal status added to TASK_STATUS reaches every caller at once.\nexport const isTerminalTaskStatus = (status: string): status is keyof typeof TASK_STATUS => status in TASK_STATUS;\n\nfunction reduceText(state: SseState, requestId: string, text: string, streaming: boolean): SseState {\n const messages = state.messages.map(msg => {\n if (msg.id !== requestId) return msg;\n const parts = [...msg.parts];\n const last = parts[parts.length - 1];\n // chat/delta fragments accumulate into the open streaming part; the final chat/response replaces it.\n const isOpenStream = last?.type === 'text' && last.streaming === true;\n const content = streaming && isOpenStream ? last.content + text : text;\n const part: MessagePart = { type: 'text', content, ...(streaming && { streaming: true }) };\n if (isOpenStream) parts[parts.length - 1] = part;\n else parts.push(part);\n return { ...msg, content, isPlaceholder: false, placeholderState: undefined, parts };\n });\n return { ...state, messages };\n}\n\nconst appendText = (msg: ChatMessage, text: string): ChatMessage => ({\n ...msg,\n content: text,\n parts: [...msg.parts, { type: 'text' as const, content: text }],\n});\n\nconst errorBubble = (msg: ChatMessage, text: string): ChatMessage => ({\n ...settled(appendText(msg, text)),\n placeholderState: undefined,\n});\n\n/** Settles a pending message into a plain error bubble — the one shape for both a failed POST and a chat/error. */\nexport function reduceError(state: SseState, messageId: string, text: string): SseState {\n const messages = state.messages.map(msg => (msg.id === messageId ? errorBubble(msg, text) : msg));\n return { ...state, messages };\n}\n\n/** The transport gave up, so no id-bearing event is coming for whatever is still pending. */\nexport function reduceTransportFailure(state: SseState, text: string): SseState {\n const messages = state.messages.map(msg => (msg.isPlaceholder ? errorBubble(msg, text) : msg));\n return { messages, task: { isTaskRunning: false } };\n}\n\n/**\n * The stream can stay healthy (no `StreamGaveUpError`) while a single dispatch's reply never arrives —\n * a dropped correlation, a silent backend failure before it ever acknowledges the request, or a reload\n * into the gap where the api has no tab to push to. `reduceTransportFailure` cannot see that, since\n * nothing told the transport it failed, so without this the bubble sits on \"thinking\" and the composer\n * stays disabled forever.\n *\n * Only fires on a message that received ZERO signs of life — still `thinking` with no progress line\n * and no streamed text. A `do`/`show` task that is genuinely still running has already advanced past\n * this (a `tool/call` flips `placeholderState` or adds a line, a `chat/delta` adds a part) and must\n * never be cut off just because it is taking a while; a task that never even started is what this\n * catches.\n */\nexport function reduceStaleReply(state: SseState, messageId: string, text: string): SseState {\n const pending = state.messages.find(msg => msg.id === messageId);\n const untouched = pending?.isPlaceholder && pending.placeholderState === 'thinking' && pending.parts.length === 0;\n return untouched ? reduceError(state, messageId, text) : state;\n}\n\nexport function reduceSse(state: SseState, event: WidgetEvent, currentMode: InstructionType): ReduceResult {\n switch (event.type) {\n case 'tool/call': {\n // A tool/call can arrive before `task/status running`, so activate here too.\n const task = state.task.isTaskRunning ? state.task : { isTaskRunning: true };\n const explanation = event.explanation || '';\n const messages = applyProgress(\n state.messages,\n task.isTaskRunning,\n currentMode,\n event.browser_tool,\n explanation,\n 'in_progress',\n );\n return {\n state: { messages, task },\n effects: [\n {\n type: 'executeTool',\n toolCallId: event.tool_call_id,\n tool: event.browser_tool,\n args: event.args,\n mode: event.mode || currentMode,\n explanation,\n },\n ],\n };\n }\n\n case 'task/status': {\n // `running` activates nothing: the first tool/call is what flips isTaskRunning, and a tell-mode reply never has a task.\n if (event.status === 'running') return noChange(state);\n const status = event.status;\n const withMessage = (msg: ChatMessage) => (event.message ? appendText(msg, event.message) : msg);\n // has_question is a pause, not a terminal status.\n const stamp =\n status === 'has_question'\n ? (msg: ChatMessage) => ({ ...withMessage(msg), placeholderState: 'waiting-for-user' as const })\n : (msg: ChatMessage) => ({ ...withMessage(msg), taskStatus: TASK_STATUS[status] });\n return { state: stampProgressMessage(state, currentMode, stamp), effects: [] };\n }\n\n case 'chat/delta':\n return { state: reduceText(state, event.request_id, event.text, true), effects: [] };\n\n case 'chat/response':\n return { state: reduceText(state, event.request_id, event.text, false), effects: [] };\n\n case 'chat/error':\n return { state: reduceError(state, event.request_id, `Error: ${event.error}`), effects: [] };\n\n // registered / heartbeat carry no state.\n default:\n return noChange(state);\n }\n}\n","import React, { createContext, useContext, useMemo, useState } from 'react';\n\nimport type { InstructionType, WidgetView } from '../types';\n\nexport interface UIState {\n isOpen: boolean;\n activeView: WidgetView;\n currentMode: InstructionType;\n error?: string;\n}\n\nexport interface UIStateActions {\n setActiveView: (view: WidgetView) => void;\n toggleWidget: () => void;\n closeWidget: () => void;\n setMode: (mode: InstructionType) => void;\n setError: (error: string | undefined) => void;\n applyState: (payload: Partial<UIState>) => void;\n}\n\ninterface UIStateContextType {\n uiState: UIState;\n uiActions: UIStateActions;\n}\n\nconst UIStateContext = createContext<UIStateContextType | undefined>(undefined);\n\nexport const UIStateProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n const [uiState, setUIState] = useState<UIState>({\n isOpen: false,\n activeView: 'home',\n currentMode: 'tell',\n });\n\n const uiActions = useMemo<UIStateActions>(\n () => ({\n setActiveView: (view: WidgetView) => setUIState(prev => ({ ...prev, activeView: view })),\n\n toggleWidget: () => setUIState(prev => ({ ...prev, isOpen: !prev.isOpen })),\n\n closeWidget: () => setUIState(prev => ({ ...prev, isOpen: false })),\n\n setMode: (mode: InstructionType) => setUIState(prev => ({ ...prev, currentMode: mode })),\n\n setError: (error: string | undefined) => setUIState(prev => ({ ...prev, error })),\n\n applyState: (payload: Partial<UIState>) => setUIState(prev => ({ ...prev, ...payload })),\n }),\n [],\n );\n\n return <UIStateContext.Provider value={{ uiState, uiActions }}>{children}</UIStateContext.Provider>;\n};\n\nexport const useUIStateContext = (): UIStateContextType => {\n const ctx = useContext(UIStateContext);\n if (!ctx) throw new Error('useUIStateContext must be used within UIStateProvider');\n return ctx;\n};\n","import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';\n\nimport type { WidgetEvent } from '../sdk';\nimport { messageDispatch as dispatchMessage } from '../services/ApiService';\nimport { browserToolService } from '../services/BrowserToolService';\nimport { createAgentMessage, createUserMessage } from '../services/ChatService';\nimport { storageService } from '../services/StorageService';\nimport { StreamClient, StreamGaveUpError } from '../services/StreamClient';\nimport type { ChatMessage, InstructionType } from '../types';\nimport { BROWSER_TOOLS } from '../utils/chat';\nimport {\n isTerminalTaskStatus,\n reduceError,\n reduceSse,\n reduceStaleReply,\n reduceStop,\n reduceToolDone,\n reduceToolProgress,\n reduceTransportFailure,\n type SseEffect,\n type SseState,\n type TaskState,\n} from './sseReducer';\nimport { useUIStateContext } from './UIStateContext';\n\n// messages + task share one committed state so they can't tear across an await.\n\nexport interface ChatActions {\n addMessage: (message: ChatMessage) => void;\n updateMessage: (messageId: string, updates: Partial<ChatMessage>) => void;\n removeMessage: (messageId: string) => void;\n setMessages: (messages: ChatMessage[]) => void;\n clearMessages: () => void;\n messageDispatch: (content: string, mode?: InstructionType, skipUserMessage?: boolean) => Promise<void>;\n}\n\nexport interface TaskActions {\n setTaskState: (isTaskRunning: boolean) => void;\n stopTask: () => Promise<void>;\n}\n\ninterface ChatContextType {\n messages: ChatMessage[];\n chatActions: ChatActions;\n taskState: TaskState;\n taskActions: TaskActions;\n}\n\nconst ChatContext = createContext<ChatContextType | undefined>(undefined);\n\nconst MAX_PROCESSED_TOOL_CALL_IDS = 1000;\n\nconst STALE_REPLY_TIMEOUT_MS = 120_000;\nconst STALE_REPLY_TEXT = 'This is taking longer than expected. Please try again.';\n\ninterface ChatProviderProps {\n children: React.ReactNode;\n previewMode?: boolean;\n}\n\nexport const ChatProvider: React.FC<ChatProviderProps> = ({ children, previewMode = false }) => {\n const { uiState, uiActions } = useUIStateContext();\n const [state, setState] = useState<SseState>(() => ({ messages: [], task: { isTaskRunning: false } }));\n\n // commit() is the ONLY writer — re-syncing from render could regress the ref between a commit and its paint.\n const stateRef = useRef<SseState>(state);\n\n const currentModeRef = useRef(uiState.currentMode);\n currentModeRef.current = uiState.currentMode;\n\n const processedToolCallIds = useRef(new Set<string>());\n\n // Transition runs synchronously here, not in a setState updater: React defers updaters (background tab, mid-burst) and captured effects are lost — tool calls that never execute.\n const commit = useCallback((transition: (s: SseState) => SseState) => {\n const prev = stateRef.current;\n const next = transition(prev);\n if (next === prev || (next.messages === prev.messages && next.task === prev.task)) return;\n stateRef.current = next;\n setState(next);\n }, []);\n\n const addMessage = useCallback(\n (message: ChatMessage) => {\n commit(s => ({ ...s, messages: [...s.messages, message] }));\n },\n [commit],\n );\n\n const updateMessage = useCallback(\n (messageId: string, updates: Partial<ChatMessage>) => {\n commit(s => ({\n ...s,\n messages: s.messages.map(msg => (msg.id === messageId ? { ...msg, ...updates } : msg)),\n }));\n },\n [commit],\n );\n\n const removeMessage = useCallback(\n (messageId: string) => {\n commit(s => ({ ...s, messages: s.messages.filter(msg => msg.id !== messageId) }));\n },\n [commit],\n );\n\n const setMessages = useCallback(\n (messages: ChatMessage[]) => {\n commit(s => ({ ...s, messages }));\n },\n [commit],\n );\n\n const clearMessages = useCallback(() => {\n commit(s => ({ ...s, messages: [] }));\n }, [commit]);\n\n const setTaskState = useCallback(\n (isTaskRunning: boolean) => {\n commit(s => ({ ...s, task: { isTaskRunning } }));\n },\n [commit],\n );\n\n useEffect(() => {\n const watchdogs = state.messages\n .filter(msg => msg.isPlaceholder)\n .map(msg => setTimeout(() => commit(s => reduceStaleReply(s, msg.id, STALE_REPLY_TEXT)), STALE_REPLY_TIMEOUT_MS));\n\n return () => watchdogs.forEach(clearTimeout);\n }, [state.messages, commit]);\n\n const messageDispatch = useCallback(\n async (content: string, mode?: InstructionType, skipUserMessage?: boolean) => {\n const effectiveMode = mode ?? currentModeRef.current;\n\n if (previewMode) {\n if (!skipUserMessage) {\n addMessage(createUserMessage(content, effectiveMode));\n }\n addMessage(createAgentMessage(\"This is a preview. In production, I'll respond to your messages here.\"));\n return;\n }\n\n const config = storageService.getCredentialedConfig();\n\n if (!config) {\n console.error('Config not loaded or incomplete');\n addMessage(\n createAgentMessage('Configuration error: Missing API credentials. Please check your widget settings.'),\n );\n return;\n }\n\n if (!skipUserMessage) {\n addMessage(createUserMessage(content, effectiveMode));\n }\n\n const placeholderId = `temp-${globalThis.crypto.randomUUID()}`;\n const placeholderMsg: ChatMessage = {\n id: placeholderId,\n content: '',\n sender: 'agent',\n timestamp: new Date(),\n mode: effectiveMode,\n isPlaceholder: true,\n placeholderState: 'thinking',\n parts: [],\n };\n addMessage(placeholderMsg);\n\n try {\n await dispatchMessage(config, content, effectiveMode, placeholderId);\n // Response arrives via SSE; placeholder stays \"thinking\"\n } catch (error) {\n console.error('Failed to send message:', error);\n commit(s =>\n reduceError(s, placeholderId, \"I'm sorry, I encountered an error processing your request. Please try again.\"),\n );\n }\n },\n [previewMode, addMessage, commit],\n );\n\n useEffect(() => {\n if (previewMode) return;\n\n const streamClient = StreamClient.getInstance();\n\n const startToolCall = async (effect: Extract<SseEffect, { type: 'executeTool' }>) => {\n const { toolCallId, tool, args, mode, explanation } = effect;\n const result = await browserToolService.executeTool(tool, args, mode, explanation);\n const error = result.success ? undefined : (result.error ?? 'Tool execution failed');\n\n commit(s =>\n reduceToolProgress(s, tool, explanation, error ? 'failed' : 'completed', currentModeRef.current, error),\n );\n if (!error && tool === 'done') {\n commit(s => reduceToolDone(s, currentModeRef.current));\n }\n\n await streamClient\n .send({\n type: 'tool/response',\n tool_call_id: toolCallId,\n success: result.success,\n data: JSON.stringify(result.data),\n error,\n })\n .catch(err => console.error('Failed to send tool response:', err));\n\n result.afterResponseAttempt?.();\n };\n\n const handleMessage = (event: WidgetEvent): void => {\n // Transport bookkeeping that must run before the pure reducer.\n if (event.type === 'tool/call') {\n const toolCallId = event.tool_call_id;\n if (processedToolCallIds.current.has(toolCallId)) return;\n processedToolCallIds.current.add(toolCallId);\n if (processedToolCallIds.current.size > MAX_PROCESSED_TOOL_CALL_IDS) {\n processedToolCallIds.current = new Set(\n [...processedToolCallIds.current].slice(-MAX_PROCESSED_TOOL_CALL_IDS / 2),\n );\n }\n\n if (!BROWSER_TOOLS.has(event.browser_tool)) {\n console.warn('[Widget] Unknown tool requested:', event.browser_tool);\n streamClient\n .send({\n type: 'tool/response',\n tool_call_id: toolCallId,\n success: false,\n error: `Unknown tool: ${event.browser_tool}`,\n })\n .catch(err => console.error('Failed to send unknown-tool response:', err));\n return;\n }\n } else if (event.type === 'task/status' && isTerminalTaskStatus(event.status)) {\n processedToolCallIds.current.clear();\n }\n\n let effects: SseEffect[] = [];\n commit(state => {\n const result = reduceSse(state, event, currentModeRef.current);\n effects = result.effects;\n return result.state;\n });\n\n for (const effect of effects) {\n startToolCall(effect).catch(error => console.error('[Widget] Tool call failed:', error));\n }\n };\n\n const handleError = (error: Error) => {\n uiActions.setError(error.message);\n // A retriable blip settles when the reply lands on the reconnected stream; a give-up never does,\n // and the composer stays disabled for as long as one bubble is still waiting.\n if (error instanceof StreamGaveUpError) commit(s => reduceTransportFailure(s, error.message));\n };\n\n const callbacks = { onMessage: handleMessage, onError: handleError };\n streamClient.addCallbacks(callbacks);\n\n return () => {\n streamClient.removeCallbacks(callbacks);\n };\n }, [previewMode, commit, uiActions]);\n\n const stopTask = useCallback(async () => {\n commit(s => reduceStop(s, currentModeRef.current));\n\n if (previewMode) return;\n\n // chat/stop carries no task id: the api stops the one dispatch it holds for this chat.\n StreamClient.getInstance()\n .send({ type: 'chat/stop' })\n .catch(err => {\n console.error('Failed to stop task remotely:', err);\n // reduceStop already stamped the message \"stopped\" — in `do` mode the agent may still be\n // clicking through the visitor's page, and `send`'s own \"Failed to send message\" toast names\n // the transport rather than the thing the user asked for and did not get.\n uiActions.setError('Could not stop the assistant — it may still be working.');\n });\n }, [previewMode, commit, uiActions]);\n\n const chatActions = useMemo<ChatActions>(\n () => ({ addMessage, updateMessage, removeMessage, setMessages, clearMessages, messageDispatch }),\n [addMessage, updateMessage, removeMessage, setMessages, clearMessages, messageDispatch],\n );\n\n const taskActions = useMemo<TaskActions>(() => ({ setTaskState, stopTask }), [setTaskState, stopTask]);\n\n return (\n <ChatContext.Provider value={{ messages: state.messages, chatActions, taskState: state.task, taskActions }}>\n {children}\n </ChatContext.Provider>\n );\n};\n\nexport const useChatContext = (): ChatContextType => {\n const ctx = useContext(ChatContext);\n if (!ctx) throw new Error('useChatContext must be used within ChatProvider');\n return ctx;\n};\n","import React, { createContext, useContext, useEffect, useState } from 'react';\n\nimport { chatService } from '../services/ChatService';\nimport { chatSessionManager } from '../services/ChatSessionManager';\nimport { StreamClient } from '../services/StreamClient';\nimport { ChatProvider, useChatContext } from './ChatContext';\nimport { UIStateProvider, useUIStateContext } from './UIStateContext';\n\n/** WidgetRoot publishes its own root here: a portal outside it escapes the element carrying the tenant tokens. */\nexport const PortalContainerContext = createContext<HTMLElement | null>(null);\n\nexport const usePortalContainer = (): HTMLElement => useContext(PortalContainerContext) ?? document.body;\n\n/** Its own component so the subscription to every message change cannot re-render the tree InitBridge wraps. */\nconst PersistBridge: React.FC = () => {\n const { uiState } = useUIStateContext();\n const { messages, taskState } = useChatContext();\n\n useEffect(() => {\n const { currentMode, isOpen } = uiState;\n chatService.persist({ messages, ...taskState, currentMode, isOpen });\n }, [messages, taskState, uiState]);\n\n return null;\n};\n\nconst InitBridge: React.FC<{ children: React.ReactNode; previewMode: boolean }> = ({ children, previewMode }) => {\n const { uiActions } = useUIStateContext();\n const { chatActions, taskActions } = useChatContext();\n const [restored, setRestored] = useState(false);\n\n useEffect(() => {\n if (previewMode) return;\n let cancelled = false;\n\n const init = async () => {\n const chatId = await chatSessionManager.getOrCreateChatId();\n if (cancelled) return;\n\n const { messages, isTaskRunning, ...ui } = chatService.restore();\n uiActions.applyState(ui);\n chatActions.setMessages(messages);\n taskActions.setTaskState(isTaskRunning);\n setRestored(true);\n\n StreamClient.getInstance()\n .connect(chatId)\n .catch((err: unknown) => console.error('Initial stream connection failed:', err));\n };\n\n void init().catch(error => {\n if (cancelled) return;\n console.error('Widget initialization failed:', error);\n uiActions.setError('Widget failed to initialise — please refresh the page.');\n });\n\n return () => {\n cancelled = true;\n };\n }, []);\n\n return (\n <>\n {children}\n {restored && <PersistBridge />}\n </>\n );\n};\n\ninterface WidgetProvidersProps {\n children: React.ReactNode;\n previewMode?: boolean;\n}\n\nexport const WidgetProviders: React.FC<WidgetProvidersProps> = ({ children, previewMode = false }) => (\n <UIStateProvider>\n <ChatProvider previewMode={previewMode}>\n <InitBridge previewMode={previewMode}>{children}</InitBridge>\n </ChatProvider>\n </UIStateProvider>\n);\n","function hexToRgb(hex: string): { r: number; g: number; b: number } | null {\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return result\n ? {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n }\n : null;\n}\n\n// WCAG relative luminance.\nfunction getLuminance(color: string): number {\n const rgb = hexToRgb(color);\n if (!rgb) return 0.5;\n\n const [r, g, b] = [rgb.r / 255, rgb.g / 255, rgb.b / 255].map(val => {\n return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);\n });\n\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\nexport function getContrastingColor(color: string): string {\n const luminance = getLuminance(color);\n return luminance > 0.5 ? '#000000' : '#ffffff';\n}\n\nexport function addOpacity(color: string, opacity: number): string {\n if (color.startsWith('rgba') || color.startsWith('rgb')) {\n const match = color.match(/(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)/);\n if (match) {\n return `rgba(${match[1]}, ${match[2]}, ${match[3]}, ${opacity})`;\n }\n }\n\n const rgb = hexToRgb(color);\n if (rgb) {\n return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${opacity})`;\n }\n\n return color;\n}\n","import type { WidgetSettingsData } from '../sdk';\nimport { addOpacity, getContrastingColor } from '../utils/color';\n\ntype SemanticTokens = {\n color: {\n background: string;\n foreground: string;\n foregroundMuted: string;\n foregroundFaint: string;\n border: string;\n primary: string;\n primaryForeground: string;\n primaryHover: string;\n secondary: string;\n secondaryForeground: string;\n secondaryBg: string;\n secondaryHover: string;\n };\n radius: string;\n motion: {\n durationAnimation: string;\n durationFade: string;\n };\n};\n\n// Fixed, not per-tenant: every widget row in production holds these, and no surface writes them.\nexport const WIDGET_RADIUS_PX = 12;\nconst DURATION_ANIMATION = '300ms';\nconst DURATION_FADE = '200ms';\n\ntype WidgetStyleSettingsDefaults = Pick<\n WidgetSettingsData,\n | 'widget_background_color'\n | 'widget_text_color'\n | 'widget_border_color'\n | 'widget_accent_color'\n | 'widget_secondary_color'\n>;\n\nconst WIDGET_STYLE_SETTINGS_DEFAULTS: WidgetStyleSettingsDefaults = {\n widget_background_color: '#ffffff',\n widget_text_color: '#1f2937',\n widget_border_color: '#e5e7eb',\n widget_accent_color: '#3b82f6',\n widget_secondary_color: '#6b7280',\n};\n\nfunction mapWidgetSettingsToSemanticTokens(settings: WidgetStyleSettingsDefaults): SemanticTokens {\n return {\n color: {\n background: settings.widget_background_color,\n foreground: settings.widget_text_color,\n foregroundMuted: addOpacity(settings.widget_text_color, 0.6),\n foregroundFaint: addOpacity(settings.widget_text_color, 0.4),\n border: settings.widget_border_color,\n primary: settings.widget_accent_color,\n primaryForeground: getContrastingColor(settings.widget_accent_color),\n primaryHover: addOpacity(settings.widget_accent_color, 0.85),\n secondary: settings.widget_secondary_color,\n secondaryForeground: '#ffffff',\n secondaryBg: addOpacity(settings.widget_secondary_color, 0.2),\n secondaryHover: addOpacity(settings.widget_secondary_color, 0.3),\n },\n radius: `${WIDGET_RADIUS_PX}px`,\n motion: {\n durationAnimation: DURATION_ANIMATION,\n durationFade: DURATION_FADE,\n },\n };\n}\n\nexport function createSemanticTokens(settings: Partial<WidgetSettingsData> = {}): SemanticTokens {\n // An explicit undefined must not shadow its default, which is what a plain spread would do.\n const overrides = Object.fromEntries(\n Object.entries(settings).filter(([, value]) => value !== undefined),\n ) as Partial<WidgetStyleSettingsDefaults>;\n return mapWidgetSettingsToSemanticTokens({ ...WIDGET_STYLE_SETTINGS_DEFAULTS, ...overrides });\n}\n\n// Inline styles on the widget root: must cover every var index.css `:host` defines, or that fallback shows through.\nexport function semanticTokensToCssCustomProperties(tokens: SemanticTokens): Record<string, string> {\n return {\n '--background': tokens.color.background,\n '--foreground': tokens.color.foreground,\n '--card': tokens.color.background,\n '--card-foreground': tokens.color.foreground,\n '--primary': tokens.color.primary,\n '--foreground-muted': tokens.color.foregroundMuted,\n '--foreground-faint': tokens.color.foregroundFaint,\n '--primary-foreground': tokens.color.primaryForeground,\n '--primary-hover': tokens.color.primaryHover,\n '--secondary': tokens.color.secondary,\n '--secondary-foreground': tokens.color.secondaryForeground,\n '--secondary-bg': tokens.color.secondaryBg,\n '--secondary-hover': tokens.color.secondaryHover,\n '--border': tokens.color.border,\n '--ring': tokens.color.primary,\n '--radius': tokens.radius,\n '--duration-animation': tokens.motion.durationAnimation,\n '--duration-fade': tokens.motion.durationFade,\n };\n}\n","import { useEffect } from 'react';\n\nconst MOBILE_MAX_WIDTH = 767;\n\nexport function useScrollLock(enabled: boolean): void {\n useEffect(() => {\n if (!enabled) return;\n\n const mql = window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH}px)`);\n if (!mql.matches) return;\n\n const doc = document.documentElement;\n const body = document.body;\n const prevDocOverflow = doc.style.overflow;\n const prevBodyOverflow = body.style.overflow;\n\n doc.style.overflow = 'hidden';\n body.style.overflow = 'hidden';\n\n return () => {\n doc.style.overflow = prevDocOverflow;\n body.style.overflow = prevBodyOverflow;\n };\n }, [enabled]);\n}\n","import { createContext, useCallback, useContext, useMemo } from 'react';\n\nimport { useChatContext } from '../context/ChatContext';\nimport { useUIStateContext } from '../context/UIStateContext';\nimport type { MarketrixConfig, WidgetSettingsData, WidgetState } from '../types';\n\nexport type ValidWidgetConfig = MarketrixConfig & Required<Pick<MarketrixConfig, keyof WidgetSettingsData>>;\n\n/** Every setting resolved: API settings plus the position and script-tag overrides WidgetRoot layers on top. */\nexport const WidgetConfigContext = createContext<ValidWidgetConfig | null>(null);\n\nexport const useWidgetConfig = (): ValidWidgetConfig => {\n const config = useContext(WidgetConfigContext);\n if (!config) throw new Error('useWidgetConfig must be used within WidgetRoot');\n return config;\n};\n\nexport const useWidget = () => {\n const { uiState, uiActions } = useUIStateContext();\n const { messages, chatActions, taskState, taskActions } = useChatContext();\n\n const state = useMemo<WidgetState>(\n () => ({ ...uiState, ...taskState, messages, isAwaitingReply: messages.some(msg => msg.isPlaceholder) }),\n [uiState, messages, taskState],\n );\n\n const resetChat = useCallback(() => {\n chatActions.clearMessages();\n taskActions.setTaskState(false);\n uiActions.setError(undefined);\n }, [chatActions, taskActions, uiActions]);\n\n const actions = useMemo(\n () => ({ ...uiActions, ...taskActions, ...chatActions, clearChatHistory: resetChat }),\n [uiActions, taskActions, chatActions, resetChat],\n );\n\n return { state, actions };\n};\n","import type React from 'react';\n\nimport type { WidgetPosition } from '../types';\n\n// Must equal Tailwind's `-5` (1.25rem) in the class strings below: the launcher positions by class,\n// the panel by inline style, and neither can be derived from the other (see CORNERS) — pinned by\n// widgetPositioning.test.ts.\nconst EDGE_OFFSET_PX = 20;\n\n// Class strings are spelled out because Tailwind only emits what it can see literally in the source.\nconst CORNERS = {\n bottom_right: { classes: 'bottom-5 right-5', vertical: 'bottom', horizontal: 'right' },\n bottom_left: { classes: 'bottom-5 left-5', vertical: 'bottom', horizontal: 'left' },\n top_right: { classes: 'top-5 right-5', vertical: 'top', horizontal: 'right' },\n top_left: { classes: 'top-5 left-5', vertical: 'top', horizontal: 'left' },\n} as const;\n\nexport const getCorner = (position: WidgetPosition) => CORNERS[position] ?? CORNERS.bottom_right;\n\nexport const isWidgetPosition = (value: unknown): value is WidgetPosition =>\n typeof value === 'string' && value in CORNERS;\n\nexport const getPositionClasses = (position: WidgetPosition): string => getCorner(position).classes;\n\nexport const getPanelPositionStyle = (position: WidgetPosition): React.CSSProperties => {\n const { vertical, horizontal } = getCorner(position);\n return { [vertical]: `${EDGE_OFFSET_PX}px`, [horizontal]: `${EDGE_OFFSET_PX}px` };\n};\n\nexport const getAnchorTopLeft = (\n position: WidgetPosition,\n vw: number,\n vh: number,\n w: number,\n h: number,\n): { x: number; y: number } => {\n const { vertical, horizontal } = getCorner(position);\n return {\n x: horizontal === 'left' ? EDGE_OFFSET_PX : vw - EDGE_OFFSET_PX - w,\n y: vertical === 'top' ? EDGE_OFFSET_PX : vh - EDGE_OFFSET_PX - h,\n };\n};\n\nexport const getNearestCornerByTranslation = (\n translation: { dx: number; dy: number },\n position: WidgetPosition,\n vw: number,\n vh: number,\n w: number,\n h: number,\n): WidgetPosition => {\n const anchor = getAnchorTopLeft(position, vw, vh, w, h);\n const x = anchor.x + translation.dx;\n const y = anchor.y + translation.dy;\n\n let nearest: WidgetPosition = position;\n let minDist = Infinity;\n for (const candidate of Object.keys(CORNERS) as WidgetPosition[]) {\n const target = getAnchorTopLeft(candidate, vw, vh, w, h);\n const dist = Math.hypot(x - target.x, y - target.y);\n if (dist < minDist) {\n minDist = dist;\n nearest = candidate;\n }\n }\n return nearest;\n};\n","import React from 'react';\n\ninterface ErrorBoundaryProps {\n children: React.ReactNode;\n label: string;\n fallback?: React.ReactNode;\n}\n\nexport class ErrorBoundary extends React.Component<ErrorBoundaryProps, { hasError: boolean }> {\n override state = { hasError: false };\n\n static getDerivedStateFromError() {\n return { hasError: true };\n }\n\n override componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(`${this.props.label} Error Boundary caught error:`, error, errorInfo);\n }\n\n override render() {\n // Render nothing rather than crash the host page; componentDidCatch already logged it.\n return this.state.hasError ? (this.props.fallback ?? null) : this.props.children;\n }\n}\n","import React, { useCallback, useLayoutEffect, useRef, useState } from 'react';\n\nimport type { WidgetPosition } from '../types';\nimport { getAnchorTopLeft, getNearestCornerByTranslation } from '../utils/widgetPositioning';\n\nconst DRAG_THRESHOLD_PX = 5;\nconst SNAP_DURATION_MS = 600;\nconst SNAP_EASING = 'cubic-bezier(0.16, 1, 0.3, 1)';\n\nexport interface UseDragSnapOptions {\n position: WidgetPosition;\n onDrag: (position: WidgetPosition) => void;\n isPreviewMode?: boolean;\n wrapperRef: React.RefObject<HTMLDivElement | null>;\n}\n\nexport interface UseDragSnapResult {\n isDragging: boolean;\n pixelPositionStyle: { left: number; top: number } | undefined;\n onPointerDown: (event: React.PointerEvent<HTMLButtonElement>) => void;\n onPointerMove: (event: React.PointerEvent<HTMLButtonElement>) => void;\n onPointerUp: (event: React.PointerEvent<HTMLButtonElement>) => void;\n onPointerCancel: (event: React.PointerEvent<HTMLButtonElement>) => void;\n suppressUntilRef: React.RefObject<number>;\n}\n\nexport function useDragSnap({\n position,\n onDrag,\n isPreviewMode = false,\n wrapperRef,\n}: UseDragSnapOptions): UseDragSnapResult {\n const [isDragging, setIsDragging] = useState(false);\n const [wrapperSize, setWrapperSize] = useState({ w: 56, h: 56 });\n const [, setViewportTick] = useState(0);\n const transitionEndRef = useRef<(() => void) | null>(null);\n\n const dragRef = useRef<{\n pointerId: number;\n startX: number;\n startY: number;\n dragging: boolean;\n lastX: number;\n lastY: number;\n } | null>(null);\n const rafRef = useRef<number | null>(null);\n const suppressUntilRef = useRef(0);\n const velocityHistoryRef = useRef<Array<{ x: number; y: number; t: number }>>([]);\n const lastVelocitySampleRef = useRef(0);\n\n const cancelRaf = () => {\n if (rafRef.current !== null) window.cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n };\n\n React.useEffect(() => cancelRaf, []);\n\n React.useEffect(() => {\n if (isPreviewMode) return;\n const onResize = () => setViewportTick(t => t + 1);\n window.addEventListener('resize', onResize);\n return () => window.removeEventListener('resize', onResize);\n }, [isPreviewMode]);\n\n const measureWrapper = useCallback(() => {\n if (!wrapperRef.current || typeof window === 'undefined') return;\n const rect = wrapperRef.current.getBoundingClientRect();\n setWrapperSize(prev =>\n prev.w === rect.width && prev.h === rect.height ? prev : { w: rect.width, h: rect.height },\n );\n }, [wrapperRef]);\n\n useLayoutEffect(() => {\n measureWrapper();\n const ro = typeof window !== 'undefined' && wrapperRef.current ? new ResizeObserver(measureWrapper) : null;\n if (ro && wrapperRef.current) ro.observe(wrapperRef.current);\n return () => ro?.disconnect();\n }, [measureWrapper, position, wrapperRef]);\n\n const vw = typeof window !== 'undefined' ? window.innerWidth : 0;\n const vh = typeof window !== 'undefined' ? window.innerHeight : 0;\n const anchor = getAnchorTopLeft(position, vw, vh, wrapperSize.w, wrapperSize.h);\n const pixelPositionStyle = !isPreviewMode && vw > 0 && vh > 0 ? { left: anchor.x, top: anchor.y } : undefined;\n\n const projectVelocity = (v: number, decel = 0.999) => ((v / 1000) * decel) / (1 - decel);\n\n const getVelocityFromHistory = (): { x: number; y: number } => {\n const h = velocityHistoryRef.current;\n if (h.length < 2) return { x: 0, y: 0 };\n const dt = h[h.length - 1].t - h[0].t;\n if (dt <= 0) return { x: 0, y: 0 };\n return {\n x: ((h[h.length - 1].x - h[0].x) / dt) * 1000,\n y: ((h[h.length - 1].y - h[0].y) / dt) * 1000,\n };\n };\n\n const resetDragStyles = () => {\n cancelRaf();\n if (wrapperRef.current) {\n wrapperRef.current.style.transform = '';\n wrapperRef.current.style.willChange = '';\n wrapperRef.current.style.transition = '';\n }\n };\n\n const commitPositionAfterAnimation = useCallback(\n (nextCorner: WidgetPosition, wrapper: HTMLDivElement) => {\n if (transitionEndRef.current) return;\n let finished = false;\n const done = () => {\n if (finished) return;\n finished = true;\n transitionEndRef.current = null;\n wrapper.style.transition = 'none';\n wrapper.style.willChange = '';\n onDrag(nextCorner);\n setIsDragging(false);\n requestAnimationFrame(() => {\n if (wrapperRef.current) {\n wrapperRef.current.style.transition = '';\n }\n });\n };\n transitionEndRef.current = done;\n const fallbackTimer = window.setTimeout(done, SNAP_DURATION_MS + 50);\n wrapper.addEventListener('transitionend', function onEnd(e: TransitionEvent) {\n if (e.target !== wrapper || e.propertyName !== 'left') return;\n window.clearTimeout(fallbackTimer);\n wrapper.removeEventListener('transitionend', onEnd);\n done();\n });\n },\n [onDrag, wrapperRef],\n );\n\n const snapToCorner = useCallback(\n (nextCorner: WidgetPosition, fromX: number, fromY: number) => {\n if (!wrapperRef.current || !pixelPositionStyle) {\n resetDragStyles();\n onDrag(nextCorner);\n setIsDragging(false);\n return;\n }\n cancelRaf();\n const wrapper = wrapperRef.current;\n const oldAnchor = getAnchorTopLeft(position, vw, vh, wrapperSize.w, wrapperSize.h);\n const newAnchor = getAnchorTopLeft(nextCorner, vw, vh, wrapperSize.w, wrapperSize.h);\n wrapper.style.transition = 'none';\n wrapper.style.transform = 'none';\n wrapper.style.willChange = 'left, top';\n wrapper.style.left = `${oldAnchor.x + fromX}px`;\n wrapper.style.top = `${oldAnchor.y + fromY}px`;\n requestAnimationFrame(() => {\n wrapper.style.transition = `left ${SNAP_DURATION_MS}ms ${SNAP_EASING}, top ${SNAP_DURATION_MS}ms ${SNAP_EASING}`;\n wrapper.style.left = `${newAnchor.x}px`;\n wrapper.style.top = `${newAnchor.y}px`;\n });\n commitPositionAfterAnimation(nextCorner, wrapper);\n },\n [\n commitPositionAfterAnimation,\n onDrag,\n pixelPositionStyle,\n position,\n vw,\n vh,\n wrapperSize.w,\n wrapperSize.h,\n wrapperRef,\n ],\n );\n\n const endDrag = (event: React.PointerEvent<HTMLButtonElement>) => {\n resetDragStyles();\n dragRef.current = null;\n setIsDragging(false);\n event.currentTarget.releasePointerCapture(event.pointerId);\n };\n\n const onPointerDown = (event: React.PointerEvent<HTMLButtonElement>) => {\n dragRef.current = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n dragging: false,\n lastX: 0,\n lastY: 0,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n };\n\n const onPointerMove = (event: React.PointerEvent<HTMLButtonElement>) => {\n const drag = dragRef.current;\n if (drag?.pointerId !== event.pointerId) return;\n\n const dx = event.clientX - drag.startX;\n const dy = event.clientY - drag.startY;\n\n if (!drag.dragging && Math.hypot(dx, dy) > DRAG_THRESHOLD_PX) {\n drag.dragging = true;\n setIsDragging(true);\n velocityHistoryRef.current = [];\n lastVelocitySampleRef.current = 0;\n if (wrapperRef.current) {\n wrapperRef.current.style.willChange = 'transform';\n wrapperRef.current.style.transition = 'none';\n }\n }\n\n if (!drag.dragging) return;\n\n drag.lastX = dx;\n drag.lastY = dy;\n\n const now = Date.now();\n if (now - lastVelocitySampleRef.current >= 10) {\n lastVelocitySampleRef.current = now;\n velocityHistoryRef.current = [\n ...velocityHistoryRef.current.slice(-5),\n { x: event.clientX, y: event.clientY, t: now },\n ];\n }\n\n if (rafRef.current === null) {\n rafRef.current = window.requestAnimationFrame(() => {\n rafRef.current = null;\n const d = dragRef.current;\n const wrapper = wrapperRef.current;\n if (!wrapper || !d) return;\n wrapper.style.transform = `translate3d(${d.lastX}px, ${d.lastY}px, 0)`;\n });\n }\n };\n\n const onPointerUp = (event: React.PointerEvent<HTMLButtonElement>) => {\n const drag = dragRef.current;\n if (drag?.pointerId !== event.pointerId) return;\n if (drag.dragging) {\n const v = getVelocityFromHistory();\n const projX = projectVelocity(v.x);\n const projY = projectVelocity(v.y);\n const projected = { dx: drag.lastX + projX, dy: drag.lastY + projY };\n\n const rect = wrapperRef.current?.getBoundingClientRect();\n const nextCorner = rect\n ? getNearestCornerByTranslation(\n projected,\n position,\n window.innerWidth,\n window.innerHeight,\n rect.width,\n rect.height,\n )\n : position;\n\n snapToCorner(nextCorner, drag.lastX, drag.lastY);\n suppressUntilRef.current = Date.now() + 600;\n dragRef.current = null;\n event.currentTarget.releasePointerCapture(event.pointerId);\n return;\n }\n endDrag(event);\n };\n\n const onPointerCancel = (event: React.PointerEvent<HTMLButtonElement>) => {\n if (dragRef.current?.pointerId !== event.pointerId) return;\n endDrag(event);\n };\n\n return {\n isDragging,\n pixelPositionStyle,\n onPointerDown,\n onPointerMove,\n onPointerUp,\n onPointerCancel,\n suppressUntilRef,\n };\n}\n","import React, { useRef } from 'react';\n\nimport MarketrixIcon from '../../assets/marketrix-icon.svg';\nimport { WIDGET_RADIUS_PX } from '../../design-system/semantic-tokens';\nimport { SHADOW } from '../../design-system/shadows';\nimport { useDragSnap } from '../../hooks/useDragSnap';\nimport { useWidget, useWidgetConfig } from '../../hooks/useWidget';\nimport type { WidgetPosition } from '../../types';\nimport { getPanelPositionStyle, getPositionClasses } from '../../utils/widgetPositioning';\nimport { Avatar } from '../base/Avatar';\nimport { Button } from '../base/Button';\nimport { Flex } from '../base/Flex';\nimport { Icon } from '../base/Icon';\nimport { Surface } from '../base/Surface';\n\ninterface WidgetFabProps {\n onDrag: (position: WidgetPosition) => void;\n}\n\nexport const WidgetFab: React.FC<WidgetFabProps> = ({ onDrag }) => {\n const {\n isPreviewMode = false,\n widget_accent_color: accentColor,\n widget_background_color: backgroundColor,\n widget_position: position,\n widget_position_z_index: zIndex,\n } = useWidgetConfig();\n const { state, actions } = useWidget();\n const open = state.isOpen;\n const taskRunning = state.isTaskRunning;\n const error = !!state.error;\n\n const showProcessingGlow = !open && (state.isAwaitingReply || taskRunning);\n const showStopControl = !open && taskRunning;\n const glowClass = error ? 'marketrix-widget-button-error-glow' : 'marketrix-widget-button-processing-glow';\n const activityRingClass = error\n ? 'marketrix-widget-button-error-activity-ring'\n : 'marketrix-widget-button-processing-activity-ring';\n\n const wrapperRef = useRef<HTMLDivElement | null>(null);\n\n const {\n isDragging,\n pixelPositionStyle,\n onPointerDown,\n onPointerMove,\n onPointerUp,\n onPointerCancel,\n suppressUntilRef,\n } = useDragSnap({ position, onDrag, isPreviewMode, wrapperRef });\n\n const effectivePositionClasses = getPositionClasses(position);\n const positionClass = isPreviewMode ? 'absolute' : 'fixed';\n\n return (\n <Surface\n ref={wrapperRef as React.Ref<HTMLElement>}\n className={`${positionClass} ${pixelPositionStyle ? '' : effectivePositionClasses} ${isDragging ? '' : 'transition-transform duration-300 ease-in-out'}`}\n style={{\n zIndex,\n pointerEvents: open ? 'none' : 'auto',\n ...(isPreviewMode ? getPanelPositionStyle(position) : {}),\n ...pixelPositionStyle,\n }}\n >\n <Surface\n className={`\n group relative w-14 h-14 overflow-visible transition-all duration-300 ease-in-out\n ${open ? 'scale-0 opacity-0 pointer-events-none' : 'scale-100 opacity-100 hover:scale-110'}\n `}\n >\n {showProcessingGlow && <Surface className={glowClass} aria-hidden />}\n\n {showStopControl && !isDragging && (\n <Button\n type='button'\n variant='secondary'\n size='sm'\n onClick={e => {\n e.preventDefault();\n e.stopPropagation();\n actions.stopTask();\n }}\n className={`absolute top-1/2 z-20 -translate-y-1/2 rounded-full border border-white/25 bg-gray-900 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-wide text-white shadow-lg opacity-0 transition-opacity duration-150 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto ${position.includes('left') ? 'left-full ml-2' : 'right-full mr-2'}`}\n style={{ border: '1px solid rgba(255,255,255,0.25)' }}\n >\n Stop\n </Button>\n )}\n\n <Button\n type='button'\n variant='bare'\n onClick={() => {\n if (Date.now() < suppressUntilRef.current) return;\n actions.toggleWidget();\n }}\n onDragStart={e => e.preventDefault()}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onPointerCancel={onPointerCancel}\n className='relative z-10 w-14 h-14 min-w-14'\n style={{\n touchAction: 'none',\n cursor: isDragging ? 'grabbing' : 'grab',\n userSelect: 'none',\n WebkitUserSelect: 'none',\n }}\n aria-label={open ? 'Close' : 'Open'}\n aria-live='polite'\n >\n <Flex className='w-full h-full items-center justify-center relative'>\n <Surface\n className={`\n relative w-12 h-12 overflow-hidden transition-[transform,opacity,background-color] duration-[167ms] ease-[cubic-bezier(0.33,0,0,1)]\n hover:scale-110 hover:duration-[250ms] active:scale-[0.85] active:duration-[134ms] active:ease-[cubic-bezier(0.45,0,0.2,1)]\n animate-launcher-entrance\n `}\n style={{\n borderRadius: `${WIDGET_RADIUS_PX}px`,\n backgroundColor: open ? backgroundColor : accentColor,\n boxShadow: SHADOW.fab,\n }}\n >\n {showProcessingGlow && (\n <svg className={activityRingClass} viewBox='0 0 54 54' fill='none' aria-hidden>\n <rect\n x='1.25'\n y='1.25'\n width='51.5'\n height='51.5'\n rx={WIDGET_RADIUS_PX + 1}\n ry={WIDGET_RADIUS_PX + 1}\n />\n </svg>\n )}\n\n <Flex\n className='absolute inset-0 items-center justify-center transition-[transform,opacity] duration-[160ms] linear'\n style={{\n transform: open ? 'rotate(30deg) scale(0)' : 'rotate(0deg) scale(1)',\n opacity: open ? 0 : 1,\n transitionProperty: 'transform, opacity',\n transitionDuration: '0.16s, 0.08s',\n transitionTimingFunction: 'linear',\n }}\n aria-hidden={open}\n >\n <Avatar\n src={MarketrixIcon}\n alt=''\n className='relative z-10 w-full h-full object-contain'\n draggable={false}\n onDragStart={e => e.preventDefault()}\n style={{\n borderRadius: `${WIDGET_RADIUS_PX}px`,\n border: 'none',\n outline: 'none',\n backgroundColor: 'transparent',\n pointerEvents: 'none',\n userSelect: 'none',\n }}\n />\n </Flex>\n\n <Flex\n className='absolute inset-0 items-center justify-center transition-[transform,opacity] duration-[160ms] linear'\n style={{\n transform: open ? 'rotate(0deg) scale(1)' : 'rotate(-30deg) scale(0)',\n opacity: open ? 1 : 0,\n transitionProperty: 'transform, opacity',\n transitionDuration: '0.16s, 0.08s',\n transitionTimingFunction: 'linear',\n }}\n aria-hidden={!open}\n >\n <Icon name='chevronDown' size={24} className='relative z-10 text-foreground pointer-events-none' />\n </Flex>\n </Surface>\n </Flex>\n </Button>\n </Surface>\n </Surface>\n );\n};\n","import { useCallback, useEffect, useRef } from 'react';\n\nconst FOCUSABLE_SELECTOR =\n 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])';\n\n/** Inside the closed shadow root `document.activeElement` retargets to the HOST, so it never names an\n * element of the widget's own tree — read focus through the container's own root instead. */\nfunction activeElementIn(container: HTMLElement): HTMLElement | null {\n const root = container.getRootNode();\n return ((root instanceof ShadowRoot ? root.activeElement : document.activeElement) as HTMLElement) ?? null;\n}\n\nfunction getFocusables(container: HTMLElement): HTMLElement[] {\n return Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(\n el => el.offsetParent !== null && !el.hasAttribute('aria-hidden'),\n );\n}\n\nexport function useFocusTrap(\n containerRef: React.RefObject<HTMLElement | null>,\n isActive: boolean,\n options?: {\n onEscape?: () => void;\n focusTargetRef?: React.RefObject<HTMLElement | null>;\n },\n) {\n const previousActiveRef = useRef(false);\n const previouslyFocusedRef = useRef<HTMLElement | null>(null);\n\n const focusFirst = useCallback(() => {\n const container = containerRef.current;\n if (!container) return;\n const target = options?.focusTargetRef?.current;\n if (target) {\n target.focus({ preventScroll: true });\n return;\n }\n const list = getFocusables(container);\n if (list[0]) list[0].focus({ preventScroll: true });\n }, [containerRef, options?.focusTargetRef]);\n\n useEffect(() => {\n if (!isActive) {\n if (previousActiveRef.current) {\n previouslyFocusedRef.current?.focus({ preventScroll: true });\n previouslyFocusedRef.current = null;\n }\n previousActiveRef.current = false;\n return;\n }\n\n const container = containerRef.current;\n if (!container) return;\n\n if (!previousActiveRef.current) {\n previouslyFocusedRef.current = activeElementIn(container);\n }\n previousActiveRef.current = true;\n\n focusFirst();\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n options?.onEscape?.();\n return;\n }\n if (e.key !== 'Tab') return;\n const focusables = getFocusables(container);\n if (focusables.length === 0) return;\n const current = activeElementIn(container);\n const idx = current ? focusables.indexOf(current) : -1;\n if (idx === -1) return;\n if (e.shiftKey) {\n if (idx === 0) {\n e.preventDefault();\n focusables[focusables.length - 1].focus();\n }\n } else {\n if (idx === focusables.length - 1) {\n e.preventDefault();\n focusables[0].focus();\n }\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, true);\n return () => document.removeEventListener('keydown', handleKeyDown, true);\n }, [isActive, containerRef, focusFirst, options?.onEscape]);\n}\n","import { useCallback, useRef, useState } from 'react';\n\nimport { readLocal, writeLocal } from '../services/StorageService';\n\ninterface Size {\n width: number;\n height: number;\n}\n\nconst MIN_WIDTH = 280;\nconst MAX_WIDTH = 600;\nconst MIN_HEIGHT = 320;\nconst DEFAULT_SIZE: Size = { width: 360, height: 450 };\n\nconst maxHeightPx = (): number => Math.floor(window.innerHeight * 0.85);\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\nfunction clampSize({ width, height }: Size): Size {\n return { width: clamp(width, MIN_WIDTH, MAX_WIDTH), height: clamp(height, MIN_HEIGHT, maxHeightPx()) };\n}\n\nfunction parsePx(value: string | undefined, fallback: number): number {\n const px = /^\\s*(\\d+(?:\\.\\d+)?)px\\s*$/.exec(value ?? '');\n return px ? Number(px[1]) : fallback;\n}\n\nconst STORAGE_KEY_PREFIX = 'marketrix_widget_size_';\n\n// growX/growY: which way a corner grows the panel when the pointer moves in +x / +y.\nexport const RESIZE_CORNERS = {\n 'top-left': { growX: -1, growY: -1, cursor: 'nwse-resize' },\n 'top-right': { growX: 1, growY: -1, cursor: 'nesw-resize' },\n 'bottom-left': { growX: -1, growY: 1, cursor: 'nesw-resize' },\n 'bottom-right': { growX: 1, growY: 1, cursor: 'nwse-resize' },\n} as const;\n\nexport type ResizeCorner = keyof typeof RESIZE_CORNERS;\n\nfunction readStoredSize(storageKey: string): Size | null {\n try {\n const stored = JSON.parse(readLocal(storageKey) ?? 'null') as { width?: unknown; height?: unknown };\n if (typeof stored?.width !== 'number' || typeof stored?.height !== 'number') return null;\n return clampSize({ width: stored.width, height: stored.height });\n } catch (error) {\n console.debug('[useResize] Ignoring an unparseable stored size:', error);\n return null;\n }\n}\n\nexport function useResize(\n settingsWidth: string | undefined,\n settingsHeight: string | undefined,\n tenantScope: string,\n isPreviewMode: boolean,\n) {\n const storageKey = `${STORAGE_KEY_PREFIX}${tenantScope}`;\n const containerRef = useRef<HTMLDivElement>(null);\n\n const [dimensions, setDimensions] = useState<Size>(\n () =>\n readStoredSize(storageKey) ??\n clampSize({\n width: parsePx(settingsWidth, DEFAULT_SIZE.width),\n height: parsePx(settingsHeight, DEFAULT_SIZE.height),\n }),\n );\n\n const dimsRef = useRef<Size>(dimensions);\n dimsRef.current = dimensions;\n\n const handleResizeStart = useCallback(\n (corner: ResizeCorner) => (e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n if (isPreviewMode) return;\n\n const startX = e.clientX;\n const startY = e.clientY;\n const startW = dimsRef.current.width;\n const startH = dimsRef.current.height;\n const { growX, growY, cursor } = RESIZE_CORNERS[corner];\n\n if (containerRef.current) {\n containerRef.current.dataset.resizing = 'true';\n }\n\n const onMove = (moveEvent: MouseEvent) => {\n const next = clampSize({\n width: startW + (moveEvent.clientX - startX) * growX,\n height: startH + (moveEvent.clientY - startY) * growY,\n });\n dimsRef.current = next;\n\n // Direct DOM update — skip React re-renders during drag\n if (containerRef.current) {\n containerRef.current.style.width = `${next.width}px`;\n containerRef.current.style.height = `${next.height}px`;\n }\n };\n\n const onUp = () => {\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('mouseup', onUp);\n document.body.style.cursor = '';\n document.body.style.userSelect = '';\n\n if (containerRef.current) {\n delete containerRef.current.dataset.resizing;\n }\n\n setDimensions({ ...dimsRef.current });\n\n if (!isPreviewMode) {\n const { width, height } = dimsRef.current;\n writeLocal(storageKey, JSON.stringify({ width, height }));\n }\n };\n\n document.body.style.cursor = cursor;\n document.body.style.userSelect = 'none';\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onUp);\n },\n [isPreviewMode, storageKey],\n );\n\n return {\n widthPx: `${dimensions.width}px`,\n heightPx: `${dimensions.height}px`,\n onResizeStart: handleResizeStart,\n containerRef,\n };\n}\n","import React from 'react';\n\nimport MarketrixIcon from '../../assets/marketrix-icon.svg';\nimport { Avatar } from '../base/Avatar';\nimport { Flex } from '../base/Flex';\nimport { Icon } from '../base/Icon';\nimport { IconButton } from '../base/IconButton';\nimport { Stack } from '../base/Stack';\nimport { Text } from '../base/Text';\n\ninterface HeaderBarProps {\n title: string;\n subtitle?: string;\n onClose: () => void;\n controls?: React.ReactNode;\n}\n\nexport const HeaderBar: React.FC<HeaderBarProps> = ({ title, subtitle, onClose, controls }) => {\n return (\n <Flex\n align='center'\n justify='between'\n paddingX='lg'\n paddingY='md'\n border='bottom'\n shrink={false}\n elevation='section'\n >\n <Flex align='center' gap='md' minWidth='0' grow>\n <Avatar src={MarketrixIcon} alt='' size='md' rounded='theme' elevation='card' />\n <Stack minWidth='0'>\n <Text size='sm' weight='semibold' truncate leading='tight'>\n {title}\n </Text>\n {subtitle != null && (\n <Text as='p' size='xs' variant='muted' truncate>\n {subtitle}\n </Text>\n )}\n </Stack>\n </Flex>\n\n <Flex align='center' gap='2xs' shrink={false}>\n {controls}\n <IconButton size='sm' label='Close' onClick={onClose}>\n <Icon name='close' size={16} />\n </IconButton>\n </Flex>\n </Flex>\n );\n};\n","import { useEffect, useImperativeHandle, useRef, useState } from 'react';\n\nimport type { InstructionType } from '../sdk';\nimport {\n createScreenAccessRequestMessage,\n createScreenshareMessage,\n createSystemMessage,\n} from '../services/ChatService';\nimport {\n isScreenSharing as isScreenSharingActive,\n startScreenShare,\n stopScreenShare,\n} from '../services/ScreenShareService';\nimport type { ChatMessage } from '../types';\n\n/** Keeps a value readable from a callback that must not be re-created (the polling interval, mounted once). */\nfunction useLatest<T>(value: T): React.RefObject<T> {\n const ref = useRef(value);\n ref.current = value;\n return ref;\n}\n\nexport interface PendingMessage {\n content: string;\n mode?: InstructionType;\n alreadyAdded?: boolean;\n}\n\nexport interface UseScreenShareOptions {\n onScreenSharingChange?: (isSharing: boolean) => void;\n onStartScreenShareRef?: React.MutableRefObject<(() => void) | null>;\n onStopScreenShareRef?: React.MutableRefObject<(() => void) | null>;\n onAddMessage: (message: ChatMessage) => void;\n onUpdateMessage: (messageId: string, updates: Partial<ChatMessage>) => void;\n onRemoveMessage?: (messageId: string) => void;\n onSendMessage: (message: string, mode?: InstructionType, skipUserMessage?: boolean) => void;\n pendingMessage: PendingMessage | null;\n setPendingMessage: (message: PendingMessage | null) => void;\n}\n\nexport interface UseScreenShareReturn {\n isScreenSharing: boolean;\n isAwaitingScreenAccess: boolean;\n showScreenAccessDialog: boolean;\n handleScreenAccessDialogAllow: () => Promise<void>;\n handleScreenAccessDialogDismiss: () => void;\n handleScreenAccessRequestAllow: () => Promise<void>;\n handleScreenAccessRequestDeny: () => void;\n requestScreenAccess: (mode: InstructionType) => void;\n}\n\nexport function useScreenShare({\n onScreenSharingChange,\n onStartScreenShareRef,\n onStopScreenShareRef,\n onAddMessage,\n onUpdateMessage,\n onRemoveMessage,\n onSendMessage,\n pendingMessage,\n setPendingMessage,\n}: UseScreenShareOptions): UseScreenShareReturn {\n const [isScreenSharing, setIsScreenSharing] = useState(false);\n const [screenShareMessageId, setScreenShareMessageId] = useState<string | null>(null);\n const [screenAccessRequestMessageId, setScreenAccessRequestMessageId] = useState<string | null>(null);\n const [showScreenAccessDialog, setShowScreenAccessDialog] = useState(false);\n\n const wasSharingRef = useLatest(isScreenSharing);\n const screenShareMessageIdRef = useLatest(screenShareMessageId);\n const onScreenSharingChangeRef = useLatest(onScreenSharingChange);\n\n const announceStopped = (messageId: string | null) => {\n if (messageId) onRemoveMessage?.(messageId);\n onAddMessage(createSystemMessage('Stopped screenshare', 'show', 'user', 'stopped-sharing'));\n setScreenShareMessageId(null);\n };\n const announceStoppedRef = useLatest(announceStopped);\n\n // The user can end the share from the browser's own UI, which fires no event we can subscribe to.\n useEffect(() => {\n const checkScreenSharing = () => {\n const isSharing = isScreenSharingActive();\n const wasSharing = wasSharingRef.current;\n const currentMessageId = screenShareMessageIdRef.current;\n if (isSharing !== wasSharing) {\n wasSharingRef.current = isSharing;\n setIsScreenSharing(isSharing);\n onScreenSharingChangeRef.current?.(isSharing);\n }\n if (wasSharing && !isSharing && currentMessageId) {\n announceStoppedRef.current(currentMessageId);\n }\n };\n checkScreenSharing();\n const interval = setInterval(checkScreenSharing, 1000);\n return () => clearInterval(interval);\n }, []);\n\n const requestScreenAccess = (mode: InstructionType) => {\n if (screenAccessRequestMessageId) return;\n const screenAccessRequestMessage = createScreenAccessRequestMessage(mode);\n setScreenAccessRequestMessageId(screenAccessRequestMessage.id);\n onAddMessage(screenAccessRequestMessage);\n };\n\n const handleStartScreenShare = () => {\n setShowScreenAccessDialog(true);\n };\n\n const flushPendingMessage = () => {\n if (!pendingMessage) return;\n const message = pendingMessage;\n setPendingMessage(null);\n onSendMessage(message.content, message.mode, message.alreadyAdded);\n };\n\n const resolveAccessRequest = (screenShareStatus: 'allowed' | 'denied') => {\n if (!screenAccessRequestMessageId) return;\n onUpdateMessage(screenAccessRequestMessageId, { screenShareStatus });\n setScreenAccessRequestMessageId(null);\n };\n\n const beginScreenShare = async () => {\n try {\n const stream = await startScreenShare();\n setIsScreenSharing(true);\n onScreenSharingChange?.(true);\n resolveAccessRequest('allowed');\n onAddMessage(createSystemMessage('Started screenshare', 'show', 'user', 'started-screenshare'));\n const screenshareMessage = createScreenshareMessage(stream, 'show');\n setScreenShareMessageId(screenshareMessage.id);\n onAddMessage(screenshareMessage);\n } catch (error) {\n console.error('Failed to start screen sharing:', error);\n setIsScreenSharing(false);\n onScreenSharingChange?.(false);\n resolveAccessRequest('denied');\n }\n flushPendingMessage();\n };\n\n const handleScreenAccessRequestAllow = beginScreenShare;\n\n const handleScreenAccessRequestDeny = () => {\n resolveAccessRequest('denied');\n flushPendingMessage();\n };\n\n const handleScreenAccessDialogAllow = async () => {\n setShowScreenAccessDialog(false);\n await beginScreenShare();\n };\n\n const handleScreenAccessDialogDismiss = () => {\n setShowScreenAccessDialog(false);\n };\n\n const stopScreenSharing = () => {\n stopScreenShare();\n setIsScreenSharing(false);\n onScreenSharingChange?.(false);\n announceStopped(screenShareMessageId);\n };\n\n useImperativeHandle(onStartScreenShareRef, () => handleStartScreenShare);\n useImperativeHandle(onStopScreenShareRef, () => stopScreenSharing);\n\n return {\n isScreenSharing,\n isAwaitingScreenAccess: screenAccessRequestMessageId !== null,\n showScreenAccessDialog,\n handleScreenAccessDialogAllow,\n handleScreenAccessDialogDismiss,\n handleScreenAccessRequestAllow,\n handleScreenAccessRequestDeny,\n requestScreenAccess,\n };\n}\n","import React, { useCallback, useEffect, useRef } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { radiusClasses } from '../../design-system/component-tokens';\nimport type { InstructionType } from '../../types';\nimport { Flex } from '../base/Flex';\nimport { Icon } from '../base/Icon';\nimport { IconButton } from '../base/IconButton';\nimport type { IconName } from '../base/icons';\nimport { Stack } from '../base/Stack';\nimport { Text } from '../base/Text';\n\nexport interface ChatInputMode {\n id: InstructionType;\n icon: IconName;\n label: string;\n}\n\nexport interface ChatInputProps {\n value: string;\n onChange: (value: string) => void;\n onSubmit: () => void;\n modes?: ChatInputMode[];\n activeMode?: InstructionType;\n onModeChange?: (mode: InstructionType) => void;\n disabled?: boolean;\n taskRunning?: boolean;\n onStop?: () => void;\n ref?: React.Ref<HTMLTextAreaElement>;\n}\n\nconst MAX_TEXTAREA_HEIGHT = 66; // 3 lines (20px each) + 6px padding\n\nfunction mergeRefs<T>(...refs: (React.Ref<T> | undefined)[]) {\n return (el: T | null) => {\n refs.forEach(r => {\n if (typeof r === 'function') r(el);\n else if (r) (r as React.MutableRefObject<T | null>).current = el;\n });\n };\n}\n\nexport function ChatInput({\n value,\n onChange,\n onSubmit,\n modes = [],\n activeMode,\n onModeChange,\n disabled = false,\n taskRunning = false,\n onStop,\n ref,\n}: ChatInputProps) {\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n useEffect(() => {\n const textarea = textareaRef.current;\n if (!textarea) return;\n textarea.style.height = 'auto';\n const { scrollHeight } = textarea;\n textarea.style.height = `${Math.min(scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n textarea.style.overflowY = scrollHeight > MAX_TEXTAREA_HEIGHT ? 'auto' : 'hidden';\n }, [value]);\n\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n onSubmit();\n }\n },\n [onSubmit],\n );\n\n const canSend = Boolean(value.trim()) && !disabled;\n\n return (\n <Stack\n background='card'\n rounded='xl'\n border\n overflow='hidden'\n className='focus-within:border-foreground-faint transition-colors'\n >\n <textarea\n ref={mergeRefs(textareaRef, ref)}\n value={value}\n onChange={e => onChange(e.target.value)}\n onKeyDown={handleKeyDown}\n placeholder='Ask anything'\n disabled={disabled}\n rows={1}\n className='block w-full min-h-0 resize-none rounded-none border-none bg-transparent px-3 text-sm text-foreground transition-colors placeholder:text-foreground-faint focus:ring-0 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50'\n style={{\n lineHeight: '20px',\n paddingTop: '4px',\n paddingBottom: '2px',\n minHeight: 'unset',\n }}\n />\n <Flex align='center' justify='between' paddingX='sm' paddingTop='xs' paddingBottom='sm'>\n <Flex align='center' gap='xs'>\n {modes.map(mode => {\n const isActive = activeMode === mode.id;\n return (\n <button\n key={mode.id}\n type='button'\n className={cn(\n 'inline-flex cursor-pointer items-center gap-0.5 border-none px-2 py-0.5 text-[11px] font-medium transition-all duration-200',\n radiusClasses.pill,\n isActive ? 'bg-primary text-primary-foreground shadow-sm' : 'bg-secondary-bg text-foreground-muted',\n )}\n onClick={e => {\n e.preventDefault();\n e.stopPropagation();\n onModeChange?.(mode.id);\n }}\n >\n <Icon name={mode.icon} size={12} />\n <Text as='span' inheritColor>\n {mode.label}\n </Text>\n </button>\n );\n })}\n </Flex>\n <IconButton\n variant={taskRunning ? 'secondary' : 'primary'}\n size='sm'\n disabled={!taskRunning && !canSend}\n label={taskRunning ? 'Stop the assistant' : 'Send message'}\n onClick={e => {\n e.preventDefault();\n e.stopPropagation();\n if (taskRunning && onStop) {\n onStop();\n } else {\n onSubmit();\n }\n }}\n >\n {taskRunning ? <Icon name='stop' size={14} /> : <Icon name='send' size={16} />}\n </IconButton>\n </Flex>\n </Stack>\n );\n}\n","'use client';\n\nimport _formatErrorMessage from \"@base-ui/utils/formatErrorMessage\";\nimport * as React from 'react';\nexport const DialogRootContext = /*#__PURE__*/React.createContext(undefined);\nif (process.env.NODE_ENV !== \"production\") DialogRootContext.displayName = \"DialogRootContext\";\nexport function useDialogRootContext(optional) {\n const store = React.useContext(DialogRootContext);\n if (!optional && store === undefined) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'Base UI: DialogRootContext is missing. Dialog parts must be placed within <Dialog.Root>.' : _formatErrorMessage(27));\n }\n return store;\n}","export let TransitionStatusDataAttributes = /*#__PURE__*/function (TransitionStatusDataAttributes) {\n /**\n * Present when the component begins animating in.\n */\n TransitionStatusDataAttributes[\"startingStyle\"] = \"data-starting-style\";\n /**\n * Present when the component is animating out.\n */\n TransitionStatusDataAttributes[\"endingStyle\"] = \"data-ending-style\";\n return TransitionStatusDataAttributes;\n}({});\nconst STARTING_HOOK = {\n 'data-starting-style': ''\n};\nconst ENDING_HOOK = {\n 'data-ending-style': ''\n};\nexport const transitionStatusMapping = {\n transitionStatus(value) {\n if (value === 'starting') {\n return STARTING_HOOK;\n }\n if (value === 'ending') {\n return ENDING_HOOK;\n }\n return null;\n }\n};","import { TransitionStatusDataAttributes, transitionStatusMapping } from \"../internals/stateAttributesMapping.mjs\";\nexport let CommonPopupDataAttributes = function (CommonPopupDataAttributes) {\n /**\n * Present when the popup is open.\n */\n CommonPopupDataAttributes[\"open\"] = \"data-open\";\n /**\n * Present when the popup is closed.\n */\n CommonPopupDataAttributes[\"closed\"] = \"data-closed\";\n /**\n * Present when the popup begins animating in.\n */\n CommonPopupDataAttributes[CommonPopupDataAttributes[\"startingStyle\"] = TransitionStatusDataAttributes.startingStyle] = \"startingStyle\";\n /**\n * Present when the popup is animating out.\n */\n CommonPopupDataAttributes[CommonPopupDataAttributes[\"endingStyle\"] = TransitionStatusDataAttributes.endingStyle] = \"endingStyle\";\n /**\n * Present when the anchor is hidden.\n */\n CommonPopupDataAttributes[\"anchorHidden\"] = \"data-anchor-hidden\";\n /**\n * Indicates which side the popup is positioned relative to the trigger.\n * @type { 'top' | 'bottom' | 'left' | 'right' | 'inline-end' | 'inline-start'}\n */\n CommonPopupDataAttributes[\"side\"] = \"data-side\";\n /**\n * Indicates how the popup is aligned relative to specified side.\n * @type {'start' | 'center' | 'end'}\n */\n CommonPopupDataAttributes[\"align\"] = \"data-align\";\n return CommonPopupDataAttributes;\n}({});\nexport let CommonTriggerDataAttributes = /*#__PURE__*/function (CommonTriggerDataAttributes) {\n /**\n * Present when the popup is open.\n */\n CommonTriggerDataAttributes[\"popupOpen\"] = \"data-popup-open\";\n /**\n * Present when a pressable trigger is pressed.\n */\n CommonTriggerDataAttributes[\"pressed\"] = \"data-pressed\";\n return CommonTriggerDataAttributes;\n}({});\n\n// Literal keys (instead of enum member references) keep the docs-only enums above\n// tree-shakeable: a runtime reference would retain the whole enum IIFE in every bundle.\nconst TRIGGER_HOOK = {\n 'data-popup-open': ''\n};\nconst PRESSABLE_TRIGGER_HOOK = {\n 'data-popup-open': '',\n 'data-pressed': ''\n};\nconst POPUP_OPEN_HOOK = {\n 'data-open': ''\n};\nconst POPUP_CLOSED_HOOK = {\n 'data-closed': ''\n};\nconst ANCHOR_HIDDEN_HOOK = {\n 'data-anchor-hidden': ''\n};\nexport const triggerOpenStateMapping = {\n open(value) {\n if (value) {\n return TRIGGER_HOOK;\n }\n return null;\n }\n};\nexport const pressableTriggerOpenStateMapping = {\n open(value) {\n if (value) {\n return PRESSABLE_TRIGGER_HOOK;\n }\n return null;\n }\n};\nexport const popupStateMapping = {\n open(value) {\n if (value) {\n return POPUP_OPEN_HOOK;\n }\n return POPUP_CLOSED_HOOK;\n },\n anchorHidden(value) {\n if (value) {\n return ANCHOR_HIDDEN_HOOK;\n }\n return null;\n }\n};\nexport const popupTransitionStateMapping = {\n ...popupStateMapping,\n ...transitionStatusMapping\n};","'use client';\n\nimport * as React from 'react';\nimport { useDialogRootContext } from \"../root/DialogRootContext.mjs\";\nimport { useRenderElement } from \"../../internals/useRenderElement.mjs\";\nimport { popupTransitionStateMapping } from \"../../utils/popupStateMapping.mjs\";\n\n/**\n * An overlay displayed beneath the popup.\n * Renders a `<div>` element.\n *\n * Documentation: [Base UI Dialog](https://base-ui.com/react/components/dialog)\n */\nexport const DialogBackdrop = /*#__PURE__*/React.forwardRef(function DialogBackdrop(componentProps, forwardedRef) {\n const {\n render,\n className,\n style,\n forceRender = false,\n ...elementProps\n } = componentProps;\n const store = useDialogRootContext();\n const open = store.useState('open');\n const nested = store.useState('nested');\n const mounted = store.useState('mounted');\n const transitionStatus = store.useState('transitionStatus');\n const state = {\n open,\n transitionStatus\n };\n return useRenderElement('div', componentProps, {\n state,\n ref: [store.context.backdropRef, forwardedRef],\n stateAttributesMapping: popupTransitionStateMapping,\n props: [{\n role: 'presentation',\n hidden: !mounted,\n style: {\n userSelect: 'none',\n WebkitUserSelect: 'none'\n }\n }, elementProps],\n enabled: forceRender || !nested\n });\n});\nif (process.env.NODE_ENV !== \"production\") DialogBackdrop.displayName = \"DialogBackdrop\";","export const none = 'none';\nexport const triggerPress = 'trigger-press';\nexport const triggerHover = 'trigger-hover';\nexport const triggerFocus = 'trigger-focus';\nexport const outsidePress = 'outside-press';\nexport const itemPress = 'item-press';\nexport const closePress = 'close-press';\nexport const linkPress = 'link-press';\nexport const clearPress = 'clear-press';\nexport const chipRemovePress = 'chip-remove-press';\nexport const trackPress = 'track-press';\nexport const incrementPress = 'increment-press';\nexport const decrementPress = 'decrement-press';\nexport const inputChange = 'input-change';\nexport const inputClear = 'input-clear';\nexport const inputBlur = 'input-blur';\nexport const inputPaste = 'input-paste';\nexport const inputPress = 'input-press';\nexport const focusOut = 'focus-out';\nexport const escapeKey = 'escape-key';\nexport const closeWatcher = 'close-watcher';\nexport const listNavigation = 'list-navigation';\nexport const keyboard = 'keyboard';\nexport const pointer = 'pointer';\nexport const drag = 'drag';\nexport const wheel = 'wheel';\nexport const scrub = 'scrub';\nexport const cancelOpen = 'cancel-open';\nexport const siblingOpen = 'sibling-open';\nexport const disabled = 'disabled';\nexport const missing = 'missing';\nexport const initial = 'initial';\nexport const imperativeAction = 'imperative-action';\nexport const swipe = 'swipe';\nexport const windowResize = 'window-resize';","import { EMPTY_OBJECT } from '@base-ui/utils/empty';\nimport { REASONS } from \"./reasons.mjs\";\n\n/**\n * Maps a change `reason` string to the corresponding native event type.\n */\n\n/**\n * Details of custom change events emitted by Base UI components.\n */\n\n/**\n * Details of custom generic events emitted by Base UI components.\n */\n\n/**\n * Creates a Base UI event details object with the given reason and utilities\n * for preventing Base UI's internal event handling.\n */\nexport function createChangeEventDetails(reason, event, trigger, customProperties) {\n let canceled = false;\n let allowPropagation = false;\n const custom = customProperties ?? EMPTY_OBJECT;\n const details = {\n reason,\n event: event ?? new Event('base-ui'),\n cancel() {\n canceled = true;\n },\n allowPropagation() {\n allowPropagation = true;\n },\n get isCanceled() {\n return canceled;\n },\n get isPropagationAllowed() {\n return allowPropagation;\n },\n trigger,\n ...custom\n };\n return details;\n}\nexport function createGenericEventDetails(reason, event, customProperties) {\n const custom = customProperties ?? EMPTY_OBJECT;\n const details = {\n reason,\n event: event ?? new Event('base-ui'),\n ...custom\n };\n return details;\n}","'use client';\n\nimport * as React from 'react';\nimport { SafeReact } from \"./safeReact.mjs\";\nlet globalId = 0;\n\n// TODO React 17: Remove `useGlobalId` once React 17 support is removed\nfunction useGlobalId(idOverride, prefix = 'mui') {\n const [defaultId, setDefaultId] = React.useState(idOverride);\n const id = idOverride || defaultId;\n React.useEffect(() => {\n if (defaultId == null) {\n // Fallback to this default id when possible.\n // Use the incrementing value for client-side rendering only.\n // We can't use it server-side.\n // If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem\n globalId += 1;\n setDefaultId(`${prefix}-${globalId}`);\n }\n }, [defaultId, prefix]);\n return id;\n}\nconst maybeReactUseId = SafeReact.useId;\n\n/**\n *\n * @example <div id={useId()} />\n * @param idOverride\n * @returns {string}\n */\nexport function useId(idOverride, prefix) {\n // React.useId() is only available from React 17.0.0.\n if (maybeReactUseId !== undefined) {\n const reactId = maybeReactUseId();\n return idOverride ?? (prefix ? `${prefix}-${reactId}` : reactId);\n }\n\n // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler\n // eslint-disable-next-line react-hooks/rules-of-hooks -- `React.useId` is invariant at runtime.\n return useGlobalId(idOverride, prefix);\n}","'use client';\n\nimport { useId } from '@base-ui/utils/useId';\n\n/**\n * Wraps `useId` and prefixes generated `id`s with `base-ui-`\n * @param {string | undefined} idOverride overrides the generated id when provided\n * @returns {string | undefined}\n */\nexport function useBaseUiId(idOverride) {\n return useId(idOverride, 'base-ui');\n}","'use client';\n\nimport * as React from 'react';\nimport { useDialogRootContext } from \"../root/DialogRootContext.mjs\";\nimport { useRenderElement } from \"../../internals/useRenderElement.mjs\";\nimport { useBaseUiId } from \"../../internals/useBaseUiId.mjs\";\n/**\n * A paragraph with additional information about the dialog.\n * Renders a `<p>` element.\n *\n * Documentation: [Base UI Dialog](https://base-ui.com/react/components/dialog)\n */\nexport const DialogDescription = /*#__PURE__*/React.forwardRef(function DialogDescription(componentProps, forwardedRef) {\n const {\n render,\n className,\n style,\n id: idProp,\n ...elementProps\n } = componentProps;\n const store = useDialogRootContext();\n const id = useBaseUiId(idProp);\n store.useSyncedValueWithCleanup('descriptionElementId', id);\n return useRenderElement('p', componentProps, {\n ref: forwardedRef,\n props: [{\n id\n }, elementProps]\n });\n});\nif (process.env.NODE_ENV !== \"production\") DialogDescription.displayName = \"DialogDescription\";","'use client';\n\nimport * as React from 'react';\nimport { EMPTY_ARRAY } from \"./empty.mjs\";\n\n/**\n * A React.useEffect equivalent that runs once, when the component is mounted.\n */\nexport function useOnMount(fn) {\n // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler -- no need to put `fn` in the dependency array\n /* eslint-disable react-hooks/exhaustive-deps */\n React.useEffect(fn, EMPTY_ARRAY);\n /* eslint-enable react-hooks/exhaustive-deps */\n}","'use client';\n\nimport { useRefWithInit } from \"./useRefWithInit.mjs\";\nimport { useOnMount } from \"./useOnMount.mjs\";\nconst EMPTY = 0;\nexport class Timeout {\n static create() {\n return new Timeout();\n }\n currentId = EMPTY;\n\n /**\n * Executes `fn` after `delay`, clearing any previously scheduled call.\n */\n start(delay, fn) {\n this.clear();\n this.currentId = setTimeout(() => {\n this.currentId = EMPTY;\n fn();\n }, delay); /* Node.js types are enabled in development */\n }\n isStarted() {\n return this.currentId !== EMPTY;\n }\n clear = () => {\n if (this.currentId !== EMPTY) {\n clearTimeout(this.currentId);\n this.currentId = EMPTY;\n }\n };\n disposeEffect = () => {\n return this.clear;\n };\n}\n\n/**\n * A `setTimeout` with automatic cleanup and guard.\n */\nexport function useTimeout() {\n const timeout = useRefWithInit(Timeout.create).current;\n useOnMount(timeout.disposeEffect);\n return timeout;\n}","/**\n * Reads `navigator.userAgent` / `navigator.platform` (legacy but universally\n * supported) into a normalized shape. In development, prefers the modern\n * `navigator.userAgentData` API on Chromium to avoid DevTools warnings about\n * the deprecated reads; that branch is dead-code-eliminated in production\n * builds to keep the bundle small.\n *\n * Returns empty/zero values when `navigator` is undefined (SSR), so every\n * derived flag safely evaluates to `false`.\n */\nfunction readRawData() {\n if (typeof navigator === 'undefined') {\n return {\n userAgent: '',\n platform: '',\n maxTouchPoints: 0\n };\n }\n if (process.env.NODE_ENV !== 'production') {\n const uaData = navigator.userAgentData;\n if (uaData && Array.isArray(uaData.brands)) {\n return {\n userAgent: uaData.brands.map(({\n brand,\n version\n }) => `${brand}/${version}`).join(' '),\n platform: uaData.platform ?? navigator.platform ?? '',\n maxTouchPoints: navigator.maxTouchPoints ?? 0\n };\n }\n }\n return {\n userAgent: navigator.userAgent,\n platform: navigator.platform ?? '',\n maxTouchPoints: navigator.maxTouchPoints ?? 0\n };\n}\nconst {\n userAgent,\n platform,\n maxTouchPoints\n} = readRawData();\nexport const lowerUserAgent = userAgent.toLowerCase();\nexport const lowerPlatform = platform.toLowerCase();\nexport { maxTouchPoints };","import { lowerUserAgent, lowerPlatform, maxTouchPoints } from \"./shared.mjs\";\n\n// iPadOS 13+ reports `MacIntel` for `navigator.platform`; disambiguated via\n// `maxTouchPoints` so iPad is classified as iOS, not macOS.\n// https://github.com/mui/base-ui/issues/1309\n/** iPhone, iPad (including iPadOS 13+ reporting as macOS), iPod. */\nexport const ios = /^i(os$|p)/.test(lowerPlatform) || lowerPlatform === 'macintel' && maxTouchPoints > 1;\n\n/** Android phones, tablets, and embedded Android browsers. */\nconst ANDROID_STRING = 'android';\nexport const android = lowerPlatform === ANDROID_STRING || lowerUserAgent.includes(ANDROID_STRING);\n\n/** macOS desktop. Excludes iPadOS, which reports as `MacIntel`. */\nexport const mac = !ios && lowerPlatform.startsWith('mac');\n\n/** Windows desktop. */\nexport const windows = lowerPlatform.startsWith('win');\n\n/** Linux desktop (including Chrome OS). */\nexport const linux = !android && /^(linux|chrome os)/.test(lowerPlatform);\n\n/** Any Apple OS (`mac || ios`). */\nexport const apple = mac || ios;","import { lowerUserAgent } from \"./shared.mjs\";\n\n// WebKit (Safari, all iOS browsers, GNOME Web). Distinguished from Blink by\n// the legacy `-webkit-backdrop-filter` name — Blink forked from WebKit in 2013\n// and only ships the unprefixed `backdrop-filter`.\n/** WebKit: Safari, all iOS browsers, GNOME Web. Excludes Blink. */\nexport const webkit = typeof CSS !== 'undefined' && !!CSS.supports?.('-webkit-backdrop-filter:none');\n\n// Anchored to `!webkit` so engines are mutually exclusive by construction.\n// Firefox-on-iOS uses WebKit (its UA marker is `FxiOS/`, not `Firefox/`); the\n// `!webkit` prefix also defends against future iOS-browser UA changes that\n// might inject `Firefox` into a WebKit-based UA.\n/** Gecko: Firefox. */\nexport const gecko = !webkit && lowerUserAgent.includes('firefox');\n\n// All Chromium-based browsers ship `Chrome/` or `Chromium/` in their UA — both\n// share the `chrom` prefix, so a single substring check covers Chrome, Edge,\n// Opera, Brave, etc. Chrome-on-iOS uses `CriOS/` and stays WebKit. The positive\n// UA check also makes this SSR-safe — an empty UA matches nothing.\n/** Blink: Chrome, Edge, Opera, Brave, and other Chromium-based browsers. */\nexport const blink = !webkit && lowerUserAgent.includes('chrom');","import { apple } from \"./os.mjs\";\n\n// Whether a screen reader is *actually* running cannot be detected. These flags\n// identify platforms where a specific screen reader could be active. VoiceOver\n// is the system screen reader on Apple platforms and works with every browser\n// there, so the flag is purely an OS check; engine-specific quirks (e.g. the\n// NSAccessibility virtual-cursor focus path) should be gated at the call site.\n/**\n * The user *may* be using VoiceOver — actual activation is not detectable.\n * True on any Apple platform (macOS, iOS, iPadOS).\n */\nexport const voiceOver = apple;","import { lowerUserAgent } from \"./shared.mjs\";\n\n/** Running in jsdom or HappyDOM (used by unit tests). */\nexport const jsdom = /jsdom|happydom/.test(lowerUserAgent);","import { platform } from '@base-ui/utils/platform';\nexport function stopEvent(event) {\n event.preventDefault();\n event.stopPropagation();\n}\nexport function isReactEvent(event) {\n return 'nativeEvent' in event;\n}\n\n// License: https://github.com/adobe/react-spectrum/blob/main/packages/@react-aria/utils/src/isVirtualEvent.ts\nexport function isVirtualClick(event) {\n if (event.pointerType === '' && event.isTrusted) {\n return true;\n }\n if (platform.os.android && event.pointerType) {\n return event.type === 'click' && event.buttons === 1;\n }\n return event.detail === 0 && !event.pointerType;\n}\nexport function isVirtualPointerEvent(event) {\n if (platform.env.jsdom) {\n return false;\n }\n return !platform.os.android && event.width === 0 && event.height === 0 || platform.os.android && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||\n // iOS VoiceOver returns 0.333• for width/height.\n event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'touch';\n}\nexport function isMouseLikePointerType(pointerType, strict) {\n // On some Linux machines with Chromium, mouse inputs return a `pointerType`\n // of \"pen\": https://github.com/floating-ui/floating-ui/issues/2015\n const values = ['mouse', 'pen'];\n if (!strict) {\n values.push('', undefined);\n }\n return values.includes(pointerType);\n}\nexport function isClickLikeEvent(event) {\n const type = event.type;\n return type === 'click' || type === 'mousedown' || type === 'keydown' || type === 'keyup';\n}","export const FOCUSABLE_ATTRIBUTE = 'data-base-ui-focusable';\nexport const ACTIVE_KEY = 'active';\nexport const SELECTED_KEY = 'selected';\nexport const TYPEABLE_SELECTOR = \"input:not([type='hidden']):not([disabled]),\" + \"[contenteditable]:not([contenteditable='false']),textarea:not([disabled])\";\nexport const ARROW_LEFT = 'ArrowLeft';\nexport const ARROW_RIGHT = 'ArrowRight';\nexport const ARROW_UP = 'ArrowUp';\nexport const ARROW_DOWN = 'ArrowDown';","import { isShadowRoot } from '@floating-ui/utils/dom';\nexport function activeElement(doc) {\n let element = doc.activeElement;\n while (element?.shadowRoot?.activeElement != null) {\n element = element.shadowRoot.activeElement;\n }\n return element;\n}\nexport function contains(parent, child) {\n if (!parent || !child) {\n return false;\n }\n const rootNode = child.getRootNode?.();\n\n // First, attempt with the faster native method.\n if (parent.contains(child)) {\n return true;\n }\n\n // Then fall back to traversing out of shadow roots when needed.\n if (rootNode && isShadowRoot(rootNode)) {\n let next = child;\n while (next) {\n if (parent === next) {\n return true;\n }\n next = next.parentNode || next.host;\n }\n }\n return false;\n}\nexport function getTarget(event) {\n if ('composedPath' in event) {\n return event.composedPath()[0];\n }\n\n // TS assumes `composedPath()` always exists, but older browsers without\n // shadow DOM support still fall back to `target`.\n return event.target;\n}","import { isElement, isHTMLElement } from '@floating-ui/utils/dom';\nimport { platform } from '@base-ui/utils/platform';\nimport { FOCUSABLE_ATTRIBUTE, TYPEABLE_SELECTOR } from \"./constants.mjs\";\nimport { activeElement, contains, getTarget } from \"../../internals/shadowDom.mjs\";\nexport { activeElement, contains, getTarget };\nexport function isTargetInsideEnabledTrigger(target, triggerElements) {\n if (!isElement(target)) {\n return false;\n }\n const targetElement = target;\n if (triggerElements.hasElement(targetElement)) {\n return !targetElement.hasAttribute('data-trigger-disabled');\n }\n for (const [, trigger] of triggerElements.entries()) {\n if (contains(trigger, targetElement)) {\n return !trigger.hasAttribute('data-trigger-disabled');\n }\n }\n return false;\n}\nexport function isEventTargetWithin(event, node) {\n if (node == null) {\n return false;\n }\n if ('composedPath' in event) {\n return event.composedPath().includes(node);\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't\n const eventAgain = event;\n return eventAgain.target != null && node.contains(eventAgain.target);\n}\nexport function isRootElement(element) {\n return element.matches('html,body');\n}\nexport function isTypeableElement(element) {\n return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);\n}\nexport function isInteractiveElement(element) {\n return element?.closest(`button,a[href],[role=\"button\"],select,[tabindex]:not([tabindex=\"-1\"]),${TYPEABLE_SELECTOR}`) != null;\n}\nexport function isTypeableCombobox(element) {\n if (!element) {\n return false;\n }\n return element.getAttribute('role') === 'combobox' && isTypeableElement(element);\n}\nexport function matchesFocusVisible(element) {\n // We don't want to block focus from working with `visibleOnly`\n // (JSDOM doesn't match `:focus-visible` when the element has `:focus`)\n if (!element || platform.env.jsdom) {\n return true;\n }\n try {\n return element.matches(':focus-visible');\n } catch (_e) {\n return true;\n }\n}\nexport function getFloatingFocusElement(floatingElement) {\n if (!floatingElement) {\n return null;\n }\n // Try to find the element that has `{...getFloatingProps()}` spread on it.\n // This indicates the floating element is acting as a positioning wrapper, and\n // so focus should be managed on the child element with the event handlers and\n // aria props.\n return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector(`[${FOCUSABLE_ATTRIBUTE}]`) || floatingElement;\n}","/**\n * Adds an event listener and returns a cleanup function to remove it.\n */\n\nexport function addEventListener(target, type, listener, options) {\n target.addEventListener(type, listener, options);\n return () => {\n target.removeEventListener(type, listener, options);\n };\n}","/**\n * Combines multiple cleanup functions into a single cleanup function.\n */\nexport function mergeCleanups(...cleanups) {\n return () => {\n for (let i = 0; i < cleanups.length; i += 1) {\n const cleanup = cleanups[i];\n if (cleanup) {\n cleanup();\n }\n }\n };\n}","'use client';\n\nimport { useIsoLayoutEffect } from \"./useIsoLayoutEffect.mjs\";\nimport { useRefWithInit } from \"./useRefWithInit.mjs\";\n\n/**\n * Untracks the provided value by turning it into a ref to remove its reactivity.\n *\n * Used to access the passed value inside `React.useEffect` without causing the effect to re-run when the value changes.\n */\nexport function useValueAsRef(value) {\n const latest = useRefWithInit(createLatestRef, value).current;\n latest.next = value;\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useIsoLayoutEffect(latest.effect);\n return latest;\n}\nfunction createLatestRef(value) {\n const latest = {\n current: value,\n next: value,\n effect: () => {\n latest.current = latest.next;\n }\n };\n return latest;\n}","'use client';\n\nimport { useRefWithInit } from \"./useRefWithInit.mjs\";\nimport { useOnMount } from \"./useOnMount.mjs\";\n/** Unlike `setTimeout`, rAF doesn't guarantee a positive integer return value, so we can't have\n * a monomorphic `uint` type with `0` meaning empty.\n * See warning note at:\n * https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame#return_value */\nconst EMPTY = null;\nlet LAST_RAF = globalThis.requestAnimationFrame;\nclass Scheduler {\n /* This implementation uses an array as a backing data-structure for frame callbacks.\n * It allows `O(1)` callback cancelling by inserting a `null` in the array, though it\n * never calls the native `cancelAnimationFrame` if there are no frames left. This can\n * be much more efficient if there is a call pattern that alterns as\n * \"request-cancel-request-cancel-…\".\n * But in the case of \"request-request-…-cancel-cancel-…\", it leaves the final animation\n * frame to run anyway. We turn that frame into a `O(1)` no-op via `callbacksCount`. */\n\n callbacks = [];\n callbacksCount = 0;\n nextId = 1;\n startId = 1;\n isScheduled = false;\n tick = timestamp => {\n this.isScheduled = false;\n const currentCallbacks = this.callbacks;\n const currentCallbacksCount = this.callbacksCount;\n\n // Update these before iterating, callbacks could call `requestAnimationFrame` again.\n this.callbacks = [];\n this.callbacksCount = 0;\n this.startId = this.nextId;\n if (currentCallbacksCount > 0) {\n for (let i = 0; i < currentCallbacks.length; i += 1) {\n currentCallbacks[i]?.(timestamp);\n }\n }\n };\n request(fn) {\n const id = this.nextId;\n this.nextId += 1;\n this.callbacks.push(fn);\n this.callbacksCount += 1;\n\n /* In a test environment with fake timers, a fake `requestAnimationFrame` can be called\n * but there's no guarantee that the animation frame will actually run before the fake\n * timers are teared, which leaves `isScheduled` set, but won't run our `tick()`. */\n const didRAFChange = process.env.NODE_ENV !== 'production' && LAST_RAF !== requestAnimationFrame && (LAST_RAF = requestAnimationFrame, true);\n if (!this.isScheduled || didRAFChange) {\n requestAnimationFrame(this.tick);\n this.isScheduled = true;\n }\n return id;\n }\n cancel(id) {\n const index = id - this.startId;\n if (index < 0 || index >= this.callbacks.length) {\n return;\n }\n this.callbacks[index] = null;\n this.callbacksCount -= 1;\n }\n}\nlet scheduler = new Scheduler();\n\n/**\n * Replaces the shared scheduler and drops all pending animation frame callbacks.\n *\n * For test environments only. The scheduler is process-global, so a callback scheduled in one test\n * but never run (e.g. requested under fake timers that were torn down before the frame fired) would\n * otherwise survive into a later test and run there against stale state. Call between tests to drop\n * such leftovers.\n */\nexport function resetAnimationFrameScheduler() {\n const previous = scheduler;\n scheduler = new Scheduler();\n // Continue the id sequence so `cancel()` calls from `AnimationFrame` instances created before the\n // reset cannot cancel callbacks scheduled after it.\n scheduler.nextId = previous.nextId;\n scheduler.startId = previous.nextId;\n // A frame requested before the reset may still be pending and holds the previous scheduler's\n // `tick`; empty its queue in place so that frame runs nothing when it eventually fires.\n previous.callbacks = [];\n previous.callbacksCount = 0;\n}\nexport class AnimationFrame {\n static create() {\n return new AnimationFrame();\n }\n static request(fn) {\n return scheduler.request(fn);\n }\n static cancel(id) {\n return scheduler.cancel(id);\n }\n currentId = EMPTY;\n\n /**\n * Executes `fn` after `delay`, clearing any previously scheduled call.\n */\n request(fn) {\n this.cancel();\n this.currentId = scheduler.request(() => {\n this.currentId = EMPTY;\n fn();\n });\n }\n cancel = () => {\n if (this.currentId !== EMPTY) {\n scheduler.cancel(this.currentId);\n this.currentId = EMPTY;\n }\n };\n disposeEffect = () => {\n return this.cancel;\n };\n}\n\n/**\n * A `requestAnimationFrame` with automatic cleanup and guard.\n */\nexport function useAnimationFrame() {\n const timeout = useRefWithInit(AnimationFrame.create).current;\n useOnMount(timeout.disposeEffect);\n return timeout;\n}","const visuallyHiddenBase = {\n clipPath: 'inset(50%)',\n overflow: 'hidden',\n whiteSpace: 'nowrap',\n border: 0,\n padding: 0,\n width: 1,\n height: 1,\n margin: -1\n};\nexport const visuallyHidden = {\n ...visuallyHiddenBase,\n position: 'fixed',\n top: 0,\n left: 0\n};\nexport const visuallyHiddenInput = {\n ...visuallyHiddenBase,\n position: 'absolute'\n};","'use client';\n\nimport * as React from 'react';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { platform } from '@base-ui/utils/platform';\nimport { visuallyHidden } from '@base-ui/utils/visuallyHidden';\n\n/**\n * @internal\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport const FocusGuard = /*#__PURE__*/React.forwardRef(function FocusGuard(props, ref) {\n const [role, setRole] = React.useState();\n useIsoLayoutEffect(() => {\n // Unlike NVDA and JAWS, VoiceOver's virtual cursor triggers `onFocus` as\n // it moves — but only on focusable/role-button elements through WebKit's\n // NSAccessibility path. Setting `role=\"button\"` lets the focus trap catch\n // the cursor.\n if (platform.screenReader.voiceOver && platform.engine.webkit) {\n setRole('button');\n }\n }, []);\n const restProps = {\n tabIndex: 0,\n // Role is only for VoiceOver\n role\n };\n return /*#__PURE__*/_jsx(\"span\", {\n ...props,\n ref: ref,\n style: visuallyHidden,\n \"aria-hidden\": role ? undefined : true,\n ...restProps,\n \"data-base-ui-focus-guard\": \"\"\n });\n});\nif (process.env.NODE_ENV !== \"production\") FocusGuard.displayName = \"FocusGuard\";","import { floor } from '@floating-ui/utils';\nimport { getComputedStyle } from '@floating-ui/utils/dom';\nimport { stopEvent } from \"./event.mjs\";\nimport { ARROW_DOWN, ARROW_LEFT, ARROW_RIGHT, ARROW_UP } from \"./constants.mjs\";\nexport function isDifferentGridRow(index, cols, prevRow) {\n return Math.floor(index / cols) !== prevRow;\n}\nexport function isIndexOutOfListBounds(list, index) {\n return index < 0 || index >= list.length;\n}\nexport function getMinListIndex(listRef, disabledIndices) {\n return findNonDisabledListIndex(listRef.current, {\n disabledIndices\n });\n}\nexport function getMaxListIndex(listRef, disabledIndices) {\n return findNonDisabledListIndex(listRef.current, {\n decrement: true,\n startingIndex: listRef.current.length,\n disabledIndices\n });\n}\nexport function findNonDisabledListIndex(list, {\n startingIndex = -1,\n decrement = false,\n disabledIndices,\n amount = 1\n} = {}) {\n let index = startingIndex;\n do {\n index += decrement ? -amount : amount;\n } while (index >= 0 && index <= list.length - 1 && isListIndexDisabled(list, index, disabledIndices));\n return index;\n}\nexport function getGridNavigatedIndex(list, {\n event,\n orientation,\n loopFocus,\n onLoop,\n rtl,\n cols,\n disabledIndices,\n minIndex,\n maxIndex,\n prevIndex,\n stopEvent: stop = false\n}) {\n let nextIndex = prevIndex;\n let verticalDirection;\n if (event.key === ARROW_UP) {\n verticalDirection = 'up';\n } else if (event.key === ARROW_DOWN) {\n verticalDirection = 'down';\n }\n if (verticalDirection) {\n // -------------------------------------------------------------------------\n // Detect row structure only when handling vertical navigation. This keeps\n // the non-vertical key paths free from row inference work.\n // -------------------------------------------------------------------------\n const rows = [];\n const rowIndexMap = [];\n let hasRoleRow = false;\n let visibleItemCount = 0;\n {\n let currentRowEl = null;\n let currentRowIndex = -1;\n list.forEach((el, idx) => {\n if (el == null) {\n return;\n }\n visibleItemCount += 1;\n const rowEl = el.closest('[role=\"row\"]');\n if (rowEl) {\n hasRoleRow = true;\n }\n if (rowEl !== currentRowEl || currentRowIndex === -1) {\n currentRowEl = rowEl;\n currentRowIndex += 1;\n rows[currentRowIndex] = [];\n }\n rows[currentRowIndex].push(idx);\n rowIndexMap[idx] = currentRowIndex;\n });\n }\n let hasDomRows = false;\n let inferredDomCols = 0;\n if (hasRoleRow) {\n for (const row of rows) {\n const rowLength = row.length;\n if (rowLength > inferredDomCols) {\n inferredDomCols = rowLength;\n }\n if (rowLength !== cols) {\n hasDomRows = true;\n }\n }\n }\n const hasVirtualizedGaps = hasDomRows && visibleItemCount < list.length;\n const verticalCols = inferredDomCols || cols;\n const navigateVertically = direction => {\n if (!hasDomRows || prevIndex === -1) {\n return undefined;\n }\n const currentRow = rowIndexMap[prevIndex];\n if (currentRow == null) {\n return undefined;\n }\n const colInRow = rows[currentRow].indexOf(prevIndex);\n const step = direction === 'up' ? -1 : 1;\n for (let nextRow = currentRow + step, i = 0; i < rows.length; i += 1, nextRow += step) {\n if (nextRow < 0 || nextRow >= rows.length) {\n if (!loopFocus || hasVirtualizedGaps) {\n return undefined;\n }\n nextRow = nextRow < 0 ? rows.length - 1 : 0;\n if (onLoop) {\n const clampedCol = Math.min(colInRow, rows[nextRow].length - 1);\n const targetItemIndex = rows[nextRow][clampedCol] ?? rows[nextRow][0];\n const returnedItemIndex = onLoop(event, prevIndex, targetItemIndex);\n nextRow = rowIndexMap[returnedItemIndex] ?? nextRow;\n }\n }\n const targetRow = rows[nextRow];\n for (let col = Math.min(colInRow, targetRow.length - 1); col >= 0; col -= 1) {\n const candidate = targetRow[col];\n if (!isListIndexDisabled(list, candidate, disabledIndices)) {\n return candidate;\n }\n }\n }\n return undefined;\n };\n const navigateVerticallyWithInferredRows = direction => {\n if (!hasVirtualizedGaps || prevIndex === -1) {\n return undefined;\n }\n const colInRow = prevIndex % verticalCols;\n const rowStep = direction === 'up' ? -verticalCols : verticalCols;\n const lastRowStart = maxIndex - maxIndex % verticalCols;\n const rowCount = floor(maxIndex / verticalCols) + 1;\n for (let rowStart = prevIndex - colInRow + rowStep, i = 0; i < rowCount; i += 1, rowStart += rowStep) {\n if (rowStart < 0 || rowStart > maxIndex) {\n if (!loopFocus) {\n return undefined;\n }\n rowStart = rowStart < 0 ? lastRowStart : 0;\n }\n const rowEnd = Math.min(rowStart + verticalCols - 1, maxIndex);\n for (let candidate = Math.min(rowStart + colInRow, rowEnd); candidate >= rowStart; candidate -= 1) {\n if (!isListIndexDisabled(list, candidate, disabledIndices)) {\n return candidate;\n }\n }\n }\n return undefined;\n };\n if (stop) {\n stopEvent(event);\n }\n const verticalCandidate = navigateVertically(verticalDirection) ?? navigateVerticallyWithInferredRows(verticalDirection);\n if (verticalCandidate !== undefined) {\n nextIndex = verticalCandidate;\n } else if (prevIndex === -1) {\n nextIndex = verticalDirection === 'up' ? maxIndex : minIndex;\n } else {\n nextIndex = findNonDisabledListIndex(list, {\n startingIndex: prevIndex,\n amount: verticalCols,\n decrement: verticalDirection === 'up',\n disabledIndices\n });\n if (loopFocus) {\n if (verticalDirection === 'up' && (prevIndex - verticalCols < minIndex || nextIndex < 0)) {\n const col = prevIndex % verticalCols;\n const maxCol = maxIndex % verticalCols;\n const offset = maxIndex - (maxCol - col);\n if (maxCol === col) {\n nextIndex = maxIndex;\n } else {\n nextIndex = maxCol > col ? offset : offset - verticalCols;\n }\n if (onLoop) {\n nextIndex = onLoop(event, prevIndex, nextIndex);\n }\n }\n if (verticalDirection === 'down' && prevIndex + verticalCols > maxIndex) {\n nextIndex = findNonDisabledListIndex(list, {\n startingIndex: prevIndex % verticalCols - verticalCols,\n amount: verticalCols,\n disabledIndices\n });\n if (onLoop) {\n nextIndex = onLoop(event, prevIndex, nextIndex);\n }\n }\n }\n }\n if (isIndexOutOfListBounds(list, nextIndex)) {\n nextIndex = prevIndex;\n }\n }\n\n // Remains on the same row/column.\n if (orientation === 'both') {\n const prevRow = floor(prevIndex / cols);\n if (event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT)) {\n if (stop) {\n stopEvent(event);\n }\n if (prevIndex % cols !== cols - 1) {\n nextIndex = findNonDisabledListIndex(list, {\n startingIndex: prevIndex,\n disabledIndices\n });\n if (loopFocus && isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = findNonDisabledListIndex(list, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n if (onLoop) {\n nextIndex = onLoop(event, prevIndex, nextIndex);\n }\n }\n } else if (loopFocus) {\n nextIndex = findNonDisabledListIndex(list, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n if (onLoop) {\n nextIndex = onLoop(event, prevIndex, nextIndex);\n }\n }\n if (isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = prevIndex;\n }\n }\n if (event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT)) {\n if (stop) {\n stopEvent(event);\n }\n if (prevIndex % cols !== 0) {\n nextIndex = findNonDisabledListIndex(list, {\n startingIndex: prevIndex,\n decrement: true,\n disabledIndices\n });\n if (loopFocus && isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = findNonDisabledListIndex(list, {\n startingIndex: prevIndex + (cols - prevIndex % cols),\n decrement: true,\n disabledIndices\n });\n if (onLoop) {\n nextIndex = onLoop(event, prevIndex, nextIndex);\n }\n }\n } else if (loopFocus) {\n nextIndex = findNonDisabledListIndex(list, {\n startingIndex: prevIndex + (cols - prevIndex % cols),\n decrement: true,\n disabledIndices\n });\n if (onLoop) {\n nextIndex = onLoop(event, prevIndex, nextIndex);\n }\n }\n if (isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = prevIndex;\n }\n }\n const lastRow = floor(maxIndex / cols) === prevRow;\n if (isIndexOutOfListBounds(list, nextIndex)) {\n if (loopFocus && lastRow) {\n nextIndex = event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT) ? maxIndex : findNonDisabledListIndex(list, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n if (onLoop) {\n nextIndex = onLoop(event, prevIndex, nextIndex);\n }\n } else {\n nextIndex = prevIndex;\n }\n }\n }\n return nextIndex;\n}\n\n/** For each cell index, gets the item index that occupies that cell */\nexport function createGridCellMap(sizes, cols, dense) {\n const cellMap = [];\n let startIndex = 0;\n sizes.forEach(({\n width,\n height\n }, index) => {\n if (width > cols) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: fix mui/no-guarded-throw\n // eslint-disable-next-line mui/no-guarded-throw\n throw new Error(`[Floating UI]: Invalid grid - item width at index ${index} is greater than grid columns`);\n }\n }\n let itemPlaced = false;\n if (dense) {\n startIndex = 0;\n }\n while (!itemPlaced) {\n const targetCells = [];\n for (let i = 0; i < width; i += 1) {\n for (let j = 0; j < height; j += 1) {\n targetCells.push(startIndex + i + j * cols);\n }\n }\n if (startIndex % cols + width <= cols && targetCells.every(cell => cellMap[cell] == null)) {\n targetCells.forEach(cell => {\n cellMap[cell] = index;\n });\n itemPlaced = true;\n } else {\n startIndex += 1;\n }\n }\n });\n\n // convert into a non-sparse array\n return [...cellMap];\n}\n\n/** Gets cell index of an item's corner or -1 when index is -1. */\nexport function getGridCellIndexOfCorner(index, sizes, cellMap, cols, corner) {\n if (index === -1) {\n return -1;\n }\n const firstCellIndex = cellMap.indexOf(index);\n const sizeItem = sizes[index];\n switch (corner) {\n case 'tl':\n return firstCellIndex;\n case 'tr':\n if (!sizeItem) {\n return firstCellIndex;\n }\n return firstCellIndex + sizeItem.width - 1;\n case 'bl':\n if (!sizeItem) {\n return firstCellIndex;\n }\n return firstCellIndex + (sizeItem.height - 1) * cols;\n case 'br':\n return cellMap.lastIndexOf(index);\n default:\n return -1;\n }\n}\n\n/** Gets all cell indices that correspond to the specified indices */\nexport function getGridCellIndices(indices, cellMap) {\n return cellMap.flatMap((index, cellIndex) => indices.includes(index) ? [cellIndex] : []);\n}\nexport function isListIndexDisabled(list, index, disabledIndices) {\n const isExplicitlyDisabled = typeof disabledIndices === 'function' ? disabledIndices(index) : disabledIndices?.includes(index) ?? false;\n if (isExplicitlyDisabled) {\n return true;\n }\n const element = list[index];\n if (!element) {\n return false;\n }\n if (!isElementVisible(element)) {\n return true;\n }\n\n // A natively disabled element can never receive focus, so it must always be\n // skipped, even when `disabledIndices` marks it as enabled. Only\n // `aria-disabled` items can be focusable-while-disabled.\n if (element.matches(':disabled')) {\n return true;\n }\n return !disabledIndices && (element.hasAttribute('disabled') || element.getAttribute('aria-disabled') === 'true');\n}\nexport function isHiddenByStyles(styles) {\n return styles.visibility === 'hidden' || styles.visibility === 'collapse';\n}\nexport function isElementVisible(element, styles = element ? getComputedStyle(element) : null) {\n if (!element || !element.isConnected || !styles || isHiddenByStyles(styles)) {\n return false;\n }\n if (typeof element.checkVisibility === 'function') {\n return element.checkVisibility();\n }\n return styles.display !== 'none' && styles.display !== 'contents';\n}","import { getComputedStyle, getNodeName, isHTMLElement, isShadowRoot } from '@floating-ui/utils/dom';\nimport { ownerDocument } from '@base-ui/utils/owner';\nimport { activeElement, contains } from \"./element.mjs\";\nimport { isElementVisible } from \"./composite.mjs\";\nconst CANDIDATE_SELECTOR = 'a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable=\"false\"]),audio[controls],video[controls]';\nfunction getParentElement(element) {\n const assignedSlot = element.assignedSlot;\n if (assignedSlot) {\n return assignedSlot;\n }\n if (element.parentElement) {\n return element.parentElement;\n }\n const rootNode = element.getRootNode();\n return isShadowRoot(rootNode) ? rootNode.host : null;\n}\nfunction getDetailsSummary(details) {\n for (const child of Array.from(details.children)) {\n if (getNodeName(child) === 'summary') {\n return child;\n }\n }\n return null;\n}\nfunction isWithinOpenDetailsSummary(element, details) {\n const summary = getDetailsSummary(details);\n return !!summary && (element === summary || contains(summary, element));\n}\nfunction isFocusableCandidate(element) {\n const nodeName = element ? getNodeName(element) : '';\n return element != null && element.matches(CANDIDATE_SELECTOR) && (nodeName !== 'summary' || element.parentElement != null && getNodeName(element.parentElement) === 'details' && getDetailsSummary(element.parentElement) === element) && (nodeName !== 'details' || getDetailsSummary(element) == null) && (nodeName !== 'input' || element.type !== 'hidden');\n}\nfunction isFocusableElement(element) {\n if (!isFocusableCandidate(element) || !element.isConnected || element.matches(':disabled')) {\n return false;\n }\n for (let current = element; current; current = getParentElement(current)) {\n const isAncestor = current !== element;\n const isSlot = getNodeName(current) === 'slot';\n if (current.hasAttribute('inert')) {\n return false;\n }\n if (isAncestor && getNodeName(current) === 'details' && !current.open && !isWithinOpenDetailsSummary(element, current) || current.hasAttribute('hidden') || !isSlot && !isVisibleInTabbableTree(current, isAncestor)) {\n return false;\n }\n }\n return true;\n}\nfunction isVisibleInTabbableTree(element, isAncestor) {\n const styles = getComputedStyle(element);\n if (!isAncestor) {\n return isElementVisible(element, styles);\n }\n return styles.display !== 'none';\n}\nfunction getTabIndex(element) {\n const tabIndex = element.tabIndex;\n if (tabIndex < 0) {\n const nodeName = getNodeName(element);\n if (nodeName === 'details' || nodeName === 'audio' || nodeName === 'video' || isHTMLElement(element) && element.isContentEditable) {\n return 0;\n }\n }\n return tabIndex;\n}\nfunction getNamedRadioInput(element) {\n if (getNodeName(element) !== 'input') {\n return null;\n }\n const input = element;\n return input.type === 'radio' && input.name !== '' ? input : null;\n}\nfunction isTabbableRadio(element, candidates) {\n const input = getNamedRadioInput(element);\n if (!input) {\n return true;\n }\n const checkedRadio = candidates.find(candidate => {\n const radio = getNamedRadioInput(candidate);\n return radio?.name === input.name && radio.form === input.form && radio.checked;\n });\n if (checkedRadio) {\n return checkedRadio === input;\n }\n return candidates.find(candidate => {\n const radio = getNamedRadioInput(candidate);\n return radio?.name === input.name && radio.form === input.form;\n }) === input;\n}\nfunction getComposedChildren(container) {\n if (isHTMLElement(container) && getNodeName(container) === 'slot') {\n const assignedElements = container.assignedElements({\n flatten: true\n });\n if (assignedElements.length > 0) {\n return assignedElements;\n }\n }\n if (isHTMLElement(container) && container.shadowRoot) {\n return Array.from(container.shadowRoot.children);\n }\n return Array.from(container.children);\n}\nfunction appendCandidates(container, list) {\n getComposedChildren(container).forEach(child => {\n if (isFocusableCandidate(child)) {\n list.push(child);\n }\n appendCandidates(child, list);\n });\n}\nfunction appendMatchingElements(container, selector, list) {\n getComposedChildren(container).forEach(child => {\n if (isHTMLElement(child) && child.matches(selector)) {\n list.push(child);\n }\n appendMatchingElements(child, selector, list);\n });\n}\nexport function isTabbable(element) {\n return isFocusableElement(element) && getTabIndex(element) >= 0;\n}\nexport function focusable(container) {\n const candidates = [];\n appendCandidates(container, candidates);\n return candidates.filter(isFocusableElement);\n}\nexport function tabbable(container) {\n const candidates = focusable(container);\n return candidates.filter(element => getTabIndex(element) >= 0 && isTabbableRadio(element, candidates));\n}\nfunction getTabbableIn(container, dir) {\n const list = tabbable(container);\n const len = list.length;\n if (len === 0) {\n return undefined;\n }\n const active = activeElement(ownerDocument(container));\n const index = list.indexOf(active);\n // eslint-disable-next-line no-nested-ternary\n const nextIndex = index === -1 ? dir === 1 ? 0 : len - 1 : index + dir;\n return list[nextIndex];\n}\nexport function getNextTabbable(referenceElement) {\n return getTabbableIn(ownerDocument(referenceElement).body, 1) || referenceElement;\n}\nexport function getPreviousTabbable(referenceElement) {\n return getTabbableIn(ownerDocument(referenceElement).body, -1) || referenceElement;\n}\nfunction getTabbableNearElement(referenceElement, dir) {\n if (!referenceElement) {\n return null;\n }\n const list = tabbable(ownerDocument(referenceElement).body);\n const elementCount = list.length;\n if (elementCount === 0) {\n return null;\n }\n const index = list.indexOf(referenceElement);\n if (index === -1) {\n return null;\n }\n const nextIndex = (index + dir + elementCount) % elementCount;\n return list[nextIndex];\n}\nexport function getTabbableAfterElement(referenceElement) {\n return getTabbableNearElement(referenceElement, 1);\n}\nexport function getTabbableBeforeElement(referenceElement) {\n return getTabbableNearElement(referenceElement, -1);\n}\nexport function isOutsideEvent(event, container) {\n const containerElement = container || event.currentTarget;\n const relatedTarget = event.relatedTarget;\n return !relatedTarget || !contains(containerElement, relatedTarget);\n}\nexport function disableFocusInside(container) {\n const tabbableElements = tabbable(container);\n tabbableElements.forEach(element => {\n element.dataset.tabindex = element.getAttribute('tabindex') || '';\n element.setAttribute('tabindex', '-1');\n });\n}\nexport function enableFocusInside(container) {\n const elements = [];\n appendMatchingElements(container, '[data-tabindex]', elements);\n elements.forEach(element => {\n const tabindex = element.dataset.tabindex;\n delete element.dataset.tabindex;\n if (tabindex) {\n element.setAttribute('tabindex', tabindex);\n } else {\n element.removeAttribute('tabindex');\n }\n });\n}","/* eslint-disable @typescript-eslint/no-loop-func */\n\nexport function getNodeChildren(nodes, id, onlyOpenChildren = true) {\n const directChildren = nodes.filter(node => node.parentId === id);\n return directChildren.flatMap(child => [...(!onlyOpenChildren || child.context?.open ? [child] : []), ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);\n}\nexport function getDeepestNode(nodes, id) {\n let deepestNodeId;\n let maxDepth = -1;\n function findDeepest(nodeId, depth) {\n if (depth > maxDepth) {\n deepestNodeId = nodeId;\n maxDepth = depth;\n }\n const children = getNodeChildren(nodes, nodeId);\n children.forEach(child => {\n findDeepest(child.id, depth + 1);\n });\n }\n findDeepest(id, 0);\n return nodes.find(node => node.id === deepestNodeId);\n}\nexport function getNodeAncestors(nodes, id) {\n let allAncestors = [];\n let currentParentId = nodes.find(node => node.id === id)?.parentId;\n while (currentParentId) {\n const currentNode = nodes.find(node => node.id === currentParentId);\n currentParentId = currentNode?.parentId;\n if (currentNode) {\n allAncestors = allAncestors.concat(currentNode);\n }\n }\n return allAncestors;\n}","export function createAttribute(name) {\n return `data-base-ui-${name}`;\n}","import { NOOP } from '@base-ui/utils/empty';\nlet rafId = 0;\nexport function enqueueFocus(el, options = {}) {\n const {\n preventScroll = false,\n sync = false,\n shouldFocus\n } = options;\n cancelAnimationFrame(rafId);\n function exec() {\n if (shouldFocus && !shouldFocus()) {\n return;\n }\n el?.focus({\n preventScroll\n });\n }\n if (sync) {\n exec();\n return NOOP;\n }\n const currentRafId = requestAnimationFrame(exec);\n rafId = currentRafId;\n return () => {\n if (rafId === currentRafId) {\n cancelAnimationFrame(currentRafId);\n rafId = 0;\n }\n };\n}","// Modified to add conditional `aria-hidden` support:\n// https://github.com/theKashey/aria-hidden/blob/9220c8f4a4fd35f63bee5510a9f41a37264382d4/src/index.ts\nimport { getNodeName, isShadowRoot } from '@floating-ui/utils/dom';\nimport { ownerDocument } from '@base-ui/utils/owner';\nconst counters = {\n inert: new WeakMap(),\n 'aria-hidden': new WeakMap()\n};\nconst markerName = 'data-base-ui-inert';\nconst uncontrolledElementsSets = {\n inert: new WeakSet(),\n 'aria-hidden': new WeakSet()\n};\nlet markerCounterMap = new WeakMap();\nlet lockCount = 0;\nfunction getUncontrolledElementsSet(controlAttribute) {\n return uncontrolledElementsSets[controlAttribute];\n}\nfunction unwrapHost(node) {\n if (!node) {\n return null;\n }\n return isShadowRoot(node) ? node.host : unwrapHost(node.parentNode);\n}\nconst correctElements = (parent, targets) => targets.map(target => {\n if (parent.contains(target)) {\n return target;\n }\n const correctedTarget = unwrapHost(target);\n if (parent.contains(correctedTarget)) {\n return correctedTarget;\n }\n return null;\n}).filter(x => x != null);\nconst buildKeepSet = targets => {\n const keep = new Set();\n targets.forEach(target => {\n let node = target;\n while (node && !keep.has(node)) {\n keep.add(node);\n node = node.parentNode;\n }\n });\n return keep;\n};\nconst collectOutsideElements = (root, keepElements, stopElements) => {\n const outside = [];\n const walk = parent => {\n if (!parent || stopElements.has(parent)) {\n return;\n }\n Array.from(parent.children).forEach(node => {\n if (getNodeName(node) === 'script') {\n return;\n }\n if (keepElements.has(node)) {\n walk(node);\n } else {\n outside.push(node);\n }\n });\n };\n walk(root);\n return outside;\n};\nfunction applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert, {\n mark = true\n}) {\n let controlAttribute = null;\n if (inert) {\n controlAttribute = 'inert';\n } else if (ariaHidden) {\n controlAttribute = 'aria-hidden';\n }\n let counterMap = null;\n let uncontrolledElementsSet = null;\n const avoidElements = correctElements(body, uncorrectedAvoidElements);\n const markerTargets = mark ? collectOutsideElements(body, buildKeepSet(avoidElements), new Set(avoidElements)) : [];\n const hiddenElements = [];\n const markedElements = [];\n if (controlAttribute) {\n const map = counters[controlAttribute];\n const currentUncontrolledElementsSet = getUncontrolledElementsSet(controlAttribute);\n uncontrolledElementsSet = currentUncontrolledElementsSet;\n counterMap = map;\n const ariaLiveElements = correctElements(body, Array.from(body.querySelectorAll('[aria-live]')));\n const controlElements = avoidElements.concat(ariaLiveElements);\n const controlTargets = collectOutsideElements(body, buildKeepSet(controlElements), new Set(controlElements));\n controlTargets.forEach(node => {\n const attr = node.getAttribute(controlAttribute);\n const alreadyHidden = attr !== null && attr !== 'false';\n const counterValue = (map.get(node) || 0) + 1;\n map.set(node, counterValue);\n hiddenElements.push(node);\n if (counterValue === 1 && alreadyHidden) {\n currentUncontrolledElementsSet.add(node);\n }\n if (!alreadyHidden) {\n node.setAttribute(controlAttribute, controlAttribute === 'inert' ? '' : 'true');\n }\n });\n }\n if (mark) {\n markerTargets.forEach(node => {\n const markerValue = (markerCounterMap.get(node) || 0) + 1;\n markerCounterMap.set(node, markerValue);\n markedElements.push(node);\n if (markerValue === 1) {\n node.setAttribute(markerName, '');\n }\n });\n }\n lockCount += 1;\n return () => {\n if (counterMap) {\n hiddenElements.forEach(element => {\n const currentCounterValue = counterMap.get(element) || 0;\n const counterValue = currentCounterValue - 1;\n counterMap.set(element, counterValue);\n if (!counterValue) {\n if (!uncontrolledElementsSet?.has(element) && controlAttribute) {\n element.removeAttribute(controlAttribute);\n }\n uncontrolledElementsSet?.delete(element);\n }\n });\n }\n if (mark) {\n markedElements.forEach(element => {\n const markerValue = (markerCounterMap.get(element) || 0) - 1;\n markerCounterMap.set(element, markerValue);\n if (!markerValue) {\n element.removeAttribute(markerName);\n }\n });\n }\n lockCount -= 1;\n if (!lockCount) {\n counters.inert = new WeakMap();\n counters['aria-hidden'] = new WeakMap();\n uncontrolledElementsSets.inert = new WeakSet();\n uncontrolledElementsSets['aria-hidden'] = new WeakSet();\n markerCounterMap = new WeakMap();\n }\n };\n}\nexport function markOthers(avoidElements, options = {}) {\n const {\n ariaHidden = false,\n inert = false,\n mark = true\n } = options;\n const body = ownerDocument(avoidElements[0]).body;\n return applyAttributeToOthers(avoidElements, body, ariaHidden, inert, {\n mark\n });\n}","export const TYPEAHEAD_RESET_MS = 500;\nexport const PATIENT_CLICK_THRESHOLD = 500;\nexport const DISABLED_TRANSITIONS_STYLE = {\n style: {\n transition: 'none'\n }\n};\nexport const CLICK_TRIGGER_IDENTIFIER = 'data-base-ui-click-trigger';\nexport const BASE_UI_SWIPE_IGNORE_ATTRIBUTE = 'data-base-ui-swipe-ignore';\nexport const LEGACY_SWIPE_IGNORE_ATTRIBUTE = 'data-swipe-ignore';\nexport const BASE_UI_SWIPE_IGNORE_SELECTOR = `[${BASE_UI_SWIPE_IGNORE_ATTRIBUTE}]`;\nexport const LEGACY_SWIPE_IGNORE_SELECTOR = `[${LEGACY_SWIPE_IGNORE_ATTRIBUTE}]`;\n\n/**\n * Used for dropdowns that usually strictly prefer top/bottom placements and\n * use `var(--available-height)` to limit their height.\n */\nexport const DROPDOWN_COLLISION_AVOIDANCE = {\n fallbackAxisSide: 'none'\n};\n\n/**\n * Used by regular popups that usually aren't scrollable and are allowed to\n * freely flip to any axis of placement.\n */\nexport const POPUP_COLLISION_AVOIDANCE = {\n fallbackAxisSide: 'end'\n};\n\n/**\n * Special visually hidden styles for the aria-owns owner element to ensure owned element\n * accessibility in iOS/Safari/VoiceControl.\n * The owner element is an empty span, so most of the common visually hidden styles are not needed.\n * @see https://github.com/floating-ui/floating-ui/issues/3403\n */\nexport const ownerVisuallyHidden = {\n clipPath: 'inset(50%)',\n position: 'fixed',\n top: 0,\n left: 0\n};","'use client';\n\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { isNode } from '@floating-ui/utils/dom';\nimport { addEventListener } from '@base-ui/utils/addEventListener';\nimport { mergeCleanups } from '@base-ui/utils/mergeCleanups';\nimport { useId } from '@base-ui/utils/useId';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { EMPTY_OBJECT } from '@base-ui/utils/empty';\nimport { FocusGuard } from \"../../utils/FocusGuard.mjs\";\nimport { enableFocusInside, disableFocusInside, getPreviousTabbable, getNextTabbable, isOutsideEvent } from \"../utils/tabbable.mjs\";\nimport { createChangeEventDetails } from \"../../internals/createBaseUIEventDetails.mjs\";\nimport { REASONS } from \"../../internals/reasons.mjs\";\nimport { createAttribute } from \"../utils/createAttribute.mjs\";\nimport { useRenderElement } from \"../../internals/useRenderElement.mjs\";\nimport { ownerVisuallyHidden } from \"../../internals/constants.mjs\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nconst PortalContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") PortalContext.displayName = \"PortalContext\";\nexport const usePortalContext = () => React.useContext(PortalContext);\nconst attr = createAttribute('portal');\nexport function useFloatingPortalNode(props = {}) {\n const {\n ref,\n container: containerProp,\n componentProps = EMPTY_OBJECT,\n elementProps\n } = props;\n const uniqueId = useId();\n const portalContext = usePortalContext();\n const parentPortalNode = portalContext?.portalNode;\n const [containerElement, setContainerElement] = React.useState(null);\n const [portalNode, setPortalNode] = React.useState(null);\n const setPortalNodeRef = useStableCallback(node => {\n if (node !== null) {\n // the useIsoLayoutEffect below watching containerProp / parentPortalNode\n // sets setPortalNode(null) when the container becomes null or changes.\n // So even though the ref callback now ignores null, the portal node still gets cleared.\n setPortalNode(node);\n }\n });\n const containerRef = React.useRef(null);\n useIsoLayoutEffect(() => {\n // Wait for the container to be resolved if explicitly `null`.\n if (containerProp === null) {\n if (containerRef.current) {\n containerRef.current = null;\n setPortalNode(null);\n setContainerElement(null);\n }\n return;\n }\n const resolvedContainer = (containerProp && (isNode(containerProp) ? containerProp : containerProp.current)) ?? parentPortalNode ?? document.body;\n if (resolvedContainer == null) {\n if (containerRef.current) {\n containerRef.current = null;\n setPortalNode(null);\n setContainerElement(null);\n }\n return;\n }\n if (containerRef.current !== resolvedContainer) {\n containerRef.current = resolvedContainer;\n setPortalNode(null);\n setContainerElement(resolvedContainer);\n }\n }, [containerProp, parentPortalNode]);\n const portalElement = useRenderElement('div', componentProps, {\n ref: [ref, setPortalNodeRef],\n props: [{\n id: uniqueId,\n [attr]: ''\n }, elementProps]\n });\n\n // This `createPortal` call injects `portalElement` into the `container`.\n // Another call inside `FloatingPortal`/`FloatingPortalLite` then injects the children into `portalElement`.\n const portalSubtree = containerElement && portalElement ? /*#__PURE__*/ReactDOM.createPortal(portalElement, containerElement) : null;\n return {\n node: portalNode,\n // `id` and `render` props can override or remove the generated ID. Use the exact\n // rendered value so `aria-owns` never points at an ID absent from the DOM.\n nodeId: /*#__PURE__*/React.isValidElement(portalElement) ? portalElement.props.id : undefined,\n subtree: portalSubtree\n };\n}\n\n/**\n * Portals the floating element into a given container element — by default,\n * outside of the app root and into the body.\n * This is necessary to ensure the floating element can appear outside any\n * potential parent containers that cause clipping (such as `overflow: hidden`),\n * while retaining its location in the React tree.\n * @see https://floating-ui.com/docs/FloatingPortal\n * @internal\n */\nexport const FloatingPortal = /*#__PURE__*/React.forwardRef(function FloatingPortal(componentProps, forwardedRef) {\n const {\n render,\n className,\n style,\n children,\n container,\n ...elementProps\n } = componentProps;\n const {\n node: portalNode,\n nodeId: portalNodeId,\n subtree: portalSubtree\n } = useFloatingPortalNode({\n container,\n ref: forwardedRef,\n componentProps,\n elementProps\n });\n const beforeOutsideRef = React.useRef(null);\n const afterOutsideRef = React.useRef(null);\n const beforeInsideRef = React.useRef(null);\n const afterInsideRef = React.useRef(null);\n const [focusManagerState, setFocusManagerState] = React.useState(null);\n const focusInsideDisabledRef = React.useRef(false);\n const modal = focusManagerState?.modal;\n const open = focusManagerState?.open;\n const shouldRenderGuards = !!focusManagerState && !focusManagerState.modal && focusManagerState.open && !!portalNode;\n\n // https://codesandbox.io/s/tabbable-portal-f4tng?file=/src/TabbablePortal.tsx\n React.useEffect(() => {\n if (!portalNode || modal) {\n return undefined;\n }\n\n // Make sure elements inside the portal element are tabbable only when the\n // portal has already been focused, either by tabbing into a focus trap\n // element outside or using the mouse.\n function onFocus(event) {\n if (portalNode && event.relatedTarget && isOutsideEvent(event)) {\n if (event.type === 'focusin') {\n if (focusInsideDisabledRef.current) {\n enableFocusInside(portalNode);\n focusInsideDisabledRef.current = false;\n }\n } else {\n disableFocusInside(portalNode);\n focusInsideDisabledRef.current = true;\n }\n }\n }\n\n // Listen to the event on the capture phase so they run before the focus\n // trap elements onFocus prop is called.\n return mergeCleanups(addEventListener(portalNode, 'focusin', onFocus, true), addEventListener(portalNode, 'focusout', onFocus, true));\n }, [portalNode, modal]);\n useIsoLayoutEffect(() => {\n if (!portalNode || open !== true || !focusInsideDisabledRef.current) {\n return;\n }\n\n // Restore tabbability before the focus manager's queued focus-on-open step runs.\n enableFocusInside(portalNode);\n focusInsideDisabledRef.current = false;\n }, [open, portalNode]);\n const portalContextValue = React.useMemo(() => ({\n beforeOutsideRef,\n afterOutsideRef,\n beforeInsideRef,\n afterInsideRef,\n portalNode,\n setFocusManagerState\n }), [portalNode]);\n return /*#__PURE__*/_jsxs(React.Fragment, {\n children: [portalSubtree, /*#__PURE__*/_jsxs(PortalContext.Provider, {\n value: portalContextValue,\n children: [shouldRenderGuards && portalNode && /*#__PURE__*/_jsx(FocusGuard, {\n \"data-type\": \"outside\",\n ref: beforeOutsideRef,\n onFocus: event => {\n if (isOutsideEvent(event, portalNode)) {\n beforeInsideRef.current?.focus();\n } else {\n const domReference = focusManagerState ? focusManagerState.domReference : null;\n const prevTabbable = getPreviousTabbable(domReference);\n prevTabbable?.focus();\n }\n }\n }), shouldRenderGuards && portalNode && /*#__PURE__*/_jsx(\"span\", {\n \"aria-owns\": portalNodeId,\n style: ownerVisuallyHidden\n }), portalNode && /*#__PURE__*/ReactDOM.createPortal(children, portalNode), shouldRenderGuards && portalNode && /*#__PURE__*/_jsx(FocusGuard, {\n \"data-type\": \"outside\",\n ref: afterOutsideRef,\n onFocus: event => {\n if (isOutsideEvent(event, portalNode)) {\n afterInsideRef.current?.focus();\n } else {\n const domReference = focusManagerState ? focusManagerState.domReference : null;\n const nextTabbable = getNextTabbable(domReference);\n nextTabbable?.focus();\n if (focusManagerState?.closeOnFocusOut) {\n focusManagerState?.onOpenChange(false, createChangeEventDetails(REASONS.focusOut, event.nativeEvent));\n }\n }\n }\n })]\n })]\n });\n});\nif (process.env.NODE_ENV !== \"production\") FloatingPortal.displayName = \"FloatingPortal\";","export function createEventEmitter() {\n const map = new Map();\n return {\n emit(event, data) {\n map.get(event)?.forEach(listener => listener(data));\n },\n on(event, listener) {\n if (!map.has(event)) {\n map.set(event, new Set());\n }\n map.get(event).add(listener);\n },\n off(event, listener) {\n map.get(event)?.delete(listener);\n }\n };\n}","'use client';\n\nimport * as React from 'react';\nimport { useId } from '@base-ui/utils/useId';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { useRefWithInit } from '@base-ui/utils/useRefWithInit';\nimport { FloatingTreeStore } from \"./FloatingTreeStore.mjs\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst FloatingNodeContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") FloatingNodeContext.displayName = \"FloatingNodeContext\";\nconst FloatingTreeContext = /*#__PURE__*/React.createContext(null);\n\n/**\n * Returns the parent node id for nested floating elements, if available.\n * Returns `null` for top-level floating elements.\n */\nif (process.env.NODE_ENV !== \"production\") FloatingTreeContext.displayName = \"FloatingTreeContext\";\nexport const useFloatingParentNodeId = () => React.useContext(FloatingNodeContext)?.id || null;\n\n/**\n * Returns the nearest floating tree context, if available.\n */\nexport const useFloatingTree = externalTree => {\n const contextTree = React.useContext(FloatingTreeContext);\n return externalTree ?? contextTree;\n};\n\n/**\n * Registers a node into the `FloatingTree`, returning its id.\n * @see https://floating-ui.com/docs/FloatingTree\n */\nexport function useFloatingNodeId(externalTree) {\n const id = useId();\n const tree = useFloatingTree(externalTree);\n const parentId = useFloatingParentNodeId();\n useIsoLayoutEffect(() => {\n if (!id) {\n return undefined;\n }\n const node = {\n id,\n parentId\n };\n tree?.addNode(node);\n return () => {\n tree?.removeNode(node);\n };\n }, [tree, id, parentId]);\n return id;\n}\n/**\n * Provides parent node context for nested floating elements.\n * @see https://floating-ui.com/docs/FloatingTree\n * @internal\n */\nexport function FloatingNode(props) {\n const {\n children,\n id\n } = props;\n const parentId = useFloatingParentNodeId();\n return /*#__PURE__*/_jsx(FloatingNodeContext.Provider, {\n value: React.useMemo(() => ({\n id,\n parentId\n }), [id, parentId]),\n children: children\n });\n}\n/**\n * Provides context for nested floating elements when they are not children of\n * each other on the DOM.\n * This is not necessary in all cases, except when there must be explicit communication between parent and child floating elements. It is necessary for:\n * - The `bubbles` option in the `useDismiss()` Hook\n * - Nested virtual list navigation\n * - Nested floating elements that each open on hover\n * - Custom communication between parent and child floating elements\n * @see https://floating-ui.com/docs/FloatingTree\n * @internal\n */\nexport function FloatingTree(props) {\n const {\n children,\n externalTree\n } = props;\n const tree = useRefWithInit(() => externalTree ?? new FloatingTreeStore()).current;\n return /*#__PURE__*/_jsx(FloatingTreeContext.Provider, {\n value: tree,\n children: children\n });\n}","/**\n * If the provided argument is a ref object, returns its `current` value.\n * Otherwise, returns the argument itself.\n */\nexport function resolveRef(maybeRef) {\n if (maybeRef == null) {\n return maybeRef;\n }\n return 'current' in maybeRef ? maybeRef.current : maybeRef;\n}","'use client';\n\nimport * as React from 'react';\nimport { getNodeName, isHTMLElement } from '@floating-ui/utils/dom';\nimport { addEventListener } from '@base-ui/utils/addEventListener';\nimport { mergeCleanups } from '@base-ui/utils/mergeCleanups';\nimport { useMergedRefs } from '@base-ui/utils/useMergedRefs';\nimport { useValueAsRef } from '@base-ui/utils/useValueAsRef';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { useTimeout } from '@base-ui/utils/useTimeout';\nimport { platform } from '@base-ui/utils/platform';\nimport { useAnimationFrame } from '@base-ui/utils/useAnimationFrame';\nimport { ownerDocument, ownerWindow } from '@base-ui/utils/owner';\nimport { FocusGuard } from \"../../utils/FocusGuard.mjs\";\nimport { activeElement, contains, getTarget, isTypeableCombobox, getFloatingFocusElement, isTypeableElement } from \"../utils/element.mjs\";\nimport { isVirtualClick, isVirtualPointerEvent, stopEvent } from \"../utils/event.mjs\";\nimport { tabbable, focusable, isOutsideEvent, isTabbable, getNextTabbable, getPreviousTabbable } from \"../utils/tabbable.mjs\";\nimport { getNodeAncestors, getNodeChildren } from \"../utils/nodes.mjs\";\nimport { isElementVisible } from \"../utils/composite.mjs\";\nimport { createChangeEventDetails } from \"../../internals/createBaseUIEventDetails.mjs\";\nimport { REASONS } from \"../../internals/reasons.mjs\";\nimport { createAttribute } from \"../utils/createAttribute.mjs\";\nimport { enqueueFocus } from \"../utils/enqueueFocus.mjs\";\nimport { markOthers } from \"../utils/markOthers.mjs\";\nimport { usePortalContext } from \"./FloatingPortal.mjs\";\nimport { useFloatingTree } from \"./FloatingTree.mjs\";\nimport { CLICK_TRIGGER_IDENTIFIER } from \"../../internals/constants.mjs\";\nimport { resolveRef } from \"../../utils/resolveRef.mjs\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nfunction getEventType(event, lastInteractionType) {\n const win = ownerWindow(getTarget(event));\n if (event instanceof win.KeyboardEvent) {\n return 'keyboard';\n }\n if (event instanceof win.FocusEvent) {\n // Focus events can be caused by a preceding pointer interaction (e.g., focusout on outside press).\n // Prefer the last known pointer type if provided, else treat as keyboard.\n return lastInteractionType || 'keyboard';\n }\n if ('pointerType' in event) {\n return event.pointerType || 'keyboard';\n }\n if ('touches' in event) {\n return 'touch';\n }\n if (event instanceof win.MouseEvent) {\n // onClick events may not contain pointer events, and will fall through to here\n return lastInteractionType || (event.detail === 0 ? 'keyboard' : 'mouse');\n }\n return '';\n}\nconst LIST_LIMIT = 20;\nlet previouslyFocusedElements = [];\nfunction clearDisconnectedPreviouslyFocusedElements() {\n previouslyFocusedElements = previouslyFocusedElements.filter(entry => {\n return entry.deref()?.isConnected;\n });\n}\nfunction addPreviouslyFocusedElement(element) {\n clearDisconnectedPreviouslyFocusedElements();\n if (element && getNodeName(element) !== 'body') {\n previouslyFocusedElements.push(new WeakRef(element));\n if (previouslyFocusedElements.length > LIST_LIMIT) {\n previouslyFocusedElements = previouslyFocusedElements.slice(-LIST_LIMIT);\n }\n }\n}\nfunction getPreviouslyFocusedElement() {\n clearDisconnectedPreviouslyFocusedElements();\n return previouslyFocusedElements[previouslyFocusedElements.length - 1]?.deref();\n}\nfunction getFirstTabbableElement(container) {\n if (!container) {\n return null;\n }\n if (isTabbable(container)) {\n return container;\n }\n return tabbable(container)[0] || container;\n}\nfunction handleTabIndex(floatingFocusElement) {\n if (floatingFocusElement.hasAttribute('tabindex') && !floatingFocusElement.hasAttribute('data-tabindex')) {\n return;\n }\n if (!floatingFocusElement.getAttribute('role')?.includes('dialog')) {\n return;\n }\n const focusableElements = focusable(floatingFocusElement);\n const tabbableContent = focusableElements.filter(element => {\n const dataTabIndex = element.getAttribute('data-tabindex') || '';\n return isTabbable(element) || element.hasAttribute('data-tabindex') && !dataTabIndex.startsWith('-');\n });\n const tabIndex = floatingFocusElement.getAttribute('tabindex');\n if (tabbableContent.length === 0) {\n if (tabIndex !== '0') {\n floatingFocusElement.setAttribute('tabindex', '0');\n // Mark our own write so the externally-managed early-return above doesn't\n // mistake it for a user-authored `tabindex` and freeze management.\n floatingFocusElement.setAttribute('data-tabindex', '0');\n }\n } else if (tabIndex !== '-1' || floatingFocusElement.hasAttribute('data-tabindex') && floatingFocusElement.getAttribute('data-tabindex') !== '-1') {\n floatingFocusElement.setAttribute('tabindex', '-1');\n floatingFocusElement.setAttribute('data-tabindex', '-1');\n }\n}\n/**\n * Provides focus management for the floating element.\n * @see https://floating-ui.com/docs/FloatingFocusManager\n * @internal\n */\nexport function FloatingFocusManager(props) {\n const {\n context,\n children,\n disabled = false,\n initialFocus = true,\n returnFocus = true,\n restoreFocus = false,\n modal = true,\n closeOnFocusOut = true,\n openInteractionType = '',\n nextFocusableElement,\n previousFocusableElement,\n beforeContentFocusGuardRef,\n externalTree,\n getInsideElements\n } = props;\n const store = 'rootStore' in context ? context.rootStore : context;\n const open = store.useState('open');\n const domReference = store.useState('domReferenceElement');\n const floating = store.useState('floatingElement');\n const {\n events,\n dataRef\n } = store.context;\n const getNodeId = useStableCallback(() => dataRef.current.floatingContext?.nodeId);\n const ignoreInitialFocus = initialFocus === false;\n // A typeable combobox reference (e.g. input/textarea) with `initialFocus={false}`\n // has different focus semantics: focus is not trapped inside the floating element,\n // so in the modal case the guards are not rendered, but `aria-hidden` is still\n // applied to the outside nodes.\n const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;\n const initialFocusRef = useValueAsRef(initialFocus);\n const returnFocusRef = useValueAsRef(returnFocus);\n const openInteractionTypeRef = useValueAsRef(openInteractionType);\n const openRef = useValueAsRef(open);\n const tree = useFloatingTree(externalTree);\n const portalContext = usePortalContext();\n const preventReturnFocusRef = React.useRef(false);\n const isPointerDownRef = React.useRef(false);\n const pointerDownOutsideRef = React.useRef(false);\n const lastFocusedTabbableRef = React.useRef(null);\n const closeTypeRef = React.useRef('');\n const lastInteractionTypeRef = React.useRef('');\n const beforeGuardRef = React.useRef(null);\n const afterGuardRef = React.useRef(null);\n const mergedBeforeGuardRef = useMergedRefs(beforeGuardRef, beforeContentFocusGuardRef, portalContext?.beforeInsideRef);\n const mergedAfterGuardRef = useMergedRefs(afterGuardRef, portalContext?.afterInsideRef);\n const blurTimeout = useTimeout();\n const pointerDownTimeout = useTimeout();\n const restoreFocusFrame = useAnimationFrame();\n const isInsidePortal = portalContext != null;\n const floatingFocusElement = getFloatingFocusElement(floating);\n const getTabbableContent = useStableCallback((container = floatingFocusElement) => {\n return container ? tabbable(container) : [];\n });\n const getResolvedInsideElements = useStableCallback(() => getInsideElements?.().filter(element => element != null) ?? []);\n\n // Prevent Tab from escaping the modal when there are no tabbable elements.\n React.useEffect(() => {\n if (disabled || !modal) {\n return undefined;\n }\n function onKeyDown(event) {\n if (event.key === 'Tab') {\n // The focus guards have nothing to focus, so we need to stop the event.\n if (contains(floatingFocusElement, activeElement(ownerDocument(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) {\n stopEvent(event);\n }\n }\n }\n const doc = ownerDocument(floatingFocusElement);\n return addEventListener(doc, 'keydown', onKeyDown);\n }, [disabled, floatingFocusElement, modal, isUntrappedTypeableCombobox, getTabbableContent]);\n\n // Track pointer/keyboard interactions to disambiguate focus and outside presses.\n React.useEffect(() => {\n if (disabled || !open) {\n return undefined;\n }\n const doc = ownerDocument(floatingFocusElement);\n function clearPointerDownOutside() {\n pointerDownOutsideRef.current = false;\n }\n function onPointerDown(event) {\n const target = getTarget(event);\n const insideElements = getResolvedInsideElements();\n const pointerTargetInside = contains(floating, target) || contains(domReference, target) || contains(portalContext?.portalNode, target) || insideElements.some(element => element === target || contains(element, target));\n pointerDownOutsideRef.current = !pointerTargetInside;\n lastInteractionTypeRef.current = event.pointerType || 'keyboard';\n if (target?.closest(`[${CLICK_TRIGGER_IDENTIFIER}]`)) {\n isPointerDownRef.current = true;\n // Reset on the next tick so a single click on a click-trigger doesn't\n // permanently suppress focus-out closing for the lifetime of the instance.\n pointerDownTimeout.start(0, () => {\n isPointerDownRef.current = false;\n });\n }\n }\n function onKeyDown() {\n lastInteractionTypeRef.current = 'keyboard';\n }\n return mergeCleanups(addEventListener(doc, 'pointerdown', onPointerDown, true), addEventListener(doc, 'pointerup', clearPointerDownOutside, true), addEventListener(doc, 'pointercancel', clearPointerDownOutside, true), addEventListener(doc, 'keydown', onKeyDown, true),\n // Avoid a stale `true` leaking into the next open (e.g. keep-mounted popups)\n // if the popup dismissed between pointerdown and pointerup.\n clearPointerDownOutside);\n }, [disabled, floating, domReference, floatingFocusElement, open, portalContext, pointerDownTimeout, getResolvedInsideElements]);\n\n // Close on focus out and restore focus within the floating tree when needed.\n React.useEffect(() => {\n if (disabled || !closeOnFocusOut) {\n return undefined;\n }\n const doc = ownerDocument(floatingFocusElement);\n\n // In Safari, buttons lose focus when pressing them.\n function handlePointerDown() {\n isPointerDownRef.current = true;\n pointerDownTimeout.start(0, () => {\n isPointerDownRef.current = false;\n });\n }\n function handleFocusIn(event) {\n const target = getTarget(event);\n if (isTabbable(target)) {\n lastFocusedTabbableRef.current = target;\n }\n }\n function handleFocusOutside(event) {\n const relatedTarget = event.relatedTarget;\n const currentTarget = event.currentTarget;\n const target = getTarget(event);\n\n // When focus is lost to the body (e.g. on a backdrop press), record the element that\n // had focus so a confirmation dialog opened while the body is focused can return focus\n // to it. Scoped to `modal` to avoid non-modal popups polluting the shared stack.\n if (modal && relatedTarget == null && target != null && contains(floating, target)) {\n addPreviouslyFocusedElement(target);\n }\n queueMicrotask(() => {\n const nodeId = getNodeId();\n const triggers = store.context.triggerElements;\n const insideElements = getResolvedInsideElements();\n const isRelatedFocusGuard = relatedTarget?.hasAttribute(createAttribute('focus-guard')) && [beforeGuardRef.current, afterGuardRef.current, portalContext?.beforeInsideRef.current, portalContext?.afterInsideRef.current, portalContext?.beforeOutsideRef.current, portalContext?.afterOutsideRef.current, resolveRef(previousFocusableElement), resolveRef(nextFocusableElement)].includes(relatedTarget);\n const movedToUnrelatedNode = !(contains(domReference, relatedTarget) || contains(floating, relatedTarget) || contains(relatedTarget, floating) || contains(portalContext?.portalNode, relatedTarget) || insideElements.some(element => element === relatedTarget || contains(element, relatedTarget)) || triggers.hasMatchingElement(trigger => contains(trigger, relatedTarget)) || isRelatedFocusGuard || tree && (getNodeChildren(tree.nodesRef.current, nodeId).find(node => contains(node.context?.elements.floating, relatedTarget) || contains(node.context?.elements.domReference, relatedTarget)) || getNodeAncestors(tree.nodesRef.current, nodeId).find(node => [node.context?.elements.floating, getFloatingFocusElement(node.context?.elements.floating)].includes(relatedTarget) || node.context?.elements.domReference === relatedTarget)));\n if (currentTarget === domReference && floatingFocusElement) {\n handleTabIndex(floatingFocusElement);\n }\n\n // Restore focus to the previously focused tabbable element to prevent\n // focus from being lost outside the floating tree.\n if (restoreFocus && currentTarget !== domReference && !isElementVisible(target) && activeElement(doc) === doc.body) {\n // Let `FloatingPortal` effect knows that focus is still inside the\n // floating tree.\n if (isHTMLElement(floatingFocusElement)) {\n floatingFocusElement.focus();\n // If explicitly requested to restore focus to the popup container, do not search\n // for the next/previous tabbable element.\n if (restoreFocus === 'popup') {\n // If the focused element is removed on pointerdown, the browser\n // tries to move focus to it right after the `.focus()` call above,\n // but because it's removed in the same tick, focus is lost instead.\n // Re-focusing asynchronously (next frame) wins that race.\n restoreFocusFrame.request(() => {\n floatingFocusElement.focus();\n });\n return;\n }\n }\n const tabbableContent = getTabbableContent();\n const prevTabbable = lastFocusedTabbableRef.current;\n const nodeToFocus = (prevTabbable && tabbableContent.includes(prevTabbable) ? prevTabbable : null) || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;\n if (isHTMLElement(nodeToFocus)) {\n nodeToFocus.focus();\n }\n }\n\n // https://github.com/floating-ui/floating-ui/issues/3060\n if (dataRef.current.insideReactTree) {\n dataRef.current.insideReactTree = false;\n return;\n }\n\n // Focus did not move inside the floating tree, and there are no tabbable\n // portal guards to handle closing.\n if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current && (\n // Fix React 18 Strict Mode returnFocus due to double rendering.\n // For an \"untrapped\" typeable combobox (input role=combobox with\n // initialFocus=false), re-opening the popup and tabbing out should still close it even\n // when the previously focused element (e.g. the next tabbable outside the popup) is\n // focused again. Otherwise, the popup remains open on the second Tab sequence:\n // click input -> Tab (closes) -> click input -> Tab.\n // Allow closing when `isUntrappedTypeableCombobox` regardless of the previously focused element.\n isUntrappedTypeableCombobox || relatedTarget !== getPreviouslyFocusedElement())) {\n preventReturnFocusRef.current = true;\n store.setOpen(false, createChangeEventDetails(REASONS.focusOut, event));\n }\n });\n }\n function markInsideReactTree() {\n if (pointerDownOutsideRef.current) {\n return;\n }\n dataRef.current.insideReactTree = true;\n blurTimeout.start(0, () => {\n dataRef.current.insideReactTree = false;\n });\n }\n const domReferenceElement = isHTMLElement(domReference) ? domReference : null;\n if (!floating && !domReferenceElement) {\n return undefined;\n }\n return mergeCleanups(domReferenceElement && addEventListener(domReferenceElement, 'focusout', handleFocusOutside), domReferenceElement && addEventListener(domReferenceElement, 'pointerdown', handlePointerDown), floating && addEventListener(floating, 'focusin', handleFocusIn), floating && addEventListener(floating, 'focusout', handleFocusOutside), floating && portalContext && addEventListener(floating, 'focusout', markInsideReactTree, true));\n }, [disabled, domReference, floating, floatingFocusElement, modal, tree, portalContext, store, closeOnFocusOut, restoreFocus, getTabbableContent, isUntrappedTypeableCombobox, getNodeId, dataRef, blurTimeout, pointerDownTimeout, restoreFocusFrame, nextFocusableElement, previousFocusableElement, getResolvedInsideElements]);\n\n // Hide everything outside the floating tree from assistive tech while open.\n React.useEffect(() => {\n if (disabled || !floating || !open) {\n return undefined;\n }\n\n // Don't hide portals nested within the parent portal.\n const portalNodes = Array.from(portalContext?.portalNode?.querySelectorAll(`[${createAttribute('portal')}]`) || []);\n const ancestors = tree ? getNodeAncestors(tree.nodesRef.current, getNodeId()) : [];\n const rootAncestorComboboxDomReference = ancestors.find(node => isTypeableCombobox(node.context?.elements.domReference || null))?.context?.elements.domReference;\n const controlInsideElements = [floating, ...portalNodes, beforeGuardRef.current, afterGuardRef.current, portalContext?.beforeOutsideRef.current, portalContext?.afterOutsideRef.current, ...getResolvedInsideElements()];\n const insideElements = [...controlInsideElements, rootAncestorComboboxDomReference, resolveRef(previousFocusableElement), resolveRef(nextFocusableElement), isUntrappedTypeableCombobox ? domReference : null].filter(x => x != null);\n const ariaHiddenCleanup = markOthers(insideElements, {\n ariaHidden: modal || isUntrappedTypeableCombobox,\n mark: false\n });\n const markerInsideElements = [floating, ...portalNodes].filter(x => x != null);\n const markerCleanup = markOthers(markerInsideElements);\n return () => {\n markerCleanup();\n ariaHiddenCleanup();\n };\n }, [open, disabled, domReference, floating, modal, portalContext, isUntrappedTypeableCombobox, tree, getNodeId, nextFocusableElement, previousFocusableElement, getResolvedInsideElements]);\n\n // Focus the initial element when the floating element opens.\n useIsoLayoutEffect(() => {\n if (!open || disabled || !isHTMLElement(floatingFocusElement)) {\n return;\n }\n closeTypeRef.current = '';\n lastInteractionTypeRef.current = '';\n const doc = ownerDocument(floatingFocusElement);\n const previouslyFocusedElement = activeElement(doc);\n\n // Wait for any layout effect state setters to execute to set `tabIndex`.\n queueMicrotask(() => {\n const initialFocusValueOrFn = initialFocusRef.current;\n const resolvedInitialFocus = typeof initialFocusValueOrFn === 'function' ? initialFocusValueOrFn(openInteractionTypeRef.current || '') : initialFocusValueOrFn;\n\n // `null` should fallback to default behavior in case of an empty ref.\n if (resolvedInitialFocus === undefined || resolvedInitialFocus === false) {\n return;\n }\n const focusAlreadyInsideFloatingEl = contains(floatingFocusElement, previouslyFocusedElement);\n if (focusAlreadyInsideFloatingEl) {\n return;\n }\n let focusableElements = null;\n const getDefaultFocusElement = () => {\n if (focusableElements == null) {\n focusableElements = getTabbableContent(floatingFocusElement);\n }\n return focusableElements[0] || floatingFocusElement;\n };\n let elToFocus;\n if (resolvedInitialFocus === true || resolvedInitialFocus === null) {\n elToFocus = getDefaultFocusElement();\n } else {\n elToFocus = resolveRef(resolvedInitialFocus);\n }\n elToFocus = elToFocus || getDefaultFocusElement();\n const hadFocusInside = contains(floatingFocusElement, activeElement(doc));\n\n // enqueueFocus returns a rAF-cancel function; we intentionally don't cancel this focus.\n void enqueueFocus(elToFocus, {\n preventScroll: elToFocus === floatingFocusElement,\n shouldFocus() {\n // This focus is queued on the next animation frame. If the floating element has closed\n // before it runs — e.g. tabbing out of a kept-mounted popup — don't pull focus back\n // onto the initial element after it has legitimately moved elsewhere.\n if (!openRef.current) {\n return false;\n }\n if (hadFocusInside) {\n return true;\n }\n const currentActiveElement = activeElement(doc);\n const focusMovedInside = currentActiveElement !== elToFocus && contains(floatingFocusElement, currentActiveElement);\n return !focusMovedInside;\n }\n });\n });\n }, [disabled, open, floatingFocusElement, getTabbableContent, initialFocusRef, openInteractionTypeRef, openRef]);\n\n // Track return focus targets and restore focus on unmount/close.\n useIsoLayoutEffect(() => {\n if (disabled || !floatingFocusElement) {\n return undefined;\n }\n const doc = ownerDocument(floatingFocusElement);\n const elementFocusedBeforeOpen = activeElement(doc);\n // Only an explicit `null` interaction type represents a programmatic open.\n // `undefined` is normalized to `''` by the prop default, so it never reaches\n // here as nullish and is intentionally not treated as programmatic.\n const preferPreviousFocus = openInteractionTypeRef.current == null;\n addPreviouslyFocusedElement(elementFocusedBeforeOpen);\n function onOpenChangeLocal(details) {\n if (!details.open) {\n closeTypeRef.current = getEventType(details.nativeEvent, lastInteractionTypeRef.current);\n }\n if (details.reason === REASONS.triggerHover && details.nativeEvent.type === 'mouseleave') {\n preventReturnFocusRef.current = true;\n }\n if (details.reason !== REASONS.outsidePress) {\n return;\n }\n if (details.nested) {\n preventReturnFocusRef.current = false;\n } else if (isVirtualClick(details.nativeEvent) || isVirtualPointerEvent(details.nativeEvent)) {\n preventReturnFocusRef.current = false;\n } else {\n // On outside press, only return focus to the reference when the browser supports the\n // `focus({ preventScroll })` option; without it, restoring focus scrolls the page.\n // Chrome on Android and Samsung Internet still don't support `preventScroll`\n // (https://issues.chromium.org/issues/41453122), so the runtime check keeps return\n // focus disabled there to avoid the scroll jump.\n let isPreventScrollSupported = false;\n ownerDocument(floatingFocusElement).createElement('div').focus({\n get preventScroll() {\n isPreventScrollSupported = true;\n return false;\n }\n });\n if (isPreventScrollSupported) {\n preventReturnFocusRef.current = false;\n } else {\n preventReturnFocusRef.current = true;\n }\n }\n }\n events.on('openchange', onOpenChangeLocal);\n function getReturnElement(closeType) {\n const returnFocusValueOrFn = returnFocusRef.current;\n let resolvedReturnFocusValue = typeof returnFocusValueOrFn === 'function' ? returnFocusValueOrFn(closeType) : returnFocusValueOrFn;\n\n // `null` should fallback to default behavior in case of an empty ref.\n if (resolvedReturnFocusValue === undefined || resolvedReturnFocusValue === false) {\n return null;\n }\n if (resolvedReturnFocusValue === null) {\n resolvedReturnFocusValue = true;\n }\n const referenceReturnElement = domReference?.isConnected ? domReference : null;\n const previousReturnElement = elementFocusedBeforeOpen?.isConnected && getNodeName(elementFocusedBeforeOpen) !== 'body' ? elementFocusedBeforeOpen : null;\n let defaultReturnElement = preferPreviousFocus ? previousReturnElement || referenceReturnElement : referenceReturnElement || previousReturnElement;\n if (!defaultReturnElement) {\n defaultReturnElement = getPreviouslyFocusedElement() || null;\n }\n if (typeof resolvedReturnFocusValue === 'boolean') {\n return defaultReturnElement;\n }\n return resolveRef(resolvedReturnFocusValue) || defaultReturnElement || null;\n }\n return () => {\n events.off('openchange', onOpenChangeLocal);\n const activeEl = activeElement(doc);\n const insideElements = getResolvedInsideElements();\n const isFocusInsideFloatingTree = contains(floating, activeEl) || insideElements.some(element => element === activeEl || contains(element, activeEl)) || tree && getNodeChildren(tree.nodesRef.current, getNodeId(), false).some(node => contains(node.context?.elements.floating, activeEl));\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const returnFocusValueOrFn = returnFocusRef.current;\n const closeType = closeTypeRef.current;\n const returnElement = getReturnElement(closeType);\n queueMicrotask(() => {\n // `returnElement` if it is tabbable, otherwise its first tabbable child,\n // otherwise `returnElement` itself (which may not be tabbable at all).\n const tabbableReturnElement = getFirstTabbableElement(returnElement);\n const hasExplicitReturnFocus = typeof returnFocusValueOrFn !== 'boolean';\n if (returnFocusValueOrFn && !preventReturnFocusRef.current && isHTMLElement(tabbableReturnElement) && (\n // If the focus moved somewhere else after mount, avoid returning focus\n // since it likely entered a different element which should be\n // respected: https://github.com/floating-ui/floating-ui/issues/2607\n !hasExplicitReturnFocus && tabbableReturnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)) {\n const focusOptions = {\n preventScroll: true\n };\n if (closeType === 'keyboard') {\n focusOptions.focusVisible = true;\n }\n tabbableReturnElement.focus(focusOptions);\n }\n preventReturnFocusRef.current = false;\n });\n };\n }, [disabled, floating, floatingFocusElement, returnFocusRef, openInteractionTypeRef, events, tree, domReference, getNodeId, getResolvedInsideElements]);\n\n // Safari may randomly scroll to the bottom of the page if an input inside a popup has focus\n // when the popup unmounts from the DOM.\n // By blurring it before the popup unmounts, we can prevent this behavior.\n useIsoLayoutEffect(() => {\n if (!platform.engine.webkit || open || !floating) {\n return;\n }\n const activeEl = activeElement(ownerDocument(floating));\n if (!isHTMLElement(activeEl) || !isTypeableElement(activeEl)) {\n return;\n }\n if (contains(floating, activeEl)) {\n activeEl.blur();\n }\n }, [open, floating]);\n\n // Synchronize the focus manager state (modal, closeOnFocusOut, open, etc.) to the\n // FloatingPortal context, which uses it to decide whether to render its own guards.\n useIsoLayoutEffect(() => {\n if (disabled || !portalContext) {\n return undefined;\n }\n portalContext.setFocusManagerState({\n modal,\n closeOnFocusOut,\n open,\n onOpenChange: store.setOpen,\n domReference\n });\n return () => {\n portalContext.setFocusManagerState(null);\n };\n }, [disabled, portalContext, modal, open, store, closeOnFocusOut, domReference]);\n\n // Keep the floating element tabIndex in sync and clear stale focus records.\n useIsoLayoutEffect(() => {\n if (disabled || !floatingFocusElement) {\n return undefined;\n }\n handleTabIndex(floatingFocusElement);\n return () => {\n queueMicrotask(clearDisconnectedPreviouslyFocusedElements);\n };\n }, [disabled, floatingFocusElement]);\n const shouldRenderGuards = !disabled && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);\n return /*#__PURE__*/_jsxs(React.Fragment, {\n children: [shouldRenderGuards && /*#__PURE__*/_jsx(FocusGuard, {\n \"data-type\": \"inside\",\n ref: mergedBeforeGuardRef,\n onFocus: event => {\n if (modal) {\n const els = getTabbableContent();\n // enqueueFocus returns a rAF-cancel function we don't need here.\n void enqueueFocus(els[els.length - 1]);\n } else if (portalContext?.portalNode) {\n preventReturnFocusRef.current = false;\n if (isOutsideEvent(event, portalContext.portalNode)) {\n const nextTabbable = getNextTabbable(domReference);\n nextTabbable?.focus();\n } else {\n resolveRef(previousFocusableElement ?? portalContext.beforeOutsideRef)?.focus();\n }\n }\n }\n }), children, shouldRenderGuards && /*#__PURE__*/_jsx(FocusGuard, {\n \"data-type\": \"inside\",\n ref: mergedAfterGuardRef,\n onFocus: event => {\n if (modal) {\n // enqueueFocus returns a rAF-cancel function we don't need here.\n void enqueueFocus(getTabbableContent()[0]);\n } else if (portalContext?.portalNode) {\n if (closeOnFocusOut) {\n preventReturnFocusRef.current = true;\n }\n if (isOutsideEvent(event, portalContext.portalNode)) {\n const prevTabbable = getPreviousTabbable(domReference);\n prevTabbable?.focus();\n } else {\n resolveRef(nextFocusableElement ?? portalContext.afterOutsideRef)?.focus();\n }\n }\n }\n })]\n });\n}","'use client';\n\n/* eslint-disable no-underscore-dangle */\nimport * as React from 'react';\nimport { addEventListener } from '@base-ui/utils/addEventListener';\nimport { mergeCleanups } from '@base-ui/utils/mergeCleanups';\nimport { ownerDocument } from '@base-ui/utils/owner';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { Timeout, useTimeout } from '@base-ui/utils/useTimeout';\nimport { getComputedStyle, getParentNode, isElement, isHTMLElement, isLastTraversableNode, isShadowRoot } from '@floating-ui/utils/dom';\nimport { platform } from '@base-ui/utils/platform';\nimport { useFloatingTree } from \"../components/FloatingTree.mjs\";\nimport { createChangeEventDetails } from \"../../internals/createBaseUIEventDetails.mjs\";\nimport { REASONS } from \"../../internals/reasons.mjs\";\nimport { createAttribute } from \"../utils/createAttribute.mjs\";\nimport { contains, getTarget, isEventTargetWithin, isRootElement } from \"../utils/element.mjs\";\nimport { isReactEvent } from \"../utils/event.mjs\";\nimport { getNodeChildren } from \"../utils/nodes.mjs\";\nfunction alwaysFalse() {\n return false;\n}\nexport function normalizeProp(normalizable) {\n return {\n escapeKey: typeof normalizable === 'boolean' ? normalizable : normalizable?.escapeKey ?? false,\n outsidePress: typeof normalizable === 'boolean' ? normalizable : normalizable?.outsidePress ?? true\n };\n}\n/**\n * Closes the floating element when a dismissal is requested — by default, when\n * the user presses the `escape` key or outside of the floating element.\n * @see https://floating-ui.com/docs/useDismiss\n */\nexport function useDismiss(context, props = {}) {\n const {\n enabled = true,\n escapeKey = true,\n outsidePress: outsidePressProp = true,\n outsidePressEvent = 'sloppy',\n referencePress = alwaysFalse,\n bubbles,\n externalTree\n } = props;\n const store = 'rootStore' in context ? context.rootStore : context;\n const open = store.useState('open');\n const floatingElement = store.useState('floatingElement');\n const {\n dataRef\n } = store.context;\n const tree = useFloatingTree(externalTree);\n const outsidePressFn = useStableCallback(typeof outsidePressProp === 'function' ? outsidePressProp : () => false);\n const outsidePress = typeof outsidePressProp === 'function' ? outsidePressFn : outsidePressProp;\n const outsidePressEnabled = outsidePress !== false;\n const getOutsidePressEventProp = useStableCallback(() => outsidePressEvent);\n const {\n escapeKey: escapeKeyBubbles,\n outsidePress: outsidePressBubbles\n } = normalizeProp(bubbles);\n const pressStartedInsideRef = React.useRef(false);\n const pressStartPreventedRef = React.useRef(false);\n // Ignore only the very next outside click after dragging from inside to outside.\n const suppressNextOutsideClickRef = React.useRef(false);\n const isComposingRef = React.useRef(false);\n const currentPointerTypeRef = React.useRef('');\n const touchStateRef = React.useRef(null);\n const cancelDismissOnEndTimeout = useTimeout();\n const clearInsideReactTreeTimeout = useTimeout();\n const clearInsideReactTree = useStableCallback(() => {\n clearInsideReactTreeTimeout.clear();\n dataRef.current.insideReactTree = false;\n });\n const hasBlockingChild = useStableCallback(bubbleKey => {\n const nodeId = dataRef.current.floatingContext?.nodeId;\n const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];\n return children.some(child => child.context?.open && !child.context.dataRef.current[bubbleKey]);\n });\n const isEventWithinOwnElements = useStableCallback(event => {\n return isEventTargetWithin(event, store.select('floatingElement')) || isEventTargetWithin(event, store.select('domReferenceElement'));\n });\n const closeOnReferencePress = useStableCallback(event => {\n if (!referencePress()) {\n return;\n }\n store.setOpen(false, createChangeEventDetails(REASONS.triggerPress, event.nativeEvent));\n });\n const closeOnEscapeKeyDown = useStableCallback(event => {\n if (!open || !enabled || !escapeKey || event.key !== 'Escape') {\n return;\n }\n\n // Wait until IME is settled. Pressing `Escape` while composing should\n // close the compose menu, but not the floating element.\n if (isComposingRef.current) {\n return;\n }\n if (!escapeKeyBubbles && hasBlockingChild('__escapeKeyBubbles')) {\n return;\n }\n const native = isReactEvent(event) ? event.nativeEvent : event;\n const eventDetails = createChangeEventDetails(REASONS.escapeKey, native);\n store.setOpen(false, eventDetails);\n if (!eventDetails.isCanceled) {\n event.preventDefault();\n }\n if (!escapeKeyBubbles && !eventDetails.isPropagationAllowed) {\n event.stopPropagation();\n }\n });\n const markInsideReactTree = useStableCallback(() => {\n dataRef.current.insideReactTree = true;\n clearInsideReactTreeTimeout.start(0, clearInsideReactTree);\n });\n const markPressStartedInsideReactTree = useStableCallback(event => {\n if (!open || !enabled || event.button !== 0) {\n return;\n }\n const target = getTarget(event.nativeEvent);\n\n // Only treat presses that start within the floating DOM subtree as inside.\n // This avoids suppressing parent dismissal when interacting with nested portals.\n if (!contains(store.select('floatingElement'), target)) {\n return;\n }\n if (!pressStartedInsideRef.current) {\n pressStartedInsideRef.current = true;\n pressStartPreventedRef.current = false;\n }\n });\n const markInsidePressStartPrevented = useStableCallback(event => {\n if (!open || !enabled) {\n return;\n }\n if (!(event.defaultPrevented || event.nativeEvent.defaultPrevented)) {\n return;\n }\n if (pressStartedInsideRef.current) {\n pressStartPreventedRef.current = true;\n }\n });\n React.useEffect(() => {\n if (!open || !enabled) {\n return clearInsideReactTree;\n }\n dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;\n dataRef.current.__outsidePressBubbles = outsidePressBubbles;\n const compositionTimeout = new Timeout();\n const preventedPressSuppressionTimeout = new Timeout();\n function handleCompositionStart() {\n compositionTimeout.clear();\n isComposingRef.current = true;\n }\n function handleCompositionEnd() {\n // Safari fires `compositionend` before `keydown`, so we need to wait\n // until the next tick to set `isComposing` to `false`.\n // https://bugs.webkit.org/show_bug.cgi?id=165004\n compositionTimeout.start(\n // 0ms or 1ms don't work in Safari. 5ms appears to consistently work.\n // Only apply to WebKit for the test to remain 0ms.\n platform.engine.webkit ? 5 : 0, () => {\n isComposingRef.current = false;\n });\n }\n function suppressImmediateOutsideClickAfterPreventedStart() {\n suppressNextOutsideClickRef.current = true;\n // Firefox can emit the synthetic outside click in a later task after\n // pointer lock exit, so microtask clearing is too early here.\n preventedPressSuppressionTimeout.start(0, () => {\n suppressNextOutsideClickRef.current = false;\n });\n }\n function resetPressStartState() {\n pressStartedInsideRef.current = false;\n pressStartPreventedRef.current = false;\n }\n function getOutsidePressEvent() {\n const type = currentPointerTypeRef.current;\n const computedType = type === 'pen' || !type ? 'mouse' : type;\n const outsidePressEventValue = getOutsidePressEventProp();\n const resolved = typeof outsidePressEventValue === 'function' ? outsidePressEventValue() : outsidePressEventValue;\n if (typeof resolved === 'string') {\n return resolved;\n }\n return resolved[computedType];\n }\n function shouldIgnoreEvent(event) {\n const computedOutsidePressEvent = getOutsidePressEvent();\n return computedOutsidePressEvent === 'intentional' && event.type !== 'click' || computedOutsidePressEvent === 'sloppy' && event.type === 'click';\n }\n function isEventWithinFloatingTree(event) {\n const nodeId = dataRef.current.floatingContext?.nodeId;\n const targetIsInsideChildren = tree && getNodeChildren(tree.nodesRef.current, nodeId).some(node => isEventTargetWithin(event, node.context?.elements.floating));\n return isEventWithinOwnElements(event) || targetIsInsideChildren;\n }\n function closeOnPressOutside(event) {\n if (shouldIgnoreEvent(event)) {\n // A new press began outside the floating element and its trigger. Clear any\n // leftover drag-out suppression so this press's eventual click can dismiss.\n if (event.type !== 'click' && !isEventWithinOwnElements(event)) {\n preventedPressSuppressionTimeout.clear();\n suppressNextOutsideClickRef.current = false;\n }\n clearInsideReactTree();\n return;\n }\n if (dataRef.current.insideReactTree) {\n clearInsideReactTree();\n return;\n }\n const target = getTarget(event);\n const inertSelector = `[${createAttribute('inert')}]`;\n const targetRoot = isElement(target) ? target.getRootNode() : null;\n const markers = Array.from((isShadowRoot(targetRoot) ? targetRoot : ownerDocument(store.select('floatingElement'))).querySelectorAll(inertSelector));\n const triggers = store.context.triggerElements;\n\n // If another trigger is clicked, don't close the floating element.\n if (target && (triggers.hasElement(target) || triggers.hasMatchingElement(trigger => contains(trigger, target)))) {\n return;\n }\n let targetRootAncestor = isElement(target) ? target : null;\n while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {\n const nextParent = getParentNode(targetRootAncestor);\n if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {\n break;\n }\n targetRootAncestor = nextParent;\n }\n\n // Check if the click occurred on a third-party element injected after the\n // floating element rendered.\n if (markers.length && isElement(target) && !isRootElement(target) &&\n // Clicked on a direct ancestor (e.g. FloatingOverlay).\n !contains(target, store.select('floatingElement')) &&\n // If the target root element contains none of the markers, then the\n // element was injected after the floating element rendered.\n markers.every(marker => !contains(targetRootAncestor, marker))) {\n return;\n }\n\n // Check if the click occurred on the scrollbar\n // Skip for touch events: scrollbars don't receive touch events on most platforms\n if (isHTMLElement(target) && !('touches' in event)) {\n const lastTraversableNode = isLastTraversableNode(target);\n const style = getComputedStyle(target);\n const scrollRe = /auto|scroll/;\n const isScrollableX = lastTraversableNode || scrollRe.test(style.overflowX);\n const isScrollableY = lastTraversableNode || scrollRe.test(style.overflowY);\n const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;\n const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;\n const isRTL = style.direction === 'rtl';\n\n // Check click position relative to scrollbar.\n // In some browsers it is possible to change the <body> (or window)\n // scrollbar to the left side, but is very rare and is difficult to\n // check for. Plus, for modal dialogs with backdrops, it is more\n // important that the backdrop is checked but not so much the window.\n const pressedVerticalScrollbar = canScrollY && (isRTL ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);\n const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;\n if (pressedVerticalScrollbar || pressedHorizontalScrollbar) {\n return;\n }\n }\n if (isEventWithinFloatingTree(event)) {\n return;\n }\n\n // In intentional mode, a press that starts inside and ends outside gets\n // one suppressed outside click. Run this after inside-target checks so\n // inside clicks don't consume the one-shot suppression.\n if (getOutsidePressEvent() === 'intentional' && suppressNextOutsideClickRef.current) {\n preventedPressSuppressionTimeout.clear();\n suppressNextOutsideClickRef.current = false;\n return;\n }\n if (typeof outsidePress === 'function' && !outsidePress(event)) {\n return;\n }\n if (hasBlockingChild('__outsidePressBubbles')) {\n return;\n }\n store.setOpen(false, createChangeEventDetails(REASONS.outsidePress, event));\n clearInsideReactTree();\n }\n function handlePointerDown(event) {\n if (getOutsidePressEvent() !== 'sloppy' || event.pointerType === 'touch' || !store.select('open') || !enabled || isEventWithinOwnElements(event)) {\n return;\n }\n closeOnPressOutside(event);\n }\n function handleTouchStart(event) {\n if (getOutsidePressEvent() !== 'sloppy' || !store.select('open') || !enabled || isEventWithinOwnElements(event)) {\n return;\n }\n const touch = event.touches[0];\n if (touch) {\n touchStateRef.current = {\n startTime: Date.now(),\n startX: touch.clientX,\n startY: touch.clientY,\n dismissOnTouchEnd: false,\n dismissOnMouseDown: true\n };\n cancelDismissOnEndTimeout.start(1000, () => {\n if (touchStateRef.current) {\n touchStateRef.current.dismissOnTouchEnd = false;\n touchStateRef.current.dismissOnMouseDown = false;\n }\n });\n }\n }\n function addTargetEventListenerOnce(event, listener) {\n const target = getTarget(event);\n if (!target) {\n return;\n }\n const unsubscribe = addEventListener(target, event.type, () => {\n listener(event);\n unsubscribe();\n });\n }\n function handleTouchStartCapture(event) {\n currentPointerTypeRef.current = 'touch';\n addTargetEventListenerOnce(event, handleTouchStart);\n }\n function closeOnPressOutsideCapture(event) {\n cancelDismissOnEndTimeout.clear();\n if (event.type === 'pointerdown') {\n currentPointerTypeRef.current = event.pointerType;\n }\n if (event.type === 'mousedown' && touchStateRef.current && !touchStateRef.current.dismissOnMouseDown) {\n return;\n }\n addTargetEventListenerOnce(event, targetEvent => {\n if (targetEvent.type === 'pointerdown') {\n handlePointerDown(targetEvent);\n } else {\n closeOnPressOutside(targetEvent);\n }\n });\n }\n function handlePressEndCapture(event) {\n if (!pressStartedInsideRef.current) {\n return;\n }\n const pressStartedInsideDefaultPrevented = pressStartPreventedRef.current;\n resetPressStartState();\n if (getOutsidePressEvent() !== 'intentional') {\n return;\n }\n if (event.type === 'pointercancel') {\n if (pressStartedInsideDefaultPrevented) {\n suppressImmediateOutsideClickAfterPreventedStart();\n }\n return;\n }\n if (isEventWithinFloatingTree(event)) {\n return;\n }\n\n // If pointerdown was prevented, no click may be generated for that\n // interaction. However, Firefox may still emit an immediate click after\n // pointerup (e.g. NumberField scrub with pointer lock), so suppress for\n // one tick to absorb that synthetic click only.\n if (pressStartedInsideDefaultPrevented) {\n suppressImmediateOutsideClickAfterPreventedStart();\n return;\n }\n\n // Avoid suppressing when outsidePress explicitly ignores this target.\n if (typeof outsidePress === 'function' && !outsidePress(event)) {\n return;\n }\n preventedPressSuppressionTimeout.clear();\n suppressNextOutsideClickRef.current = true;\n clearInsideReactTree();\n }\n function handleTouchMove(event) {\n if (getOutsidePressEvent() !== 'sloppy' || !touchStateRef.current || isEventWithinOwnElements(event)) {\n return;\n }\n const touch = event.touches[0];\n if (!touch) {\n return;\n }\n const deltaX = Math.abs(touch.clientX - touchStateRef.current.startX);\n const deltaY = Math.abs(touch.clientY - touchStateRef.current.startY);\n const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);\n if (distance > 5) {\n touchStateRef.current.dismissOnTouchEnd = true;\n }\n if (distance > 10) {\n closeOnPressOutside(event);\n cancelDismissOnEndTimeout.clear();\n touchStateRef.current = null;\n }\n }\n function handleTouchMoveCapture(event) {\n addTargetEventListenerOnce(event, handleTouchMove);\n }\n function handleTouchEnd(event) {\n if (getOutsidePressEvent() !== 'sloppy' || !touchStateRef.current || isEventWithinOwnElements(event)) {\n return;\n }\n if (touchStateRef.current.dismissOnTouchEnd) {\n closeOnPressOutside(event);\n }\n cancelDismissOnEndTimeout.clear();\n touchStateRef.current = null;\n }\n function handleTouchEndCapture(event) {\n addTargetEventListenerOnce(event, handleTouchEnd);\n }\n const doc = ownerDocument(floatingElement);\n const unsubscribe = mergeCleanups(escapeKey && mergeCleanups(addEventListener(doc, 'keydown', closeOnEscapeKeyDown), addEventListener(doc, 'compositionstart', handleCompositionStart), addEventListener(doc, 'compositionend', handleCompositionEnd)), outsidePressEnabled && mergeCleanups(addEventListener(doc, 'click', closeOnPressOutsideCapture, true), addEventListener(doc, 'pointerdown', closeOnPressOutsideCapture, true), addEventListener(doc, 'pointerup', handlePressEndCapture, true), addEventListener(doc, 'pointercancel', handlePressEndCapture, true), addEventListener(doc, 'mousedown', closeOnPressOutsideCapture, true), addEventListener(doc, 'mouseup', handlePressEndCapture, true), addEventListener(doc, 'touchstart', handleTouchStartCapture, true), addEventListener(doc, 'touchmove', handleTouchMoveCapture, true), addEventListener(doc, 'touchend', handleTouchEndCapture, true)));\n return () => {\n unsubscribe();\n compositionTimeout.clear();\n preventedPressSuppressionTimeout.clear();\n resetPressStartState();\n suppressNextOutsideClickRef.current = false;\n clearInsideReactTree();\n };\n }, [dataRef, floatingElement, escapeKey, outsidePressEnabled, outsidePress, open, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, clearInsideReactTree, getOutsidePressEventProp, hasBlockingChild, isEventWithinOwnElements, tree, store, cancelDismissOnEndTimeout]);\n const reference = React.useMemo(() => ({\n onKeyDown: closeOnEscapeKeyDown,\n onPointerDown: closeOnReferencePress,\n onClick: closeOnReferencePress\n }), [closeOnEscapeKeyDown, closeOnReferencePress]);\n const floating = React.useMemo(() => ({\n onKeyDown: closeOnEscapeKeyDown,\n // `onMouseDown` may be blocked if `event.preventDefault()` is called in\n // `onPointerDown`, such as with <NumberField.ScrubArea>.\n // See https://github.com/mui/base-ui/pull/3379\n onPointerDown: markInsidePressStartPrevented,\n onMouseDown: markInsidePressStartPrevented,\n onClickCapture: markInsideReactTree,\n onMouseDownCapture(event) {\n markInsideReactTree();\n markPressStartedInsideReactTree(event);\n },\n onPointerDownCapture(event) {\n markInsideReactTree();\n markPressStartedInsideReactTree(event);\n },\n onMouseUpCapture: markInsideReactTree,\n onTouchEndCapture: markInsideReactTree,\n onTouchMoveCapture: markInsideReactTree\n }), [closeOnEscapeKeyDown, markInsideReactTree, markPressStartedInsideReactTree, markInsidePressStartPrevented]);\n return React.useMemo(() => enabled ? {\n reference,\n floating,\n trigger: reference\n } : {}, [enabled, reference, floating]);\n}","export { useSyncExternalStore } from 'react';\n\nexport function useSyncExternalStoreWithSelector(): never {\n throw new Error('React 19 uses its native useSyncExternalStore');\n}\n","import * as React from 'react';\nimport { useRefWithInit } from \"./useRefWithInit.mjs\";\nconst hooks = [];\nlet currentInstance = undefined;\nexport function getInstance() {\n return currentInstance;\n}\nexport function setInstance(instance) {\n currentInstance = instance;\n}\nexport function register(hook) {\n hooks.push(hook);\n}\n\n/**\n * Wraps a component function to enable performance optimizations for internal hooks.\n *\n * **Performance Optimization:**\n * Components wrapped with `fastComponent` have access to a shared \"instance\" context that enables\n * specialized hook implementations to batch operations and reduce overhead. The wrapper creates a\n * stable instance object that persists across renders, sets it as the current context, calls\n * registered hooks before and after rendering, then clears the context. The primary benefit is\n * with `useStore`, where multiple store subscriptions within the same component are collapsed into\n * a single `useSyncExternalStore` subscription per store, significantly reducing re-render overhead.\n * This optimization is only active on React 19+; on earlier versions `useStore` falls back to a\n * separate subscription per call.\n *\n * **Requirements:**\n * - The component function should follow standard React component patterns\n * - `useStore` calls must keep a stable order and count across renders, as batched hooks are\n * matched by call index\n * - Do not rely on the instance context outside of specialized hooks\n *\n * @param fn - The component function to wrap\n * @returns A wrapped component with the same signature as the input function\n *\n * @example\n * ```tsx\n * // Wrapping a component to enable optimized useStore batching\n * export const TooltipRoot = fastComponent(function TooltipRoot(props) {\n * // These useStore calls share a single subscription\n * const open = useStore(store, (state) => state.open);\n * const disabled = useStore(store, (state) => state.disabled);\n * const value = useStore(store, (state) => state.value);\n * // ...\n * });\n * ```\n */\nexport function fastComponent(fn) {\n const FastComponent = (props, forwardedRef) => {\n const instance = useRefWithInit(createInstance).current;\n let result;\n try {\n currentInstance = instance;\n for (const hook of hooks) {\n hook.before(instance);\n }\n result = fn(props, forwardedRef);\n for (const hook of hooks) {\n hook.after(instance);\n }\n instance.didInitialize = true;\n } finally {\n currentInstance = undefined;\n }\n return result;\n };\n FastComponent.displayName = fn.displayName || fn.name;\n return FastComponent;\n}\n\n/**\n * Wraps a component function with ref forwarding to enable performance optimizations for internal hooks.\n *\n * This is a convenience wrapper that combines `fastComponent` with `React.forwardRef`, enabling\n * both performance optimizations and proper ref forwarding. See `fastComponent` for details on\n * the performance benefits.\n *\n * @param fn - The component function that accepts props and a forwarded ref\n * @returns A wrapped component with ref forwarding enabled\n *\n * @example\n * ```tsx\n * // Wrapping a component with ref forwarding and optimized hooks\n * export const TooltipTrigger = fastComponentRef(function TooltipTrigger(\n * props,\n * forwardedRef\n * ) {\n * const store = useContext(TooltipContext);\n * const open = useStore(store, (state) => state.open);\n * // ... component logic with ref\n * return <button ref={forwardedRef} {...props} />;\n * });\n * ```\n */\nexport function fastComponentRef(fn) {\n return /*#__PURE__*/React.forwardRef(fastComponent(fn));\n}\nfunction createInstance() {\n return {\n didInitialize: false\n };\n}","import * as React from 'react';\n/* We need to import the shim because React 17 does not support the `useSyncExternalStore` API.\n * More info: https://github.com/mui/mui-x/issues/18303#issuecomment-2958392341 */\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\nimport { isReactVersionAtLeast } from \"../reactVersion.mjs\";\nimport { register, getInstance } from \"../fastHooks.mjs\";\n/* Some tests fail in R18 with the raw useSyncExternalStore. It may be possible to make it work\n * but for now we only enable it for R19+. */\nconst canUseRawUseSyncExternalStore = isReactVersionAtLeast(19);\nconst useStoreImplementation = canUseRawUseSyncExternalStore ? useStoreFast : useStoreLegacy;\nexport function useStore(store, selector, a1, a2, a3) {\n return useStoreImplementation(store, selector, a1, a2, a3);\n}\nfunction useStoreR19(store, selector, a1, a2, a3) {\n const getSelection = React.useCallback(() => selector(store.getSnapshot(), a1, a2, a3), [store, selector, a1, a2, a3]);\n return useSyncExternalStore(store.subscribe, getSelection, getSelection);\n}\nregister({\n before(instance) {\n instance.syncIndex = 0;\n if (!instance.didInitialize) {\n instance.syncTick = 1;\n instance.syncHooks = [];\n instance.didChangeStore = true;\n instance.getSnapshot = () => {\n let didChange = false;\n for (let i = 0; i < instance.syncHooks.length; i += 1) {\n const hook = instance.syncHooks[i];\n const value = hook.selector(hook.store.state, hook.a1, hook.a2, hook.a3);\n if (!Object.is(hook.value, value)) {\n didChange = true;\n hook.value = value;\n }\n }\n if (didChange) {\n instance.syncTick += 1;\n }\n return instance.syncTick;\n };\n }\n },\n after(instance) {\n if (instance.syncHooks.length > 0) {\n if (instance.didChangeStore) {\n instance.didChangeStore = false;\n instance.subscribe = onStoreChange => {\n const stores = new Set();\n for (const hook of instance.syncHooks) {\n stores.add(hook.store);\n }\n const unsubscribes = [];\n for (const store of stores) {\n unsubscribes.push(store.subscribe(onStoreChange));\n }\n return () => {\n for (const unsubscribe of unsubscribes) {\n unsubscribe();\n }\n };\n };\n }\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useSyncExternalStore(instance.subscribe, instance.getSnapshot, instance.getSnapshot);\n }\n }\n});\nfunction useStoreFast(store, selector, a1, a2, a3) {\n const instance = getInstance();\n if (!instance) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useStoreR19(store, selector, a1, a2, a3);\n }\n const index = instance.syncIndex;\n instance.syncIndex += 1;\n let hook;\n if (!instance.didInitialize) {\n hook = {\n store,\n selector,\n a1,\n a2,\n a3,\n value: selector(store.getSnapshot(), a1, a2, a3)\n };\n instance.syncHooks.push(hook);\n } else {\n hook = instance.syncHooks[index];\n if (hook.store !== store || hook.selector !== selector || !Object.is(hook.a1, a1) || !Object.is(hook.a2, a2) || !Object.is(hook.a3, a3)) {\n if (hook.store !== store) {\n instance.didChangeStore = true;\n }\n hook.store = store;\n hook.selector = selector;\n hook.a1 = a1;\n hook.a2 = a2;\n hook.a3 = a3;\n hook.value = selector(store.getSnapshot(), a1, a2, a3);\n }\n }\n return hook.value;\n}\nfunction useStoreLegacy(store, selector, a1, a2, a3) {\n return useSyncExternalStoreWithSelector(store.subscribe, store.getSnapshot, store.getSnapshot, state => selector(state, a1, a2, a3));\n}","import { useStore } from \"./useStore.mjs\";\n/**\n * A data store implementation that allows subscribing to state changes and updating the state.\n * It uses an observer pattern to notify subscribers when the state changes.\n */\nexport class Store {\n /**\n * The current state of the store.\n * This property is updated immediately when the state changes as a result of calling {@link setState}, {@link update}, or {@link set}.\n * To subscribe to state changes, use the {@link useState} method. The value returned by {@link useState} is updated after the component renders (similarly to React's useState).\n * The values can be used directly (to avoid subscribing to the store) in effects or event handlers.\n *\n * Do not modify properties in state directly. Instead, use the provided methods to ensure proper state management and listener notification.\n */\n\n // Internal state to handle recursive `setState()` calls\n\n constructor(state) {\n this.state = state;\n this.listeners = new Set();\n this.updateTick = 0;\n }\n\n /**\n * Registers a listener that will be called whenever the store's state changes.\n *\n * @param fn The listener function to be called on state changes.\n * @returns A function to unsubscribe the listener.\n */\n subscribe = fn => {\n this.listeners.add(fn);\n return () => {\n this.listeners.delete(fn);\n };\n };\n\n /**\n * Returns the current state of the store.\n */\n getSnapshot = () => {\n return this.state;\n };\n\n /**\n * Updates the entire store's state and notifies all registered listeners.\n *\n * @param newState The new state to set for the store.\n */\n setState(newState) {\n if (this.state === newState) {\n return;\n }\n this.state = newState;\n this.updateTick += 1;\n const currentTick = this.updateTick;\n for (const listener of this.listeners) {\n if (currentTick !== this.updateTick) {\n // If the tick has changed, a recursive `setState` call has been made,\n // and it has already notified all listeners.\n return;\n }\n listener(newState);\n }\n }\n\n /**\n * Merges the provided changes into the current state and notifies listeners if there are changes.\n *\n * @param changes An object containing the changes to apply to the current state.\n */\n update(changes) {\n for (const key in changes) {\n if (!Object.is(this.state[key], changes[key])) {\n this.setState({\n ...this.state,\n ...changes\n });\n return;\n }\n }\n }\n\n /**\n * Sets a specific key in the store's state to a new value and notifies listeners if the value has changed.\n *\n * @param key The key in the store's state to update.\n * @param value The new value to set for the specified key.\n */\n set(key, value) {\n if (!Object.is(this.state[key], value)) {\n this.setState({\n ...this.state,\n [key]: value\n });\n }\n }\n\n /**\n * Gives the state a new reference and updates all registered listeners.\n */\n notifyAll() {\n const newState = {\n ...this.state\n };\n this.setState(newState);\n }\n use(selector, a1, a2, a3) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useStore(this, selector, a1, a2, a3);\n }\n}","/* False positives - ESLint thinks we're calling a hook from a class component. */\n/* eslint-disable react-hooks/rules-of-hooks */\n'use client';\n\nimport * as React from 'react';\nimport { Store } from \"./Store.mjs\";\nimport { useStore } from \"./useStore.mjs\";\nimport { useStableCallback } from \"../useStableCallback.mjs\";\nimport { useIsoLayoutEffect } from \"../useIsoLayoutEffect.mjs\";\nimport { NOOP } from \"../empty.mjs\";\n\n/**\n * A Store that supports controlled state keys, non-reactive values and provides utility methods for React.\n */\nexport class ReactStore extends Store {\n /**\n * Creates a new ReactStore instance.\n *\n * @param state Initial state of the store.\n * @param context Non-reactive context values.\n * @param selectors Optional selectors for use with `useState`.\n */\n constructor(state, context = {}, selectors) {\n super(state);\n this.context = context;\n this.selectors = selectors;\n }\n\n /**\n * Non-reactive values such as refs, callbacks, etc.\n */\n\n /**\n * Synchronizes a single external value into the store.\n *\n * Note that the while the value in `state` is updated immediately, the value returned\n * by `useState` is updated before the next render (similarly to React's `useState`).\n */\n useSyncedValue(key, value) {\n React.useDebugValue(key);\n // eslint-disable-next-line consistent-this\n const store = this;\n useIsoLayoutEffect(() => {\n if (store.state[key] !== value) {\n store.set(key, value);\n }\n }, [store, key, value]);\n }\n\n /**\n * Synchronizes a single external value into the store and\n * cleans it up (sets to `undefined`) on unmount.\n *\n * Note that the while the value in `state` is updated immediately, the value returned\n * by `useState` is updated before the next render (similarly to React's `useState`).\n */\n useSyncedValueWithCleanup(key, value) {\n // eslint-disable-next-line consistent-this\n const store = this;\n useIsoLayoutEffect(() => {\n if (store.state[key] !== value) {\n store.set(key, value);\n }\n return () => {\n store.set(key, undefined);\n };\n }, [store, key, value]);\n }\n\n /**\n * Synchronizes multiple external values into the store.\n *\n * Note that the while the values in `state` are updated immediately, the values returned\n * by `useState` are updated before the next render (similarly to React's `useState`).\n */\n useSyncedValues(statePart) {\n // eslint-disable-next-line consistent-this\n const store = this;\n if (process.env.NODE_ENV !== 'production') {\n // Check that an object with the same shape is passed on every render\n React.useDebugValue(statePart, p => Object.keys(p));\n const keys = React.useRef(Object.keys(statePart)).current;\n const nextKeys = Object.keys(statePart);\n if (keys.length !== nextKeys.length || keys.some((key, index) => key !== nextKeys[index])) {\n console.error('ReactStore.useSyncedValues expects the same prop keys on every render. Keys should be stable.');\n }\n }\n const dependencies = Object.values(statePart);\n useIsoLayoutEffect(() => {\n store.update(statePart);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store, ...dependencies]);\n }\n\n /**\n * Registers a controllable prop pair (`controlled`, `defaultValue`) for a specific key. If `controlled`\n * is non-undefined, the store's state at `key` is updated to match `controlled`.\n */\n useControlledProp(key, controlled) {\n React.useDebugValue(key);\n // eslint-disable-next-line consistent-this\n const store = this;\n const isControlled = controlled !== undefined;\n useIsoLayoutEffect(() => {\n if (isControlled && !Object.is(store.state[key], controlled)) {\n // Set the internal state to match the controlled value.\n store.setState({\n ...store.state,\n [key]: controlled\n });\n }\n }, [store, key, controlled, isControlled]);\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n const cache = this.controlledValues ??= new Map();\n if (!cache.has(key)) {\n cache.set(key, isControlled);\n }\n const previouslyControlled = cache.get(key);\n if (previouslyControlled !== undefined && previouslyControlled !== isControlled) {\n console.error(`A component is changing the ${isControlled ? '' : 'un'}controlled state of ${key.toString()} to be ${isControlled ? 'un' : ''}controlled. Elements should not switch from uncontrolled to controlled (or vice versa).`);\n }\n }\n }\n\n /** Gets the current value from the store using a selector with the provided key.\n *\n * @param key Key of the selector to use.\n */\n\n select(key, a1, a2, a3) {\n const selector = this.selectors[key];\n return selector(this.state, a1, a2, a3);\n }\n\n /**\n * Returns a value from the store's state using a selector function.\n * Used to subscribe to specific parts of the state.\n * This methods causes a rerender whenever the selected state changes.\n *\n * @param key Key of the selector to use.\n */\n\n useState(key, a1, a2, a3) {\n React.useDebugValue(key);\n return useStore(this, this.selectors[key], a1, a2, a3);\n }\n\n /**\n * Wraps a function with `useStableCallback` to ensure it has a stable reference\n * and assigns it to the context.\n *\n * @param key Key of the event callback. Must be a function in the context.\n * @param fn Function to assign.\n */\n useContextCallback(key, fn) {\n React.useDebugValue(key);\n const stableFunction = useStableCallback(fn ?? NOOP);\n this.context[key] = stableFunction;\n }\n\n /**\n * Returns a stable setter function for a specific key in the store's state.\n * It's commonly used to pass as a ref callback to React elements.\n *\n * @param key Key of the state to set.\n */\n useStateSetter(key) {\n const ref = React.useRef(undefined);\n if (ref.current === undefined) {\n ref.current = value => {\n this.set(key, value);\n };\n }\n return ref.current;\n }\n\n /**\n * Observes changes derived from the store's selectors and calls the listener when the selected value changes.\n *\n * @param key Key of the selector to observe.\n * @param listener Listener function called when the selector result changes.\n */\n\n observe(selector, listener) {\n let selectFn;\n if (typeof selector === 'function') {\n selectFn = selector;\n } else {\n selectFn = this.selectors[selector];\n }\n let prevValue = selectFn(this.state);\n listener(prevValue, prevValue, this);\n return this.subscribe(nextState => {\n const nextValue = selectFn(nextState);\n if (!Object.is(prevValue, nextValue)) {\n const oldValue = prevValue;\n prevValue = nextValue;\n listener(nextValue, oldValue, this);\n }\n });\n }\n}","import { ReactStore } from '@base-ui/utils/store';\nimport { createEventEmitter } from \"../utils/createEventEmitter.mjs\";\nimport { isClickLikeEvent } from \"../utils.mjs\";\nconst selectors = {\n open: state => state.open,\n transitionStatus: state => state.transitionStatus,\n domReferenceElement: state => state.domReferenceElement,\n referenceElement: state => state.positionReference ?? state.referenceElement,\n floatingElement: state => state.floatingElement,\n floatingId: state => state.floatingId\n};\nexport class FloatingRootStore extends ReactStore {\n constructor(options) {\n const {\n syncOnly,\n nested,\n onOpenChange,\n triggerElements,\n ...initialState\n } = options;\n super({\n ...initialState,\n positionReference: initialState.referenceElement,\n domReferenceElement: initialState.referenceElement\n }, {\n onOpenChange,\n dataRef: {\n current: {}\n },\n events: createEventEmitter(),\n nested,\n triggerElements\n }, selectors);\n this.syncOnly = syncOnly;\n }\n\n /**\n * Syncs the event used by hover logic to distinguish hover-open from click-like interaction.\n */\n syncOpenEvent = (newOpen, event) => {\n if (!newOpen || !this.state.open ||\n // Prevent a pending hover-open from overwriting a click-open event, while allowing\n // click events to upgrade a hover-open.\n event != null && isClickLikeEvent(event)) {\n this.context.dataRef.current.openEvent = newOpen ? event : undefined;\n }\n };\n\n /**\n * Runs the root-owned side effects for an open state change.\n */\n dispatchOpenChange = (newOpen, eventDetails) => {\n this.syncOpenEvent(newOpen, eventDetails.event);\n const details = {\n open: newOpen,\n reason: eventDetails.reason,\n nativeEvent: eventDetails.event,\n nested: this.context.nested,\n triggerElement: eventDetails.trigger\n };\n this.context.events.emit('openchange', details);\n };\n\n /**\n * Emits the `openchange` event through the internal event emitter and calls the `onOpenChange` handler with the provided arguments.\n *\n * @param newOpen The new open state.\n * @param eventDetails Details about the event that triggered the open state change.\n */\n setOpen = (newOpen, eventDetails) => {\n if (this.syncOnly) {\n this.context.onOpenChange?.(newOpen, eventDetails);\n return;\n }\n this.dispatchOpenChange(newOpen, eventDetails);\n this.context.onOpenChange?.(newOpen, eventDetails);\n };\n}","'use client';\n\nimport * as React from 'react';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { isElement } from '@floating-ui/utils/dom';\nimport { FloatingRootStore } from \"../components/FloatingRootStore.mjs\";\n/**\n * Keeps a FloatingRootStore in sync with the provided PopupStore.\n * Uses the provided FloatingRootStore when one exists, otherwise creates one once and updates it on every render.\n */\nexport function useSyncedFloatingRootContext(options) {\n const {\n popupStore,\n treatPopupAsFloatingElement = false,\n floatingRootContext: floatingRootContextProp,\n floatingId,\n nested,\n onOpenChange\n } = options;\n const open = popupStore.useState('open');\n const referenceElement = popupStore.useState('activeTriggerElement');\n const floatingElement = popupStore.useState(treatPopupAsFloatingElement ? 'popupElement' : 'positionerElement');\n const triggerElements = popupStore.context.triggerElements;\n const handleOpenChange = onOpenChange;\n const internalStoreRef = React.useRef(null);\n if (floatingRootContextProp === undefined && internalStoreRef.current === null) {\n internalStoreRef.current = new FloatingRootStore({\n open,\n transitionStatus: undefined,\n referenceElement,\n floatingElement,\n triggerElements,\n onOpenChange: handleOpenChange,\n floatingId,\n syncOnly: true,\n nested\n });\n }\n const store = floatingRootContextProp ?? internalStoreRef.current;\n popupStore.useSyncedValue('floatingId', floatingId);\n useIsoLayoutEffect(() => {\n const valuesToSync = {\n open,\n floatingId,\n referenceElement,\n floatingElement\n };\n if (isElement(referenceElement)) {\n valuesToSync.domReferenceElement = referenceElement;\n }\n if (store.state.positionReference === store.state.referenceElement) {\n valuesToSync.positionReference = referenceElement;\n }\n store.update(valuesToSync);\n }, [open, floatingId, referenceElement, floatingElement, store]);\n\n // Keep non-reactive context values fresh for interactions that call `store.setOpen`.\n store.context.onOpenChange = handleOpenChange;\n store.context.nested = nested;\n return store;\n}","'use client';\n\nimport * as React from 'react';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { AnimationFrame } from '@base-ui/utils/useAnimationFrame';\n/**\n * Provides a status string for CSS animations.\n * @param open - a boolean that determines if the element is open.\n * @param enableIdleState - a boolean that enables the `'idle'` state between `'starting'` and `'ending'`\n */\nexport function useTransitionStatus(open, enableIdleState = false, deferEndingState = false) {\n const [transitionStatus, setTransitionStatus] = React.useState(open && enableIdleState ? 'idle' : undefined);\n const [mounted, setMounted] = React.useState(open);\n if (open && !mounted) {\n setMounted(true);\n setTransitionStatus('starting');\n }\n if (!open && mounted && transitionStatus !== 'ending' && !deferEndingState) {\n setTransitionStatus('ending');\n }\n if (!open && !mounted && transitionStatus === 'ending') {\n setTransitionStatus(undefined);\n }\n useIsoLayoutEffect(() => {\n if (!open && mounted && transitionStatus !== 'ending' && deferEndingState) {\n const frame = AnimationFrame.request(() => {\n setTransitionStatus('ending');\n });\n return () => {\n AnimationFrame.cancel(frame);\n };\n }\n return undefined;\n }, [open, mounted, transitionStatus, deferEndingState]);\n useIsoLayoutEffect(() => {\n if (!open || enableIdleState) {\n return undefined;\n }\n const frame = AnimationFrame.request(() => {\n // Avoid `flushSync` here due to Firefox.\n // See https://github.com/mui/base-ui/pull/3424\n setTransitionStatus(undefined);\n });\n return () => {\n AnimationFrame.cancel(frame);\n };\n }, [enableIdleState, open]);\n useIsoLayoutEffect(() => {\n if (!open || !enableIdleState) {\n return undefined;\n }\n if (open && mounted && transitionStatus !== 'idle') {\n setTransitionStatus('starting');\n }\n const frame = AnimationFrame.request(() => {\n setTransitionStatus('idle');\n });\n return () => {\n AnimationFrame.cancel(frame);\n };\n }, [enableIdleState, open, mounted, transitionStatus]);\n return {\n mounted,\n setMounted,\n transitionStatus\n };\n}","'use client';\n\nimport * as ReactDOM from 'react-dom';\nimport { useAnimationFrame } from '@base-ui/utils/useAnimationFrame';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { resolveRef } from \"../utils/resolveRef.mjs\";\n\n/**\n * Executes a function once all animations have finished on the provided element.\n * If an animation is canceled, waits for any replacement animations before executing.\n * @param elementOrRef - The element to watch for animations.\n * @param waitForStartingStyleRemoved - Whether to wait for [data-starting-style] to be removed before checking for animations.\n * @returns A function that takes a callback to execute once all animations have finished, and an optional AbortSignal to abort the callback\n */\nexport function useAnimationsFinished(elementOrRef, waitForStartingStyleRemoved = false) {\n const frame = useAnimationFrame();\n return useStableCallback((fnToExecute,\n /**\n * An optional [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that\n * can be used to abort `fnToExecute` before all the animations have finished.\n * @default null\n */\n signal = null) => {\n frame.cancel();\n const element = resolveRef(elementOrRef);\n if (element == null) {\n return;\n }\n const resolvedElement = element;\n const done = () => {\n // Synchronously flush the unmounting of the component so that the browser doesn't\n // paint: https://github.com/mui/base-ui/issues/979\n ReactDOM.flushSync(fnToExecute);\n };\n if (typeof resolvedElement.getAnimations !== 'function' || globalThis.BASE_UI_ANIMATIONS_DISABLED) {\n fnToExecute();\n return;\n }\n function exec() {\n Promise.all(resolvedElement.getAnimations().map(animation => animation.finished)).then(() => {\n if (!signal?.aborted) {\n done();\n }\n }, () => {\n if (signal?.aborted) {\n return;\n }\n const currentAnimations = resolvedElement.getAnimations();\n if (currentAnimations.some(animation => animation.pending || animation.playState !== 'finished')) {\n // Sometimes animations can be aborted because a property they depend on changes while the animation plays.\n // In such cases, we need to re-check if any new animations have started.\n exec();\n return;\n }\n done();\n });\n }\n if (waitForStartingStyleRemoved) {\n const startingStyleAttribute = 'data-starting-style';\n\n // If `[data-starting-style]` isn't present, fall back to waiting one more frame\n // to give \"open\" animations a chance to be registered.\n if (!resolvedElement.hasAttribute(startingStyleAttribute)) {\n frame.request(exec);\n return;\n }\n\n // Wait for `[data-starting-style]` to have been removed.\n const attributeObserver = new MutationObserver(() => {\n if (!resolvedElement.hasAttribute(startingStyleAttribute)) {\n attributeObserver.disconnect();\n exec();\n }\n });\n attributeObserver.observe(resolvedElement, {\n attributes: true,\n attributeFilter: [startingStyleAttribute]\n });\n signal?.addEventListener('abort', () => attributeObserver.disconnect(), {\n once: true\n });\n return;\n }\n frame.request(exec);\n });\n}","'use client';\n\nimport * as React from 'react';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { useAnimationsFinished } from \"./useAnimationsFinished.mjs\";\n\n/**\n * Calls the provided function when the CSS open/close animation or transition completes.\n */\nexport function useOpenChangeComplete(parameters) {\n const {\n enabled = true,\n open,\n ref,\n onComplete: onCompleteParam\n } = parameters;\n const onComplete = useStableCallback(onCompleteParam);\n const runOnceAnimationsFinish = useAnimationsFinished(ref, open);\n React.useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n const abortController = new AbortController();\n runOnceAnimationsFinish(onComplete, abortController.signal);\n return () => {\n abortController.abort();\n };\n }, [enabled, open, onComplete, runOnceAnimationsFinish]);\n}","'use client';\n\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { EMPTY_OBJECT } from '@base-ui/utils/empty';\nimport { useId } from '@base-ui/utils/useId';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { useRefWithInit } from '@base-ui/utils/useRefWithInit';\nimport { FOCUSABLE_ATTRIBUTE } from \"../../floating-ui-react/utils/constants.mjs\";\nimport { useFloatingParentNodeId } from \"../../floating-ui-react/components/FloatingTree.mjs\";\nimport { useSyncedFloatingRootContext } from \"../../floating-ui-react/hooks/useSyncedFloatingRootContext.mjs\";\nimport { useTransitionStatus } from \"../../internals/useTransitionStatus.mjs\";\nimport { useOpenChangeComplete } from \"../../internals/useOpenChangeComplete.mjs\";\nimport { createChangeEventDetails } from \"../../internals/createBaseUIEventDetails.mjs\";\nimport { REASONS } from \"../../internals/reasons.mjs\";\nexport const FOCUSABLE_POPUP_PROPS = {\n tabIndex: -1,\n [FOCUSABLE_ATTRIBUTE]: ''\n};\n\n/**\n * Returns the default `initialFocus` resolver for a popup. When opened by touch it focuses the\n * popup element itself to prevent the virtual keyboard from opening (required for Android\n * specifically; iOS handles this automatically). Otherwise it falls back to the default behavior.\n */\nexport function createDefaultInitialFocus(popupRef) {\n return interactionType => interactionType === 'touch' ? popupRef.current : true;\n}\n\n/**\n * The subset of a popup handle that a Root needs to bind its store to. Both the real handle classes\n * and any test double satisfy it.\n */\n\n/**\n * Creates and owns a popup store on behalf of a Root part. The store is created exactly once, with\n * controlled props and root state synced separately after creation. Sets up the synced floating\n * root context and returns the store.\n *\n * @param createStore Factory that builds the store. Called exactly once, receiving the floating id\n * and whether the popup is nested inside another floating element, both resolved on the first render.\n * @param treatPopupAsFloatingElement Whether the popup element is passed to Floating UI as the\n * floating element instead of the default positioner.\n */\nexport function usePopupRootStore(createStore, treatPopupAsFloatingElement = false) {\n const floatingId = useId();\n const nested = useFloatingParentNodeId() != null;\n const store = useRefWithInit(() => createStore(floatingId, nested)).current;\n useSyncedFloatingRootContext({\n popupStore: store,\n treatPopupAsFloatingElement,\n floatingRootContext: store.state.floatingRootContext,\n floatingId,\n nested,\n onOpenChange: store.setOpen\n });\n return store;\n}\n\n/**\n * Attaches a Root's store to a handle for this component's committed lifetime. Popup Roots render\n * it before their interactions and user children so its layout effect runs before descendant layout\n * effects. This lets descendants call the handle during the Root's initial commit without attaching\n * during render, which would leak suspended or abandoned stores. Store subscribers are notified by\n * `attachStore` in this ordinary layout phase, where React permits synchronous updates.\n *\n * Popup Roots must render this component only when a handle is present so handle-less Roots avoid\n * mounting an extra fiber and layout effect.\n */\nexport function PopupHandleAttachment({\n handle,\n store\n}) {\n useIsoLayoutEffect(() => {\n return handle.attachStore(store);\n }, [handle, store]);\n return null;\n}\n\n/**\n * Returns a callback ref that registers/unregisters the trigger element in the store.\n *\n * @param store The Store instance where the trigger should be registered.\n */\nexport function useTriggerRegistration(id, store) {\n // Keep track of the currently registered element to unregister it on unmount or id change.\n const registeredElementIdRef = React.useRef(null);\n const registeredElementRef = React.useRef(null);\n return React.useCallback(element => {\n if (id === undefined) {\n return;\n }\n let shouldSyncTriggerCount = false;\n if (registeredElementIdRef.current !== null) {\n const registeredId = registeredElementIdRef.current;\n const registeredElement = registeredElementRef.current;\n const currentElement = store.context.triggerElements.getById(registeredId);\n if (registeredElement && currentElement === registeredElement) {\n store.context.triggerElements.delete(registeredId);\n shouldSyncTriggerCount = true;\n }\n registeredElementIdRef.current = null;\n registeredElementRef.current = null;\n }\n if (element !== null) {\n registeredElementIdRef.current = id;\n registeredElementRef.current = element;\n store.context.triggerElements.add(id, element);\n shouldSyncTriggerCount = true;\n }\n if (shouldSyncTriggerCount) {\n const triggerCount = store.context.triggerElements.size;\n if (store.select('open') && store.state.triggerCount !== triggerCount) {\n store.set('triggerCount', triggerCount);\n }\n }\n }, [store, id]);\n}\nexport function setPopupOpenState(state, open, trigger, preventUnmountOnClose = false) {\n if (open) {\n // Opening starts a new close cycle, so clear any previous request to keep the popup mounted.\n state.preventUnmountingOnClose = false;\n } else if (preventUnmountOnClose) {\n state.preventUnmountingOnClose = true;\n }\n const triggerId = trigger?.id ?? null;\n\n // If a popup is closing, the `trigger` may be undefined.\n // We want to keep the previous value so that exit animations are played and focus is returned correctly.\n if (triggerId || open) {\n state.activeTriggerId = triggerId;\n state.activeTriggerElement = trigger ?? null;\n }\n}\nexport function attachPreventUnmountOnClose(eventDetails) {\n let preventUnmountOnClose = false;\n eventDetails.preventUnmountOnClose = () => {\n preventUnmountOnClose = true;\n };\n return () => preventUnmountOnClose;\n}\n\n/**\n * Runs the shared open-change sequence for a popup store: notifies `onOpenChange`,\n * honors cancellation, dispatches the floating root change, maps the reason to an\n * `instantType`, and commits the state update (synchronously for hover so\n * `getAnimations()` observes it). Stores supply their own differences via\n * `extraState` (e.g. the last change reason) and `onBeforeDispatch` (e.g. updating\n * inline-rect coordinates).\n */\nexport function applyPopupOpenChange(store, nextOpen, eventDetails, options = {}) {\n const reason = eventDetails.reason;\n const isHover = reason === REASONS.triggerHover;\n const isFocusOpen = nextOpen && reason === REASONS.triggerFocus;\n const isDismissClose = !nextOpen && (reason === REASONS.triggerPress || reason === REASONS.escapeKey);\n const shouldPreventUnmountOnClose = attachPreventUnmountOnClose(eventDetails);\n store.context.onOpenChange?.(nextOpen, eventDetails);\n if (eventDetails.isCanceled) {\n return;\n }\n options.onBeforeDispatch?.();\n store.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);\n const changeState = () => {\n // Spread `extraState` first so `open` always reflects `nextOpen`, keeping it in\n // sync with the value already passed to `dispatchOpenChange`/`setPopupOpenState`.\n const updatedState = {\n ...options.extraState,\n open: nextOpen\n };\n if (isFocusOpen) {\n updatedState.instantType = 'focus';\n } else if (isDismissClose) {\n updatedState.instantType = 'dismiss';\n } else if (isHover) {\n updatedState.instantType = undefined;\n }\n setPopupOpenState(updatedState, nextOpen, eventDetails.trigger, shouldPreventUnmountOnClose());\n store.update(updatedState);\n };\n if (isHover) {\n // Flush synchronously for hover so `node.getAnimations()` sees the new state.\n ReactDOM.flushSync(changeState);\n } else {\n changeState();\n }\n}\n\n/**\n * Sets up trigger data forwarding to the store.\n *\n * @param triggerId Id of the trigger.\n * @param triggerElementRef Ref for the trigger DOM element.\n * @param store The Store instance managing the popup state.\n * @param stateUpdates An object with state updates to apply when the trigger is active.\n */\nexport function useTriggerDataForwarding(triggerId, triggerElementRef, store, stateUpdates) {\n const isMountedByThisTrigger = store.useState('isMountedByTrigger', triggerId);\n const baseRegisterTrigger = useTriggerRegistration(triggerId, store);\n\n // Applies trigger-owned state (active-trigger ownership and payload) when the trigger registers.\n // Stable so payload/`stateUpdates` changes do not change the ref identity (which would needlessly\n // churn registration); it reads the latest closure values when invoked.\n const applyTriggerData = useStableCallback(element => {\n const open = store.select('open');\n const activeTriggerId = store.select('activeTriggerId');\n if (activeTriggerId === triggerId) {\n store.update({\n activeTriggerElement: element,\n ...(open ? stateUpdates : null)\n });\n return;\n }\n if (activeTriggerId == null && open) {\n // If a popup is already open, a detached trigger can mount before any active trigger\n // has been established. Claim the first registered trigger so trigger-owned focus\n // management and ARIA relationships work.\n store.update({\n activeTriggerId: triggerId,\n activeTriggerElement: element,\n ...stateUpdates\n });\n }\n });\n\n // Intentionally NOT stable. Its identity is derived from `baseRegisterTrigger`, which is keyed on\n // `[store, id]`, so when a handle-backed trigger's store pointer swaps the merged ref re-fires —\n // unregistering from the previous store and registering into the new one. This lets a detached\n // trigger follow its handle's currently-attached store across attach/detach/remount. (A stable\n // callback would keep its identity and never re-fire on a store swap.)\n const registerTrigger = React.useCallback(element => {\n baseRegisterTrigger(element);\n if (element) {\n applyTriggerData(element);\n }\n }, [baseRegisterTrigger, applyTriggerData]);\n useIsoLayoutEffect(() => {\n if (isMountedByThisTrigger) {\n store.update({\n activeTriggerElement: triggerElementRef.current,\n ...stateUpdates\n });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);\n return {\n registerTrigger,\n isMountedByThisTrigger\n };\n}\n/**\n * Keeps trigger registration state synchronized while the popup is open.\n *\n * When a popup opens without an explicit trigger id and exactly one trigger is registered, that\n * trigger is claimed as the active trigger. When the active trigger id is still registered but its\n * element changed, the active element is refreshed. When the active trigger id is missing from the\n * registry but the same element is still registered under a different id (e.g. the rendered trigger\n * carries its own DOM `id` that differs from Base UI's internal trigger id), the active id is\n * reassociated to the registered id instead of being treated as lost. When the active trigger\n * unregisters, the default path preserves existing ownership so non-closing popup families do not\n * silently claim a different trigger while staying open.\n *\n * If `closeOnActiveTriggerUnmount` is enabled, unregistering a previously resolved active trigger\n * requests a close after a microtask so a same-tick replacement trigger with the same id can\n * register first. An active trigger id that has not matched a registered trigger yet is treated as\n * pending and does not request a close.\n *\n * This should be called on the Root part.\n *\n * @param store The Store instance managing the popup state.\n * @param options Options for active trigger unmount behavior.\n */\nexport function useImplicitActiveTrigger(store, options = {}) {\n const {\n closeOnActiveTriggerUnmount = false\n } = options;\n // Distinguishes a trigger that unmounted from a new active trigger that has not hydrated yet.\n const resolvedActiveTriggerIdRef = React.useRef(null);\n const open = store.useState('open');\n const reactiveTriggerCount = store.useState('triggerCount');\n // Subscribe to the active trigger id so the reconciliation below reruns when ownership moves to\n // another trigger while the popup stays open (e.g. a focus/hover handoff between triggers).\n const activeTriggerId = store.useState('activeTriggerId');\n // Subscribe to the active trigger element so the reconciliation reruns when a pending active\n // trigger registers in a commit where the trigger count nets out unchanged (registration\n // forwards the element to the store when the registering trigger matches the active id).\n // Without this, the id would never be marked resolved and a later genuine unmount would be\n // misclassified as pending, disabling `closeOnActiveTriggerUnmount`.\n const reactiveActiveTriggerElement = store.useState('activeTriggerElement');\n useIsoLayoutEffect(() => {\n if (!open) {\n resolvedActiveTriggerIdRef.current = null;\n if (store.state.triggerCount !== 0) {\n store.set('triggerCount', 0);\n }\n return;\n }\n const triggerCount = store.context.triggerElements.size;\n const stateUpdates = {};\n if (store.state.triggerCount !== triggerCount) {\n stateUpdates.triggerCount = triggerCount;\n }\n const currentActiveTriggerId = store.select('activeTriggerId');\n let lostActiveTriggerId = null;\n if (currentActiveTriggerId) {\n const activeTriggerElement = store.context.triggerElements.getById(currentActiveTriggerId);\n if (!activeTriggerElement) {\n for (const [triggerId, triggerElement] of store.context.triggerElements.entries()) {\n if (triggerElement === store.state.activeTriggerElement) {\n stateUpdates.activeTriggerId = triggerId;\n stateUpdates.activeTriggerElement = triggerElement;\n resolvedActiveTriggerIdRef.current = triggerId;\n break;\n }\n }\n if (stateUpdates.activeTriggerId === undefined) {\n if (resolvedActiveTriggerIdRef.current === currentActiveTriggerId) {\n lostActiveTriggerId = currentActiveTriggerId;\n } else {\n resolvedActiveTriggerIdRef.current = null;\n }\n }\n } else {\n resolvedActiveTriggerIdRef.current = currentActiveTriggerId;\n if (activeTriggerElement !== store.state.activeTriggerElement) {\n stateUpdates.activeTriggerElement = activeTriggerElement;\n }\n }\n } else {\n resolvedActiveTriggerIdRef.current = null;\n }\n if (!lostActiveTriggerId && !currentActiveTriggerId && triggerCount === 1) {\n const iteratorResult = store.context.triggerElements.entries().next();\n if (!iteratorResult.done) {\n const [implicitTriggerId, implicitTriggerElement] = iteratorResult.value;\n stateUpdates.activeTriggerId = implicitTriggerId;\n stateUpdates.activeTriggerElement = implicitTriggerElement;\n resolvedActiveTriggerIdRef.current = implicitTriggerId;\n }\n }\n if (stateUpdates.triggerCount !== undefined || stateUpdates.activeTriggerId !== undefined || stateUpdates.activeTriggerElement !== undefined) {\n store.update(stateUpdates);\n }\n if (lostActiveTriggerId) {\n if (closeOnActiveTriggerUnmount) {\n // Defer so a same-tick replacement trigger with the same id can register first.\n queueMicrotask(() => {\n if (store.select('open') && store.select('activeTriggerId') === lostActiveTriggerId && !store.context.triggerElements.getById(lostActiveTriggerId)) {\n const eventDetails = createChangeEventDetails(REASONS.none);\n store.setOpen(false, eventDetails);\n // If closing is canceled, keep the previous active trigger ownership for the\n // still-open popup instead of claiming another trigger implicitly.\n if (!eventDetails.isCanceled) {\n store.update({\n activeTriggerId: null,\n activeTriggerElement: null\n });\n }\n }\n });\n }\n }\n }, [open, store, reactiveTriggerCount, activeTriggerId, reactiveActiveTriggerElement, closeOnActiveTriggerUnmount]);\n}\n\n/**\n * Manages the mounted state of the popup.\n * Sets up the transition status listeners and handles unmounting when needed.\n * Updates the `mounted`, `transitionStatus`, and `preventUnmountingOnClose` states in the store.\n *\n * @param open Whether the popup is open.\n * @param store The Store instance managing the popup state.\n * @param onUnmount Optional callback to be called when the popup is unmounted.\n *\n * @returns A function to forcibly unmount the popup.\n */\nexport function useOpenStateTransitions(open, store, onUnmount) {\n const {\n mounted,\n setMounted,\n transitionStatus\n } = useTransitionStatus(open);\n const preventUnmountingOnClose = store.useState('preventUnmountingOnClose');\n // Opening starts a new close cycle. Clear during render so the close-completion hook below\n // reads the synchronized value on the same pass.\n const syncedPreventUnmountingOnClose = open ? false : preventUnmountingOnClose;\n store.useSyncedValues({\n mounted,\n transitionStatus,\n preventUnmountingOnClose: syncedPreventUnmountingOnClose\n });\n const forceUnmount = useStableCallback(() => {\n setMounted(false);\n store.update({\n activeTriggerId: null,\n activeTriggerElement: null,\n mounted: false,\n preventUnmountingOnClose: false\n });\n onUnmount?.();\n store.context.onOpenChangeComplete?.(false);\n });\n useOpenChangeComplete({\n enabled: mounted && !open && !syncedPreventUnmountingOnClose,\n open,\n ref: store.context.popupRef,\n onComplete() {\n if (!open) {\n forceUnmount();\n }\n }\n });\n return {\n forceUnmount,\n transitionStatus\n };\n}\nexport function usePopupInteractionProps(store, statePart) {\n store.useSyncedValues(statePart);\n useIsoLayoutEffect(() => () => {\n store.update({\n activeTriggerProps: EMPTY_OBJECT,\n inactiveTriggerProps: EMPTY_OBJECT,\n popupProps: EMPTY_OBJECT\n });\n }, [store]);\n}\nexport function usePopupRootSync(store, open) {\n useIsoLayoutEffect(() => {\n if (!open && store.state.openMethod !== null) {\n store.set('openMethod', null);\n }\n }, [open, store]);\n useIsoLayoutEffect(() => () => {\n if (store.state.openMethod !== null) {\n store.set('openMethod', null);\n }\n }, [store]);\n}","/**\n * Development-only reverse index of element to registered id, keyed by the owning map.\n *\n * Registration would otherwise have to scan every entry to detect an element claimed by two ids,\n * making the mount of many triggers sharing one handle quadratic. Kept module-scoped, lazily\n * initialized, and read only from `process.env.NODE_ENV` guards so production builds drop it along\n * with the checks.\n */\nlet devElementIdsByMap;\nfunction getDevElementIds(map) {\n devElementIdsByMap ??= new WeakMap();\n let elementIds = devElementIdsByMap.get(map);\n if (!elementIds) {\n elementIds = new WeakMap();\n devElementIdsByMap.set(map, elementIds);\n }\n return elementIds;\n}\n\n/**\n * Data structure to keep track of popup trigger elements by their IDs.\n *\n * Element lookups iterate the id map rather than maintaining a parallel Set. Registration is O(1),\n * while `hasElement` and `hasMatchingElement` are linear in the number of triggers.\n */\nexport class PopupTriggerMap {\n constructor() {\n this.idMap = new Map();\n }\n\n /**\n * Adds a trigger element with the given ID.\n *\n * Note: The provided element is assumed to not be registered under multiple IDs.\n */\n add(id, element) {\n if (process.env.NODE_ENV !== 'production') {\n const elementIds = getDevElementIds(this);\n const existingId = elementIds.get(element);\n if (existingId !== undefined && existingId !== id) {\n // TODO: fix mui/no-guarded-throw\n // eslint-disable-next-line mui/no-guarded-throw\n throw new Error('Base UI: A trigger element cannot be registered under multiple IDs in PopupTriggerMap.');\n }\n\n // Reusing an id for a different element evicts the previous one, so it must lose its claim\n // on the id or a later registration under a different id would be reported as a duplicate.\n const previousElement = this.idMap.get(id);\n if (previousElement !== undefined && previousElement !== element) {\n elementIds.delete(previousElement);\n }\n elementIds.set(element, id);\n }\n this.idMap.set(id, element);\n }\n\n /**\n * Removes the trigger element with the given ID.\n */\n delete(id) {\n if (process.env.NODE_ENV !== 'production') {\n const element = this.idMap.get(id);\n if (element !== undefined) {\n devElementIdsByMap?.get(this)?.delete(element);\n }\n }\n this.idMap.delete(id);\n }\n\n /**\n * Whether the given element is registered as a trigger.\n */\n hasElement(element) {\n for (const registered of this.idMap.values()) {\n if (registered === element) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Whether there is a registered trigger element matching the given predicate.\n */\n hasMatchingElement(predicate) {\n for (const element of this.idMap.values()) {\n if (predicate(element)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Returns the trigger element associated with the given ID, or undefined if no such element exists.\n */\n getById(id) {\n return this.idMap.get(id);\n }\n\n /**\n * Returns an iterable of all registered trigger entries, where each entry is a tuple of [id, element].\n */\n entries() {\n return this.idMap.entries();\n }\n\n /**\n * Returns an iterable of all registered trigger elements.\n */\n elements() {\n return this.idMap.values();\n }\n\n /**\n * Returns the number of registered trigger elements.\n */\n get size() {\n return this.idMap.size;\n }\n}","import { PopupTriggerMap } from \"../../utils/popups/index.mjs\";\nimport { FloatingRootStore } from \"../components/FloatingRootStore.mjs\";\nexport function getEmptyRootContext() {\n return new FloatingRootStore({\n open: false,\n transitionStatus: undefined,\n floatingElement: null,\n referenceElement: null,\n triggerElements: new PopupTriggerMap(),\n floatingId: undefined,\n syncOnly: false,\n nested: false,\n onOpenChange: undefined\n });\n}","import { EMPTY_OBJECT } from '@base-ui/utils/empty';\nimport { FloatingRootStore } from \"../../floating-ui-react/components/FloatingRootStore.mjs\";\nimport { getEmptyRootContext } from \"../../floating-ui-react/utils/getEmptyRootContext.mjs\";\n\n/**\n * State common to all popup stores.\n */\n\nexport function createInitialPopupStoreState() {\n return {\n open: false,\n openProp: undefined,\n mounted: false,\n transitionStatus: undefined,\n floatingRootContext: getEmptyRootContext(),\n floatingId: undefined,\n triggerCount: 0,\n preventUnmountingOnClose: false,\n payload: undefined,\n activeTriggerId: null,\n activeTriggerElement: null,\n triggerIdProp: undefined,\n popupElement: null,\n positionerElement: null,\n activeTriggerProps: EMPTY_OBJECT,\n inactiveTriggerProps: EMPTY_OBJECT,\n popupProps: EMPTY_OBJECT\n };\n}\nexport function createPopupFloatingRootContext(triggerElements, floatingId, nested = false) {\n return new FloatingRootStore({\n open: false,\n transitionStatus: undefined,\n floatingElement: null,\n referenceElement: null,\n triggerElements,\n floatingId,\n syncOnly: true,\n nested,\n onOpenChange: undefined\n });\n}\nconst activeTriggerIdSelector = state => state.triggerIdProp ?? state.activeTriggerId;\nconst openSelector = state => state.openProp ?? state.open;\nconst popupIdSelector = state => {\n const popupId = state.popupElement?.id ?? state.floatingId;\n return popupId || undefined;\n};\nfunction triggerOwnsOpenPopup(state, triggerId) {\n return triggerId !== undefined && openSelector(state) && activeTriggerIdSelector(state) === triggerId;\n}\nfunction triggerOwnsOpenPopupOrIsOnlyTrigger(state, triggerId) {\n if (triggerOwnsOpenPopup(state, triggerId)) {\n return true;\n }\n return triggerId !== undefined && openSelector(state) && activeTriggerIdSelector(state) == null && state.triggerCount === 1;\n}\nexport const popupStoreSelectors = {\n open: openSelector,\n mounted: state => state.mounted,\n transitionStatus: state => state.transitionStatus,\n floatingRootContext: state => state.floatingRootContext,\n triggerCount: state => state.triggerCount,\n preventUnmountingOnClose: state => state.preventUnmountingOnClose,\n payload: state => state.payload,\n activeTriggerId: activeTriggerIdSelector,\n activeTriggerElement: state => state.mounted ? state.activeTriggerElement : null,\n popupId: popupIdSelector,\n /**\n * Whether the trigger with the given ID was used to open the popup.\n */\n isTriggerActive: (state, triggerId) => triggerId !== undefined && activeTriggerIdSelector(state) === triggerId,\n /**\n * Whether the popup is open and was activated by a trigger with the given ID.\n */\n isOpenedByTrigger: (state, triggerId) => triggerOwnsOpenPopup(state, triggerId),\n /**\n * Whether the popup is mounted and was activated by a trigger with the given ID.\n */\n isMountedByTrigger: (state, triggerId) => triggerId !== undefined && activeTriggerIdSelector(state) === triggerId && state.mounted,\n triggerProps: (state, isActive) => isActive ? state.activeTriggerProps : state.inactiveTriggerProps,\n /**\n * Popup id for the trigger that currently owns the open popup.\n */\n triggerPopupId: (state, triggerId) => triggerOwnsOpenPopupOrIsOnlyTrigger(state, triggerId) ? popupIdSelector(state) : undefined,\n popupProps: state => state.popupProps,\n popupElement: state => state.popupElement,\n positionerElement: state => state.positionerElement\n};\n\n/**\n * Store members a detached handle-backed trigger reads or invokes for trigger registration and data\n * forwarding. `set`/`update` are included only for trigger-count and trigger-data bookkeeping; on a\n * detached (inert) store they are intentionally no-ops, so a write through them is not guaranteed to\n * be durable. Component handle-store views Pick these from their concrete store (preserving its\n * context and selectors) and add any component-specific trigger-invoked members such as `setOpen`.\n */\n\n/**\n * The subset of a popup store that trigger registration and data forwarding rely on. Narrow enough\n * that an inert store can be passed while detached.\n */","'use client';\n\nimport _formatErrorMessage from \"@base-ui/utils/formatErrorMessage\";\nimport * as React from 'react';\nexport const DialogPortalContext = /*#__PURE__*/React.createContext(undefined);\nif (process.env.NODE_ENV !== \"production\") DialogPortalContext.displayName = \"DialogPortalContext\";\nexport function useDialogPortalContext() {\n const value = React.useContext(DialogPortalContext);\n if (value === undefined) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'Base UI: <Dialog.Portal> is missing.' : _formatErrorMessage(26));\n }\n return value;\n}","import { isHTMLElement } from '@floating-ui/utils/dom';\nexport { stopEvent, isIndexOutOfListBounds, isListIndexDisabled, findNonDisabledListIndex, getMaxListIndex, getMinListIndex } from \"../../floating-ui-react/utils.mjs\";\nexport const ARROW_UP = 'ArrowUp';\nexport const ARROW_DOWN = 'ArrowDown';\nexport const ARROW_LEFT = 'ArrowLeft';\nexport const ARROW_RIGHT = 'ArrowRight';\nexport const HOME = 'Home';\nexport const END = 'End';\nexport const PAGE_UP = 'PageUp';\nexport const PAGE_DOWN = 'PageDown';\nexport const COMPOSITE_KEYS = new Set([ARROW_UP, ARROW_DOWN, ARROW_LEFT, ARROW_RIGHT, HOME, END]);\nexport const SHIFT = 'Shift';\nexport const MODIFIER_KEYS = [SHIFT, 'Control', 'Alt', 'Meta'];\nfunction isInputElement(element) {\n return isHTMLElement(element) && element.tagName === 'INPUT';\n}\nexport function isNativeInput(element) {\n if (isInputElement(element) && element.selectionStart != null) {\n return true;\n }\n if (isHTMLElement(element) && element.tagName === 'TEXTAREA') {\n return true;\n }\n return false;\n}\nexport function scrollIntoViewIfNeeded(scrollContainer, element, direction, orientation) {\n if (!scrollContainer || !element || !element.scrollTo) {\n return;\n }\n let targetX = scrollContainer.scrollLeft;\n let targetY = scrollContainer.scrollTop;\n const isOverflowingX = scrollContainer.clientWidth < scrollContainer.scrollWidth;\n const isOverflowingY = scrollContainer.clientHeight < scrollContainer.scrollHeight;\n if (isOverflowingX && orientation !== 'vertical') {\n const elementOffsetLeft = getOffset(scrollContainer, element, 'left');\n const containerStyles = getStyles(scrollContainer);\n const elementStyles = getStyles(element);\n if (direction === 'ltr') {\n if (elementOffsetLeft + element.offsetWidth + elementStyles.scrollMarginRight > scrollContainer.scrollLeft + scrollContainer.clientWidth - containerStyles.scrollPaddingRight) {\n // overflow to the right, scroll to align right edges\n targetX = elementOffsetLeft + element.offsetWidth + elementStyles.scrollMarginRight - scrollContainer.clientWidth + containerStyles.scrollPaddingRight;\n } else if (elementOffsetLeft - elementStyles.scrollMarginLeft < scrollContainer.scrollLeft + containerStyles.scrollPaddingLeft) {\n // overflow to the left, scroll to align left edges\n targetX = elementOffsetLeft - elementStyles.scrollMarginLeft - containerStyles.scrollPaddingLeft;\n }\n }\n if (direction === 'rtl') {\n if (elementOffsetLeft - elementStyles.scrollMarginLeft < scrollContainer.scrollLeft + containerStyles.scrollPaddingLeft) {\n // overflow to the left, scroll to align left edges\n targetX = elementOffsetLeft - elementStyles.scrollMarginLeft - containerStyles.scrollPaddingLeft;\n } else if (elementOffsetLeft + element.offsetWidth + elementStyles.scrollMarginRight > scrollContainer.scrollLeft + scrollContainer.clientWidth - containerStyles.scrollPaddingRight) {\n // overflow to the right, scroll to align right edges\n targetX = elementOffsetLeft + element.offsetWidth + elementStyles.scrollMarginRight - scrollContainer.clientWidth + containerStyles.scrollPaddingRight;\n }\n }\n }\n if (isOverflowingY && orientation !== 'horizontal') {\n const elementOffsetTop = getOffset(scrollContainer, element, 'top');\n const containerStyles = getStyles(scrollContainer);\n const elementStyles = getStyles(element);\n if (elementOffsetTop - elementStyles.scrollMarginTop < scrollContainer.scrollTop + containerStyles.scrollPaddingTop) {\n // overflow upwards, align top edges\n targetY = elementOffsetTop - elementStyles.scrollMarginTop - containerStyles.scrollPaddingTop;\n } else if (elementOffsetTop + element.offsetHeight + elementStyles.scrollMarginBottom > scrollContainer.scrollTop + scrollContainer.clientHeight - containerStyles.scrollPaddingBottom) {\n // overflow downwards, align bottom edges\n targetY = elementOffsetTop + element.offsetHeight + elementStyles.scrollMarginBottom - scrollContainer.clientHeight + containerStyles.scrollPaddingBottom;\n }\n }\n scrollContainer.scrollTo({\n left: targetX,\n top: targetY,\n behavior: 'auto'\n });\n}\nfunction getOffset(ancestor, element, side) {\n const propName = side === 'left' ? 'offsetLeft' : 'offsetTop';\n let result = 0;\n while (element.offsetParent) {\n result += element[propName];\n if (element.offsetParent === ancestor) {\n break;\n }\n element = element.offsetParent;\n }\n return result;\n}\nfunction getStyles(element) {\n const styles = getComputedStyle(element);\n return {\n scrollMarginTop: parseFloat(styles.scrollMarginTop) || 0,\n scrollMarginRight: parseFloat(styles.scrollMarginRight) || 0,\n scrollMarginBottom: parseFloat(styles.scrollMarginBottom) || 0,\n scrollMarginLeft: parseFloat(styles.scrollMarginLeft) || 0,\n scrollPaddingTop: parseFloat(styles.scrollPaddingTop) || 0,\n scrollPaddingRight: parseFloat(styles.scrollPaddingRight) || 0,\n scrollPaddingBottom: parseFloat(styles.scrollPaddingBottom) || 0,\n scrollPaddingLeft: parseFloat(styles.scrollPaddingLeft) || 0\n };\n}","import { transitionStatusMapping } from \"../../internals/stateAttributesMapping.mjs\";\nimport { popupStateMapping } from \"../../utils/popupStateMapping.mjs\";\n/**\n * Shared by `Dialog.Popup` and `Dialog.Viewport`, whose states have the same shape.\n * `nested` is not mapped: unmapped `true` booleans already render as `data-nested`.\n */\nexport const dialogStateAttributesMapping = {\n ...popupStateMapping,\n ...transitionStatusMapping,\n nestedDialogOpen(value) {\n return value ? {\n 'data-nested-dialog-open': ''\n } : null;\n }\n};","'use client';\n\nimport * as React from 'react';\nimport { FloatingFocusManager } from \"../../floating-ui-react/index.mjs\";\nimport { useDialogRootContext } from \"../root/DialogRootContext.mjs\";\nimport { useRenderElement } from \"../../internals/useRenderElement.mjs\";\nimport { useDialogPortalContext } from \"../portal/DialogPortalContext.mjs\";\nimport { useOpenChangeComplete } from \"../../internals/useOpenChangeComplete.mjs\";\nimport { COMPOSITE_KEYS } from \"../../internals/composite/composite.mjs\";\nimport { FOCUSABLE_POPUP_PROPS, createDefaultInitialFocus } from \"../../utils/popups/index.mjs\";\nimport { dialogStateAttributesMapping } from \"../utils/stateAttributesMapping.mjs\";\n\n/**\n * A container for the dialog contents.\n * Renders a `<div>` element.\n *\n * Documentation: [Base UI Dialog](https://base-ui.com/react/components/dialog)\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport const DialogPopup = /*#__PURE__*/React.forwardRef(function DialogPopup(componentProps, forwardedRef) {\n const {\n render,\n className,\n style,\n finalFocus,\n initialFocus,\n ...elementProps\n } = componentProps;\n const store = useDialogRootContext();\n const descriptionElementId = store.useState('descriptionElementId');\n const disablePointerDismissal = store.useState('disablePointerDismissal');\n const floatingRootContext = store.useState('floatingRootContext');\n const rootPopupProps = store.useState('popupProps');\n const modal = store.useState('modal');\n const mounted = store.useState('mounted');\n const nested = store.useState('nested');\n const nestedOpenDialogCount = store.useState('nestedOpenDialogCount');\n const open = store.useState('open');\n const openMethod = store.useState('openMethod');\n const titleElementId = store.useState('titleElementId');\n const transitionStatus = store.useState('transitionStatus');\n const role = store.useState('role');\n const floatingId = floatingRootContext.useState('floatingId');\n useDialogPortalContext();\n useOpenChangeComplete({\n open,\n ref: store.context.popupRef,\n onComplete() {\n if (open) {\n store.context.onOpenChangeComplete?.(true);\n }\n }\n });\n const resolvedInitialFocus = initialFocus === undefined ? createDefaultInitialFocus(store.context.popupRef) : initialFocus;\n const nestedDialogOpen = nestedOpenDialogCount > 0;\n const setPopupElement = store.useStateSetter('popupElement');\n const state = {\n open,\n nested,\n transitionStatus,\n nestedDialogOpen\n };\n const element = useRenderElement('div', componentProps, {\n state,\n props: [rootPopupProps, {\n id: floatingId,\n 'aria-labelledby': titleElementId,\n 'aria-describedby': descriptionElementId,\n role,\n ...FOCUSABLE_POPUP_PROPS,\n hidden: !mounted,\n onKeyDown(event) {\n if (COMPOSITE_KEYS.has(event.key)) {\n event.stopPropagation();\n }\n },\n style: {\n '--nested-dialogs': nestedOpenDialogCount\n }\n }, elementProps],\n ref: [forwardedRef, store.context.popupRef, setPopupElement],\n stateAttributesMapping: dialogStateAttributesMapping\n });\n return /*#__PURE__*/_jsx(FloatingFocusManager, {\n context: floatingRootContext,\n openInteractionType: openMethod,\n disabled: !mounted,\n closeOnFocusOut: !disablePointerDismissal,\n initialFocus: resolvedInitialFocus,\n returnFocus: finalFocus,\n modal: modal !== false,\n restoreFocus: \"popup\",\n children: element\n });\n});\nif (process.env.NODE_ENV !== \"production\") DialogPopup.displayName = \"DialogPopup\";","import { isReactVersionAtLeast } from \"./reactVersion.mjs\";\nexport function inertValue(value) {\n if (isReactVersionAtLeast(19)) {\n return value;\n }\n // compatibility with React < 19\n return value ? 'true' : undefined;\n}","import * as React from 'react';\n\n/**\n * @internal\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport const InternalBackdrop = /*#__PURE__*/React.forwardRef(function InternalBackdrop(props, ref) {\n const {\n cutout,\n ...otherProps\n } = props;\n let clipPath;\n if (cutout) {\n const rect = cutout.getBoundingClientRect();\n clipPath = `polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${rect.left}px ${rect.top}px,${rect.left}px ${rect.bottom}px,${rect.right}px ${rect.bottom}px,${rect.right}px ${rect.top}px,${rect.left}px ${rect.top}px)`;\n }\n return /*#__PURE__*/_jsx(\"div\", {\n ref: ref,\n role: \"presentation\"\n // Ensures Floating UI's outside press detection runs, as it considers\n // it an element that existed when the popup rendered.\n ,\n \"data-base-ui-inert\": \"\",\n ...otherProps,\n style: {\n position: 'fixed',\n inset: 0,\n userSelect: 'none',\n WebkitUserSelect: 'none',\n clipPath\n }\n });\n});\nif (process.env.NODE_ENV !== \"production\") InternalBackdrop.displayName = \"InternalBackdrop\";","'use client';\n\nimport * as React from 'react';\nimport { inertValue } from '@base-ui/utils/inertValue';\nimport { FloatingPortal } from \"../../floating-ui-react/index.mjs\";\nimport { useDialogRootContext } from \"../root/DialogRootContext.mjs\";\nimport { DialogPortalContext } from \"./DialogPortalContext.mjs\";\nimport { InternalBackdrop } from \"../../utils/InternalBackdrop.mjs\";\n\n/**\n * A portal element that moves the popup to a different part of the DOM.\n * By default, the portal element is appended to `<body>`.\n * Renders a `<div>` element.\n *\n * Documentation: [Base UI Dialog](https://base-ui.com/react/components/dialog)\n */\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nexport const DialogPortal = /*#__PURE__*/React.forwardRef(function DialogPortal(props, forwardedRef) {\n const {\n keepMounted = false,\n ...portalProps\n } = props;\n const store = useDialogRootContext();\n const mounted = store.useState('mounted');\n const modal = store.useState('modal');\n const open = store.useState('open');\n const shouldRender = mounted || keepMounted;\n if (!shouldRender) {\n return null;\n }\n return /*#__PURE__*/_jsx(DialogPortalContext.Provider, {\n value: keepMounted,\n children: /*#__PURE__*/_jsxs(FloatingPortal, {\n ref: forwardedRef,\n ...portalProps,\n children: [mounted && modal === true && /*#__PURE__*/_jsx(InternalBackdrop, {\n ref: store.context.internalBackdropRef,\n inert: inertValue(!open)\n }), props.children]\n })\n });\n});\nif (process.env.NODE_ENV !== \"production\") DialogPortal.displayName = \"DialogPortal\";","'use client';\n\nimport { isOverflowElement } from '@floating-ui/utils/dom';\nimport { addEventListener } from \"./addEventListener.mjs\";\nimport { platform } from \"./platform/index.mjs\";\nimport { ownerDocument, ownerWindow } from \"./owner.mjs\";\nimport { useIsoLayoutEffect } from \"./useIsoLayoutEffect.mjs\";\nimport { Timeout } from \"./useTimeout.mjs\";\nimport { AnimationFrame } from \"./useAnimationFrame.mjs\";\nlet originalHtmlStyles = {};\nlet originalBodyStyles = {};\nlet originalHtmlScrollBehavior = '';\n\n// The viewport's overflow comes from <html> when it establishes its own scroll container, and\n// propagates from <body> otherwise. An `overflow` style on the other element doesn't lock the page.\nfunction getViewportScroller(html, body) {\n return isOverflowElement(html) ? html : body;\n}\nfunction isPageScrollLocked(win, html, body) {\n return /hidden|clip/.test(win.getComputedStyle(getViewportScroller(html, body)).overflowY);\n}\nfunction hasInsetScrollbars(referenceElement) {\n if (typeof document === 'undefined') {\n return false;\n }\n const doc = ownerDocument(referenceElement);\n const win = ownerWindow(doc);\n return win.innerWidth - doc.documentElement.clientWidth > 0;\n}\nfunction supportsStableScrollbarGutter(referenceElement) {\n const supported = typeof CSS !== 'undefined' && CSS.supports && CSS.supports('scrollbar-gutter', 'stable');\n if (!supported || typeof document === 'undefined') {\n return false;\n }\n const doc = ownerDocument(referenceElement);\n const html = doc.documentElement;\n const body = doc.body;\n const scrollContainer = getViewportScroller(html, body);\n const originalScrollContainerOverflowY = scrollContainer.style.overflowY;\n const originalHtmlStyleGutter = html.style.scrollbarGutter;\n html.style.scrollbarGutter = 'stable';\n scrollContainer.style.overflowY = 'scroll';\n const before = scrollContainer.offsetWidth;\n scrollContainer.style.overflowY = 'hidden';\n const after = scrollContainer.offsetWidth;\n scrollContainer.style.overflowY = originalScrollContainerOverflowY;\n html.style.scrollbarGutter = originalHtmlStyleGutter;\n return before === after;\n}\nfunction preventScrollOverlayScrollbars(referenceElement) {\n const doc = ownerDocument(referenceElement);\n const html = doc.documentElement;\n const body = doc.body;\n\n // If an `overflow` style is present on <html>, we need to lock it, because a lock on <body>\n // won't have any effect.\n // But if <body> has an `overflow` style (like `overflow-x: hidden`), we need to lock it\n // instead, as sticky elements shift otherwise.\n const elementToLock = getViewportScroller(html, body);\n const originalElementToLockStyles = {\n overflowY: elementToLock.style.overflowY,\n overflowX: elementToLock.style.overflowX\n };\n Object.assign(elementToLock.style, {\n overflowY: 'hidden',\n overflowX: 'hidden'\n });\n return () => {\n Object.assign(elementToLock.style, originalElementToLockStyles);\n };\n}\nfunction preventScrollInsetScrollbars(referenceElement) {\n const doc = ownerDocument(referenceElement);\n const html = doc.documentElement;\n const body = doc.body;\n const win = ownerWindow(html);\n let scrollTop = 0;\n let scrollLeft = 0;\n let updateGutterOnly = false;\n const resizeFrame = AnimationFrame.create();\n\n // Pinch-zoom in Safari causes a shift. Just don't lock scroll if there's any pinch-zoom.\n if (platform.engine.webkit && (win.visualViewport?.scale ?? 1) !== 1) {\n return () => {};\n }\n function lockScroll() {\n /* DOM reads: */\n\n const htmlStyles = win.getComputedStyle(html);\n const bodyStyles = win.getComputedStyle(body);\n const htmlScrollbarGutterValue = htmlStyles.scrollbarGutter || '';\n const hasBothEdges = htmlScrollbarGutterValue.includes('both-edges');\n const scrollbarGutterValue = hasBothEdges ? 'stable both-edges' : 'stable';\n scrollTop = html.scrollTop;\n scrollLeft = html.scrollLeft;\n originalHtmlStyles = {\n scrollbarGutter: html.style.scrollbarGutter,\n overflowY: html.style.overflowY,\n overflowX: html.style.overflowX\n };\n originalHtmlScrollBehavior = html.style.scrollBehavior;\n originalBodyStyles = {\n position: body.style.position,\n height: body.style.height,\n width: body.style.width,\n boxSizing: body.style.boxSizing,\n overflowY: body.style.overflowY,\n overflowX: body.style.overflowX,\n scrollBehavior: body.style.scrollBehavior\n };\n const isScrollableY = html.scrollHeight > html.clientHeight;\n const isScrollableX = html.scrollWidth > html.clientWidth;\n const hasConstantOverflowY = htmlStyles.overflowY === 'scroll' || bodyStyles.overflowY === 'scroll';\n const hasConstantOverflowX = htmlStyles.overflowX === 'scroll' || bodyStyles.overflowX === 'scroll';\n\n // Values can be negative in Firefox\n const scrollbarWidth = Math.max(0, win.innerWidth - body.clientWidth);\n const scrollbarHeight = Math.max(0, win.innerHeight - body.clientHeight);\n\n // Avoid shift due to the default <body> margin. This does cause elements to be clipped\n // with whitespace. Warn if <body> has margins?\n const marginY = parseFloat(bodyStyles.marginTop) + parseFloat(bodyStyles.marginBottom);\n const marginX = parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight);\n const elementToLock = getViewportScroller(html, body);\n updateGutterOnly = supportsStableScrollbarGutter(referenceElement);\n\n /*\n * DOM writes:\n * Do not read the DOM past this point!\n */\n\n if (updateGutterOnly) {\n html.style.scrollbarGutter = scrollbarGutterValue;\n elementToLock.style.overflowY = 'hidden';\n elementToLock.style.overflowX = 'hidden';\n return;\n }\n Object.assign(html.style, {\n scrollbarGutter: scrollbarGutterValue,\n overflowY: 'hidden',\n overflowX: 'hidden'\n });\n if (isScrollableY || hasConstantOverflowY) {\n html.style.overflowY = 'scroll';\n }\n if (isScrollableX || hasConstantOverflowX) {\n html.style.overflowX = 'scroll';\n }\n Object.assign(body.style, {\n position: 'relative',\n height: marginY || scrollbarHeight ? `calc(100dvh - ${marginY + scrollbarHeight}px)` : '100dvh',\n width: marginX || scrollbarWidth ? `calc(100vw - ${marginX + scrollbarWidth}px)` : '100vw',\n boxSizing: 'border-box',\n // Assign the longhands that `cleanup` restores, so nothing is left behind.\n overflowY: 'hidden',\n overflowX: 'hidden',\n scrollBehavior: 'unset'\n });\n body.scrollTop = scrollTop;\n body.scrollLeft = scrollLeft;\n html.setAttribute('data-base-ui-scroll-locked', '');\n html.style.scrollBehavior = 'unset';\n }\n function cleanup() {\n Object.assign(html.style, originalHtmlStyles);\n Object.assign(body.style, originalBodyStyles);\n if (!updateGutterOnly) {\n html.scrollTop = scrollTop;\n html.scrollLeft = scrollLeft;\n html.removeAttribute('data-base-ui-scroll-locked');\n html.style.scrollBehavior = originalHtmlScrollBehavior;\n }\n }\n function handleResize() {\n cleanup();\n resizeFrame.request(lockScroll);\n }\n lockScroll();\n const unsubscribeResize = addEventListener(win, 'resize', handleResize);\n return () => {\n resizeFrame.cancel();\n cleanup();\n // Sometimes this cleanup can run after test teardown because it is called\n // in a `setTimeout(fn, 0)`. Guard the returned cleanup to avoid calling\n // `removeEventListener` when it is no longer available in tests.\n if (typeof win.removeEventListener === 'function') {\n unsubscribeResize();\n }\n };\n}\nclass ScrollLocker {\n lockCount = 0;\n restore = null;\n timeoutLock = Timeout.create();\n timeoutUnlock = Timeout.create();\n acquire(referenceElement) {\n this.lockCount += 1;\n if (this.lockCount === 1 && this.restore === null) {\n this.timeoutLock.start(0, () => this.lock(referenceElement));\n }\n return this.release;\n }\n release = () => {\n this.lockCount -= 1;\n if (this.lockCount === 0 && this.restore) {\n this.timeoutUnlock.start(0, this.unlock);\n }\n };\n unlock = () => {\n if (this.lockCount === 0 && this.restore) {\n this.restore?.();\n this.restore = null;\n }\n };\n lock(referenceElement) {\n if (this.lockCount === 0 || this.restore !== null) {\n return;\n }\n const doc = ownerDocument(referenceElement);\n const html = doc.documentElement;\n const body = doc.body;\n const win = ownerWindow(html);\n\n // The page is already locked, either by the site author or by a non-Base UI overlay that\n // hasn't cleaned up yet. Leave it alone and wait for the lock to clear before taking over,\n // otherwise we'd snapshot the locked state and restore it after our own lock is released.\n if (isPageScrollLocked(win, html, body)) {\n const observer = new win.MutationObserver(() => {\n if (isPageScrollLocked(win, html, body)) {\n return;\n }\n observer.disconnect();\n this.restore = null;\n this.lock(referenceElement);\n });\n\n // Watch every attribute: locks are applied through inline styles, classes, or attributes\n // paired with a stylesheet (`data-scroll-locked` in react-remove-scroll, for example).\n const options = {\n attributes: true\n };\n observer.observe(html, options);\n observer.observe(body, options);\n this.restore = () => observer.disconnect();\n return;\n }\n const hasOverlayScrollbars = platform.os.ios || !hasInsetScrollbars(referenceElement);\n\n // On iOS, scroll locking does not work if the navbar is collapsed. Due to numerous\n // side effects and bugs that arise on iOS, it must be researched extensively before\n // being enabled to ensure it doesn't cause the following issues:\n // - Textboxes must scroll into view when focused, nor cause a glitchy scroll animation.\n // - The navbar must not force itself into view and cause layout shift.\n // - Scroll containers must not flicker upon closing a popup when it has an exit animation.\n this.restore = hasOverlayScrollbars ? preventScrollOverlayScrollbars(referenceElement) : preventScrollInsetScrollbars(referenceElement);\n }\n}\nconst SCROLL_LOCKER = new ScrollLocker();\n\n/**\n * Locks the scroll of the document when enabled.\n *\n * @param enabled - Whether to enable the scroll lock.\n * @param referenceElement - Element to use as a reference for lock calculations.\n */\nexport function useScrollLock(enabled = true, referenceElement = null) {\n useIsoLayoutEffect(() => {\n if (!enabled) {\n return undefined;\n }\n return SCROLL_LOCKER.acquire(referenceElement);\n }, [enabled, referenceElement]);\n}","'use client';\n\nimport * as React from 'react';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { useScrollLock } from '@base-ui/utils/useScrollLock';\nimport { useDismiss } from \"../../floating-ui-react/index.mjs\";\nimport { contains, getTarget } from \"../../floating-ui-react/utils.mjs\";\nimport { usePopupInteractionProps } from \"../../utils/popups/index.mjs\";\nexport function DialogInteractions({\n store,\n parentContext,\n isDrawer\n}) {\n const open = store.useState('open');\n const disablePointerDismissal = store.useState('disablePointerDismissal');\n const modal = store.useState('modal');\n const popupElement = store.useState('popupElement');\n const floatingRootContext = store.useState('floatingRootContext');\n const [ownNestedOpenDialogs, setOwnNestedOpenDialogs] = React.useState(0);\n const [ownNestedOpenDrawers, setOwnNestedOpenDrawers] = React.useState(0);\n const isTopmost = ownNestedOpenDialogs === 0;\n const dismiss = useDismiss(floatingRootContext, {\n outsidePressEvent() {\n if (store.context.internalBackdropRef.current || store.context.backdropRef.current) {\n return 'intentional';\n }\n // Ensure `aria-hidden` on outside elements is removed immediately\n // on outside press when trapping focus.\n return {\n mouse: modal === 'trap-focus' ? 'sloppy' : 'intentional',\n touch: 'sloppy'\n };\n },\n outsidePress(event) {\n if (!store.context.outsidePressEnabledRef.current) {\n return false;\n }\n\n // For mouse events, only accept left button (button 0)\n // For touch events, a single touch is equivalent to left button\n if ('button' in event && event.button !== 0) {\n return false;\n }\n if ('touches' in event) {\n // Outside press can be handled on `touchend`, where the lifted point is\n // reported in `changedTouches` and `touches` contains any remaining\n // active points. Treat it as a single-finger tap only when exactly one\n // touch ended and no other fingers are still down.\n if (event.type === 'touchend') {\n if (event.changedTouches.length !== 1 || event.touches.length !== 0) {\n return false;\n }\n } else if (event.touches.length !== 1) {\n return false;\n }\n }\n const target = getTarget(event);\n if (isTopmost && !disablePointerDismissal) {\n // Only close if the click occurred on the dialog's owning backdrop.\n // This supports multiple modal dialogs that aren't nested in the React tree:\n // https://github.com/mui/base-ui/issues/1320\n if (modal) {\n const internalBackdrop = store.context.internalBackdropRef.current;\n const backdrop = store.context.backdropRef.current;\n return internalBackdrop || backdrop ? internalBackdrop === target || backdrop === target || contains(target, popupElement) && !target?.hasAttribute('data-base-ui-portal') : true;\n }\n return true;\n }\n return false;\n },\n escapeKey: isTopmost\n });\n useScrollLock(open && modal === true, popupElement);\n\n // Listen for nested open/close events on this store to maintain the counts.\n // A close notification is an open notification with zeroed counts.\n store.useContextCallback('onNestedDialogOpen', (dialogCount, drawerCount) => {\n setOwnNestedOpenDialogs(dialogCount);\n setOwnNestedOpenDrawers(drawerCount);\n });\n\n // Notify parent of our open/close state using parent callbacks, if any\n useIsoLayoutEffect(() => {\n if (parentContext?.onNestedDialogOpen) {\n if (open) {\n parentContext.onNestedDialogOpen(ownNestedOpenDialogs + 1, ownNestedOpenDrawers + (isDrawer ? 1 : 0));\n } else {\n parentContext.onNestedDialogOpen(0, 0);\n }\n }\n return () => {\n if (parentContext?.onNestedDialogOpen && open) {\n parentContext.onNestedDialogOpen(0, 0);\n }\n };\n }, [isDrawer, open, ownNestedOpenDialogs, ownNestedOpenDrawers, parentContext]);\n usePopupInteractionProps(store, {\n // `enabled` is not passed to `useDismiss`, so its props are always defined,\n // and `trigger` is the same object as `reference`.\n activeTriggerProps: dismiss.reference,\n inactiveTriggerProps: dismiss.trigger,\n // DialogPopup and DrawerPopup spread `FOCUSABLE_POPUP_PROPS` directly, so\n // this only needs to carry the dismiss handlers.\n popupProps: dismiss.floating,\n nestedOpenDialogCount: ownNestedOpenDialogs,\n nestedOpenDrawerCount: ownNestedOpenDrawers\n });\n return null;\n}","import * as React from 'react';\nimport { ReactStore } from '@base-ui/utils/store';\nimport { NullStore } from \"../../utils/NullStore.mjs\";\nimport { createPopupFloatingRootContext, createInitialPopupStoreState, popupStoreSelectors, PopupTriggerMap, setPopupOpenState } from \"../../utils/popups/index.mjs\";\nconst selectors = {\n ...popupStoreSelectors,\n modal: state => state.modal,\n nested: state => state.nested,\n nestedOpenDialogCount: state => state.nestedOpenDialogCount,\n nestedOpenDrawerCount: state => state.nestedOpenDrawerCount,\n disablePointerDismissal: state => state.disablePointerDismissal,\n openMethod: state => state.openMethod,\n descriptionElementId: state => state.descriptionElementId,\n titleElementId: state => state.titleElementId,\n viewportElement: state => state.viewportElement,\n role: state => state.role\n};\n\n/**\n * The subset of `DialogStore` that detached handle-backed triggers rely on. Both the real\n * `DialogStore` and the inert fallback store satisfy it, so a trigger can read from whichever\n * store the handle currently exposes.\n */\n\nexport class DialogStore extends ReactStore {\n constructor(initialState, floatingId, nested) {\n const triggerElements = new PopupTriggerMap();\n const state = createInitialState(initialState, triggerElements, floatingId, nested);\n super(state, createInitialContext(triggerElements), selectors);\n }\n setOpen = (nextOpen, eventDetails) => {\n eventDetails.preventUnmountOnClose = () => {\n this.set('preventUnmountingOnClose', true);\n };\n if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {\n // When closing the dialog, pass the old trigger to the onOpenChange event\n // so it's not reset too early (potentially causing focus issues in controlled scenarios).\n eventDetails.trigger = this.state.activeTriggerElement ?? undefined;\n }\n this.context.onOpenChange?.(nextOpen, eventDetails);\n if (eventDetails.isCanceled) {\n return;\n }\n this.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);\n const updatedState = {\n open: nextOpen\n };\n setPopupOpenState(updatedState, nextOpen, eventDetails.trigger);\n this.update(updatedState);\n };\n}\n\n/**\n * Creates the inert fallback store used by detached handle-backed triggers while no\n * `Dialog.Root` is attached. It preserves a dialog-specific trigger registry in context so\n * detached triggers can register before migrating to the live root store.\n */\nexport function createNullDialogStore() {\n const triggerElements = new PopupTriggerMap();\n return new NullStore(Object.freeze(createInitialState(undefined, triggerElements)), Object.freeze(createInitialContext(triggerElements)), selectors);\n}\nfunction createInitialState(initialState, triggerElements, floatingId, nested = false) {\n const state = {\n ...createInitialPopupStoreState(),\n modal: true,\n disablePointerDismissal: false,\n viewportElement: null,\n descriptionElementId: undefined,\n titleElementId: undefined,\n openMethod: null,\n nested: false,\n nestedOpenDialogCount: 0,\n nestedOpenDrawerCount: 0,\n role: 'dialog',\n ...initialState\n };\n state.floatingRootContext = createPopupFloatingRootContext(triggerElements, floatingId, nested);\n return state;\n}\nfunction createInitialContext(triggerElements) {\n return {\n popupRef: /*#__PURE__*/React.createRef(),\n backdropRef: /*#__PURE__*/React.createRef(),\n internalBackdropRef: /*#__PURE__*/React.createRef(),\n outsidePressEnabledRef: {\n current: true\n },\n triggerElements,\n onOpenChange: undefined,\n onOpenChangeComplete: undefined\n };\n}","'use client';\n\nimport * as React from 'react';\nimport { DialogInteractions } from \"./useDialogRoot.mjs\";\nimport { DialogRootContext, useDialogRootContext } from \"./DialogRootContext.mjs\";\nimport { DialogStore } from \"../store/DialogStore.mjs\";\nimport { createChangeEventDetails } from \"../../internals/createBaseUIEventDetails.mjs\";\nimport { REASONS } from \"../../internals/reasons.mjs\";\nimport { useImplicitActiveTrigger, useOpenStateTransitions, PopupHandleAttachment, usePopupRootStore, usePopupRootSync } from \"../../utils/popups/index.mjs\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nexport function useRenderDialogRoot(mode, props) {\n const {\n children,\n open: openProp,\n defaultOpen = false,\n onOpenChange,\n onOpenChangeComplete,\n disablePointerDismissal: disablePointerDismissalProp = false,\n modal: modalProp = true,\n actionsRef,\n handle,\n triggerId: triggerIdProp,\n defaultTriggerId: defaultTriggerIdProp = null\n } = props;\n const isDrawer = mode === 'drawer';\n const isAlertDialog = mode === 'alert-dialog';\n const modal = isAlertDialog ? true : modalProp;\n const disablePointerDismissal = isAlertDialog || disablePointerDismissalProp;\n const role = isAlertDialog ? 'alertdialog' : 'dialog';\n const parentStore = useDialogRootContext(true);\n const nested = parentStore != null;\n const rootState = {\n modal,\n disablePointerDismissal,\n nested,\n role\n };\n\n // The store is owned by this Root instance and created exactly once. It is not tied to the handle:\n // the handle attaches to it, so swapping the handle re-attaches rather than recreating state.\n // Default values are only initial values; controlled values and root state are synced after creation.\n // Dialogs pass the popup element to Floating UI as the floating element (`treatPopupAsFloatingElement`).\n const store = usePopupRootStore((floatingId, floatingNested) => new DialogStore({\n open: defaultOpen,\n openProp,\n activeTriggerId: defaultTriggerIdProp,\n triggerIdProp,\n ...rootState\n }, floatingId, floatingNested), true);\n store.useControlledProp('openProp', openProp);\n store.useControlledProp('triggerIdProp', triggerIdProp);\n store.useSyncedValues(rootState);\n store.useContextCallback('onOpenChange', onOpenChange);\n store.useContextCallback('onOpenChangeComplete', onOpenChangeComplete);\n const open = store.useState('open');\n const mounted = store.useState('mounted');\n const payload = store.useState('payload');\n usePopupRootSync(store, open);\n useImplicitActiveTrigger(store);\n const {\n forceUnmount\n } = useOpenStateTransitions(open, store);\n React.useImperativeHandle(actionsRef, () => ({\n unmount: forceUnmount,\n close: () => store.setOpen(false, createChangeEventDetails(REASONS.imperativeAction))\n }), [forceUnmount, store]);\n const shouldRenderInteractions = open || mounted;\n return /*#__PURE__*/_jsxs(DialogRootContext.Provider, {\n value: store,\n children: [handle && /*#__PURE__*/_jsx(PopupHandleAttachment, {\n handle: handle,\n store: store\n }), shouldRenderInteractions && /*#__PURE__*/_jsx(DialogInteractions, {\n store: store,\n parentContext: parentStore?.context,\n isDrawer: isDrawer\n }), typeof children === 'function' ? children({\n payload\n }) : children]\n });\n}","'use client';\n\nimport { useRenderDialogRoot } from \"./useRenderDialogRoot.mjs\";\n\n/**\n * Groups all parts of the dialog.\n * Doesn't render its own HTML element.\n *\n * Documentation: [Base UI Dialog](https://base-ui.com/react/components/dialog)\n */\nexport function DialogRoot(props) {\n return useRenderDialogRoot('dialog', props);\n}","'use client';\n\nimport * as React from 'react';\nimport { useDialogRootContext } from \"../root/DialogRootContext.mjs\";\nimport { useRenderElement } from \"../../internals/useRenderElement.mjs\";\nimport { useBaseUiId } from \"../../internals/useBaseUiId.mjs\";\n/**\n * A heading that labels the dialog.\n * Renders an `<h2>` element.\n *\n * Documentation: [Base UI Dialog](https://base-ui.com/react/components/dialog)\n */\nexport const DialogTitle = /*#__PURE__*/React.forwardRef(function DialogTitle(componentProps, forwardedRef) {\n const {\n render,\n className,\n style,\n id: idProp,\n ...elementProps\n } = componentProps;\n const store = useDialogRootContext();\n const id = useBaseUiId(idProp);\n store.useSyncedValueWithCleanup('titleElementId', id);\n return useRenderElement('h2', componentProps, {\n ref: forwardedRef,\n props: [{\n id\n }, elementProps]\n });\n});\nif (process.env.NODE_ENV !== \"production\") DialogTitle.displayName = \"DialogTitle\";","import { Dialog } from '@base-ui/react/dialog';\nimport React from 'react';\n\nimport { usePortalContainer } from '../../context/WidgetProviders';\nimport { getElevationStyle } from '../../design-system/component-tokens';\nimport { LAYER_TOKENS } from '../../design-system/layers';\nimport { Button } from '../base/Button';\nimport { Flex } from '../base/Flex';\n\nexport interface WidgetDialogProps {\n open: boolean;\n onClose: () => void;\n title: string;\n description?: string;\n onConfirm?: () => void;\n confirmLabel?: string;\n cancelLabel?: string;\n}\n\nexport const WidgetDialog: React.FC<WidgetDialogProps> = ({\n open,\n onClose,\n title,\n description,\n onConfirm,\n confirmLabel = 'Confirm',\n cancelLabel = 'Cancel',\n}) => {\n const portalContainer = usePortalContainer();\n\n return (\n <Dialog.Root\n open={open}\n onOpenChange={(next, eventDetails) => {\n if (!next && eventDetails.reason !== 'none') onClose();\n }}\n >\n <Dialog.Portal container={portalContainer}>\n <Dialog.Backdrop\n className='fixed inset-0 bg-black/20 animate-dialog-overlay-in'\n style={{ zIndex: LAYER_TOKENS.dialog }}\n />\n <Dialog.Popup\n className='fixed top-1/2 left-1/2 flex max-h-[85vh] w-full max-w-sm -translate-x-1/2 -translate-y-1/2 flex-col overflow-auto rounded-lg bg-card p-4 animate-dialog-content-in'\n style={{ ...getElevationStyle('panel'), zIndex: LAYER_TOKENS.dialog }}\n >\n <Dialog.Title className='mb-1 text-base font-semibold text-foreground'>{title}</Dialog.Title>\n {description != null && (\n <Dialog.Description className='mb-4 text-sm leading-relaxed text-foreground-muted'>\n {description}\n </Dialog.Description>\n )}\n <Flex gap='md' justify='end'>\n <Button\n type='button'\n variant='secondary'\n size='sm'\n shape='pill'\n onClick={e => {\n e.preventDefault();\n e.stopPropagation();\n onClose();\n }}\n >\n {cancelLabel}\n </Button>\n <Button\n type='button'\n variant='primary'\n size='sm'\n shape='pill'\n onClick={e => {\n e.preventDefault();\n e.stopPropagation();\n onConfirm?.();\n }}\n >\n {confirmLabel}\n </Button>\n </Flex>\n </Dialog.Popup>\n </Dialog.Portal>\n </Dialog.Root>\n );\n};\n","import type { CSSProperties, Ref } from 'react';\n\nimport { cn } from '@/lib/utils';\n\ntype SpinnerSize = 'sm' | 'md' | 'lg';\n\nexport interface SpinnerProps {\n size?: SpinnerSize;\n style?: CSSProperties;\n ref?: Ref<HTMLDivElement>;\n}\n\nconst sizeStyles: Record<SpinnerSize, string> = {\n sm: 'h-3.5 w-3.5 border-[1.5px]',\n md: 'h-5 w-5 border-2',\n lg: 'h-6 w-6 border-2',\n};\n\nexport function Spinner({ size = 'md', style, ref }: SpinnerProps) {\n return (\n <div ref={ref} className='inline-flex items-center gap-1.5' data-size={size} role='status' style={style}>\n <div\n aria-hidden='true'\n className={cn('animate-spin rounded-full border-current border-t-transparent flex-shrink-0', sizeStyles[size])}\n />\n <span className='sr-only'>Loading</span>\n </div>\n );\n}\n","import React from 'react';\n\nimport { Flex } from '../base/Flex';\nimport { Spinner } from '../base/Spinner';\nimport { Text } from '../base/Text';\n\ninterface ThinkingIndicatorProps {\n isWaitingForUser: boolean;\n}\n\nexport const ThinkingIndicator: React.FC<ThinkingIndicatorProps> = ({ isWaitingForUser }) => {\n return (\n <Flex align='center' gap='sm' paddingY='2xs'>\n <Spinner size='sm' />\n <Text as='span' size='xs' weight='normal' variant='faint'>\n {isWaitingForUser ? 'Waiting for you to complete the action' : 'Thinking'}\n </Text>\n </Flex>\n );\n};\n","import React from 'react';\n\nimport { useWidget } from '../../hooks/useWidget';\nimport type { ChatMessage } from '../../types';\nimport { Flex } from '../base/Flex';\nimport { Stack } from '../base/Stack';\nimport { Surface } from '../base/Surface';\nimport { Text } from '../base/Text';\nimport { ThinkingIndicator } from './ThinkingIndicator';\n\ninterface MessageContentProps {\n message: ChatMessage;\n isLastMessage: boolean;\n}\n\nexport const MessageContent: React.FC<MessageContentProps> = ({ message, isLastMessage }) => {\n const { isTaskRunning } = useWidget().state;\n const isWaitingForUser = message.placeholderState === 'waiting-for-user';\n const showThinking = isTaskRunning && isLastMessage && (message.mode === 'show' || message.mode === 'do');\n\n if (message.parts.length > 0) {\n return (\n <Stack gap='sm'>\n {message.parts.map((part, index) => {\n if (part.type === 'text') {\n if (!part.content) return null;\n return (\n <Text\n as='div'\n key={`part-${index}`}\n size='sm'\n weight='medium'\n style={{\n wordBreak: 'break-word',\n whiteSpace: 'pre-wrap',\n marginBottom: '4px',\n }}\n >\n {part.content}\n </Text>\n );\n } else if (part.type === 'progress') {\n return (\n <Flex key={`part-${index}`} align='start' gap='md'>\n <Text as='span' size='xs' weight='medium' style={{ flex: 1, whiteSpace: 'pre-wrap' }}>\n {part.content}\n </Text>\n </Flex>\n );\n }\n return null;\n })}\n\n {((message.isPlaceholder && !message.parts.some(p => p.type === 'text')) || showThinking) && (\n <ThinkingIndicator isWaitingForUser={isWaitingForUser} />\n )}\n </Stack>\n );\n }\n\n if (message.isPlaceholder || (isTaskRunning && isLastMessage && (message.mode === 'show' || message.mode === 'do'))) {\n return <ThinkingIndicator isWaitingForUser={isWaitingForUser} />;\n }\n\n if (message.content) {\n return (\n <Text as='div' size='sm' weight='medium' style={{ wordBreak: 'break-word', whiteSpace: 'pre-wrap' }}>\n {message.content}\n </Text>\n );\n }\n\n return <Surface />;\n};\n","import React from 'react';\n\nimport { useWidgetConfig } from '../../hooks/useWidget';\nimport type { ChatMessage } from '../../types';\nimport { addOpacity } from '../../utils/color';\nimport { Icon } from '../base/Icon';\nimport type { IconName } from '../base/icons';\n\nconst STATUS_ICONS: Record<NonNullable<ChatMessage['taskStatus']>, { name: IconName; opacity: number }> = {\n done: { name: 'checkCircle', opacity: 1 },\n failed: { name: 'exclamationCircle', opacity: 0.75 },\n stopped: { name: 'circle', opacity: 0.5 },\n};\n\nexport const TaskStatusIcon: React.FC<{ status: NonNullable<ChatMessage['taskStatus']> }> = ({ status }) => {\n const { name, opacity } = STATUS_ICONS[status];\n return (\n <Icon\n name={name}\n size={14}\n style={{ color: addOpacity(useWidgetConfig().widget_accent_color, opacity), flexShrink: 0 }}\n />\n );\n};\n","import React, { useEffect, useRef, useState } from 'react';\n\nimport { Flex } from '../base/Flex';\nimport { Icon } from '../base/Icon';\nimport { Spinner } from '../base/Spinner';\nimport { Surface } from '../base/Surface';\nimport { Text } from '../base/Text';\n\ninterface VideoStreamDisplayProps {\n stream: MediaStream | null;\n}\n\nconst TOP_RADIUS = '8px';\nconst OVERLAY_BORDER_RADIUS = `${TOP_RADIUS} ${TOP_RADIUS} 0 0`;\nconst OVERLAY_BG = '#111827';\nconst MUTED_TEXT_COLOR = 'rgba(255,255,255,0.7)';\n\nconst Overlay: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (\n <Flex\n position='absolute'\n inset='0'\n align='center'\n justify='center'\n style={{ backgroundColor: OVERLAY_BG, borderRadius: OVERLAY_BORDER_RADIUS, zIndex: 10 }}\n >\n <Flex direction='column' align='center' gap='md' style={{ textAlign: 'center', padding: '0 16px' }}>\n {children}\n <Text as='span' size='xs' weight='medium' style={{ color: MUTED_TEXT_COLOR }}>\n {label}\n </Text>\n </Flex>\n </Flex>\n);\n\nexport const VideoStreamDisplay: React.FC<VideoStreamDisplayProps> = ({ stream }) => {\n const videoRef = useRef<HTMLVideoElement>(null);\n const playPromiseRef = useRef<Promise<void> | null>(null);\n const [isLoaded, setIsLoaded] = useState(false);\n const [hasError, setHasError] = useState(false);\n\n // A superseded play() rejects with AbortError; nothing can act on it, but an unhandled rejection is noisy.\n const discardPendingPlay = () => {\n playPromiseRef.current?.catch(() => undefined);\n playPromiseRef.current = null;\n };\n\n useEffect(() => {\n if (videoRef.current && stream) {\n const video = videoRef.current;\n\n setIsLoaded(false);\n setHasError(false);\n\n discardPendingPlay();\n video.srcObject = stream;\n\n const handleLoadedMetadata = () => {\n setIsLoaded(true);\n };\n\n const handleError = () => {\n setHasError(true);\n setIsLoaded(false);\n };\n\n video.addEventListener('loadedmetadata', handleLoadedMetadata);\n video.addEventListener('error', handleError);\n\n const playPromise = video.play();\n playPromiseRef.current = playPromise;\n\n playPromise\n .then(() => {\n setIsLoaded(true);\n })\n .catch(error => {\n // AbortError is expected when a new stream loads mid-play; not a real error\n if (error instanceof Error && error.name !== 'AbortError') {\n console.error('Error playing video stream:', error);\n setHasError(true);\n }\n playPromiseRef.current = null;\n });\n\n return () => {\n video.removeEventListener('loadedmetadata', handleLoadedMetadata);\n video.removeEventListener('error', handleError);\n };\n }\n\n return () => {\n discardPendingPlay();\n if (videoRef.current) {\n videoRef.current.srcObject = null;\n }\n setIsLoaded(false);\n setHasError(false);\n };\n }, [stream]);\n\n if (!stream) return null;\n\n return (\n <Surface\n width='full'\n overflow='hidden'\n position='relative'\n style={{\n marginBottom: '4px',\n borderRadius: OVERLAY_BORDER_RADIUS,\n backgroundColor: '#000000',\n boxShadow: '0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)',\n }}\n >\n {!isLoaded && !hasError && (\n <Overlay label='Loading stream...'>\n <Spinner size='lg' style={{ color: 'white' }} />\n </Overlay>\n )}\n\n {hasError && (\n <Overlay label='Failed to load stream'>\n <Icon name='alertCircle' size={32} style={{ color: '#9ca3af' }} />\n </Overlay>\n )}\n\n <video\n ref={videoRef}\n autoPlay\n muted\n playsInline\n style={{\n width: '100%',\n height: 'auto',\n maxHeight: '192px',\n objectFit: 'contain',\n borderRadius: OVERLAY_BORDER_RADIUS,\n transition: 'opacity 500ms',\n opacity: isLoaded ? 1 : 0,\n minHeight: '120px',\n background: 'linear-gradient(135deg, #111827 0%, #374151 100%)',\n }}\n />\n\n {isLoaded && !hasError && (\n <Flex\n position='absolute'\n align='center'\n gap='sm'\n animate='fadeIn'\n style={{\n top: '8px',\n right: '8px',\n padding: '4px 8px',\n borderRadius: '9999px',\n backgroundColor: 'rgba(55,65,81,0.9)',\n backdropFilter: 'blur(4px)',\n zIndex: 20,\n boxShadow: '0 2px 8px rgba(31, 41, 55, 0.4)',\n }}\n >\n <Flex position='relative' align='center' justify='center'>\n <Surface\n position='absolute'\n rounded='full'\n animate='ping'\n style={{ width: '8px', height: '8px', backgroundColor: 'white', opacity: 0.75 }}\n />\n <Surface\n position='relative'\n rounded='full'\n style={{ width: '6px', height: '6px', backgroundColor: 'white' }}\n />\n </Flex>\n <Text\n as='span'\n size='xs'\n weight='semibold'\n style={{ color: 'white', textTransform: 'uppercase', letterSpacing: '0.05em', fontSize: '10px' }}\n >\n Live\n </Text>\n </Flex>\n )}\n\n <Flex\n position='absolute'\n inset='0'\n align='center'\n justify='center'\n style={{\n borderRadius: OVERLAY_BORDER_RADIUS,\n backgroundColor: 'rgba(0,0,0,0)',\n zIndex: 30,\n pointerEvents: 'none',\n }}\n >\n <Surface\n rounded='lg'\n style={{\n padding: '4px 12px',\n backgroundColor: 'rgba(0,0,0,0.7)',\n backdropFilter: 'blur(4px)',\n }}\n >\n <Text as='div' size='xs' weight='medium' style={{ color: 'white' }}>\n Screen Sharing Active\n </Text>\n </Surface>\n </Flex>\n </Surface>\n );\n};\n","import React from 'react';\n\nimport MarketrixIcon from '../../assets/marketrix-icon.svg';\nimport type { ChatMessage } from '../../types';\nimport { formatMessageTime } from '../../utils/chat';\nimport { Avatar } from '../base/Avatar';\nimport { Button } from '../base/Button';\nimport { Flex } from '../base/Flex';\nimport { Icon } from '../base/Icon';\nimport { Stack } from '../base/Stack';\nimport { Text } from '../base/Text';\nimport { MessageContent } from './MessageContent';\nimport { TaskStatusIcon } from './TaskStatusIcon';\nimport { VideoStreamDisplay } from './VideoStreamDisplay';\n\ninterface MessageItemProps {\n message: ChatMessage;\n index: number;\n isLastMessage: boolean;\n onScreenAccessAllow?: () => void;\n onScreenAccessDeny?: () => void;\n}\n\nexport const MessageItem: React.FC<MessageItemProps> = ({\n message,\n index,\n isLastMessage,\n onScreenAccessAllow,\n onScreenAccessDeny,\n}) => {\n if (message.isSystemMessage) {\n return (\n <Flex key={`message-${message.id}-${index}`} justify='center' align='center'>\n <Text as='span' variant='faint' weight='normal' style={{ fontSize: '10px' }}>\n {message.content}\n </Text>\n </Flex>\n );\n }\n\n const isUser = message.sender === 'user';\n const leadingIcon = isUser\n ? message.mode === 'show' || message.mode === 'do'\n ? ('mousePointerClick' as const)\n : undefined\n : message.isScreenAccessRequest || message.placeholderState === 'waiting-for-user'\n ? ('checkCircle' as const)\n : undefined;\n\n return (\n <Stack\n key={`message-${message.id}-${index}`}\n style={{ marginTop: '10px' }}\n role='article'\n aria-roledescription='message'\n aria-label={isUser ? 'You said…' : 'Agent says…'}\n animate={isLastMessage ? 'fadeIn' : undefined}\n >\n <Flex align='start' gap='sm' width='full'>\n <Flex shrink={false} style={{ width: '20px', height: '20px', marginTop: '6px' }}>\n {!isUser && (\n <Avatar\n src={MarketrixIcon}\n alt='Marketrix AI'\n size={20}\n fit='cover'\n rounded='theme'\n style={{\n border: 'none',\n outline: 'none',\n display: 'block',\n backgroundColor: 'transparent',\n }}\n />\n )}\n </Flex>\n\n <Stack\n grow\n position='relative'\n rounded='theme'\n elevation='card'\n style={{\n padding: message.videoStream ? '0' : '8px 10px',\n border: '1px solid transparent',\n backgroundColor: isUser ? 'var(--primary)' : undefined,\n color: isUser ? 'var(--primary-foreground)' : 'var(--foreground)',\n }}\n >\n {message.videoStream && <VideoStreamDisplay stream={message.videoStream} />}\n {!message.videoStream &&\n (leadingIcon ? (\n <Flex align='start' gap='sm'>\n <Flex shrink={false} style={{ marginTop: '3px' }}>\n <Icon name={leadingIcon} size={13} />\n </Flex>\n <Stack grow>\n <MessageContent message={message} isLastMessage={isLastMessage} />\n </Stack>\n </Flex>\n ) : (\n <MessageContent message={message} isLastMessage={isLastMessage} />\n ))}\n\n {message.isScreenAccessRequest && !message.screenShareStatus && (\n <Flex align='center' gap='sm' style={{ marginTop: '6px' }}>\n <Button type='button' variant='primary' size='sm' shape='pill' onClick={() => onScreenAccessAllow?.()}>\n Yes\n </Button>\n <Button type='button' variant='secondary' size='sm' shape='pill' onClick={() => onScreenAccessDeny?.()}>\n No\n </Button>\n </Flex>\n )}\n\n {message.isScreenAccessRequest && message.screenShareStatus && (\n <Text as='div' variant='faint' size='xs' italic style={{ marginTop: '2px' }}>\n {message.screenShareStatus === 'allowed' ? 'Sure' : 'Check HTML Instead'}\n </Text>\n )}\n\n {!isUser && message.taskStatus && (\n <Flex position='absolute' align='center' justify='center' style={{ bottom: '4px', right: '4px' }}>\n <TaskStatusIcon status={message.taskStatus} />\n </Flex>\n )}\n </Stack>\n\n <Flex shrink={false} style={{ width: '20px' }} />\n </Flex>\n {!message.isPlaceholder && (\n <Text as='div' variant='faint' size='xxs' align='right' style={{ marginTop: '2px', marginRight: '26px' }}>\n {formatMessageTime(message.timestamp)}\n </Text>\n )}\n </Stack>\n );\n};\n","import React, { useEffect, useMemo, useRef, useState } from 'react';\n\nimport { SHADOW } from '../../design-system/shadows';\nimport { useWidget, useWidgetConfig } from '../../hooks/useWidget';\nimport type { ChatMessage } from '../../types';\nimport { addOpacity } from '../../utils/color';\nimport { Button } from '../base/Button';\nimport { Flex } from '../base/Flex';\nimport { Icon } from '../base/Icon';\nimport { IconButton } from '../base/IconButton';\nimport { Surface } from '../base/Surface';\nimport { Text } from '../base/Text';\nimport { MessageItem } from './MessageItem';\n\nconst scrollButtonStyle: React.CSSProperties = {\n boxShadow: SHADOW.button,\n backgroundColor: 'var(--card)',\n border: '1px solid var(--border)',\n pointerEvents: 'auto',\n};\n\ninterface MessageListProps {\n messagesEndRef: React.RefObject<HTMLDivElement | null>;\n onScreenAccessAllow: () => void;\n onScreenAccessDeny: () => void;\n}\n\nexport const MessageList = ({ messagesEndRef, onScreenAccessAllow, onScreenAccessDeny }: MessageListProps) => {\n const widgetConfig = useWidgetConfig();\n const { state, actions } = useWidget();\n const { messages } = state;\n const isPreviewMode = widgetConfig.isPreviewMode ?? false;\n const [showScrollTop, setShowScrollTop] = useState(false);\n const [showScrollBottom, setShowScrollBottom] = useState(false);\n const containerRef = useRef<HTMLDivElement>(null);\n\n const greetingMessage = useMemo<ChatMessage>(\n () => ({\n id: 'welcome',\n content: widgetConfig.widget_body,\n sender: 'agent',\n timestamp: new Date(),\n isPlaceholder: false,\n parts: [],\n }),\n [widgetConfig.widget_body],\n );\n const allMessages = useMemo(() => [greetingMessage, ...messages], [greetingMessage, messages]);\n\n const handleScroll = () => {\n if (containerRef.current) {\n const { scrollTop, scrollHeight, clientHeight } = containerRef.current;\n setShowScrollTop(scrollTop > 200);\n\n const isAtBottom = Math.abs(scrollHeight - scrollTop - clientHeight) < 50;\n setShowScrollBottom(!isAtBottom && scrollHeight > clientHeight);\n }\n };\n\n const scrollToTop = () => {\n containerRef.current?.scrollTo({ top: 0, behavior: 'smooth' });\n };\n\n // Skip in preview mode to prevent scrolling the parent modal\n const scrollToBottom = () => {\n if (messagesEndRef.current) {\n !isPreviewMode && messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });\n }\n };\n\n useEffect(() => {\n // rAF so the DOM is laid out and scroll height is final before we scroll\n window.requestAnimationFrame(() => {\n if (messagesEndRef.current) {\n !isPreviewMode && messagesEndRef.current.scrollIntoView({ behavior: 'auto' });\n !isPreviewMode && handleScroll();\n }\n });\n }, [messages.length, isPreviewMode]);\n\n // Follow a streaming reply: pin to bottom as the last message grows (chat/delta), unless the user scrolled away.\n const lastContentLength = messages[messages.length - 1]?.content?.length ?? 0;\n useEffect(() => {\n const el = containerRef.current;\n if (!el || isPreviewMode) return;\n const isAtBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 120;\n if (isAtBottom) {\n window.requestAnimationFrame(() => messagesEndRef.current?.scrollIntoView({ behavior: 'auto' }));\n }\n }, [lastContentLength, isPreviewMode, messagesEndRef]);\n\n return (\n <Surface position='relative' height='full'>\n <Surface\n key='message-list-container'\n ref={containerRef as React.RefObject<HTMLDivElement>}\n onScroll={handleScroll}\n role='log'\n aria-relevant='additions'\n height='full'\n overflowY='auto'\n paddingX='lg'\n paddingY='sm'\n style={{\n backgroundColor: widgetConfig.widget_background_color.includes('gradient')\n ? 'transparent'\n : widgetConfig.widget_background_color,\n backgroundImage: widgetConfig.widget_background_color.includes('gradient')\n ? widgetConfig.widget_background_color\n : `linear-gradient(135deg, ${widgetConfig.widget_background_color} 0%, ${widgetConfig.widget_background_color} 100%)`,\n scrollbarColor: `${addOpacity(widgetConfig.widget_border_color, 0.3)} ${addOpacity(widgetConfig.widget_border_color, 0.1)}`,\n scrollbarWidth: 'thin',\n }}\n >\n {allMessages.map((message: ChatMessage, index: number) => (\n <MessageItem\n key={`message-${message.id}-${index}`}\n message={message}\n index={index}\n isLastMessage={index === allMessages.length - 1}\n onScreenAccessAllow={onScreenAccessAllow}\n onScreenAccessDeny={onScreenAccessDeny}\n />\n ))}\n\n {messages.length > 0 && (\n <Flex justify='center' style={{ marginTop: '12px', marginBottom: '4px' }}>\n <Button type='button' variant='bare' onClick={actions.clearChatHistory}>\n <Text size='xs' variant='muted' style={{ cursor: 'pointer' }}>\n Clear conversation\n </Text>\n </Button>\n </Flex>\n )}\n\n <Surface key='scroll-anchor' ref={messagesEndRef as React.RefObject<HTMLDivElement>} />\n </Surface>\n\n {showScrollTop && (\n <Flex\n position='absolute'\n justify='center'\n style={{ top: '8px', left: 0, right: 0, zIndex: 10, pointerEvents: 'none' }}\n >\n <IconButton\n variant='secondary'\n size='sm'\n label='Scroll to top'\n onClick={scrollToTop}\n style={scrollButtonStyle}\n >\n <Icon name='arrowUp' size={10} style={{ color: widgetConfig.widget_accent_color }} />\n </IconButton>\n </Flex>\n )}\n\n {showScrollBottom && (\n <Flex\n position='absolute'\n justify='center'\n style={{ bottom: '8px', left: 0, right: 0, zIndex: 10, pointerEvents: 'none' }}\n >\n <IconButton\n variant='secondary'\n size='sm'\n label='Scroll to bottom'\n onClick={scrollToBottom}\n style={scrollButtonStyle}\n >\n <Icon name='arrowDown' size={10} style={{ color: widgetConfig.widget_accent_color }} />\n </IconButton>\n </Flex>\n )}\n </Surface>\n );\n};\n","import React, { useRef, useState } from 'react';\n\nimport { type PendingMessage, useScreenShare } from '../../hooks/useScreenShare';\nimport { useWidget, useWidgetConfig } from '../../hooks/useWidget';\nimport type { InstructionType } from '../../sdk';\nimport { createSystemMessage, createUserMessage } from '../../services/ChatService';\nimport { showModeService } from '../../services/ShowModeService';\nimport type { MarketrixConfig } from '../../types';\nimport { getModeDisplayName } from '../../utils/chat';\nimport { ErrorBoundary } from '../base/ErrorBoundary';\nimport { Stack } from '../base/Stack';\nimport { Surface } from '../base/Surface';\nimport { Text } from '../base/Text';\nimport { ChatInput, type ChatInputMode } from '../blocks/ChatInput';\nimport { WidgetDialog } from '../blocks/WidgetDialog';\nimport { MessageList } from '../chat/MessageList';\n\ninterface ChatViewProps {\n onScreenSharingChange: (isSharing: boolean) => void;\n onStartScreenShareRef: React.MutableRefObject<(() => void) | null>;\n onStopScreenShareRef: React.MutableRefObject<(() => void) | null>;\n messageInputRef: React.RefObject<HTMLTextAreaElement | null>;\n}\n\n// Display order, and the setting that enables each.\nconst MODES: Array<{ id: InstructionType; icon: ChatInputMode['icon']; flag: keyof MarketrixConfig }> = [\n { id: 'tell', icon: 'chatBubble', flag: 'widget_feature_tell' },\n { id: 'show', icon: 'mousePointerClick', flag: 'widget_feature_show' },\n { id: 'do', icon: 'ticktick', flag: 'widget_feature_do' },\n];\n\nexport const ChatView: React.FC<ChatViewProps> = ({\n onScreenSharingChange,\n onStartScreenShareRef,\n onStopScreenShareRef,\n messageInputRef,\n}) => {\n const config = useWidgetConfig();\n const { state, actions } = useWidget();\n const { currentMode, isTaskRunning, isAwaitingReply } = state;\n\n const [inputValue, setInputValue] = useState('');\n const messagesEndRef = useRef<HTMLDivElement>(null);\n\n const [pendingMessage, setPendingMessage] = useState<PendingMessage | null>(null);\n\n const {\n isScreenSharing,\n isAwaitingScreenAccess,\n showScreenAccessDialog,\n handleScreenAccessDialogAllow,\n handleScreenAccessDialogDismiss,\n handleScreenAccessRequestAllow,\n handleScreenAccessRequestDeny,\n requestScreenAccess,\n } = useScreenShare({\n onScreenSharingChange,\n onStartScreenShareRef,\n onStopScreenShareRef,\n onAddMessage: actions.addMessage,\n onUpdateMessage: actions.updateMessage,\n onRemoveMessage: actions.removeMessage,\n onSendMessage: actions.messageDispatch,\n pendingMessage,\n setPendingMessage,\n });\n\n const composerLocked = isAwaitingScreenAccess || isAwaitingReply;\n\n const handleSendMessage = () => {\n if (!inputValue.trim() || composerLocked) return;\n const messageContent = inputValue.trim();\n setInputValue('');\n actions.addMessage(createUserMessage(messageContent, currentMode));\n if (config.use_screenshare !== false && (currentMode === 'show' || currentMode === 'do') && !isScreenSharing) {\n setPendingMessage({ content: messageContent, mode: currentMode, alreadyAdded: true });\n requestScreenAccess(currentMode);\n } else {\n void actions.messageDispatch(messageContent, currentMode, true);\n }\n };\n\n const handleModeChange = (mode: InstructionType) => {\n if (mode === currentMode) return;\n actions.addMessage(\n createSystemMessage(`Switched to ${getModeDisplayName(mode)} mode`, mode, 'agent', 'mode-change'),\n );\n actions.setMode(mode);\n };\n\n return (\n <Stack height='full' id='view-chat' role='tabpanel' aria-labelledby='tab-chat'>\n {showScreenAccessDialog && (\n <WidgetDialog\n open={showScreenAccessDialog}\n onClose={handleScreenAccessDialogDismiss}\n title='Can I take a look at your screen?'\n description='By allowing screen access, Marketrix can understand your current context to guide you better and complete tasks on your behalf.'\n onConfirm={handleScreenAccessDialogAllow}\n confirmLabel='Yes'\n cancelLabel='No'\n />\n )}\n\n <Surface grow overflow='hidden' paddingY='2xs' style={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}>\n <ErrorBoundary\n label='Chat'\n fallback={\n <Text as='div' size='xs' align='center' variant='muted' style={{ padding: '16px' }}>\n Something went wrong displaying messages. Please refresh.\n </Text>\n }\n >\n <MessageList\n messagesEndRef={messagesEndRef}\n onScreenAccessAllow={handleScreenAccessRequestAllow}\n onScreenAccessDeny={handleScreenAccessRequestDeny}\n />\n </ErrorBoundary>\n </Surface>\n\n <Surface\n background='card'\n border\n elevation='card'\n paddingPreset='card'\n rounded='xl'\n style={{ margin: '0 12px 12px 12px', marginTop: 'auto' }}\n >\n <ChatInput\n ref={messageInputRef}\n value={inputValue}\n onChange={setInputValue}\n onSubmit={handleSendMessage}\n modes={MODES.filter(({ flag }) => config[flag]).map(({ id, icon }) => ({\n id,\n icon,\n label: getModeDisplayName(id),\n }))}\n activeMode={currentMode}\n onModeChange={handleModeChange}\n disabled={composerLocked}\n taskRunning={isTaskRunning}\n onStop={() => {\n showModeService.cleanup();\n void actions.stopTask();\n }}\n />\n </Surface>\n </Stack>\n );\n};\n","import type { InstructionType, MarketrixConfig } from '../types';\n\nexport interface SuggestedActionItem {\n id: string;\n text: string;\n type: InstructionType;\n}\n\nconst DEFAULT_CHIPS: SuggestedActionItem[] = [\n { id: 'show-add-product', text: 'Show me how to add a new product', type: 'show' },\n { id: 'show-login', text: 'Show me how to login', type: 'show' },\n { id: 'do-login', text: 'Do the login process for me', type: 'do' },\n { id: 'show-revenue', text: 'Show me the revenue metrics', type: 'show' },\n { id: 'tell-conversion-rate', text: 'What does my conversion rate mean and how can I improve it?', type: 'tell' },\n];\n\nexport function getSuggestedActionsFromConfig(config: MarketrixConfig): SuggestedActionItem[] {\n const chips = config.widget_chips;\n if (!chips?.length) return DEFAULT_CHIPS;\n\n return chips.map((chip, index) => ({\n id: `chip-${chip.chip_text.replace(/\\s+/g, '-').toLowerCase()}-${index}`,\n text: chip.chip_text,\n type: chip.chip_mode,\n }));\n}\n","import React from 'react';\n\nimport { useWidgetConfig } from '../../hooks/useWidget';\nimport type { SuggestedActionItem } from '../../utils/suggestedActions';\nimport { Button } from '../base/Button';\nimport { Stack } from '../base/Stack';\nimport { Text } from '../base/Text';\n\ninterface SuggestedActionsProps {\n actions: SuggestedActionItem[];\n onActionClick: (action: SuggestedActionItem, event: React.MouseEvent) => Promise<void>;\n}\n\nexport const SuggestedActions: React.FC<SuggestedActionsProps> = ({ actions, onActionClick }) => {\n const widgetConfig = useWidgetConfig();\n if (actions.length === 0) return null;\n\n return (\n <Stack gap='sm'>\n {actions.map((action, chipIndex) => (\n <Button\n key={`welcome-chip-${action.id}-${chipIndex}`}\n elevation='card'\n shape='theme'\n size='sm'\n variant='chip'\n full\n onClick={e => onActionClick(action, e)}\n style={{\n color: widgetConfig.widget_text_color,\n paddingTop: '8px',\n paddingBottom: '8px',\n }}\n >\n <Text as='span' weight='normal' leading='tight'>\n {action.type === 'show' ? (\n <>Show me {action.text.replace(/^Show me\\s*/i, '')}</>\n ) : action.type === 'do' ? (\n <>Do {action.text.replace(/^Do\\s*/i, '')}</>\n ) : (\n action.text\n )}\n </Text>\n </Button>\n ))}\n </Stack>\n );\n};\n","import React from 'react';\n\nimport { useWidget, useWidgetConfig } from '../../hooks/useWidget';\nimport { getSuggestedActionsFromConfig, type SuggestedActionItem } from '../../utils/suggestedActions';\nimport { Button } from '../base/Button';\nimport { Icon } from '../base/Icon';\nimport { Stack } from '../base/Stack';\nimport { Surface } from '../base/Surface';\nimport { Text } from '../base/Text';\nimport { SuggestedActions } from '../chat/SuggestedActions';\n\ninterface HomeViewProps {\n onNavigateToChat: () => void;\n onChipClick: (action: SuggestedActionItem) => void;\n}\n\nexport const HomeView: React.FC<HomeViewProps> = ({ onNavigateToChat, onChipClick }) => {\n const config = useWidgetConfig();\n const { messages } = useWidget().state;\n const suggestedActions = getSuggestedActionsFromConfig(config);\n\n const handleActionClick = async (action: SuggestedActionItem, event: React.MouseEvent) => {\n event.preventDefault();\n event.stopPropagation();\n onNavigateToChat();\n onChipClick(action);\n };\n\n return (\n <Stack height='full' overflow='hidden' id='view-home' role='tabpanel' aria-labelledby='tab-home'>\n <Stack grow overflowY='auto' padding='lg'>\n <Surface style={{ textAlign: 'center', paddingTop: '8px', paddingBottom: '16px' }}>\n <Text as='h2' size='lg' weight='semibold'>\n {config.widget_greeting}\n </Text>\n <Text as='p' variant='muted' size='sm' style={{ marginTop: '2px' }}>\n {config.widget_body}\n </Text>\n </Surface>\n\n <Stack gap='sm'>\n <Button\n type='button'\n variant='primary'\n full\n onClick={onNavigateToChat}\n aria-label='Ask a question'\n style={{\n paddingTop: '10px',\n paddingBottom: '10px',\n }}\n >\n <Icon name='chat' size={16} />\n Ask a question\n </Button>\n\n <SuggestedActions actions={suggestedActions} onActionClick={handleActionClick} />\n </Stack>\n </Stack>\n\n {messages.length > 0 && (\n <Surface\n background='card'\n border\n elevation='card'\n paddingPreset='card'\n rounded='xl'\n style={{ margin: '0 12px 12px 12px' }}\n >\n <Text as='p' size='xs' weight='semibold' style={{ marginBottom: '2px' }}>\n Recent conversation\n </Text>\n <Text\n as='p'\n size='xs'\n variant='muted'\n style={{ display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}\n >\n {messages[messages.length - 1].content || 'Message'}\n </Text>\n <Text\n as='p'\n size='xs'\n variant='muted'\n onClick={onNavigateToChat}\n style={{ marginTop: '4px', cursor: 'pointer' }}\n >\n Continue conversation →\n </Text>\n </Surface>\n )}\n </Stack>\n );\n};\n","import React from 'react';\n\nimport { RESIZE_CORNERS, type ResizeCorner } from '../../hooks/useResize';\n\nfunction getCornerStyle(corner: ResizeCorner): React.CSSProperties {\n const isTop = corner.startsWith('top');\n const isLeft = corner.endsWith('left');\n return {\n position: 'absolute',\n width: '20px',\n height: '20px',\n padding: '4px',\n touchAction: 'none',\n zIndex: 10,\n display: 'flex',\n alignItems: isTop ? 'flex-start' : 'flex-end',\n justifyContent: isLeft ? 'flex-start' : 'flex-end',\n cursor: RESIZE_CORNERS[corner].cursor,\n top: isTop ? 0 : undefined,\n bottom: isTop ? undefined : 0,\n left: isLeft ? 0 : undefined,\n right: isLeft ? undefined : 0,\n };\n}\n\nexport interface ResizeHandlesProps {\n onResizeStart: (corner: ResizeCorner) => (e: React.MouseEvent) => void;\n}\n\nexport const ResizeHandles: React.FC<ResizeHandlesProps> = ({ onResizeStart }) => (\n <>\n {(Object.keys(RESIZE_CORNERS) as ResizeCorner[]).map(corner => (\n <div\n key={corner}\n role='separator'\n aria-label={`Resize widget from ${corner.replace('-', ' ')}`}\n title='Drag to resize'\n style={getCornerStyle(corner)}\n onMouseDown={onResizeStart(corner)}\n />\n ))}\n </>\n);\n","import React from 'react';\n\nimport { TAB_BAR_HEIGHT } from '../../design-system/component-tokens';\nimport type { WidgetView } from '../../types';\nimport { Button } from '../base/Button';\nimport { Flex } from '../base/Flex';\nimport { Icon } from '../base/Icon';\nimport type { IconName } from '../base/icons';\nimport { Text } from '../base/Text';\n\nconst TAB_DEFS: { id: WidgetView; icon: IconName; label: string }[] = [\n { id: 'home', icon: 'home', label: 'Home' },\n { id: 'chat', icon: 'chat', label: 'Chat' },\n];\n\nexport interface ShellTabBarProps {\n activeView: WidgetView;\n onChange: (view: WidgetView) => void;\n}\n\nexport const ShellTabBar: React.FC<ShellTabBarProps> = ({ activeView, onChange }) => {\n return (\n <Flex role='tablist' align='center' justify='around' shrink={false} border='top' style={{ height: TAB_BAR_HEIGHT }}>\n {TAB_DEFS.map(tab => {\n const isActive = activeView === tab.id;\n return (\n <Button\n key={tab.id}\n role='tab'\n aria-selected={isActive}\n aria-controls={`view-${tab.id}`}\n id={`tab-${tab.id}`}\n onClick={() => onChange(tab.id)}\n active={isActive}\n stacked\n variant='tab'\n >\n {isActive && (\n <Text as='span' inheritColor style={{ position: 'absolute', top: 0, left: '25%', right: '25%' }}>\n <span className='block h-0.5 w-full rounded-full bg-primary' />\n </Text>\n )}\n <Text as='span' inheritColor aria-hidden='true'>\n <Icon name={tab.icon} size={20} />\n </Text>\n <Text as='span' size='xs' align='center' inheritColor truncate block>\n {tab.label}\n </Text>\n </Button>\n );\n })}\n </Flex>\n );\n};\n","import React, { useRef, useState } from 'react';\n\nimport { SHADOW } from '../../design-system/shadows';\nimport { useFocusTrap } from '../../hooks/useFocusTrap';\nimport { useResize } from '../../hooks/useResize';\nimport { useWidget, useWidgetConfig } from '../../hooks/useWidget';\nimport { createUserMessage } from '../../services/ChatService';\nimport { tenantScope } from '../../services/WidgetService';\nimport type { SuggestedActionItem } from '../../utils/suggestedActions';\nimport { getCorner, getPanelPositionStyle } from '../../utils/widgetPositioning';\nimport { Icon } from '../base/Icon';\nimport { IconButton } from '../base/IconButton';\nimport { Stack } from '../base/Stack';\nimport { Surface } from '../base/Surface';\nimport { HeaderBar } from '../blocks/HeaderBar';\nimport { ChatView } from '../views/ChatView';\nimport { HomeView } from '../views/HomeView';\nimport { ResizeHandles } from './ResizeHandles';\nimport { ShellTabBar } from './ShellTabBar';\n\nexport const MessengerShell: React.FC = () => {\n const config = useWidgetConfig();\n const { state, actions } = useWidget();\n const { isOpen, activeView } = state;\n const isPreviewMode = config.isPreviewMode ?? false;\n\n const { widthPx, heightPx, onResizeStart, containerRef } = useResize(\n config.widget_width,\n config.widget_height,\n tenantScope(config),\n isPreviewMode,\n );\n\n const messageInputRef = useRef<HTMLTextAreaElement | null>(null);\n const navDirection = activeView === 'chat' ? 'forward' : 'back';\n\n useFocusTrap(containerRef, isOpen, {\n onEscape: actions.closeWidget,\n focusTargetRef: activeView === 'chat' ? messageInputRef : undefined,\n });\n\n const panelPositionStyle = getPanelPositionStyle(config.widget_position);\n\n // Must stay above the early return below.\n const [headerScreenSharing, setHeaderScreenSharing] = useState(false);\n const chatViewStartScreenShareRef = useRef<(() => void) | null>(null);\n const chatViewStopScreenShareRef = useRef<(() => void) | null>(null);\n\n if (!isOpen) return null;\n\n const backgroundImage = config.widget_background_color.includes('gradient')\n ? config.widget_background_color\n : `linear-gradient(135deg, ${config.widget_background_color} 0%, ${config.widget_background_color} 100%)`;\n\n const { vertical, horizontal } = getCorner(config.widget_position);\n\n const handleNavigateToChat = () => {\n actions.setActiveView('chat');\n };\n\n const handleChipClick = (action: SuggestedActionItem) => {\n actions.addMessage(createUserMessage(action.text, action.type, 'chip-message'));\n actions.setMode(action.type);\n void actions.messageDispatch(action.text, action.type, true);\n };\n\n const screenShareHandler =\n activeView === 'chat' && config.use_screenshare !== false\n ? () => {\n if (headerScreenSharing) {\n chatViewStopScreenShareRef.current?.();\n } else {\n chatViewStartScreenShareRef.current?.();\n }\n }\n : undefined;\n\n return (\n <Stack\n ref={containerRef}\n position={isPreviewMode ? 'absolute' : 'fixed'}\n rounded='theme'\n border\n overflow='hidden'\n style={{\n zIndex: config.widget_position_z_index,\n backgroundImage,\n transformOrigin: `${vertical} ${horizontal}`,\n width: widthPx,\n height: heightPx,\n fontSize: '14px',\n ...panelPositionStyle,\n pointerEvents: 'auto',\n scrollbarWidth: 'thin',\n animation: 'messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)',\n boxShadow: SHADOW.panel,\n }}\n >\n <HeaderBar\n title={config.widget_header}\n subtitle={config.widget_body}\n onClose={actions.closeWidget}\n controls={\n screenShareHandler && (\n <IconButton\n variant='ghost'\n size='sm'\n label={headerScreenSharing ? 'Stop screen sharing' : 'Start screen sharing'}\n onClick={screenShareHandler}\n >\n {headerScreenSharing && (\n <span className='absolute top-0.5 right-0.5 inline-flex h-1.5 w-1.5'>\n <span className='absolute inline-flex h-full w-full animate-ping rounded-full bg-current opacity-75' />\n <span className='relative inline-flex h-1.5 w-1.5 rounded-full bg-current' />\n </span>\n )}\n <Icon name='screenShare' size={16} />\n </IconButton>\n )\n }\n />\n\n <Surface grow overflow='hidden' style={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}>\n <Surface\n key={activeView}\n data-view-transition\n data-direction={navDirection}\n style={{ width: '100%', height: '100%' }}\n >\n {activeView === 'home' && <HomeView onNavigateToChat={handleNavigateToChat} onChipClick={handleChipClick} />}\n {activeView === 'chat' && (\n <ChatView\n onScreenSharingChange={setHeaderScreenSharing}\n onStartScreenShareRef={chatViewStartScreenShareRef}\n onStopScreenShareRef={chatViewStopScreenShareRef}\n messageInputRef={messageInputRef}\n />\n )}\n </Surface>\n </Surface>\n\n <ShellTabBar activeView={activeView} onChange={actions.setActiveView} />\n\n {!isPreviewMode && <ResizeHandles onResizeStart={onResizeStart} />}\n </Stack>\n );\n};\n","import React, { useEffect, useState } from 'react';\n\nimport { PortalContainerContext } from '../context/WidgetProviders';\nimport { LAYER_TOKENS } from '../design-system/layers';\nimport { createSemanticTokens, semanticTokensToCssCustomProperties } from '../design-system/semantic-tokens';\nimport { useScrollLock } from '../hooks/useScrollLock';\nimport { useWidget, type ValidWidgetConfig, WidgetConfigContext } from '../hooks/useWidget';\nimport { WidgetSettingsDataSchema } from '../sdk';\nimport { readLocal, writeLocal } from '../services/StorageService';\nimport { StreamClient } from '../services/StreamClient';\nimport { tenantScope } from '../services/WidgetService';\nimport type { MarketrixConfig, WidgetPosition } from '../types';\nimport { addOpacity } from '../utils/color';\nimport { getCorner, isWidgetPosition } from '../utils/widgetPositioning';\nimport { ErrorBoundary } from './base/ErrorBoundary';\nimport { Surface } from './base/Surface';\nimport { NotificationToast } from './blocks/NotificationToast';\nimport { WidgetFab } from './blocks/WidgetFab';\nimport { MessengerShell } from './navigation/MessengerShell';\n\ninterface WidgetRootProps {\n config: MarketrixConfig;\n}\n\nexport const WidgetRoot: React.FC<WidgetRootProps> = ({ config }) => {\n const [showGreeting, setShowGreeting] = useState(false);\n const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);\n const { state, actions } = useWidget();\n const streamClient = StreamClient.getInstance();\n const isPreviewMode = config.isPreviewMode ?? false;\n const configValid = WidgetSettingsDataSchema.safeParse(config).success;\n\n useScrollLock(state.isOpen);\n\n const [widgetPosition, setWidgetPosition] = useState<WidgetPosition>(config.widget_position ?? 'bottom_right');\n\n const positionStorageKey = `marketrix_widget_position_${tenantScope(config)}`;\n\n useEffect(() => {\n const stored = isPreviewMode ? null : readLocal(positionStorageKey);\n if (isWidgetPosition(stored)) {\n setWidgetPosition(stored);\n return;\n }\n // Only a drag writes the key: seeding it with the dashboard default would pin that value forever.\n setWidgetPosition(config.widget_position ?? 'bottom_right');\n }, [isPreviewMode, positionStorageKey, config.widget_position]);\n\n useEffect(() => {\n if (state.isOpen || isPreviewMode || config.widget_appearance !== 'default' || !config.widget_greeting_toast) {\n setShowGreeting(false);\n return;\n }\n const timer = setTimeout(() => setShowGreeting(true), 2000);\n return () => clearTimeout(timer);\n }, [state.isOpen, isPreviewMode, config.widget_appearance, config.widget_greeting_toast]);\n\n const handlePositionChange = (position: WidgetPosition) => {\n setWidgetPosition(position);\n if (!isPreviewMode) writeLocal(positionStorageKey, position);\n };\n\n if (!configValid) {\n return null;\n }\n\n const hiddenByConfig =\n !config.widget_enabled || config.show_widget === false || config.widget_appearance === 'hidden';\n if (!isPreviewMode && hiddenByConfig) {\n return null;\n }\n\n const effectiveWidgetZIndex = Math.max(config.widget_position_z_index ?? 0, LAYER_TOKENS.panel);\n\n const effectiveConfig = {\n ...config,\n widget_position: widgetPosition,\n widget_position_z_index: effectiveWidgetZIndex,\n } as ValidWidgetConfig;\n\n const showProcessingFeedback = state.isAwaitingReply || state.isTaskRunning;\n const customStyles = semanticTokensToCssCustomProperties(createSemanticTokens(config)) as React.CSSProperties;\n\n return (\n <WidgetConfigContext value={effectiveConfig}>\n <Surface\n ref={setPortalContainer}\n data-marketrix-widget\n position='relative'\n style={{ ...customStyles, ...(isPreviewMode && { width: '100%', height: '100%' }) }}\n >\n <PortalContainerContext value={portalContainer}>\n {showProcessingFeedback && (\n <Surface\n data-screen-edge-glow\n position='fixed'\n inset='0'\n style={{\n boxShadow: `inset 0 0 22px 2px ${addOpacity(effectiveConfig.widget_accent_color, 0.72)}, inset 0 0 46px 10px ${addOpacity(effectiveConfig.widget_accent_color, 0.28)}`,\n pointerEvents: 'none',\n zIndex: LAYER_TOKENS.screenEdgeGlow,\n }}\n />\n )}\n\n <ErrorBoundary label='Widget'>\n <MessengerShell />\n </ErrorBoundary>\n\n <WidgetFab onDrag={handlePositionChange} />\n\n {state.error && (\n <NotificationToast\n tone='error'\n title={state.error}\n onDismiss={() => actions.setError(undefined)}\n // Offered only when it can achieve something, and it now reconnects — it used to be\n // byte-identical to onDismiss, so the one error where reconnecting IS the remedy showed a\n // Retry button that only hid the toast.\n {...(streamClient.canReconnect() && {\n onRetry: () => {\n actions.setError(undefined);\n streamClient.reconnectNow();\n },\n })}\n position={getCorner(widgetPosition).vertical === 'top' ? 'bottom-center' : 'above-fab'}\n />\n )}\n\n {showGreeting && !state.error && config.widget_greeting && (\n <NotificationToast\n tone='info'\n title={config.widget_greeting}\n body={config.widget_body}\n onDismiss={() => setShowGreeting(false)}\n position='bottom-center'\n />\n )}\n </PortalContainerContext>\n </Surface>\n </WidgetConfigContext>\n );\n};\n","export function isHTMLElement(element: Element | null): element is HTMLElement {\n return element instanceof HTMLElement;\n}\n\nexport function isHTMLScriptElement(element: Element | null): element is HTMLScriptElement {\n return element instanceof HTMLScriptElement;\n}\n","import React from 'react';\nimport { createRoot, type Root } from 'react-dom/client';\n\nimport { NotificationToast } from '../components/blocks/NotificationToast';\nimport { WidgetRoot } from '../components/WidgetRoot';\nimport { WidgetProviders } from '../context/WidgetProviders';\nimport type { NotificationTone } from '../design-system/component-tokens';\nimport shadowStyles from '../index.css?inline';\nimport type { MarketrixConfig } from '../types';\nimport { WIDGET_SHADOW_HOST_CLASS } from './dom';\nimport { isHTMLScriptElement } from './validation';\n\nexport interface WidgetMount {\n instance: Root;\n config: MarketrixConfig;\n container: HTMLElement;\n host: HTMLElement | undefined;\n previewMode: boolean;\n}\n\nexport const widgetState: { mount: WidgetMount | null } = { mount: null };\n\nlet noticeRoot: Root | null = null;\n\n/** The one place a closed shadow root is opened and the widget CSS injected into it. */\nconst attachShadowMount = (\n container: HTMLElement,\n mountId: string,\n): { shadowRoot: ShadowRoot; mountEl: HTMLElement } => {\n const shadowRoot = container.attachShadow({ mode: 'closed' });\n\n const styleEl = document.createElement('style');\n styleEl.textContent = shadowStyles;\n shadowRoot.appendChild(styleEl);\n\n const mountEl = document.createElement('div');\n mountEl.id = mountId;\n shadowRoot.appendChild(mountEl);\n\n return { shadowRoot, mountEl };\n};\n\nexport const createWidgetContainer = (\n parentContainer?: HTMLElement,\n): { container: HTMLElement; shadowRoot: ShadowRoot; mountEl: HTMLElement } => {\n const parent = parentContainer ?? document.body;\n\n const container = document.createElement('div');\n container.className = WIDGET_SHADOW_HOST_CLASS;\n container.style.pointerEvents = 'auto';\n if (parentContainer) {\n Object.assign(container.style, { width: '100%', height: '100%', position: 'relative', overflow: 'visible' });\n }\n parent.appendChild(container);\n\n const { shadowRoot, mountEl } = attachShadowMount(container, 'marketrix-widget-root');\n Object.assign(mountEl.style, { pointerEvents: 'auto', width: '100%', height: '100%', position: 'relative' });\n\n return { container, shadowRoot, mountEl };\n};\n\n// previewMode disables all network operations (for integration previews).\nexport const mountWidgetToContainer = (mountEl: HTMLElement, config: MarketrixConfig, previewMode = false): Root => {\n const root = createRoot(mountEl);\n\n root.render(\n <React.StrictMode>\n <WidgetProviders previewMode={previewMode}>\n <WidgetRoot config={config} />\n </WidgetProviders>\n </React.StrictMode>,\n );\n\n return root;\n};\n\nexport const isWidgetInitialized = (): boolean => widgetState.mount !== null;\n\nexport const getCurrentConfig = (): MarketrixConfig | null => widgetState.mount?.config ?? null;\n\nexport const showHostPageNotice = (message: string, tone: NotificationTone = 'neutral'): void => {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return;\n }\n\n hideHostPageNotice();\n\n const noticeContainer = document.createElement('div');\n noticeContainer.id = 'marketrix-widget-notice-container';\n noticeContainer.className = 'marketrix-widget-notice-container';\n document.body.appendChild(noticeContainer);\n\n const { mountEl } = attachShadowMount(noticeContainer, 'marketrix-widget-notice-root');\n\n noticeRoot = createRoot(mountEl);\n noticeRoot.render(\n <React.StrictMode>\n <NotificationToast tone={tone} title={message} onDismiss={hideHostPageNotice} />\n </React.StrictMode>,\n );\n};\n\nexport const hideHostPageNotice = (): void => {\n noticeRoot?.unmount();\n noticeRoot = null;\n document.getElementById('marketrix-widget-notice-container')?.remove();\n};\n\n// initWidget is passed in (not imported) to avoid a circular dependency.\nexport const autoInitializeWidget = (initWidget: (config: MarketrixConfig) => Promise<void>): void => {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return;\n }\n\n // Window-level guard survives ES module re-execution.\n if (window.__mtx?.state) {\n return;\n }\n\n const scripts = document.querySelectorAll('script[mtx-id]');\n const script = scripts[scripts.length - 1];\n\n if (!script || !isHTMLScriptElement(script)) {\n return;\n }\n\n const mtxId = script.getAttribute('mtx-id');\n const mtxKey = script.getAttribute('mtx-key');\n const mtxApiHost = script.getAttribute('mtx-api-host');\n\n // mtx-api-host is as required as the credentials: there is no default, and an unconfigured SDK\n // resolves every request against the HOST PAGE's origin, so omitting it silently posts widget\n // traffic at the customer's own site instead of failing.\n if (!mtxId || !mtxKey || !mtxApiHost) {\n if (isWidgetInitialized()) return;\n console.error('[AutoInit] Missing required attributes:', {\n hasMtxId: !!mtxId,\n hasMtxKey: !!mtxKey,\n hasMtxApiHost: !!mtxApiHost,\n });\n showHostPageNotice('Please configure mtx-id, mtx-key and mtx-api-host', 'error');\n return;\n }\n\n const config: MarketrixConfig = { mtxId, mtxKey, mtxApiHost };\n if (script.getAttribute('mtx-use-screenshare') === 'false') config.use_screenshare = false;\n\n initWidget(config).catch(error => console.error('[AutoInit] Failed to initialize widget:', error));\n};\n","declare global {\n interface Window {\n __mtx?: { state?: 'initializing' | 'active' };\n }\n}\n\nimport React, { useEffect, useRef } from 'react';\nimport type { Root } from 'react-dom/client';\n\nimport { configureSdk } from './sdk';\nimport { chatSessionManager } from './services/ChatSessionManager';\nimport { RrwebSessionRecorder } from './services/RrwebSessionRecorder';\nimport { type CredentialedConfig, storageService } from './services/StorageService';\nimport { StreamClient } from './services/StreamClient';\nimport { createConfigFromSettings, loadWidgetConfig } from './services/WidgetService';\nimport type { AddWidgetConfig, MarketrixConfig, MarketrixWidgetProps } from './types';\nimport {\n autoInitializeWidget,\n createWidgetContainer,\n getCurrentConfig,\n hideHostPageNotice,\n isWidgetInitialized,\n mountWidgetToContainer,\n showHostPageNotice,\n widgetState,\n} from './utils/bootstrap';\nimport { isHTMLElement } from './utils/validation';\n\nlet initPromise: Promise<void> | null = null;\nlet lifecycleGeneration = 0;\nlet rrwebSessionRecorder: RrwebSessionRecorder | null = null;\n\n/** The one production/imperative-preview mount. */\nfunction mount(config: MarketrixConfig, host: HTMLElement | undefined, previewMode = false): void {\n const { container, mountEl } = createWidgetContainer(host);\n const instance = mountWidgetToContainer(mountEl, config, previewMode);\n widgetState.mount = { instance, config, container, host, previewMode };\n}\n\n// Call only via initWidget(), which guards with initPromise.\nasync function initWidgetInternal(\n config: MarketrixConfig,\n container: HTMLElement | undefined,\n generation: number,\n): Promise<void> {\n window.__mtx = { state: 'initializing' };\n\n showHostPageNotice('Loading widget settings...');\n let finalConfig: CredentialedConfig;\n try {\n // Production only: every preview path mounts directly and never reaches here. There is no default\n // host, so leaving the SDK unconfigured would resolve each request against the HOST PAGE's origin.\n configureSdk(config.mtxApiHost ?? '');\n finalConfig = await loadWidgetConfig(config);\n } catch (error) {\n if (generation !== lifecycleGeneration) return;\n console.error('Marketrix Widget initialization failed:', error);\n showHostPageNotice(error instanceof Error ? error.message : 'Failed to initialize widget', 'error');\n window.__mtx = undefined;\n return;\n }\n if (generation !== lifecycleGeneration) return;\n hideHostPageNotice();\n\n storageService.setConfig(finalConfig);\n mount(finalConfig, container);\n window.__mtx = { state: 'active' };\n\n if (finalConfig.widget_recording && finalConfig.mtxApp) {\n void (async () => {\n try {\n await StreamClient.getInstance().waitUntilRegistered();\n if (generation !== lifecycleGeneration) return;\n const chatId = await chatSessionManager.getOrCreateChatId();\n if (generation !== lifecycleGeneration) return;\n const recorder = new RrwebSessionRecorder(chatId, finalConfig.mtxApp as number);\n rrwebSessionRecorder = recorder;\n await recorder.start();\n if (generation !== lifecycleGeneration) {\n recorder.stop();\n if (rrwebSessionRecorder === recorder) rrwebSessionRecorder = null;\n }\n } catch (error) {\n if (generation === lifecycleGeneration) console.error('Failed to start session recording:', error);\n }\n })();\n }\n}\n\nexport const initWidget = (config: MarketrixConfig, container?: HTMLElement): Promise<void> => {\n if (initPromise) return initPromise;\n\n // window-level guard survives ES module re-execution, which resets module-level vars.\n if (window.__mtx?.state) return Promise.resolve();\n if (isWidgetInitialized()) {\n console.warn('Marketrix Widget: already initialized');\n return Promise.resolve();\n }\n\n const generation = ++lifecycleGeneration;\n const pending = initWidgetInternal(config, container, generation);\n initPromise = pending;\n void pending.then(\n () => {\n if (initPromise === pending) initPromise = null;\n },\n () => {\n if (initPromise === pending) initPromise = null;\n },\n );\n return pending;\n};\n\nexport const unmountWidget = (): void => {\n lifecycleGeneration++;\n StreamClient.getInstance().disconnect();\n rrwebSessionRecorder?.stop();\n rrwebSessionRecorder = null;\n\n const active = widgetState.mount;\n widgetState.mount = null;\n if (active) {\n active.instance.unmount();\n active.container.remove();\n console.log('Marketrix Widget destroyed');\n }\n\n initPromise = null;\n window.__mtx = undefined;\n\n hideHostPageNotice();\n};\n\nexport const updateMarketrixConfig = async (newConfig: Partial<MarketrixConfig>): Promise<void> => {\n const active = widgetState.mount;\n if (!active) return;\n\n const { config, host, previewMode } = active;\n const updatedConfig = { ...config, ...newConfig };\n unmountWidget();\n if (previewMode) mount(updatedConfig, host, true);\n else await initWidget(updatedConfig, host);\n};\n\nexport { getCurrentConfig };\n\n// Preview-mode React entry point — mounts its own shadow DOM inside the parent container.\nexport const MarketrixWidget: React.FC<MarketrixWidgetProps> = ({ settings, container }) => {\n const containerRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n const widgetContainerRef = useRef<HTMLElement | null>(null);\n\n useEffect(() => {\n const parentContainer = container ?? containerRef?.current?.parentElement ?? document.body;\n\n if (!parentContainer || !isHTMLElement(parentContainer)) {\n console.error('MarketrixWidget: Invalid container');\n return;\n }\n\n const { container: widgetContainer, mountEl } = createWidgetContainer(parentContainer);\n\n widgetContainerRef.current = widgetContainer;\n\n rootRef.current = mountWidgetToContainer(\n mountEl,\n { ...createConfigFromSettings(settings), isPreviewMode: true },\n true,\n );\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n rootRef.current = null;\n }\n if (widgetContainerRef.current) {\n widgetContainerRef.current.remove();\n widgetContainerRef.current = null;\n }\n };\n }, [settings, container]);\n\n if (container) {\n return null;\n }\n\n return <div ref={containerRef} style={{ width: '100%', height: '100%', position: 'relative' }} />;\n};\n\nexport const mountWidget = async (config: AddWidgetConfig): Promise<void> => {\n const container = config.container;\n\n if (config.settings !== undefined) {\n unmountWidget();\n // Preview: no network, and deliberately no global production instance.\n const { settings, container: _container, ...restConfig } = config;\n mount({ ...createConfigFromSettings(settings, restConfig), isPreviewMode: true }, container, true);\n } else if (config.mtxId !== undefined && config.mtxKey !== undefined) {\n const { container: _container, ...restConfig } = config;\n await initWidget(restConfig, container);\n } else {\n throw new Error('Invalid configuration: provide either settings (preview) or mtxId+mtxKey (production)');\n }\n};\n\nif (typeof window !== 'undefined') {\n setTimeout(() => {\n try {\n autoInitializeWidget(initWidget);\n } catch (error) {\n console.debug('Marketrix Widget: Auto-init registration skipped', error);\n }\n }, 0);\n}\n\nexport type { InstructionType } from './sdk';\nexport type { AddWidgetConfig, ChatMessage, MarketrixConfig, MarketrixWidgetProps, WidgetState } from './types';\n\nexport default {\n MarketrixWidget,\n mountWidget,\n initWidget,\n unmountWidget,\n updateMarketrixConfig,\n getCurrentConfig,\n};\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,32,40,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165],"mappings":"6YAMA,SAAS,EAAQ,GACf,OAAO,MAAM,QAAQ,GAAS,EAAQ,QAAqC,GAAK,CAAC,EACnF,CAaA,IAAM,EAAY,OAIZ,EAAN,cAAyB,MACvB,WAAA,IAAe,GACb,SAAS,GACT,KAAK,KAAO,YACd,GAGF,SAAS,EAAK,GACZ,IAAI,EACJ,MAAA,KACE,GAAI,EACF,OAAO,EAAO,OAEhB,MAAM,EAAS,IAEf,OADA,EAAS,CAAE,UACJ,EAEX,CAuBA,SAAS,IACP,OAAO,WALsB,sCAM/B,CACA,SAAS,EAAU,EAAM,EAAU,CAAC,EAAG,GAErC,OADe,KAAuB,SACvB,UAAU,EAAM,EAAS,EAC1C,CACA,SAAS,EAAa,EAAM,EAAO,EAAU,CAAC,GAC5C,IAAK,EACH,OAEF,MAAM,EAeR,SAAyB,GACvB,GAAI,aAAiB,MAAO,CAC1B,MAAM,EAAY,CAChB,QAAS,EAAM,QACf,KAAM,EAAM,KACZ,MAAO,EAAM,OAKf,QAHI,SAAU,IAAgC,iBAAf,EAAM,MAA2C,iBAAf,EAAM,OACrE,EAAU,KAAO,EAAM,MAElB,CACT,CACA,MAAO,CAAE,QAAS,OAAO,GAC3B,CA5BoB,CAAgB,GAClC,EAAK,gBAAgB,GAChB,EAAQ,QAAQ,SAAW,EAAQ,OAAO,SAAW,GACxD,EAAK,UAAU,CACb,KApBoB,EAqBpB,QAAS,EAA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