{
  "version": 3,
  "sources": ["../../../../../node_modules/@vercel/oidc/dist/get-context.js", "../../../../../node_modules/@vercel/oidc/dist/auth-errors.js", "../../../../../node_modules/@vercel/oidc/dist/index-browser.js", "../../src/code-generation/utils/isLocalizedValueProperty.ts", "../../src/code-generation/utils/stripLocalizedValues.ts", "../../../../../node_modules/@framerjs/framer-events/lib/esm/generated/CanvasPageAdd.js", "../../../../../node_modules/@framerjs/framer-events/lib/esm/generated/ComponentCanvasCreate.js", "../../../../../node_modules/@framerjs/framer-events/lib/esm/generated/ComponentCanvasVariantCreate.js", "../../../../../node_modules/@framerjs/framer-events/lib/esm/generated/ComponentDesignInstance.js", "../../../../../node_modules/@framerjs/framer-events/lib/esm/generated/PropertyLayoutUpdate.js", "../../../../../node_modules/@framerjs/framer-events/lib/esm/generated/VariableReferenceCreate.js", "../../src/document/models/CanvasTree/utils/getConstraintsLocked.ts", "../../src/document/components/tools/utils/FramesHelper.ts", "../../src/document/models/CanvasTree/actions/variantActions.ts", "../../src/document/utils/undoRedoEntryChecks.ts", "../../src/document/stores/PopoverStore.ts", "../../src/document/EngineChanges.ts", "../../src/web/pages/project/permissions/projectPermissions.ts", "../../src/editorbar/engine/useOnPageEngine.ts", "../../src/web/pages/project/permissions/isViewOnly.ts", "../../src/document/models/CanvasTree/traits/WithPath.ts", "../../src/document/components/utils/list.ts", "../../src/document/stores/PathSelectionStore.ts", "../../src/document/components/tools/pathEdit/utils/index.ts", "../../src/document/stores/ToolStore.ts", "../../src/document/components/chrome/Pages/utils/editPanelRow.ts", "../../src/document/components/chrome/Pages/utils/editPageRow.ts", "../../src/document/models/CanvasTree/nodes/RichTextNode.utils.ts", "../../src/document/models/CanvasTree/nodes/isImportableComponentNode.ts", "../../src/document/components/chrome/Pages/utils/getAllExistingFolderAndPagePaths.ts", "../../src/document/components/utils/getUniquePagePath.ts", "../../src/document/components/chrome/Pages/utils/createRouteSegment.ts", "../../src/document/components/chrome/contentManagement/utils/createContentManagementNodeIfNeeded.ts", "../../../../../node_modules/base-x/src/esm/index.js", "../../src/utils/baseX.ts", "../../src/utils/base62.ts", "../../src/document/models/updateTreeCacheForVekter.ts", "../../src/document/components/chrome/properties/utils/createVariable.ts", "../../src/app/ai/config/disableAi.ts", "../../src/document/components/tools/utils/updateItemsOrder.ts", "../../src/code-generation/utils/variantEditingHelpers.ts", "../../src/document/models/CanvasTree/nodes/utils/convertCSSColorVariableToValue.ts", "../../src/document/components/chrome/assets/utils/getNodeName.ts", "../../src/document/models/CanvasTree/nodes/utils/entityReferenceNode.ts", "../../src/document/models/CanvasTree/nodes/utils/entityFolderNode.ts", "../../src/document/models/CanvasTree/traits/utils/isWebPageInstance.ts", "../../src/document/models/CanvasTree/utils/nodeIdsOrNodes.ts", "../../src/document/models/controlProps/getCodeComponentControlPropValues.ts", "../../src/document/stores/ModalStore.ts", "../../src/document/utils/collectionItemVisibility.ts", "../../src/document/stores/SelectionStore.ts", "../../src/document/utils/breakPointAndVariantMatching.ts", "../../src/document/components/chrome/properties/panels/utils/getFilters.ts", "../../src/document/models/CanvasTree/traits/TraitType.ts", "../../src/document/utils/compatibleControlProps.ts", "../../src/document/utils/getCompatibleNodeProperties.ts", "../../src/document/components/tools/utils/uniquePairs.ts", "../../src/document/components/tools/utils/stackCreateHelper.ts", "../../src/document/utils/layoutSectionHelpers.ts", "../../src/utils/paperjs/utils/normalizeWithPath.ts", "../../src/utils/paperjs/importSVG.ts", "../../src/document/components/chrome/QuickActions/types.ts", "../../src/document/components/chrome/shared/UpsellModal/utils/countPagesWithVariants.ts", "../../src/document/components/chrome/shared/UpsellModal/utils/abTestUpsellModals.ts", "../../src/document/components/chrome/shared/UpsellModal/utils/analyticsEventsUpsellModals.ts", "../../src/document/components/chrome/siteSettings/CustomCode/utils/duplicateCustomCodeForPage.ts", "../../src/modules/waitForComponentLoaderToCatchUp.ts", "../../src/code-generation/utils/waitForLoadingComponentsWithTimeout.ts", "../../src/code-generation/components/helpers/ensureModulesAreLoaded.ts", "../../src/document/models/CanvasTree/nodes/utils/detachTextStylePresetsForBreakpoints.ts", "../../src/document/models/CanvasTree/traits/codeComponentVariantPropKeys.ts", "../../src/document/models/CanvasTree/traits/utils/applyTokenOverrides.ts", "../../src/document/utils/replaceWebPage.ts", "../../src/document/components/chrome/properties/panels/utils/getTextStylePresetBreakpoints.ts", "../../src/document/models/richText/richTextHash.ts", "../../src/utils/collectionUtils.ts", "../../src/utils/moduleIdentifierForNode.ts", "../../src/utils/clipboard/utils.ts", "../../src/document/components/chrome/Pages/utils/getRouteSegmentPositionInParent.ts", "../../src/document/components/tools/utils/remapOverrides.ts", "../../src/document/components/tools/utils/updateNodeConnections.ts", "../../src/document/components/unlinking/Unlinkable.ts", "../../src/document/components/unlinking/utils.ts", "../../src/document/components/unlinking/importExternalSmartComponentOrWebpage.ts", "../../src/document/components/chrome/assets/utils/expandAssetEntityItems.ts", "../../src/document/components/utils/webPageTitles.ts", "../../src/document/components/chrome/analytics/utils/configureAbTest.ts", "../../src/document/components/chrome/analytics/utils/addAbVariant.ts", "../../src/document/components/chrome/analytics/utils/promptAddAbVariant.ts", "../../src/document/components/chrome/properties/panels/utils/trackDimensionTypeChange.ts", "../../src/document/components/utils/countChildNodes.ts", "../../src/document/components/utils/detachComponentHelpers.ts", "../../src/document/components/utils/enableAutoSizeForNodes.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/ai-sdk-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/api-call-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/empty-response-body-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/get-error-message.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/invalid-argument-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/invalid-prompt-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/invalid-response-data-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/json-parse-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/load-api-key-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/load-setting-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/no-content-generated-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/no-such-model-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/too-many-embedding-values-for-call-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/type-validation-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/errors/unsupported-functionality-error.ts", "../../../../../node_modules/@ai-sdk/provider/src/json-value/is-json.ts", "../../../../../node_modules/zod/v3/helpers/util.js", "../../../../../node_modules/zod/v3/ZodError.js", "../../../../../node_modules/zod/v3/locales/en.js", "../../../../../node_modules/zod/v3/errors.js", "../../../../../node_modules/zod/v3/helpers/parseUtil.js", "../../../../../node_modules/zod/v3/helpers/errorUtil.js", "../../../../../node_modules/zod/v3/types.js", "../../../../../node_modules/eventsource-parser/src/errors.ts", "../../../../../node_modules/eventsource-parser/src/parse.ts", "../../../../../node_modules/eventsource-parser/src/stream.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/combine-headers.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/convert-async-iterator-to-readable-stream.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/create-tool-name-mapping.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/delay.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/delayed-promise.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/extract-response-headers.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/uint8-utils.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/convert-image-model-file-to-data-uri.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/convert-to-form-data.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/download-error.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/read-response-with-size-limit.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/validate-download-url.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/download-blob.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/generate-id.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/get-error-message.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/get-from-api.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/handle-fetch-error.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/is-abort-error.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/get-runtime-environment-user-agent.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/normalize-headers.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/with-user-agent-suffix.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/version.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/inject-json-instruction.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/is-non-nullable.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/is-url-supported.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/load-api-key.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/load-optional-setting.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/load-setting.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/media-type-to-extension.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/parse-json.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/secure-json-parse.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/validate-types.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/schema.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/add-additional-properties-to-json-schema.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/options.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/select-parser.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/any.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/array.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/branded.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/catch.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/date.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/default.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/effects.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/enum.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/literal.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/record.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/string.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/map.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/never.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/null.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/union.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/number.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/object.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/optional.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/promise.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/set.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/get-relative-path.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parse-def.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/refs.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/parse-json-event-stream.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/parse-provider-options.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/post-to-api.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/types/tool.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/provider-tool-factory.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/remove-undefined-entries.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/resolve.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/response-handler.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/strip-file-extension.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/without-trailing-slash.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/is-async-iterable.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/types/execute-tool.ts", "../../../../../node_modules/@ai-sdk/provider-utils/src/index.ts", "../../../../../node_modules/zod/index.js", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-provider.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/as-gateway-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/create-gateway-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/gateway-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/gateway-authentication-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/gateway-invalid-request-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/gateway-rate-limit-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/gateway-model-not-found-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/gateway-internal-server-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/gateway-response-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/extract-api-call-response.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/gateway-timeout-error.ts", "../../../../../node_modules/@ai-sdk/gateway/src/errors/parse-auth-method.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-fetch-metadata.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-model-entry.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-spend-report.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-generation-info.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-language-model.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-embedding-model.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-image-model.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-video-model.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-reranking-model.ts", "../../../../../node_modules/@ai-sdk/gateway/src/tool/parallel-search.ts", "../../../../../node_modules/@ai-sdk/gateway/src/tool/perplexity-search.ts", "../../../../../node_modules/@ai-sdk/gateway/src/gateway-tools.ts", "../../../../../node_modules/@ai-sdk/gateway/src/vercel-environment.ts", "../../../../../node_modules/@ai-sdk/gateway/src/version.ts", "../../../../../node_modules/@opentelemetry/api/src/platform/browser/globalThis.ts", "../../../../../node_modules/@opentelemetry/api/src/version.ts", "../../../../../node_modules/@opentelemetry/api/src/internal/semver.ts", "../../../../../node_modules/@opentelemetry/api/src/internal/global-utils.ts", "../../../../../node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts", "../../../../../node_modules/@opentelemetry/api/src/diag/types.ts", "../../../../../node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts", "../../../../../node_modules/@opentelemetry/api/src/api/diag.ts", "../../../../../node_modules/@opentelemetry/api/src/context/context.ts", "../../../../../node_modules/@opentelemetry/api/src/context/NoopContextManager.ts", "../../../../../node_modules/@opentelemetry/api/src/api/context.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/trace_flags.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/invalid-span-constants.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/NonRecordingSpan.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/context-utils.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/spancontext-utils.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/NoopTracer.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/ProxyTracer.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/NoopTracerProvider.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/ProxyTracerProvider.ts", "../../../../../node_modules/@opentelemetry/api/src/trace/status.ts", "../../../../../node_modules/@opentelemetry/api/src/context-api.ts", "../../../../../node_modules/@opentelemetry/api/src/api/trace.ts", "../../../../../node_modules/@opentelemetry/api/src/trace-api.ts", "../../../../../node_modules/ai/src/index.ts", "../../../../../node_modules/ai/src/agent/tool-loop-agent.ts", "../../../../../node_modules/ai/src/generate-text/generate-text.ts", "../../../../../node_modules/ai/src/error/index.ts", "../../../../../node_modules/ai/src/error/invalid-argument-error.ts", "../../../../../node_modules/ai/src/error/invalid-stream-part-error.ts", "../../../../../node_modules/ai/src/error/invalid-tool-approval-error.ts", "../../../../../node_modules/ai/src/error/invalid-tool-input-error.ts", "../../../../../node_modules/ai/src/error/tool-call-not-found-for-approval-error.ts", "../../../../../node_modules/ai/src/error/missing-tool-result-error.ts", "../../../../../node_modules/ai/src/error/no-image-generated-error.ts", "../../../../../node_modules/ai/src/error/no-object-generated-error.ts", "../../../../../node_modules/ai/src/error/no-output-generated-error.ts", "../../../../../node_modules/ai/src/error/no-speech-generated-error.ts", "../../../../../node_modules/ai/src/error/no-transcript-generated-error.ts", "../../../../../node_modules/ai/src/error/no-video-generated-error.ts", "../../../../../node_modules/ai/src/error/no-such-tool-error.ts", "../../../../../node_modules/ai/src/error/tool-call-repair-error.ts", "../../../../../node_modules/ai/src/error/unsupported-model-version-error.ts", "../../../../../node_modules/ai/src/error/ui-message-stream-error.ts", "../../../../../node_modules/ai/src/prompt/invalid-data-content-error.ts", "../../../../../node_modules/ai/src/prompt/invalid-message-role-error.ts", "../../../../../node_modules/ai/src/prompt/message-conversion-error.ts", "../../../../../node_modules/ai/src/util/retry-error.ts", "../../../../../node_modules/ai/src/util/as-array.ts", "../../../../../node_modules/ai/src/util/notify.ts", "../../../../../node_modules/ai/src/logger/log-warnings.ts", "../../../../../node_modules/ai/src/model/resolve-model.ts", "../../../../../node_modules/ai/src/util/log-v2-compatibility-warning.ts", "../../../../../node_modules/ai/src/model/as-embedding-model-v3.ts", "../../../../../node_modules/ai/src/model/as-image-model-v3.ts", "../../../../../node_modules/ai/src/model/as-language-model-v3.ts", "../../../../../node_modules/ai/src/model/as-speech-model-v3.ts", "../../../../../node_modules/ai/src/model/as-transcription-model-v3.ts", "../../../../../node_modules/ai/src/prompt/call-settings.ts", "../../../../../node_modules/ai/src/prompt/convert-to-language-model-prompt.ts", "../../../../../node_modules/ai/src/util/detect-media-type.ts", "../../../../../node_modules/ai/src/util/download/download.ts", "../../../../../node_modules/ai/src/version.ts", "../../../../../node_modules/ai/src/util/download/download-function.ts", "../../../../../node_modules/ai/src/prompt/data-content.ts", "../../../../../node_modules/ai/src/prompt/split-data-url.ts", "../../../../../node_modules/ai/src/prompt/create-tool-model-output.ts", "../../../../../node_modules/ai/src/prompt/prepare-call-settings.ts", "../../../../../node_modules/ai/src/prompt/prepare-tools-and-tool-choice.ts", "../../../../../node_modules/ai/src/util/is-non-empty-object.ts", "../../../../../node_modules/ai/src/prompt/standardize-prompt.ts", "../../../../../node_modules/ai/src/prompt/message.ts", "../../../../../node_modules/ai/src/types/provider-metadata.ts", "../../../../../node_modules/ai/src/types/json-value.ts", "../../../../../node_modules/ai/src/prompt/content-part.ts", "../../../../../node_modules/ai/src/prompt/wrap-gateway-error.ts", "../../../../../node_modules/ai/src/telemetry/assemble-operation-name.ts", "../../../../../node_modules/ai/src/telemetry/get-base-telemetry-attributes.ts", "../../../../../node_modules/ai/src/telemetry/get-tracer.ts", "../../../../../node_modules/ai/src/telemetry/noop-tracer.ts", "../../../../../node_modules/ai/src/telemetry/record-span.ts", "../../../../../node_modules/ai/src/telemetry/select-telemetry-attributes.ts", "../../../../../node_modules/ai/src/telemetry/stringify-for-telemetry.ts", "../../../../../node_modules/ai/src/telemetry/telemetry-integration-registry.ts", "../../../../../node_modules/ai/src/telemetry/get-global-telemetry-integration.ts", "../../../../../node_modules/ai/src/types/usage.ts", "../../../../../node_modules/ai/src/util/merge-objects.ts", "../../../../../node_modules/ai/src/util/retry-with-exponential-backoff.ts", "../../../../../node_modules/ai/src/util/prepare-retries.ts", "../../../../../node_modules/ai/src/generate-text/collect-tool-approvals.ts", "../../../../../node_modules/ai/src/generate-text/execute-tool-call.ts", "../../../../../node_modules/ai/src/util/now.ts", "../../../../../node_modules/ai/src/generate-text/extract-reasoning-content.ts", "../../../../../node_modules/ai/src/generate-text/extract-text-content.ts", "../../../../../node_modules/ai/src/generate-text/generated-file.ts", "../../../../../node_modules/ai/src/generate-text/is-approval-needed.ts", "../../../../../node_modules/ai/src/generate-text/output.ts", "../../../../../node_modules/ai/src/util/parse-partial-json.ts", "../../../../../node_modules/ai/src/util/fix-json.ts", "../../../../../node_modules/ai/src/generate-text/parse-tool-call.ts", "../../../../../node_modules/ai/src/generate-text/step-result.ts", "../../../../../node_modules/ai/src/generate-text/stop-condition.ts", "../../../../../node_modules/ai/src/generate-text/to-response-messages.ts", "../../../../../node_modules/ai/src/util/merge-abort-signals.ts", "../../../../../node_modules/ai/src/generate-text/stream-text.ts", "../../../../../node_modules/ai/src/util/prepare-headers.ts", "../../../../../node_modules/ai/src/text-stream/create-text-stream-response.ts", "../../../../../node_modules/ai/src/util/write-to-server-response.ts", "../../../../../node_modules/ai/src/text-stream/pipe-text-stream-to-response.ts", "../../../../../node_modules/ai/src/ui-message-stream/json-to-sse-transform-stream.ts", "../../../../../node_modules/ai/src/ui-message-stream/ui-message-stream-headers.ts", "../../../../../node_modules/ai/src/ui-message-stream/create-ui-message-stream-response.ts", "../../../../../node_modules/ai/src/ui-message-stream/get-response-ui-message-id.ts", "../../../../../node_modules/ai/src/ui/process-ui-message-stream.ts", "../../../../../node_modules/ai/src/ui-message-stream/ui-message-chunks.ts", "../../../../../node_modules/ai/src/ui/ui-messages.ts", "../../../../../node_modules/ai/src/ui-message-stream/handle-ui-message-stream-finish.ts", "../../../../../node_modules/ai/src/ui-message-stream/pipe-ui-message-stream-to-response.ts", "../../../../../node_modules/ai/src/util/async-iterable-stream.ts", "../../../../../node_modules/ai/src/util/consume-stream.ts", "../../../../../node_modules/ai/src/util/create-resolvable-promise.ts", "../../../../../node_modules/ai/src/util/create-stitchable-stream.ts", "../../../../../node_modules/ai/src/generate-text/run-tools-transformation.ts", "../../../../../node_modules/ai/src/ui-message-stream/create-ui-message-stream.ts", "../../../../../node_modules/ai/src/ui-message-stream/read-ui-message-stream.ts", "../../../../../node_modules/ai/src/ui/convert-to-model-messages.ts", "../../../../../node_modules/ai/src/ui/validate-ui-messages.ts", "../../../../../node_modules/ai/src/agent/create-agent-ui-stream.ts", "../../../../../node_modules/ai/src/agent/create-agent-ui-stream-response.ts", "../../../../../node_modules/ai/src/agent/pipe-agent-ui-stream-to-response.ts", "../../../../../node_modules/ai/src/embed/embed.ts", "../../../../../node_modules/ai/src/embed/embed-many.ts", "../../../../../node_modules/ai/src/util/split-array.ts", "../../../../../node_modules/ai/src/generate-image/generate-image.ts", "../../../../../node_modules/ai/src/generate-image/index.ts", "../../../../../node_modules/ai/src/generate-object/generate-object.ts", "../../../../../node_modules/ai/src/generate-object/output-strategy.ts", "../../../../../node_modules/ai/src/generate-object/parse-and-validate-object-result.ts", "../../../../../node_modules/ai/src/generate-object/validate-object-generation-input.ts", "../../../../../node_modules/ai/src/generate-object/stream-object.ts", "../../../../../node_modules/ai/src/util/cosine-similarity.ts", "../../../../../node_modules/ai/src/util/download/create-download.ts", "../../../../../node_modules/ai/src/util/data-url.ts", "../../../../../node_modules/ai/src/util/is-deep-equal-data.ts", "../../../../../node_modules/ai/src/util/serial-job-executor.ts", "../../../../../node_modules/ai/src/util/simulate-readable-stream.ts", "../../../../../node_modules/ai/src/generate-speech/generate-speech.ts", "../../../../../node_modules/ai/src/generate-speech/generated-audio-file.ts", "../../../../../node_modules/ai/src/generate-text/prune-messages.ts", "../../../../../node_modules/ai/src/generate-text/smooth-stream.ts", "../../../../../node_modules/ai/src/generate-video/generate-video.ts", "../../../../../node_modules/ai/src/middleware/default-embedding-settings-middleware.ts", "../../../../../node_modules/ai/src/middleware/default-settings-middleware.ts", "../../../../../node_modules/ai/src/middleware/extract-json-middleware.ts", "../../../../../node_modules/ai/src/util/get-potential-start-index.ts", "../../../../../node_modules/ai/src/middleware/extract-reasoning-middleware.ts", "../../../../../node_modules/ai/src/middleware/simulate-streaming-middleware.ts", "../../../../../node_modules/ai/src/middleware/add-tool-input-examples-middleware.ts", "../../../../../node_modules/ai/src/middleware/wrap-language-model.ts", "../../../../../node_modules/ai/src/middleware/wrap-embedding-model.ts", "../../../../../node_modules/ai/src/middleware/wrap-image-model.ts", "../../../../../node_modules/ai/src/model/as-provider-v3.ts", "../../../../../node_modules/ai/src/middleware/wrap-provider.ts", "../../../../../node_modules/ai/src/registry/custom-provider.ts", "../../../../../node_modules/ai/src/registry/no-such-provider-error.ts", "../../../../../node_modules/ai/src/registry/provider-registry.ts", "../../../../../node_modules/ai/src/rerank/rerank.ts", "../../../../../node_modules/ai/src/transcribe/transcribe.ts", "../../../../../node_modules/ai/src/ui/call-completion-api.ts", "../../../../../node_modules/ai/src/ui/process-text-stream.ts", "../../../../../node_modules/ai/src/ui/chat.ts", "../../../../../node_modules/ai/src/ui/convert-file-list-to-file-ui-parts.ts", "../../../../../node_modules/ai/src/ui/default-chat-transport.ts", "../../../../../node_modules/ai/src/ui/http-chat-transport.ts", "../../../../../node_modules/ai/src/ui/direct-chat-transport.ts", "../../../../../node_modules/ai/src/ui/last-assistant-message-is-complete-with-approval-responses.ts", "../../../../../node_modules/ai/src/ui/last-assistant-message-is-complete-with-tool-calls.ts", "../../../../../node_modules/ai/src/ui/transform-text-to-ui-message-stream.ts", "../../../../../node_modules/ai/src/ui/text-stream-chat-transport.ts", "../../src/app/ai/StreamingDSLParser.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/ai-sdk-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/api-call-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/empty-response-body-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/get-error-message.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/invalid-argument-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/invalid-prompt-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/invalid-response-data-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/json-parse-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/load-api-key-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/load-setting-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/no-content-generated-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/no-such-model-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/too-many-embedding-values-for-call-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/type-validation-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/errors/unsupported-functionality-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider/src/json-value/is-json.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/combine-headers.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/convert-async-iterator-to-readable-stream.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/create-tool-name-mapping.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/delay.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/delayed-promise.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/extract-response-headers.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/uint8-utils.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/convert-image-model-file-to-data-uri.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/convert-to-form-data.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/download-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/read-response-with-size-limit.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/validate-download-url.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/download-blob.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/generate-id.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/get-error-message.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/get-from-api.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/handle-fetch-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/is-abort-error.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/get-runtime-environment-user-agent.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/normalize-headers.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/with-user-agent-suffix.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/version.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/inject-json-instruction.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/is-non-nullable.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/is-url-supported.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/load-api-key.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/load-optional-setting.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/load-setting.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/media-type-to-extension.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/parse-json.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/secure-json-parse.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/validate-types.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/schema.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/add-additional-properties-to-json-schema.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/options.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/select-parser.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/any.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/array.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/branded.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/catch.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/date.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/default.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/effects.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/enum.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/literal.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/record.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/string.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/map.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/never.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/null.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/union.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/number.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/object.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/optional.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/promise.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/set.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/get-relative-path.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parse-def.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/refs.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/parse-json-event-stream.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/parse-provider-options.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/post-to-api.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/types/tool.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/provider-tool-factory.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/remove-undefined-entries.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/resolve.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/response-handler.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/strip-file-extension.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/without-trailing-slash.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/is-async-iterable.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/types/execute-tool.ts", "../../../../../node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider-utils/src/index.ts", "../../../../../node_modules/@ai-sdk/openai/src/openai-provider.ts", "../../../../../node_modules/@ai-sdk/openai/src/chat/openai-chat-language-model.ts", "../../../../../node_modules/@ai-sdk/openai/src/openai-error.ts", "../../../../../node_modules/@ai-sdk/openai/src/openai-language-model-capabilities.ts", "../../../../../node_modules/@ai-sdk/openai/src/chat/convert-openai-chat-usage.ts", "../../../../../node_modules/@ai-sdk/openai/src/chat/convert-to-openai-chat-messages.ts", "../../../../../node_modules/@ai-sdk/openai/src/chat/get-response-metadata.ts", "../../../../../node_modules/@ai-sdk/openai/src/chat/map-openai-finish-reason.ts", "../../../../../node_modules/@ai-sdk/openai/src/chat/openai-chat-api.ts", "../../../../../node_modules/@ai-sdk/openai/src/chat/openai-chat-options.ts", "../../../../../node_modules/@ai-sdk/openai/src/chat/openai-chat-prepare-tools.ts", "../../../../../node_modules/@ai-sdk/openai/src/completion/openai-completion-language-model.ts", "../../../../../node_modules/@ai-sdk/openai/src/completion/convert-openai-completion-usage.ts", "../../../../../node_modules/@ai-sdk/openai/src/completion/convert-to-openai-completion-prompt.ts", "../../../../../node_modules/@ai-sdk/openai/src/completion/get-response-metadata.ts", "../../../../../node_modules/@ai-sdk/openai/src/completion/map-openai-finish-reason.ts", "../../../../../node_modules/@ai-sdk/openai/src/completion/openai-completion-api.ts", "../../../../../node_modules/@ai-sdk/openai/src/completion/openai-completion-options.ts", "../../../../../node_modules/@ai-sdk/openai/src/embedding/openai-embedding-model.ts", "../../../../../node_modules/@ai-sdk/openai/src/embedding/openai-embedding-options.ts", "../../../../../node_modules/@ai-sdk/openai/src/embedding/openai-embedding-api.ts", "../../../../../node_modules/@ai-sdk/openai/src/image/openai-image-model.ts", "../../../../../node_modules/@ai-sdk/openai/src/image/openai-image-api.ts", "../../../../../node_modules/@ai-sdk/openai/src/image/openai-image-options.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/apply-patch.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/code-interpreter.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/custom.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/file-search.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/image-generation.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/local-shell.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/shell.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/tool-search.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/web-search.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/web-search-preview.ts", "../../../../../node_modules/@ai-sdk/openai/src/tool/mcp.ts", "../../../../../node_modules/@ai-sdk/openai/src/openai-tools.ts", "../../../../../node_modules/@ai-sdk/openai/src/responses/openai-responses-language-model.ts", "../../../../../node_modules/@ai-sdk/openai/src/responses/convert-openai-responses-usage.ts", "../../../../../node_modules/@ai-sdk/openai/src/responses/convert-to-openai-responses-input.ts", "../../../../../node_modules/@ai-sdk/openai/src/responses/map-openai-responses-finish-reason.ts", "../../../../../node_modules/@ai-sdk/openai/src/responses/openai-responses-api.ts", "../../../../../node_modules/@ai-sdk/openai/src/responses/openai-responses-options.ts", "../../../../../node_modules/@ai-sdk/openai/src/responses/openai-responses-prepare-tools.ts", "../../../../../node_modules/@ai-sdk/openai/src/speech/openai-speech-model.ts", "../../../../../node_modules/@ai-sdk/openai/src/speech/openai-speech-options.ts", "../../../../../node_modules/@ai-sdk/openai/src/transcription/openai-transcription-model.ts", "../../../../../node_modules/@ai-sdk/openai/src/transcription/openai-transcription-api.ts", "../../../../../node_modules/@ai-sdk/openai/src/transcription/openai-transcription-options.ts", "../../../../../node_modules/@ai-sdk/openai/src/version.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/chat/openai-compatible-chat-language-model.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/utils/to-camel-case.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/openai-compatible-error.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/chat/convert-openai-compatible-chat-usage.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/chat/convert-to-openai-compatible-chat-messages.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/chat/get-response-metadata.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/chat/map-openai-compatible-finish-reason.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/chat/openai-compatible-chat-options.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/chat/openai-compatible-prepare-tools.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/completion/openai-compatible-completion-language-model.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/completion/convert-openai-compatible-completion-usage.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/completion/convert-to-openai-compatible-completion-prompt.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/completion/get-response-metadata.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/completion/map-openai-compatible-finish-reason.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/completion/openai-compatible-completion-options.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/embedding/openai-compatible-embedding-model.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/embedding/openai-compatible-embedding-options.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/image/openai-compatible-image-model.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/openai-compatible-provider.ts", "../../../../../node_modules/@ai-sdk/openai-compatible/src/version.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/ai-sdk-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/api-call-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/empty-response-body-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/get-error-message.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/invalid-argument-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/invalid-prompt-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/invalid-response-data-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/json-parse-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/load-api-key-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/load-setting-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/no-content-generated-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/no-such-model-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/too-many-embedding-values-for-call-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/type-validation-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/errors/unsupported-functionality-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/src/json-value/is-json.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/combine-headers.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/convert-async-iterator-to-readable-stream.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/create-tool-name-mapping.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/delay.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/delayed-promise.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/extract-response-headers.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/uint8-utils.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/convert-image-model-file-to-data-uri.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/convert-to-form-data.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/download-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/read-response-with-size-limit.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/validate-download-url.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/download-blob.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/generate-id.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/get-error-message.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/get-from-api.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/handle-fetch-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/is-abort-error.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/get-runtime-environment-user-agent.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/normalize-headers.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/with-user-agent-suffix.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/version.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/inject-json-instruction.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/is-non-nullable.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/is-url-supported.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/load-api-key.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/load-optional-setting.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/load-setting.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/media-type-to-extension.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/parse-json.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/secure-json-parse.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/validate-types.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/schema.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/add-additional-properties-to-json-schema.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/options.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/select-parser.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/any.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/array.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/branded.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/catch.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/date.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/default.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/effects.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/enum.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/literal.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/record.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/string.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/map.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/never.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/null.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/union.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/number.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/object.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/optional.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/promise.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/set.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/get-relative-path.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parse-def.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/refs.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/parse-json-event-stream.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/parse-provider-options.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/post-to-api.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/types/tool.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/provider-tool-factory.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/remove-undefined-entries.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/resolve.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/response-handler.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/strip-file-extension.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/without-trailing-slash.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/is-async-iterable.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/types/execute-tool.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/index.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/src/errors.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/src/parse.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/src/stream.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/schemas/reasoning-details.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/utils/type-guards.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/schemas/format.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/schemas/error-response.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/schemas/provider-metadata.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/utils/compute-token-usage.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/utils/map-finish-reason.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/utils/with-stream-error-handling.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/utils/deterministic-stringify.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/utils/reasoning-details-duplicate-tracker.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/types/openrouter-chat-completions-input.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/chat/is-url.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/chat/file-url-utils.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/chat/convert-to-openrouter-chat-messages.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/chat/get-tool-choice.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/chat/schemas.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/schemas/image.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/chat/index.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/completion/convert-to-openrouter-completion-prompt.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/completion/schemas.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/completion/index.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/embedding/schemas.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/embedding/index.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/facade.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/image/schemas.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/image/index.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/tool/web-search.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/utils/remove-undefined.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/utils/with-user-agent-suffix.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/version.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/video/schemas.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/video/index.ts", "../../../../../node_modules/@openrouter/ai-sdk-provider/src/provider.ts", "../../src/app/ai/aiServiceError.ts", "../../src/app/ai/contourOverride.ts", "../../src/utils/tryParseJSON.ts", "../../src/app/ai/openAICompatibleRequestBody.ts", "../../src/app/ai/tracing/openRouterTrace.ts", "../../src/app/ai/config/openRouter.ts", "../../src/code-generation/utils/OverlayCollector.ts", "../../src/code-generation/utils/builtInCodeComponents.ts", "../../src/utils/componentPresetUtils.ts", "../../src/code-generation/utils/CSSCollector.ts", "../../src/code-generation/utils/SubqueryCollector.ts", "../../src/code-generation/utils/getVisibility.ts", "../../src/code-generation/utils/outdatedCacheError.ts", "../../src/code-generation/jsx/computeRendersWithMotion.ts", "../../src/code-generation/jsx/serializesToSameValue.ts", "../../src/code-generation/jsx/difference.ts", "../../src/code-generation/jsx/getValidOverrideImportSpecifiers.ts", "../../src/document/models/CanvasTree/traits/CollectionVariableType.ts", "../../src/document/models/CanvasTree/traits/CollectionVariableDefinition.ts", "../../src/app/ai/utils/collections.ts", "../../src/app/ai/utils/kitSection.ts", "../../src/document/models/CanvasTree/actions/setVariableValueActions.ts", "../../src/document/models/controlProps/getControlPropValuesForCodeGeneration.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectVectorInstanceVariables.ts", "../../src/code-generation/utils/getAttributesFromCodeComponent.ts", "../../src/code-generation/utils/processSvgImageAssets.ts", "../../src/code-generation/utils/shaderFallbackImages.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectAriaLabel.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectAsProp.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectBackdrop.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectBackgroundImage.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectBorder.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectCSSResetAttribute.ts", "../../src/document/components/utils/plugins.ts", "../../src/utils/moduleTypeForIdentifier.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectCodeComponentContainerProps.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectDataNosnippet.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectDraggable.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectEvents.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectFlowEffect.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectFonts.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectFormInputStep.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectHideScrollbarsDataAttribute.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectHighlight.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectLLMSnapshotAttributes.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectLayoutHintDataAttributes.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectLink.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectMotionDrag.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectRelativeOverlaysWithTriggerActions.ts", "../../src/document/models/CanvasTree/nodes/utils/extractInlineStyles.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectRichText.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectSVGFill.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectStyledText.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectTextContent.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectTextSelection.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectTextVerticalAlignment.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectTitleAndDescription.ts", "../../src/document/models/CanvasTree/traits/collectProps/collectTransition.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectMotionLayoutProps.ts", "../../src/code-generation/jsx/propsForNode.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectCursor.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectLink.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectList.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectOverscrollBehavior.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectScrollMargin.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectTapHighlight.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectTextSelection.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectUserSelect.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectViewTransitionName.ts", "../../src/document/models/CanvasTree/traits/collectStyles/collectWillChange.ts", "../../src/code-generation/jsx/styleForNode.ts", "../../src/code-generation/utils/styleDefaults.ts", "../../src/code-generation/jsx/utils.ts", "../../src/code-generation/jsx/jsxAttributesForNode.ts", "../../src/code-generation/loader/PreloadCollectorContext.ts", "../../src/document/components/chrome/properties/utils/getQueryParamNameOfVariable.ts", "../../src/code-generation/loader/RouteLoaderSerializer.ts", "../../src/code-generation/loader/buildRouteLoaderPlan.ts", "../../src/code-generation/loader/getRouteLoaderQueryKey.ts", "../../src/code-generation/loader/RouteLoaderCollector.ts", "../../src/code-generation/utils/serializeFetchData.ts", "../../src/code-generation/loader/PreloadNode.ts", "../../src/code-generation/loader/VariantPreloadCollector.ts", "../../src/code-generation/loader/PreloadCollector.ts", "../../src/code-generation/simulatedDOM/cache.ts", "../../src/code-generation/simulatedDOM/SimulationContext.ts", "../../src/code-generation/simulatedDOM/CantCalculate.ts", "../../src/code-generation/simulatedDOM/cssValue.ts", "../../src/document/models/CanvasTree/traits/utils/applyCollectionFilters.ts", "../../src/document/models/CanvasTree/traits/utils/applyCollectionOptions.ts", "../../src/code-generation/simulatedDOM/utils.ts", "../../src/code-generation/simulatedDOM/grid.ts", "../../src/code-generation/simulatedDOM/numberValue.ts", "../../src/code-generation/simulatedDOM/stack.ts", "../../src/code-generation/simulatedDOM/text.ts", "../../src/code-generation/simulatedDOM/simulateHeight.ts", "../../src/code-generation/simulatedDOM/simulateCSSWidth.ts", "../../src/code-generation/simulatedDOM/simulateYPosition.ts", "../../src/code-generation/simulatedDOM/SimulatedDOM.ts", "../../src/code-generation/utils/AppearIdCollector.ts", "../../src/code-generation/utils/AssetCollector.ts", "../../src/code-generation/utils/ConditionalRenderingCollector.ts", "../../src/code-generation/utils/ElementIdCollector.ts", "../../src/code-generation/utils/ErrorCollector.ts", "../../src/document/base-engine/BaseScopeStore.ts", "../../src/document/models/CanvasTree/actions/openURLActions.ts", "../../src/document/models/CanvasTree/actions/resetVariablesActions.ts", "../../src/code-generation/utils/EventCollector.ts", "../../src/code-generation/utils/FetchDataCollector.ts", "../../src/code-generation/utils/FontCollector.ts", "../../src/code-generation/utils/KitSectionStructureCollector.ts", "../../src/code-generation/utils/LayoutTemplateHitTargetAnnotationCollector.ts", "../../src/code-generation/components/GeneratedSubmodule.ts", "../../src/code-generation/utils/valueTransformCollector/functions/numberToString.ts", "../../src/code-generation/utils/valueTransformCollector/getValueTransformArguments.ts", "../../src/code-generation/utils/valueTransformCollector/functions/addImageAlt.ts", "../../src/code-generation/utils/valueTransformCollector/functions/arrayLength.ts", "../../src/code-generation/utils/valueTransformCollector/functions/arrayToArray.ts", "../../src/code-generation/utils/valueTransformCollector/functions/containsAll.ts", "../../src/code-generation/utils/valueTransformCollector/functions/containsAny.ts", "../../src/code-generation/utils/valueTransformCollector/functions/convertFromBoolean.ts", "../../src/code-generation/utils/valueTransformCollector/functions/utils/getConvertFromEnumOrStringOutputValue.ts", "../../src/code-generation/utils/valueTransformCollector/functions/convertFromEnum.ts", "../../src/code-generation/utils/valueTransformCollector/functions/convertFromString.ts", "../../src/code-generation/utils/valueTransformCollector/functions/endsWith.ts", "../../src/code-generation/utils/valueTransformCollector/functions/equals.ts", "../../src/code-generation/utils/valueTransformCollector/functions/extractDateSegment.ts", "../../src/code-generation/utils/valueTransformCollector/functions/getGridColumnCSSValue.ts", "../../src/code-generation/utils/valueTransformCollector/functions/getGridRowCSSValue.ts", "../../src/code-generation/utils/valueTransformCollector/functions/getNumericColumnGap.ts", "../../src/code-generation/utils/valueTransformCollector/functions/greaterThan.ts", "../../src/code-generation/utils/valueTransformCollector/functions/htmlEscape.ts", "../../src/code-generation/utils/valueTransformCollector/functions/htmlUnescape.ts", "../../src/code-generation/utils/valueTransformCollector/functions/isAfter.ts", "../../src/code-generation/utils/valueTransformCollector/functions/isBefore.ts", "../../src/code-generation/utils/valueTransformCollector/functions/isBetweenDates.ts", "../../src/code-generation/utils/valueTransformCollector/functions/isEven.ts", "../../src/code-generation/utils/valueTransformCollector/functions/isIncludedIn.ts", "../../src/code-generation/utils/valueTransformCollector/functions/isOdd.ts", "../../src/code-generation/utils/valueTransformCollector/functions/isSet.ts", "../../src/code-generation/utils/valueTransformCollector/functions/jsonStringify.ts", "../../src/code-generation/utils/valueTransformCollector/functions/lessThan.ts", "../../src/code-generation/utils/valueTransformCollector/functions/negate.ts", "../../src/code-generation/utils/valueTransformCollector/functions/numberToPixelString.ts", "../../src/code-generation/utils/valueTransformCollector/functions/offsetAndLimitArray.ts", "../../src/code-generation/utils/valueTransformCollector/functions/percentageToCornerShape.ts", "../../src/code-generation/utils/valueTransformCollector/functions/prefix.ts", "../../src/code-generation/utils/valueTransformCollector/functions/radiusForCorner.ts", "../../src/code-generation/utils/valueTransformCollector/functions/reverseArray.ts", "../../src/code-generation/utils/valueTransformCollector/functions/startsWith.ts", "../../src/code-generation/utils/valueTransformCollector/functions/suffix.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toAxisOverflow.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toBoolean.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toDateString.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toImageSrc.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toNumber.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toOverflowWithClipFallback.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toResponsiveImage.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toString.ts", "../../src/code-generation/utils/valueTransformCollector/functions/toZIndex.ts", "../../src/code-generation/utils/valueTransformCollector/getValueTransformFunction.ts", "../../src/code-generation/utils/valueTransformCollector/ValueTransformCollector.ts", "../../src/code-generation/utils/LocalizedValueCollector.ts", "../../src/code-generation/utils/MetricsCollector.ts", "../../src/code-generation/utils/TrackingIdCollector.ts", "../../src/code-generation/utils/TriggerActionCollector.ts", "../../src/code-generation/utils/VectorSetCollector.ts", "../../src/document/models/CanvasTree/traits/collectStyles/nodeRendersWithMotion.ts", "../../src/utils/layoutTemplates.ts", "../../src/code-generation/jsx/createDeduplicatedDynamicValueBinding.ts", "../../src/code-generation/jsx/jsxContext.ts", "../../src/code-generation/jsx/jsxForRepeater.ts", "../../src/code-generation/utils/shouldNodeUseListItem.ts", "../../src/code-generation/jsx/componentForNode.ts", "../../src/code-generation/jsx/jsxTagNameForNode.ts", "../../src/code-generation/jsx/repeaterUtils.ts", "../../src/code-generation/jsx/jsxForNode.ts", "../../src/document/components/utils/renameLayers.ts", "../../src/document/models/CanvasTree/traits/utils/isSymbol.ts", "../../src/document/models/CanvasTree/utils/insertTemplateNode.ts", "../../src/document/components/utils/componentHelpers.ts", "../../src/document/components/utils/replaceNodes.ts", "../../src/document/models/CanvasTree/traits/ScalableVectorStyles.ts", "../../src/document/models/CanvasTree/traits/utils/sizeMinusPadding.ts", "../../src/document/components/utils/dimensions.ts", "../../src/document/components/utils/scaleToolUtils.ts", "../../src/document/components/utils/contextActions.ts", "../../src/document/utils/assignDeep.ts", "../../src/document/crdt/sync/crdtTreeUpdater.ts", "../../src/utils/fileExtensionNames.ts", "../../src/utils/sanitizedVariableName.ts", "../../src/utils/createCodeComponent.ts", "../../src/utils/createCodeOverride.ts", "../../src/code-editor/utils.ts", "../../src/modules/isModulesInTreeOn.ts", "../../src/document/firstScopeFinder.ts", "../../src/document/loader/TaskScheduler.ts", "../../src/code-generation/components/GeneratedComponent.ts", "../../src/code-generation/components/generateMetadataModule.ts", "../../src/document/components/chrome/contentManagement/utils/arrayGalleryUtils.ts", "../../src/document/components/chrome/properties/panels/utils/eventKeyToDisplayName.ts", "../../src/document/components/chrome/contentManagement/utils/collectionFieldPopoutId.ts", "../../src/document/components/chrome/properties/utils/createVariableInScope.ts", "../../src/document/components/tools/utils/createAndAssignActionVariableToNode.ts", "../../src/document/models/CanvasTree/nodes/utils/relativeOverlayDefaults.ts", "../../src/document/models/CanvasTree/nodes/utils/overlayCreationHelpers.ts", "../../src/modules/DependencyGraph.ts", "../../src/code-generation/cmsVersion.ts", "../../src/code-generation/components/generateSnippetsModule.ts", "../../src/code-generation/moduleTypeForSourceNode.ts", "../../src/document/utils/isDrawablePageGroundNode.ts", "../../src/document/utils/moduleSourceNodeHelpers.ts", "../../src/utils/result.ts", "../../src/document/components/utils/getCollectionItemSelectorFromLink.ts", "../../src/document/components/utils/getLinkDataIdentifiers.ts", "../../src/document/utils/LockQueue.ts", "../../src/document/components/chrome/properties/utils/resetNodeOverrides.ts"],
  "sourcesContent": ["\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar get_context_exports = {};\n__export(get_context_exports, {\n  SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,\n  getContext: () => getContext\n});\nmodule.exports = __toCommonJS(get_context_exports);\nconst SYMBOL_FOR_REQ_CONTEXT = Symbol.for(\"@vercel/request-context\");\nfunction getContext() {\n  const fromSymbol = globalThis;\n  return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  SYMBOL_FOR_REQ_CONTEXT,\n  getContext\n});\n", "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar auth_errors_exports = {};\n__export(auth_errors_exports, {\n  AccessTokenMissingError: () => AccessTokenMissingError,\n  RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError\n});\nmodule.exports = __toCommonJS(auth_errors_exports);\nclass AccessTokenMissingError extends Error {\n  constructor() {\n    super(\n      \"No authentication found. Please log in with the Vercel CLI (vercel login).\"\n    );\n    this.name = \"AccessTokenMissingError\";\n  }\n}\nclass RefreshAccessTokenFailedError extends Error {\n  constructor(cause) {\n    super(\"Failed to refresh authentication token.\", { cause });\n    this.name = \"RefreshAccessTokenFailedError\";\n  }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  AccessTokenMissingError,\n  RefreshAccessTokenFailedError\n});\n", "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar index_browser_exports = {};\n__export(index_browser_exports, {\n  AccessTokenMissingError: () => import_auth_errors.AccessTokenMissingError,\n  RefreshAccessTokenFailedError: () => import_auth_errors.RefreshAccessTokenFailedError,\n  getContext: () => import_get_context.getContext,\n  getVercelOidcToken: () => getVercelOidcToken,\n  getVercelOidcTokenSync: () => getVercelOidcTokenSync,\n  getVercelToken: () => getVercelToken\n});\nmodule.exports = __toCommonJS(index_browser_exports);\nvar import_get_context = require(\"./get-context\");\nvar import_auth_errors = require(\"./auth-errors\");\nasync function getVercelOidcToken() {\n  return \"\";\n}\nfunction getVercelOidcTokenSync() {\n  return \"\";\n}\nasync function getVercelToken() {\n  throw new Error(\"getVercelToken is not supported in browser environments\");\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  AccessTokenMissingError,\n  RefreshAccessTokenFailedError,\n  getContext,\n  getVercelOidcToken,\n  getVercelOidcTokenSync,\n  getVercelToken\n});\n", "import type { AnyNodeUpdateSource } from \"document/models/CanvasTree/index.ts\"\nimport type { KeysMatchingInUnion } from \"document/models/CanvasTree/utils/keysMatchingInUnion.ts\"\nimport type { LocalizedValues } from \"document/models/LocalizedValue.ts\"\nimport { getKeys } from \"utils/getKeys.ts\"\n\ntype RequiredLocalizedValuesNodeKey = Exclude<\n\tNonNullable<KeysMatchingInUnion<AnyNodeUpdateSource, LocalizedValues>>,\n\t\"webMetadata\" | \"shaderMouseSpringOptions\"\n>\n\nconst localizedValueKeysRecord: Record<RequiredLocalizedValuesNodeKey, true> = {\n\tallItemsLabelLocalized: true,\n\tbooleanTrueLabelLocalized: true,\n\tbooleanFalseLabelLocalized: true,\n\tfillImageLocalized: true,\n\tformInputPlaceholderLocalized: true,\n\thtmlLocalized: true,\n\taltAttributeLocalized: true,\n\ttitleLocalized: true,\n\tdescriptionLocalized: true,\n\tlinkLocalized: true,\n}\n\nconst localizedValueKeys: Set<string> = new Set(getKeys(localizedValueKeysRecord))\n\nexport const testing = { localizedValueKeys }\n\nexport function isLocalizedValueProperty(key: string): boolean {\n\treturn localizedValueKeys.has(key)\n}\n", "import type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isPrefixedControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport { isArray, isObject } from \"utils/typeChecks.ts\"\nimport { isLocalizedValueProperty } from \"./isLocalizedValueProperty.ts\"\n\nfunction cloneControlPropArrayAndStripLocalizedValues(array: unknown[]): unknown[] {\n\treturn array.map(value => {\n\t\tif (isObject(value)) return cloneControlPropObjectAndStripLocalizedValues(value)\n\t\tif (isArray(value)) return cloneControlPropArrayAndStripLocalizedValues(value)\n\t\treturn value\n\t})\n}\n\n// Within control props, all localized value keys are suffixed with \"Localized\".\n// As of 2025-01 it's at least \"valueLocalized\" and \"altLocalized\".\nexport function isLocalizedControlPropKey(key: string): boolean {\n\treturn key.endsWith(\"Localized\")\n}\n\nfunction cloneControlPropObjectAndStripLocalizedValues(object: Record<string, unknown>): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {}\n\n\tfor (const key in object) {\n\t\tif (isLocalizedControlPropKey(key)) continue\n\n\t\tconst value = object[key]\n\t\tif (isObject(value)) {\n\t\t\tresult[key] = cloneControlPropObjectAndStripLocalizedValues(value)\n\t\t} else if (isArray(value)) {\n\t\t\tresult[key] = cloneControlPropArrayAndStripLocalizedValues(value)\n\t\t} else {\n\t\t\tresult[key] = value\n\t\t}\n\t}\n\n\treturn result\n}\n\nexport function cloneNodePropsAndStripLocalizedValues(node: CanvasNode): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {}\n\n\tlet key: keyof CanvasNode\n\tfor (key in node) {\n\t\tif (isLocalizedValueProperty(key)) continue\n\n\t\tif (!isPrefixedControlPropKey(key)) {\n\t\t\tresult[key] = node[key]\n\t\t\tcontinue\n\t\t}\n\n\t\tconst value = node[key]\n\t\tif (isObject(value)) {\n\t\t\tresult[key] = cloneControlPropObjectAndStripLocalizedValues(value)\n\t\t} else if (isArray(value)) {\n\t\t\tresult[key] = cloneControlPropArrayAndStripLocalizedValues(value)\n\t\t} else {\n\t\t\tresult[key] = value\n\t\t}\n\t}\n\n\treturn result\n}\n\nexport function cloneReplicaOverridesAndStripLocalizedValues(\n\toverrides: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {}\n\n\tfor (const key in overrides) {\n\t\tif (isLocalizedValueProperty(key)) continue\n\n\t\tif (!isPrefixedControlPropKey(key)) {\n\t\t\tresult[key] = overrides[key]\n\t\t\tcontinue\n\t\t}\n\n\t\tconst value = overrides[key]\n\t\tif (isObject(value)) {\n\t\t\tresult[key] = cloneControlPropObjectAndStripLocalizedValues(value)\n\t\t} else if (isArray(value)) {\n\t\t\tresult[key] = cloneControlPropArrayAndStripLocalizedValues(value)\n\t\t} else {\n\t\t\tresult[key] = value\n\t\t}\n\t}\n\n\treturn result\n}\n", "import { triggerEvent } from \"../listeners\";\nfunction createCanvasPageAddEvent(payload) {\n  console.warn(\"[DEPRECATED] Use triggerCanvasPageAddEvent instead of createCanvasPageAddEvent.\");\n  return {\n    ...payload,\n    event: \"canvas_page_add\"\n  };\n}\nconst meta = {\n  track: true\n};\nfunction triggerCanvasPageAddEvent(payload) {\n  const event = {\n    ...payload,\n    event: \"canvas_page_add\"\n  };\n  triggerEvent(event, meta);\n}\nexport {\n  createCanvasPageAddEvent,\n  triggerCanvasPageAddEvent\n};\n", "import { triggerEvent } from \"../listeners\";\nfunction createComponentCanvasCreateEvent(payload) {\n  console.warn(\"[DEPRECATED] Use triggerComponentCanvasCreateEvent instead of createComponentCanvasCreateEvent.\");\n  return {\n    ...payload,\n    event: \"component_canvas_create\"\n  };\n}\nconst meta = {\n  track: true\n};\nfunction triggerComponentCanvasCreateEvent(payload) {\n  const event = {\n    ...payload,\n    event: \"component_canvas_create\"\n  };\n  triggerEvent(event, meta);\n}\nexport {\n  createComponentCanvasCreateEvent,\n  triggerComponentCanvasCreateEvent\n};\n", "import { triggerEvent } from \"../listeners\";\nfunction createComponentCanvasVariantCreateEvent(payload) {\n  console.warn(\"[DEPRECATED] Use triggerComponentCanvasVariantCreateEvent instead of createComponentCanvasVariantCreateEvent.\");\n  return {\n    ...payload,\n    event: \"component_canvas_variant_create\"\n  };\n}\nconst meta = {\n  track: true\n};\nfunction triggerComponentCanvasVariantCreateEvent(payload) {\n  const event = {\n    ...payload,\n    event: \"component_canvas_variant_create\"\n  };\n  triggerEvent(event, meta);\n}\nexport {\n  createComponentCanvasVariantCreateEvent,\n  triggerComponentCanvasVariantCreateEvent\n};\n", "import { triggerEvent } from \"../listeners\";\nfunction createComponentDesignInstanceEvent(payload) {\n  console.warn(\"[DEPRECATED] Use triggerComponentDesignInstanceEvent instead of createComponentDesignInstanceEvent.\");\n  return {\n    ...payload,\n    event: \"component_design_instance\"\n  };\n}\nconst meta = {\n  track: true\n};\nfunction triggerComponentDesignInstanceEvent(payload) {\n  const event = {\n    ...payload,\n    event: \"component_design_instance\"\n  };\n  triggerEvent(event, meta);\n}\nexport {\n  createComponentDesignInstanceEvent,\n  triggerComponentDesignInstanceEvent\n};\n", "import { triggerEvent } from \"../listeners\";\nfunction createPropertyLayoutUpdateEvent(payload) {\n  console.warn(\"[DEPRECATED] Use triggerPropertyLayoutUpdateEvent instead of createPropertyLayoutUpdateEvent.\");\n  return {\n    ...payload,\n    event: \"property_layout_update\"\n  };\n}\nconst meta = {\n  track: true\n};\nfunction triggerPropertyLayoutUpdateEvent(payload) {\n  const event = {\n    ...payload,\n    event: \"property_layout_update\"\n  };\n  triggerEvent(event, meta);\n}\nexport {\n  createPropertyLayoutUpdateEvent,\n  triggerPropertyLayoutUpdateEvent\n};\n", "import { triggerEvent } from \"../listeners\";\nfunction createVariableReferenceCreateEvent(payload) {\n  console.warn(\"[DEPRECATED] Use triggerVariableReferenceCreateEvent instead of createVariableReferenceCreateEvent.\");\n  return {\n    ...payload,\n    event: \"variable_reference_create\"\n  };\n}\nconst meta = {\n  track: true\n};\nfunction triggerVariableReferenceCreateEvent(payload) {\n  const event = {\n    ...payload,\n    event: \"variable_reference_create\"\n  };\n  triggerEvent(event, meta);\n}\nexport {\n  createVariableReferenceCreateEvent,\n  triggerVariableReferenceCreateEvent\n};\n", "import type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isBoolean } from \"utils/typeChecks.ts\"\nimport { isPinnable } from \"../traits/WithPins.ts\"\n\n/** Returns whether the layout pins of a node should be updated when a node is moved to a new position and / or size */\nexport function getConstraintsLocked(node: CanvasNode, override?: boolean): boolean {\n\t// Allow the value to be overridden on purpose (move tool does this for example when moving to a new parent)\n\tif (isBoolean(override)) {\n\t\treturn override\n\t}\n\t// Reuse existing value on the node\n\tif (isPinnable(node)) {\n\t\treturn node.constraintsLocked\n\t}\n\t// Allow for updating the pins\n\treturn false\n}\n", "import { palette } from \"@framerjs/fresco/tokens\"\nimport { assert } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { CanvasNode, CanvasTree, LoadedScopeNode, MaybeNodeID, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { FrameNode, NullID } from \"document/models/CanvasTree/index.ts\"\nimport { randomID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport { isShapeContainerNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { WithAspectRatio } from \"document/models/CanvasTree/traits/WithAspectRatio.ts\"\nimport {\n\tgetFloatingPositionProps,\n\twithFloatingPosition,\n} from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { getLayoutType } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport type { WithPins } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { FramePresetID } from \"document/models/CanvasTree/traits/utils/framePresets.ts\"\nimport { getViewportProviderForNode } from \"document/models/CanvasTree/traits/utils/viewportHelpers.ts\"\nimport { getViewportRect } from \"document/models/CanvasTree/utils/geometry.ts\"\nimport { getConstraintsLocked } from \"document/models/CanvasTree/utils/getConstraintsLocked.ts\"\nimport { guessConstrainedFrame } from \"document/models/ConstraintSolver.ts\"\nimport { shouldGuessPinToBottom } from \"document/models/shouldGuessPinToBottom.ts\"\nimport { shouldGuessPinToRight } from \"document/models/shouldGuessPinToRight.ts\"\nimport { Point } from \"library/render/types/Point.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport { Size } from \"library/render/types/Size.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\n\nexport function constraintsForDropAtPosition(\n\tengine: VekterEngine,\n\tparentId: MaybeNodeID,\n\tposition: Point,\n\tsize: Size,\n): Partial<WithPins & WithAspectRatio> {\n\tconst tree = engine.tree\n\tconst positionAdjustedToCenter = {\n\t\tx: Math.round(position.x - size.width / 2),\n\t\ty: Math.round(position.y - size.height / 2),\n\t}\n\tconst parent = tree.getNode(parentId)\n\tif (!parentId || !parent) {\n\t\treturn { left: positionAdjustedToCenter.x, top: positionAdjustedToCenter.y }\n\t} // else\n\n\tconst viewportProvider = getViewportProviderForNode(engine.tree, parentId)\n\tconst viewport = viewportProvider ? getViewportRect(engine.tree, viewportProvider) : null\n\t// When dropping a new node it shouldn't be fixed layout by default, so we\n\t// don't need to think about the viewport rect here.\n\tconst parentSize: Size = tree.getRect(parent)\n\tconst positionInParent = tree.convertPointToNode(parent, positionAdjustedToCenter)\n\tconst frame = { x: positionInParent.x, y: positionInParent.y, width: size.width, height: size.height }\n\tconst aspectRatio = frame.width / frame.height\n\tconst constrainedFrame: ReturnType<typeof guessConstrainedFrame> & Partial<WithAspectRatio> = guessConstrainedFrame(\n\t\tframe,\n\t\t{ sizing: parentSize, positioning: parentSize, viewport, layout: getLayoutType(parent) },\n\t\t// The node doesn't exist yet so can't have floating position\n\t\t// properties.\n\t\tnull,\n\t\t{\n\t\t\taspectRatio,\n\t\t\tshouldGuessPinToBottom: shouldGuessPinToBottom(tree, null, parent),\n\t\t\tshouldGuessPinToRight: shouldGuessPinToRight(tree, null, parent),\n\t\t},\n\t)\n\t// guessConstrainedFrame will not retain the aspectRatio (because normally the node will\n\t// already have it) So we add it to the update here.\n\tconstrainedFrame.aspectRatio = aspectRatio\n\treturn constrainedFrame\n}\n\nconst frameIsntOverExistingGroundNode = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tframe: Rect,\n\tfilledFrames?: Rect[],\n) => {\n\tconst groundNodes = activeScope.getGroundNodes().map(node => {\n\t\treturn tree.getRect(node)\n\t})\n\tif (filledFrames !== undefined) {\n\t\tgroundNodes.push(...filledFrames)\n\t}\n\treturn (\n\t\tgroundNodes.find(frameFrame => {\n\t\t\treturn Rect.intersects(frame, frameFrame)\n\t\t}) === undefined\n\t)\n}\n\nconst mostRightGroundNode = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tsize: Size,\n\tfilledFrames?: Rect[],\n\txOffsetDistance?: number,\n) => {\n\tconst groundNodes = activeScope.getGroundNodes().map(node => {\n\t\treturn tree.getRect(node)\n\t})\n\tif (filledFrames !== undefined) {\n\t\tgroundNodes.push(...filledFrames)\n\t}\n\tconst ordered = groundNodes.sort((a, b) => {\n\t\treturn Rect.maxX(a) > Rect.maxX(b) ? -1 : 1\n\t})\n\tconst first = ordered[0]\n\tif (first !== undefined) {\n\t\treturn addDefaultOffset(first, size, xOffsetDistance)\n\t}\n\treturn null\n}\n\nconst mostRightGroundNodeWithSimilarSize = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tsize: Size,\n\tfilledFrames?: Rect[],\n\txOffsetDistance?: number,\n): Rect | null => {\n\tconst groundNodes = activeScope.getGroundNodes().map(node => {\n\t\treturn tree.getRect(node)\n\t})\n\tif (filledFrames !== undefined) {\n\t\tgroundNodes.push(...filledFrames)\n\t}\n\tconst similarNodes = groundNodes.filter(node => {\n\t\treturn (\n\t\t\t(node.width === size.width && node.height === size.height) ||\n\t\t\t(node.height === size.width && node.width === size.height)\n\t\t)\n\t})\n\tconst ordered = similarNodes.sort((a, b) => {\n\t\treturn Rect.maxX(a) > Rect.maxX(b) ? -1 : 1\n\t})\n\tconst first = ordered[0]\n\tif (first !== undefined) {\n\t\treturn addDefaultOffset(first, size, xOffsetDistance)\n\t}\n\treturn null\n}\n\nconst selectedGroundNodesWithEqualSize = (tree: CanvasTree, selection: readonly NodeID[], size: Size) => {\n\treturn selection\n\t\t.map(id => tree.getNode(id))\n\t\t.filter((node: CanvasNode) => {\n\t\t\treturn Size.equals(node.rect(null), size)\n\t\t}) as CanvasNode[]\n}\n\nfunction getSuggestedRect({\n\ttree,\n\tactiveScope,\n\tnode,\n\tsize,\n\tfilledRects,\n\toffsetDistance,\n}: {\n\ttree: CanvasTree\n\tactiveScope: LoadedScopeNode\n\tnode: CanvasNode\n\tsize: Size\n\tfilledRects?: Rect[]\n\toffsetDistance: Partial<Point>\n}): Rect {\n\tconst result = { ...tree.getRect(node), ...size }\n\tconst groundNodeRects = activeScope.getGroundNodes().map(groundNode => groundNode.rect())\n\tif (filledRects) {\n\t\tgroundNodeRects.push(...filledRects)\n\t}\n\tlet blocked: Rect | undefined = result\n\tlet counter = 0\n\twhile (blocked) {\n\t\tif (!isUndefined(offsetDistance.x)) {\n\t\t\tresult.x = offsetRectAlongAxis(\"x\", blocked, offsetDistance.x)\n\t\t}\n\t\tif (!isUndefined(offsetDistance.y)) {\n\t\t\tresult.y = offsetRectAlongAxis(\"y\", blocked, offsetDistance.y)\n\t\t}\n\t\tblocked = groundNodeRects.find(frameNodeFrame => {\n\t\t\treturn Rect.intersects(frameNodeFrame, result)\n\t\t})\n\t\tif (counter > groundNodeRects.length) {\n\t\t\treturn result\n\t\t} // making sure our loop stops\n\t\tcounter++\n\t}\n\treturn result\n}\n\nexport const bothSidesOf = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tnode: CanvasNode,\n\tsize: Size,\n\toffsetDistance: Partial<Point> = { x: 100, y: undefined },\n\tfilledRects?: Rect[],\n): Rect => {\n\treturn getSuggestedRect({\n\t\ttree,\n\t\tactiveScope,\n\t\tnode,\n\t\tsize,\n\t\tfilledRects,\n\t\toffsetDistance: offsetDistance,\n\t})\n}\n\nexport const rightSideOf = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tnode: CanvasNode,\n\tsize: Size,\n\txOffsetDistance: number = 100,\n\tfilledRects?: Rect[],\n): Rect => {\n\treturn getSuggestedRect({\n\t\ttree,\n\t\tactiveScope,\n\t\tnode,\n\t\tsize,\n\t\tfilledRects,\n\t\toffsetDistance: { x: xOffsetDistance },\n\t})\n}\n\nexport const bottomSideOf = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tnode: CanvasNode,\n\tsize: Size,\n\tyOffsetDistance: number = 100,\n\tfilledRects?: Rect[],\n): Rect => {\n\treturn getSuggestedRect({\n\t\ttree,\n\t\tactiveScope,\n\t\tnode,\n\t\tsize,\n\t\tfilledRects,\n\t\toffsetDistance: { y: yOffsetDistance },\n\t})\n}\n\nfunction offsetRectAlongAxis(axis: \"x\" | \"y\", rect: Rect, distance: number): number {\n\tconst max = axis === \"x\" ? Rect.maxX : Rect.maxY\n\treturn max(rect) + distance\n}\n\nfunction addDefaultOffset(rect: Rect, size: Size, xOffsetDistance: number = 100): Rect {\n\treturn { ...rect, x: offsetRectAlongAxis(\"x\", rect, xOffsetDistance), ...size }\n}\n\nexport const suggestedRect = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tsize: Size | Rect,\n\tselection?: readonly NodeID[],\n\tfilledRects?: Rect[],\n\toriginal?: NodeID,\n\txOffsetDistance?: number,\n): Rect => {\n\tif (original) {\n\t\tconst node = tree.getNode(original)\n\t\tif (node) {\n\t\t\treturn rightSideOf(tree, activeScope, node, size, xOffsetDistance, filledRects)\n\t\t}\n\t}\n\tif (selection) {\n\t\tconst equalFrames = selectedGroundNodesWithEqualSize(tree, selection, size)\n\t\tif (equalFrames.length) {\n\t\t\tconst suggestions = equalFrames.map(node => {\n\t\t\t\treturn addDefaultOffset(node.rect(), size, xOffsetDistance)\n\t\t\t})\n\t\t\tconst suited = suggestions.find(frame => {\n\t\t\t\treturn frameIsntOverExistingGroundNode(tree, activeScope, frame, filledRects)\n\t\t\t})\n\t\t\tif (suited) {\n\t\t\t\treturn suited\n\t\t\t} // else\n\t\t\tconst first = equalFrames[0]\n\t\t\tassert(first, \"Equal frame must be defined\")\n\t\t\treturn rightSideOf(tree, activeScope, first, size, xOffsetDistance, filledRects)\n\t\t}\n\t}\n\tconst similar = mostRightGroundNodeWithSimilarSize(tree, activeScope, size, filledRects, xOffsetDistance)\n\tif (similar !== null && frameIsntOverExistingGroundNode(tree, activeScope, similar, filledRects)) {\n\t\treturn similar\n\t}\n\tconst mostRight = mostRightGroundNode(tree, activeScope, size, filledRects, xOffsetDistance)\n\tif (mostRight !== null && frameIsntOverExistingGroundNode(tree, activeScope, mostRight, filledRects)) {\n\t\treturn mostRight\n\t}\n\treturn { ...size, x: 0, y: 0 }\n}\n\nexport const suggestedConstraintsForCopiedNode = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tnode: CanvasNode & WithPins,\n\tselection: readonly NodeID[],\n\tfilledFrames: Rect[],\n) => {\n\tconst frame = tree.getRect(node)\n\tconst parent = tree.getParent(node.id)\n\n\tlet xOffsetDistance: number | undefined\n\tif (isShapeContainerNode(node)) {\n\t\txOffsetDistance = Math.min(frame.width, 100)\n\t}\n\n\tconst frameSuggestion = suggestedRect(tree, activeScope, frame, selection, filledFrames, node.id, xOffsetDistance)\n\tfilledFrames.push(frameSuggestion)\n\treturn guessConstrainedFrame(\n\t\tframeSuggestion,\n\t\tnull,\n\t\twithFloatingPosition(node) ? getFloatingPositionProps(node) : null,\n\t\t{\n\t\t\tshouldGuessPinToBottom: true,\n\t\t\tshouldGuessPinToRight: shouldGuessPinToRight(tree, node, parent),\n\t\t},\n\t)\n}\n\nexport const suggestedTopLevelFrame = (\n\ttree: CanvasTree,\n\tactiveScope: LoadedScopeNode,\n\tselection: NodeID[],\n\tposition: Point,\n): MaybeNodeID => {\n\tif (selection.length > 0) {\n\t\tconst nodeId = selection[selection.length - 1]\n\t\tconst parentNode = tree.getGroundFrameAncestor(nodeId, true)\n\t\tif (parentNode) {\n\t\t\treturn parentNode.id\n\t\t}\n\t}\n\tfor (const node of tree.sortVisually(tree.getNodesAtPoint(activeScope, position)).reverse()) {\n\t\tif (node instanceof FrameNode && tree.getParent(node.id) === NullID) {\n\t\t\tconst isReplica = isReplicaOrReplicaChild(node)\n\t\t\tif (isReplica) continue\n\t\t\treturn node.id\n\t\t}\n\t}\n\treturn NullID\n}\n\nexport const createScreenWithPreset = (engine: VekterEngine, frame: Rect, framePreset?: FramePresetID): NodeID => {\n\tconst id = randomID()\n\tconst attributes: Partial<FrameNode> = {\n\t\ttop: frame.y,\n\t\tleft: frame.x,\n\t\twidth: frame.width,\n\t\theight: frame.height,\n\t\toverflow: \"clip\",\n\t\tisScreen: true,\n\t}\n\tattributes.framePreset = framePreset\n\n\tengine.createFrame(NullID, { id, ...attributes })\n\n\treturn id\n}\n\nexport const createWrappingFrame = (engine: VekterEngine, frame: Rect) => {\n\tconst tree = engine.tree\n\tconst id = randomID()\n\tconst attributes: Partial<FrameNode> = {\n\t\ttop: frame.y,\n\t\tleft: frame.x,\n\t\twidth: frame.width,\n\t\theight: frame.height,\n\t\toverflow: \"clip\",\n\t\tisScreen: true,\n\t}\n\n\t// create wrapping frame\n\tengine.createFrame(NullID, { id, ...attributes })\n\n\t// find nodes we want to place inside of new frame\n\tconst nodesInRect = engine.stores.scopeStore.active.getGroundNodes(node => {\n\t\tconst nodeFrame = tree.getRect(node)\n\t\t// filter out the new frame\n\t\treturn node.id !== id && Rect.containsRect(frame, nodeFrame)\n\t})\n\n\t// move nodes inside\n\tnodesInRect.forEach(node => {\n\t\tconst parent = tree.getParent(node.id)\n\t\tconst nodeFrame = tree.getRect(node)\n\t\tconst convertedFrame = Rect.offset(nodeFrame, Point.reverse(frame))\n\t\tengine.moveNode(node.id, id)\n\t\tengine.tree.current(node)?.set(\n\t\t\tnode.updateForRect({\n\t\t\t\trect: convertedFrame,\n\t\t\t\t// Viewport is always null here because this is only used in\n\t\t\t\t// prototyping canvas pages where viewport is not a concept.\n\t\t\t\tparentSizeInfo: { sizing: frame, positioning: frame, viewport: null, layout: getLayoutType(parent) },\n\t\t\t\tconstraintsLocked: getConstraintsLocked(node),\n\t\t\t\tshouldGuessPinToBottom: true,\n\t\t\t\tshouldGuessPinToRight: shouldGuessPinToRight(engine.tree, node, parent),\n\t\t\t}),\n\t\t)\n\t})\n\n\treturn id\n}\n\nconst frameColors = [\"#9ef\", \"#4cf\", \"#3af\", \"#38f\", \"#26f\"]\nconst agentDefaultFrameColor = \"#BDF\"\n\nexport const getNextFrameColor = (() => {\n\tlet index = -1\n\tconst colorCount = frameColors.length\n\n\treturn () => {\n\t\tif (experiments.isOn(\"agent\")) return agentDefaultFrameColor\n\t\tif (experiments.isOn(\"greyFrameDefault\")) return palette.dark20\n\t\tindex++\n\t\treturn frameColors[index % colorCount]\n\t}\n})()\n", "import type { AnyComponentLoader, SetVariantOptions, SetVariantType } from \"@framerjs/framer-runtime\"\nimport { setVariantActionControlTypes, setVariantActionDefaults } from \"@framerjs/framer-runtime\"\nimport type { EventAction } from \"document/models/EventAction.ts\"\nimport { isEventAction } from \"document/models/EventAction.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { v4 as uuid } from \"uuid\"\nimport type { CanvasTree } from \"../CanvasTree.ts\"\nimport type { CanvasNode } from \"../nodes/CanvasNode.ts\"\nimport type { MaybeNodeID } from \"../nodes/NodeID.ts\"\nimport { isSmartComponentNode } from \"../nodes/utils/nodeCheck.ts\"\nimport { HardCodedCodeIdentifier } from \"../traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport type { ActionControlValues } from \"./actions.ts\"\nimport { containsActionsOfType, getActionsOfType } from \"./actions.ts\"\n\ntype SetVariantActionModel = SetVariantOptions\ntype SetVariantActionControls = ActionControlValues<SetVariantActionModel>\n\nconst controlDefaults: SetVariantActionControls = {\n\ttype: {\n\t\ttype: setVariantActionControlTypes.type,\n\t\tvalue: setVariantActionDefaults.type,\n\t},\n\tvariantId: {\n\t\ttype: setVariantActionControlTypes.variantId,\n\t\tvalue: undefined,\n\t},\n\tpauseOffscreen: {\n\t\ttype: setVariantActionControlTypes.pauseOffscreen,\n\t\tvalue: setVariantActionDefaults.pauseOffscreen,\n\t},\n}\n\nexport const setVariantActionKeys: { [Key in keyof SetVariantActionModel]: Key } = {\n\ttype: \"type\",\n\tvariantId: \"variantId\",\n\tpauseOffscreen: \"pauseOffscreen\",\n}\n\nexport interface SetVariantAction extends EventAction {\n\tcontrols: SetVariantActionControls\n}\n\nconst setVariantTypeMap: { [key in SetVariantType]: true } = {\n\tcycle: true,\n\tset: true,\n}\n\nexport function isSetVariantType(value: unknown): value is SetVariantType {\n\treturn isString(value) && value in setVariantTypeMap\n}\n\nexport function isSetVariantAction(value: unknown): value is SetVariantAction {\n\treturn isEventAction(value) && value.actionIdentifier === HardCodedCodeIdentifier.setVariantAction\n}\n\nexport function getSetVariantTarget(action: SetVariantAction): MaybeNodeID {\n\tif (action.controls.type?.value !== \"set\") return null\n\treturn action.controls.variantId?.value ?? null\n}\n\nexport function containsSetVariantAction(value: unknown): value is readonly EventAction[] {\n\treturn Array.isArray(value) && value.some(isSetVariantAction)\n}\n\nexport function containsSetVariantActionWithoutVariant(value: unknown): value is readonly EventAction[] {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tvalue.some(\n\t\t\taction =>\n\t\t\t\tisSetVariantAction(action) && action.controls.type?.value === \"set\" && !action.controls.variantId?.value,\n\t\t)\n\t)\n}\n\nexport function hasVariantLinks(node: CanvasNode, componentLoader: AnyComponentLoader): boolean {\n\treturn containsActionsOfType(node, isSetVariantAction, componentLoader)\n}\n\nexport function getSetVariantActionTargets(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tcomponentLoader: AnyComponentLoader,\n): string[] {\n\tconst actions = getActionsOfType(node, isSetVariantAction, componentLoader)\n\tconst targets: string[] = []\n\n\tactions.forEach(action => {\n\t\tconst type = action.controls.type?.value\n\t\tswitch (type) {\n\t\t\tcase \"set\": {\n\t\t\t\tconst variantId = action.controls.variantId?.value\n\t\t\t\tif (variantId) targets.push(variantId)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"cycle\": {\n\t\t\t\tconst scopeNode = tree.getScopeNodeFor(node)\n\t\t\t\tif (!isSmartComponentNode(scopeNode)) return\n\n\t\t\t\tconst variantNodes = scopeNode.getTopLevelVariants()\n\t\t\t\tif (variantNodes.length <= 1) return\n\n\t\t\t\tconst groundNode = tree.getGroundNodeFor(node)\n\t\t\t\tconst currentVariantIndex = variantNodes.findIndex(variantNode => variantNode.id === groundNode.id)\n\t\t\t\tif (currentVariantIndex === -1) return\n\n\t\t\t\tconst indexPlusOne = currentVariantIndex + 1\n\t\t\t\tconst nextVariantIndex = indexPlusOne >= variantNodes.length ? 0 : indexPlusOne\n\t\t\t\tconst nextVariantNode = variantNodes[nextVariantIndex]\n\t\t\t\tif (nextVariantNode) targets.push(nextVariantNode.id)\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t})\n\n\treturn targets\n}\n\nexport function getSetVariantOptionsFromActionControls(\n\tcontrols: SetVariantAction[\"controls\"],\n): Partial<SetVariantOptions> {\n\tconst options: Partial<SetVariantOptions> = {}\n\n\tObject.entries(controls).forEach(([key, control]) => {\n\t\toptions[key] = control?.value\n\t})\n\n\treturn options\n}\n\n// When using the Link Tool to create a new set variant action, we only want to\n// *replace* the action if the meta is the same.\nfunction hasMatchingActionMeta(a?: SetVariantAction[\"meta\"], b?: SetVariantAction[\"meta\"]): boolean {\n\tif (a?.inputValue !== b?.inputValue) return false\n\tif (a?.delay !== b?.delay) return false\n\tif (a?.key !== b?.key) return false\n\treturn true\n}\n\nexport type UpdateSetVariantOptions = Partial<SetVariantActionModel>\nexport function updateSetVariantVariant(\n\tactions: unknown,\n\toptions: UpdateSetVariantOptions,\n\tmeta?: SetVariantAction[\"meta\"],\n): EventAction[] {\n\tconst result: EventAction[] = Array.isArray(actions) ? [...actions] : []\n\n\tconst setVariantActionIndex = result.findIndex(isSetVariantAction)\n\tconst existingSetVariantAction = result[setVariantActionIndex]\n\tif (isSetVariantAction(existingSetVariantAction) && hasMatchingActionMeta(existingSetVariantAction.meta, meta)) {\n\t\tconst controls: Readonly<SetVariantActionControls> = {\n\t\t\t...existingSetVariantAction.controls,\n\t\t\t...addControlTypesToModel(options),\n\t\t}\n\t\tconst newAction: EventAction = {\n\t\t\t...existingSetVariantAction,\n\t\t\tcontrols: controls,\n\t\t\tmeta: { ...existingSetVariantAction.meta, ...meta },\n\t\t}\n\t\tresult[setVariantActionIndex] = newAction\n\t} else {\n\t\tconst action = createSetVariantAction(options, undefined, meta)\n\t\tresult.push(action)\n\t}\n\n\treturn result\n}\n\nfunction addControlTypesToModel(model: Partial<SetVariantActionModel>): Partial<SetVariantActionControls> {\n\tconst modelWithTypes: Partial<SetVariantActionControls> = {}\n\n\tObject.entries(model).forEach(([key, value]) => {\n\t\tmodelWithTypes[key] = {\n\t\t\ttype: setVariantActionControlTypes[key as keyof typeof setVariantActionControlTypes],\n\t\t\tvalue,\n\t\t}\n\t})\n\n\treturn modelWithTypes\n}\n\nexport function createSetVariantAction(\n\tmodel?: Partial<SetVariantActionModel>,\n\tid?: string,\n\tmeta?: SetVariantAction[\"meta\"],\n) {\n\tconst modelWithTypes = addControlTypesToModel({ ...model })\n\n\tconst newAction: SetVariantAction = {\n\t\tidentifier: id ? id : uuid(),\n\t\tactionIdentifier: HardCodedCodeIdentifier.setVariantAction,\n\t\tcontrols: {\n\t\t\t...controlDefaults,\n\t\t\t...modelWithTypes,\n\t\t},\n\t}\n\n\tif (meta) Object.assign(newAction, { meta })\n\n\treturn newAction\n}\n\nexport function updatedSetVariantAction(\n\taction: SetVariantAction,\n\tcontrolOverrides: Partial<SetVariantActionControls>,\n): SetVariantAction {\n\tconst controls = {\n\t\t...action.controls,\n\t\t...controlOverrides,\n\t}\n\treturn { ...action, controls }\n}\n", "import type { CanvasTree, RootNode } from \"document/models/CanvasTree/index.ts\"\nimport { isRedirectRouteNode, isRootNode, isRoutesNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { WithVariables } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { withVariables } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ClassDiscriminator } from \"utils/withClassDiscriminator.ts\"\nimport type { UndoRedoEntry } from \"../stores/UndoRedoManager.ts\"\n\nexport function isRedirectUndoRedoEntry(entry: UndoRedoEntry | undefined, tree: CanvasTree): boolean {\n\tif (!entry) return false\n\tif (entry.changes.length === 0) return false\n\n\tfor (const change of entry.changes) {\n\t\tconst node = tree.get(change.id)\n\n\t\tif (isRedirectRouteNode(node)) continue\n\t\tif (isRoutesNode(node)) continue\n\t\tif (!node && change.added === ClassDiscriminator.RedirectRouteNode) continue\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nexport function isVariableUndoRedoEntry(entry: UndoRedoEntry | undefined, tree: CanvasTree): boolean {\n\tif (!entry) return false\n\tif (entry.changes.length === 0) return false\n\n\tfor (const change of entry.changes) {\n\t\tconst node = tree.get(change.id)\n\t\tif (!node || !withVariables(node)) return false\n\t\tconst variablesKey: keyof WithVariables = \"variables\"\n\t\treturn variablesKey in change.from\n\t}\n\n\treturn true\n}\n\nexport function isLocalesUndoRedoEntry(entry: UndoRedoEntry | undefined, tree: CanvasTree): boolean {\n\tif (!entry) return false\n\tif (entry.changes.length === 0) return false\n\n\tfor (const change of entry.changes) {\n\t\tconst node = tree.get(change.id)\n\t\tif (!isRootNode(node)) return false\n\n\t\tconst localesKey: keyof RootNode = \"locales\"\n\t\tif (localesKey in change.from) return true\n\t\tif (change.from._deleted?.includes(localesKey)) return true\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n", "import { EngineStore } from \"document/EngineStore.ts\"\n\nexport enum PopoverType {\n\tNone,\n\tInvite,\n\tCopyLink,\n\tPublish,\n\tProject,\n\tBranch,\n}\n\nexport class PopoverStore extends EngineStore {\n\tactive: PopoverType = PopoverType.None\n}\n", "import { getLogger } from \"@framerjs/shared\"\nimport { environment } from \"environment/index.ts\"\nimport type { EngineStore } from \"./EngineStore.ts\"\nimport type { BaseEngineScheduler } from \"./base-engine/BaseEngine.ts\"\n\nconst log = getLogger(\"EngineChanges\")\n\nexport const enum EngineChange {\n\tTreeStore = \"TreeStore\",\n\tTree = \"Tree\",\n\tHighlight = \"Highlight\",\n\tArrows = \"Arrows\",\n\tShapeContainerNodes = \"ShapeContainerNodes\",\n\tLocalSmartComponents = \"LocalSmartComponents\",\n\tLocalLayoutTemplates = \"LocalLayoutTemplates\",\n\tVariableProviderInfo = \"VariableProviderInfo\",\n\tColorStyleTokens = \"ColorStyleTokens\",\n\tTextStylePresets = \"TextStylePresets\",\n\n\t// Used when the node cache is synced with DOM layout after rendering,\n\t// because we want any selection outlines to update\n\tTreeDOMLayoutSync = \"TreeDOMLayoutSync\",\n\tTool = \"Tool\",\n\tExitMove = \"ExitMove\", // Special overlay grids flag to do as little work as possible.\n\n\tCanvasStore = \"CanvasStore\", // CanvasStore properties other than the ones below\n\tCanvasZoom = \"CanvasZoom\", // Render quality changes\n\tCanvasLiveTransform = \"CanvasLiveTransform\", // Texture transform only changes\n\tAssetMap = \"AssetMap\", // Changes to the Asset Map\n\n\t// ComponentStore\n\tPendingBundle = \"PendingBundle\",\n\tActiveBundle = \"ActiveBundle\",\n\tScriptErrors = \"ScriptErrors\",\n\n\tMouseStore = \"MouseStore\",\n\tRemoteUsersStore = \"RemoteUsersStore\",\n\n\tPathSelection = \"PathSelection\",\n\n\tUserDefaultsStore = \"UserDefaultsStore\",\n\tDocumentSettings = \"DocumentSettings\",\n\n\tSelectionOutline = \"SelectionOutline\",\n\n\tCustomFontStore = \"CustomFontStore\",\n\n\tTabContentWidth = \"TabContentWidth\",\n\tPropertyPanelWidth = \"PropertyPanelWidth\",\n\n\tFeedbackStore = \"FeedbackStore\",\n}\n\ninterface OnPageSignalStore {\n\tscheduler: Pick<BaseEngineScheduler, \"signalChanges\">\n}\n\nexport type EngineChangeFlag = EngineStore | EngineChange | OnPageSignalStore\n\nexport type EngineChangeSignal = (...flags: EngineChangeFlag[]) => void\n\n// TODO: make it proper \"opaque\" type when implemented in TypeScript\nexport type ObserverToken = () => unknown & { __opaque: \"ObserverToken\" }\ntype Observer = () => unknown\n\nexport class EngineChanges {\n\tprivate changes: Set<EngineChangeFlag> = new Set()\n\n\taddChanges = (...flags: EngineChangeFlag[]) => {\n\t\tfor (const flag of flags) {\n\t\t\tthis.changes.add(flag)\n\t\t}\n\t}\n\n\tget flags(): Set<EngineChangeFlag> {\n\t\treturn this.changes\n\t}\n\n\thas(...flags: EngineChangeFlag[]): boolean {\n\t\tfor (const flag of flags) {\n\t\t\tif (this.changes.has(flag)) return true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate changeObserverFlags: EngineChangeFlag[][] = []\n\tprivate changeObservers: Observer[] = []\n\n\t// Used when signalling observers, so we don't mutate the observer lists\n\t// while iterating over them.\n\tprivate inSignalAllObservers = false\n\tprivate observersToRemove: ObserverToken[] = []\n\n\tobserve(...args: [...EngineChangeFlag[], Observer]): ObserverToken {\n\t\tconst observer = args.pop() as Observer\n\t\tconst flags = args as EngineChangeFlag[]\n\t\tif (environment.isDebugBuild && flags.some(f => f === undefined)) {\n\t\t\tlog.warn(\n\t\t\t\t\"changes.observe was called with undefined as one of the flags. It might be caused by observing a store that hasn't been instantiated yet.\",\n\t\t\t)\n\t\t}\n\n\t\tthis.changeObserverFlags.push(flags)\n\t\tthis.changeObservers.push(observer)\n\t\treturn observer as ObserverToken\n\t}\n\n\tobserveWithComponent<State>(\n\t\tflags: EngineChangeFlag[],\n\t\tcomponent: React.Component<unknown, State>,\n\t\tcalculateState: () => State,\n\t): ObserverToken {\n\t\tthis.changeObserverFlags.push(flags)\n\t\tconst callback = () => {\n\t\t\tif (environment.benchmarkSkipRendering) return\n\t\t\tcomponent.setState(calculateState())\n\t\t}\n\t\tthis.changeObservers.push(callback)\n\t\treturn callback as ObserverToken\n\t}\n\n\tremoveObserver(callback: ObserverToken) {\n\t\t// Cannot remove observers when iterating over the observer lists.\n\t\tif (this.inSignalAllObservers) {\n\t\t\tthis.observersToRemove.push(callback)\n\t\t\treturn\n\t\t}\n\n\t\tconst at = this.changeObservers.indexOf(callback)\n\t\tif (at === -1) return\n\t\tthis.changeObserverFlags.splice(at, 1)\n\t\tthis.changeObservers.splice(at, 1)\n\t}\n\n\tsignalAllObservers() {\n\t\tif (!this.changes) return\n\n\t\tconst changedFlags = this.changes\n\t\tconst flagsByObserver = this.changeObserverFlags\n\t\tconst callbacks = this.changeObservers\n\n\t\tthis.inSignalAllObservers = true\n\t\tfor (let i = 0; i < flagsByObserver.length; i++) {\n\t\t\tconst observerFlags = flagsByObserver[i]!\n\t\t\tfor (const flag of observerFlags) {\n\t\t\t\tif (changedFlags.has(flag)) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: callbacks and flagsByObserver are parallel arrays\n\t\t\t\t\tcallbacks[i]!()\n\t\t\t\t\t// make sure we only call the callback once\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.inSignalAllObservers = false\n\n\t\t// Remove any observers that we didn't yet remove because we were looping.\n\t\tif (this.observersToRemove.length > 0) {\n\t\t\tfor (const observer of this.observersToRemove) {\n\t\t\t\tthis.removeObserver(observer)\n\t\t\t}\n\t\t\tthis.observersToRemove.length = 0\n\t\t}\n\n\t\tthis.changes.clear()\n\t}\n\n\tsignalObserversFor(...changedFlags: EngineChangeFlag[]) {\n\t\tconst changedFlagsSet = new Set(changedFlags)\n\t\tconst flagsByObserver = this.changeObserverFlags\n\t\tconst callbacks = this.changeObservers\n\t\tfor (let i = 0; i < flagsByObserver.length; i++) {\n\t\t\tconst observerFlags = flagsByObserver[i]!\n\t\t\tfor (const flag of observerFlags) {\n\t\t\t\tif (changedFlagsSet.has(flag)) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: callbacks and flagsByObserver are parallel arrays\n\t\t\t\t\tcallbacks[i]!()\n\t\t\t\t\t// make sure we only call the callback once\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tchangedFlagsSet.forEach(changedFlag => this.changes.delete(changedFlag))\n\t}\n}\n", "import {\n\tACLPermission,\n\ttype ACLPermissions,\n\ttype InviteACLEntry,\n\ttype UserACLEntry,\n\tfullPermissions,\n\tnoPermissions,\n} from \"@framerjs/app-shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { EngineStores } from \"document/EngineStores.ts\"\nimport type { VekterEngineScheduler } from \"document/VekterEngineScheduler.ts\"\nimport type { ChromeStore } from \"document/stores/ChromeStore.ts\"\nimport type { ProjectStore } from \"document/stores/ProjectStore.ts\"\nimport type { SessionStore } from \"document/stores/SessionStore.ts\"\nimport { environment } from \"environment/index.ts\"\nimport { isShallowEqual } from \"utils/isShallowEqual.ts\"\nimport { deepFreeze } from \"utils/updatable.ts\"\n\nexport interface PermissionState {\n\t/**\n\t * `ChromeStore.userIsViewer`\n\t *\n\t * TODO: This is partially overlapping the user ACL, but we also use it\n\t * to force view-only state for debugging/QA/tests. We should make this\n\t * solely about the latter.\n\t */\n\tuserIsViewer: boolean\n\n\t/**\n\t * `ChromeStore.userIsAccountSharing`\n\t *\n\t * When true, indicates the user is in account sharing mode and should be view-only.\n\t */\n\tuserIsAccountSharing?: boolean\n\n\t/**\n\t * `ChromeStore.isViewingBranchFromOtherUser`\n\t *\n\t * When true, the user is viewing a branch they don't own and should be view-only.\n\t */\n\tisViewingBranchFromOtherUser?: boolean\n\n\t/** `ProjectStore.acl` */\n\tacl: (UserACLEntry | InviteACLEntry)[]\n\n\t/** `SessionStore.user?.id` */\n\tuserId: string\n}\n\nexport function getACLPermissions(state: PermissionState): ACLPermissions {\n\tif (state.userIsViewer) {\n\t\treturn noPermissions\n\t}\n\n\tif (environment.isAutomation || environment.isTest) {\n\t\treturn fullPermissions\n\t}\n\n\tconst userEntry = state.acl.find(entry => entry.user.id === state.userId)\n\treturn userEntry?.permissions ?? noPermissions\n}\n\n/**\n * ExtendedPermissions is a wrapper around ACLPermissions which:\n *\n * - Translates the ACLPermission enums to booleans, so that they're easier to\n *   deal with and less error prone (e.g., `if (aclPermissions.canDesign)` will\n *   always evaluate to true, even if canDesign is \"off\").\n *\n * - Adds a few additional, derived permissions.\n *\n *   Derived permissions are not actually managed by the user, are not part of\n *   the ACL, and are not stored or returned from the backend.\n *\n *   They exist mostly as a convenience, and as a way to centralize certain\n *   permissions, e.g., if we ever change our mind on what actual permissions\n *   you need in order to edit site settings, we can do it in a single place.\n */\nexport class ExtendedPermissions {\n\tconstructor(private aclPermissions: ACLPermissions) {}\n\n\tget canDesign(): boolean {\n\t\treturn this.aclPermissions.canDesign === ACLPermission.On\n\t}\n\n\tget canEditContent(): boolean {\n\t\treturn this.aclPermissions.canEditContent === ACLPermission.On\n\t}\n\n\tget canPublish(): boolean {\n\t\treturn this.aclPermissions.canPublish === ACLPermission.On\n\t}\n\n\tget canEditSiteSettings(): boolean {\n\t\treturn this.canDesign && this.canEditContent && this.canPublish\n\t}\n\n\tget canPublishToStaging(): boolean {\n\t\treturn this.canDesign || this.canEditContent || this.canPublish\n\t}\n\n\tget canInviteCollaborators(): boolean {\n\t\treturn this.canDesign || this.canEditContent || this.canPublish\n\t}\n\n\tget canEditVariables(): boolean {\n\t\treturn this.canDesign\n\t}\n\n\tget canAddCollections(): boolean {\n\t\treturn this.canDesign\n\t}\n\n\tget canEditAnalytics(): boolean {\n\t\treturn this.canDesign || this.canEditContent\n\t}\n\n\t/** Locales are only editable by site owners, and not by content editors. */\n\tget canEditLocales(): boolean {\n\t\treturn this.canDesign\n\t}\n\n\t/** Values can be localized by content editors. */\n\tget canEditLocalizedValues(): boolean {\n\t\treturn this.canEditContent\n\t}\n\n\t/** True if the user can send tree updates to the server. */\n\tget canSendDiffs(): boolean {\n\t\treturn this.canDesign || this.canEditContent\n\t}\n}\n\nexport const permissionToText = deepFreeze({\n\tcanDesign: Dictionary.Design,\n\tcanEditContent: Dictionary.Content,\n\tcanPublish: \"Deploy\",\n\tcanEditSiteSettings: `Design and ${Dictionary.Content} and Deploy`,\n\tcanPublishToStaging: `Design or ${Dictionary.Content} or Deploy`,\n\tcanInviteCollaborators: `Design or ${Dictionary.Content} or Deploy`,\n\tcanEditVariables: Dictionary.Design,\n\tcanAddCollections: Dictionary.Design,\n\tcanEditAnalytics: `Design or ${Dictionary.Content}`,\n\tcanEditLocales: Dictionary.Design,\n\tcanEditLocalizedValues: Dictionary.Content,\n\tcanSendDiffs: `Design or ${Dictionary.Content}`,\n} as const satisfies { [K in keyof ExtendedPermissions]: string })\n\nexport function getPermissions(state: PermissionState): ExtendedPermissions {\n\tconst aclPermissions = getACLPermissions(state)\n\treturn new ExtendedPermissions(aclPermissions)\n}\n\nexport type PermissionStateDependencies = [ChromeStore, ProjectStore, SessionStore]\n\nexport const getPermissionStateDependencies = (stores: EngineStores): PermissionStateDependencies => [\n\tstores.chromeStore,\n\tstores.projectStore,\n\tstores.sessionStore,\n]\n\nexport const getPermissionState = ([\n\tchromeStore,\n\tprojectStore,\n\tsessionStore,\n]: PermissionStateDependencies): PermissionState => ({\n\tuserIsViewer: chromeStore.userIsViewer,\n\tuserIsAccountSharing: chromeStore.userIsAccountSharing,\n\tisViewingBranchFromOtherUser: chromeStore.isViewingBranchFromOtherUser,\n\tacl: projectStore.acl,\n\tuserId: sessionStore.user.id,\n})\n\n/**\n * Subscribe to changes in the {@link PermissionState | permission state}.\n *\n * Use `subscribeToPermissionStateWithIsReadyChanges` if you need `isReady`.\n */\nexport function subscribeToPermissionStateChanges(\n\tstores: EngineStores,\n\tscheduler: VekterEngineScheduler,\n\tobserver: (state: PermissionState) => void,\n\t{ signal }: { signal: AbortSignal },\n): void {\n\tconst dependencies = getPermissionStateDependencies(stores)\n\tlet currentState = getPermissionState(dependencies)\n\n\tconst token = scheduler.changes.observe(...dependencies, () => {\n\t\tconst nextState = getPermissionState(dependencies)\n\t\tif (isShallowEqual(currentState, nextState)) return\n\t\tcurrentState = nextState\n\t\tobserver(nextState)\n\t})\n\n\tsignal.addEventListener(\n\t\t\"abort\",\n\t\t() => {\n\t\t\tscheduler.changes.removeObserver(token)\n\t\t},\n\t\t{ once: true },\n\t)\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { type BaseEngine, useBaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport type { OnPageEngine } from \"./OnPageEngine.ts\"\n\n/**\n * @returns The OnPageEngine instance.\n * @throws If the engine is not an OnPageEngine.\n */\nexport function useAndAssertOnPageEngine() {\n\tconst engine = useBaseEngine()\n\tassert(isOnPageEngine(engine), \"Expected OnPageEngine\")\n\treturn engine\n}\n\nexport function isOnPageEngine(engine: BaseEngine): engine is OnPageEngine {\n\treturn engine.name === \"OnPageEngine\"\n}\n", "import type { EngineStores } from \"document/EngineStores.ts\"\nimport type { VekterEngineScheduler } from \"document/VekterEngineScheduler.ts\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport type { LoadingStore } from \"document/stores/LoadingStore.ts\"\nimport { isVekterEngine } from \"document/useVekterEngine.ts\"\nimport { isOnPageEngine } from \"editorbar/engine/useOnPageEngine.ts\"\nimport { isShallowEqual } from \"utils/isShallowEqual.ts\"\nimport {\n\tExtendedPermissions,\n\ttype PermissionState,\n\ttype PermissionStateDependencies,\n\tgetACLPermissions,\n\tgetPermissionState,\n\tgetPermissionStateDependencies,\n} from \"./projectPermissions.ts\"\n\nexport interface PermissionStateWithIsReady extends PermissionState {\n\t/** `LoadingStore.isReady` */\n\tisReady: boolean\n}\n\ntype PermissionStateWithIsReadyDependencies = [LoadingStore, ...PermissionStateDependencies]\n\nexport const getPermissionStateWithIsReadyDependencies = (\n\tstores: EngineStores,\n): PermissionStateWithIsReadyDependencies => [stores.loadingStore, ...getPermissionStateDependencies(stores)]\n\nexport const getPermissionStateWithIsReady = ([\n\tloadingStore,\n\t...permissionStateDependencies\n]: PermissionStateWithIsReadyDependencies): PermissionStateWithIsReady => ({\n\tisReady: loadingStore.isReady,\n\t...getPermissionState(permissionStateDependencies),\n})\n\n/**\n * Given a subset of the app's state, and an optional permission to check for, returns whether the\n * UI should be view-only or not.\n *\n * It is meant to be the broadest possible check of the view-only state, for when you don't really\n * care if UI is view-only because the document is still loading, or because the network got\n * disconnected, or because the user is lacking the necessary permission.\n */\nexport function isViewOnly(state: PermissionStateWithIsReady, permissionToCheck: keyof ExtendedPermissions): boolean {\n\tif (!state.isReady || state.userIsViewer) return true\n\tif (state.isViewingBranchFromOtherUser) return true\n\t// if the user is sharing account, block anything but invitation ability\n\tif (state.userIsAccountSharing && permissionToCheck !== \"canInviteCollaborators\") return true\n\tconst aclPermissions = getACLPermissions(state)\n\tconst extendedPermissions = new ExtendedPermissions(aclPermissions)\n\tconst hasPermission = extendedPermissions[permissionToCheck]\n\treturn !hasPermission\n}\n\n/** A convenience wrapper around {@link isViewOnly} that gets all the necessary state for you. */\nexport function getIsViewOnly(engine: BaseEngine, permissionToCheck: keyof ExtendedPermissions): boolean {\n\tif (isVekterEngine(engine)) {\n\t\tif (engine.stores.chromeStore.isDetachedEditableMode) return !engine.stores.loadingStore.isReady\n\t\treturn isViewOnly(\n\t\t\tgetPermissionStateWithIsReady(getPermissionStateWithIsReadyDependencies(engine.stores)),\n\t\t\tpermissionToCheck,\n\t\t)\n\t}\n\n\tif (isOnPageEngine(engine)) {\n\t\t// TODO: Implement view-only in `OnPageEngine`.\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n/**\n * Subscribe to changes in the {@link PermissionStateWithIsReady | permission state with `isReady`}.\n *\n * Use `subscribeToPermissionStateChanges` if you don't need `isReady`.\n */\nexport function subscribeToPermissionStateWithIsReadyChanges(\n\tstores: EngineStores,\n\tscheduler: VekterEngineScheduler,\n\tobserver: (state: PermissionStateWithIsReady) => void,\n\t{ signal }: { signal: AbortSignal },\n): void {\n\tconst dependencies = getPermissionStateWithIsReadyDependencies(stores)\n\tlet currentState = getPermissionStateWithIsReady(dependencies)\n\n\tconst token = scheduler.changes.observe(...dependencies, () => {\n\t\tconst nextState = getPermissionStateWithIsReady(dependencies)\n\t\tif (isShallowEqual(currentState, nextState)) return\n\t\tcurrentState = nextState\n\t\tobserver(nextState)\n\t})\n\n\tsignal.addEventListener(\n\t\t\"abort\",\n\t\t() => {\n\t\t\tscheduler.changes.removeObserver(token)\n\t\t},\n\t\t{ once: true },\n\t)\n}\n", "import type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport type { WithPath } from \"library/render/traits/Path.ts\"\nimport { withPath as withPathTraits } from \"library/render/traits/Path.ts\"\n\nexport function withPath(node: CanvasNode): node is CanvasNode & WithPath {\n\treturn withPathTraits(node)\n}\n", "export const elementsEqual = <T>(a: T[], b: T[]) => {\n\tif (a === b) return true\n\tif (a.length !== b.length) return false\n\n\tconst set = new Set(a)\n\tfor (const e of b) {\n\t\tif (!set.has(e)) return false\n\t}\n\treturn true\n}\n\nexport const intersection = <T>(a: T[], b: T[], equals?: (a: T, b: T) => boolean) => {\n\tconst result: T[] = []\n\tfor (const itemA of a) {\n\t\tconst index = findIndex(b, itemA, equals)\n\t\tif (index !== -1) {\n\t\t\tresult.push(itemA)\n\t\t}\n\t}\n\treturn result\n}\n\nexport const union = <T>(a: T[], b: T[], equals?: (a: T, b: T) => boolean) => {\n\tif (!equals) {\n\t\treturn Array.from(new Set([...a, ...b]))\n\t}\n\tconst result: T[] = [...a]\n\tfor (const itemB of b) {\n\t\tconst index = findIndex(result, itemB, equals)\n\t\tif (index === -1) {\n\t\t\tresult.push(itemB)\n\t\t}\n\t}\n\treturn result\n}\n\nexport const without = <T>(a: T[], b: T[], equals?: (a: T, b: T) => boolean) => {\n\treturn a.filter(itemA => {\n\t\tconst index = findIndex(b, itemA, equals)\n\t\treturn index === -1\n\t})\n}\n\nfunction findIndex<T>(array: T[], item: T, equals?: (a: T, b: T) => boolean): number {\n\tif (equals) {\n\t\treturn array.findIndex(arrayItem => equals(arrayItem, item))\n\t} else {\n\t\treturn array.indexOf(item)\n\t}\n}\n", "import type { EngineChangeSignal } from \"document/EngineChanges.ts\"\nimport { EngineChange } from \"document/EngineChanges.ts\"\nimport { union } from \"document/components/utils/list.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { CanvasPanelTab } from \"document/utils/ActiveEditorType.ts\"\nimport type { WithPath } from \"library/render/traits/Path.ts\"\nimport type { Line } from \"library/render/types/Line.ts\"\nimport type { Point } from \"library/render/types/Point.ts\"\nimport type { ChromeStore } from \"./ChromeStore.ts\"\n\nexport enum SegmentHandle {\n\tIn,\n\tOut,\n}\n\nexport enum PathSelectionType {\n\tSegments,\n\tCurves,\n}\n\nexport interface SegmentHandleSelector {\n\tid: NodeID\n\thandle: SegmentHandle\n\tindex: number\n}\n\nexport enum PointRounding {\n\tFull = 1,\n\tHalf = 0.5,\n}\n\nexport interface PathSegmentSelector {\n\tid: NodeID\n\tindex: number\n}\n\nexport interface ClosestCurve {\n\tid: NodeID\n\tsegmentIndex: number\n\tdistance: number\n\tprojectedTime: number\n\tprojectedPoint: Point\n\tmidPoint: Point\n\tmidPointInRange: boolean\n}\n\nexport interface PathSelectionState {\n\tsegmentSelection: PathSegmentSelector[]\n\tselectionType: PathSelectionType\n\tsegmentHandle: SegmentHandleSelector | null\n\tsegmentHovered: PathSegmentSelector | null\n\tclosestCurve: ClosestCurve | null\n\tpointRounding: PointRounding\n\tsnapConstraint: Line | null\n}\n\nfunction validateSelection(tree: CanvasTree, state: PathSelectionState) {\n\tconst newSelection: PathSegmentSelector[] = []\n\n\tfor (const selector of state.segmentSelection) {\n\t\tconst node = tree.getNode<CanvasNode & WithPath>(selector.id)\n\t\tif (!node || selector.index >= node.pathSegments.length) {\n\t\t\tcontinue\n\t\t}\n\t\tnewSelection.push(selector)\n\t}\n\n\tlet newSegmentHandle = state.segmentHandle\n\tif (newSegmentHandle) {\n\t\tconst node = tree.getNode<CanvasNode & WithPath>(newSegmentHandle.id)\n\t\tif (!node || newSegmentHandle.index >= node.pathSegments.length) {\n\t\t\tnewSegmentHandle = null\n\t\t}\n\t}\n\n\t// Clear stale closestCurve when its node was removed or shrunk so consumers\n\t// (PathDefault.split, PathCurveBend.start, PathSegmentHandles, PathCurves) never\n\t// index past the end. Otherwise undo/agent edits that shrink the path while the\n\t// mouse hasn't moved can leave segmentIndex out of range. Open paths produce one\n\t// fewer curve than segments (no wrap-around), so the max valid index differs.\n\tlet newClosestCurve = state.closestCurve\n\tif (newClosestCurve) {\n\t\tconst node = tree.getNode<CanvasNode & WithPath>(newClosestCurve.id)\n\t\tconst curveCount = node ? (node.pathClosed ? node.pathSegments.length : node.pathSegments.length - 1) : 0\n\t\tif (!node || newClosestCurve.segmentIndex >= curveCount) {\n\t\t\tnewClosestCurve = null\n\t\t}\n\t}\n\n\treturn { ...state, segmentSelection: newSelection, segmentHandle: newSegmentHandle, closestCurve: newClosestCurve }\n}\n\nexport class PathSelectionStore {\n\tstate: PathSelectionState = {\n\t\tsegmentSelection: [],\n\t\tselectionType: PathSelectionType.Segments,\n\t\tsegmentHandle: null,\n\t\tsegmentHovered: null,\n\t\tclosestCurve: null,\n\t\tpointRounding: PointRounding.Half,\n\t\tsnapConstraint: null,\n\t}\n\n\tconstructor(\n\t\tprivate addChanges: EngineChangeSignal,\n\t\tprivate chromeStore: ChromeStore,\n\t) {}\n\n\tvalidateSegmentSelection(tree: CanvasTree) {\n\t\tthis.state = validateSelection(tree, this.state)\n\t\tthis.addChanges(EngineChange.PathSelection)\n\t}\n\n\tsetSegmentSelection(segmentSelection: PathSegmentSelector[], selectionType: PathSelectionType) {\n\t\tthis.state = { ...this.state, segmentSelection, selectionType }\n\t\tthis.addChanges(EngineChange.PathSelection)\n\n\t\tthis.chromeStore.activeRightPanelTab = CanvasPanelTab.Properties\n\t}\n\n\ttoggleSegmentSelection(segmentSelection: PathSegmentSelector[], selectionType: PathSelectionType) {\n\t\tif (this.state.selectionType !== selectionType) {\n\t\t\tthis.state = { ...this.state, segmentSelection, selectionType }\n\t\t}\n\t\tconst newAndUnique = segmentSelection.filter(segment => {\n\t\t\treturn (\n\t\t\t\tthis.state.segmentSelection.find(sel => {\n\t\t\t\t\treturn segment.id === sel.id && segment.index === sel.index\n\t\t\t\t}) === undefined\n\t\t\t)\n\t\t})\n\t\tconst previousSelectionFiltered = this.state.segmentSelection.filter(sel => {\n\t\t\treturn (\n\t\t\t\tsegmentSelection.find(segment => {\n\t\t\t\t\treturn segment.id === sel.id && segment.index === sel.index\n\t\t\t\t}) === undefined\n\t\t\t)\n\t\t})\n\t\tthis.state = { ...this.state, segmentSelection: union(newAndUnique, previousSelectionFiltered) }\n\t\tthis.addChanges(EngineChange.PathSelection)\n\n\t\tthis.chromeStore.activeRightPanelTab = CanvasPanelTab.Properties\n\t}\n\n\tsetSegmentHandle(segmentHandle: SegmentHandleSelector | null) {\n\t\tthis.state = { ...this.state, segmentHandle }\n\t\tthis.addChanges(EngineChange.PathSelection)\n\t}\n\n\tsetHoveredSegment(segmentHovered: PathSegmentSelector | null) {\n\t\tthis.state = { ...this.state, segmentHovered }\n\t\tthis.addChanges(EngineChange.PathSelection)\n\t}\n\n\tsetClosestCurve(closestCurve: ClosestCurve | null) {\n\t\tthis.state = { ...this.state, closestCurve }\n\t\tthis.addChanges(EngineChange.PathSelection)\n\t}\n\n\tsetPathPointRounding(pointRounding: PointRounding) {\n\t\tthis.state = { ...this.state, pointRounding }\n\t\tthis.addChanges(EngineChange.PathSelection)\n\t}\n\n\tsetPathConstraint(snapConstraint: Line | null) {\n\t\tthis.state = { ...this.state, snapConstraint }\n\t\tthis.addChanges(EngineChange.PathSelection)\n\t}\n}\n", "import { assert, List } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type {\n\tCanvasNode,\n\tCanvasTree,\n\tNodeID,\n\tRectangleShapeNode,\n\tVectorNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { BooleanShapeNode, NullID, PathNode } from \"document/models/CanvasTree/index.ts\"\nimport { randomID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport {\n\tisBooleanShapeNode,\n\tisShapeContainerNode,\n\tisShapeGroupNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { WithBoxShadow } from \"document/models/CanvasTree/traits/WithBoxShadow.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport type { WithFill, WithOptionalFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport type { WithOpacity } from \"document/models/CanvasTree/traits/WithOpacity.ts\"\nimport { withPath } from \"document/models/CanvasTree/traits/WithPath.ts\"\nimport { PathBooleanType } from \"document/models/CanvasTree/traits/WithPathBoolean.ts\"\nimport type { WithPosition } from \"document/models/CanvasTree/traits/WithPosition.ts\"\nimport { withRotation } from \"document/models/CanvasTree/traits/WithRotation.ts\"\nimport { withShape } from \"document/models/CanvasTree/traits/WithShape.ts\"\nimport type { WithSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport type { WithStroke } from \"document/models/CanvasTree/traits/WithStroke.ts\"\nimport { BasicShape } from \"document/models/CanvasTree/traits/utils/basicShape/index.ts\"\nimport { nodeEffects } from \"document/models/CanvasTree/traits/utils/effects.ts\"\nimport { convertPathToParent, convertPointToParent } from \"document/models/CanvasTree/utils/convertPathToParent.ts\"\nimport { convertPointFromNodeToDescendant } from \"document/models/CanvasTree/utils/geometry.ts\"\nimport { reverseSegment } from \"document/models/CanvasTree/utils/reverseSegment.ts\"\nimport { Matrix } from \"document/models/Matrix.ts\"\nimport { Path } from \"document/models/Path.ts\"\nimport type {\n\tClosestCurve,\n\tPathSegmentSelector,\n\tPointRounding,\n\tSegmentHandleSelector,\n} from \"document/stores/PathSelectionStore.ts\"\nimport { PathSelectionType, SegmentHandle } from \"document/stores/PathSelectionStore.ts\"\nimport { Tools } from \"document/stores/ToolEnum.ts\"\nimport { Map as ImmutableMap } from \"immutable\"\nimport type { WithPath, WithPaths } from \"library/render/traits/Path.ts\"\nimport { isStraightCurve } from \"library/render/traits/Path.ts\"\nimport type { WithShape } from \"library/render/traits/Shape.ts\"\nimport { Line } from \"library/render/types/Line.ts\"\nimport { PathSegment } from \"library/render/types/PathSegment.ts\"\nimport { Point } from \"library/render/types/Point.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\nimport { getIsViewOnly } from \"web/pages/project/permissions/isViewOnly.ts\"\nexport { convertPointToParent, reverseSegment }\n\ntype StyledVectorNode = VectorNode &\n\tWithShape &\n\tWithPosition &\n\tWithSize &\n\tWithStroke &\n\tWithFill &\n\tWithOptionalFill &\n\tWithBoxShadow\n\nexport function flattenEnabled(engine: VekterEngine, nodes: CanvasNode[]): nodes is CanvasNode[] & StyledVectorNode[] {\n\tif (getIsViewOnly(engine, \"canDesign\") || nodes.length === 0) {\n\t\treturn false\n\t}\n\n\treturn (\n\t\tnodes.find(node => {\n\t\t\treturn !(!withPath(node) && withShape(node) && !isShapeGroupNode(node) && !node.originalid)\n\t\t}) === undefined\n\t)\n}\n\nexport function flattenShapes(\n\tengine: VekterEngine,\n\tnodes: StyledVectorNode[],\n\tenterEditMode?: boolean,\n\tignoreUndo?: boolean,\n) {\n\tconst ids = nodes.map(node => {\n\t\treturn flattenShape(engine, node, enterEditMode, ignoreUndo)[0]\n\t})\n\tengine.stores.selectionStore.set(ids)\n}\n\nexport function flattenShape(\n\tengine: VekterEngine,\n\tnode: StyledVectorNode,\n\tenterEditMode?: boolean,\n\tignoreUndo?: boolean,\n): [NodeID, WithPaths] {\n\tconst tree = engine.tree\n\tlet currentPaths: WithPaths\n\n\tif (BasicShape.isBasicShape(node)) {\n\t\tcurrentPaths = BasicShape.createPath(node)\n\t} else {\n\t\tcurrentPaths = node.calculatedPaths()\n\t}\n\n\tconst paths = convertPathToParent(node, currentPaths)\n\tconst canvasPath = convertPathToCanvas(tree, node, currentPaths)\n\n\t// TODO: copy over other properties like name and target name\n\n\tconst id = randomID()\n\tconst boundingBox = Path.boundingBox(paths)\n\tconst style = copyShapeStyle(node)\n\tconst effects = nodeEffects(node)\n\n\tif (style.fillType === \"linear-gradient\" && style.fillLinearGradient) {\n\t\tstyle.fillType = \"linear-gradient\"\n\t\tconst rotation = isNumber(node.rotation) ? node.rotation : 0\n\t\tstyle.fillLinearGradient = style.fillLinearGradient.updated({\n\t\t\tangle: style.fillLinearGradient.angle + rotation,\n\t\t})\n\t}\n\n\tif (paths.length === 1) {\n\t\tconst firstPath = paths[0]\n\t\tassert(firstPath !== undefined, \"Expected first path after length === 1 check\")\n\t\tconst newPath = Path.offset(firstPath, Point.reverse(boundingBox))\n\t\tengine.createPath(node.parentid, { id, ...newPath, ...boundingBox, ...style, ...effects })\n\t} else {\n\t\tconst nodesToAdd: CanvasNode[] = []\n\n\t\tconst booleanNode = new BooleanShapeNode({\n\t\t\tid,\n\t\t\tparentid: node.parentid,\n\t\t\tpathBoolean: PathBooleanType.Join,\n\t\t\t...boundingBox,\n\t\t\t...style,\n\t\t\t...effects,\n\t\t})\n\t\tnodesToAdd.push(booleanNode)\n\n\t\tfor (const path of paths) {\n\t\t\tconst childBoundingBox = Path.boundingBox(path)\n\t\t\tconst frame = { ...childBoundingBox, ...Point.subtract(childBoundingBox, boundingBox) }\n\t\t\tconst newPath = Path.offset(path, Point.reverse(childBoundingBox))\n\n\t\t\tconst pathNode = new PathNode({ parentid: id, ...frame, ...newPath, ...style })\n\t\t\tnodesToAdd.push(pathNode)\n\t\t}\n\t\tengine.tree.insertNodes(nodesToAdd)\n\t}\n\n\t// Make sure the position in the list does not change\n\t// NOTE: This should work with TreeAction.replace, but doesn\u2019t\n\tconst parent = tree.getParent(node.id)\n\tif (parent !== null && withChildren(parent)) {\n\t\tconst index = parent.children.indexOf(node)\n\t\tengine.moveNode(id, parent.id, index)\n\t}\n\n\tengine.deleteNode(node.id)\n\n\tif (!ignoreUndo) {\n\t\tengine.stores.selectionStore.set(id)\n\t}\n\n\tif (enterEditMode === true) {\n\t\tengine.setTool(Tools.Path)\n\t}\n\n\treturn [id, canvasPath]\n}\n\nexport function groupPathSegmentSelectors(selectors: PathSegmentSelector[]) {\n\tconst result: { [key: string]: number[] } = {}\n\n\tselectors.forEach(selector => {\n\t\tconst indices = result[selector.id] ?? []\n\t\tindices.push(selector.index)\n\t\tresult[selector.id] = indices\n\t})\n\n\treturn result\n}\n\nexport function roundedPoint(point: Point, pointRounding: PointRounding) {\n\t// We used to allow for different rounding settings, now we only support half points\n\tconst roundingFactor = 1 / pointRounding\n\treturn {\n\t\tx: Math.round(point.x * roundingFactor) / roundingFactor,\n\t\ty: Math.round(point.y * roundingFactor) / roundingFactor,\n\t}\n}\n\nexport function segmentHandlePoint(tree: CanvasTree, handleSelector: SegmentHandleSelector): Point | null {\n\tconst node = tree.getNode(handleSelector.id) as PathNode\n\tif (!node?.pathSegments) return null\n\tconst segment = node.pathSegments[handleSelector.index]\n\tif (!segment) return null\n\tconst pointInLayer =\n\t\thandleSelector.handle === SegmentHandle.In\n\t\t\t? PathSegment.calculatedHandleIn(segment)\n\t\t\t: PathSegment.calculatedHandleOut(segment)\n\treturn tree.convertPointToCanvas(node, pointInLayer)\n}\n\nfunction oppositeHandle(segment: PathSegment, handleSelector: SegmentHandleSelector) {\n\treturn handleSelector.handle === SegmentHandle.In\n\t\t? { x: segment.handleOutX, y: segment.handleOutY }\n\t\t: { x: segment.handleInX, y: segment.handleInY }\n}\n\nexport function handleUpdate(\n\ttree: CanvasTree,\n\thandleSelector: SegmentHandleSelector,\n\tpoint: Point,\n\toriginalSegment?: PathSegment,\n\talt?: boolean,\n) {\n\tconst node = tree.getNode(handleSelector.id) as PathNode\n\tconst segmentAnchor = node.pathSegments[handleSelector.index]\n\tassert(segmentAnchor !== undefined, \"Expected segment at handleSelector.index\")\n\tpoint = tree.convertPointToNode(node, point)\n\tpoint = Point.subtract(point, segmentAnchor)\n\n\treturn List.update(node.pathSegments, handleSelector.index, (segment: PathSegment) => {\n\t\tlet oppositePoint = oppositeHandle(segment, handleSelector)\n\t\tlet isStraight = segment.handleMirroring === \"straight\"\n\t\tlet handleMirroring = segment.handleMirroring\n\n\t\tif (originalSegment) {\n\t\t\toppositePoint = oppositeHandle(originalSegment, handleSelector)\n\t\t\tisStraight = originalSegment.handleMirroring === \"straight\"\n\t\t\thandleMirroring = originalSegment.handleMirroring\n\t\t}\n\n\t\tif (isStraight) {\n\t\t\thandleMirroring = \"symmetric\"\n\t\t}\n\n\t\tif (originalSegment && alt) {\n\t\t\tif (handleMirroring === \"disconnected\" || handleMirroring === \"asymmetric\") {\n\t\t\t\thandleMirroring = \"symmetric\"\n\t\t\t} else {\n\t\t\t\thandleMirroring = \"disconnected\"\n\t\t\t}\n\t\t}\n\n\t\tif (handleMirroring === \"symmetric\") {\n\t\t\toppositePoint = Point.reverse(point)\n\t\t}\n\n\t\tconst isHandleIn = handleSelector.handle === SegmentHandle.In\n\t\tconst handleInX = isHandleIn ? point.x : oppositePoint.x\n\t\tconst handleInY = isHandleIn ? point.y : oppositePoint.y\n\t\tconst handleOutX = isHandleIn ? oppositePoint.x : point.x\n\t\tconst handleOutY = isHandleIn ? oppositePoint.y : point.y\n\n\t\treturn segment.merge({ handleOutX, handleOutY, handleInX, handleInY, handleMirroring })\n\t})\n}\n\nexport function collectDescendantShapesAndFlattenRotations(\n\tengine: VekterEngine,\n\tnode: CanvasNode,\n\tconvertAllToPaths = false,\n\tcurrentSelection?: NodeID[],\n) {\n\tconst tree = engine.tree\n\tlet descendantPaths = ImmutableMap<NodeID, WithPath>()\n\tlet descendantBasicShapes = ImmutableMap<NodeID, null | Point[]>()\n\n\tif (!withShape(node) && !isShapeContainerNode(node)) {\n\t\treturn { descendantPaths, descendantBasicShapes }\n\t}\n\n\tconst descendantPathCollection: { [id: string]: WithPath } = {}\n\tcollectDescendantPaths(tree, node, descendantPathCollection)\n\tconst descendantPathID = Object.keys(descendantPathCollection)\n\tfor (let i = 0, il = descendantPathID.length; i < il; i++) {\n\t\tconst id = descendantPathID[i]\n\t\tassert(id !== undefined, \"Expected id at index within loop bounds\")\n\t\tconst path = descendantPathCollection[id]\n\t\tassert(path !== undefined, \"Expected path for id from Object.keys\")\n\t\tdescendantPaths = descendantPaths.set(id, path)\n\t}\n\n\tconst descendantBasicShapeCollection: { [id: string]: null | Point[] } = {}\n\tcollectDescendantBasicShapes(tree, node, descendantBasicShapeCollection, convertAllToPaths)\n\tconst descendantBasicShapeID = Object.keys(descendantBasicShapeCollection)\n\tfor (let i = 0, il = descendantBasicShapeID.length; i < il; i++) {\n\t\tconst id = descendantBasicShapeID[i]\n\t\tassert(id !== undefined, \"Expected id at index within loop bounds\")\n\t\tconst points = descendantBasicShapeCollection[id]\n\t\tassert(points !== undefined, \"Expected points for id from Object.keys\")\n\t\tdescendantBasicShapes = descendantBasicShapes.set(id, points)\n\t}\n\n\t// Flatten rotated basic shapes\n\n\tdescendantBasicShapes.forEach((value: Point[] | null, id: NodeID) => {\n\t\tif (value !== null) return\n\n\t\tconst shape = tree.getNode(id) as RectangleShapeNode | null\n\t\tif (!shape) return\n\t\tif (!flattenEnabled(engine, [shape])) return\n\n\t\tconst [newId, pathSegments] = flattenShape(engine, shape, false, true)\n\t\tconst pathSegment = pathSegments[0]\n\t\tassert(pathSegment !== undefined, \"Expected pathSegment from flattenShape\")\n\t\tdescendantPaths = descendantPaths.set(newId, pathSegment)\n\n\t\tif (currentSelection?.includes(id)) {\n\t\t\tengine.stores.selectionStore.toggle(newId)\n\t\t}\n\t})\n\n\treturn { descendantPaths, descendantBasicShapes }\n}\n\nexport function collectShapeContainerDescendantShapesAndFlattenRotations(engine: VekterEngine, node: CanvasNode) {\n\tconst tree = engine.tree\n\tlet shapeContainerDescendantPaths = ImmutableMap<NodeID, WithPath>()\n\tlet shapeContainerDescendantBasicShapes = ImmutableMap<NodeID, null | Point[]>()\n\n\tif (!isShapeContainerNode(node)) {\n\t\treturn { shapeContainerDescendantPaths, shapeContainerDescendantBasicShapes }\n\t}\n\n\tconst descendantPathCollection: { [id: string]: WithPath } = {}\n\tcollectDescendantPaths(tree, node, descendantPathCollection, node)\n\tconst descendantPathID = Object.keys(descendantPathCollection)\n\tfor (let i = 0, il = descendantPathID.length; i < il; i++) {\n\t\tconst id = descendantPathID[i]\n\t\tassert(id !== undefined, \"Expected id at index within loop bounds\")\n\t\tconst path = descendantPathCollection[id]\n\t\tassert(path !== undefined, \"Expected path for id from Object.keys\")\n\t\tshapeContainerDescendantPaths = shapeContainerDescendantPaths.set(id, path)\n\t}\n\n\tconst descendantBasicShapeCollection: { [id: string]: null | Point[] } = {}\n\tcollectDescendantBasicShapes(tree, node, descendantBasicShapeCollection, false, false, node)\n\tconst descendantBasicShapeID = Object.keys(descendantBasicShapeCollection)\n\tfor (let i = 0, il = descendantBasicShapeID.length; i < il; i++) {\n\t\tconst id = descendantBasicShapeID[i]\n\t\tassert(id !== undefined, \"Expected id at index within loop bounds\")\n\t\tconst points = descendantBasicShapeCollection[id]\n\t\tassert(points !== undefined, \"Expected points for id from Object.keys\")\n\t\tshapeContainerDescendantBasicShapes = shapeContainerDescendantBasicShapes.set(id, points)\n\t}\n\n\t// Flatten rotated basic shapes\n\n\tshapeContainerDescendantBasicShapes.forEach((value: Point[] | null, id: NodeID) => {\n\t\tif (value !== null) return\n\n\t\tconst shape = tree.getNode(id) as RectangleShapeNode | null\n\t\tif (!shape) return\n\t\tif (!flattenEnabled(engine, [shape])) return\n\n\t\tconst [newId, pathSegments] = flattenShape(engine, shape, false, true)\n\n\t\tconst pathSegment = pathSegments[0]\n\t\tassert(pathSegment !== undefined, \"Expected pathSegment from flattenShape\")\n\t\tconst convertedPathSegmentsArray = convertPathToNode(tree, node, [pathSegment])\n\t\tconst convertedPathSegments = convertedPathSegmentsArray[0]\n\t\tassert(convertedPathSegments !== undefined, \"Expected converted path segments at index 0\")\n\n\t\tshapeContainerDescendantPaths = shapeContainerDescendantPaths.set(newId, {\n\t\t\tpathSegments: convertedPathSegments,\n\t\t\tpathClosed: true,\n\t\t})\n\t})\n\n\treturn { shapeContainerDescendantPaths, shapeContainerDescendantBasicShapes }\n}\n\nfunction collectDescendantPaths(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tresult: { [id: string]: WithPath },\n\tupperBounds?: CanvasNode,\n) {\n\tif (isShapeGroupNode(node) || isBooleanShapeNode(node) || isShapeContainerNode(node)) {\n\t\tfor (const child of node.children) {\n\t\t\tif (withShape(child)) {\n\t\t\t\tcollectDescendantPaths(tree, child, result, upperBounds)\n\t\t\t}\n\t\t}\n\t} else if (withPath(node)) {\n\t\tconst convertedPaths = convertPathToCanvas(tree, node, node)\n\t\tconst firstPath = convertedPaths[0]\n\t\tassert(firstPath !== undefined, \"Expected path from convertPathToCanvas\")\n\t\tlet projectedPath = firstPath.pathSegments\n\n\t\tif (upperBounds) {\n\t\t\tconst convertedToNode = convertPathToNode(tree, upperBounds, [\n\t\t\t\t{\n\t\t\t\t\tpathSegments: projectedPath,\n\t\t\t\t\tpathClosed: node.pathClosed,\n\t\t\t\t},\n\t\t\t])\n\t\t\tconst firstConverted = convertedToNode[0]\n\t\t\tassert(firstConverted !== undefined, \"Expected converted path at index 0\")\n\t\t\tprojectedPath = firstConverted\n\t\t}\n\n\t\tresult[node.id] = { pathSegments: projectedPath, pathClosed: node.pathClosed }\n\t}\n}\n\nfunction collectDescendantBasicShapes(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tresult: { [id: string]: Point[] | null },\n\trotated: boolean = false,\n\tconvertAllToPaths = false,\n\tupperBounds?: CanvasNode,\n) {\n\tif (isShapeGroupNode(node) || isBooleanShapeNode(node) || isShapeContainerNode(node)) {\n\t\tfor (const child of node.children) {\n\t\t\tconst rotatedChild = withRotation(child) && isNumber(child.rotation) && child.rotation % 90 !== 0\n\t\t\tconst isRotated = rotatedChild || rotated\n\t\t\tif (withShape(child)) {\n\t\t\t\tcollectDescendantBasicShapes(tree, child, result, isRotated, convertAllToPaths, upperBounds)\n\t\t\t}\n\t\t}\n\t} else if (!withPath(node) && withShape(node)) {\n\t\tif (rotated || convertAllToPaths) {\n\t\t\tresult[node.id] = null\n\t\t} else {\n\t\t\tconst corners = Rect.pointsAtOrigin(tree.getRect(node))\n\t\t\tresult[node.id] = corners.map(corner => {\n\t\t\t\tconst point = tree.convertPointToCanvas(node, corner)\n\t\t\t\tif (!upperBounds) return point\n\t\t\t\treturn tree.convertPointToNode(upperBounds, point, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nexport function convertPathToCanvas(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\twithPaths: WithPaths | WithPath,\n\tzoom = 1,\n): WithPaths {\n\tlet paths: WithPath[] = []\n\tif (Array.isArray(withPaths)) {\n\t\tpaths = withPaths\n\t} else {\n\t\tpaths = [withPaths]\n\t}\n\n\treturn paths.map(({ pathSegments, pathClosed }) => {\n\t\tconst segments = pathSegments.map((segment: PathSegment) => {\n\t\t\treturn convertSegmentToCanvas(tree, node, segment, zoom, undefined)\n\t\t})\n\t\treturn { pathSegments: segments, pathClosed }\n\t})\n}\n\nexport function convertSegmentToCanvas(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tsegment: PathSegment,\n\tzoom = 1,\n\tframeOverride?: Rect,\n) {\n\tconst anchor = Point.multiply(tree.convertPointToCanvas(node, segment, true, frameOverride), zoom)\n\tconst handleIn = Point.multiply(\n\t\ttree.convertPointToCanvas(node, PathSegment.calculatedHandleIn(segment), true, frameOverride),\n\t\tzoom,\n\t)\n\tconst handleOut = Point.multiply(\n\t\ttree.convertPointToCanvas(node, PathSegment.calculatedHandleOut(segment), true, frameOverride),\n\t\tzoom,\n\t)\n\tconst localHandleIn = Point.subtract(handleIn, anchor)\n\tconst localHandleOut = Point.subtract(handleOut, anchor)\n\n\treturn segment.merge({\n\t\t...anchor,\n\t\thandleOutX: localHandleOut.x,\n\t\thandleOutY: localHandleOut.y,\n\t\thandleInX: localHandleIn.x,\n\t\thandleInY: localHandleIn.y,\n\t})\n}\n\nexport function convertPathToNode(tree: CanvasTree, node: CanvasNode, withPaths: WithPaths) {\n\treturn withPaths.map(({ pathSegments }) => {\n\t\treturn pathSegments.map((segment: PathSegment) => {\n\t\t\tconst anchor = tree.convertPointToNode(node, segment)\n\t\t\tconst handleIn = tree.convertPointToNode(node, PathSegment.calculatedHandleIn(segment))\n\t\t\tconst handleOut = tree.convertPointToNode(node, PathSegment.calculatedHandleOut(segment))\n\t\t\tconst localHandleIn = Point.subtract(handleIn, anchor)\n\t\t\tconst localHandleOut = Point.subtract(handleOut, anchor)\n\n\t\t\treturn segment.merge({\n\t\t\t\t...anchor,\n\t\t\t\thandleOutX: localHandleOut.x,\n\t\t\t\thandleOutY: localHandleOut.y,\n\t\t\t\thandleInX: localHandleIn.x,\n\t\t\t\thandleInY: localHandleIn.y,\n\t\t\t})\n\t\t})\n\t})\n}\n\nexport function convertPathFromNodeToDescendant(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tdescendant: CanvasNode,\n\twithPaths: WithPaths,\n) {\n\treturn withPaths.map(({ pathSegments }) => {\n\t\treturn pathSegments.map((segment: PathSegment) => {\n\t\t\tconst anchorPoint = { x: segment.x, y: segment.y }\n\t\t\tconst anchor = convertPointFromNodeToDescendant(tree, node, descendant, anchorPoint)\n\t\t\tconst handleIn = convertPointFromNodeToDescendant(tree, node, descendant, PathSegment.calculatedHandleIn(segment))\n\t\t\tconst handleOut = convertPointFromNodeToDescendant(\n\t\t\t\ttree,\n\t\t\t\tnode,\n\t\t\t\tdescendant,\n\t\t\t\tPathSegment.calculatedHandleOut(segment),\n\t\t\t)\n\t\t\tconst localHandleIn = Point.subtract(handleIn, anchor)\n\t\t\tconst localHandleOut = Point.subtract(handleOut, anchor)\n\n\t\t\treturn segment.merge({\n\t\t\t\t...anchor,\n\t\t\t\thandleOutX: localHandleOut.x,\n\t\t\t\thandleOutY: localHandleOut.y,\n\t\t\t\thandleInX: localHandleIn.x,\n\t\t\t\thandleInY: localHandleIn.y,\n\t\t\t})\n\t\t})\n\t})\n}\n\nexport function convertPath(matrix: DOMMatrixReadOnly, withPaths: WithPaths): PathSegment[][] {\n\treturn withPaths.map(({ pathSegments }) => {\n\t\treturn pathSegments.map((segment: PathSegment) => {\n\t\t\tconst anchor = Matrix.convertPoint(matrix, segment)\n\t\t\tconst handleIn = Matrix.convertPoint(matrix, PathSegment.calculatedHandleIn(segment))\n\t\t\tconst handleOut = Matrix.convertPoint(matrix, PathSegment.calculatedHandleOut(segment))\n\t\t\tconst localHandleIn = Point.subtract(handleIn, anchor)\n\t\t\tconst localHandleOut = Point.subtract(handleOut, anchor)\n\n\t\t\treturn segment.merge({\n\t\t\t\t...anchor,\n\t\t\t\thandleOutX: localHandleOut.x,\n\t\t\t\thandleOutY: localHandleOut.y,\n\t\t\t\thandleInX: localHandleIn.x,\n\t\t\t\thandleInY: localHandleIn.y,\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunction updateNodeWithPathAndBoundingBox(engine: VekterEngine, node: PathNode, update: Partial<WithPath>) {\n\tconst normalizedUpdate = node.updateForPath(update)\n\tengine.tree.current(node)?.set(normalizedUpdate)\n}\n\nexport function cloneNodeAndUpdatePath(\n\ttree: CanvasTree,\n\tengine: VekterEngine,\n\tnode: PathNode,\n\tupdate: Partial<WithPath>,\n\tnewId: NodeID,\n) {\n\tconst parent = tree.getParent(node.id)\n\tconst normalizedUpdate = node.updateForPath(update) as Partial<PathNode>\n\tengine.createPath(parent ? parent.id : NullID, {\n\t\t...normalizedUpdate,\n\t\tid: newId,\n\t\trotation: node.rotation,\n\t\t...copyShapeStyle(node),\n\t})\n}\n\nexport function generateSegmentSelection(\n\ttree: CanvasTree,\n\tsegmentSelection: PathSegmentSelector[],\n\tselectionType: PathSelectionType,\n) {\n\tif (selectionType === PathSelectionType.Segments) {\n\t\treturn segmentSelection\n\t}\n\tconst result: PathSegmentSelector[] = []\n\tconst grouped = groupPathSegmentSelectors(segmentSelection)\n\tconst ids = Object.keys(grouped)\n\tfor (let i = 0, il = ids.length; i < il; i++) {\n\t\tconst id = ids[i]\n\t\tassert(id !== undefined, \"Expected id at index within loop bounds\")\n\t\tconst indexes: number[] = []\n\t\tconst pathNode = tree.getNode(id) as PathNode\n\t\tconst selectors = grouped[id]\n\t\tassert(selectors !== undefined, \"Expected selectors for id from grouped object\")\n\t\tconst segmentCount = pathNode.pathSegments.length\n\t\tfor (let j = 0, jl = selectors.length; j < jl; j++) {\n\t\t\tconst index = selectors[j]\n\t\t\tassert(index !== undefined, \"Expected value at index of selectors within loop bounds\")\n\t\t\tindexes.push(index)\n\t\t\tconst next = index + 1\n\t\t\tif (next === segmentCount) {\n\t\t\t\tindexes.push(0)\n\t\t\t} else {\n\t\t\t\tindexes.push(next)\n\t\t\t}\n\t\t}\n\t\tfor (let k = 0, kl = indexes.length; k < kl; k++) {\n\t\t\tconst index = indexes[k]\n\t\t\tassert(index !== undefined, \"Expected value in indexes array within loop bounds\")\n\t\t\tresult.push({ id: pathNode.id, index })\n\t\t}\n\t}\n\treturn result\n}\n\nexport function partOfSelection(selection: PathSegmentSelector[], id: NodeID, index: number) {\n\tfor (const selector of selection) {\n\t\tif (selector.id === id && selector.index === index) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nexport function joinPaths(\n\ttree: CanvasTree,\n\tengine: VekterEngine,\n\tselected: PathNode,\n\tselectedSegment: PathSegmentSelector,\n\thovering: PathNode,\n\thoveringSegment: PathSegmentSelector,\n) {\n\tconst toPathInCanvas = convertPathToCanvas(tree, hovering, hovering)\n\tconst convertedPaths = convertPathToNode(tree, selected, toPathInCanvas)\n\tconst firstConvertedPath = convertedPaths[0]\n\tassert(firstConvertedPath !== undefined, \"Expected converted path at index 0\")\n\tlet localPath = firstConvertedPath\n\tconst addFromBeggining = !Path.isLastSegment(selected.pathSegments, selected.pathClosed, selectedSegment.index)\n\tconst appendEnd = Path.isLastSegment(hovering.pathSegments, hovering.pathClosed, hoveringSegment.index)\n\tconst reverse = (!addFromBeggining && appendEnd) || (addFromBeggining && !appendEnd)\n\tif (reverse) {\n\t\tlocalPath = Path.reverse(localPath)\n\t}\n\tlet pathSegments: readonly PathSegment[]\n\tif (addFromBeggining) {\n\t\tpathSegments = List.unshift(selected.pathSegments, ...localPath)\n\t} else {\n\t\tpathSegments = List.push(selected.pathSegments, ...localPath)\n\t}\n\n\tengine.deleteNode(hovering.id)\n\tupdateNodeWithPathAndBoundingBox(engine, selected, { pathSegments })\n}\n\nexport function curveAngle(from: PathSegment, to: PathSegment, time: 0 | 1): Point {\n\tconst straight = isStraightCurve(from, to)\n\n\tif (time === 0) {\n\t\tif (straight) {\n\t\t\treturn Point.subtract(to, from)\n\t\t}\n\t\tif (from.handleOutX !== 0 || from.handleOutY !== 0) {\n\t\t\tconst handleOut = PathSegment.calculatedHandleOut(from)\n\t\t\treturn Point.subtract(handleOut, from)\n\t\t}\n\t\tconst handleIn = PathSegment.calculatedHandleIn(to)\n\t\treturn Point.subtract(handleIn, from)\n\t} else {\n\t\tif (straight) {\n\t\t\treturn Point.subtract(from, to)\n\t\t}\n\t\tif (to.handleInX !== 0 || to.handleInY !== 0) {\n\t\t\tconst handleIn = PathSegment.calculatedHandleIn(to)\n\t\t\treturn Point.subtract(handleIn, to)\n\t\t}\n\t\tconst handleOut = PathSegment.calculatedHandleOut(from)\n\t\treturn Point.subtract(handleOut, to)\n\t}\n}\n\nexport function curveDerivative(tree: CanvasTree, curve: ClosestCurve): Line | null {\n\tconst pathNode = tree.getNode(curve.id) as PathNode\n\tif (!pathNode) {\n\t\treturn null\n\t}\n\n\tconst lowSegment = pathNode.pathSegments[curve.segmentIndex]\n\tif (!lowSegment) return null\n\tconst highSegment = pathNode.pathSegments[curve.segmentIndex + 1]\n\tif (!highSegment) return null\n\n\tconst canvasLow = convertSegmentToCanvas(tree, pathNode, lowSegment)\n\tconst canvasHigh = convertSegmentToCanvas(tree, pathNode, highSegment)\n\n\tconst begin = curve.projectedTime < 0.5\n\tconst anchor = begin ? PathSegment.point(canvasLow) : PathSegment.point(canvasHigh)\n\tconst angle = curveAngle(canvasLow, canvasHigh, 0)\n\n\treturn Line(anchor, Point.add(anchor, angle))\n}\n\nexport const MIDPOINT_IN_RANGE_THRESHOLD = 15 // export for tests\nexport function closestCurve(tree: CanvasTree, node: PathNode, mouse: Point, zoom: number): ClosestCurve | null {\n\tconst distanceThreshold = 5 / zoom\n\tconst midPointInRangeThreshold = MIDPOINT_IN_RANGE_THRESHOLD / zoom\n\n\t// major shortcut before we start to calculate\n\tconst canvasRect = node.cache.canvasRect\n\tif (canvasRect) {\n\t\tif (canvasRect.x - mouse.x > distanceThreshold) return null\n\t\tif (canvasRect.y - mouse.y > distanceThreshold) return null\n\t\tif (mouse.x - (canvasRect.x + canvasRect.width) > distanceThreshold) return null\n\t\tif (mouse.y - (canvasRect.y + canvasRect.height) > distanceThreshold) return null\n\t}\n\n\tconst bezierCurves = Path.toBezierJS(node, node)\n\tconst relativePoint = tree.convertPointToNode(node, mouse)\n\n\tlet shortestIndex = -1\n\tlet shortestDistance = Infinity\n\tlet projectedTime = 0\n\n\tfor (let i = 0, il = bezierCurves.length; i < il; i++) {\n\t\tconst bezierCurve = bezierCurves[i]\n\t\tassert(bezierCurve !== undefined, \"Expected bezierCurve at index within loop bounds\")\n\t\tconst projection = bezierCurve.project(relativePoint)\n\t\tconst distance = projection.d\n\t\tconst t = projection.t\n\n\t\tif (distance >= shortestDistance || t === 0 || t === 1) {\n\t\t\tcontinue\n\t\t}\n\n\t\tshortestDistance = distance\n\t\tshortestIndex = i\n\t\tprojectedTime = t\n\t}\n\n\tif (shortestIndex === -1) return null\n\n\tconst curve = bezierCurves[shortestIndex]\n\tassert(curve !== undefined, \"Expected curve at shortestIndex\")\n\tconst projectedPoint = curve.get(projectedTime)\n\tconst midPoint = curve.get(0.5)\n\n\tconst midPointInRange = Point.distance(relativePoint, midPoint) < midPointInRangeThreshold\n\n\treturn {\n\t\tid: node.id,\n\t\tsegmentIndex: shortestIndex,\n\t\tdistance: shortestDistance,\n\t\tprojectedPoint,\n\t\tprojectedTime,\n\t\tmidPoint,\n\t\tmidPointInRange,\n\t}\n}\n\nexport function copyShapeStyle(\n\tshape: CanvasNode & WithStroke & WithFill & WithOptionalFill & WithBoxShadow & WithOpacity,\n): WithStroke &\n\t// Conic gradient is not supported by shapes\n\tOmit<WithOptionalFill, \"fillConicGradient\"> &\n\tWithBoxShadow &\n\tWithOpacity {\n\treturn {\n\t\tstrokeEnabled: shape.strokeEnabled,\n\t\tstrokeAlignment: shape.strokeAlignment,\n\t\tstrokeWidth: shape.strokeWidth,\n\t\tstrokeColor: shape.strokeColor,\n\t\tlineJoin: shape.lineJoin,\n\t\tlineCap: shape.lineCap,\n\t\tstrokeMiterLimit: shape.strokeMiterLimit,\n\t\tstrokeDashArray: shape.strokeDashArray,\n\t\tstrokeDashOffset: shape.strokeDashOffset,\n\t\tfillEnabled: shape.fillEnabled,\n\t\tfillType: shape.fillType,\n\t\tfillColor: shape.fillColor,\n\t\tfillLinearGradient: shape.fillLinearGradient,\n\t\tfillRadialGradient: shape.fillRadialGradient,\n\t\tfillImage: shape.fillImage,\n\t\tfillImageResize: shape.fillImageResize,\n\t\tfillImageOriginalName: shape.fillImageOriginalName,\n\t\tfillImagePixelWidth: shape.fillImagePixelWidth,\n\t\tfillImagePixelHeight: shape.fillImagePixelHeight,\n\t\tfillImagePositionX: shape.fillImagePositionX,\n\t\tfillImagePositionY: shape.fillImagePositionY,\n\t\tfillImageTileSize: shape.fillImageTileSize,\n\t\tboxShadows: shape.boxShadows,\n\t\topacity: shape.opacity,\n\t}\n}\n", "import type { VariableReference } from \"@framerjs/document-migrations/src/types/V75.ts\"\nimport { assertNever, getLogger } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { EngineChangeSignal } from \"document/EngineChanges.ts\"\nimport { EngineChange } from \"document/EngineChanges.ts\"\nimport { EngineStore } from \"document/EngineStore.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { convertPathToCanvas } from \"document/components/tools/pathEdit/utils/index.ts\"\nimport type { CanvasNode, MaybeNodeID, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { NullID } from \"document/models/CanvasTree/index.ts\"\nimport type { PlaceholderItem } from \"document/models/CanvasTree/nodes/CanvasNodeCache.ts\"\nimport type { Link } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport { convertFrameToCanvas } from \"document/models/CanvasTree/utils/geometry.ts\"\nimport type { FramePoint } from \"document/models/FramePoint.ts\"\nimport { Path } from \"document/models/Path.ts\"\nimport { type ShapeTools, Tools } from \"document/stores/ToolEnum.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { type Point, isEqual } from \"library/index.ts\"\nimport { withShape } from \"library/render/traits/Shape.ts\"\nimport type { Line } from \"library/render/types/Line.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport type { EditorState } from \"prosemirror-state\"\nimport type { EditorView } from \"prosemirror-view\"\nimport { getIsViewOnly } from \"web/pages/project/permissions/isViewOnly.ts\"\nimport type { BaseToolStore } from \"../base-engine/BaseToolStore.ts\"\nimport type { EffectStore } from \"./EffectStore.ts\"\n\nexport { Tools }\n\nconst log = getLogger(\"ToolStore\")\n\nexport interface NodeWithPlaceholders {\n\tid: NodeID\n\tplaceholders: PlaceholderItem[]\n}\n\nexport class ToolStore extends EngineStore implements BaseToolStore {\n\tupdate = 0\n\ttooltip?: string\n\tshapeToolActive = false\n\tfeedbackModeActive = false\n\thandle: FramePoint | null = null\n\tstraightLineAnchorIndex: 0 | 1 = 0\n\n\tproseMirrorView: EditorView | null = null\n\tproseMirrorState: EditorState | null = null\n\ttextLink: Link | VariableReference | null = null\n\teditedTextLink: Link | VariableReference | undefined = undefined\n\n\tstackInsertionIndicator: Line | null = null\n\treplaceableFloatingPositionNode: MaybeNodeID = null\n\n\tprivate activeTool = Tools.Highlight\n\n\tget tool() {\n\t\treturn this.activeTool\n\t}\n\n\t// When the text tool is active, this will hold the id of the text node being edited.\n\tnodeInTextEditorId: MaybeNodeID = NullID\n\tnodeInPathEditorOffset: Point | null = null\n\n\t// The move tool will keep this updated with the current stack or grid drag and drop placeholders.\n\tnodesWithPlaceholders: NodeWithPlaceholders[] | null = null\n\n\tcodeComponentInProgressInsertionIndicatorNodeIDs: Set<NodeID> = new Set()\n\n\t// FIXME: addChanges should not be used manually inside EngineStores\n\tconstructor(\n\t\tprivate addChanges: EngineChangeSignal,\n\t\tprivate readonly effectsStore: EffectStore,\n\t) {\n\t\tsuper()\n\t}\n\n\tpostProcess(update: number) {\n\t\tthis.update = update\n\t}\n\n\tget isDefaultToolActive() {\n\t\treturn this.tool === Tools.Highlight || this.tool === Tools.DirectSelect\n\t}\n\n\tupdateDragAndDropPlaceholder(node: CanvasNode | null | undefined) {\n\t\tif (node) {\n\t\t\tconst placeholders = node.cache.placeholders\n\t\t\tconst update = placeholders ? [{ id: node.id, placeholders }] : null\n\t\t\tif (isEqual(update, this.nodesWithPlaceholders)) return\n\t\t\tthis.nodesWithPlaceholders = update\n\t\t} else {\n\t\t\tthis.nodesWithPlaceholders = null\n\t\t}\n\t}\n\n\tsetTool(tool: Tools) {\n\t\t// Move tool will only cancel the preview when the move has a delta.\n\t\t// Otherwise clicking a node to change the selection will cancel the\n\t\t// preview.\n\t\tif (Tools.canEditTree(tool) && tool !== Tools.Move) {\n\t\t\t// Disable effect preview before starting a new tool that edits.\n\t\t\tthis.effectsStore.exitPreview()\n\t\t}\n\n\t\tthis.shapeToolActive = isShapeTool(tool)\n\n\t\tif (!isFeedbackTool(tool)) {\n\t\t\tthis.feedbackModeActive = false\n\t\t}\n\n\t\tif (this.tool === Tools.Move && tool !== Tools.Move) {\n\t\t\tthis.addChanges(EngineChange.ExitMove)\n\t\t}\n\n\t\tif (this.tool !== tool) {\n\t\t\tthis.addChanges(EngineChange.Tool)\n\t\t}\n\n\t\tthis.activeTool = tool\n\t}\n\n\t/** Cache for canvas frames of a multi-selection. Invalidate when the tree/zoom changes, or the selection changes. */\n\tcachedSelectionFrame: Map<string, { merged: Rect; frames: Rect[] }> = new Map()\n\tgetZoomAdjustedSelectionFrames(\n\t\tengine: VekterEngine,\n\t\tselection: NodeID[],\n\t\tzoom: number,\n\t\tallowCache = experiments.isOn(\"agent\"),\n\t) {\n\t\tif (!selection.length) return undefined\n\n\t\tif (allowCache) {\n\t\t\tconst hash = getCachedSelectionFrameHash(\n\t\t\t\tengine.tree.root.update,\n\t\t\t\tengine.stores.treeStore.domLayoutUpdate,\n\t\t\t\tselection,\n\t\t\t\tzoom,\n\t\t\t)\n\t\t\tconst cached = this.cachedSelectionFrame.get(hash)\n\t\t\tif (cached) {\n\t\t\t\tlog.debug(\"using cached selection frames\", hash, cached)\n\t\t\t\treturn cached\n\t\t\t}\n\t\t}\n\n\t\treturn this.calculateZoomAdjustedSelectionFrames(engine, selection, zoom)\n\t}\n\n\tprivate setCachedSelectionFrames(\n\t\trootUpdate: number,\n\t\tdomLayoutUpdate: number,\n\t\tselection: NodeID[],\n\t\tzoom: number,\n\t\tmerged: Rect,\n\t\tframes: Rect[],\n\t) {\n\t\t// Trim the cache to the last 100 frames\n\t\tif (this.cachedSelectionFrame.size > 100) {\n\t\t\tthis.cachedSelectionFrame.clear()\n\t\t}\n\n\t\tthis.cachedSelectionFrame.set(getCachedSelectionFrameHash(rootUpdate, domLayoutUpdate, selection, zoom), {\n\t\t\tmerged,\n\t\t\tframes,\n\t\t})\n\t}\n\n\tprivate calculateZoomAdjustedSelectionFrames(\n\t\tengine: VekterEngine,\n\t\tselection: NodeID[],\n\t\tzoom: number,\n\t): { merged: Rect; frames: Rect[] } | undefined {\n\t\tconst tree = engine.tree\n\t\tconst update = tree.root.update\n\t\tconst domLayoutUpdate = engine.stores.treeStore.domLayoutUpdate\n\t\tlog.debug(\"calculate selection frames\", {\n\t\t\tupdate,\n\t\t\tdomLayoutUpdate,\n\t\t\tselection,\n\t\t\tzoom,\n\t\t})\n\t\tconst outlineFrames: Rect[] = []\n\n\t\tconst mergedFrame = selection.reduce((previous: undefined | Rect, id) => {\n\t\t\tconst node = tree.getNode(id)\n\t\t\tif (!node?.cache.visible) return previous\n\n\t\t\tlet canvasFrame: Rect\n\n\t\t\tif (withShape(node)) {\n\t\t\t\tconst calculatedPaths = node.calculatedPaths()\n\t\t\t\tconst canvasPath = convertPathToCanvas(tree, node, calculatedPaths)\n\t\t\t\tcanvasFrame = Path.boundingBox(canvasPath, 0)\n\t\t\t} else {\n\t\t\t\tcanvasFrame = convertFrameToCanvas(tree, node)\n\t\t\t}\n\t\t\tconst frame = Rect.roundToOutside(Rect.multiply(canvasFrame, zoom))\n\t\t\toutlineFrames.push(frame)\n\t\t\treturn previous ? Rect.merge(previous, frame) : frame\n\t\t}, undefined)\n\n\t\tif (!mergedFrame) return undefined\n\n\t\tthis.setCachedSelectionFrames(update, domLayoutUpdate, selection, zoom, mergedFrame, outlineFrames)\n\t\tlog.debug(\"calculated selection frames\", { merged: mergedFrame, frames: outlineFrames })\n\t\treturn { merged: mergedFrame, frames: outlineFrames }\n\t}\n}\n\nfunction getCachedSelectionFrameHash(rootUpdate: number, domLayoutUpdate: number, selection: NodeID[], zoom: number) {\n\treturn rootUpdate + \":\" + domLayoutUpdate + \":\" + selection.join(\",\") + \":\" + zoom\n}\n\nfunction isToolAllowedInVectorSetNode(tool: Tools) {\n\t// TODO: Rename when removing shape mode, this is used for vector set as well.\n\tswitch (tool) {\n\t\t// These tools cannot be used in shape mode.\n\t\t// Switching to them will exit the mode.\n\t\tcase Tools.CollectionReferenceVariableEdit:\n\t\tcase Tools.CreateColumns:\n\t\tcase Tools.CreateFrame:\n\t\tcase Tools.CreateGrid:\n\t\tcase Tools.CreateGridRow:\n\t\tcase Tools.CreateGridSpan:\n\t\tcase Tools.CreateMasonry:\n\t\tcase Tools.CreateImage:\n\t\tcase Tools.CreateRounded:\n\t\tcase Tools.CreateRows:\n\t\tcase Tools.CreateScreen:\n\t\tcase Tools.CreateStack:\n\t\tcase Tools.CreateText:\n\t\tcase Tools.CreateVideo:\n\t\tcase Tools.DateVariableEdit:\n\t\tcase Tools.EnumVariableEdit:\n\t\tcase Tools.Link:\n\t\tcase Tools.LoadingShield:\n\t\tcase Tools.RichTextVariableEdit:\n\t\tcase Tools.SlotConnect:\n\t\tcase Tools.StringVariableEdit:\n\t\tcase Tools.TextEdit:\n\t\t\treturn false\n\n\t\t// These tools are either shape tools,\n\t\t// or can be used while in shape mode without exiting the mode.\n\t\tcase Tools.AgentPanel:\n\t\tcase Tools.AgentDragSelect:\n\t\tcase Tools.AgentSelect:\n\t\tcase Tools.Chat:\n\t\tcase Tools.Comment:\n\t\tcase Tools.CreateOvalShape:\n\t\tcase Tools.CreatePolygonShape:\n\t\tcase Tools.CreateRectangleShape:\n\t\tcase Tools.CreateStarShape:\n\t\tcase Tools.DirectSelect:\n\t\tcase Tools.FillGradient:\n\t\tcase Tools.Gap:\n\t\tcase Tools.Guide:\n\t\tcase Tools.Highlight:\n\t\tcase Tools.HighlightStackItem:\n\t\tcase Tools.LineAnchorMove:\n\t\tcase Tools.MaskGradient:\n\t\tcase Tools.Move:\n\t\tcase Tools.Padding:\n\t\tcase Tools.Pan:\n\t\tcase Tools.Path:\n\t\tcase Tools.Radius:\n\t\tcase Tools.Resize:\n\t\tcase Tools.RichTextEdit:\n\t\tcase Tools.Rotate:\n\t\tcase Tools.SampleColor:\n\t\tcase Tools.Scale:\n\t\tcase Tools.Select:\n\t\tcase Tools.Unknown:\n\t\tcase Tools.ViewportResize:\n\t\tcase Tools.Zoom:\n\t\tcase Tools.ZoomSelect:\n\t\t\treturn true\n\n\t\tdefault:\n\t\t\t// Triggers an error if a new tool gets added without explicitly\n\t\t\t// assigning it a return value above. This is to force an explicit\n\t\t\t// decision about whether the new tool can be used in shape mode.\n\t\t\tassertNever(tool)\n\t}\n}\n\nfunction isShapeTool(tool: Tools): tool is ShapeTools {\n\tswitch (tool) {\n\t\tcase Tools.AgentPanel:\n\t\tcase Tools.AgentDragSelect:\n\t\tcase Tools.AgentSelect:\n\t\tcase Tools.CollectionReferenceVariableEdit:\n\t\tcase Tools.Chat:\n\t\tcase Tools.Comment:\n\t\tcase Tools.CreateColumns:\n\t\tcase Tools.CreateFrame:\n\t\tcase Tools.CreateGrid:\n\t\tcase Tools.CreateGridRow:\n\t\tcase Tools.CreateGridSpan:\n\t\tcase Tools.CreateMasonry:\n\t\tcase Tools.CreateImage:\n\t\tcase Tools.CreateRounded:\n\t\tcase Tools.CreateRows:\n\t\tcase Tools.CreateScreen:\n\t\tcase Tools.CreateStack:\n\t\tcase Tools.CreateText:\n\t\tcase Tools.CreateVideo:\n\t\tcase Tools.DirectSelect:\n\t\tcase Tools.FillGradient:\n\t\tcase Tools.Gap:\n\t\tcase Tools.Guide:\n\t\tcase Tools.Highlight:\n\t\tcase Tools.HighlightStackItem:\n\t\tcase Tools.Link:\n\t\tcase Tools.LoadingShield:\n\t\tcase Tools.MaskGradient:\n\t\tcase Tools.Move:\n\t\tcase Tools.Padding:\n\t\tcase Tools.Pan:\n\t\tcase Tools.Radius:\n\t\tcase Tools.Resize:\n\t\tcase Tools.RichTextEdit:\n\t\tcase Tools.RichTextVariableEdit:\n\t\tcase Tools.StringVariableEdit:\n\t\tcase Tools.DateVariableEdit:\n\t\tcase Tools.EnumVariableEdit:\n\t\tcase Tools.Rotate:\n\t\tcase Tools.SampleColor:\n\t\tcase Tools.Scale:\n\t\tcase Tools.Select:\n\t\tcase Tools.SlotConnect:\n\t\tcase Tools.TextEdit:\n\t\tcase Tools.Unknown:\n\t\tcase Tools.ViewportResize:\n\t\tcase Tools.Zoom:\n\t\tcase Tools.ZoomSelect:\n\t\t\treturn false\n\n\t\tcase Tools.CreateOvalShape:\n\t\tcase Tools.CreatePolygonShape:\n\t\tcase Tools.CreateRectangleShape:\n\t\tcase Tools.CreateStarShape:\n\t\tcase Tools.LineAnchorMove:\n\t\tcase Tools.Path:\n\t\t\treturn true\n\n\t\tdefault:\n\t\t\tassertNever(tool)\n\t}\n}\n\nfunction isFeedbackTool(tool: Tools) {\n\tswitch (tool) {\n\t\t// These tools are either feedback tools,\n\t\t// or can be used while in feedback mode without exiting the mode.\n\t\tcase Tools.Chat:\n\t\tcase Tools.Comment:\n\t\tcase Tools.Pan:\n\t\tcase Tools.Zoom:\n\t\tcase Tools.ZoomSelect:\n\t\t\treturn true\n\n\t\t// These tools cannot be used in feedback mode.\n\t\t// Switching to them will exit the mode.\n\t\tcase Tools.AgentPanel:\n\t\tcase Tools.AgentDragSelect:\n\t\tcase Tools.AgentSelect:\n\t\tcase Tools.Highlight:\n\t\tcase Tools.DirectSelect:\n\t\tcase Tools.Select:\n\t\tcase Tools.Move:\n\t\tcase Tools.Resize:\n\t\tcase Tools.Scale:\n\t\tcase Tools.Rotate:\n\t\tcase Tools.LineAnchorMove:\n\t\tcase Tools.CollectionReferenceVariableEdit:\n\t\tcase Tools.CreateFrame:\n\t\tcase Tools.CreateRounded:\n\t\tcase Tools.CreateImage:\n\t\tcase Tools.CreateVideo:\n\t\tcase Tools.CreateScreen:\n\t\tcase Tools.CreateText:\n\t\tcase Tools.CreateOvalShape:\n\t\tcase Tools.CreateRectangleShape:\n\t\tcase Tools.CreatePolygonShape:\n\t\tcase Tools.CreateStarShape:\n\t\tcase Tools.CreateStack:\n\t\tcase Tools.CreateRows:\n\t\tcase Tools.CreateColumns:\n\t\tcase Tools.CreateGrid:\n\t\tcase Tools.CreateGridRow:\n\t\tcase Tools.CreateGridSpan:\n\t\tcase Tools.CreateMasonry:\n\t\tcase Tools.TextEdit:\n\t\tcase Tools.RichTextEdit:\n\t\tcase Tools.RichTextVariableEdit:\n\t\tcase Tools.StringVariableEdit:\n\t\tcase Tools.DateVariableEdit:\n\t\tcase Tools.EnumVariableEdit:\n\t\tcase Tools.Padding:\n\t\tcase Tools.Gap:\n\t\tcase Tools.Path:\n\t\tcase Tools.SampleColor:\n\t\tcase Tools.Radius:\n\t\tcase Tools.FillGradient:\n\t\tcase Tools.MaskGradient:\n\t\tcase Tools.SlotConnect:\n\t\tcase Tools.Link:\n\t\tcase Tools.Guide:\n\t\tcase Tools.Unknown:\n\t\tcase Tools.ViewportResize:\n\t\tcase Tools.HighlightStackItem:\n\t\tcase Tools.LoadingShield:\n\t\t\treturn false\n\n\t\tdefault:\n\t\t\t// Triggers an error if a new tool gets added without explicitly\n\t\t\t// assigning it a return value above. This is to force an explicit\n\t\t\t// decision about whether the new tool can be used in feedback mode.\n\t\t\tassertNever(tool)\n\t}\n}\n\nexport function isZoomTool(tool: Tools) {\n\tswitch (tool) {\n\t\tcase Tools.Zoom:\n\t\tcase Tools.ZoomSelect:\n\t\t\treturn true\n\n\t\tcase Tools.AgentPanel:\n\t\tcase Tools.AgentDragSelect:\n\t\tcase Tools.AgentSelect:\n\t\tcase Tools.Highlight:\n\t\tcase Tools.DirectSelect:\n\t\tcase Tools.Select:\n\t\tcase Tools.Pan:\n\t\tcase Tools.Move:\n\t\tcase Tools.Resize:\n\t\tcase Tools.Scale:\n\t\tcase Tools.Rotate:\n\t\tcase Tools.LineAnchorMove:\n\t\tcase Tools.CollectionReferenceVariableEdit:\n\t\tcase Tools.CreateFrame:\n\t\tcase Tools.CreateRounded:\n\t\tcase Tools.CreateImage:\n\t\tcase Tools.CreateVideo:\n\t\tcase Tools.CreateScreen:\n\t\tcase Tools.CreateText:\n\t\tcase Tools.CreateOvalShape:\n\t\tcase Tools.CreateRectangleShape:\n\t\tcase Tools.CreatePolygonShape:\n\t\tcase Tools.CreateStarShape:\n\t\tcase Tools.CreateStack:\n\t\tcase Tools.CreateRows:\n\t\tcase Tools.CreateColumns:\n\t\tcase Tools.CreateGrid:\n\t\tcase Tools.CreateGridRow:\n\t\tcase Tools.CreateGridSpan:\n\t\tcase Tools.CreateMasonry:\n\t\tcase Tools.TextEdit:\n\t\tcase Tools.RichTextEdit:\n\t\tcase Tools.RichTextVariableEdit:\n\t\tcase Tools.StringVariableEdit:\n\t\tcase Tools.DateVariableEdit:\n\t\tcase Tools.EnumVariableEdit:\n\t\tcase Tools.Padding:\n\t\tcase Tools.Gap:\n\t\tcase Tools.Path:\n\t\tcase Tools.SampleColor:\n\t\tcase Tools.Radius:\n\t\tcase Tools.FillGradient:\n\t\tcase Tools.MaskGradient:\n\t\tcase Tools.SlotConnect:\n\t\tcase Tools.Link:\n\t\tcase Tools.Chat:\n\t\tcase Tools.Comment:\n\t\tcase Tools.Guide:\n\t\tcase Tools.Unknown:\n\t\tcase Tools.ViewportResize:\n\t\tcase Tools.HighlightStackItem:\n\t\tcase Tools.LoadingShield:\n\t\t\treturn false\n\n\t\tdefault:\n\t\t\t// Triggers an error if a new tool gets added without explicitly\n\t\t\t// assigning it a return value above. This is to force an explicit\n\t\t\t// decision about whether the new tool is a zoom tool.\n\t\t\tassertNever(tool)\n\t}\n}\n\nexport function isToolAllowedInViewOnly(tool: Tools) {\n\t// FIXME: Tools.Move handles selection for non-selectable nodes (see isSelectable.ts)\n\t// and for selecting nodes by clicking on the Screen Title. This should not be handled by Move.\n\tswitch (tool) {\n\t\tcase Tools.Highlight:\n\t\tcase Tools.DirectSelect:\n\t\tcase Tools.Select:\n\t\tcase Tools.Pan:\n\t\tcase Tools.Zoom:\n\t\tcase Tools.ZoomSelect:\n\t\tcase Tools.Move:\n\t\tcase Tools.Chat:\n\t\tcase Tools.Comment:\n\t\tcase Tools.Unknown:\n\t\tcase Tools.LoadingShield:\n\t\t\treturn true\n\n\t\tcase Tools.AgentPanel:\n\t\tcase Tools.AgentDragSelect:\n\t\tcase Tools.AgentSelect:\n\t\tcase Tools.Resize:\n\t\tcase Tools.Scale:\n\t\tcase Tools.Rotate:\n\t\tcase Tools.LineAnchorMove:\n\t\tcase Tools.CollectionReferenceVariableEdit:\n\t\tcase Tools.CreateFrame:\n\t\tcase Tools.CreateRounded:\n\t\tcase Tools.CreateImage:\n\t\tcase Tools.CreateVideo:\n\t\tcase Tools.CreateScreen:\n\t\tcase Tools.CreateText:\n\t\tcase Tools.CreateOvalShape:\n\t\tcase Tools.CreateRectangleShape:\n\t\tcase Tools.CreatePolygonShape:\n\t\tcase Tools.CreateStarShape:\n\t\tcase Tools.CreateStack:\n\t\tcase Tools.CreateRows:\n\t\tcase Tools.CreateColumns:\n\t\tcase Tools.CreateGrid:\n\t\tcase Tools.CreateGridRow:\n\t\tcase Tools.CreateGridSpan:\n\t\tcase Tools.CreateMasonry:\n\t\tcase Tools.TextEdit:\n\t\tcase Tools.RichTextEdit:\n\t\tcase Tools.RichTextVariableEdit:\n\t\tcase Tools.StringVariableEdit:\n\t\tcase Tools.DateVariableEdit:\n\t\tcase Tools.EnumVariableEdit:\n\t\tcase Tools.Padding:\n\t\tcase Tools.Gap:\n\t\tcase Tools.Path:\n\t\tcase Tools.SampleColor:\n\t\tcase Tools.Radius:\n\t\tcase Tools.FillGradient:\n\t\tcase Tools.MaskGradient:\n\t\tcase Tools.SlotConnect:\n\t\tcase Tools.Link:\n\t\tcase Tools.Guide:\n\t\tcase Tools.ViewportResize:\n\t\tcase Tools.HighlightStackItem:\n\t\t\treturn false\n\n\t\tdefault:\n\t\t\t// Triggers an error if a new tool gets added without explicitly\n\t\t\t// assigning it a return value above. This is to force an explicit\n\t\t\t// decision about whether the new tool should be enabled in\n\t\t\t// view-only mode.\n\t\t\tassertNever(tool)\n\t}\n}\n\nexport function isToolAllowedWhenCollectionOverlayActive(tool: Tools) {\n\tswitch (tool) {\n\t\tcase Tools.Pan:\n\t\tcase Tools.Zoom:\n\t\tcase Tools.LoadingShield:\n\t\t\treturn true\n\n\t\tcase Tools.AgentPanel:\n\t\tcase Tools.AgentDragSelect:\n\t\tcase Tools.AgentSelect:\n\t\tcase Tools.ZoomSelect:\n\t\tcase Tools.Move:\n\t\tcase Tools.Highlight:\n\t\tcase Tools.DirectSelect:\n\t\tcase Tools.Select:\n\t\tcase Tools.Chat:\n\t\tcase Tools.Comment:\n\t\tcase Tools.Unknown:\n\t\tcase Tools.Resize:\n\t\tcase Tools.Scale:\n\t\tcase Tools.Rotate:\n\t\tcase Tools.LineAnchorMove:\n\t\tcase Tools.CollectionReferenceVariableEdit:\n\t\tcase Tools.CreateFrame:\n\t\tcase Tools.CreateRounded:\n\t\tcase Tools.CreateImage:\n\t\tcase Tools.CreateVideo:\n\t\tcase Tools.CreateScreen:\n\t\tcase Tools.CreateText:\n\t\tcase Tools.CreateOvalShape:\n\t\tcase Tools.CreateRectangleShape:\n\t\tcase Tools.CreatePolygonShape:\n\t\tcase Tools.CreateStarShape:\n\t\tcase Tools.CreateStack:\n\t\tcase Tools.CreateRows:\n\t\tcase Tools.CreateColumns:\n\t\tcase Tools.CreateGrid:\n\t\tcase Tools.CreateGridRow:\n\t\tcase Tools.CreateGridSpan:\n\t\tcase Tools.CreateMasonry:\n\t\tcase Tools.TextEdit:\n\t\tcase Tools.RichTextEdit:\n\t\tcase Tools.RichTextVariableEdit:\n\t\tcase Tools.StringVariableEdit:\n\t\tcase Tools.DateVariableEdit:\n\t\tcase Tools.EnumVariableEdit:\n\t\tcase Tools.Padding:\n\t\tcase Tools.Gap:\n\t\tcase Tools.Path:\n\t\tcase Tools.SampleColor:\n\t\tcase Tools.Radius:\n\t\tcase Tools.FillGradient:\n\t\tcase Tools.MaskGradient:\n\t\tcase Tools.SlotConnect:\n\t\tcase Tools.Link:\n\t\tcase Tools.Guide:\n\t\tcase Tools.ViewportResize:\n\t\tcase Tools.HighlightStackItem:\n\t\t\treturn false\n\n\t\tdefault:\n\t\t\t// Triggers an error if a new tool gets added without explicitly\n\t\t\t// assigning it a return value above. This is to force an explicit\n\t\t\t// decision about whether the new tool should be enabled in\n\t\t\t// view-only mode.\n\t\t\tassertNever(tool)\n\t}\n}\n\nfunction isToolAllowedInTemplatePreview(tool: Tools) {\n\tswitch (tool) {\n\t\tcase Tools.Highlight:\n\t\tcase Tools.DirectSelect:\n\t\tcase Tools.Select:\n\t\tcase Tools.Pan:\n\t\tcase Tools.Zoom:\n\t\tcase Tools.ZoomSelect:\n\t\tcase Tools.Move:\n\t\tcase Tools.Unknown:\n\t\t\treturn true\n\n\t\tcase Tools.AgentPanel:\n\t\tcase Tools.AgentDragSelect:\n\t\tcase Tools.AgentSelect:\n\t\tcase Tools.Chat:\n\t\tcase Tools.Comment:\n\t\tcase Tools.Resize:\n\t\tcase Tools.Scale:\n\t\tcase Tools.Rotate:\n\t\tcase Tools.LineAnchorMove:\n\t\tcase Tools.CollectionReferenceVariableEdit:\n\t\tcase Tools.CreateFrame:\n\t\tcase Tools.CreateRounded:\n\t\tcase Tools.CreateImage:\n\t\tcase Tools.CreateVideo:\n\t\tcase Tools.CreateScreen:\n\t\tcase Tools.CreateText:\n\t\tcase Tools.CreateOvalShape:\n\t\tcase Tools.CreateRectangleShape:\n\t\tcase Tools.CreatePolygonShape:\n\t\tcase Tools.CreateStarShape:\n\t\tcase Tools.CreateStack:\n\t\tcase Tools.CreateRows:\n\t\tcase Tools.CreateColumns:\n\t\tcase Tools.CreateGrid:\n\t\tcase Tools.CreateGridRow:\n\t\tcase Tools.CreateGridSpan:\n\t\tcase Tools.CreateMasonry:\n\t\tcase Tools.TextEdit:\n\t\tcase Tools.RichTextEdit:\n\t\tcase Tools.RichTextVariableEdit:\n\t\tcase Tools.StringVariableEdit:\n\t\tcase Tools.DateVariableEdit:\n\t\tcase Tools.EnumVariableEdit:\n\t\tcase Tools.Padding:\n\t\tcase Tools.Gap:\n\t\tcase Tools.Path:\n\t\tcase Tools.SampleColor:\n\t\tcase Tools.Radius:\n\t\tcase Tools.FillGradient:\n\t\tcase Tools.MaskGradient:\n\t\tcase Tools.SlotConnect:\n\t\tcase Tools.Link:\n\t\tcase Tools.Guide:\n\t\tcase Tools.ViewportResize:\n\t\tcase Tools.HighlightStackItem:\n\t\tcase Tools.LoadingShield:\n\t\t\treturn false\n\n\t\tdefault:\n\t\t\t// Triggers an error if a new tool gets added without explicitly\n\t\t\t// assigning it a return value above. This is to force an explicit\n\t\t\t// decision about whether the new tool should be enabled in\n\t\t\t// view-only mode.\n\t\t\tassertNever(tool)\n\t}\n}\n\nexport function isToolAllowedInMode(engine: VekterEngine, tool: Tools) {\n\tif (engine.stores.historyStore.isLoadingDocument) {\n\t\treturn tool === Tools.LoadingShield\n\t}\n\n\tif (getIsViewOnly(engine, \"canDesign\")) {\n\t\treturn isToolAllowedInViewOnly(tool)\n\t}\n\n\tif (engine.stores.chromeStore.isPreviewingFeaturedTemplate) {\n\t\treturn isToolAllowedInTemplatePreview(tool)\n\t}\n\n\treturn true\n}\n\nexport function isToolAllowedInScopeType(tool: Tools, scopeType: ScopeType) {\n\tif (scopeType === ScopeType.VectorSet) {\n\t\treturn isToolAllowedInVectorSetNode(tool)\n\t}\n\n\tif (scopeType === ScopeType.WebPage && tool === Tools.Link) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nexport function assertCanUseToolInMode(engine: VekterEngine, tool: Tools) {\n\tif (getIsViewOnly(engine, \"canDesign\") && !isToolAllowedInViewOnly(tool)) {\n\t\tthrow Error(\"Viewer mode: Tool \" + tool + \" is a forbidden action.\")\n\t}\n\n\tif (engine.stores.chromeStore.isPreviewingFeaturedTemplate && !isToolAllowedInTemplatePreview(tool)) {\n\t\tthrow Error(\"Previwing template mode: Tool \" + tool + \" is a forbidden action.\")\n\t}\n}\n\nexport const isLayoutTool = (tool: Tools) => {\n\treturn (\n\t\ttool === Tools.CreateRows ||\n\t\ttool === Tools.CreateColumns ||\n\t\ttool === Tools.CreateGrid ||\n\t\ttool === Tools.CreateGridRow ||\n\t\ttool === Tools.CreateGridSpan ||\n\t\ttool === Tools.CreateMasonry ||\n\t\ttool === Tools.CreateStack\n\t)\n}\n\nexport function isToolWithHandle(tool: Tools) {\n\treturn (\n\t\ttool === Tools.Rotate ||\n\t\ttool === Tools.Resize ||\n\t\ttool === Tools.Scale ||\n\t\ttool === Tools.Padding ||\n\t\ttool === Tools.Gap\n\t)\n}\n", "const editActionsForPanelTitles = new Map<string, () => void>()\n\nexport function registerEditActionForPanelTitle(id: string, action: () => void) {\n\teditActionsForPanelTitles.set(id, action)\n}\n\nexport function deregisterEditActionForPanelTitle(id: string) {\n\teditActionsForPanelTitles.delete(id)\n}\n\nexport function editPanelTitle(inputId: string) {\n\teditActionsForPanelTitles.get(inputId)?.()\n}\n", "import type { NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { editPanelTitle } from \"./editPanelRow.ts\"\n\nconst PAGE_INPUT_ID = `__page_input`\n\nexport function getPageInputId(id: NodeID) {\n\treturn `${PAGE_INPUT_ID}_${id}`\n}\n\nexport function editPageTitle(id: NodeID) {\n\tconst inputId = getPageInputId(id)\n\teditPanelTitle(inputId)\n}\n", "import { assertNever } from \"@framerjs/shared\"\nimport { objectKeys } from \"library/utils/objectKeys.ts\"\nimport { setStylePreset } from \"prosemirror/schema/utils.ts\"\nimport { InlineStyles, setStyles } from \"prosemirror/styles.ts\"\nimport { getDefaultTextStylePreset } from \"utils/textStylePresetUtils.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\nimport type { CanvasTree } from \"../CanvasTree.ts\"\nimport { textStylePresetDefaults } from \"../records/TextStylePresetRecord.ts\"\nimport type { VariableReference } from \"../traits/VariableReference.ts\"\nimport type { WithComponentPresets } from \"../traits/WithComponentPresets.ts\"\nimport { prefixComponentPresetKey } from \"../traits/WithComponentPresets.ts\"\nimport type { RichTextTag } from \"../traits/WithRichTextTag.ts\"\nimport type { WithStylePresets } from \"../traits/WithStylePresets.ts\"\nimport { getTextStylePresetKey } from \"../traits/WithStylePresets.ts\"\nimport { isReplica } from \"../traits/WithTemplate.ts\"\nimport { type FontSize, isFontSizeCSSDimension } from \"../traits/WithTextStyle.ts\"\nimport { parseCSSDimension } from \"../traits/utils/CSSDimension.ts\"\nimport { PresetsListNode } from \"./PresetsListNode.ts\"\nimport { RichTextNode } from \"./RichTextNode.ts\"\nimport {\n\tisBlockquoteStylePresetNode,\n\tisComponentPresetNode,\n\tisImageStylePresetNode,\n\tisInlineCodeStylePresetNode,\n\tisLinkStylePresetNode,\n\tisTableStylePresetNode,\n\tisTextStylePresetNode,\n} from \"./utils/nodeCheck.ts\"\n\ntype WithPresets = Partial<WithStylePresets> & WithComponentPresets\n\nexport function getDefaultPresets(tree: CanvasTree): WithPresets {\n\tconst result: WithPresets = {}\n\n\tconst listNode = PresetsListNode.get(tree)\n\tif (!listNode) return result\n\n\tfor (const preset of listNode.children) {\n\t\tif (isReplica(preset)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isTextStylePresetNode(preset)) {\n\t\t\tconst key = getTextStylePresetKey(preset.tag)\n\t\t\tresult[key] ??= preset.id\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isLinkStylePresetNode(preset)) {\n\t\t\tresult.stylePresetLink ??= preset.id\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isInlineCodeStylePresetNode(preset)) {\n\t\t\tresult.stylePresetInlineCode ??= preset.id\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isImageStylePresetNode(preset)) {\n\t\t\tresult.stylePresetImage ??= preset.id\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isBlockquoteStylePresetNode(preset)) {\n\t\t\tresult.stylePresetBlockquote ??= preset.id\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isTableStylePresetNode(preset)) {\n\t\t\tresult.stylePresetTable ??= preset.id\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isComponentPresetNode(preset)) {\n\t\t\tconst key = prefixComponentPresetKey(preset.componentIdentifier)\n\t\t\tresult[key] ??= preset.id\n\t\t\tcontinue\n\t\t}\n\n\t\tassertNever(preset)\n\t}\n\n\treturn result\n}\n\nexport function applyDefaultPresets(tree: CanvasTree, node: RichTextNode) {\n\tconst defaultPresets = getDefaultPresets(tree)\n\tconst update: Partial<RichTextNode> = {}\n\n\tconst keys = objectKeys(defaultPresets)\n\tfor (const key of keys) {\n\t\tconst id = node[key]\n\t\tconst existing = tree.get(id)\n\t\tif (existing) continue\n\n\t\tupdate[key] = defaultPresets[key]\n\t}\n\n\tif (Object.keys(update).length > 0) {\n\t\tnode.set(update)\n\t}\n}\n\nexport function createRichTextNodeWithTag({\n\ttree,\n\ttag,\n\ttext = \"\",\n\ttextColor,\n\tattributes = {},\n}: {\n\ttree: CanvasTree\n\ttag: RichTextTag\n\ttext?: string\n\tattributes?: Partial<RichTextNode>\n\ttextColor?: string\n}) {\n\tconst dom = document.createElement(tag)\n\tdom.innerText = text\n\n\tconst preset = getDefaultTextStylePreset(tree, tag)\n\tif (preset) {\n\t\tsetStylePreset(dom, preset.id)\n\n\t\tif (textColor) {\n\t\t\tsetStyles(dom.style, InlineStyles.transforms, { textColor })\n\t\t}\n\t} else {\n\t\tconst defaults = textStylePresetDefaults[tag]\n\t\tconst defaultFontSize = defaults.fontSize\n\t\tlet fontSize: FontSize | VariableReference | undefined\n\t\tif (isFontSizeCSSDimension(defaultFontSize)) {\n\t\t\tfontSize = parseCSSDimension(defaultFontSize)\n\t\t} else if (isNumber(defaultFontSize)) {\n\t\t\tfontSize = [defaultFontSize, \"px\"]\n\t\t}\n\n\t\tconst styles: InlineStyles = {\n\t\t\t...defaults,\n\t\t\tfontSize,\n\t\t\ttextColor: textColor ?? defaults.textColor,\n\t\t}\n\n\t\tsetStyles(dom.style, InlineStyles.transforms, styles)\n\t}\n\n\treturn new RichTextNode({\n\t\thtml: dom.outerHTML,\n\t\t...getDefaultPresets(tree),\n\t\t...attributes,\n\t})\n}\n", "import type { CanvasNode } from \"./CanvasNode.ts\"\nimport type { LoadedSmartComponentNode } from \"./SmartComponentNode.ts\"\nimport type { LoadedWebPageNode } from \"./WebPageNode.ts\"\nimport { isSmartComponentNode, isWebPageNode } from \"./utils/nodeCheck.ts\"\n\nexport type ImportableComponentNode = LoadedSmartComponentNode | LoadedWebPageNode\n\nexport function isImportableComponentNode(node: CanvasNode | null): node is ImportableComponentNode {\n\treturn isSmartComponentNode(node) || isWebPageNode(node)\n}\n", "import type { CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport type { RouteSegmentNode } from \"document/models/CanvasTree/nodes/RouteSegmentNode.ts\"\nimport { getRouteSegmentRootNode } from \"document/models/CanvasTree/nodes/RouteSegmentRootNode.utils.ts\"\n\nfunction collectPath(result: Set<string>, tree: CanvasTree, node: RouteSegmentNode, path: string) {\n\tconst segmentPath = `${path}/${node.segment}`\n\tresult.add(segmentPath)\n\n\tfor (const routeSegment of node.children) {\n\t\tcollectPath(result, tree, routeSegment, segmentPath)\n\t}\n}\n\n/**\n * Generates a Set of all existing paths in the tree. This also includes empty folders.\n * If you want to only get web pages, use `routeSegmentRootNode.getAllWebPagePaths()` instead\n */\nexport function getAllExistingFolderAndPagePathsFromRouteSegments(tree: CanvasTree) {\n\tconst result = new Set<string>()\n\n\tconst routeSegmentRootNode = getRouteSegmentRootNode(tree)\n\n\tfor (const routeSegment of routeSegmentRootNode.children) {\n\t\tcollectPath(result, tree, routeSegment, \"\")\n\t}\n\n\treturn result\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport type { VariableID } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { uniqueName } from \"document/utils/uniqueName.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { pathVariablesRegExpGlobal } from \"library/router/pathVariables.ts\"\nimport { getCollectionForIdentifier } from \"utils/getCollectionForIdentifier.ts\"\nimport { hasPathVariableShape } from \"utils/pathVariables.ts\"\nimport type { AnyWebPageNode } from \"../../models/CanvasTree/nodes/WebPageNode.ts\"\nimport { getAllExistingFolderAndPagePathsFromRouteSegments } from \"../chrome/Pages/utils/getAllExistingFolderAndPagePaths.ts\"\nimport { getRawWebPagePath } from \"./getWebPagePath.ts\"\nimport { pathToName } from \"./pathToName.ts\"\nimport { valueToPath } from \"./valueToPath.ts\"\n\nconst missingSlugFallback = \":missing-slug\"\n\nfunction getSlugInfoForCollection(\n\tidentifier: ModuleExportIdentifierString,\n\ttree: CanvasTree,\n\tcomponentLoader: AnyComponentLoader,\n): { id: VariableID; name: string } | undefined {\n\t// Read from the tree if possible.\n\tconst collection = getCollectionForIdentifier(tree, identifier)\n\tif (collection) {\n\t\treturn collection.getSlugVariable()\n\t}\n\n\tconst data = componentLoader.dataForIdentifier(identifier)\n\tif (!data) return\n\n\tconst slugId = data.annotations?.[AnnotationKey.FramerSlug]\n\tif (!slugId) return\n\n\tconst control = data.properties[slugId]\n\tif (control?.type !== ControlType.String) return\n\n\treturn {\n\t\tid: slugId,\n\t\tname: control.title ?? Dictionary.Slug.toLowerCase(),\n\t}\n}\n\nexport function convertReadablePathVariablesToIds(\n\tidentifier: ModuleExportIdentifierString,\n\tpath: string | undefined,\n\ttree: CanvasTree,\n\tcomponentLoader: AnyComponentLoader,\n): string {\n\tif (!path) return \"/unknown\"\n\n\tconst slugInfo = getSlugInfoForCollection(identifier, tree, componentLoader)\n\n\tlet numberOfVariables = 0\n\n\tlet result = path.replace(pathVariablesRegExpGlobal, (_variable, _name) => {\n\t\tnumberOfVariables++\n\t\tif (!slugInfo) return missingSlugFallback\n\t\treturn `:${slugInfo.id}`\n\t})\n\n\t// The slug is already added\n\tif (numberOfVariables > 0) {\n\t\treturn result\n\t}\n\n\t// Add slash if needed\n\tif (!result.endsWith(\"/\")) {\n\t\tresult += \"/\"\n\t}\n\n\t// Add known slug\n\tif (slugInfo) {\n\t\treturn result + `:${slugInfo.id}`\n\t}\n\n\treturn result + missingSlugFallback\n}\n\nfunction isLastSegmentSlug(path: string) {\n\tconst segments = path.split(\"/\")\n\tconst lastSegment = segments[segments.length - 1]\n\tif (!lastSegment) return false\n\treturn hasPathVariableShape(lastSegment)\n}\n\n/**\n * Generates a valid and unique path from the input. Also attempts to convert\n * path variables from their human-friendly version to the actual property name.\n */\nexport const getUniquePagePath = (\n\tnewPath: string,\n\ttree: CanvasTree,\n\tcomponentLoader: AnyComponentLoader,\n\tnode: AnyWebPageNode | null,\n\tisDuplicate = false,\n): { path: string; suggestedName: string } => {\n\tnewPath = valueToPath(newPath)\n\n\tconst existingPaths = getAllExistingFolderAndPagePathsFromRouteSegments(tree)\n\tconst homePageNodeId = tree.root.homePageNodeId\n\tconst isHomePage = !!node && node.id === homePageNodeId\n\tif (newPath === \"/\" && !isHomePage) {\n\t\tnewPath = \"/page\"\n\t}\n\n\tif (node?.dataIdentifier) {\n\t\tnewPath = convertReadablePathVariablesToIds(node.dataIdentifier, newPath, tree, componentLoader)\n\t}\n\n\tconst hasTrailingSlash = newPath.endsWith(\"/\") && !isHomePage\n\tlet pageWithoutTrailingSlash = newPath\n\tif (hasTrailingSlash) pageWithoutTrailingSlash = newPath.slice(0, -1)\n\n\tconst currentPath = getRawWebPagePath(tree, node)\n\t// We should check the existing paths for the path, as opposed to the one without the trailing slash. Because\n\t// eventually we will add the trailing slash back to the created path.\n\tif (existingPaths.has(newPath) && (isDuplicate || newPath !== currentPath)) {\n\t\t// If the path with trailing slash already exists, add the path without trailing slash to the set of existing\n\t\t// paths to ensure it will be post-fixed.\n\t\texistingPaths.add(pageWithoutTrailingSlash)\n\n\t\t// Avoid breaking the slug by adding a copy suffix to the last segment.\n\t\tif (isLastSegmentSlug(pageWithoutTrailingSlash)) {\n\t\t\tpageWithoutTrailingSlash += \"/copy\"\n\t\t}\n\n\t\tpageWithoutTrailingSlash = uniqueName(pageWithoutTrailingSlash, existingPaths, {\n\t\t\twithDash: true,\n\t\t})\n\t}\n\treturn {\n\t\tpath: hasTrailingSlash ? `${pageWithoutTrailingSlash}/` : pageWithoutTrailingSlash,\n\t\tsuggestedName: pathToName(newPath),\n\t}\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert } from \"@framerjs/shared\"\nimport { convertReadablePathVariablesToIds } from \"document/components/utils/getUniquePagePath.ts\"\nimport type { AnyWebPageNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { RouteSegmentNode } from \"document/models/CanvasTree/nodes/RouteSegmentNode.ts\"\nimport type { RouteSegmentRootNode } from \"document/models/CanvasTree/nodes/RouteSegmentRootNode.ts\"\nimport { getRouteSegmentRootNode } from \"document/models/CanvasTree/nodes/RouteSegmentRootNode.utils.ts\"\nimport { isRouteSegmentNode, isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasPathVariableShape } from \"utils/pathVariables.ts\"\nimport { splitPathToSegmentsAndSlugify } from \"./commons.ts\"\n\nexport function createRouteSegment(\n\ttree: CanvasTree,\n\tcomponentLoader: AnyComponentLoader,\n\twebPageNode: AnyWebPageNode | undefined,\n\tdataIdentifier: ModuleExportIdentifierString | undefined,\n\tfullPath: string,\n\toptions?: {\n\t\tpositionInParent?: number\n\t},\n) {\n\tconst segments = splitPathToSegmentsAndSlugify(fullPath, isWebPageNode(webPageNode, true))\n\tassert(segments.length > 0, \"Path must have at least one segment\")\n\n\tlet currentParent: RouteSegmentRootNode | RouteSegmentNode = getRouteSegmentRootNode(tree)\n\tsegments.forEach((segment, index) => {\n\t\tconst isLastSegment = index === segments.length - 1\n\t\tconst positionInParent = isLastSegment ? options?.positionInParent : undefined\n\n\t\t// Only the :slug part of a collection detail page path hold a dataIdentifier\n\t\tconst dataIdentifierForSegment = hasPathVariableShape(segment) ? dataIdentifier : undefined\n\t\tif (dataIdentifierForSegment) {\n\t\t\tsegment = convertReadablePathVariablesToIds(dataIdentifierForSegment, segment, tree, componentLoader)\n\t\t}\n\n\t\tconst existingSegment: RouteSegmentNode | undefined = currentParent.children.find(node => node.segment === segment)\n\n\t\tconst addingWebPageToExistingSegment = existingSegment && isLastSegment && webPageNode\n\t\tif (!existingSegment || (addingWebPageToExistingSegment && existingSegment.webPageId)) {\n\t\t\t// In a rare case, the segment might already have a web page. For\n\t\t\t// example, you can have two collections with the identical name,\n\t\t\t// which allows you to create two index pages with the same path\n\t\t\t// (e.g. /blog). If one of the them already has a web page, we'll\n\t\t\t// create a new segment for the other one.\n\t\t\tconst newSegment = new RouteSegmentNode({\n\t\t\t\tsegment,\n\t\t\t\twebPageId: isLastSegment ? webPageNode?.id : undefined,\n\t\t\t\tdataIdentifier: dataIdentifierForSegment,\n\t\t\t})\n\n\t\t\ttree.insertNode(newSegment, currentParent.id, positionInParent)\n\t\t\tcurrentParent = newSegment\n\t\t} else if (addingWebPageToExistingSegment) {\n\t\t\texistingSegment.set({\n\t\t\t\twebPageId: webPageNode.id,\n\t\t\t\tdataIdentifier: dataIdentifierForSegment,\n\t\t\t})\n\t\t\tcurrentParent = existingSegment\n\t\t} else {\n\t\t\tcurrentParent = existingSegment\n\t\t}\n\t})\n\n\tassert(isRouteSegmentNode(currentParent), \"Current parent should be the created RouteSegmentNode\")\n\treturn currentParent\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { type CanvasTree, ContentManagementNode } from \"document/models/CanvasTree/index.ts\"\nimport { getContentManagementNode } from \"document/models/CanvasTree/nodes/ContentManagementNode.utils.ts\"\n\nexport function createContentManagementNodeIfNeeded(tree: CanvasTree): ContentManagementNode {\n\tconst existingContentManagementNode = getContentManagementNode(tree)\n\tif (existingContentManagementNode) {\n\t\t// FIXME If CMS Node will ever become shallow this code needs to be checked/updated\n\t\tassert(existingContentManagementNode.isLoaded(), \"ContentManagementNode should be loaded\")\n\t\treturn existingContentManagementNode\n\t}\n\tconst contentManagementNode = new ContentManagementNode()\n\ttree.insertNode(contentManagementNode, tree.root.id)\n\treturn contentManagementNode\n}\n", "// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n  if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n  const BASE_MAP = new Uint8Array(256)\n  for (let j = 0; j < BASE_MAP.length; j++) {\n    BASE_MAP[j] = 255\n  }\n  for (let i = 0; i < ALPHABET.length; i++) {\n    const x = ALPHABET.charAt(i)\n    const xc = x.charCodeAt(0)\n    if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n    BASE_MAP[xc] = i\n  }\n  const BASE = ALPHABET.length\n  const LEADER = ALPHABET.charAt(0)\n  const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n  const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n  function encode (source) {\n    // eslint-disable-next-line no-empty\n    if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n      source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n    } else if (Array.isArray(source)) {\n      source = Uint8Array.from(source)\n    }\n    if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n    if (source.length === 0) { return '' }\n    // Skip & count leading zeroes.\n    let zeroes = 0\n    let length = 0\n    let pbegin = 0\n    const pend = source.length\n    while (pbegin !== pend && source[pbegin] === 0) {\n      pbegin++\n      zeroes++\n    }\n    // Allocate enough space in big-endian base58 representation.\n    const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n    const b58 = new Uint8Array(size)\n    // Process the bytes.\n    while (pbegin !== pend) {\n      let carry = source[pbegin]\n      // Apply \"b58 = b58 * 256 + ch\".\n      let i = 0\n      for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n        carry += (256 * b58[it1]) >>> 0\n        b58[it1] = (carry % BASE) >>> 0\n        carry = (carry / BASE) >>> 0\n      }\n      if (carry !== 0) { throw new Error('Non-zero carry') }\n      length = i\n      pbegin++\n    }\n    // Skip leading zeroes in base58 result.\n    let it2 = size - length\n    while (it2 !== size && b58[it2] === 0) {\n      it2++\n    }\n    // Translate the result into a string.\n    let str = LEADER.repeat(zeroes)\n    for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n    return str\n  }\n  function decodeUnsafe (source) {\n    if (typeof source !== 'string') { throw new TypeError('Expected String') }\n    if (source.length === 0) { return new Uint8Array() }\n    let psz = 0\n    // Skip and count leading '1's.\n    let zeroes = 0\n    let length = 0\n    while (source[psz] === LEADER) {\n      zeroes++\n      psz++\n    }\n    // Allocate enough space in big-endian base256 representation.\n    const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n    const b256 = new Uint8Array(size)\n    // Process the characters.\n    while (psz < source.length) {\n      // Find code of next character\n      const charCode = source.charCodeAt(psz)\n      // Base map can not be indexed using char code\n      if (charCode > 255) { return }\n      // Decode character\n      let carry = BASE_MAP[charCode]\n      // Invalid character\n      if (carry === 255) { return }\n      let i = 0\n      for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n        carry += (BASE * b256[it3]) >>> 0\n        b256[it3] = (carry % 256) >>> 0\n        carry = (carry / 256) >>> 0\n      }\n      if (carry !== 0) { throw new Error('Non-zero carry') }\n      length = i\n      psz++\n    }\n    // Skip leading zeroes in b256.\n    let it4 = size - length\n    while (it4 !== size && b256[it4] === 0) {\n      it4++\n    }\n    const vch = new Uint8Array(zeroes + (size - it4))\n    let j = zeroes\n    while (it4 !== size) {\n      vch[j++] = b256[it4++]\n    }\n    return vch\n  }\n  function decode (string) {\n    const buffer = decodeUnsafe(string)\n    if (buffer) { return buffer }\n    throw new Error('Non-base' + BASE + ' character')\n  }\n  return {\n    encode,\n    decodeUnsafe,\n    decode\n  }\n}\nexport default base\n", "import basePackage from \"base-x\"\n\ntype BaseXFunction = typeof basex\n\n// This is a wrapper around the base-x package to make sure it works with CommonJS and ES Modules.\n// It was created to support the ai-evals (see esbuild/ai-evals.mjs) that are using CommonJS.\nexport function basex(alphabet: string): basePackage.BaseConverter {\n\tconst base: BaseXFunction =\n\t\ttypeof basePackage === \"function\" ? basePackage : (basePackage as unknown as { default: BaseXFunction }).default\n\n\treturn base(alphabet)\n}\n", "import { basex } from \"./baseX.ts\"\n\n// https://en.wikipedia.org/wiki/Base62\nconst BASE_62_ALPHABET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\nconst BASE_62_CONVERTER = basex(BASE_62_ALPHABET)\n\n/** This is the number of bits that fit into a single output character. */\nconst MAX_LENGTH_MULTIPLIER = 8 / Math.log2(62)\n\n/**\n * Compatible with `sha256`. Zero-padded to the length of a `0xFF`-filled byte\n * array of the same length as `byteArray`. See the tests for examples.\n */\nexport const encodeByteArrayToBase62 = (byteArray: Uint8Array): string =>\n\tBASE_62_CONVERTER.encode(byteArray).padStart(Math.ceil(byteArray.length * MAX_LENGTH_MULTIPLIER), \"0\")\n\nexport const randomBase62 = (length: number = 20): string =>\n\tArray(length)\n\t\t.fill(0)\n\t\t.map(() => BASE_62_ALPHABET[Math.floor(Math.random() * BASE_62_ALPHABET.length)])\n\t\t.join(\"\")\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, getLogger, isEditorBar } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { EngineStores } from \"document/EngineStores.ts\"\nimport type { LayoutCache, LayoutTemplateDOMInfo } from \"document/LayoutCache.ts\"\nimport type { SandboxRepeaterData } from \"document/SandboxRepeaterData.ts\"\nimport type { SandboxVisibility } from \"document/SandboxVisibility.ts\"\nimport type { EffectPreviewState } from \"document/utils/EffectPreviewType.ts\"\nimport {\n\ttype RenderId,\n\tgetChildRenderId,\n\tgetRepeatedChildRenderId,\n\tisPrimaryRenderId,\n} from \"document/utils/RenderId.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport { isEqual } from \"library/render/utils/isEqual.ts\"\nimport { isShallowEqual } from \"utils/isShallowEqual.ts\"\nimport { isRepeatedItem } from \"utils/repeaterUtils.ts\"\nimport { isSet } from \"utils/typeChecks.ts\"\nimport type { CanvasTree } from \"./CanvasTree/CanvasTree.ts\"\nimport type { RootNode } from \"./CanvasTree/index.ts\"\nimport type { CanvasNode } from \"./CanvasTree/nodes/CanvasNode.ts\"\nimport type {\n\tBoundingBox,\n\tLayoutTemplateRenderCacheBySelector,\n\tRenderInstanceCache,\n} from \"./CanvasTree/nodes/CanvasNodeCache.ts\"\nimport type { MaybeNodeID, NodeID } from \"./CanvasTree/nodes/NodeID.ts\"\nimport type { ScopeNode } from \"./CanvasTree/nodes/ScopeNode.ts\"\nimport { isScopeNode } from \"./CanvasTree/nodes/ScopeNode.ts\"\nimport { isDataRepeater, isOverlayNode, isSlotPropertyNode, isWebPageNode } from \"./CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isFixedOrRelativeOverlay } from \"./CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport type {\n\tCombinedVariableProviderControlMap,\n\tCombinedVariableProviderValueMap,\n} from \"./CanvasTree/traits/VariableProvider.ts\"\nimport { withDOMLayout } from \"./CanvasTree/traits/WithDOMLayout.ts\"\nimport { hasFlowEffect } from \"./CanvasTree/traits/WithFlowEffect.ts\"\nimport {\n\ttype GridRowHeightType,\n\ttype LayoutType,\n\thasAnyLayout,\n\thasGridLayout,\n\twithLayout,\n} from \"./CanvasTree/traits/WithLayout.ts\"\nimport { getLayoutTemplateForBreakpoint } from \"./CanvasTree/traits/WithLayoutTemplate.ts\"\nimport type { Locale, LocaleId } from \"./CanvasTree/traits/WithLocales.ts\"\nimport { isLockedOrLockedByParent } from \"./CanvasTree/traits/WithLock.ts\"\nimport { isPinnable } from \"./CanvasTree/traits/WithPins.ts\"\nimport { hasRepeatArray } from \"./CanvasTree/traits/WithRepeatArray.ts\"\nimport { withShape } from \"./CanvasTree/traits/WithShape.ts\"\nimport { withStroke } from \"./CanvasTree/traits/WithStroke.ts\"\nimport { isHiddenMaster, isMaster, isReplica } from \"./CanvasTree/traits/WithTemplate.ts\"\nimport { hasTickerEffect } from \"./CanvasTree/traits/WithTickerEffect.ts\"\nimport { DEFAULT_ORIGIN, creates3dContext } from \"./CanvasTree/traits/WithTransforms.ts\"\nimport { isBreakpointVariant, isVariant } from \"./CanvasTree/traits/WithVariant.ts\"\nimport { isFormContainer } from \"./CanvasTree/traits/forms/WithFormContainer.ts\"\nimport { isPositionRelative } from \"./CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport type { ViewportCacheContext } from \"./CanvasTree/traits/utils/viewportHelpers.ts\"\nimport {\n\tcanNodeProvideViewportRect,\n\tcreateCacheContext,\n\tviewportRectForCacheContext,\n} from \"./CanvasTree/traits/utils/viewportHelpers.ts\"\nimport { convertCornerPointsToCanvas } from \"./CanvasTree/utils/geometry.ts\"\nimport { Matrix } from \"./Matrix.ts\"\n\ntype ParentRectByRenderId = Map<RenderId, Rect>\ntype ParentMatrixByRenderId = Map<RenderId, DOMMatrixReadOnly>\n\nconst log = getLogger(\"update-tree-cache-for-vekter\")\n\nfunction isIncluded(id: NodeID, included: NodeID | Set<NodeID>): boolean {\n\tif (!included) return true\n\tif (isSet(included)) return included.has(id)\n\treturn included === id\n}\n\nconst NO_DATA_REPEATER_ANCESTORS: NodeID[] = []\nObject.freeze(NO_DATA_REPEATER_ANCESTORS)\n\nconst NO_REPEATER_ITEM_ANCESTORS: NodeID[] = []\nObject.freeze(NO_REPEATER_ITEM_ANCESTORS)\n\nfunction shouldSkipLegacyDataRepeaterRepeatedChild(node: CanvasNode): boolean {\n\treturn hasRepeatArray(node)\n}\n\nfunction getAncestorMatrix(\n\tnode: CanvasNode,\n\tparentRect: Rect | undefined,\n\tparentMatrix: DOMMatrixReadOnly | undefined,\n\tgroundMatrix: DOMMatrixReadOnly | undefined,\n) {\n\tif (!isFixedOrRelativeOverlay(node)) return parentMatrix ?? Matrix.identity()\n\tif (isOverlayNode(node)) return groundMatrix ?? parentMatrix ?? Matrix.identity()\n\n\t// If a floating layer becomes a ground node we should just render it\n\t// normally.\n\tif (!parentMatrix || !parentRect) return Matrix.identity()\n\n\t// A relative overlay is positioned (and measured) relative to its parent's\n\t// bounding client rect. Other transforms on the parent (like rotation)\n\t// should not be propagated to the overlay. Thus when we encounter a\n\t// relative overlay, we create a fresh matrix containing only the\n\t// translation enough to determine the parent bounding box.\n\treturn Matrix.boundingRectMatrix(parentMatrix, parentRect)\n}\n\nexport function updateTreeCacheForVekter(\n\ttree: CanvasTree,\n\tlayoutCache: LayoutCache,\n\tsandboxRepeaterData: SandboxRepeaterData,\n\tsandboxVisibility: SandboxVisibility,\n\tcomponentLoader: ComponentLoader,\n\tcomponentLoaderHash: string | undefined,\n\tactiveLocaleId: LocaleId | undefined,\n\teffectPreviewState: EffectPreviewState | undefined,\n\tscopeId?: NodeID | Set<NodeID>,\n): CanvasTree {\n\tconst root = tree.root\n\tconst cache = root.cache\n\tconst activeLocale = root.getLocale(activeLocaleId)\n\tcache.visible = true\n\tcache.lockedByParent = false\n\tcache.renderId = root.id\n\tresetBoundingBox(cache)\n\tconst children = root.children\n\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tassert(!root.mutable, \"Node should not be mutable when updating cache\")\n\t}\n\n\tfor (const child of children) {\n\t\tif (scopeId && !isIncluded(child.id, scopeId)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isScopeNode(child)) {\n\t\t\tif (!child.isLoaded()) continue\n\n\t\t\tupdateScopeNodeCache(\n\t\t\t\ttree,\n\t\t\t\tchild,\n\t\t\t\troot,\n\t\t\t\tlayoutCache,\n\t\t\t\tsandboxRepeaterData,\n\t\t\t\tsandboxVisibility,\n\t\t\t\tcomponentLoader,\n\t\t\t\tcomponentLoaderHash,\n\t\t\t\tactiveLocale,\n\t\t\t\teffectPreviewState,\n\t\t\t)\n\t\t} else {\n\t\t\tupdateVekterNodeCache(\n\t\t\t\ttree,\n\t\t\t\tchild,\n\t\t\t\troot,\n\t\t\t\tfalse,\n\t\t\t\ttrue,\n\t\t\t\tfalse,\n\t\t\t\tnew Map(),\n\t\t\t\tnew Map(),\n\t\t\t\tfalse,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tNO_DATA_REPEATER_ANCESTORS,\n\t\t\t\tNO_REPEATER_ITEM_ANCESTORS,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tlayoutCache,\n\t\t\t\tsandboxRepeaterData,\n\t\t\t\tsandboxVisibility,\n\t\t\t\tcomponentLoader,\n\t\t\t\tcomponentLoaderHash,\n\t\t\t\tactiveLocale,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\teffectPreviewState,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t}\n\n\t\textendBoundingBoxes(root, child)\n\t}\n\treturn tree\n}\n\nexport function updateTreeCacheForVekterWithStores(\n\tcomponentLoader: ComponentLoader,\n\tstores: EngineStores,\n\tscopeId?: NodeID | Set<NodeID>,\n) {\n\treturn updateTreeCacheForVekter(\n\t\tstores.treeStore.getDataTreeOrPartialTree(),\n\t\tstores.layoutCache,\n\t\tstores.treeStore.sandboxRepeaterData,\n\t\tstores.treeStore.sandboxVisibility,\n\t\tcomponentLoader,\n\t\tcomponentLoader.activeBundleHash,\n\t\tstores.chromeStore.canvasLocaleId,\n\t\tstores.effectStore.getState(),\n\t\tscopeId,\n\t)\n}\n\nfunction updateScopeNodeCache(\n\ttree: CanvasTree,\n\tnode: ScopeNode,\n\tparent: RootNode,\n\tlayoutCache: LayoutCache,\n\tsandboxRepeaterData: SandboxRepeaterData,\n\tsandboxVisibility: SandboxVisibility,\n\tcomponentLoader: ComponentLoader,\n\tcomponentLoaderHash: string | undefined,\n\tactiveLocale: Locale | undefined,\n\teffectPreviewState: EffectPreviewState | undefined,\n) {\n\tconst cache = node.cache\n\tcache.visible = true\n\tcache.lockedByParent = false\n\tcache.renderId = node.id\n\tcache.parentRenderId = parent.id\n\tresetBoundingBox(cache)\n\tconst children = node.children\n\tconst { combinedVariableValueMap, combinedVariableControlMap } = node.combineVariableValueAndControlMaps(\n\t\ttree,\n\t\tundefined,\n\t\tundefined,\n\t\tundefined,\n\t\tcomponentLoader,\n\t\tsandboxRepeaterData,\n\t\tcomponentLoaderHash,\n\t\tactiveLocale,\n\t)\n\n\tconst isWebPage = isWebPageNode(node)\n\tfor (const child of children) {\n\t\tupdateVekterNodeCache(\n\t\t\ttree,\n\t\t\tchild,\n\t\t\tnode,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\tnew Map(),\n\t\t\tnew Map(),\n\t\t\tfalse,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tNO_DATA_REPEATER_ANCESTORS,\n\t\t\tNO_REPEATER_ITEM_ANCESTORS,\n\t\t\tcombinedVariableValueMap,\n\t\t\tcombinedVariableControlMap,\n\t\t\tlayoutCache,\n\t\t\tsandboxRepeaterData,\n\t\t\tsandboxVisibility,\n\t\t\tcomponentLoader,\n\t\t\tcomponentLoaderHash,\n\t\t\tactiveLocale,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\teffectPreviewState,\n\t\t\tisWebPage,\n\t\t)\n\t\textendBoundingBoxes(node, child)\n\t}\n}\n\ninterface GroundNodeContext extends ViewportCacheContext {\n\tgroundNodeId: MaybeNodeID\n\tgroundNodeMatrix: DOMMatrixReadOnly\n}\n\nfunction updateVekterNodeCache(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tparent: CanvasNode,\n\tinsideVariant: boolean,\n\tparentVisible: boolean,\n\tparentLocked: boolean,\n\tparentRectByRenderId: ParentRectByRenderId,\n\tparentMatrixByRenderId: ParentMatrixByRenderId,\n\tparentUsesDOMRect: boolean,\n\tmasterAncestorId: MaybeNodeID,\n\treplicaAncestorId: MaybeNodeID,\n\toverlayAncestorId: MaybeNodeID,\n\tslotPropertyAncestorId: MaybeNodeID,\n\tformContainerAncestorId: MaybeNodeID,\n\ttickerAncestorId: MaybeNodeID,\n\tflowEffectAncestorId: MaybeNodeID,\n\tdataRepeaterAncestorIds: NodeID[],\n\tdataRepeaterItemAncestorIds: NodeID[],\n\tinheritedVariableValueMap: CombinedVariableProviderValueMap | undefined,\n\tinheritedVariableControlMap: CombinedVariableProviderControlMap | undefined,\n\tlayoutCache: LayoutCache,\n\tsandboxRepeaterData: SandboxRepeaterData,\n\tsandboxVisibility: SandboxVisibility,\n\tcomponentLoader: ComponentLoader,\n\tcomponentLoaderHash: string | undefined,\n\tactiveLocale: Locale | undefined,\n\tgroundNodeContext: GroundNodeContext | undefined,\n\tparentDirectedLayout: LayoutType | undefined,\n\tparentDirectedRowHeightType: GridRowHeightType | undefined,\n\teffectPreview: EffectPreviewState | undefined,\n\tisWebPage: boolean | undefined,\n): void {\n\tconst cache = node.cache\n\n\t// Already updating the active locale here because it's value can impact visibility\n\tconst previousActiveLocale = cache.activeVekterLocale\n\tcache.activeVekterLocale = activeLocale\n\n\tconst { combinedVariableMapsAreEqual } = node.combineVariableValueAndControlMaps(\n\t\ttree,\n\t\tundefined,\n\t\tinheritedVariableValueMap,\n\t\tinheritedVariableControlMap,\n\t\tcomponentLoader,\n\t\tsandboxRepeaterData,\n\t\tcomponentLoaderHash,\n\t\tactiveLocale,\n\t)\n\n\tconst nodeIsDataRepeater = isDataRepeater(node)\n\t/** Collection is empty, or entirely filtered out */\n\tconst repeaterIsEmpty = nodeIsDataRepeater ? sandboxRepeaterData.isEmpty(node.id) : false\n\n\tconst [primaryRenderInstance, secondaryRenderInstances] = getRenderInstances(\n\t\ttree,\n\t\tnode,\n\t\tparent,\n\t\tparentRectByRenderId,\n\t\tparentMatrixByRenderId,\n\t\tlayoutCache,\n\t\tsandboxRepeaterData,\n\t\tsandboxVisibility,\n\t)\n\n\tcache.groundNodeAncestorId = groundNodeContext?.groundNodeId\n\tcache.masterAncestorId = masterAncestorId\n\tcache.replicaAncestorId = replicaAncestorId\n\tcache.overlayAncestorId = overlayAncestorId\n\tcache.formContainerAncestorId = formContainerAncestorId\n\tcache.tickerAncestorId = tickerAncestorId\n\n\tconst visible = parentVisible && !!primaryRenderInstance\n\n\tconst groundNodeMatrixSame =\n\t\t!groundNodeContext || Matrix.equals(cache.groundNodeMatrix, groundNodeContext.groundNodeMatrix)\n\tconst hasSameLayout = !withLayout(node) || cache.layout === node.layout\n\tconst hasSameLocale = previousActiveLocale === cache.activeVekterLocale\n\tconst viewportRect = viewportRectForCacheContext(node, groundNodeContext)\n\n\tconst isInEffectPreview = !!effectPreview?.nodes.has(node.id)\n\tconst effectPreviewSame =\n\t\tisInEffectPreview === cache.isEffectPreview &&\n\t\tisEqual(effectPreview?.effectIds ?? null, cache.effectIds) &&\n\t\t(effectPreview?.type ?? null) === cache.effectType &&\n\t\tcache.webPageEffect === isWebPage\n\n\t// Variants (Webpage or Smart Component variants) can provide viewports. If\n\t// the layer can provide a viewport, we can't, and don't need to create a\n\t// viewport rect to compare to the cached rect. The only way the\n\t// viewportHeight of this rect can change is if the variant node's own\n\t// CanvasNode.viewportHeight property changes. If that has changed\n\t// cache.lastUpdate will also have changed and we will invalidate the cache\n\t// for us. For all other nodes, we can create a viewportRect and compare\n\t// that it hasn't changed.\n\tconst viewportSame = canNodeProvideViewportRect(node) || Rect.equals(cache.viewportRect, viewportRect)\n\n\tinsideVariant ||= isVariant(node)\n\n\tconst hasSameProperties =\n\t\thasSameLayout &&\n\t\thasSameLocale &&\n\t\tviewportSame &&\n\t\teffectPreviewSame &&\n\t\tcombinedVariableMapsAreEqual &&\n\t\tcache.insideVariant === insideVariant &&\n\t\tcache.visible === visible &&\n\t\tcache.repeaterIsEmpty === repeaterIsEmpty &&\n\t\tcache.lockedByParent === parentLocked &&\n\t\tcache.lastUpdate === node.update &&\n\t\tcache.parentDirected === parentDirectedLayout &&\n\t\tcache.parentDirectedRowHeightType === parentDirectedRowHeightType &&\n\t\tcache.flowEffectAncestorId === flowEffectAncestorId &&\n\t\tcache.tickerAncestorId === tickerAncestorId &&\n\t\tcanReuseRenderInstance(node.cache.getRenderInstance(node.id), primaryRenderInstance) &&\n\t\tcanReuseSecondaryRenderInstances(node.cache.secondaryRenderInstances, secondaryRenderInstances) &&\n\t\tgetLayoutTemplateForBreakpoint(tree, node) === cache.usesLayoutTemplateRectForModuleIdentifier\n\n\tconst same = hasSameProperties && groundNodeMatrixSame\n\tif (same) return\n\n\tcache.isEffectPreview = isInEffectPreview\n\tcache.effectIds = effectPreview?.effectIds ?? null\n\tcache.effectType = effectPreview?.type ?? null\n\tcache.webPageEffect = isWebPage\n\tcache.ancestorRepeaterIds = dataRepeaterAncestorIds\n\tcache.repeatedAncestorRepeaterIds = dataRepeaterItemAncestorIds\n\n\tconst perf = process.env.NODE_ENV !== \"production\" && window.perf\n\tif (perf) perf.cacheUpdated()\n\n\tif (!hasSameProperties) {\n\t\tif (perf) perf.cacheReset()\n\n\t\tcache.reset()\n\t\tcache.groundNodeAncestorId = groundNodeContext?.groundNodeId\n\t\tcache.masterAncestorId = masterAncestorId\n\t\tcache.replicaAncestorId = replicaAncestorId\n\t\tcache.overlayAncestorId = overlayAncestorId\n\t\tcache.slotPropertyAncestorId = slotPropertyAncestorId\n\t\tcache.formContainerAncestorId = formContainerAncestorId\n\t\tcache.tickerAncestorId = tickerAncestorId\n\t\tcache.flowEffectAncestorId = flowEffectAncestorId\n\n\t\tcache.activeVekterLocale = activeLocale\n\t\tcache.visible = visible\n\t\tcache.repeaterIsEmpty = repeaterIsEmpty\n\t\tcache.insideVariant = insideVariant\n\t\tcache.lockedByParent = parentLocked\n\t\tcache.lastUpdate = node.update\n\t\tcache.parentDirected = parentDirectedLayout\n\t\tcache.parentDirectedRowHeightType = parentDirectedRowHeightType\n\t\tcache.viewportRect = viewportRect\n\t\tcache.layout = withLayout(node) ? node.layout : undefined\n\t\tcache.ancestorRepeaterIds = dataRepeaterAncestorIds\n\t\tcache.repeatedAncestorRepeaterIds = dataRepeaterItemAncestorIds\n\t\tcache.usesLayoutTemplateRectForModuleIdentifier = withDOMLayout(node)\n\t\t\t? node.usesLayoutTemplateRectForModuleIdentifier()\n\t\t\t: undefined\n\n\t\tif (primaryRenderInstance) {\n\t\t\tcache.renderId = node.id\n\t\t\tObject.assign(cache, primaryRenderInstance)\n\t\t}\n\n\t\tcache.secondaryRenderInstances = secondaryRenderInstances\n\t} else {\n\t\tcache.canvasRect = undefined\n\t}\n\n\tconst {\n\t\tparentRectByRenderIdForChildren,\n\t\tparentMatrixByRenderIdForChildren,\n\t\tparentUsesDOMRectForChildren,\n\t\tgroundNodeContextForChildren,\n\t} = updateNodeLayoutCache(tree, node, parentUsesDOMRect, groundNodeContext, layoutCache)\n\n\tconst children = node.children\n\tif (!children) return\n\n\tconst nodeLayout = hasAnyLayout(node) ? node.layout : undefined\n\tconst nodeGridRowHeightType = hasGridLayout(node) ? node.gridRowHeightType : undefined\n\n\tlet masterId = masterAncestorId\n\tif (!masterId && isMaster(node)) masterId = node.id\n\n\tlet replicaId = replicaAncestorId\n\tif (!replicaId && isReplica(node)) replicaId = node.id\n\n\tconst descendantRepeaterIds = nextDescendantRepeaterIds(node, dataRepeaterAncestorIds)\n\n\tfor (const child of children) {\n\t\tif (!hasSameLayout) {\n\t\t\tfor (const [, renderInstance] of child.cache.iterateRenderInstances()) {\n\t\t\t\trenderInstance.parentRect = undefined\n\t\t\t}\n\t\t}\n\n\t\t// Handle the selectable/non-selectable variations of repeated children\n\t\tconst childIsRepeatedItem =\n\t\t\tnodeIsDataRepeater && isRepeatedItem(tree, child, node) && !shouldSkipLegacyDataRepeaterRepeatedChild(child)\n\t\tconst repeatedChildHidden = childIsRepeatedItem && repeaterIsEmpty\n\t\t/**\n\t\t * While the parent may or may not be visible, we can treat it as not-visible to force not-visible on the child.\n\t\t * Should only be overridden from visible -> not-visible, not the other way round\n\t\t */\n\t\tconst isVisibleAndNonHiddenCollectionContent = experiments.isOn(\"visibilityFromSandbox\")\n\t\t\t? visible\n\t\t\t: childIsRepeatedItem\n\t\t\t\t? !repeatedChildHidden && visible\n\t\t\t\t: visible\n\n\t\tconst {\n\t\t\tcombinedVariableControlMap: childCombinedVariableControlMap,\n\t\t\tcombinedVariableValueMap: childCombinedVariableValueMap,\n\t\t} = node.combineVariableValueAndControlMaps(\n\t\t\ttree,\n\t\t\tchild,\n\t\t\tinheritedVariableValueMap,\n\t\t\tinheritedVariableControlMap,\n\t\t\tcomponentLoader,\n\t\t\tsandboxRepeaterData,\n\t\t\tcomponentLoaderHash,\n\t\t\tactiveLocale,\n\t\t)\n\n\t\tupdateVekterNodeCache(\n\t\t\ttree,\n\t\t\tchild,\n\t\t\tnode,\n\t\t\tinsideVariant,\n\t\t\tisVisibleAndNonHiddenCollectionContent,\n\t\t\tisLockedOrLockedByParent(node),\n\t\t\tparentRectByRenderIdForChildren,\n\t\t\tparentMatrixByRenderIdForChildren,\n\t\t\tparentUsesDOMRectForChildren,\n\t\t\tmasterId,\n\t\t\treplicaId,\n\t\t\tisFixedOrRelativeOverlay(node) ? node.id : overlayAncestorId,\n\t\t\tisSlotPropertyNode(node) ? node.id : slotPropertyAncestorId,\n\t\t\tisFormContainer(node) ? node.id : formContainerAncestorId,\n\t\t\thasTickerEffect(node) ? node.id : tickerAncestorId,\n\t\t\thasFlowEffect(node) ? node.id : flowEffectAncestorId,\n\t\t\tdescendantRepeaterIds,\n\t\t\tchildIsRepeatedItem ? nextDescendantRepeaterIds(node, dataRepeaterItemAncestorIds) : dataRepeaterItemAncestorIds,\n\t\t\tchildCombinedVariableValueMap,\n\t\t\tchildCombinedVariableControlMap,\n\t\t\tlayoutCache,\n\t\t\tsandboxRepeaterData,\n\t\t\tsandboxVisibility,\n\t\t\tcomponentLoader,\n\t\t\tcomponentLoaderHash,\n\t\t\tactiveLocale,\n\t\t\tgroundNodeContextForChildren,\n\t\t\tnodeLayout,\n\t\t\tnodeGridRowHeightType,\n\t\t\teffectPreview,\n\t\t\tisWebPage,\n\t\t)\n\n\t\textendBoundingBoxes(node, child)\n\t}\n}\n\n/**\n * This is the same as the updateTreeCacheForVekter function, except it only\n * changes layout-related cached properties, and doesn't reset the cache.\n */\nexport function updateTreeCacheWithLatestDOMLayout(\n\ttree: CanvasTree,\n\tlayoutCache: LayoutCache,\n\tchangedNodeIds: Set<NodeID>,\n) {\n\tconst affectedNodeIds = buildAffectedNodesAndAncestorsSet(tree, changedNodeIds)\n\n\tconst root = tree.root\n\tconst cache = root.cache\n\tcache.visible = true\n\tcache.renderId = root.id\n\tresetBoundingBox(cache)\n\tconst children = root.children\n\tfor (const child of children) {\n\t\tif (isScopeNode(child)) {\n\t\t\tif (!child.isLoaded()) continue\n\t\t\tupdateCanvasScopeCacheWithLatestDOMLayout(tree, child, root, layoutCache, affectedNodeIds)\n\t\t} else {\n\t\t\tupdateNodeCacheWithLatestDOMLayout(\n\t\t\t\ttree,\n\t\t\t\tchild,\n\t\t\t\troot,\n\t\t\t\tnew Map(),\n\t\t\t\tnew Map(),\n\t\t\t\tfalse,\n\t\t\t\tlayoutCache,\n\t\t\t\taffectedNodeIds,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t}\n\t\textendBoundingBoxes(root, child)\n\t}\n\treturn affectedNodeIds\n}\n\n/**\n * Expands a set of node IDs to include all nodes on the path to those nodes, as\n * well as all nodes that are descendants of the affected nodes. Useful when we\n * need to update the tree cache with new layout measurements, which should also\n * update parentRects, matrices and other related values for all descendants.\n *\n * @param tree the tree\n * @param affectedNodeIds a set IDs of the affected nodes\n */\nexport function buildAffectedNodesAndAncestorsSet(tree: CanvasTree, affectedNodeIds: Set<NodeID>) {\n\tconst nodes = new Set<NodeID>()\n\tconst nodesWithExhaustedDescendants = new Set<NodeID>()\n\n\tfunction addDescendants(node: CanvasNode) {\n\t\t// we don't need to go down branches we've seen before\n\t\tif (nodesWithExhaustedDescendants.has(node.id)) return\n\t\tnodes.add(node.id)\n\t\tnodesWithExhaustedDescendants.add(node.id)\n\n\t\tif (!node.children) return\n\t\tnode.children.forEach(addDescendants)\n\t}\n\n\tfunction addAncestors(node: CanvasNode) {\n\t\tlet id: string | null | undefined = node.id\n\n\t\twhile (id && !nodes.has(id)) {\n\t\t\tnodes.add(id)\n\t\t\tconst current: CanvasNode | null = tree.getNode(id)\n\t\t\tid = current?.parentid\n\t\t}\n\t}\n\n\tfor (const id of affectedNodeIds) {\n\t\tconst affectedNode = tree.getNode(id)\n\n\t\tif (affectedNode) {\n\t\t\taddAncestors(affectedNode)\n\n\t\t\t// if the layout of this node changes, all of its children will also need to have\n\t\t\t// their matrices recalculated since they depend on the parent matrix\n\t\t\tif (affectedNode.children) {\n\t\t\t\taffectedNode.children.forEach(addDescendants)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nodes\n}\n\nexport function nextDescendantRepeaterIds(node: CanvasNode, ancestorRepeaterIds: NodeID[]) {\n\tif (isDataRepeater(node)) {\n\t\tif (ancestorRepeaterIds.length === 0) return [node.id]\n\t\treturn [...ancestorRepeaterIds, node.id]\n\t}\n\treturn ancestorRepeaterIds\n}\n\nfunction updateCanvasScopeCacheWithLatestDOMLayout(\n\ttree: CanvasTree,\n\tnode: ScopeNode,\n\tparent: RootNode,\n\tlayoutCache: LayoutCache,\n\taffectedNodeIds: Set<NodeID>,\n) {\n\tconst cache = node.cache\n\tcache.visible = true\n\tcache.renderId = node.id\n\tcache.parentRenderId = parent.id\n\tresetBoundingBox(cache)\n\tconst children = node.children\n\tfor (const child of children) {\n\t\tupdateNodeCacheWithLatestDOMLayout(\n\t\t\ttree,\n\t\t\tchild,\n\t\t\tnode,\n\t\t\tnew Map(),\n\t\t\tnew Map(),\n\t\t\tfalse,\n\t\t\tlayoutCache,\n\t\t\taffectedNodeIds,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t)\n\t\textendBoundingBoxes(node, child)\n\t}\n}\n\nfunction updateNodeCacheWithLatestDOMLayout(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tparent: CanvasNode,\n\tparentRectByRenderId: ParentRectByRenderId,\n\tparentMatrixByRenderId: ParentMatrixByRenderId,\n\tparentUsesDOMRect: boolean,\n\tlayoutCache: LayoutCache,\n\taffectedNodeIds: Set<NodeID>,\n\tparentDirectedLayout: LayoutType | undefined,\n\tparentDirectedRowHeightType: GridRowHeightType | undefined,\n\tgroundNodeContext: GroundNodeContext | undefined,\n): void {\n\tif (!affectedNodeIds.has(node.id)) return\n\n\tconst cache = node.cache\n\n\tcache.parentDirected = parentDirectedLayout\n\tcache.parentDirectedRowHeightType = parentDirectedRowHeightType\n\n\tcache.viewportRect = viewportRectForCacheContext(node, groundNodeContext)\n\t// cache.visible is already set by the pre-render cache update\n\tif (!cache.visible) return\n\n\tfor (const [renderId, renderInstance] of cache.iterateRenderInstances()) {\n\t\tconst parentRenderId = renderInstance.parentRenderId\n\t\tassert(parentRenderId, \"Missing `parentRenderId`\")\n\n\t\trenderInstance.parentRect = parentRectByRenderId.get(parentRenderId)\n\t\trenderInstance.parentMatrix = parentMatrixByRenderId.get(parentRenderId)\n\t\trenderInstance.parentDirectedRect = getParentDirectedRect(node, renderId, parent, layoutCache)\n\t}\n\n\tconst {\n\t\tparentRectByRenderIdForChildren,\n\t\tparentMatrixByRenderIdForChildren,\n\t\tparentUsesDOMRectForChildren,\n\t\tgroundNodeContextForChildren,\n\t} = updateNodeLayoutCache(tree, node, parentUsesDOMRect, groundNodeContext, layoutCache)\n\n\tconst children = node.children\n\tif (!children) return\n\n\tconst nodeLayout = hasAnyLayout(node) ? node.layout : undefined\n\tconst nodeGridRowHeightType = hasGridLayout(node) ? node.gridRowHeightType : undefined\n\n\tfor (const child of children) {\n\t\tupdateNodeCacheWithLatestDOMLayout(\n\t\t\ttree,\n\t\t\tchild,\n\t\t\tnode,\n\t\t\tparentRectByRenderIdForChildren,\n\t\t\tparentMatrixByRenderIdForChildren,\n\t\t\tparentUsesDOMRectForChildren,\n\t\t\tlayoutCache,\n\t\t\taffectedNodeIds,\n\t\t\tnodeLayout,\n\t\t\tnodeGridRowHeightType,\n\t\t\tgroundNodeContextForChildren,\n\t\t)\n\t\textendBoundingBoxes(node, child)\n\t}\n}\n\nfunction updateLayoutTemplateRenderCache(\n\tnode: CanvasNode,\n\trects: Map<string, LayoutTemplateDOMInfo> | undefined,\n): LayoutTemplateRenderCacheBySelector | undefined {\n\tif (!rects || !isPinnable(node) || !isBreakpointVariant(node)) return undefined\n\tconst result: LayoutTemplateRenderCacheBySelector = new Map()\n\n\tfor (const [layoutTemplateSelector, rect] of rects) {\n\t\tconst originX = rect.originX ?? DEFAULT_ORIGIN * rect.width\n\t\tconst originY = rect.originY ?? DEFAULT_ORIGIN * rect.height\n\n\t\tlet groundMatrix = Matrix.identity()\n\n\t\t// skip ground node translation in on-page editing to avoid coordinate offsets\n\t\tif (!isEditorBar()) {\n\t\t\tgroundMatrix = groundMatrix.translate(node.left ?? 0, node.top ?? 0)\n\t\t}\n\n\t\tconst selectorMatrix = groundMatrix\n\t\t\t.translate(originX, originY)\n\t\t\t.multiplySelf(Matrix.identity().translate(rect.x, rect.y).multiplySelf(rect.matrix))\n\t\t\t.translateSelf(-originX, -originY)\n\n\t\tconst canvasCorners = Matrix.convertPointsWithClipping(\n\t\t\tselectorMatrix,\n\t\t\tRect.pointsAtOrigin({ width: rect.width, height: rect.height }),\n\t\t)\n\n\t\tresult.set(layoutTemplateSelector, {\n\t\t\tdomRect: rect,\n\t\t\tcanvasCorners,\n\t\t\tcanvasRect: Rect.boundingRectFromPoints(canvasCorners),\n\t\t})\n\t}\n\n\treturn result\n}\n\nfunction updateNodeLayoutCache(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tparentUsesDOMRect: boolean,\n\tgroundNodeContext: GroundNodeContext | undefined,\n\tlayoutCache: LayoutCache,\n) {\n\tconst cache = node.cache\n\n\tconst domRects = layoutCache.getRects(node.id)\n\tif (domRects) {\n\t\tcache.domRects = new Map(domRects)\n\t}\n\n\tconst usesLayoutTemplateRect = withDOMLayout(node) && Boolean(cache.usesLayoutTemplateRectForModuleIdentifier)\n\tif (usesLayoutTemplateRect) {\n\t\tcache.layoutTemplateRects = updateLayoutTemplateRenderCache(node, layoutCache.getLayoutTemplateRects(node.id))\n\t}\n\n\tcache.groundNodeMatrix = groundNodeContext?.groundNodeMatrix ?? null\n\n\t// Nodes contained in DOMRect-using nodes should not use pixelAligned rects\n\t// when constructing their matrix. This is because rect()'s pixel-aligning\n\t// works on the top/left coordinate, and the actual HTML element might be\n\t// positioned using a top/right absolute position, depending on pinning, so\n\t// its resolved top/left coordinate might be on a subpixel. When this\n\t// happens, pixel-aligning will lead to outlines falling out of sync.\n\t// For an example, see: https://github.com/framer/company/issues/20267\n\tconst usesDOMRect = withDOMLayout(node) && node.usesDOMRectCached()\n\tconst pixelAlign = !(usesDOMRect || parentUsesDOMRect)\n\n\t// We've already set the parentRect on the node cache. When we use\n\t// `getParentRectForSizing/Positioning`, we won't be doing extra work, and\n\t// will reuse the cached rect if the parent rect is the correct one. This\n\t// allows us to keep our logic about when to use a viewport rect vs a parent\n\t// rect consolidated.\n\t//\n\t// We don't allow a node that provides a viewport rect (variants) to use the\n\t// cache (realistically only variant ground nodes), because they always need\n\t// to compute their viewportRect, and can never rely on a cache value since\n\t// it won't exist yet, as it requires the rect of the node itself, which we\n\t// get here.\n\tconst allowCache = !!cache.viewportRect || !canNodeProvideViewportRect(node)\n\n\tlet groundNodeContextForChildren: GroundNodeContext | undefined\n\tconst parentRectByRenderIdForChildren: ParentRectByRenderId = new Map()\n\tconst parentMatrixByRenderIdForChildren: ParentMatrixByRenderId = new Map()\n\n\tfor (const [renderId, renderInstance] of cache.iterateRenderInstances()) {\n\t\tconst { parentRect, parentMatrix, parentDirectedRect } = renderInstance\n\n\t\tconst parentSizeInfo = tree.getParentSizeInfo(node, undefined, pixelAlign, allowCache, renderId)\n\t\tconst rect = parentDirectedRect ?? node.rect(parentSizeInfo, pixelAlign, undefined, renderId)\n\t\tparentRectByRenderIdForChildren.set(renderId, rect)\n\n\t\tconst transformMatrix = node.originAdjustedMatrix(parentSizeInfo, rect, renderId)\n\t\tconst ancestorMatrix = getAncestorMatrix(node, parentRect, parentMatrix, groundNodeContext?.groundNodeMatrix)\n\n\t\tlet matrix: DOMMatrix\n\t\ttry {\n\t\t\tmatrix = ancestorMatrix.multiply(transformMatrix)\n\t\t} catch (error) {\n\t\t\t// Trap for https://github.com/framer/company/issues/20713\n\t\t\tlog.reportErrorOncePerMinute(error, {\n\t\t\t\tparentRect,\n\t\t\t\tframe: rect,\n\t\t\t\tparentMatrix: ancestorMatrix,\n\t\t\t\ttransformMatrix,\n\t\t\t})\n\t\t\tmatrix = new DOMMatrix()\n\t\t}\n\n\t\tconst parentMatrixForChildren = creates3dContext(node) ? matrix : Matrix.flatProjectionMatrix(matrix)\n\t\tparentMatrixByRenderIdForChildren.set(renderId, parentMatrixForChildren)\n\n\t\trenderInstance.matrix = matrix\n\n\t\t// Compute and cache the corner points of the layer. Do this after we update the matrix in the cache, so we can\n\t\t// reuse the cache rather than reconstructing the matrices.\n\t\tconst cornerPoints = convertCornerPointsToCanvas(tree, node, false, undefined, renderId)\n\t\trenderInstance.cornerPoints = cornerPoints\n\t\t// Compute and cache the canvas rect.\n\t\tlet canvasRect = Rect.boundingRectFromPoints(cornerPoints)\n\t\trenderInstance.canvasRect = canvasRect\n\n\t\t// Update the bounding rect.\n\t\tif (withShape(node) && withStroke(node) && node.strokeEnabled) {\n\t\t\tconst strokeWidth = node.resolveValue(\"strokeWidth\") ?? 0\n\t\t\tcanvasRect = Rect.inflate(canvasRect, strokeWidth / 2)\n\t\t}\n\n\t\tif (usesLayoutTemplateRect) {\n\t\t\tsetBoundingBox(renderInstance, cache.getLayoutTemplateContainerRect()?.canvasRect ?? canvasRect)\n\t\t} else {\n\t\t\tsetBoundingBox(renderInstance, canvasRect)\n\t\t}\n\n\t\tif (isPrimaryRenderId(renderId)) {\n\t\t\tgroundNodeContextForChildren =\n\t\t\t\tgroundNodeContext ??\n\t\t\t\tcreateCacheContext<GroundNodeContext>(node, rect, {\n\t\t\t\t\tgroundNodeId: node.id,\n\t\t\t\t\tgroundNodeMatrix: parentMatrixForChildren,\n\t\t\t\t})\n\t\t}\n\t}\n\n\treturn {\n\t\tparentRectByRenderIdForChildren,\n\t\tparentMatrixByRenderIdForChildren,\n\t\tparentUsesDOMRectForChildren: usesDOMRect,\n\t\tgroundNodeContextForChildren,\n\t}\n}\n\nfunction isNodeRenderVisible(node: CanvasNode, renderId: RenderId, sandboxVisibility: SandboxVisibility): boolean {\n\tif (experiments.isOn(\"visibilityFromSandbox\")) {\n\t\treturn sandboxVisibility.getVisible(renderId)\n\t}\n\n\tconst isHiddenOverlay = isFixedOrRelativeOverlay(node) && !node.cache.overlayVisible\n\treturn node.isVisible() && !isHiddenMaster(node) && !isHiddenOverlay\n}\n\nfunction canReuseRenderInstance(\n\tcachedRenderInstance: RenderInstanceCache | undefined,\n\trenderInstance: RenderInstanceCache | undefined,\n): boolean {\n\tif (!cachedRenderInstance && !renderInstance) return true\n\tif (!cachedRenderInstance || !renderInstance) return false\n\n\treturn (\n\t\tRect.equals(cachedRenderInstance.parentRect ?? null, renderInstance.parentRect ?? null) &&\n\t\tMatrix.equals(cachedRenderInstance.parentMatrix ?? null, renderInstance.parentMatrix ?? null) &&\n\t\tRect.equals(cachedRenderInstance.parentDirectedRect ?? null, renderInstance.parentDirectedRect ?? null) &&\n\t\tisShallowEqual(cachedRenderInstance.repeaterItemIds, renderInstance.repeaterItemIds) &&\n\t\tcachedRenderInstance.repeaterItemId === renderInstance.repeaterItemId\n\t)\n}\n\nfunction canReuseSecondaryRenderInstances(\n\tcachedSecondaryRenderInstances: Map<RenderId, RenderInstanceCache> | undefined,\n\tsecondaryRenderInstances: Map<RenderId, RenderInstanceCache> | undefined,\n): boolean {\n\tif (!cachedSecondaryRenderInstances && !secondaryRenderInstances) return true\n\tif (!cachedSecondaryRenderInstances || !secondaryRenderInstances) return false\n\n\tif (cachedSecondaryRenderInstances.size !== secondaryRenderInstances.size) return false\n\n\tfor (const [renderId, renderInstance] of secondaryRenderInstances) {\n\t\tconst cachedRenderInstance = cachedSecondaryRenderInstances.get(renderId)\n\t\tif (!canReuseRenderInstance(renderInstance, cachedRenderInstance)) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunction getRenderInstance(\n\tnode: CanvasNode,\n\trenderId: RenderId,\n\tparent: CanvasNode,\n\tparentRenderId: RenderId,\n\trepeaterItemId: string | undefined,\n\tparentRectByRenderId: ParentRectByRenderId,\n\tparentMatrixByRenderId: ParentMatrixByRenderId,\n\tlayoutCache: LayoutCache,\n\tsandboxRepeaterData: SandboxRepeaterData,\n): RenderInstanceCache {\n\treturn {\n\t\tparentRenderId,\n\n\t\tparentRect: parentRectByRenderId.get(parentRenderId),\n\t\tparentMatrix: parentMatrixByRenderId.get(parentRenderId),\n\n\t\tparentDirectedRect: getParentDirectedRect(node, renderId, parent, layoutCache),\n\n\t\tmatrix: undefined,\n\t\tcanvasRect: undefined,\n\t\tcornerPoints: undefined,\n\n\t\trepeaterItemIds: sandboxRepeaterData.getItemIds(renderId),\n\t\trepeaterItemId: repeaterItemId,\n\n\t\tminX: Infinity,\n\t\tmaxX: -Infinity,\n\t\tminY: Infinity,\n\t\tmaxY: -Infinity,\n\t}\n}\n\nfunction getRenderInstances(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tparent: CanvasNode,\n\tparentRectByRenderId: ParentRectByRenderId,\n\tparentMatrixByRenderId: ParentMatrixByRenderId,\n\tlayoutCache: LayoutCache,\n\tsandboxRepeaterData: SandboxRepeaterData,\n\tsandboxVisibility: SandboxVisibility,\n) {\n\tconst renderInstances = new Map<RenderId, RenderInstanceCache>()\n\n\tif (\n\t\tisDataRepeater(parent) &&\n\t\tisRepeatedItem(tree, node, parent) &&\n\t\t!shouldSkipLegacyDataRepeaterRepeatedChild(node)\n\t) {\n\t\tfor (const [parentRenderId, parentRenderInstance] of parent.cache.iterateRenderInstances()) {\n\t\t\tconst repeaterItemIds = parentRenderInstance.repeaterItemIds\n\t\t\tif (!repeaterItemIds) continue\n\n\t\t\tfor (let itemIndex = 0; itemIndex < repeaterItemIds.length; itemIndex++) {\n\t\t\t\tconst itemId = repeaterItemIds[itemIndex]\n\t\t\t\tif (!itemId) continue\n\n\t\t\t\tconst repeaterRenderId = getRepeatedChildRenderId(parentRenderId, parent.id, itemId, itemIndex)\n\t\t\t\tconst renderId = getChildRenderId(repeaterRenderId, node.id)\n\t\t\t\tif (!isNodeRenderVisible(node, renderId, sandboxVisibility)) continue\n\n\t\t\t\trenderInstances.set(\n\t\t\t\t\trenderId,\n\t\t\t\t\tgetRenderInstance(\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\trenderId,\n\t\t\t\t\t\tparent,\n\t\t\t\t\t\tparentRenderId,\n\t\t\t\t\t\titemId ?? parentRenderInstance.repeaterItemId,\n\t\t\t\t\t\tparentRectByRenderId,\n\t\t\t\t\t\tparentMatrixByRenderId,\n\t\t\t\t\t\tlayoutCache,\n\t\t\t\t\t\tsandboxRepeaterData,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t} else if (hasRepeatArray(node)) {\n\t\tfor (const [parentRenderId, parentRenderInstance] of parent.cache.iterateRenderInstances()) {\n\t\t\tconst nodeRenderId = getChildRenderId(parentRenderId, node.id)\n\t\t\tconst repeaterItemIds = sandboxRepeaterData.getItemIds(nodeRenderId)\n\t\t\tif (!repeaterItemIds) continue\n\n\t\t\tfor (let itemIndex = 0; itemIndex < repeaterItemIds.length; itemIndex++) {\n\t\t\t\tconst itemId = repeaterItemIds[itemIndex]\n\t\t\t\tif (!itemId) continue\n\n\t\t\t\tconst renderId = getRepeatedChildRenderId(nodeRenderId, node.id, itemId, itemIndex)\n\t\t\t\tif (!isNodeRenderVisible(node, renderId, sandboxVisibility)) continue\n\n\t\t\t\trenderInstances.set(\n\t\t\t\t\trenderId,\n\t\t\t\t\tgetRenderInstance(\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\trenderId,\n\t\t\t\t\t\tparent,\n\t\t\t\t\t\tparentRenderId,\n\t\t\t\t\t\titemId ?? parentRenderInstance.repeaterItemId,\n\t\t\t\t\t\tparentRectByRenderId,\n\t\t\t\t\t\tparentMatrixByRenderId,\n\t\t\t\t\t\tlayoutCache,\n\t\t\t\t\t\tsandboxRepeaterData,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (const [parentRenderId, parentRenderInstance] of parent.cache.iterateRenderInstances()) {\n\t\t\tconst renderId = getChildRenderId(parentRenderId, node.id)\n\t\t\tif (!isNodeRenderVisible(node, renderId, sandboxVisibility)) continue\n\n\t\t\trenderInstances.set(\n\t\t\t\trenderId,\n\t\t\t\tgetRenderInstance(\n\t\t\t\t\tnode,\n\t\t\t\t\trenderId,\n\t\t\t\t\tparent,\n\t\t\t\t\tparentRenderId,\n\t\t\t\t\tparentRenderInstance.repeaterItemId,\n\t\t\t\t\tparentRectByRenderId,\n\t\t\t\t\tparentMatrixByRenderId,\n\t\t\t\t\tlayoutCache,\n\t\t\t\t\tsandboxRepeaterData,\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\n\tconst primaryRenderInstance = renderInstances.get(node.id)\n\trenderInstances.delete(node.id)\n\n\tconst secondaryRenderInstances = renderInstances.size > 0 ? renderInstances : undefined\n\n\treturn [primaryRenderInstance, secondaryRenderInstances] as const\n}\n\nfunction resetBoundingBox(box: BoundingBox) {\n\tbox.minX = Infinity\n\tbox.maxX = -Infinity\n\tbox.minY = Infinity\n\tbox.maxY = -Infinity\n}\n\nfunction setBoundingBox(box: BoundingBox, rect: Rect) {\n\tbox.minX = rect.x\n\tbox.maxX = rect.x + rect.width\n\tbox.minY = rect.y\n\tbox.maxY = rect.y + rect.height\n}\n\nfunction extendBoundingBox(box: BoundingBox, other: BoundingBox) {\n\tif (box.minX > other.minX) box.minX = other.minX\n\tif (box.maxX < other.maxX) box.maxX = other.maxX\n\tif (box.minY > other.minY) box.minY = other.minY\n\tif (box.maxY < other.maxY) box.maxY = other.maxY\n}\n\nfunction extendBoundingBoxes(node: CanvasNode, child: CanvasNode) {\n\tfor (const [, childRenderInstance] of child.cache.iterateRenderInstances()) {\n\t\tconst parentRenderId = childRenderInstance.parentRenderId\n\t\tassert(parentRenderId, \"Missing `parentRenderId`\")\n\t\tconst renderInstance = node.cache.getRenderInstance(parentRenderId)\n\t\t// Parent render instance may not exist during partial updates (e.g., undo)\n\t\t// when tree structure changes. Skip extending if parent not rendered.\n\t\tif (!renderInstance) continue\n\n\t\textendBoundingBox(renderInstance, childRenderInstance)\n\t}\n}\n\nfunction getParentDirectedRect(\n\tnode: CanvasNode,\n\trenderId: RenderId,\n\tparent: CanvasNode,\n\tlayoutCache: LayoutCache,\n): Rect | undefined {\n\tif (!hasAnyLayout(parent)) return\n\tif (!isPositionRelative(node, parent)) return\n\n\treturn layoutCache.getRect(renderId)\n}\n", "import { isAssetReference } from \"@framerjs/assets\"\nimport type { VariableCreateScopeType } from \"@framerjs/events\"\nimport { assert } from \"@framerjs/shared\"\nimport { randomID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport type {\n\tArrayVariableDefinition,\n\tBooleanVariableDefinition,\n\tBorderRadiusVariableDefinition,\n\tBorderVariableDefinition,\n\tBoxShadowVariableDefinition,\n\tCollectionReferenceVariableDefinition,\n\tColorVariableDefinition,\n\tControlReferenceVariableDefinition,\n\tCursorVariableDefinition,\n\tCustomCursorVariableDefinition,\n\tDateVariableDefinition,\n\tEnumVariableDefinition,\n\tEventHandlerVariableDefinition,\n\tFileVariableDefinition,\n\tGapVariableDefinition,\n\tImageVariableDefinition,\n\tLinkRelValuesVariableDefinition,\n\tLinkVariableDefinition,\n\tLocationVariableDefinition,\n\tMultiCollectionReferenceVariableDefinition,\n\tNodePropertyControlReferenceVariableDefinition,\n\tNumberVariableDefinition,\n\tPaddingVariableDefinition,\n\tRichTextVariableDefinition,\n\tScrollSectionRefVariableDefinition,\n\tSlugVariableDefinition,\n\tStringVariableDefinition,\n\tTrackingIdVariableDefinition,\n\tTransitionVariableDefinition,\n\tVariableDefinition,\n\tVariableType,\n\tVectorSetItemVariableDefinition,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport type {\n\tArrayValue,\n\tObjectControlProp,\n\tStaticArrayControlPropValue,\n} from \"document/models/controlProps/ControlProp.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isDefined, isString } from \"utils/typeChecks.ts\"\nimport { record } from \"web/lib/tracker.ts\"\n\n/**\n * Only enums and files should be lifted as a control reference. They are only compatible if they\n * match the exact property. Other properties like numbers should be lifted as regular number\n * variables. Because else we will end up with slightly different behaviors for number variables.\n * For example referenced numbers would not be supported by value transforms (e.g. Convert to\n * String). And you would not be able to use conditional logic (e.g. Boolean -> Number). And you\n * would only be able to assign these numbers to a specific property. Making them less reusable.\n */\nfunction assertValidControlReferenceIfNeeded(props: CreateVariableOptions) {\n\tif (props.type !== \"controlReference\" && props.type !== \"nodePropertyControlReference\") return\n\n\tconst { expectedType } = props\n\tassert(\n\t\texpectedType === ControlType.Enum ||\n\t\t\texpectedType === ControlType.SegmentedEnum ||\n\t\t\texpectedType === ControlType.File,\n\t)\n}\n\n/**\n * Creates four placeholder images when the variable is meant for a smart component. Otherwise\n * returns an empty array.\n */\nexport function createGalleryVariableDefaultValue({\n\tgalleryImageId,\n\tisSmartComponent,\n}: {\n\tgalleryImageId: string\n\tisSmartComponent: boolean\n}): StaticArrayControlPropValue {\n\t// Only smart component should have placeholders, for example within the CMS we don't support a\n\t// default value for arrays.\n\tif (!isSmartComponent) {\n\t\treturn []\n\t}\n\n\treturn Array(4)\n\t\t.fill(null)\n\t\t.map((): ArrayValue & ObjectControlProp => ({\n\t\t\tid: randomID(),\n\t\t\ttype: ControlType.Object,\n\t\t\tvalue: { [galleryImageId]: { type: ControlType.Image, value: undefined } },\n\t\t}))\n}\n\nexport type CreateVariableOptions =\n\t| CreateArray\n\t| CreateBool\n\t| CreateColor\n\t| CreateImage\n\t| CreateNumber\n\t| CreateString\n\t| CreateRichText\n\t| CreateEventHandler\n\t| CreateControlReference\n\t| CreateSlug\n\t| CreateLink\n\t| CreateLinkRelValues\n\t| CreateDate\n\t| CreateEnum\n\t| CreateNodePropertyControlReference\n\t| CreateFile\n\t| CreateScrollSectionRef\n\t| CreateCustomCursor\n\t| CreateCursor\n\t| CreateTransition\n\t| CreateBorder\n\t| CreateBoxShadow\n\t| CreateGap\n\t| CreatePadding\n\t| CreateBorderRadius\n\t| CreateLocation\n\t| CreateCollectionReference\n\t| CreateMultiCollectionReference\n\t| CreateTrackingId\n\t| CreateVectorSetItem\n\ntype WithoutIdAndExposeInProps<T> = Omit<T, \"id\" | \"exposeInProps\"> & { id?: string }\n\ntype CreateArray = WithoutIdAndExposeInProps<ArrayVariableDefinition>\ntype CreateBool = WithoutIdAndExposeInProps<BooleanVariableDefinition>\ntype CreateColor = WithoutIdAndExposeInProps<ColorVariableDefinition>\ntype CreateImage = WithoutIdAndExposeInProps<ImageVariableDefinition>\ntype CreateNumber = WithoutIdAndExposeInProps<NumberVariableDefinition>\ntype CreateString = WithoutIdAndExposeInProps<StringVariableDefinition>\ntype CreateRichText = WithoutIdAndExposeInProps<RichTextVariableDefinition>\ntype CreateEventHandler = WithoutIdAndExposeInProps<EventHandlerVariableDefinition>\ntype CreateControlReference = WithoutIdAndExposeInProps<ControlReferenceVariableDefinition>\ntype CreateNodePropertyControlReference = WithoutIdAndExposeInProps<NodePropertyControlReferenceVariableDefinition>\ntype CreateSlug = WithoutIdAndExposeInProps<SlugVariableDefinition>\ntype CreateLink = WithoutIdAndExposeInProps<LinkVariableDefinition>\ntype CreateLinkRelValues = WithoutIdAndExposeInProps<LinkRelValuesVariableDefinition>\ntype CreateDate = WithoutIdAndExposeInProps<DateVariableDefinition>\ntype CreateEnum = WithoutIdAndExposeInProps<EnumVariableDefinition>\ntype CreateFile = WithoutIdAndExposeInProps<FileVariableDefinition>\ntype CreateScrollSectionRef = WithoutIdAndExposeInProps<ScrollSectionRefVariableDefinition>\ntype CreateCustomCursor = WithoutIdAndExposeInProps<CustomCursorVariableDefinition>\ntype CreateCursor = WithoutIdAndExposeInProps<CursorVariableDefinition>\ntype CreateTransition = WithoutIdAndExposeInProps<TransitionVariableDefinition>\ntype CreateBorder = WithoutIdAndExposeInProps<BorderVariableDefinition>\ntype CreateBoxShadow = WithoutIdAndExposeInProps<BoxShadowVariableDefinition>\ntype CreateGap = WithoutIdAndExposeInProps<GapVariableDefinition>\ntype CreatePadding = WithoutIdAndExposeInProps<PaddingVariableDefinition>\ntype CreateBorderRadius = WithoutIdAndExposeInProps<BorderRadiusVariableDefinition>\ntype CreateLocation = WithoutIdAndExposeInProps<LocationVariableDefinition>\ntype CreateCollectionReference = WithoutIdAndExposeInProps<CollectionReferenceVariableDefinition>\ntype CreateMultiCollectionReference = WithoutIdAndExposeInProps<MultiCollectionReferenceVariableDefinition>\ntype CreateTrackingId = WithoutIdAndExposeInProps<TrackingIdVariableDefinition>\ntype CreateVectorSetItem = WithoutIdAndExposeInProps<VectorSetItemVariableDefinition>\n\nexport function createVariable(props: CreateBool, scopeType: VariableCreateScopeType): BooleanVariableDefinition\nexport function createVariable(props: CreateColor, scopeType: VariableCreateScopeType): ColorVariableDefinition\nexport function createVariable(props: CreateImage, scopeType: VariableCreateScopeType): ImageVariableDefinition\nexport function createVariable(props: CreateNumber, scopeType: VariableCreateScopeType): NumberVariableDefinition\nexport function createVariable(props: CreateString, scopeType: VariableCreateScopeType): StringVariableDefinition\nexport function createVariable(props: CreateRichText, scopeType: VariableCreateScopeType): RichTextVariableDefinition\nexport function createVariable(\n\tprops: CreateEventHandler,\n\tscopeType: VariableCreateScopeType,\n): EventHandlerVariableDefinition\nexport function createVariable(\n\tprops: CreateControlReference,\n\tscopeType: VariableCreateScopeType,\n): ControlReferenceVariableDefinition\nexport function createVariable(\n\tprops: CreateNodePropertyControlReference,\n\tscopeType: VariableCreateScopeType,\n): NodePropertyControlReferenceVariableDefinition\nexport function createVariable(props: CreateLink, scopeType: VariableCreateScopeType): LinkVariableDefinition\nexport function createVariable(\n\tprops: CreateLinkRelValues,\n\tscopeType: VariableCreateScopeType,\n): LinkRelValuesVariableDefinition\nexport function createVariable(props: CreateDate, scopeType: VariableCreateScopeType): DateVariableDefinition\nexport function createVariable(props: CreateSlug, scopeType: VariableCreateScopeType): SlugVariableDefinition\nexport function createVariable(props: CreateEnum, scopeType: VariableCreateScopeType): EnumVariableDefinition\nexport function createVariable(props: CreateFile, scopeType: VariableCreateScopeType): FileVariableDefinition\nexport function createVariable(\n\tprops: CreateScrollSectionRef,\n\tscopeType: VariableCreateScopeType,\n): ScrollSectionRefVariableDefinition\nexport function createVariable(\n\tprops: CreateCustomCursor,\n\tscopeType: VariableCreateScopeType,\n): CustomCursorVariableDefinition\nexport function createVariable(props: CreateCursor, scopeType: VariableCreateScopeType): CursorVariableDefinition\nexport function createVariable(\n\tprops: CreateTransition,\n\tscopeType: VariableCreateScopeType,\n): TransitionVariableDefinition\nexport function createVariable(props: CreateBorder, scopeType: VariableCreateScopeType): BorderVariableDefinition\nexport function createVariable(props: CreateLocation, scopeType: VariableCreateScopeType): LocationVariableDefinition\nexport function createVariable(\n\tprops: CreateCollectionReference,\n\tscopeType: VariableCreateScopeType,\n): CollectionReferenceVariableDefinition\nexport function createVariable(\n\tprops: CreateMultiCollectionReference,\n\tscopeType: VariableCreateScopeType,\n): MultiCollectionReferenceVariableDefinition\nexport function createVariable(props: CreateArray, scopeType: VariableCreateScopeType): ArrayVariableDefinition\nexport function createVariable(props: CreateBoxShadow, scopeType: VariableCreateScopeType): BoxShadowVariableDefinition\nexport function createVariable(props: CreateGap, scopeType: VariableCreateScopeType): GapVariableDefinition\nexport function createVariable(props: CreatePadding, scopeType: VariableCreateScopeType): PaddingVariableDefinition\nexport function createVariable(\n\tprops: CreateVectorSetItem,\n\tscopeType: VariableCreateScopeType,\n): VectorSetItemVariableDefinition\nexport function createVariable(\n\tprops: CreateBorderRadius,\n\tscopeType: VariableCreateScopeType,\n): BorderRadiusVariableDefinition\nexport function createVariable(props: CreateVariableOptions, scopeType: VariableCreateScopeType): VariableDefinition\nexport function createVariable(\n\tprops: CreateTrackingId,\n\tscopeType: VariableCreateScopeType,\n): TrackingIdVariableDefinition\nexport function createVariable(props: CreateVariableOptions, scopeType: VariableCreateScopeType): VariableDefinition {\n\tassert(\n\t\tprops.type !== (ControlType.ResponsiveImage as VariableType),\n\t\t`Image variables are compiled to be responsive images. To\n        prevent confusion we don't allow creation of type responsive images.\n        Because that would mean that two different types represent the same thing.`,\n\t)\n\tassertValidControlReferenceIfNeeded(props)\n\n\tif (props.type !== ControlType.TrackingId && props.type !== ControlType.VectorSetItem) {\n\t\t// TODO: update events schema\n\t\trecord(\"variable_create\", { scopeType, variableType: props.type })\n\t}\n\n\t// Make sure image variables use valid asset references.\n\tif (props.type === ControlType.Image) {\n\t\tif (isString(props.initialValue)) {\n\t\t\tif (!isAssetReference(props.initialValue)) {\n\t\t\t\tprops.initialValue = undefined\n\t\t\t}\n\t\t} else if (isDefined(props.initialValue) && isString(props.initialValue.value)) {\n\t\t\tif (!isAssetReference(props.initialValue.value)) {\n\t\t\t\tprops.initialValue = undefined\n\t\t\t}\n\t\t}\n\t}\n\n\tif (props.type === ControlType.Array && scopeType === \"canvas_component\") {\n\t\t// NOTE: We explicitly do not lift the minCount and maxCount constraints from CMS array\n\t\t//       variables into components. We don't have a UI to manage these yet.\n\t\tassert(props.minCount === undefined, \"minCount should not be lifted to component\")\n\t\tassert(props.maxCount === undefined, \"maxCount should not be lifted to component\")\n\t}\n\n\treturn {\n\t\tid: randomID(),\n\t\t...props,\n\t}\n}\n", "import { isOrganizationSpace } from \"@framerjs/app-shared\"\nimport type { ModalOpenSource } from \"@framerjs/events\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\n\nexport class AiDisabledError extends Error {\n\treadonly reason = \"ai-disabled\" as const\n\n\tconstructor(message = \"AI features have been disabled.\") {\n\t\tsuper(message)\n\t\tthis.name = \"AiDisabledError\"\n\t}\n}\n\nexport function isAiDisabledError(error: unknown): error is AiDisabledError {\n\treturn error instanceof AiDisabledError\n}\n\nexport function isAiDisabled(engine: VekterEngine): boolean {\n\tconst projectSpaceId = engine.stores.projectStore.project?.space.id\n\tif (!projectSpaceId) return false\n\tconst space = engine.stores.sessionStore.user.spaces.find(s => s.id === projectSpaceId)\n\treturn isOrganizationSpace(space) && space.configuration.disableAi === true\n}\n\nfunction showAiDisabledModal(engine: VekterEngine, source: ModalOpenSource) {\n\tengine.stores.modalStore.set({\n\t\ttype: ModalType.Confirmation,\n\t\tsource,\n\t\ttitle: \"AI Features Disabled\",\n\t\tdescription: \"An admin has disabled all AI features. Contact them to re-enable access.\",\n\t\tcancelLabel: Dictionary.Dismiss,\n\t\tonCancel: () => engine.stores.modalStore.dismiss(),\n\t})\n}\n\n/** Returns true and shows a confirmation modal when AI features are disabled in the current workspace */\nexport function showModalIfAiDisabled(engine: VekterEngine, source: ModalOpenSource): boolean {\n\tif (!isAiDisabled(engine)) return false\n\tshowAiDisabledModal(engine, source)\n\treturn true\n}\n", "import type { NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { WithItemsOrder } from \"document/models/CanvasTree/traits/WithItemsOrder.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\n\ntype RenamedIds = Map<NodeID, NodeID>\n\nexport function updateItemsOrder(itemsOrder: WithItemsOrder[\"itemsOrder\"], renamedIds: RenamedIds) {\n\tif (isUndefined(itemsOrder)) return itemsOrder\n\n\tconst nextItemsOrder: NodeID[] = []\n\tfor (const id of itemsOrder) {\n\t\t// The id might not be renamed if the same id is not in use in the new tree, in this case we preserve the\n\t\t// old id in the itemsOrder to avoid losing the order override\n\t\tnextItemsOrder.push(renamedIds.get(id) ?? id)\n\t}\n\n\treturn nextItemsOrder.length > 0 ? nextItemsOrder : undefined\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { updateItemsOrder } from \"document/components/tools/utils/updateItemsOrder.ts\"\n// Helpers for inserting nodes into a replica variant\nimport type { RenamedIds } from \"document/components/tools/utils/updateNodeConnections.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tTemplateHelper,\n\tgenerateReplicaChildId,\n\tmergeOverrides,\n} from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport { updateReplicaNodeOverrides } from \"document/models/CanvasTree/nodes/utils/updateReplicaOverrides.ts\"\nimport { hasItemsOrderOverride } from \"document/models/CanvasTree/traits/WithItemsOrder.ts\"\nimport type {\n\tIsReplica,\n\tIsReplicaChild,\n\tIsReplicaOrReplicaChild,\n} from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isReplicaVariantOrReplicaVariantChild, isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { getRelatedReplicaNodes, isVisibleInOtherVariants } from \"./isOnlyVisibleInCurrentVariant.ts\"\nimport { cloneReplicaOverridesAndStripLocalizedValues } from \"./stripLocalizedValues.ts\"\n\n// Given a replica node, check if the experiment is enabled and if the node is a\n// replica variant (child) node. If yes, return its original node.\nexport function getOriginalVariantNodeIfExists(\n\ttree: CanvasTree,\n\tnode: CanvasNode & IsReplicaOrReplicaChild,\n): CanvasNode | null {\n\tif (!isReplicaVariantOrReplicaVariantChild(node)) return null\n\tconst originalNode = tree.getNode(node.originalid)\n\tassert(originalNode, \"The original variant node should exist\")\n\n\treturn originalNode\n}\n\n// Returns the ids of the subtree nodes\n// only export for tests\nexport function applyOverridesToOriginal(tree: CanvasTree, replica: CanvasNode & IsReplica, originalNode: CanvasNode) {\n\tconst inheritedReplica = TemplateHelper.inheritedReplicaNode(tree, replica.replicaInfo.inheritsFrom)\n\tconst allOverrides = mergeOverrides(replica.replicaInfo.overrides, inheritedReplica?.replicaInfo.overrides)\n\n\tfor (const originalSubTreeNode of originalNode.walk()) {\n\t\tconst overrides = allOverrides[originalSubTreeNode.id]\n\t\tif (!overrides) continue\n\t\t// Original nodes should not have itemsOrder set, because it has no\n\t\t// effects. We should actually sort the children if we want to preserve\n\t\t// the order.\n\t\tconst { _deleted, itemsOrder: _, ...update } = overrides\n\t\t_deleted?.forEach(deletedProp => (update[deletedProp] = undefined))\n\t\ttree.current(originalSubTreeNode)?.set(update)\n\t}\n}\n\n/**\n * Get all nodes in the inheritance chain, starting with the original, and optionally the inheritsFrom node for gesture variants\n */\n// only export for tests\nexport function getUpstreamNodes(tree: CanvasTree, node: CanvasNode & IsReplicaOrReplicaChild): CanvasNode[] {\n\tconst originalNode = tree.getNode(node.originalid)\n\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, node)\n\tif (!originalNode || !replica || !isVariant(replica)) return []\n\n\tif (!replica.replicaInfo.inheritsFrom) return [originalNode]\n\n\tconst inheritsFromReplica = tree.getNode(replica.replicaInfo.inheritsFrom)\n\tif (!inheritsFromReplica) return [originalNode]\n\n\tconst inheritsFromNodeId = generateReplicaChildId(inheritsFromReplica.id, originalNode.id)\n\tconst inheritsFromNode = tree.getNode(inheritsFromNodeId)\n\treturn inheritsFromNode ? [originalNode, inheritsFromNode] : [originalNode]\n}\n\nexport function updateNodeWhenMovedOutOfVariant(\n\tengine: VekterEngine,\n\tnode: CanvasNode & IsReplicaChild,\n\toriginalNode: CanvasNode,\n\tnewSelection: Set<NodeID>,\n) {\n\tconst replica = TemplateHelper.getReplicaForTemplateNode(engine.tree, node)\n\tassert(replica, \"replica should exist when moving node out of replica\")\n\tassert(isVariant(replica), \"replica must be a variant\")\n\n\t// Apply the overrides on all the nodes in the subtree, so the node\n\t// appears the same when we drag it out of the variant.\n\tapplyOverridesToOriginal(engine.tree, replica, originalNode)\n\n\t// If the original node is hidden and the replica is visible, make sure\n\t// the original node becomes visible when we drag the replica out of the\n\t// variant\n\tif (node.isVisible() && !originalNode.isVisible()) {\n\t\tengine.tree.current(originalNode)?.set({ visible: true })\n\t}\n\n\t// When the replica node is moved out of the variant, we are moving the\n\t// original node\n\tnewSelection.delete(node.id)\n\tnewSelection.add(originalNode.id)\n}\n\n/**\n * Perform following updates after a node is inserted into a replica variant,\n * this includes:\n * - hide the original node\n * - override the replica variant node to be visible\n *\n * @param engine\n * @param originalNode - The original (inserted) node\n * @param replicaParent - The new parent node in the replica variant\n * @param originalParent - The original parent node in the primary variant\n * @returns The id of the replica node in the replica variant\n */\nexport function updateInsertedVariantNode(\n\tengine: VekterEngine,\n\toriginalNode: CanvasNode,\n\treplicaParent: (CanvasNode & IsReplicaOrReplicaChild) | null,\n\toriginalParent: CanvasNode | null,\n\trenamedIds?: RenamedIds,\n): NodeID {\n\tif (!replicaParent || !originalParent) return originalNode.id\n\tassert(isReplicaOrReplicaChild(replicaParent), \"Fail to update variant nodes: parent must be a replica\")\n\n\tconst replica = TemplateHelper.getReplicaForTemplateNode(engine.tree, replicaParent)\n\tassert(replica, \"Fail to update variant nodes: replica should exist\")\n\tassert(isVariant(replica), \"Fail to update variant nodes: replica must be an variant\")\n\n\t// If the parent is a replica variant (child), the clone is inserted into the original node, but\n\t// we should keep the selection on the replica clone\n\n\tif (isVisibleInOtherVariants(engine.tree, replicaParent)) {\n\t\t// Hide the original clone and override the replica clone to be visible\n\t\tengine.tree.current(originalNode)?.set({ visible: false })\n\t\tconst newOverrides: { [key: string]: unknown } = { visible: true }\n\n\t\t// When duplicating a replica stack/grid with itemsOrder override, the original (inserted) node still carry the\n\t\t// itemsOrder. We remap the ids and write it into the replica overrides. The residual itemsOrder will be cleared\n\t\t// in the prefreeze phase (see FrameNode.preFreeze).\n\t\tif (hasItemsOrderOverride(originalNode) && renamedIds) {\n\t\t\tnewOverrides.itemsOrder = updateItemsOrder(originalNode.itemsOrder, renamedIds)\n\t\t}\n\t\tupdateReplicaNodeOverrides(engine.tree, replica, originalNode.id, newOverrides)\n\t}\n\n\tconst replicaNodeId = generateReplicaChildId(replica.id, originalNode.id)\n\treturn replicaNodeId\n}\n\nexport function updateNodeWhenMovedIntoVariant(\n\tengine: VekterEngine,\n\toriginalNode: CanvasNode,\n\tnewParent: CanvasNode & IsReplicaOrReplicaChild,\n\toriginalParent: CanvasNode,\n\tnewSelection: Set<NodeID>,\n\trenamedIds?: RenamedIds,\n): NodeID {\n\tconst replicaNodeId = updateInsertedVariantNode(engine, originalNode, newParent, originalParent, renamedIds)\n\n\tnewSelection.delete(originalNode.id)\n\tnewSelection.add(replicaNodeId)\n\n\treturn replicaNodeId\n}\n\nexport function updateNodeWhenReparentedInVariant(\n\tengine: VekterEngine,\n\tnode: CanvasNode & IsReplicaChild,\n\tnewParent: CanvasNode & IsReplicaOrReplicaChild,\n) {\n\tconst upstreamNodes = getUpstreamNodes(engine.tree, node)\n\tconst upstreamNewParents = getUpstreamNodes(engine.tree, newParent)\n\n\t// If the upstream node is hidden by the current parent, after we move\n\t// it into the new parent (visible), we want it to stay hidden.\n\t// @TODO: For now we just update the first node we find, but there might\n\t// be an edge case which requires more complex logic. For example, when\n\t// re-parenting a node in a gesture, if the original node is hidden by\n\t// its parent, and the node in the inheritsFrom already has visibility\n\t// overridden to true, then we should reset its visibility override\n\tconst upstreamNodeHiddenByParent = upstreamNodes.find((upstreamNode, idx) => {\n\t\tif (!upstreamNode.isVisible() || upstreamNode.cache.visible === true) return false\n\t\tconst upstreamNewParent = upstreamNewParents[idx]\n\t\treturn upstreamNewParent?.cache.visible ?? false\n\t})\n\n\tif (upstreamNodeHiddenByParent) {\n\t\tengine.tree.get(upstreamNodeHiddenByParent.id)?.set({ visible: false })\n\t\tnode.set({ visible: true }, engine.tree, true)\n\t}\n}\n\n/**\n * When duplicating a node inside of the primary variant, we make sure to keep all\n * replica variant overrides for the entire subtree.\n * @param engine\n * @param sourceNode - The node that is duplicated inside of the primary\n */\nexport function applyOverridesToReplicasOfDuplicatedPrimaryChild(\n\tengine: VekterEngine,\n\tsourceNode: CanvasNode,\n\trenamedIds: RenamedIds,\n) {\n\tgetRelatedReplicaNodes(engine.tree, sourceNode).forEach(({ replicaRoot }) => {\n\t\tconst overriddenNodeIds = Object.keys(replicaRoot.replicaInfo.overrides)\n\t\tconst notOverridden = overriddenNodeIds.every(id => !renamedIds.has(id))\n\t\tif (notOverridden) return\n\n\t\tconst replicaInfo = { ...replicaRoot.replicaInfo }\n\t\tconst replicaOverrides = { ...replicaInfo.overrides }\n\t\treplicaInfo.overrides = replicaOverrides\n\t\trenamedIds.forEach((targetId, sourceId) => {\n\t\t\tif (sourceId in replicaOverrides) {\n\t\t\t\tconst value = { ...replicaOverrides[sourceId] }\n\t\t\t\tconst prevItemsOrder = value.itemsOrder\n\t\t\t\tif (\"itemsOrder\" in value && Array.isArray(prevItemsOrder)) {\n\t\t\t\t\tvalue.itemsOrder = updateItemsOrder(prevItemsOrder, renamedIds)\n\t\t\t\t}\n\t\t\t\treplicaOverrides[targetId] = cloneReplicaOverridesAndStripLocalizedValues(value)\n\t\t\t}\n\t\t})\n\t\tengine.tree.get(replicaRoot.id)?.set({ replicaInfo })\n\t})\n}\n", "import { isUndefined } from \"utils/typeChecks.ts\"\nimport type { CanvasTree } from \"../../CanvasTree.ts\"\nimport { findTokenNode } from \"../../utils/findTokenNode.ts\"\nimport { isTokenCSSVariable, tokenIdFromCSSVariable } from \"../../utils/tokens.ts\"\n\nexport function convertCSSColorVariableToValue(\n\tvalue: string | undefined,\n\ttree: CanvasTree,\n\tdefaultValue: string = \"transparent\",\n): string {\n\tif (isUndefined(value)) return defaultValue\n\tif (!isTokenCSSVariable(value)) return value\n\n\tconst tokenId = tokenIdFromCSSVariable(value)\n\tconst token = tokenId ? findTokenNode(tokenId, tree) : null\n\treturn token?.light ?? defaultValue\n}\n", "import { Dictionary } from \"app/dictionary.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { withGetName } from \"document/models/CanvasTree/traits/WithGetName.ts\"\nimport { withName } from \"document/models/CanvasTree/traits/WithName.ts\"\nimport { getNameFromPath } from \"document/utils/assetPath.ts\"\n\n/**\n * Returns the node's name using the following precedence:\n * 1. If the node implements getName(), returns the result of getName().\n * 2. If the node has a 'name' property, returns the name processed by getNameFromPath.\n * 3. Otherwise, returns Dictionary.Unknown.\n */\nexport function getNodeName(node: CanvasNode): string {\n\tif (withGetName(node)) return getNameFromPath(node.getName())\n\n\tconst name = node.resolveValue(\"name\")\n\tif (withName(node) && name) {\n\t\treturn getNameFromPath(name)\n\t}\n\n\treturn Dictionary.Unknown\n}\n", "import type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { isDefined, isNull } from \"utils/typeChecks.ts\"\nimport type { CanvasTree } from \"../../CanvasTree.ts\"\nimport type { CanvasNode } from \"../CanvasNode.ts\"\nimport type { EntityFolderNode } from \"../EntityFolderNode.ts\"\nimport {\n\ttype CodeFileEntityReferenceNodeId,\n\tEntityReferenceNode,\n\ttype EntityReferenceNodeId,\n\tbuildCodeFileEntityReferenceNodeId,\n\tbuildEntityReferenceNodeId,\n\tisEntityReferenceNodeId,\n} from \"../EntityReferenceNode.ts\"\nimport {\n\tCODE_FILE_ENTITY_TYPE_ROOT_ID,\n\ttype EntityTypeRootId,\n\ttype EntityTypeRootNode,\n\tensureEntityTypeRootNode,\n\tisEntityTypeRootNodeId,\n} from \"../EntityTypeRootNode.ts\"\nimport type { NodeID } from \"../NodeID.ts\"\nimport { isEntityFolderNode } from \"./nodeCheck.ts\"\n\n/**\n * Creates a reference node for the given node ID if it does not already exist.\n * If the `parentId` provided is entity type root, then we don't create a\n * reference node for the node. This is because for new nodes, we want them to\n * be created at the root level of the entity type without any folders.\n */\nexport function createReferenceForNodeIfNeeded(tree: CanvasTree, parentId: NodeID, nodeId: NodeID, isCodeFile = false) {\n\t// When we are creating an item at the root level we don't want to create\n\t// a reference node for it.\n\tif (isEntityTypeRootNodeId(parentId)) {\n\t\t// If the parent node does not exist, we create it on demand.\n\t\t// Realistically this is just for types introduced after the feature was\n\t\t// launched.\n\t\tif (!tree.has(parentId)) ensureEntityTypeRootNode(tree, parentId)\n\t\treturn\n\t}\n\n\tconst referenceId = isCodeFile ? buildCodeFileEntityReferenceNodeId(nodeId) : buildEntityReferenceNodeId(nodeId)\n\tif (tree.has(referenceId)) return\n\n\tconst referenceNode = new EntityReferenceNode({\n\t\tid: referenceId,\n\t})\n\n\ttree.insertNode(referenceNode, parentId)\n}\n\n/**\n * Creates a reference node for the given node ID, even if the parent is a type root.\n * This is used by analytics (funnels/AB tests) which always require references to\n * work correctly with the folder system.\n */\nexport function createReferenceAlways(tree: CanvasTree, parentId: NodeID, nodeId: NodeID) {\n\t// Ensure the parent exists\n\tif (isEntityTypeRootNodeId(parentId) && !tree.has(parentId)) {\n\t\tensureEntityTypeRootNode(tree, parentId)\n\t}\n\n\t// If the nodeId is already a reference ID, use it directly instead of wrapping it again\n\tconst referenceId = isEntityReferenceNodeId(nodeId) ? nodeId : buildEntityReferenceNodeId(nodeId)\n\tif (tree.has(referenceId)) return referenceId\n\n\tconst referenceNode = new EntityReferenceNode({\n\t\tid: referenceId,\n\t})\n\n\ttree.insertNode(referenceNode, parentId)\n\treturn referenceId\n}\n\nfunction findNodePosition(tree: CanvasTree, nodeId: EntityReferenceNodeId | CodeFileEntityReferenceNodeId) {\n\tconst node = tree.get<EntityReferenceNode>(nodeId)\n\tif (isNull(node)) return\n\n\tconst parentNode = tree.get(node.parentid)\n\tif (isNull(parentNode)) return\n\n\treturn parentNode.children?.findIndex(child => child.id === nodeId)\n}\n\nexport function duplicateEntityReferenceNode(\n\tengineOrTree: VekterEngine | CanvasTree, // TODO: remove engine and update all references to use CanvasTree directly\n\tnodeId: NodeID,\n\tnewNodeId: NodeID,\n) {\n\tconst tree = \"tree\" in engineOrTree ? engineOrTree.tree : engineOrTree\n\tconst referenceNode = EntityReferenceNode.get(tree, nodeId)\n\n\t// If the node we are duplicating does not have a reference that it is at the root so no need to create reference as well\n\tif (isNull(referenceNode)) return\n\n\tconst duplicatedReferenceId = buildEntityReferenceNodeId(newNodeId)\n\tconst duplicatedReferenceNode = new EntityReferenceNode({\n\t\tid: duplicatedReferenceId,\n\t})\n\n\tconst currentReferencePosition = findNodePosition(tree, referenceNode.id)\n\tconst position = isDefined(currentReferencePosition) ? currentReferencePosition + 1 : undefined\n\n\t// Insert the duplicate reference in the same parent as the original reference node\n\ttree.insertNode(duplicatedReferenceNode, referenceNode.parentid, position)\n}\n\nexport function removeNodeWithReference(tree: CanvasTree, nodeId: NodeID) {\n\tconst node = tree.get(nodeId)\n\tif (isNull(node)) return\n\n\ttree.removeNode(node)\n\n\tremoveReferenceForNode(tree, nodeId)\n}\n\nexport function removeReferenceForNode(tree: CanvasTree, id: NodeID, options?: { isCodeFile: boolean }) {\n\tconst { isCodeFile = false } = options ?? {}\n\n\t// Remove reference node to preset node if exists\n\tconst referenceId = isCodeFile ? buildCodeFileEntityReferenceNodeId(id) : buildEntityReferenceNodeId(id)\n\ttree.remove(referenceId)\n}\n\n/**\n * Builds a reference node ID for a given type root ID and reference ID.\n * Because code file local module nodes can be referenced in both the components\n * and code type roots, we need to differentiate between them hence adding the code file prefix\n * for references in the type root code file.\n *\n * @param typeRootId The type root ID.\n * @param referenceId The reference ID.\n * @returns The reference node ID.\n */\nexport function buildReferenceNodeId(\n\ttypeRootId: EntityTypeRootId,\n\treferenceId: NodeID,\n): EntityReferenceNodeId | CodeFileEntityReferenceNodeId {\n\tif (typeRootId === CODE_FILE_ENTITY_TYPE_ROOT_ID) {\n\t\treturn buildCodeFileEntityReferenceNodeId(referenceId)\n\t}\n\n\treturn buildEntityReferenceNodeId(referenceId)\n}\n\nfunction entityFolderWithName(name: string) {\n\treturn (entity: CanvasNode): entity is EntityFolderNode => {\n\t\treturn isEntityFolderNode(entity) && entity.name === name\n\t}\n}\n\nexport function existingFolderWithName(\n\tparent: EntityFolderNode | EntityTypeRootNode,\n\tsegment: string,\n): EntityFolderNode | null {\n\treturn parent.children.find(entityFolderWithName(segment)) ?? null\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { getNodeName } from \"document/components/chrome/assets/utils/getNodeName.ts\"\nimport { splitPathToSegments } from \"document/utils/assetPath.ts\"\nimport { isArray } from \"utils/typeChecks.ts\"\nimport type { CanvasTree } from \"../../CanvasTree.ts\"\nimport type { CanvasNode } from \"../CanvasNode.ts\"\nimport { EntityFolderNode } from \"../EntityFolderNode.ts\"\nimport {\n\tAB_TESTS_ENTITY_TYPE_ROOT_ID,\n\tCODE_FILE_ENTITY_TYPE_ROOT_ID,\n\ttype EntityTypeRootId,\n\ttype EntityTypeRootNode,\n\tFUNNELS_ENTITY_TYPE_ROOT_ID,\n\tisEntityTypeRootNode,\n} from \"../EntityTypeRootNode.ts\"\nimport type { NodeID } from \"../NodeID.ts\"\nimport { buildReferenceNodeId, createReferenceForNodeIfNeeded, existingFolderWithName } from \"./entityReferenceNode.ts\"\nimport { isEntityFolderNode, isEntityReferenceNode } from \"./nodeCheck.ts\"\n\n/**\n * Finds a folder node by name within a parent node.\n */\nexport function getFolderNodeByName(\n\tparentNode: EntityFolderNode | EntityTypeRootNode,\n\tname: string,\n): EntityFolderNode | null {\n\treturn (\n\t\tparentNode.children.find(\n\t\t\t(child): child is EntityFolderNode => isEntityFolderNode(child) && child.getName() === name,\n\t\t) ?? null\n\t)\n}\n\n/**\n * Checks if a node is a valid parent for entity items (folder or type root).\n */\nexport function isValidEntityParentNode(parentNode: CanvasNode): parentNode is EntityTypeRootNode | EntityFolderNode {\n\treturn isEntityTypeRootNode(parentNode) || isEntityFolderNode(parentNode)\n}\n\n/**\n * Folders and references live in independent namespaces \u2014 they can share a\n * name freely. Callers tell us which side they're placing so we only flag\n * collisions against same-kind siblings at the leaf.\n */\ntype AssetEntityKind = \"folder\" | \"reference\"\n\n/**\n * Returns true when placing an asset of `kind` at the given path would\n * collide with an existing same-kind sibling at the leaf.\n *\n * Intermediate segments are walked through child folders; if the path can't\n * be resolved (a folder along the way is missing), nothing is there to\n * collide with and we return false.\n */\nexport function wouldAssetEntityCollide(\n\ttree: CanvasTree,\n\tpathSegments: string[],\n\tparentId: NodeID,\n\tkind: AssetEntityKind,\n): boolean {\n\tlet entityParentId = parentId\n\n\tfor (const [index, segment] of pathSegments.entries()) {\n\t\tconst entity = tree.getNode(entityParentId)\n\t\tif (!entity || !isValidEntityParentNode(entity)) return false\n\n\t\tconst isLeaf = index === pathSegments.length - 1\n\t\tif (isLeaf) return nameDoesCollideWithSiblingOfSameKind(entity, segment, kind)\n\n\t\tconst nextFolder = getFolderNodeByName(entity, segment)\n\t\tif (!nextFolder) return false\n\t\tentityParentId = nextFolder.id\n\t}\n\n\treturn false\n}\n\nfunction nameDoesCollideWithSiblingOfSameKind(\n\tcontainer: EntityFolderNode | EntityTypeRootNode,\n\tname: string,\n\tkind: AssetEntityKind,\n): boolean {\n\tfor (const child of container.children) {\n\t\tif (child.getName() !== name) continue\n\t\tif (kind === \"folder\" && isEntityFolderNode(child)) return true\n\t\tif (kind === \"reference\" && isEntityReferenceNode(child)) return true\n\t}\n\treturn false\n}\n\n/**\n * Analytics entity types (Funnels and A/B Tests) have unique properties\n * such as allowing duplicate folder names at the same level.\n */\nexport function isAnalyticsEntityType(typeRootId: EntityTypeRootId): boolean {\n\treturn typeRootId === FUNNELS_ENTITY_TYPE_ROOT_ID || typeRootId === AB_TESTS_ENTITY_TYPE_ROOT_ID\n}\n\nexport function createEntityFolderNodesFromPath(tree: CanvasTree, path: string | string[], parentId: NodeID): NodeID {\n\tconst segments = isArray(path) ? path : getParentSegmentsFromPath(path)\n\tif (segments.length === 0) return parentId\n\n\tlet folder = tree.get<EntityFolderNode | EntityTypeRootNode>(parentId)\n\tassert(folder && isValidEntityParentNode(folder), \"A reference must be in a folder.\")\n\n\tfor (const segment of segments) {\n\t\tconst existing = existingFolderWithName(folder, segment)\n\t\tif (existing) {\n\t\t\tfolder = existing\n\t\t\tcontinue\n\t\t}\n\n\t\tfolder = tree.insertNode(new EntityFolderNode({ name: segment }), folder.id)\n\t}\n\n\treturn folder.id\n}\n\n/**\n * Gets full path from an entity folder node id.\n *\n * @param engine  VekterEngine\n * @param id EntityFolderNode id\n * @returns The full path from folder node parent to root.\n */\nexport function getPathForEntityFolderNodeId(engine: VekterEngine, id: string): string {\n\tconst node = engine.tree.get(id)\n\tif (!isEntityFolderNode(node)) {\n\t\treturn \"\"\n\t}\n\n\tconst path = [node.name]\n\tfor (const ancestor of node.ancestors()) {\n\t\tif (!isEntityFolderNode(ancestor)) break\n\t\tpath.unshift(ancestor.name)\n\t}\n\n\treturn `/${path.join(\"/\")}`\n}\n\n/**\n * Gets path parts for a referenced node.\n *\n * @param tree The CanvasTree instance\n * @param node The CanvasNode to get path parts for\n * @param entityTypeRootId The entity type root id\n * @returns Array of path segments from folder node parent to the node\n */\nfunction getPathPartsForReferencedNode(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tentityTypeRootId: EntityTypeRootId,\n): string[] {\n\tconst entityReferenceId = buildReferenceNodeId(entityTypeRootId, node.id)\n\tconst entityReferenceNode = tree.get(entityReferenceId)\n\n\t// If the node has an entity reference node, we need to get the path from that node\n\t// There might be a path in the name if created from quick actions,\n\t// in which case we should make sure the name is extracted (/a/b/c -> c)\n\tconst path = [getNodeName(node)]\n\tif (entityReferenceNode) {\n\t\tfor (const ancestor of entityReferenceNode.ancestors()) {\n\t\t\tif (!isEntityFolderNode(ancestor)) break\n\t\t\tpath.unshift(getNodeName(ancestor))\n\t\t}\n\t}\n\treturn path\n}\n\nexport function getPathPartsForReferencedNodeId(\n\ttree: CanvasTree,\n\tid: NodeID,\n\tentityTypeRootId: EntityTypeRootId,\n): string[] {\n\tconst node = tree.get(id)\n\tassert(node, \"Node must exist\")\n\treturn getPathPartsForReferencedNode(tree, node, entityTypeRootId)\n}\n\nexport function getPathForReferencedNodeId(\n\ttree: CanvasTree,\n\tid: NodeID,\n\tentityTypeRootId: EntityTypeRootId,\n\toptions: { leadingSlash?: boolean } = { leadingSlash: true },\n): string {\n\tconst node = tree.get(id)\n\tassert(node, \"Node must exist\")\n\treturn getPathForReferencedNode(tree, node, entityTypeRootId, options)\n}\n\nexport function getPathForReferencedNode(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tentityTypeRootId: EntityTypeRootId,\n\toptions: { leadingSlash?: boolean } = { leadingSlash: true },\n): string {\n\tconst pathParts = getPathPartsForReferencedNode(tree, node, entityTypeRootId)\n\tconst path = pathParts.join(\"/\")\n\tif (!options.leadingSlash) return path\n\treturn `/${path}`\n}\n\n/**\n * Gets the path segments excluding the file name.\n * Returns an empty array if the path is empty or has no segments.\n *\n * @param path Full path string including the file name.\n * @returns The parent segments of the path, or empty array if no valid segments.\n */\nexport function getParentSegmentsFromPath(path: string): string[] {\n\tconst segments = splitPathToSegments(path)\n\treturn segments.slice(0, -1)\n}\n\n/**\n * Moves a node to a folder if it has a name. If the folder does not exist, it\n * will be created.\n */\nexport function createFolderStructureForNode(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tnewName: string,\n\tentityRootId: NodeID,\n): string | undefined {\n\tconst segments = splitPathToSegments(newName)\n\tif (segments.length === 0) return\n\n\tconst name = segments.pop()\n\tconst parentId = createEntityFolderNodesFromPath(tree, newName, entityRootId)\n\n\tconst isCodeFile = entityRootId === CODE_FILE_ENTITY_TYPE_ROOT_ID\n\tcreateReferenceForNodeIfNeeded(tree, parentId, node.id, isCodeFile)\n\n\tnode.set({ name })\n\n\treturn parentId\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { CanvasNode, CanvasTree } from \"../../index.ts\"\nimport type { ShallowWebPageNode } from \"../../nodes/WebPageNode.ts\"\nimport { isWebPageNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { localScreenComponentId } from \"../../nodes/utils/smartComponentInstanceHelpers.ts\"\nimport type { WithCodeComponent } from \"../WithCodeComponent.ts\"\nimport { withCodeComponent } from \"../WithCodeComponent.ts\"\n\n// The readonly property is added to make WebPageInstances type safe\ntype WebPageInstance = CanvasNode & WithCodeComponent & { readonly __isWebPageInstance: never }\n\nexport function isWebPageInstance<Node extends CanvasNode>(\n\ttree: CanvasTree,\n\tnode: Node,\n): node is Node & WebPageInstance {\n\tif (!withCodeComponent(node)) return false\n\tconst id = localScreenComponentId(node.codeComponentIdentifier)\n\tif (!id) return false\n\tconst scopeNode = tree.getNode(id)\n\treturn Boolean(scopeNode && isWebPageNode(scopeNode))\n}\n\nexport function getWebPageForInstance(tree: CanvasTree, node: WebPageInstance): ShallowWebPageNode {\n\tconst id = localScreenComponentId(node.codeComponentIdentifier)\n\tassert(id, \"WebPageInstance should have a local canvas component id\")\n\tconst scopeNode = tree.getNode(id)\n\tassert(scopeNode, \"SmartComponentInstance should have a local WebPageNode\")\n\tassert(isWebPageNode(scopeNode), \"WebPageInstance its WebPageNode should be a web page\")\n\treturn scopeNode\n}\n", "import type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\n\nexport type NodeIDsOrNodes = NodeID[] | CanvasNode[]\n\nexport const getNodesForNodeIDsOrNodes = (nodeIDsOrNodes: NodeIDsOrNodes, tree: CanvasTree) => {\n\tif (nodeIDsOrNodes.length === 0) return []\n\tif (typeof nodeIDsOrNodes[0] === \"string\") {\n\t\treturn tree.withoutDescendants(tree.getNodes(nodeIDsOrNodes as NodeID[]))\n\t} else {\n\t\treturn nodeIDsOrNodes as CanvasNode[]\n\t}\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { CodeComponentNode } from \"../CanvasTree/index.ts\"\nimport { getControlPropValues } from \"./getControlPropValues.ts\"\n\n/**\n * Get the control prop values including dynamic values and unresolved asset references. Slots and\n * event handlers are excluded.\n */\nexport function getCodeComponentControlPropValues(\n\tnode: CodeComponentNode,\n\tcomponentLoader: AnyComponentLoader,\n): Record<string, unknown> {\n\tconst propertyControls = componentLoader.getPropertyControlsForIdentifier(node.codeComponentIdentifier)\n\tif (!propertyControls) return {}\n\treturn getControlPropValues(propertyControls, node.getControlProps(propertyControls))\n}\n", "import type {\n\tPaidProjectLicenseType,\n\tProjectBase,\n\tProjectLicensePeriod,\n\tTeamAddOnLicenseType,\n\tTeamLicenseType,\n} from \"@framerjs/app-shared\"\nimport type { TeamSubscriptionSyncAction } from \"@framerjs/app-shared/src/ProjectState.ts\"\nimport type { ModalOpenSource, UpsellType } from \"@framerjs/events\"\nimport type {\n\tConfirmationModalButtonDirection,\n\tConfirmationModalConfirmationButtonVariant,\n\tConfirmationModalDismissButtonVariant,\n} from \"@framerjs/fresco/src/components/ConfirmationModal\"\nimport type { KeyboardConfirmMode } from \"@framerjs/fresco/src/components/Modal\"\nimport type { ExternalModuleExportIdentifier, GlobalModuleId, ModuleType, Prettify } from \"@framerjs/shared\"\nimport { List } from \"@framerjs/shared\"\nimport { EngineStore } from \"document/EngineStore.ts\"\nimport type { QuickActionsCategory } from \"document/components/chrome/QuickActions/types.ts\"\nimport type { LoadingFullDocumentModal } from \"document/components/chrome/shared/LoadingFullDocumentModal.tsx\"\nimport type { AddonInfo } from \"document/components/chrome/siteSettings/Plans/Stripe/addOns/useAddonPurchaseInfo.ts\"\nimport type { UpsellFeature } from \"document/components/chrome/siteSettings/Plans/Stripe/utils/upsell.ts\"\nimport type { CodeComponentIsolationMode } from \"document/components/unlinking/enterCodeComponentIsolation.ts\"\nimport type {\n\tCanvasTree,\n\tNodeID,\n\tShallowWebPageNode,\n\tSmartComponentNode,\n\tWebPageNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type { AbVariant } from \"document/models/CanvasTree/nodes/FunnelNode.ts\"\nimport type { VectorSetNode } from \"document/models/CanvasTree/nodes/VectorSetNode.ts\"\nimport type { Locale, LocaleId } from \"document/models/CanvasTree/traits/WithLocales.ts\"\nimport type { VariableID } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { isLocalesUndoRedoEntry, isVariableUndoRedoEntry } from \"document/utils/undoRedoEntryChecks.ts\"\nimport type { Rect } from \"library/index.ts\"\nimport type { RelativeNumber } from \"library/render/types/RelativeNumber.ts\"\nimport type { VekterPluginManifest } from \"plugins/plugins.ts\"\nimport type React from \"react\"\nimport { record } from \"web/lib/tracker.ts\"\nimport type { ImageUploadResult } from \"web/pages/project/lib/UploadService.ts\"\nimport type { InitialState as InitialPluginState } from \"#framer-plugin/initialState.ts\"\nimport type { Mode } from \"#framer-plugin/messages.ts\"\nimport type { UndoRedoEntry } from \"./UndoRedoManager.ts\"\n\nexport enum CodeFileCreationType {\n\tComponent = \"Component\",\n\tOverride = \"Override\",\n}\n\nexport type ModalProps<T extends ModalType> = Omit<Extract<Modal, { type: T }>, \"type\">\nexport type ActiveModalProps<T extends ModalType> = Omit<Extract<ActiveModal, { type: T }>, \"type\">\n\nexport interface ConfirmationConfiguration {\n\t/** The title text displayed at the top of the confirmation modal */\n\ttitle: string\n\t/** The main description or body content of the modal, can be a string or a React element */\n\tdescription: React.ReactNode\n\t/** The label shown on the primary confirm/action button */\n\tconfirmLabel?: string\n\t/** The label shown on the cancel button (defaults to a standard cancel string) */\n\tcancelLabel?: string\n\t/** Controls which keyboard shortcut triggers the confirm action */\n\tkeyboardConfirmMode?: KeyboardConfirmMode\n\t/** If true, pressing the Enter key triggers the cancel action */\n\tcancelOnEnter?: boolean\n\t/** If true, avoids dismissing the modal automatically after confirming (caller must handle dismissal) */\n\tavoidDismissOnConfirm?: boolean\n\t/** If true, disables dismissing the modal via outside clicks or escape; requires explicit user interaction */\n\tinteractionRequired?: boolean\n\t/** Function called when the user confirms (supports async logic) */\n\tonConfirm?: () => void | Promise<void>\n\t/** Optional function called when the user cancels */\n\tonCancel?: () => void\n\t/** Optional function called when the modal is dismissed, regardless of method */\n\tonDismiss?: () => void\n\t/** Button variant for the confirm/action button (visual style) */\n\tvariant?: ConfirmationModalConfirmationButtonVariant\n\t/** Button variant for the dismiss/cancel button (visual style) */\n\tdismissVariant?: ConfirmationModalDismissButtonVariant\n\t/** Layout direction of the confirm/cancel buttons */\n\tbuttonDirection?: ConfirmationModalButtonDirection\n\t/** If true, displays a backdrop behind the modal */\n\thasBackdrop?: boolean\n}\n\ntype ModalForComponent<T extends ModalType, C extends React.ComponentType<unknown>> = {\n\ttype: T\n} & React.ComponentProps<C>\n\nexport interface SwitchToYearlyCurrentItems {\n\tteamPlan: { quantity: number; licenseType: TeamLicenseType } | null\n\tteamAddons: { plan: string; quantity: number; licenseType: TeamAddOnLicenseType }[]\n}\n\nexport type Modal =\n\t| { type: ModalType.None }\n\t| { type: ModalType.AddToLibrary; moduleId: GlobalModuleId; exportSpecifier: string; path?: string }\n\t| { type: ModalType.BatchTranslate; localesWithKeyPaths: { locale: Locale; keyPaths: ReadonlySet<string> }[] }\n\t| { type: ModalType.ConfirmBatchTranslateAll; activeLocale: Locale }\n\t| { type: ModalType.ConfirmBatchTranslateLayers; nodeIds: NodeID[] }\n\t| { type: ModalType.ConfirmDefaultLanguage; onConfirm: () => void }\n\t| {\n\t\t\ttype: ModalType.CodeFileCreation\n\t\t\tcreationType?: CodeFileCreationType\n\t\t\tparentId?: NodeID\n\t  }\n\t| { type: ModalType.ConvertToCMSPage; webPageId: NodeID }\n\t| { type: ModalType.ConvertToKitPage; webPageIds: NodeID[]; createBlankKitPage?: boolean }\n\t| ({ type: ModalType.Confirmation } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmationPlugin } & ConfirmationConfiguration)\n\t| {\n\t\t\ttype: ModalType.ConfirmAcquireAddOn\n\t\t\ttitle: string\n\t\t\tdescription: string\n\t\t\taddonInfo: AddonInfo\n\t  }\n\t| ({ type: ModalType.ConfirmDeleteCollectionItems } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmDeleteCustomCode } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmCollectionItemStatusChange } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmHideAllInThisLocale } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmDraftLocale } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmPublishAbTest } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmDestructiveFeedbackAction; onConfirm: () => Promise<void> } & ConfirmationConfiguration)\n\t| ({ type: ModalType.StopAbTest } & {\n\t\t\tfunnelId: NodeID\n\t\t\tonConfirm: (params: {\n\t\t\t\tvariantId: NodeID\n\t\t\t\t/** Only set when the test is conclusive */\n\t\t\t\tlift: number | undefined\n\t\t\t\tabVariantsSnapshot: readonly AbVariant[]\n\t\t\t\tdeleteOtherVariants: boolean\n\t\t\t}) => Promise<void>\n\t  })\n\t| ({ type: ModalType.CreateAbTest } & { onConfirm: (selectedPageId: NodeID) => void })\n\t| ({ type: ModalType.ConfirmDraftPage } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmPublishDraftCollectionItem } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmPublishDraftLocale } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmPublishDraftPage } & ConfirmationConfiguration)\n\t| ({ type: ModalType.ConfirmUpdatingAbVariants } & ConfirmationConfiguration)\n\t| {\n\t\t\ttype: ModalType.CreateComponent\n\t\t\tonSuccess?: (node: SmartComponentNode) => void\n\t  }\n\t| { type: ModalType.CreateManagedCollection; manifest: VekterPluginManifest }\n\t| {\n\t\t\ttype: ModalType.CustomBreakpoint\n\t\t\tactionType: \"add\" | \"update\"\n\t\t\tbaseNodeId: NodeID\n\t\t\tname?: string\n\t\t\twidth?: number\n\t  }\n\t| { type: ModalType.DeleteCodeFile; path: string; onConfirm: () => Promise<void> }\n\t| { type: ModalType.DeleteEntityFolder; path: string; canDeleteFolder: boolean; onConfirm: () => Promise<void> }\n\t| { type: ModalType.DeleteCustomFont; assetKeysToDelete: string[] }\n\t| {\n\t\t\ttype: ModalType.DeleteFile\n\t\t\tpath: string\n\t\t\tisCodeFileInUse: boolean\n\t\t\tonConfirm: () => Promise<void>\n\t\t\thasBackdrop?: boolean\n\t\t\ttitle?: string\n\t  }\n\t| {\n\t\t\ttype: ModalType.DeleteMultipleEntityFolders\n\t\t\tpaths: string[]\n\t\t\tcanDeleteAll: boolean\n\t\t\tonConfirm: () => Promise<void>\n\t  }\n\t| {\n\t\t\ttype: ModalType.DeleteMultipleCodeFiles\n\t\t\tpaths: string[]\n\t\t\tcanDeleteAll: boolean\n\t\t\tonConfirm: () => Promise<void>\n\t  }\n\t| { type: ModalType.DuplicateProjectWithVersion }\n\t| { type: ModalType.DuplicateWebPage; duplicateFromId: string }\n\t| {\n\t\t\ttype: ModalType.ImageCrop\n\t\t\tinitialImage: string\n\t\t\tonChange: (croppedImageResult: Promise<ImageUploadResult[]>) => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.ImageFocalPoint\n\t\t\timage: string\n\t\t\tpositionX: RelativeNumber | undefined\n\t\t\tpositionY: RelativeNumber | undefined\n\t\t\tonChange: (positionX: RelativeNumber, positionY: RelativeNumber) => void\n\t  }\n\t| { type: ModalType.ImportFigma }\n\t| ModalForComponent<ModalType.LoadingFullDocument, typeof LoadingFullDocumentModal>\n\t| ({ type: ModalType.LocaleSettings } & (\n\t\t\t| { initialLocaleId: LocaleId; initialNewLocale?: undefined; initialLanguageCode?: undefined }\n\t\t\t| { initialNewLocale: true; initialLocaleId?: undefined; initialLanguageCode?: string }\n\t  ))\n\t| { type: ModalType.LocaleReady; activeLocale: Locale }\n\t| { type: ModalType.LocalizationGlossary }\n\t| { type: ModalType.NudgePreferences }\n\t| { type: ModalType.OverrideFile; path?: string; onConfirm: () => void }\n\t| {\n\t\t\ttype: ModalType.PlanCancellation\n\t\t\tprojectId: string\n\t\t\trefreshSubscriptions: () => Promise<void>\n\t\t\tnextBillDate: Date\n\t\t\tcurrentProjectLicenseType: PaidProjectLicenseType\n\t\t\tprice: string\n\t\t\tcurrency: string\n\t  }\n\t| { type: ModalType.PublishModule }\n\t| {\n\t\t\ttype: ModalType.QuickActions\n\t\t\tinitialCategory?: QuickActionsCategory\n\t\t\tinitialPluginState?: InitialPluginState\n\t  }\n\t| { type: ModalType.RemoveTeamLibraryModule; onCancel(): void; onConfirm(): void }\n\t| { type: ModalType.ReplaceTextStylePreset; presetId: NodeID }\n\t| { type: ModalType.Shortcuts }\n\t| { type: ModalType.FigmaImportTutorial }\n\t| {\n\t\t\ttype: ModalType.ApplyPromotionCode\n\t\t\tprojectId: string\n\t\t\tteamId: string\n\t\t\tonClose: () => void\n\t\t\tonSuccess: () => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.FlexToYearly\n\t\t\tteamId: string\n\t\t\tcurrency: string\n\t\t\teditorCount: number\n\t\t\tonClose: () => void\n\t\t\tonSuccess: () => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.SwitchToYearly\n\t\t\tteamId: string\n\t\t\tcurrency: string\n\t\t\tcurrentItems: SwitchToYearlyCurrentItems\n\t\t\tonClose: () => void\n\t\t\tonSuccess: () => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.ManageSeats\n\t\t\tteamId: string\n\t\t\tcurrency: string\n\t\t\tcurrentContentEditorQuantity: number\n\t\t\tcurrentEditorQuantity: number\n\t\t\tminAllowedEditorCount: number\n\t\t\tminAllowedContentEditorCount: number\n\t\t\tperiod: ProjectLicensePeriod\n\t\t\tonClose: () => void\n\t\t\tonSuccess: (targets: { editorQuantity: number; contentEditorQuantity: number }) => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.MigrateBilling\n\t\t\tteamId: string\n\t\t\thasMultipleSites: boolean\n\t\t\thasFlexEditors: boolean\n\t\t\tonClose: () => void\n\t\t\tonSuccess: () => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.UnlinkComponent\n\t\t\tidentifier: ExternalModuleExportIdentifier\n\t\t\tmoduleType: ModuleType | string\n\t\t\tnodeId?: string\n\t\t\tenterIsolation?: boolean\n\t\t\tcodeComponentIsolationMode?: CodeComponentIsolationMode\n\t  }\n\t| {\n\t\t\ttype: ModalType.UnsavedChanges\n\t\t\tdescription: string\n\t\t\tonConfirm: (action: \"discard\" | \"cancel\" | \"save\") => void\n\t  }\n\t| { type: ModalType.TransferProject; userEmail: string }\n\t| {\n\t\t\ttype: ModalType.UnsupportedFileSize\n\t\t\tsizeInKB: number\n\t\t\tmaxSizeInKB: number\n\t\t\tonRetry: () => unknown\n\t  }\n\t| { type: ModalType.UnsupportedFileType; extension: string; helpUrl: string; onRetry: () => unknown }\n\t| {\n\t\t\ttype: ModalType.SelectProjectToUpgrade\n\t\t\tteamId: string\n\t\t\tcurrentTeamLicense: TeamLicenseType\n\t\t\thasActiveSubscription: boolean\n\t\t\tonDismiss: () => void\n\t\t\tprojects?: ProjectBase[]\n\t  }\n\t| { type: ModalType.UpgradeDocument }\n\t| {\n\t\t\ttype: ModalType.UpsellFeature\n\t\t\ttitle: string\n\t\t\tdescription: React.ReactNode\n\t\t\tupsellFeature: UpsellFeature\n\t  }\n\t| { type: ModalType.Variables }\n\t| { type: ModalType.Welcome }\n\t| { type: ModalType.CompleteSignup }\n\t| {\n\t\t\ttype: ModalType.UpsellEnterprise\n\t\t\tdescription: string\n\t\t\tupsell: UpsellType\n\t\t\tupsellFeatures: string[]\n\t  }\n\t| { type: ModalType.DeprecatedDrafts }\n\t| {\n\t\t\ttype: ModalType.EditVector\n\t\t\tvectorSetNodeId: NodeID\n\t\t\tmoduleId: GlobalModuleId\n\t\t\titemCount: number\n\t\t\tinstanceNodeId?: NodeID\n\t  }\n\t| { type: ModalType.CreateTeam }\n\t| { type: ModalType.ImportRedirects }\n\t| { type: ModalType.ReplaceWebPage; oldNode: ShallowWebPageNode }\n\t| {\n\t\t\ttype: ModalType.RequestControl\n\t\t\tonConfirm: () => Promise<void>\n\t  }\n\t| {\n\t\t\ttype: ModalType.SubscriptionNotInOrder\n\t\t\tteamId: string\n\t\t\tteamSyncAction: TeamSubscriptionSyncAction\n\t\t\tisBillingV3: boolean\n\t\t\tcanReactivate: boolean\n\t  }\n\t| {\n\t\t\ttype: ModalType.PluginFromURL\n\t\t\tenvironment: \"development\" | \"default\"\n\t\t\tonSelectPlugin: (pluginManifest: VekterPluginManifest) => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.PluginWithModePicker\n\t\t\tmodes: Exclude<Mode, \"canvas\">[]\n\t\t\tonSelect: (pluginManifest: VekterPluginManifest, mode: Exclude<Mode, \"canvas\">) => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.AcquireAddonModal\n\t\t\taddonInfo: AddonInfo\n\t\t\tonSuccess?: () => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.BuyAiCreditsModal\n\t\t\tonSuccess?: () => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.CreateLayoutTemplate\n\t\t\twebPage?: WebPageNode\n\t\t\tonConfirm: (name: string) => void\n\t  }\n\t| ({\n\t\t\ttype: ModalType.ConfirmRemoveTriggerEvent\n\t  } & ConfirmationConfiguration)\n\t| {\n\t\t\ttype: ModalType.VectorImport\n\t\t\tsvgsToImport: File[]\n\t\t\tscopeId: NodeID\n\t\t\tcurrentVectorLayout?: Rect\n\t\t\tonSuccess?: (vectorSet: VectorSetNode) => void\n\t\t\tonCreateVectorSet?: (id: NodeID, itemsCount: number) => VectorSetNode\n\t  }\n\t| {\n\t\t\ttype: ModalType.VectorSetCreation\n\t\t\tonConfirm?: ((name: string) => void) | undefined\n\t  }\n\t| {\n\t\t\ttype: ModalType.VectorSetUnlink\n\t\t\tvectorSetNodeId: NodeID\n\t\t\titemCount: number\n\t\t\treplaceAll?: boolean\n\t\t\t/** The external vector module node ID (for finding the local vector after unlinking) */\n\t\t\tmoduleId?: GlobalModuleId\n\t\t\t/** The specific canvas instance (CodeComponentNode) to replace when not replacing all */\n\t\t\tinstanceNodeId?: NodeID\n\t\t\tonSuccess?: (vectorSet: VectorSetNode, localVectorId?: NodeID) => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.OnPageCMSFieldsModal\n\t\t\tfieldIdsToShow: VariableID[]\n\t\t\trequiredFieldsOnly: boolean\n\t\t\tcollectionNodeId: NodeID\n\t\t\tcollectionItemId: NodeID\n\t  }\n\t| {\n\t\t\ttype: ModalType.OnPageRichTextEditor\n\t\t\tcontrolKey: string\n\t\t\tnodeId: NodeID\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardAddFile\n\t\t\taction: \"add\"\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardAddRedirect\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardAddHeader\n\t\t\taction: \"add\"\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardAddRewrite\n\t\t\taction: \"add\"\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardEditFile\n\t\t\taction: \"edit\"\n\t\t\tnodeId: NodeID\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardEditHeader\n\t\t\taction: \"edit\"\n\t\t\tnodeId: NodeID\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardEditRedirect\n\t\t\tredirectNodeId: NodeID\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardEditRewrite\n\t\t\taction: \"edit\"\n\t\t\tnodeId: NodeID\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardRequestProjectAccess\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardUnsupportedFileType\n\t\t\textension: string\n\t\t\thelpUrl: string\n\t\t\tonRetry: () => unknown\n\t\t\tonCancel: () => void\n\t\t\tonDismiss: () => void\n\t  }\n\t| {\n\t\t\ttype: ModalType.DashboardAcquireAddonModal\n\t\t\tonSuccess?: () => void\n\t\t\taddonInfo: AddonInfo\n\t  }\n\t| {\n\t\t\ttype: ModalType.OnPageRichTextVariantOverride\n\t\t\trichTextNodeId: string\n\t  }\n\t| { type: ModalType.Templates }\n\t| { type: ModalType.ViewCustomCode; customCodeId: NodeID }\n\t| { type: ModalType.EditCustomCode; customCodeId: NodeID | null; initialPageId?: NodeID }\n\t| { type: ModalType.KitRemix }\n\t| { type: ModalType.LayoutTemplateFlowEffectRegeneration; onSuccess?: () => void }\n\nconst noModal: ActiveModal = { type: ModalType.None, source: \"undefined\" }\n\nexport type ActiveModal = Modal & { source: ModalOpenSource }\n\ntype ActiveModalByTypeMap = {\n\t[T in ModalType]: Prettify<Extract<ActiveModal, { type: T }>>\n}\n\nexport class ModalStore extends EngineStore {\n\tprivate _stack: readonly ActiveModal[] = []\n\n\tget stack(): readonly ActiveModal[] {\n\t\treturn this._stack\n\t}\n\n\tget active(): ActiveModal {\n\t\tconst lastItem = this._stack[this._stack.length - 1]\n\t\treturn lastItem ?? noModal\n\t}\n\n\tprivate trackModalOpen({ type, source }: ActiveModal) {\n\t\trecord(\"modal_open\", { modalType: type, source })\n\t}\n\n\tpush<T extends ModalType>(modal: ActiveModalByTypeMap[T]) {\n\t\tthis._stack = List.push(this._stack, modal)\n\t\tthis.trackModalOpen(modal)\n\t}\n\n\tset<T extends ModalType>(modal: ActiveModalByTypeMap[T]) {\n\t\tthis._stack = [modal]\n\t\tthis.trackModalOpen(modal)\n\t}\n\n\t/** Dismiss the top most modal. */\n\tdismiss = () => {\n\t\tthis._stack = List.pop(this._stack)\n\t}\n\n\tdismissAll() {\n\t\tif (this._stack.length === 0) return\n\t\tthis._stack = []\n\t}\n\n\t/** Dismiss all modals of a a given type. */\n\tdismissModal(type: ModalType) {\n\t\tthis._stack = List.filter(this._stack, modal => modal.type !== type)\n\t}\n\n\tisVisible = () => {\n\t\treturn this.active.type !== ModalType.None\n\t}\n\n\tshouldBlockUndoRedo = (undoRedoEntry: UndoRedoEntry | undefined, tree: CanvasTree) => {\n\t\tconst activeType = this.active.type\n\t\tswitch (activeType) {\n\t\t\tcase ModalType.None:\n\t\t\t\treturn false\n\t\t\tcase ModalType.Variables:\n\t\t\t\treturn !isVariableUndoRedoEntry(undoRedoEntry, tree)\n\t\t\tcase ModalType.LocaleSettings:\n\t\t\t\treturn !isLocalesUndoRedoEntry(undoRedoEntry, tree)\n\t\t\tdefault:\n\t\t\t\treturn true\n\t\t}\n\t}\n}\n", "import type { CollectionItemNode } from \"document/models/CanvasTree/index.ts\"\n\ninterface CollectionItemVisibilityContext {\n\tcurrentUserId: string | undefined\n}\n\nexport function isCurrentUserPrivateDraftCollectionItem(\n\titem: CollectionItemNode,\n\t{ currentUserId }: CollectionItemVisibilityContext,\n) {\n\treturn Boolean(currentUserId) && Boolean(item.parentid) && item.privateToUserId === currentUserId\n}\n\nexport function isCollectionItemVisibleToCurrentUser(\n\titem: CollectionItemNode,\n\t{ currentUserId }: CollectionItemVisibilityContext,\n) {\n\treturn !item.privateToUserId || item.privateToUserId === currentUserId\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { EngineStore } from \"document/EngineStore.ts\"\nimport type { CanvasNode, CanvasTree, MaybeNodeID, NodeID, ScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport { isCollectionItemNode, isCollectionNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isCollectionItemVisibleToCurrentUser as isCollectionItemVisibleToUser } from \"document/utils/collectionItemVisibility.ts\"\nimport { isShallowArrayEqual } from \"utils/isShallowEqual.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport type { ChromeStore } from \"./ChromeStore.ts\"\nimport type { GuidesStore } from \"./GuidesStore.ts\"\nimport type { OverlayStore } from \"./OverlayStore.ts\"\nimport type { SessionStore } from \"./SessionStore.ts\"\n\nexport type Selection = NodeID[]\ntype Selectable = NodeID | CanvasNode | Iterable<NodeID> | Iterable<CanvasNode>\n\nfunction getIdsFromSelectable(selectable: Selectable): Selection {\n\tif (isString(selectable)) {\n\t\treturn [selectable]\n\t}\n\n\tif (\"id\" in selectable) {\n\t\treturn [selectable.id]\n\t}\n\n\tconst result: Selection = []\n\n\tfor (const item of selectable) {\n\t\tif (isString(item)) {\n\t\t\tresult.push(item)\n\t\t} else {\n\t\t\tresult.push(item.id)\n\t\t}\n\t}\n\n\treturn result\n}\n\nexport function isSelectionEqual(oldSelection: Selection, newSelection: Selection) {\n\tif (oldSelection === newSelection) return true\n\tif (oldSelection.length !== newSelection.length) return false\n\n\tconst oldIds = new Set(oldSelection)\n\n\tfor (const id of newSelection) {\n\t\tconst inOldSelection = oldIds.has(id)\n\t\tif (!inOldSelection) return false\n\t}\n\n\treturn true\n}\n\ninterface Options {\n\tsticky?: boolean\n\tswitchToLayers?: boolean\n\tswitchToProperties?: boolean\n\t/**\n\t * When updating the selection after undo/redo the tree is not yet\n\t * committed, but contains the latest information about what is selectable.\n\t * Provide it so we can show the correct overlays.\n\t */\n\ttree?: CanvasTree\n}\n\nexport class SelectionStore extends EngineStore {\n\tprivate _previousIds: Selection = []\n\tprivate _ids: Selection = []\n\tprivate _nodes: CanvasNode[] = []\n\tprivate _isSticky = false // Makes it harder to select descendants\n\tprivate _commonGroundNode?: CanvasNode\n\n\tgradientStopId: NodeID | undefined = undefined\n\n\tconstructor(\n\t\tprivate readonly guides: GuidesStore,\n\t\tprivate readonly chromeStore: ChromeStore,\n\t\tprivate readonly overlayStore: OverlayStore,\n\t\tprivate readonly sessionStore: SessionStore,\n\t) {\n\t\tsuper()\n\t}\n\n\tget ids() {\n\t\treturn this._ids\n\t}\n\n\tget nodes() {\n\t\treturn this._nodes\n\t}\n\n\tget isSticky() {\n\t\treturn this._isSticky\n\t}\n\n\tget commonGroundNode() {\n\t\treturn this._commonGroundNode\n\t}\n\n\tget commonGroundNodeId(): MaybeNodeID {\n\t\treturn this._commonGroundNode?.id ?? null\n\t}\n\n\tget previousIds() {\n\t\treturn this._previousIds\n\t}\n\n\tset(selectable: Selectable, options: Options = {}) {\n\t\tconst ids = getIdsFromSelectable(selectable)\n\n\t\tconst isEqual = isSelectionEqual(this._ids, ids)\n\t\tif (isEqual) return\n\n\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\tconst uniqueIds = new Set(ids)\n\t\t\tassert(uniqueIds.size === ids.length, \"Selection contains duplicated ids\")\n\t\t}\n\t\tthis._previousIds = this._ids\n\t\tthis._ids = ids\n\t\tthis._isSticky = options.sticky ?? ids.length > 1\n\n\t\t// FIXME: This should be solved by store dependencies once they are merged:\n\t\t// https://github.com/framer/FramerStudio/pull/6208\n\t\tif (ids.length > 0) {\n\t\t\tthis.guides.clearSelected()\n\t\t}\n\t\t// By default assume that we don't want to switch to the layers tab\n\t\tconst { switchToLayers = false, switchToProperties = false, tree } = options\n\t\tthis.chromeStore.onCanvasSelectionChange(ids, switchToLayers, switchToProperties)\n\t\tthis.overlayStore.onCanvasSelectionChange(ids, { tree })\n\t}\n\n\ttoggle(\n\t\tselectable: Selectable,\n\t\t{\n\t\t\tswitchToLayers = false,\n\t\t\tswitchToProperties = false,\n\t\t}: { switchToLayers?: boolean; switchToProperties?: boolean } = {},\n\t) {\n\t\tconst ids = getIdsFromSelectable(selectable)\n\t\tconst newIds = new Set(this.ids)\n\n\t\tfor (const id of ids) {\n\t\t\tconst containsId = newIds.has(id)\n\n\t\t\tif (containsId) {\n\t\t\t\tnewIds.delete(id)\n\t\t\t} else {\n\t\t\t\tnewIds.add(id)\n\t\t\t}\n\t\t}\n\n\t\tthis._ids = Array.from(newIds)\n\t\tthis.chromeStore.onCanvasSelectionChange(this.ids, switchToLayers, switchToProperties)\n\t\tthis.overlayStore.onCanvasSelectionChange(newIds, { toggle: true })\n\t}\n\n\tclear() {\n\t\tthis.set([])\n\t}\n\n\tupdateNodes(tree: CanvasTree) {\n\t\tconst nodes = tree.getNodes(this.ids)\n\t\tconst nodesChanged = !isShallowArrayEqual(this.nodes, nodes)\n\t\tif (nodesChanged) {\n\t\t\tthis._nodes = nodes\n\t\t}\n\n\t\tif (\n\t\t\tnodesChanged ||\n\t\t\t// Common ground node stopped being a ground node.\n\t\t\t(this.commonGroundNode && !tree.isGroundNode(this.commonGroundNode))\n\t\t) {\n\t\t\tthis.updateCommonGroundNode(tree)\n\t\t}\n\t}\n\n\tprivate updateCommonGroundNode(tree: CanvasTree) {\n\t\tlet candidate: CanvasNode | undefined\n\n\t\tfor (const node of this.nodes) {\n\t\t\tconst groundNode = tree.getGroundNodeFor(node)\n\t\t\tif (!candidate) {\n\t\t\t\tcandidate = groundNode\n\t\t\t} else if (candidate !== groundNode) {\n\t\t\t\t// Selection has different ground nodes\n\t\t\t\tcandidate = undefined\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tthis._commonGroundNode = candidate\n\t}\n\n\tpostProcess(\n\t\ttree: CanvasTree,\n\t\tscope: ScopeNode,\n\t\tpreviousTree: CanvasTree,\n\t\tgradientStopId = this.gradientStopId,\n\t\tselection = this._ids,\n\t) {\n\t\tthis.gradientStopId = gradientStopId\n\n\t\tconst newSelection: Selection = []\n\t\tfor (const id of selection) {\n\t\t\tconst node = tree.getNode(id)\n\t\t\tif (node) {\n\t\t\t\tif (isCollectionItemNode(node) && !this.isCollectionItemVisibleToCurrentUser(node)) {\n\t\t\t\t\tthis.selectCollectionForInvalidCollectionItem(tree, node, newSelection)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// Hidden masters are on the root node and therefore filtered out as well.\n\t\t\t\tif (tree.isAncestorOfNode(node, scope.id)) {\n\t\t\t\t\tnewSelection.push(id)\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// When a selected collection item is removed via multiplayer or a plugin call, we want\n\t\t\t// to select the collection itself instead of nothing at all, otherwise it results in a\n\t\t\t// jarring experience. Only one collection item can be selected at a time\n\t\t\t// (multi-selection is done via `ContentManagementStore`), so, just to make sure that\n\t\t\t// nothing unexpected slips through, the selection is cleared and set to the collection\n\t\t\t// of the removed item.\n\n\t\t\tconst previousCollectionItemNode = previousTree.getNode(id)\n\t\t\tif (!isCollectionItemNode(previousCollectionItemNode)) continue\n\n\t\t\tthis.selectCollectionForInvalidCollectionItem(tree, previousCollectionItemNode, newSelection)\n\t\t\tbreak\n\t\t}\n\n\t\tthis.set(newSelection, { tree })\n\t\tthis.updateNodes(tree)\n\t}\n\n\tprivate isCollectionItemVisibleToCurrentUser(node: CanvasNode) {\n\t\tif (!isCollectionItemNode(node)) return true\n\t\treturn isCollectionItemVisibleToUser(node, { currentUserId: this.sessionStore.user.id })\n\t}\n\n\tprivate selectCollectionForInvalidCollectionItem(\n\t\ttree: CanvasTree,\n\t\tcollectionItemNode: CanvasNode,\n\t\tnewSelection: Selection,\n\t) {\n\t\tconst collectionNode = tree.getNode(collectionItemNode.parentid)\n\t\tif (!isCollectionNode(collectionNode)) return\n\n\t\tnewSelection.splice(0, newSelection.length, collectionNode.id)\n\t}\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { CanvasNode, CanvasTree, CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { ReplicaOverrides } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { IsBreakpoint, IsTopLevelVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport type { ControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { prefixControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport type { EnumControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\n\ninterface VariantControlInfo {\n\tkey: string\n\tcontrol: EnumControlDescription\n\tdefaultVariant: string\n}\n\nexport function findVariantControlInfo(\n\tcomponentLoader: AnyComponentLoader,\n\tnode: CodeComponentNode,\n): VariantControlInfo | null {\n\tconst component = componentLoader.componentForIdentifier(node.codeComponentIdentifier)\n\tif (!component?.properties) return null\n\tconst variantControl = Object.entries(component.properties).find(([, description]) => {\n\t\treturn description && description.title === \"Variant\" && description.type === ControlType.Enum\n\t}) as [string, EnumControlDescription] | undefined\n\tif (!variantControl) return null\n\tconst [key, control] = variantControl\n\tif (control.options.length <= 1) return null\n\tconst defaultVariant = control.defaultValue ?? control.options[0]\n\tif (!isString(defaultVariant)) return null\n\treturn { key, control, defaultVariant }\n}\n\nexport function findMatchingVariant(\n\tbreakPointName: string,\n\t{ control: variantControl }: VariantControlInfo,\n): string | null {\n\tconst lowercaseBreakpointName = breakPointName.toLowerCase().trim()\n\tconst options = variantControl.optionTitles ?? variantControl.options\n\tconst variantIndex = options.findIndex(option => isString(option) && option.toLowerCase() === lowercaseBreakpointName)\n\tif (variantIndex === -1) return null\n\tconst variant = variantControl.options[variantIndex]\n\treturn isString(variant) ? variant : null\n}\n\nexport function overridesToMakeVariantsMatchNewBreakpoint(\n\tcomponentLoader: AnyComponentLoader,\n\ttree: CanvasTree,\n\tbreakPointName: string,\n\tbaseVariant: CanvasNode & IsTopLevelVariant & IsBreakpoint,\n): ReplicaOverrides | null {\n\tconst newOverrides: ReplicaOverrides = {}\n\n\tfor (const node of baseVariant.walk()) {\n\t\tif (!isCodeComponentNode(node)) continue\n\t\tconst controlInfo = findVariantControlInfo(componentLoader, node)\n\t\tif (!controlInfo) continue\n\t\tconst variant = findMatchingVariant(breakPointName, controlInfo)\n\t\tif (!variant) continue\n\t\tlet originalNode: Readonly<CodeComponentNode> | null = node\n\t\tif (isReplicaChild(node)) {\n\t\t\toriginalNode = tree.getNode<CodeComponentNode>(node.originalid)\n\t\t}\n\t\tif (!originalNode) continue\n\t\tconst originalVariant = originalNode.getRawControlProp(controlInfo.key) ?? controlInfo.defaultVariant\n\t\tif (originalVariant === variant) continue\n\n\t\tconst controlProp: ControlProp = {\n\t\t\ttype: ControlType.Enum,\n\t\t\tvalue: variant,\n\t\t}\n\t\tnewOverrides[originalNode.id] = { [prefixControlPropKey(controlInfo.key)]: controlProp }\n\t}\n\n\treturn Object.keys(newOverrides).length > 0 ? newOverrides : null\n}\n", "import type { WithFilters } from \"document/models/CanvasTree/traits/WithFilters.ts\"\n\nexport const filterKeys: (keyof WithFilters)[] = [\n\t\"blur\",\n\t\"backgroundBlur\",\n\t\"brightness\",\n\t\"contrast\",\n\t\"grayscale\",\n\t\"hueRotate\",\n\t\"invert\",\n\t\"saturate\",\n\t\"sepia\",\n]\n", "import type { WithPath } from \"library/render/traits/Path.ts\"\nimport type { WithAltText } from \"./WithAltText.ts\"\nimport type { WithAspectRatio } from \"./WithAspectRatio.ts\"\nimport type { WithBackdrop } from \"./WithBackdrop.ts\"\nimport type { WithBlending } from \"./WithBlending.ts\"\nimport type { WithBorder } from \"./WithBorder.ts\"\nimport type { WithBoxShadow } from \"./WithBoxShadow.ts\"\nimport type { WithCornerShape } from \"./WithCornerShape.ts\"\nimport type { WithCursor } from \"./WithCursor.ts\"\nimport type { WithCustomizations } from \"./WithCustomizations.ts\"\nimport type { WithDraggable } from \"./WithDraggable.ts\"\nimport type { WithExport } from \"./WithExport.ts\"\nimport type { WithFillImageAlts, WithOptionalFill } from \"./WithFill.ts\"\nimport type { WithFilters } from \"./WithFilters.ts\"\nimport type { WithFlowEffect } from \"./WithFlowEffect.ts\"\nimport type { WithFrameEvents } from \"./WithFrameEvents.ts\"\nimport type { WithFramePreset } from \"./WithFramePreset.ts\"\nimport type { WithGridItemSize } from \"./WithGridItemSize.ts\"\nimport type { WithGuides } from \"./WithGuides.ts\"\nimport type { WithImageRendering } from \"./WithImageRendering.ts\"\nimport type { WithIntrinsicSize } from \"./WithIntrinsicSize.ts\"\nimport type { WithItemsOrder } from \"./WithItemsOrder.ts\"\nimport type { WithLayout } from \"./WithLayout.ts\"\nimport type { WithLink } from \"./WithLink.ts\"\nimport type { WithLinkStyle } from \"./WithLinkStyle.ts\"\nimport type { WithMasks } from \"./WithMasks.ts\"\nimport type { WithName } from \"./WithName.ts\"\nimport type { WithOpacity } from \"./WithOpacity.ts\"\nimport type { WithOverflow } from \"./WithOverflow.ts\"\nimport type { WithOverlayGrid } from \"./WithOverlayGrid.ts\"\nimport type { WithOverscrollBehavior } from \"./WithOverscrollBehavior.ts\"\nimport type { WithPadding } from \"./WithPadding.ts\"\nimport type { WithParagraphSpacing } from \"./WithParagraphSpacing.ts\"\nimport type { WithPins } from \"./WithPins.ts\"\nimport type { WithPointerEvents } from \"./WithPointerEvents.ts\"\nimport type { WithPolygon } from \"./WithPolygon.ts\"\nimport type { WithPosition } from \"./WithPosition.ts\"\nimport type { WithPositionType } from \"./WithPositionType.ts\"\nimport type { WithRadius, WithRelativeRadius } from \"./WithRadius.ts\"\nimport type { WithRadiusPerCorner } from \"./WithRadiusPerCorner.ts\"\nimport type { WithRichText } from \"./WithRichText.ts\"\nimport type { WithRootFontSize } from \"./WithRootFontSize.ts\"\nimport type { WithRotation } from \"./WithRotation.ts\"\nimport type { WithScrollTarget } from \"./WithScrollTarget.ts\"\nimport type { WithScrollbars } from \"./WithScrollbars.ts\"\nimport type { WithShadow } from \"./WithShadow.ts\"\nimport type { WithSize } from \"./WithSize.ts\"\nimport type { WithSizeConstraints } from \"./WithSizeConstraints.ts\"\nimport type { WithSizeToFit } from \"./WithSizeToFit.ts\"\nimport type { WithSpikes } from \"./WithSpikes.ts\"\nimport type { WithStroke } from \"./WithStroke.ts\"\nimport type { WithStylePresets } from \"./WithStylePresets.ts\"\nimport type { WithStyledText } from \"./WithStyledText.ts\"\nimport type { WithTapHighlight } from \"./WithTapHighlight.ts\"\nimport type { WithTextContent } from \"./WithTextContent.ts\"\nimport type { WithTextFit } from \"./WithTextFit.ts\"\nimport type { WithTextSelection } from \"./WithTextSelection.ts\"\nimport type { WithTextStyle } from \"./WithTextStyle.ts\"\nimport type { WithTextVerticalAlignment } from \"./WithTextVerticalAlignment.ts\"\nimport type { WithTextWrapBalance } from \"./WithTextWrapBalance.ts\"\nimport type { WithTransforms } from \"./WithTransforms.ts\"\nimport type { WithTransition } from \"./WithTransition.ts\"\nimport type { WithUserSelect } from \"./WithUserSelect.ts\"\nimport type { WithBreakpoint, WithGesture, WithVariant } from \"./WithVariant.ts\"\nimport type { WithViewTransitionNone } from \"./WithViewTransitionNone.ts\"\nimport type { WithViewport } from \"./WithViewport.ts\"\nimport type { WithVisibility } from \"./WithVisibility.ts\"\nimport type { WithZIndex } from \"./WithZIndex.ts\"\nimport type { WithFormBooleanInputType } from \"./forms/WithFormBooleanInputType.ts\"\nimport type { WithFormInputFocusedStyles } from \"./forms/WithFormInputFocusedStyles.ts\"\nimport type { WithFormInputIcon } from \"./forms/WithFormInputIcon.ts\"\nimport type { WithFormInputInvalidStyles } from \"./forms/WithFormInputInvalidStyles.ts\"\nimport type { WithFormInputPlaceholder } from \"./forms/WithFormInputPlaceholder.ts\"\nimport type { WithFormInputStep } from \"./forms/WithFormInputStep.ts\"\nimport type { WithFormInputFontStyles } from \"./forms/WithFormInputTextStyles.ts\"\nimport type { WithFormTextInputType } from \"./forms/WithTextInputType.ts\"\n\nexport enum TraitType {\n\t_,\n\tAccessibility = \"accessibility\",\n\tAction = \"action\",\n\tAnchorLinkOffsetY = \"anchorLinkOffsetY\",\n\tBackfaceVisibility = \"backfaceVisibility\",\n\tBackgroundBlur = \"backgroundBlur\",\n\tBlending = \"blending\",\n\tBlur = \"blur\",\n\tBorder = \"border\",\n\tBrightness = \"brightness\",\n\tCanvasSettings = \"canvasSettings\",\n\tCodeOverride = \"codeOverride\",\n\tContrast = \"contrast\",\n\tControlProps = \"controlProps\",\n\tCornerShape = \"cornerShape\",\n\tCursor = \"cursor\",\n\tCustomCursor = \"customCursor\",\n\tCustomizations = \"customizations\",\n\tDraggable = \"draggable\",\n\tEffects = \"effects\",\n\tFill = \"fill\",\n\tFillImageAlts = \"fillImageAlts\",\n\tFlowEffect = \"flowEffect\",\n\tFont = \"font\",\n\tFontSize = \"fontSize\",\n\tForm = \"form\",\n\tFormBooleanInputCheckedEffect = \"formBooleanInputCheckedEffect\",\n\tFormBooleanInputType = \"formBooleanInputType\",\n\tFormBooleanInputValue = \"formBooleanInputValue\",\n\tFormInputColor = \"formInputColor\",\n\tFormInputFocusedBorder = \"formInputFocusedBorder\",\n\tFormInputFocusedBoxShadow = \"formInputFocusedBoxShadow\",\n\tFormInputFocusedFill = \"formInputFocusedFill\",\n\tFormInputFocusedTransition = \"formInputFocusedTransition\",\n\tFormInputFont = \"formInputFont\",\n\tFormInputIcon = \"formInputIcon\",\n\tFormInputInvalidTextColor = \"formInputInvalidTextColor\",\n\tFormInputLabelColor = \"formInputLabelColor\",\n\tFormInputLabelFont = \"formInputLabelFont\",\n\tFormInputMaxLength = \"formInputMaxLength\",\n\tFormInputPadding = \"formInputPadding\",\n\tFormInputStep = \"formInputStep\",\n\tFormInputTextAreaResize = \"formInputTextAreaResize\",\n\tFormLabelFont = \"formLabelFont\",\n\tFormPlaceholderColor = \"formPlaceholderColor\",\n\tFormTextInputType = \"formTextInputType\",\n\tFormTextInputTypeMax = \"formTextInputTypeMax\",\n\tFormTextInputTypeMin = \"formTextInputTypeMin\",\n\tGrayscale = \"grayscale\",\n\tHueRotate = \"hueRotate\",\n\tImageRendering = \"imageRendering\",\n\tIntrinsicSize = \"intrinsicSize\",\n\tInvert = \"invert\",\n\tItemsOrder = \"itemsOrder\",\n\tLayout = \"layout\",\n\tLetterSpacing = \"letterSpacing\",\n\tLineHeight = \"lineHeight\",\n\tLink = \"link\",\n\tLinkStyle = \"linkStyle\",\n\tMask = \"mask\",\n\tName = \"name\",\n\tOpacity = \"opacity\",\n\tOpenTypeFontFeatures = \"openTypeFontFeatures\",\n\tOverflow = \"overflow\",\n\tOverflowX = \"overflowX\",\n\tOverflowY = \"overflowY\",\n\tOverlay = \"overlay\",\n\tOverlayTransition = \"overlayTransition\",\n\tOverscroll = \"overscroll\",\n\tPadding = \"padding\",\n\tParagraphSpacing = \"paragraphSpacing\",\n\tPath = \"vectorPath\",\n\tPerspective = \"perspective\",\n\tPointerEvents = \"pointerEvents\",\n\tPosition = \"position\",\n\tPositionType = \"positionType\",\n\tRadius = \"radius\",\n\tRichText = \"richText\",\n\tRootFontSize = \"rootFontSize\",\n\tRotation = \"rotation\",\n\tSaturate = \"saturate\",\n\tScale = \"scale\",\n\tScrollbars = \"scrollbars\",\n\tScrollTarget = \"scrollTarget\",\n\tSepia = \"sepia\",\n\tShadows = \"shadows\",\n\tSize = \"size\",\n\tSizeConstraints = \"sizeConstraints\",\n\tSkew = \"skew\",\n\tStroke = \"stroke\",\n\tStyledText = \"styledText\",\n\tStylePresets = \"stylePresets\",\n\tTapHighlight = \"tapHighlight\",\n\tTextAlignment = \"textAlignment\",\n\tTextBackgroundColor = \"textBackgroundColor\",\n\tTextBackgroundCornerShape = \"textBackgroundCornerShape\",\n\tTextBackgroundPadding = \"textBackgroundPadding\",\n\tTextBackgroundRadius = \"textBackgroundRadius\",\n\tTextColor = \"textColor\",\n\tTextContent = \"textContent\",\n\tTextDecoration = \"textDecoration\",\n\tTextSelection = \"textSelection\",\n\tTextStroke = \"textStroke\",\n\tTextTransform = \"textTransform\",\n\tTextTruncation = \"textTruncation\",\n\tTextVerticalAlignment = \"textVerticalAlignment\",\n\tTextWrapBalance = \"textWrapBalance\",\n\tTransformOrigin = \"transformOrigin\",\n\tTransformStylePreserve3d = \"transformStylePreserve3d\",\n\tTransition = \"transition\",\n\tTranslateZ = \"translateZ\",\n\tTriggerActions = \"triggerActions\",\n\tUnknown = \"unknown\",\n\tUserSelect = \"userSelect\",\n\tViewTransitionNone = \"viewTransitionNone\",\n\tVisibility = \"visibility\",\n\tZIndex = \"zIndex\",\n}\n\n// TODO: This is not an exhaustive list, but only what is required for Frames.\ntype TraitTypeKey =\n\t| keyof Pick<WithItemsOrder, \"itemsOrder\">\n\t| keyof WithAltText\n\t| keyof WithAspectRatio\n\t| keyof WithBackdrop\n\t| keyof WithBlending\n\t| keyof WithBorder\n\t| keyof WithBoxShadow\n\t| keyof WithBreakpoint\n\t| keyof WithCursor\n\t| keyof WithCustomizations\n\t| keyof WithCornerShape\n\t| keyof WithExport\n\t| keyof WithFilters\n\t| keyof WithFlowEffect\n\t| keyof WithFrameEvents\n\t| keyof WithFramePreset\n\t| keyof WithFormInputStep\n\t| keyof WithGesture\n\t| keyof WithGridItemSize\n\t| keyof WithGuides\n\t| keyof WithImageRendering\n\t| keyof WithIntrinsicSize\n\t| keyof WithLayout\n\t| keyof WithLink\n\t| keyof WithLinkStyle\n\t| keyof WithMasks\n\t| keyof WithName\n\t| keyof WithOpacity\n\t| keyof WithOptionalFill\n\t| keyof WithFillImageAlts\n\t| keyof WithOverflow\n\t| keyof WithOverlayGrid\n\t| keyof WithOverscrollBehavior\n\t| keyof WithPadding\n\t| keyof WithParagraphSpacing\n\t| keyof WithPath\n\t| keyof WithPins\n\t| keyof WithPointerEvents\n\t| keyof WithPolygon\n\t| keyof WithPosition\n\t| keyof WithPositionType\n\t| keyof WithRadius\n\t| keyof WithRadiusPerCorner\n\t| keyof WithRelativeRadius\n\t| keyof WithRichText\n\t| keyof WithRotation\n\t| keyof WithScrollbars\n\t| keyof WithScrollTarget\n\t| keyof WithTextSelection\n\t| keyof WithShadow\n\t| keyof WithSize\n\t| keyof WithSizeConstraints\n\t| keyof WithSizeToFit\n\t| keyof WithSpikes\n\t| keyof WithStroke\n\t| keyof WithStyledText\n\t| keyof WithStylePresets\n\t| keyof WithTapHighlight\n\t| keyof WithTextContent\n\t| keyof WithTextFit\n\t| keyof WithTextStyle\n\t| keyof WithTextVerticalAlignment\n\t| keyof WithTextWrapBalance\n\t| keyof WithTransforms\n\t| keyof WithRootFontSize\n\t| keyof WithDraggable\n\t| keyof WithUserSelect\n\t| keyof WithVariant\n\t| keyof WithVisibility\n\t| keyof WithFormTextInputType\n\t| keyof WithZIndex\n\t| keyof WithTransition\n\t| keyof WithMasks\n\t| keyof WithFormInputFocusedStyles\n\t| keyof WithFormInputIcon\n\t| keyof Pick<WithFormInputPlaceholder, \"formInputPlaceholderColor\">\n\t| keyof WithFormInputFontStyles\n\t| keyof WithFormInputInvalidStyles\n\t| keyof WithFormBooleanInputType\n\t| keyof WithViewport\n\t| keyof WithViewTransitionNone\n\n// todo: inspect the trait type groupings in this map to see if they ring true\nexport const traitTypeMap: Record<TraitTypeKey, TraitType> = {\n\tleft: TraitType.Position,\n\tright: TraitType.Position,\n\ttop: TraitType.Position,\n\tbottom: TraitType.Position,\n\tcenterAnchorX: TraitType.Position,\n\tcenterAnchorY: TraitType.Position,\n\tconstraintsLocked: TraitType.Position,\n\n\tx: TraitType.Position,\n\ty: TraitType.Position,\n\n\twidth: TraitType.Size,\n\twidthType: TraitType.Size,\n\theight: TraitType.Size,\n\theightType: TraitType.Size,\n\taspectRatio: TraitType.Size,\n\n\titemsOrder: TraitType.ItemsOrder,\n\n\tlayout: TraitType.Layout,\n\tgap: TraitType.Layout,\n\tgridAlignment: TraitType.Layout,\n\tgridColumnCount: TraitType.Layout,\n\tgridColumnWidthType: TraitType.Layout,\n\tgridColumnWidth: TraitType.Layout,\n\tgridColumnMinWidth: TraitType.Layout,\n\tgridRowHeightType: TraitType.Layout,\n\tgridRowHeight: TraitType.Layout,\n\tgridRowCount: TraitType.Layout,\n\tstackDirection: TraitType.Layout,\n\tstackDistribution: TraitType.Layout,\n\tstackAlignment: TraitType.Layout,\n\tstackWrapEnabled: TraitType.Layout,\n\tgridType: TraitType.Layout,\n\n\tgridItemFillCellWidth: TraitType.Size,\n\tgridItemFillCellHeight: TraitType.Size,\n\n\tgridItemHorizontalAlignment: TraitType.Position,\n\tgridItemVerticalAlignment: TraitType.Position,\n\tgridItemColumnSpan: TraitType.Size,\n\tgridItemRowSpan: TraitType.Size,\n\n\tminHeight: TraitType.SizeConstraints,\n\tminWidth: TraitType.SizeConstraints,\n\tmaxHeight: TraitType.SizeConstraints,\n\tmaxWidth: TraitType.SizeConstraints,\n\n\tparagraphSpacing: TraitType.ParagraphSpacing,\n\n\tposition: TraitType.PositionType,\n\tpositionStickyTop: TraitType.PositionType,\n\tpositionStickyRight: TraitType.PositionType,\n\tpositionStickyBottom: TraitType.PositionType,\n\tpositionStickyLeft: TraitType.PositionType,\n\n\tintrinsicWidth: TraitType.IntrinsicSize,\n\tintrinsicHeight: TraitType.IntrinsicSize,\n\n\tfillColor: TraitType.Fill,\n\tfillEnabled: TraitType.Fill,\n\tfillImage: TraitType.Fill,\n\tfillImageOriginalName: TraitType.Fill,\n\tfillImagePixelHeight: TraitType.Fill,\n\tfillImagePixelWidth: TraitType.Fill,\n\tfillImageResize: TraitType.Fill,\n\tfillImagePositionX: TraitType.Fill,\n\tfillImagePositionY: TraitType.Fill,\n\tfillImageTileSize: TraitType.Fill,\n\tfillImageAlts: TraitType.FillImageAlts,\n\tfillType: TraitType.Fill,\n\tfillRadialGradient: TraitType.Fill,\n\tfillLinearGradient: TraitType.Fill,\n\tfillConicGradient: TraitType.Fill,\n\n\ttapHighlightColor: TraitType.TapHighlight,\n\n\ttextSelection: TraitType.TextSelection,\n\n\tmasks: TraitType.Mask,\n\n\tradius: TraitType.Radius,\n\tradiusBottomLeft: TraitType.Radius,\n\tradiusBottomRight: TraitType.Radius,\n\tradiusIsRelative: TraitType.Radius,\n\tradiusPerCorner: TraitType.Radius,\n\tradiusTopLeft: TraitType.Radius,\n\tradiusTopRight: TraitType.Radius,\n\n\tcornerShape: TraitType.CornerShape,\n\n\tborderTop: TraitType.Border,\n\tborderBottom: TraitType.Border,\n\tborderLeft: TraitType.Border,\n\tborderRight: TraitType.Border,\n\tborderEnabled: TraitType.Border,\n\tborderWidth: TraitType.Border,\n\tborderStyle: TraitType.Border,\n\tborderColor: TraitType.Border,\n\tborderPerSide: TraitType.Border,\n\n\trotation: TraitType.Rotation,\n\trotate3d: TraitType.Rotation,\n\trotateX: TraitType.Rotation,\n\trotateY: TraitType.Rotation,\n\n\tblendingMode: TraitType.Blending,\n\n\topacity: TraitType.Opacity,\n\n\tbackgroundBlur: TraitType.BackgroundBlur,\n\n\toverflow: TraitType.Overflow,\n\toverflowY: TraitType.OverflowY,\n\toverflowX: TraitType.OverflowX,\n\n\toverscrollBehavior: TraitType.Overscroll,\n\n\tvisible: TraitType.Visibility,\n\n\tbrightness: TraitType.Brightness,\n\tcontrast: TraitType.Contrast,\n\tgrayscale: TraitType.Grayscale,\n\thueRotate: TraitType.HueRotate,\n\tinvert: TraitType.Invert,\n\tsaturate: TraitType.Saturate,\n\tsepia: TraitType.Sepia,\n\tblur: TraitType.Blur,\n\n\tboxShadows: TraitType.Shadows,\n\tshadows: TraitType.Shadows,\n\n\tguidesX: TraitType.CanvasSettings,\n\tguidesY: TraitType.CanvasSettings,\n\texportOptions: TraitType.CanvasSettings,\n\toverlayGrid: TraitType.CanvasSettings,\n\tgesture: TraitType.CanvasSettings,\n\tsizeToFit: TraitType.CanvasSettings,\n\tframePreset: TraitType.CanvasSettings,\n\tisVariant: TraitType.CanvasSettings,\n\n\tonTap: TraitType.Action,\n\tonTapStart: TraitType.Action,\n\tonClick: TraitType.Action,\n\tonMouseUp: TraitType.Action,\n\tonMouseDown: TraitType.Action,\n\tonMouseEnter: TraitType.Action,\n\tonMouseLeave: TraitType.Action,\n\tonAppear: TraitType.Action,\n\tonKeyDown: TraitType.Action,\n\n\tpadding: TraitType.Padding,\n\tpaddingPerSide: TraitType.Padding,\n\tpaddingTop: TraitType.Padding,\n\tpaddingRight: TraitType.Padding,\n\tpaddingBottom: TraitType.Padding,\n\tpaddingLeft: TraitType.Padding,\n\n\tname: TraitType.Name,\n\n\tstrokeEnabled: TraitType.Stroke,\n\tstrokeAlignment: TraitType.Stroke,\n\tstrokeWidth: TraitType.Stroke,\n\tstrokeColor: TraitType.Stroke,\n\tlineJoin: TraitType.Stroke,\n\tlineCap: TraitType.Stroke,\n\tstrokeMiterLimit: TraitType.Stroke,\n\tstrokeDashArray: TraitType.Stroke,\n\tstrokeDashOffset: TraitType.Stroke,\n\n\thtml: TraitType.RichText,\n\thtmlLocalized: TraitType.RichText,\n\thtmlContent: TraitType.RichText,\n\ttextFitScale: TraitType.RichText,\n\ttextFitViewBoxSize: TraitType.RichText,\n\ttextFitViewBoxSizeLocalized: TraitType.RichText,\n\n\tstylePresetHeading1: TraitType.StylePresets,\n\tstylePresetHeading2: TraitType.StylePresets,\n\tstylePresetHeading3: TraitType.StylePresets,\n\tstylePresetHeading4: TraitType.StylePresets,\n\tstylePresetHeading5: TraitType.StylePresets,\n\tstylePresetHeading6: TraitType.StylePresets,\n\tstylePresetParagraph: TraitType.StylePresets,\n\tstylePresetLink: TraitType.StylePresets,\n\tstylePresetAnchorLink: TraitType.StylePresets,\n\tstylePresetBlockquote: TraitType.StylePresets,\n\tstylePresetTable: TraitType.StylePresets,\n\tstylePresetInlineCode: TraitType.StylePresets,\n\tstylePresetImage: TraitType.StylePresets,\n\n\tanchorLinkOffsetY: TraitType.AnchorLinkOffsetY,\n\n\tstyledText: TraitType.StyledText,\n\tgetStyledText: TraitType.StyledText,\n\n\t// TextStyle\n\tfont: TraitType.Font,\n\trootFontSize: TraitType.RootFontSize,\n\ttextColor: TraitType.TextColor,\n\ttextBackgroundColor: TraitType.TextBackgroundColor,\n\ttextBackgroundRadius: TraitType.TextBackgroundRadius,\n\ttextBackgroundCornerShape: TraitType.TextBackgroundCornerShape,\n\ttextBackgroundPadding: TraitType.TextBackgroundPadding,\n\tfontSize: TraitType.FontSize,\n\tletterSpacing: TraitType.LetterSpacing,\n\ttextTransform: TraitType.TextTransform,\n\ttextDecoration: TraitType.TextDecoration,\n\ttextDecorationColor: TraitType.TextDecoration,\n\ttextDecorationThickness: TraitType.TextDecoration,\n\ttextDecorationStyle: TraitType.TextDecoration,\n\ttextDecorationSkipInk: TraitType.TextDecoration,\n\ttextDecorationOffset: TraitType.TextDecoration,\n\tlineHeight: TraitType.LineHeight,\n\ttextAlignment: TraitType.TextAlignment,\n\ttextStrokeWidth: TraitType.TextStroke,\n\ttextStrokeColor: TraitType.TextStroke,\n\ttextWrapBalance: TraitType.TextWrapBalance,\n\topenTypeFontFeatures: TraitType.OpenTypeFontFeatures,\n\n\tlink: TraitType.Link,\n\tlinkOpenInNewTab: TraitType.Link,\n\tlinkSmoothScroll: TraitType.Link,\n\tlinkClickTrackingId: TraitType.Link,\n\tlinkLocalized: TraitType.Link,\n\tlinkRelValues: TraitType.Link,\n\tlinkPreserveParams: TraitType.Link,\n\tgetLink: TraitType.Link,\n\n\tlinkFont: TraitType.LinkStyle,\n\tlinkTextColor: TraitType.LinkStyle,\n\tlinkFontSize: TraitType.LinkStyle,\n\tlinkTextTransform: TraitType.LinkStyle,\n\tlinkTextDecoration: TraitType.LinkStyle,\n\tlinkTextDecorationColor: TraitType.LinkStyle,\n\tlinkTextDecorationThickness: TraitType.LinkStyle,\n\tlinkTextDecorationStyle: TraitType.LinkStyle,\n\tlinkTextDecorationSkipInk: TraitType.LinkStyle,\n\tlinkTextDecorationOffset: TraitType.LinkStyle,\n\tlinkTextBackgroundColor: TraitType.LinkStyle,\n\tlinkTextBackgroundRadius: TraitType.LinkStyle,\n\tlinkTextBackgroundCornerShape: TraitType.LinkStyle,\n\tlinkTextBackgroundPadding: TraitType.LinkStyle,\n\tlinkHoverFont: TraitType.LinkStyle,\n\tlinkHoverTextColor: TraitType.LinkStyle,\n\tlinkHoverFontSize: TraitType.LinkStyle,\n\tlinkHoverTextTransform: TraitType.LinkStyle,\n\tlinkHoverTextDecoration: TraitType.LinkStyle,\n\tlinkHoverTextDecorationColor: TraitType.LinkStyle,\n\tlinkHoverTextDecorationThickness: TraitType.LinkStyle,\n\tlinkHoverTextDecorationStyle: TraitType.LinkStyle,\n\tlinkHoverTextDecorationSkipInk: TraitType.LinkStyle,\n\tlinkHoverTextDecorationOffset: TraitType.LinkStyle,\n\tlinkHoverTextBackgroundColor: TraitType.LinkStyle,\n\tlinkHoverTextBackgroundRadius: TraitType.LinkStyle,\n\tlinkHoverTextBackgroundCornerShape: TraitType.LinkStyle,\n\tlinkHoverTextBackgroundPadding: TraitType.LinkStyle,\n\tlinkCurrentFont: TraitType.LinkStyle,\n\tlinkCurrentTextColor: TraitType.LinkStyle,\n\tlinkCurrentFontSize: TraitType.LinkStyle,\n\tlinkCurrentTextTransform: TraitType.LinkStyle,\n\tlinkCurrentTextDecoration: TraitType.LinkStyle,\n\tlinkCurrentTextDecorationColor: TraitType.LinkStyle,\n\tlinkCurrentTextDecorationThickness: TraitType.LinkStyle,\n\tlinkCurrentTextDecorationStyle: TraitType.LinkStyle,\n\tlinkCurrentTextDecorationSkipInk: TraitType.LinkStyle,\n\tlinkCurrentTextDecorationOffset: TraitType.LinkStyle,\n\tlinkCurrentTextBackgroundColor: TraitType.LinkStyle,\n\tlinkCurrentTextBackgroundRadius: TraitType.LinkStyle,\n\tlinkCurrentTextBackgroundCornerShape: TraitType.LinkStyle,\n\tlinkCurrentTextBackgroundPadding: TraitType.LinkStyle,\n\n\ttextContent: TraitType.TextContent,\n\ttextVerticalAlignment: TraitType.TextVerticalAlignment,\n\n\tvariantTransition: TraitType.Transition,\n\n\tpathSegments: TraitType.Path,\n\tpathClosed: TraitType.Path,\n\tspikeCount: TraitType.Path,\n\tspikeDepth: TraitType.Path,\n\tpolygonSides: TraitType.Path,\n\n\telementId: TraitType.ScrollTarget,\n\tscrollMarginTop: TraitType.ScrollTarget,\n\tscrollTargetEnabled: TraitType.ScrollTarget,\n\n\taltAttribute: TraitType.Accessibility,\n\taltAttributeLocalized: TraitType.Accessibility,\n\n\tcursor: TraitType.Cursor,\n\n\tcustomCursorSmartComponentId: TraitType.CustomCursor,\n\tcustomCursorFollow: TraitType.CustomCursor,\n\tcustomCursorOffsetX: TraitType.CustomCursor,\n\tcustomCursorOffsetY: TraitType.CustomCursor,\n\tcustomCursorVariant: TraitType.CustomCursor,\n\tcustomCursorType: TraitType.CustomCursor,\n\tcustomCursorTransitionEnabled: TraitType.CustomCursor,\n\tcustomCursorTransition: TraitType.CustomCursor,\n\tcustomCursorPlacement: TraitType.CustomCursor,\n\tcustomCursorAlignment: TraitType.CustomCursor,\n\n\tpointerEvents: TraitType.PointerEvents,\n\tuserSelect: TraitType.UserSelect,\n\tzIndex: TraitType.ZIndex,\n\n\tdraggable: TraitType.Draggable,\n\n\timageRendering: TraitType.ImageRendering,\n\n\tviewportHeight: TraitType.CanvasSettings,\n\tisBreakpoint: TraitType.CanvasSettings,\n\n\tbackdropFill: TraitType.Overlay,\n\tbackdropFillEnabled: TraitType.Overlay,\n\tbackdropDismissible: TraitType.Overlay,\n\tblockDocumentScrolling: TraitType.Overlay,\n\tbackdropExitTransition: TraitType.OverlayTransition,\n\tbackdropEnterTransition: TraitType.OverlayTransition,\n\tbackdropTransitionLocked: TraitType.OverlayTransition,\n\n\thideScrollbars: TraitType.Scrollbars,\n\n\tcustomizations: TraitType.Customizations,\n\tcustomizationsDescription: TraitType.Customizations,\n\tcustomizationsSectionId: TraitType.Customizations,\n\tcustomizationsCategory: TraitType.Customizations,\n\tcustomizationsRules: TraitType.Customizations,\n\tisApplyingCustomizations: TraitType.Customizations,\n\n\ttranslateZ: TraitType.TranslateZ,\n\tscale: TraitType.Scale,\n\tskewX: TraitType.Skew,\n\tskewY: TraitType.Skew,\n\n\tbackfaceVisibility: TraitType.BackfaceVisibility,\n\tperspective: TraitType.Perspective,\n\ttransformStylePreserve3d: TraitType.TransformStylePreserve3d,\n\n\ttransformOriginX: TraitType.TransformOrigin,\n\ttransformOriginY: TraitType.TransformOrigin,\n\n\ttransition: TraitType.Transition,\n\tformInputFontSize: TraitType.FormInputFont,\n\tformInputFontFamily: TraitType.FormInputFont,\n\tformInputFontSelector: TraitType.FormInputFont,\n\tformInputFontWeight: TraitType.FormInputFont,\n\tformInputFontStyle: TraitType.FormInputFont,\n\tformInputPlaceholderColor: TraitType.FormPlaceholderColor,\n\tformInputFontColor: TraitType.FormInputColor,\n\tformInputFontLetterSpacing: TraitType.FormInputFont,\n\tformInputFontLetterSpacingUnit: TraitType.FormInputFont,\n\tformInputFontLineHeight: TraitType.FormInputFont,\n\tformInputFontLineHeightUnit: TraitType.FormInputFont,\n\tformInputFontTextAlignment: TraitType.FormInputFont,\n\tformInputOpenTypeFontFeatures: TraitType.FormInputFont,\n\tformInputVariationAxes: TraitType.FormInputFont,\n\tformTextInputType: TraitType.FormTextInputType,\n\tformTextAreaResizable: TraitType.FormInputTextAreaResize,\n\tformTextInputMinNumber: TraitType.FormTextInputTypeMin,\n\tformTextInputMaxNumber: TraitType.FormTextInputTypeMax,\n\tformInputMaxLength: TraitType.FormInputMaxLength,\n\tformInputStep: TraitType.FormInputStep,\n\n\tformBooleanInputType: TraitType.FormBooleanInputType,\n\tformBooleanInputValue: TraitType.FormBooleanInputValue,\n\tformBooleanInputCheckedBorderColor: TraitType.FormBooleanInputCheckedEffect,\n\tformBooleanInputCheckedBorderWidth: TraitType.FormBooleanInputCheckedEffect,\n\tformBooleanInputCheckedBorderStyle: TraitType.FormBooleanInputCheckedEffect,\n\tformBooleanInputCheckedBoxShadow: TraitType.FormBooleanInputCheckedEffect,\n\tformBooleanInputCheckedFillColor: TraitType.FormBooleanInputCheckedEffect,\n\tformBooleanInputCheckedTransition: TraitType.FormBooleanInputCheckedEffect,\n\n\tformInputFocusedBackgroundColor: TraitType.FormInputFocusedFill,\n\tformInputFocusedBorderColor: TraitType.FormInputFocusedBorder,\n\tformInputFocusedBorderStyle: TraitType.FormInputFocusedBorder,\n\tformInputFocusedBorderWidth: TraitType.FormInputFocusedBorder,\n\tformInputFocusedBoxShadow: TraitType.FormInputFocusedBoxShadow,\n\tformInputFocusedTransition: TraitType.FormInputFocusedTransition,\n\n\tformInputInvalidTextColor: TraitType.FormInputInvalidTextColor,\n\n\tformInputIconImage: TraitType.FormInputIcon,\n\tformInputIconColor: TraitType.FormInputIcon,\n\n\tviewTransitionNone: TraitType.ViewTransitionNone,\n\tflowEffectEnabled: TraitType.FlowEffect,\n\tflowEffectTransition: TraitType.FlowEffect,\n}\n\nexport function getPropKeysByTraitTypes(traitTypes: readonly TraitType[]): TraitTypeKey[] {\n\tconst result: TraitTypeKey[] = []\n\n\tlet key: TraitTypeKey\n\tfor (key in traitTypeMap) {\n\t\tconst traitType = traitTypeMap[key]\n\n\t\tif (traitTypes.includes(traitType)) {\n\t\t\tresult.push(key)\n\t\t}\n\t}\n\n\treturn result\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { isValidPropertyValue } from \"document/components/chrome/properties/codeComponentRows/utils/isValidPropertyValue.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport type { WithControlProps } from \"document/models/CanvasTree/traits/WithControlProps.ts\"\nimport { isReplicaVariantChild } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport type { RawControlProps } from \"document/models/controlProps/RawControlProp.ts\"\nimport { isRawControlProp } from \"document/models/controlProps/RawControlProp.ts\"\nimport { prefixControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport { controlTypesAreCompatible } from \"document/models/controlProps/controlTypesAreCompatible.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport type { Mutable } from \"utils/Mutable.ts\"\n\n/**\n * Returns the props and their values from `source` that are compatible with `target`.\n */\nexport function compatibleControlProps(\n\tcomponentLoader: ComponentLoader,\n\tsource: CanvasNode & WithControlProps,\n\ttarget: CanvasNode & WithControlProps,\n): RawControlProps {\n\tconst targetIdentifier = target.getControlPropSourceIdentifier()\n\tif (!targetIdentifier) return {}\n\tconst propertyControls = componentLoader.getPropertyControlsForIdentifier(targetIdentifier)\n\tif (!propertyControls) {\n\t\treturn {}\n\t}\n\n\t// Collect all props compatible with target (and their values) from the source component.\n\tconst targetProps: Mutable<RawControlProps> = {}\n\tObject.entries(propertyControls).forEach(([controlKey, targetControl]) => {\n\t\tif (!targetControl) return\n\t\tif (isReplicaVariantChild(target) && targetControl.type === ControlType.Slot) {\n\t\t\t// Slot overrides are not allowed within replica variants\n\t\t\treturn\n\t\t}\n\t\tconst nodeKey = prefixControlPropKey(controlKey)\n\t\tconst sourceProp = source[nodeKey]\n\n\t\t// The data is missing.\n\t\tif (!isRawControlProp(sourceProp)) return\n\n\t\t// The data doesn't have a type.\n\t\tif (!sourceProp.type) return\n\n\t\t// The source control prop is not compatible with the target control.\n\t\tif (!controlTypesAreCompatible(targetControl.type, sourceProp.type)) return\n\n\t\tif (targetControl.type === ControlType.Enum && !isValidPropertyValue(targetControl, sourceProp.value)) {\n\t\t\t// While both source and target props are enums, the source value is not compatible with target.\n\t\t\treturn\n\t\t}\n\t\ttargetProps[nodeKey] = sourceProp\n\t})\n\treturn targetProps\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { filterKeys } from \"document/components/chrome/properties/panels/utils/getFilters.ts\"\nimport type { AnyNodeUpdate, CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isAnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport {\n\tisCanvasPageNode,\n\tisFrameNode,\n\tisGridComponent,\n\tisRichTextNode,\n\tisStackComponent,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { TraitType, traitTypeMap } from \"document/models/CanvasTree/traits/TraitType.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { withBlending } from \"document/models/CanvasTree/traits/WithBlending.ts\"\nimport { withBorder } from \"document/models/CanvasTree/traits/WithBorder.ts\"\nimport { supportsBoxShadow, supportsRealisticShadow } from \"document/models/CanvasTree/traits/WithBoxShadow.ts\"\nimport { withCodeComponent } from \"document/models/CanvasTree/traits/WithCodeComponent.ts\"\nimport { withCodeOverride } from \"document/models/CanvasTree/traits/WithCodeOverride.ts\"\nimport { withCornerShape } from \"document/models/CanvasTree/traits/WithCornerShape.ts\"\nimport { withCursor } from \"document/models/CanvasTree/traits/WithCursor.ts\"\nimport { withDraggable } from \"document/models/CanvasTree/traits/WithDraggable.ts\"\nimport {\n\tsupportsConicGradient,\n\tsupportsFillImageAlts,\n\twithFill,\n\twithFillImageAlts,\n\twithOptionalFill,\n} from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { withFilters } from \"document/models/CanvasTree/traits/WithFilters.ts\"\nimport {\n\tgetFloatingPositionProps,\n\thasFloatingPosition,\n} from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { withImageRendering } from \"document/models/CanvasTree/traits/WithImageRendering.ts\"\nimport { withMasks } from \"document/models/CanvasTree/traits/WithMasks.ts\"\nimport { withOpacity } from \"document/models/CanvasTree/traits/WithOpacity.ts\"\nimport { withOverflow } from \"document/models/CanvasTree/traits/WithOverflow.ts\"\nimport { withOverscrollBehavior } from \"document/models/CanvasTree/traits/WithOverscrollBehavior.ts\"\nimport { withPadding } from \"document/models/CanvasTree/traits/WithPadding.ts\"\nimport { withPointerEvents } from \"document/models/CanvasTree/traits/WithPointerEvents.ts\"\nimport { withRadius, withRelativeRadius } from \"document/models/CanvasTree/traits/WithRadius.ts\"\nimport { withRadiusPerCorner } from \"document/models/CanvasTree/traits/WithRadiusPerCorner.ts\"\nimport { withRotation } from \"document/models/CanvasTree/traits/WithRotation.ts\"\nimport { withScrollbars } from \"document/models/CanvasTree/traits/WithScrollbars.ts\"\nimport { withShader } from \"document/models/CanvasTree/traits/WithShader.ts\"\nimport { withShadow } from \"document/models/CanvasTree/traits/WithShadow.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { withStroke } from \"document/models/CanvasTree/traits/WithStroke.ts\"\nimport { stylePresetKeys } from \"document/models/CanvasTree/traits/WithStylePresets.ts\"\nimport { withStyledText } from \"document/models/CanvasTree/traits/WithStyledText.ts\"\nimport { isFontSize, migrateLetterSpacing } from \"document/models/CanvasTree/traits/WithTextStyle.ts\"\nimport { withTextVerticalAlignment } from \"document/models/CanvasTree/traits/WithTextVerticalAlignment.ts\"\nimport { withTextWrapBalance } from \"document/models/CanvasTree/traits/WithTextWrapBalance.ts\"\nimport { withTransforms } from \"document/models/CanvasTree/traits/WithTransforms.ts\"\nimport { withTransition } from \"document/models/CanvasTree/traits/WithTransition.ts\"\nimport { withUserSelect } from \"document/models/CanvasTree/traits/WithUserSelect.ts\"\nimport { withVariables } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isReplicaVariantOrReplicaVariantChild, isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { withViewTransitionNone } from \"document/models/CanvasTree/traits/WithViewTransitionNone.ts\"\nimport { withVisibility } from \"document/models/CanvasTree/traits/WithVisibility.ts\"\nimport { withZIndex } from \"document/models/CanvasTree/traits/WithZIndex.ts\"\nimport type { WithFormBooleanInputType } from \"document/models/CanvasTree/traits/forms/WithFormBooleanInputType.ts\"\nimport { withFormBooleanInputType } from \"document/models/CanvasTree/traits/forms/WithFormBooleanInputType.ts\"\nimport { withFormInputFocusedStyles } from \"document/models/CanvasTree/traits/forms/WithFormInputFocusedStyles.ts\"\nimport { withFormInputIcon } from \"document/models/CanvasTree/traits/forms/WithFormInputIcon.ts\"\nimport { withFormInputPlaceholder } from \"document/models/CanvasTree/traits/forms/WithFormInputPlaceholder.ts\"\nimport { withFormInputFontStyles } from \"document/models/CanvasTree/traits/forms/WithFormInputTextStyles.ts\"\nimport { withFormTextInputType } from \"document/models/CanvasTree/traits/forms/WithTextInputType.ts\"\nimport { getSupportedEffects, withAnyEffect } from \"document/models/CanvasTree/traits/utils/effects.ts\"\nimport { positionTypeUpdateForNewParent } from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { supportsViewportSizing } from \"document/models/CanvasTree/traits/utils/viewportHelpers.ts\"\nimport { isBorderValues } from \"document/models/controlProps/BorderControlPropValue.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { isArray, isUndefined } from \"utils/typeChecks.ts\"\nimport { compatibleControlProps } from \"./compatibleControlProps.ts\"\n\nexport function shouldApplyUpdate(trait: TraitType, limitToTrait: TraitType | TraitType[] | undefined): boolean {\n\tif (!limitToTrait) return true\n\tconst limits = new Set(isArray(limitToTrait) ? limitToTrait : [limitToTrait])\n\treturn limits.has(trait)\n}\n\n/**\n * Get the compatible styles and code component properties from a source node, the result can be applied to the target node.\n * @param tree\n * @param sourceNode\n * @param targetNode\n * @param newParent\n * @param variableFallbackValues optional variable fallback values\n * @param limitToTrait\n * @returns An update that can be applied to the target node\n */\nexport function getCompatibleNodeProperties(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tsourceNode: CanvasNode,\n\ttargetNode: CanvasNode,\n\tnewParent?: CanvasNode | null,\n\tvariableFallbackValues?: Record<string, any>,\n\tlimitToTrait?: TraitType | TraitType[],\n): AnyNodeUpdate {\n\tconst scopeNode = tree.getScopeNodeFor(targetNode)\n\t/**\n\t * Check if variable is in scope, if not we try to use the provided fallback value\n\t * */\n\tfunction withVariableFallback<T>(value: T): T {\n\t\tif (!isVariableReference(value)) return value\n\t\tif (scopeNode && withVariables(scopeNode) && scopeNode.hasVariable(value.id)) {\n\t\t\treturn value\n\t\t}\n\t\treturn (variableFallbackValues?.[value.id] as T) ?? value\n\t}\n\n\tconst update: AnyNodeUpdate = {}\n\n\tif (!supportsViewportSizing(tree, targetNode)) {\n\t\tif (withSizeDimensionType(sourceNode)) {\n\t\t\tif (sourceNode.widthType === DimensionType.Viewport) {\n\t\t\t\tupdate.widthType = DimensionType.Percentage\n\t\t\t}\n\n\t\t\tif (sourceNode.heightType === DimensionType.Viewport) {\n\t\t\t\tupdate.heightType = DimensionType.Percentage\n\t\t\t}\n\t\t}\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.Visibility, limitToTrait) &&\n\t\twithVisibility(sourceNode) &&\n\t\twithVisibility(targetNode)\n\t) {\n\t\tupdate.visible = withVariableFallback(sourceNode.visible)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Border, limitToTrait) && withBorder(sourceNode) && withBorder(targetNode)) {\n\t\tupdate.borderEnabled = sourceNode.borderEnabled\n\t\tupdate.borderWidth = sourceNode.borderWidth\n\t\tupdate.borderColor = sourceNode.borderColor\n\t\tupdate.borderStyle = sourceNode.borderStyle\n\t\tupdate.borderPerSide = sourceNode.borderPerSide\n\t\tupdate.borderLeft = sourceNode.borderLeft\n\t\tupdate.borderTop = sourceNode.borderTop\n\t\tupdate.borderRight = sourceNode.borderRight\n\t\tupdate.borderBottom = sourceNode.borderBottom\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Border, limitToTrait) && withBorder(sourceNode) && withStroke(targetNode)) {\n\t\tif (isDynamicValue(sourceNode.borderEnabled)) {\n\t\t\tconst resolvedValue = sourceNode.resolveValue(\"borderEnabled\")\n\n\t\t\tif (isBorderValues(resolvedValue)) {\n\t\t\t\tupdate.strokeEnabled = true\n\t\t\t\tupdate.strokeWidth = resolvedValue.borderWidth\n\t\t\t\tupdate.strokeColor = resolvedValue.borderColor\n\t\t\t} else {\n\t\t\t\tupdate.strokeEnabled = false\n\t\t\t}\n\t\t} else {\n\t\t\tupdate.strokeEnabled = sourceNode.borderEnabled\n\t\t\tupdate.strokeWidth = sourceNode.borderWidth\n\t\t\tupdate.strokeColor = sourceNode.borderColor\n\t\t}\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Stroke, limitToTrait) && withStroke(sourceNode) && withStroke(targetNode)) {\n\t\tupdate.strokeEnabled = sourceNode.strokeEnabled\n\t\tupdate.strokeColor = sourceNode.strokeColor\n\t\tupdate.strokeWidth = sourceNode.strokeWidth\n\t\tupdate.strokeAlignment = sourceNode.strokeAlignment\n\t\tupdate.lineJoin = sourceNode.lineJoin\n\t\tupdate.lineCap = sourceNode.lineCap\n\t\tupdate.strokeMiterLimit = sourceNode.strokeMiterLimit\n\t\tupdate.strokeDashArray = sourceNode.strokeDashArray\n\t\tupdate.strokeDashOffset = sourceNode.strokeDashOffset\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Stroke, limitToTrait) && withStroke(sourceNode) && withBorder(targetNode)) {\n\t\tupdate.borderEnabled = sourceNode.strokeEnabled\n\t\tupdate.borderWidth = sourceNode.resolveValue(\"strokeWidth\")\n\t\tupdate.borderColor = sourceNode.resolveValue(\"strokeColor\")\n\t}\n\n\tif (shouldApplyUpdate(TraitType.FormInputTextAreaResize, limitToTrait) && withFormTextInputType(sourceNode)) {\n\t\tupdate.formTextAreaResizable = sourceNode.formTextAreaResizable\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormInputFocusedFill, limitToTrait) &&\n\t\twithFormInputFocusedStyles(sourceNode) &&\n\t\twithFormInputFocusedStyles(targetNode)\n\t) {\n\t\tupdate.formInputFocusedBackgroundColor = sourceNode.formInputFocusedBackgroundColor\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormInputFocusedBorder, limitToTrait) &&\n\t\twithFormInputFocusedStyles(sourceNode) &&\n\t\twithFormInputFocusedStyles(targetNode)\n\t) {\n\t\tupdate.formInputFocusedBorderColor = sourceNode.formInputFocusedBorderColor\n\t\tupdate.formInputFocusedBorderWidth = sourceNode.formInputFocusedBorderWidth\n\t\tupdate.formInputFocusedBorderStyle = sourceNode.formInputFocusedBorderStyle\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormInputFocusedBoxShadow, limitToTrait) &&\n\t\twithFormInputFocusedStyles(sourceNode) &&\n\t\twithFormInputFocusedStyles(targetNode)\n\t) {\n\t\tupdate.formInputFocusedBoxShadow = sourceNode.formInputFocusedBoxShadow\n\t\t\t? [...sourceNode.formInputFocusedBoxShadow]\n\t\t\t: undefined\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormInputFocusedTransition, limitToTrait) &&\n\t\twithFormInputFocusedStyles(sourceNode) &&\n\t\twithFormInputFocusedStyles(targetNode)\n\t) {\n\t\tupdate.formInputFocusedTransition = sourceNode.formInputFocusedTransition\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormInputColor, limitToTrait) &&\n\t\twithFormInputFontStyles(sourceNode) &&\n\t\twithFormInputFontStyles(targetNode)\n\t) {\n\t\tupdate.formInputFontColor = sourceNode.formInputFontColor\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormPlaceholderColor, limitToTrait) &&\n\t\twithFormInputPlaceholder(sourceNode) &&\n\t\twithFormInputPlaceholder(targetNode)\n\t) {\n\t\tupdate.formInputPlaceholderColor = sourceNode.formInputPlaceholderColor\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormInputPadding, limitToTrait) &&\n\t\twithPadding(sourceNode) &&\n\t\twithPadding(targetNode)\n\t) {\n\t\tupdate.padding = sourceNode.padding\n\t\tupdate.paddingPerSide = sourceNode.paddingPerSide\n\t\tupdate.paddingTop = sourceNode.paddingTop\n\t\tupdate.paddingRight = sourceNode.paddingRight\n\t\tupdate.paddingBottom = sourceNode.paddingBottom\n\t\tupdate.paddingLeft = sourceNode.paddingLeft\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.Shadows, limitToTrait) &&\n\t\tsupportsBoxShadow(sourceNode) &&\n\t\tsupportsBoxShadow(targetNode)\n\t) {\n\t\tconst sourceNodeBoxShadows = withVariableFallback(sourceNode.boxShadows)\n\t\tif (supportsRealisticShadow(targetNode)) {\n\t\t\tupdate.boxShadows = sourceNodeBoxShadows\n\t\t} else {\n\t\t\tif (!isDynamicValue(sourceNodeBoxShadows)) {\n\t\t\t\tupdate.boxShadows = sourceNodeBoxShadows?.filter(shadow => shadow.type !== \"realistic\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Shadows, limitToTrait) && withShadow(sourceNode) && withShadow(targetNode)) {\n\t\tupdate.shadows = sourceNode.shadows\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Rotation, limitToTrait) && withRotation(sourceNode) && withRotation(targetNode)) {\n\t\tupdate.rotation = sourceNode.rotation\n\t\tif (withTransforms(targetNode) && withTransforms(sourceNode)) {\n\t\t\tupdate.rotate3d = sourceNode.rotate3d\n\t\t\tupdate.rotateX = sourceNode.rotateX\n\t\t\tupdate.rotateY = sourceNode.rotateY\n\t\t}\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Overflow, limitToTrait) && withOverflow(sourceNode) && withOverflow(targetNode)) {\n\t\tupdate.overflow = withVariableFallback(sourceNode.overflow)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.Overscroll, limitToTrait) &&\n\t\twithOverscrollBehavior(sourceNode) &&\n\t\twithOverscrollBehavior(targetNode)\n\t) {\n\t\tupdate.overscrollBehavior = withVariableFallback(sourceNode.overscrollBehavior)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Cursor, limitToTrait) && withCursor(sourceNode) && withCursor(targetNode)) {\n\t\tupdate.cursor = withVariableFallback(sourceNode.cursor)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.CustomCursor, limitToTrait) && withCursor(sourceNode) && withCursor(targetNode)) {\n\t\tupdate.customCursorType = sourceNode.customCursorType\n\t\tupdate.customCursorSmartComponentId = sourceNode.customCursorSmartComponentId\n\t\tupdate.customCursorVariant = sourceNode.customCursorVariant\n\t\tupdate.customCursorFollow = sourceNode.customCursorFollow\n\t\tupdate.customCursorOffsetX = sourceNode.customCursorOffsetX\n\t\tupdate.customCursorOffsetY = sourceNode.customCursorOffsetY\n\t\tupdate.customCursorTransitionEnabled = sourceNode.customCursorTransitionEnabled\n\t\tupdate.customCursorTransition = sourceNode.customCursorTransition\n\t\tupdate.customCursorPlacement = sourceNode.customCursorPlacement\n\t\tupdate.customCursorAlignment = sourceNode.customCursorAlignment\n\t}\n\n\tif (withFilters(sourceNode) && withFilters(targetNode)) {\n\t\tfor (const filterKey of filterKeys) {\n\t\t\tconst trait = traitTypeMap[filterKey]\n\t\t\tif (shouldApplyUpdate(trait, limitToTrait)) {\n\t\t\t\tupdate[filterKey] = withVariableFallback(sourceNode[filterKey])\n\t\t\t}\n\t\t}\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Blending, limitToTrait) && withBlending(sourceNode) && withBlending(targetNode)) {\n\t\tupdate.blendingMode = withVariableFallback(sourceNode.blendingMode)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.Transition, limitToTrait) &&\n\t\twithTransition(sourceNode) &&\n\t\twithTransition(targetNode)\n\t) {\n\t\tconst sourceTransition = isVariant(sourceNode) ? sourceNode.variantTransition : sourceNode.transition\n\t\tif (isVariant(targetNode)) {\n\t\t\tupdate.variantTransition = sourceTransition\n\t\t} else {\n\t\t\tupdate.transition = sourceTransition\n\t\t}\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Fill, limitToTrait) && withFill(sourceNode) && withFill(targetNode)) {\n\t\tupdate.fillColor = withVariableFallback(sourceNode.fillColor)\n\t\tupdate.fillType = sourceNode.fillType\n\t\tupdate.fillLinearGradient = sourceNode.fillLinearGradient\n\t\tupdate.fillRadialGradient = sourceNode.fillRadialGradient\n\t\tupdate.fillConicGradient = sourceNode.fillConicGradient\n\n\t\t// Only apply conic gradient to nodes that support it, otherwise keep the current fill type or revert back to\n\t\t// solid color.\n\t\tif (update.fillType === \"conic-gradient\" && !supportsConicGradient(targetNode)) {\n\t\t\tupdate.fillType = targetNode.fillType ?? \"color\"\n\t\t}\n\n\t\tconst imageUpdate = withVariableFallback(sourceNode.fillImage)\n\t\tif (!isDynamicValue(imageUpdate)) {\n\t\t\tupdate.fillImage = imageUpdate\n\t\t} else if (isDynamicValue(imageUpdate) && targetNode.supportsDynamicValues()) {\n\t\t\tupdate.fillImage = imageUpdate\n\t\t}\n\n\t\t// Only apply fill image alts if the target node supports them\n\t\tif (\n\t\t\tshouldApplyUpdate(TraitType.FillImageAlts, limitToTrait) &&\n\t\t\tsupportsFillImageAlts(tree, targetNode) &&\n\t\t\twithFillImageAlts(sourceNode)\n\t\t) {\n\t\t\tupdate.fillImageAlts = sourceNode.fillImageAlts ? [...sourceNode.fillImageAlts] : undefined\n\t\t}\n\n\t\tupdate.fillImageResize = sourceNode.fillImageResize\n\t\tupdate.fillImagePixelWidth = sourceNode.fillImagePixelWidth\n\t\tupdate.fillImagePixelHeight = sourceNode.fillImagePixelHeight\n\t\tupdate.fillImagePositionX = sourceNode.fillImagePositionX\n\t\tupdate.fillImagePositionY = sourceNode.fillImagePositionY\n\t\tupdate.fillImageTileSize = sourceNode.fillImageTileSize\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Fill, limitToTrait) && withOptionalFill(sourceNode) && withOptionalFill(targetNode)) {\n\t\tupdate.fillEnabled = sourceNode.fillEnabled\n\t}\n\n\t// Reset fit image dimension if required. This reset could happen if size is being a applied to a node without image fill\n\t// or if a non-image fill is being applied to a node with fit image dimension.\n\tif (\n\t\t(shouldApplyUpdate(TraitType.Size, limitToTrait) || shouldApplyUpdate(TraitType.Fill, limitToTrait)) &&\n\t\twithSizeDimensionType(sourceNode) &&\n\t\twithSizeDimensionType(targetNode)\n\t) {\n\t\tconst targetFillType = update.fillType ?? (withFill(targetNode) ? targetNode.fillType : undefined)\n\t\tconst targetHeightType = update.heightType ?? targetNode.heightType\n\t\tconst targetWidthType = update.widthType ?? targetNode.widthType\n\n\t\tif (targetWidthType === DimensionType.FitImage && targetFillType !== \"image\") {\n\t\t\tupdate.width = targetNode.rect().width\n\t\t\tupdate.widthType = DimensionType.FixedNumber\n\t\t}\n\t\tif (targetHeightType === DimensionType.FitImage && targetFillType !== \"image\") {\n\t\t\tupdate.height = targetNode.rect().height\n\t\t\tupdate.heightType = DimensionType.FixedNumber\n\t\t}\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Opacity, limitToTrait) && withOpacity(sourceNode) && withOpacity(targetNode)) {\n\t\tupdate.opacity = withVariableFallback(sourceNode.opacity)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Radius, limitToTrait) && withRadius(sourceNode) && withRadius(targetNode)) {\n\t\tupdate.radius = withVariableFallback(sourceNode.radius)\n\t\tif (withRelativeRadius(sourceNode) && withRelativeRadius(targetNode)) {\n\t\t\tupdate.radiusIsRelative = sourceNode.radiusIsRelative\n\t\t}\n\t\tif (withRadiusPerCorner(sourceNode) && withRadiusPerCorner(targetNode)) {\n\t\t\tupdate.radiusPerCorner = sourceNode.radiusPerCorner\n\t\t\tupdate.radiusBottomLeft = sourceNode.radiusBottomLeft\n\t\t\tupdate.radiusBottomRight = sourceNode.radiusBottomRight\n\t\t\tupdate.radiusTopLeft = sourceNode.radiusTopLeft\n\t\t\tupdate.radiusTopRight = sourceNode.radiusTopRight\n\t\t}\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.CornerShape, limitToTrait) &&\n\t\twithCornerShape(sourceNode) &&\n\t\twithCornerShape(targetNode)\n\t) {\n\t\tupdate.cornerShape = withVariableFallback(sourceNode.cornerShape)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.PointerEvents, limitToTrait) &&\n\t\twithPointerEvents(sourceNode) &&\n\t\twithPointerEvents(targetNode) &&\n\t\t!isCanvasPageNode(scopeNode)\n\t) {\n\t\tupdate.pointerEvents = withVariableFallback(sourceNode.pointerEvents)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Draggable, limitToTrait) && withDraggable(sourceNode) && withDraggable(targetNode)) {\n\t\tupdate.draggable = withVariableFallback(sourceNode.draggable)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.UserSelect, limitToTrait) &&\n\t\twithUserSelect(sourceNode) &&\n\t\twithUserSelect(targetNode)\n\t) {\n\t\tupdate.userSelect = withVariableFallback(sourceNode.userSelect)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.ImageRendering, limitToTrait) &&\n\t\twithImageRendering(sourceNode) &&\n\t\twithImageRendering(targetNode)\n\t) {\n\t\tupdate.imageRendering = withVariableFallback(sourceNode.imageRendering)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.OverflowX, limitToTrait) && withOverflow(sourceNode) && withOverflow(targetNode)) {\n\t\tupdate.overflowX = withVariableFallback(sourceNode.overflowX)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.OverflowY, limitToTrait) && withOverflow(sourceNode) && withOverflow(targetNode)) {\n\t\tupdate.overflowY = withVariableFallback(sourceNode.overflowY)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.ZIndex, limitToTrait) && withZIndex(sourceNode) && withZIndex(targetNode)) {\n\t\tupdate.zIndex = withVariableFallback(sourceNode.zIndex)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.Scrollbars, limitToTrait) &&\n\t\twithScrollbars(sourceNode) &&\n\t\twithScrollbars(targetNode)\n\t) {\n\t\tupdate.hideScrollbars = withVariableFallback(sourceNode.hideScrollbars)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.TextVerticalAlignment, limitToTrait) &&\n\t\twithTextVerticalAlignment(sourceNode) &&\n\t\twithTextVerticalAlignment(targetNode)\n\t) {\n\t\tupdate.textVerticalAlignment = sourceNode.textVerticalAlignment\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.TextWrapBalance, limitToTrait) &&\n\t\twithTextWrapBalance(sourceNode) &&\n\t\twithTextWrapBalance(targetNode)\n\t) {\n\t\tupdate.textWrapBalance = sourceNode.textWrapBalance\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.StyledText, limitToTrait) &&\n\t\tisAnyTextNode(sourceNode) &&\n\t\twithStyledText(targetNode)\n\t) {\n\t\tupdate.font = sourceNode.getFonts(false)[0]\n\t\tupdate.textColor = sourceNode.getTextColors(false)[0]\n\n\t\tconst fontSize = sourceNode.getFontSizes(false)[0]\n\t\tupdate.fontSize = isFontSize(fontSize) ? fontSize[0] : fontSize\n\n\t\tconst letterSpacing = sourceNode.getLetterSpacings(false)[0]\n\t\tupdate.letterSpacing = isUndefined(letterSpacing) ? letterSpacing : migrateLetterSpacing(letterSpacing)\n\t\tupdate.textTransform = sourceNode.getTextTransforms(false)[0]\n\t\tupdate.textDecoration = sourceNode.getTextDecorations(false)[0]\n\t\tupdate.lineHeight = sourceNode.getLineHeights(false)[0]\n\t\tupdate.textAlignment = sourceNode.getTextAlignments(false)[0]\n\n\t\tupdate.styledText = targetNode.styledText\n\t\t\t.setFont(undefined, false)\n\t\t\t.setTextColor(undefined, false)\n\t\t\t.setFontSize(undefined, false)\n\t\t\t.setLetterSpacing(undefined, false)\n\t\t\t.setTextTransform(undefined, false)\n\t\t\t.setTextDecoration(undefined, false)\n\t\t\t.setLineHeight(undefined)\n\t\t\t.setTextAlignment(undefined)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Link, limitToTrait) && isAnyTextNode(sourceNode) && isAnyTextNode(targetNode)) {\n\t\tupdate.linkFont = sourceNode.linkFont\n\t\tupdate.linkTextColor = sourceNode.linkTextColor\n\t\tupdate.linkFontSize = sourceNode.linkFontSize\n\t\tupdate.linkTextTransform = sourceNode.linkTextTransform\n\t\tupdate.linkTextDecoration = sourceNode.linkTextDecoration\n\t\tupdate.linkHoverFont = sourceNode.linkHoverFont\n\t\tupdate.linkHoverTextColor = sourceNode.linkHoverTextColor\n\t\tupdate.linkHoverFontSize = sourceNode.linkHoverFontSize\n\t\tupdate.linkHoverTextTransform = sourceNode.linkHoverTextTransform\n\t\tupdate.linkHoverTextDecoration = sourceNode.linkHoverTextDecoration\n\t\tupdate.linkCurrentFont = sourceNode.linkCurrentFont\n\t\tupdate.linkCurrentTextColor = sourceNode.linkCurrentTextColor\n\t\tupdate.linkCurrentFontSize = sourceNode.linkCurrentFontSize\n\t\tupdate.linkCurrentTextTransform = sourceNode.linkCurrentTextTransform\n\t\tupdate.linkCurrentTextDecoration = sourceNode.linkCurrentTextDecoration\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Mask, limitToTrait) && withMasks(sourceNode) && withMasks(targetNode)) {\n\t\tupdate.masks = sourceNode.masks\n\t}\n\n\tif (isRichTextNode(sourceNode) && isRichTextNode(targetNode)) {\n\t\tif (shouldApplyUpdate(TraitType.FontSize, limitToTrait)) {\n\t\t\tupdate.textFitScale = sourceNode.textFitScale\n\t\t\tupdate.textFitViewBoxSize = sourceNode.textFitViewBoxSize\n\t\t}\n\n\t\tif (shouldApplyUpdate(TraitType.ParagraphSpacing, limitToTrait)) {\n\t\t\tupdate.paragraphSpacing = sourceNode.paragraphSpacing\n\t\t}\n\n\t\tif (shouldApplyUpdate(TraitType.StyledText, limitToTrait)) {\n\t\t\tconst textStrokeWidth = sourceNode.getTextStrokeWidths(false)[0]\n\t\t\tconst textStrokeColor = sourceNode.getTextStrokeColors(false)[0]\n\t\t\tif (!isUndefined(textStrokeWidth)) update.textStrokeWidth = textStrokeWidth\n\t\t\tif (textStrokeColor) update.textStrokeColor = textStrokeColor\n\t\t}\n\n\t\tif (shouldApplyUpdate(TraitType.RichText, limitToTrait)) {\n\t\t\tfor (const key of stylePresetKeys) {\n\t\t\t\tconst presetId = sourceNode[key]\n\t\t\t\tif (tree.has(presetId)) {\n\t\t\t\t\tupdate[key] = presetId\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.ControlProps, limitToTrait) &&\n\t\twithCodeComponent(sourceNode) &&\n\t\twithCodeComponent(targetNode)\n\t) {\n\t\t// Paste all code component properties that have the same key and type.\n\t\tconst styleProps = compatibleControlProps(componentLoader, sourceNode, targetNode)\n\t\tObject.assign(update, styleProps)\n\t}\n\n\t// NOTE: We handle shaders separately from code components in order to prevent copying control props between the two node types.\n\tif (shouldApplyUpdate(TraitType.ControlProps, limitToTrait) && withShader(sourceNode) && withShader(targetNode)) {\n\t\tconst styleProps = compatibleControlProps(componentLoader, sourceNode, targetNode)\n\t\tObject.assign(update, styleProps)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.CodeOverride, limitToTrait) &&\n\t\twithCodeOverride(sourceNode) &&\n\t\twithCodeOverride(targetNode)\n\t) {\n\t\tupdate.codeOverrideEnabled = sourceNode.codeOverrideEnabled\n\t\tupdate.codeOverrideIdentifier = sourceNode.codeOverrideIdentifier\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormInputFont, limitToTrait) &&\n\t\twithFormInputFontStyles(sourceNode) &&\n\t\twithFormInputFontStyles(targetNode)\n\t) {\n\t\tupdate.formInputFontFamily = sourceNode.formInputFontFamily\n\t\tupdate.formInputFontWeight = sourceNode.formInputFontWeight\n\t\tupdate.formInputFontStyle = sourceNode.formInputFontStyle\n\t\tupdate.formInputFontSize = sourceNode.formInputFontSize\n\t\tupdate.formInputFontSelector = sourceNode.formInputFontSelector\n\t\tupdate.formInputFontLetterSpacing = sourceNode.formInputFontLetterSpacing\n\t\tupdate.formInputFontLetterSpacingUnit = sourceNode.formInputFontLetterSpacingUnit\n\t\tupdate.formInputFontLineHeight = sourceNode.formInputFontLineHeight\n\t\tupdate.formInputFontLineHeightUnit = sourceNode.formInputFontLineHeightUnit\n\t\tupdate.formInputFontTextAlignment = sourceNode.formInputFontTextAlignment\n\t\tupdate.formInputOpenTypeFontFeatures = sourceNode.formInputOpenTypeFontFeatures\n\t\tupdate.formInputVariationAxes = sourceNode.formInputVariationAxes\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Layout, limitToTrait) && isFrameNode(targetNode)) {\n\t\tconst isStack = isStackComponent(sourceNode)\n\t\tconst isGrid = isGridComponent(sourceNode)\n\n\t\tif (isStack || isGrid) {\n\t\t\tif (!isReplicaVariantOrReplicaVariantChild(targetNode)) update.layout = sourceNode.layout\n\t\t\tupdate.gap = sourceNode.gap\n\t\t\tupdate.padding = sourceNode.padding\n\t\t\tupdate.paddingPerSide = sourceNode.paddingPerSide\n\t\t\tupdate.paddingTop = sourceNode.paddingTop\n\t\t\tupdate.paddingRight = sourceNode.paddingRight\n\t\t\tupdate.paddingBottom = sourceNode.paddingBottom\n\t\t\tupdate.paddingLeft = sourceNode.paddingLeft\n\n\t\t\tif (isStack) {\n\t\t\t\tupdate.stackDirection = sourceNode.stackDirection\n\t\t\t\tupdate.stackDistribution = sourceNode.stackDistribution\n\t\t\t\tupdate.stackAlignment = sourceNode.stackAlignment\n\t\t\t}\n\n\t\t\tif (isGrid) {\n\t\t\t\tupdate.gridAlignment = sourceNode.gridAlignment\n\t\t\t\tupdate.gridColumnCount = sourceNode.gridColumnCount\n\t\t\t\tupdate.gridColumnWidthType = sourceNode.gridColumnWidthType\n\t\t\t\tupdate.gridColumnWidth = sourceNode.gridColumnWidth\n\t\t\t\tupdate.gridColumnMinWidth = sourceNode.gridColumnMinWidth\n\t\t\t\tupdate.gridRowHeightType = sourceNode.gridRowHeightType\n\t\t\t\tupdate.gridRowHeight = sourceNode.gridRowHeight\n\t\t\t\tupdate.gridRowCount = sourceNode.gridRowCount\n\t\t\t\tupdate.gridType = sourceNode.gridType\n\t\t\t}\n\t\t}\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Position, limitToTrait)) {\n\t\tObject.assign(update, positionTypeUpdateForNewParent(sourceNode, newParent))\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.Perspective, limitToTrait) &&\n\t\twithTransforms(sourceNode) &&\n\t\twithTransforms(targetNode)\n\t) {\n\t\tupdate.perspective = withVariableFallback(sourceNode.perspective)\n\t}\n\n\t// Only share floating layout properties if both the target and source are\n\t// already floating. This ensures that we don't accidentally create a\n\t// floating layer without a trigger.\n\tif (\n\t\tshouldApplyUpdate(TraitType.Overlay, limitToTrait) &&\n\t\thasFloatingPosition(sourceNode) &&\n\t\thasFloatingPosition(targetNode) &&\n\t\tnewParent\n\t) {\n\t\tconst floatingPositionProps = getFloatingPositionProps(sourceNode)\n\t\tObject.assign(update, floatingPositionProps)\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Effects, limitToTrait) && withAnyEffect(sourceNode) && withAnyEffect(targetNode)) {\n\t\tObject.assign(update, getSupportedEffects(targetNode, sourceNode))\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.TransformOrigin, limitToTrait) &&\n\t\twithTransforms(sourceNode) &&\n\t\twithTransforms(targetNode)\n\t) {\n\t\tObject.assign(update, {\n\t\t\ttransformOriginX: sourceNode.transformOriginX,\n\t\t\ttransformOriginY: sourceNode.transformOriginY,\n\t\t})\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.BackfaceVisibility, limitToTrait) &&\n\t\twithTransforms(sourceNode) &&\n\t\twithTransforms(targetNode)\n\t) {\n\t\tObject.assign(update, { backfaceVisibility: sourceNode.backfaceVisibility })\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.TransformStylePreserve3d, limitToTrait) &&\n\t\twithTransforms(sourceNode) &&\n\t\twithTransforms(targetNode)\n\t) {\n\t\tObject.assign(update, { transformStylePreserve3d: sourceNode.transformStylePreserve3d })\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.TranslateZ, limitToTrait) &&\n\t\twithTransforms(sourceNode) &&\n\t\twithTransforms(targetNode)\n\t) {\n\t\tObject.assign(update, { translateZ: sourceNode.translateZ })\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Scale, limitToTrait) && withTransforms(sourceNode) && withTransforms(targetNode)) {\n\t\tObject.assign(update, { scale: sourceNode.scale })\n\t}\n\n\tif (shouldApplyUpdate(TraitType.Skew, limitToTrait) && withTransforms(sourceNode) && withTransforms(targetNode)) {\n\t\tObject.assign(update, { skewX: sourceNode.skewX, skewY: sourceNode.skewY })\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormBooleanInputType, limitToTrait) &&\n\t\twithFormBooleanInputType(sourceNode) &&\n\t\twithFormBooleanInputType(targetNode)\n\t) {\n\t\tObject.assign(update, { formBooleanInputType: sourceNode.formBooleanInputType })\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormBooleanInputValue, limitToTrait) &&\n\t\twithFormBooleanInputType(sourceNode) &&\n\t\twithFormBooleanInputType(targetNode)\n\t) {\n\t\tObject.assign(update, { formBooleanInputValue: sourceNode.formBooleanInputValue })\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormBooleanInputCheckedEffect, limitToTrait) &&\n\t\twithFormBooleanInputType(sourceNode) &&\n\t\twithFormBooleanInputType(targetNode)\n\t) {\n\t\tconst values: Partial<WithFormBooleanInputType> = {\n\t\t\tformBooleanInputCheckedBorderColor: sourceNode.formBooleanInputCheckedBorderColor,\n\t\t\tformBooleanInputCheckedBorderWidth: sourceNode.formBooleanInputCheckedBorderWidth,\n\t\t\tformBooleanInputCheckedBorderStyle: sourceNode.formBooleanInputCheckedBorderStyle,\n\t\t\tformBooleanInputCheckedFillColor: sourceNode.formBooleanInputCheckedFillColor,\n\t\t\tformBooleanInputCheckedBoxShadow: sourceNode.formBooleanInputCheckedBoxShadow,\n\t\t\tformBooleanInputCheckedTransition: sourceNode.formBooleanInputCheckedTransition,\n\t\t}\n\t\tObject.assign(update, values)\n\t}\n\n\tif (\n\t\tshouldApplyUpdate(TraitType.FormInputIcon, limitToTrait) &&\n\t\twithFormInputIcon(sourceNode) &&\n\t\twithFormInputIcon(targetNode)\n\t) {\n\t\tObject.assign(update, {\n\t\t\tformInputIconImage: sourceNode.formInputIconImage,\n\t\t\tformInputIconColor: sourceNode.formInputIconColor,\n\t\t})\n\t}\n\tif (\n\t\tshouldApplyUpdate(TraitType.ViewTransitionNone, limitToTrait) &&\n\t\twithViewTransitionNone(sourceNode) &&\n\t\twithViewTransitionNone(targetNode)\n\t) {\n\t\tupdate.viewTransitionNone = sourceNode.viewTransitionNone\n\t}\n\n\treturn update\n}\n", "export const uniquePairs = <T extends {}>(list: T[]): [T, T][] => {\n\tconst result: [T, T][] = []\n\tlist.forEach((itemA, index) => {\n\t\tfor (let j = index + 1; j < list.length; j++) {\n\t\t\tconst itemB = list[j]\n\t\t\tresult.push([itemA, itemB])\n\t\t}\n\t})\n\treturn result\n}\n", "import { getRelatedReplicaNodes } from \"code-generation/utils/isOnlyVisibleInCurrentVariant.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isDrawableNode } from \"document/models/CanvasTree/index.ts\"\nimport type FrameNode from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport { TemplateHelper } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport {\n\tisDesignPageNode,\n\tisShapeContainerNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { NonDynamicValue, NonDynamicValueRecord } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type { WithAspectRatio } from \"document/models/CanvasTree/traits/WithAspectRatio.ts\"\nimport { withAspectRatio } from \"document/models/CanvasTree/traits/WithAspectRatio.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport type { HasStackLayout, WithLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport {\n\tdefaultStackAlignment,\n\tdefaultStackDistribution,\n\tgetLayoutType,\n\thasGridLayout,\n\thasStackLayout,\n\twithLayout,\n} from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { isLockedOrLockedByParent } from \"document/models/CanvasTree/traits/WithLock.ts\"\nimport { type WithPadding, paddingDefinedDefaults, withPadding } from \"document/models/CanvasTree/traits/WithPadding.ts\"\nimport type { WithPins } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { isPinnable } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { isScreen } from \"document/models/CanvasTree/traits/WithScreen.ts\"\nimport type { WithSizeConstraints } from \"document/models/CanvasTree/traits/WithSizeConstraints.ts\"\nimport { supportsSizeConstraints } from \"document/models/CanvasTree/traits/WithSizeConstraints.ts\"\nimport { hasViewportHeight, hasViewportWidth } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isDeviceNode } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifierChecks.ts\"\nimport { isPositionAbsolute, isPositionFixed } from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { convertFrameToCanvas } from \"document/models/CanvasTree/utils/geometry.ts\"\nimport { shouldGuessPinToBottom } from \"document/models/shouldGuessPinToBottom.ts\"\nimport { shouldGuessPinToRight } from \"document/models/shouldGuessPinToRight.ts\"\nimport type { StackDirection } from \"library/components/Stack/types.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { Point } from \"library/render/types/Point.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport type { Size } from \"library/render/types/Size.ts\"\nimport type { NonUndefinedRecord } from \"utils/NonUndefined.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { uniquePairs } from \"./uniquePairs.ts\"\n\nexport function inferStackDirectionForChildren(\n\ttree: CanvasTree,\n\tchildNodes: CanvasNode[] /* these need to be siblings */,\n\tcontainerSize: Size,\n): NonDynamicValue<NonNullable<WithLayout[\"stackDirection\"]>> {\n\tconst childRects = childNodes.map(node => convertFrameToCanvas(tree, node))\n\n\t// If we have only two rects, we want to know if they overlap over an axis\n\tif (childRects.length === 2) {\n\t\tconst [firstRect, secondRect] = childRects as [Rect, Rect]\n\t\tconst isVerticalStack = rectsAreVerticallyStacked(firstRect, secondRect)\n\t\tconst isHorizontalStack = rectsAreHorizontallyStacked(firstRect, secondRect)\n\t\tif (isVerticalStack && !isHorizontalStack) return \"vertical\"\n\t\tif (isHorizontalStack && !isVerticalStack) return \"horizontal\"\n\t}\n\n\tconst centerPoints = childRects.map(rect => Rect.center(rect))\n\tif (centerPoints.length <= 1) {\n\t\tif (childRects.length === 1) {\n\t\t\t// If we have a single child, check which direction leaves the most space for new siblings\n\t\t\tconst [rect] = childRects as [Rect]\n\t\t\tconst widthRatio = containerSize.width / Math.max(1, rect.width)\n\t\t\tconst heightRatio = containerSize.height / Math.max(1, rect.height)\n\t\t\treturn widthRatio < heightRatio ? \"vertical\" : \"horizontal\"\n\t\t}\n\t\treturn containerSize.width < containerSize.height ? \"vertical\" : \"horizontal\"\n\t}\n\n\tconst pairs = uniquePairs(centerPoints)\n\tconst deltaXs: number[] = []\n\tconst deltaYs: number[] = []\n\tpairs.forEach(([pointA, pointB]) => {\n\t\tdeltaXs.push(Math.abs(pointA.x - pointB.x))\n\t\tdeltaYs.push(Math.abs(pointA.y - pointB.y))\n\t})\n\tconst totalDeltaX = deltaXs.reduce((a, b) => a + b, 0)\n\tconst totalDeltaY = deltaYs.reduce((a, b) => a + b, 0)\n\tconst isHorizontal = totalDeltaX > totalDeltaY\n\treturn isHorizontal ? \"horizontal\" : \"vertical\"\n}\n\nfunction inferChildrenOrder(\n\tengine: VekterEngine,\n\tchildNodes: CanvasNode[],\n\tdirection: WithLayout[\"stackDirection\"],\n): CanvasNode[] {\n\treturn [...childNodes].sort((a, b) => {\n\t\tconst rectA = engine.tree.getRect(a)\n\t\tconst rectB = engine.tree.getRect(b)\n\t\treturn direction === \"horizontal\" ? rectA.x - rectB.x : rectA.y - rectB.y\n\t})\n}\n\nexport function distributionSupportsGap(distribution: WithLayout[\"stackDistribution\"]): boolean {\n\tif (isDynamicValue(distribution)) return true\n\tswitch (distribution) {\n\t\tcase \"start\":\n\t\tcase \"center\":\n\t\tcase \"end\":\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\nexport function inferStackLayout(\n\tengine: VekterEngine,\n\tchildren: CanvasNode[],\n\trect: Rect,\n): NonDynamicValueRecord<NonUndefinedRecord<HasStackLayout & WithPadding>> {\n\tconst stackDirection = inferStackDirectionForChildren(engine.tree, children, rect)\n\tconst gap = engine.stores.persistedUserDefaults.layoutGap\n\treturn {\n\t\tlayout: \"stack\",\n\t\tstackDirection,\n\t\tgap,\n\t\tstackDistribution: defaultStackDistribution,\n\t\tstackAlignment: defaultStackAlignment,\n\t\tstackWrapEnabled: false,\n\t\tpadding: 0,\n\t\tpaddingPerSide: false,\n\t\tpaddingTop: 0,\n\t\tpaddingRight: 0,\n\t\tpaddingBottom: 0,\n\t\tpaddingLeft: 0,\n\t}\n}\n\nfunction sortChildren(engine: VekterEngine, orderedChildNodes: CanvasNode[]) {\n\torderedChildNodes.forEach((childNode, idx) => {\n\t\tengine.tree.moveNodeIndex(childNode, idx)\n\t})\n}\n\nexport function updateChildrenSizingWhenWrappedInStack(\n\tengine: VekterEngine,\n\tstackNode: FrameNode & WithLayout,\n\tstackDirection: \"horizontal\" | \"vertical\",\n\tchildren: CanvasNode[],\n\tstackRect: Rect,\n) {\n\tconst isAutoCrossAxis =\n\t\t(stackDirection === \"horizontal\" && stackNode.heightType === DimensionType.Auto) ||\n\t\t(stackDirection === \"vertical\" && stackNode.widthType === DimensionType.Auto)\n\n\tif (!isAutoCrossAxis) {\n\t\tmakeChildrenResponsiveHorizontally(engine, children, stackDirection, stackRect, {})\n\t}\n}\n\nfunction makeChildrenResponsiveHorizontally(\n\tengine: VekterEngine,\n\tchildren: CanvasNode[],\n\tdirection: StackDirection,\n\tcontainerSize: Size,\n\tpaddingInfo: Partial<WithPadding>,\n) {\n\t// Don't try to be smart for horizontal lists or if the padding is dynamic\n\tif (direction === \"horizontal\" || isDynamicValue(paddingInfo.padding)) return\n\n\tconst contentSize = { ...containerSize }\n\n\tif (paddingInfo.paddingPerSide) {\n\t\tif (paddingInfo.paddingLeft) contentSize.width -= paddingInfo.paddingLeft\n\t\tif (paddingInfo.paddingRight) contentSize.width -= paddingInfo.paddingRight\n\t\tif (paddingInfo.paddingTop) contentSize.height -= paddingInfo.paddingTop\n\t\tif (paddingInfo.paddingBottom) contentSize.height -= paddingInfo.paddingBottom\n\t} else if (paddingInfo.padding) {\n\t\tconst doublePadding = paddingInfo.padding * 2\n\t\tcontentSize.width -= doublePadding\n\t\tcontentSize.height -= doublePadding\n\t}\n\n\tcontentSize.width = Math.max(0, contentSize.width)\n\tcontentSize.height = Math.max(0, contentSize.height)\n\tconst contentWidth = contentSize.width\n\n\tif (contentWidth > 0) {\n\t\tchildren.forEach(child => {\n\t\t\tif (!isPinnable(child)) return\n\t\t\tif (isShapeContainerNode(child)) return\n\t\t\tif (isPositionAbsolute(child) || isPositionFixed(child)) return\n\t\t\tif (child.widthType === DimensionType.Auto) return\n\t\t\t// A viewport node's rect on the canvas is just an arbitrary representation, not the actual size of the node\n\t\t\t// in preview/site, so even if it looks like the node is stretched to fill the stack, it doesn't make sense\n\t\t\t// to make it fractional.\n\t\t\tif (child.widthType === DimensionType.Viewport) return\n\n\t\t\tconst rect = engine.tree.getRect(child)\n\t\t\tconst relativeSize = rect.width / contentWidth\n\n\t\t\t// Make responsive\n\t\t\tif (relativeSize > 0.96) {\n\t\t\t\tconst parent = engine.tree.getParent(child.id)\n\t\t\t\tconst parentSizeInfo = engine.tree.getParentSizeInfo(child)\n\t\t\t\tif (parentSizeInfo.sizing && child.heightType === DimensionType.Viewport) {\n\t\t\t\t\t// If the node is using vh, it should ignore the vertical padding. The parentSize's height returned\n\t\t\t\t\t// by tree.getParentSizeForSizing would be the viewport height for a vh node, use that instead of\n\t\t\t\t\t// the contentSize (which subtracts the vertical padding).\n\t\t\t\t\tparentSizeInfo.sizing = { ...contentSize, height: parentSizeInfo.sizing.height }\n\t\t\t\t}\n\t\t\t\tconst childRect = engine.tree.getRect(child)\n\n\t\t\t\tconst update: Partial<WithPins> = child.updateForRect({\n\t\t\t\t\trect: childRect,\n\t\t\t\t\tparentSizeInfo,\n\t\t\t\t\tconstraintsLocked: true,\n\t\t\t\t\tshouldGuessPinToBottom: shouldGuessPinToBottom(engine.tree, child),\n\t\t\t\t\tshouldGuessPinToRight: shouldGuessPinToRight(engine.tree, child, parent),\n\t\t\t\t})\n\n\t\t\t\tupdate.width = 1\n\t\t\t\t// If the widthType is percentage, it will be responsive too, so\n\t\t\t\t// we do not update it.\n\t\t\t\tif (child.width !== DimensionType.Percentage) {\n\t\t\t\t\tupdate.widthType = DimensionType.FractionOfFreeSpace\n\t\t\t\t}\n\t\t\t\tchild.set(update)\n\t\t\t}\n\t\t})\n\t}\n}\n\nexport function reparentStackChildren(\n\tengine: VekterEngine,\n\tnewStackId: NodeID,\n\tnewStackRect: Rect,\n\tchildNodes: CanvasNode[],\n\tdirection: WithLayout[\"stackDirection\"],\n) {\n\tconst newStack = engine.tree.getNode<FrameNode>(newStackId)\n\tif (!newStack) return\n\n\tconst orderedChildren = inferChildrenOrder(engine, childNodes, direction)\n\n\torderedChildren.forEach(child => {\n\t\tif (isDrawableNode(child) && isLockedOrLockedByParent(child)) {\n\t\t\treturn\n\t\t}\n\t\tif (isDeviceNode(child)) {\n\t\t\treturn\n\t\t}\n\n\t\tconst parent = engine.tree.getParent(child.id)\n\t\tconst childFrame = engine.tree.getRect(child)\n\t\tconst convertedFrame = Rect.offset(childFrame, Point.reverse(newStackRect))\n\n\t\tengine.moveNode(child.id, newStackId)\n\n\t\t// If the child is using vw/vh, its width/height should not be affected by the new drawn parent rect.\n\t\tconst parentSizeForSizing = { ...newStackRect }\n\t\tconst currentParentSizeInfo = engine.tree.getParentSizeInfo(child)\n\t\tif (hasViewportWidth(child) && currentParentSizeInfo.sizing) {\n\t\t\tparentSizeForSizing.width = currentParentSizeInfo.sizing.width\n\t\t}\n\t\tif (hasViewportHeight(child) && currentParentSizeInfo.sizing) {\n\t\t\tparentSizeForSizing.height = currentParentSizeInfo.sizing.height\n\t\t}\n\n\t\tengine.tree.current(child)?.set({\n\t\t\t// @FIXME: we should go over the replica variants and update their constraints as well, if overridden.\n\t\t\t...child.updateForRect({\n\t\t\t\trect: convertedFrame,\n\t\t\t\tparentSizeInfo: {\n\t\t\t\t\tsizing: parentSizeForSizing,\n\t\t\t\t\tpositioning: newStackRect,\n\t\t\t\t\tviewport: currentParentSizeInfo?.viewport ?? null,\n\t\t\t\t\tlayout: getLayoutType(parent),\n\t\t\t\t},\n\t\t\t\tconstraintsLocked: false,\n\t\t\t\tshouldGuessPinToBottom: true,\n\t\t\t\tshouldGuessPinToRight: shouldGuessPinToRight(engine.tree, child, parent),\n\t\t\t}),\n\t\t\ttop: null,\n\t\t\tleft: null,\n\t\t\tbottom: null,\n\t\t\tright: null,\n\t\t\t// Turn wrapped children into position: relative by default.\n\t\t\tposition: undefined,\n\t\t})\n\n\t\t// Unset the position on all replica as well.\n\t\tconst relatedNodes = getRelatedReplicaNodes(engine.tree, child)\n\t\t// Can't use resetNodeOverrides directly here as it creates a circular dependency with contextActions.\n\t\trelatedNodes.forEach(({ replicaRoot, relatedNode }) => {\n\t\t\tTemplateHelper.resetOverridesByProperty(engine.tree, replicaRoot, relatedNode, [\"position\"])\n\t\t})\n\t})\n}\n\nfunction rectsAreVerticallyStacked(rectA: Rect, rectB: Rect): boolean {\n\tconst aMax = Rect.maxX(rectA)\n\tconst bMax = Rect.maxX(rectB)\n\treturn aMax > rectB.x && bMax > rectA.x\n}\n\nfunction rectsAreHorizontallyStacked(rectA: Rect, rectB: Rect): boolean {\n\tconst aMax = Rect.maxY(rectA)\n\tconst bMax = Rect.maxY(rectB)\n\treturn aMax > rectB.y && bMax > rectA.y\n}\n\nexport function convertChildrenToFixedSizeAlongDimension(tree: CanvasTree, dimension: keyof Size, node: CanvasNode) {\n\tif (!withChildren(node)) return\n\n\tconst dimensionTypeKey: keyof WithPins = dimension === \"width\" ? \"widthType\" : \"heightType\"\n\tnode.children.forEach(child => {\n\t\tif (!isPinnable(child)) return\n\t\tif (\n\t\t\tchild[dimensionTypeKey] === DimensionType.FractionOfFreeSpace ||\n\t\t\tchild[dimensionTypeKey] === DimensionType.Percentage\n\t\t) {\n\t\t\tconst childRect = tree.getRect(child)\n\t\t\tconst update: Partial<WithPins & WithAspectRatio> = {\n\t\t\t\t[dimensionTypeKey]: DimensionType.FixedNumber,\n\t\t\t\t[dimension]: childRect[dimension],\n\t\t\t}\n\t\t\tif (withAspectRatio(child)) {\n\t\t\t\tupdate.aspectRatio = null\n\t\t\t}\n\t\t\ttree.current(child)?.set(update)\n\t\t}\n\t})\n}\n\nexport function applySizeConstraintToChildren(tree: CanvasTree, node: CanvasNode) {\n\tif (!withChildren(node) || !isPinnable(node)) return\n\n\tconst updatedChildren = new Set<CanvasNode>()\n\tnode.children.forEach(child => {\n\t\tif (!isPinnable(child) || !supportsSizeConstraints(child)) return\n\t\tconst childRect = tree.getRect(child)\n\t\tconst update: Partial<WithSizeConstraints> = {}\n\t\tif (node.widthType === DimensionType.Auto) {\n\t\t\tif (child.widthType === DimensionType.FractionOfFreeSpace || child.widthType === DimensionType.Percentage) {\n\t\t\t\tupdate.minWidth = childRect.width\n\t\t\t\tupdatedChildren.add(child)\n\t\t\t}\n\t\t}\n\n\t\tif (node.heightType === DimensionType.Auto) {\n\t\t\tif (child.heightType === DimensionType.FractionOfFreeSpace || child.heightType === DimensionType.Percentage) {\n\t\t\t\tupdate.minHeight = childRect.height\n\t\t\t}\n\t\t}\n\n\t\tif (Object.keys(update).length > 0) {\n\t\t\tupdatedChildren.add(child)\n\t\t\ttree.current(child)?.set(update)\n\t\t}\n\t})\n\n\tif (updatedChildren.size > 0) {\n\t\tshowChildrenDimensionChangeToast()\n\t}\n}\n\nfunction showChildrenDimensionChangeToast() {\n\ttoast({\n\t\ttype: \"add\",\n\t\tvariant: \"info\",\n\t\tkey: \"setting-stack-direction-causes-children-change\",\n\t\tprimaryText: \"Min sizing added\",\n\t\tsecondaryText: \"to prevent layout collapse.\",\n\t\ticon: \"thumbnail\",\n\t\tduration: 5000,\n\t\tshowCloseButton: \"always\",\n\t})\n}\n\nexport interface DimensionTypeOverrides {\n\twidthType?: DimensionType\n\theightType?: DimensionType\n}\n\nexport function enableStackLayoutForNode(\n\tengine: VekterEngine,\n\tnode: CanvasNode,\n\tdimensionTypeOverrides: DimensionTypeOverrides = {},\n) {\n\tif (!withLayout(node) || !withChildren(node)) return\n\tif (hasStackLayout(node)) return\n\n\tconst update: Partial<WithLayout & DimensionTypeOverrides> = {\n\t\tlayout: \"stack\",\n\t\t...dimensionTypeOverrides,\n\t}\n\n\tconst containerSize = engine.tree.getRect(node)\n\tconst scope = engine.tree.getScopeNodeFor(node)\n\tconst isScreenOrWebPageRoot =\n\t\tisScreen(node) ||\n\t\t(isVariant(node) && isWebPageNode(scope)) ||\n\t\t(node.__unsafeIsGroundNode(engine.tree) && isDesignPageNode(scope))\n\tconst children = node.children.toArray()\n\tconst direction = isScreenOrWebPageRoot\n\t\t? \"vertical\"\n\t\t: inferStackDirectionForChildren(engine.tree, children, containerSize)\n\tconst orderedChildren = inferChildrenOrder(engine, children, direction)\n\n\tif (!isReplicaOrReplicaChild(node)) sortChildren(engine, orderedChildren)\n\tconst wasGrid = hasGridLayout(node)\n\tconst gap = node.gap ?? engine.stores.persistedUserDefaults.layoutGap\n\tconst stackDistribution = isScreenOrWebPageRoot ? \"start\" : \"center\"\n\n\t// Try to reuse the settings when toggling between grid & stack\n\tupdate.stackDirection = wasGrid ? (node.stackDirection ?? direction) : direction\n\tupdate.stackDistribution = wasGrid ? (node.stackDistribution ?? stackDistribution) : stackDistribution\n\tupdate.gap = wasGrid || distributionSupportsGap(stackDistribution) ? gap : 0\n\tupdate.stackAlignment = wasGrid ? (node.stackAlignment ?? defaultStackAlignment) : defaultStackAlignment\n\tupdate.stackWrapEnabled = wasGrid ? (node.stackWrapEnabled ?? false) : false\n\n\tconst paddingUpdate: WithPadding =\n\t\twasGrid && withPadding(node)\n\t\t\t? {\n\t\t\t\t\tpadding: node.padding,\n\t\t\t\t\tpaddingPerSide: node.paddingPerSide,\n\t\t\t\t\tpaddingLeft: node.paddingLeft,\n\t\t\t\t\tpaddingRight: node.paddingRight,\n\t\t\t\t\tpaddingTop: node.paddingTop,\n\t\t\t\t\tpaddingBottom: node.paddingBottom,\n\t\t\t\t}\n\t\t\t: { ...paddingDefinedDefaults }\n\n\tconst isAutoCrossAxis =\n\t\t(direction === \"horizontal\" && dimensionTypeOverrides.heightType === DimensionType.Auto) ||\n\t\t(direction === \"vertical\" && dimensionTypeOverrides.widthType === DimensionType.Auto)\n\n\tif (!isAutoCrossAxis) {\n\t\tmakeChildrenResponsiveHorizontally(engine, children, direction, containerSize, paddingUpdate)\n\t}\n\n\t// Make sure we only use padding per side when the sides are unequal\n\tif (paddingUpdate.paddingPerSide) {\n\t\tconst { paddingTop, paddingRight, paddingBottom, paddingLeft } = paddingUpdate\n\t\tif (paddingTop === paddingRight && paddingTop === paddingBottom && paddingTop === paddingLeft) {\n\t\t\tpaddingUpdate.paddingPerSide = false\n\t\t\tpaddingUpdate.padding = paddingTop\n\t\t}\n\t}\n\n\tnode.set({ ...update, ...paddingUpdate })\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { DimensionTypeOverrides } from \"document/components/tools/utils/stackCreateHelper.ts\"\nimport { enableStackLayoutForNode } from \"document/components/tools/utils/stackCreateHelper.ts\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isAnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport { isFrameNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasAnyLayout, hasStackLayout, withLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { withSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { isBreakpointVariant, isPrimaryVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport { checkDimensionEnabled } from \"./layoutHelpers.ts\"\n\nconst minLayoutSectionWidth = 900\n\nexport function isLayoutSectionBasedOnIntrinsicSize(size: {\n\tintrinsicWidth: number\n\tintrinsicHeight: number\n}): boolean {\n\treturn size.intrinsicWidth >= minLayoutSectionWidth\n}\n\nexport function isLayoutSection(tree: CanvasTree, node: CanvasNode, parentNode?: CanvasNode): boolean {\n\tif (isAnyTextNode(node)) return false\n\tconst parent = parentNode ?? tree.getParent(node.id)\n\treturn Boolean(parent && isBreakpointVariant(parent))\n}\n\nexport function simpleSelectionForLayoutSectionEnabled(zoom: number): boolean {\n\treturn zoom <= 0.5\n}\n\nfunction shouldAutoConvertParentToStack(tree: CanvasTree, parent: CanvasNode, nodeToInsert: CanvasNode): boolean {\n\tif (!isFrameNode(parent) || !isPrimaryVariant(parent) || !isBreakpointVariant(parent)) return false\n\tif (hasAnyLayout(parent)) return false\n\tif (!isLayoutSection(tree, nodeToInsert, parent)) return false\n\tconst isFullWidth =\n\t\twithSize(nodeToInsert) &&\n\t\twithSizeDimensionType(nodeToInsert) &&\n\t\tnodeToInsert.widthType === DimensionType.Percentage &&\n\t\tnodeToInsert.width === 1\n\tif (withSize(nodeToInsert) && nodeToInsert.width < minLayoutSectionWidth && !isFullWidth) return false\n\n\tconst children = parent.children.filter(child => child.id !== nodeToInsert.id)\n\n\tif (children.length === 0) return true\n\n\tconst breakpointRect = tree.getRect(parent)\n\tconst breakpointWidth = breakpointRect.width || 1 // Make sure we don't divide by zero\n\n\tconst childRects = children.map(child => tree.getRect(child))\n\n\tconst anyChildSpanningLessThanHalfTheWidth = childRects.some(childRect => childRect.width / breakpointWidth < 0.5)\n\tif (anyChildSpanningLessThanHalfTheWidth) return false\n\n\tconst noIntersectingChildren = childRects.every((childRectA, idxA) => {\n\t\treturn childRects.every((childRectB, idxB) => {\n\t\t\tif (idxA === idxB) return true\n\t\t\treturn !Rect.intersects(childRectA, childRectB)\n\t\t})\n\t})\n\n\treturn noIntersectingChildren\n}\n\n/**\n * We convert a parent to a stack if it's a primary breakpoint without any children or without any\n * overlapping children.\n */\nexport function autoConvertParentToStackIfNeeded(\n\tengine: VekterEngine,\n\tparent: CanvasNode,\n\tnodeToInsert: CanvasNode,\n\tinsertionRect: Rect,\n) {\n\tif (!withLayout(parent)) return\n\tif (!shouldAutoConvertParentToStack(engine.tree, parent, nodeToInsert)) return\n\n\tconst dimensionTypeOverrides: DimensionTypeOverrides = {}\n\n\t// Only change height to auto for large elements\n\tif (insertionRect.height > 500) {\n\t\tdimensionTypeOverrides.heightType = DimensionType.Auto\n\t}\n\n\tenableStackLayoutForNode(engine, parent, dimensionTypeOverrides)\n\tparent.set({ gap: 0 })\n}\n\n/**\n * Make web page auto height if its a primary breakpoint and a vertical stack\n * and the new content no longer fits.\n */\nexport function makePrimaryBreakpointAutoSizingIfNeeded(\n\tengine: VekterEngine,\n\tparent: CanvasNode,\n\tnodeToInsert: CanvasNode,\n\tinsertionRect: Rect,\n) {\n\tif (!isFrameNode(parent) || !isPrimaryVariant(parent) || !isBreakpointVariant(parent)) return\n\tif (!hasStackLayout(parent) || parent.stackDirection !== \"vertical\") return\n\tif (!isLayoutSection(engine.tree, nodeToInsert, parent)) return\n\tif (parent.heightType === DimensionType.Auto) return\n\n\tconst parentAutoHeightEnabled = checkDimensionEnabled(engine.tree, engine.componentLoader, parent).height[\n\t\tDimensionType.Auto\n\t]\n\tif (!parentAutoHeightEnabled) return\n\n\tconst children = parent.children.filter(child => child.id !== nodeToInsert.id)\n\n\tif (children.length === 0) return\n\n\tconst groundNodeSize = engine.tree.getRect(parent)\n\n\tconst childrenRects = children.map(child => engine.tree.getRect(child))\n\tconst childrenBounds = Rect.merge(...childrenRects)\n\n\t// Check if existing children + the newly inserted node fit within the parent\n\tif (childrenBounds.height + insertionRect.height <= groundNodeSize.height) return\n\n\tparent.set({\n\t\theight: groundNodeSize.height,\n\t\theightType: DimensionType.Auto,\n\t})\n\n\t// Change any child that has a \"fr\" height to fixed height.\n\tchildren.forEach((child, i) => {\n\t\tconst rect = childrenRects[i]\n\t\t// childrenRects is mapped from children, so their length should match\n\t\tassert(rect, \"Child rect must be defined\")\n\n\t\tif (!withSize(child)) return\n\t\tif (!withSizeDimensionType(child)) return\n\t\tif (child.heightType !== DimensionType.FractionOfFreeSpace) return\n\n\t\tchild.set({\n\t\t\theight: rect.height,\n\t\t\theightType: DimensionType.FixedNumber,\n\t\t})\n\t})\n}\n", "import { Path } from \"document/models/Path.ts\"\nimport type { WithPath } from \"library/render/traits/Path.ts\"\nimport type { Rect } from \"library/render/types/Rect.ts\"\n\nexport function normalizeWithPath(withPath: WithPath): [WithPath, Rect] {\n\tconst frame = Path.boundingBox(withPath)\n\tconst updatedSegments = withPath.pathSegments.map(segment => {\n\t\treturn segment.merge({\n\t\t\tx: segment.x - frame.x,\n\t\t\ty: segment.y - frame.y,\n\t\t})\n\t})\n\treturn [\n\t\t{\n\t\t\tpathClosed: withPath.pathClosed,\n\t\t\tpathSegments: updatedSegments,\n\t\t},\n\t\tframe,\n\t]\n}\n", "import { assert, getLogger } from \"@framerjs/shared\"\nimport type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport type { SVGNode } from \"document/models/CanvasTree/index.ts\"\nimport { NullID, randomID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport ShapeContainerNode from \"document/models/CanvasTree/nodes/ShapeContainerNode.ts\"\nimport ShapeGroupNode from \"document/models/CanvasTree/nodes/ShapeGroupNode.ts\"\nimport type { DrawableNode } from \"document/models/CanvasTree/nodes/TreeNode.ts\"\nimport { BooleanShapeNode } from \"document/models/CanvasTree/nodes/shapes/BooleanShapeNode.ts\"\nimport { PathNode } from \"document/models/CanvasTree/nodes/shapes/PathNode.ts\"\nimport type { WithFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { PathBooleanType } from \"document/models/CanvasTree/traits/WithPathBoolean.ts\"\nimport type { WithPosition } from \"document/models/CanvasTree/traits/WithPosition.ts\"\nimport type { WithSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport { withSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport { LinearGradient } from \"document/models/Gradient.ts\"\nimport type { Size } from \"library/index.ts\"\nimport { Point } from \"library/render/types/Point.ts\"\nimport { domParser } from \"library/render/utils/dom.ts\"\nimport { getPaperLazily } from \"utils/paperjs/utils/getPaper.js\"\nimport { normalizeWithPath } from \"utils/paperjs/utils/normalizeWithPath.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { convertPaperPathItemAttributes, convertPaperPathItemToWithPaths } from \"./paperjsToVekter.ts\"\nimport type { PaperType } from \"./utils/getPaper.js\"\n\ntype MaybeDrawableNode = null | DrawableNode\n\nexport function importSVG(\n\tsvg: string,\n\tcreateEmptyTree: () => CanvasTree,\n\tsize?: Size,\n\tnode?: SVGNode | undefined,\n): ShapeContainerNode | null {\n\tconst log = getLogger(\"app:importSVG\")\n\n\tlet svgStringOrElement: string | SVGElement = svg\n\tlet attributeOverrides: Partial<WithFill> | undefined\n\tlet svgSize: Size | undefined = undefined\n\n\tif (node && node.colorable) {\n\t\tconst svgDocument = domParser(svg, \"image/svg+xml\")\n\t\tconst svgElement = svgDocument.documentElement as HTMLElement & SVGSVGElement\n\t\tif (!svgElement) {\n\t\t\tthrow new Error(`Unsupported SVG: ${svg}}`)\n\t\t}\n\t\tconst presetFill = svgElement.getAttribute(\"fill\")\n\t\tconst shouldFill = !(presetFill && presetFill.toLowerCase() === \"none\")\n\n\t\tif (shouldFill) {\n\t\t\tif (node.fillType === \"linear-gradient\" && node.fillLinearGradient instanceof LinearGradient) {\n\t\t\t\tattributeOverrides = {\n\t\t\t\t\tfillType: \"linear-gradient\",\n\t\t\t\t\tfillLinearGradient: node.fillLinearGradient,\n\t\t\t\t}\n\t\t\t} else if (node.fillType === \"image\" && node.fillImage) {\n\t\t\t\tattributeOverrides = {\n\t\t\t\t\tfillType: \"image\",\n\t\t\t\t\tfillImage: node.fillImage,\n\t\t\t\t\tfillImageResize: node.fillImageResize,\n\t\t\t\t\tfillImagePixelWidth: node.fillImagePixelWidth,\n\t\t\t\t\tfillImagePixelHeight: node.fillImagePixelHeight,\n\t\t\t\t}\n\t\t\t} else if (node.fillType === \"color\" && isString(node.fillColor)) {\n\t\t\t\tconst Paper = getPaperLazily()\n\t\t\t\tconst fillColorForStyle = new Paper.Color(node.fillColor)\n\t\t\t\tconst fillColorCSS = fillColorForStyle.toCSS(false)\n\t\t\t\tif (shouldFill) {\n\t\t\t\t\tsvgElement.setAttribute(\"style\", `fill: ${fillColorCSS}; color: ${fillColorCSS}`)\n\t\t\t\t}\n\n\t\t\t\tconst presetStroke = svgElement.getAttribute(\"stroke\")\n\t\t\t\tif (presetStroke && presetStroke.toLowerCase() === \"currentcolor\") {\n\t\t\t\t\tsvgElement.setAttribute(\"stroke\", fillColorCSS)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsvgStringOrElement = svgElement\n\t\t}\n\t}\n\n\tconst processed = preProcessSVGForPaper(svgStringOrElement)\n\tsvgStringOrElement = processed.svgElement\n\tsvgSize = processed.svgSize\n\n\tlet anErrorOccuredWhileImporting = false\n\tconst Paper = getPaperLazily()\n\tconst paperItem = Paper.project.importSVG(svgStringOrElement, {\n\t\texpandShapes: true,\n\t\tinsert: false,\n\t\tsize,\n\t\tonError: (error: any) => {\n\t\t\tlog.reportError(error)\n\t\t\tanErrorOccuredWhileImporting = true\n\n\t\t\t// For reasons unknown, PaperJS decides to leave SVGs lingering\n\t\t\t// on the canvas when an error occurs. Clean this up:\n\t\t\tconst body = document && document.getElementsByTagName(\"body\")\n\t\t\tif (body && body[0]) {\n\t\t\t\tlet lastChild = body[0].lastElementChild\n\t\t\t\twhile (lastChild && lastChild.tagName === \"svg\") {\n\t\t\t\t\tlastChild.remove()\n\t\t\t\t\tlastChild = body[0].lastElementChild\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\n\tif (anErrorOccuredWhileImporting) {\n\t\treturn null\n\t}\n\n\tlet nodes: DrawableNode[]\n\ttry {\n\t\tnodes = convertPaperItemToNodes({\n\t\t\titem: paperItem,\n\t\t\tfillOverrides: attributeOverrides,\n\t\t\ttree: createEmptyTree(),\n\t\t})\n\t} catch (error) {\n\t\tlog.reportError(error)\n\t\treturn null\n\t}\n\n\tconst root = nodes[0]\n\tif (!root) {\n\t\treturn null\n\t}\n\n\t// In some cases, Paper doesn't produce a root node with the exact size defined on the SVG, but\n\t// rather the bound of the descendant shapes. Our scaling logic works on the assumption that\n\t// Paper will import the SVG as its intrinsic size, so update it to be so.\n\tif (withSize(root) && svgSize) {\n\t\troot.set({ width: svgSize.width, height: svgSize.height })\n\t}\n\n\t// Pull it through a tree to make sure all internals are correct\n\treturn createEmptyTree().insertNodes(nodes).getNode(root.id) as ShapeContainerNode\n}\n\n/** @deprecated NOTE: Only exported for testing */\nexport function convertPaperItemToNodes({\n\titem,\n\ttree,\n\tnodes = [],\n\tparent = null,\n\tparentAbsolutePosition = Point(0, 0),\n\tfillOverrides,\n}: {\n\titem: PaperType.Item\n\ttree: CanvasTree\n\tnodes?: DrawableNode[]\n\tparent?: MaybeDrawableNode\n\tparentAbsolutePosition?: Point\n\tfillOverrides?: Partial<WithFill>\n}): DrawableNode[] {\n\tconst Paper = getPaperLazily()\n\tif (item instanceof Paper.Group) {\n\t\treturn convertPaperGroupToNodes({ group: item, nodes, parent, parentAbsolutePosition, tree, fillOverrides })\n\t} else if (item instanceof Paper.PathItem) {\n\t\treturn convertPaperPathItemToNodes({ item, nodes, parent, parentAbsolutePosition, fillOverrides })\n\t} else if (process.env.NODE_ENV !== \"test\") {\n\t\t// biome-ignore lint/suspicious/noConsole: <explanation>\n\t\tconsole.warn(`Unhandled Paper item:`, item)\n\t}\n\treturn nodes\n}\n\n// Prepare the SVG into a good state so that Paper can import it bug-free.\nfunction preProcessSVGForPaper(svgStringOrElement: string | SVGElement) {\n\tconst svgElement = isString(svgStringOrElement)\n\t\t? (domParser(svgStringOrElement, \"image/svg+xml\").documentElement as HTMLElement & SVGSVGElement)\n\t\t: svgStringOrElement\n\tif (!svgElement) {\n\t\tthrow new Error(`Unsupported SVG: ${svgStringOrElement}}`)\n\t}\n\tlet svgSize: Size | undefined = undefined\n\n\t// If the width/height set on the SVG does not match the viewBox, Paper will attempt to\n\t// scale the shapes in order to fit them into the provided size. But that scaling is not\n\t// always correct. Here we attemp to match the viewBox and its width/height, so that Paper\n\t// would just import it as its intrinsic size, and we will handle the scaling ourselves\n\t// afterwards.\n\tconst viewBox = svgElement.getAttribute(\"viewBox\")\n\tconst width = svgElement.getAttribute(\"width\")\n\tconst height = svgElement.getAttribute(\"height\")\n\tif (viewBox) {\n\t\tconst [_, __, viewBoxWidth, viewBoxHeight] = viewBox.split(\" \")\n\t\tif (viewBoxWidth && viewBoxHeight) {\n\t\t\tsvgElement.setAttribute(\"width\", viewBoxWidth)\n\t\t\tsvgElement.setAttribute(\"height\", viewBoxHeight)\n\t\t\tsvgSize = { width: parseInt(viewBoxWidth), height: parseInt(viewBoxHeight) }\n\t\t}\n\t} else if (width && height) {\n\t\t// SVGO drops the viewBox as an optimization, if the size matches the viewBox. If we\n\t\t// can't find a viewBox, check the width/height set on the svg\n\t\tsvgSize = { width: parseInt(width), height: parseInt(height) }\n\t}\n\n\t// Iterate through the children and update them if needed.\n\tpreProcessElementsForPaper(svgElement)\n\n\treturn { svgElement, svgSize }\n}\n\nfunction preProcessElementsForPaper(element: Element) {\n\tpreProcessRadius(element)\n\n\tfor (const child of element.children) {\n\t\tpreProcessElementsForPaper(child)\n\t}\n}\n\nfunction preProcessRadius(element: Element) {\n\t// If the radius is set only on one axis, Paper will drop the radius. If a properly specified\n\t// value is provided for rx but not for ry (or the opposite), then the browser will consider the\n\t// missing value equal to the defined one. Therefore we update the other axis to match.\n\t// See: https://github.com/paperjs/paper.js/issues/1863\n\tconst rx = element.getAttribute(\"rx\")\n\tconst ry = element.getAttribute(\"ry\")\n\tif (!rx && !ry) return\n\tif (rx && ry) return\n\tif (rx) {\n\t\telement.setAttribute(\"ry\", rx)\n\t} else if (ry) {\n\t\telement.setAttribute(\"rx\", ry)\n\t}\n}\n\nfunction convertPaperPathItemToNodes({\n\titem,\n\tnodes = [],\n\tparent = null,\n\tparentAbsolutePosition = Point(0, 0),\n\tfillOverrides,\n}: {\n\titem: PaperType.PathItem\n\tnodes?: DrawableNode[]\n\tparent?: MaybeDrawableNode\n\tparentAbsolutePosition?: Point\n\tfillOverrides?: Partial<WithFill>\n}): DrawableNode[] {\n\tconst withPaths = convertPaperPathItemToWithPaths({ item, parentAbsolutePosition })\n\tconst pathAttributes = convertPaperPathItemAttributes(item)\n\tconst parentid = parent ? parent.id : NullID\n\n\tconst isSingular = withPaths.length === 1\n\tif (isSingular) {\n\t\tconst singlePath = withPaths[0]\n\t\tassert(singlePath, \"Path must be defined\")\n\t\tconst [{ pathSegments, pathClosed }, frame] = normalizeWithPath(singlePath)\n\n\t\t// Ignore empty paths.\n\t\tif (pathSegments.length) {\n\t\t\tconst node = new PathNode({\n\t\t\t\tparentid,\n\t\t\t\tpathSegments,\n\t\t\t\tpathClosed,\n\t\t\t\t...pathAttributes,\n\t\t\t\t...fillOverrides,\n\t\t\t\t...frame,\n\t\t\t})\n\n\t\t\tnodes.push(node)\n\t\t}\n\t} else if (withPaths.length) {\n\t\tconst bounds = convertPaperItemBounds(item)\n\t\t// Paper's bounds coordinates are absolute, but we need x/y to be\n\t\t// relative to our parent.\n\t\tconst booleanContainerX = bounds.x - parentAbsolutePosition.x\n\t\tconst booleanContainerY = bounds.y - parentAbsolutePosition.y\n\n\t\tconst booleanId = randomID()\n\t\tconst childNodes: DrawableNode[] = []\n\n\t\twithPaths.forEach(withPath => {\n\t\t\tconst [{ pathSegments, pathClosed }, frame] = normalizeWithPath(withPath)\n\t\t\tif (!pathSegments.length) return\n\n\t\t\tconst childNode = new PathNode({\n\t\t\t\tparentid: booleanId,\n\t\t\t\tpathSegments,\n\t\t\t\tpathClosed,\n\t\t\t\t...fillOverrides,\n\t\t\t\t// frame.x/y coordinates are relative to \"parent\", but since we're\n\t\t\t\t// inserting a BooleanShapeNode \"container\" in between, we need to\n\t\t\t\t// offset by that container's x/y.\n\t\t\t\tx: frame.x - booleanContainerX,\n\t\t\t\ty: frame.y - booleanContainerY,\n\t\t\t\twidth: frame.width,\n\t\t\t\theight: frame.height,\n\t\t\t})\n\n\t\t\tchildNodes.push(childNode)\n\t\t})\n\n\t\tif (childNodes.length) {\n\t\t\tconst pathBoolean = item.fillRule === \"evenodd\" ? PathBooleanType.Exclude : PathBooleanType.Join\n\t\t\tconst node = new BooleanShapeNode({\n\t\t\t\tid: booleanId,\n\t\t\t\tparentid,\n\t\t\t\tpathBoolean,\n\t\t\t\t...pathAttributes,\n\t\t\t\t...fillOverrides,\n\t\t\t\tx: booleanContainerX,\n\t\t\t\ty: booleanContainerY,\n\t\t\t\twidth: bounds.width,\n\t\t\t\theight: bounds.height,\n\t\t\t})\n\t\t\tnodes.push(node, ...childNodes)\n\t\t}\n\t}\n\n\treturn nodes\n}\n\nfunction convertPaperGroupToNodes({\n\tgroup,\n\ttree,\n\tnodes = [],\n\tparent = null,\n\tparentAbsolutePosition = Point(0, 0),\n\tfillOverrides,\n}: {\n\tgroup: PaperType.Group\n\ttree: CanvasTree\n\tnodes?: DrawableNode[]\n\tparent?: MaybeDrawableNode\n\tparentAbsolutePosition?: Point\n\tfillOverrides?: Partial<WithFill>\n}): DrawableNode[] {\n\tconst bounds = convertPaperItemBounds(group)\n\tconst parentid = parent ? parent.id : NullID\n\n\tlet node: DrawableNode\n\tlet nodeAbsolutePosition: Point\n\n\tif (parentid) {\n\t\tnode = new ShapeGroupNode({\n\t\t\tparentid,\n\t\t\t// Paper's bounds coordinates are absolute, but we need x/y to be\n\t\t\t// relative to our parent.\n\t\t\tx: bounds.x - parentAbsolutePosition.x,\n\t\t\ty: bounds.y - parentAbsolutePosition.y,\n\t\t\twidth: bounds.width,\n\t\t\theight: bounds.height,\n\t\t})\n\t\tnodeAbsolutePosition = Point(bounds.x, bounds.y)\n\t} else {\n\t\tnode = new ShapeContainerNode({\n\t\t\tparentid,\n\t\t\tleft: 0,\n\t\t\ttop: 0,\n\t\t\twidth: bounds.x + bounds.width,\n\t\t\theight: bounds.y + bounds.height,\n\t\t\tfillEnabled: false,\n\t\t})\n\t\tnodeAbsolutePosition = Point(0, 0)\n\t}\n\n\tnodes.push(node)\n\n\tgroup.children.forEach(groupChild => {\n\t\tconvertPaperItemToNodes({\n\t\t\titem: groupChild,\n\t\t\tnodes,\n\t\t\tparent: node,\n\t\t\tparentAbsolutePosition: nodeAbsolutePosition,\n\t\t\ttree,\n\t\t\tfillOverrides,\n\t\t})\n\t})\n\n\treturn nodes\n}\n\nfunction convertPaperItemBounds(item: PaperType.Item): WithPosition & WithSize {\n\tconst { x, y, width, height } = item.bounds\n\treturn {\n\t\tx,\n\t\ty,\n\t\twidth,\n\t\theight,\n\t}\n}\n\nexport const ImportSVGTesting = {\n\tpreProcessSVGForPaper,\n}\n", "import type { MenuOptionIcon } from \"@framerjs/framer-services\"\nimport type { AppAction, ComponentQuickActions } from \"app/AppActions.ts\"\nimport type { ActiveModal } from \"document/stores/ModalStore.ts\"\nimport type { VekterPluginManifest } from \"plugins/plugins.ts\"\nimport type React from \"react\"\nimport type { FunctionComponent } from \"react\"\nimport { isObject, isString } from \"utils/typeChecks.ts\"\nimport type { ProjectComponent } from \"./utils/useComponentsActions.tsx\"\nimport type { FindNodesOptions } from \"./utils/useFindNodesQuickActions.tsx\"\n\nexport type QuickActionsItemId = string\n\n/** The identifier is a combination of the type and id to prevent id collisions */\nexport type QuickActionsItemIdentifier = string\nconst identifierKey = \"identifier\"\n\nexport enum QuickActionsType {\n\tAssetStyles = \"AssetStyles\",\n\tCanvasScope = \"CanvasScope\",\n\tCodeFile = \"CodeFile\",\n\tCodeImport = \"CodeImport\",\n\tCollection = \"Collection\",\n\tCollectionPageItem = \"CollectionPageItem\",\n\tComponent = \"Component\",\n\tContextMenuItem = \"ContextMenuItem\",\n\tCreateCollection = \"CreateCollection\",\n\tCreateCollectionFolder = \"CreateCollectionFolder\",\n\tFindNodes = \"FindNodes\",\n\tGoToCodeCrashSourceNode = \"GoToCodeCrashSourceNode\",\n\tHandshake = \"Handshake\",\n\tLayoutTemplate = \"LayoutTemplate\",\n\tLocaleScopeFilter = \"LocaleScopeFilter\",\n\tLocaleStatusFilter = \"LocaleStatusFilter\",\n\tMainMenuItem = \"MainMenuItem\",\n\tOpenDevelopmentPlugin = \"OpenDevelopmentPlugin\",\n\tOpenExternalUrl = \"OpenExternalUrl\",\n\tOpenModal = \"OpenModal\",\n\tPlugin = \"Plugin\",\n\tSelectCategory = \"SelectCategory\",\n\tSmartComponent = \"SmartComponent\",\n\tTeamLibrary = \"TeamLibrary\",\n\tVersionHistory = \"VersionHistory\",\n\tWorkspacePlugin = \"WorkspacePlugin\",\n}\n\nexport enum QuickActionsGroupSpecificType {\n\tAnalytics = \"Analytics\",\n\tCanvasCreateActions = \"CanvasCreateActions\",\n\tCode = \"Code\",\n\tContextSubMenu = \"ContextSubMenu\",\n\tExperiments = \"Experiments\",\n\tHelp = \"Help\",\n\tMarketplacePlugins = \"MarketplacePlugins\",\n\tNavigate = \"Navigate\",\n\tPluginMarketplace = \"PluginMarketplace\",\n\tPluginVisibleAtStart = \"PluginVisibleAtStart\",\n\tPreferences = \"Preferences\",\n\tPreview = \"Preview\",\n\tProject = \"Project\",\n\tSiteSettings = \"SiteSettings\",\n}\n\nexport enum QuickActionsTintType {\n\tComponentPurple = \"ComponentPurple\",\n\tAssetStyleIcon = \"AssetStyleIcon\",\n}\n\nexport enum QuickActionsCategoryType {\n\tAssetStyles = \"AssetStylesCategory\",\n\tCodeImport = \"CodeImportCategory\",\n\tCollectionPageItem = \"CollectionPageItemCategory\",\n\tComponents = \"ComponentsCategory\",\n\tDefault = \"DefaultCategory\",\n\tFindNodes = \"FindNodesCategory\",\n\tLocaleScopeFilter = \"LocaleScopeFilterCategory\",\n\tLocaleStatusFilter = \"LocaleStatusFilterCategory\",\n\tManagedCollectionPlugins = \"ManagedCollectionPluginsCategory\",\n\tPlugins = \"PluginsCategory\",\n\tTeamLibrary = \"TeamLibraryCategory\",\n\tWorkspacePlugins = \"WorkspacePluginsCategory\",\n}\n\nexport type QuickActionsCategoryTypeWithoutOptions = Exclude<\n\tQuickActionsCategoryType,\n\tQuickActionsCategoryType.AssetStyles | QuickActionsCategoryType.FindNodes | QuickActionsCategoryType.Components\n>\n\nexport type QuickActionsCategory =\n\t| { type: QuickActionsCategoryTypeWithoutOptions }\n\t| { type: QuickActionsCategoryType.AssetStyles; activeItemId: string }\n\t| { type: QuickActionsCategoryType.Components; activeComponent: ProjectComponent }\n\t| { type: QuickActionsCategoryType.FindNodes; options: FindNodesOptions }\n\nexport type QuickActionsGroupType = QuickActionsType | QuickActionsGroupSpecificType | QuickActionsCategoryType\n\ninterface QuickActionsExternalIcon {\n\ticonURL: string\n}\n\nexport function isQuickActionsExternalURLIcon(icon: QuickActionsIconType): icon is QuickActionsExternalIcon {\n\tconst quickActionsIconKey: keyof QuickActionsExternalIcon = \"iconURL\"\n\treturn isObject(icon) && quickActionsIconKey in icon\n}\n\nexport function isQuickActionsItemWithExternalIcon(item: QuickActionsItem) {\n\tif (!isObject(item.icon)) return false\n\tif (item.id === QuickActionsCategoryType.WorkspacePlugins) return true\n\n\treturn isQuickActionsExternalURLIcon(item.icon)\n}\n\nexport type QuickActionsIconType =\n\t| keyof typeof import(\"./utils/icons.tsx\")\n\t| NonNullable<React.ReactNode>\n\t| FunctionComponent\n\t| QuickActionsExternalIcon\n\t| MenuOptionIcon\n\ninterface QuickActionsItemBase {\n\tkind: \"item\"\n\ttype: QuickActionsType\n\tid: QuickActionsItemId\n\tname: string | string[]\n\tshortcut?: string[]\n\taliases?: readonly Lowercase<string>[]\n\tchecked?: boolean\n\ticon?: QuickActionsIconType\n\twithInnerShadow?: boolean\n\ttint?: QuickActionsTintType\n\tkey?: string\n\tappAction?: AppAction\n\tsearchable?: boolean\n\n\temptyStateForCategories?: ReadonlySet<QuickActionsCategoryType>\n\temptyStateOnly?: boolean\n\n\t[identifierKey]?: QuickActionsItemIdentifier\n}\n\ninterface QuickActionSelectCategoryItem extends QuickActionsItemBase {\n\ttype: QuickActionsType.SelectCategory\n\tcategory: QuickActionsCategory\n}\n\ninterface QuickActionItemWithAllAppAction extends QuickActionsItemBase {\n\ttype: QuickActionsType.MainMenuItem | QuickActionsType.AssetStyles\n\tappAction: AppAction\n}\n\ninterface QuickActionItemComponent extends QuickActionsItemBase {\n\ttype: QuickActionsType.Component\n\tappAction: ComponentQuickActions\n}\n\ninterface QuickActionItemOpenExternalUrl extends QuickActionsItemBase {\n\ttype: QuickActionsType.OpenExternalUrl\n\turl: string\n\tshowOpenActionText?: boolean\n}\n\ninterface QuickActionItemOpenModal extends QuickActionsItemBase {\n\ttype: QuickActionsType.OpenModal\n\tmodal: ActiveModal\n}\n\ninterface QuickActionItemOpenPlugin extends QuickActionsItemBase {\n\ttype: QuickActionsType.Plugin\n\tpluginManifest: VekterPluginManifest\n}\n\ntype CustomQuickActionItem =\n\t| QuickActionSelectCategoryItem\n\t| QuickActionItemWithAllAppAction\n\t| QuickActionItemComponent\n\t| QuickActionItemOpenExternalUrl\n\t| QuickActionItemOpenModal\n\t| QuickActionItemOpenPlugin\n\nexport type CustomQuickActionItemType = CustomQuickActionItem[\"type\"]\n\ninterface QuickActionRemainingItem extends QuickActionsItemBase {\n\ttype: Exclude<QuickActionsType, CustomQuickActionItemType>\n}\n\nexport type QuickActionsItem = QuickActionRemainingItem | CustomQuickActionItem\n\nexport interface QuickActionsGroup {\n\tkind: \"group\"\n\ttype: QuickActionsGroupType\n\t/** Can use the key to uniquely identify this group in a list of groups. */\n\tkey?: string\n\t/** If no key was provided, the list will use the title as the key for this group. */\n\ttitle: string | string[]\n\titems: readonly QuickActionsItem[]\n\taliases?: readonly Lowercase<string>[]\n}\n\nconst emptyStateCategories = {\n\t[QuickActionsCategoryType.Default]: true,\n\t[QuickActionsCategoryType.Plugins]: true,\n\t[QuickActionsCategoryType.ManagedCollectionPlugins]: true,\n\t[QuickActionsCategoryType.WorkspacePlugins]: true,\n} as const satisfies Partial<Record<QuickActionsCategoryType, true>>\n\ntype QuickActionsEmptyStateCategory = keyof typeof emptyStateCategories\n\nexport function isEmptyStateCategory(category: unknown): category is QuickActionsEmptyStateCategory {\n\tif (!isString(category)) return false\n\treturn Object.hasOwn(emptyStateCategories, category)\n}\n\nconst backableCategories = {\n\t[QuickActionsCategoryType.FindNodes]: true,\n\t[QuickActionsCategoryType.Plugins]: true,\n\t[QuickActionsCategoryType.ManagedCollectionPlugins]: true,\n\t[QuickActionsCategoryType.WorkspacePlugins]: true,\n} as const satisfies Partial<Record<QuickActionsCategoryType, true>>\n\ntype QuickActionsBackableCategory = keyof typeof backableCategories\n\nexport function canGoBackFromCategory(category: QuickActionsCategoryType): category is QuickActionsBackableCategory {\n\treturn Object.hasOwn(backableCategories, category)\n}\n\ninterface QuickActionsEmptyStateItem {\n\tkind: \"emptyState\"\n\tcategoryType: QuickActionsEmptyStateCategory\n}\n\nexport type QuickActionsItemSelectable = QuickActionsItem & {\n\t[identifierKey]: QuickActionsItemIdentifier\n}\n\nexport type QuickActionsVirtualListItem = QuickActionsGroup | QuickActionsItemSelectable | QuickActionsEmptyStateItem\n\nexport enum FindNodesType {\n\tStylePreset = \"UsingStylePreset\",\n\tComponentPreset = \"UsingComponentPreset\",\n\tColorStyleToken = \"UsingColorStyleToken\",\n\tCodeComponent = \"UsingCodeComponent\",\n\tCodeFile = \"UsingCodeFile\",\n\tVectorSet = \"UsingVectorSet\",\n}\n\nexport function isSelectableQuickActionItem(\n\titem: QuickActionsVirtualListItem | undefined,\n): item is QuickActionsItemSelectable {\n\treturn item?.kind === \"item\"\n}\n", "import type { CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\n\n/**\n * Returns the amount of A/B tests that are currently linked to pages\n */\nexport const countPagesWithVariants = (tree: CanvasTree): number => {\n\tconst webPageNodeIds = tree.root.children.reduce((set, node) => {\n\t\tif (!isWebPageNode(node)) {\n\t\t\treturn set\n\t\t}\n\t\tif (node.abTestingParentId && tree.has(node.abTestingParentId)) {\n\t\t\tset.add(node.abTestingParentId)\n\t\t}\n\t\treturn set\n\t}, new Set<NodeID>())\n\treturn webPageNodeIds.size\n}\n", "import { AddOnLicenseType, ProjectLicenseType, getAddOnLicenseTypeName, openNewTab } from \"@framerjs/app-shared\"\nimport { UpsellType } from \"@framerjs/events\"\nimport type { ModalOpenSource } from \"@framerjs/framer-events\"\nimport { assert } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { UpsellFeature } from \"document/components/chrome/siteSettings/Plans/Stripe/utils/upsell.ts\"\nimport { MAX_AB_TESTS_ON_SELF_SERVE } from \"document/components/chrome/siteSettings/Usage/constants.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { enterpriseUpsellURL } from \"utils/staticURLs.ts\"\nimport { countPagesWithVariants } from \"./countPagesWithVariants.ts\"\n\n/**\n * Shows the A/B test upsell modal if the user needs to upgrade.\n * Returns true if an upsell modal was shown, false otherwise.\n */\nexport function showAbTestUpsell(\n\tengine: VekterEngine,\n\tsource: ModalOpenSource,\n\t{ isAddingTest }: { isAddingTest: boolean },\n): boolean {\n\tassert(engine.stores.projectStore.project, \"Project should be defined\")\n\tconst { settings, usage, license } = engine.stores.projectStore.project\n\n\tconst abTestsCount = countPagesWithVariants(engine.tree) + (isAddingTest ? 1 : 0)\n\tconst abTests =\n\t\t// Treat allowed AB tests as 0 when Advanced Analytics is off (matches add-on upsell).\n\t\t// TODO: Remove once backend returns add-on-aware AB test limits.\n\t\tsettings.featureFlags.canUseAdvancedAnalytics === \"on\" ? (settings.resourceLimits.abTests ?? Infinity) : 0\n\n\tconst maxAbTests = settings.resourceLimits.maxAbTests ?? Infinity\n\n\t// Within limits, no upsell needed\n\tif (abTestsCount <= abTests) {\n\t\treturn false\n\t}\n\n\t// Enterprise users that are over their limit should contact support\n\tconst isEnterprise = license.type === ProjectLicenseType.EnterpriseSite\n\tif (isEnterprise) {\n\t\tengine.stores.modalStore.set({\n\t\t\ttype: ModalType.Confirmation,\n\t\t\ttitle: \"Increase Limits\",\n\t\t\tdescription:\n\t\t\t\t\"You\u2019ve reached the limit for A/B tests. Please contact your account manager to increase your limits.\",\n\t\t\tsource,\n\t\t\tconfirmLabel: Dictionary.ContactUs,\n\t\t\tcancelLabel: Dictionary.MaybeLater,\n\t\t\tonConfirm: () => openNewTab(enterpriseUpsellURL),\n\t\t})\n\t\treturn true\n\t}\n\n\tconst addOnName = getAddOnLicenseTypeName(AddOnLicenseType.AdvancedAnalytics)\n\n\t// Can buy an add-on to get more A/B tests\n\tif (abTestsCount <= maxAbTests) {\n\t\tconst eventsUsage = Math.max(\n\t\t\tusage.advancedAnalytics?.currentMonth ?? 0,\n\t\t\tusage.advancedAnalytics?.previousMonth ?? 0,\n\t\t\t1,\n\t\t)\n\t\tengine.stores.modalStore.set({\n\t\t\ttype: ModalType.ConfirmAcquireAddOn,\n\t\t\ttitle: \"A/B Testing\",\n\t\t\tdescription: `Buy the ${addOnName} ${Dictionary.AddOn} to run A/B tests, add triggers and funnels, and boost your overall conversion rates.`,\n\t\t\taddonInfo: {\n\t\t\t\taddonLicenseType: AddOnLicenseType.AdvancedAnalytics,\n\t\t\t\tquantity: eventsUsage,\n\t\t\t},\n\t\t\tsource,\n\t\t})\n\t\treturn true\n\t}\n\n\t// Beyond what self-serve add-ons can cover, upsell to enterprise\n\tif (abTestsCount > MAX_AB_TESTS_ON_SELF_SERVE) {\n\t\tengine.stores.modalStore.set({\n\t\t\ttype: ModalType.UpsellEnterprise,\n\t\t\tsource,\n\t\t\tdescription:\n\t\t\t\t\"Sign up for an Enterprise plan to add even more A/B Tests, and get access to other powerful features.\",\n\t\t\tupsell: UpsellType.advancedAnalyticsEnterpriseUpsell,\n\t\t\tupsellFeatures: [\n\t\t\t\t\"Custom Limits\",\n\t\t\t\t\"Custom Hosting\",\n\t\t\t\t\"Custom Proxy Support\",\n\t\t\t\t\"Enterprise Security\",\n\t\t\t\t\"Dedicated Support\",\n\t\t\t],\n\t\t})\n\t\treturn true\n\t}\n\n\t// Default: upsell to a plan that supports A/B tests\n\tengine.stores.modalStore.set({\n\t\ttype: ModalType.UpsellFeature,\n\t\tupsellFeature: UpsellFeature.abTests,\n\t\ttitle: \"A/B Testing\",\n\t\tdescription: `Upgrade and buy the ${addOnName} ${Dictionary.AddOn} to run A/B tests, add triggers and funnels, and boost conversion rates.`,\n\t\tsource,\n\t})\n\treturn true\n}\n", "import { AddOnLicenseType, ProjectLicenseType, getAddOnLicenseTypeName, openNewTab } from \"@framerjs/app-shared\"\nimport { UpsellType } from \"@framerjs/events\"\nimport type { ModalOpenSource } from \"@framerjs/framer-events\"\nimport { assertNever } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { UpsellFeature } from \"document/components/chrome/siteSettings/Plans/Stripe/utils/upsell.ts\"\nimport { MAX_TRACKING_EVENTS_ON_SELF_SERVE } from \"document/components/chrome/siteSettings/Usage/constants.ts\"\nimport type { ProjectStore } from \"document/stores/ProjectStore.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { enterpriseUpsellURL } from \"utils/staticURLs.ts\"\n\nexport enum AnalyticsEventsUpsellAction {\n\tContact,\n\tAddOn,\n\tUpgradeToEnterprise,\n\tUpgrade,\n}\n\nexport interface AnalyticsEventsUpsellResult {\n\taction: AnalyticsEventsUpsellAction\n\teventsUsage: number\n\ttrackingEventsLimit: number\n}\n\n/**\n * Determines whether an analytics events upsell is needed and which action to take.\n * Returns null if no upsell is needed (usage is within limits).\n */\nexport function getAnalyticsEventsUpsell(projectStore: ProjectStore): AnalyticsEventsUpsellResult | null {\n\tif (!projectStore.project) return null\n\tconst { settings, usage, license } = projectStore.project\n\n\tconst trackingEventsLimit = settings.resourceLimits.trackingEventsLimit ?? Infinity\n\tconst maxTrackingEventsLimit = settings.resourceLimits.maxTrackingEventsLimit ?? Infinity\n\n\tconst eventsUsage = Math.max(usage.advancedAnalytics?.currentMonth ?? 0, usage.advancedAnalytics?.previousMonth ?? 0)\n\n\t// Within limits, no upsell needed\n\tif (eventsUsage <= trackingEventsLimit) {\n\t\treturn null\n\t}\n\n\t// Enterprise users that are over their events limit should contact support\n\tconst isEnterprise = license.type === ProjectLicenseType.EnterpriseSite\n\tif (isEnterprise) {\n\t\treturn { action: AnalyticsEventsUpsellAction.Contact, eventsUsage, trackingEventsLimit }\n\t}\n\n\t// Can buy an add-on to get more tracking events\n\tif (eventsUsage <= maxTrackingEventsLimit) {\n\t\treturn { action: AnalyticsEventsUpsellAction.AddOn, eventsUsage, trackingEventsLimit }\n\t}\n\n\t// Beyond what self-serve add-ons can cover, upsell to enterprise\n\tif (eventsUsage > MAX_TRACKING_EVENTS_ON_SELF_SERVE) {\n\t\treturn { action: AnalyticsEventsUpsellAction.UpgradeToEnterprise, eventsUsage, trackingEventsLimit }\n\t}\n\n\t// Default: upsell to a plan that supports more analytics events\n\treturn { action: AnalyticsEventsUpsellAction.Upgrade, eventsUsage, trackingEventsLimit }\n}\n\n/**\n * Shows the analytics events upsell modal based on the given upsell result.\n */\nfunction handleAnalyticsEventsUpsell(\n\tengine: VekterEngine,\n\tsource: ModalOpenSource,\n\tresult: AnalyticsEventsUpsellResult,\n): void {\n\tconst addOnName = getAddOnLicenseTypeName(AddOnLicenseType.AdvancedAnalytics)\n\n\tswitch (result.action) {\n\t\tcase AnalyticsEventsUpsellAction.Contact:\n\t\t\tengine.stores.modalStore.set({\n\t\t\t\ttype: ModalType.Confirmation,\n\t\t\t\ttitle: \"Increase Limits\",\n\t\t\t\tdescription: `You\u2019ve reached the limit for analytics events. Please contact your account manager to increase your limits.`,\n\t\t\t\tsource,\n\t\t\t\tconfirmLabel: Dictionary.ContactUs,\n\t\t\t\tcancelLabel: Dictionary.MaybeLater,\n\t\t\t\tonConfirm: () => openNewTab(enterpriseUpsellURL),\n\t\t\t})\n\t\t\treturn\n\n\t\tcase AnalyticsEventsUpsellAction.AddOn:\n\t\t\tengine.stores.modalStore.set({\n\t\t\t\ttype: ModalType.AcquireAddonModal,\n\t\t\t\tsource,\n\t\t\t\taddonInfo: {\n\t\t\t\t\taddonLicenseType: AddOnLicenseType.AdvancedAnalytics,\n\t\t\t\t\tquantity: Math.max(result.eventsUsage, 1),\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn\n\n\t\tcase AnalyticsEventsUpsellAction.UpgradeToEnterprise:\n\t\t\tengine.stores.modalStore.set({\n\t\t\t\ttype: ModalType.UpsellEnterprise,\n\t\t\t\tsource,\n\t\t\t\tdescription:\n\t\t\t\t\t\"Sign up for an Enterprise plan to increase your analytics events limit and get access to other powerful features.\",\n\t\t\t\tupsell: UpsellType.advancedAnalyticsEnterpriseUpsell,\n\t\t\t\tupsellFeatures: [\n\t\t\t\t\t\"Custom Limits\",\n\t\t\t\t\t\"Custom Hosting\",\n\t\t\t\t\t\"Custom Proxy Support\",\n\t\t\t\t\t\"Enterprise Security\",\n\t\t\t\t\t\"Dedicated Support\",\n\t\t\t\t],\n\t\t\t})\n\t\t\treturn\n\n\t\tcase AnalyticsEventsUpsellAction.Upgrade:\n\t\t\tengine.stores.modalStore.set({\n\t\t\t\ttype: ModalType.UpsellFeature,\n\t\t\t\tupsellFeature: UpsellFeature.trackingEventsLimit,\n\t\t\t\ttitle: addOnName,\n\t\t\t\tdescription:\n\t\t\t\t\t\"You\u2019ve exceeded your analytics events limit. Upgrade your plan to continue using funnels and A/B testing.\",\n\t\t\t\tsource,\n\t\t\t})\n\t\t\treturn\n\n\t\tdefault:\n\t\t\tassertNever(result.action)\n\t}\n}\n\n/**\n * Shows the analytics events usage upsell modal if the user is over their tracking events limit.\n * Returns true if an upsell modal was shown, false otherwise.\n */\nexport function showAnalyticsEventsUpsell(engine: VekterEngine, source: ModalOpenSource): boolean {\n\tconst result = getAnalyticsEventsUpsell(engine.stores.projectStore)\n\tif (result === null) return false\n\thandleAnalyticsEventsUpsell(engine, source, result)\n\treturn true\n}\n", "import { emptyArray } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { CustomCodeScopeNode, type NodeID } from \"document/models/CanvasTree/index.ts\"\n\n/**\n * Duplicates custom code references from a source page to a target page.\n *\n * For each custom code node that references the source page, the target page ID\n * is added to its pageIds. This is used when creating A/B testing variants so\n * that the variant inherits the same custom code snippets as the original page.\n */\nexport function duplicateCustomCodeForPage(engine: VekterEngine, sourcePageId: NodeID, targetPageId: NodeID) {\n\tconst scope = CustomCodeScopeNode.get(engine.tree)\n\n\treturn engine.loadScopesThenProcess([scope], ([loadedScope]) => {\n\t\tif (!loadedScope) return\n\n\t\tfor (const node of loadedScope.children) {\n\t\t\tconst currentNode = engine.tree.current(node)\n\t\t\tif (!currentNode) continue\n\n\t\t\tconst pageIds = currentNode.pageIds ?? emptyArray()\n\t\t\tif (!pageIds.includes(sourcePageId) || pageIds.includes(targetPageId)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcurrentNode.set({ pageIds: [...pageIds, targetPageId] })\n\t\t}\n\t})\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, delay, getLogger } from \"@framerjs/shared\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\n\nconst log = getLogger(\"waitForComponentLoaderToCatchUp\")\n\nconst DEFAULT_TIMEOUT = 20_000\nconst POLL_DELAY = 500\n\nconst enum Status {\n\tTimeout = \"timeout\",\n}\n\nexport class WaitForLoadingComponentsError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly missing: ModuleExportIdentifierString[],\n\t\treadonly error: ModuleExportIdentifierString[],\n\t\treadonly wasTimeout = false,\n\t) {\n\t\tsuper(message)\n\t}\n}\n\nexport function isWaitForLoadingComponentsError(error: Error): error is WaitForLoadingComponentsError {\n\treturn error instanceof WaitForLoadingComponentsError\n}\n\n/**\n * Waits until module changes that reached `ModulesStore` have also reached the component loader.\n *\n * Module writes update `ModulesStore` first, then the sandbox evaluates those modules and posts entity\n * updates back to the editor's component loader. Callers that read component definitions immediately\n * after creating or updating a module need this handoff to finish first. We wait on revisions instead\n * of exported entities so modules with no component exports, or modules that evaluate to an error, can\n * still be treated as processed.\n */\nexport async function waitForComponentLoaderToCatchUp(\n\tcomponentLoader: ComponentLoader,\n\tmodulesStore: ModulesStore,\n\tmaxTimeout = DEFAULT_TIMEOUT,\n) {\n\tconst start = performance.now()\n\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined\n\tconst revision = await race<number | Status>(\n\t\t() =>\n\t\t\tnew Promise<Status>(resolve => {\n\t\t\t\ttimeoutId = setTimeout(resolve, maxTimeout, Status.Timeout)\n\t\t\t}),\n\t\tasync () => {\n\t\t\t// Wait for the modules store to be idle then grab its revision. Notice this can take\n\t\t\t// very long if somehow a lot of module work was queued.\n\t\t\tawait modulesStore.whenIdle()\n\t\t\tconst targetRevision = modulesStore.revision\n\t\t\tassert(targetRevision >= 0, \"moduleStore.revision cannot be negative\")\n\n\t\t\tawait modulesStore.loadAllLocalModules()\n\t\t\treturn targetRevision\n\t\t},\n\t)\n\tclearTimeout(timeoutId)\n\n\tif (revision === Status.Timeout) {\n\t\tthrow new WaitForLoadingComponentsError(\"ensureComponentsInLoader: Modules store not ready in time.\", [], [], true)\n\t}\n\n\t// Then wait for the component loader to have loaded at least that revision. This should always\n\t// succeed. But could be too slow. And just incase we do limit the amount of iterations.\n\tfor (let i = 0; i < 1000; i++) {\n\t\tconst componentLoaderRevision = componentLoader.modulesRevision\n\t\tif (revision <= componentLoaderRevision) break\n\t\tif (performance.now() - start > maxTimeout) {\n\t\t\tlog.debug(\"component loader not updated in time: want:\", revision, \"got:\", componentLoaderRevision)\n\t\t\tthrow new WaitForLoadingComponentsError(\n\t\t\t\t\"ensureComponentsInLoader: Component loader not updated in time.\",\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\ttrue,\n\t\t\t)\n\t\t}\n\t\tawait delay(POLL_DELAY)\n\t}\n}\n\n/** Small wrapper around Promise.race to reduce syntax noise and keep typescript strict. */\nasync function race<T>(...args: (() => Promise<T>)[]): Promise<T> {\n\treturn Promise.race(args.map(async fn => fn()))\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { getLogger } from \"@framerjs/shared\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport {\n\tWaitForLoadingComponentsError,\n\twaitForComponentLoaderToCatchUp,\n} from \"modules/waitForComponentLoaderToCatchUp.ts\"\nimport { isNull } from \"utils/typeChecks.ts\"\n\nconst log = getLogger(\"ensureComponentsInLoader\")\n\nconst MINIMUM_COMPONENT_LOADER_WAIT_TIME = 30 * 1000\n\n/**\n * When we encounter a module when generating code, we wait for the modules\n * store to confirm that the module has been evaluated in the sandbox. This is\n * important since external modules are lazy loaded. However, just waiting for\n * confirmation that it has been evaluated does not guarantee that the component\n * definition is available in the editor's component loader. It could take up to\n * ~50ms for the data to be transmitted to the client over post message. This\n * helper adds the ability to wait for that information to be available before\n * proceeding with code generation.\n *\n * Ideally this would be built into the modules store functionality.\n */\nexport async function waitForLoadingComponentsWithTimeout(\n\tcomponentLoader: ComponentLoader,\n\tcodeComponentIdentifiers: ModuleExportIdentifierString[],\n\tmodulesStore: ModulesStore,\n\tmaxTimeout?: number,\n): Promise<void> {\n\t// We wait a decent amount plus a little extra for each new component.\n\tconst newModuleCount = getMissingComponents(codeComponentIdentifiers, componentLoader).length\n\t// Note that this return means that the modules are loaded, but might not be up-to-date.\n\tif (newModuleCount === 0) return\n\n\tconst maxWaitTime = maxTimeout ?? MINIMUM_COMPONENT_LOADER_WAIT_TIME + newModuleCount * 2000\n\tlog.debug(\"modules:\", codeComponentIdentifiers.length, \", new:\", newModuleCount, \", timeout:\", maxWaitTime)\n\n\tawait waitForComponentLoaderToCatchUp(componentLoader, modulesStore, maxWaitTime)\n\n\t// If there are no missing components then we are good.\n\tconst missing = getMissingComponents(codeComponentIdentifiers, componentLoader)\n\tif (missing.length === 0) return\n\n\t// Otherwise we want to log the components that are missing and those that are in error. And\n\t// throw an exception for our callers to handle.\n\tconst errors = componentsWithErrors(codeComponentIdentifiers, componentLoader)\n\tlog.debug(\"components loaded, but some are missing\", { missing, errors })\n\tthrow new WaitForLoadingComponentsError(\"ensureComponentsInLoader: Some modules are missing.\", missing, errors)\n}\n\nexport function getMissingComponents(\n\tidentifiers: ModuleExportIdentifierString[],\n\tcomponentLoader: ComponentLoader,\n): ModuleExportIdentifierString[] {\n\tconst missing = new Set<ModuleExportIdentifierString>()\n\tfor (const identifier of identifiers) {\n\t\tif (componentLoader.componentForIdentifier(identifier)) continue\n\t\tmissing.add(identifier)\n\t}\n\treturn Array.from(missing)\n}\n\nfunction componentsWithErrors(\n\tidentifiers: ModuleExportIdentifierString[],\n\tcomponentLoader: ComponentLoader,\n): ModuleExportIdentifierString[] {\n\tconst errors = new Set<ModuleExportIdentifierString>()\n\tfor (const identifier of identifiers) {\n\t\tif (isNull(componentLoader.errorForIdentifier(identifier))) continue\n\t\terrors.add(identifier)\n\t}\n\treturn Array.from(errors)\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ExternalModuleExportIdentifier, ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { parseModuleIdentifier } from \"@framerjs/shared\"\nimport { waitForLoadingComponentsWithTimeout } from \"code-generation/utils/waitForLoadingComponentsWithTimeout.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\n\nexport async function ensureModulesAreLoaded(\n\tmoduleIdentifiers: ModuleExportIdentifierString[],\n\tmodulesStore: ModulesStore,\n\tcomponentLoader: ComponentLoader,\n) {\n\tconst externalModuleExportIdentifiers: ExternalModuleExportIdentifier[] = []\n\tmoduleIdentifiers.forEach(identifier => {\n\t\tconst parsedId = parseModuleIdentifier(identifier)\n\t\tif (parsedId && parsedId.kind === \"externalModuleExport\") {\n\t\t\texternalModuleExportIdentifiers.push(parsedId)\n\t\t}\n\t})\n\n\tif (externalModuleExportIdentifiers.length) {\n\t\tawait modulesStore.preloadExternalModules(externalModuleExportIdentifiers)\n\t}\n\n\tawait waitForLoadingComponentsWithTimeout(componentLoader, moduleIdentifiers, modulesStore)\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { CanvasTree } from \"../../CanvasTree.ts\"\nimport { isVariableReference } from \"../../traits/VariableReference.ts\"\nimport { withBreakpointVariants } from \"../../traits/WithBreakpointVariants.ts\"\nimport { withSize } from \"../../traits/WithSize.ts\"\nimport type { IsMaster } from \"../../traits/WithTemplate.ts\"\nimport { isPrimaryVariant } from \"../../traits/WithVariant.ts\"\nimport type { CanvasNode } from \"../CanvasNode.ts\"\nimport type { RichTextNode } from \"../RichTextNode.ts\"\nimport { generateReplicaChildId } from \"../TemplateHelper.ts\"\nimport type { TextStylePresetNode } from \"../TextStylePresetNode.ts\"\nimport { isRichTextNode } from \"./nodeCheck.ts\"\n\n/**\n * Removes the provided text style preset and applies the properties from as\n * inline styles, including any breakpoint specific styles.\n *\n * @param tree\n * @param primaryNode - Primary node is used to find the webpage the rich text belongs to.\n * @param richTextNode - Text to apply inline styles to.\n * @param presetBreakpointNodes - Text style presets with `breakpointWidth`\n * attribute. These are technically replicas of the original preset.\n * @param presetNode - Original preset node that is used as a fallback if no\n * breakpoints are matched.\n */\nexport function detachTextStylePresetsFromBreakpoints(\n\ttree: CanvasTree,\n\tprimaryNode: CanvasNode & IsMaster,\n\trichTextNode: RichTextNode,\n\tpresetBreakpointNodes: TextStylePresetNode[],\n\tpresetNode: TextStylePresetNode,\n) {\n\t// For rich text nodes that have references to \"formatted text\" variables\n\t// (e.g CMS fields such as in a CMS detail page or repeater), don't detach\n\t// them and use the project default text styles.\n\tif (isVariableReference(richTextNode.htmlContent)) return\n\n\tconst scopeWithBreakpoints = tree.getScopeNodeFor(primaryNode)\n\tassert(scopeWithBreakpoints && withBreakpointVariants(scopeWithBreakpoints), \"Can't find scope with breakpoints\")\n\n\tconst breakpointNodes = scopeWithBreakpoints.getTopLevelVariants()\n\n\tconst breakpointNodesWithRichTextNodes = breakpointNodes.map(breakpointNode => {\n\t\tconst richTextNodeId = isPrimaryVariant(breakpointNode)\n\t\t\t? richTextNode.id\n\t\t\t: generateReplicaChildId(breakpointNode.id, richTextNode.id)\n\n\t\tconst richTextNodeInBreakpoint = tree.get(richTextNodeId)\n\t\tassert(\n\t\t\trichTextNodeInBreakpoint && isRichTextNode(richTextNodeInBreakpoint),\n\t\t\t\"Can't find rich text node in breakpoint\",\n\t\t)\n\n\t\treturn [breakpointNode, richTextNodeInBreakpoint] as const\n\t})\n\n\tfor (const [breakpointNode, richTextNodeInBreakpoint] of breakpointNodesWithRichTextNodes) {\n\t\tassert(withSize(breakpointNode), \"Can't read width attribute of node\")\n\n\t\t// Breakpoints are sorted from largest to smallest width.\n\t\tconst presetBreakpointToDetach =\n\t\t\tpresetBreakpointNodes.findLast(\n\t\t\t\tpresetBreakpoint => (presetBreakpoint.breakpointWidth ?? 0) > breakpointNode.width,\n\t\t\t) ?? presetNode\n\n\t\trichTextNodeInBreakpoint.detachTextStylePreset(presetBreakpointToDetach, true)\n\t}\n}\n", "import type CodeComponentNode from \"../nodes/CodeComponentNode.ts\"\n\n/**\n * List of CodeComponentNode keys that target variants of the instance, and may\n * need to be remapped when unlinking.\n */\nexport const codeComponentVariantPropKeys = [\n\t\"formButtonSuccessVariant\",\n\t\"formButtonPendingVariant\",\n\t\"formButtonErrorVariant\",\n\t\"formButtonIncompleteVariant\",\n\t\"whileOpenEffectVariant\",\n\t\"appearEffectVisibleVariantId\",\n\t\"appearEffectObscuredVariantId\",\n\t\"dataLoaderLoadingVariant\",\n\t\"dataLoaderDisabledVariant\",\n] satisfies (keyof CodeComponentNode)[]\n", "import { assertNever, unhandledError } from \"@framerjs/shared\"\nimport { isEmptyObject } from \"@framerjs/shared/src/isEmptyObject.ts\"\nimport { getRelatedReplicaNodes } from \"code-generation/utils/isOnlyVisibleInCurrentVariant.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { isBorderValues } from \"document/models/controlProps/BorderControlPropValue.ts\"\nimport type { BorderControlProp, ColorControlProp, ControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { parseCSSVariable } from \"library/render/utils/parseCSSVariable.ts\"\nimport { type CSSVariableName, isCSSVariableName } from \"prosemirror/variables.ts\"\nimport { isNull } from \"utils/typeChecks.ts\"\nimport type { CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport type CodeComponentNode from \"../../nodes/CodeComponentNode.ts\"\nimport type { NodeID } from \"../../nodes/NodeID.ts\"\nimport { PresetsListNode } from \"../../nodes/PresetsListNode.ts\"\nimport type { RichTextNode } from \"../../nodes/RichTextNode.ts\"\nimport type { SmartComponentNode } from \"../../nodes/SmartComponentNode.ts\"\nimport { type StylePresetNode, isStylePresetPrimaryNode } from \"../../nodes/utils/isStylePresetNode.ts\"\nimport {\n\tisBlockquoteStylePresetNode,\n\tisCodeComponentNode,\n\tisImageStylePresetNode,\n\tisInlineCodeStylePresetNode,\n\tisLinkStylePresetNode,\n\tisRichTextNode,\n\tisSmartComponentNode,\n\tisTextStylePresetNode,\n} from \"../../nodes/utils/nodeCheck.ts\"\nimport { isTokenCSSVariable, tokenIdFromCustomProperty } from \"../../utils/tokens.ts\"\nimport { withBorder } from \"../WithBorder.ts\"\nimport { withFill } from \"../WithFill.ts\"\nimport { withStroke } from \"../WithStroke.ts\"\nimport { stylePresetKeys } from \"../WithStylePresets.ts\"\nimport { isReplicaOrReplicaChild } from \"../WithTemplate.ts\"\nimport type { BorderVariableDefinition, ColorVariableDefinition, VariableDefinition } from \"../WithVariables.ts\"\n\n/**\n * Apply the token overrides to the smart component node and all its children. Used when unlinking a component.\n *\n * @param engine - The engine to apply the token overrides to.\n * @param instance - The instance of the smart component node which contains the overrides.\n * @param node - The smart component node to apply the token overrides to.\n */\nexport function applyTokenOverridesToUnlinkedSmartComponentNode(\n\tengine: VekterEngine,\n\tinstance: CodeComponentNode,\n\tnode: SmartComponentNode,\n) {\n\tconst tokenOverrides = instance.tokenOverrides\n\tif (!tokenOverrides || isEmptyObject(tokenOverrides)) return\n\n\tapplyTokenOverridesToSmartComponentNode(engine, node, tokenOverrides)\n\n\t// Finally remove token overrides from the instance\n\tinstance.set({ tokenOverrides: undefined })\n}\n\n/**\n * Apply the token overrides to the smart component node and all its children.\n *\n * @param engine - The engine to apply the token overrides to.\n * @param node - The smart component node to apply the token overrides to.\n * @param tokenOverrides - The token overrides to apply.\n */\nfunction applyTokenOverridesToSmartComponentNode(\n\tengine: VekterEngine,\n\tnode: SmartComponentNode,\n\ttokenOverrides: Record<CSSVariableName, string>,\n) {\n\t// For other nodes replace token usage with value from token overrides\n\tapplyTokenOverrides(engine, node.id, tokenOverrides)\n\n\tconst newVariables: VariableDefinition[] = []\n\n\t// Apply token overrides to the smart component variables initial value\n\tfor (const variable of node.variables) {\n\t\tif (!isControlTypeWithColor(variable)) {\n\t\t\tnewVariables.push(variable)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch (variable.type) {\n\t\t\tcase ControlType.Border:\n\t\t\t\tnewVariables.push(\n\t\t\t\t\tisBorderValues(variable.initialValue)\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...variable,\n\t\t\t\t\t\t\t\tinitialValue: {\n\t\t\t\t\t\t\t\t\t...variable.initialValue,\n\t\t\t\t\t\t\t\t\tborderColor: getTokenOverrideForValue(variable.initialValue.borderColor, tokenOverrides),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: variable,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase ControlType.Color:\n\t\t\t\tnewVariables.push({\n\t\t\t\t\t...variable,\n\t\t\t\t\tinitialValue: getTokenOverrideForValue(variable.initialValue, tokenOverrides),\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tassertNever(variable, \"Unsupported variable type.\")\n\t\t}\n\t}\n\n\tnode.set({ variables: newVariables })\n}\n\n/**\n * Apply the token overrides to the node and also to the replica nodes in other variants and its children.\n *\n * @param engine - The engine to apply the token overrides to.\n * @param nodeId- The id of the node to apply the token overrides to.\n * @param tokenOverrides - The token overrides to apply.\n *\n */\nexport function applyTokenOverrides(\n\tengine: VekterEngine,\n\tnodeId: NodeID,\n\ttokenOverrides: Record<CSSVariableName, string>,\n) {\n\tconst currentNode = engine.tree.get(nodeId)\n\tif (!currentNode) return\n\n\tfor (const { node: walkNode, skipChildren } of currentNode.walkWithSkipChildren()) {\n\t\t// We make sure we go over the replicas below when needed but this guarantees that if node is a scope node\n\t\t// we don't go over the replicas twice.\n\t\tif (isReplicaOrReplicaChild(walkNode)) {\n\t\t\tskipChildren()\n\t\t\tcontinue\n\t\t}\n\n\t\tapplyTokenOverridesToNode(engine, walkNode, tokenOverrides)\n\t\tapplyTokenOverridesToReplicaNodes(engine, walkNode, tokenOverrides)\n\n\t\tif (!isCodeComponentNode(walkNode) || walkNode.isVectorInstance) continue\n\n\t\tconst smartComponentId = walkNode.getLocalSmartComponentNodeId()\n\t\tif (!smartComponentId) {\n\t\t\t// External module so set the token overrides on the code component node\n\t\t\twalkNode.set({ tokenOverrides })\n\t\t\tcontinue\n\t\t}\n\n\t\tconst smartComponentNode = engine.tree.get(smartComponentId)\n\t\tif (!isSmartComponentNode(smartComponentNode)) continue\n\t\tif (!smartComponentNode.isLoaded()) continue\n\n\t\t// If the node is a code component node, apply the token overrides to the smart component node and all its children.\n\t\t// This will cause the overrides to be applied in all other instances of this Smart Component, so may create unintended changes in other webpages.\n\t\tapplyTokenOverridesToSmartComponentNode(engine, smartComponentNode, tokenOverrides)\n\n\t\t// Forcing a code generation update to ensure the token overrides are applied to the smart component node instances.\n\t\tvoid engine.stores.codeGenerationStore.updateComponent(smartComponentNode.id)\n\t}\n}\n\n/**\n * Apply the token overrides to the replica nodes in other variants.\n *\n * @param engine - The engine to apply the token overrides to.\n * @param node - The node to apply the token overrides to.\n * @param tokenOverrides - The token overrides to apply.\n */\nfunction applyTokenOverridesToReplicaNodes(\n\tengine: VekterEngine,\n\tnode: CanvasNode,\n\ttokenOverrides: Record<CSSVariableName, string>,\n) {\n\t// Apply the token overrides to the replica nodes in other variants\n\tconst replicaNodes = getRelatedReplicaNodes(engine.tree, node)\n\n\tfor (const replicaNode of replicaNodes) {\n\t\tconst { relatedNode, replicaRoot } = replicaNode\n\t\tconst overrides = replicaRoot.replicaInfo.overrides\n\n\t\tconst relatedNodeOverrides = overrides[node.id]\n\t\tif (!relatedNodeOverrides) continue\n\n\t\tapplyTokenOverridesToNode(engine, relatedNode, tokenOverrides)\n\t}\n}\n\n/**\n * Apply the token overrides to the node's properties and control props (code component nodes).\n *\n * @param tree - The tree to apply the token overrides to.\n * @param node - The node to apply the token overrides to.\n * @param tokenOverrides - The token overrides to apply.\n *\n */\nfunction applyTokenOverridesToNode(\n\tengine: VekterEngine,\n\tnode: CanvasNode,\n\ttokenOverrides: Record<CSSVariableName, string>,\n) {\n\tif (withFill(node)) {\n\t\tconst newColor = getTokenOverrideForValue(node.fillColor, tokenOverrides)\n\t\tif (newColor) node.set({ fillColor: newColor })\n\t}\n\n\tif (withBorder(node)) {\n\t\tconst newColor = getTokenOverrideForValue(node.borderColor, tokenOverrides)\n\t\tif (newColor) node.set({ borderColor: newColor })\n\t}\n\n\tif (withStroke(node)) {\n\t\tconst newColor = getTokenOverrideForValue(node.strokeColor, tokenOverrides)\n\t\tif (newColor) node.set({ strokeColor: newColor })\n\t}\n\n\tif (isRichTextNode(node)) {\n\t\tif (node.htmlContent) {\n\t\t\tapplyTokenOverridesToNodePresets(engine, node, tokenOverrides)\n\t\t} else {\n\t\t\tconst replacementColorTokensMap = new Map<string, string>()\n\t\t\tfor (const tokenCustomProperty in tokenOverrides) {\n\t\t\t\tif (!isCSSVariableName(tokenCustomProperty)) continue\n\t\t\t\t// Only collect overrides for tokens actually referenced in the html.\n\t\t\t\tif (!node.html.includes(tokenCustomProperty)) continue\n\n\t\t\t\tconst color = tokenOverrides[tokenCustomProperty]\n\t\t\t\tconst colorTokenId = tokenIdFromCustomProperty(tokenCustomProperty)\n\t\t\t\tif (!colorTokenId) continue\n\n\t\t\t\treplacementColorTokensMap.set(colorTokenId, `var(${tokenCustomProperty}, ${color})`)\n\t\t\t}\n\n\t\t\tif (replacementColorTokensMap.size > 0) node.replaceColorTokenVariables(replacementColorTokensMap)\n\n\t\t\tif (node.hasLinks()) {\n\t\t\t\tnode.remapLinkStylePresets(presetId => {\n\t\t\t\t\tconst preset = getPresetWithTokenOverrides(engine, presetId, tokenOverrides)\n\t\t\t\t\tif (isLinkStylePresetNode(preset)) return preset\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t} else if (isCodeComponentNode(node)) {\n\t\tconst component = engine.componentLoader.componentForIdentifier(node.codeComponentIdentifier)\n\t\tif (!component) return\n\n\t\tconst controlProps = node.getControlProps(component.properties)\n\t\tif (!controlProps) return\n\n\t\tfor (const controlKey in controlProps) {\n\t\t\tconst controlProp = controlProps[controlKey]\n\t\t\tif (!controlProp || !isControlTypeWithColor(controlProp)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tswitch (controlProp.type) {\n\t\t\t\tcase ControlType.Border:\n\t\t\t\t\tif (!isBorderValues(controlProp.value)) break\n\n\t\t\t\t\tnode.setControlProp(controlKey, {\n\t\t\t\t\t\t...controlProp,\n\t\t\t\t\t\tvalue: {\n\t\t\t\t\t\t\t...controlProp.value,\n\t\t\t\t\t\t\tborderColor: getTokenOverrideForValue(controlProp.value.borderColor, tokenOverrides),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t\tbreak\n\t\t\t\tcase ControlType.Color:\n\t\t\t\t\tnode.setControlProp(controlKey, {\n\t\t\t\t\t\t...controlProp,\n\t\t\t\t\t\tvalue: getTokenOverrideForValue(controlProp.value, tokenOverrides),\n\t\t\t\t\t})\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(controlProp, \"Unsupported control type.\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction applyTokenOverridesToNodePresets(\n\tengine: VekterEngine,\n\tnode: RichTextNode,\n\ttokenOverrides: Record<CSSVariableName, string>,\n) {\n\t// Process the different preset types\n\tfor (const key of stylePresetKeys) {\n\t\tconst presetId = node[key]\n\t\tif (!presetId) continue\n\n\t\tconst preset = getPresetWithTokenOverrides(engine, presetId, tokenOverrides)\n\t\tif (isStylePresetPrimaryNode(preset)) node.set({ [key]: preset.id })\n\t}\n}\n\nfunction getPresetWithTokenOverrides(\n\tengine: VekterEngine,\n\tpresetId: NodeID,\n\ttokenOverrides: Record<CSSVariableName, string>,\n) {\n\tconst currentPreset = engine.tree.getNodeWithTrait(presetId, isStylePresetPrimaryNode)\n\t// Check if preset node exists, might be one of default presets\n\tif (!currentPreset) return\n\n\tconst presetWithTokenOverrides = createPresetWithTokenOverrides(currentPreset, tokenOverrides)\n\n\t// If our current preset already has overrides applied, we can skip\n\tif (isSamePreset(currentPreset, presetWithTokenOverrides)) return currentPreset\n\n\t// Search for a preset with the same relevant fields and it has the overrides applied\n\tconst presetsListNode = PresetsListNode.ensure(engine.tree)\n\n\tconst equivalentPresetWithTokenOverrides = presetsListNode\n\t\t.getStylePresets()\n\t\t.filter(preset => preset.id !== presetId && isSamePreset(preset, presetWithTokenOverrides))\n\n\tif (!equivalentPresetWithTokenOverrides.length) {\n\t\t// Make sure we insert the new preset in the tree\n\t\tengine.tree.insertNode(presetWithTokenOverrides, presetsListNode.id)\n\n\t\tengine.stores.codeGenerationStore.createModuleFromComponentSource(presetWithTokenOverrides).catch(unhandledError)\n\n\t\treturn presetWithTokenOverrides\n\t}\n\n\treturn equivalentPresetWithTokenOverrides?.[0]\n}\n\nfunction isSamePreset(preset1: StylePresetNode, preset2: StylePresetNode) {\n\tif (preset1.__class !== preset2.__class) return false\n\n\tif (isTextStylePresetNode(preset1) && isTextStylePresetNode(preset2)) {\n\t\treturn preset1.equals(preset2)\n\t}\n\tif (isLinkStylePresetNode(preset1) && isLinkStylePresetNode(preset2)) {\n\t\treturn preset1.equals(preset2)\n\t}\n\tif (isBlockquoteStylePresetNode(preset1) && isBlockquoteStylePresetNode(preset2)) {\n\t\treturn preset1.equals(preset2)\n\t}\n\tif (isInlineCodeStylePresetNode(preset1) && isInlineCodeStylePresetNode(preset2)) {\n\t\treturn preset1.equals(preset2)\n\t}\n\tif (isImageStylePresetNode(preset1) && isImageStylePresetNode(preset2)) {\n\t\treturn preset1.equals(preset2)\n\t}\n\n\treturn false\n}\n\nfunction createPresetWithTokenOverrides(\n\toriginalPreset: StylePresetNode,\n\ttokenOverrides: Record<CSSVariableName, string>,\n) {\n\tconst presetWithTokenOverrides = originalPreset.clone()\n\tapplyTokenOverridesToPreset(presetWithTokenOverrides, tokenOverrides)\n\treturn presetWithTokenOverrides\n}\n\nfunction applyTokenOverridesToPreset(preset: CanvasNode, tokenOverrides: Record<CSSVariableName, string>) {\n\tif (isTextStylePresetNode(preset)) {\n\t\tpreset.textColor = getTokenOverrideForValue(preset.textColor, tokenOverrides)\n\t\tpreset.textStrokeColor = getTokenOverrideForValue(preset.textStrokeColor, tokenOverrides)\n\t\tpreset.textDecorationColor = getTokenOverrideForValue(preset.textDecorationColor, tokenOverrides)\n\t} else if (isLinkStylePresetNode(preset)) {\n\t\tpreset.linkTextColor = getTokenOverrideForValue(preset.linkTextColor, tokenOverrides)\n\t\tpreset.linkTextDecorationColor = getTokenOverrideForValue(preset.linkTextDecorationColor, tokenOverrides)\n\t\tpreset.linkTextBackgroundColor = getTokenOverrideForValue(preset.linkTextBackgroundColor, tokenOverrides)\n\t\tpreset.linkHoverTextColor = getTokenOverrideForValue(preset.linkHoverTextColor, tokenOverrides)\n\t\tpreset.linkHoverTextDecorationColor = getTokenOverrideForValue(preset.linkHoverTextDecorationColor, tokenOverrides)\n\t\tpreset.linkHoverTextBackgroundColor = getTokenOverrideForValue(preset.linkHoverTextBackgroundColor, tokenOverrides)\n\t\tpreset.linkCurrentTextColor = getTokenOverrideForValue(preset.linkCurrentTextColor, tokenOverrides)\n\t\tpreset.linkCurrentTextDecorationColor = getTokenOverrideForValue(\n\t\t\tpreset.linkCurrentTextDecorationColor,\n\t\t\ttokenOverrides,\n\t\t)\n\t\tpreset.linkCurrentTextBackgroundColor = getTokenOverrideForValue(\n\t\t\tpreset.linkCurrentTextBackgroundColor,\n\t\t\ttokenOverrides,\n\t\t)\n\t} else if (isImageStylePresetNode(preset)) {\n\t\tpreset.borderColor = getTokenOverrideForValue(preset.borderColor, tokenOverrides)\n\t} else if (isBlockquoteStylePresetNode(preset)) {\n\t\tpreset.textColor = getTokenOverrideForValue(preset.textColor, tokenOverrides)\n\t\tpreset.textDecorationColor = getTokenOverrideForValue(preset.textDecorationColor, tokenOverrides)\n\t\tpreset.textStrokeColor = getTokenOverrideForValue(preset.textStrokeColor, tokenOverrides)\n\t\tpreset.borderColor = getTokenOverrideForValue(preset.borderColor, tokenOverrides)\n\t\tpreset.fillColor = getTokenOverrideForValue(preset.fillColor, tokenOverrides)\n\t\tpreset.lineColor = getTokenOverrideForValue(preset.lineColor, tokenOverrides)\n\t} else if (isInlineCodeStylePresetNode(preset)) {\n\t\tpreset.inlineCodeTextColor = getTokenOverrideForValue(preset.inlineCodeTextColor, tokenOverrides)\n\t\tpreset.inlineCodeFillColor = getTokenOverrideForValue(preset.inlineCodeFillColor, tokenOverrides)\n\t\tpreset.borderColor = getTokenOverrideForValue(preset.borderColor, tokenOverrides)\n\t}\n}\n\n/**\n * Get the token override for a value if the value is a CSS variable.\n *\n * @param value - The value to get the token override for.\n * @param tokenOverrides - The token overrides to apply.\n * @returns A new CSS Variable with the token override and the new fallback value.\n */\nfunction getTokenOverrideForValue<T>(value: T, tokenOverrides: Record<CSSVariableName, string>): T | string {\n\tif (isNull(value) || !isTokenCSSVariable(value)) return value\n\n\t// Also get metadata from the original value to preserve it\n\tconst { customProperty, metadata } = parseCSSVariable(value)\n\tif (!isCSSVariableName(customProperty)) return value\n\n\tconst newColor = tokenOverrides[customProperty]\n\tif (!newColor) return value\n\n\t// To keep a reference to which token the property refers too we set the value and keep the CSS variable\n\t// custom property. We leverage the fact that we don't add the tokens to the project when generating so the fallback\n\t// value is always applied.\n\tconst newVariable = `var(${customProperty}, ${newColor})`\n\n\treturn metadata ? `${newVariable} ${metadata}` : newVariable\n}\n\ntype VariableWithColor = ColorVariableDefinition | BorderVariableDefinition\ntype ControlPropWithColor = ColorControlProp | BorderControlProp\n\nexport function isControlTypeWithColor(variable: VariableDefinition): variable is VariableWithColor\nexport function isControlTypeWithColor(variable: ControlProp): variable is ControlPropWithColor\nexport function isControlTypeWithColor(\n\tvariable: ControlProp | VariableDefinition,\n): variable is ControlPropWithColor | VariableWithColor {\n\tswitch (variable.type) {\n\t\tcase ControlType.Color:\n\t\tcase ControlType.Border:\n\t\t\treturn true\n\t\tcase ControlType.Array:\n\t\tcase ControlType.Boolean:\n\t\tcase ControlType.Number:\n\t\tcase ControlType.String:\n\t\tcase ControlType.RichText:\n\t\tcase ControlType.EventHandler:\n\t\tcase ControlType.Image:\n\t\tcase ControlType.File:\n\t\tcase ControlType.ScrollSectionRef:\n\t\tcase ControlType.CustomCursor:\n\t\tcase ControlType.Cursor:\n\t\tcase ControlType.Transition:\n\t\tcase ControlType.BoxShadow:\n\t\tcase ControlType.Gap:\n\t\tcase ControlType.Padding:\n\t\tcase ControlType.BorderRadius:\n\t\tcase ControlType.CollectionReference:\n\t\tcase ControlType.MultiCollectionReference:\n\t\tcase ControlType.TrackingId:\n\t\tcase ControlType.VectorSetItem:\n\t\tcase ControlType.Date:\n\t\tcase ControlType.Enum:\n\t\tcase ControlType.Link:\n\t\tcase ControlType.LinkRelValues:\n\t\tcase ControlType.FusedNumber:\n\t\tcase ControlType.Object:\n\t\tcase ControlType.Font:\n\t\tcase ControlType.PageScope:\n\t\tcase ControlType.Slot:\n\t\tcase ControlType.Location:\n\t\tcase \"slug\":\n\t\tcase \"controlReference\":\n\t\tcase \"nodePropertyControlReference\":\n\t\t\treturn false\n\t\tdefault:\n\t\t\tassertNever(variable, \"Check if we support this variable type.\")\n\t}\n}\n", "import type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { getRouteSegmentNodeByWebPageId } from \"document/components/chrome/Pages/utils/getRouteSegmentNodeByWebPageId.ts\"\nimport type { LoadedScopeNode, LoadedWebPageNode, RootNode, WebPageNode } from \"document/models/CanvasTree/index.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { isBreakpointVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\n\nexport function isEmptyWebPage(node: LoadedScopeNode): node is LoadedWebPageNode {\n\tif (!isWebPageNode(node)) return false\n\n\tfor (const child of node.children) {\n\t\tif (!isBreakpointVariant(child)) return false\n\t\tif (withChildren(child) && child.children.length > 0) return false\n\t}\n\n\treturn true\n}\n\nexport function replaceWebPage(engine: VekterEngine, oldNode: WebPageNode, newNode: WebPageNode) {\n\t// Don't replace the page if it is a CMS detail page.\n\tif (hasCollectionDataSource(newNode)) return\n\n\tlet rootNodeUpdate: Partial<RootNode> | undefined\n\n\tengine.stores.scopeStore.removeNode(oldNode)\n\n\t// If there's a route segment asscoiated with the old node, remove the new segment node created during cloning,\n\t// update the webPageId on the old one\n\tconst newRouteSegmentNode = getRouteSegmentNodeByWebPageId(engine.tree, newNode.id)\n\tif (newRouteSegmentNode) {\n\t\tengine.tree.removeNode(newRouteSegmentNode)\n\t}\n\n\tconst homePageId = engine.tree.root.homePageNodeId\n\tconst oldRouteSegmentNode = getRouteSegmentNodeByWebPageId(engine.tree, oldNode.id)\n\tif (oldRouteSegmentNode) {\n\t\t// If we're replacing the home page, remove the old route segment node because the\n\t\t// home page should not be associated with a route segment.\n\t\tif (oldNode.id === homePageId) {\n\t\t\tengine.tree.removeNode(oldRouteSegmentNode)\n\t\t} else {\n\t\t\toldRouteSegmentNode.set({ webPageId: newNode.id })\n\t\t}\n\t}\n\n\tengine.tree.current(newNode)?.set({\n\t\tname: oldNode.name,\n\t\tpagePath: oldNode.pagePath,\n\t})\n\n\tif (!engine.tree.has(homePageId)) {\n\t\trootNodeUpdate ??= {}\n\t\trootNodeUpdate.homePageNodeId = newNode.id\n\t}\n\n\tif (rootNodeUpdate) {\n\t\tengine.tree.root.set(rootNodeUpdate)\n\t}\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport { PresetsListNode } from \"document/models/CanvasTree/nodes/PresetsListNode.ts\"\nimport type { TextStylePresetNode } from \"document/models/CanvasTree/nodes/TextStylePresetNode.ts\"\nimport { isTextStylePresetNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { type IsReplica, isReplica } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isDefined } from \"utils/typeChecks.ts\"\n\nexport function getTextStylePresetBreakpointOverridesFromTree(tree: CanvasTree, preset: TextStylePresetNode) {\n\treturn getTextStylePresetBreakpointsFromTree(tree, preset)\n\t\t.map(breakpoint => breakpoint.replicaInfo.overrides[breakpoint.originalid])\n\t\t.filter(isDefined)\n}\n\nexport function getTextStylePresetBreakpoints(presets: TextStylePresetNode[], preset: TextStylePresetNode) {\n\treturn presets\n\t\t.filter(\n\t\t\t(breakpoint): breakpoint is TextStylePresetNode & IsReplica =>\n\t\t\t\tisReplica(breakpoint) && breakpoint.originalid === preset.id,\n\t\t)\n\t\t.sort((left, right) => (right.breakpointWidth ?? 0) - (left.breakpointWidth ?? 0))\n}\n\n/**\n * Returns breakpoints for a preset sorted by `breakpointWidth` from largest to smallest.\n */\nexport function getTextStylePresetBreakpointsFromTree(tree: CanvasTree, preset: TextStylePresetNode) {\n\tconst listNode = PresetsListNode.get(tree)\n\tassert(listNode, \"Can't find PresetsListNode\")\n\n\tconst presets = listNode.children.filter(isTextStylePresetNode)\n\treturn getTextStylePresetBreakpoints(presets, preset)\n}\n", "import { murmurHash, stableStringify } from \"@framerjs/shared\"\nimport { isEqual } from \"library/render/utils/isEqual.ts\"\nimport { cmsSchemaParams, makeSchema } from \"prosemirror/schema/index.ts\"\nimport type { RichTextDocument, RichTextDocumentVariant } from \"./RichTextDocument.ts\"\nimport { type RichTextDocumentMapper, mapRichTextDocument } from \"./richTextDocumentTraversal.ts\"\nimport { getHTMLFromRichTextTreeValue } from \"./richTextPmAdapter.ts\"\nimport type { RichTextTreeValue } from \"./richTextStorage.ts\"\nimport { getRichTextDocumentFromRichTextTreeValue } from \"./richTextStorageDocument.ts\"\n\ntype RichTextTreeValueStorageFormat = \"html\" | \"json\"\n\nconst cmsSchema = makeSchema(cmsSchemaParams)\n\n/**\n * Hash a rich text value in its native storage format.\n * HTML-backed (string) values use murmurHash of the HTML string.\n * JSON-backed (RichTextDocument) values use a stable content hash that ignores generated node ids.\n * No cross-format conversion is performed.\n */\nexport function getRichTextTreeValueHash(value: RichTextTreeValue): number {\n\tif (typeof value === \"string\") return murmurHash(value)\n\n\treturn getRichTextDocumentContentHash(getRichTextDocumentFromRichTextTreeValue(value, value.variant))\n}\n\nexport function getRichTextTreeValueStorageFormat(value: RichTextTreeValue): RichTextTreeValueStorageFormat {\n\treturn typeof value === \"string\" ? \"html\" : \"json\"\n}\n\nexport function getCanonicalRichTextTreeValueHash(value: RichTextTreeValue, variant: RichTextDocumentVariant): number {\n\treturn getRichTextDocumentContentHash(getRichTextDocumentFromRichTextTreeValue(value, variant))\n}\n\nexport function getRichTextTreeValueStorageMigrationHash(\n\tvalue: RichTextTreeValue,\n\tformat: RichTextTreeValueStorageFormat,\n\tvariant: RichTextDocumentVariant,\n): number {\n\tif (format === \"html\") {\n\t\t// TODO(richTextJson): Remove this once rich text no longer rolls back through\n\t\t// HTML-only editor boundaries. This branch only exists for that narrow rollback\n\t\t// path, so localized hashes can still migrate with the persisted storage format.\n\t\tconst html = typeof value === \"string\" ? value : getHTMLFromRichTextTreeValue(value, cmsSchema)\n\t\treturn murmurHash(html)\n\t}\n\n\treturn getCanonicalRichTextTreeValueHash(value, variant)\n}\n\n/**\n * Replace every rich-text node ID in `document` with a deterministic sequential value, leaving\n * the rest of the structure untouched. Only actual rich-text node IDs are replaced \u2014 nested\n * content like module props is preserved verbatim.\n *\n * Two documents that differ only in minted node IDs (for example after independent HTML\u2192JSON\n * parses on sibling sources) produce the same canonical form, so equality and hashing built on\n * top of this function ignore ID drift.\n */\nfunction getRichTextDocumentWithCanonicalIds(document: RichTextDocument): RichTextDocument {\n\tlet counter = 0\n\tconst nextId = () => String(counter++)\n\tconst withNextId = <T extends { id: string }>(node: T): T => ({ ...node, id: nextId() })\n\tconst mapper = {\n\t\tdocument: currentDocument => currentDocument,\n\t\ttextBlock: withNextId,\n\t\tbulletedList: withNextId,\n\t\tnumberedList: withNextId,\n\t\tlistItem: withNextId,\n\t\tblockquote: withNextId,\n\t\tmedia: withNextId,\n\t\tmodule: withNextId,\n\t\ttable: withNextId,\n\t\ttableRow: withNextId,\n\t\ttableCell: withNextId,\n\t\ttext: withNextId,\n\t\tlineBreak: withNextId,\n\t} satisfies Required<RichTextDocumentMapper>\n\n\treturn mapRichTextDocument(document, mapper, { normalize: false })\n}\n\n/**\n * Hash an already-normalized RichTextDocument by replacing all rich-text node IDs\n * with deterministic sequential values, then hashing the result. Only actual\n * rich-text node IDs are replaced \u2014 nested content like module props is untouched.\n */\nfunction getRichTextDocumentContentHash(document: RichTextDocument): number {\n\treturn murmurHash(stableStringify(getRichTextDocumentWithCanonicalIds(document)))\n}\n\n/**\n * Compare two `RichTextDocument`s structurally, treating documents that differ only in minted\n * node IDs as equal. Faster path for reference-identical documents; otherwise canonicalize IDs\n * and deep-compare via `isEqual`.\n *\n * Used by translation memory dedup so independent translations on sibling sources (which mint\n * fresh IDs on each parse) still collapse together.\n */\nexport function areRichTextDocumentsCanonicallyEqual(a: RichTextDocument, b: RichTextDocument): boolean {\n\tif (a === b) return true\n\treturn isEqual(getRichTextDocumentWithCanonicalIds(a), getRichTextDocumentWithCanonicalIds(b))\n}\n", "import type { ComponentLoader, DataDefinition } from \"@framerjs/framer-runtime\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, isModuleExportIdentifier, parseModuleIdentifier, shouldBeNever } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { pathToName } from \"document/components/utils/pathToName.ts\"\nimport type { CanvasTree, CollectionItemNode, CollectionNode, MaybeNodeID } from \"document/models/CanvasTree/index.ts\"\nimport { CONTENT_MANAGEMENT_ID } from \"document/models/CanvasTree/nodes/ContentManagementNode.ts\"\nimport { getContentManagementNode } from \"document/models/CanvasTree/nodes/ContentManagementNode.utils.ts\"\nimport { isCollectionItemNode, isCollectionNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { HasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport {\n\ttype SlugVariableDefinition,\n\ttype StringVariableDefinition,\n\tisVariableDefinition,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport type { LocalizedTextValue, LocalizedValues } from \"document/models/LocalizedValue.ts\"\nimport type { CollectionControlProp } from \"document/models/controlProps/CollectionControlProp.ts\"\nimport type { RichTextControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport {\n\tisRawControlProp,\n\ttype RawControlProp,\n\ttype RawControlProps,\n} from \"document/models/controlProps/RawControlProp.ts\"\nimport { prefixControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport type {\n\tRichTextBlock,\n\tRichTextBlockquoteBlock,\n\tRichTextDocument,\n\tRichTextListItem,\n\tRichTextTableCell,\n\tRichTextTableRow,\n} from \"document/models/richText/RichTextDocument.ts\"\nimport { getRichTextTreeValueHash } from \"document/models/richText/richTextHash.ts\"\nimport { parseRichTextHtmlToDocument } from \"document/models/richText/richTextHtmlParser.ts\"\nimport { isRichTextTreeValue, type RichTextTreeValue } from \"document/models/richText/richTextStorage.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport { ControlType, isEqual } from \"library/index.ts\"\nimport { escapeHTML, unescapeHTML } from \"library/render/utils/dom.ts\"\nimport type { PersistedModule } from \"modules/ModulesStorage.ts\"\nimport { CMS_MODULE_IDENTIFIER_ATTR, moduleIdentifierAttributeRegex } from \"prosemirror/schema/module.ts\"\nimport type { Mutable } from \"./Mutable.ts\"\nimport { getCollectionForIdentifier } from \"./getCollectionForIdentifier.ts\"\nimport { isObject, isString, isUndefined } from \"./typeChecks.ts\"\n\nconst modulePropsAttributeRegex = /data-module-props=(['\"])(.*?)\\1/gsu\n\ninterface CollectionData {\n\tidentifier: ModuleExportIdentifierString\n\tmodule?: PersistedModule\n\tentity?: DataDefinition\n}\n\nexport function getCollectionData(\n\tcomponentLoader: ComponentLoader,\n\tmodulesStore: ModulesStore,\n\tnode: CollectionNode,\n): CollectionData {\n\tconst identifier = node.instanceIdentifier\n\tconst module = modulesStore.getPersistedModuleByLocalIdentifier(identifier)\n\tconst entity = componentLoader.dataForIdentifier(identifier) ?? undefined\n\treturn { identifier, module, entity }\n}\n\nexport function getSlugIdFromDataDefinition(dataDefinition: DataDefinition): string | undefined {\n\treturn dataDefinition.annotations?.[AnnotationKey.FramerSlug]\n}\n\nexport function getCollectionName(node: CollectionNode, fallback: string = Dictionary.Collection): string {\n\tconst name = node.resolveValue(\"name\")\n\tif (!name) return fallback\n\tif (name.toLowerCase().includes(\"collection\")) return name\n\treturn `${name.trim()} ${Dictionary.Collection}`\n}\n\nfunction getCollectionItemTitle(itemNode: CollectionItemNode, titleVariable: StringVariableDefinition | undefined) {\n\tif (isUndefined(titleVariable)) return\n\n\tconst controlProp = itemNode.getControlProp(titleVariable.id)\n\tconst value = controlProp?.value || titleVariable.initialValue\n\n\tif (isString(value) && value.length > 0) return value\n}\n\nexport function getCollectionItemSlug(itemNode: CollectionItemNode, slugVariable: SlugVariableDefinition | undefined) {\n\tif (isUndefined(slugVariable)) return\n\n\tconst controlProp = itemNode.getControlProp(slugVariable.id)\n\tconst value = controlProp?.value || slugVariable.initialValue\n\n\tif (isString(value) && value.length > 0) return value\n}\n\nexport function getCollectionItemName(collectionNode: CollectionNode, itemNode: CollectionItemNode) {\n\tconst titleVariable = collectionNode.getTitleVariable()\n\tconst title = getCollectionItemTitle(itemNode, titleVariable)\n\tif (isString(title)) return title\n\n\tconst slugVariable = collectionNode.getSlugVariable()\n\tconst slug = getCollectionItemSlug(itemNode, slugVariable)\n\tif (isString(slug)) return pathToName(slug)\n\n\treturn Dictionary.CollectionItem\n}\n\n/**\n * Gets path variables for a CMS page by finding the first non-draft item\n * and extracting its slug variable. This is useful for generating example\n * URLs for screenshots.\n */\nexport function getSamplePathVariablesForCMSPage(\n\ttree: CanvasTree,\n\tcmsWebPage: HasCollectionDataSource,\n): Record<string, string> | undefined {\n\t// FIXME If CMS Node will ever become shallow this code needs to be checked/updated\n\tconst contentManagementNode = getContentManagementNode(tree)?.loaded\n\tconst collectionNode = contentManagementNode?.children.find(\n\t\tnode => node.instanceIdentifier === cmsWebPage.dataIdentifier,\n\t)\n\tconst slugVariable = collectionNode?.getSlugVariable()\n\tconst firstNonDraftItem = collectionNode?.getSortedChildren(\"public-only\", \"group-drafts\").find(item => !item.isDraft)\n\n\tif (!firstNonDraftItem || !slugVariable || !collectionNode) return undefined\n\n\tconst slug = getCollectionItemSlug(firstNonDraftItem, slugVariable)\n\tif (isString(slug)) return { [slugVariable.id]: slug }\n}\n\nfunction getSelectedCollection(engine: VekterEngine): CollectionNode | null {\n\tconst { ids } = engine.stores.selectionStore\n\tconst firstNodeId = ids[0]\n\tif (!firstNodeId) return null\n\tconst firstNode = engine.tree.getNode(firstNodeId)\n\tif (isCollectionNode(firstNode)) return firstNode\n\tif (isCollectionItemNode(firstNode)) {\n\t\tconst parentNode = engine.tree.getNode(firstNode.parentid)\n\t\tif (isCollectionNode(parentNode)) return parentNode\n\t}\n\treturn null\n}\n\nexport function getSelectedCollectionId(engine: VekterEngine): MaybeNodeID {\n\tconst selectionCollection = getSelectedCollection(engine)\n\treturn selectionCollection ? selectionCollection.id : null\n}\n\nexport function getSelectedCollectionName(engine: VekterEngine): string | null {\n\tconst selectionCollection = getSelectedCollection(engine)\n\treturn selectionCollection ? selectionCollection.resolveValue(\"name\") : null\n}\n\nexport function getCollectionCount(tree: CanvasTree): number {\n\t// FIXME If CMS Node will ever become shallow this code needs to be checked/updated\n\tconst contentManagementNode = getContentManagementNode(tree)?.loaded\n\tif (!contentManagementNode) return 0\n\treturn contentManagementNode.children.length\n}\n\nexport function getTotalCollectionItemCount(tree: CanvasTree): number {\n\t// FIXME If CMS Node will ever become shallow this code needs to be checked/updated\n\tconst contentManagementNode = getContentManagementNode(tree)?.loaded\n\tif (!contentManagementNode) return 0\n\treturn contentManagementNode.children.reduce((count, collectionNode) => count + collectionNode.getItemCount(), 0)\n}\n\nfunction isRichTextControlProp(\n\tcontrolProp: CollectionControlProp,\n): controlProp is RichTextControlProp & { value: RichTextTreeValue } {\n\treturn controlProp.type === ControlType.RichText && isRichTextTreeValue(controlProp.value)\n}\n\ntype ModuleIdentifierReplacer = (identifier: ModuleExportIdentifierString) => ModuleExportIdentifierString | undefined\n\nfunction getModuleIdentifierReplacer(\n\tfromIdentifier: ModuleExportIdentifierString,\n\ttoIdentifier: ModuleExportIdentifierString,\n): ModuleIdentifierReplacer {\n\tconst parsedFromId = parseModuleIdentifier(fromIdentifier)\n\n\treturn moduleIdentifier => {\n\t\tconst parsedId = parseModuleIdentifier(moduleIdentifier)\n\t\tif (!parsedId || !parsedFromId) return\n\n\t\tif (\n\t\t\tparsedId.kind === \"localModuleExport\" &&\n\t\t\tparsedFromId.kind === \"localModuleExport\" &&\n\t\t\tparsedId.localId === parsedFromId.localId\n\t\t) {\n\t\t\treturn toIdentifier\n\t\t}\n\n\t\tif (\n\t\t\tparsedId.kind === \"externalModuleExport\" &&\n\t\t\tparsedFromId.kind === \"externalModuleExport\" &&\n\t\t\tparsedId.moduleId === parsedFromId.moduleId &&\n\t\t\tparsedId.exportSpecifier === parsedFromId.exportSpecifier\n\t\t) {\n\t\t\treturn toIdentifier\n\t\t}\n\t}\n}\n\nfunction updateModuleIdentifiersInCollectionItemRichText(value: string, replacer: ModuleIdentifierReplacer): string {\n\tconst updatedValue = value.replaceAll(moduleIdentifierAttributeRegex, (match: string, moduleIdentifier: string) => {\n\t\tconst newIdentifier = replacer(moduleIdentifier as ModuleExportIdentifierString)\n\n\t\tif (newIdentifier) {\n\t\t\treturn `${CMS_MODULE_IDENTIFIER_ATTR}=\"${newIdentifier}\"`\n\t\t}\n\n\t\treturn match\n\t})\n\n\treturn updatedValue.replaceAll(modulePropsAttributeRegex, (match: string, quote: string, serializedProps: string) => {\n\t\tlet rawProps: unknown\n\n\t\ttry {\n\t\t\trawProps = JSON.parse(unescapeHTML(serializedProps))\n\t\t} catch {\n\t\t\treturn match\n\t\t}\n\n\t\tconst updatedProps = updateModuleIdentifiersInNestedControlPropValue(rawProps, replacer)\n\t\tif (updatedProps === rawProps) return match\n\n\t\treturn `data-module-props=${quote}${escapeHTML(JSON.stringify(updatedProps))}${quote}`\n\t})\n}\n\nfunction collectModuleIdentifiersFromRawControlProps(\n\tcontrolProps: RawControlProps,\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n) {\n\tfor (const controlProp of Object.values(controlProps)) {\n\t\tif (!controlProp) continue\n\t\tcollectModuleIdentifiersFromRawControlProp(controlProp, moduleIdentifiers)\n\t}\n}\n\nfunction collectModuleIdentifiersFromRawControlProp(\n\tcontrolProp: RawControlProp,\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n) {\n\tswitch (controlProp.type) {\n\t\tcase ControlType.VectorSetItem:\n\t\t\tif (isString(controlProp.value) && isModuleExportIdentifier(controlProp.value)) {\n\t\t\t\tmoduleIdentifiers.add(controlProp.value)\n\t\t\t}\n\t\t\treturn\n\t\tcase ControlType.RichText:\n\t\t\tif (isRichTextTreeValue(controlProp.value)) {\n\t\t\t\tcollectModuleIdentifiersFromRichTextTreeValue(controlProp.value, moduleIdentifiers)\n\t\t\t}\n\t\t\treturn\n\t\tcase ControlType.Array:\n\t\tcase ControlType.Object:\n\t\t\tcollectModuleIdentifiersFromNestedControlPropValue(controlProp.value, moduleIdentifiers)\n\t\t\treturn\n\t}\n}\n\nfunction collectModuleIdentifiersFromNestedControlPropValue(\n\tvalue: unknown,\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n) {\n\tif (isRawControlProp(value)) {\n\t\tcollectModuleIdentifiersFromRawControlProp(value, moduleIdentifiers)\n\t\treturn\n\t}\n\n\tif (Array.isArray(value)) {\n\t\tfor (const item of value) {\n\t\t\tcollectModuleIdentifiersFromNestedControlPropValue(item, moduleIdentifiers)\n\t\t}\n\t\treturn\n\t}\n\n\tif (!isObject(value)) return\n\n\tfor (const nestedValue of Object.values(value)) {\n\t\tcollectModuleIdentifiersFromNestedControlPropValue(nestedValue, moduleIdentifiers)\n\t}\n}\n\nfunction hasModuleIdentifierInRawControlProps(\n\tcontrolProps: RawControlProps,\n\tidentifier: ModuleExportIdentifierString,\n): boolean {\n\tfor (const controlProp of Object.values(controlProps)) {\n\t\tif (controlProp && hasModuleIdentifierInRawControlProp(controlProp, identifier)) return true\n\t}\n\n\treturn false\n}\n\nfunction hasModuleIdentifierInRawControlProp(\n\tcontrolProp: RawControlProp,\n\tidentifier: ModuleExportIdentifierString,\n): boolean {\n\tswitch (controlProp.type) {\n\t\tcase ControlType.VectorSetItem:\n\t\t\treturn controlProp.value === identifier\n\t\tcase ControlType.RichText:\n\t\t\treturn isRichTextTreeValue(controlProp.value) && richTextTreeValueHasModule(controlProp.value, identifier)\n\t\tcase ControlType.Array:\n\t\tcase ControlType.Object:\n\t\t\treturn hasModuleIdentifierInNestedControlPropValue(controlProp.value, identifier)\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\nfunction hasModuleIdentifierInNestedControlPropValue(\n\tvalue: unknown,\n\tidentifier: ModuleExportIdentifierString,\n): boolean {\n\tif (isRawControlProp(value)) {\n\t\treturn hasModuleIdentifierInRawControlProp(value, identifier)\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn value.some(item => hasModuleIdentifierInNestedControlPropValue(item, identifier))\n\t}\n\n\tif (!isObject(value)) return false\n\n\treturn Object.values(value).some(nestedValue => hasModuleIdentifierInNestedControlPropValue(nestedValue, identifier))\n}\n\nfunction collectModuleIdentifiersFromRichTextDocument(\n\tdocument: RichTextDocument,\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n) {\n\tcollectModuleIdentifiersFromRichTextBlocks(document.children, moduleIdentifiers)\n}\n\nfunction collectModuleIdentifiersFromRichTextTreeValue(\n\tvalue: RichTextTreeValue,\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n\tvariant: \"collectionControlProp\" | \"collectionControlPropLocalized\" = \"collectionControlProp\",\n) {\n\tif (typeof value === \"string\") {\n\t\tcollectModuleIdentifiersFromRichTextDocument(parseRichTextHtmlToDocument(value, variant), moduleIdentifiers)\n\t\treturn\n\t}\n\n\tcollectModuleIdentifiersFromRichTextDocument(value, moduleIdentifiers)\n}\n\nfunction collectModuleIdentifiersFromRichTextBlocks(\n\tblocks: RichTextBlock[],\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n) {\n\tfor (const block of blocks) {\n\t\tswitch (block.type) {\n\t\t\tcase \"module\":\n\t\t\t\tif (isModuleExportIdentifier(block.identifier)) {\n\t\t\t\t\tmoduleIdentifiers.add(block.identifier)\n\t\t\t\t}\n\t\t\t\tcollectModuleIdentifiersFromRawControlProps(block.props, moduleIdentifiers)\n\t\t\t\tbreak\n\t\t\tcase \"bulletedList\":\n\t\t\tcase \"numberedList\":\n\t\t\t\tcollectModuleIdentifiersFromRichTextListItems(block.children, moduleIdentifiers)\n\t\t\t\tbreak\n\t\t\tcase \"blockquote\":\n\t\t\t\tcollectModuleIdentifiersFromRichTextBlocks(block.children, moduleIdentifiers)\n\t\t\t\tbreak\n\t\t\tcase \"table\":\n\t\t\t\tcollectModuleIdentifiersFromRichTextTableRows(block.children, moduleIdentifiers)\n\t\t\t\tbreak\n\t\t\tcase \"textBlock\":\n\t\t\tcase \"media\":\n\t\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunction collectModuleIdentifiersFromRichTextListItems(\n\titems: RichTextListItem[],\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n) {\n\tfor (const item of items) {\n\t\tcollectModuleIdentifiersFromRichTextBlocks(item.children, moduleIdentifiers)\n\t}\n}\n\nfunction collectModuleIdentifiersFromRichTextTableRows(\n\trows: RichTextTableRow[],\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n) {\n\tfor (const row of rows) {\n\t\tcollectModuleIdentifiersFromRichTextTableCells(row.children, moduleIdentifiers)\n\t}\n}\n\nfunction collectModuleIdentifiersFromRichTextTableCells(\n\tcells: RichTextTableCell[],\n\tmoduleIdentifiers: Set<ModuleExportIdentifierString>,\n) {\n\tfor (const cell of cells) {\n\t\tcollectModuleIdentifiersFromRichTextBlocks(cell.children, moduleIdentifiers)\n\t}\n}\n\nfunction richTextTreeValueHasModule(\n\tvalue: RichTextTreeValue,\n\tidentifier: ModuleExportIdentifierString,\n\tvariant: \"collectionControlProp\" | \"collectionControlPropLocalized\" = \"collectionControlProp\",\n): boolean {\n\tif (typeof value === \"string\") {\n\t\treturn richTextDocumentHasModule(parseRichTextHtmlToDocument(value, variant), identifier)\n\t}\n\n\treturn richTextDocumentHasModule(value, identifier)\n}\n\nfunction richTextDocumentHasModule(document: RichTextDocument, identifier: ModuleExportIdentifierString): boolean {\n\treturn richTextBlocksHaveModule(document.children, identifier)\n}\n\nfunction richTextBlocksHaveModule(blocks: RichTextBlock[], identifier: ModuleExportIdentifierString): boolean {\n\tfor (const block of blocks) {\n\t\tswitch (block.type) {\n\t\t\tcase \"module\":\n\t\t\t\tif (block.identifier === identifier || hasModuleIdentifierInRawControlProps(block.props, identifier)) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase \"bulletedList\":\n\t\t\tcase \"numberedList\":\n\t\t\t\tif (richTextListItemsHaveModule(block.children, identifier)) return true\n\t\t\t\tbreak\n\t\t\tcase \"blockquote\":\n\t\t\t\tif (richTextBlocksHaveModule(block.children, identifier)) return true\n\t\t\t\tbreak\n\t\t\tcase \"table\":\n\t\t\t\tif (richTextTableRowsHaveModule(block.children, identifier)) return true\n\t\t\t\tbreak\n\t\t\tcase \"textBlock\":\n\t\t\tcase \"media\":\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunction richTextListItemsHaveModule(items: RichTextListItem[], identifier: ModuleExportIdentifierString): boolean {\n\treturn items.some(item => richTextBlocksHaveModule(item.children, identifier))\n}\n\nfunction richTextTableRowsHaveModule(rows: RichTextTableRow[], identifier: ModuleExportIdentifierString): boolean {\n\treturn rows.some(row => richTextTableCellsHaveModule(row.children, identifier))\n}\n\nfunction richTextTableCellsHaveModule(cells: RichTextTableCell[], identifier: ModuleExportIdentifierString): boolean {\n\treturn cells.some(cell => richTextBlocksHaveModule(cell.children, identifier))\n}\n\nexport function getModuleIdentifiersForRichTextTreeValue(\n\tvalue: RichTextTreeValue,\n\tvariant: \"collectionControlProp\" | \"collectionControlPropLocalized\" = \"collectionControlProp\",\n): ModuleExportIdentifierString[] {\n\tconst moduleIdentifiers = new Set<ModuleExportIdentifierString>()\n\tcollectModuleIdentifiersFromRichTextTreeValue(value, moduleIdentifiers, variant)\n\treturn [...moduleIdentifiers]\n}\n\nfunction updateModuleIdentifiersInCollectionItemRichTextTreeValue(\n\tvalue: RichTextTreeValue,\n\treplacer: ModuleIdentifierReplacer,\n): RichTextTreeValue {\n\tif (typeof value === \"string\") {\n\t\treturn updateModuleIdentifiersInCollectionItemRichText(value, replacer)\n\t}\n\n\tconst updatedChildren = updateModuleIdentifiersInRichTextBlocks(value.children, replacer)\n\treturn updatedChildren === value.children ? value : { ...value, children: updatedChildren }\n}\n\nfunction updateModuleIdentifiersInRawControlProps(\n\tcontrolProps: RawControlProps,\n\treplacer: ModuleIdentifierReplacer,\n): RawControlProps {\n\tlet updatedControlProps: Mutable<RawControlProps> | undefined\n\n\tfor (const [key, controlProp] of Object.entries(controlProps)) {\n\t\tif (!controlProp) continue\n\n\t\tconst updatedControlProp = updateModuleIdentifiersInRawControlProp(controlProp, replacer)\n\t\tif (updatedControlProp === controlProp) continue\n\n\t\tupdatedControlProps ??= { ...controlProps }\n\t\tupdatedControlProps[key] = updatedControlProp\n\t}\n\n\treturn updatedControlProps ?? controlProps\n}\n\nfunction updateModuleIdentifiersInRawControlProp(\n\tcontrolProp: RawControlProp,\n\treplacer: ModuleIdentifierReplacer,\n): RawControlProp {\n\tswitch (controlProp.type) {\n\t\tcase ControlType.VectorSetItem: {\n\t\t\tif (!isString(controlProp.value) || !isModuleExportIdentifier(controlProp.value)) return controlProp\n\n\t\t\tconst updatedValue = replacer(controlProp.value)\n\t\t\tif (isUndefined(updatedValue) || updatedValue === controlProp.value) return controlProp\n\n\t\t\treturn { ...controlProp, value: updatedValue }\n\t\t}\n\t\tcase ControlType.RichText: {\n\t\t\tif (!isRichTextTreeValue(controlProp.value)) return controlProp\n\n\t\t\tconst updatedValue = updateModuleIdentifiersInCollectionItemRichTextTreeValue(controlProp.value, replacer)\n\t\t\treturn updatedValue === controlProp.value ? controlProp : { ...controlProp, value: updatedValue }\n\t\t}\n\t\tcase ControlType.Array:\n\t\tcase ControlType.Object: {\n\t\t\tconst updatedValue = updateModuleIdentifiersInNestedControlPropValue(controlProp.value, replacer)\n\t\t\treturn updatedValue === controlProp.value ? controlProp : { ...controlProp, value: updatedValue }\n\t\t}\n\t\tdefault:\n\t\t\treturn controlProp\n\t}\n}\n\nfunction updateModuleIdentifiersInNestedControlPropValue(value: unknown, replacer: ModuleIdentifierReplacer): unknown {\n\tif (isRawControlProp(value)) {\n\t\treturn updateModuleIdentifiersInRawControlProp(value, replacer)\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn mapItemsWithStructuralSharing(value, item => updateModuleIdentifiersInNestedControlPropValue(item, replacer))\n\t}\n\n\tif (!isObject(value)) return value\n\n\tlet updatedValue: Record<string, unknown> | undefined\n\n\tfor (const [key, nestedValue] of Object.entries(value)) {\n\t\tconst updatedNestedValue = updateModuleIdentifiersInNestedControlPropValue(nestedValue, replacer)\n\t\tif (updatedNestedValue === nestedValue) continue\n\n\t\tupdatedValue ??= { ...value }\n\t\tupdatedValue[key] = updatedNestedValue\n\t}\n\n\treturn updatedValue ?? value\n}\n\nexport function mapItemsWithStructuralSharing<Item>(items: Item[], updateItem: (item: Item) => Item): Item[] {\n\tlet updatedItems: Item[] | undefined\n\n\tfor (let index = 0; index < items.length; index++) {\n\t\tconst item = items[index]\n\t\tassert(item, \"Expected rich text item to exist\")\n\n\t\tconst updatedItem = updateItem(item)\n\t\tif (updatedItem === item) continue\n\n\t\tupdatedItems ??= Array.from(items)\n\t\tupdatedItems[index] = updatedItem\n\t}\n\n\treturn updatedItems ?? items\n}\n\nfunction updateModuleIdentifiersInRichTextBlocks(\n\tblocks: RichTextBlock[],\n\treplacer: ModuleIdentifierReplacer,\n): RichTextBlock[] {\n\treturn mapItemsWithStructuralSharing(blocks, block => updateModuleIdentifiersInRichTextBlock(block, replacer))\n}\n\nfunction updateModuleIdentifiersInRichTextListItems(\n\titems: RichTextListItem[],\n\treplacer: ModuleIdentifierReplacer,\n): RichTextListItem[] {\n\treturn mapItemsWithStructuralSharing(items, item => {\n\t\tconst updatedChildren = updateModuleIdentifiersInRichTextBlocks(item.children, replacer)\n\t\tif (updatedChildren === item.children) return item\n\t\treturn { ...item, children: updatedChildren }\n\t})\n}\n\nfunction updateModuleIdentifiersInRichTextTableRows(\n\trows: RichTextTableRow[],\n\treplacer: ModuleIdentifierReplacer,\n): RichTextTableRow[] {\n\treturn mapItemsWithStructuralSharing(rows, row => {\n\t\tconst updatedChildren = updateModuleIdentifiersInRichTextTableCells(row.children, replacer)\n\t\tif (updatedChildren === row.children) return row\n\t\treturn { ...row, children: updatedChildren }\n\t})\n}\n\nfunction updateModuleIdentifiersInRichTextTableCells(\n\tcells: RichTextTableCell[],\n\treplacer: ModuleIdentifierReplacer,\n): RichTextTableCell[] {\n\treturn mapItemsWithStructuralSharing(cells, cell => {\n\t\tconst updatedChildren = updateModuleIdentifiersInRichTextBlocks(cell.children, replacer)\n\t\tif (updatedChildren === cell.children) return cell\n\t\treturn { ...cell, children: updatedChildren }\n\t})\n}\n\nfunction updateModuleIdentifiersInRichTextBlock(\n\tblock: RichTextBlock,\n\treplacer: ModuleIdentifierReplacer,\n): RichTextBlock {\n\tswitch (block.type) {\n\t\tcase \"module\": {\n\t\t\tconst updatedIdentifier = replacer(block.identifier)\n\t\t\tconst nextIdentifier =\n\t\t\t\tisUndefined(updatedIdentifier) || updatedIdentifier === block.identifier ? block.identifier : updatedIdentifier\n\t\t\tconst updatedProps = updateModuleIdentifiersInRawControlProps(block.props, replacer)\n\t\t\treturn nextIdentifier === block.identifier && updatedProps === block.props\n\t\t\t\t? block\n\t\t\t\t: { ...block, identifier: nextIdentifier, props: updatedProps }\n\t\t}\n\t\tcase \"bulletedList\":\n\t\tcase \"numberedList\": {\n\t\t\tconst updatedChildren = updateModuleIdentifiersInRichTextListItems(block.children, replacer)\n\t\t\treturn updatedChildren === block.children ? block : { ...block, children: updatedChildren }\n\t\t}\n\t\tcase \"blockquote\": {\n\t\t\tconst updatedChildren = updateModuleIdentifiersInRichTextBlocks(block.children, replacer)\n\t\t\treturn updatedChildren === block.children\n\t\t\t\t? block\n\t\t\t\t: ({ ...block, children: updatedChildren } satisfies RichTextBlockquoteBlock)\n\t\t}\n\t\tcase \"table\": {\n\t\t\tconst updatedChildren = updateModuleIdentifiersInRichTextTableRows(block.children, replacer)\n\t\t\treturn updatedChildren === block.children ? block : { ...block, children: updatedChildren }\n\t\t}\n\t\tcase \"textBlock\":\n\t\tcase \"media\":\n\t\t\treturn block\n\t\tdefault:\n\t\t\tshouldBeNever(block)\n\t\t\treturn block\n\t}\n}\n\nexport function updateModuleIdentifiersInRichTextControlProp(\n\tcontrolProp: RichTextControlProp,\n\treplacer: ModuleIdentifierReplacer,\n): RichTextControlProp {\n\tif (!isRichTextTreeValue(controlProp.value)) return controlProp\n\n\tconst previousBaseValue = controlProp.value\n\tconst newBaseValue = updateModuleIdentifiersInCollectionItemRichTextTreeValue(previousBaseValue, replacer)\n\n\tlet updatedLocalizedValue: Mutable<LocalizedValues<LocalizedTextValue>> | undefined\n\n\tif (controlProp.valueLocalized) {\n\t\tconst previousBaseValueHash = getRichTextTreeValueHash(previousBaseValue)\n\t\tconst newBaseValueHash = getRichTextTreeValueHash(newBaseValue)\n\n\t\tupdatedLocalizedValue = {}\n\n\t\tfor (const localeId of Object.keys(controlProp.valueLocalized)) {\n\t\t\tconst localizedValue = controlProp.valueLocalized[localeId]\n\t\t\tif (!localizedValue) continue\n\n\t\t\t// We use the hash to check if a translation is outdated or not. When updating\n\t\t\t// embeds we don't want it to invalidate existing translations, so we update the\n\t\t\t// hash to the latest version if the translation was previously in sync with the\n\t\t\t// base language.\n\t\t\tconst baseValueDidChange = newBaseValue !== previousBaseValue\n\t\t\tconst shouldUpdateHashToLatest = localizedValue.hash === previousBaseValueHash && baseValueDidChange\n\n\t\t\tif (!localizedValue.value) {\n\t\t\t\tif (shouldUpdateHashToLatest) {\n\t\t\t\t\tupdatedLocalizedValue[localeId] = { ...localizedValue, hash: newBaseValueHash }\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tupdatedLocalizedValue[localeId] = localizedValue\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst newLocalizedValue = updateModuleIdentifiersInCollectionItemRichTextTreeValue(localizedValue.value, replacer)\n\n\t\t\tupdatedLocalizedValue[localeId] = {\n\t\t\t\t...localizedValue,\n\t\t\t\tvalue: newLocalizedValue,\n\t\t\t\thash: shouldUpdateHashToLatest ? newBaseValueHash : localizedValue.hash,\n\t\t\t}\n\t\t}\n\t}\n\n\tif (controlProp.value === newBaseValue && isEqual(controlProp.valueLocalized, updatedLocalizedValue)) {\n\t\treturn controlProp\n\t}\n\n\tconst updatedControlProp: RichTextControlProp = {\n\t\t...controlProp,\n\t\tvalue: newBaseValue,\n\t}\n\n\tif (updatedLocalizedValue) {\n\t\tupdatedControlProp.valueLocalized = updatedLocalizedValue\n\t}\n\n\treturn updatedControlProp\n}\n\nexport function getModuleIdentifierUpdateForCollectionItem(\n\titemNode: CollectionItemNode,\n\treplacer: ModuleIdentifierReplacer,\n) {\n\tconst controlProps = itemNode.getControlProps()\n\tconst update: Partial<CollectionItemNode> = {}\n\n\tfor (const [key, controlProp] of Object.entries(controlProps)) {\n\t\tif (isRichTextControlProp(controlProp)) {\n\t\t\tconst updatedControlProp = updateModuleIdentifiersInRichTextControlProp(controlProp, replacer)\n\t\t\tif (updatedControlProp === controlProp) continue\n\t\t\tupdate[prefixControlPropKey(key)] = updatedControlProp\n\t\t\tcontinue\n\t\t}\n\n\t\tif (\n\t\t\tcontrolProp.type === ControlType.VectorSetItem &&\n\t\t\tisString(controlProp.value) &&\n\t\t\tisModuleExportIdentifier(controlProp.value)\n\t\t) {\n\t\t\tconst newValue = replacer(controlProp.value)\n\t\t\tif (!newValue) continue\n\n\t\t\tupdate[prefixControlPropKey(key)] = { ...controlProp, value: newValue }\n\t\t}\n\t}\n\n\treturn Object.keys(update).length > 0 ? update : undefined\n}\n\n/**\n * This function will iterate over all collection items in all collections and\n * replace module references (from) with a new module reference (to). This will\n * trigger the collections modules to regenerate.\n *\n * Note: this operation could get quite heavy as its operating over nested\n * structures and on large sites there can be hundreds of collection items. In\n * the future we may want to consider keeping track of which collection items\n * have module references or something like that.\n */\nexport function replaceModuleIdentifierInCollections(\n\ttree: CanvasTree,\n\tfromIdentifier: ModuleExportIdentifierString,\n\ttoIdentifier: ModuleExportIdentifierString,\n) {\n\t// FIXME If CMS Node will ever become shallow this code needs to be checked/updated\n\tconst contentManagementNode = getContentManagementNode(tree)?.loaded\n\tif (!contentManagementNode) return\n\n\tconst replacer = getModuleIdentifierReplacer(fromIdentifier, toIdentifier)\n\n\tfor (const collectionNode of contentManagementNode.children) {\n\t\tfor (const itemNode of collectionNode.getUnsortedChildren()) {\n\t\t\tconst update = getModuleIdentifierUpdateForCollectionItem(itemNode, replacer)\n\t\t\tif (update) itemNode.set(update)\n\t\t}\n\t}\n}\n\nexport function collectionItemHasModule(node: CollectionItemNode, identifier: ModuleExportIdentifierString) {\n\tconst controlProps = node.getControlProps()\n\n\tfor (const controlProp of Object.values(controlProps)) {\n\t\tif (isRichTextControlProp(controlProp)) {\n\t\t\tif (richTextTreeValueHasModule(controlProp.value, identifier)) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif (controlProp.valueLocalized) {\n\t\t\t\tfor (const localeId of Object.keys(controlProp.valueLocalized)) {\n\t\t\t\t\tconst localizedValue = controlProp.valueLocalized[localeId]\n\t\t\t\t\tif (localizedValue?.value && richTextTreeValueHasModule(localizedValue.value, identifier)) return true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (controlProp.type === ControlType.VectorSetItem && controlProp.value === identifier) return true\n\t}\n\n\treturn false\n}\n\nexport function someCollectionHasModule(tree: CanvasTree, identifier: ModuleExportIdentifierString) {\n\t// FIXME If CMS Node will ever become shallow this code needs to be checked/updated\n\tconst contentManagementNode = getContentManagementNode(tree)?.loaded\n\tif (!contentManagementNode) return false\n\n\tfor (const collectionNode of contentManagementNode.children) {\n\t\tfor (const itemNode of collectionNode.getUnsortedChildren()) {\n\t\t\tif (collectionItemHasModule(itemNode, identifier)) return true\n\t\t}\n\t}\n\n\treturn false\n}\n\nexport function getModuleIdentifiersForCollection(collectionNode: CollectionNode) {\n\tconst moduleIdentifiers: Set<ModuleExportIdentifierString> = new Set()\n\tconst validVariableIds = new Set(collectionNode.variables.filter(isVariableDefinition).map(variable => variable.id))\n\n\tfor (const itemNode of collectionNode.getUnsortedChildren()) {\n\t\tconst identifiers = getModuleIdentifiersForCollectionItem(itemNode, validVariableIds)\n\n\t\tfor (const identifier of identifiers) {\n\t\t\tmoduleIdentifiers.add(identifier)\n\t\t}\n\t}\n\n\treturn [...moduleIdentifiers]\n}\n\nexport function getModuleIdentifiersForCollectionItem(itemNode: CollectionItemNode, validVariableIds?: Set<string>) {\n\tconst moduleIdentifiers: Set<ModuleExportIdentifierString> = new Set()\n\tconst controlProps = itemNode.getControlProps()\n\n\tfor (const [key, controlProp] of Object.entries(controlProps)) {\n\t\tif (validVariableIds && !validVariableIds.has(key)) continue\n\n\t\tif (isRichTextControlProp(controlProp)) {\n\t\t\tfor (const componentIdentifier of getModuleIdentifiersForRichTextTreeValue(controlProp.value)) {\n\t\t\t\tmoduleIdentifiers.add(componentIdentifier)\n\t\t\t}\n\n\t\t\tif (controlProp.valueLocalized) {\n\t\t\t\tfor (const localeId of Object.keys(controlProp.valueLocalized)) {\n\t\t\t\t\tconst localizedValue = controlProp.valueLocalized[localeId]\n\t\t\t\t\tif (!localizedValue?.value) continue\n\n\t\t\t\t\tfor (const componentIdentifier of getModuleIdentifiersForRichTextTreeValue(\n\t\t\t\t\t\tlocalizedValue.value,\n\t\t\t\t\t\t\"collectionControlPropLocalized\",\n\t\t\t\t\t)) {\n\t\t\t\t\t\tmoduleIdentifiers.add(componentIdentifier)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tcontrolProp.type === ControlType.VectorSetItem &&\n\t\t\tisString(controlProp.value) &&\n\t\t\tisModuleExportIdentifier(controlProp.value)\n\t\t) {\n\t\t\tmoduleIdentifiers.add(controlProp.value)\n\t\t}\n\t}\n\n\treturn [...moduleIdentifiers]\n}\n\nexport function editInCMS(\n\tengine: VekterEngine,\n\tdataIdentifier: ModuleExportIdentifierString,\n\titemIdentifier?: MaybeNodeID,\n) {\n\tconst collection = getCollectionForIdentifier(engine.tree, dataIdentifier)\n\tif (!collection) return\n\n\tconst selectedCollectionItem = itemIdentifier ?? collection.getUnsortedChildren()[0]\n\n\tengine.stores.scopeStore.select(CONTENT_MANAGEMENT_ID, { keepHistory: false })\n\tengine.stores.selectionStore.set(selectedCollectionItem ?? collection)\n}\n", "import type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, isModuleExportIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCodeComponentNode,\n\tisCollectionItemNode,\n\tisShaderNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { WithCodeComponent } from \"document/models/CanvasTree/traits/WithCodeComponent.ts\"\nimport type { WithCodeOverride } from \"document/models/CanvasTree/traits/WithCodeOverride.ts\"\nimport { withCodeOverride } from \"document/models/CanvasTree/traits/WithCodeOverride.ts\"\nimport type { WithCodeOverridesExperiment } from \"document/models/CanvasTree/traits/WithCodeOverrides.ts\"\nimport { withCodeOverridesExperiment } from \"document/models/CanvasTree/traits/WithCodeOverrides.ts\"\nimport type { WithCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { withCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport {\n\ttype WithVariables,\n\tisVectorSetItemVariableInitialValue,\n\twithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport type { WithShader } from \"../document/models/CanvasTree/traits/WithShader.ts\"\nimport { getModuleIdentifierUpdateForCollectionItem, getModuleIdentifiersForCollectionItem } from \"./collectionUtils.ts\"\n\nfunction isValid(value: string | undefined): value is ModuleExportIdentifierString {\n\tif (!value) return false\n\tconst parsed = parseModuleIdentifier(value)\n\tif (!parsed) return false\n\treturn parsed.kind === \"externalModuleExport\" || parsed.kind === \"localModuleExport\"\n}\n\n/** Returns all module identifiers that are found on a node. */\nexport function forEachModuleIdentifierOfNode(\n\tnode: CanvasNode,\n\tcallback: (identifier: ModuleExportIdentifierString) => void,\n) {\n\tif (isCodeComponentNode(node) && isValid(node.codeComponentIdentifier)) {\n\t\tcallback(node.codeComponentIdentifier)\n\t}\n\tif (withCollectionDataSource(node) && node.dataIdentifier) {\n\t\tcallback(node.dataIdentifier)\n\t}\n\tif (withCodeOverride(node) && isValid(node.codeOverrideIdentifier)) {\n\t\tcallback(node.codeOverrideIdentifier)\n\t}\n\tif (withCodeOverridesExperiment(node)) {\n\t\tnode.codeOverrides?.forEach(override => {\n\t\t\tcallback(override.identifier)\n\t\t})\n\t}\n\tif (isCollectionItemNode(node)) {\n\t\tgetModuleIdentifiersForCollectionItem(node).forEach(callback)\n\t}\n\tif (isShaderNode(node) && isValid(node.shaderModuleIdentifier)) {\n\t\tcallback(node.shaderModuleIdentifier)\n\t}\n\tif (withVariables(node)) {\n\t\tfor (const variable of node.variables) {\n\t\t\tif (variable.type === \"controlReference\") {\n\t\t\t\tif (isValid(variable.entityIdentifier)) {\n\t\t\t\t\tcallback(variable.entityIdentifier)\n\t\t\t\t}\n\t\t\t} else if (variable.type === ControlType.VectorSetItem) {\n\t\t\t\tconst { initialValue } = variable\n\t\t\t\tif (isVectorSetItemVariableInitialValue(initialValue) && isValid(initialValue.identifier)) {\n\t\t\t\t\tcallback(initialValue.identifier)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function generateModuleIdentifierUpdateForNode<T extends CanvasNode>(\n\tnode: T,\n\t/** Return a string to update the module identifier. */\n\tgetUpdatedModuleIdentifier: (identifier: ModuleExportIdentifierString) => ModuleExportIdentifierString | undefined,\n): Partial<T> | undefined {\n\tconst update: Partial<\n\t\tWithCodeComponent &\n\t\t\tWithCollectionDataSource &\n\t\t\tWithCodeOverride &\n\t\t\tWithCodeOverridesExperiment &\n\t\t\tWithShader &\n\t\t\tWithVariables\n\t> = {}\n\n\tif (isCodeComponentNode(node) && isValid(node.codeComponentIdentifier)) {\n\t\tconst codeComponentIdentifier = getUpdatedModuleIdentifier(node.codeComponentIdentifier)\n\t\tif (codeComponentIdentifier) update.codeComponentIdentifier = codeComponentIdentifier\n\t}\n\tif (withCollectionDataSource(node) && node.dataIdentifier) {\n\t\tconst dataIdentifier = getUpdatedModuleIdentifier(node.dataIdentifier)\n\t\tif (dataIdentifier) {\n\t\t\tassert(isModuleExportIdentifier(dataIdentifier))\n\t\t\tupdate.dataIdentifier = dataIdentifier\n\t\t}\n\t}\n\tif (withCodeOverride(node) && isValid(node.codeOverrideIdentifier)) {\n\t\tconst codeOverrideIdentifier = getUpdatedModuleIdentifier(node.codeOverrideIdentifier)\n\t\tif (codeOverrideIdentifier) {\n\t\t\tupdate.codeOverrideIdentifier = codeOverrideIdentifier\n\t\t}\n\t}\n\tif (withCodeOverridesExperiment(node) && node.codeOverrides) {\n\t\tlet shouldBeUpdated = false\n\t\tconst codeOverrides = node.codeOverrides.map(override => {\n\t\t\tconst identifier = getUpdatedModuleIdentifier(override.identifier)\n\t\t\tif (!identifier) return override\n\t\t\tshouldBeUpdated = true\n\t\t\treturn { ...override, identifier }\n\t\t})\n\t\tif (shouldBeUpdated) {\n\t\t\tupdate.codeOverrides = codeOverrides\n\t\t}\n\t}\n\tif (isCollectionItemNode(node)) {\n\t\tconst itemNodeUpdate = getModuleIdentifierUpdateForCollectionItem(node, getUpdatedModuleIdentifier)\n\t\tif (itemNodeUpdate) Object.assign(update, itemNodeUpdate)\n\t}\n\tif (isShaderNode(node) && isValid(node.shaderModuleIdentifier)) {\n\t\tconst shaderModuleIdentifier = getUpdatedModuleIdentifier(node.shaderModuleIdentifier)\n\t\tif (shaderModuleIdentifier) {\n\t\t\tupdate.shaderModuleIdentifier = shaderModuleIdentifier\n\t\t}\n\t}\n\tif (withVariables(node)) {\n\t\tlet shouldUpdate = false\n\t\tconst variables = node.variables.map(variable => {\n\t\t\tif (variable.type === \"controlReference\") {\n\t\t\t\tif (!isValid(variable.entityIdentifier)) return variable\n\n\t\t\t\tconst entityIdentifier = getUpdatedModuleIdentifier(variable.entityIdentifier)\n\t\t\t\tif (!entityIdentifier) return variable\n\n\t\t\t\tshouldUpdate = true\n\t\t\t\treturn { ...variable, entityIdentifier }\n\t\t\t}\n\n\t\t\tif (variable.type === ControlType.VectorSetItem) {\n\t\t\t\tif (!isVectorSetItemVariableInitialValue(variable.initialValue)) return variable\n\t\t\t\tif (!isValid(variable.initialValue.identifier)) return variable\n\n\t\t\t\tconst newIdentifier = getUpdatedModuleIdentifier(variable.initialValue.identifier)\n\t\t\t\tif (!newIdentifier) return variable\n\n\t\t\t\tshouldUpdate = true\n\t\t\t\treturn {\n\t\t\t\t\t...variable,\n\t\t\t\t\tinitialValue: { ...variable.initialValue, identifier: newIdentifier },\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn variable\n\t\t})\n\n\t\tif (shouldUpdate) {\n\t\t\tupdate.variables = variables\n\t\t}\n\t}\n\n\tconst noUpdate = Object.keys(update).length === 0\n\tif (noUpdate) return undefined\n\n\treturn update as Partial<T>\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ExternalModuleExportIdentifier, GlobalModuleId, ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport {\n\tassert,\n\texternalModuleIdentifier,\n\tisExternalModuleIdentifier,\n\tisLocalModuleIdentifier,\n\tparseModuleIdentifier,\n\ttoLocalIdentifier,\n} from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { getTextStylePresetBreakpoints } from \"document/components/chrome/properties/panels/utils/getTextStylePresetBreakpoints.ts\"\nimport type {\n\tCanvasNode,\n\tCanvasTree,\n\tCollectionNode,\n\tNodeID,\n\tRichTextNode,\n\tScopeNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type { InlineCodeStylePresetNode } from \"document/models/CanvasTree/nodes/InlineCodeStylePresetNode.ts\"\nimport type { LinkStylePresetNode } from \"document/models/CanvasTree/nodes/LinkStylePresetNode.ts\"\nimport { PresetsListNode } from \"document/models/CanvasTree/nodes/PresetsListNode.ts\"\nimport type { TextStylePresetNode } from \"document/models/CanvasTree/nodes/TextStylePresetNode.ts\"\nimport { detachTextStylePresetsFromBreakpoints } from \"document/models/CanvasTree/nodes/utils/detachTextStylePresetsForBreakpoints.ts\"\nimport { isStylePresetPrimaryNode } from \"document/models/CanvasTree/nodes/utils/isStylePresetNode.ts\"\nimport {\n\tisBlockquoteStylePresetNode,\n\tisCollectionNode,\n\tisImageStylePresetNode,\n\tisInlineCodeStylePresetNode,\n\tisLinkStylePresetNode,\n\tisRichTextNode,\n\tisTextStylePresetBreakpointNode,\n\tisTextStylePresetNode,\n\tisTextStylePresetPrimaryNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport type { WithSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport { withSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport type { WithStylePresetsKey } from \"document/models/CanvasTree/traits/WithStylePresets.ts\"\nimport {\n\tinlineCodeStylePresetKeys,\n\tlinkStylePresetKeys,\n\tstylePresetKeys,\n\ttextStylePresetKeys,\n} from \"document/models/CanvasTree/traits/WithStylePresets.ts\"\nimport type { IsReplica, ReplicaOverrides } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { getMasterAncestor, isReplica } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isAnyCollectionReferencingVariableDefinition } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isBreakpointVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isTokenCSSVariable, tokenIdFromCSSVariable } from \"document/models/CanvasTree/utils/tokens.ts\"\nimport { isConicGradient } from \"document/models/ConicGradientClass.ts\"\nimport { isLinearGradient } from \"document/models/LinearGradientClass.ts\"\nimport { isRadialGradient } from \"document/models/RadialGradientClass.ts\"\nimport { isBoxShadow } from \"document/models/Shadow.ts\"\nimport { isBorderValues } from \"document/models/controlProps/BorderControlPropValue.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport type { Mutable } from \"utils/Mutable.ts\"\nimport { forEachModuleIdentifierOfNode, generateModuleIdentifierUpdateForNode } from \"utils/moduleIdentifierForNode.ts\"\nimport { isArray } from \"utils/typeChecks.ts\"\nimport { vectorSetIdentifiersForClipboard } from \"utils/vectorSets.ts\"\nimport { v4 as uuid } from \"uuid\"\nimport type { ClipboardModuleData, SerializableMap } from \"./helpers/types.ts\"\n\ninterface PasteStylePresets<PresetNode> extends RemapStylePresetOptions<PresetNode> {\n\treadonly engine: VekterEngine\n\treadonly node: RichTextNode\n\treadonly breakpointVariantIds?: Set<NodeID>\n\tshouldDetachTextStyles?: boolean\n}\n\ninterface RemapStylePresetOptions<PresetNode> {\n\treadonly pastedPresetMap: Map<string, TextStylePresetNode | LinkStylePresetNode | InlineCodeStylePresetNode>\n\treadonly stylePresetNodes?: PresetNode[]\n\tshouldCreateNewPresets?: boolean\n\t/** If a preset with the same ID already exists in the tree, reuse it regardless of the values. */\n\treusePresetWithSameId?: boolean\n}\n\n/**\n * Collect and serialize text and link style preset nodes for a rich text node.\n * If the presets have any related breakpoint node, it will also collect those.\n */\nexport function collectStylePresetNodes(tree: CanvasTree, presetMap: SerializableMap, node: CanvasNode) {\n\tif (!isRichTextNode(node)) return\n\n\tconst presets = node.getStylePresetsForCodeGeneration(tree)\n\n\tfor (const preset of presets) {\n\t\tconst breakpointNodes = tree.getNodes(preset.cache.replicaInstances ?? [])\n\n\t\tfor (const breakpointNode of breakpointNodes) {\n\t\t\tpresetMap[breakpointNode.id] ??= breakpointNode.toJS()\n\t\t}\n\n\t\tpresetMap[preset.id] ??= preset.toJS()\n\t}\n}\n\nfunction remapNodeStylePresets<PresetNode extends CanvasNode>(\n\tnode: RichTextNode,\n\tstylePresetKeys: readonly WithStylePresetsKey[],\n\tcallback: (presetId: string) => PresetNode | undefined,\n) {\n\tfor (const key of stylePresetKeys) {\n\t\tconst presetId = node[key]\n\t\tif (!presetId) continue\n\n\t\tconst replacedPreset = callback(presetId)\n\t\tif (!replacedPreset) continue\n\t\tif (replacedPreset.id === presetId) continue\n\n\t\tnode.set({ [key]: replacedPreset.id })\n\t}\n}\n\n/** Text Style Preset Helpers */\n\nexport function pasteTextStylePresets({\n\tengine,\n\tnode,\n\tpastedPresetMap,\n\tstylePresetNodes,\n\tshouldDetachTextStyles,\n\tbreakpointVariantIds,\n\tshouldCreateNewPresets,\n\treusePresetWithSameId,\n}: PasteStylePresets<TextStylePresetNode>) {\n\tif (!stylePresetNodes) return\n\n\tconst options: RemapTextStylePresetOptions = {\n\t\tpastedPresetMap,\n\t\tstylePresetNodes,\n\t\tshouldCreateNewPresets,\n\t\treusePresetWithSameId,\n\t}\n\n\tconst remapTextStylePresets = (presetId: string) => remapTextStylePresetFromNode(engine, presetId, options)\n\tremapNodeStylePresets(node, textStylePresetKeys, remapTextStylePresets)\n\tnode.remapTextStylePresets(remapTextStylePresets)\n\n\tif (!shouldDetachTextStyles) return\n\n\tconst primaryNode = getMasterAncestor(node)\n\tconst groundNode = engine.tree.getGroundNodeFor(node)\n\n\t// Detach all the presets on the pasted rich text node. This is done by finding\n\t// all preset IDs on the node and getting matching preset in the pasted info.\n\tfor (const presetId of node.getStylePresetIdsForCodeGeneration()) {\n\t\tconst presetNode = stylePresetNodes.find(preset => preset.id === presetId)\n\n\t\tif (!presetNode || !isTextStylePresetPrimaryNode(presetNode)) continue\n\n\t\tconst presetBreakpoints = getTextStylePresetBreakpoints(stylePresetNodes, presetNode)\n\n\t\tif (primaryNode) {\n\t\t\tdetachTextStylePresetsFromBreakpoints(engine.tree, primaryNode, node, presetBreakpoints, presetNode)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (breakpointVariantIds?.has(groundNode.id) && withSize(groundNode)) {\n\t\t\tconst presetBreakpointToDetach =\n\t\t\t\tpresetBreakpoints.findLast(presetBreakpoint => (presetBreakpoint.breakpointWidth ?? 0) > groundNode.width) ??\n\t\t\t\tpresetNode\n\n\t\t\tnode.detachTextStylePreset(presetBreakpointToDetach, false)\n\t\t\tcontinue\n\t\t}\n\n\t\tnode.detachTextStylePreset(presetNode, false)\n\t}\n}\n\ntype RemapTextStylePresetOptions = RemapStylePresetOptions<TextStylePresetNode>\n\nfunction remapTextStylePresetFromNode(\n\tengine: VekterEngine,\n\tpresetId: string,\n\t{ pastedPresetMap, stylePresetNodes, shouldCreateNewPresets, reusePresetWithSameId }: RemapTextStylePresetOptions,\n): TextStylePresetNode | undefined {\n\tif (!stylePresetNodes) return\n\n\tconst sourcePreset = stylePresetNodes.find(preset => preset.id === presetId)\n\tif (!sourcePreset) return\n\n\t// Check if the tree contains a preset with the same ID, and if the value is the same.\n\tconst existingPreset = engine.tree.get(presetId)\n\n\tif (isTextStylePresetPrimaryNode(existingPreset) && (reusePresetWithSameId || existingPreset.equals(sourcePreset))) {\n\t\tpastedPresetMap.set(presetId, existingPreset)\n\t\treturn existingPreset\n\t}\n\n\tif (!shouldCreateNewPresets) return\n\n\t// If we didn't find an identical preset in the tree, check all the existing presets and see if\n\t// we find one with identical values.\n\tconst listNode = PresetsListNode.ensure(engine.tree)\n\tconst targetPresetByProps = listNode.getTextStylePresets().find(child => child.equals(sourcePreset))\n\tif (targetPresetByProps && isTextStylePresetPrimaryNode(targetPresetByProps)) {\n\t\tpastedPresetMap.set(presetId, targetPresetByProps)\n\t\treturn targetPresetByProps\n\t}\n\n\t// If we didn't find an equivalent preset, create a new one.\n\tconst clonedPreset = existingPreset ? sourcePreset.clone() : sourcePreset.cloneWithIds()\n\tengine.tree.insertNode(clonedPreset, listNode.id)\n\tpastedPresetMap.set(presetId, clonedPreset)\n\t// Find all the breakpoint presets too\n\tconst sourcePresetBreakpoints = stylePresetNodes.filter(preset => preset.originalid === presetId)\n\tfor (const breakpointPreset of sourcePresetBreakpoints) {\n\t\t// Check if the tree contains the current preset.\n\t\tconst targetBreakpointPresetById = engine.tree.get(presetId)\n\t\tconst hasTargetBreakpointPresetById =\n\t\t\ttargetBreakpointPresetById && isTextStylePresetBreakpointNode(targetBreakpointPresetById)\n\t\tif (hasTargetBreakpointPresetById && targetBreakpointPresetById.equals(breakpointPreset)) {\n\t\t\tpastedPresetMap.set(presetId, targetBreakpointPresetById)\n\t\t\tcontinue\n\t\t}\n\t\tconst clonedBreakpointPreset = targetBreakpointPresetById\n\t\t\t? breakpointPreset.clone()\n\t\t\t: breakpointPreset.cloneWithIds()\n\t\tengine.tree.insertNode(clonedBreakpointPreset, listNode.id)\n\t\tpastedPresetMap.set(presetId, clonedBreakpointPreset)\n\t}\n\n\treturn clonedPreset\n}\n\n/** Link Style Preset Helpers */\n\nexport function pasteLinkStylePresets({\n\tengine,\n\tnode,\n\tpastedPresetMap,\n\tstylePresetNodes,\n}: PasteStylePresets<LinkStylePresetNode>) {\n\tif (!stylePresetNodes) return\n\n\tconst options: RemapLinkStylePresets = {\n\t\tpastedPresetMap,\n\t\tstylePresetNodes,\n\t}\n\n\tconst remapLinkStylePresets = (presetId: string) => remapLinkStylePresetFromNode(engine, presetId, options)\n\tremapNodeStylePresets(node, linkStylePresetKeys, remapLinkStylePresets)\n\tnode.remapLinkStylePresets(remapLinkStylePresets)\n}\n\ntype RemapLinkStylePresets = RemapStylePresetOptions<LinkStylePresetNode>\n\nfunction remapLinkStylePresetFromNode(\n\tengine: VekterEngine,\n\tpresetId: string,\n\t{ pastedPresetMap, stylePresetNodes }: RemapLinkStylePresets,\n) {\n\tif (!stylePresetNodes) return\n\n\tconst sourcePreset = stylePresetNodes.find(preset => preset.id === presetId)\n\tif (!sourcePreset) return\n\n\tif (!isLinkStylePresetNode(sourcePreset)) return\n\n\t// Check if the tree contains the current preset.\n\tconst targetPresetById = engine.tree.get(presetId)\n\tconst hasTargetPresetById = targetPresetById && isLinkStylePresetNode(targetPresetById)\n\tif (hasTargetPresetById && targetPresetById.equals(sourcePreset)) {\n\t\tpastedPresetMap.set(presetId, targetPresetById)\n\t\treturn targetPresetById\n\t}\n\n\t// Check all the existing presets and see is we have an equivalent.\n\tconst listNode = PresetsListNode.ensure(engine.tree)\n\tconst targetPresetByProps = listNode.getLinkStylePresets().find(child => child.equals(sourcePreset))\n\tif (targetPresetByProps && isLinkStylePresetNode(targetPresetByProps)) {\n\t\tpastedPresetMap.set(presetId, targetPresetByProps)\n\t\treturn targetPresetByProps\n\t}\n\n\t// At this point we just create a new one.\n\tconst clonedPreset = targetPresetById ? sourcePreset.clone() : sourcePreset.cloneWithIds()\n\tengine.tree.insertNode(clonedPreset, listNode.id)\n\tpastedPresetMap.set(presetId, clonedPreset)\n\n\treturn clonedPreset\n}\n\n/** Inline Code Style Preset Helpers */\n\nexport function pasteInlineCodeStylePresets({\n\tengine,\n\tnode,\n\tpastedPresetMap,\n\tstylePresetNodes,\n}: PasteStylePresets<InlineCodeStylePresetNode>) {\n\tif (!stylePresetNodes) return\n\n\tconst options: RemapInlineCodeStylePresets = {\n\t\tpastedPresetMap,\n\t\tstylePresetNodes,\n\t}\n\n\tconst remapInlineCodeStylePresets = (presetId: string) =>\n\t\tremapInlineCodeStylePresetFromNode(engine, presetId, options)\n\tremapNodeStylePresets(node, inlineCodeStylePresetKeys, remapInlineCodeStylePresets)\n\tnode.remapInlineCodeStylePresets(remapInlineCodeStylePresets)\n}\n\ntype RemapInlineCodeStylePresets = RemapStylePresetOptions<InlineCodeStylePresetNode>\n\nfunction remapInlineCodeStylePresetFromNode(\n\tengine: VekterEngine,\n\tpresetId: string,\n\t{ pastedPresetMap, stylePresetNodes }: RemapInlineCodeStylePresets,\n) {\n\tif (!stylePresetNodes) return\n\n\tconst sourcePreset = stylePresetNodes.find(preset => preset.id === presetId)\n\tif (!sourcePreset) return\n\n\tif (!isInlineCodeStylePresetNode(sourcePreset)) return\n\n\t// Check if the tree contains the current preset.\n\tconst targetPresetById = engine.tree.get(presetId)\n\tconst hasTargetPresetById = targetPresetById && isInlineCodeStylePresetNode(targetPresetById)\n\tif (hasTargetPresetById && targetPresetById.equals(sourcePreset)) {\n\t\tpastedPresetMap.set(presetId, targetPresetById)\n\t\treturn targetPresetById\n\t}\n\n\t// Check all the existing presets and see is we have an equivalent.\n\tconst listNode = PresetsListNode.ensure(engine.tree)\n\tconst targetPresetByProps = listNode.getInlineCodeStylePresets().find(child => child.equals(sourcePreset))\n\tif (targetPresetByProps && isInlineCodeStylePresetNode(targetPresetByProps)) {\n\t\tpastedPresetMap.set(presetId, targetPresetByProps)\n\t\treturn targetPresetByProps\n\t}\n\n\t// At this point we just create a new one.\n\tconst clonedPreset = targetPresetById ? sourcePreset.clone() : sourcePreset.cloneWithIds()\n\tengine.tree.insertNode(clonedPreset, listNode.id)\n\tpastedPresetMap.set(presetId, clonedPreset)\n\n\treturn clonedPreset\n}\n\nexport function getWebPagePropsForCopiedBreakpoint(scopeNode: ScopeNode) {\n\tif (!isWebPageNode(scopeNode)) return\n\n\treturn {\n\t\tid: scopeNode.id,\n\t\tpagePath: scopeNode.pagePath,\n\t\twebMetadata: scopeNode.webMetadata,\n\t\tdataIdentifier: scopeNode.dataIdentifier,\n\t}\n}\n\nexport function collectClipboardModuleData(\n\tmodulesStore: ModulesStore,\n\ttree: CanvasTree,\n\troot: CanvasNode,\n\tscopeNode: ScopeNode | null,\n\tcollectedCollections: CollectedCollections,\n): {\n\tmoduleData: ClipboardModuleData\n} {\n\tconst moduleData: ClipboardModuleData = {}\n\tconst seenVectorSets = new Set<GlobalModuleId>()\n\n\tfunction processNode(node: CanvasNode) {\n\t\tforEachModuleIdentifierOfNode(node, identifier => {\n\t\t\t// If we stored the collection in the clipboard data there's no need to add its module\n\t\t\t// data.\n\t\t\tif (collectedCollections.has(identifier)) return\n\n\t\t\tconst parsedIdentifier = getParsedExternalModuleIdentifier(modulesStore, identifier)\n\t\t\tif (parsedIdentifier) moduleData[identifier] = parsedIdentifier\n\n\t\t\t// If the identifier is for a Vector, we add all the vector set items to the clipboard\n\t\t\t// data.\n\t\t\tconst vectorInfo = vectorSetIdentifiersForClipboard(identifier, tree, modulesStore, seenVectorSets)\n\t\t\tif (vectorInfo) Object.assign(moduleData, vectorInfo)\n\t\t})\n\t}\n\n\tfor (const node of root.walk()) {\n\t\tprocessNode(node)\n\t}\n\n\tif (isWebPageNode(scopeNode)) processNode(scopeNode)\n\n\treturn { moduleData }\n}\n\nfunction getParsedExternalModuleIdentifier(\n\tmodulesStore: ModulesStore,\n\tidentifier: string,\n): ExternalModuleExportIdentifier | undefined {\n\tconst parsedId = parseModuleIdentifier(identifier)\n\n\tif (parsedId && parsedId.kind === \"localModuleExport\") {\n\t\tconst persistedModule = modulesStore.getPersistedModuleByLocalId(parsedId.localId)\n\t\tif (!persistedModule) return undefined\n\t\tassert(persistedModule.files.module, \"expected module typed file in persisted module\")\n\t\treturn externalModuleIdentifier(\n\t\t\tpersistedModule.id,\n\t\t\tpersistedModule.saveId,\n\t\t\tpersistedModule.files.module,\n\t\t\tparsedId.exportSpecifier,\n\t\t)\n\t}\n\n\tif (parsedId && parsedId.kind === \"externalModuleExport\") {\n\t\treturn parsedId\n\t}\n}\n\nfunction getReplacementIdentifier(\n\tmodulesStore: ModulesStore,\n\tidentifier: string,\n\tparsedExternalModuleIdentifier: ExternalModuleExportIdentifier,\n): ModuleExportIdentifierString | null {\n\t// Parse the identifier as it was copied in the source project.\n\tconst parsedId = parseModuleIdentifier(identifier)\n\n\tif (isLocalModuleIdentifier(parsedId)) {\n\t\t// FIXME: Wait for the modules store instead of throwing.\n\t\tassert(modulesStore.initialized, \"Cannot paste modules before modulesStore has been initialized.\")\n\n\t\t// Since this is a local module identifier, we may need to replace it with an external\n\t\t// module reference so that Framer can load the module correctly. We need to do this if\n\t\t// the module was copied from another project.\n\n\t\t// Attempt to find the module in the current project by its local id.\n\t\t// NOTE: It's possible that we find a module even if we're in a different project because\n\t\t//       local ids are not globally unique and may overlap between projects.\n\t\tconst moduleId = modulesStore.getPersistedModuleByLocalId(parsedId.localId)?.id\n\t\t// Because of the above, we only consider the module local to this project if the global\n\t\t// module id matches between the copied module and any local one we found in this project.\n\t\tconst isLocalModule = moduleId === parsedExternalModuleIdentifier.moduleId\n\t\t// Return early if the module is from the same project.\n\t\tif (isLocalModule) return null\n\n\t\treturn parsedExternalModuleIdentifier.value\n\t}\n\n\tif (isExternalModuleIdentifier(parsedId) && parsedId.kind === \"externalModuleExport\") {\n\t\tconst localId = modulesStore.getPersistedModuleByGlobalId(parsedId.moduleId)?.localId\n\t\t// If the component is not originally coming from this project then it must already have its codeComponentIdentifier\n\t\t// set in the externalIdentifier format, so we don't need to replace it, and we can early return here.\n\t\tif (!localId) return null\n\n\t\t// This handles situations when we insert a component from another project,\n\t\t// but that component actually originates (has its primary) from the local project.\n\t\treturn toLocalIdentifier(parsedId, localId).value\n\t}\n\n\treturn null\n}\n\nfunction replaceNode<T extends CanvasNode>(\n\ttree: CanvasTree,\n\tparentId: NodeID,\n\tchildIndex: number,\n\tnode: T,\n\tupdate: Partial<T>,\n) {\n\tconst replacementNode = node.cloneWithIds()\n\treplacementNode.set(update)\n\ttree.removeNode(node)\n\ttree.insertNode(replacementNode, parentId, childIndex)\n}\n\nexport function pasteModules(\n\tcomponentLoader: AnyComponentLoader,\n\tmodulesStore: ModulesStore,\n\tcopyTree: CanvasTree,\n\tmoduleData: ClipboardModuleData | undefined,\n) {\n\tif (!moduleData) return copyTree\n\n\tfor (const descendant of copyTree.root.walk()) {\n\t\tif (!withChildren(descendant)) continue\n\n\t\tdescendant.children.forEach((child, idx) => {\n\t\t\tif (moduleData) {\n\t\t\t\tconst nodeUpdate = generateModuleIdentifierUpdateForNode(child, identifier => {\n\t\t\t\t\tconst parsedExternalModuleIdentifier = moduleData[identifier]\n\t\t\t\t\tif (!parsedExternalModuleIdentifier) return undefined\n\t\t\t\t\tconst replacement = getReplacementIdentifier(modulesStore, identifier, parsedExternalModuleIdentifier)\n\t\t\t\t\treturn replacement ? replacement : undefined\n\t\t\t\t})\n\n\t\t\t\tif (!nodeUpdate) return\n\n\t\t\t\tconst currentChild = copyTree.current(child)\n\t\t\t\tif (!currentChild) return\n\n\t\t\t\treplaceNode(copyTree, descendant.id, idx, currentChild, nodeUpdate)\n\t\t\t}\n\t\t})\n\t}\n\treturn copyTree.commit(componentLoader)\n}\n\nexport function isReplicaWithSize(node: CanvasNode): node is CanvasNode & IsReplica & WithSize {\n\treturn isReplica(node) && withSize(node)\n}\n\nexport function collectOverridesForBreakpoints(\n\ttree: CanvasTree,\n\tbreakpointOverrides: Map<number, ReplicaOverrides>,\n\tcopyNode: CanvasNode,\n) {\n\tconst sourceNode = tree.get(copyNode.id)\n\tif (!sourceNode) return\n\n\tconst masterNode = getMasterAncestor(sourceNode)\n\tif (!masterNode || !isBreakpointVariant(masterNode)) return\n\n\tconst breakpointNodes = tree.getNodes(masterNode.cache.replicaInstances ?? []).filter(isReplicaWithSize)\n\n\tfor (const { width, replicaInfo } of breakpointNodes) {\n\t\tconst overrides = breakpointOverrides.get(width) ?? {}\n\t\tconst nodeOverrides = replicaInfo.overrides[copyNode.id]\n\t\tif (nodeOverrides) {\n\t\t\toverrides[copyNode.id] = nodeOverrides\n\t\t}\n\t\tbreakpointOverrides.set(width, overrides)\n\t}\n\n\t// Add the desktop variant to the breakpoint overrides so we can match the\n\t// width when pasting if it's closest to the target breakpoint.\n\tif (withSize(masterNode) && !breakpointOverrides.get(masterNode.width)) {\n\t\tbreakpointOverrides.set(masterNode.width, {})\n\t}\n}\n\nexport function collectColorTokensFromValue(\n\ttree: CanvasTree,\n\tvalue: unknown,\n\tcolorTokens: SerializableMap,\n\trenamedIds?: Record<string, string>,\n) {\n\tif (!value) return\n\n\tif (isTokenCSSVariable(value)) {\n\t\tconst tokenId = tokenIdFromCSSVariable(value)\n\t\tconst tokenNode = tree.get(tokenId)\n\n\t\tif (tokenNode && !(tokenNode.id in colorTokens)) {\n\t\t\tconst clonedNode = tokenNode.cloneWithIds()\n\t\t\tcolorTokens[clonedNode.id] = clonedNode.toJS()\n\t\t\tif (renamedIds) renamedIds[tokenNode.id] = uuid()\n\t\t}\n\n\t\treturn\n\t}\n\n\tif (isBoxShadow(value)) {\n\t\tcollectColorTokensFromValue(tree, value.color, colorTokens, renamedIds)\n\t\treturn\n\t}\n\n\tif (isLinearGradient(value) || isConicGradient(value) || isRadialGradient(value)) {\n\t\tfor (const colorStop of value.stops) {\n\t\t\tcollectColorTokensFromValue(tree, colorStop.value, colorTokens, renamedIds)\n\t\t}\n\t\treturn\n\t}\n\n\tif (isArray(value)) {\n\t\tfor (const item of value) {\n\t\t\tcollectColorTokensFromValue(tree, item, colorTokens, renamedIds)\n\t\t}\n\t\treturn\n\t}\n\n\tif (isBorderValues(value)) {\n\t\tcollectColorTokensFromValue(tree, value.borderColor, colorTokens, renamedIds)\n\t\treturn\n\t}\n}\n\nexport function collectColorTokenNodes(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tcolorTokens: SerializableMap,\n\trenamedIds?: Record<string, string>,\n) {\n\tfor (const key in node) {\n\t\t// eslint-disable-next-line framer-studio/no-mutable-node-type-operations\n\t\tcollectColorTokensFromValue(tree, node[key as keyof CanvasNode], colorTokens, renamedIds)\n\t}\n\n\tif (isRichTextNode(node)) {\n\t\t// Even text with dynamic content can have color overrides with tokens.\n\t\tconst inlineStyleTokens = node.getInlineStyleTokenVariables()\n\t\tcollectColorTokensFromValue(tree, inlineStyleTokens, colorTokens, renamedIds)\n\n\t\t// If this node is assigned a variable we need to collect the color tokens from the style presets.\n\t\tif (isDynamicValue(node.htmlContent) || isDynamicValue(node.textContent)) {\n\t\t\tcollectColorTokensFromPresets(tree, node, colorTokens, renamedIds)\n\t\t\treturn\n\t\t}\n\n\t\tconst inlinePresets = node.getTextStylePresets(false)\n\n\t\tfor (const presetId of inlinePresets) {\n\t\t\tif (!presetId) continue\n\t\t\tcollectColorTokensFromPreset(tree, presetId, colorTokens, renamedIds)\n\t\t}\n\n\t\tif (node.hasLinks()) {\n\t\t\tconst linkPresets = node.getLinkStylePresets(true)\n\t\t\tfor (const presetId of linkPresets) {\n\t\t\t\tconst preset = tree.getNodeWithTrait(presetId, isLinkStylePresetNode)\n\t\t\t\tif (!preset) continue\n\n\t\t\t\tcollectColorTokensFromLinkPreset(tree, preset, colorTokens, renamedIds)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction collectColorTokensFromPreset(\n\ttree: CanvasTree,\n\tpresetId: string,\n\tcolorTokens: SerializableMap,\n\trenamedIds?: Record<string, string>,\n) {\n\tconst preset = tree.getNodeWithTrait(presetId, isStylePresetPrimaryNode)\n\tif (!preset) return\n\n\tif (isTextStylePresetNode(preset)) {\n\t\tcollectColorTokensFromValue(tree, preset.textColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.textStrokeColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.textDecorationColor, colorTokens, renamedIds)\n\t} else if (isLinkStylePresetNode(preset)) {\n\t\tcollectColorTokensFromLinkPreset(tree, preset, colorTokens, renamedIds)\n\t} else if (isBlockquoteStylePresetNode(preset)) {\n\t\tcollectColorTokensFromValue(tree, preset.textColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.textDecorationColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.textStrokeColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.borderColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.fillColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.lineColor, colorTokens, renamedIds)\n\t} else if (isInlineCodeStylePresetNode(preset)) {\n\t\tcollectColorTokensFromValue(tree, preset.inlineCodeTextColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.inlineCodeFillColor, colorTokens, renamedIds)\n\t\tcollectColorTokensFromValue(tree, preset.borderColor, colorTokens, renamedIds)\n\t} else if (isImageStylePresetNode(preset)) {\n\t\tcollectColorTokensFromValue(tree, preset.borderColor, colorTokens, renamedIds)\n\t}\n}\n\nfunction collectColorTokensFromPresets(\n\ttree: CanvasTree,\n\tnode: RichTextNode,\n\tcolorTokens: SerializableMap,\n\trenamedIds?: Record<string, string>,\n) {\n\tfor (const key of stylePresetKeys) {\n\t\tconst presetId = node[key]\n\t\tif (!presetId) continue\n\n\t\tcollectColorTokensFromPreset(tree, presetId, colorTokens, renamedIds)\n\t}\n}\n\nfunction collectColorTokensFromLinkPreset(\n\ttree: CanvasTree,\n\tpreset: LinkStylePresetNode,\n\tcolorTokens: SerializableMap,\n\trenamedIds?: Record<string, string>,\n) {\n\tcollectColorTokensFromValue(tree, preset.linkTextColor, colorTokens, renamedIds)\n\tcollectColorTokensFromValue(tree, preset.linkTextDecorationColor, colorTokens, renamedIds)\n\tcollectColorTokensFromValue(tree, preset.linkTextBackgroundColor, colorTokens, renamedIds)\n\tcollectColorTokensFromValue(tree, preset.linkHoverTextColor, colorTokens, renamedIds)\n\tcollectColorTokensFromValue(tree, preset.linkHoverTextDecorationColor, colorTokens, renamedIds)\n\tcollectColorTokensFromValue(tree, preset.linkHoverTextBackgroundColor, colorTokens, renamedIds)\n\tcollectColorTokensFromValue(tree, preset.linkCurrentTextColor, colorTokens, renamedIds)\n\tcollectColorTokensFromValue(tree, preset.linkCurrentTextDecorationColor, colorTokens, renamedIds)\n\tcollectColorTokensFromValue(tree, preset.linkCurrentTextBackgroundColor, colorTokens, renamedIds)\n}\n\n/**\n * Adapts a 0%..100% number range into a different range, e.g. 25%..80%\n * used to combine multiple actions with progress reports\n */\nexport function percentRange(percent: number, from: number, to: number): number {\n\tconst total = to - from\n\treturn Math.ceil((percent / 100) * total + from)\n}\n\nexport function unsafeMakeMutable<Obj>(object: Obj) {\n\treturn object as Mutable<Obj>\n}\n\nexport type CollectedCollections = Map<ModuleExportIdentifierString, CollectionNode>\n\nexport function collectCollections(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tcollectedCollections: CollectedCollections,\n): void {\n\tif (hasCollectionDataSource(node)) {\n\t\tconst parsedIdentifier = parseModuleIdentifier(node.dataIdentifier)\n\t\tif (!isLocalModuleIdentifier(parsedIdentifier)) return\n\n\t\tconst collectionNode = tree.getNodeWithTrait(parsedIdentifier.localIdName, isCollectionNode)\n\t\tif (collectionNode) {\n\t\t\tcollectedCollections.set(node.dataIdentifier, collectionNode)\n\t\t\tcollectCollections(tree, collectionNode, collectedCollections)\n\t\t}\n\t}\n\n\tif (isCollectionNode(node)) {\n\t\tfor (const variable of node.variables) {\n\t\t\tif (!isAnyCollectionReferencingVariableDefinition(variable)) continue\n\n\t\t\tconst parsedIdentifier = parseModuleIdentifier(variable.dataIdentifier)\n\t\t\tif (!isLocalModuleIdentifier(parsedIdentifier)) continue\n\n\t\t\tconst collectionNode = tree.getNodeWithTrait(parsedIdentifier.localIdName, isCollectionNode)\n\t\t\tif (!collectionNode) continue\n\n\t\t\tif (collectedCollections.has(variable.dataIdentifier)) continue\n\t\t\tcollectedCollections.set(variable.dataIdentifier, collectionNode)\n\t\t\tcollectCollections(tree, collectionNode, collectedCollections)\n\t\t}\n\t}\n}\n", "import type { CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { RouteSegmentNode } from \"document/models/CanvasTree/nodes/RouteSegmentNode.ts\"\nimport type { RouteSegmentRootNode } from \"document/models/CanvasTree/nodes/RouteSegmentRootNode.ts\"\nimport { getRouteSegmentNodeByWebPageId } from \"./getRouteSegmentNodeByWebPageId.ts\"\n\nexport function getWebPagePositionInParent(tree: CanvasTree, webPageId: NodeID) {\n\tconst routeSegment = getRouteSegmentNodeByWebPageId(tree, webPageId)\n\tconst routeSegmentParent = tree.get<RouteSegmentRootNode | RouteSegmentNode>(routeSegment?.parentid)\n\treturn routeSegmentParent?.children.findIndex(node => node.id === routeSegment?.id)\n}\n", "import type { ReplicaOverrides } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { updateItemsOrder } from \"./updateItemsOrder.ts\"\nimport type { RenamedIds } from \"./updateNodeConnections.ts\"\n\nexport function remapOverrides(\n\toverrides: ReplicaOverrides,\n\trenamedIds: RenamedIds,\n\tremapItemsOrder = false,\n): ReplicaOverrides {\n\tconst nextOverrides = {}\n\tfor (const key in overrides) {\n\t\tconst value = { ...overrides[key] }\n\n\t\t// Optionally update `node.itemsOrder` to point to the renamed children\n\t\t// in the primary.\n\t\tif (\"itemsOrder\" in value && Array.isArray(value.itemsOrder) && remapItemsOrder) {\n\t\t\tvalue.itemsOrder = updateItemsOrder(value.itemsOrder, renamedIds)\n\t\t}\n\n\t\tnextOverrides[renamedIds.get(key) ?? key] = value\n\t}\n\treturn nextOverrides\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { isEmptyObject, isLocalModuleIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { localModuleIdentifierForStableName } from \"@framerjs/shared/src/moduleIdentifiers.ts\"\nimport { eventsForNode } from \"document/components/chrome/properties/utils/eventActions.ts\"\nimport { isNavigationAction } from \"document/models/CanvasTree/actions/navigationActions.ts\"\nimport { isShowOverlayAction, isShowRelativeOverlayAction } from \"document/models/CanvasTree/actions/overlayActions.ts\"\nimport { isSetVariantAction } from \"document/models/CanvasTree/actions/variantActions.ts\"\nimport type {\n\tAnyNodeUpdate,\n\tCanvasNode,\n\tCanvasTree,\n\tCodeComponentNode,\n\tCollectionItemNode,\n\tNodeID,\n} from \"document/models/CanvasTree/index.ts\"\nimport { randomID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport {\n\tisCodeComponentNode,\n\tisCollectionItemNode,\n\tisCollectionNode,\n\tisDataRepeater,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { getSlotKeys } from \"document/models/CanvasTree/nodes/utils/slotUtils.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { createVariableReference, isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { hasCollectionDataSourceLoader } from \"document/models/CanvasTree/traits/WithCollectionDataSourceLoader.ts\"\nimport { withDragEffect } from \"document/models/CanvasTree/traits/WithDragEffect.ts\"\nimport type { WithFrameEvents } from \"document/models/CanvasTree/traits/WithFrameEvents.ts\"\nimport { withFrameEvents } from \"document/models/CanvasTree/traits/WithFrameEvents.ts\"\nimport { withStyleAppearPageEffect } from \"document/models/CanvasTree/traits/WithStyleAppearEffect.ts\"\nimport { withStyleTransformEffect } from \"document/models/CanvasTree/traits/WithStyleTransformEffect.ts\"\nimport { withTextEffect } from \"document/models/CanvasTree/traits/WithTextEffect.ts\"\nimport { isAnyCollectionReferencingVariableDefinition } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { withVariantAppearPageEffect } from \"document/models/CanvasTree/traits/WithVariantAppearEffect.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport type { WithFormInputEvents } from \"document/models/CanvasTree/traits/forms/WithFormInputEvents.ts\"\nimport { withFormInputEvents } from \"document/models/CanvasTree/traits/forms/WithFormInputEvents.ts\"\nimport { withAnyEffect } from \"document/models/CanvasTree/traits/utils/effects.ts\"\nimport type { EventAction } from \"document/models/EventAction.ts\"\nimport type {\n\tControlProps,\n\tScrollSectionRefControlProp,\n\tSlotControlItem,\n} from \"document/models/controlProps/ControlProp.ts\"\nimport { withId } from \"document/models/controlProps/ControlProp.ts\"\nimport { type RawControlProps, isRawControlProp } from \"document/models/controlProps/RawControlProp.ts\"\nimport { prefixControlPropKey, prefixControlProps } from \"document/models/controlProps/controlPropKey.ts\"\nimport { getScrollSectionRefControlPropValue } from \"document/models/controlProps/getControlProps.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport type { Mutable } from \"utils/Mutable.ts\"\nimport { isKeySetAndNotInherited } from \"utils/isKeySetAndNotInherited.ts\"\nimport { isShallowArrayEqual } from \"utils/isShallowEqual.ts\"\nimport { getRepeatedItemIdUpdate } from \"utils/repeaterUtils.ts\"\nimport { isArray, isObject, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { generateVariableReferenceUpdateForNode } from \"utils/updateDynamicValues.ts\"\n\n// When pasting two Frames where the first Frame links to the second Frame we\n// want to recreate that link between the first pasted Frame and the second\n// pasted Frame.\nexport class RenamedIds extends Map<NodeID, NodeID> {\n\tdeclare readonly id: \"renamedIds\" // So that you can't assign Map to RenamedIds\n\n\toverride get(oldId: NodeID): NodeID | undefined {\n\t\tlet newId = super.get(oldId)\n\n\t\twhile (newId) {\n\t\t\tconst nextId = super.get(newId)\n\t\t\tif (nextId === undefined) break\n\t\t\tnewId = nextId\n\t\t}\n\n\t\treturn newId\n\t}\n}\n\nfunction createActionUpdate(action: EventAction, renamedIds: RenamedIds): RawControlProps | undefined {\n\tif (isNavigationAction(action)) {\n\t\tif (!action.controls.target?.value) return\n\t\tconst target = renamedIds.get(action.controls.target.value)\n\t\tif (!target) return\n\t\treturn {\n\t\t\ttarget: {\n\t\t\t\t...action.controls.target,\n\t\t\t\tvalue: target,\n\t\t\t},\n\t\t}\n\t}\n\tif (isSetVariantAction(action)) {\n\t\tif (!action.controls.variantId?.value) return\n\t\tconst target = renamedIds.get(action.controls.variantId.value)\n\t\tif (!target) return\n\t\treturn {\n\t\t\tvariantId: {\n\t\t\t\t...action.controls.variantId,\n\t\t\t\tvalue: target,\n\t\t\t},\n\t\t}\n\t}\n\tif (isShowOverlayAction(action)) {\n\t\tif (!action.controls.overlay?.value) return\n\t\tconst target = renamedIds.get(action.controls.overlay.value)\n\t\tif (!target) return\n\t\treturn {\n\t\t\toverlay: {\n\t\t\t\t...action.controls.overlay,\n\t\t\t\tvalue: target,\n\t\t\t},\n\t\t}\n\t}\n}\n\nfunction updateNodeLinks(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: (CanvasNode & WithFrameEvents) | (CanvasNode & WithFormInputEvents) | CodeComponentNode,\n\trenamedIds: RenamedIds,\n\tinOverlay: boolean,\n) {\n\tconst isCodeComponent = isCodeComponentNode(node)\n\tconst properties: AnyNodeUpdate = {}\n\n\t// We track if we actually need to make any changes.\n\tlet shouldChange = false\n\n\tconst events = eventsForNode(componentLoader, node)\n\tfor (const eventKey in events) {\n\t\tconst nodeKey = isCodeComponent ? prefixControlPropKey(eventKey) : eventKey\n\t\tif (!isKeySetAndNotInherited(tree, node, nodeKey)) continue\n\n\t\tconst actions = events[eventKey]\n\t\tif (!isArray(actions)) continue\n\n\t\tconst nextActions: EventAction[] = []\n\t\tlet eventKeyHasUpdate: boolean = false\n\n\t\tfor (const action of actions) {\n\t\t\t// Skip adding overlay actions if we are already in an overlay.\n\t\t\tconst removeShowOverlayAction = inOverlay && (isShowOverlayAction(action) || isShowRelativeOverlayAction(action))\n\n\t\t\tif (removeShowOverlayAction) {\n\t\t\t\teventKeyHasUpdate = true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If there is no update, just add the current action back to the\n\t\t\t// actions list.\n\t\t\tconst update = createActionUpdate(action, renamedIds)\n\t\t\tif (!update) {\n\t\t\t\tnextActions.push(action)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnextActions.push({\n\t\t\t\t...action,\n\t\t\t\tcontrols: {\n\t\t\t\t\t...action.controls,\n\t\t\t\t\t...update,\n\t\t\t\t},\n\t\t\t})\n\n\t\t\teventKeyHasUpdate = true\n\t\t}\n\n\t\tif (!eventKeyHasUpdate) continue\n\n\t\tif (isCodeComponent) {\n\t\t\tproperties[prefixControlPropKey(eventKey)] = {\n\t\t\t\ttype: ControlType.EventHandler,\n\t\t\t\tvalue: nextActions,\n\t\t\t}\n\t\t} else {\n\t\t\tproperties[eventKey as keyof WithFrameEvents] = nextActions\n\t\t}\n\n\t\tshouldChange = true\n\t}\n\n\tif (!shouldChange) return\n\n\tnode.set(properties, tree)\n}\n\nfunction updateNodeSlots(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CodeComponentNode,\n\trenamedIds: RenamedIds,\n) {\n\t// We track if we actually need to make any changes.\n\tconst updatedProps: Mutable<ControlProps> = {}\n\n\t// Create a link between the target node, so any changes will also trigger the code component\n\t// node.\n\tfunction linkChanges(slotTarget: NodeID) {\n\t\tconst targetNode = tree.get(slotTarget)\n\t\tif (!targetNode) return\n\n\t\ttargetNode.linkTo(node.id)\n\t}\n\n\tconst slotKeys = getSlotKeys(node, componentLoader)\n\tfor (const slotKey of slotKeys) {\n\t\tif (!isKeySetAndNotInherited(tree, node, prefixControlPropKey(slotKey))) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst controlProp = node.getRawControlProp(slotKey)\n\t\tif (!controlProp) continue\n\n\t\tif (controlProp.type === ControlType.Slot && isArray(controlProp.value)) {\n\t\t\tlet didUpdate = false\n\t\t\tconst updatedSlotItems = controlProp.value.map(slotItem => {\n\t\t\t\tif (!isObject(slotItem)) return slotItem\n\t\t\t\tconst referenceKey: keyof SlotControlItem = \"reference\"\n\t\t\t\tif (!isString(slotItem[referenceKey])) return slotItem\n\t\t\t\tconst renamedTarget = renamedIds.get(slotItem.reference)\n\t\t\t\tif (!renamedTarget) return slotItem\n\t\t\t\tdidUpdate = true\n\t\t\t\tlinkChanges(renamedTarget)\n\t\t\t\treturn { ...slotItem, [referenceKey]: renamedTarget }\n\t\t\t})\n\t\t\tif (!didUpdate) continue\n\t\t\tupdatedProps[slotKey] = {\n\t\t\t\ttype: ControlType.Slot,\n\t\t\t\tvalue: updatedSlotItems as SlotControlItem[],\n\t\t\t}\n\t\t} else if (\n\t\t\t(controlProp.type === null || controlProp.type === ControlType.ComponentInstance) &&\n\t\t\tisString(controlProp.value)\n\t\t) {\n\t\t\tconst renamedTarget = renamedIds.get(controlProp.value)\n\t\t\tif (!renamedTarget) continue\n\t\t\tupdatedProps[slotKey] = {\n\t\t\t\ttype: ControlType.Slot,\n\t\t\t\tvalue: [{ id: \"first-item\", reference: renamedTarget }],\n\t\t\t}\n\t\t\tlinkChanges(renamedTarget)\n\t\t} else if (isArray(controlProp.value)) {\n\t\t\tlet didUpdate = false\n\t\t\tconst updatedSlotItems: SlotControlItem[] = []\n\n\t\t\tfor (let index = 0; index < controlProp.value.length; index++) {\n\t\t\t\tconst arrayItem = controlProp.value[index]\n\t\t\t\tif (!isRawControlProp(arrayItem)) continue\n\t\t\t\tif (arrayItem.type !== null && arrayItem.type !== ControlType.ComponentInstance) continue\n\t\t\t\tif (!isString(arrayItem.value)) continue\n\t\t\t\tconst id = withId(arrayItem) ? arrayItem.id : randomID()\n\t\t\t\tconst renamedTarget = renamedIds.get(arrayItem.value)\n\t\t\t\tupdatedSlotItems.push({ id, reference: renamedTarget ?? arrayItem.value })\n\t\t\t\tif (!renamedTarget) continue\n\t\t\t\tlinkChanges(renamedTarget)\n\t\t\t\tdidUpdate = true\n\t\t\t}\n\n\t\t\tif (!didUpdate) continue\n\t\t\tupdatedProps[slotKey] = {\n\t\t\t\ttype: ControlType.Slot,\n\t\t\t\tvalue: updatedSlotItems,\n\t\t\t}\n\t\t}\n\t}\n\tif (isEmptyObject(updatedProps)) return\n\tconst update = prefixControlProps(updatedProps)\n\tnode.set(update, tree)\n}\n\nfunction updateNodeScrollSectionRefs(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CodeComponentNode,\n\trenamedIds: RenamedIds,\n) {\n\t// We track if we actually need to make any changes.\n\tconst updatedProps: Mutable<ControlProps<ScrollSectionRefControlProp>> = {}\n\n\tconst properties = componentLoader.componentForIdentifier(node.codeComponentIdentifier)?.properties\n\tfor (const key in properties) {\n\t\tif (!isKeySetAndNotInherited(tree, node, prefixControlPropKey(key))) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst property = properties[key]\n\t\t// @TODO - We can technically support ScrollSectionRef's in Arrays and\n\t\t// Objects, though it is not possible via the app right now. We should\n\t\t// improve this helper to update ScrollSectionRefs in ControlType.Array\n\t\t// and ControlType.Object.\n\t\tif (property?.type !== ControlType.ScrollSectionRef) continue\n\n\t\tconst controlProp = node.getRawControlProp(key)\n\t\tif (!controlProp) continue\n\n\t\tconst value = getScrollSectionRefControlPropValue(property, controlProp)\n\t\tif (!value || isVariableReference(value) || !isString(value.target)) continue\n\n\t\tconst renamedTarget = renamedIds.get(value.target)\n\t\tif (!renamedTarget) continue\n\n\t\tupdatedProps[key] = { type: ControlType.ScrollSectionRef, value: { ...value, target: renamedTarget } }\n\t}\n\n\tif (isEmptyObject(updatedProps)) return\n\n\tnode.set(prefixControlProps(updatedProps), tree)\n}\n\n// Update effect section targets to point to the remapped ids.\nfunction updateNodeEffectSections(node: CanvasNode, renamedIds: RenamedIds) {\n\tif (withVariantAppearPageEffect(node) && isArray(node.appearEffectScrollTargets)) {\n\t\tconst appearEffectScrollTargets = node.appearEffectScrollTargets.map(entry => {\n\t\t\tif (!entry.target || isVariableReference(entry.target)) return entry\n\t\t\tconst renamedTarget = renamedIds.get(entry.target)\n\t\t\tif (!renamedTarget) return entry\n\n\t\t\treturn {\n\t\t\t\tid: randomID(),\n\t\t\t\tvariant: entry.variant,\n\t\t\t\ttarget: renamedTarget,\n\t\t\t}\n\t\t})\n\t\tnode.set({ appearEffectScrollTargets })\n\t}\n\n\tif (withStyleAppearPageEffect(node) && isString(node.styleAppearEffectScrollTarget)) {\n\t\tconst styleAppearEffectScrollTarget = renamedIds.get(node.styleAppearEffectScrollTarget)\n\t\tif (styleAppearEffectScrollTarget) node.set({ styleAppearEffectScrollTarget })\n\t}\n\n\tif (withStyleTransformEffect(node) && isArray(node.styleTransformEffectScrollTargets)) {\n\t\tconst styleTransformEffectScrollTargets = node.styleTransformEffectScrollTargets.map(entry => {\n\t\t\tif (!entry.target || isVariableReference(entry.target)) return entry\n\t\t\tconst renamedTarget = renamedIds.get(entry.target)\n\t\t\tif (!renamedTarget) return entry\n\n\t\t\treturn {\n\t\t\t\tid: randomID(),\n\t\t\t\tstyle: entry.style,\n\t\t\t\ttarget: renamedTarget,\n\t\t\t}\n\t\t})\n\t\tnode.set({ styleTransformEffectScrollTargets })\n\t}\n\n\tif (withDragEffect(node) && node.dragEffectConstraintElement) {\n\t\tconst dragEffectConstraintElement = renamedIds.get(node.dragEffectConstraintElement)\n\t\tif (dragEffectConstraintElement) node.set({ dragEffectConstraintElement })\n\t}\n\n\tif (withTextEffect(node) && isString(node.textEffectScrollTarget)) {\n\t\tconst textEffectScrollTarget = renamedIds.get(node.textEffectScrollTarget)\n\t\tif (textEffectScrollTarget) node.set({ textEffectScrollTarget })\n\t}\n}\n\nexport function updateNodeConnections(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CanvasNode,\n\trenamedIds: RenamedIds,\n\tinOverlay: boolean,\n) {\n\tnode = node.draftOrCurrent()\n\n\tif (withFrameEvents(node) || withFormInputEvents(node)) {\n\t\tupdateNodeLinks(tree, componentLoader, node, renamedIds, inOverlay)\n\t}\n\n\tif (isCodeComponentNode(node)) {\n\t\tupdateNodeLinks(tree, componentLoader, node, renamedIds, inOverlay)\n\t\tupdateNodeSlots(tree, componentLoader, node, renamedIds)\n\t\tupdateNodeScrollSectionRefs(tree, componentLoader, node, renamedIds)\n\t}\n\n\tif (withAnyEffect(node)) {\n\t\tupdateNodeEffectSections(node, renamedIds)\n\t}\n\n\tif (isFormContainer(node) && node.formSubmitButtonId) {\n\t\tconst formSubmitButtonId = renamedIds.get(node.formSubmitButtonId)\n\t\tif (formSubmitButtonId) node.set({ formSubmitButtonId })\n\t}\n\n\tif (hasCollectionDataSourceLoader(node) && node.dataSourceLoaderId) {\n\t\tconst dataSourceLoaderId = renamedIds.get(node.dataSourceLoaderId)\n\t\tif (dataSourceLoaderId) node.set({ dataSourceLoaderId })\n\t}\n\n\tif (isDataRepeater(node)) {\n\t\tif (node.repeatedItemId !== undefined) {\n\t\t\tconst repeatedItemId = renamedIds.get(node.repeatedItemId)\n\t\t\tif (repeatedItemId) {\n\t\t\t\tnode.set(getRepeatedItemIdUpdate(repeatedItemId))\n\t\t\t}\n\t\t} else if (node.collectionRepeatedItemId) {\n\t\t\tconst collectionRepeatedItemId = renamedIds.get(node.collectionRepeatedItemId)\n\t\t\tif (collectionRepeatedItemId) {\n\t\t\t\t// Only updating `collectionRepeatedItemId` and not `repeatedItemId` to avoid no\n\t\t\t\t// longer falling back to the first child while doing that before the rename.\n\t\t\t\tnode.set({ collectionRepeatedItemId })\n\t\t\t}\n\t\t}\n\t}\n\n\tif (hasCollectionDataSource(node)) {\n\t\tconst renamedIdentifier = getRenamedDataIdentifier(node.dataIdentifier, renamedIds)\n\t\tif (renamedIdentifier) {\n\t\t\tnode.set({ dataIdentifier: renamedIdentifier })\n\t\t}\n\t}\n\n\tif (isCollectionNode(node)) {\n\t\tconst renamedVariables = node.variables.map(variable => {\n\t\t\tif (!isAnyCollectionReferencingVariableDefinition(variable)) return variable\n\n\t\t\tconst renamedIdentifier = getRenamedDataIdentifier(variable.dataIdentifier, renamedIds)\n\t\t\tif (!renamedIdentifier) return variable\n\n\t\t\treturn {\n\t\t\t\t...variable,\n\t\t\t\tdataIdentifier: renamedIdentifier,\n\t\t\t}\n\t\t})\n\n\t\tif (!isShallowArrayEqual(node.variables, renamedVariables)) {\n\t\t\tnode.set({ variables: renamedVariables })\n\t\t}\n\t}\n\n\tif (isCollectionItemNode(node)) {\n\t\tupdateCollectionItemNodeReferences(node, renamedIds)\n\t}\n\n\t// Update all dynamic values which provider matches a renamed id\n\tconst variableReferenceUpdate = generateVariableReferenceUpdateForNode(tree, node, variableReference => {\n\t\tif (!variableReference.providerId) return\n\t\tconst updatedProviderId = renamedIds.get(variableReference.providerId)\n\t\tif (!updatedProviderId) return\n\n\t\treturn createVariableReference(renamedIds.get(variableReference.id) ?? variableReference.id, updatedProviderId)\n\t})\n\n\tif (variableReferenceUpdate) node.set(variableReferenceUpdate)\n\n\tif (node.children) {\n\t\tfor (const child of node.children) {\n\t\t\tupdateNodeConnections(tree, componentLoader, child, renamedIds, inOverlay)\n\t\t}\n\t}\n\n\treturn node\n}\n\nfunction getRenamedDataIdentifier(dataIdentifier: ModuleExportIdentifierString, renamedIds: RenamedIds) {\n\tconst parsedIdentifier = parseModuleIdentifier(dataIdentifier)\n\tif (!isLocalModuleIdentifier(parsedIdentifier)) return null\n\n\tconst renamedCollectionId = renamedIds.get(parsedIdentifier.localIdName)\n\tif (!renamedCollectionId) return null\n\n\tconst renamedIdentifier = localModuleIdentifierForStableName(\n\t\tparsedIdentifier.type,\n\t\trenamedCollectionId,\n\t\tparsedIdentifier.exportSpecifier,\n\t)\n\treturn renamedIdentifier.value\n}\n\nfunction updateCollectionItemNodeReferences(collectionItemNode: CollectionItemNode, renamedIds: RenamedIds) {\n\tconst controlProps = collectionItemNode.getControlProps()\n\tfor (const [key, controlProp] of Object.entries(controlProps)) {\n\t\tif (controlProp?.type === ControlType.CollectionReference && isString(controlProp.value)) {\n\t\t\tconst renamedId = renamedIds.get(controlProp.value)\n\n\t\t\tif (renamedId) {\n\t\t\t\tcollectionItemNode.setControlProp(key, {\n\t\t\t\t\t...controlProp,\n\t\t\t\t\tvalue: renamedId,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tcontrolProp?.type === ControlType.MultiCollectionReference &&\n\t\t\t!isUndefined(controlProp.value) &&\n\t\t\t!isDynamicValue(controlProp.value)\n\t\t) {\n\t\t\tconst renamedValue = controlProp.value.map(id => renamedIds.get(id) ?? id)\n\n\t\t\tif (!isShallowArrayEqual(controlProp.value, renamedValue)) {\n\t\t\t\tcollectionItemNode.setControlProp(key, {\n\t\t\t\t\t...controlProp,\n\t\t\t\t\tvalue: renamedValue,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n}\n", "import type { CanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport type { CollectionNode } from \"document/models/CanvasTree/nodes/CollectionNode.ts\"\nimport type { ImportableComponentNode } from \"document/models/CanvasTree/nodes/isImportableComponentNode.ts\"\nimport { isImportableComponentNode } from \"document/models/CanvasTree/nodes/isImportableComponentNode.ts\"\nimport { isCollectionNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\n\nexport type UnlinkableNode = ImportableComponentNode | CollectionNode\n\nexport function isUnlinkableNode(node: CanvasNode | null): node is UnlinkableNode {\n\treturn isImportableComponentNode(node) || isCollectionNode(node)\n}\n", "import { migrateDocument } from \"@framerjs/document-migrations\"\nimport { getServiceMap } from \"@framerjs/framer-environment/domains.ts\"\nimport { AnnotationKey, hasAnnotation } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ModulesAPI } from \"@framerjs/framer-services\"\nimport type {\n\tExternalModuleBareIdentifierString,\n\tExternalModuleExportIdentifier,\n\tGlobalModuleId,\n\tLocalModuleId,\n} from \"@framerjs/shared\"\nimport {\n\tassert,\n\tModuleType,\n\tasGlobalId,\n\tasLocalId,\n\texternalModuleIdentifier,\n\tisLocalModuleIdentifier,\n\tparseModuleIdentifier,\n\ttoExternalIdentifier,\n\ttoLocalIdentifier,\n\tunhandledError,\n} from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { CanvasChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport { duplicatedFromForNode } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport type { TextStylePresetNode } from \"document/models/CanvasTree/nodes/TextStylePresetNode.ts\"\nimport { canvasNodeFromValue } from \"document/models/CanvasTree/nodes/canvasNodeFromValue.ts\"\nimport { isExternalModuleNode, isTextStylePresetNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasItemsOrderOverride, withItemsOrder } from \"document/models/CanvasTree/traits/WithItemsOrder.ts\"\nimport { isReplica } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport { forEachModuleIdentifierOfNode, generateModuleIdentifierUpdateForNode } from \"utils/moduleIdentifierForNode.ts\"\nimport { getVectorSetInfo } from \"utils/vectorSets.ts\"\nimport { insertVectorSetModuleIds } from \"../chrome/insertSidebar/dataSources/items/vectorSetItems.ts\"\nimport type { RenamedIds } from \"../tools/utils/updateNodeConnections.ts\"\nimport type { UnlinkableNode } from \"./Unlinkable.ts\"\nimport { isUnlinkableNode } from \"./Unlinkable.ts\"\n\n// We didn't track the tree version until recently. However, the feature was\n// launched when 75 was the latest tree version, so we can safely fallback to\n// this version.\nconst DEFAULT_TREE_VERSION = 75\n\nconst cloneOverrides = {\n\tmutable: true,\n\tupdate: 0,\n} as const\n\nexport function cloneWithRenamedIdMap<T extends CanvasNode>(\n\toriginalNode: T,\n\tlocalIdsToExternalIdentifiers: LocalIdToExternalIdentifierMap,\n\texternalModulesToLocalIds: ExternalModuleIdToLocalIdMap,\n\tmap?: RenamedIds,\n\ttrackDuplication: boolean = false,\n) {\n\tfunction cloneNodeWithMap<T extends CanvasNode>(node: T, parentId?: NodeID, insideVariant: boolean = false) {\n\t\tconst clone = node.cloneEmpty()\n\t\tclone.assign(node, cloneOverrides, {\n\t\t\tcache: clone.cache,\n\t\t\tid: clone.id,\n\t\t})\n\n\t\t// A clone is always an original node, which is not suppose to have an itemsOrder override. Any itemsOrder overrides\n\t\t// to preserve should be done through replicaInfo.\n\t\tif (withItemsOrder(clone)) {\n\t\t\tclone.itemsOrder = undefined\n\t\t}\n\n\t\t// Helpers (such as getChildrenInVisualOrder) may expect nodes that are\n\t\t// children of variants to have a cache value that is set when walking\n\t\t// the tree in updateTreeCacheForVekter. However, we may be cloning from\n\t\t// a node that has not yet been inserted into the tree, and so its cache\n\t\t// my never have been populated. In this case we ensure that helper\n\t\t// functions that rely on this run by manually setting the value.\n\t\tnode.cache.insideVariant = insideVariant\n\n\t\tconst children = hasItemsOrderOverride(node) ? node.getChildrenInVisualOrder() : node.children\n\t\tif (children) {\n\t\t\tclone.children = new CanvasChildList(children.map(child => cloneNodeWithMap(child, clone.id, insideVariant)))\n\t\t}\n\n\t\tconst update: Partial<CanvasNode> = {\n\t\t\tparentid: parentId,\n\t\t\t...generateModuleIdentifierUpdateForNodeForCloning(\n\t\t\t\tnode,\n\t\t\t\tlocalIdsToExternalIdentifiers,\n\t\t\t\texternalModulesToLocalIds,\n\t\t\t),\n\t\t}\n\n\t\tif (isReplica(node) && !isVariant(node)) {\n\t\t\tObject.assign(update, {\n\t\t\t\treplicaInfo: undefined,\n\t\t\t\toriginalid: undefined,\n\t\t\t\t...node.replicaInfo.overrides[node.replicaInfo.master],\n\t\t\t\t_deleted: undefined,\n\t\t\t})\n\t\t}\n\n\t\tif (trackDuplication) {\n\t\t\tObject.assign(update, { duplicatedFrom: duplicatedFromForNode(node.duplicatedFrom, node.id) })\n\t\t}\n\n\t\tclone.assign(update)\n\t\tif (map) {\n\t\t\t// Sometimes we rename node ids twice. To make sure we keep track of all the steps,\n\t\t\t// let's add a new entry for the \"intermediate\" node id.\n\t\t\tif (map.has(node.id)) {\n\t\t\t\tconst newId = map.get(node.id)\n\t\t\t\tif (newId) {\n\t\t\t\t\tmap.set(newId, clone.id)\n\t\t\t\t}\n\t\t\t}\n\t\t\tmap.set(node.id, clone.id)\n\t\t\t// If the renamed node is a replica (should only happen when detaching an instance set to a replica variant)\n\t\t\t// keep track of the original id as well for remapping things like itemsOrder.\n\t\t\tif (node.originalid && !map.has(node.originalid)) {\n\t\t\t\tmap.set(node.originalid, clone.id)\n\t\t\t}\n\t\t}\n\n\t\treturn clone\n\t}\n\n\treturn cloneNodeWithMap(originalNode, undefined, isVariant(originalNode))\n}\n\nexport interface UnlinkDependencies {\n\tassets: readonly string[]\n\timports: readonly ModulesAPI.ImportDependency[]\n\townerType: string\n\townerId: string\n}\n\nexport type LocalIdToExternalIdentifierMap = Map<LocalModuleId, ExternalModuleBareIdentifierString>\nexport type ExternalModuleIdToLocalIdMap = Map<GlobalModuleId, LocalModuleId>\n\nexport function generateModuleIdentifierUpdateForNodeForCloning<T extends CanvasNode>(\n\tnode: T,\n\tlocalIdsToExternalIdentifiers: LocalIdToExternalIdentifierMap,\n\texternalModuleIdsToLocalIds: ExternalModuleIdToLocalIdMap,\n): Partial<T> | undefined {\n\treturn generateModuleIdentifierUpdateForNode(node, moduleIdentifierString => {\n\t\tconst moduleIdentifier = parseModuleIdentifier(moduleIdentifierString)\n\n\t\tif (moduleIdentifier.kind === \"localModuleExport\") {\n\t\t\tconst externalIdentifier = localIdsToExternalIdentifiers.get(moduleIdentifier.localId)\n\t\t\tif (!externalIdentifier) return\n\n\t\t\tconst { moduleId, saveId, file } = parseModuleIdentifier(externalIdentifier)\n\t\t\treturn toExternalIdentifier(moduleIdentifier, moduleId, saveId, file).value\n\t\t}\n\n\t\tif (moduleIdentifier.kind === \"externalModuleExport\") {\n\t\t\tconst localId = externalModuleIdsToLocalIds.get(moduleIdentifier.moduleId)\n\t\t\tif (!localId) return\n\n\t\t\treturn toLocalIdentifier(moduleIdentifier, localId).value\n\t\t}\n\t})\n}\n\nfunction getLocalIdToExternalIdentifierMap(\n\timports: readonly ModulesAPI.ImportDependency[],\n): LocalIdToExternalIdentifierMap {\n\tconst localIdsToExternalIdentifiers: LocalIdToExternalIdentifierMap = new Map()\n\n\tfor (const moduleImport of imports) {\n\t\tif (moduleImport.type === \"local\") {\n\t\t\tconst moduleId = asGlobalId(moduleImport.moduleId)\n\t\t\tlocalIdsToExternalIdentifiers.set(\n\t\t\t\tasLocalId(moduleImport.localId),\n\t\t\t\texternalModuleIdentifier(moduleId, moduleImport.saveId, moduleImport.file).value,\n\t\t\t)\n\t\t}\n\t}\n\n\treturn localIdsToExternalIdentifiers\n}\n\n/**\n * Make a fetch request for all module imports that are local and are CSS type,\n * parse them and return only the `TextStylePreset` nodes.\n */\nexport async function collectTextStylePresets(imports: readonly ModulesAPI.ImportDependency[]) {\n\tconst textStylePresets: Map<NodeID, TextStylePresetNode> = new Map()\n\n\tfor await (const moduleImport of imports) {\n\t\tif (moduleImport.type === \"local\" && moduleImport.moduleType === ModuleType.CSS) {\n\t\t\tconst moduleTree = await fetchTreeJSON({\n\t\t\t\tmoduleId: asGlobalId(moduleImport.moduleId),\n\t\t\t\tsaveId: moduleImport.saveId,\n\t\t\t})\n\n\t\t\tconst { __treeSerializationVersion, ...root } = moduleTree\n\t\t\tconst version = __treeSerializationVersion || DEFAULT_TREE_VERSION\n\n\t\t\tconst { root: migratedNode } = migrateDocument({ root, version })\n\t\t\tconst node = canvasNodeFromValue(migratedNode)\n\n\t\t\tif (isTextStylePresetNode(node)) {\n\t\t\t\ttextStylePresets.set(node.id, node)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [...textStylePresets.values()]\n}\n\nexport function collectUnlinkIdentifiers(\n\tnode: CanvasNode,\n\tmodulesStore: ModulesStore,\n\tdependencies: UnlinkDependencies,\n): {\n\tidentifiers: ExternalModuleExportIdentifier[]\n\tlocalIdsToExternalIdentifiers: LocalIdToExternalIdentifierMap\n\texternalModuleIdsToLocalIds: ExternalModuleIdToLocalIdMap\n} {\n\t// Construct a map that converts local imports to external ones (since\n\t// everything that used to be local to the unlinked component will now be\n\t// external).\n\tconst localIdsToExternalIdentifiers = getLocalIdToExternalIdentifierMap(dependencies.imports)\n\t// Maps the externalIdentifiers that are originally coming from this project to their localIds\n\tconst externalModuleIdsToLocalIds: ExternalModuleIdToLocalIdMap = new Map()\n\t// Scan for all module references inside the canvas node.\n\tconst identifiers: ExternalModuleExportIdentifier[] = []\n\n\tfor (const n of node.walk()) {\n\t\tforEachModuleIdentifierOfNode(n, moduleIdentifierString => {\n\t\t\tlet moduleIdentifier = parseModuleIdentifier(moduleIdentifierString)\n\t\t\t// Convert the local identifier to an external one if it's local.\n\t\t\tif (isLocalModuleIdentifier(moduleIdentifier)) {\n\t\t\t\tconst externalId = localIdsToExternalIdentifiers.get(moduleIdentifier.localId)\n\t\t\t\tif (!externalId) {\n\t\t\t\t\t// Failed to convert this local module identifier to an external one.\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Make the identifier external, maintaining the export specifier.\n\t\t\t\tconst { moduleId, saveId, file } = parseModuleIdentifier(externalId)\n\t\t\t\tmoduleIdentifier = toExternalIdentifier(moduleIdentifier, moduleId, saveId, file)\n\t\t\t}\n\t\t\tif (moduleIdentifier.kind === \"externalModuleExport\") {\n\t\t\t\t// We should always hit this condition since we currently don't\n\t\t\t\t// support non-export ids. Ensure there's a module node for this\n\t\t\t\t// module and export.\n\t\t\t\tconst localModule = modulesStore.getPersistedModuleByGlobalId(moduleIdentifier.moduleId)\n\t\t\t\tif (localModule) {\n\t\t\t\t\texternalModuleIdsToLocalIds.set(moduleIdentifier.moduleId, localModule.localId)\n\t\t\t\t} else {\n\t\t\t\t\tidentifiers.push(moduleIdentifier)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\treturn { identifiers, localIdsToExternalIdentifiers, externalModuleIdsToLocalIds }\n}\n\nexport async function fetchTreeJSON({ moduleId, saveId }: { moduleId: GlobalModuleId; saveId: string }) {\n\ttry {\n\t\tconst response = await fetch(`${getServiceMap().modulesCDN}/${moduleId}/${saveId}/tree.json`)\n\t\treturn await response.json()\n\t} catch (error) {\n\t\tunhandledError(error)\n\t}\n}\n\nexport async function fetchUnlinkResources(\n\tengine: VekterEngine,\n\tidentifier: ExternalModuleExportIdentifier,\n): Promise<{\n\tnode: UnlinkableNode\n\tdependencies: UnlinkDependencies\n}> {\n\tconst [treeJSON, dependencies] = await Promise.all([\n\t\tfetchTreeJSON(identifier),\n\t\tengine.stores.modulesStore.getModuleDependencies(identifier),\n\t])\n\n\tassert(treeJSON, \"Can't get tree.json for module identifier\")\n\tassert(dependencies, \"Can't get dependencies for module identifier\")\n\n\tconst { __treeSerializationVersion, ...root } = treeJSON\n\tconst version = __treeSerializationVersion || DEFAULT_TREE_VERSION\n\n\tconst { root: migratedNode } = migrateDocument({ root, version })\n\tconst node = canvasNodeFromValue(migratedNode)\n\n\tassert(isUnlinkableNode(node), \"Node should be un-linkable.\")\n\n\treturn { node, dependencies }\n}\n\nexport async function importUnlinkAssets(\n\tengine: VekterEngine,\n\tdependencies: UnlinkDependencies,\n\tidentifier: ExternalModuleExportIdentifier,\n) {\n\tconst projectId = engine.remoteDocument?.projectId\n\tif (projectId && dependencies.assets.length > 0) {\n\t\t// Copy over the module's assets from the source project.\n\t\ttry {\n\t\t\tawait engine.stores.assetStore.assetService?.duplicateModuleAssets(identifier.moduleId, identifier.saveId)\n\t\t} catch {\n\t\t\t// TODO: Show a toast here.\n\t\t}\n\t}\n}\n\nexport function isBuiltInVectorSet(moduleId: string): boolean {\n\treturn insertVectorSetModuleIds.has(moduleId)\n}\n\nexport function isBuiltInVectorSetFromIdentifier(engine: BaseEngine, codeComponentIdentifier: string): boolean {\n\tconst vectorSetInfo = getVectorSetInfo(engine.stores.modulesStore, engine.tree, codeComponentIdentifier)\n\treturn vectorSetInfo ? isBuiltInVectorSet(vectorSetInfo.moduleId) : false\n}\n\nexport function isUnlinkingDisabledOnNode(engine: BaseEngine, id: NodeID): boolean {\n\tconst node = engine.tree.getNodeWithTrait(id, isExternalModuleNode)\n\tif (!node) return true\n\n\tconst component = engine.componentLoader.componentForIdentifier(node.codeComponentIdentifier)\n\tif (component && hasAnnotation(component.annotations, AnnotationKey.FramerDisableUnlink)) return true\n\n\treturn false\n}\n", "import type { ComponentCanvasCreateSource } from \"@framerjs/framer-events\"\nimport { triggerComponentCanvasCreateEvent } from \"@framerjs/framer-events\"\nimport { assert, type ExternalModuleExportIdentifier, assertNever, getLogger, unhandledError } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { ensureModulesAreLoaded } from \"code-generation/components/helpers/ensureModulesAreLoaded.ts\"\nimport { getRelatedReplicaNodes } from \"code-generation/utils/isOnlyVisibleInCurrentVariant.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type {\n\tCanvasNode,\n\tCodeComponentNode,\n\tLoadedLayoutTemplateNode,\n\tLoadedSmartComponentNode,\n\tLoadedWebPageNode,\n\tRichTextNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { CanvasChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport { InlineCodeStylePresetNode } from \"document/models/CanvasTree/nodes/InlineCodeStylePresetNode.ts\"\nimport { LinkStylePresetNode } from \"document/models/CanvasTree/nodes/LinkStylePresetNode.ts\"\nimport { getDefaultPresets } from \"document/models/CanvasTree/nodes/RichTextNode.utils.ts\"\nimport { TemplateHelper, createDuplicatedFromIfAllowed } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport { TextStylePresetNode } from \"document/models/CanvasTree/nodes/TextStylePresetNode.ts\"\nimport type { ImportableComponentNode } from \"document/models/CanvasTree/nodes/isImportableComponentNode.ts\"\nimport { isImportableComponentNode } from \"document/models/CanvasTree/nodes/isImportableComponentNode.ts\"\nimport { detachTextStylePresetsFromBreakpoints } from \"document/models/CanvasTree/nodes/utils/detachTextStylePresetsForBreakpoints.ts\"\nimport {\n\tisCodeComponentNode,\n\tisRichTextNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isComputedValue } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport type { ValueTransform } from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport { isPinnable } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { withReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport { isRichTextTag } from \"document/models/CanvasTree/traits/WithRichTextTag.ts\"\nimport type { IsReplica } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isMaster, isReplica, isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { IsPrimaryVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport {\n\tisBreakpointVariant,\n\tisGestureVariant,\n\tisPrimaryVariant,\n\tisReplicaVariant,\n\tisVariant,\n} from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { codeComponentVariantPropKeys } from \"document/models/CanvasTree/traits/codeComponentVariantPropKeys.ts\"\nimport { applyTokenOverridesToUnlinkedSmartComponentNode } from \"document/models/CanvasTree/traits/utils/applyTokenOverrides.ts\"\nimport type { ControlProp, ControlProps } from \"document/models/controlProps/ControlProp.ts\"\nimport { prefixControlPropKey, prefixControlProps } from \"document/models/controlProps/controlPropKey.ts\"\nimport { ActiveContentPanelTab } from \"document/utils/ActiveEditorType.ts\"\nimport { isEmptyWebPage, replaceWebPage } from \"document/utils/replaceWebPage.ts\"\nimport { uniqueName } from \"document/utils/uniqueName.ts\"\nimport type { Size } from \"library/index.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport type { Mutable } from \"utils/Mutable.ts\"\nimport { pasteInlineCodeStylePresets, pasteLinkStylePresets, pasteTextStylePresets } from \"utils/clipboard/utils.ts\"\nimport { dataDefinitionHasCollectionReference } from \"utils/collectionReferenceUtils.ts\"\nimport { getDefaultInlineCodeStylePreset, insertInlineCodeStylePreset } from \"utils/inlineCodeStylePresetUtils.ts\"\nimport { isKeySetAndNotInherited } from \"utils/isKeySetAndNotInherited.ts\"\nimport { getDefaultLinkStylePreset, insertLinkStylePreset } from \"utils/linkStylePresetUtils.ts\"\nimport { getDefaultTextStylePreset, insertTextStylePreset } from \"utils/textStylePresetUtils.ts\"\nimport { tryParseNumber } from \"utils/tryParseNumber.ts\"\nimport { isNumber, isString } from \"utils/typeChecks.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { createRouteSegment } from \"../chrome/Pages/utils/createRouteSegment.ts\"\nimport { getWebPagePositionInParent } from \"../chrome/Pages/utils/getRouteSegmentPositionInParent.ts\"\nimport { getTextStylePresetBreakpoints } from \"../chrome/properties/panels/utils/getTextStylePresetBreakpoints.ts\"\nimport { remapOverrides } from \"../tools/utils/remapOverrides.ts\"\nimport { RenamedIds, updateNodeConnections } from \"../tools/utils/updateNodeConnections.ts\"\nimport { getUniquePagePath } from \"../utils/getUniquePagePath.ts\"\nimport { getRawWebPagePath } from \"../utils/getWebPagePath.ts\"\nimport type { InternalImportExternalComponentFunctionOptions } from \"./common.ts\"\nimport type { ExternalModuleIdToLocalIdMap, LocalIdToExternalIdentifierMap } from \"./utils.ts\"\nimport {\n\tcloneWithRenamedIdMap,\n\tcollectTextStylePresets,\n\tcollectUnlinkIdentifiers,\n\tfetchUnlinkResources,\n\tgenerateModuleIdentifierUpdateForNodeForCloning,\n\timportUnlinkAssets,\n} from \"./utils.ts\"\n\nconst logger = getLogger(\"importExternalSmartComponentOrWebpage\")\n\n/**\n * Makes sure that the component name is unique. If a component with the same name already exists we\n * append the word Copy and a count if its more than 1.\n */\nfunction getUniqueComponentName(\n\tengine: VekterEngine,\n\tcurrentName: string | null,\n\tpreferredName: string | undefined,\n): string {\n\tconst allScopeNames = new Set(\n\t\tengine.stores.scopeStore\n\t\t\t.getSmartComponentNodes()\n\t\t\t.map(node => node.name)\n\t\t\t.filter(isString),\n\t)\n\n\tif (preferredName || currentName === null) {\n\t\treturn uniqueName(preferredName ?? Dictionary.Component, allScopeNames)\n\t}\n\n\treturn uniqueName(currentName, allScopeNames)\n}\n\nfunction remapVariantIdsInValueTransform(transform: ValueTransform, renamedIds: RenamedIds): ValueTransform {\n\tconst updatedTransform = { ...transform }\n\n\tswitch (updatedTransform.name) {\n\t\t/**\n\t\t * {@link insertReferenceTabsFilter} applies this transform to the component instances.\n\t\t */\n\t\tcase \"convertFromBoolean\": {\n\t\t\tif (isString(updatedTransform.truthy)) {\n\t\t\t\tupdatedTransform.truthy = renamedIds.get(updatedTransform.truthy) ?? updatedTransform.truthy\n\t\t\t}\n\n\t\t\tif (isString(updatedTransform.falsy)) {\n\t\t\t\tupdatedTransform.falsy = renamedIds.get(updatedTransform.falsy) ?? updatedTransform.falsy\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t\tcase \"addImageAlt\":\n\t\tcase \"arrayLength\":\n\t\tcase \"arrayToArray\":\n\t\tcase \"contains\":\n\t\tcase \"containsAll\":\n\t\tcase \"containsAny\":\n\t\tcase \"convertFromEnum\":\n\t\tcase \"convertFromString\":\n\t\tcase \"endsWith\":\n\t\tcase \"enumToDisplayName\":\n\t\tcase \"equals\":\n\t\tcase \"extractDateSegment\":\n\t\tcase \"getGridColumnCSSValue\":\n\t\tcase \"getGridRowCSSValue\":\n\t\tcase \"getNumericColumnGap\":\n\t\tcase \"greaterThan\":\n\t\tcase \"htmlEscape\":\n\t\tcase \"htmlUnescape\":\n\t\tcase \"isAfter\":\n\t\tcase \"isBefore\":\n\t\tcase \"isBetweenDates\":\n\t\tcase \"isEven\":\n\t\tcase \"isIncludedIn\":\n\t\tcase \"isOdd\":\n\t\tcase \"isSet\":\n\t\tcase \"jsonStringify\":\n\t\tcase \"lessThan\":\n\t\tcase \"negate\":\n\t\tcase \"numberToPixelString\":\n\t\tcase \"numberToString\":\n\t\tcase \"offsetAndLimitArray\":\n\t\tcase \"percentageToCornerShape\":\n\t\tcase \"prefix\":\n\t\tcase \"radiusForCorner\":\n\t\tcase \"reverseArray\":\n\t\tcase \"startsWith\":\n\t\tcase \"suffix\":\n\t\tcase \"toAxisOverflow\":\n\t\tcase \"toBoolean\":\n\t\tcase \"toDateString\":\n\t\tcase \"toggleInList\":\n\t\tcase \"toImageSrc\":\n\t\tcase \"toNumber\":\n\t\tcase \"toOverflowWithClipFallback\":\n\t\tcase \"toResponsiveImage\":\n\t\tcase \"toString\":\n\t\tcase \"toZIndex\": {\n\t\t\t// We intentionally don't handle these transforms.\n\t\t\t// This is a bug, but it's unclear whether it affects enough users to justify spending effort here.\n\t\t\tlogger.reportError(\n\t\t\t\t\"remapVariantIdsInValueTransform encountered a transform that can't handle. If it mapped to component variants, they are broken and the user needs to manually remap them.\",\n\t\t\t\t{\n\t\t\t\t\ttransformName: updatedTransform.name,\n\t\t\t\t},\n\t\t\t)\n\t\t\tbreak\n\t\t}\n\t\tdefault:\n\t\t\tassertNever(updatedTransform)\n\t}\n\n\treturn updatedTransform\n}\n\ninterface CloneSmartComponentOrWebPageOptions {\n\tpreferredName?: string\n\tinsertionIndex?: number\n\t/**\n\t * Whether to open the new component in isolation.\n\t *\n\t * **When setting this to `false`, the generated code will not contain\n\t * auto-measured dimensions so make sure to set them manually!**\n\t */\n\tenterIsolation?: boolean\n\tlocalIdsToExternalIdentifiers?: LocalIdToExternalIdentifierMap\n\texternalModuleIdsToLocalIds?: ExternalModuleIdToLocalIdMap\n\tinstance?: CodeComponentNode | null\n\trenamedIds?: RenamedIds\n\tisAutoDetach?: boolean\n\tintrinsicSize?: Size\n\t/**\n\t * Any rich text nodes that contain these text style presets will be\n\t * detached, applying the text properties to the node.\n\t * */\n\ttextStylePresets?: TextStylePresetNode[]\n\tlinkStylePresets?: LinkStylePresetNode[]\n\tinlineCodeStylePresets?: InlineCodeStylePresetNode[]\n\tpastedPresetMap?: Map<string, LinkStylePresetNode | TextStylePresetNode>\n\tshouldPasteTextStyles?: boolean\n\treusePresetWithSameId?: boolean\n\tabTesting?: boolean\n\tcloneWithScopeIds?: boolean\n}\n\nexport function cloneScopeNodeWithVariants<T extends ImportableComponentNode | LoadedLayoutTemplateNode>(\n\tengine: VekterEngine,\n\tscopeNodeWithVariants: T,\n\tprimaryVariantNode: CanvasNode & IsPrimaryVariant,\n\ttrackingSource: ComponentCanvasCreateSource,\n\t{\n\t\tinsertionIndex,\n\t\tpreferredName,\n\t\tenterIsolation = true,\n\t\tlocalIdsToExternalIdentifiers = new Map(),\n\t\texternalModuleIdsToLocalIds = new Map(),\n\t\tinstance,\n\t\trenamedIds = new RenamedIds(),\n\t\tisAutoDetach = false,\n\t\tintrinsicSize,\n\t\ttextStylePresets,\n\t\tlinkStylePresets,\n\t\tinlineCodeStylePresets,\n\t\tpastedPresetMap = new Map(),\n\t\tshouldPasteTextStyles = false,\n\t\treusePresetWithSameId,\n\t\tabTesting = false,\n\t\tcloneWithScopeIds = false,\n\t}: CloneSmartComponentOrWebPageOptions = {},\n): T {\n\t// Detach into a temporary tree if provided.\n\tconst tree = isAutoDetach ? CanvasTree.createWithRouteSegmentRoot() : engine.tree\n\tconst cloneProps: { [key: string]: unknown } = {\n\t\tchildren: new CanvasChildList(),\n\t}\n\tif (isWebPageNode(scopeNodeWithVariants)) {\n\t\tconst defaultNewPath =\n\t\t\tscopeNodeWithVariants.id === engine.tree.root.homePageNodeId\n\t\t\t\t? Dictionary.Home\n\t\t\t\t: getRawWebPagePath(engine.tree, scopeNodeWithVariants)\n\t\tconst { suggestedName, path } = getUniquePagePath(\n\t\t\tpreferredName ?? defaultNewPath ?? Dictionary.Page,\n\t\t\tengine.tree,\n\t\t\tengine.componentLoader,\n\t\t\tscopeNodeWithVariants,\n\t\t\ttrue,\n\t\t)\n\t\t// @FIXME: deprecate node.pagePath when we support route segments for CMS pages, use the suggested path to\n\t\t// create a route segment directly\n\t\tcloneProps.pagePath = path\n\t\tcloneProps.name = suggestedName\n\t} else {\n\t\tcloneProps.name = getUniqueComponentName(engine, scopeNodeWithVariants.resolveValue(\"name\"), preferredName)\n\t}\n\n\tlet clonedScopeNodeWithVariants: LoadedSmartComponentNode | LoadedWebPageNode | LoadedLayoutTemplateNode | undefined\n\tif (cloneWithScopeIds) {\n\t\t// Currently the only code path that clones a layout template is AI Kit generation (duplicate\n\t\t// layout template is handled separately, see duplicateLayoutTemplateNode), which constructs a\n\t\t// layout template from the kit clipboard data. In this case, we want to preserve the layout\n\t\t// template node ID, so that we could use it to determine if a layout template is from a kit or\n\t\t// not. There is a non-zero chance that the ID might have been occupied by a local node already,\n\t\t// and in which case we would just bail out, but the chance is slim so we're taking the shortcut\n\t\t// now.\n\t\tclonedScopeNodeWithVariants = scopeNodeWithVariants.cloneWithIds(cloneProps)\n\t} else {\n\t\tclonedScopeNodeWithVariants = scopeNodeWithVariants.clone(cloneProps)\n\t\trenamedIds.set(scopeNodeWithVariants.id, clonedScopeNodeWithVariants.id)\n\t}\n\n\t// Tracking\n\t// TODO: add web page tracking\n\tif (isSmartComponentNode(scopeNodeWithVariants)) {\n\t\ttriggerComponentCanvasCreateEvent({\n\t\t\tcomponentId: clonedScopeNodeWithVariants.id,\n\t\t\tsource: trackingSource,\n\t\t})\n\t}\n\n\tconst nextIdentifier = clonedScopeNodeWithVariants.instanceIdentifier\n\n\t// This takes care of lifted variables\n\tconst moduleIdentifierUpdate = generateModuleIdentifierUpdateForNodeForCloning(\n\t\tclonedScopeNodeWithVariants,\n\t\tlocalIdsToExternalIdentifiers,\n\t\texternalModuleIdsToLocalIds,\n\t)\n\n\tif (moduleIdentifierUpdate) {\n\t\t// Cast because TypeScript doesn't do correlated unions, and the type of parameters of .set\n\t\t// here is an intersection of all possible values.\n\t\tclonedScopeNodeWithVariants.set(\n\t\t\tmoduleIdentifierUpdate as Partial<LoadedSmartComponentNode & LoadedWebPageNode & LoadedLayoutTemplateNode>,\n\t\t)\n\t}\n\n\tconst trackDuplication = isBreakpointVariant(primaryVariantNode)\n\n\t// Clone the primary variant while building a hashmap of each old id in the\n\t// primary tree to the id of the cloned layer. We use this map to update\n\t// replicaOverrides. Later this map will also include the mapping of old\n\t// variant ids to new variant ids. This will allow us to update the\n\t// `variant` prop of an instance to point to the new correct variant. We\n\t// don't need to map variables because we don't need to generate new ids for\n\t// them.\n\tconst nextPrimary = cloneWithRenamedIdMap(\n\t\tprimaryVariantNode,\n\t\tlocalIdsToExternalIdentifiers,\n\t\texternalModuleIdsToLocalIds,\n\t\trenamedIds,\n\t\ttrackDuplication,\n\t)\n\tconst nodesToLink: CanvasNode[] = [nextPrimary]\n\n\t// Update the new SmartComponentNode to point to the new primary variant,\n\t// and insert both the new SmartComponentNode and Primary Variant into the\n\t// tree so that subsequent instance of the Primary Variant can be created.\n\tclonedScopeNodeWithVariants.baseVariantId = nextPrimary.id\n\tclonedScopeNodeWithVariants.addChild(nextPrimary)\n\n\tfor (const groundNode of scopeNodeWithVariants.children) {\n\t\t// Skip the primary variant, we already processed it. Skip any gesture\n\t\t// variant, we may not have created the new variant it inherits from\n\t\t// yet, and we need to remap it's `inheritsFrom` property to point to\n\t\t// the cloned top-level variant.\n\t\tif (groundNode.id === primaryVariantNode.id || isGestureVariant(groundNode)) continue\n\n\t\tif (isReplica(groundNode) && isVariant(groundNode)) {\n\t\t\tconst overrides = remapOverrides(groundNode.replicaInfo.overrides, renamedIds, true)\n\n\t\t\t// Use the dimensions of the groundNode if available. When copy\n\t\t\t// pasting the dimensions in the overrides are not correct because\n\t\t\t// we don't update them in getClipboardData.\n\t\t\tif (isPinnable(groundNode)) {\n\t\t\t\toverrides[nextPrimary.id] ??= {}\n\t\t\t\tconst primaryOverrides = overrides[nextPrimary.id]!\n\t\t\t\tprimaryOverrides.top = groundNode.top\n\t\t\t\tprimaryOverrides.left = groundNode.left\n\t\t\t\tprimaryOverrides.right = groundNode.right\n\t\t\t\tprimaryOverrides.bottom = groundNode.bottom\n\t\t\t\tprimaryOverrides.centerAnchorX = groundNode.centerAnchorX\n\t\t\t\tprimaryOverrides.centerAnchorY = groundNode.centerAnchorY\n\t\t\t}\n\n\t\t\tconst nextNode = TemplateHelper.create(engine.tree, nextPrimary, {\n\t\t\t\toverrides,\n\t\t\t\tduplicatedFrom: createDuplicatedFromIfAllowed(groundNode),\n\t\t\t})\n\n\t\t\trenamedIds.set(groundNode.id, nextNode.id)\n\t\t\tnodesToLink.push(nextNode)\n\t\t\tclonedScopeNodeWithVariants.addChild(nextNode)\n\t\t} else {\n\t\t\tconst nextNode = cloneWithRenamedIdMap(\n\t\t\t\tgroundNode,\n\t\t\t\tlocalIdsToExternalIdentifiers,\n\t\t\t\texternalModuleIdsToLocalIds,\n\t\t\t\tundefined,\n\t\t\t\ttrackDuplication,\n\t\t\t)\n\t\t\tnodesToLink.push(nextNode)\n\t\t\trenamedIds.set(groundNode.id, nextNode.id)\n\t\t\tclonedScopeNodeWithVariants.addChild(nextNode)\n\t\t}\n\t}\n\n\ttree.insertNode(clonedScopeNodeWithVariants, undefined, insertionIndex)\n\n\t// Now iterate through the ground nodes again, this time tracking the index,\n\t// and only processing gesture variants, inserting them in the correct\n\t// order.\n\tfor (let index = 0; index < scopeNodeWithVariants.children.length; index++) {\n\t\tconst gestureNode = scopeNodeWithVariants.children.at(index)!\n\t\tif (!isGestureVariant(gestureNode)) continue\n\t\tconst nextNode = TemplateHelper.create(tree, nextPrimary, {\n\t\t\toverrides: remapOverrides(gestureNode.replicaInfo.overrides, renamedIds, true),\n\t\t\tinheritsFrom: renamedIds.get(gestureNode.replicaInfo.inheritsFrom),\n\t\t\tduplicatedFrom: createDuplicatedFromIfAllowed(gestureNode),\n\t\t})\n\t\trenamedIds.set(gestureNode.id, nextNode.id)\n\t\tnodesToLink.push(nextNode)\n\t\ttree.insertNode(nextNode, clonedScopeNodeWithVariants.id, index)\n\t}\n\n\tconst defaultPresets = getDefaultPresets(tree)\n\n\tfor (const node of nodesToLink) {\n\t\t// Update the targets of setVariant actions, and slot content in the new\n\t\t// nodes we have created.\n\t\tupdateNodeConnections(tree, engine.componentLoader, node, renamedIds, false)\n\n\t\tif (!textStylePresets && !linkStylePresets && !inlineCodeStylePresets) continue\n\n\t\t// Detach all the text style presets on every rich text node.\n\t\tconst richTextNodes: RichTextNode[] = []\n\n\t\tfor (const child of node.walk()) {\n\t\t\tif (!isRichTextNode(child)) continue\n\t\t\trichTextNodes.push(child)\n\t\t}\n\n\t\t// First detach all text styles we got from the imports of this module.\n\t\tfor (const richTextNode of richTextNodes) {\n\t\t\tconst presetIds = richTextNode.getStylePresetIdsForCodeGeneration()\n\n\t\t\tif (linkStylePresets) {\n\t\t\t\tpasteLinkStylePresets({\n\t\t\t\t\tengine,\n\t\t\t\t\tnode: richTextNode,\n\t\t\t\t\tpastedPresetMap,\n\t\t\t\t\tstylePresetNodes: linkStylePresets,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (inlineCodeStylePresets) {\n\t\t\t\tpasteInlineCodeStylePresets({\n\t\t\t\t\tengine,\n\t\t\t\t\tnode: richTextNode,\n\t\t\t\t\tpastedPresetMap,\n\t\t\t\t\tstylePresetNodes: inlineCodeStylePresets,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (textStylePresets) {\n\t\t\t\tif (shouldPasteTextStyles) {\n\t\t\t\t\tpasteTextStylePresets({\n\t\t\t\t\t\tengine,\n\t\t\t\t\t\tnode: richTextNode,\n\t\t\t\t\t\tpastedPresetMap,\n\t\t\t\t\t\tstylePresetNodes: textStylePresets,\n\t\t\t\t\t\tshouldDetachTextStyles: false,\n\t\t\t\t\t\tshouldCreateNewPresets: shouldPasteTextStyles,\n\t\t\t\t\t\treusePresetWithSameId,\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tfor (const presetToDetach of textStylePresets) {\n\t\t\t\t\t\tif (!presetIds.has(presetToDetach.id)) continue\n\n\t\t\t\t\t\tif (isWebPageNode(scopeNodeWithVariants) && isBreakpointVariant(node)) {\n\t\t\t\t\t\t\t// The detachTextStylePresetsFromBreakpoints iterates over\n\t\t\t\t\t\t\t// the primary and replicas of each rich text node and\n\t\t\t\t\t\t\t// detaches the text styles presets. Therefore we don't want\n\t\t\t\t\t\t\t// to call the detachTextStylePresetsFromBreakpoints\n\t\t\t\t\t\t\t// function for replicas.\n\t\t\t\t\t\t\tif (isMaster(node)) {\n\t\t\t\t\t\t\t\tconst presetBreakpoints = getTextStylePresetBreakpoints(textStylePresets, presetToDetach)\n\t\t\t\t\t\t\t\tdetachTextStylePresetsFromBreakpoints(\n\t\t\t\t\t\t\t\t\ttree,\n\t\t\t\t\t\t\t\t\tnextPrimary,\n\t\t\t\t\t\t\t\t\trichTextNode,\n\t\t\t\t\t\t\t\t\tpresetBreakpoints,\n\t\t\t\t\t\t\t\t\tpresetToDetach,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (isMaster(node) || isKeySetAndNotInherited(tree, richTextNode, \"html\")) {\n\t\t\t\t\t\t\t\trichTextNode.detachTextStylePreset(presetToDetach, false)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Then replace all missing text styles with the default ones in the\n\t\t// project. We do this in another loop so we don't accidentally replace\n\t\t// text styles in breakpoint before we've detached the primary.\n\t\tfor (const richTextNode of richTextNodes) {\n\t\t\tif (isKeySetAndNotInherited(tree, richTextNode, \"html\")) {\n\t\t\t\trichTextNode.remapTextStylePresets((_, tag) => {\n\t\t\t\t\tconst presetTag = isRichTextTag(tag) ? tag : \"p\"\n\n\t\t\t\t\tconst preset =\n\t\t\t\t\t\trichTextNode.getNodeTextStylePreset(tree, presetTag) ??\n\t\t\t\t\t\tgetDefaultTextStylePreset(tree, presetTag) ??\n\t\t\t\t\t\tTextStylePresetNode.createDefault(presetTag)\n\n\t\t\t\t\tinsertTextStylePreset(engine, preset)\n\t\t\t\t\treturn preset\n\t\t\t\t})\n\n\t\t\t\trichTextNode.remapLinkStylePresets(() => {\n\t\t\t\t\tconst preset =\n\t\t\t\t\t\trichTextNode.getNodeLinkStylePreset(tree) ??\n\t\t\t\t\t\tgetDefaultLinkStylePreset(tree) ??\n\t\t\t\t\t\tLinkStylePresetNode.createDefault()\n\n\t\t\t\t\tinsertLinkStylePreset(engine, preset)\n\t\t\t\t\treturn preset\n\t\t\t\t})\n\n\t\t\t\trichTextNode.remapInlineCodeStylePresets(() => {\n\t\t\t\t\tconst preset =\n\t\t\t\t\t\trichTextNode.getNodeInlineCodeStylePreset(tree) ??\n\t\t\t\t\t\tgetDefaultInlineCodeStylePreset(tree) ??\n\t\t\t\t\t\tnew InlineCodeStylePresetNode()\n\n\t\t\t\t\tinsertInlineCodeStylePreset(engine, preset)\n\t\t\t\t\treturn preset\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tfor (const presetKey in defaultPresets) {\n\t\t\t\tif (!isKeySetAndNotInherited(tree, richTextNode, presetKey)) continue\n\t\t\t\trichTextNode.set({ [presetKey]: defaultPresets[presetKey as keyof typeof defaultPresets] })\n\t\t\t}\n\t\t}\n\t}\n\n\tconst { codeGenerationStore } = engine.stores\n\n\t// Only generate code for unique presets (outside of the loops above for richTextNode * variant)\n\tfor (const clonedPreset of pastedPresetMap.values()) {\n\t\tif (!isReplicaOrReplicaChild(clonedPreset)) {\n\t\t\tcodeGenerationStore.createModuleFromComponentSource(clonedPreset).catch(unhandledError)\n\t\t}\n\t}\n\n\t// We cannot (and don't want to) generate code from a smart component\n\t// detached into a temporary tree for auto detach.\n\tif (isAutoDetach) {\n\t\t// If we have called `node.set` on any replica nodes, for example, when\n\t\t// remapping or relinking nodes, we need to ensure that those properties\n\t\t// are set on the replicaOverrides.\n\t\ttree.commit(engine.componentLoader)\n\n\t\treturn clonedScopeNodeWithVariants.draftOrCurrent() as T\n\t} else {\n\t\tconst primaryVariant = tree.get(clonedScopeNodeWithVariants.baseVariantId)\n\t\tif (primaryVariant && isPrimaryVariant(primaryVariant)) {\n\t\t\tfor (const child of clonedScopeNodeWithVariants.children) {\n\t\t\t\tif (isReplicaVariant(child) && child.replicaInfo.master === primaryVariant.id) {\n\t\t\t\t\tTemplateHelper.registerInInheritedNode(primaryVariant, child)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// We are intentionally updating the node before running codeGeneration as a\n\t// separate task. This is to optimize undo groups. While avoiding creating\n\t// said groups over a delayed period.\n\tengine.scheduler.process(() => {\n\t\tif (!instance) return\n\n\t\tconst oldExternalIdentifier = engine.tree.current(instance)?.codeComponentIdentifier\n\t\tif (!oldExternalIdentifier) return\n\n\t\tfor (const nodeId of engine.stores.treeStore.treeIndex.codeComponentNodeIds) {\n\t\t\tconst codeComponent = engine.tree.getNodeWithTrait(nodeId, isCodeComponentNode)\n\t\t\tif (!codeComponent) continue\n\t\t\tif (isReplicaOrReplicaChild(codeComponent)) continue\n\t\t\tif (codeComponent.codeComponentIdentifier !== oldExternalIdentifier) continue\n\n\t\t\tconst controlsUpdate: Mutable<ControlProps> = {}\n\t\t\tconst propertyUpdate: Partial<CodeComponentNode> = {}\n\t\t\tconst props = codeComponent.getRawControlProps()\n\n\t\t\t// If the instance had a variant property set, use the hash map we've built\n\t\t\t// while cloning the tree to update it to a new value.\n\t\t\tif (props.variant?.value && isString(props.variant.value)) {\n\t\t\t\tconst newVariantValue = renamedIds.get(props.variant.value) ?? nextPrimary.id\n\t\t\t\tconst newVariantProp: ControlProp = { type: ControlType.Enum, value: newVariantValue }\n\t\t\t\tcontrolsUpdate.variant = newVariantProp\n\t\t\t} else if (props.variant?.value && isComputedValue(props.variant.value)) {\n\t\t\t\tconst computedValue = props.variant.value\n\t\t\t\tconst updatedTransforms = computedValue.transforms.map(transform =>\n\t\t\t\t\tremapVariantIdsInValueTransform(transform, renamedIds),\n\t\t\t\t)\n\t\t\t\tconst newVariantProp: ControlProp = {\n\t\t\t\t\ttype: ControlType.Enum,\n\t\t\t\t\tvalue: { ...computedValue, transforms: updatedTransforms },\n\t\t\t\t}\n\t\t\t\tcontrolsUpdate.variant = newVariantProp\n\t\t\t}\n\n\t\t\tfor (const key of codeComponentVariantPropKeys) {\n\t\t\t\tconst value = codeComponent[key]\n\t\t\t\tif (!isString(value)) continue\n\t\t\t\tpropertyUpdate[key] = renamedIds.get(value) ?? undefined\n\t\t\t}\n\n\t\t\tgetRelatedReplicaNodes(engine.tree, codeComponent).forEach(({ relatedNode, replicaRoot }) => {\n\t\t\t\tconst overrides = replicaRoot.replicaInfo.overrides[relatedNode.originalid]\n\t\t\t\tif (!overrides) return\n\n\t\t\t\t// Update the related node if it overrides any variant properties.\n\t\t\t\tconst propertyOverrides: Partial<CodeComponentNode & IsReplica> = {}\n\t\t\t\tfor (const key of codeComponentVariantPropKeys) {\n\t\t\t\t\tif (!(key in overrides)) continue\n\t\t\t\t\tconst value = overrides[key]\n\t\t\t\t\tif (!isString(value)) continue\n\t\t\t\t\tpropertyUpdate[key] = renamedIds.get(value) ?? undefined\n\t\t\t\t}\n\t\t\t\trelatedNode.set(propertyOverrides)\n\n\t\t\t\t// Check if variant prop is overridden, and update it if so.\n\t\t\t\tif (!(prefixControlPropKey(\"variant\") in overrides)) return\n\t\t\t\tconst variantProp = relatedNode.getRawControlProp(\"variant\")\n\t\t\t\tif (!variantProp || !isString(variantProp.value)) return\n\t\t\t\t// Map existing variant value to rename\n\t\t\t\tconst renamedVariant = renamedIds.get(variantProp.value)\n\t\t\t\tif (!renamedVariant) return\n\t\t\t\tconst newVariantProp: ControlProp = { type: ControlType.Enum, value: renamedVariant }\n\t\t\t\trelatedNode.set(prefixControlProps({ variant: newVariantProp }))\n\t\t\t})\n\n\t\t\tcodeComponent.set({\n\t\t\t\tcodeComponentIdentifier: nextIdentifier,\n\t\t\t\t...propertyUpdate,\n\t\t\t\t...prefixControlProps(controlsUpdate),\n\t\t\t})\n\t\t}\n\t})\n\n\tconst generationPromise = codeGenerationStore.createModuleFromComponentSource(\n\t\tclonedScopeNodeWithVariants,\n\t\tintrinsicSize,\n\t)\n\n\tif (instance) {\n\t\tgenerationPromise\n\t\t\t.then(\n\t\t\t\tengine.scheduler.wrapHandler(() => {\n\t\t\t\t\tinstance = engine.tree.get<CodeComponentNode>(instance?.id)\n\t\t\t\t\tif (!instance) return\n\n\t\t\t\t\t// If the original unlinked component instance was the child of\n\t\t\t\t\t// another smart component, schedule regeneration of the parent\n\t\t\t\t\t// smart component as soon as the child instance has been\n\t\t\t\t\t// generated, skipping the debounce.\n\t\t\t\t\tconst scopeNode = engine.stores.treeStore.tree.getScopeNodeFor(instance)?.loaded\n\t\t\t\t\tif (!scopeNode || !withReplicaVariants(scopeNode)) return\n\n\t\t\t\t\tconst primaryVariant = engine.stores.treeStore.tree.get(scopeNode.baseVariantId)\n\t\t\t\t\tif (primaryVariant && isPrimaryVariant(primaryVariant)) {\n\t\t\t\t\t\tcodeGenerationStore.updateComponent(scopeNode.id).catch(unhandledError)\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.catch(unhandledError)\n\t}\n\n\tif (enterIsolation) {\n\t\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Layers\n\t\t// Finally, navigate into the newly created scope.\n\t\tengine.stores.scopeStore.select(clonedScopeNodeWithVariants.id, { keepHistory: true })\n\t}\n\n\tif (isWebPageNode(clonedScopeNodeWithVariants) && !abTesting) {\n\t\tassert(isString(cloneProps.pagePath), \"pagePath should be a string\")\n\t\tconst webPagePositionInParent = getWebPagePositionInParent(engine.tree, scopeNodeWithVariants.id)\n\t\tconst nextRouteSegmentPosition = isNumber(webPagePositionInParent) ? webPagePositionInParent + 1 : undefined\n\n\t\tcreateRouteSegment(\n\t\t\tengine.tree,\n\t\t\tengine.componentLoader,\n\t\t\tclonedScopeNodeWithVariants,\n\t\t\tclonedScopeNodeWithVariants.dataIdentifier,\n\t\t\tcloneProps.pagePath,\n\t\t\t{\n\t\t\t\tpositionInParent: nextRouteSegmentPosition,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn clonedScopeNodeWithVariants.draftOrCurrent() as T\n}\n\nasync function importExternalCanvasScopeNode(\n\tengine: VekterEngine,\n\t{\n\t\tidentifier,\n\t\tenterIsolation,\n\t\tinstance: instanceInput,\n\t\tisAutoDetach,\n\t\trenamedIds = new RenamedIds(),\n\t\tinfo,\n\t\tscheduleTreeUpdate,\n\t}: InternalImportExternalComponentFunctionOptions,\n) {\n\tconst { node, dependencies } = await fetchUnlinkResources(engine, identifier)\n\tassert(isImportableComponentNode(node), \"Should be a generated node.\")\n\n\t// Can only update original nodes, not replica children\n\tconst instance = engine.tree.get(instanceInput?.getPrimaryId())\n\tassert(!instance || isCodeComponentNode(instance), \"instance should be a code component.\")\n\n\tconst primaryVariantNode = node.children.find(child => child.id === node.baseVariantId)\n\tassert(\n\t\tprimaryVariantNode && isPrimaryVariant(primaryVariantNode),\n\t\t\"Unlink: Can't unlink a tree which doesn't have a Primary Variant node\",\n\t)\n\n\tconst { identifiers, localIdsToExternalIdentifiers, externalModuleIdsToLocalIds } = collectUnlinkIdentifiers(\n\t\tnode,\n\t\tengine.stores.modulesStore,\n\t\tdependencies,\n\t)\n\n\tawait ensureModulesAreLoaded(\n\t\tidentifiers.map(parsedIdentifier => parsedIdentifier.value),\n\t\tengine.stores.modulesStore,\n\t\tengine.componentLoader,\n\t)\n\n\t// External collection with references currently break the canvas, so we\n\t// disable unlinking for them for now.\n\tconst hasCollectionWithReferences = identifiers.some(parsedIdentifier => {\n\t\tconst dataDefinition = engine.componentLoader.dataForIdentifier(parsedIdentifier.value)\n\t\tif (!dataDefinition) return false\n\n\t\treturn dataDefinitionHasCollectionReference(dataDefinition)\n\t})\n\n\tif (hasCollectionWithReferences) {\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tvariant: \"info\",\n\t\t\tprimaryText: \"Remove references\",\n\t\t\tsecondaryText: \"before unlinking.\",\n\t\t})\n\n\t\treturn\n\t}\n\n\tconst textStylePresets = await collectTextStylePresets(dependencies.imports)\n\n\tawait importUnlinkAssets(engine, dependencies, identifier)\n\n\t// Atomically ensure module nodes exist together with cloning and potentially replacing the unlinked instance.\n\tconst nextComponentNode = await engine.stores.modulesStore.addExternalModulesToProject(identifiers, {\n\t\tonTreeUpdate: () => {\n\t\t\tconst currentInstance = engine.tree.current(instance)\n\t\t\t// reuse the copied node's size for the new component\n\t\t\tconst width = tryParseNumber(info.module.metadata[ModuleMetadata.IntrinsicWidth], true) ?? 200\n\t\t\tconst height = tryParseNumber(info.module.metadata[ModuleMetadata.IntrinsicHeight], true) ?? 200\n\t\t\tconst newNode = cloneScopeNodeWithVariants(engine, node, primaryVariantNode, \"unlink\", {\n\t\t\t\tenterIsolation,\n\t\t\t\tlocalIdsToExternalIdentifiers,\n\t\t\t\texternalModuleIdsToLocalIds,\n\t\t\t\tinstance: currentInstance,\n\t\t\t\trenamedIds,\n\t\t\t\tisAutoDetach,\n\t\t\t\tintrinsicSize: { width, height },\n\t\t\t\ttextStylePresets,\n\t\t\t})\n\t\t\tif (currentInstance) {\n\t\t\t\tif (isSmartComponentNode(newNode)) {\n\t\t\t\t\t// Drill down token overrides to code component node instances and make sure the\n\t\t\t\t\t// colors in other children are updated with values\n\t\t\t\t\tapplyTokenOverridesToUnlinkedSmartComponentNode(engine, currentInstance, newNode)\n\t\t\t\t}\n\n\t\t\t\t// @TODO - It would be nice to remove the external module from the asset panel here,\n\t\t\t\t// without losing the external module information incase the unlink is undone.\n\t\t\t}\n\t\t\treturn newNode\n\t\t},\n\t\tscheduleTreeUpdate,\n\t})\n\treturn nextComponentNode\n}\n\nexport async function importExternalSmartComponent(\n\tengine: VekterEngine,\n\toptions: InternalImportExternalComponentFunctionOptions,\n): Promise<LoadedSmartComponentNode | undefined> {\n\tconst nextSmartComponentNode = await importExternalCanvasScopeNode(engine, options)\n\tif (!nextSmartComponentNode) return\n\n\tassert(isSmartComponentNode(nextSmartComponentNode), \"node should be a smart component\")\n\tconst { isAutoDetach } = options\n\t// If not detaching into a temporary tree, wait until the local smart\n\t// component is compiled before returning the local identifier.\n\tif (!isAutoDetach) await engine.stores.codeGenerationStore.untilCompiled(nextSmartComponentNode.id)\n\treturn nextSmartComponentNode.draftOrCurrent()\n}\n\nexport async function importExternalWebPageNode(\n\tengine: VekterEngine,\n\tidentifier: ExternalModuleExportIdentifier,\n): Promise<ImportableComponentNode | undefined> {\n\tconst [info] = await engine.stores.modulesStore.preloadExternalModules([identifier])\n\tif (!info) return\n\n\tconst nextWebPageNode = await importExternalCanvasScopeNode(engine, {\n\t\tidentifier,\n\t\tenterIsolation: false,\n\t\tinfo,\n\t})\n\tassert(isWebPageNode(nextWebPageNode), \"node should be a web page\")\n\n\tconst { path, suggestedName } = getUniquePagePath(\n\t\tnextWebPageNode.resolveValue(\"name\") ?? Dictionary.Page,\n\t\tengine.tree,\n\t\tengine.componentLoader,\n\t\tnextWebPageNode,\n\t\ttrue,\n\t)\n\n\tengine.scheduler.processWhenReady(() => {\n\t\tengine.tree.current(nextWebPageNode)?.set({ name: suggestedName, pagePath: path })\n\n\t\tconst activeScope = engine.stores.scopeStore.active\n\t\tif (isEmptyWebPage(activeScope)) {\n\t\t\treplaceWebPage(engine, activeScope, nextWebPageNode)\n\t\t}\n\n\t\tengine.stores.scopeStore.select(nextWebPageNode.id, { keepHistory: false })\n\t})\n\n\treturn nextWebPageNode\n}\n", "import type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { EntityFolderNode } from \"document/models/CanvasTree/nodes/EntityFolderNode.ts\"\nimport { EntityReferenceNode } from \"document/models/CanvasTree/nodes/EntityReferenceNode.ts\"\nimport {\n\tAB_TESTS_ENTITY_TYPE_ROOT_ID,\n\tBLOCKQUOTE_ENTITY_ROOT_ID,\n\tCMS_ENTITY_ROOT_ID,\n\tCODE_FILE_ENTITY_TYPE_ROOT_ID,\n\tCOLOR_ENTITY_ROOT_ID,\n\tCOMPONENTS_ENTITY_TYPE_ROOT_ID,\n\tCONTENT_MANAGEMENT_ENTITY_TYPE_ROOT_ID,\n\ttype EntityTypeRootId,\n\tFUNNELS_ENTITY_TYPE_ROOT_ID,\n\tINLINE_CODE_ENTITY_ROOT_ID,\n\tLAYOUT_TEMPLATE_ENTITY_ROOT_ID,\n\tLINK_ENTITY_ROOT_ID,\n\tTEXT_ENTITY_ROOT_ID,\n\tVECTOR_SET_ENTITY_TYPE_ROOT_ID,\n\tisEntityTypeRootNode,\n} from \"document/models/CanvasTree/nodes/EntityTypeRootNode.ts\"\nimport { isEntityFolderNode, isEntityReferenceNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { assert, assertNever } from \"library/utils/assert.ts\"\nimport { isNull } from \"utils/typeChecks.ts\"\n\n/**\n * Expands ancestors of a reference node which can be folder or root nodes or of an original node\n * which are always root nodes.\n *\n * @param engine VekterEngine.\n * @param id The id of an original node. We need to check if reference for it exists.\n * @param popout Whether the folder is expanded in the popout or not.\n */\nexport function expandAssetEntityItemsFromNode(\n\tengine: VekterEngine,\n\tid: NodeID,\n\trootId: EntityTypeRootId,\n\tpopout: boolean,\n) {\n\tconst isCodeFile = rootId === CODE_FILE_ENTITY_TYPE_ROOT_ID\n\tconst referenceNode = EntityReferenceNode.get(engine.tree, id, isCodeFile)\n\tif (isNull(referenceNode)) {\n\t\texpandAssetEntityItems(engine, rootId, popout)\n\t\treturn\n\t}\n\n\tif (!referenceNode.parentid) return\n\n\texpandAssetEntityItems(engine, referenceNode.parentid, popout)\n}\n\n/**\n * Expands the given folder entity node and all its ancestors.\n *\n * If the node is a type root, it expands the section and root folder. If the node is a\n * folder, it expands all the parent folders, the root folder and the section.\n * @param engine VekterEngine.\n * @param nodeId The id of a folder or type root node.\n * @param popout Whether the folder is expanded in the popout or not.\n */\nexport function expandAssetEntityItems(engine: VekterEngine, nodeId: NodeID, popout: boolean) {\n\tconst node = engine.tree.get(nodeId)\n\tif (isNull(node)) return\n\n\t// If node is an entity type root we just need to expand section and root folder\n\t// Code files do not display a root folder but no point in handling it differently\n\tif (isEntityTypeRootNode(node)) {\n\t\texpandSectionItem(engine, node.id)\n\t\tengine.stores.chromeStore.expandAssetEntityItem(node.id, popout)\n\t\treturn\n\t}\n\n\tif (!isEntityFolderNode(node)) return\n\n\tconst allFolderAncestorsIds = new Set<NodeID>()\n\n\t// Always expand direct parent folder\n\tallFolderAncestorsIds.add(nodeId)\n\n\tfor (const ancestor of node.ancestors()) {\n\t\tif (isEntityTypeRootNode(ancestor)) {\n\t\t\tallFolderAncestorsIds.add(ancestor.id)\n\n\t\t\t// Also make sure we expand the section root\n\t\t\texpandSectionItem(engine, ancestor.id)\n\t\t} else if (isEntityFolderNode(ancestor)) {\n\t\t\tallFolderAncestorsIds.add(ancestor.id)\n\t\t}\n\t}\n\n\tengine.stores.chromeStore.expandAssetEntityItems(allFolderAncestorsIds, popout)\n}\n\nfunction expandSectionItem(engine: VekterEngine, nodeId: EntityTypeRootId) {\n\tswitch (nodeId) {\n\t\tcase CODE_FILE_ENTITY_TYPE_ROOT_ID:\n\t\t\tif (!engine.stores.chromeStore.codeFilesExpanded) {\n\t\t\t\tengine.stores.chromeStore.toggleCodeFiles()\n\t\t\t}\n\t\t\tbreak\n\t\tcase COMPONENTS_ENTITY_TYPE_ROOT_ID:\n\t\t\tif (!engine.stores.chromeStore.componentsExpanded) {\n\t\t\t\tengine.stores.chromeStore.toggleComponents()\n\t\t\t}\n\t\t\tbreak\n\t\tcase LAYOUT_TEMPLATE_ENTITY_ROOT_ID:\n\t\t\tif (!engine.stores.chromeStore.layoutTemplatesExpanded) {\n\t\t\t\tengine.stores.chromeStore.toggleLayoutTemplates()\n\t\t\t}\n\t\t\tbreak\n\t\tcase VECTOR_SET_ENTITY_TYPE_ROOT_ID:\n\t\t\tif (!engine.stores.chromeStore.vectorSetsExpanded) {\n\t\t\t\tengine.stores.chromeStore.toggleVectorSets()\n\t\t\t}\n\t\t\tbreak\n\t\tcase BLOCKQUOTE_ENTITY_ROOT_ID:\n\t\tcase CMS_ENTITY_ROOT_ID:\n\t\tcase COLOR_ENTITY_ROOT_ID:\n\t\tcase INLINE_CODE_ENTITY_ROOT_ID:\n\t\tcase LINK_ENTITY_ROOT_ID:\n\t\tcase TEXT_ENTITY_ROOT_ID:\n\t\t\tif (!engine.stores.chromeStore.stylesExpanded) {\n\t\t\t\tengine.stores.chromeStore.toggleStyles()\n\t\t\t}\n\t\t\tbreak\n\t\tcase FUNNELS_ENTITY_TYPE_ROOT_ID:\n\t\tcase AB_TESTS_ENTITY_TYPE_ROOT_ID:\n\t\tcase CONTENT_MANAGEMENT_ENTITY_TYPE_ROOT_ID:\n\t\t\t// These sections don't have expand/collapse toggles in Assets panel\n\t\t\tbreak\n\n\t\tdefault:\n\t\t\tassertNever(nodeId)\n\t}\n}\n\nexport function getFolderAndReferencedIdsForSelection(\n\tengine: VekterEngine,\n\tselectedIds: ReadonlySet<NodeID>,\n): { folderIds: Set<NodeID>; referencedIds: Set<NodeID> } {\n\tconst folderIds = new Set<NodeID>()\n\tconst referencedIds = new Set<NodeID>()\n\tconst nodes = engine.tree.getNodes(selectedIds)\n\n\tfor (const node of engine.tree.withoutDescendants(nodes)) {\n\t\tif (isEntityFolderNode(node)) {\n\t\t\t// We traverse the descendants of the folder to categorize the nodes into folders and references\n\t\t\tfor (const descendant of node.walk()) {\n\t\t\t\tif (isEntityReferenceNode(descendant)) {\n\t\t\t\t\treferencedIds.add(descendant.referenceId)\n\t\t\t\t}\n\n\t\t\t\tif (isEntityFolderNode(descendant)) {\n\t\t\t\t\tfolderIds.add(descendant.id)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treferencedIds.add(node.id)\n\t\t}\n\t}\n\treturn { folderIds, referencedIds }\n}\n\n/** Filters a set of folder IDs down to only those whose folder node exists and has no non-folder descendants. */\nexport function getEmptyFolderIds(engine: VekterEngine, folderIds: Set<NodeID>): Set<NodeID> {\n\tconst emptyFolderIds = new Set<NodeID>()\n\n\tfor (const id of folderIds) {\n\t\tconst node = engine.tree.get(id)\n\t\tassert(isEntityFolderNode(node), `Expected folder node for id ${id}`)\n\n\t\tif (!isFolderEmpty(node)) continue\n\t\temptyFolderIds.add(id)\n\t}\n\n\treturn emptyFolderIds\n}\n\nfunction isFolderEmpty(node: EntityFolderNode): boolean {\n\tfor (const descendant of node.descendants()) {\n\t\tif (!isEntityFolderNode(descendant)) return false\n\t}\n\treturn true\n}\n", "import type { ComponentLoader, DataDefinition } from \"@framerjs/framer-runtime\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { AnyWebPageNode, CanvasTree, NodeID, ShallowWebPageNode } from \"document/models/CanvasTree/index.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { FALLBACK_PATH, getWebPagePath } from \"./getWebPagePath.ts\"\n\nexport function getWebPageDisplayTitle(\n\ttree: CanvasTree,\n\twebPage: AnyWebPageNode,\n\tcollectionData: DataDefinition | null,\n): string {\n\tconst isHomePage = tree.root.homePageNodeId === webPage.id\n\tif (isHomePage) return Dictionary.Home\n\n\tif (webPage.dataIdentifier) {\n\t\treturn collectionData ? `${collectionData.name} Pages` : \"No Name\"\n\t}\n\n\treturn getWebPagePath(tree, webPage) || FALLBACK_PATH\n}\n\nexport function getTitleForWebPage(tree: CanvasTree, componentLoader: ComponentLoader, webPage: ShallowWebPageNode) {\n\tconst data = hasCollectionDataSource(webPage) ? componentLoader.dataForIdentifier(webPage.dataIdentifier) : null\n\treturn getWebPageDisplayTitle(tree, webPage, data)\n}\n\nexport function getTitleForWebPageId(tree: CanvasTree, componentLoader: ComponentLoader, id: NodeID) {\n\tconst webPage = tree.get(id)\n\tif (!isWebPageNode(webPage)) return Dictionary.Missing\n\treturn getTitleForWebPage(tree, componentLoader, webPage)\n}\n", "import type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { getRawWebPagePath } from \"document/components/utils/getWebPagePath.ts\"\nimport { pathToName } from \"document/components/utils/pathToName.ts\"\nimport { getWebPageDisplayTitle } from \"document/components/utils/webPageTitles.ts\"\nimport type { LoadedAnalyticsScopeNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { AB_TESTS_ENTITY_TYPE_ROOT_ID } from \"document/models/CanvasTree/nodes/EntityTypeRootNode.ts\"\nimport { FunnelNode } from \"document/models/CanvasTree/nodes/FunnelNode.ts\"\nimport { FunnelStepActionNode } from \"document/models/CanvasTree/nodes/FunnelStepActionNode.ts\"\nimport { FunnelStepNode } from \"document/models/CanvasTree/nodes/FunnelStepNode.ts\"\nimport { createReferenceAlways } from \"document/models/CanvasTree/nodes/utils/entityReferenceNode.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { record } from \"web/lib/tracker.ts\"\n\n/** Creates a new A/B test funnel for a page and returns its id, or returns the id of the existing one */\nexport const configureAbTest = function (\n\tengine: VekterEngine,\n\twebPageId: NodeID,\n\tanalyticsScope: LoadedAnalyticsScopeNode,\n): NodeID | undefined {\n\tlet webPage = engine.tree.getNodeWithTrait(webPageId, isWebPageNode)\n\tif (!webPage) return\n\n\t// Resolve the control page if called with a variant page id\n\tif (webPage.abTestingParentId) {\n\t\twebPage = engine.tree.getNodeWithTrait(webPage.abTestingParentId, isWebPageNode)\n\t}\n\tif (!webPage) return\n\n\t// Check if the funnel already exists\n\tconst funnel = webPage.getAbTestingFunnel(analyticsScope)\n\tif (funnel) return funnel.id\n\n\tconst data = hasCollectionDataSource(webPage)\n\t\t? engine.componentLoader.dataForIdentifier(webPage.dataIdentifier)\n\t\t: null\n\tconst title = getWebPageDisplayTitle(engine.tree, webPage, data)\n\tconst newFunnel = new FunnelNode({\n\t\tname: pathToName(title),\n\t\tabTestingParentId: webPage.id,\n\t})\n\tconst step = new FunnelStepNode({ name: `View ${title}` })\n\tconst action = new FunnelStepActionNode({\n\t\ttrackingEventType: \"pageview\",\n\t\ttrackingRoutePath: getRawWebPagePath(engine.tree, webPage),\n\t})\n\tstep.addChild(action)\n\tnewFunnel.addChild(step)\n\tengine.tree.insertNode(newFunnel, analyticsScope.id)\n\n\t// Create a reference at the AB tests type root so the test is properly tracked\n\t// This ensures drag/drop into folders works correctly\n\tcreateReferenceAlways(engine.tree, AB_TESTS_ENTITY_TYPE_ROOT_ID, newFunnel.id)\n\n\trecord(\"funnel_create\", { funnelId: newFunnel.id, abTestingParentId: webPage.id })\n\trecord(\"funnel_step_create\", { funnelId: newFunnel.id, stepId: step.id, eventType: \"pageview\", actionCount: 1 })\n\treturn newFunnel.id\n}\n", "import { emptyArray } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { duplicateCustomCodeForPage } from \"document/components/chrome/siteSettings/CustomCode/utils/duplicateCustomCodeForPage.ts\"\nimport { cloneScopeNodeWithVariants } from \"document/components/unlinking/importExternalSmartComponentOrWebpage.ts\"\nimport { AnalyticsScopeNode, type LoadedWebPageNode, type NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { buildEntityReferenceNodeId } from \"document/models/CanvasTree/nodes/EntityReferenceNode.ts\"\nimport { ROUTE_SEGMENT_ROOT_NODE_ID } from \"document/models/CanvasTree/nodes/RouteSegmentRootNode.ts\"\nimport { getWebPageRecord } from \"document/models/CanvasTree/records/WebPageRecord.ts\"\nimport { ActiveContentPanelTab } from \"document/utils/ActiveEditorType.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport { getRouteSegmentNodeByWebPageId } from \"../../Pages/utils/getRouteSegmentNodeByWebPageId.ts\"\nimport { expandAssetEntityItems } from \"../../assets/utils/expandAssetEntityItems.ts\"\nimport { configureAbTest } from \"./configureAbTest.ts\"\n\n/**\n * Adds a new A/B testing variant to the given web page by cloning it.\n * @param parentFolderId Optional folder ID to place the A/B test reference inside after configuration\n */\nexport function addAbVariant(engine: VekterEngine, webPage: LoadedWebPageNode, parentFolderId?: NodeID) {\n\tconst variants = webPage.getAbTestingChildren(engine.tree) ?? emptyArray()\n\tlet preferredName: string | undefined\n\n\tfor (let i = 0; i <= variants.length; i++) {\n\t\tconst name = i === 0 ? Dictionary.Variant : `${Dictionary.Variant} ${i}`\n\t\tif (variants.every(v => v.name !== name)) {\n\t\t\tpreferredName = name\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Insert after the last variant\n\tconst lastVariant = variants[variants.length - 1] ?? webPage\n\tconst newWebPage = cloneScopeNodeWithVariants(engine, webPage, webPage.getPrimaryVariant(), \"duplicate\", {\n\t\tenterIsolation: false,\n\t\tpreferredName,\n\t\tinsertionIndex: engine.tree.root.children.findIndex(child => child.id === lastVariant.id) + 1,\n\t\tabTesting: true,\n\t})\n\n\t// We may be cloning a variant, in which case we should use its `abTestingParentId`\n\t// Additionally, A/B testing variants should be always created undrafted\n\t// Ensure the new variant is assigned the default distribution weight\n\tnewWebPage.set({\n\t\tabTestingParentId: webPage.abTestingParentId ?? webPage.id,\n\t\tabTestingDistributionWeightPpm: getWebPageRecord().abTestingDistributionWeightPpm,\n\t\tisDraft: undefined,\n\t})\n\n\t// Duplicate custom code references from the original page to the new variant\n\tduplicateCustomCodeForPage(engine, webPage.id, newWebPage.id)\n\n\t// Track the creation of the new variant\n\trecord(\"ab_variant_create\", { pageId: newWebPage.id, abTestingParentId: webPage.abTestingParentId ?? webPage.id })\n\n\t// This will switch to the new scope and zoom/scroll it with our default behavior.\n\tengine.stores.scopeStore.select(newWebPage.id, { keepHistory: false })\n\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Pages\n\n\t// If this is the control page, we need to expand the route segment\n\tif (!webPage.abTestingParentId) {\n\t\tconst routeSegmentId = getRouteSegmentNodeByWebPageId(engine.tree, webPage.id)?.id ?? ROUTE_SEGMENT_ROOT_NODE_ID\n\t\tif (routeSegmentId) engine.stores.chromeStore.expandRouteSegment(routeSegmentId)\n\t}\n\n\t// If a folder was specified, configure the A/B test and move its reference to the folder\n\tif (parentFolderId) {\n\t\tconst analyticsScope = AnalyticsScopeNode.ensure(engine.tree)\n\t\tengine.loadScopesThenProcess([analyticsScope], ([loadedAnalyticsScope]) => {\n\t\t\tif (!loadedAnalyticsScope) return\n\t\t\tconst abTestFunnelId = configureAbTest(engine, webPage.id, loadedAnalyticsScope)\n\t\t\tif (abTestFunnelId) {\n\t\t\t\t// configureAbTest creates the reference at the type root, move it to the folder\n\t\t\t\tconst referenceId = buildEntityReferenceNodeId(abTestFunnelId)\n\t\t\t\tconst referenceNode = engine.tree.get(referenceId)\n\t\t\t\tif (referenceNode) {\n\t\t\t\t\tengine.tree.moveNode(referenceNode, parentFolderId)\n\t\t\t\t}\n\t\t\t\texpandAssetEntityItems(engine, parentFolderId, false)\n\t\t\t}\n\t\t})\n\t}\n}\n", "import type { ModalOpenSource } from \"@framerjs/framer-events\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { LoadedAnalyticsScopeNode, LoadedWebPageNode } from \"document/models/CanvasTree/index.ts\"\nimport { FunnelStatus } from \"document/models/CanvasTree/nodes/FunnelNode.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { showAbTestUpsell } from \"../../shared/UpsellModal/utils/abTestUpsellModals.ts\"\nimport { showAnalyticsEventsUpsell } from \"../../shared/UpsellModal/utils/analyticsEventsUpsellModals.ts\"\nimport { addAbVariant } from \"./addAbVariant.ts\"\n\n/**\n * Adds a new A/B testing variant to the given web page.\n * Generates a unique name: `Variant`, `Variant 1`, `Variant 2`, etc.\n * Navigates to the new variant after creation.\n */\nexport function promptAddAbVariant(\n\tengine: VekterEngine,\n\twebPage: LoadedWebPageNode,\n\tanalyticsScope: LoadedAnalyticsScopeNode | null,\n\tsource: ModalOpenSource,\n) {\n\tif (showAbTestUpsell(engine, source, { isAddingTest: false })) return\n\tif (showAnalyticsEventsUpsell(engine, source)) return\n\n\tconst isRunning = webPage.getAbTestingFunnel(analyticsScope)?.status === FunnelStatus.Started\n\tconst onConfirm = engine.scheduler.wrapHandler(() => addAbVariant(engine, webPage))\n\tif (!isRunning) return onConfirm()\n\n\tengine.stores.modalStore.set({\n\t\ttype: ModalType.ConfirmUpdatingAbVariants,\n\t\tsource,\n\t\ttitle: \"Updating Variants\",\n\t\tdescription: \"Updating variants while running an A/B test could potentially skew your results.\",\n\t\tconfirmLabel: \"Confirm\",\n\t\tonConfirm,\n\t\tvariant: \"destructive\",\n\t})\n}\n", "import { triggerPropertyLayoutUpdateEvent } from \"@framerjs/framer-events\"\nimport { assertNever } from \"@framerjs/shared\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isPinnable } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\n\nfunction dimensionTypeToTrackingEventString(dimensionType?: DimensionType): string | undefined {\n\tif (dimensionType === undefined) {\n\t\treturn undefined\n\t}\n\tswitch (dimensionType) {\n\t\tcase DimensionType.Auto:\n\t\t\treturn \"auto\"\n\t\tcase DimensionType.FixedNumber:\n\t\t\treturn \"fixed\"\n\t\tcase DimensionType.FractionOfFreeSpace:\n\t\t\treturn \"fraction\"\n\t\tcase DimensionType.Percentage:\n\t\t\treturn \"percentage\"\n\t\tcase DimensionType.Viewport:\n\t\t\treturn \"viewport\"\n\t\tcase DimensionType.FitImage:\n\t\t\treturn \"fit-image\"\n\t\tdefault:\n\t\t\tassertNever(dimensionType)\n\t}\n}\n\nexport function trackDimensionTypeChange(\n\tnode: CanvasNode,\n\t{ widthType, heightType }: { widthType?: DimensionType; heightType?: DimensionType },\n\tsource: string,\n) {\n\tif (!isPinnable(node)) return\n\tconst widthTypeDidChange = widthType !== undefined && node.widthType !== widthType\n\tconst heightTypeDidChange = heightType !== undefined && node.heightType !== heightType\n\tif (!widthTypeDidChange && !heightTypeDidChange) return\n\ttriggerPropertyLayoutUpdateEvent({\n\t\twidthType: dimensionTypeToTrackingEventString(widthType),\n\t\theightType: dimensionTypeToTrackingEventString(heightType),\n\t\tsource,\n\t\tnodeType: node.__class,\n\t\tcomponentId: isCodeComponentNode(node) ? node.codeComponentIdentifier : undefined,\n\t})\n}\n", "import type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isShapeContainerNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\n\nexport function countChildNodes(node: CanvasNode) {\n\tif (!withChildren(node)) return 0\n\tif (isShapeContainerNode(node)) return 0\n\tlet count = 0\n\n\tconst directChildCount = node.children.length\n\tcount += directChildCount\n\n\tnode.children.forEach(child => {\n\t\tcount += countChildNodes(child)\n\t})\n\n\treturn count\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { isEmptyObject } from \"@framerjs/shared\"\nimport type {\n\tAnyNodeKey,\n\tAnyNodeUpdate,\n\tCanvasNode,\n\tCanvasTree,\n\tCodeComponentNode,\n\tNodeID,\n} from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isComputedValueFromVariableReference } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport type { CombinedVariableProviderValueMap } from \"document/models/CanvasTree/traits/VariableProvider.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { EventActionMap } from \"document/models/CanvasTree/traits/WithEventActions.ts\"\nimport type { ReplicaNodeOverrides } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport {\n\ttype VariableID,\n\tisArrayVariable,\n\tisVariableDefinition,\n\twithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport type { IsVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { EagerVariableProviderMap } from \"document/models/CanvasTree/traits/utils/EagerVariableProviderMap.ts\"\nimport { allComputedValueFromVariableKeys } from \"document/models/CanvasTree/utils/allVariableKeys.ts\"\nimport { getNodeUpdateResolvingDynamicValues } from \"document/models/CanvasTree/utils/getNodeUpdateResolvingDynamicValues.ts\"\nimport type { RawControlProp } from \"document/models/controlProps/RawControlProp.ts\"\nimport { isRawControlProp } from \"document/models/controlProps/RawControlProp.ts\"\nimport {\n\tisPrefixedControlPropKey,\n\tprefixControlPropKey,\n\tremoveControlPropKeyPrefix,\n} from \"document/models/controlProps/controlPropKey.ts\"\nimport { getControlPropValues } from \"document/models/controlProps/getControlPropValues.ts\"\nimport { getControlProps } from \"document/models/controlProps/getControlProps.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { isKeySetAndNotInherited } from \"utils/isKeySetAndNotInherited.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\nimport { type GetUpdatedVariableReference, generateVariableReferenceUpdateForNode } from \"utils/updateDynamicValues.ts\"\n\n/**\n * Remaps repeated-item variable references inside instance control props to the detached replacement scope.\n */\nexport function getDetachedRepeatVariableControlPropUpdate(\n\ttree: CanvasTree,\n\tinstance: CodeComponentNode,\n\tdetachedVariableProviderId?: NodeID,\n): AnyNodeUpdate | undefined {\n\tif (!detachedVariableProviderId) return\n\n\tconst primaryInstance = tree.getNodeWithTrait(instance.getPrimaryId(), isCodeComponentNode)\n\tconst repeatArray = instance.repeatArray ?? primaryInstance?.repeatArray\n\tif (!repeatArray) return\n\n\tconst repeatItemVariableIds = getRepeatItemVariableIds(tree, instance, repeatArray)\n\tif (repeatItemVariableIds.size === 0) return\n\n\tconst sourceInstances = [instance]\n\tif (primaryInstance && primaryInstance !== instance) {\n\t\tsourceInstances.unshift(primaryInstance)\n\t}\n\tconst update: AnyNodeUpdate = {}\n\tfor (const sourceInstance of sourceInstances) {\n\t\tconst sourceUpdate = generateVariableReferenceUpdateForNode(tree, sourceInstance, reference => {\n\t\t\tif (!isReferenceToInstanceRepeatProvider(reference, sourceInstance, repeatItemVariableIds)) return\n\n\t\t\treturn {\n\t\t\t\t...reference,\n\t\t\t\tproviderId: detachedVariableProviderId,\n\t\t\t}\n\t\t})\n\t\tif (!sourceUpdate) continue\n\n\t\tfor (const [key, value] of Object.entries(sourceUpdate)) {\n\t\t\tif (sourceInstance !== instance && isKeySetAndNotInherited(tree, instance, key)) continue\n\t\t\tObject.assign(update, { [key]: value })\n\t\t}\n\t}\n\n\treturn isEmptyObject(update) ? undefined : update\n}\n\nfunction getRepeatItemVariableIds(\n\ttree: CanvasTree,\n\tinstance: CodeComponentNode,\n\trepeatArray: VariableReference,\n): ReadonlySet<VariableID> {\n\tconst providerNode = repeatArray.providerId ? tree.getNode(repeatArray.providerId) : tree.getScopeNodeFor(instance)\n\tif (!withVariables(providerNode)) return new Set()\n\n\tconst repeatVariable = providerNode.getVariable(repeatArray.id)\n\tif (!repeatVariable || !isArrayVariable(repeatVariable)) return new Set()\n\n\treturn new Set(repeatVariable.itemVariables.filter(isVariableDefinition).map(variable => variable.id))\n}\n\nfunction isReferenceToInstanceRepeatProvider(\n\treference: VariableReference,\n\tinstance: CodeComponentNode,\n\trepeatItemVariableIds: ReadonlySet<VariableID>,\n): boolean {\n\tif (!repeatItemVariableIds.has(reference.id)) return false\n\tif (!reference.providerId) return true\n\t// Replica instance overrides are keyed by the primary instance id, so repeat item refs may still use that provider.\n\treturn reference.providerId === instance.id || reference.providerId === instance.getPrimaryId()\n}\n\nfunction isReferenceToScope(reference: VariableReference, scopeId: NodeID): boolean {\n\treturn (reference.providerId ?? scopeId) === scopeId\n}\n\nfunction getUpdatedRepeatVariableControlProp(\n\tcontrolKey: string,\n\trepeatVariableControlPropUpdate: AnyNodeUpdate,\n): RawControlProp | undefined {\n\tconst updatedControlProp = repeatVariableControlPropUpdate?.[prefixControlPropKey(controlKey)]\n\treturn isRawControlProp(updatedControlProp) ? updatedControlProp : undefined\n}\n\n/**\n * Preserves computed values that are backed by instance-level repeated-item control props.\n * Plain VariableReferences are remapped by generateVariableReferenceUpdateForNode.\n */\nexport function getDetachedNodeComputedValueUpdate(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\toriginalScopeId: NodeID,\n\trepeatVariableControlPropUpdate: AnyNodeUpdate | undefined,\n): AnyNodeUpdate | undefined {\n\tif (!repeatVariableControlPropUpdate) return\n\n\tconst update: AnyNodeUpdate = {}\n\tfor (const key of allComputedValueFromVariableKeys) {\n\t\tif (!(key in node)) continue\n\t\tif (!isKeySetAndNotInherited(tree, node, key)) continue\n\n\t\tconst rawValue = node[key as keyof typeof node]\n\t\tif (!isVariableReference(rawValue) || !isReferenceToScope(rawValue, originalScopeId)) continue\n\n\t\tconst rawControlProp = getUpdatedRepeatVariableControlProp(rawValue.id, repeatVariableControlPropUpdate)\n\t\tif (!rawControlProp || !isComputedValueFromVariableReference(rawControlProp.value)) continue\n\n\t\tObject.assign(update, { [key]: rawControlProp.value })\n\t}\n\n\treturn isEmptyObject(update) ? undefined : update\n}\n\nexport function getDetachedControlPropValues(\n\tinstance: CodeComponentNode,\n\tcomponentLoader: ComponentLoader,\n\trepeatVariableControlPropUpdate: AnyNodeUpdate | undefined,\n) {\n\tconst propertyControls = componentLoader.getPropertyControlsForIdentifier(instance.codeComponentIdentifier)\n\tif (!propertyControls) return {}\n\n\t// Remap instance-scoped repeated-item refs so detached layers resolve them from the replacement node.\n\tconst rawControlProps: Record<string, RawControlProp | undefined> = { ...instance.getRawControlProps() }\n\tif (repeatVariableControlPropUpdate) {\n\t\tfor (const key in repeatVariableControlPropUpdate) {\n\t\t\tif (!isPrefixedControlPropKey(key)) continue\n\n\t\t\tconst controlKey = removeControlPropKeyPrefix(key)\n\t\t\tconst updatedControlProp = repeatVariableControlPropUpdate[key]\n\t\t\tif (isRawControlProp(updatedControlProp)) rawControlProps[controlKey] = updatedControlProp\n\t\t}\n\t}\n\n\tconst controlProps = getControlProps(propertyControls, rawControlProps)\n\treturn getControlPropValues(propertyControls, controlProps)\n}\n\nexport function replicaOverridesForInstanceVariables(\n\tsource: CanvasNode & IsVariant,\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tinstance: CodeComponentNode,\n\toriginalScopeId: NodeID,\n\tdetachedVariableProviderId?: NodeID,\n) {\n\tconst repeatVariableControlPropUpdate = getDetachedRepeatVariableControlPropUpdate(\n\t\ttree,\n\t\tinstance,\n\t\tdetachedVariableProviderId,\n\t)\n\tconst controlPropValues = getDetachedControlPropValues(instance, componentLoader, repeatVariableControlPropUpdate)\n\tconst variableValues = new EagerVariableProviderMap(Object.entries(controlPropValues))\n\tconst variableValuesByProvider: CombinedVariableProviderValueMap = new Map()\n\tvariableValuesByProvider.set(originalScopeId, variableValues)\n\tconst detachedVariableReferenceUpdate = getDetachedInstanceVariableReferenceUpdate(\n\t\toriginalScopeId,\n\t\trepeatVariableControlPropUpdate,\n\t)\n\n\tconst updates: Record<NodeID, Partial<Record<AnyNodeKey, unknown>>> = {}\n\tfor (const descendant of source.walk()) {\n\t\tconst descendantId = descendant.getPrimaryId()\n\n\t\tconst variableToPropertyMap = getNodeUpdateResolvingDynamicValues(\n\t\t\ttree,\n\t\t\toriginalScopeId,\n\t\t\tdescendant,\n\t\t\tvariableValuesByProvider,\n\t\t)\n\t\tif (variableToPropertyMap) {\n\t\t\tupdates[descendantId] = {\n\t\t\t\t...updates[descendantId],\n\t\t\t\t...variableToPropertyMap,\n\t\t\t}\n\t\t}\n\n\t\t// Later updates intentionally win: reference remapping preserves live repeat bindings,\n\t\t// and computed preservation restores values that source-scope cleanup would otherwise flatten.\n\t\tif (detachedVariableReferenceUpdate) {\n\t\t\tconst dynamicReferenceUpdate = generateVariableReferenceUpdateForNode(\n\t\t\t\ttree,\n\t\t\t\tdescendant,\n\t\t\t\tdetachedVariableReferenceUpdate,\n\t\t\t)\n\t\t\tif (dynamicReferenceUpdate) {\n\t\t\t\tupdates[descendantId] = {\n\t\t\t\t\t...updates[descendantId],\n\t\t\t\t\t...dynamicReferenceUpdate,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst detachedNodeComputedValueUpdate = getDetachedNodeComputedValueUpdate(\n\t\t\ttree,\n\t\t\tdescendant,\n\t\t\toriginalScopeId,\n\t\t\trepeatVariableControlPropUpdate,\n\t\t)\n\t\tif (detachedNodeComputedValueUpdate) {\n\t\t\tupdates[descendantId] = {\n\t\t\t\t...updates[descendantId],\n\t\t\t\t...detachedNodeComputedValueUpdate,\n\t\t\t}\n\t\t}\n\n\t\tif (descendantId === source.id && instance.repeatArray && updates[descendantId]) {\n\t\t\tdelete updates[descendantId].repeatArray\n\t\t}\n\t}\n\n\treturn updates\n}\n\nexport function getDetachedInstanceVariableReferenceUpdate(\n\toriginalScopeId: NodeID,\n\trepeatVariableControlPropUpdate: AnyNodeUpdate | undefined,\n): GetUpdatedVariableReference | undefined {\n\tif (!repeatVariableControlPropUpdate) return\n\n\treturn (reference: VariableReference) => {\n\t\tif (!isReferenceToScope(reference, originalScopeId)) return\n\n\t\tconst rawControlProp = getUpdatedRepeatVariableControlProp(reference.id, repeatVariableControlPropUpdate)\n\t\tif (!rawControlProp) return\n\t\tif (!isVariableReference(rawControlProp.value)) return\n\n\t\treturn rawControlProp.value\n\t}\n}\n\nexport function withoutPositionOrSizeOrNameProperties(overrides: ReplicaNodeOverrides) {\n\tconst {\n\t\tleft,\n\t\ttop,\n\t\tright,\n\t\tbottom,\n\t\tcenterAnchorX,\n\t\tcenterAnchorY,\n\t\tconstraintsLocked,\n\t\twidth,\n\t\twidthType,\n\t\theight,\n\t\theightType,\n\t\taspectRatio,\n\t\tname,\n\t\t...rest\n\t} = overrides\n\n\treturn rest\n}\n\nexport function getRawEventActions(componentLoader: ComponentLoader, instance: CodeComponentNode) {\n\tconst propertyControls = componentLoader.getPropertyControlsForIdentifier(instance.codeComponentIdentifier)\n\tif (!propertyControls) return\n\tconst instanceActions: EventActionMap = {}\n\tconst keys = Object.keys(propertyControls)\n\n\t// Get the raw, unmapped keys for each action so that we can associate them\n\t// with a relevant event variable. Using `CodeComponentNode.getActions()`\n\t// maps the keys to the human readable values which we can't use.\n\tfor (const key of keys) {\n\t\tconst control = propertyControls[key]\n\t\tif (!control || control.type !== ControlType.EventHandler) continue\n\n\t\tconst controlProp = instance.getRawControlProp(key)\n\t\tif (!controlProp) continue\n\t\tconst { value } = controlProp\n\t\tif (!Array.isArray(value) || value.length === 0) continue\n\n\t\tinstanceActions[key] = value\n\t}\n\n\treturn instanceActions\n}\n\nexport function blendNestedOpacityAndRotation(\n\tnodeOverridesA: ReplicaNodeOverrides,\n\t{\n\t\topacity,\n\t\trotation,\n\t}: { opacity?: number | VariableReference | unknown; rotation?: number | VariableReference | unknown },\n) {\n\tif (isVariableReference(opacity)) {\n\t\tnodeOverridesA.opacity = opacity\n\t} else if (nodeOverridesA?.opacity || opacity) {\n\t\tconst value = isNumber(opacity) ? opacity : 1\n\t\tnodeOverridesA.opacity = (nodeOverridesA.opacity ?? 1) * value\n\t}\n\n\tif (isVariableReference(rotation)) {\n\t\tnodeOverridesA.rotation = rotation\n\t} else if (nodeOverridesA?.rotation || rotation) {\n\t\tconst value = isNumber(rotation) ? rotation : 0\n\t\tnodeOverridesA.rotation = (nodeOverridesA.rotation ?? 0) + value\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { supportsAutoSizing } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport {\n\tconvertChildrenToFixedSizeAlongDimension,\n\tenableStackLayoutForNode,\n} from \"document/components/tools/utils/stackCreateHelper.ts\"\nimport type { CanvasNode, FrameNode } from \"document/models/CanvasTree/index.ts\"\nimport { isAnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport { isCodeComponentNode, isFrameNode, isRichTextNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { getChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { withFramePreset } from \"document/models/CanvasTree/traits/WithFramePreset.ts\"\nimport { hasStackLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { isBreakpointVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { record } from \"web/lib/tracker.ts\"\n\nexport type EventSource = \"context_menu\" | \"main_menu\"\n\n/**\n * Returns true if all nodes are frame nodes and can be auto-sized (Text and Stack nodes).\n */\nexport function isAutoSizeVisible(withoutDescendants: CanvasNode[]) {\n\treturn withoutDescendants.every(node => isFrameNode(node) || isAnyTextNode(node) || isCodeComponentNode(node))\n}\n\n/**\n * Returns true if all nodes are frame nodes and can be auto-sized (Text and Stack nodes).\n */\nexport function canAutoSizeNodes(\n\tcomponentLoader: ComponentLoader,\n\twithoutDescendants: CanvasNode[],\n\tisViewOnly: boolean,\n) {\n\tif (isViewOnly) return false\n\n\treturn withoutDescendants.every(node => {\n\t\tif (!isFrameNode(node) && !isCodeComponentNode(node) && !isRichTextNode(node)) return false\n\t\tif (isBreakpointVariant(node)) return false\n\t\tif (isFrameNode(node) && getChildren(node).length === 0) return false\n\t\tif (isCodeComponentNode(node)) {\n\t\t\tconst supportedLayout = node.getSupportedLayout(componentLoader)\n\t\t\tif (!supportsAutoSizing(supportedLayout.width) || !supportsAutoSizing(supportedLayout.height)) return false\n\t\t}\n\n\t\t// The option is enabled if at least one of the size types is not auto.\n\t\treturn node.widthType !== DimensionType.Auto || node.heightType !== DimensionType.Auto\n\t})\n}\n\nexport function enableAutoSizeForNodes(\n\tengine: VekterEngine,\n\twithoutDescendants: CanvasNode[],\n\teventSource?: EventSource,\n) {\n\tfor (const node of withoutDescendants) {\n\t\tif (isAnyTextNode(node) || isCodeComponentNode(node)) {\n\t\t\tnode.set({\n\t\t\t\twidthType: DimensionType.Auto,\n\t\t\t\theightType: DimensionType.Auto,\n\t\t\t})\n\n\t\t\tif (isAnyTextNode(node) && eventSource) record(\"layout_fit_text\", { source: eventSource })\n\t\t} else if (isFrameNode(node)) {\n\t\t\tconst update: Partial<FrameNode> = {\n\t\t\t\twidthType: DimensionType.Auto,\n\t\t\t\theightType: DimensionType.Auto,\n\t\t\t\taspectRatio: null,\n\t\t\t}\n\n\t\t\tif (!hasStackLayout(node)) enableStackLayoutForNode(engine, node, update)\n\n\t\t\tconvertChildrenToFixedSizeAlongDimension(engine.tree, \"width\", node)\n\t\t\tconvertChildrenToFixedSizeAlongDimension(engine.tree, \"height\", node)\n\n\t\t\tif (withFramePreset(node)) update.framePreset = null\n\n\t\t\tnode.set(update)\n\n\t\t\tif (eventSource) record(\"layout_stack\", { layoutType: \"stack\", source: eventSource })\n\t\t}\n\t}\n}\n", "/**\n * Symbol used for identifying AI SDK Error instances.\n * Enables checking if an error is an instance of AISDKError across package versions.\n */\nconst marker = 'vercel.ai.error';\nconst symbol = Symbol.for(marker);\n\n/**\n * Custom error class for AI SDK related errors.\n * @extends Error\n */\nexport class AISDKError extends Error {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The underlying cause of the error, if any.\n   */\n  readonly cause?: unknown;\n\n  /**\n   * Creates an AI SDK Error.\n   *\n   * @param {Object} params - The parameters for creating the error.\n   * @param {string} params.name - The name of the error.\n   * @param {string} params.message - The error message.\n   * @param {unknown} [params.cause] - The underlying cause of the error.\n   */\n  constructor({\n    name,\n    message,\n    cause,\n  }: {\n    name: string;\n    message: string;\n    cause?: unknown;\n  }) {\n    super(message);\n\n    this.name = name;\n    this.cause = cause;\n  }\n\n  /**\n   * Checks if the given error is an AI SDK Error.\n   * @param {unknown} error - The error to check.\n   * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n   */\n  static isInstance(error: unknown): error is AISDKError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  protected static hasMarker(error: unknown, marker: string): boolean {\n    const markerSymbol = Symbol.for(marker);\n    return (\n      error != null &&\n      typeof error === 'object' &&\n      markerSymbol in error &&\n      typeof error[markerSymbol] === 'boolean' &&\n      error[markerSymbol] === true\n    );\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_APICallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class APICallError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly url: string;\n  readonly requestBodyValues: unknown;\n  readonly statusCode?: number;\n\n  readonly responseHeaders?: Record<string, string>;\n  readonly responseBody?: string;\n\n  readonly isRetryable: boolean;\n  readonly data?: unknown;\n\n  constructor({\n    message,\n    url,\n    requestBodyValues,\n    statusCode,\n    responseHeaders,\n    responseBody,\n    cause,\n    isRetryable = statusCode != null &&\n      (statusCode === 408 || // request timeout\n        statusCode === 409 || // conflict\n        statusCode === 429 || // too many requests\n        statusCode >= 500), // server error\n    data,\n  }: {\n    message: string;\n    url: string;\n    requestBodyValues: unknown;\n    statusCode?: number;\n    responseHeaders?: Record<string, string>;\n    responseBody?: string;\n    cause?: unknown;\n    isRetryable?: boolean;\n    data?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.url = url;\n    this.requestBodyValues = requestBodyValues;\n    this.statusCode = statusCode;\n    this.responseHeaders = responseHeaders;\n    this.responseBody = responseBody;\n    this.isRetryable = isRetryable;\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is APICallError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_EmptyResponseBodyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class EmptyResponseBodyError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message = 'Empty response body' }: { message?: string } = {}) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is EmptyResponseBodyError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "export function getErrorMessage(error: unknown | undefined) {\n  if (error == null) {\n    return 'unknown error';\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return error.message;\n  }\n\n  return JSON.stringify(error);\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A function argument is invalid.\n */\nexport class InvalidArgumentError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly argument: string;\n\n  constructor({\n    message,\n    cause,\n    argument,\n  }: {\n    argument: string;\n    message: string;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.argument = argument;\n  }\n\n  static isInstance(error: unknown): error is InvalidArgumentError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidPromptError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A prompt is invalid. This error should be thrown by providers when they cannot\n * process a prompt.\n */\nexport class InvalidPromptError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly prompt: unknown;\n\n  constructor({\n    prompt,\n    message,\n    cause,\n  }: {\n    prompt: unknown;\n    message: string;\n    cause?: unknown;\n  }) {\n    super({ name, message: `Invalid prompt: ${message}`, cause });\n\n    this.prompt = prompt;\n  }\n\n  static isInstance(error: unknown): error is InvalidPromptError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidResponseDataError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Server returned a response with invalid data content.\n * This should be thrown by providers when they cannot parse the response from the API.\n */\nexport class InvalidResponseDataError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly data: unknown;\n\n  constructor({\n    data,\n    message = `Invalid response data: ${JSON.stringify(data)}.`,\n  }: {\n    data: unknown;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is InvalidResponseDataError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_JSONParseError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class JSONParseError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly text: string;\n\n  constructor({ text, cause }: { text: string; cause: unknown }) {\n    super({\n      name,\n      message:\n        `JSON parsing failed: ` +\n        `Text: ${text}.\\n` +\n        `Error message: ${getErrorMessage(cause)}`,\n      cause,\n    });\n\n    this.text = text;\n  }\n\n  static isInstance(error: unknown): error is JSONParseError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadAPIKeyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadAPIKeyError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message }: { message: string }) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is LoadAPIKeyError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadSettingError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadSettingError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message }: { message: string }) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is LoadSettingError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoContentGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when the AI provider fails to generate any content.\n */\nexport class NoContentGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({\n    message = 'No content generated.',\n  }: { message?: string } = {}) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is NoContentGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoSuchModelError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchModelError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly modelId: string;\n  readonly modelType:\n    | 'languageModel'\n    | 'embeddingModel'\n    | 'imageModel'\n    | 'transcriptionModel'\n    | 'speechModel'\n    | 'rerankingModel'\n    | 'videoModel';\n\n  constructor({\n    errorName = name,\n    modelId,\n    modelType,\n    message = `No such ${modelType}: ${modelId}`,\n  }: {\n    errorName?: string;\n    modelId: string;\n    modelType:\n      | 'languageModel'\n      | 'embeddingModel'\n      | 'imageModel'\n      | 'transcriptionModel'\n      | 'speechModel'\n      | 'rerankingModel'\n      | 'videoModel';\n    message?: string;\n  }) {\n    super({ name: errorName, message });\n\n    this.modelId = modelId;\n    this.modelType = modelType;\n  }\n\n  static isInstance(error: unknown): error is NoSuchModelError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_TooManyEmbeddingValuesForCallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class TooManyEmbeddingValuesForCallError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly provider: string;\n  readonly modelId: string;\n  readonly maxEmbeddingsPerCall: number;\n  readonly values: Array<unknown>;\n\n  constructor(options: {\n    provider: string;\n    modelId: string;\n    maxEmbeddingsPerCall: number;\n    values: Array<unknown>;\n  }) {\n    super({\n      name,\n      message:\n        `Too many values for a single embedding call. ` +\n        `The ${options.provider} model \"${options.modelId}\" can only embed up to ` +\n        `${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`,\n    });\n\n    this.provider = options.provider;\n    this.modelId = options.modelId;\n    this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n    this.values = options.values;\n  }\n\n  static isInstance(\n    error: unknown,\n  ): error is TooManyEmbeddingValuesForCallError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_TypeValidationError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport interface TypeValidationContext {\n  /**\n   * Field path in dot notation (e.g., \"message.metadata\", \"message.parts[3].data\")\n   */\n  field?: string;\n\n  /**\n   * Entity name (e.g., tool name, data type name)\n   */\n  entityName?: string;\n\n  /**\n   * Entity identifier (e.g., message ID, tool call ID)\n   */\n  entityId?: string;\n}\n\nexport class TypeValidationError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly value: unknown;\n  readonly context?: TypeValidationContext;\n\n  constructor({\n    value,\n    cause,\n    context,\n  }: {\n    value: unknown;\n    cause: unknown;\n    context?: TypeValidationContext;\n  }) {\n    let contextPrefix = 'Type validation failed';\n\n    if (context?.field) {\n      contextPrefix += ` for ${context.field}`;\n    }\n\n    if (context?.entityName || context?.entityId) {\n      contextPrefix += ' (';\n      const parts: string[] = [];\n      if (context.entityName) {\n        parts.push(context.entityName);\n      }\n      if (context.entityId) {\n        parts.push(`id: \"${context.entityId}\"`);\n      }\n      contextPrefix += parts.join(', ');\n      contextPrefix += ')';\n    }\n\n    super({\n      name,\n      message:\n        `${contextPrefix}: ` +\n        `Value: ${JSON.stringify(value)}.\\n` +\n        `Error message: ${getErrorMessage(cause)}`,\n      cause,\n    });\n\n    this.value = value;\n    this.context = context;\n  }\n\n  static isInstance(error: unknown): error is TypeValidationError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  /**\n   * Wraps an error into a TypeValidationError.\n   * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n   * Otherwise, it creates a new TypeValidationError.\n   *\n   * @param {Object} params - The parameters for wrapping the error.\n   * @param {unknown} params.value - The value that failed validation.\n   * @param {unknown} params.cause - The original error or cause of the validation failure.\n   * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n   * @returns {TypeValidationError} A TypeValidationError instance.\n   */\n  static wrap({\n    value,\n    cause,\n    context,\n  }: {\n    value: unknown;\n    cause: unknown;\n    context?: TypeValidationContext;\n  }): TypeValidationError {\n    if (\n      TypeValidationError.isInstance(cause) &&\n      cause.value === value &&\n      cause.context?.field === context?.field &&\n      cause.context?.entityName === context?.entityName &&\n      cause.context?.entityId === context?.entityId\n    ) {\n      return cause;\n    }\n\n    return new TypeValidationError({ value, cause, context });\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_UnsupportedFunctionalityError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class UnsupportedFunctionalityError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly functionality: string;\n\n  constructor({\n    functionality,\n    message = `'${functionality}' functionality not supported.`,\n  }: {\n    functionality: string;\n    message?: string;\n  }) {\n    super({ name, message });\n    this.functionality = functionality;\n  }\n\n  static isInstance(error: unknown): error is UnsupportedFunctionalityError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import type { JSONArray, JSONObject, JSONValue } from './json-value';\n\nexport function isJSONValue(value: unknown): value is JSONValue {\n  if (\n    value === null ||\n    typeof value === 'string' ||\n    typeof value === 'number' ||\n    typeof value === 'boolean'\n  ) {\n    return true;\n  }\n\n  if (Array.isArray(value)) {\n    return value.every(isJSONValue);\n  }\n\n  if (typeof value === 'object') {\n    return Object.entries(value).every(\n      ([key, val]) =>\n        typeof key === 'string' && (val === undefined || isJSONValue(val)),\n    );\n  }\n\n  return false;\n}\n\nexport function isJSONArray(value: unknown): value is JSONArray {\n  return Array.isArray(value) && value.every(isJSONValue);\n}\n\nexport function isJSONObject(value: unknown): value is JSONObject {\n  return (\n    value != null &&\n    typeof value === 'object' &&\n    Object.entries(value).every(\n      ([key, val]) =>\n        typeof key === 'string' && (val === undefined || isJSONValue(val)),\n    )\n  );\n}\n", "export var util;\n(function (util) {\n    util.assertEqual = (_) => { };\n    function assertIs(_arg) { }\n    util.assertIs = assertIs;\n    function assertNever(_x) {\n        throw new Error();\n    }\n    util.assertNever = assertNever;\n    util.arrayToEnum = (items) => {\n        const obj = {};\n        for (const item of items) {\n            obj[item] = item;\n        }\n        return obj;\n    };\n    util.getValidEnumValues = (obj) => {\n        const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n        const filtered = {};\n        for (const k of validKeys) {\n            filtered[k] = obj[k];\n        }\n        return util.objectValues(filtered);\n    };\n    util.objectValues = (obj) => {\n        return util.objectKeys(obj).map(function (e) {\n            return obj[e];\n        });\n    };\n    util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n        ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n        : (object) => {\n            const keys = [];\n            for (const key in object) {\n                if (Object.prototype.hasOwnProperty.call(object, key)) {\n                    keys.push(key);\n                }\n            }\n            return keys;\n        };\n    util.find = (arr, checker) => {\n        for (const item of arr) {\n            if (checker(item))\n                return item;\n        }\n        return undefined;\n    };\n    util.isInteger = typeof Number.isInteger === \"function\"\n        ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n        : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n    function joinValues(array, separator = \" | \") {\n        return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n    }\n    util.joinValues = joinValues;\n    util.jsonStringifyReplacer = (_, value) => {\n        if (typeof value === \"bigint\") {\n            return value.toString();\n        }\n        return value;\n    };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n    objectUtil.mergeShapes = (first, second) => {\n        return {\n            ...first,\n            ...second, // second overwrites first\n        };\n    };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n    \"string\",\n    \"nan\",\n    \"number\",\n    \"integer\",\n    \"float\",\n    \"boolean\",\n    \"date\",\n    \"bigint\",\n    \"symbol\",\n    \"function\",\n    \"undefined\",\n    \"null\",\n    \"array\",\n    \"object\",\n    \"unknown\",\n    \"promise\",\n    \"void\",\n    \"never\",\n    \"map\",\n    \"set\",\n]);\nexport const getParsedType = (data) => {\n    const t = typeof data;\n    switch (t) {\n        case \"undefined\":\n            return ZodParsedType.undefined;\n        case \"string\":\n            return ZodParsedType.string;\n        case \"number\":\n            return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n        case \"boolean\":\n            return ZodParsedType.boolean;\n        case \"function\":\n            return ZodParsedType.function;\n        case \"bigint\":\n            return ZodParsedType.bigint;\n        case \"symbol\":\n            return ZodParsedType.symbol;\n        case \"object\":\n            if (Array.isArray(data)) {\n                return ZodParsedType.array;\n            }\n            if (data === null) {\n                return ZodParsedType.null;\n            }\n            if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n                return ZodParsedType.promise;\n            }\n            if (typeof Map !== \"undefined\" && data instanceof Map) {\n                return ZodParsedType.map;\n            }\n            if (typeof Set !== \"undefined\" && data instanceof Set) {\n                return ZodParsedType.set;\n            }\n            if (typeof Date !== \"undefined\" && data instanceof Date) {\n                return ZodParsedType.date;\n            }\n            return ZodParsedType.object;\n        default:\n            return ZodParsedType.unknown;\n    }\n};\n", "import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n    \"invalid_type\",\n    \"invalid_literal\",\n    \"custom\",\n    \"invalid_union\",\n    \"invalid_union_discriminator\",\n    \"invalid_enum_value\",\n    \"unrecognized_keys\",\n    \"invalid_arguments\",\n    \"invalid_return_type\",\n    \"invalid_date\",\n    \"invalid_string\",\n    \"too_small\",\n    \"too_big\",\n    \"invalid_intersection_types\",\n    \"not_multiple_of\",\n    \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n    const json = JSON.stringify(obj, null, 2);\n    return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n    get errors() {\n        return this.issues;\n    }\n    constructor(issues) {\n        super();\n        this.issues = [];\n        this.addIssue = (sub) => {\n            this.issues = [...this.issues, sub];\n        };\n        this.addIssues = (subs = []) => {\n            this.issues = [...this.issues, ...subs];\n        };\n        const actualProto = new.target.prototype;\n        if (Object.setPrototypeOf) {\n            // eslint-disable-next-line ban/ban\n            Object.setPrototypeOf(this, actualProto);\n        }\n        else {\n            this.__proto__ = actualProto;\n        }\n        this.name = \"ZodError\";\n        this.issues = issues;\n    }\n    format(_mapper) {\n        const mapper = _mapper ||\n            function (issue) {\n                return issue.message;\n            };\n        const fieldErrors = { _errors: [] };\n        const processError = (error) => {\n            for (const issue of error.issues) {\n                if (issue.code === \"invalid_union\") {\n                    issue.unionErrors.map(processError);\n                }\n                else if (issue.code === \"invalid_return_type\") {\n                    processError(issue.returnTypeError);\n                }\n                else if (issue.code === \"invalid_arguments\") {\n                    processError(issue.argumentsError);\n                }\n                else if (issue.path.length === 0) {\n                    fieldErrors._errors.push(mapper(issue));\n                }\n                else {\n                    let curr = fieldErrors;\n                    let i = 0;\n                    while (i < issue.path.length) {\n                        const el = issue.path[i];\n                        const terminal = i === issue.path.length - 1;\n                        if (!terminal) {\n                            curr[el] = curr[el] || { _errors: [] };\n                            // if (typeof el === \"string\") {\n                            //   curr[el] = curr[el] || { _errors: [] };\n                            // } else if (typeof el === \"number\") {\n                            //   const errorArray: any = [];\n                            //   errorArray._errors = [];\n                            //   curr[el] = curr[el] || errorArray;\n                            // }\n                        }\n                        else {\n                            curr[el] = curr[el] || { _errors: [] };\n                            curr[el]._errors.push(mapper(issue));\n                        }\n                        curr = curr[el];\n                        i++;\n                    }\n                }\n            }\n        };\n        processError(this);\n        return fieldErrors;\n    }\n    static assert(value) {\n        if (!(value instanceof ZodError)) {\n            throw new Error(`Not a ZodError: ${value}`);\n        }\n    }\n    toString() {\n        return this.message;\n    }\n    get message() {\n        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n    }\n    get isEmpty() {\n        return this.issues.length === 0;\n    }\n    flatten(mapper = (issue) => issue.message) {\n        const fieldErrors = Object.create(null);\n        const formErrors = [];\n        for (const sub of this.issues) {\n            if (sub.path.length > 0) {\n                const firstEl = sub.path[0];\n                fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n                fieldErrors[firstEl].push(mapper(sub));\n            }\n            else {\n                formErrors.push(mapper(sub));\n            }\n        }\n        return { formErrors, fieldErrors };\n    }\n    get formErrors() {\n        return this.flatten();\n    }\n}\nZodError.create = (issues) => {\n    const error = new ZodError(issues);\n    return error;\n};\n", "import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n    let message;\n    switch (issue.code) {\n        case ZodIssueCode.invalid_type:\n            if (issue.received === ZodParsedType.undefined) {\n                message = \"Required\";\n            }\n            else {\n                message = `Expected ${issue.expected}, received ${issue.received}`;\n            }\n            break;\n        case ZodIssueCode.invalid_literal:\n            message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n            break;\n        case ZodIssueCode.unrecognized_keys:\n            message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n            break;\n        case ZodIssueCode.invalid_union:\n            message = `Invalid input`;\n            break;\n        case ZodIssueCode.invalid_union_discriminator:\n            message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n            break;\n        case ZodIssueCode.invalid_enum_value:\n            message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n            break;\n        case ZodIssueCode.invalid_arguments:\n            message = `Invalid function arguments`;\n            break;\n        case ZodIssueCode.invalid_return_type:\n            message = `Invalid function return type`;\n            break;\n        case ZodIssueCode.invalid_date:\n            message = `Invalid date`;\n            break;\n        case ZodIssueCode.invalid_string:\n            if (typeof issue.validation === \"object\") {\n                if (\"includes\" in issue.validation) {\n                    message = `Invalid input: must include \"${issue.validation.includes}\"`;\n                    if (typeof issue.validation.position === \"number\") {\n                        message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n                    }\n                }\n                else if (\"startsWith\" in issue.validation) {\n                    message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n                }\n                else if (\"endsWith\" in issue.validation) {\n                    message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n                }\n                else {\n                    util.assertNever(issue.validation);\n                }\n            }\n            else if (issue.validation !== \"regex\") {\n                message = `Invalid ${issue.validation}`;\n            }\n            else {\n                message = \"Invalid\";\n            }\n            break;\n        case ZodIssueCode.too_small:\n            if (issue.type === \"array\")\n                message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n            else if (issue.type === \"string\")\n                message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n            else if (issue.type === \"number\")\n                message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n            else if (issue.type === \"bigint\")\n                message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n            else if (issue.type === \"date\")\n                message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n            else\n                message = \"Invalid input\";\n            break;\n        case ZodIssueCode.too_big:\n            if (issue.type === \"array\")\n                message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n            else if (issue.type === \"string\")\n                message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n            else if (issue.type === \"number\")\n                message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n            else if (issue.type === \"bigint\")\n                message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n            else if (issue.type === \"date\")\n                message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n            else\n                message = \"Invalid input\";\n            break;\n        case ZodIssueCode.custom:\n            message = `Invalid input`;\n            break;\n        case ZodIssueCode.invalid_intersection_types:\n            message = `Intersection results could not be merged`;\n            break;\n        case ZodIssueCode.not_multiple_of:\n            message = `Number must be a multiple of ${issue.multipleOf}`;\n            break;\n        case ZodIssueCode.not_finite:\n            message = \"Number must be finite\";\n            break;\n        default:\n            message = _ctx.defaultError;\n            util.assertNever(issue);\n    }\n    return { message };\n};\nexport default errorMap;\n", "import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n    overrideErrorMap = map;\n}\nexport function getErrorMap() {\n    return overrideErrorMap;\n}\n", "import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n    const { data, path, errorMaps, issueData } = params;\n    const fullPath = [...path, ...(issueData.path || [])];\n    const fullIssue = {\n        ...issueData,\n        path: fullPath,\n    };\n    if (issueData.message !== undefined) {\n        return {\n            ...issueData,\n            path: fullPath,\n            message: issueData.message,\n        };\n    }\n    let errorMessage = \"\";\n    const maps = errorMaps\n        .filter((m) => !!m)\n        .slice()\n        .reverse();\n    for (const map of maps) {\n        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n    }\n    return {\n        ...issueData,\n        path: fullPath,\n        message: errorMessage,\n    };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n    const overrideMap = getErrorMap();\n    const issue = makeIssue({\n        issueData: issueData,\n        data: ctx.data,\n        path: ctx.path,\n        errorMaps: [\n            ctx.common.contextualErrorMap, // contextual error map is first priority\n            ctx.schemaErrorMap, // then schema-bound map if available\n            overrideMap, // then global override map\n            overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n        ].filter((x) => !!x),\n    });\n    ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n    constructor() {\n        this.value = \"valid\";\n    }\n    dirty() {\n        if (this.value === \"valid\")\n            this.value = \"dirty\";\n    }\n    abort() {\n        if (this.value !== \"aborted\")\n            this.value = \"aborted\";\n    }\n    static mergeArray(status, results) {\n        const arrayValue = [];\n        for (const s of results) {\n            if (s.status === \"aborted\")\n                return INVALID;\n            if (s.status === \"dirty\")\n                status.dirty();\n            arrayValue.push(s.value);\n        }\n        return { status: status.value, value: arrayValue };\n    }\n    static async mergeObjectAsync(status, pairs) {\n        const syncPairs = [];\n        for (const pair of pairs) {\n            const key = await pair.key;\n            const value = await pair.value;\n            syncPairs.push({\n                key,\n                value,\n            });\n        }\n        return ParseStatus.mergeObjectSync(status, syncPairs);\n    }\n    static mergeObjectSync(status, pairs) {\n        const finalObject = {};\n        for (const pair of pairs) {\n            const { key, value } = pair;\n            if (key.status === \"aborted\")\n                return INVALID;\n            if (value.status === \"aborted\")\n                return INVALID;\n            if (key.status === \"dirty\")\n                status.dirty();\n            if (value.status === \"dirty\")\n                status.dirty();\n            if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n                finalObject[key.value] = value.value;\n            }\n        }\n        return { status: status.value, value: finalObject };\n    }\n}\nexport const INVALID = Object.freeze({\n    status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n", "export var errorUtil;\n(function (errorUtil) {\n    errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n    // biome-ignore lint:\n    errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n", "import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n    constructor(parent, value, path, key) {\n        this._cachedPath = [];\n        this.parent = parent;\n        this.data = value;\n        this._path = path;\n        this._key = key;\n    }\n    get path() {\n        if (!this._cachedPath.length) {\n            if (Array.isArray(this._key)) {\n                this._cachedPath.push(...this._path, ...this._key);\n            }\n            else {\n                this._cachedPath.push(...this._path, this._key);\n            }\n        }\n        return this._cachedPath;\n    }\n}\nconst handleResult = (ctx, result) => {\n    if (isValid(result)) {\n        return { success: true, data: result.value };\n    }\n    else {\n        if (!ctx.common.issues.length) {\n            throw new Error(\"Validation failed but no issues detected.\");\n        }\n        return {\n            success: false,\n            get error() {\n                if (this._error)\n                    return this._error;\n                const error = new ZodError(ctx.common.issues);\n                this._error = error;\n                return this._error;\n            },\n        };\n    }\n};\nfunction processCreateParams(params) {\n    if (!params)\n        return {};\n    const { errorMap, invalid_type_error, required_error, description } = params;\n    if (errorMap && (invalid_type_error || required_error)) {\n        throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n    }\n    if (errorMap)\n        return { errorMap: errorMap, description };\n    const customMap = (iss, ctx) => {\n        const { message } = params;\n        if (iss.code === \"invalid_enum_value\") {\n            return { message: message ?? ctx.defaultError };\n        }\n        if (typeof ctx.data === \"undefined\") {\n            return { message: message ?? required_error ?? ctx.defaultError };\n        }\n        if (iss.code !== \"invalid_type\")\n            return { message: ctx.defaultError };\n        return { message: message ?? invalid_type_error ?? ctx.defaultError };\n    };\n    return { errorMap: customMap, description };\n}\nexport class ZodType {\n    get description() {\n        return this._def.description;\n    }\n    _getType(input) {\n        return getParsedType(input.data);\n    }\n    _getOrReturnCtx(input, ctx) {\n        return (ctx || {\n            common: input.parent.common,\n            data: input.data,\n            parsedType: getParsedType(input.data),\n            schemaErrorMap: this._def.errorMap,\n            path: input.path,\n            parent: input.parent,\n        });\n    }\n    _processInputParams(input) {\n        return {\n            status: new ParseStatus(),\n            ctx: {\n                common: input.parent.common,\n                data: input.data,\n                parsedType: getParsedType(input.data),\n                schemaErrorMap: this._def.errorMap,\n                path: input.path,\n                parent: input.parent,\n            },\n        };\n    }\n    _parseSync(input) {\n        const result = this._parse(input);\n        if (isAsync(result)) {\n            throw new Error(\"Synchronous parse encountered promise.\");\n        }\n        return result;\n    }\n    _parseAsync(input) {\n        const result = this._parse(input);\n        return Promise.resolve(result);\n    }\n    parse(data, params) {\n        const result = this.safeParse(data, params);\n        if (result.success)\n            return result.data;\n        throw result.error;\n    }\n    safeParse(data, params) {\n        const ctx = {\n            common: {\n                issues: [],\n                async: params?.async ?? false,\n                contextualErrorMap: params?.errorMap,\n            },\n            path: params?.path || [],\n            schemaErrorMap: this._def.errorMap,\n            parent: null,\n            data,\n            parsedType: getParsedType(data),\n        };\n        const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n        return handleResult(ctx, result);\n    }\n    \"~validate\"(data) {\n        const ctx = {\n            common: {\n                issues: [],\n                async: !!this[\"~standard\"].async,\n            },\n            path: [],\n            schemaErrorMap: this._def.errorMap,\n            parent: null,\n            data,\n            parsedType: getParsedType(data),\n        };\n        if (!this[\"~standard\"].async) {\n            try {\n                const result = this._parseSync({ data, path: [], parent: ctx });\n                return isValid(result)\n                    ? {\n                        value: result.value,\n                    }\n                    : {\n                        issues: ctx.common.issues,\n                    };\n            }\n            catch (err) {\n                if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n                    this[\"~standard\"].async = true;\n                }\n                ctx.common = {\n                    issues: [],\n                    async: true,\n                };\n            }\n        }\n        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n            ? {\n                value: result.value,\n            }\n            : {\n                issues: ctx.common.issues,\n            });\n    }\n    async parseAsync(data, params) {\n        const result = await this.safeParseAsync(data, params);\n        if (result.success)\n            return result.data;\n        throw result.error;\n    }\n    async safeParseAsync(data, params) {\n        const ctx = {\n            common: {\n                issues: [],\n                contextualErrorMap: params?.errorMap,\n                async: true,\n            },\n            path: params?.path || [],\n            schemaErrorMap: this._def.errorMap,\n            parent: null,\n            data,\n            parsedType: getParsedType(data),\n        };\n        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n        return handleResult(ctx, result);\n    }\n    refine(check, message) {\n        const getIssueProperties = (val) => {\n            if (typeof message === \"string\" || typeof message === \"undefined\") {\n                return { message };\n            }\n            else if (typeof message === \"function\") {\n                return message(val);\n            }\n            else {\n                return message;\n            }\n        };\n        return this._refinement((val, ctx) => {\n            const result = check(val);\n            const setError = () => ctx.addIssue({\n                code: ZodIssueCode.custom,\n                ...getIssueProperties(val),\n            });\n            if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n                return result.then((data) => {\n                    if (!data) {\n                        setError();\n                        return false;\n                    }\n                    else {\n                        return true;\n                    }\n                });\n            }\n            if (!result) {\n                setError();\n                return false;\n            }\n            else {\n                return true;\n            }\n        });\n    }\n    refinement(check, refinementData) {\n        return this._refinement((val, ctx) => {\n            if (!check(val)) {\n                ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n                return false;\n            }\n            else {\n                return true;\n            }\n        });\n    }\n    _refinement(refinement) {\n        return new ZodEffects({\n            schema: this,\n            typeName: ZodFirstPartyTypeKind.ZodEffects,\n            effect: { type: \"refinement\", refinement },\n        });\n    }\n    superRefine(refinement) {\n        return this._refinement(refinement);\n    }\n    constructor(def) {\n        /** Alias of safeParseAsync */\n        this.spa = this.safeParseAsync;\n        this._def = def;\n        this.parse = this.parse.bind(this);\n        this.safeParse = this.safeParse.bind(this);\n        this.parseAsync = this.parseAsync.bind(this);\n        this.safeParseAsync = this.safeParseAsync.bind(this);\n        this.spa = this.spa.bind(this);\n        this.refine = this.refine.bind(this);\n        this.refinement = this.refinement.bind(this);\n        this.superRefine = this.superRefine.bind(this);\n        this.optional = this.optional.bind(this);\n        this.nullable = this.nullable.bind(this);\n        this.nullish = this.nullish.bind(this);\n        this.array = this.array.bind(this);\n        this.promise = this.promise.bind(this);\n        this.or = this.or.bind(this);\n        this.and = this.and.bind(this);\n        this.transform = this.transform.bind(this);\n        this.brand = this.brand.bind(this);\n        this.default = this.default.bind(this);\n        this.catch = this.catch.bind(this);\n        this.describe = this.describe.bind(this);\n        this.pipe = this.pipe.bind(this);\n        this.readonly = this.readonly.bind(this);\n        this.isNullable = this.isNullable.bind(this);\n        this.isOptional = this.isOptional.bind(this);\n        this[\"~standard\"] = {\n            version: 1,\n            vendor: \"zod\",\n            validate: (data) => this[\"~validate\"](data),\n        };\n    }\n    optional() {\n        return ZodOptional.create(this, this._def);\n    }\n    nullable() {\n        return ZodNullable.create(this, this._def);\n    }\n    nullish() {\n        return this.nullable().optional();\n    }\n    array() {\n        return ZodArray.create(this);\n    }\n    promise() {\n        return ZodPromise.create(this, this._def);\n    }\n    or(option) {\n        return ZodUnion.create([this, option], this._def);\n    }\n    and(incoming) {\n        return ZodIntersection.create(this, incoming, this._def);\n    }\n    transform(transform) {\n        return new ZodEffects({\n            ...processCreateParams(this._def),\n            schema: this,\n            typeName: ZodFirstPartyTypeKind.ZodEffects,\n            effect: { type: \"transform\", transform },\n        });\n    }\n    default(def) {\n        const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n        return new ZodDefault({\n            ...processCreateParams(this._def),\n            innerType: this,\n            defaultValue: defaultValueFunc,\n            typeName: ZodFirstPartyTypeKind.ZodDefault,\n        });\n    }\n    brand() {\n        return new ZodBranded({\n            typeName: ZodFirstPartyTypeKind.ZodBranded,\n            type: this,\n            ...processCreateParams(this._def),\n        });\n    }\n    catch(def) {\n        const catchValueFunc = typeof def === \"function\" ? def : () => def;\n        return new ZodCatch({\n            ...processCreateParams(this._def),\n            innerType: this,\n            catchValue: catchValueFunc,\n            typeName: ZodFirstPartyTypeKind.ZodCatch,\n        });\n    }\n    describe(description) {\n        const This = this.constructor;\n        return new This({\n            ...this._def,\n            description,\n        });\n    }\n    pipe(target) {\n        return ZodPipeline.create(this, target);\n    }\n    readonly() {\n        return ZodReadonly.create(this);\n    }\n    isOptional() {\n        return this.safeParse(undefined).success;\n    }\n    isNullable() {\n        return this.safeParse(null).success;\n    }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n//   /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n//   /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n//   /^[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// const emailRegex =\n//   /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n//   /^[a-z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9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]))\\/(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\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n    let secondsRegexSource = `[0-5]\\\\d`;\n    if (args.precision) {\n        secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n    }\n    else if (args.precision == null) {\n        secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n    }\n    const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n    return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n    return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n    let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n    const opts = [];\n    opts.push(args.local ? `Z?` : `Z`);\n    if (args.offset)\n        opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n    regex = `${regex}(${opts.join(\"|\")})`;\n    return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n    if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n        return true;\n    }\n    if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n        return true;\n    }\n    return false;\n}\nfunction isValidJWT(jwt, alg) {\n    if (!jwtRegex.test(jwt))\n        return false;\n    try {\n        const [header] = jwt.split(\".\");\n        if (!header)\n            return false;\n        // Convert base64url to base64\n        const base64 = header\n            .replace(/-/g, \"+\")\n            .replace(/_/g, \"/\")\n            .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n        // @ts-ignore\n        const decoded = JSON.parse(atob(base64));\n        if (typeof decoded !== \"object\" || decoded === null)\n            return false;\n        if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n            return false;\n        if (!decoded.alg)\n            return false;\n        if (alg && decoded.alg !== alg)\n            return false;\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nfunction isValidCidr(ip, version) {\n    if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n        return true;\n    }\n    if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n        return true;\n    }\n    return false;\n}\nexport class ZodString extends ZodType {\n    _parse(input) {\n        if (this._def.coerce) {\n            input.data = String(input.data);\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.string) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.string,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const status = new ParseStatus();\n        let ctx = undefined;\n        for (const check of this._def.checks) {\n            if (check.kind === \"min\") {\n                if (input.data.length < check.value) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_small,\n                        minimum: check.value,\n                        type: \"string\",\n                        inclusive: true,\n                        exact: false,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"max\") {\n                if (input.data.length > check.value) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_big,\n                        maximum: check.value,\n                        type: \"string\",\n                        inclusive: true,\n                        exact: false,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"length\") {\n                const tooBig = input.data.length > check.value;\n                const tooSmall = input.data.length < check.value;\n                if (tooBig || tooSmall) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    if (tooBig) {\n                        addIssueToContext(ctx, {\n                            code: ZodIssueCode.too_big,\n                            maximum: check.value,\n                            type: \"string\",\n                            inclusive: true,\n                            exact: true,\n                            message: check.message,\n                        });\n                    }\n                    else if (tooSmall) {\n                        addIssueToContext(ctx, {\n                            code: ZodIssueCode.too_small,\n                            minimum: check.value,\n                            type: \"string\",\n                            inclusive: true,\n                            exact: true,\n                            message: check.message,\n                        });\n                    }\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"email\") {\n                if (!emailRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"email\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"emoji\") {\n                if (!emojiRegex) {\n                    emojiRegex = new RegExp(_emojiRegex, \"u\");\n                }\n                if (!emojiRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"emoji\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"uuid\") {\n                if (!uuidRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"uuid\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"nanoid\") {\n                if (!nanoidRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"nanoid\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"cuid\") {\n                if (!cuidRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"cuid\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"cuid2\") {\n                if (!cuid2Regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"cuid2\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"ulid\") {\n                if (!ulidRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"ulid\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"url\") {\n                try {\n                    // @ts-ignore\n                    new URL(input.data);\n                }\n                catch {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"url\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"regex\") {\n                check.regex.lastIndex = 0;\n                const testResult = check.regex.test(input.data);\n                if (!testResult) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"regex\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"trim\") {\n                input.data = input.data.trim();\n            }\n            else if (check.kind === \"includes\") {\n                if (!input.data.includes(check.value, check.position)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: { includes: check.value, position: check.position },\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"toLowerCase\") {\n                input.data = input.data.toLowerCase();\n            }\n            else if (check.kind === \"toUpperCase\") {\n                input.data = input.data.toUpperCase();\n            }\n            else if (check.kind === \"startsWith\") {\n                if (!input.data.startsWith(check.value)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: { startsWith: check.value },\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"endsWith\") {\n                if (!input.data.endsWith(check.value)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: { endsWith: check.value },\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"datetime\") {\n                const regex = datetimeRegex(check);\n                if (!regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: \"datetime\",\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"date\") {\n                const regex = dateRegex;\n                if (!regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: \"date\",\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"time\") {\n                const regex = timeRegex(check);\n                if (!regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: \"time\",\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"duration\") {\n                if (!durationRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"duration\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"ip\") {\n                if (!isValidIP(input.data, check.version)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"ip\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"jwt\") {\n                if (!isValidJWT(input.data, check.alg)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"jwt\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"cidr\") {\n                if (!isValidCidr(input.data, check.version)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"cidr\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"base64\") {\n                if (!base64Regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"base64\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"base64url\") {\n                if (!base64urlRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"base64url\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else {\n                util.assertNever(check);\n            }\n        }\n        return { status: status.value, value: input.data };\n    }\n    _regex(regex, validation, message) {\n        return this.refinement((data) => regex.test(data), {\n            validation,\n            code: ZodIssueCode.invalid_string,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    _addCheck(check) {\n        return new ZodString({\n            ...this._def,\n            checks: [...this._def.checks, check],\n        });\n    }\n    email(message) {\n        return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n    }\n    url(message) {\n        return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n    }\n    emoji(message) {\n        return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n    }\n    uuid(message) {\n        return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n    }\n    nanoid(message) {\n        return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n    }\n    cuid(message) {\n        return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n    }\n    cuid2(message) {\n        return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n    }\n    ulid(message) {\n        return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n    }\n    base64(message) {\n        return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n    }\n    base64url(message) {\n        // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n        return this._addCheck({\n            kind: \"base64url\",\n            ...errorUtil.errToObj(message),\n        });\n    }\n    jwt(options) {\n        return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n    }\n    ip(options) {\n        return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n    }\n    cidr(options) {\n        return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n    }\n    datetime(options) {\n        if (typeof options === \"string\") {\n            return this._addCheck({\n                kind: \"datetime\",\n                precision: null,\n                offset: false,\n                local: false,\n                message: options,\n            });\n        }\n        return this._addCheck({\n            kind: \"datetime\",\n            precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n            offset: options?.offset ?? false,\n            local: options?.local ?? false,\n            ...errorUtil.errToObj(options?.message),\n        });\n    }\n    date(message) {\n        return this._addCheck({ kind: \"date\", message });\n    }\n    time(options) {\n        if (typeof options === \"string\") {\n            return this._addCheck({\n                kind: \"time\",\n                precision: null,\n                message: options,\n            });\n        }\n        return this._addCheck({\n            kind: \"time\",\n            precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n            ...errorUtil.errToObj(options?.message),\n        });\n    }\n    duration(message) {\n        return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n    }\n    regex(regex, message) {\n        return this._addCheck({\n            kind: \"regex\",\n            regex: regex,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    includes(value, options) {\n        return this._addCheck({\n            kind: \"includes\",\n            value: value,\n            position: options?.position,\n            ...errorUtil.errToObj(options?.message),\n        });\n    }\n    startsWith(value, message) {\n        return this._addCheck({\n            kind: \"startsWith\",\n            value: value,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    endsWith(value, message) {\n        return this._addCheck({\n            kind: \"endsWith\",\n            value: value,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    min(minLength, message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: minLength,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    max(maxLength, message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: maxLength,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    length(len, message) {\n        return this._addCheck({\n            kind: \"length\",\n            value: len,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    /**\n     * Equivalent to `.min(1)`\n     */\n    nonempty(message) {\n        return this.min(1, errorUtil.errToObj(message));\n    }\n    trim() {\n        return new ZodString({\n            ...this._def,\n            checks: [...this._def.checks, { kind: \"trim\" }],\n        });\n    }\n    toLowerCase() {\n        return new ZodString({\n            ...this._def,\n            checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n        });\n    }\n    toUpperCase() {\n        return new ZodString({\n            ...this._def,\n            checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n        });\n    }\n    get isDatetime() {\n        return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n    }\n    get isDate() {\n        return !!this._def.checks.find((ch) => ch.kind === \"date\");\n    }\n    get isTime() {\n        return !!this._def.checks.find((ch) => ch.kind === \"time\");\n    }\n    get isDuration() {\n        return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n    }\n    get isEmail() {\n        return !!this._def.checks.find((ch) => ch.kind === \"email\");\n    }\n    get isURL() {\n        return !!this._def.checks.find((ch) => ch.kind === \"url\");\n    }\n    get isEmoji() {\n        return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n    }\n    get isUUID() {\n        return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n    }\n    get isNANOID() {\n        return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n    }\n    get isCUID() {\n        return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n    }\n    get isCUID2() {\n        return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n    }\n    get isULID() {\n        return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n    }\n    get isIP() {\n        return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n    }\n    get isCIDR() {\n        return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n    }\n    get isBase64() {\n        return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n    }\n    get isBase64url() {\n        // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n        return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n    }\n    get minLength() {\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n        }\n        return min;\n    }\n    get maxLength() {\n        let max = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return max;\n    }\n}\nZodString.create = (params) => {\n    return new ZodString({\n        checks: [],\n        typeName: ZodFirstPartyTypeKind.ZodString,\n        coerce: params?.coerce ?? false,\n        ...processCreateParams(params),\n    });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n    const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n    const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n    const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n    const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n    const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n    return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n    constructor() {\n        super(...arguments);\n        this.min = this.gte;\n        this.max = this.lte;\n        this.step = this.multipleOf;\n    }\n    _parse(input) {\n        if (this._def.coerce) {\n            input.data = Number(input.data);\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.number) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.number,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        let ctx = undefined;\n        const status = new ParseStatus();\n        for (const check of this._def.checks) {\n            if (check.kind === \"int\") {\n                if (!util.isInteger(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_type,\n                        expected: \"integer\",\n                        received: \"float\",\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"min\") {\n                const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n                if (tooSmall) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_small,\n                        minimum: check.value,\n                        type: \"number\",\n                        inclusive: check.inclusive,\n                        exact: false,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"max\") {\n                const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n                if (tooBig) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_big,\n                        maximum: check.value,\n                        type: \"number\",\n                        inclusive: check.inclusive,\n                        exact: false,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"multipleOf\") {\n                if (floatSafeRemainder(input.data, check.value) !== 0) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.not_multiple_of,\n                        multipleOf: check.value,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"finite\") {\n                if (!Number.isFinite(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.not_finite,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else {\n                util.assertNever(check);\n            }\n        }\n        return { status: status.value, value: input.data };\n    }\n    gte(value, message) {\n        return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n    }\n    gt(value, message) {\n        return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n    }\n    lte(value, message) {\n        return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n    }\n    lt(value, message) {\n        return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n    }\n    setLimit(kind, value, inclusive, message) {\n        return new ZodNumber({\n            ...this._def,\n            checks: [\n                ...this._def.checks,\n                {\n                    kind,\n                    value,\n                    inclusive,\n                    message: errorUtil.toString(message),\n                },\n            ],\n        });\n    }\n    _addCheck(check) {\n        return new ZodNumber({\n            ...this._def,\n            checks: [...this._def.checks, check],\n        });\n    }\n    int(message) {\n        return this._addCheck({\n            kind: \"int\",\n            message: errorUtil.toString(message),\n        });\n    }\n    positive(message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: 0,\n            inclusive: false,\n            message: errorUtil.toString(message),\n        });\n    }\n    negative(message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: 0,\n            inclusive: false,\n            message: errorUtil.toString(message),\n        });\n    }\n    nonpositive(message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: 0,\n            inclusive: true,\n            message: errorUtil.toString(message),\n        });\n    }\n    nonnegative(message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: 0,\n            inclusive: true,\n            message: errorUtil.toString(message),\n        });\n    }\n    multipleOf(value, message) {\n        return this._addCheck({\n            kind: \"multipleOf\",\n            value: value,\n            message: errorUtil.toString(message),\n        });\n    }\n    finite(message) {\n        return this._addCheck({\n            kind: \"finite\",\n            message: errorUtil.toString(message),\n        });\n    }\n    safe(message) {\n        return this._addCheck({\n            kind: \"min\",\n            inclusive: true,\n            value: Number.MIN_SAFE_INTEGER,\n            message: errorUtil.toString(message),\n        })._addCheck({\n            kind: \"max\",\n            inclusive: true,\n            value: Number.MAX_SAFE_INTEGER,\n            message: errorUtil.toString(message),\n        });\n    }\n    get minValue() {\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n        }\n        return min;\n    }\n    get maxValue() {\n        let max = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return max;\n    }\n    get isInt() {\n        return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n    }\n    get isFinite() {\n        let max = null;\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n                return true;\n            }\n            else if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n            else if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return Number.isFinite(min) && Number.isFinite(max);\n    }\n}\nZodNumber.create = (params) => {\n    return new ZodNumber({\n        checks: [],\n        typeName: ZodFirstPartyTypeKind.ZodNumber,\n        coerce: params?.coerce || false,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodBigInt extends ZodType {\n    constructor() {\n        super(...arguments);\n        this.min = this.gte;\n        this.max = this.lte;\n    }\n    _parse(input) {\n        if (this._def.coerce) {\n            try {\n                input.data = BigInt(input.data);\n            }\n            catch {\n                return this._getInvalidInput(input);\n            }\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.bigint) {\n            return this._getInvalidInput(input);\n        }\n        let ctx = undefined;\n        const status = new ParseStatus();\n        for (const check of this._def.checks) {\n            if (check.kind === \"min\") {\n                const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n                if (tooSmall) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_small,\n                        type: \"bigint\",\n                        minimum: check.value,\n                        inclusive: check.inclusive,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"max\") {\n                const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n                if (tooBig) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_big,\n                        type: \"bigint\",\n                        maximum: check.value,\n                        inclusive: check.inclusive,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"multipleOf\") {\n                if (input.data % check.value !== BigInt(0)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.not_multiple_of,\n                        multipleOf: check.value,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else {\n                util.assertNever(check);\n            }\n        }\n        return { status: status.value, value: input.data };\n    }\n    _getInvalidInput(input) {\n        const ctx = this._getOrReturnCtx(input);\n        addIssueToContext(ctx, {\n            code: ZodIssueCode.invalid_type,\n            expected: ZodParsedType.bigint,\n            received: ctx.parsedType,\n        });\n        return INVALID;\n    }\n    gte(value, message) {\n        return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n    }\n    gt(value, message) {\n        return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n    }\n    lte(value, message) {\n        return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n    }\n    lt(value, message) {\n        return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n    }\n    setLimit(kind, value, inclusive, message) {\n        return new ZodBigInt({\n            ...this._def,\n            checks: [\n                ...this._def.checks,\n                {\n                    kind,\n                    value,\n                    inclusive,\n                    message: errorUtil.toString(message),\n                },\n            ],\n        });\n    }\n    _addCheck(check) {\n        return new ZodBigInt({\n            ...this._def,\n            checks: [...this._def.checks, check],\n        });\n    }\n    positive(message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: BigInt(0),\n            inclusive: false,\n            message: errorUtil.toString(message),\n        });\n    }\n    negative(message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: BigInt(0),\n            inclusive: false,\n            message: errorUtil.toString(message),\n        });\n    }\n    nonpositive(message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: BigInt(0),\n            inclusive: true,\n            message: errorUtil.toString(message),\n        });\n    }\n    nonnegative(message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: BigInt(0),\n            inclusive: true,\n            message: errorUtil.toString(message),\n        });\n    }\n    multipleOf(value, message) {\n        return this._addCheck({\n            kind: \"multipleOf\",\n            value,\n            message: errorUtil.toString(message),\n        });\n    }\n    get minValue() {\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n        }\n        return min;\n    }\n    get maxValue() {\n        let max = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return max;\n    }\n}\nZodBigInt.create = (params) => {\n    return new ZodBigInt({\n        checks: [],\n        typeName: ZodFirstPartyTypeKind.ZodBigInt,\n        coerce: params?.coerce ?? false,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodBoolean extends ZodType {\n    _parse(input) {\n        if (this._def.coerce) {\n            input.data = Boolean(input.data);\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.boolean) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.boolean,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodBoolean.create = (params) => {\n    return new ZodBoolean({\n        typeName: ZodFirstPartyTypeKind.ZodBoolean,\n        coerce: params?.coerce || false,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodDate extends ZodType {\n    _parse(input) {\n        if (this._def.coerce) {\n            input.data = new Date(input.data);\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.date) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.date,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        if (Number.isNaN(input.data.getTime())) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_date,\n            });\n            return INVALID;\n        }\n        const status = new ParseStatus();\n        let ctx = undefined;\n        for (const check of this._def.checks) {\n            if (check.kind === \"min\") {\n                if (input.data.getTime() < check.value) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_small,\n                        message: check.message,\n                        inclusive: true,\n                        exact: false,\n                        minimum: check.value,\n                        type: \"date\",\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"max\") {\n                if (input.data.getTime() > check.value) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_big,\n                        message: check.message,\n                        inclusive: true,\n                        exact: false,\n                        maximum: check.value,\n                        type: \"date\",\n                    });\n                    status.dirty();\n                }\n            }\n            else {\n                util.assertNever(check);\n            }\n        }\n        return {\n            status: status.value,\n            value: new Date(input.data.getTime()),\n        };\n    }\n    _addCheck(check) {\n        return new ZodDate({\n            ...this._def,\n            checks: [...this._def.checks, check],\n        });\n    }\n    min(minDate, message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: minDate.getTime(),\n            message: errorUtil.toString(message),\n        });\n    }\n    max(maxDate, message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: maxDate.getTime(),\n            message: errorUtil.toString(message),\n        });\n    }\n    get minDate() {\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n        }\n        return min != null ? new Date(min) : null;\n    }\n    get maxDate() {\n        let max = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return max != null ? new Date(max) : null;\n    }\n}\nZodDate.create = (params) => {\n    return new ZodDate({\n        checks: [],\n        coerce: params?.coerce || false,\n        typeName: ZodFirstPartyTypeKind.ZodDate,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodSymbol extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.symbol) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.symbol,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodSymbol.create = (params) => {\n    return new ZodSymbol({\n        typeName: ZodFirstPartyTypeKind.ZodSymbol,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodUndefined extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.undefined) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.undefined,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodUndefined.create = (params) => {\n    return new ZodUndefined({\n        typeName: ZodFirstPartyTypeKind.ZodUndefined,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodNull extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.null) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.null,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodNull.create = (params) => {\n    return new ZodNull({\n        typeName: ZodFirstPartyTypeKind.ZodNull,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodAny extends ZodType {\n    constructor() {\n        super(...arguments);\n        // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n        this._any = true;\n    }\n    _parse(input) {\n        return OK(input.data);\n    }\n}\nZodAny.create = (params) => {\n    return new ZodAny({\n        typeName: ZodFirstPartyTypeKind.ZodAny,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodUnknown extends ZodType {\n    constructor() {\n        super(...arguments);\n        // required\n        this._unknown = true;\n    }\n    _parse(input) {\n        return OK(input.data);\n    }\n}\nZodUnknown.create = (params) => {\n    return new ZodUnknown({\n        typeName: ZodFirstPartyTypeKind.ZodUnknown,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodNever extends ZodType {\n    _parse(input) {\n        const ctx = this._getOrReturnCtx(input);\n        addIssueToContext(ctx, {\n            code: ZodIssueCode.invalid_type,\n            expected: ZodParsedType.never,\n            received: ctx.parsedType,\n        });\n        return INVALID;\n    }\n}\nZodNever.create = (params) => {\n    return new ZodNever({\n        typeName: ZodFirstPartyTypeKind.ZodNever,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodVoid extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.undefined) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.void,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodVoid.create = (params) => {\n    return new ZodVoid({\n        typeName: ZodFirstPartyTypeKind.ZodVoid,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodArray extends ZodType {\n    _parse(input) {\n        const { ctx, status } = this._processInputParams(input);\n        const def = this._def;\n        if (ctx.parsedType !== ZodParsedType.array) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.array,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        if (def.exactLength !== null) {\n            const tooBig = ctx.data.length > def.exactLength.value;\n            const tooSmall = ctx.data.length < def.exactLength.value;\n            if (tooBig || tooSmall) {\n                addIssueToContext(ctx, {\n                    code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n                    minimum: (tooSmall ? def.exactLength.value : undefined),\n                    maximum: (tooBig ? def.exactLength.value : undefined),\n                    type: \"array\",\n                    inclusive: true,\n                    exact: true,\n                    message: def.exactLength.message,\n                });\n                status.dirty();\n            }\n        }\n        if (def.minLength !== null) {\n            if (ctx.data.length < def.minLength.value) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.too_small,\n                    minimum: def.minLength.value,\n                    type: \"array\",\n                    inclusive: true,\n                    exact: false,\n                    message: def.minLength.message,\n                });\n                status.dirty();\n            }\n        }\n        if (def.maxLength !== null) {\n            if (ctx.data.length > def.maxLength.value) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.too_big,\n                    maximum: def.maxLength.value,\n                    type: \"array\",\n                    inclusive: true,\n                    exact: false,\n                    message: def.maxLength.message,\n                });\n                status.dirty();\n            }\n        }\n        if (ctx.common.async) {\n            return Promise.all([...ctx.data].map((item, i) => {\n                return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n            })).then((result) => {\n                return ParseStatus.mergeArray(status, result);\n            });\n        }\n        const result = [...ctx.data].map((item, i) => {\n            return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n        });\n        return ParseStatus.mergeArray(status, result);\n    }\n    get element() {\n        return this._def.type;\n    }\n    min(minLength, message) {\n        return new ZodArray({\n            ...this._def,\n            minLength: { value: minLength, message: errorUtil.toString(message) },\n        });\n    }\n    max(maxLength, message) {\n        return new ZodArray({\n            ...this._def,\n            maxLength: { value: maxLength, message: errorUtil.toString(message) },\n        });\n    }\n    length(len, message) {\n        return new ZodArray({\n            ...this._def,\n            exactLength: { value: len, message: errorUtil.toString(message) },\n        });\n    }\n    nonempty(message) {\n        return this.min(1, message);\n    }\n}\nZodArray.create = (schema, params) => {\n    return new ZodArray({\n        type: schema,\n        minLength: null,\n        maxLength: null,\n        exactLength: null,\n        typeName: ZodFirstPartyTypeKind.ZodArray,\n        ...processCreateParams(params),\n    });\n};\nfunction deepPartialify(schema) {\n    if (schema instanceof ZodObject) {\n        const newShape = {};\n        for (const key in schema.shape) {\n            const fieldSchema = schema.shape[key];\n            newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n        }\n        return new ZodObject({\n            ...schema._def,\n            shape: () => newShape,\n        });\n    }\n    else if (schema instanceof ZodArray) {\n        return new ZodArray({\n            ...schema._def,\n            type: deepPartialify(schema.element),\n        });\n    }\n    else if (schema instanceof ZodOptional) {\n        return ZodOptional.create(deepPartialify(schema.unwrap()));\n    }\n    else if (schema instanceof ZodNullable) {\n        return ZodNullable.create(deepPartialify(schema.unwrap()));\n    }\n    else if (schema instanceof ZodTuple) {\n        return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n    }\n    else {\n        return schema;\n    }\n}\nexport class ZodObject extends ZodType {\n    constructor() {\n        super(...arguments);\n        this._cached = null;\n        /**\n         * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n         * If you want to pass through unknown properties, use `.passthrough()` instead.\n         */\n        this.nonstrict = this.passthrough;\n        // extend<\n        //   Augmentation extends ZodRawShape,\n        //   NewOutput extends util.flatten<{\n        //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n        //       ? Augmentation[k][\"_output\"]\n        //       : k extends keyof Output\n        //       ? Output[k]\n        //       : never;\n        //   }>,\n        //   NewInput extends util.flatten<{\n        //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n        //       ? Augmentation[k][\"_input\"]\n        //       : k extends keyof Input\n        //       ? Input[k]\n        //       : never;\n        //   }>\n        // >(\n        //   augmentation: Augmentation\n        // ): ZodObject<\n        //   extendShape<T, Augmentation>,\n        //   UnknownKeys,\n        //   Catchall,\n        //   NewOutput,\n        //   NewInput\n        // > {\n        //   return new ZodObject({\n        //     ...this._def,\n        //     shape: () => ({\n        //       ...this._def.shape(),\n        //       ...augmentation,\n        //     }),\n        //   }) as any;\n        // }\n        /**\n         * @deprecated Use `.extend` instead\n         *  */\n        this.augment = this.extend;\n    }\n    _getCached() {\n        if (this._cached !== null)\n            return this._cached;\n        const shape = this._def.shape();\n        const keys = util.objectKeys(shape);\n        this._cached = { shape, keys };\n        return this._cached;\n    }\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.object) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.object,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const { status, ctx } = this._processInputParams(input);\n        const { shape, keys: shapeKeys } = this._getCached();\n        const extraKeys = [];\n        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n            for (const key in ctx.data) {\n                if (!shapeKeys.includes(key)) {\n                    extraKeys.push(key);\n                }\n            }\n        }\n        const pairs = [];\n        for (const key of shapeKeys) {\n            const keyValidator = shape[key];\n            const value = ctx.data[key];\n            pairs.push({\n                key: { status: \"valid\", value: key },\n                value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n                alwaysSet: key in ctx.data,\n            });\n        }\n        if (this._def.catchall instanceof ZodNever) {\n            const unknownKeys = this._def.unknownKeys;\n            if (unknownKeys === \"passthrough\") {\n                for (const key of extraKeys) {\n                    pairs.push({\n                        key: { status: \"valid\", value: key },\n                        value: { status: \"valid\", value: ctx.data[key] },\n                    });\n                }\n            }\n            else if (unknownKeys === \"strict\") {\n                if (extraKeys.length > 0) {\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.unrecognized_keys,\n                        keys: extraKeys,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (unknownKeys === \"strip\") {\n            }\n            else {\n                throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n            }\n        }\n        else {\n            // run catchall validation\n            const catchall = this._def.catchall;\n            for (const key of extraKeys) {\n                const value = ctx.data[key];\n                pairs.push({\n                    key: { status: \"valid\", value: key },\n                    value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n                    ),\n                    alwaysSet: key in ctx.data,\n                });\n            }\n        }\n        if (ctx.common.async) {\n            return Promise.resolve()\n                .then(async () => {\n                const syncPairs = [];\n                for (const pair of pairs) {\n                    const key = await pair.key;\n                    const value = await pair.value;\n                    syncPairs.push({\n                        key,\n                        value,\n                        alwaysSet: pair.alwaysSet,\n                    });\n                }\n                return syncPairs;\n            })\n                .then((syncPairs) => {\n                return ParseStatus.mergeObjectSync(status, syncPairs);\n            });\n        }\n        else {\n            return ParseStatus.mergeObjectSync(status, pairs);\n        }\n    }\n    get shape() {\n        return this._def.shape();\n    }\n    strict(message) {\n        errorUtil.errToObj;\n        return new ZodObject({\n            ...this._def,\n            unknownKeys: \"strict\",\n            ...(message !== undefined\n                ? {\n                    errorMap: (issue, ctx) => {\n                        const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n                        if (issue.code === \"unrecognized_keys\")\n                            return {\n                                message: errorUtil.errToObj(message).message ?? defaultError,\n                            };\n                        return {\n                            message: defaultError,\n                        };\n                    },\n                }\n                : {}),\n        });\n    }\n    strip() {\n        return new ZodObject({\n            ...this._def,\n            unknownKeys: \"strip\",\n        });\n    }\n    passthrough() {\n        return new ZodObject({\n            ...this._def,\n            unknownKeys: \"passthrough\",\n        });\n    }\n    // const AugmentFactory =\n    //   <Def extends ZodObjectDef>(def: Def) =>\n    //   <Augmentation extends ZodRawShape>(\n    //     augmentation: Augmentation\n    //   ): ZodObject<\n    //     extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n    //     Def[\"unknownKeys\"],\n    //     Def[\"catchall\"]\n    //   > => {\n    //     return new ZodObject({\n    //       ...def,\n    //       shape: () => ({\n    //         ...def.shape(),\n    //         ...augmentation,\n    //       }),\n    //     }) as any;\n    //   };\n    extend(augmentation) {\n        return new ZodObject({\n            ...this._def,\n            shape: () => ({\n                ...this._def.shape(),\n                ...augmentation,\n            }),\n        });\n    }\n    /**\n     * Prior to zod@1.0.12 there was a bug in the\n     * inferred type of merged objects. Please\n     * upgrade if you are experiencing issues.\n     */\n    merge(merging) {\n        const merged = new ZodObject({\n            unknownKeys: merging._def.unknownKeys,\n            catchall: merging._def.catchall,\n            shape: () => ({\n                ...this._def.shape(),\n                ...merging._def.shape(),\n            }),\n            typeName: ZodFirstPartyTypeKind.ZodObject,\n        });\n        return merged;\n    }\n    // merge<\n    //   Incoming extends AnyZodObject,\n    //   Augmentation extends Incoming[\"shape\"],\n    //   NewOutput extends {\n    //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n    //       ? Augmentation[k][\"_output\"]\n    //       : k extends keyof Output\n    //       ? Output[k]\n    //       : never;\n    //   },\n    //   NewInput extends {\n    //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n    //       ? Augmentation[k][\"_input\"]\n    //       : k extends keyof Input\n    //       ? Input[k]\n    //       : never;\n    //   }\n    // >(\n    //   merging: Incoming\n    // ): ZodObject<\n    //   extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n    //   Incoming[\"_def\"][\"unknownKeys\"],\n    //   Incoming[\"_def\"][\"catchall\"],\n    //   NewOutput,\n    //   NewInput\n    // > {\n    //   const merged: any = new ZodObject({\n    //     unknownKeys: merging._def.unknownKeys,\n    //     catchall: merging._def.catchall,\n    //     shape: () =>\n    //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n    //     typeName: ZodFirstPartyTypeKind.ZodObject,\n    //   }) as any;\n    //   return merged;\n    // }\n    setKey(key, schema) {\n        return this.augment({ [key]: schema });\n    }\n    // merge<Incoming extends AnyZodObject>(\n    //   merging: Incoming\n    // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n    // ZodObject<\n    //   extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n    //   Incoming[\"_def\"][\"unknownKeys\"],\n    //   Incoming[\"_def\"][\"catchall\"]\n    // > {\n    //   // const mergedShape = objectUtil.mergeShapes(\n    //   //   this._def.shape(),\n    //   //   merging._def.shape()\n    //   // );\n    //   const merged: any = new ZodObject({\n    //     unknownKeys: merging._def.unknownKeys,\n    //     catchall: merging._def.catchall,\n    //     shape: () =>\n    //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n    //     typeName: ZodFirstPartyTypeKind.ZodObject,\n    //   }) as any;\n    //   return merged;\n    // }\n    catchall(index) {\n        return new ZodObject({\n            ...this._def,\n            catchall: index,\n        });\n    }\n    pick(mask) {\n        const shape = {};\n        for (const key of util.objectKeys(mask)) {\n            if (mask[key] && this.shape[key]) {\n                shape[key] = this.shape[key];\n            }\n        }\n        return new ZodObject({\n            ...this._def,\n            shape: () => shape,\n        });\n    }\n    omit(mask) {\n        const shape = {};\n        for (const key of util.objectKeys(this.shape)) {\n            if (!mask[key]) {\n                shape[key] = this.shape[key];\n            }\n        }\n        return new ZodObject({\n            ...this._def,\n            shape: () => shape,\n        });\n    }\n    /**\n     * @deprecated\n     */\n    deepPartial() {\n        return deepPartialify(this);\n    }\n    partial(mask) {\n        const newShape = {};\n        for (const key of util.objectKeys(this.shape)) {\n            const fieldSchema = this.shape[key];\n            if (mask && !mask[key]) {\n                newShape[key] = fieldSchema;\n            }\n            else {\n                newShape[key] = fieldSchema.optional();\n            }\n        }\n        return new ZodObject({\n            ...this._def,\n            shape: () => newShape,\n        });\n    }\n    required(mask) {\n        const newShape = {};\n        for (const key of util.objectKeys(this.shape)) {\n            if (mask && !mask[key]) {\n                newShape[key] = this.shape[key];\n            }\n            else {\n                const fieldSchema = this.shape[key];\n                let newField = fieldSchema;\n                while (newField instanceof ZodOptional) {\n                    newField = newField._def.innerType;\n                }\n                newShape[key] = newField;\n            }\n        }\n        return new ZodObject({\n            ...this._def,\n            shape: () => newShape,\n        });\n    }\n    keyof() {\n        return createZodEnum(util.objectKeys(this.shape));\n    }\n}\nZodObject.create = (shape, params) => {\n    return new ZodObject({\n        shape: () => shape,\n        unknownKeys: \"strip\",\n        catchall: ZodNever.create(),\n        typeName: ZodFirstPartyTypeKind.ZodObject,\n        ...processCreateParams(params),\n    });\n};\nZodObject.strictCreate = (shape, params) => {\n    return new ZodObject({\n        shape: () => shape,\n        unknownKeys: \"strict\",\n        catchall: ZodNever.create(),\n        typeName: ZodFirstPartyTypeKind.ZodObject,\n        ...processCreateParams(params),\n    });\n};\nZodObject.lazycreate = (shape, params) => {\n    return new ZodObject({\n        shape,\n        unknownKeys: \"strip\",\n        catchall: ZodNever.create(),\n        typeName: ZodFirstPartyTypeKind.ZodObject,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodUnion extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        const options = this._def.options;\n        function handleResults(results) {\n            // return first issue-free validation if it exists\n            for (const result of results) {\n                if (result.result.status === \"valid\") {\n                    return result.result;\n                }\n            }\n            for (const result of results) {\n                if (result.result.status === \"dirty\") {\n                    // add issues from dirty option\n                    ctx.common.issues.push(...result.ctx.common.issues);\n                    return result.result;\n                }\n            }\n            // return invalid\n            const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_union,\n                unionErrors,\n            });\n            return INVALID;\n        }\n        if (ctx.common.async) {\n            return Promise.all(options.map(async (option) => {\n                const childCtx = {\n                    ...ctx,\n                    common: {\n                        ...ctx.common,\n                        issues: [],\n                    },\n                    parent: null,\n                };\n                return {\n                    result: await option._parseAsync({\n                        data: ctx.data,\n                        path: ctx.path,\n                        parent: childCtx,\n                    }),\n                    ctx: childCtx,\n                };\n            })).then(handleResults);\n        }\n        else {\n            let dirty = undefined;\n            const issues = [];\n            for (const option of options) {\n                const childCtx = {\n                    ...ctx,\n                    common: {\n                        ...ctx.common,\n                        issues: [],\n                    },\n                    parent: null,\n                };\n                const result = option._parseSync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: childCtx,\n                });\n                if (result.status === \"valid\") {\n                    return result;\n                }\n                else if (result.status === \"dirty\" && !dirty) {\n                    dirty = { result, ctx: childCtx };\n                }\n                if (childCtx.common.issues.length) {\n                    issues.push(childCtx.common.issues);\n                }\n            }\n            if (dirty) {\n                ctx.common.issues.push(...dirty.ctx.common.issues);\n                return dirty.result;\n            }\n            const unionErrors = issues.map((issues) => new ZodError(issues));\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_union,\n                unionErrors,\n            });\n            return INVALID;\n        }\n    }\n    get options() {\n        return this._def.options;\n    }\n}\nZodUnion.create = (types, params) => {\n    return new ZodUnion({\n        options: types,\n        typeName: ZodFirstPartyTypeKind.ZodUnion,\n        ...processCreateParams(params),\n    });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n//////////                                 //////////\n//////////      ZodDiscriminatedUnion      //////////\n//////////                                 //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n    if (type instanceof ZodLazy) {\n        return getDiscriminator(type.schema);\n    }\n    else if (type instanceof ZodEffects) {\n        return getDiscriminator(type.innerType());\n    }\n    else if (type instanceof ZodLiteral) {\n        return [type.value];\n    }\n    else if (type instanceof ZodEnum) {\n        return type.options;\n    }\n    else if (type instanceof ZodNativeEnum) {\n        // eslint-disable-next-line ban/ban\n        return util.objectValues(type.enum);\n    }\n    else if (type instanceof ZodDefault) {\n        return getDiscriminator(type._def.innerType);\n    }\n    else if (type instanceof ZodUndefined) {\n        return [undefined];\n    }\n    else if (type instanceof ZodNull) {\n        return [null];\n    }\n    else if (type instanceof ZodOptional) {\n        return [undefined, ...getDiscriminator(type.unwrap())];\n    }\n    else if (type instanceof ZodNullable) {\n        return [null, ...getDiscriminator(type.unwrap())];\n    }\n    else if (type instanceof ZodBranded) {\n        return getDiscriminator(type.unwrap());\n    }\n    else if (type instanceof ZodReadonly) {\n        return getDiscriminator(type.unwrap());\n    }\n    else if (type instanceof ZodCatch) {\n        return getDiscriminator(type._def.innerType);\n    }\n    else {\n        return [];\n    }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.object) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.object,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const discriminator = this.discriminator;\n        const discriminatorValue = ctx.data[discriminator];\n        const option = this.optionsMap.get(discriminatorValue);\n        if (!option) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_union_discriminator,\n                options: Array.from(this.optionsMap.keys()),\n                path: [discriminator],\n            });\n            return INVALID;\n        }\n        if (ctx.common.async) {\n            return option._parseAsync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            });\n        }\n        else {\n            return option._parseSync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            });\n        }\n    }\n    get discriminator() {\n        return this._def.discriminator;\n    }\n    get options() {\n        return this._def.options;\n    }\n    get optionsMap() {\n        return this._def.optionsMap;\n    }\n    /**\n     * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n     * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n     * have a different value for each object in the union.\n     * @param discriminator the name of the discriminator property\n     * @param types an array of object schemas\n     * @param params\n     */\n    static create(discriminator, options, params) {\n        // Get all the valid discriminator values\n        const optionsMap = new Map();\n        // try {\n        for (const type of options) {\n            const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n            if (!discriminatorValues.length) {\n                throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n            }\n            for (const value of discriminatorValues) {\n                if (optionsMap.has(value)) {\n                    throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n                }\n                optionsMap.set(value, type);\n            }\n        }\n        return new ZodDiscriminatedUnion({\n            typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n            discriminator,\n            options,\n            optionsMap,\n            ...processCreateParams(params),\n        });\n    }\n}\nfunction mergeValues(a, b) {\n    const aType = getParsedType(a);\n    const bType = getParsedType(b);\n    if (a === b) {\n        return { valid: true, data: a };\n    }\n    else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n        const bKeys = util.objectKeys(b);\n        const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n        const newObj = { ...a, ...b };\n        for (const key of sharedKeys) {\n            const sharedValue = mergeValues(a[key], b[key]);\n            if (!sharedValue.valid) {\n                return { valid: false };\n            }\n            newObj[key] = sharedValue.data;\n        }\n        return { valid: true, data: newObj };\n    }\n    else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n        if (a.length !== b.length) {\n            return { valid: false };\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 { valid: false };\n            }\n            newArray.push(sharedValue.data);\n        }\n        return { valid: true, data: newArray };\n    }\n    else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n        return { valid: true, data: a };\n    }\n    else {\n        return { valid: false };\n    }\n}\nexport class ZodIntersection extends ZodType {\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        const handleParsed = (parsedLeft, parsedRight) => {\n            if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n                return INVALID;\n            }\n            const merged = mergeValues(parsedLeft.value, parsedRight.value);\n            if (!merged.valid) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.invalid_intersection_types,\n                });\n                return INVALID;\n            }\n            if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n                status.dirty();\n            }\n            return { status: status.value, value: merged.data };\n        };\n        if (ctx.common.async) {\n            return Promise.all([\n                this._def.left._parseAsync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                }),\n                this._def.right._parseAsync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                }),\n            ]).then(([left, right]) => handleParsed(left, right));\n        }\n        else {\n            return handleParsed(this._def.left._parseSync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            }), this._def.right._parseSync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            }));\n        }\n    }\n}\nZodIntersection.create = (left, right, params) => {\n    return new ZodIntersection({\n        left: left,\n        right: right,\n        typeName: ZodFirstPartyTypeKind.ZodIntersection,\n        ...processCreateParams(params),\n    });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.array) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.array,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        if (ctx.data.length < this._def.items.length) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.too_small,\n                minimum: this._def.items.length,\n                inclusive: true,\n                exact: false,\n                type: \"array\",\n            });\n            return INVALID;\n        }\n        const rest = this._def.rest;\n        if (!rest && ctx.data.length > this._def.items.length) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.too_big,\n                maximum: this._def.items.length,\n                inclusive: true,\n                exact: false,\n                type: \"array\",\n            });\n            status.dirty();\n        }\n        const items = [...ctx.data]\n            .map((item, itemIndex) => {\n            const schema = this._def.items[itemIndex] || this._def.rest;\n            if (!schema)\n                return null;\n            return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n        })\n            .filter((x) => !!x); // filter nulls\n        if (ctx.common.async) {\n            return Promise.all(items).then((results) => {\n                return ParseStatus.mergeArray(status, results);\n            });\n        }\n        else {\n            return ParseStatus.mergeArray(status, items);\n        }\n    }\n    get items() {\n        return this._def.items;\n    }\n    rest(rest) {\n        return new ZodTuple({\n            ...this._def,\n            rest,\n        });\n    }\n}\nZodTuple.create = (schemas, params) => {\n    if (!Array.isArray(schemas)) {\n        throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n    }\n    return new ZodTuple({\n        items: schemas,\n        typeName: ZodFirstPartyTypeKind.ZodTuple,\n        rest: null,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodRecord extends ZodType {\n    get keySchema() {\n        return this._def.keyType;\n    }\n    get valueSchema() {\n        return this._def.valueType;\n    }\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.object) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.object,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const pairs = [];\n        const keyType = this._def.keyType;\n        const valueType = this._def.valueType;\n        for (const key in ctx.data) {\n            pairs.push({\n                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n                value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n                alwaysSet: key in ctx.data,\n            });\n        }\n        if (ctx.common.async) {\n            return ParseStatus.mergeObjectAsync(status, pairs);\n        }\n        else {\n            return ParseStatus.mergeObjectSync(status, pairs);\n        }\n    }\n    get element() {\n        return this._def.valueType;\n    }\n    static create(first, second, third) {\n        if (second instanceof ZodType) {\n            return new ZodRecord({\n                keyType: first,\n                valueType: second,\n                typeName: ZodFirstPartyTypeKind.ZodRecord,\n                ...processCreateParams(third),\n            });\n        }\n        return new ZodRecord({\n            keyType: ZodString.create(),\n            valueType: first,\n            typeName: ZodFirstPartyTypeKind.ZodRecord,\n            ...processCreateParams(second),\n        });\n    }\n}\nexport class ZodMap extends ZodType {\n    get keySchema() {\n        return this._def.keyType;\n    }\n    get valueSchema() {\n        return this._def.valueType;\n    }\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.map) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.map,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const keyType = this._def.keyType;\n        const valueType = this._def.valueType;\n        const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n            return {\n                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n                value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n            };\n        });\n        if (ctx.common.async) {\n            const finalMap = new Map();\n            return Promise.resolve().then(async () => {\n                for (const pair of pairs) {\n                    const key = await pair.key;\n                    const value = await pair.value;\n                    if (key.status === \"aborted\" || value.status === \"aborted\") {\n                        return INVALID;\n                    }\n                    if (key.status === \"dirty\" || value.status === \"dirty\") {\n                        status.dirty();\n                    }\n                    finalMap.set(key.value, value.value);\n                }\n                return { status: status.value, value: finalMap };\n            });\n        }\n        else {\n            const finalMap = new Map();\n            for (const pair of pairs) {\n                const key = pair.key;\n                const value = pair.value;\n                if (key.status === \"aborted\" || value.status === \"aborted\") {\n                    return INVALID;\n                }\n                if (key.status === \"dirty\" || value.status === \"dirty\") {\n                    status.dirty();\n                }\n                finalMap.set(key.value, value.value);\n            }\n            return { status: status.value, value: finalMap };\n        }\n    }\n}\nZodMap.create = (keyType, valueType, params) => {\n    return new ZodMap({\n        valueType,\n        keyType,\n        typeName: ZodFirstPartyTypeKind.ZodMap,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodSet extends ZodType {\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.set) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.set,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const def = this._def;\n        if (def.minSize !== null) {\n            if (ctx.data.size < def.minSize.value) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.too_small,\n                    minimum: def.minSize.value,\n                    type: \"set\",\n                    inclusive: true,\n                    exact: false,\n                    message: def.minSize.message,\n                });\n                status.dirty();\n            }\n        }\n        if (def.maxSize !== null) {\n            if (ctx.data.size > def.maxSize.value) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.too_big,\n                    maximum: def.maxSize.value,\n                    type: \"set\",\n                    inclusive: true,\n                    exact: false,\n                    message: def.maxSize.message,\n                });\n                status.dirty();\n            }\n        }\n        const valueType = this._def.valueType;\n        function finalizeSet(elements) {\n            const parsedSet = new Set();\n            for (const element of elements) {\n                if (element.status === \"aborted\")\n                    return INVALID;\n                if (element.status === \"dirty\")\n                    status.dirty();\n                parsedSet.add(element.value);\n            }\n            return { status: status.value, value: parsedSet };\n        }\n        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n        if (ctx.common.async) {\n            return Promise.all(elements).then((elements) => finalizeSet(elements));\n        }\n        else {\n            return finalizeSet(elements);\n        }\n    }\n    min(minSize, message) {\n        return new ZodSet({\n            ...this._def,\n            minSize: { value: minSize, message: errorUtil.toString(message) },\n        });\n    }\n    max(maxSize, message) {\n        return new ZodSet({\n            ...this._def,\n            maxSize: { value: maxSize, message: errorUtil.toString(message) },\n        });\n    }\n    size(size, message) {\n        return this.min(size, message).max(size, message);\n    }\n    nonempty(message) {\n        return this.min(1, message);\n    }\n}\nZodSet.create = (valueType, params) => {\n    return new ZodSet({\n        valueType,\n        minSize: null,\n        maxSize: null,\n        typeName: ZodFirstPartyTypeKind.ZodSet,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodFunction extends ZodType {\n    constructor() {\n        super(...arguments);\n        this.validate = this.implement;\n    }\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.function) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.function,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        function makeArgsIssue(args, error) {\n            return makeIssue({\n                data: args,\n                path: ctx.path,\n                errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n                issueData: {\n                    code: ZodIssueCode.invalid_arguments,\n                    argumentsError: error,\n                },\n            });\n        }\n        function makeReturnsIssue(returns, error) {\n            return makeIssue({\n                data: returns,\n                path: ctx.path,\n                errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n                issueData: {\n                    code: ZodIssueCode.invalid_return_type,\n                    returnTypeError: error,\n                },\n            });\n        }\n        const params = { errorMap: ctx.common.contextualErrorMap };\n        const fn = ctx.data;\n        if (this._def.returns instanceof ZodPromise) {\n            // Would love a way to avoid disabling this rule, but we need\n            // an alias (using an arrow function was what caused 2651).\n            // eslint-disable-next-line @typescript-eslint/no-this-alias\n            const me = this;\n            return OK(async function (...args) {\n                const error = new ZodError([]);\n                const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n                    error.addIssue(makeArgsIssue(args, e));\n                    throw error;\n                });\n                const result = await Reflect.apply(fn, this, parsedArgs);\n                const parsedReturns = await me._def.returns._def.type\n                    .parseAsync(result, params)\n                    .catch((e) => {\n                    error.addIssue(makeReturnsIssue(result, e));\n                    throw error;\n                });\n                return parsedReturns;\n            });\n        }\n        else {\n            // Would love a way to avoid disabling this rule, but we need\n            // an alias (using an arrow function was what caused 2651).\n            // eslint-disable-next-line @typescript-eslint/no-this-alias\n            const me = this;\n            return OK(function (...args) {\n                const parsedArgs = me._def.args.safeParse(args, params);\n                if (!parsedArgs.success) {\n                    throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n                }\n                const result = Reflect.apply(fn, this, parsedArgs.data);\n                const parsedReturns = me._def.returns.safeParse(result, params);\n                if (!parsedReturns.success) {\n                    throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n                }\n                return parsedReturns.data;\n            });\n        }\n    }\n    parameters() {\n        return this._def.args;\n    }\n    returnType() {\n        return this._def.returns;\n    }\n    args(...items) {\n        return new ZodFunction({\n            ...this._def,\n            args: ZodTuple.create(items).rest(ZodUnknown.create()),\n        });\n    }\n    returns(returnType) {\n        return new ZodFunction({\n            ...this._def,\n            returns: returnType,\n        });\n    }\n    implement(func) {\n        const validatedFunc = this.parse(func);\n        return validatedFunc;\n    }\n    strictImplement(func) {\n        const validatedFunc = this.parse(func);\n        return validatedFunc;\n    }\n    static create(args, returns, params) {\n        return new ZodFunction({\n            args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n            returns: returns || ZodUnknown.create(),\n            typeName: ZodFirstPartyTypeKind.ZodFunction,\n            ...processCreateParams(params),\n        });\n    }\n}\nexport class ZodLazy extends ZodType {\n    get schema() {\n        return this._def.getter();\n    }\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        const lazySchema = this._def.getter();\n        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n    }\n}\nZodLazy.create = (getter, params) => {\n    return new ZodLazy({\n        getter: getter,\n        typeName: ZodFirstPartyTypeKind.ZodLazy,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodLiteral extends ZodType {\n    _parse(input) {\n        if (input.data !== this._def.value) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                received: ctx.data,\n                code: ZodIssueCode.invalid_literal,\n                expected: this._def.value,\n            });\n            return INVALID;\n        }\n        return { status: \"valid\", value: input.data };\n    }\n    get value() {\n        return this._def.value;\n    }\n}\nZodLiteral.create = (value, params) => {\n    return new ZodLiteral({\n        value: value,\n        typeName: ZodFirstPartyTypeKind.ZodLiteral,\n        ...processCreateParams(params),\n    });\n};\nfunction createZodEnum(values, params) {\n    return new ZodEnum({\n        values,\n        typeName: ZodFirstPartyTypeKind.ZodEnum,\n        ...processCreateParams(params),\n    });\n}\nexport class ZodEnum extends ZodType {\n    _parse(input) {\n        if (typeof input.data !== \"string\") {\n            const ctx = this._getOrReturnCtx(input);\n            const expectedValues = this._def.values;\n            addIssueToContext(ctx, {\n                expected: util.joinValues(expectedValues),\n                received: ctx.parsedType,\n                code: ZodIssueCode.invalid_type,\n            });\n            return INVALID;\n        }\n        if (!this._cache) {\n            this._cache = new Set(this._def.values);\n        }\n        if (!this._cache.has(input.data)) {\n            const ctx = this._getOrReturnCtx(input);\n            const expectedValues = this._def.values;\n            addIssueToContext(ctx, {\n                received: ctx.data,\n                code: ZodIssueCode.invalid_enum_value,\n                options: expectedValues,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n    get options() {\n        return this._def.values;\n    }\n    get enum() {\n        const enumValues = {};\n        for (const val of this._def.values) {\n            enumValues[val] = val;\n        }\n        return enumValues;\n    }\n    get Values() {\n        const enumValues = {};\n        for (const val of this._def.values) {\n            enumValues[val] = val;\n        }\n        return enumValues;\n    }\n    get Enum() {\n        const enumValues = {};\n        for (const val of this._def.values) {\n            enumValues[val] = val;\n        }\n        return enumValues;\n    }\n    extract(values, newDef = this._def) {\n        return ZodEnum.create(values, {\n            ...this._def,\n            ...newDef,\n        });\n    }\n    exclude(values, newDef = this._def) {\n        return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n            ...this._def,\n            ...newDef,\n        });\n    }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n    _parse(input) {\n        const nativeEnumValues = util.getValidEnumValues(this._def.values);\n        const ctx = this._getOrReturnCtx(input);\n        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n            const expectedValues = util.objectValues(nativeEnumValues);\n            addIssueToContext(ctx, {\n                expected: util.joinValues(expectedValues),\n                received: ctx.parsedType,\n                code: ZodIssueCode.invalid_type,\n            });\n            return INVALID;\n        }\n        if (!this._cache) {\n            this._cache = new Set(util.getValidEnumValues(this._def.values));\n        }\n        if (!this._cache.has(input.data)) {\n            const expectedValues = util.objectValues(nativeEnumValues);\n            addIssueToContext(ctx, {\n                received: ctx.data,\n                code: ZodIssueCode.invalid_enum_value,\n                options: expectedValues,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n    get enum() {\n        return this._def.values;\n    }\n}\nZodNativeEnum.create = (values, params) => {\n    return new ZodNativeEnum({\n        values: values,\n        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodPromise extends ZodType {\n    unwrap() {\n        return this._def.type;\n    }\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.promise,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n        return OK(promisified.then((data) => {\n            return this._def.type.parseAsync(data, {\n                path: ctx.path,\n                errorMap: ctx.common.contextualErrorMap,\n            });\n        }));\n    }\n}\nZodPromise.create = (schema, params) => {\n    return new ZodPromise({\n        type: schema,\n        typeName: ZodFirstPartyTypeKind.ZodPromise,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodEffects extends ZodType {\n    innerType() {\n        return this._def.schema;\n    }\n    sourceType() {\n        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n            ? this._def.schema.sourceType()\n            : this._def.schema;\n    }\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        const effect = this._def.effect || null;\n        const checkCtx = {\n            addIssue: (arg) => {\n                addIssueToContext(ctx, arg);\n                if (arg.fatal) {\n                    status.abort();\n                }\n                else {\n                    status.dirty();\n                }\n            },\n            get path() {\n                return ctx.path;\n            },\n        };\n        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n        if (effect.type === \"preprocess\") {\n            const processed = effect.transform(ctx.data, checkCtx);\n            if (ctx.common.async) {\n                return Promise.resolve(processed).then(async (processed) => {\n                    if (status.value === \"aborted\")\n                        return INVALID;\n                    const result = await this._def.schema._parseAsync({\n                        data: processed,\n                        path: ctx.path,\n                        parent: ctx,\n                    });\n                    if (result.status === \"aborted\")\n                        return INVALID;\n                    if (result.status === \"dirty\")\n                        return DIRTY(result.value);\n                    if (status.value === \"dirty\")\n                        return DIRTY(result.value);\n                    return result;\n                });\n            }\n            else {\n                if (status.value === \"aborted\")\n                    return INVALID;\n                const result = this._def.schema._parseSync({\n                    data: processed,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n                if (result.status === \"aborted\")\n                    return INVALID;\n                if (result.status === \"dirty\")\n                    return DIRTY(result.value);\n                if (status.value === \"dirty\")\n                    return DIRTY(result.value);\n                return result;\n            }\n        }\n        if (effect.type === \"refinement\") {\n            const executeRefinement = (acc) => {\n                const result = effect.refinement(acc, checkCtx);\n                if (ctx.common.async) {\n                    return Promise.resolve(result);\n                }\n                if (result instanceof Promise) {\n                    throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n                }\n                return acc;\n            };\n            if (ctx.common.async === false) {\n                const inner = this._def.schema._parseSync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n                if (inner.status === \"aborted\")\n                    return INVALID;\n                if (inner.status === \"dirty\")\n                    status.dirty();\n                // return value is ignored\n                executeRefinement(inner.value);\n                return { status: status.value, value: inner.value };\n            }\n            else {\n                return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n                    if (inner.status === \"aborted\")\n                        return INVALID;\n                    if (inner.status === \"dirty\")\n                        status.dirty();\n                    return executeRefinement(inner.value).then(() => {\n                        return { status: status.value, value: inner.value };\n                    });\n                });\n            }\n        }\n        if (effect.type === \"transform\") {\n            if (ctx.common.async === false) {\n                const base = this._def.schema._parseSync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n                if (!isValid(base))\n                    return INVALID;\n                const result = effect.transform(base.value, checkCtx);\n                if (result instanceof Promise) {\n                    throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n                }\n                return { status: status.value, value: result };\n            }\n            else {\n                return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n                    if (!isValid(base))\n                        return INVALID;\n                    return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n                        status: status.value,\n                        value: result,\n                    }));\n                });\n            }\n        }\n        util.assertNever(effect);\n    }\n}\nZodEffects.create = (schema, effect, params) => {\n    return new ZodEffects({\n        schema,\n        typeName: ZodFirstPartyTypeKind.ZodEffects,\n        effect,\n        ...processCreateParams(params),\n    });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n    return new ZodEffects({\n        schema,\n        effect: { type: \"preprocess\", transform: preprocess },\n        typeName: ZodFirstPartyTypeKind.ZodEffects,\n        ...processCreateParams(params),\n    });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType === ZodParsedType.undefined) {\n            return OK(undefined);\n        }\n        return this._def.innerType._parse(input);\n    }\n    unwrap() {\n        return this._def.innerType;\n    }\n}\nZodOptional.create = (type, params) => {\n    return new ZodOptional({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodOptional,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodNullable extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType === ZodParsedType.null) {\n            return OK(null);\n        }\n        return this._def.innerType._parse(input);\n    }\n    unwrap() {\n        return this._def.innerType;\n    }\n}\nZodNullable.create = (type, params) => {\n    return new ZodNullable({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodNullable,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodDefault extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        let data = ctx.data;\n        if (ctx.parsedType === ZodParsedType.undefined) {\n            data = this._def.defaultValue();\n        }\n        return this._def.innerType._parse({\n            data,\n            path: ctx.path,\n            parent: ctx,\n        });\n    }\n    removeDefault() {\n        return this._def.innerType;\n    }\n}\nZodDefault.create = (type, params) => {\n    return new ZodDefault({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodDefault,\n        defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodCatch extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        // newCtx is used to not collect issues from inner types in ctx\n        const newCtx = {\n            ...ctx,\n            common: {\n                ...ctx.common,\n                issues: [],\n            },\n        };\n        const result = this._def.innerType._parse({\n            data: newCtx.data,\n            path: newCtx.path,\n            parent: {\n                ...newCtx,\n            },\n        });\n        if (isAsync(result)) {\n            return result.then((result) => {\n                return {\n                    status: \"valid\",\n                    value: result.status === \"valid\"\n                        ? result.value\n                        : this._def.catchValue({\n                            get error() {\n                                return new ZodError(newCtx.common.issues);\n                            },\n                            input: newCtx.data,\n                        }),\n                };\n            });\n        }\n        else {\n            return {\n                status: \"valid\",\n                value: result.status === \"valid\"\n                    ? result.value\n                    : this._def.catchValue({\n                        get error() {\n                            return new ZodError(newCtx.common.issues);\n                        },\n                        input: newCtx.data,\n                    }),\n            };\n        }\n    }\n    removeCatch() {\n        return this._def.innerType;\n    }\n}\nZodCatch.create = (type, params) => {\n    return new ZodCatch({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodCatch,\n        catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodNaN extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.nan) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.nan,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return { status: \"valid\", value: input.data };\n    }\n}\nZodNaN.create = (params) => {\n    return new ZodNaN({\n        typeName: ZodFirstPartyTypeKind.ZodNaN,\n        ...processCreateParams(params),\n    });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        const data = ctx.data;\n        return this._def.type._parse({\n            data,\n            path: ctx.path,\n            parent: ctx,\n        });\n    }\n    unwrap() {\n        return this._def.type;\n    }\n}\nexport class ZodPipeline extends ZodType {\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.common.async) {\n            const handleAsync = async () => {\n                const inResult = await this._def.in._parseAsync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n                if (inResult.status === \"aborted\")\n                    return INVALID;\n                if (inResult.status === \"dirty\") {\n                    status.dirty();\n                    return DIRTY(inResult.value);\n                }\n                else {\n                    return this._def.out._parseAsync({\n                        data: inResult.value,\n                        path: ctx.path,\n                        parent: ctx,\n                    });\n                }\n            };\n            return handleAsync();\n        }\n        else {\n            const inResult = this._def.in._parseSync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            });\n            if (inResult.status === \"aborted\")\n                return INVALID;\n            if (inResult.status === \"dirty\") {\n                status.dirty();\n                return {\n                    status: \"dirty\",\n                    value: inResult.value,\n                };\n            }\n            else {\n                return this._def.out._parseSync({\n                    data: inResult.value,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n            }\n        }\n    }\n    static create(a, b) {\n        return new ZodPipeline({\n            in: a,\n            out: b,\n            typeName: ZodFirstPartyTypeKind.ZodPipeline,\n        });\n    }\n}\nexport class ZodReadonly extends ZodType {\n    _parse(input) {\n        const result = this._def.innerType._parse(input);\n        const freeze = (data) => {\n            if (isValid(data)) {\n                data.value = Object.freeze(data.value);\n            }\n            return data;\n        };\n        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n    }\n    unwrap() {\n        return this._def.innerType;\n    }\n}\nZodReadonly.create = (type, params) => {\n    return new ZodReadonly({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodReadonly,\n        ...processCreateParams(params),\n    });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n//////////                    //////////\n//////////      z.custom      //////////\n//////////                    //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n    const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n    const p2 = typeof p === \"string\" ? { message: p } : p;\n    return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n    if (check)\n        return ZodAny.create().superRefine((data, ctx) => {\n            const r = check(data);\n            if (r instanceof Promise) {\n                return r.then((r) => {\n                    if (!r) {\n                        const params = cleanParams(_params, data);\n                        const _fatal = params.fatal ?? fatal ?? true;\n                        ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n                    }\n                });\n            }\n            if (!r) {\n                const params = cleanParams(_params, data);\n                const _fatal = params.fatal ?? fatal ?? true;\n                ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n            }\n            return;\n        });\n    return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n    object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n    ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n    ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n    ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n    ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n    ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n    ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n    ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n    ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n    ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n    ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n    ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n    ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n    ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n    ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n    ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n    ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n    ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n    ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n    ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n    ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n    ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n    ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n    ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n    ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n    ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n    ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n    ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n    ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n    ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n    ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n    ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n    ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n    ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n    ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n    ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n    ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n    constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n    message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n    string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n    number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n    boolean: ((arg) => ZodBoolean.create({\n        ...arg,\n        coerce: true,\n    })),\n    bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n    date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n", "/**\n * The type of error that occurred.\n * @public\n */\nexport type ErrorType = 'invalid-retry' | 'unknown-field'\n\n/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n  /**\n   * The type of error that occurred.\n   */\n  type: ErrorType\n\n  /**\n   * In the case of an unknown field encountered in the stream, this will be the field name.\n   */\n  field?: string | undefined\n\n  /**\n   * In the case of an unknown field encountered in the stream, this will be the value of the field.\n   */\n  value?: string | undefined\n\n  /**\n   * The line that caused the error, if available.\n   */\n  line?: string | undefined\n\n  constructor(\n    message: string,\n    options: {type: ErrorType; field?: string; value?: string; line?: string},\n  ) {\n    super(message)\n    this.name = 'ParseError'\n    this.type = options.type\n    this.field = options.field\n    this.value = options.value\n    this.line = options.line\n  }\n}\n", "/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport {ParseError} from './errors.ts'\nimport type {EventSourceParser, ParserCallbacks} from './types.ts'\n\n// ASCII codes used in the hot parsing paths.\nconst LF = 10\nconst CR = 13\nconst SPACE = 32\n\n// oxlint-disable-next-line no-unused-vars\nfunction noop(_arg: unknown) {\n  // intentional noop\n}\n\n/**\n * Creates a new EventSource parser.\n *\n * @param callbacks - Callbacks to invoke on different parsing events:\n *   - `onEvent` when a new event is parsed\n *   - `onError` when an error occurs\n *   - `onRetry` when a new reconnection interval has been sent from the server\n *   - `onComment` when a comment is encountered in the stream\n *\n * @returns A new EventSource parser, with `parse` and `reset` methods.\n * @public\n */\nexport function createParser(callbacks: ParserCallbacks): EventSourceParser {\n  if (typeof callbacks === 'function') {\n    throw new TypeError(\n      '`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?',\n    )\n  }\n\n  const {onEvent = noop, onError = noop, onRetry = noop, onComment} = callbacks\n\n  // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n  // Stored as an array of fragments and only joined when a line terminator arrives.\n  // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n  // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n  // server that emits one giant content block). Buffering as fragments + joining once\n  // makes the same workload linear.\n  const pendingFragments: string[] = []\n\n  let isFirstChunk = true\n  let id: string | undefined\n  let data = ''\n  let dataLines = 0\n  let eventType: string | undefined\n\n  /**\n   * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n   * not yet form a complete line are held back and prepended to the next chunk,\n   * so callers can pass arbitrary slices of the stream without worrying about\n   * line boundaries.\n   *\n   * Per the SSE spec, a UTF-8 BOM (0xEF 0xBB 0xBF) at the start of the very\n   * first chunk is stripped before parsing.\n   *\n   * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n   */\n  function feed(chunk: string) {\n    if (isFirstChunk) {\n      isFirstChunk = false\n      // Match and strip UTF-8 BOM from the start of the stream, if present.\n      // (Per the spec, this is only valid at the very start of the stream)\n      if (\n        chunk.charCodeAt(0) === 0xef &&\n        chunk.charCodeAt(1) === 0xbb &&\n        chunk.charCodeAt(2) === 0xbf\n      ) {\n        chunk = chunk.slice(3)\n      }\n    }\n\n    // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n    // straight to `processLines`, exactly like the original implementation.\n    // Zero new work in the common case (every chunk ends with `\\n\\n`).\n    if (pendingFragments.length === 0) {\n      const trailing = processLines(chunk)\n      if (trailing !== '') pendingFragments.push(trailing)\n      return\n    }\n\n    // We have a buffered prefix. If this chunk also has no terminator, append\n    // to the buffer without concatenating — that's the O(N²) trap we're\n    // avoiding (large single `data:` payload split across many tiny chunks).\n    if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n      pendingFragments.push(chunk)\n      return\n    }\n\n    // Terminator arrived. Join the accumulated fragments + this chunk once,\n    // process, and buffer any new trailing partial line.\n    pendingFragments.push(chunk)\n    const input = pendingFragments.join('')\n    pendingFragments.length = 0\n    const trailing = processLines(input)\n    if (trailing !== '') pendingFragments.push(trailing)\n  }\n\n  /**\n   * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n   * Returns any trailing bytes that did not terminate with a line break, so the\n   * caller can prepend them to the next chunk.\n   *\n   * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n   * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n   * present in the chunk. The slow path is spec-correct but does more work per line.\n   */\n  function processLines(chunk: string): string {\n    let searchIndex = 0\n\n    // Fast path: LF-only chunk (the common case for typical SSE servers).\n    // We can scan forward with a single `indexOf('\\n')` per line and inline\n    // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n    // the slow path needs.\n    if (chunk.indexOf('\\r') === -1) {\n      let lfIndex = chunk.indexOf('\\n', searchIndex)\n      while (lfIndex !== -1) {\n        // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n        // and reset the buffered fields. This is hoisted out of `parseLine` because\n        // it's the single most common line shape after `data:` lines.\n        if (searchIndex === lfIndex) {\n          if (dataLines > 0) {\n            onEvent({id, event: eventType, data})\n          }\n          id = undefined\n          data = ''\n          dataLines = 0\n          eventType = undefined\n          searchIndex = lfIndex + 1\n          lfIndex = chunk.indexOf('\\n', searchIndex)\n          continue\n        }\n        const firstCharCode = chunk.charCodeAt(searchIndex)\n        if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n          // `data:` line — append the value to the event's data buffer.\n          // 'data:'.length === 5, 'data: '.length === 6\n          const valueStart =\n            chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5\n          const value = chunk.slice(valueStart, lfIndex)\n          // Fast path within a fast path: if this is the first data line AND the\n          // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n          // without ever writing to the `data` buffer. This is the shape of a\n          // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n          // hot enough to be worth the duplication.\n          if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n            onEvent({id, event: eventType, data: value})\n            id = undefined\n            data = ''\n            eventType = undefined\n            searchIndex = lfIndex + 2\n            lfIndex = chunk.indexOf('\\n', searchIndex)\n            continue\n          }\n          // Multi-line data: concatenate with newline separator per spec.\n          data = dataLines === 0 ? value : `${data}\\n${value}`\n          dataLines++\n        } else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n          // `event:` line — set the event type for the next dispatch. Per spec,\n          // an empty value resets `event type` to its default (undefined here).\n          // 'event:'.length === 6, 'event: '.length === 7\n          eventType =\n            chunk.slice(\n              chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n              lfIndex,\n            ) || undefined\n        } else {\n          // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n          // fields, or malformed lines. These are rarer and go through the full\n          // per-line parser, which handles the SSE field grammar in detail.\n          parseLine(chunk, searchIndex, lfIndex)\n        }\n        searchIndex = lfIndex + 1\n        lfIndex = chunk.indexOf('\\n', searchIndex)\n      }\n      return chunk.slice(searchIndex)\n    }\n\n    // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n    // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n    // the nearest `\\r` and `\\n` and picking whichever comes first.\n    while (searchIndex < chunk.length) {\n      const crIndex = chunk.indexOf('\\r', searchIndex)\n      const lfIndex = chunk.indexOf('\\n', searchIndex)\n\n      let lineEnd = -1\n      if (crIndex !== -1 && lfIndex !== -1) {\n        lineEnd = crIndex < lfIndex ? crIndex : lfIndex\n      } else if (crIndex !== -1) {\n        // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n        // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n        // in the next chunk. Defer until we see more input.\n        if (crIndex === chunk.length - 1) {\n          lineEnd = -1\n        } else {\n          lineEnd = crIndex\n        }\n      } else if (lfIndex !== -1) {\n        lineEnd = lfIndex\n      }\n\n      if (lineEnd === -1) {\n        break\n      }\n\n      parseLine(chunk, searchIndex, lineEnd)\n      searchIndex = lineEnd + 1\n      // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n      // pair is treated as a single terminator rather than an empty line.\n      if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n        searchIndex++\n      }\n    }\n\n    return chunk.slice(searchIndex)\n  }\n\n  function parseLine(chunk: string, start: number, end: number) {\n    if (start === end) {\n      dispatchEvent()\n      return\n    }\n\n    const firstCharCode = chunk.charCodeAt(start)\n\n    if (isDataPrefix(chunk, start, firstCharCode)) {\n      // 'data:'.length === 5, 'data: '.length === 6\n      const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5\n      const value = chunk.slice(valueStart, end)\n      data = dataLines === 0 ? value : `${data}\\n${value}`\n      dataLines++\n      return\n    }\n\n    if (isEventPrefix(chunk, start, firstCharCode)) {\n      // 'event:'.length === 6, 'event: '.length === 7\n      eventType =\n        chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined\n      return\n    }\n\n    // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n    if (\n      firstCharCode === 105 &&\n      chunk.charCodeAt(start + 1) === 100 &&\n      chunk.charCodeAt(start + 2) === 58\n    ) {\n      // 'id:'.length === 3, 'id: '.length === 4\n      const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end)\n      id = value.includes('\\0') ? undefined : value\n      return\n    }\n\n    // Comment line — ':' = 58\n    if (firstCharCode === 58) {\n      if (onComment) {\n        const line = chunk.slice(start, end)\n        // skip ':' (+1), or ': ' (+2) when a space follows\n        onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1))\n      }\n      return\n    }\n\n    const line = chunk.slice(start, end)\n    const fieldSeparatorIndex = line.indexOf(':')\n    if (fieldSeparatorIndex === -1) {\n      processField(line, '', line)\n      return\n    }\n\n    const field = line.slice(0, fieldSeparatorIndex)\n    // skip ':' (+1), or ': ' (+2) when a space follows\n    const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1\n    const value = line.slice(fieldSeparatorIndex + offset)\n    processField(field, value, line)\n  }\n\n  function processField(field: string, value: string, line: string) {\n    // Field names must be compared literally, with no case folding performed.\n    switch (field) {\n      case 'event':\n        // Set the `event type` buffer to field value\n        eventType = value || undefined\n        break\n      case 'data':\n        data = dataLines === 0 ? value : `${data}\\n${value}`\n        dataLines++\n        break\n      case 'id':\n        // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n        // the field value. Otherwise, ignore the field.\n        id = value.includes('\\0') ? undefined : value\n        break\n      case 'retry':\n        // If the field value consists of only ASCII digits, then interpret the field value as an\n        // integer in base ten, and set the event stream's reconnection time to that integer.\n        // Otherwise, ignore the field.\n        if (/^\\d+$/.test(value)) {\n          onRetry(parseInt(value, 10))\n        } else {\n          onError(\n            new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n              type: 'invalid-retry',\n              value,\n              line,\n            }),\n          )\n        }\n        break\n      default:\n        // Otherwise, the field is ignored.\n        onError(\n          new ParseError(\n            `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`,\n            {type: 'unknown-field', field, value, line},\n          ),\n        )\n        break\n    }\n  }\n\n  function dispatchEvent() {\n    if (dataLines > 0) {\n      onEvent({\n        id,\n        event: eventType,\n        data,\n      })\n    }\n\n    id = undefined\n    data = ''\n    dataLines = 0\n    eventType = undefined\n  }\n\n  function reset(options: {consume?: boolean} = {}) {\n    if (options.consume && pendingFragments.length > 0) {\n      const incompleteLine = pendingFragments.join('')\n      parseLine(incompleteLine, 0, incompleteLine.length)\n    }\n\n    isFirstChunk = true\n    id = undefined\n    data = ''\n    dataLines = 0\n    eventType = undefined\n    pendingFragments.length = 0\n  }\n\n  return {feed, reset}\n}\n\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n  return (\n    firstCharCode === 100 &&\n    chunk.charCodeAt(i + 1) === 97 &&\n    chunk.charCodeAt(i + 2) === 116 &&\n    chunk.charCodeAt(i + 3) === 97 &&\n    chunk.charCodeAt(i + 4) === 58\n  )\n}\n\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n  return (\n    firstCharCode === 101 &&\n    chunk.charCodeAt(i + 1) === 118 &&\n    chunk.charCodeAt(i + 2) === 101 &&\n    chunk.charCodeAt(i + 3) === 110 &&\n    chunk.charCodeAt(i + 4) === 116 &&\n    chunk.charCodeAt(i + 5) === 58\n  )\n}\n", "import {createParser} from './parse.ts'\nimport type {EventSourceMessage, EventSourceParser} from './types.ts'\n\n/**\n * Options for the EventSourceParserStream.\n *\n * @public\n */\nexport interface StreamOptions {\n  /**\n   * Behavior when a parsing error occurs.\n   *\n   * - A custom function can be provided to handle the error.\n   * - `'terminate'` will error the stream and stop parsing.\n   * - Any other value will ignore the error and continue parsing.\n   *\n   * @defaultValue `undefined`\n   */\n  onError?: ('terminate' | ((error: Error) => void)) | undefined\n\n  /**\n   * Callback for when a reconnection interval is sent from the server.\n   *\n   * @param retry - The number of milliseconds to wait before reconnecting.\n   */\n  onRetry?: ((retry: number) => void) | undefined\n\n  /**\n   * Callback for when a comment is encountered in the stream.\n   *\n   * @param comment - The comment encountered in the stream.\n   */\n  onComment?: ((comment: string) => void) | undefined\n}\n\n/**\n * A TransformStream that ingests a stream of strings and produces a stream of `EventSourceMessage`.\n *\n * @example Basic usage\n * ```\n * const eventStream =\n *   response.body\n *     .pipeThrough(new TextDecoderStream())\n *     .pipeThrough(new EventSourceParserStream())\n * ```\n *\n * @example Terminate stream on parsing errors\n * ```\n * const eventStream =\n *  response.body\n *   .pipeThrough(new TextDecoderStream())\n *   .pipeThrough(new EventSourceParserStream({terminateOnError: true}))\n * ```\n *\n * @public\n */\nexport class EventSourceParserStream extends TransformStream<string, EventSourceMessage> {\n  constructor({onError, onRetry, onComment}: StreamOptions = {}) {\n    let parser!: EventSourceParser\n\n    super({\n      start(controller) {\n        parser = createParser({\n          onEvent: (event) => {\n            controller.enqueue(event)\n          },\n          onError(error) {\n            if (onError === 'terminate') {\n              controller.error(error)\n            } else if (typeof onError === 'function') {\n              onError(error)\n            }\n\n            // Ignore by default\n          },\n          onRetry,\n          onComment,\n        })\n      },\n      transform(chunk) {\n        parser.feed(chunk)\n      },\n    })\n  }\n}\n\nexport {type ErrorType, ParseError} from './errors.ts'\nexport type {EventSourceMessage} from './types.ts'\n", "export function combineHeaders(\n  ...headers: Array<Record<string, string | undefined> | undefined>\n): Record<string, string | undefined> {\n  return headers.reduce(\n    (combinedHeaders, currentHeaders) => ({\n      ...combinedHeaders,\n      ...(currentHeaders ?? {}),\n    }),\n    {},\n  ) as Record<string, string | undefined>;\n}\n", "/**\n * Converts an AsyncIterator to a ReadableStream.\n *\n * @template T - The type of elements produced by the AsyncIterator.\n * @param { <T>} iterator - The AsyncIterator to convert.\n * @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.\n */\nexport function convertAsyncIteratorToReadableStream<T>(\n  iterator: AsyncIterator<T>,\n): ReadableStream<T> {\n  let cancelled = false;\n\n  return new ReadableStream<T>({\n    /**\n     * Called when the consumer wants to pull more data from the stream.\n     *\n     * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n     * @returns {Promise<void>}\n     */\n    async pull(controller) {\n      if (cancelled) return;\n      try {\n        const { value, done } = await iterator.next();\n        if (done) {\n          controller.close();\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (error) {\n        controller.error(error);\n      }\n    },\n    /**\n     * Called when the consumer cancels the stream.\n     */\n    async cancel(reason?: unknown) {\n      cancelled = true;\n      if (iterator.return) {\n        try {\n          await iterator.return(reason);\n        } catch {\n          // intentionally ignore errors during cancellation\n        }\n      }\n    },\n  });\n}\n", "import type {\n  LanguageModelV3FunctionTool,\n  LanguageModelV3ProviderTool,\n} from '@ai-sdk/provider';\n\n/**\n * Interface for mapping between custom tool names and provider tool names.\n */\nexport interface ToolNameMapping {\n  /**\n   * Maps a custom tool name (used by the client) to the provider's tool name.\n   * If the custom tool name does not have a mapping, returns the input name.\n   *\n   * @param customToolName - The custom name of the tool defined by the client.\n   * @returns The corresponding provider tool name, or the input name if not mapped.\n   */\n  toProviderToolName: (customToolName: string) => string;\n\n  /**\n   * Maps a provider tool name to the custom tool name used by the client.\n   * If the provider tool name does not have a mapping, returns the input name.\n   *\n   * @param providerToolName - The name of the tool as understood by the provider.\n   * @returns The corresponding custom tool name, or the input name if not mapped.\n   */\n  toCustomToolName: (providerToolName: string) => string;\n}\n\n/**\n * @param tools - Tools that were passed to the language model.\n * @param providerToolNames - Maps the provider tool ids to the provider tool names.\n */\nexport function createToolNameMapping({\n  tools = [],\n  providerToolNames,\n  resolveProviderToolName,\n}: {\n  /**\n   * Tools that were passed to the language model.\n   */\n  tools:\n    | Array<LanguageModelV3FunctionTool | LanguageModelV3ProviderTool>\n    | undefined;\n\n  /**\n   * Maps the provider tool ids to the provider tool names.\n   */\n  providerToolNames: Record<`${string}.${string}`, string>;\n\n  /**\n   * Optional resolver for provider tool names that cannot be represented as\n   * static id -> name mappings (e.g. dynamic provider names).\n   */\n  resolveProviderToolName?: (\n    tool: LanguageModelV3ProviderTool,\n  ) => string | undefined;\n}): ToolNameMapping {\n  const customToolNameToProviderToolName: Record<string, string> = {};\n  const providerToolNameToCustomToolName: Record<string, string> = {};\n\n  for (const tool of tools) {\n    if (tool.type === 'provider') {\n      const providerToolName =\n        resolveProviderToolName?.(tool) ??\n        (tool.id in providerToolNames ? providerToolNames[tool.id] : undefined);\n\n      if (providerToolName == null) {\n        continue;\n      }\n\n      customToolNameToProviderToolName[tool.name] = providerToolName;\n      providerToolNameToCustomToolName[providerToolName] = tool.name;\n    }\n  }\n\n  return {\n    toProviderToolName: (customToolName: string) =>\n      customToolNameToProviderToolName[customToolName] ?? customToolName,\n    toCustomToolName: (providerToolName: string) =>\n      providerToolNameToCustomToolName[providerToolName] ?? providerToolName,\n  };\n}\n", "/**\n * Creates a Promise that resolves after a specified delay\n * @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.\n * @param signal - Optional AbortSignal to cancel the delay\n * @returns A Promise that resolves after the specified delay\n * @throws {DOMException} When the signal is aborted\n */\nexport async function delay(\n  delayInMs?: number | null,\n  options?: {\n    abortSignal?: AbortSignal;\n  },\n): Promise<void> {\n  if (delayInMs == null) {\n    return Promise.resolve();\n  }\n\n  const signal = options?.abortSignal;\n\n  return new Promise<void>((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(createAbortError());\n      return;\n    }\n\n    const timeoutId = setTimeout(() => {\n      cleanup();\n      resolve();\n    }, delayInMs);\n\n    const cleanup = () => {\n      clearTimeout(timeoutId);\n      signal?.removeEventListener('abort', onAbort);\n    };\n\n    const onAbort = () => {\n      cleanup();\n      reject(createAbortError());\n    };\n\n    signal?.addEventListener('abort', onAbort);\n  });\n}\n\nfunction createAbortError(): DOMException {\n  return new DOMException('Delay was aborted', 'AbortError');\n}\n", "/**\n * Delayed promise. It is only constructed once the value is accessed.\n * This is useful to avoid unhandled promise rejections when the promise is created\n * but not accessed.\n */\nexport class DelayedPromise<T> {\n  private status:\n    | { type: 'pending' }\n    | { type: 'resolved'; value: T }\n    | { type: 'rejected'; error: unknown } = { type: 'pending' };\n  private _promise: Promise<T> | undefined;\n  private _resolve: undefined | ((value: T) => void) = undefined;\n  private _reject: undefined | ((error: unknown) => void) = undefined;\n\n  get promise(): Promise<T> {\n    if (this._promise) {\n      return this._promise;\n    }\n\n    this._promise = new Promise<T>((resolve, reject) => {\n      if (this.status.type === 'resolved') {\n        resolve(this.status.value);\n      } else if (this.status.type === 'rejected') {\n        reject(this.status.error);\n      }\n\n      this._resolve = resolve;\n      this._reject = reject;\n    });\n\n    return this._promise;\n  }\n\n  resolve(value: T): void {\n    this.status = { type: 'resolved', value };\n\n    if (this._promise) {\n      this._resolve?.(value);\n    }\n  }\n\n  reject(error: unknown): void {\n    this.status = { type: 'rejected', error };\n\n    if (this._promise) {\n      this._reject?.(error);\n    }\n  }\n\n  isResolved(): boolean {\n    return this.status.type === 'resolved';\n  }\n\n  isRejected(): boolean {\n    return this.status.type === 'rejected';\n  }\n\n  isPending(): boolean {\n    return this.status.type === 'pending';\n  }\n}\n", "/**\n * Extracts the headers from a response object and returns them as a key-value object.\n *\n * @param response - The response object to extract headers from.\n * @returns The headers as a key-value object.\n */\nexport function extractResponseHeaders(response: Response) {\n  return Object.fromEntries<string>([...response.headers]);\n}\n", "// btoa and atob need to be invoked as a function call, not as a method call.\n// Otherwise CloudFlare will throw a\n// \"TypeError: Illegal invocation: function called with incorrect this reference\"\nconst { btoa, atob } = globalThis;\n\nexport function convertBase64ToUint8Array(base64String: string) {\n  const base64Url = base64String.replace(/-/g, '+').replace(/_/g, '/');\n  const latin1string = atob(base64Url);\n  return Uint8Array.from(latin1string, byte => byte.codePointAt(0)!);\n}\n\nexport function convertUint8ArrayToBase64(array: Uint8Array): string {\n  let latin1string = '';\n\n  // Note: regular for loop to support older JavaScript versions that\n  // do not support for..of on Uint8Array\n  for (let i = 0; i < array.length; i++) {\n    latin1string += String.fromCodePoint(array[i]);\n  }\n\n  return btoa(latin1string);\n}\n\nexport function convertToBase64(value: string | Uint8Array): string {\n  return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n", "import type { ImageModelV3File } from '@ai-sdk/provider';\nimport { convertUint8ArrayToBase64 } from './uint8-utils';\n\n/**\n * Convert an ImageModelV3File to a URL or data URI string.\n *\n * If the file is a URL, it returns the URL as-is.\n * If the file is base64 data, it returns a data URI with the base64 data.\n * If the file is a Uint8Array, it converts it to base64 and returns a data URI.\n */\nexport function convertImageModelFileToDataUri(file: ImageModelV3File): string {\n  if (file.type === 'url') return file.url;\n\n  return `data:${file.mediaType};base64,${\n    typeof file.data === 'string'\n      ? file.data\n      : convertUint8ArrayToBase64(file.data)\n  }`;\n}\n", "/**\n * Converts an input object to FormData for multipart/form-data requests.\n *\n * Handles the following cases:\n * - `null` or `undefined` values are skipped\n * - Arrays with a single element are appended as a single value\n * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)\n *   unless `useArrayBrackets` is set to `false`\n * - All other values are appended directly\n *\n * @param input - The input object to convert. Use a generic type for type validation.\n * @param options - Optional configuration object.\n * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.\n *   Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.\n * @returns A FormData object containing the input values.\n *\n * @example\n * ```ts\n * type MyInput = {\n *   model: string;\n *   prompt: string;\n *   images: Blob[];\n * };\n *\n * const formData = convertToFormData<MyInput>({\n *   model: 'gpt-image-1',\n *   prompt: 'A cat',\n *   images: [blob1, blob2],\n * });\n * ```\n */\nexport function convertToFormData<T extends Record<string, unknown>>(\n  input: T,\n  options: { useArrayBrackets?: boolean } = {},\n): FormData {\n  const { useArrayBrackets = true } = options;\n  const formData = new FormData();\n\n  for (const [key, value] of Object.entries(input)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      if (value.length === 1) {\n        formData.append(key, value[0] as string | Blob);\n        continue;\n      }\n\n      const arrayKey = useArrayBrackets ? `${key}[]` : key;\n      for (const item of value) {\n        formData.append(arrayKey, item as string | Blob);\n      }\n      continue;\n    }\n\n    formData.append(key, value as string | Blob);\n  }\n\n  return formData;\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_DownloadError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class DownloadError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly url: string;\n  readonly statusCode?: number;\n  readonly statusText?: string;\n\n  constructor({\n    url,\n    statusCode,\n    statusText,\n    cause,\n    message = cause == null\n      ? `Failed to download ${url}: ${statusCode} ${statusText}`\n      : `Failed to download ${url}: ${cause}`,\n  }: {\n    url: string;\n    statusCode?: number;\n    statusText?: string;\n    message?: string;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.url = url;\n    this.statusCode = statusCode;\n    this.statusText = statusText;\n  }\n\n  static isInstance(error: unknown): error is DownloadError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { DownloadError } from './download-error';\n\n/**\n * Default maximum download size: 2 GiB.\n *\n * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the\n * body internally, then creates the JS ArrayBuffer), so very large downloads\n * risk exceeding the default V8 heap limit on 64-bit systems and terminating\n * the process with an out-of-memory error.\n *\n * Setting this limit converts an unrecoverable OOM crash into a catchable\n * `DownloadError`.\n */\nexport const DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\n\n/**\n * Reads a fetch Response body with a size limit to prevent memory exhaustion.\n *\n * Checks the Content-Length header for early rejection, then reads the body\n * incrementally via ReadableStream and aborts with a DownloadError when the\n * limit is exceeded.\n *\n * @param response - The fetch Response to read.\n * @param url - The URL being downloaded (used in error messages).\n * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.\n * @returns A Uint8Array containing the response body.\n * @throws DownloadError if the response exceeds maxBytes.\n */\nexport async function readResponseWithSizeLimit({\n  response,\n  url,\n  maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE,\n}: {\n  response: Response;\n  url: string;\n  maxBytes?: number;\n}): Promise<Uint8Array> {\n  // Early rejection based on Content-Length header\n  const contentLength = response.headers.get('content-length');\n  if (contentLength != null) {\n    const length = parseInt(contentLength, 10);\n    if (!isNaN(length) && length > maxBytes) {\n      throw new DownloadError({\n        url,\n        message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`,\n      });\n    }\n  }\n\n  const body = response.body;\n\n  // Handle missing body (empty responses)\n  if (body == null) {\n    return new Uint8Array(0);\n  }\n\n  const reader = body.getReader();\n  const chunks: Uint8Array[] = [];\n  let totalBytes = 0;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n\n      if (done) {\n        break;\n      }\n\n      totalBytes += value.length;\n\n      if (totalBytes > maxBytes) {\n        throw new DownloadError({\n          url,\n          message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`,\n        });\n      }\n\n      chunks.push(value);\n    }\n  } finally {\n    try {\n      await reader.cancel();\n    } finally {\n      reader.releaseLock();\n    }\n  }\n\n  // Concatenate chunks into a single Uint8Array\n  const result = new Uint8Array(totalBytes);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.length;\n  }\n\n  return result;\n}\n", "import { DownloadError } from './download-error';\n\n/**\n * Validates that a URL is safe to download from, blocking private/internal addresses\n * to prevent SSRF attacks.\n *\n * @param url - The URL string to validate.\n * @throws DownloadError if the URL is unsafe.\n */\nexport function validateDownloadUrl(url: string): void {\n  let parsed: URL;\n  try {\n    parsed = new URL(url);\n  } catch {\n    throw new DownloadError({\n      url,\n      message: `Invalid URL: ${url}`,\n    });\n  }\n\n  // data: URLs are inline content, so they do not trigger a network fetch or SSRF risk.\n  if (parsed.protocol === 'data:') {\n    return;\n  }\n\n  // Only allow http and https network protocols\n  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n    throw new DownloadError({\n      url,\n      message: `URL scheme must be http, https, or data, got ${parsed.protocol}`,\n    });\n  }\n\n  const hostname = parsed.hostname;\n\n  // Block empty hostname\n  if (!hostname) {\n    throw new DownloadError({\n      url,\n      message: `URL must have a hostname`,\n    });\n  }\n\n  // Block localhost and .local domains\n  if (\n    hostname === 'localhost' ||\n    hostname.endsWith('.local') ||\n    hostname.endsWith('.localhost')\n  ) {\n    throw new DownloadError({\n      url,\n      message: `URL with hostname ${hostname} is not allowed`,\n    });\n  }\n\n  // Check for IPv6 addresses (enclosed in brackets in URLs)\n  if (hostname.startsWith('[') && hostname.endsWith(']')) {\n    const ipv6 = hostname.slice(1, -1);\n    if (isPrivateIPv6(ipv6)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IPv6 address ${hostname} is not allowed`,\n      });\n    }\n    return;\n  }\n\n  // Check for IPv4 addresses\n  if (isIPv4(hostname)) {\n    if (isPrivateIPv4(hostname)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IP address ${hostname} is not allowed`,\n      });\n    }\n    return;\n  }\n}\n\nfunction isIPv4(hostname: string): boolean {\n  const parts = hostname.split('.');\n  if (parts.length !== 4) return false;\n  return parts.every(part => {\n    const num = Number(part);\n    return (\n      Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part\n    );\n  });\n}\n\nfunction isPrivateIPv4(ip: string): boolean {\n  const parts = ip.split('.').map(Number);\n  const [a, b] = parts;\n\n  // 0.0.0.0/8\n  if (a === 0) return true;\n  // 10.0.0.0/8\n  if (a === 10) return true;\n  // 127.0.0.0/8\n  if (a === 127) return true;\n  // 169.254.0.0/16\n  if (a === 169 && b === 254) return true;\n  // 172.16.0.0/12\n  if (a === 172 && b >= 16 && b <= 31) return true;\n  // 192.168.0.0/16\n  if (a === 192 && b === 168) return true;\n\n  return false;\n}\n\nfunction isPrivateIPv6(ip: string): boolean {\n  const normalized = ip.toLowerCase();\n\n  // ::1 (loopback)\n  if (normalized === '::1') return true;\n  // :: (unspecified)\n  if (normalized === '::') return true;\n\n  // Check for IPv4-mapped addresses (::ffff:x.x.x.x or ::ffff:HHHH:HHHH)\n  if (normalized.startsWith('::ffff:')) {\n    const mappedPart = normalized.slice(7);\n    // Dotted-decimal form: ::ffff:127.0.0.1\n    if (isIPv4(mappedPart)) {\n      return isPrivateIPv4(mappedPart);\n    }\n    // Hex form: ::ffff:7f00:1 (URL parser normalizes to this)\n    const hexParts = mappedPart.split(':');\n    if (hexParts.length === 2) {\n      const high = parseInt(hexParts[0], 16);\n      const low = parseInt(hexParts[1], 16);\n      if (!isNaN(high) && !isNaN(low)) {\n        const a = (high >> 8) & 0xff;\n        const b = high & 0xff;\n        const c = (low >> 8) & 0xff;\n        const d = low & 0xff;\n        return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n      }\n    }\n  }\n\n  // fc00::/7 (unique local addresses - fc00:: and fd00::)\n  if (normalized.startsWith('fc') || normalized.startsWith('fd')) return true;\n\n  // fe80::/10 (link-local)\n  if (normalized.startsWith('fe80')) return true;\n\n  return false;\n}\n", "import { DownloadError } from './download-error';\nimport {\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n} from './read-response-with-size-limit';\nimport { validateDownloadUrl } from './validate-download-url';\n\n/**\n * Download a file from a URL and return it as a Blob.\n *\n * @param url - The URL to download from.\n * @param options - Optional settings for the download.\n * @param options.maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n * @param options.abortSignal - An optional abort signal to cancel the download.\n * @returns A Promise that resolves to the downloaded Blob.\n *\n * @throws DownloadError if the download fails or exceeds maxBytes.\n */\nexport async function downloadBlob(\n  url: string,\n  options?: { maxBytes?: number; abortSignal?: AbortSignal },\n): Promise<Blob> {\n  validateDownloadUrl(url);\n  try {\n    const response = await fetch(url, {\n      signal: options?.abortSignal,\n    });\n\n    // Validate final URL after redirects to prevent SSRF via open redirect\n    if (response.redirected) {\n      validateDownloadUrl(response.url);\n    }\n\n    if (!response.ok) {\n      throw new DownloadError({\n        url,\n        statusCode: response.status,\n        statusText: response.statusText,\n      });\n    }\n\n    const data = await readResponseWithSizeLimit({\n      response,\n      url,\n      maxBytes: options?.maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE,\n    });\n\n    const contentType = response.headers.get('content-type') ?? undefined;\n    return new Blob([data], contentType ? { type: contentType } : undefined);\n  } catch (error) {\n    if (DownloadError.isInstance(error)) {\n      throw error;\n    }\n\n    throw new DownloadError({ url, cause: error });\n  }\n}\n", "import { InvalidArgumentError } from '@ai-sdk/provider';\n\n/**\n * Creates an ID generator.\n * The total length of the ID is the sum of the prefix, separator, and random part length.\n * Not cryptographically secure.\n *\n * @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.\n * @param prefix - The prefix of the ID to generate. Optional.\n * @param separator - The separator between the prefix and the random part of the ID. Default: '-'.\n * @param size - The size of the random part of the ID to generate. Default: 16.\n */\nexport const createIdGenerator = ({\n  prefix,\n  size = 16,\n  alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n  separator = '-',\n}: {\n  prefix?: string;\n  separator?: string;\n  size?: number;\n  alphabet?: string;\n} = {}): IdGenerator => {\n  const generator = () => {\n    const alphabetLength = alphabet.length;\n    const chars = new Array(size);\n    for (let i = 0; i < size; i++) {\n      chars[i] = alphabet[(Math.random() * alphabetLength) | 0];\n    }\n    return chars.join('');\n  };\n\n  if (prefix == null) {\n    return generator;\n  }\n\n  // check that the prefix is not part of the alphabet (otherwise prefix checking can fail randomly)\n  if (alphabet.includes(separator)) {\n    throw new InvalidArgumentError({\n      argument: 'separator',\n      message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`,\n    });\n  }\n\n  return () => `${prefix}${separator}${generator()}`;\n};\n\n/**\n * A function that generates an ID.\n */\nexport type IdGenerator = () => string;\n\n/**\n * Generates a 16-character random string to use for IDs.\n * Not cryptographically secure.\n */\nexport const generateId = createIdGenerator();\n", "export function getErrorMessage(error: unknown | undefined) {\n  if (error == null) {\n    return 'unknown error';\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return error.message;\n  }\n\n  return JSON.stringify(error);\n}\n", "import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport type { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport type { ResponseHandler } from './response-handler';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\nimport { VERSION } from './version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const getFromApi = async <T>({\n  url,\n  headers = {},\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  try {\n    const response = await fetch(url, {\n      method: 'GET',\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      signal: abortSignal,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: {},\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: {},\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: {},\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: {},\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: {} });\n  }\n};\n", "import { APICallError } from '@ai-sdk/provider';\nimport { isAbortError } from './is-abort-error';\n\nconst FETCH_FAILED_ERROR_MESSAGES = ['fetch failed', 'failed to fetch'];\n\nconst BUN_ERROR_CODES = [\n  'ConnectionRefused',\n  'ConnectionClosed',\n  'FailedToOpenSocket',\n  'ECONNRESET',\n  'ECONNREFUSED',\n  'ETIMEDOUT',\n  'EPIPE',\n];\n\nfunction isBunNetworkError(error: unknown): error is Error & { code?: string } {\n  if (!(error instanceof Error)) {\n    return false;\n  }\n\n  const code = (error as any).code;\n  if (typeof code === 'string' && BUN_ERROR_CODES.includes(code)) {\n    return true;\n  }\n\n  return false;\n}\n\nexport function handleFetchError({\n  error,\n  url,\n  requestBodyValues,\n}: {\n  error: unknown;\n  url: string;\n  requestBodyValues: unknown;\n}) {\n  if (isAbortError(error)) {\n    return error;\n  }\n\n  // unwrap original error when fetch failed (for easier debugging):\n  if (\n    error instanceof TypeError &&\n    FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())\n  ) {\n    const cause = (error as any).cause;\n\n    if (cause != null) {\n      // Failed to connect to server:\n      return new APICallError({\n        message: `Cannot connect to API: ${cause.message}`,\n        cause,\n        url,\n        requestBodyValues,\n        isRetryable: true, // retry when network error\n      });\n    }\n  }\n\n  if (isBunNetworkError(error)) {\n    return new APICallError({\n      message: `Cannot connect to API: ${error.message}`,\n      cause: error,\n      url,\n      requestBodyValues,\n      isRetryable: true,\n    });\n  }\n\n  return error;\n}\n", "export function isAbortError(error: unknown): error is Error {\n  return (\n    (error instanceof Error || error instanceof DOMException) &&\n    (error.name === 'AbortError' ||\n      error.name === 'ResponseAborted' || // Next.js\n      error.name === 'TimeoutError')\n  );\n}\n", "export function getRuntimeEnvironmentUserAgent(\n  globalThisAny: any = globalThis as any,\n): string {\n  // Browsers\n  if (globalThisAny.window) {\n    return `runtime/browser`;\n  }\n\n  // Cloudflare Workers / Deno / Bun / Node.js >= 21.1\n  if (globalThisAny.navigator?.userAgent) {\n    return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n  }\n\n  // Nodes.js < 21.1\n  if (globalThisAny.process?.versions?.node) {\n    return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n  }\n\n  if (globalThisAny.EdgeRuntime) {\n    return `runtime/vercel-edge`;\n  }\n\n  return 'runtime/unknown';\n}\n", "/**\n * Normalizes different header inputs into a plain record with lower-case keys.\n * Entries with `undefined` or `null` values are removed.\n *\n * @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.\n * @returns A record containing the normalized header entries.\n */\nexport function normalizeHeaders(\n  headers:\n    | HeadersInit\n    | Record<string, string | undefined>\n    | Array<[string, string | undefined]>\n    | undefined,\n): Record<string, string> {\n  if (headers == null) {\n    return {};\n  }\n\n  const normalized: Record<string, string> = {};\n\n  if (headers instanceof Headers) {\n    headers.forEach((value, key) => {\n      normalized[key.toLowerCase()] = value;\n    });\n  } else {\n    if (!Array.isArray(headers)) {\n      headers = Object.entries(headers);\n    }\n\n    for (const [key, value] of headers) {\n      if (value != null) {\n        normalized[key.toLowerCase()] = value;\n      }\n    }\n  }\n\n  return normalized;\n}\n", "import { normalizeHeaders } from './normalize-headers';\n\n/**\n * Appends suffix parts to the `user-agent` header.\n * If a `user-agent` header already exists, the suffix parts are appended to it.\n * If no `user-agent` header exists, a new one is created with the suffix parts.\n * Automatically removes undefined entries from the headers.\n *\n * @param headers - The original headers.\n * @param userAgentSuffixParts - The parts to append to the `user-agent` header.\n * @returns The new headers with the `user-agent` header set or updated.\n */\nexport function withUserAgentSuffix(\n  headers: HeadersInit | Record<string, string | undefined> | undefined,\n  ...userAgentSuffixParts: string[]\n): Record<string, string> {\n  const normalizedHeaders = new Headers(normalizeHeaders(headers));\n\n  const currentUserAgentHeader = normalizedHeaders.get('user-agent') || '';\n\n  normalizedHeaders.set(\n    'user-agent',\n    [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(' '),\n  );\n\n  return Object.fromEntries(normalizedHeaders.entries());\n}\n", "// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n", "import type {\n  JSONSchema7,\n  LanguageModelV3Message,\n  LanguageModelV3Prompt,\n} from '@ai-sdk/provider';\n\nconst DEFAULT_SCHEMA_PREFIX = 'JSON schema:';\nconst DEFAULT_SCHEMA_SUFFIX =\n  'You MUST answer with a JSON object that matches the JSON schema above.';\nconst DEFAULT_GENERIC_SUFFIX = 'You MUST answer with JSON.';\n\nexport function injectJsonInstruction({\n  prompt,\n  schema,\n  schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : undefined,\n  schemaSuffix = schema != null\n    ? DEFAULT_SCHEMA_SUFFIX\n    : DEFAULT_GENERIC_SUFFIX,\n}: {\n  prompt?: string;\n  schema?: JSONSchema7;\n  schemaPrefix?: string;\n  schemaSuffix?: string;\n}): string {\n  return [\n    prompt != null && prompt.length > 0 ? prompt : undefined,\n    prompt != null && prompt.length > 0 ? '' : undefined, // add a newline if prompt is not null\n    schemaPrefix,\n    schema != null ? JSON.stringify(schema) : undefined,\n    schemaSuffix,\n  ]\n    .filter(line => line != null)\n    .join('\\n');\n}\n\nexport function injectJsonInstructionIntoMessages({\n  messages,\n  schema,\n  schemaPrefix,\n  schemaSuffix,\n}: {\n  messages: LanguageModelV3Prompt;\n  schema?: JSONSchema7;\n  schemaPrefix?: string;\n  schemaSuffix?: string;\n}): LanguageModelV3Prompt {\n  const systemMessage: LanguageModelV3Message =\n    messages[0]?.role === 'system'\n      ? { ...messages[0] }\n      : { role: 'system', content: '' };\n\n  systemMessage.content = injectJsonInstruction({\n    prompt: systemMessage.content,\n    schema,\n    schemaPrefix,\n    schemaSuffix,\n  });\n\n  return [\n    systemMessage,\n    ...(messages[0]?.role === 'system' ? messages.slice(1) : messages),\n  ];\n}\n", "/**\n * Type guard that checks whether a value is not `null` or `undefined`.\n *\n * @template T - The type of the value to check.\n * @param value - The value to check.\n * @returns `true` if the value is neither `null` nor `undefined`, otherwise `false`.\n */\nexport function isNonNullable<T>(\n  value: T | undefined | null,\n): value is NonNullable<T> {\n  return value != null;\n}\n", "/**\n * Checks if the given URL is supported natively by the model.\n *\n * @param mediaType - The media type of the URL. Case-sensitive.\n * @param url - The URL to check.\n * @param supportedUrls - A record where keys are case-sensitive media types (or '*')\n *                        and values are arrays of RegExp patterns for URLs.\n *\n * @returns `true` if the URL matches a pattern under the specific media type\n *          or the wildcard '*', `false` otherwise.\n */\nexport function isUrlSupported({\n  mediaType,\n  url,\n  supportedUrls,\n}: {\n  mediaType: string;\n  url: string;\n  supportedUrls: Record<string, RegExp[]>;\n}): boolean {\n  // standardize media type and url to lower case\n  url = url.toLowerCase();\n  mediaType = mediaType.toLowerCase();\n\n  return (\n    Object.entries(supportedUrls)\n      // standardize supported url map into lowercase prefixes:\n      .map(([key, value]) => {\n        const mediaType = key.toLowerCase();\n        return mediaType === '*' || mediaType === '*/*'\n          ? { mediaTypePrefix: '', regexes: value }\n          : { mediaTypePrefix: mediaType.replace(/\\*/, ''), regexes: value };\n      })\n      // gather all regexp pattern from matched media type prefixes:\n      .filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix))\n      .flatMap(({ regexes }) => regexes)\n      // check if any pattern matches the url:\n      .some(pattern => pattern.test(url))\n  );\n}\n", "import { LoadAPIKeyError } from '@ai-sdk/provider';\n\nexport function loadApiKey({\n  apiKey,\n  environmentVariableName,\n  apiKeyParameterName = 'apiKey',\n  description,\n}: {\n  apiKey: string | undefined;\n  environmentVariableName: string;\n  apiKeyParameterName?: string;\n  description: string;\n}): string {\n  if (typeof apiKey === 'string') {\n    return apiKey;\n  }\n\n  if (apiKey != null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string.`,\n    });\n  }\n\n  if (typeof process === 'undefined') {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.`,\n    });\n  }\n\n  apiKey = process.env[environmentVariableName];\n\n  if (apiKey == null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`,\n    });\n  }\n\n  if (typeof apiKey !== 'string') {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`,\n    });\n  }\n\n  return apiKey;\n}\n", "/**\n * Loads an optional `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @returns The setting value.\n */\nexport function loadOptionalSetting({\n  settingValue,\n  environmentVariableName,\n}: {\n  settingValue: string | undefined;\n  environmentVariableName: string;\n}): string | undefined {\n  if (typeof settingValue === 'string') {\n    return settingValue;\n  }\n\n  if (settingValue != null || typeof process === 'undefined') {\n    return undefined;\n  }\n\n  settingValue = process.env[environmentVariableName];\n\n  if (settingValue == null || typeof settingValue !== 'string') {\n    return undefined;\n  }\n\n  return settingValue;\n}\n", "import { LoadSettingError } from '@ai-sdk/provider';\n\n/**\n * Loads a `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @param settingName - The setting name.\n * @param description - The description of the setting.\n * @returns The setting value.\n */\nexport function loadSetting({\n  settingValue,\n  environmentVariableName,\n  settingName,\n  description,\n}: {\n  settingValue: string | undefined;\n  environmentVariableName: string;\n  settingName: string;\n  description: string;\n}): string {\n  if (typeof settingValue === 'string') {\n    return settingValue;\n  }\n\n  if (settingValue != null) {\n    throw new LoadSettingError({\n      message: `${description} setting must be a string.`,\n    });\n  }\n\n  if (typeof process === 'undefined') {\n    throw new LoadSettingError({\n      message:\n        `${description} setting is missing. ` +\n        `Pass it using the '${settingName}' parameter. ` +\n        `Environment variables are not supported in this environment.`,\n    });\n  }\n\n  settingValue = process.env[environmentVariableName];\n\n  if (settingValue == null) {\n    throw new LoadSettingError({\n      message:\n        `${description} setting is missing. ` +\n        `Pass it using the '${settingName}' parameter ` +\n        `or the ${environmentVariableName} environment variable.`,\n    });\n  }\n\n  if (typeof settingValue !== 'string') {\n    throw new LoadSettingError({\n      message:\n        `${description} setting must be a string. ` +\n        `The value of the ${environmentVariableName} environment variable is not a string.`,\n    });\n  }\n\n  return settingValue;\n}\n", "/**\n * Maps a media type to its corresponding file extension.\n * It was originally introduced to set a filename for audio file uploads\n * in https://github.com/vercel/ai/pull/8159.\n *\n * @param mediaType The media type to map.\n * @returns The corresponding file extension\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n */\nexport function mediaTypeToExtension(mediaType: string) {\n  const [_type, subtype = ''] = mediaType.toLowerCase().split('/');\n\n  return (\n    {\n      mpeg: 'mp3',\n      'x-wav': 'wav',\n      opus: 'ogg',\n      mp4: 'm4a',\n      'x-m4a': 'm4a',\n    }[subtype] ?? subtype\n  );\n}\n", "import {\n  JSONParseError,\n  TypeValidationError,\n  type JSONValue,\n} from '@ai-sdk/provider';\nimport { secureJsonParse } from './secure-json-parse';\nimport { safeValidateTypes, validateTypes } from './validate-types';\nimport type { FlexibleSchema } from './schema';\n\n/**\n * Parses a JSON string into an unknown object.\n *\n * @param text - The JSON string to parse.\n * @returns {JSONValue} - The parsed JSON object.\n */\nexport async function parseJSON(options: {\n  text: string;\n  schema?: undefined;\n}): Promise<JSONValue>;\n/**\n * Parses a JSON string into a strongly-typed object using the provided schema.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns {Promise<T>} - The parsed object.\n */\nexport async function parseJSON<T>(options: {\n  text: string;\n  schema: FlexibleSchema<T>;\n}): Promise<T>;\nexport async function parseJSON<T>({\n  text,\n  schema,\n}: {\n  text: string;\n  schema?: FlexibleSchema<T>;\n}): Promise<T> {\n  try {\n    const value = secureJsonParse(text);\n\n    if (schema == null) {\n      return value;\n    }\n\n    return validateTypes<T>({ value, schema });\n  } catch (error) {\n    if (\n      JSONParseError.isInstance(error) ||\n      TypeValidationError.isInstance(error)\n    ) {\n      throw error;\n    }\n\n    throw new JSONParseError({ text, cause: error });\n  }\n}\n\nexport type ParseResult<T> =\n  | { success: true; value: T; rawValue: unknown }\n  | {\n      success: false;\n      error: JSONParseError | TypeValidationError;\n      rawValue: unknown;\n    };\n\n/**\n * Safely parses a JSON string and returns the result as an object of type `unknown`.\n *\n * @param text - The JSON string to parse.\n * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.\n */\nexport async function safeParseJSON(options: {\n  text: string;\n  schema?: undefined;\n}): Promise<ParseResult<JSONValue>>;\n/**\n * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeParseJSON<T>(options: {\n  text: string;\n  schema: FlexibleSchema<T>;\n}): Promise<ParseResult<T>>;\nexport async function safeParseJSON<T>({\n  text,\n  schema,\n}: {\n  text: string;\n  schema?: FlexibleSchema<T>;\n}): Promise<ParseResult<T>> {\n  try {\n    const value = secureJsonParse(text);\n\n    if (schema == null) {\n      return { success: true, value: value as T, rawValue: value };\n    }\n\n    return await safeValidateTypes<T>({ value, schema });\n  } catch (error) {\n    return {\n      success: false,\n      error: JSONParseError.isInstance(error)\n        ? error\n        : new JSONParseError({ text, cause: error }),\n      rawValue: undefined,\n    };\n  }\n}\n\nexport function isParsableJson(input: string): boolean {\n  try {\n    secureJsonParse(input);\n    return true;\n  } catch {\n    return false;\n  }\n}\n", "// Licensed under BSD-3-Clause (this file only)\n// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js\n//\n// Copyright (c) Vercel, Inc. (https://vercel.com)\n// Copyright (c) 2019 The Fastify Team\n// Copyright (c) 2019, Sideway Inc, and project contributors\n// All rights reserved.\n//\n// The complete list of contributors can be found at:\n// - https://github.com/hapijs/bourne/graphs/contributors\n// - https://github.com/fastify/secure-json-parse/graphs/contributors\n// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.ts\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nconst suspectProtoRx =\n  /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nconst suspectConstructorRx =\n  /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\n\nfunction _parse(text: string) {\n  // Parse normally\n  const obj = JSON.parse(text);\n\n  // Ignore null and non-objects\n  if (obj === null || typeof obj !== 'object') {\n    return obj;\n  }\n\n  if (\n    suspectProtoRx.test(text) === false &&\n    suspectConstructorRx.test(text) === false\n  ) {\n    return obj;\n  }\n\n  // Scan result for proto keys\n  return filter(obj);\n}\n\nfunction filter(obj: any) {\n  let next = [obj];\n\n  while (next.length) {\n    const nodes = next;\n    next = [];\n\n    for (const node of nodes) {\n      if (Object.prototype.hasOwnProperty.call(node, '__proto__')) {\n        throw new SyntaxError('Object contains forbidden prototype property');\n      }\n\n      if (\n        Object.prototype.hasOwnProperty.call(node, 'constructor') &&\n        node.constructor !== null &&\n        typeof node.constructor === 'object' &&\n        Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')\n      ) {\n        throw new SyntaxError('Object contains forbidden prototype property');\n      }\n\n      for (const key in node) {\n        const value = node[key];\n        if (value && typeof value === 'object') {\n          next.push(value);\n        }\n      }\n    }\n  }\n  return obj;\n}\n\nexport function secureJsonParse(text: string) {\n  const { stackTraceLimit } = Error;\n  try {\n    // Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90\n    Error.stackTraceLimit = 0;\n  } catch (e) {\n    // Fallback in case Error is immutable (v8 readonly)\n    return _parse(text);\n  }\n\n  try {\n    return _parse(text);\n  } finally {\n    Error.stackTraceLimit = stackTraceLimit;\n  }\n}\n", "import {\n  TypeValidationError,\n  type TypeValidationContext,\n} from '@ai-sdk/provider';\nimport { asSchema, type FlexibleSchema } from './schema';\n\n/**\n * Validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @param {TypeValidationContext} options.context - Optional context about what is being validated.\n * @returns {Promise<T>} - The typed object.\n */\nexport async function validateTypes<OBJECT>({\n  value,\n  schema,\n  context,\n}: {\n  value: unknown;\n  schema: FlexibleSchema<OBJECT>;\n  context?: TypeValidationContext;\n}): Promise<OBJECT> {\n  const result = await safeValidateTypes({ value, schema, context });\n\n  if (!result.success) {\n    throw TypeValidationError.wrap({ value, cause: result.error, context });\n  }\n\n  return result.value;\n}\n\n/**\n * Safely validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The JSON object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @param {TypeValidationContext} options.context - Optional context about what is being validated.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeValidateTypes<OBJECT>({\n  value,\n  schema,\n  context,\n}: {\n  value: unknown;\n  schema: FlexibleSchema<OBJECT>;\n  context?: TypeValidationContext;\n}): Promise<\n  | {\n      success: true;\n      value: OBJECT;\n      rawValue: unknown;\n    }\n  | {\n      success: false;\n      error: TypeValidationError;\n      rawValue: unknown;\n    }\n> {\n  const actualSchema = asSchema(schema);\n\n  try {\n    if (actualSchema.validate == null) {\n      return { success: true, value: value as OBJECT, rawValue: value };\n    }\n\n    const result = await actualSchema.validate(value);\n\n    if (result.success) {\n      return { success: true, value: result.value, rawValue: value };\n    }\n\n    return {\n      success: false,\n      error: TypeValidationError.wrap({ value, cause: result.error, context }),\n      rawValue: value,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: TypeValidationError.wrap({ value, cause: error, context }),\n      rawValue: value,\n    };\n  }\n}\n", "import { TypeValidationError, type JSONSchema7 } from '@ai-sdk/provider';\nimport type {\n  StandardSchemaV1,\n  StandardJSONSchemaV1,\n} from '@standard-schema/spec';\nimport type * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport { addAdditionalPropertiesToJsonSchema } from './add-additional-properties-to-json-schema';\nimport { zod3ToJsonSchema } from './to-json-schema/zod3-to-json-schema';\n\n/**\n * Used to mark schemas so we can support both Zod and custom schemas.\n */\nconst schemaSymbol = Symbol.for('vercel.ai.schema');\n\nexport type ValidationResult<OBJECT> =\n  | { success: true; value: OBJECT }\n  | { success: false; error: Error };\n\nexport type Schema<OBJECT = unknown> = {\n  /**\n   * Used to mark schemas so we can support both Zod and custom schemas.\n   */\n  [schemaSymbol]: true;\n\n  /**\n   * Schema type for inference.\n   */\n  _type: OBJECT;\n\n  /**\n   * Optional. Validates that the structure of a value matches this schema,\n   * and returns a typed version of the value if it does.\n   */\n  readonly validate?: (\n    value: unknown,\n  ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n\n  /**\n   * The JSON Schema for the schema. It is passed to the providers.\n   */\n  readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;\n};\n\n/**\n * Creates a schema with deferred creation.\n * This is important to reduce the startup time of the library\n * and to avoid initializing unused validators.\n *\n * @param createValidator A function that creates a schema.\n * @returns A function that returns a schema.\n */\nexport function lazySchema<SCHEMA>(\n  createSchema: () => Schema<SCHEMA>,\n): LazySchema<SCHEMA> {\n  // cache the validator to avoid initializing it multiple times\n  let schema: Schema<SCHEMA> | undefined;\n  return () => {\n    if (schema == null) {\n      schema = createSchema();\n    }\n    return schema;\n  };\n}\n\nexport type LazySchema<SCHEMA> = () => Schema<SCHEMA>;\n\nexport type ZodSchema<SCHEMA = any> =\n  | z3.Schema<SCHEMA, z3.ZodTypeDef, any>\n  | z4.core.$ZodType<SCHEMA, any>;\n\nexport type StandardSchema<SCHEMA = any> = StandardSchemaV1<unknown, SCHEMA> &\n  StandardJSONSchemaV1<unknown, SCHEMA>;\n\nexport type FlexibleSchema<SCHEMA = any> =\n  | Schema<SCHEMA>\n  | LazySchema<SCHEMA>\n  | ZodSchema<SCHEMA>\n  | StandardSchema<SCHEMA>;\n\nexport type InferSchema<SCHEMA> =\n  SCHEMA extends ZodSchema<infer T>\n    ? T\n    : SCHEMA extends StandardSchema<infer T>\n      ? T\n      : SCHEMA extends LazySchema<infer T>\n        ? T\n        : SCHEMA extends Schema<infer T>\n          ? T\n          : never;\n\n/**\n * Create a schema using a JSON Schema.\n *\n * @param jsonSchema The JSON Schema for the schema.\n * @param options.validate Optional. A validation function for the schema.\n */\nexport function jsonSchema<OBJECT = unknown>(\n  jsonSchema:\n    | JSONSchema7\n    | PromiseLike<JSONSchema7>\n    | (() => JSONSchema7 | PromiseLike<JSONSchema7>),\n  {\n    validate,\n  }: {\n    validate?: (\n      value: unknown,\n    ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n  } = {},\n): Schema<OBJECT> {\n  return {\n    [schemaSymbol]: true,\n    _type: undefined as OBJECT, // should never be used directly\n    get jsonSchema() {\n      if (typeof jsonSchema === 'function') {\n        jsonSchema = jsonSchema(); // cache the function results\n      }\n      return jsonSchema;\n    },\n    validate,\n  };\n}\n\nfunction isSchema(value: unknown): value is Schema {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    schemaSymbol in value &&\n    value[schemaSymbol] === true &&\n    'jsonSchema' in value &&\n    'validate' in value\n  );\n}\n\nexport function asSchema<OBJECT>(\n  schema: FlexibleSchema<OBJECT> | undefined,\n): Schema<OBJECT> {\n  return schema == null\n    ? jsonSchema({ properties: {}, additionalProperties: false })\n    : isSchema(schema)\n      ? schema\n      : '~standard' in schema\n        ? schema['~standard'].vendor === 'zod'\n          ? zodSchema(schema as ZodSchema<OBJECT>)\n          : standardSchema(schema as StandardSchema<OBJECT>)\n        : schema();\n}\n\nfunction standardSchema<OBJECT>(\n  standardSchema: StandardSchema<OBJECT>,\n): Schema<OBJECT> {\n  return jsonSchema(\n    () =>\n      addAdditionalPropertiesToJsonSchema(\n        standardSchema['~standard'].jsonSchema.input({\n          target: 'draft-07',\n        }) as JSONSchema7,\n      ),\n    {\n      validate: async value => {\n        const result = await standardSchema['~standard'].validate(value);\n        return 'value' in result\n          ? { success: true, value: result.value }\n          : {\n              success: false,\n              error: new TypeValidationError({\n                value,\n                cause: result.issues,\n              }),\n            };\n      },\n    },\n  );\n}\n\nexport function zod3Schema<OBJECT>(\n  zodSchema: z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  // default to no references (to support openapi conversion for google)\n  const useReferences = options?.useReferences ?? false;\n\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () =>\n      zod3ToJsonSchema(zodSchema, {\n        $refStrategy: useReferences ? 'root' : 'none',\n      }) as JSONSchema7,\n    {\n      validate: async value => {\n        const result = await zodSchema.safeParseAsync(value);\n        return result.success\n          ? { success: true, value: result.data }\n          : { success: false, error: result.error };\n      },\n    },\n  );\n}\n\nexport function zod4Schema<OBJECT>(\n  zodSchema: z4.core.$ZodType<OBJECT, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  // default to no references (to support openapi conversion for google)\n  const useReferences = options?.useReferences ?? false;\n\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () =>\n      addAdditionalPropertiesToJsonSchema(\n        z4.toJSONSchema(zodSchema, {\n          target: 'draft-7',\n          io: 'input',\n          reused: useReferences ? 'ref' : 'inline',\n        }) as JSONSchema7,\n      ),\n    {\n      validate: async value => {\n        const result = await z4.safeParseAsync(zodSchema, value);\n        return result.success\n          ? { success: true, value: result.data }\n          : { success: false, error: result.error };\n      },\n    },\n  );\n}\n\nexport function isZod4Schema(\n  zodSchema: z4.core.$ZodType<any, any> | z3.Schema<any, z3.ZodTypeDef, any>,\n): zodSchema is z4.core.$ZodType<any, any> {\n  // https://zod.dev/library-authors?id=how-to-support-zod-3-and-zod-4-simultaneously\n  return '_zod' in zodSchema;\n}\n\nexport function zodSchema<OBJECT>(\n  zodSchema:\n    | z4.core.$ZodType<OBJECT, any>\n    | z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  if (isZod4Schema(zodSchema)) {\n    return zod4Schema(zodSchema, options);\n  } else {\n    return zod3Schema(zodSchema, options);\n  }\n}\n", "import type { JSONSchema7, JSONSchema7Definition } from '@ai-sdk/provider';\n\n/**\n * Recursively adds additionalProperties: false to the JSON schema. This is necessary because some providers (e.g. OpenAI) do not support additionalProperties: true.\n */\nexport function addAdditionalPropertiesToJsonSchema(\n  jsonSchema: JSONSchema7,\n): JSONSchema7 {\n  if (\n    jsonSchema.type === 'object' ||\n    (Array.isArray(jsonSchema.type) && jsonSchema.type.includes('object'))\n  ) {\n    jsonSchema.additionalProperties = false;\n    const { properties } = jsonSchema;\n    if (properties != null) {\n      for (const key of Object.keys(properties)) {\n        properties[key] = visit(properties[key]);\n      }\n    }\n  }\n\n  if (jsonSchema.items != null) {\n    jsonSchema.items = Array.isArray(jsonSchema.items)\n      ? jsonSchema.items.map(visit)\n      : visit(jsonSchema.items);\n  }\n\n  if (jsonSchema.anyOf != null) {\n    jsonSchema.anyOf = jsonSchema.anyOf.map(visit);\n  }\n\n  if (jsonSchema.allOf != null) {\n    jsonSchema.allOf = jsonSchema.allOf.map(visit);\n  }\n\n  if (jsonSchema.oneOf != null) {\n    jsonSchema.oneOf = jsonSchema.oneOf.map(visit);\n  }\n\n  const { definitions } = jsonSchema;\n  if (definitions != null) {\n    for (const key of Object.keys(definitions)) {\n      definitions[key] = visit(definitions[key]);\n    }\n  }\n\n  return jsonSchema;\n}\n\nfunction visit(def: JSONSchema7Definition): JSONSchema7Definition {\n  if (typeof def === 'boolean') return def;\n  return addAdditionalPropertiesToJsonSchema(def);\n}\n", "import type { ZodSchema, ZodTypeDef } from 'zod/v3';\nimport type { Refs, Seen } from './refs';\nimport type { JsonSchema7Type } from './parse-types';\n\nexport type DateStrategy =\n  | 'format:date-time'\n  | 'format:date'\n  | 'string'\n  | 'integer';\n\nexport const ignoreOverride = Symbol(\n  'Let zodToJsonSchema decide on which parser to use',\n);\n\nexport type OverrideCallback = (\n  def: ZodTypeDef,\n  refs: Refs,\n  seen: Seen | undefined,\n  forceResolution?: boolean,\n) => JsonSchema7Type | undefined | typeof ignoreOverride;\n\nexport type PostProcessCallback = (\n  jsonSchema: JsonSchema7Type | undefined,\n  def: ZodTypeDef,\n  refs: Refs,\n) => JsonSchema7Type | undefined;\n\nexport const jsonDescription: PostProcessCallback = (jsonSchema, def) => {\n  if (def.description) {\n    try {\n      return {\n        ...jsonSchema,\n        ...JSON.parse(def.description),\n      };\n    } catch {}\n  }\n\n  return jsonSchema;\n};\n\nexport type Options = {\n  name: string | undefined;\n  $refStrategy: 'root' | 'relative' | 'none' | 'seen';\n  basePath: string[];\n  effectStrategy: 'input' | 'any';\n  pipeStrategy: 'input' | 'output' | 'all';\n  dateStrategy: DateStrategy | DateStrategy[];\n  mapStrategy: 'entries' | 'record';\n  removeAdditionalStrategy: 'passthrough' | 'strict';\n  allowedAdditionalProperties: true | undefined;\n  rejectedAdditionalProperties: false | undefined;\n  strictUnions: boolean;\n  definitionPath: string;\n  definitions: Record<string, ZodSchema>;\n  errorMessages: boolean;\n  patternStrategy: 'escape' | 'preserve';\n  applyRegexFlags: boolean;\n  emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod';\n  base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod';\n  nameStrategy: 'ref' | 'title';\n  override?: OverrideCallback;\n  postProcess?: PostProcessCallback;\n};\n\nexport const defaultOptions: Options = {\n  name: undefined,\n  $refStrategy: 'root',\n  basePath: ['#'],\n  effectStrategy: 'input',\n  pipeStrategy: 'all',\n  dateStrategy: 'format:date-time',\n  mapStrategy: 'entries',\n  removeAdditionalStrategy: 'passthrough',\n  allowedAdditionalProperties: true,\n  rejectedAdditionalProperties: false,\n  definitionPath: 'definitions',\n  strictUnions: false,\n  definitions: {},\n  errorMessages: false,\n  patternStrategy: 'escape',\n  applyRegexFlags: false,\n  emailStrategy: 'format:email',\n  base64Strategy: 'contentEncoding:base64',\n  nameStrategy: 'ref',\n};\n\nexport const getDefaultOptions = (\n  options: Partial<Options> | string | undefined,\n) =>\n  (typeof options === 'string'\n    ? {\n        ...defaultOptions,\n        name: options,\n      }\n    : {\n        ...defaultOptions,\n        ...options,\n      }) as Options;\n", "import { ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseAnyDef } from './parsers/any';\nimport { parseArrayDef } from './parsers/array';\nimport { parseBigintDef } from './parsers/bigint';\nimport { parseBooleanDef } from './parsers/boolean';\nimport { parseBrandedDef } from './parsers/branded';\nimport { parseCatchDef } from './parsers/catch';\nimport { parseDateDef } from './parsers/date';\nimport { parseDefaultDef } from './parsers/default';\nimport { parseEffectsDef } from './parsers/effects';\nimport { parseEnumDef } from './parsers/enum';\nimport { parseIntersectionDef } from './parsers/intersection';\nimport { parseLiteralDef } from './parsers/literal';\nimport { parseMapDef } from './parsers/map';\nimport { parseNativeEnumDef } from './parsers/native-enum';\nimport { parseNeverDef } from './parsers/never';\nimport { parseNullDef } from './parsers/null';\nimport { parseNullableDef } from './parsers/nullable';\nimport { parseNumberDef } from './parsers/number';\nimport { parseObjectDef } from './parsers/object';\nimport { parseOptionalDef } from './parsers/optional';\nimport { parsePipelineDef } from './parsers/pipeline';\nimport { parsePromiseDef } from './parsers/promise';\nimport { parseRecordDef } from './parsers/record';\nimport { parseSetDef } from './parsers/set';\nimport { parseStringDef } from './parsers/string';\nimport { parseTupleDef } from './parsers/tuple';\nimport { parseUndefinedDef } from './parsers/undefined';\nimport { parseUnionDef } from './parsers/union';\nimport { parseUnknownDef } from './parsers/unknown';\nimport type { Refs } from './refs';\nimport { parseReadonlyDef } from './parsers/readonly';\nimport type { JsonSchema7Type } from './parse-types';\n\nexport type InnerDefGetter = () => any;\n\nexport const selectParser = (\n  def: any,\n  typeName: ZodFirstPartyTypeKind,\n  refs: Refs,\n): JsonSchema7Type | undefined | InnerDefGetter => {\n  switch (typeName) {\n    case ZodFirstPartyTypeKind.ZodString:\n      return parseStringDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodNumber:\n      return parseNumberDef(def);\n    case ZodFirstPartyTypeKind.ZodObject:\n      return parseObjectDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodBigInt:\n      return parseBigintDef(def);\n    case ZodFirstPartyTypeKind.ZodBoolean:\n      return parseBooleanDef();\n    case ZodFirstPartyTypeKind.ZodDate:\n      return parseDateDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodUndefined:\n      return parseUndefinedDef();\n    case ZodFirstPartyTypeKind.ZodNull:\n      return parseNullDef();\n    case ZodFirstPartyTypeKind.ZodArray:\n      return parseArrayDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodUnion:\n    case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n      return parseUnionDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodIntersection:\n      return parseIntersectionDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodTuple:\n      return parseTupleDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodRecord:\n      return parseRecordDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodLiteral:\n      return parseLiteralDef(def);\n    case ZodFirstPartyTypeKind.ZodEnum:\n      return parseEnumDef(def);\n    case ZodFirstPartyTypeKind.ZodNativeEnum:\n      return parseNativeEnumDef(def);\n    case ZodFirstPartyTypeKind.ZodNullable:\n      return parseNullableDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodOptional:\n      return parseOptionalDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodMap:\n      return parseMapDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodSet:\n      return parseSetDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodLazy:\n      return () => (def as any).getter()._def;\n    case ZodFirstPartyTypeKind.ZodPromise:\n      return parsePromiseDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodNaN:\n    case ZodFirstPartyTypeKind.ZodNever:\n      return parseNeverDef();\n    case ZodFirstPartyTypeKind.ZodEffects:\n      return parseEffectsDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodAny:\n      return parseAnyDef();\n    case ZodFirstPartyTypeKind.ZodUnknown:\n      return parseUnknownDef();\n    case ZodFirstPartyTypeKind.ZodDefault:\n      return parseDefaultDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodBranded:\n      return parseBrandedDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodReadonly:\n      return parseReadonlyDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodCatch:\n      return parseCatchDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodPipeline:\n      return parsePipelineDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodFunction:\n    case ZodFirstPartyTypeKind.ZodVoid:\n    case ZodFirstPartyTypeKind.ZodSymbol:\n      return undefined;\n    default:\n      /* c8 ignore next */\n      return ((_: never) => undefined)(typeName);\n  }\n};\n", "export type JsonSchema7AnyType = { $ref?: string };\n\nexport function parseAnyDef(): JsonSchema7AnyType {\n  return {};\n}\n", "import { ZodFirstPartyTypeKind, type ZodArrayDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport type JsonSchema7ArrayType = {\n  type: 'array';\n  items?: JsonSchema7Type;\n  minItems?: number;\n  maxItems?: number;\n};\n\nexport function parseArrayDef(def: ZodArrayDef, refs: Refs) {\n  const res: JsonSchema7ArrayType = {\n    type: 'array',\n  };\n  if (\n    def.type?._def &&\n    def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny\n  ) {\n    res.items = parseDef(def.type._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items'],\n    });\n  }\n\n  if (def.minLength) {\n    res.minItems = def.minLength.value;\n  }\n  if (def.maxLength) {\n    res.maxItems = def.maxLength.value;\n  }\n  if (def.exactLength) {\n    res.minItems = def.exactLength.value;\n    res.maxItems = def.exactLength.value;\n  }\n  return res;\n}\n", "import type { ZodBigIntDef } from 'zod/v3';\n\nexport type JsonSchema7BigintType = {\n  type: 'integer';\n  format: 'int64';\n  minimum?: BigInt;\n  exclusiveMinimum?: BigInt;\n  maximum?: BigInt;\n  exclusiveMaximum?: BigInt;\n  multipleOf?: BigInt;\n};\n\nexport function parseBigintDef(def: ZodBigIntDef): JsonSchema7BigintType {\n  const res: JsonSchema7BigintType = {\n    type: 'integer',\n    format: 'int64',\n  };\n\n  if (!def.checks) return res;\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'min':\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case 'max':\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n\n        break;\n      case 'multipleOf':\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n", "export type JsonSchema7BooleanType = {\n  type: 'boolean';\n};\n\nexport function parseBooleanDef(): JsonSchema7BooleanType {\n  return { type: 'boolean' };\n}\n", "import type { ZodBrandedDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { Refs } from '../refs';\n\nexport function parseBrandedDef(_def: ZodBrandedDef<any>, refs: Refs) {\n  return parseDef(_def.type._def, refs);\n}\n", "import type { ZodCatchDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { Refs } from '../refs';\n\nexport const parseCatchDef = (def: ZodCatchDef<any>, refs: Refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n", "import type { ZodDateDef } from 'zod/v3';\nimport type { Refs } from '../refs';\nimport type { DateStrategy } from '../options';\n\nexport type JsonSchema7DateType =\n  | {\n      type: 'integer' | 'string';\n      format: 'unix-time' | 'date-time' | 'date';\n      minimum?: number;\n      maximum?: number;\n    }\n  | {\n      anyOf: JsonSchema7DateType[];\n    };\n\nexport function parseDateDef(\n  def: ZodDateDef,\n  refs: Refs,\n  overrideDateStrategy?: DateStrategy,\n): JsonSchema7DateType {\n  const strategy = overrideDateStrategy ?? refs.dateStrategy;\n\n  if (Array.isArray(strategy)) {\n    return {\n      anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n    };\n  }\n\n  switch (strategy) {\n    case 'string':\n    case 'format:date-time':\n      return {\n        type: 'string',\n        format: 'date-time',\n      };\n    case 'format:date':\n      return {\n        type: 'string',\n        format: 'date',\n      };\n    case 'integer':\n      return integerDateParser(def);\n  }\n}\n\nconst integerDateParser = (def: ZodDateDef) => {\n  const res: JsonSchema7DateType = {\n    type: 'integer',\n    format: 'unix-time',\n  };\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'min':\n        res.minimum = check.value;\n        break;\n      case 'max':\n        res.maximum = check.value;\n        break;\n    }\n  }\n\n  return res;\n};\n", "import type { ZodDefaultDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport function parseDefaultDef(\n  _def: ZodDefaultDef,\n  refs: Refs,\n): JsonSchema7Type & { default: any } {\n  return {\n    ...parseDef(_def.innerType._def, refs),\n    default: _def.defaultValue(),\n  };\n}\n", "import type { ZodEffectsDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport function parseEffectsDef(\n  _def: ZodEffectsDef,\n  refs: Refs,\n): JsonSchema7Type | undefined {\n  return refs.effectStrategy === 'input'\n    ? parseDef(_def.schema._def, refs)\n    : parseAnyDef();\n}\n", "import type { ZodEnumDef } from 'zod/v3';\n\nexport type JsonSchema7EnumType = {\n  type: 'string';\n  enum: string[];\n};\n\nexport function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType {\n  return {\n    type: 'string',\n    enum: Array.from(def.values),\n  };\n}\n", "import type { ZodIntersectionDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport type { JsonSchema7StringType } from './string';\n\nexport type JsonSchema7AllOfType = {\n  allOf: JsonSchema7Type[];\n  unevaluatedProperties?: boolean;\n};\n\nconst isJsonSchema7AllOfType = (\n  type: JsonSchema7Type | JsonSchema7StringType,\n): type is JsonSchema7AllOfType => {\n  if ('type' in type && type.type === 'string') return false;\n  return 'allOf' in type;\n};\n\nexport function parseIntersectionDef(\n  def: ZodIntersectionDef,\n  refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined {\n  const allOf = [\n    parseDef(def.left._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'allOf', '0'],\n    }),\n    parseDef(def.right._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'allOf', '1'],\n    }),\n  ].filter((x): x is JsonSchema7Type => !!x);\n\n  const mergedAllOf: JsonSchema7Type[] = [];\n  // If either of the schemas is an allOf, merge them into a single allOf\n  allOf.forEach(schema => {\n    if (isJsonSchema7AllOfType(schema)) {\n      mergedAllOf.push(...schema.allOf);\n    } else {\n      let nestedSchema: JsonSchema7Type = schema;\n      if (\n        'additionalProperties' in schema &&\n        schema.additionalProperties === false\n      ) {\n        const { additionalProperties, ...rest } = schema;\n        nestedSchema = rest;\n      }\n      mergedAllOf.push(nestedSchema);\n    }\n  });\n  return mergedAllOf.length ? { allOf: mergedAllOf } : undefined;\n}\n", "import type { ZodLiteralDef } from 'zod/v3';\n\nexport type JsonSchema7LiteralType =\n  | {\n      type: 'string' | 'number' | 'integer' | 'boolean';\n      const: string | number | boolean;\n    }\n  | {\n      type: 'object' | 'array';\n    };\n\nexport function parseLiteralDef(def: ZodLiteralDef): JsonSchema7LiteralType {\n  const parsedType = typeof def.value;\n  if (\n    parsedType !== 'bigint' &&\n    parsedType !== 'number' &&\n    parsedType !== 'boolean' &&\n    parsedType !== 'string'\n  ) {\n    return {\n      type: Array.isArray(def.value) ? 'array' : 'object',\n    };\n  }\n\n  return {\n    type: parsedType === 'bigint' ? 'integer' : parsedType,\n    const: def.value,\n  };\n}\n", "import {\n  ZodFirstPartyTypeKind,\n  type ZodMapDef,\n  type ZodRecordDef,\n  type ZodTypeAny,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport { parseBrandedDef } from './branded';\nimport type { JsonSchema7EnumType } from './enum';\nimport { parseStringDef, type JsonSchema7StringType } from './string';\n\ntype JsonSchema7RecordPropertyNamesType =\n  | Omit<JsonSchema7StringType, 'type'>\n  | Omit<JsonSchema7EnumType, 'type'>;\n\nexport type JsonSchema7RecordType = {\n  type: 'object';\n  additionalProperties?: JsonSchema7Type | true;\n  propertyNames?: JsonSchema7RecordPropertyNamesType;\n};\n\nexport function parseRecordDef(\n  def: ZodRecordDef<ZodTypeAny, ZodTypeAny> | ZodMapDef,\n  refs: Refs,\n): JsonSchema7RecordType {\n  const schema: JsonSchema7RecordType = {\n    type: 'object',\n    additionalProperties:\n      parseDef(def.valueType._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'additionalProperties'],\n      }) ?? refs.allowedAdditionalProperties,\n  };\n\n  if (\n    def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n    def.keyType._def.checks?.length\n  ) {\n    const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n\n    return {\n      ...schema,\n      propertyNames: keyType,\n    };\n  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n    return {\n      ...schema,\n      propertyNames: {\n        enum: def.keyType._def.values,\n      },\n    };\n  } else if (\n    def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&\n    def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n    def.keyType._def.type._def.checks?.length\n  ) {\n    const { type, ...keyType } = parseBrandedDef(\n      def.keyType._def,\n      refs,\n    ) as JsonSchema7StringType;\n\n    return {\n      ...schema,\n      propertyNames: keyType,\n    };\n  }\n\n  return schema;\n}\n", "import type { ZodStringDef } from 'zod/v3';\nimport type { Refs } from '../refs';\n\nlet emojiRegex: RegExp | undefined = undefined;\n\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n  /**\n   * `c` was changed to `[cC]` to replicate /i flag\n   */\n  cuid: /^[cC][^\\s-]{8,}$/,\n  cuid2: /^[0-9a-z]+$/,\n  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n  /**\n   * `a-z` was added to replicate /i flag\n   */\n  email:\n    /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n  /**\n   * Constructed a valid Unicode RegExp\n   *\n   * Lazily instantiate since this type of regex isn't supported\n   * in all envs (e.g. React Native).\n   *\n   * See:\n   * https://github.com/colinhacks/zod/issues/2433\n   * Fix in Zod:\n   * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n   */\n  emoji: () => {\n    if (emojiRegex === undefined) {\n      emojiRegex = RegExp(\n        '^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$',\n        'u',\n      );\n    }\n    return emojiRegex;\n  },\n  /**\n   * Unused\n   */\n  uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n  /**\n   * Unused\n   */\n  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])$/,\n  ipv4Cidr:\n    /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n  /**\n   * Unused\n   */\n  ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n  ipv6Cidr:\n    /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n  base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n  base64url:\n    /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n  nanoid: /^[a-zA-Z0-9_-]{21}$/,\n  jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n} as const;\n\nexport type JsonSchema7StringType = {\n  type: 'string';\n  minLength?: number;\n  maxLength?: number;\n  format?:\n    | 'email'\n    | 'idn-email'\n    | 'uri'\n    | 'uuid'\n    | 'date-time'\n    | 'ipv4'\n    | 'ipv6'\n    | 'date'\n    | 'time'\n    | 'duration';\n  pattern?: string;\n  allOf?: {\n    pattern: string;\n  }[];\n  anyOf?: {\n    format: string;\n  }[];\n  contentEncoding?: string;\n};\n\nexport function parseStringDef(\n  def: ZodStringDef,\n  refs: Refs,\n): JsonSchema7StringType {\n  const res: JsonSchema7StringType = {\n    type: 'string',\n  };\n\n  if (def.checks) {\n    for (const check of def.checks) {\n      switch (check.kind) {\n        case 'min':\n          res.minLength =\n            typeof res.minLength === 'number'\n              ? Math.max(res.minLength, check.value)\n              : check.value;\n          break;\n        case 'max':\n          res.maxLength =\n            typeof res.maxLength === 'number'\n              ? Math.min(res.maxLength, check.value)\n              : check.value;\n\n          break;\n        case 'email':\n          switch (refs.emailStrategy) {\n            case 'format:email':\n              addFormat(res, 'email', check.message, refs);\n              break;\n            case 'format:idn-email':\n              addFormat(res, 'idn-email', check.message, refs);\n              break;\n            case 'pattern:zod':\n              addPattern(res, zodPatterns.email, check.message, refs);\n              break;\n          }\n\n          break;\n        case 'url':\n          addFormat(res, 'uri', check.message, refs);\n          break;\n        case 'uuid':\n          addFormat(res, 'uuid', check.message, refs);\n          break;\n        case 'regex':\n          addPattern(res, check.regex, check.message, refs);\n          break;\n        case 'cuid':\n          addPattern(res, zodPatterns.cuid, check.message, refs);\n          break;\n        case 'cuid2':\n          addPattern(res, zodPatterns.cuid2, check.message, refs);\n          break;\n        case 'startsWith':\n          addPattern(\n            res,\n            RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n            check.message,\n            refs,\n          );\n          break;\n        case 'endsWith':\n          addPattern(\n            res,\n            RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n            check.message,\n            refs,\n          );\n          break;\n        case 'datetime':\n          addFormat(res, 'date-time', check.message, refs);\n          break;\n        case 'date':\n          addFormat(res, 'date', check.message, refs);\n          break;\n        case 'time':\n          addFormat(res, 'time', check.message, refs);\n          break;\n        case 'duration':\n          addFormat(res, 'duration', check.message, refs);\n          break;\n        case 'length':\n          res.minLength =\n            typeof res.minLength === 'number'\n              ? Math.max(res.minLength, check.value)\n              : check.value;\n          res.maxLength =\n            typeof res.maxLength === 'number'\n              ? Math.min(res.maxLength, check.value)\n              : check.value;\n          break;\n        case 'includes': {\n          addPattern(\n            res,\n            RegExp(escapeLiteralCheckValue(check.value, refs)),\n            check.message,\n            refs,\n          );\n          break;\n        }\n        case 'ip': {\n          if (check.version !== 'v6') {\n            addFormat(res, 'ipv4', check.message, refs);\n          }\n          if (check.version !== 'v4') {\n            addFormat(res, 'ipv6', check.message, refs);\n          }\n          break;\n        }\n        case 'base64url':\n          addPattern(res, zodPatterns.base64url, check.message, refs);\n          break;\n        case 'jwt':\n          addPattern(res, zodPatterns.jwt, check.message, refs);\n          break;\n        case 'cidr': {\n          if (check.version !== 'v6') {\n            addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n          }\n          if (check.version !== 'v4') {\n            addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n          }\n          break;\n        }\n        case 'emoji':\n          addPattern(res, zodPatterns.emoji(), check.message, refs);\n          break;\n        case 'ulid': {\n          addPattern(res, zodPatterns.ulid, check.message, refs);\n          break;\n        }\n        case 'base64': {\n          switch (refs.base64Strategy) {\n            case 'format:binary': {\n              addFormat(res, 'binary' as any, check.message, refs);\n              break;\n            }\n\n            case 'contentEncoding:base64': {\n              res.contentEncoding = 'base64';\n              break;\n            }\n\n            case 'pattern:zod': {\n              addPattern(res, zodPatterns.base64, check.message, refs);\n              break;\n            }\n          }\n          break;\n        }\n        case 'nanoid': {\n          addPattern(res, zodPatterns.nanoid, check.message, refs);\n        }\n        case 'toLowerCase':\n        case 'toUpperCase':\n        case 'trim':\n          break;\n        default:\n          /* c8 ignore next */\n          ((_: never) => {})(check);\n      }\n    }\n  }\n\n  return res;\n}\n\nfunction escapeLiteralCheckValue(literal: string, refs: Refs): string {\n  return refs.patternStrategy === 'escape'\n    ? escapeNonAlphaNumeric(literal)\n    : literal;\n}\n\nconst ALPHA_NUMERIC = new Set(\n  'ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789',\n);\n\nfunction escapeNonAlphaNumeric(source: string) {\n  let result = '';\n\n  for (let i = 0; i < source.length; i++) {\n    if (!ALPHA_NUMERIC.has(source[i])) {\n      result += '\\\\';\n    }\n\n    result += source[i];\n  }\n\n  return result;\n}\n\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(\n  schema: JsonSchema7StringType,\n  value: Required<JsonSchema7StringType>['format'],\n  message: string | undefined,\n  refs: Refs,\n) {\n  if (schema.format || schema.anyOf?.some(x => x.format)) {\n    if (!schema.anyOf) {\n      schema.anyOf = [];\n    }\n\n    if (schema.format) {\n      schema.anyOf!.push({\n        format: schema.format,\n      });\n      delete schema.format;\n    }\n\n    schema.anyOf!.push({\n      format: value,\n      ...(message &&\n        refs.errorMessages && { errorMessage: { format: message } }),\n    });\n  } else {\n    schema.format = value;\n  }\n}\n\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(\n  schema: JsonSchema7StringType,\n  regex: RegExp,\n  message: string | undefined,\n  refs: Refs,\n) {\n  if (schema.pattern || schema.allOf?.some(x => x.pattern)) {\n    if (!schema.allOf) {\n      schema.allOf = [];\n    }\n\n    if (schema.pattern) {\n      schema.allOf!.push({\n        pattern: schema.pattern,\n      });\n      delete schema.pattern;\n    }\n\n    schema.allOf!.push({\n      pattern: stringifyRegExpWithFlags(regex, refs),\n      ...(message &&\n        refs.errorMessages && { errorMessage: { pattern: message } }),\n    });\n  } else {\n    schema.pattern = stringifyRegExpWithFlags(regex, refs);\n  }\n}\n\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex: RegExp, refs: Refs): string {\n  if (!refs.applyRegexFlags || !regex.flags) {\n    return regex.source;\n  }\n\n  // Currently handled flags\n  const flags = {\n    i: regex.flags.includes('i'), // Case-insensitive\n    m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters\n    s: regex.flags.includes('s'), // `.` matches newlines\n  };\n\n  // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n  const source = flags.i ? regex.source.toLowerCase() : regex.source;\n  let pattern = '';\n  let isEscaped = false;\n  let inCharGroup = false;\n  let inCharRange = false;\n\n  for (let i = 0; i < source.length; i++) {\n    if (isEscaped) {\n      pattern += source[i];\n      isEscaped = false;\n      continue;\n    }\n\n    if (flags.i) {\n      if (inCharGroup) {\n        if (source[i].match(/[a-z]/)) {\n          if (inCharRange) {\n            pattern += source[i];\n            pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n            inCharRange = false;\n          } else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {\n            pattern += source[i];\n            inCharRange = true;\n          } else {\n            pattern += `${source[i]}${source[i].toUpperCase()}`;\n          }\n          continue;\n        }\n      } else if (source[i].match(/[a-z]/)) {\n        pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n        continue;\n      }\n    }\n\n    if (flags.m) {\n      if (source[i] === '^') {\n        pattern += `(^|(?<=[\\r\\n]))`;\n        continue;\n      } else if (source[i] === '$') {\n        pattern += `($|(?=[\\r\\n]))`;\n        continue;\n      }\n    }\n\n    if (flags.s && source[i] === '.') {\n      pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n      continue;\n    }\n\n    pattern += source[i];\n    if (source[i] === '\\\\') {\n      isEscaped = true;\n    } else if (inCharGroup && source[i] === ']') {\n      inCharGroup = false;\n    } else if (!inCharGroup && source[i] === '[') {\n      inCharGroup = true;\n    }\n  }\n\n  try {\n    new RegExp(pattern);\n  } catch {\n    console.warn(\n      `Could not convert regex pattern at ${refs.currentPath.join(\n        '/',\n      )} to a flag-independent form! Falling back to the flag-ignorant source`,\n    );\n    return regex.source;\n  }\n\n  return pattern;\n}\n", "import type { ZodMapDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport { parseAnyDef } from './any';\nimport { parseRecordDef, type JsonSchema7RecordType } from './record';\n\nexport type JsonSchema7MapType = {\n  type: 'array';\n  maxItems: 125;\n  items: {\n    type: 'array';\n    items: [JsonSchema7Type, JsonSchema7Type];\n    minItems: 2;\n    maxItems: 2;\n  };\n};\n\nexport function parseMapDef(\n  def: ZodMapDef,\n  refs: Refs,\n): JsonSchema7MapType | JsonSchema7RecordType {\n  if (refs.mapStrategy === 'record') {\n    return parseRecordDef(def, refs);\n  }\n\n  const keys =\n    parseDef(def.keyType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items', 'items', '0'],\n    }) || parseAnyDef();\n  const values =\n    parseDef(def.valueType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items', 'items', '1'],\n    }) || parseAnyDef();\n  return {\n    type: 'array',\n    maxItems: 125,\n    items: {\n      type: 'array',\n      items: [keys, values],\n      minItems: 2,\n      maxItems: 2,\n    },\n  };\n}\n", "import type { ZodNativeEnumDef } from 'zod/v3';\n\nexport type JsonSchema7NativeEnumType = {\n  type: 'string' | 'number' | ['string', 'number'];\n  enum: (string | number)[];\n};\n\nexport function parseNativeEnumDef(\n  def: ZodNativeEnumDef,\n): JsonSchema7NativeEnumType {\n  const object = def.values;\n  const actualKeys = Object.keys(def.values).filter((key: string) => {\n    return typeof object[object[key]] !== 'number';\n  });\n\n  const actualValues = actualKeys.map((key: string) => object[key]);\n\n  const parsedTypes = Array.from(\n    new Set(actualValues.map((values: string | number) => typeof values)),\n  );\n\n  return {\n    type:\n      parsedTypes.length === 1\n        ? parsedTypes[0] === 'string'\n          ? 'string'\n          : 'number'\n        : ['string', 'number'],\n    enum: actualValues,\n  };\n}\n", "import { parseAnyDef, type JsonSchema7AnyType } from './any';\n\nexport type JsonSchema7NeverType = {\n  not: JsonSchema7AnyType;\n};\n\nexport function parseNeverDef(): JsonSchema7NeverType | undefined {\n  return { not: parseAnyDef() };\n}\n", "export type JsonSchema7NullType = {\n  type: 'null';\n};\n\nexport function parseNullDef(): JsonSchema7NullType {\n  return {\n    type: 'null',\n  };\n}\n", "import type {\n  ZodDiscriminatedUnionDef,\n  ZodLiteralDef,\n  ZodTypeAny,\n  ZodUnionDef,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport const primitiveMappings = {\n  ZodString: 'string',\n  ZodNumber: 'number',\n  ZodBigInt: 'integer',\n  ZodBoolean: 'boolean',\n  ZodNull: 'null',\n} as const;\ntype ZodPrimitive = keyof typeof primitiveMappings;\ntype JsonSchema7Primitive =\n  (typeof primitiveMappings)[keyof typeof primitiveMappings];\n\nexport type JsonSchema7UnionType =\n  | JsonSchema7PrimitiveUnionType\n  | JsonSchema7AnyOfType;\n\ntype JsonSchema7PrimitiveUnionType =\n  | {\n      type: JsonSchema7Primitive | JsonSchema7Primitive[];\n    }\n  | {\n      type: JsonSchema7Primitive | JsonSchema7Primitive[];\n      enum: (string | number | bigint | boolean | null)[];\n    };\n\ntype JsonSchema7AnyOfType = {\n  anyOf: JsonSchema7Type[];\n};\n\nexport function parseUnionDef(\n  def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n  refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined {\n  const options: readonly ZodTypeAny[] =\n    def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\n  // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n  if (\n    options.every(\n      x =>\n        x._def.typeName in primitiveMappings &&\n        (!x._def.checks || !x._def.checks.length),\n    )\n  ) {\n    // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n\n    const types = options.reduce((types: JsonSchema7Primitive[], x) => {\n      const type = primitiveMappings[x._def.typeName as ZodPrimitive]; //Can be safely casted due to row 43\n      return type && !types.includes(type) ? [...types, type] : types;\n    }, []);\n\n    return {\n      type: types.length > 1 ? types : types[0],\n    };\n  } else if (\n    options.every(x => x._def.typeName === 'ZodLiteral' && !x.description)\n  ) {\n    // all options literals\n\n    const types = options.reduce(\n      (acc: JsonSchema7Primitive[], x: { _def: ZodLiteralDef }) => {\n        const type = typeof x._def.value;\n        switch (type) {\n          case 'string':\n          case 'number':\n          case 'boolean':\n            return [...acc, type];\n          case 'bigint':\n            return [...acc, 'integer' as const];\n          case 'object':\n            if (x._def.value === null) return [...acc, 'null' as const];\n          case 'symbol':\n          case 'undefined':\n          case 'function':\n          default:\n            return acc;\n        }\n      },\n      [],\n    );\n\n    if (types.length === options.length) {\n      // all the literals are primitive, as far as null can be considered primitive\n\n      const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n      return {\n        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n        enum: options.reduce(\n          (acc, x) => {\n            return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n          },\n          [] as (string | number | bigint | boolean | null)[],\n        ),\n      };\n    }\n  } else if (options.every(x => x._def.typeName === 'ZodEnum')) {\n    return {\n      type: 'string',\n      enum: options.reduce(\n        (acc: string[], x) => [\n          ...acc,\n          ...x._def.values.filter((x: string) => !acc.includes(x)),\n        ],\n        [],\n      ),\n    };\n  }\n\n  return asAnyOf(def, refs);\n}\n\nconst asAnyOf = (\n  def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n  refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined => {\n  const anyOf = (\n    (def.options instanceof Map\n      ? Array.from(def.options.values())\n      : def.options) as any[]\n  )\n    .map((x, i) =>\n      parseDef(x._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'anyOf', `${i}`],\n      }),\n    )\n    .filter(\n      (x): x is JsonSchema7Type =>\n        !!x &&\n        (!refs.strictUnions ||\n          (typeof x === 'object' && Object.keys(x).length > 0)),\n    );\n\n  return anyOf.length ? { anyOf } : undefined;\n};\n", "import type { ZodNullableDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport type { JsonSchema7NullType } from './null';\nimport { primitiveMappings } from './union';\n\nexport type JsonSchema7NullableType =\n  | {\n      anyOf: [JsonSchema7Type, JsonSchema7NullType];\n    }\n  | {\n      type: [string, 'null'];\n    };\n\nexport function parseNullableDef(\n  def: ZodNullableDef,\n  refs: Refs,\n): JsonSchema7NullableType | undefined {\n  if (\n    ['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(\n      def.innerType._def.typeName,\n    ) &&\n    (!def.innerType._def.checks || !def.innerType._def.checks.length)\n  ) {\n    return {\n      type: [\n        primitiveMappings[\n          def.innerType._def.typeName as keyof typeof primitiveMappings\n        ],\n        'null',\n      ],\n    };\n  }\n\n  const base = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'anyOf', '0'],\n  });\n\n  return base && { anyOf: [base, { type: 'null' }] };\n}\n", "import type { ZodNumberDef } from 'zod/v3';\n\nexport type JsonSchema7NumberType = {\n  type: 'number' | 'integer';\n  minimum?: number;\n  exclusiveMinimum?: number;\n  maximum?: number;\n  exclusiveMaximum?: number;\n  multipleOf?: number;\n};\n\nexport function parseNumberDef(def: ZodNumberDef): JsonSchema7NumberType {\n  const res: JsonSchema7NumberType = {\n    type: 'number',\n  };\n\n  if (!def.checks) return res;\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'int':\n        res.type = 'integer';\n        break;\n      case 'min':\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case 'max':\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n        break;\n      case 'multipleOf':\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n", "import type { ZodObjectDef, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport type JsonSchema7ObjectType = {\n  type: 'object';\n  properties: Record<string, JsonSchema7Type>;\n  additionalProperties?: boolean | JsonSchema7Type;\n  required?: string[];\n};\n\nexport function parseObjectDef(def: ZodObjectDef, refs: Refs) {\n  const result: JsonSchema7ObjectType = {\n    type: 'object',\n    properties: {},\n  };\n\n  const required: string[] = [];\n\n  const shape = def.shape();\n\n  for (const propName in shape) {\n    let propDef = shape[propName];\n\n    if (propDef === undefined || propDef._def === undefined) {\n      continue;\n    }\n\n    const propOptional = safeIsOptional(propDef);\n\n    const parsedDef = parseDef(propDef._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'properties', propName],\n      propertyPath: [...refs.currentPath, 'properties', propName],\n    });\n\n    if (parsedDef === undefined) {\n      continue;\n    }\n\n    result.properties[propName] = parsedDef;\n\n    if (!propOptional) {\n      required.push(propName);\n    }\n  }\n\n  if (required.length) {\n    result.required = required;\n  }\n\n  const additionalProperties = decideAdditionalProperties(def, refs);\n\n  if (additionalProperties !== undefined) {\n    result.additionalProperties = additionalProperties;\n  }\n\n  return result;\n}\n\nfunction decideAdditionalProperties(def: ZodObjectDef, refs: Refs) {\n  if (def.catchall._def.typeName !== 'ZodNever') {\n    return parseDef(def.catchall._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'additionalProperties'],\n    });\n  }\n\n  switch (def.unknownKeys) {\n    case 'passthrough':\n      return refs.allowedAdditionalProperties;\n    case 'strict':\n      return refs.rejectedAdditionalProperties;\n    case 'strip':\n      return refs.removeAdditionalStrategy === 'strict'\n        ? refs.allowedAdditionalProperties\n        : refs.rejectedAdditionalProperties;\n  }\n}\n\nfunction safeIsOptional(schema: ZodTypeAny): boolean {\n  try {\n    return schema.isOptional();\n  } catch {\n    return true;\n  }\n}\n", "import type { ZodOptionalDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport const parseOptionalDef = (\n  def: ZodOptionalDef,\n  refs: Refs,\n): JsonSchema7Type | undefined => {\n  if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n    return parseDef(def.innerType._def, refs);\n  }\n\n  const innerSchema = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'anyOf', '1'],\n  });\n\n  return innerSchema\n    ? { anyOf: [{ not: parseAnyDef() }, innerSchema] }\n    : parseAnyDef();\n};\n", "import type { ZodPipelineDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport type { JsonSchema7AllOfType } from './intersection';\n\nexport const parsePipelineDef = (\n  def: ZodPipelineDef<any, any>,\n  refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined => {\n  if (refs.pipeStrategy === 'input') {\n    return parseDef(def.in._def, refs);\n  } else if (refs.pipeStrategy === 'output') {\n    return parseDef(def.out._def, refs);\n  }\n\n  const a = parseDef(def.in._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'allOf', '0'],\n  });\n  const b = parseDef(def.out._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],\n  });\n\n  return {\n    allOf: [a, b].filter((x): x is JsonSchema7Type => x !== undefined),\n  };\n};\n", "import type { ZodPromiseDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport function parsePromiseDef(\n  def: ZodPromiseDef,\n  refs: Refs,\n): JsonSchema7Type | undefined {\n  return parseDef(def.type._def, refs);\n}\n", "import type { ZodSetDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport type JsonSchema7SetType = {\n  type: 'array';\n  uniqueItems: true;\n  items?: JsonSchema7Type;\n  minItems?: number;\n  maxItems?: number;\n};\n\nexport function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType {\n  const items = parseDef(def.valueType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'items'],\n  });\n\n  const schema: JsonSchema7SetType = {\n    type: 'array',\n    uniqueItems: true,\n    items,\n  };\n\n  if (def.minSize) {\n    schema.minItems = def.minSize.value;\n  }\n\n  if (def.maxSize) {\n    schema.maxItems = def.maxSize.value;\n  }\n\n  return schema;\n}\n", "import type { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport type JsonSchema7TupleType = {\n  type: 'array';\n  minItems: number;\n  items: JsonSchema7Type[];\n} & (\n  | {\n      maxItems: number;\n    }\n  | {\n      additionalItems?: JsonSchema7Type;\n    }\n);\n\nexport function parseTupleDef(\n  def: ZodTupleDef<ZodTupleItems | [], ZodTypeAny | null>,\n  refs: Refs,\n): JsonSchema7TupleType {\n  if (def.rest) {\n    return {\n      type: 'array',\n      minItems: def.items.length,\n      items: def.items\n        .map((x, i) =>\n          parseDef(x._def, {\n            ...refs,\n            currentPath: [...refs.currentPath, 'items', `${i}`],\n          }),\n        )\n        .reduce(\n          (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n          [],\n        ),\n      additionalItems: parseDef(def.rest._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'additionalItems'],\n      }),\n    };\n  } else {\n    return {\n      type: 'array',\n      minItems: def.items.length,\n      maxItems: def.items.length,\n      items: def.items\n        .map((x, i) =>\n          parseDef(x._def, {\n            ...refs,\n            currentPath: [...refs.currentPath, 'items', `${i}`],\n          }),\n        )\n        .reduce(\n          (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n          [],\n        ),\n    };\n  }\n}\n", "import { parseAnyDef, type JsonSchema7AnyType } from './any';\n\nexport type JsonSchema7UndefinedType = {\n  not: JsonSchema7AnyType;\n};\n\nexport function parseUndefinedDef(): JsonSchema7UndefinedType {\n  return {\n    not: parseAnyDef(),\n  };\n}\n", "import { parseAnyDef, type JsonSchema7AnyType } from './any';\n\nexport type JsonSchema7UnknownType = JsonSchema7AnyType;\n\nexport function parseUnknownDef(): JsonSchema7UnknownType {\n  return parseAnyDef();\n}\n", "import type { ZodReadonlyDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { Refs } from '../refs';\n\nexport const parseReadonlyDef = (def: ZodReadonlyDef<any>, refs: Refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n", "export const getRelativePath = (pathA: string[], pathB: string[]) => {\n  let i = 0;\n  for (; i < pathA.length && i < pathB.length; i++) {\n    if (pathA[i] !== pathB[i]) break;\n  }\n  return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');\n};\n", "import type { ZodTypeDef } from 'zod/v3';\nimport type { Refs, Seen } from './refs';\nimport { ignoreOverride } from './options';\nimport type { JsonSchema7Type } from './parse-types';\nimport { selectParser } from './select-parser';\nimport { getRelativePath } from './get-relative-path';\nimport { parseAnyDef } from './parsers/any';\n\nexport function parseDef(\n  def: ZodTypeDef,\n  refs: Refs,\n  forceResolution = false, // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61.\n): JsonSchema7Type | undefined {\n  const seenItem = refs.seen.get(def);\n\n  if (refs.override) {\n    const overrideResult = refs.override?.(\n      def,\n      refs,\n      seenItem,\n      forceResolution,\n    );\n\n    if (overrideResult !== ignoreOverride) {\n      return overrideResult;\n    }\n  }\n\n  if (seenItem && !forceResolution) {\n    const seenSchema = get$ref(seenItem, refs);\n\n    if (seenSchema !== undefined) {\n      return seenSchema;\n    }\n  }\n\n  const newItem: Seen = { def, path: refs.currentPath, jsonSchema: undefined };\n\n  refs.seen.set(def, newItem);\n\n  const jsonSchemaOrGetter = selectParser(def, (def as any).typeName, refs);\n\n  // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n  const jsonSchema =\n    typeof jsonSchemaOrGetter === 'function'\n      ? parseDef(jsonSchemaOrGetter(), refs)\n      : jsonSchemaOrGetter;\n\n  if (jsonSchema) {\n    addMeta(def, refs, jsonSchema);\n  }\n\n  if (refs.postProcess) {\n    const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n\n    newItem.jsonSchema = jsonSchema;\n\n    return postProcessResult;\n  }\n\n  newItem.jsonSchema = jsonSchema;\n\n  return jsonSchema;\n}\n\nconst get$ref = (\n  item: Seen,\n  refs: Refs,\n):\n  | {\n      $ref: string;\n    }\n  | {}\n  | undefined => {\n  switch (refs.$refStrategy) {\n    case 'root':\n      return { $ref: item.path.join('/') };\n    case 'relative':\n      return { $ref: getRelativePath(refs.currentPath, item.path) };\n    case 'none':\n    case 'seen': {\n      if (\n        item.path.length < refs.currentPath.length &&\n        item.path.every((value, index) => refs.currentPath[index] === value)\n      ) {\n        console.warn(\n          `Recursive reference detected at ${refs.currentPath.join(\n            '/',\n          )}! Defaulting to any`,\n        );\n\n        return parseAnyDef();\n      }\n\n      return refs.$refStrategy === 'seen' ? parseAnyDef() : undefined;\n    }\n  }\n};\n\nconst addMeta = (\n  def: ZodTypeDef,\n  refs: Refs,\n  jsonSchema: JsonSchema7Type,\n): JsonSchema7Type => {\n  if (def.description) {\n    jsonSchema.description = def.description;\n  }\n  return jsonSchema;\n};\n", "import type { ZodTypeDef } from 'zod/v3';\nimport { getDefaultOptions, type Options } from './options';\nimport type { JsonSchema7Type } from './parse-types';\n\nexport type Refs = {\n  seen: Map<ZodTypeDef, Seen>;\n  currentPath: string[];\n  propertyPath: string[] | undefined;\n} & Options;\n\nexport type Seen = {\n  def: ZodTypeDef;\n  path: string[];\n  jsonSchema: JsonSchema7Type | undefined;\n};\n\nexport const getRefs = (options?: string | Partial<Options>): Refs => {\n  const _options = getDefaultOptions(options);\n  const currentPath =\n    _options.name !== undefined\n      ? [..._options.basePath, _options.definitionPath, _options.name]\n      : _options.basePath;\n  return {\n    ..._options,\n    currentPath: currentPath,\n    propertyPath: undefined,\n    seen: new Map(\n      Object.entries(_options.definitions).map(([name, def]) => [\n        def._def,\n        {\n          def: def._def,\n          path: [..._options.basePath, _options.definitionPath, name],\n          // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n          jsonSchema: undefined,\n        },\n      ]),\n    ),\n  };\n};\n", "import type { ZodSchema } from 'zod/v3';\nimport type { Options } from './options';\nimport { parseDef } from './parse-def';\nimport type { JsonSchema7Type } from './parse-types';\nimport { getRefs } from './refs';\nimport { parseAnyDef } from './parsers/any';\n\nconst zod3ToJsonSchema = (\n  schema: ZodSchema<any>,\n  options?: Partial<Options> | string,\n): JsonSchema7Type & {\n  $schema?: string;\n  definitions?: {\n    [key: string]: JsonSchema7Type;\n  };\n} => {\n  const refs = getRefs(options);\n\n  let definitions =\n    typeof options === 'object' && options.definitions\n      ? Object.entries(options.definitions).reduce(\n          (acc: { [key: string]: JsonSchema7Type }, [name, schema]) => ({\n            ...acc,\n            [name]:\n              parseDef(\n                schema._def,\n                {\n                  ...refs,\n                  currentPath: [...refs.basePath, refs.definitionPath, name],\n                },\n                true,\n              ) ?? parseAnyDef(),\n          }),\n          {},\n        )\n      : undefined;\n\n  const name =\n    typeof options === 'string'\n      ? options\n      : options?.nameStrategy === 'title'\n        ? undefined\n        : options?.name;\n\n  const main =\n    parseDef(\n      schema._def,\n      name === undefined\n        ? refs\n        : {\n            ...refs,\n            currentPath: [...refs.basePath, refs.definitionPath, name],\n          },\n      false,\n    ) ?? (parseAnyDef() as JsonSchema7Type);\n\n  const title =\n    typeof options === 'object' &&\n    options.name !== undefined &&\n    options.nameStrategy === 'title'\n      ? options.name\n      : undefined;\n\n  if (title !== undefined) {\n    main.title = title;\n  }\n\n  const combined: ReturnType<typeof zod3ToJsonSchema> =\n    name === undefined\n      ? definitions\n        ? {\n            ...main,\n            [refs.definitionPath]: definitions,\n          }\n        : main\n      : {\n          $ref: [\n            ...(refs.$refStrategy === 'relative' ? [] : refs.basePath),\n            refs.definitionPath,\n            name,\n          ].join('/'),\n          [refs.definitionPath]: {\n            ...definitions,\n            [name]: main,\n          },\n        };\n\n  combined.$schema = 'http://json-schema.org/draft-07/schema#';\n\n  return combined;\n};\n\nexport { zod3ToJsonSchema };\n", "import {\n  EventSourceParserStream,\n  type EventSourceMessage,\n} from 'eventsource-parser/stream';\nimport { safeParseJSON, type ParseResult } from './parse-json';\nimport type { FlexibleSchema } from './schema';\n\n/**\n * Parses a JSON event stream into a stream of parsed JSON objects.\n */\nexport function parseJsonEventStream<T>({\n  stream,\n  schema,\n}: {\n  stream: ReadableStream<Uint8Array>;\n  schema: FlexibleSchema<T>;\n}): ReadableStream<ParseResult<T>> {\n  return stream\n    .pipeThrough(new TextDecoderStream())\n    .pipeThrough(new EventSourceParserStream())\n    .pipeThrough(\n      new TransformStream<EventSourceMessage, ParseResult<T>>({\n        async transform({ data }, controller) {\n          // ignore the 'DONE' event that e.g. OpenAI sends:\n          if (data === '[DONE]') {\n            return;\n          }\n\n          controller.enqueue(await safeParseJSON({ text: data, schema }));\n        },\n      }),\n    );\n}\n", "import { InvalidArgumentError } from '@ai-sdk/provider';\nimport { safeValidateTypes } from './validate-types';\nimport type { FlexibleSchema } from './schema';\n\nexport async function parseProviderOptions<OPTIONS>({\n  provider,\n  providerOptions,\n  schema,\n}: {\n  provider: string;\n  providerOptions: Record<string, unknown> | undefined;\n  schema: FlexibleSchema<OPTIONS>;\n}): Promise<OPTIONS | undefined> {\n  if (providerOptions?.[provider] == null) {\n    return undefined;\n  }\n\n  const parsedProviderOptions = await safeValidateTypes<OPTIONS | undefined>({\n    value: providerOptions[provider],\n    schema,\n  });\n\n  if (!parsedProviderOptions.success) {\n    throw new InvalidArgumentError({\n      argument: 'providerOptions',\n      message: `invalid ${provider} provider options`,\n      cause: parsedProviderOptions.error,\n    });\n  }\n\n  return parsedProviderOptions.value;\n}\n", "import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport type { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport type { ResponseHandler } from './response-handler';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\nimport { VERSION } from './version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const postJsonToApi = async <T>({\n  url,\n  headers,\n  body,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  body: unknown;\n  failedResponseHandler: ResponseHandler<APICallError>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) =>\n  postToApi({\n    url,\n    headers: {\n      'Content-Type': 'application/json',\n      ...headers,\n    },\n    body: {\n      content: JSON.stringify(body),\n      values: body,\n    },\n    failedResponseHandler,\n    successfulResponseHandler,\n    abortSignal,\n    fetch,\n  });\n\nexport const postFormDataToApi = async <T>({\n  url,\n  headers,\n  formData,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  formData: FormData;\n  failedResponseHandler: ResponseHandler<APICallError>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) =>\n  postToApi({\n    url,\n    headers,\n    body: {\n      content: formData,\n      values: Object.fromEntries((formData as any).entries()),\n    },\n    failedResponseHandler,\n    successfulResponseHandler,\n    abortSignal,\n    fetch,\n  });\n\nexport const postToApi = async <T>({\n  url,\n  headers = {},\n  body,\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  body: {\n    content: string | FormData | Uint8Array;\n    values: unknown;\n  };\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  try {\n    const response = await fetch(url, {\n      method: 'POST',\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      body: body.content,\n      signal: abortSignal,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: body.values,\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: body.values,\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: body.values,\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: body.values,\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: body.values });\n  }\n};\n", "import type { JSONValue, JSONObject } from '@ai-sdk/provider';\nimport type { FlexibleSchema } from '../schema';\nimport type { ToolResultOutput } from './content-part';\nimport type { ModelMessage } from './model-message';\nimport type { ProviderOptions } from './provider-options';\n\n/**\n * Additional options that are sent into each tool call.\n */\nexport interface ToolExecutionOptions {\n  /**\n   * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n   */\n  toolCallId: string;\n\n  /**\n   * Messages that were sent to the language model to initiate the response that contained the tool call.\n   * The messages **do not** include the system prompt nor the assistant response that contained the tool call.\n   */\n  messages: ModelMessage[];\n\n  /**\n   * An optional abort signal that indicates that the overall operation should be aborted.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * User-defined context.\n   *\n   * Treat the context object as immutable inside tools.\n   * Mutating the context object can lead to race conditions and unexpected results\n   * when tools are called in parallel.\n   *\n   * If you need to mutate the context, analyze the tool calls and results\n   * in `prepareStep` and update it there.\n   *\n   * Experimental (can break in patch releases).\n   */\n  experimental_context?: unknown;\n}\n\n/**\n * Function that is called to determine if the tool needs approval before it can be executed.\n */\nexport type ToolNeedsApprovalFunction<INPUT> = (\n  input: INPUT,\n  options: {\n    /**\n     * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n     */\n    toolCallId: string;\n\n    /**\n     * Messages that were sent to the language model to initiate the response that contained the tool call.\n     * The messages **do not** include the system prompt nor the assistant response that contained the tool call.\n     */\n    messages: ModelMessage[];\n\n    /**\n     * Additional context.\n     *\n     * Experimental (can break in patch releases).\n     */\n    experimental_context?: unknown;\n  },\n) => boolean | PromiseLike<boolean>;\n\nexport type ToolExecuteFunction<INPUT, OUTPUT> = (\n  input: INPUT,\n  options: ToolExecutionOptions,\n) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;\n\n// 0 extends 1 & N checks for any\n// [N] extends [never] checks for never\ntype NeverOptional<N, T> = 0 extends 1 & N\n  ? Partial<T>\n  : [N] extends [never]\n    ? Partial<Record<keyof T, undefined>>\n    : T;\n\ntype ToolOutputProperties<INPUT, OUTPUT> = NeverOptional<\n  OUTPUT,\n  | {\n      /**\n       * An async function that is called with the arguments from the tool call and produces a result.\n       * If not provided, the tool will not be executed automatically.\n       *\n       * @args is the input of the tool call.\n       * @options.abortSignal is a signal that can be used to abort the tool call.\n       */\n      execute: ToolExecuteFunction<INPUT, OUTPUT>;\n\n      outputSchema?: FlexibleSchema<OUTPUT>;\n    }\n  | {\n      outputSchema: FlexibleSchema<OUTPUT>;\n\n      execute?: never;\n    }\n>;\n\n/**\n * A tool contains the description and the schema of the input that the tool expects.\n * This enables the language model to generate the input.\n *\n * The tool can also contain an optional execute function for the actual execution function of the tool.\n */\nexport type Tool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n> = {\n  /**\n   * An optional description of what the tool does.\n   * Will be used by the language model to decide whether to use the tool.\n   * Not used for provider-defined tools.\n   */\n  description?: string;\n\n  /**\n   * An optional title of the tool.\n   */\n  title?: string;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Optional metadata about the tool itself (e.g. its source).\n   *\n   * Unlike `providerOptions`, this metadata is not sent to the language\n   * model. Instead, it is propagated onto the resulting tool call's\n   * `toolMetadata` so consumers can read it from tool call / result parts\n   * and UI message parts. This is useful for sources of dynamic tools (e.g.\n   * an MCP server) to identify themselves.\n   */\n  metadata?: JSONObject;\n\n  /**\n   * The schema of the input that the tool expects.\n   * The language model will use this to generate the input.\n   * It is also used to validate the output of the language model.\n   *\n   * You can use descriptions on the schema properties to make the input understandable for the language model.\n   */\n  inputSchema: FlexibleSchema<INPUT>;\n\n  /**\n   * An optional list of input examples that show the language\n   * model what the input should look like.\n   */\n  inputExamples?: Array<{ input: NoInfer<INPUT> }>;\n\n  /**\n   * Whether the tool needs approval before it can be executed.\n   */\n  needsApproval?:\n    | boolean\n    | ToolNeedsApprovalFunction<[INPUT] extends [never] ? unknown : INPUT>;\n\n  /**\n   * Strict mode setting for the tool.\n   *\n   * Providers that support strict mode will use this setting to determine\n   * how the input should be generated. Strict mode will always produce\n   * valid inputs, but it might limit what input schemas are supported.\n   */\n  strict?: boolean;\n\n  /**\n   * Optional function that is called when the argument streaming starts.\n   * Only called when the tool is used in a streaming context.\n   */\n  onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;\n\n  /**\n   * Optional function that is called when an argument streaming delta is available.\n   * Only called when the tool is used in a streaming context.\n   */\n  onInputDelta?: (\n    options: { inputTextDelta: string } & ToolExecutionOptions,\n  ) => void | PromiseLike<void>;\n\n  /**\n   * Optional function that is called when a tool call can be started,\n   * even if the execute function is not provided.\n   */\n  onInputAvailable?: (\n    options: {\n      input: [INPUT] extends [never] ? unknown : INPUT;\n    } & ToolExecutionOptions,\n  ) => void | PromiseLike<void>;\n} & ToolOutputProperties<INPUT, OUTPUT> & {\n    /**\n     * Optional conversion function that maps the tool result to an output that can be used by the language model.\n     *\n     * If not provided, the tool result will be sent as a JSON object.\n     */\n    toModelOutput?: (options: {\n      /**\n       * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n       */\n      toolCallId: string;\n\n      /**\n       * The input of the tool call.\n       */\n      input: [INPUT] extends [never] ? unknown : INPUT;\n\n      /**\n       * The output of the tool call.\n       */\n      output: 0 extends 1 & OUTPUT\n        ? any\n        : [OUTPUT] extends [never]\n          ? any\n          : NoInfer<OUTPUT>;\n    }) => ToolResultOutput | PromiseLike<ToolResultOutput>;\n  } & (\n    | {\n        /**\n         * Tool with user-defined input and output schemas.\n         */\n        type?: undefined | 'function';\n      }\n    | {\n        /**\n         * Tool that is defined at runtime (e.g. an MCP tool).\n         * The types of input and output are not known at development time.\n         */\n        type: 'dynamic';\n      }\n    | {\n        /**\n         * Tool with provider-defined input and output schemas.\n         */\n        type: 'provider';\n\n        /**\n         * The ID of the tool. Must follow the format `<provider-name>.<unique-tool-name>`.\n         */\n        id: `${string}.${string}`;\n\n        /**\n         * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.\n         */\n        args: Record<string, unknown>;\n\n        /**\n         * Whether this provider-executed tool supports deferred results.\n         *\n         * When true, the tool result may not be returned in the same turn as the\n         * tool call (e.g., when using programmatic tool calling where a server tool\n         * triggers a client-executed tool, and the server tool's result is deferred\n         * until the client tool is resolved).\n         *\n         * This flag allows the AI SDK to handle tool results that arrive without\n         * a matching tool call in the current response.\n         *\n         * @default false\n         */\n        supportsDeferredResults?: boolean;\n      }\n  );\n\n/**\n * Infer the input type of a tool.\n */\nexport type InferToolInput<TOOL extends Tool> =\n  TOOL extends Tool<infer INPUT, any> ? INPUT : never;\n\n/**\n * Infer the output type of a tool.\n */\nexport type InferToolOutput<TOOL extends Tool> =\n  TOOL extends Tool<any, infer OUTPUT> ? OUTPUT : never;\n\n/**\n * Helper function for inferring the execute args of a tool.\n */\n// Note: overload order is important for auto-completion\nexport function tool<INPUT, OUTPUT>(\n  tool: Tool<INPUT, OUTPUT>,\n): Tool<INPUT, OUTPUT>;\nexport function tool<INPUT>(tool: Tool<INPUT, never>): Tool<INPUT, never>;\nexport function tool<OUTPUT>(tool: Tool<never, OUTPUT>): Tool<never, OUTPUT>;\nexport function tool(tool: Tool<never, never>): Tool<never, never>;\nexport function tool(tool: any): any {\n  return tool;\n}\n\n/**\n * Defines a dynamic tool.\n */\nexport function dynamicTool(tool: {\n  description?: string;\n  title?: string;\n  providerOptions?: ProviderOptions;\n  metadata?: JSONObject;\n  inputSchema: FlexibleSchema<unknown>;\n  execute: ToolExecuteFunction<unknown, unknown>;\n\n  /**\n   * Optional conversion function that maps the tool result to an output that can be used by the language model.\n   *\n   * If not provided, the tool result will be sent as a JSON object.\n   */\n  toModelOutput?: (options: {\n    /**\n     * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n     */\n    toolCallId: string;\n\n    /**\n     * The input of the tool call.\n     */\n    input: unknown;\n\n    /**\n     * The output of the tool call.\n     */\n    output: unknown;\n  }) => ToolResultOutput | PromiseLike<ToolResultOutput>;\n\n  /**\n   * Whether the tool needs approval before it can be executed.\n   */\n  needsApproval?: boolean | ToolNeedsApprovalFunction<unknown>;\n}): Tool<unknown, unknown> & {\n  type: 'dynamic';\n} {\n  return { ...tool, type: 'dynamic' };\n}\n", "import { tool, type Tool, type ToolExecuteFunction } from './types/tool';\nimport type { FlexibleSchema } from './schema';\n\nexport type ProviderToolFactory<INPUT, ARGS extends object> = <OUTPUT>(\n  options: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  },\n) => Tool<INPUT, OUTPUT>;\n\nexport function createProviderToolFactory<INPUT, ARGS extends object>({\n  id,\n  inputSchema,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n}): ProviderToolFactory<INPUT, ARGS> {\n  return <OUTPUT>({\n    execute,\n    outputSchema,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    outputSchema?: FlexibleSchema<OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  }): Tool<INPUT, OUTPUT> =>\n    tool({\n      type: 'provider',\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      execute,\n      needsApproval,\n      toModelOutput,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n    });\n}\n\nexport type ProviderToolFactoryWithOutputSchema<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n> = (\n  options: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  },\n) => Tool<INPUT, OUTPUT>;\n\nexport function createProviderToolFactoryWithOutputSchema<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n>({\n  id,\n  inputSchema,\n  outputSchema,\n  supportsDeferredResults,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n  outputSchema: FlexibleSchema<OUTPUT>;\n  /**\n   * Whether this provider-executed tool supports deferred results.\n   *\n   * When true, the tool result may not be returned in the same turn as the\n   * tool call (e.g., when using programmatic tool calling where a server tool\n   * triggers a client-executed tool, and the server tool's result is deferred\n   * until the client tool is resolved).\n   *\n   * @default false\n   */\n  supportsDeferredResults?: boolean;\n}): ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS> {\n  return ({\n    execute,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  }): Tool<INPUT, OUTPUT> =>\n    tool({\n      type: 'provider',\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      execute,\n      needsApproval,\n      toModelOutput,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n      supportsDeferredResults,\n    });\n}\n", "/**\n * Removes entries from a record where the value is null or undefined.\n * @param record - The input object whose entries may be null or undefined.\n * @returns A new object containing only entries with non-null and non-undefined values.\n */\nexport function removeUndefinedEntries<T>(\n  record: Record<string, T | undefined>,\n): Record<string, T> {\n  return Object.fromEntries(\n    Object.entries(record).filter(([_key, value]) => value != null),\n  ) as Record<string, T>;\n}\n", "import type { MaybePromiseLike } from './maybe-promise-like';\n\nexport type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);\n\n/**\n * Resolves a value that could be a raw value, a Promise, a function returning a value,\n * or a function returning a Promise.\n */\nexport async function resolve<T>(value: Resolvable<T>): Promise<T> {\n  // If it's a function, call it to get the value/promise\n  if (typeof value === 'function') {\n    value = (value as Function)();\n  }\n\n  // Otherwise just resolve whatever we got (value or promise)\n  return Promise.resolve(value as T);\n}\n", "import { APICallError, EmptyResponseBodyError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { parseJSON, safeParseJSON, type ParseResult } from './parse-json';\nimport { parseJsonEventStream } from './parse-json-event-stream';\nimport type { FlexibleSchema } from './schema';\n\nexport type ResponseHandler<RETURN_TYPE> = (options: {\n  url: string;\n  requestBodyValues: unknown;\n  response: Response;\n}) => PromiseLike<{\n  value: RETURN_TYPE;\n  rawValue?: unknown;\n  responseHeaders?: Record<string, string>;\n}>;\n\nexport const createJsonErrorResponseHandler =\n  <T>({\n    errorSchema,\n    errorToMessage,\n    isRetryable,\n  }: {\n    errorSchema: FlexibleSchema<T>;\n    errorToMessage: (error: T) => string;\n    isRetryable?: (response: Response, error?: T) => boolean;\n  }): ResponseHandler<APICallError> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseBody = await response.text();\n    const responseHeaders = extractResponseHeaders(response);\n\n    // Some providers return an empty response body for some errors:\n    if (responseBody.trim() === '') {\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: response.statusText,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          isRetryable: isRetryable?.(response),\n        }),\n      };\n    }\n\n    // resilient parsing in case the response is not JSON or does not match the schema:\n    try {\n      const parsedError = await parseJSON({\n        text: responseBody,\n        schema: errorSchema,\n      });\n\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: errorToMessage(parsedError),\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          data: parsedError,\n          isRetryable: isRetryable?.(response, parsedError),\n        }),\n      };\n    } catch (parseError) {\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: response.statusText,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          isRetryable: isRetryable?.(response),\n        }),\n      };\n    }\n  };\n\nexport const createEventSourceResponseHandler =\n  <T>(\n    chunkSchema: FlexibleSchema<T>,\n  ): ResponseHandler<ReadableStream<ParseResult<T>>> =>\n  async ({ response }: { response: Response }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (response.body == null) {\n      throw new EmptyResponseBodyError({});\n    }\n\n    return {\n      responseHeaders,\n      value: parseJsonEventStream({\n        stream: response.body,\n        schema: chunkSchema,\n      }),\n    };\n  };\n\nexport const createJsonResponseHandler =\n  <T>(responseSchema: FlexibleSchema<T>): ResponseHandler<T> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseBody = await response.text();\n\n    const parsedResult = await safeParseJSON({\n      text: responseBody,\n      schema: responseSchema,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!parsedResult.success) {\n      throw new APICallError({\n        message: 'Invalid JSON response',\n        cause: parsedResult.error,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n        url,\n        requestBodyValues,\n      });\n    }\n\n    return {\n      responseHeaders,\n      value: parsedResult.value,\n      rawValue: parsedResult.rawValue,\n    };\n  };\n\nexport const createBinaryResponseHandler =\n  (): ResponseHandler<Uint8Array> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.body) {\n      throw new APICallError({\n        message: 'Response body is empty',\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody: undefined,\n      });\n    }\n\n    try {\n      const buffer = await response.arrayBuffer();\n      return {\n        responseHeaders,\n        value: new Uint8Array(buffer),\n      };\n    } catch (error) {\n      throw new APICallError({\n        message: 'Failed to read response as array buffer',\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody: undefined,\n        cause: error,\n      });\n    }\n  };\n\nexport const createStatusCodeErrorResponseHandler =\n  (): ResponseHandler<APICallError> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n    const responseBody = await response.text();\n\n    return {\n      responseHeaders,\n      value: new APICallError({\n        message: response.statusText,\n        url,\n        requestBodyValues: requestBodyValues as Record<string, unknown>,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n      }),\n    };\n  };\n", "/**\n * Strips file extension segments from a filename.\n *\n * Examples:\n * - \"report.pdf\" -> \"report\"\n * - \"archive.tar.gz\" -> \"archive\"\n * - \"filename\" -> \"filename\"\n */\nexport function stripFileExtension(filename: string): string {\n  const firstDotIndex = filename.indexOf('.');\n\n  return firstDotIndex === -1 ? filename : filename.slice(0, firstDotIndex);\n}\n", "export function withoutTrailingSlash(url: string | undefined) {\n  return url?.replace(/\\/$/, '');\n}\n", "export function isAsyncIterable<T = any>(obj: any): obj is AsyncIterable<T> {\n  return obj != null && typeof obj[Symbol.asyncIterator] === 'function';\n}\n", "import { isAsyncIterable } from '../is-async-iterable';\nimport type { ToolExecutionOptions, ToolExecuteFunction } from './tool';\n\nexport async function* executeTool<INPUT, OUTPUT>({\n  execute,\n  input,\n  options,\n}: {\n  execute: ToolExecuteFunction<INPUT, OUTPUT>;\n  input: INPUT;\n  options: ToolExecutionOptions;\n}): AsyncGenerator<\n  { type: 'preliminary'; output: OUTPUT } | { type: 'final'; output: OUTPUT }\n> {\n  const result = execute(input, options);\n\n  if (isAsyncIterable(result)) {\n    let lastOutput: OUTPUT | undefined;\n    for await (const output of result) {\n      lastOutput = output;\n      yield { type: 'preliminary', output };\n    }\n    yield { type: 'final', output: lastOutput! };\n  } else {\n    yield { type: 'final', output: await result };\n  }\n}\n", "export * from './combine-headers';\nexport { convertAsyncIteratorToReadableStream } from './convert-async-iterator-to-readable-stream';\nexport {\n  createToolNameMapping,\n  type ToolNameMapping,\n} from './create-tool-name-mapping';\nexport * from './delay';\nexport { DelayedPromise } from './delayed-promise';\nexport * from './extract-response-headers';\nexport { convertImageModelFileToDataUri } from './convert-image-model-file-to-data-uri';\nexport { convertToFormData } from './convert-to-form-data';\nexport { downloadBlob } from './download-blob';\nexport { DownloadError } from './download-error';\nexport {\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n} from './read-response-with-size-limit';\nexport * from './fetch-function';\nexport { createIdGenerator, generateId, type IdGenerator } from './generate-id';\nexport * from './get-error-message';\nexport * from './get-from-api';\nexport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nexport { injectJsonInstructionIntoMessages } from './inject-json-instruction';\nexport * from './is-abort-error';\nexport { isNonNullable } from './is-non-nullable';\nexport { isUrlSupported } from './is-url-supported';\nexport * from './load-api-key';\nexport { loadOptionalSetting } from './load-optional-setting';\nexport { loadSetting } from './load-setting';\nexport { type MaybePromiseLike } from './maybe-promise-like';\nexport { mediaTypeToExtension } from './media-type-to-extension';\nexport { normalizeHeaders } from './normalize-headers';\nexport * from './parse-json';\nexport { parseJsonEventStream } from './parse-json-event-stream';\nexport { parseProviderOptions } from './parse-provider-options';\nexport * from './post-to-api';\nexport {\n  createProviderToolFactory,\n  createProviderToolFactoryWithOutputSchema,\n  type ProviderToolFactory,\n  type ProviderToolFactoryWithOutputSchema,\n} from './provider-tool-factory';\nexport * from './remove-undefined-entries';\nexport * from './resolve';\nexport * from './response-handler';\nexport {\n  asSchema,\n  jsonSchema,\n  lazySchema,\n  zodSchema,\n  type FlexibleSchema,\n  type InferSchema,\n  type LazySchema,\n  type Schema,\n  type ValidationResult,\n} from './schema';\nexport { stripFileExtension } from './strip-file-extension';\nexport * from './uint8-utils';\nexport { validateDownloadUrl } from './validate-download-url';\nexport * from './validate-types';\nexport { VERSION } from './version';\nexport { withUserAgentSuffix } from './with-user-agent-suffix';\nexport * from './without-trailing-slash';\n\n// folder re-exports\nexport * from './types';\n\n// external re-exports\nexport type * from '@standard-schema/spec';\nexport {\n  EventSourceParserStream,\n  type EventSourceMessage,\n} from 'eventsource-parser/stream';\n", "import * as z from \"./v4/classic/external.js\";\nexport * from \"./v4/classic/external.js\";\nexport { z };\nexport default z;\n", "import {\n  loadOptionalSetting,\n  withoutTrailingSlash,\n  withUserAgentSuffix,\n  type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { asGatewayError, GatewayAuthenticationError } from './errors';\nimport {\n  GATEWAY_AUTH_METHOD_HEADER,\n  parseAuthMethod,\n} from './errors/parse-auth-method';\nimport {\n  GatewayFetchMetadata,\n  type GatewayFetchMetadataResponse,\n  type GatewayCreditsResponse,\n} from './gateway-fetch-metadata';\nimport {\n  GatewaySpendReport,\n  type GatewaySpendReportParams,\n  type GatewaySpendReportResponse,\n} from './gateway-spend-report';\nimport {\n  GatewayGenerationInfoFetcher,\n  type GatewayGenerationInfoParams,\n  type GatewayGenerationInfo,\n} from './gateway-generation-info';\nimport { GatewayLanguageModel } from './gateway-language-model';\nimport { GatewayEmbeddingModel } from './gateway-embedding-model';\nimport { GatewayImageModel } from './gateway-image-model';\nimport { GatewayVideoModel } from './gateway-video-model';\nimport { GatewayRerankingModel } from './gateway-reranking-model';\nimport type { GatewayEmbeddingModelId } from './gateway-embedding-model-settings';\nimport type { GatewayImageModelId } from './gateway-image-model-settings';\nimport type { GatewayRerankingModelId } from './gateway-reranking-model-settings';\nimport type { GatewayVideoModelId } from './gateway-video-model-settings';\nimport { gatewayTools } from './gateway-tools';\nimport { getVercelOidcToken, getVercelRequestId } from './vercel-environment';\nimport type { GatewayModelId } from './gateway-language-model-settings';\nimport type {\n  LanguageModelV3,\n  EmbeddingModelV3,\n  ImageModelV3,\n  RerankingModelV3,\n  Experimental_VideoModelV3,\n  ProviderV3,\n} from '@ai-sdk/provider';\nimport { VERSION } from './version';\n\nexport interface GatewayProvider extends ProviderV3 {\n  (modelId: GatewayModelId): LanguageModelV3;\n\n  /**\n   * Creates a model for text generation.\n   */\n  chat(modelId: GatewayModelId): LanguageModelV3;\n\n  /**\n   * Creates a model for text generation.\n   */\n  languageModel(modelId: GatewayModelId): LanguageModelV3;\n\n  /**\n   * Returns available providers and models for use with the remote provider.\n   */\n  getAvailableModels(): Promise<GatewayFetchMetadataResponse>;\n\n  /**\n   * Returns credit information for the authenticated user.\n   */\n  getCredits(): Promise<GatewayCreditsResponse>;\n\n  /**\n   * Returns a spend report with cost, token, and request count data,\n   * aggregated by the specified dimension.\n   */\n  getSpendReport(\n    params: GatewaySpendReportParams,\n  ): Promise<GatewaySpendReportResponse>;\n\n  /**\n   * Returns detailed information about a specific generation by its ID,\n   * including cost, token usage, latency, and provider details.\n   */\n  getGenerationInfo(\n    params: GatewayGenerationInfoParams,\n  ): Promise<GatewayGenerationInfo>;\n\n  /**\n   * Creates a model for generating text embeddings.\n   */\n  embedding(modelId: GatewayEmbeddingModelId): EmbeddingModelV3;\n\n  /**\n   * Creates a model for generating text embeddings.\n   */\n  embeddingModel(modelId: GatewayEmbeddingModelId): EmbeddingModelV3;\n\n  /**\n   * @deprecated Use `embeddingModel` instead.\n   */\n  textEmbeddingModel(modelId: GatewayEmbeddingModelId): EmbeddingModelV3;\n\n  /**\n   * Creates a model for generating images.\n   */\n  image(modelId: GatewayImageModelId): ImageModelV3;\n\n  /**\n   * Creates a model for generating images.\n   */\n  imageModel(modelId: GatewayImageModelId): ImageModelV3;\n\n  /**\n   * Creates a model for generating videos.\n   */\n  video(modelId: GatewayVideoModelId): Experimental_VideoModelV3;\n\n  /**\n   * Creates a model for generating videos.\n   */\n  videoModel(modelId: GatewayVideoModelId): Experimental_VideoModelV3;\n\n  /**\n   * Creates a model for reranking documents.\n   */\n  reranking(modelId: GatewayRerankingModelId): RerankingModelV3;\n\n  /**\n   * Creates a model for reranking documents.\n   */\n  rerankingModel(modelId: GatewayRerankingModelId): RerankingModelV3;\n\n  /**\n   * Gateway-specific tools executed server-side.\n   */\n  tools: typeof gatewayTools;\n}\n\nexport interface GatewayProviderSettings {\n  /**\n   * The base URL prefix for API calls. Defaults to `https://ai-gateway.vercel.sh/v1/ai`.\n   */\n  baseURL?: string;\n\n  /**\n   * API key that is being sent using the `Authorization` header.\n   */\n  apiKey?: string;\n\n  /**\n   * Custom headers to include in the requests.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Custom fetch implementation. You can use it as a middleware to intercept requests,\n   * or to provide a custom fetch implementation for e.g. testing.\n   */\n  fetch?: FetchFunction;\n\n  /**\n   * How frequently to refresh the metadata cache in milliseconds.\n   */\n  metadataCacheRefreshMillis?: number;\n\n  /**\n   * @internal For testing purposes only\n   */\n  _internal?: {\n    currentDate?: () => Date;\n  };\n}\n\nconst AI_GATEWAY_PROTOCOL_VERSION = '0.0.1';\n\n/**\n * Create a remote provider instance.\n */\nexport function createGatewayProvider(\n  options: GatewayProviderSettings = {},\n): GatewayProvider {\n  let pendingMetadata: Promise<GatewayFetchMetadataResponse> | null = null;\n  let metadataCache: GatewayFetchMetadataResponse | null = null;\n  const cacheRefreshMillis =\n    options.metadataCacheRefreshMillis ?? 1000 * 60 * 5;\n  let lastFetchTime = 0;\n\n  const baseURL =\n    withoutTrailingSlash(options.baseURL) ??\n    'https://ai-gateway.vercel.sh/v3/ai';\n\n  const getHeaders = async () => {\n    try {\n      const auth = await getGatewayAuthToken(options);\n      return withUserAgentSuffix(\n        {\n          Authorization: `Bearer ${auth.token}`,\n          'ai-gateway-protocol-version': AI_GATEWAY_PROTOCOL_VERSION,\n          [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,\n          ...options.headers,\n        },\n        `ai-sdk/gateway/${VERSION}`,\n      );\n    } catch (error) {\n      throw GatewayAuthenticationError.createContextualError({\n        apiKeyProvided: false,\n        oidcTokenProvided: false,\n        statusCode: 401,\n        cause: error,\n      });\n    }\n  };\n\n  const createO11yHeaders = () => {\n    const deploymentId = loadOptionalSetting({\n      settingValue: undefined,\n      environmentVariableName: 'VERCEL_DEPLOYMENT_ID',\n    });\n    const environment = loadOptionalSetting({\n      settingValue: undefined,\n      environmentVariableName: 'VERCEL_ENV',\n    });\n    const region = loadOptionalSetting({\n      settingValue: undefined,\n      environmentVariableName: 'VERCEL_REGION',\n    });\n    const projectId = loadOptionalSetting({\n      settingValue: undefined,\n      environmentVariableName: 'VERCEL_PROJECT_ID',\n    });\n\n    return async () => {\n      const requestId = await getVercelRequestId();\n      return {\n        ...(deploymentId && { 'ai-o11y-deployment-id': deploymentId }),\n        ...(environment && { 'ai-o11y-environment': environment }),\n        ...(region && { 'ai-o11y-region': region }),\n        ...(requestId && { 'ai-o11y-request-id': requestId }),\n        ...(projectId && { 'ai-o11y-project-id': projectId }),\n      };\n    };\n  };\n\n  const createLanguageModel = (modelId: GatewayModelId) => {\n    return new GatewayLanguageModel(modelId, {\n      provider: 'gateway',\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders(),\n    });\n  };\n\n  const getAvailableModels = async () => {\n    const now = options._internal?.currentDate?.().getTime() ?? Date.now();\n    if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {\n      lastFetchTime = now;\n\n      pendingMetadata = new GatewayFetchMetadata({\n        baseURL,\n        headers: getHeaders,\n        fetch: options.fetch,\n      })\n        .getAvailableModels()\n        .then(metadata => {\n          metadataCache = metadata;\n          return metadata;\n        })\n        .catch(async (error: unknown) => {\n          throw await asGatewayError(\n            error,\n            await parseAuthMethod(await getHeaders()),\n          );\n        });\n    }\n\n    return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;\n  };\n\n  const getCredits = async () => {\n    return new GatewayFetchMetadata({\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n    })\n      .getCredits()\n      .catch(async (error: unknown) => {\n        throw await asGatewayError(\n          error,\n          await parseAuthMethod(await getHeaders()),\n        );\n      });\n  };\n\n  const getSpendReport = async (params: GatewaySpendReportParams) => {\n    return new GatewaySpendReport({\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n    })\n      .getSpendReport(params)\n      .catch(async (error: unknown) => {\n        throw await asGatewayError(\n          error,\n          await parseAuthMethod(await getHeaders()),\n        );\n      });\n  };\n\n  const getGenerationInfo = async (params: GatewayGenerationInfoParams) => {\n    return new GatewayGenerationInfoFetcher({\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n    })\n      .getGenerationInfo(params)\n      .catch(async (error: unknown) => {\n        throw await asGatewayError(\n          error,\n          await parseAuthMethod(await getHeaders()),\n        );\n      });\n  };\n\n  const provider = function (modelId: GatewayModelId) {\n    if (new.target) {\n      throw new Error(\n        'The Gateway Provider model function cannot be called with the new keyword.',\n      );\n    }\n\n    return createLanguageModel(modelId);\n  };\n\n  provider.specificationVersion = 'v3' as const;\n  provider.getAvailableModels = getAvailableModels;\n  provider.getCredits = getCredits;\n  provider.getSpendReport = getSpendReport;\n  provider.getGenerationInfo = getGenerationInfo;\n  provider.imageModel = (modelId: GatewayImageModelId) => {\n    return new GatewayImageModel(modelId, {\n      provider: 'gateway',\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders(),\n    });\n  };\n  provider.languageModel = createLanguageModel;\n  const createEmbeddingModel = (modelId: GatewayEmbeddingModelId) => {\n    return new GatewayEmbeddingModel(modelId, {\n      provider: 'gateway',\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders(),\n    });\n  };\n  provider.embeddingModel = createEmbeddingModel;\n  provider.textEmbeddingModel = createEmbeddingModel;\n  provider.videoModel = (modelId: GatewayVideoModelId) => {\n    return new GatewayVideoModel(modelId, {\n      provider: 'gateway',\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders(),\n    });\n  };\n  const createRerankingModel = (modelId: GatewayRerankingModelId) => {\n    return new GatewayRerankingModel(modelId, {\n      provider: 'gateway',\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders(),\n    });\n  };\n  provider.rerankingModel = createRerankingModel;\n  provider.reranking = createRerankingModel;\n  provider.chat = provider.languageModel;\n  provider.embedding = provider.embeddingModel;\n  provider.image = provider.imageModel;\n  provider.video = provider.videoModel;\n  provider.tools = gatewayTools;\n  return provider;\n}\n\nexport const gateway = createGatewayProvider();\n\nexport async function getGatewayAuthToken(\n  options: GatewayProviderSettings,\n): Promise<{ token: string; authMethod: 'api-key' | 'oidc' }> {\n  const apiKey = loadOptionalSetting({\n    settingValue: options.apiKey,\n    environmentVariableName: 'AI_GATEWAY_API_KEY',\n  });\n\n  if (apiKey) {\n    return {\n      token: apiKey,\n      authMethod: 'api-key',\n    };\n  }\n\n  const oidcToken = await getVercelOidcToken();\n  return {\n    token: oidcToken,\n    authMethod: 'oidc',\n  };\n}\n", "import { APICallError } from '@ai-sdk/provider';\nimport { createGatewayErrorFromResponse } from './create-gateway-error';\nimport { extractApiCallResponse } from './extract-api-call-response';\nimport { GatewayError } from './gateway-error';\nimport { GatewayTimeoutError } from './gateway-timeout-error';\n\n/**\n * Checks if an error is a timeout error from undici.\n * Only checks undici-specific error codes to avoid false positives.\n */\nfunction isTimeoutError(error: unknown): boolean {\n  if (!(error instanceof Error)) {\n    return false;\n  }\n\n  // Check for undici-specific timeout error codes\n  const errorCode = (error as any).code;\n  if (typeof errorCode === 'string') {\n    const undiciTimeoutCodes = [\n      'UND_ERR_HEADERS_TIMEOUT',\n      'UND_ERR_BODY_TIMEOUT',\n      'UND_ERR_CONNECT_TIMEOUT',\n    ];\n    return undiciTimeoutCodes.includes(errorCode);\n  }\n\n  return false;\n}\n\nexport async function asGatewayError(\n  error: unknown,\n  authMethod?: 'api-key' | 'oidc',\n) {\n  if (GatewayError.isInstance(error)) {\n    return error;\n  }\n\n  // Check if this is a timeout error (or has a timeout error in the cause chain)\n  if (isTimeoutError(error)) {\n    return GatewayTimeoutError.createTimeoutError({\n      originalMessage: error instanceof Error ? error.message : 'Unknown error',\n      cause: error,\n    });\n  }\n\n  // Check if this is an APICallError caused by a timeout\n  if (APICallError.isInstance(error)) {\n    // Check if the cause is a timeout error\n    if (error.cause && isTimeoutError(error.cause)) {\n      return GatewayTimeoutError.createTimeoutError({\n        originalMessage: error.message,\n        cause: error,\n      });\n    }\n\n    return await createGatewayErrorFromResponse({\n      response: extractApiCallResponse(error),\n      statusCode: error.statusCode ?? 500,\n      defaultMessage: 'Gateway request failed',\n      cause: error,\n      authMethod,\n    });\n  }\n\n  return await createGatewayErrorFromResponse({\n    response: {},\n    statusCode: 500,\n    defaultMessage:\n      error instanceof Error\n        ? `Gateway request failed: ${error.message}`\n        : 'Unknown Gateway error',\n    cause: error,\n    authMethod,\n  });\n}\n", "import { z } from 'zod/v4';\nimport type { GatewayError } from './gateway-error';\nimport { GatewayAuthenticationError } from './gateway-authentication-error';\nimport { GatewayInvalidRequestError } from './gateway-invalid-request-error';\nimport { GatewayRateLimitError } from './gateway-rate-limit-error';\nimport {\n  GatewayModelNotFoundError,\n  modelNotFoundParamSchema,\n} from './gateway-model-not-found-error';\nimport { GatewayInternalServerError } from './gateway-internal-server-error';\nimport { GatewayResponseError } from './gateway-response-error';\nimport {\n  lazySchema,\n  safeValidateTypes,\n  validateTypes,\n  zodSchema,\n  type InferSchema,\n} from '@ai-sdk/provider-utils';\n\nexport async function createGatewayErrorFromResponse({\n  response,\n  statusCode,\n  defaultMessage = 'Gateway request failed',\n  cause,\n  authMethod,\n}: {\n  response: unknown;\n  statusCode: number;\n  defaultMessage?: string;\n  cause?: unknown;\n  authMethod?: 'api-key' | 'oidc';\n}): Promise<GatewayError> {\n  const parseResult = await safeValidateTypes({\n    value: response,\n    schema: gatewayErrorResponseSchema,\n  });\n\n  if (!parseResult.success) {\n    // Try to extract generationId even if validation failed\n    const rawGenerationId =\n      typeof response === 'object' &&\n      response !== null &&\n      'generationId' in response\n        ? (response as { generationId?: string }).generationId\n        : undefined;\n\n    return new GatewayResponseError({\n      message: `Invalid error response format: ${defaultMessage}`,\n      statusCode,\n      response,\n      validationError: parseResult.error,\n      cause,\n      generationId: rawGenerationId,\n    });\n  }\n\n  const validatedResponse: GatewayErrorResponse = parseResult.value;\n  const errorType = validatedResponse.error.type;\n  const message = validatedResponse.error.message;\n  const generationId = validatedResponse.generationId ?? undefined;\n\n  switch (errorType) {\n    case 'authentication_error':\n      return GatewayAuthenticationError.createContextualError({\n        apiKeyProvided: authMethod === 'api-key',\n        oidcTokenProvided: authMethod === 'oidc',\n        statusCode,\n        cause,\n        generationId,\n      });\n    case 'invalid_request_error':\n      return new GatewayInvalidRequestError({\n        message,\n        statusCode,\n        cause,\n        generationId,\n      });\n    case 'rate_limit_exceeded':\n      return new GatewayRateLimitError({\n        message,\n        statusCode,\n        cause,\n        generationId,\n      });\n    case 'model_not_found': {\n      const modelResult = await safeValidateTypes({\n        value: validatedResponse.error.param,\n        schema: modelNotFoundParamSchema,\n      });\n\n      return new GatewayModelNotFoundError({\n        message,\n        statusCode,\n        modelId: modelResult.success ? modelResult.value.modelId : undefined,\n        cause,\n        generationId,\n      });\n    }\n    case 'internal_server_error':\n      return new GatewayInternalServerError({\n        message,\n        statusCode,\n        cause,\n        generationId,\n      });\n    default:\n      return new GatewayInternalServerError({\n        message,\n        statusCode,\n        cause,\n        generationId,\n      });\n  }\n}\n\nconst gatewayErrorResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      error: z.object({\n        message: z.string(),\n        type: z.string().nullish(),\n        param: z.unknown().nullish(),\n        code: z.union([z.string(), z.number()]).nullish(),\n      }),\n      generationId: z.string().nullish(),\n    }),\n  ),\n);\n\nexport type GatewayErrorResponse = InferSchema<\n  typeof gatewayErrorResponseSchema\n>;\n", "const marker = 'vercel.ai.gateway.error';\nconst symbol = Symbol.for(marker);\n\nexport abstract class GatewayError extends Error {\n  private readonly [symbol] = true; // used in isInstance\n\n  abstract readonly name: string;\n  abstract readonly type: string;\n  readonly statusCode: number;\n  readonly cause?: unknown;\n  readonly generationId?: string;\n  readonly isRetryable: boolean;\n\n  constructor({\n    message,\n    statusCode = 500,\n    cause,\n    generationId,\n    isRetryable = statusCode != null &&\n      (statusCode === 408 || // request timeout\n        statusCode === 409 || // conflict\n        statusCode === 429 || // too many requests\n        statusCode >= 500), // server error\n  }: {\n    message: string;\n    statusCode?: number;\n    cause?: unknown;\n    generationId?: string;\n    isRetryable?: boolean;\n  }) {\n    super(generationId ? `${message} [${generationId}]` : message);\n    this.statusCode = statusCode;\n    this.cause = cause;\n    this.generationId = generationId;\n    this.isRetryable = isRetryable;\n  }\n\n  /**\n   * Checks if the given error is a Gateway Error.\n   * @param {unknown} error - The error to check.\n   * @returns {boolean} True if the error is a Gateway Error, false otherwise.\n   */\n  static isInstance(error: unknown): error is GatewayError {\n    return GatewayError.hasMarker(error);\n  }\n\n  static hasMarker(error: unknown): error is GatewayError {\n    return (\n      typeof error === 'object' &&\n      error !== null &&\n      symbol in error &&\n      (error as any)[symbol] === true\n    );\n  }\n}\n", "import { GatewayError } from './gateway-error';\n\nconst name = 'GatewayAuthenticationError';\nconst marker = `vercel.ai.gateway.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Authentication failed - invalid API key or OIDC token\n */\nexport class GatewayAuthenticationError extends GatewayError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly name = name;\n  readonly type = 'authentication_error';\n\n  constructor({\n    message = 'Authentication failed',\n    statusCode = 401,\n    cause,\n    generationId,\n  }: {\n    message?: string;\n    statusCode?: number;\n    cause?: unknown;\n    generationId?: string;\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n  }\n\n  static isInstance(error: unknown): error is GatewayAuthenticationError {\n    return GatewayError.hasMarker(error) && symbol in error;\n  }\n\n  /**\n   * Creates a contextual error message when authentication fails\n   */\n  static createContextualError({\n    apiKeyProvided,\n    oidcTokenProvided,\n    message = 'Authentication failed',\n    statusCode = 401,\n    cause,\n    generationId,\n  }: {\n    apiKeyProvided: boolean;\n    oidcTokenProvided: boolean;\n    message?: string;\n    statusCode?: number;\n    cause?: unknown;\n    generationId?: string;\n  }): GatewayAuthenticationError {\n    let contextualMessage: string;\n\n    if (apiKeyProvided) {\n      contextualMessage = `AI Gateway authentication failed: Invalid API key.\n\nCreate a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\n\nProvide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;\n    } else if (oidcTokenProvided) {\n      contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.\n\nRun 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.\n\nAlternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;\n    } else {\n      contextualMessage = `AI Gateway authentication failed: No authentication provided.\n\nOption 1 - API key:\nCreate an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\nProvide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.\n\nOption 2 - OIDC token:\nRun 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;\n    }\n\n    return new GatewayAuthenticationError({\n      message: contextualMessage,\n      statusCode,\n      cause,\n      generationId,\n    });\n  }\n}\n", "import { GatewayError } from './gateway-error';\n\nconst name = 'GatewayInvalidRequestError';\nconst marker = `vercel.ai.gateway.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Invalid request - missing headers, malformed data, etc.\n */\nexport class GatewayInvalidRequestError extends GatewayError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly name = name;\n  readonly type = 'invalid_request_error';\n\n  constructor({\n    message = 'Invalid request',\n    statusCode = 400,\n    cause,\n    generationId,\n  }: {\n    message?: string;\n    statusCode?: number;\n    cause?: unknown;\n    generationId?: string;\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n  }\n\n  static isInstance(error: unknown): error is GatewayInvalidRequestError {\n    return GatewayError.hasMarker(error) && symbol in error;\n  }\n}\n", "import { GatewayError } from './gateway-error';\n\nconst name = 'GatewayRateLimitError';\nconst marker = `vercel.ai.gateway.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Rate limit exceeded.\n */\nexport class GatewayRateLimitError extends GatewayError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly name = name;\n  readonly type = 'rate_limit_exceeded';\n\n  constructor({\n    message = 'Rate limit exceeded',\n    statusCode = 429,\n    cause,\n    generationId,\n  }: {\n    message?: string;\n    statusCode?: number;\n    cause?: unknown;\n    generationId?: string;\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n  }\n\n  static isInstance(error: unknown): error is GatewayRateLimitError {\n    return GatewayError.hasMarker(error) && symbol in error;\n  }\n}\n", "import { z } from 'zod/v4';\nimport { GatewayError } from './gateway-error';\nimport { lazySchema, zodSchema } from '@ai-sdk/provider-utils';\n\nconst name = 'GatewayModelNotFoundError';\nconst marker = `vercel.ai.gateway.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport const modelNotFoundParamSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      modelId: z.string(),\n    }),\n  ),\n);\n\n/**\n * Model not found or not available\n */\nexport class GatewayModelNotFoundError extends GatewayError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly name = name;\n  readonly type = 'model_not_found';\n  readonly modelId?: string;\n\n  constructor({\n    message = 'Model not found',\n    statusCode = 404,\n    modelId,\n    cause,\n    generationId,\n  }: {\n    message?: string;\n    statusCode?: number;\n    modelId?: string;\n    cause?: unknown;\n    generationId?: string;\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this.modelId = modelId;\n  }\n\n  static isInstance(error: unknown): error is GatewayModelNotFoundError {\n    return GatewayError.hasMarker(error) && symbol in error;\n  }\n}\n", "import { GatewayError } from './gateway-error';\n\nconst name = 'GatewayInternalServerError';\nconst marker = `vercel.ai.gateway.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Internal server error from the Gateway\n */\nexport class GatewayInternalServerError extends GatewayError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly name = name;\n  readonly type = 'internal_server_error';\n\n  constructor({\n    message = 'Internal server error',\n    statusCode = 500,\n    cause,\n    generationId,\n  }: {\n    message?: string;\n    statusCode?: number;\n    cause?: unknown;\n    generationId?: string;\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n  }\n\n  static isInstance(error: unknown): error is GatewayInternalServerError {\n    return GatewayError.hasMarker(error) && symbol in error;\n  }\n}\n", "import type { TypeValidationError } from '@ai-sdk/provider';\nimport { GatewayError } from './gateway-error';\n\nconst name = 'GatewayResponseError';\nconst marker = `vercel.ai.gateway.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Gateway response parsing error\n */\nexport class GatewayResponseError extends GatewayError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly name = name;\n  readonly type = 'response_error';\n  readonly response?: unknown;\n  readonly validationError?: TypeValidationError;\n\n  constructor({\n    message = 'Invalid response from Gateway',\n    statusCode = 502,\n    response,\n    validationError,\n    cause,\n    generationId,\n  }: {\n    message?: string;\n    statusCode?: number;\n    response?: unknown;\n    validationError?: TypeValidationError;\n    cause?: unknown;\n    generationId?: string;\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this.response = response;\n    this.validationError = validationError;\n  }\n\n  static isInstance(error: unknown): error is GatewayResponseError {\n    return GatewayError.hasMarker(error) && symbol in error;\n  }\n}\n", "import type { APICallError } from '@ai-sdk/provider';\n\nexport function extractApiCallResponse(error: APICallError): unknown {\n  if (error.data !== undefined) {\n    return error.data;\n  }\n  if (error.responseBody != null) {\n    try {\n      return JSON.parse(error.responseBody);\n    } catch {\n      return error.responseBody;\n    }\n  }\n  return {};\n}\n", "import { GatewayError } from './gateway-error';\n\nconst name = 'GatewayTimeoutError';\nconst marker = `vercel.ai.gateway.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Client request timed out before receiving a response.\n */\nexport class GatewayTimeoutError extends GatewayError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly name = name;\n  readonly type = 'timeout_error';\n\n  constructor({\n    message = 'Request timed out',\n    statusCode = 408,\n    cause,\n    generationId,\n  }: {\n    message?: string;\n    statusCode?: number;\n    cause?: unknown;\n    generationId?: string;\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n  }\n\n  static isInstance(error: unknown): error is GatewayTimeoutError {\n    return GatewayError.hasMarker(error) && symbol in error;\n  }\n\n  /**\n   * Creates a helpful timeout error message with troubleshooting guidance\n   */\n  static createTimeoutError({\n    originalMessage,\n    statusCode = 408,\n    cause,\n    generationId,\n  }: {\n    originalMessage: string;\n    statusCode?: number;\n    cause?: unknown;\n    generationId?: string;\n  }): GatewayTimeoutError {\n    const message = `Gateway request timed out: ${originalMessage}\n\n    This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;\n\n    return new GatewayTimeoutError({\n      message,\n      statusCode,\n      cause,\n      generationId,\n    });\n  }\n}\n", "import { z } from 'zod/v4';\nimport {\n  lazySchema,\n  safeValidateTypes,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\n\nexport const GATEWAY_AUTH_METHOD_HEADER = 'ai-gateway-auth-method' as const;\n\nexport async function parseAuthMethod(\n  headers: Record<string, string | undefined>,\n) {\n  const result = await safeValidateTypes({\n    value: headers[GATEWAY_AUTH_METHOD_HEADER],\n    schema: gatewayAuthMethodSchema,\n  });\n\n  return result.success ? result.value : undefined;\n}\n\nconst gatewayAuthMethodSchema = lazySchema(() =>\n  zodSchema(z.union([z.literal('api-key'), z.literal('oidc')])),\n);\n", "import {\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  getFromApi,\n  lazySchema,\n  resolve,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { asGatewayError } from './errors';\nimport type { GatewayConfig } from './gateway-config';\nimport {\n  KNOWN_MODEL_TYPES,\n  type GatewayLanguageModelEntry,\n  type KnownModelType,\n} from './gateway-model-entry';\n\ntype GatewayFetchMetadataConfig = GatewayConfig;\n\nexport interface GatewayFetchMetadataResponse {\n  models: GatewayLanguageModelEntry[];\n}\n\nexport interface GatewayCreditsResponse {\n  /** The remaining gateway credit balance available for API usage */\n  balance: string;\n  /** The total amount of gateway credits that have been consumed */\n  totalUsed: string;\n}\n\nexport class GatewayFetchMetadata {\n  constructor(private readonly config: GatewayFetchMetadataConfig) {}\n\n  async getAvailableModels(): Promise<GatewayFetchMetadataResponse> {\n    try {\n      const { value } = await getFromApi({\n        url: `${this.config.baseURL}/config`,\n        headers: await resolve(this.config.headers()),\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewayAvailableModelsResponseSchema,\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        fetch: this.config.fetch,\n      });\n\n      return value;\n    } catch (error) {\n      throw await asGatewayError(error);\n    }\n  }\n\n  async getCredits(): Promise<GatewayCreditsResponse> {\n    try {\n      const baseUrl = new URL(this.config.baseURL);\n\n      const { value } = await getFromApi({\n        url: `${baseUrl.origin}/v1/credits`,\n        headers: await resolve(this.config.headers()),\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewayCreditsResponseSchema,\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        fetch: this.config.fetch,\n      });\n\n      return value;\n    } catch (error) {\n      throw await asGatewayError(error);\n    }\n  }\n}\n\nconst gatewayAvailableModelsResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      models: z\n        .array(\n          z.object({\n            id: z.string(),\n            name: z.string(),\n            description: z.string().nullish(),\n            pricing: z\n              .object({\n                input: z.string(),\n                output: z.string(),\n                input_cache_read: z.string().nullish(),\n                input_cache_write: z.string().nullish(),\n              })\n              .transform(\n                ({ input, output, input_cache_read, input_cache_write }) => ({\n                  input,\n                  output,\n                  ...(input_cache_read\n                    ? { cachedInputTokens: input_cache_read }\n                    : {}),\n                  ...(input_cache_write\n                    ? { cacheCreationInputTokens: input_cache_write }\n                    : {}),\n                }),\n              )\n              .nullish(),\n            specification: z.object({\n              specificationVersion: z.literal('v3'),\n              provider: z.string(),\n              modelId: z.string(),\n            }),\n            modelType: z.string().nullish(),\n          }),\n        )\n        .transform(models =>\n          models.filter(\n            (m): m is typeof m & { modelType?: KnownModelType | null } =>\n              m.modelType == null ||\n              KNOWN_MODEL_TYPES.includes(m.modelType as KnownModelType),\n          ),\n        ),\n    }),\n  ),\n);\n\nconst gatewayCreditsResponseSchema = lazySchema(() =>\n  zodSchema(\n    z\n      .object({\n        balance: z.string(),\n        total_used: z.string(),\n      })\n      .transform(({ balance, total_used }) => ({\n        balance,\n        totalUsed: total_used,\n      })),\n  ),\n);\n", "import type { LanguageModelV3 } from '@ai-sdk/provider';\n\nexport const KNOWN_MODEL_TYPES = [\n  'embedding',\n  'image',\n  'language',\n  'reranking',\n  'video',\n] as const;\n\nexport type KnownModelType = (typeof KNOWN_MODEL_TYPES)[number];\n\nexport interface GatewayLanguageModelEntry {\n  /**\n   * The model id used by the remote provider in model settings and for specifying the\n   * intended model for text generation.\n   */\n  id: string;\n\n  /**\n   * The display name of the model for presentation in user-facing contexts.\n   */\n  name: string;\n\n  /**\n   * Optional description of the model.\n   */\n  description?: string | null;\n\n  /**\n   * Optional pricing information for the model.\n   */\n  pricing?: {\n    /**\n     * Cost per input token in USD.\n     */\n    input: string;\n    /**\n     * Cost per output token in USD.\n     */\n    output: string;\n    /**\n     * Cost per cached input token in USD.\n     * Only present for providers/models that support prompt caching.\n     */\n    cachedInputTokens?: string;\n    /**\n     * Cost per input token to create/write cache entries in USD.\n     * Only present for providers/models that support prompt caching.\n     */\n    cacheCreationInputTokens?: string;\n  } | null;\n\n  /**\n   * Additional AI SDK language model specifications for the model.\n   */\n  specification: GatewayLanguageModelSpecification;\n\n  /**\n   * Optional field to differentiate between model types.\n   */\n  modelType?: KnownModelType | null;\n}\n\nexport type GatewayLanguageModelSpecification = Pick<\n  LanguageModelV3,\n  'specificationVersion' | 'provider' | 'modelId'\n>;\n", "import {\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  getFromApi,\n  lazySchema,\n  resolve,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { asGatewayError } from './errors';\nimport type { GatewayConfig } from './gateway-config';\n\nexport interface GatewaySpendReportParams {\n  /** Start date in YYYY-MM-DD format (inclusive) */\n  startDate: string;\n  /** End date in YYYY-MM-DD format (inclusive) */\n  endDate: string;\n  /** Primary aggregation dimension. Defaults to 'day'. */\n  groupBy?: 'day' | 'user' | 'model' | 'tag' | 'provider' | 'credential_type';\n  /** Time granularity when groupBy is 'day'. */\n  datePart?: 'day' | 'hour';\n  /** Filter to a specific user's spend. */\n  userId?: string;\n  /** Filter to a specific model (e.g. 'anthropic/claude-sonnet-4.5'). */\n  model?: string;\n  /** Filter to a specific provider (e.g. 'anthropic'). */\n  provider?: string;\n  /** Filter to BYOK or system credentials. */\n  credentialType?: 'byok' | 'system';\n  /** Filter to requests with these tags. */\n  tags?: string[];\n}\n\nexport interface GatewaySpendReportRow {\n  /** Date string (present when groupBy is 'day') */\n  day?: string;\n  /** Hour timestamp (present when groupBy is 'day' and datePart is 'hour') */\n  hour?: string;\n  /** User identifier (present when groupBy is 'user') */\n  user?: string;\n  /** Model identifier (present when groupBy is 'model') */\n  model?: string;\n  /** Tag value (present when groupBy is 'tag') */\n  tag?: string;\n  /** Provider name (present when groupBy is 'provider') */\n  provider?: string;\n  /** Credential type (present when groupBy is 'credential_type') */\n  credentialType?: 'byok' | 'system';\n\n  /** Total cost in USD */\n  totalCost: number;\n  /** Market cost in USD */\n  marketCost?: number;\n  /** Number of input tokens */\n  inputTokens?: number;\n  /** Number of output tokens */\n  outputTokens?: number;\n  /** Number of cached input tokens */\n  cachedInputTokens?: number;\n  /** Number of cache creation input tokens */\n  cacheCreationInputTokens?: number;\n  /** Number of reasoning tokens */\n  reasoningTokens?: number;\n  /** Number of requests */\n  requestCount?: number;\n}\n\nexport interface GatewaySpendReportResponse {\n  results: GatewaySpendReportRow[];\n}\n\nexport class GatewaySpendReport {\n  constructor(private readonly config: GatewayConfig) {}\n\n  async getSpendReport(\n    params: GatewaySpendReportParams,\n  ): Promise<GatewaySpendReportResponse> {\n    try {\n      const baseUrl = new URL(this.config.baseURL);\n\n      const searchParams = new URLSearchParams();\n      searchParams.set('start_date', params.startDate);\n      searchParams.set('end_date', params.endDate);\n\n      if (params.groupBy) {\n        searchParams.set('group_by', params.groupBy);\n      }\n      if (params.datePart) {\n        searchParams.set('date_part', params.datePart);\n      }\n      if (params.userId) {\n        searchParams.set('user_id', params.userId);\n      }\n      if (params.model) {\n        searchParams.set('model', params.model);\n      }\n      if (params.provider) {\n        searchParams.set('provider', params.provider);\n      }\n      if (params.credentialType) {\n        searchParams.set('credential_type', params.credentialType);\n      }\n      if (params.tags && params.tags.length > 0) {\n        searchParams.set('tags', params.tags.join(','));\n      }\n\n      const { value } = await getFromApi({\n        url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,\n        headers: await resolve(this.config.headers()),\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewaySpendReportResponseSchema,\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        fetch: this.config.fetch,\n      });\n\n      return value;\n    } catch (error) {\n      throw await asGatewayError(error);\n    }\n  }\n}\n\nconst gatewaySpendReportResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      results: z.array(\n        z\n          .object({\n            day: z.string().optional(),\n            hour: z.string().optional(),\n            user: z.string().optional(),\n            model: z.string().optional(),\n            tag: z.string().optional(),\n            provider: z.string().optional(),\n            credential_type: z.enum(['byok', 'system']).optional(),\n            total_cost: z.number(),\n            market_cost: z.number().optional(),\n            input_tokens: z.number().optional(),\n            output_tokens: z.number().optional(),\n            cached_input_tokens: z.number().optional(),\n            cache_creation_input_tokens: z.number().optional(),\n            reasoning_tokens: z.number().optional(),\n            request_count: z.number().optional(),\n          })\n          .transform(\n            ({\n              credential_type,\n              total_cost,\n              market_cost,\n              input_tokens,\n              output_tokens,\n              cached_input_tokens,\n              cache_creation_input_tokens,\n              reasoning_tokens,\n              request_count,\n              ...rest\n            }) => ({\n              ...rest,\n              ...(credential_type !== undefined\n                ? { credentialType: credential_type }\n                : {}),\n              totalCost: total_cost,\n              ...(market_cost !== undefined ? { marketCost: market_cost } : {}),\n              ...(input_tokens !== undefined\n                ? { inputTokens: input_tokens }\n                : {}),\n              ...(output_tokens !== undefined\n                ? { outputTokens: output_tokens }\n                : {}),\n              ...(cached_input_tokens !== undefined\n                ? { cachedInputTokens: cached_input_tokens }\n                : {}),\n              ...(cache_creation_input_tokens !== undefined\n                ? { cacheCreationInputTokens: cache_creation_input_tokens }\n                : {}),\n              ...(reasoning_tokens !== undefined\n                ? { reasoningTokens: reasoning_tokens }\n                : {}),\n              ...(request_count !== undefined\n                ? { requestCount: request_count }\n                : {}),\n            }),\n          ),\n      ),\n    }),\n  ),\n);\n", "import {\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  getFromApi,\n  lazySchema,\n  resolve,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { asGatewayError } from './errors';\nimport type { GatewayConfig } from './gateway-config';\n\nexport interface GatewayGenerationInfoParams {\n  /** The generation ID to look up (format: gen_<ulid>) */\n  id: string;\n}\n\nexport interface GatewayGenerationInfo {\n  /** The generation ID */\n  id: string;\n  /** Total cost in USD */\n  totalCost: number;\n  /** Upstream inference cost in USD (BYOK only) */\n  upstreamInferenceCost: number;\n  /** Usage cost in USD (same as totalCost) */\n  usage: number;\n  /** ISO 8601 timestamp when the generation was created */\n  createdAt: string;\n  /** Model identifier */\n  model: string;\n  /** Whether BYOK credentials were used */\n  isByok: boolean;\n  /** Provider that served this generation */\n  providerName: string;\n  /** Whether streaming was used */\n  streamed: boolean;\n  /** Finish reason (e.g. 'stop') */\n  finishReason: string;\n  /** Time to first token in milliseconds */\n  latency: number;\n  /** Total generation time in milliseconds */\n  generationTime: number;\n  /** Number of prompt tokens */\n  promptTokens: number;\n  /** Number of completion tokens */\n  completionTokens: number;\n  /** Reasoning tokens used */\n  reasoningTokens: number;\n  /** Cached tokens used */\n  cachedTokens: number;\n  /** Cache creation input tokens */\n  cacheCreationTokens: number;\n  /** Billable web search calls */\n  billableWebSearchCalls: number;\n}\n\nexport class GatewayGenerationInfoFetcher {\n  constructor(private readonly config: GatewayConfig) {}\n\n  async getGenerationInfo(\n    params: GatewayGenerationInfoParams,\n  ): Promise<GatewayGenerationInfo> {\n    try {\n      const baseUrl = new URL(this.config.baseURL);\n\n      const { value } = await getFromApi({\n        url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,\n        headers: await resolve(this.config.headers()),\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewayGenerationInfoResponseSchema,\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        fetch: this.config.fetch,\n      });\n\n      return value;\n    } catch (error) {\n      throw await asGatewayError(error);\n    }\n  }\n}\n\nconst gatewayGenerationInfoResponseSchema = lazySchema(() =>\n  zodSchema(\n    z\n      .object({\n        data: z\n          .object({\n            id: z.string(),\n            total_cost: z.number(),\n            upstream_inference_cost: z.number(),\n            usage: z.number(),\n            created_at: z.string(),\n            model: z.string(),\n            is_byok: z.boolean(),\n            provider_name: z.string(),\n            streamed: z.boolean(),\n            finish_reason: z.string(),\n            latency: z.number(),\n            generation_time: z.number(),\n            native_tokens_prompt: z.number(),\n            native_tokens_completion: z.number(),\n            native_tokens_reasoning: z.number(),\n            native_tokens_cached: z.number(),\n            native_tokens_cache_creation: z.number(),\n            billable_web_search_calls: z.number(),\n          })\n          .transform(\n            ({\n              total_cost,\n              upstream_inference_cost,\n              created_at,\n              is_byok,\n              provider_name,\n              finish_reason,\n              generation_time,\n              native_tokens_prompt,\n              native_tokens_completion,\n              native_tokens_reasoning,\n              native_tokens_cached,\n              native_tokens_cache_creation,\n              billable_web_search_calls,\n              ...rest\n            }) => ({\n              ...rest,\n              totalCost: total_cost,\n              upstreamInferenceCost: upstream_inference_cost,\n              createdAt: created_at,\n              isByok: is_byok,\n              providerName: provider_name,\n              finishReason: finish_reason,\n              generationTime: generation_time,\n              promptTokens: native_tokens_prompt,\n              completionTokens: native_tokens_completion,\n              reasoningTokens: native_tokens_reasoning,\n              cachedTokens: native_tokens_cached,\n              cacheCreationTokens: native_tokens_cache_creation,\n              billableWebSearchCalls: billable_web_search_calls,\n            }),\n          ),\n      })\n      .transform(({ data }) => data),\n  ),\n);\n", "import type {\n  LanguageModelV3,\n  LanguageModelV3CallOptions,\n  SharedV3Warning,\n  LanguageModelV3FilePart,\n  LanguageModelV3StreamPart,\n  LanguageModelV3GenerateResult,\n  LanguageModelV3StreamResult,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  postJsonToApi,\n  resolve,\n  type ParseResult,\n  type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { GatewayConfig } from './gateway-config';\nimport type { GatewayModelId } from './gateway-language-model-settings';\nimport { asGatewayError } from './errors';\nimport { parseAuthMethod } from './errors/parse-auth-method';\n\ntype GatewayChatConfig = GatewayConfig & {\n  provider: string;\n  o11yHeaders: Resolvable<Record<string, string>>;\n};\n\nexport class GatewayLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = 'v3';\n  readonly supportedUrls = { '*/*': [/.*/] };\n\n  constructor(\n    readonly modelId: GatewayModelId,\n    private readonly config: GatewayChatConfig,\n  ) {}\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  private async getArgs(options: LanguageModelV3CallOptions) {\n    const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;\n\n    return {\n      args: this.maybeEncodeFileParts(optionsWithoutSignal),\n      warnings: [],\n    };\n  }\n\n  async doGenerate(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3GenerateResult> {\n    const { args, warnings } = await this.getArgs(options);\n    const { abortSignal } = options;\n\n    const resolvedHeaders = await resolve(this.config.headers());\n\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue: rawResponse,\n      } = await postJsonToApi({\n        url: this.getUrl(),\n        headers: combineHeaders(\n          resolvedHeaders,\n          options.headers,\n          this.getModelConfigHeaders(this.modelId, false),\n          await resolve(this.config.o11yHeaders),\n        ),\n        body: args,\n        successfulResponseHandler: createJsonResponseHandler(z.any()),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        ...(abortSignal && { abortSignal }),\n        fetch: this.config.fetch,\n      });\n\n      return {\n        ...responseBody,\n        request: { body: args },\n        response: { headers: responseHeaders, body: rawResponse },\n        warnings,\n      };\n    } catch (error) {\n      throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n    }\n  }\n\n  async doStream(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3StreamResult> {\n    const { args, warnings } = await this.getArgs(options);\n    const { abortSignal } = options;\n\n    const resolvedHeaders = await resolve(this.config.headers());\n\n    try {\n      const { value: response, responseHeaders } = await postJsonToApi({\n        url: this.getUrl(),\n        headers: combineHeaders(\n          resolvedHeaders,\n          options.headers,\n          this.getModelConfigHeaders(this.modelId, true),\n          await resolve(this.config.o11yHeaders),\n        ),\n        body: args,\n        successfulResponseHandler: createEventSourceResponseHandler(z.any()),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        ...(abortSignal && { abortSignal }),\n        fetch: this.config.fetch,\n      });\n\n      return {\n        stream: response.pipeThrough(\n          new TransformStream<\n            ParseResult<LanguageModelV3StreamPart>,\n            LanguageModelV3StreamPart\n          >({\n            start(controller) {\n              if (warnings.length > 0) {\n                controller.enqueue({ type: 'stream-start', warnings });\n              }\n            },\n            transform(chunk, controller) {\n              if (chunk.success) {\n                const streamPart = chunk.value;\n\n                // Handle raw chunks: if this is a raw chunk from the gateway API,\n                // only emit it if includeRawChunks is true\n                if (streamPart.type === 'raw' && !options.includeRawChunks) {\n                  return; // Skip raw chunks if not requested\n                }\n\n                if (\n                  streamPart.type === 'response-metadata' &&\n                  streamPart.timestamp &&\n                  typeof streamPart.timestamp === 'string'\n                ) {\n                  streamPart.timestamp = new Date(streamPart.timestamp);\n                }\n\n                controller.enqueue(streamPart);\n              } else {\n                controller.error(\n                  (chunk as { success: false; error: unknown }).error,\n                );\n              }\n            },\n          }),\n        ),\n        request: { body: args },\n        response: { headers: responseHeaders },\n      };\n    } catch (error) {\n      throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n    }\n  }\n\n  private isFilePart(part: unknown) {\n    return (\n      part && typeof part === 'object' && 'type' in part && part.type === 'file'\n    );\n  }\n\n  /**\n   * Encodes file parts in the prompt to base64. Mutates the passed options\n   * instance directly to avoid copying the file data.\n   * @param options - The options to encode.\n   * @returns The options with the file parts encoded.\n   */\n  private maybeEncodeFileParts(options: LanguageModelV3CallOptions) {\n    for (const message of options.prompt) {\n      for (const part of message.content) {\n        if (this.isFilePart(part)) {\n          const filePart = part as LanguageModelV3FilePart;\n          // If the file part is a URL it will get cleanly converted to a string.\n          // If it's a binary file attachment we convert it to a data url.\n          // In either case, server-side we should only ever see URLs as strings.\n          if (filePart.data instanceof Uint8Array) {\n            const buffer = Uint8Array.from(filePart.data);\n            const base64Data = Buffer.from(buffer).toString('base64');\n            filePart.data = new URL(\n              `data:${filePart.mediaType || 'application/octet-stream'};base64,${base64Data}`,\n            );\n          }\n        }\n      }\n    }\n    return options;\n  }\n\n  private getUrl() {\n    return `${this.config.baseURL}/language-model`;\n  }\n\n  private getModelConfigHeaders(modelId: string, streaming: boolean) {\n    return {\n      'ai-language-model-specification-version': '3',\n      'ai-language-model-id': modelId,\n      'ai-language-model-streaming': String(streaming),\n    };\n  }\n}\n", "import type {\n  EmbeddingModelV3,\n  SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  lazySchema,\n  postJsonToApi,\n  resolve,\n  zodSchema,\n  type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { asGatewayError } from './errors';\nimport { parseAuthMethod } from './errors/parse-auth-method';\nimport type { GatewayConfig } from './gateway-config';\n\nexport class GatewayEmbeddingModel implements EmbeddingModelV3 {\n  readonly specificationVersion = 'v3';\n  readonly maxEmbeddingsPerCall = 2048;\n  readonly supportsParallelCalls = true;\n\n  constructor(\n    readonly modelId: string,\n    private readonly config: GatewayConfig & {\n      provider: string;\n      o11yHeaders: Resolvable<Record<string, string>>;\n    },\n  ) {}\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  async doEmbed({\n    values,\n    headers,\n    abortSignal,\n    providerOptions,\n  }: Parameters<EmbeddingModelV3['doEmbed']>[0]): Promise<\n    Awaited<ReturnType<EmbeddingModelV3['doEmbed']>>\n  > {\n    const resolvedHeaders = await resolve(this.config.headers());\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue,\n      } = await postJsonToApi({\n        url: this.getUrl(),\n        headers: combineHeaders(\n          resolvedHeaders,\n          headers ?? {},\n          this.getModelConfigHeaders(),\n          await resolve(this.config.o11yHeaders),\n        ),\n        body: {\n          values,\n          ...(providerOptions ? { providerOptions } : {}),\n        },\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewayEmbeddingResponseSchema,\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        ...(abortSignal && { abortSignal }),\n        fetch: this.config.fetch,\n      });\n\n      return {\n        embeddings: responseBody.embeddings,\n        usage: responseBody.usage ?? undefined,\n        providerMetadata:\n          responseBody.providerMetadata as unknown as SharedV3ProviderMetadata,\n        response: { headers: responseHeaders, body: rawValue },\n        warnings: [],\n      };\n    } catch (error) {\n      throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n    }\n  }\n\n  private getUrl() {\n    return `${this.config.baseURL}/embedding-model`;\n  }\n\n  private getModelConfigHeaders() {\n    return {\n      'ai-embedding-model-specification-version': '3',\n      'ai-model-id': this.modelId,\n    };\n  }\n}\n\nconst gatewayEmbeddingResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      embeddings: z.array(z.array(z.number())),\n      usage: z.object({ tokens: z.number() }).nullish(),\n      providerMetadata: z\n        .record(z.string(), z.record(z.string(), z.unknown()))\n        .optional(),\n    }),\n  ),\n);\n", "import type {\n  ImageModelV3,\n  ImageModelV3File,\n  ImageModelV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  convertUint8ArrayToBase64,\n  createJsonResponseHandler,\n  createJsonErrorResponseHandler,\n  postJsonToApi,\n  resolve,\n  type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { GatewayConfig } from './gateway-config';\nimport { asGatewayError } from './errors';\nimport { parseAuthMethod } from './errors/parse-auth-method';\n\nexport class GatewayImageModel implements ImageModelV3 {\n  readonly specificationVersion = 'v3' as const;\n  // Set a very large number to prevent client-side splitting of requests\n  readonly maxImagesPerCall = Number.MAX_SAFE_INTEGER;\n\n  constructor(\n    readonly modelId: string,\n    private readonly config: GatewayConfig & {\n      provider: string;\n      o11yHeaders: Resolvable<Record<string, string>>;\n    },\n  ) {}\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  async doGenerate({\n    prompt,\n    n,\n    size,\n    aspectRatio,\n    seed,\n    files,\n    mask,\n    providerOptions,\n    headers,\n    abortSignal,\n  }: Parameters<ImageModelV3['doGenerate']>[0]): Promise<\n    Awaited<ReturnType<ImageModelV3['doGenerate']>>\n  > {\n    const resolvedHeaders = await resolve(this.config.headers());\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue,\n      } = await postJsonToApi({\n        url: this.getUrl(),\n        headers: combineHeaders(\n          resolvedHeaders,\n          headers ?? {},\n          this.getModelConfigHeaders(),\n          await resolve(this.config.o11yHeaders),\n        ),\n        body: {\n          prompt,\n          n,\n          ...(size && { size }),\n          ...(aspectRatio && { aspectRatio }),\n          ...(seed && { seed }),\n          ...(providerOptions && { providerOptions }),\n          ...(files && {\n            files: files.map(file => maybeEncodeImageFile(file)),\n          }),\n          ...(mask && { mask: maybeEncodeImageFile(mask) }),\n        },\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewayImageResponseSchema,\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        ...(abortSignal && { abortSignal }),\n        fetch: this.config.fetch,\n      });\n\n      return {\n        images: responseBody.images, // Always base64 strings from server\n        warnings: responseBody.warnings ?? [],\n        providerMetadata:\n          responseBody.providerMetadata as ImageModelV3ProviderMetadata,\n        response: {\n          timestamp: new Date(),\n          modelId: this.modelId,\n          headers: responseHeaders,\n        },\n        ...(responseBody.usage != null && {\n          usage: {\n            inputTokens: responseBody.usage.inputTokens ?? undefined,\n            outputTokens: responseBody.usage.outputTokens ?? undefined,\n            totalTokens: responseBody.usage.totalTokens ?? undefined,\n          },\n        }),\n      };\n    } catch (error) {\n      throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n    }\n  }\n\n  private getUrl() {\n    return `${this.config.baseURL}/image-model`;\n  }\n\n  private getModelConfigHeaders() {\n    return {\n      'ai-image-model-specification-version': '3',\n      'ai-model-id': this.modelId,\n    };\n  }\n}\n\nfunction maybeEncodeImageFile(file: ImageModelV3File) {\n  if (file.type === 'file' && file.data instanceof Uint8Array) {\n    return {\n      ...file,\n      data: convertUint8ArrayToBase64(file.data),\n    };\n  }\n  return file;\n}\n\nconst providerMetadataEntrySchema = z\n  .object({\n    images: z.array(z.unknown()).optional(),\n  })\n  .catchall(z.unknown());\n\nconst gatewayImageWarningSchema = z.discriminatedUnion('type', [\n  z.object({\n    type: z.literal('unsupported'),\n    feature: z.string(),\n    details: z.string().optional(),\n  }),\n  z.object({\n    type: z.literal('compatibility'),\n    feature: z.string(),\n    details: z.string().optional(),\n  }),\n  z.object({\n    type: z.literal('other'),\n    message: z.string(),\n  }),\n]);\n\nconst gatewayImageUsageSchema = z.object({\n  inputTokens: z.number().nullish(),\n  outputTokens: z.number().nullish(),\n  totalTokens: z.number().nullish(),\n});\n\nconst gatewayImageResponseSchema = z.object({\n  images: z.array(z.string()), // Always base64 strings over the wire\n  warnings: z.array(gatewayImageWarningSchema).optional(),\n  providerMetadata: z\n    .record(z.string(), providerMetadataEntrySchema)\n    .optional(),\n  usage: gatewayImageUsageSchema.optional(),\n});\n", "import {\n  APICallError,\n  type Experimental_VideoModelV3,\n  type Experimental_VideoModelV3CallOptions,\n  type Experimental_VideoModelV3File,\n  type Experimental_VideoModelV3VideoData,\n  type SharedV3ProviderMetadata,\n  type SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  convertUint8ArrayToBase64,\n  createJsonErrorResponseHandler,\n  parseJsonEventStream,\n  postJsonToApi,\n  resolve,\n  type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { GatewayConfig } from './gateway-config';\nimport { asGatewayError } from './errors';\nimport { parseAuthMethod } from './errors/parse-auth-method';\n\nexport class GatewayVideoModel implements Experimental_VideoModelV3 {\n  readonly specificationVersion = 'v3' as const;\n  // Set a very large number to prevent client-side splitting of requests\n  readonly maxVideosPerCall = Number.MAX_SAFE_INTEGER;\n\n  constructor(\n    readonly modelId: string,\n    private readonly config: GatewayConfig & {\n      provider: string;\n      o11yHeaders: Resolvable<Record<string, string>>;\n    },\n  ) {}\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  async doGenerate({\n    prompt,\n    n,\n    aspectRatio,\n    resolution,\n    duration,\n    fps,\n    seed,\n    image,\n    providerOptions,\n    headers,\n    abortSignal,\n  }: Experimental_VideoModelV3CallOptions): Promise<{\n    videos: Array<Experimental_VideoModelV3VideoData>;\n    warnings: Array<SharedV3Warning>;\n    providerMetadata?: SharedV3ProviderMetadata;\n    response: {\n      timestamp: Date;\n      modelId: string;\n      headers: Record<string, string> | undefined;\n    };\n  }> {\n    const resolvedHeaders = await resolve(this.config.headers());\n    try {\n      const { responseHeaders, value: responseBody } = await postJsonToApi({\n        url: this.getUrl(),\n        headers: combineHeaders(\n          resolvedHeaders,\n          headers ?? {},\n          this.getModelConfigHeaders(),\n          await resolve(this.config.o11yHeaders),\n          { accept: 'text/event-stream' },\n        ),\n        body: {\n          prompt,\n          n,\n          ...(aspectRatio && { aspectRatio }),\n          ...(resolution && { resolution }),\n          ...(duration && { duration }),\n          ...(fps && { fps }),\n          ...(seed && { seed }),\n          ...(providerOptions && { providerOptions }),\n          ...(image && { image: maybeEncodeVideoFile(image) }),\n        },\n        successfulResponseHandler: async ({\n          response,\n          url,\n          requestBodyValues,\n        }: {\n          url: string;\n          requestBodyValues: unknown;\n          response: Response;\n        }) => {\n          if (response.body == null) {\n            throw new APICallError({\n              message: 'SSE response body is empty',\n              url,\n              requestBodyValues,\n              statusCode: response.status,\n            });\n          }\n\n          const eventStream = parseJsonEventStream({\n            stream: response.body,\n            schema: gatewayVideoEventSchema,\n          });\n\n          const reader = eventStream.getReader();\n          const { done, value: parseResult } = await reader.read();\n          reader.releaseLock();\n\n          if (done || !parseResult) {\n            throw new APICallError({\n              message: 'SSE stream ended without a data event',\n              url,\n              requestBodyValues,\n              statusCode: response.status,\n            });\n          }\n\n          if (!parseResult.success) {\n            throw new APICallError({\n              message: 'Failed to parse video SSE event',\n              cause: parseResult.error,\n              url,\n              requestBodyValues,\n              statusCode: response.status,\n            });\n          }\n\n          const event = parseResult.value;\n\n          if (event.type === 'error') {\n            throw new APICallError({\n              message: event.message,\n              statusCode: event.statusCode,\n              url,\n              requestBodyValues,\n              responseHeaders: Object.fromEntries([...response.headers]),\n              responseBody: JSON.stringify(event),\n              data: {\n                error: {\n                  message: event.message,\n                  type: event.errorType,\n                  param: event.param,\n                },\n              },\n            });\n          }\n\n          // event.type === 'result'\n          return {\n            value: {\n              videos: event.videos,\n              warnings: event.warnings,\n              providerMetadata: event.providerMetadata,\n            },\n            responseHeaders: Object.fromEntries([...response.headers]),\n          };\n        },\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        ...(abortSignal && { abortSignal }),\n        fetch: this.config.fetch,\n      });\n\n      return {\n        videos: responseBody.videos,\n        warnings: responseBody.warnings ?? [],\n        providerMetadata:\n          responseBody.providerMetadata as SharedV3ProviderMetadata,\n        response: {\n          timestamp: new Date(),\n          modelId: this.modelId,\n          headers: responseHeaders,\n        },\n      };\n    } catch (error) {\n      throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n    }\n  }\n\n  private getUrl() {\n    return `${this.config.baseURL}/video-model`;\n  }\n\n  private getModelConfigHeaders() {\n    return {\n      'ai-video-model-specification-version': '3',\n      'ai-model-id': this.modelId,\n    };\n  }\n}\n\nfunction maybeEncodeVideoFile(file: Experimental_VideoModelV3File) {\n  if (file.type === 'file' && file.data instanceof Uint8Array) {\n    return {\n      ...file,\n      data: convertUint8ArrayToBase64(file.data),\n    };\n  }\n  return file;\n}\n\nconst providerMetadataEntrySchema = z\n  .object({\n    videos: z.array(z.unknown()).optional(),\n  })\n  .catchall(z.unknown());\n\nconst gatewayVideoDataSchema = z.union([\n  z.object({\n    type: z.literal('url'),\n    url: z.string(),\n    mediaType: z.string(),\n  }),\n  z.object({\n    type: z.literal('base64'),\n    data: z.string(),\n    mediaType: z.string(),\n  }),\n]);\n\nconst gatewayVideoWarningSchema = z.discriminatedUnion('type', [\n  z.object({\n    type: z.literal('unsupported'),\n    feature: z.string(),\n    details: z.string().optional(),\n  }),\n  z.object({\n    type: z.literal('compatibility'),\n    feature: z.string(),\n    details: z.string().optional(),\n  }),\n  z.object({\n    type: z.literal('other'),\n    message: z.string(),\n  }),\n]);\n\nconst gatewayVideoEventSchema = z.discriminatedUnion('type', [\n  z.object({\n    type: z.literal('result'),\n    videos: z.array(gatewayVideoDataSchema),\n    warnings: z.array(gatewayVideoWarningSchema).optional(),\n    providerMetadata: z\n      .record(z.string(), providerMetadataEntrySchema)\n      .optional(),\n  }),\n  z.object({\n    type: z.literal('error'),\n    message: z.string(),\n    errorType: z.string(),\n    statusCode: z.number(),\n    param: z.unknown().nullable(),\n  }),\n]);\n", "import type {\n  RerankingModelV3,\n  SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  lazySchema,\n  postJsonToApi,\n  resolve,\n  zodSchema,\n  type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { asGatewayError } from './errors';\nimport { parseAuthMethod } from './errors/parse-auth-method';\nimport type { GatewayConfig } from './gateway-config';\n\nexport class GatewayRerankingModel implements RerankingModelV3 {\n  readonly specificationVersion = 'v3';\n\n  constructor(\n    readonly modelId: string,\n    private readonly config: GatewayConfig & {\n      provider: string;\n      o11yHeaders: Resolvable<Record<string, string>>;\n    },\n  ) {}\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  async doRerank({\n    documents,\n    query,\n    topN,\n    headers,\n    abortSignal,\n    providerOptions,\n  }: Parameters<RerankingModelV3['doRerank']>[0]): Promise<\n    Awaited<ReturnType<RerankingModelV3['doRerank']>>\n  > {\n    const resolvedHeaders = await resolve(this.config.headers());\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue,\n      } = await postJsonToApi({\n        url: this.getUrl(),\n        headers: combineHeaders(\n          resolvedHeaders,\n          headers ?? {},\n          this.getModelConfigHeaders(),\n          await resolve(this.config.o11yHeaders),\n        ),\n        body: {\n          documents,\n          query,\n          ...(topN != null ? { topN } : {}),\n          ...(providerOptions ? { providerOptions } : {}),\n        },\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewayRerankingResponseSchema,\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z.any(),\n          errorToMessage: data => data,\n        }),\n        ...(abortSignal && { abortSignal }),\n        fetch: this.config.fetch,\n      });\n\n      return {\n        ranking: responseBody.ranking,\n        providerMetadata:\n          responseBody.providerMetadata as unknown as SharedV3ProviderMetadata,\n        response: { headers: responseHeaders, body: rawValue },\n        warnings: [],\n      };\n    } catch (error) {\n      throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n    }\n  }\n\n  private getUrl() {\n    return `${this.config.baseURL}/reranking-model`;\n  }\n\n  private getModelConfigHeaders() {\n    return {\n      'ai-reranking-model-specification-version': '3',\n      'ai-model-id': this.modelId,\n    };\n  }\n}\n\nconst gatewayRerankingResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      ranking: z.array(\n        z.object({\n          index: z.number(),\n          relevanceScore: z.number(),\n        }),\n      ),\n      providerMetadata: z\n        .record(z.string(), z.record(z.string(), z.unknown()))\n        .optional(),\n    }),\n  ),\n);\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod';\n\nexport interface ParallelSearchSourcePolicy {\n  /**\n   * List of domains to include in search results.\n   * Example: ['wikipedia.org', 'nature.com']\n   */\n  includeDomains?: string[];\n\n  /**\n   * List of domains to exclude from search results.\n   * Example: ['reddit.com', 'twitter.com']\n   */\n  excludeDomains?: string[];\n\n  /**\n   * Only include results published after this date (ISO 8601 format).\n   * Example: '2024-01-01'\n   */\n  afterDate?: string;\n}\n\nexport interface ParallelSearchExcerpts {\n  /**\n   * Maximum characters per result.\n   */\n  maxCharsPerResult?: number;\n\n  /**\n   * Maximum total characters across all results.\n   */\n  maxCharsTotal?: number;\n}\n\nexport interface ParallelSearchFetchPolicy {\n  /**\n   * Maximum age in seconds for cached content.\n   * Set to 0 to always fetch fresh content.\n   */\n  maxAgeSeconds?: number;\n}\n\nexport interface ParallelSearchConfig {\n  /**\n   * Mode preset for different use cases:\n   * - \"one-shot\": Comprehensive results with longer excerpts for single-response answers (default)\n   * - \"agentic\": Concise, token-efficient results for multi-step agentic workflows\n   */\n  mode?: 'one-shot' | 'agentic';\n\n  /**\n   * Default maximum number of results to return (1-20).\n   * Defaults to 10 if not specified.\n   */\n  maxResults?: number;\n\n  /**\n   * Default source policy for controlling which domains to include/exclude.\n   */\n  sourcePolicy?: ParallelSearchSourcePolicy;\n\n  /**\n   * Default excerpt configuration for controlling result length.\n   */\n  excerpts?: ParallelSearchExcerpts;\n\n  /**\n   * Default fetch policy for controlling content freshness.\n   */\n  fetchPolicy?: ParallelSearchFetchPolicy;\n}\n\nexport interface ParallelSearchResult {\n  /** URL of the search result */\n  url: string;\n  /** Title of the search result */\n  title: string;\n  /** Extracted text excerpt/content from the page */\n  excerpt: string;\n  /** Publication date of the content (may be null) */\n  publishDate?: string | null;\n  /** Relevance score for the result */\n  relevanceScore?: number;\n}\n\nexport interface ParallelSearchResponse {\n  /** Unique identifier for this search request */\n  searchId: string;\n  /** Array of search results */\n  results: ParallelSearchResult[];\n}\n\nexport interface ParallelSearchError {\n  /** Error type */\n  error:\n    | 'api_error'\n    | 'rate_limit'\n    | 'timeout'\n    | 'invalid_input'\n    | 'configuration_error'\n    | 'unknown';\n  /** HTTP status code if applicable */\n  statusCode?: number;\n  /** Human-readable error message */\n  message: string;\n}\n\nexport interface ParallelSearchInput {\n  /**\n   * Natural-language description of the web research goal.\n   * Include source or freshness guidance and broader context from the task.\n   * Maximum 5000 characters.\n   */\n  objective: string;\n\n  /**\n   * Optional search queries to supplement the objective.\n   * Maximum 200 characters per query.\n   */\n  search_queries?: string[];\n\n  /**\n   * Mode preset for different use cases:\n   * - \"one-shot\": Comprehensive results with longer excerpts\n   * - \"agentic\": Concise, token-efficient results for multi-step workflows\n   */\n  mode?: 'one-shot' | 'agentic';\n\n  /**\n   * Maximum number of results to return (1-20).\n   * Defaults to 10 if not specified.\n   */\n  max_results?: number;\n\n  /**\n   * Source policy for controlling which domains to include/exclude.\n   */\n  source_policy?: {\n    include_domains?: string[];\n    exclude_domains?: string[];\n    after_date?: string;\n  };\n\n  /**\n   * Excerpt configuration for controlling result length.\n   */\n  excerpts?: {\n    max_chars_per_result?: number;\n    max_chars_total?: number;\n  };\n\n  /**\n   * Fetch policy for controlling content freshness.\n   */\n  fetch_policy?: {\n    max_age_seconds?: number;\n  };\n}\n\nexport type ParallelSearchOutput = ParallelSearchResponse | ParallelSearchError;\n\nconst parallelSearchInputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      objective: z\n        .string()\n        .describe(\n          'Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters.',\n        ),\n\n      search_queries: z\n        .array(z.string())\n        .optional()\n        .describe(\n          'Optional search queries to supplement the objective. Maximum 200 characters per query.',\n        ),\n\n      mode: z\n        .enum(['one-shot', 'agentic'])\n        .optional()\n        .describe(\n          'Mode preset: \"one-shot\" for comprehensive results with longer excerpts (default), \"agentic\" for concise, token-efficient results for multi-step workflows.',\n        ),\n\n      max_results: z\n        .number()\n        .optional()\n        .describe(\n          'Maximum number of results to return (1-20). Defaults to 10 if not specified.',\n        ),\n\n      source_policy: z\n        .object({\n          include_domains: z\n            .array(z.string())\n            .optional()\n            .describe('List of domains to include in search results.'),\n          exclude_domains: z\n            .array(z.string())\n            .optional()\n            .describe('List of domains to exclude from search results.'),\n          after_date: z\n            .string()\n            .optional()\n            .describe(\n              'Only include results published after this date (ISO 8601 format).',\n            ),\n        })\n        .optional()\n        .describe(\n          'Source policy for controlling which domains to include/exclude and freshness.',\n        ),\n\n      excerpts: z\n        .object({\n          max_chars_per_result: z\n            .number()\n            .optional()\n            .describe('Maximum characters per result.'),\n          max_chars_total: z\n            .number()\n            .optional()\n            .describe('Maximum total characters across all results.'),\n        })\n        .optional()\n        .describe('Excerpt configuration for controlling result length.'),\n\n      fetch_policy: z\n        .object({\n          max_age_seconds: z\n            .number()\n            .optional()\n            .describe(\n              'Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.',\n            ),\n        })\n        .optional()\n        .describe('Fetch policy for controlling content freshness.'),\n    }),\n  ),\n);\n\nconst parallelSearchOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.union([\n      // Success response\n      z.object({\n        searchId: z.string(),\n        results: z.array(\n          z.object({\n            url: z.string(),\n            title: z.string(),\n            excerpt: z.string(),\n            publishDate: z.string().nullable().optional(),\n            relevanceScore: z.number().optional(),\n          }),\n        ),\n      }),\n      // Error response\n      z.object({\n        error: z.enum([\n          'api_error',\n          'rate_limit',\n          'timeout',\n          'invalid_input',\n          'configuration_error',\n          'unknown',\n        ]),\n        statusCode: z.number().optional(),\n        message: z.string(),\n      }),\n    ]),\n  ),\n);\n\nexport const parallelSearchToolFactory =\n  createProviderToolFactoryWithOutputSchema<\n    ParallelSearchInput,\n    ParallelSearchOutput,\n    ParallelSearchConfig\n  >({\n    id: 'gateway.parallel_search',\n    inputSchema: parallelSearchInputSchema,\n    outputSchema: parallelSearchOutputSchema,\n  });\n\nexport const parallelSearch = (\n  config: ParallelSearchConfig = {},\n): ReturnType<typeof parallelSearchToolFactory> =>\n  parallelSearchToolFactory(config);\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod';\n\nexport interface PerplexitySearchConfig {\n  /**\n   * Default maximum number of search results to return (1-20, default: 10).\n   */\n  maxResults?: number;\n\n  /**\n   * Default maximum tokens to extract per search result page (256-2048, default: 2048).\n   */\n  maxTokensPerPage?: number;\n\n  /**\n   * Default maximum total tokens across all search results (default: 25000, max: 1000000).\n   */\n  maxTokens?: number;\n\n  /**\n   * Default two-letter ISO 3166-1 alpha-2 country code for regional search results.\n   * Examples: 'US', 'GB', 'FR'\n   */\n  country?: string;\n\n  /**\n   * Default list of domains to include or exclude from search results (max 20).\n   * To include: ['nature.com', 'science.org']\n   * To exclude: ['-example.com', '-spam.net']\n   */\n  searchDomainFilter?: string[];\n\n  /**\n   * Default list of ISO 639-1 language codes to filter results (max 10, lowercase).\n   * Examples: ['en', 'fr', 'de']\n   */\n  searchLanguageFilter?: string[];\n\n  /**\n   * Default recency filter for results.\n   * Cannot be combined with searchAfterDate/searchBeforeDate at runtime.\n   */\n  searchRecencyFilter?: 'day' | 'week' | 'month' | 'year';\n}\n\nexport interface PerplexitySearchResult {\n  /** Title of the search result */\n  title: string;\n  /** URL of the search result */\n  url: string;\n  /** Text snippet/preview of the content */\n  snippet: string;\n  /** Publication date of the content */\n  date?: string;\n  /** Last updated date of the content */\n  lastUpdated?: string;\n}\n\nexport interface PerplexitySearchResponse {\n  /** Array of search results */\n  results: PerplexitySearchResult[];\n  /** Unique identifier for this search request */\n  id: string;\n}\n\nexport interface PerplexitySearchError {\n  /** Error type */\n  error: 'api_error' | 'rate_limit' | 'timeout' | 'invalid_input' | 'unknown';\n  /** HTTP status code if applicable */\n  statusCode?: number;\n  /** Human-readable error message */\n  message: string;\n}\n\nexport interface PerplexitySearchInput {\n  /**\n   * Search query (string) or multiple queries (array of up to 5 strings).\n   * Multi-query searches return combined results from all queries.\n   */\n  query: string | string[];\n\n  /**\n   * Maximum number of search results to return (1-20, default: 10).\n   */\n  max_results?: number;\n\n  /**\n   * Maximum number of tokens to extract per search result page (256-2048, default: 2048).\n   */\n  max_tokens_per_page?: number;\n\n  /**\n   * Maximum total tokens across all search results (default: 25000, max: 1000000).\n   */\n  max_tokens?: number;\n\n  /**\n   * Two-letter ISO 3166-1 alpha-2 country code for regional search results.\n   * Examples: 'US', 'GB', 'FR'\n   */\n  country?: string;\n\n  /**\n   * List of domains to include or exclude from search results (max 20).\n   * To include: ['nature.com', 'science.org']\n   * To exclude: ['-example.com', '-spam.net']\n   */\n  search_domain_filter?: string[];\n\n  /**\n   * List of ISO 639-1 language codes to filter results (max 10, lowercase).\n   * Examples: ['en', 'fr', 'de']\n   */\n  search_language_filter?: string[];\n\n  /**\n   * Include only results published after this date.\n   * Format: 'MM/DD/YYYY' (e.g., '3/1/2025')\n   * Cannot be used with search_recency_filter.\n   */\n  search_after_date?: string;\n\n  /**\n   * Include only results published before this date.\n   * Format: 'MM/DD/YYYY' (e.g., '3/15/2025')\n   * Cannot be used with search_recency_filter.\n   */\n  search_before_date?: string;\n\n  /**\n   * Include only results last updated after this date.\n   * Format: 'MM/DD/YYYY' (e.g., '3/1/2025')\n   * Cannot be used with search_recency_filter.\n   */\n  last_updated_after_filter?: string;\n\n  /**\n   * Include only results last updated before this date.\n   * Format: 'MM/DD/YYYY' (e.g., '3/15/2025')\n   * Cannot be used with search_recency_filter.\n   */\n  last_updated_before_filter?: string;\n\n  /**\n   * Filter results by relative time period.\n   * Cannot be used with search_after_date or search_before_date.\n   */\n  search_recency_filter?: 'day' | 'week' | 'month' | 'year';\n}\n\nexport type PerplexitySearchOutput =\n  | PerplexitySearchResponse\n  | PerplexitySearchError;\n\nconst perplexitySearchInputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      query: z\n        .union([z.string(), z.array(z.string())])\n        .describe(\n          'Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries.',\n        ),\n\n      max_results: z\n        .number()\n        .optional()\n        .describe(\n          'Maximum number of search results to return (1-20, default: 10)',\n        ),\n\n      max_tokens_per_page: z\n        .number()\n        .optional()\n        .describe(\n          'Maximum number of tokens to extract per search result page (256-2048, default: 2048)',\n        ),\n\n      max_tokens: z\n        .number()\n        .optional()\n        .describe(\n          'Maximum total tokens across all search results (default: 25000, max: 1000000)',\n        ),\n\n      country: z\n        .string()\n        .optional()\n        .describe(\n          \"Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')\",\n        ),\n\n      search_domain_filter: z\n        .array(z.string())\n        .optional()\n        .describe(\n          \"List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']\",\n        ),\n\n      search_language_filter: z\n        .array(z.string())\n        .optional()\n        .describe(\n          \"List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']\",\n        ),\n\n      search_after_date: z\n        .string()\n        .optional()\n        .describe(\n          \"Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter.\",\n        ),\n\n      search_before_date: z\n        .string()\n        .optional()\n        .describe(\n          \"Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter.\",\n        ),\n\n      last_updated_after_filter: z\n        .string()\n        .optional()\n        .describe(\n          \"Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter.\",\n        ),\n\n      last_updated_before_filter: z\n        .string()\n        .optional()\n        .describe(\n          \"Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter.\",\n        ),\n\n      search_recency_filter: z\n        .enum(['day', 'week', 'month', 'year'])\n        .optional()\n        .describe(\n          'Filter results by relative time period. Cannot be used with search_after_date or search_before_date.',\n        ),\n    }),\n  ),\n);\n\nconst perplexitySearchOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.union([\n      // Success response\n      z.object({\n        results: z.array(\n          z.object({\n            title: z.string(),\n            url: z.string(),\n            snippet: z.string(),\n            date: z.string().optional(),\n            lastUpdated: z.string().optional(),\n          }),\n        ),\n        id: z.string(),\n      }),\n      // Error response\n      z.object({\n        error: z.enum([\n          'api_error',\n          'rate_limit',\n          'timeout',\n          'invalid_input',\n          'unknown',\n        ]),\n        statusCode: z.number().optional(),\n        message: z.string(),\n      }),\n    ]),\n  ),\n);\n\nexport const perplexitySearchToolFactory =\n  createProviderToolFactoryWithOutputSchema<\n    PerplexitySearchInput,\n    PerplexitySearchOutput,\n    PerplexitySearchConfig\n  >({\n    id: 'gateway.perplexity_search',\n    inputSchema: perplexitySearchInputSchema,\n    outputSchema: perplexitySearchOutputSchema,\n  });\n\nexport const perplexitySearch = (\n  config: PerplexitySearchConfig = {},\n): ReturnType<typeof perplexitySearchToolFactory> =>\n  perplexitySearchToolFactory(config);\n", "import { parallelSearch } from './tool/parallel-search';\nimport { perplexitySearch } from './tool/perplexity-search';\n\n/**\n * Gateway-specific provider-defined tools.\n */\nexport const gatewayTools = {\n  /**\n   * Search the web using Parallel AI's Search API for LLM-optimized excerpts.\n   *\n   * Takes a natural language objective and returns relevant excerpts,\n   * replacing multiple keyword searches with a single call for broad\n   * or complex queries. Supports different search types for depth vs\n   * breadth tradeoffs.\n   */\n  parallelSearch,\n\n  /**\n   * Search the web using Perplexity's Search API for real-time information,\n   * news, research papers, and articles.\n   *\n   * Provides ranked search results with advanced filtering options including\n   * domain, language, date range, and recency filters.\n   */\n  perplexitySearch,\n};\n", "import { getContext } from '@vercel/oidc';\nexport { getVercelOidcToken } from '@vercel/oidc';\n\nexport async function getVercelRequestId(): Promise<string | undefined> {\n  return getContext().headers?.['x-vercel-id'];\n}\n", "// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Updates to this file should also be replicated to @opentelemetry/core too.\n\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * - <object> (When all else fails)\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexport const _globalThis: typeof globalThis =\n  typeof globalThis === 'object'\n    ? globalThis\n    : typeof self === 'object'\n    ? self\n    : typeof window === 'object'\n    ? window\n    : typeof global === 'object'\n    ? global\n    : ({} as typeof globalThis);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n *    - 1.x package cannot use global 2.x package\n *    - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n *    - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n *    - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n  ownVersion: string\n): (globalVersion: string) => boolean {\n  const acceptedVersions = new Set<string>([ownVersion]);\n  const rejectedVersions = new Set<string>();\n\n  const myVersionMatch = ownVersion.match(re);\n  if (!myVersionMatch) {\n    // we cannot guarantee compatibility so we always return noop\n    return () => false;\n  }\n\n  const ownVersionParsed = {\n    major: +myVersionMatch[1],\n    minor: +myVersionMatch[2],\n    patch: +myVersionMatch[3],\n    prerelease: myVersionMatch[4],\n  };\n\n  // if ownVersion has a prerelease tag, versions must match exactly\n  if (ownVersionParsed.prerelease != null) {\n    return function isExactmatch(globalVersion: string): boolean {\n      return globalVersion === ownVersion;\n    };\n  }\n\n  function _reject(v: string) {\n    rejectedVersions.add(v);\n    return false;\n  }\n\n  function _accept(v: string) {\n    acceptedVersions.add(v);\n    return true;\n  }\n\n  return function isCompatible(globalVersion: string): boolean {\n    if (acceptedVersions.has(globalVersion)) {\n      return true;\n    }\n\n    if (rejectedVersions.has(globalVersion)) {\n      return false;\n    }\n\n    const globalVersionMatch = globalVersion.match(re);\n    if (!globalVersionMatch) {\n      // cannot parse other version\n      // we cannot guarantee compatibility so we always noop\n      return _reject(globalVersion);\n    }\n\n    const globalVersionParsed = {\n      major: +globalVersionMatch[1],\n      minor: +globalVersionMatch[2],\n      patch: +globalVersionMatch[3],\n      prerelease: globalVersionMatch[4],\n    };\n\n    // if globalVersion has a prerelease tag, versions must match exactly\n    if (globalVersionParsed.prerelease != null) {\n      return _reject(globalVersion);\n    }\n\n    // major versions must match\n    if (ownVersionParsed.major !== globalVersionParsed.major) {\n      return _reject(globalVersion);\n    }\n\n    if (ownVersionParsed.major === 0) {\n      if (\n        ownVersionParsed.minor === globalVersionParsed.minor &&\n        ownVersionParsed.patch <= globalVersionParsed.patch\n      ) {\n        return _accept(globalVersion);\n      }\n\n      return _reject(globalVersion);\n    }\n\n    if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n      return _accept(globalVersion);\n    }\n\n    return _reject(globalVersion);\n  };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n *    - 1.x package cannot use global 2.x package\n *    - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n *    - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n *    - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n  `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal<Type extends keyof OTelGlobalAPI>(\n  type: Type,\n  instance: OTelGlobalAPI[Type],\n  diag: DiagLogger,\n  allowOverride = false\n): boolean {\n  const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n    GLOBAL_OPENTELEMETRY_API_KEY\n  ] ?? {\n    version: VERSION,\n  });\n\n  if (!allowOverride && api[type]) {\n    // already registered an API of this type\n    const err = new Error(\n      `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n    );\n    diag.error(err.stack || err.message);\n    return false;\n  }\n\n  if (api.version !== VERSION) {\n    // All registered APIs must be of the same version exactly\n    const err = new Error(\n      `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n    );\n    diag.error(err.stack || err.message);\n    return false;\n  }\n\n  api[type] = instance;\n  diag.debug(\n    `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n  );\n\n  return true;\n}\n\nexport function getGlobal<Type extends keyof OTelGlobalAPI>(\n  type: Type\n): OTelGlobalAPI[Type] | undefined {\n  const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n  if (!globalVersion || !isCompatible(globalVersion)) {\n    return;\n  }\n  return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n  diag.debug(\n    `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n  );\n  const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n  if (api) {\n    delete api[type];\n  }\n}\n\ntype OTelGlobal = {\n  [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n  version: string;\n\n  diag?: DiagLogger;\n  trace?: TracerProvider;\n  context?: ContextManager;\n  metrics?: MeterProvider;\n  propagation?: TextMapPropagator;\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n  private _namespace: string;\n\n  constructor(props: ComponentLoggerOptions) {\n    this._namespace = props.namespace || 'DiagComponentLogger';\n  }\n\n  public debug(...args: any[]): void {\n    return logProxy('debug', this._namespace, args);\n  }\n\n  public error(...args: any[]): void {\n    return logProxy('error', this._namespace, args);\n  }\n\n  public info(...args: any[]): void {\n    return logProxy('info', this._namespace, args);\n  }\n\n  public warn(...args: any[]): void {\n    return logProxy('warn', this._namespace, args);\n  }\n\n  public verbose(...args: any[]): void {\n    return logProxy('verbose', this._namespace, args);\n  }\n}\n\nfunction logProxy(\n  funcName: keyof DiagLogger,\n  namespace: string,\n  args: any\n): void {\n  const logger = getGlobal('diag');\n  // shortcut if logger not set\n  if (!logger) {\n    return;\n  }\n\n  args.unshift(namespace);\n  return logger[funcName](...(args as Parameters<DiagLogFunction>));\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n  /** Log an error scenario that was not expected and caused the requested operation to fail. */\n  error: DiagLogFunction;\n\n  /**\n   * Log a warning scenario to inform the developer of an issues that should be investigated.\n   * The requested operation may or may not have succeeded or completed.\n   */\n  warn: DiagLogFunction;\n\n  /**\n   * Log a general informational message, this should not affect functionality.\n   * This is also the default logging level so this should NOT be used for logging\n   * debugging level information.\n   */\n  info: DiagLogFunction;\n\n  /**\n   * Log a general debug message that can be useful for identifying a failure.\n   * Information logged at this level may include diagnostic details that would\n   * help identify a failure scenario.\n   * For example: Logging the order of execution of async operations.\n   */\n  debug: DiagLogFunction;\n\n  /**\n   * Log a detailed (verbose) trace level logging that can be used to identify failures\n   * where debug level logging would be insufficient, this level of tracing can include\n   * input and output parameters and as such may include PII information passing through\n   * the API. As such it is recommended that this level of tracing should not be enabled\n   * in a production environment.\n   */\n  verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n  /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n  NONE = 0,\n\n  /** Identifies an error scenario */\n  ERROR = 30,\n\n  /** Identifies a warning scenario */\n  WARN = 50,\n\n  /** General informational log message */\n  INFO = 60,\n\n  /** General debug log message */\n  DEBUG = 70,\n\n  /**\n   * Detailed trace level logging should only be used for development, should only be set\n   * in a development environment.\n   */\n  VERBOSE = 80,\n\n  /** Used to set the logging level to include all logging */\n  ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n  namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n  /**\n   * The {@link DiagLogLevel} used to filter logs sent to the logger.\n   *\n   * @defaultValue DiagLogLevel.INFO\n   */\n  logLevel?: DiagLogLevel;\n\n  /**\n   * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n   */\n  suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n  /**\n   * Set the global DiagLogger and DiagLogLevel.\n   * If a global diag logger is already set, this will override it.\n   *\n   * @param logger - The {@link DiagLogger} instance to set as the default logger.\n   * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n   * @returns `true` if the logger was successfully registered, else `false`\n   */\n  setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n  /**\n   *\n   * @param logger - The {@link DiagLogger} instance to set as the default logger.\n   * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n   * @returns `true` if the logger was successfully registered, else `false`\n   */\n  setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n  maxLevel: DiagLogLevel,\n  logger: DiagLogger\n): DiagLogger {\n  if (maxLevel < DiagLogLevel.NONE) {\n    maxLevel = DiagLogLevel.NONE;\n  } else if (maxLevel > DiagLogLevel.ALL) {\n    maxLevel = DiagLogLevel.ALL;\n  }\n\n  // In case the logger is null or undefined\n  logger = logger || {};\n\n  function _filterFunc(\n    funcName: keyof DiagLogger,\n    theLevel: DiagLogLevel\n  ): DiagLogFunction {\n    const theFunc = logger[funcName];\n\n    if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n      return theFunc.bind(logger);\n    }\n    return function () {};\n  }\n\n  return {\n    error: _filterFunc('error', DiagLogLevel.ERROR),\n    warn: _filterFunc('warn', DiagLogLevel.WARN),\n    info: _filterFunc('info', DiagLogLevel.INFO),\n    debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n    verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n  };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n  ComponentLoggerOptions,\n  DiagLogFunction,\n  DiagLogger,\n  DiagLoggerApi,\n  DiagLogLevel,\n} from '../diag/types';\nimport {\n  getGlobal,\n  registerGlobal,\n  unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n  private static _instance?: DiagAPI;\n\n  /** Get the singleton instance of the DiagAPI API */\n  public static instance(): DiagAPI {\n    if (!this._instance) {\n      this._instance = new DiagAPI();\n    }\n\n    return this._instance;\n  }\n\n  /**\n   * Private internal constructor\n   * @private\n   */\n  private constructor() {\n    function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n      return function (...args) {\n        const logger = getGlobal('diag');\n        // shortcut if logger not set\n        if (!logger) return;\n        return logger[funcName](...args);\n      };\n    }\n\n    // Using self local variable for minification purposes as 'this' cannot be minified\n    const self = this;\n\n    // DiagAPI specific functions\n\n    const setLogger: DiagLoggerApi['setLogger'] = (\n      logger,\n      optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n    ) => {\n      if (logger === self) {\n        // There isn't much we can do here.\n        // Logging to the console might break the user application.\n        // Try to log to self. If a logger was previously registered it will receive the log.\n        const err = new Error(\n          'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n        );\n        self.error(err.stack ?? err.message);\n        return false;\n      }\n\n      if (typeof optionsOrLogLevel === 'number') {\n        optionsOrLogLevel = {\n          logLevel: optionsOrLogLevel,\n        };\n      }\n\n      const oldLogger = getGlobal('diag');\n      const newLogger = createLogLevelDiagLogger(\n        optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n        logger\n      );\n      // There already is an logger registered. We'll let it know before overwriting it.\n      if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n        const stack = new Error().stack ?? '<failed to generate stacktrace>';\n        oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n        newLogger.warn(\n          `Current logger will overwrite one already registered from ${stack}`\n        );\n      }\n\n      return registerGlobal('diag', newLogger, self, true);\n    };\n\n    self.setLogger = setLogger;\n\n    self.disable = () => {\n      unregisterGlobal(API_NAME, self);\n    };\n\n    self.createComponentLogger = (options: ComponentLoggerOptions) => {\n      return new DiagComponentLogger(options);\n    };\n\n    self.verbose = _logProxy('verbose');\n    self.debug = _logProxy('debug');\n    self.info = _logProxy('info');\n    self.warn = _logProxy('warn');\n    self.error = _logProxy('error');\n  }\n\n  public setLogger!: DiagLoggerApi['setLogger'];\n  /**\n   *\n   */\n  public createComponentLogger!: (\n    options: ComponentLoggerOptions\n  ) => DiagLogger;\n\n  // DiagLogger implementation\n  public verbose!: DiagLogFunction;\n  public debug!: DiagLogFunction;\n  public info!: DiagLogFunction;\n  public warn!: DiagLogFunction;\n  public error!: DiagLogFunction;\n\n  /**\n   * Unregister the global logger and return to Noop\n   */\n  public disable!: () => void;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n  // The specification states that for the same input, multiple calls should\n  // return different keys. Due to the nature of the JS dependency management\n  // system, this creates problems where multiple versions of some package\n  // could hold different keys for the same property.\n  //\n  // Therefore, we use Symbol.for which returns the same key for the same input.\n  return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n  private _currentContext!: Map<symbol, unknown>;\n\n  /**\n   * Construct a new context which inherits values from an optional parent context.\n   *\n   * @param parentContext a context from which to inherit values\n   */\n  constructor(parentContext?: Map<symbol, unknown>) {\n    // for minification\n    const self = this;\n\n    self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n    self.getValue = (key: symbol) => self._currentContext.get(key);\n\n    self.setValue = (key: symbol, value: unknown): Context => {\n      const context = new BaseContext(self._currentContext);\n      context._currentContext.set(key, value);\n      return context;\n    };\n\n    self.deleteValue = (key: symbol): Context => {\n      const context = new BaseContext(self._currentContext);\n      context._currentContext.delete(key);\n      return context;\n    };\n  }\n\n  /**\n   * Get a value from the context.\n   *\n   * @param key key which identifies a context value\n   */\n  public getValue!: (key: symbol) => unknown;\n\n  /**\n   * Create a new context which inherits from this context and has\n   * the given key set to the given value.\n   *\n   * @param key context key for which to set the value\n   * @param value value to set for the given key\n   */\n  public setValue!: (key: symbol, value: unknown) => Context;\n\n  /**\n   * Return a new context which inherits from this context but does\n   * not contain a value for the given key.\n   *\n   * @param key context key for which to clear a value\n   */\n  public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n  active(): types.Context {\n    return ROOT_CONTEXT;\n  }\n\n  with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n    _context: types.Context,\n    fn: F,\n    thisArg?: ThisParameterType<F>,\n    ...args: A\n  ): ReturnType<F> {\n    return fn.call(thisArg, ...args);\n  }\n\n  bind<T>(_context: types.Context, target: T): T {\n    return target;\n  }\n\n  enable(): this {\n    return this;\n  }\n\n  disable(): this {\n    return this;\n  }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n  getGlobal,\n  registerGlobal,\n  unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n  private static _instance?: ContextAPI;\n\n  /** Empty private constructor prevents end users from constructing a new instance of the API */\n  private constructor() {}\n\n  /** Get the singleton instance of the Context API */\n  public static getInstance(): ContextAPI {\n    if (!this._instance) {\n      this._instance = new ContextAPI();\n    }\n\n    return this._instance;\n  }\n\n  /**\n   * Set the current context manager.\n   *\n   * @returns true if the context manager was successfully registered, else false\n   */\n  public setGlobalContextManager(contextManager: ContextManager): boolean {\n    return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n  }\n\n  /**\n   * Get the currently active context\n   */\n  public active(): Context {\n    return this._getContextManager().active();\n  }\n\n  /**\n   * Execute a function with an active context\n   *\n   * @param context context to be active during function execution\n   * @param fn function to execute in a context\n   * @param thisArg optional receiver to be used for calling fn\n   * @param args optional arguments forwarded to fn\n   */\n  public with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n    context: Context,\n    fn: F,\n    thisArg?: ThisParameterType<F>,\n    ...args: A\n  ): ReturnType<F> {\n    return this._getContextManager().with(context, fn, thisArg, ...args);\n  }\n\n  /**\n   * Bind a context to a target function or event emitter\n   *\n   * @param context context to bind to the event emitter or function. Defaults to the currently active context\n   * @param target function or event emitter to bind\n   */\n  public bind<T>(context: Context, target: T): T {\n    return this._getContextManager().bind(context, target);\n  }\n\n  private _getContextManager(): ContextManager {\n    return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n  }\n\n  /** Disable and remove the global context manager */\n  public disable() {\n    this._getContextManager().disable();\n    unregisterGlobal(API_NAME, DiagAPI.instance());\n  }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum TraceFlags {\n  /** Represents no flag set. */\n  NONE = 0x0,\n  /** Bit to represent whether trace is sampled in trace flags. */\n  SAMPLED = 0x1 << 0,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\nexport const INVALID_SPANID = '0000000000000000';\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n  traceId: INVALID_TRACEID,\n  spanId: INVALID_SPANID,\n  traceFlags: TraceFlags.NONE,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nexport class NonRecordingSpan implements Span {\n  constructor(\n    private readonly _spanContext: SpanContext = INVALID_SPAN_CONTEXT\n  ) {}\n\n  // Returns a SpanContext.\n  spanContext(): SpanContext {\n    return this._spanContext;\n  }\n\n  // By default does nothing\n  setAttribute(_key: string, _value: unknown): this {\n    return this;\n  }\n\n  // By default does nothing\n  setAttributes(_attributes: SpanAttributes): this {\n    return this;\n  }\n\n  // By default does nothing\n  addEvent(_name: string, _attributes?: SpanAttributes): this {\n    return this;\n  }\n\n  addLink(_link: Link): this {\n    return this;\n  }\n\n  addLinks(_links: Link[]): this {\n    return this;\n  }\n\n  // By default does nothing\n  setStatus(_status: SpanStatus): this {\n    return this;\n  }\n\n  // By default does nothing\n  updateName(_name: string): this {\n    return this;\n  }\n\n  // By default does nothing\n  end(_endTime?: TimeInput): void {}\n\n  // isRecording always returns false for NonRecordingSpan.\n  isRecording(): boolean {\n    return false;\n  }\n\n  // By default does nothing\n  recordException(_exception: Exception, _time?: TimeInput): void {}\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n\n/**\n * span key\n */\nconst SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context: Context): Span | undefined {\n  return (context.getValue(SPAN_KEY) as Span) || undefined;\n}\n\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan(): Span | undefined {\n  return getSpan(ContextAPI.getInstance().active());\n}\n\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context: Context, span: Span): Context {\n  return context.setValue(SPAN_KEY, span);\n}\n\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context: Context): Context {\n  return context.deleteValue(SPAN_KEY);\n}\n\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(\n  context: Context,\n  spanContext: SpanContext\n): Context {\n  return setSpan(context, new NonRecordingSpan(spanContext));\n}\n\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context: Context): SpanContext | undefined {\n  return getSpan(context)?.spanContext();\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\n\nconst VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nconst VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\n\nexport function isValidTraceId(traceId: string): boolean {\n  return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\n\nexport function isValidSpanId(spanId: string): boolean {\n  return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext: SpanContext): boolean {\n  return (\n    isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)\n  );\n}\n\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext: SpanContext): Span {\n  return new NonRecordingSpan(spanContext);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { Context } from '../context/types';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { isSpanContextValid } from './spancontext-utils';\nimport { SpanOptions } from './SpanOptions';\nimport { SpanContext } from './span_context';\nimport { Tracer } from './tracer';\n\nconst contextApi = ContextAPI.getInstance();\n\n/**\n * No-op implementations of {@link Tracer}.\n */\nexport class NoopTracer implements Tracer {\n  // startSpan starts a noop span.\n  startSpan(\n    name: string,\n    options?: SpanOptions,\n    context = contextApi.active()\n  ): Span {\n    const root = Boolean(options?.root);\n    if (root) {\n      return new NonRecordingSpan();\n    }\n\n    const parentFromContext = context && getSpanContext(context);\n\n    if (\n      isSpanContext(parentFromContext) &&\n      isSpanContextValid(parentFromContext)\n    ) {\n      return new NonRecordingSpan(parentFromContext);\n    } else {\n      return new NonRecordingSpan();\n    }\n  }\n\n  startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n    name: string,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n    name: string,\n    opts: SpanOptions | undefined,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n    name: string,\n    opts: SpanOptions | undefined,\n    ctx: Context | undefined,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n    name: string,\n    arg2?: F | SpanOptions,\n    arg3?: F | Context,\n    arg4?: F\n  ): ReturnType<F> | undefined {\n    let opts: SpanOptions | undefined;\n    let ctx: Context | undefined;\n    let fn: F;\n\n    if (arguments.length < 2) {\n      return;\n    } else if (arguments.length === 2) {\n      fn = arg2 as F;\n    } else if (arguments.length === 3) {\n      opts = arg2 as SpanOptions | undefined;\n      fn = arg3 as F;\n    } else {\n      opts = arg2 as SpanOptions | undefined;\n      ctx = arg3 as Context | undefined;\n      fn = arg4 as F;\n    }\n\n    const parentContext = ctx ?? contextApi.active();\n    const span = this.startSpan(name, opts, parentContext);\n    const contextWithSpanSet = setSpan(parentContext, span);\n\n    return contextApi.with(contextWithSpanSet, fn, undefined, span);\n  }\n}\n\nfunction isSpanContext(spanContext: any): spanContext is SpanContext {\n  return (\n    typeof spanContext === 'object' &&\n    typeof spanContext['spanId'] === 'string' &&\n    typeof spanContext['traceId'] === 'string' &&\n    typeof spanContext['traceFlags'] === 'number'\n  );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { NoopTracer } from './NoopTracer';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER = new NoopTracer();\n\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nexport class ProxyTracer implements Tracer {\n  // When a real implementation is provided, this will be it\n  private _delegate?: Tracer;\n\n  constructor(\n    private _provider: TracerDelegator,\n    public readonly name: string,\n    public readonly version?: string,\n    public readonly options?: TracerOptions\n  ) {}\n\n  startSpan(name: string, options?: SpanOptions, context?: Context): Span {\n    return this._getTracer().startSpan(name, options, context);\n  }\n\n  startActiveSpan<F extends (span: Span) => unknown>(\n    _name: string,\n    _options: F | SpanOptions,\n    _context?: F | Context,\n    _fn?: F\n  ): ReturnType<F> {\n    const tracer = this._getTracer();\n    return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n  }\n\n  /**\n   * Try to get a tracer from the proxy tracer provider.\n   * If the proxy tracer provider has no delegate, return a noop tracer.\n   */\n  private _getTracer() {\n    if (this._delegate) {\n      return this._delegate;\n    }\n\n    const tracer = this._provider.getDelegateTracer(\n      this.name,\n      this.version,\n      this.options\n    );\n\n    if (!tracer) {\n      return NOOP_TRACER;\n    }\n\n    this._delegate = tracer;\n    return this._delegate;\n  }\n}\n\nexport interface TracerDelegator {\n  getDelegateTracer(\n    name: string,\n    version?: string,\n    options?: TracerOptions\n  ): Tracer | undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopTracer } from './NoopTracer';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\nimport { TracerProvider } from './tracer_provider';\n\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nexport class NoopTracerProvider implements TracerProvider {\n  getTracer(\n    _name?: string,\n    _version?: string,\n    _options?: TracerOptions\n  ): Tracer {\n    return new NoopTracer();\n  }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerProvider } from './tracer_provider';\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n *   When a delegate is set, traces are provided from the delegate.\n *   When a delegate is set after tracers have already been provided,\n *   all tracers already provided will use the provided delegate implementation.\n */\nexport class ProxyTracerProvider implements TracerProvider {\n  private _delegate?: TracerProvider;\n\n  /**\n   * Get a {@link ProxyTracer}\n   */\n  getTracer(name: string, version?: string, options?: TracerOptions): Tracer {\n    return (\n      this.getDelegateTracer(name, version, options) ??\n      new ProxyTracer(this, name, version, options)\n    );\n  }\n\n  getDelegate(): TracerProvider {\n    return this._delegate ?? NOOP_TRACER_PROVIDER;\n  }\n\n  /**\n   * Set the delegate tracer provider\n   */\n  setDelegate(delegate: TracerProvider) {\n    this._delegate = delegate;\n  }\n\n  getDelegateTracer(\n    name: string,\n    version?: string,\n    options?: TracerOptions\n  ): Tracer | undefined {\n    return this._delegate?.getTracer(name, version, options);\n  }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n  /** The status code of this message. */\n  code: SpanStatusCode;\n  /** A developer-facing error message. */\n  message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n  /**\n   * The default status.\n   */\n  UNSET = 0,\n  /**\n   * The operation has been validated by an Application developer or\n   * Operator to have completed successfully.\n   */\n  OK = 1,\n  /**\n   * The operation contains an error.\n   */\n  ERROR = 2,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport const context = ContextAPI.getInstance();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  getGlobal,\n  registerGlobal,\n  unregisterGlobal,\n} from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport {\n  isSpanContextValid,\n  wrapSpanContext,\n} from '../trace/spancontext-utils';\nimport { Tracer } from '../trace/tracer';\nimport { TracerProvider } from '../trace/tracer_provider';\nimport {\n  deleteSpan,\n  getActiveSpan,\n  getSpan,\n  getSpanContext,\n  setSpan,\n  setSpanContext,\n} from '../trace/context-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'trace';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nexport class TraceAPI {\n  private static _instance?: TraceAPI;\n\n  private _proxyTracerProvider = new ProxyTracerProvider();\n\n  /** Empty private constructor prevents end users from constructing a new instance of the API */\n  private constructor() {}\n\n  /** Get the singleton instance of the Trace API */\n  public static getInstance(): TraceAPI {\n    if (!this._instance) {\n      this._instance = new TraceAPI();\n    }\n\n    return this._instance;\n  }\n\n  /**\n   * Set the current global tracer.\n   *\n   * @returns true if the tracer provider was successfully registered, else false\n   */\n  public setGlobalTracerProvider(provider: TracerProvider): boolean {\n    const success = registerGlobal(\n      API_NAME,\n      this._proxyTracerProvider,\n      DiagAPI.instance()\n    );\n    if (success) {\n      this._proxyTracerProvider.setDelegate(provider);\n    }\n    return success;\n  }\n\n  /**\n   * Returns the global tracer provider.\n   */\n  public getTracerProvider(): TracerProvider {\n    return getGlobal(API_NAME) || this._proxyTracerProvider;\n  }\n\n  /**\n   * Returns a tracer from the global tracer provider.\n   */\n  public getTracer(name: string, version?: string): Tracer {\n    return this.getTracerProvider().getTracer(name, version);\n  }\n\n  /** Remove the global tracer provider */\n  public disable() {\n    unregisterGlobal(API_NAME, DiagAPI.instance());\n    this._proxyTracerProvider = new ProxyTracerProvider();\n  }\n\n  public wrapSpanContext = wrapSpanContext;\n\n  public isSpanContextValid = isSpanContextValid;\n\n  public deleteSpan = deleteSpan;\n\n  public getSpan = getSpan;\n\n  public getActiveSpan = getActiveSpan;\n\n  public getSpanContext = getSpanContext;\n\n  public setSpan = setSpan;\n\n  public setSpanContext = setSpanContext;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport const trace = TraceAPI.getInstance();\n", "// import globals\nimport './global';\n\n// re-exports:\nexport { createGateway, gateway, type GatewayModelId } from '@ai-sdk/gateway';\nexport {\n  asSchema,\n  createIdGenerator,\n  dynamicTool,\n  generateId,\n  jsonSchema,\n  parseJsonEventStream,\n  tool,\n  zodSchema,\n  type FlexibleSchema,\n  type IdGenerator,\n  type InferSchema,\n  type InferToolInput,\n  type InferToolOutput,\n  type Schema,\n  type Tool,\n  type ToolApprovalRequest,\n  type ToolApprovalResponse,\n  type ToolCallOptions,\n  type ToolExecutionOptions,\n  type ToolExecuteFunction,\n} from '@ai-sdk/provider-utils';\n\n// directory exports\nexport * from './agent';\nexport * from './embed';\nexport * from './error';\nexport * from './generate-image';\nexport * from './generate-object';\nexport * from './generate-speech';\nexport * from './generate-text';\nexport * from './generate-video';\nexport * from './logger';\nexport * from './middleware';\nexport * from './prompt';\nexport * from './registry';\nexport * from './rerank';\nexport * from './text-stream';\nexport * from './transcribe';\nexport * from './types';\nexport * from './ui';\nexport * from './ui-message-stream';\nexport * from './util';\nexport * from './telemetry';\n", "import { validateTypes, type ModelMessage } from '@ai-sdk/provider-utils';\nimport { generateText } from '../generate-text/generate-text';\nimport type { GenerateTextResult } from '../generate-text/generate-text-result';\nimport type { Output } from '../generate-text/output';\nimport type { StepResult } from '../generate-text/step-result';\nimport { stepCountIs } from '../generate-text/stop-condition';\nimport { streamText } from '../generate-text/stream-text';\nimport type { StreamTextResult } from '../generate-text/stream-text-result';\nimport type { ToolSet } from '../generate-text/tool-set';\nimport type { Prompt } from '../prompt';\nimport type {\n  Agent,\n  AgentCallParameters,\n  AgentStreamParameters,\n} from './agent';\nimport type {\n  ToolLoopAgentOnStepFinishCallback,\n  ToolLoopAgentSettings,\n} from './tool-loop-agent-settings';\n\n/**\n * A tool loop agent is an agent that runs tools in a loop. In each step,\n * it calls the LLM, and if there are tool calls, it executes the tools\n * and calls the LLM again in a new step with the tool results.\n *\n * The loop continues until:\n * - A finish reasoning other than tool-calls is returned, or\n * - A tool that is invoked does not have an execute function, or\n * - A tool call needs approval, or\n * - A stop condition is met (default stop condition is stepCountIs(20))\n */\nexport class ToolLoopAgent<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  OUTPUT extends Output = never,\n> implements Agent<CALL_OPTIONS, TOOLS, OUTPUT> {\n  readonly version = 'agent-v1';\n\n  private readonly settings: ToolLoopAgentSettings<CALL_OPTIONS, TOOLS, OUTPUT>;\n\n  constructor(settings: ToolLoopAgentSettings<CALL_OPTIONS, TOOLS, OUTPUT>) {\n    this.settings = settings;\n  }\n\n  /**\n   * The id of the agent.\n   */\n  get id(): string | undefined {\n    return this.settings.id;\n  }\n\n  /**\n   * The tools that the agent can use.\n   */\n  get tools(): TOOLS {\n    return this.settings.tools as TOOLS;\n  }\n\n  private async prepareCall(options: {\n    prompt?: string | Array<ModelMessage>;\n    messages?: Array<ModelMessage>;\n    options?: CALL_OPTIONS;\n  }): Promise<\n    Omit<\n      ToolLoopAgentSettings<CALL_OPTIONS, TOOLS, OUTPUT>,\n      'prepareCall' | 'instructions' | 'onStepFinish'\n    > &\n      Prompt\n  > {\n    if (\n      this.settings.callOptionsSchema != null &&\n      options.options !== undefined\n    ) {\n      const validatedOptions = await validateTypes({\n        value: options.options,\n        schema: this.settings.callOptionsSchema,\n        context: { field: 'options' },\n      });\n      options = { ...options, options: validatedOptions };\n    }\n\n    const { onStepFinish: _settingsOnStepFinish, ...settingsWithoutCallback } =\n      this.settings;\n    const baseCallArgs = {\n      ...settingsWithoutCallback,\n      stopWhen: this.settings.stopWhen ?? stepCountIs(20),\n      ...options,\n    };\n\n    const preparedCallArgs =\n      (await this.settings.prepareCall?.(\n        baseCallArgs as Parameters<\n          NonNullable<\n            ToolLoopAgentSettings<CALL_OPTIONS, TOOLS, OUTPUT>['prepareCall']\n          >\n        >[0],\n      )) ?? baseCallArgs;\n\n    const { instructions, messages, prompt, ...callArgs } = preparedCallArgs;\n\n    return {\n      ...callArgs,\n\n      // restore prompt types\n      ...({ system: instructions, messages, prompt } as Prompt),\n    };\n  }\n\n  private mergeOnStepFinishCallbacks(\n    methodCallback: ToolLoopAgentOnStepFinishCallback<TOOLS> | undefined,\n  ): ToolLoopAgentOnStepFinishCallback<TOOLS> | undefined {\n    const constructorCallback = this.settings.onStepFinish;\n\n    if (methodCallback && constructorCallback) {\n      return async (stepResult: StepResult<TOOLS>) => {\n        await constructorCallback(stepResult);\n        await methodCallback(stepResult);\n      };\n    }\n\n    return methodCallback ?? constructorCallback;\n  }\n\n  /**\n   * Generates an output from the agent (non-streaming).\n   */\n  async generate({\n    abortSignal,\n    timeout,\n    onStepFinish,\n    ...options\n  }: AgentCallParameters<CALL_OPTIONS, TOOLS>): Promise<\n    GenerateTextResult<TOOLS, OUTPUT>\n  > {\n    return generateText({\n      ...(await this.prepareCall(options)),\n      abortSignal,\n      timeout,\n      onStepFinish: this.mergeOnStepFinishCallbacks(onStepFinish),\n    });\n  }\n\n  /**\n   * Streams an output from the agent (streaming).\n   */\n  async stream({\n    abortSignal,\n    timeout,\n    experimental_transform,\n    onStepFinish,\n    ...options\n  }: AgentStreamParameters<CALL_OPTIONS, TOOLS>): Promise<\n    StreamTextResult<TOOLS, OUTPUT>\n  > {\n    return streamText({\n      ...(await this.prepareCall(options)),\n      abortSignal,\n      timeout,\n      experimental_transform,\n      onStepFinish: this.mergeOnStepFinishCallbacks(onStepFinish),\n    });\n  }\n}\n", "import type {\n  LanguageModelV3,\n  LanguageModelV3Content,\n  LanguageModelV3ToolCall,\n} from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  getErrorMessage,\n  withUserAgentSuffix,\n  type IdGenerator,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport type { Tracer } from '@opentelemetry/api';\nimport { NoOutputGeneratedError } from '../error';\nimport { notify } from '../util/notify';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport type { ModelMessage } from '../prompt';\nimport {\n  getStepTimeoutMs,\n  getTotalTimeoutMs,\n  TimeoutConfiguration,\n  type CallSettings,\n} from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport { prepareCallSettings } from '../prompt/prepare-call-settings';\nimport { prepareToolsAndToolChoice } from '../prompt/prepare-tools-and-tool-choice';\nimport type { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { ToolCallNotFoundForApprovalError } from '../error/tool-call-not-found-for-approval-error';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport { stringifyForTelemetry } from '../telemetry/stringify-for-telemetry';\nimport { getGlobalTelemetryIntegration } from '../telemetry/get-global-telemetry-integration';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport type {\n  LanguageModel,\n  LanguageModelRequestMetadata,\n  ToolChoice,\n} from '../types';\nimport {\n  addLanguageModelUsage,\n  asLanguageModelUsage,\n  type LanguageModelUsage,\n} from '../types/usage';\nimport { asArray } from '../util/as-array';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { mergeObjects } from '../util/merge-objects';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type {\n  OnFinishEvent,\n  OnStartEvent,\n  OnStepFinishEvent,\n  OnStepStartEvent,\n  OnToolCallFinishEvent,\n  OnToolCallStartEvent,\n} from './callback-events';\nimport { collectToolApprovals } from './collect-tool-approvals';\nimport type { ContentPart } from './content-part';\nimport { executeToolCall } from './execute-tool-call';\nimport { extractReasoningContent } from './extract-reasoning-content';\nimport { extractTextContent } from './extract-text-content';\nimport type { GenerateTextResult } from './generate-text-result';\nimport { DefaultGeneratedFile } from './generated-file';\nimport { isApprovalNeeded } from './is-approval-needed';\nimport { text, type Output } from './output';\nimport type { InferCompleteOutput } from './output-utils';\nimport { parseToolCall } from './parse-tool-call';\nimport type { PrepareStepFunction } from './prepare-step';\nimport type { ResponseMessage } from './response-message';\nimport { DefaultStepResult, type StepResult } from './step-result';\nimport {\n  isStopConditionMet,\n  stepCountIs,\n  type StopCondition,\n} from './stop-condition';\nimport { toResponseMessages } from './to-response-messages';\nimport type { ToolApprovalRequestOutput } from './tool-approval-request-output';\nimport type { TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type { TypedToolError } from './tool-error';\nimport type { ToolOutput } from './tool-output';\nimport type { TypedToolResult } from './tool-result';\nimport type { ToolSet } from './tool-set';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\n\nconst originalGenerateId = createIdGenerator({\n  prefix: 'aitxt',\n  size: 24,\n});\n\n/**\n * Include settings for generateText (requestBody and responseBody).\n */\ntype GenerateTextIncludeSettings = {\n  requestBody?: boolean;\n  responseBody?: boolean;\n};\n\n/**\n * Callback that is set using the `experimental_onStart` option.\n *\n * Called when the generateText operation begins, before any LLM calls.\n * Use this callback for logging, analytics, or initializing state at the\n * start of a generation.\n *\n * @param event - The event object containing generation configuration.\n */\nexport type GenerateTextOnStartCallback<\n  TOOLS extends ToolSet = ToolSet,\n  OUTPUT extends Output = Output,\n> = (\n  event: OnStartEvent<TOOLS, OUTPUT, GenerateTextIncludeSettings>,\n) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `experimental_onStepStart` option.\n *\n * Called when a step (LLM call) begins, before the provider is called.\n * Each step represents a single LLM invocation. Multiple steps occur when\n * using tool calls (the model may be called multiple times in a loop).\n *\n * @param event - The event object containing step configuration.\n */\nexport type GenerateTextOnStepStartCallback<\n  TOOLS extends ToolSet = ToolSet,\n  OUTPUT extends Output = Output,\n> = (\n  event: OnStepStartEvent<TOOLS, OUTPUT, GenerateTextIncludeSettings>,\n) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `experimental_onToolCallStart` option.\n *\n * Called when a tool execution begins, before the tool's `execute` function is invoked.\n * Use this for logging tool invocations, tracking tool usage, or pre-execution validation.\n *\n * @param event - The event object containing tool call information.\n */\nexport type GenerateTextOnToolCallStartCallback<\n  TOOLS extends ToolSet = ToolSet,\n> = (event: OnToolCallStartEvent<TOOLS>) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `experimental_onToolCallFinish` option.\n *\n * Called when a tool execution completes, either successfully or with an error.\n * Use this for logging tool results, tracking execution time, or error handling.\n *\n * The event uses a discriminated union on the `success` field:\n * - When `success: true`: `output` contains the tool result, `error` is never present.\n * - When `success: false`: `error` contains the error, `output` is never present.\n *\n * @param event - The event object containing tool call result information.\n */\nexport type GenerateTextOnToolCallFinishCallback<\n  TOOLS extends ToolSet = ToolSet,\n> = (event: OnToolCallFinishEvent<TOOLS>) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `onStepFinish` option.\n *\n * Called when a step (LLM call) completes. The event includes all step result\n * properties (text, tool calls, usage, etc.) along with additional metadata.\n *\n * @param stepResult - The result of the step.\n */\nexport type GenerateTextOnStepFinishCallback<TOOLS extends ToolSet> = (\n  event: OnStepFinishEvent<TOOLS>,\n) => Promise<void> | void;\n\n/**\n * Callback that is set using the `onFinish` option.\n *\n * Called when the entire generation completes (all steps finished).\n * The event includes the final step's result properties along with\n * aggregated data from all steps.\n *\n * @param event - The final result along with aggregated step data.\n */\nexport type GenerateTextOnFinishCallback<TOOLS extends ToolSet> = (\n  event: OnFinishEvent<TOOLS>,\n) => PromiseLike<void> | void;\n\n/**\n * Generate a text and call tools for a given prompt using a language model.\n *\n * This function does not stream the output. If you want to stream the output, use `streamText` instead.\n *\n * @param model - The language model to use.\n *\n * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n * @param toolChoice - The tool choice strategy. Default: 'auto'.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. When unset, system messages are allowed with a warning.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param experimental_context - User-defined context object that flows through the entire generation lifecycle.\n * @param experimental_onStart - Callback invoked when generation begins, before any LLM calls.\n * @param experimental_onStepStart - Callback invoked when each step begins, before the provider is called.\n * Receives step number, messages (in ModelMessage format), tools, and context.\n * @param experimental_onToolCallStart - Callback invoked before each tool execution begins.\n * Receives tool name, call ID, input, and context.\n * @param experimental_onToolCallFinish - Callback invoked after each tool execution completes.\n * Uses a discriminated union: check `success` to determine if `output` or `error` is present.\n * @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.\n * @param onFinish - Callback that is called when all steps are finished and the response is complete.\n *\n * @returns\n * A result object that contains the generated text, the results of the tool calls, and additional information.\n */\nexport async function generateText<\n  TOOLS extends ToolSet,\n  OUTPUT extends Output = Output<string, string>,\n>({\n  model: modelArg,\n  tools,\n  toolChoice,\n  system,\n  prompt,\n  messages,\n  allowSystemInMessages,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  timeout,\n  headers,\n  stopWhen = stepCountIs(1),\n  experimental_output,\n  output = experimental_output,\n  experimental_telemetry: telemetry,\n  providerOptions,\n  experimental_activeTools,\n  activeTools = experimental_activeTools,\n  experimental_prepareStep,\n  prepareStep = experimental_prepareStep,\n  experimental_repairToolCall: repairToolCall,\n  experimental_download: download,\n  experimental_context,\n  experimental_include: include,\n  _internal: { generateId = originalGenerateId } = {},\n  experimental_onStart: onStart,\n  experimental_onStepStart: onStepStart,\n  experimental_onToolCallStart: onToolCallStart,\n  experimental_onToolCallFinish: onToolCallFinish,\n  onStepFinish,\n  onFinish,\n  ...settings\n}: CallSettings &\n  Prompt & {\n    /**\n     * The language model to use.\n     */\n    model: LanguageModel;\n\n    /**\n     * The tools that the model can call. The model needs to support calling tools.\n     */\n    tools?: TOOLS;\n\n    /**\n     * The tool choice strategy. Default: 'auto'.\n     */\n    toolChoice?: ToolChoice<NoInfer<TOOLS>>;\n\n    /**\n     * Condition for stopping the generation when there are tool results in the last step.\n     * When the condition is an array, any of the conditions can be met to stop the generation.\n     *\n     * @default stepCountIs(1)\n     */\n    stopWhen?:\n      | StopCondition<NoInfer<TOOLS>>\n      | Array<StopCondition<NoInfer<TOOLS>>>;\n\n    /**\n     * Optional telemetry configuration (experimental).\n     */\n    experimental_telemetry?: TelemetrySettings;\n\n    /**\n     * Additional provider-specific options. They are passed through\n     * to the provider from the AI SDK and enable provider-specific\n     * functionality that can be fully encapsulated in the provider.\n     */\n    providerOptions?: ProviderOptions;\n\n    /**\n     * @deprecated Use `activeTools` instead.\n     */\n    experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;\n\n    /**\n     * Limits the tools that are available for the model to call without\n     * changing the tool call and result types in the result.\n     */\n    activeTools?: Array<keyof NoInfer<TOOLS>>;\n\n    /**\n     * Optional specification for parsing structured outputs from the LLM response.\n     */\n    output?: OUTPUT;\n\n    /**\n     * Optional specification for parsing structured outputs from the LLM response.\n     *\n     * @deprecated Use `output` instead.\n     */\n    experimental_output?: OUTPUT;\n\n    /**\n     * Custom download function to use for URLs.\n     *\n     * By default, files are downloaded if the model does not support the URL for the given media type.\n     */\n    experimental_download?: DownloadFunction | undefined;\n\n    /**\n     * @deprecated Use `prepareStep` instead.\n     */\n    experimental_prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;\n\n    /**\n     * Optional function that you can use to provide different settings for a step.\n     */\n    prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;\n\n    /**\n     * A function that attempts to repair a tool call that failed to parse.\n     */\n    experimental_repairToolCall?: ToolCallRepairFunction<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called when the generateText operation begins,\n     * before any LLM calls are made.\n     */\n    experimental_onStart?: GenerateTextOnStartCallback<NoInfer<TOOLS>, OUTPUT>;\n\n    /**\n     * Callback that is called when a step (LLM call) begins,\n     * before the provider is called.\n     */\n    experimental_onStepStart?: GenerateTextOnStepStartCallback<\n      NoInfer<TOOLS>,\n      OUTPUT\n    >;\n\n    /**\n     * Callback that is called right before a tool's execute function runs.\n     */\n    experimental_onToolCallStart?: GenerateTextOnToolCallStartCallback<\n      NoInfer<TOOLS>\n    >;\n\n    /**\n     * Callback that is called right after a tool's execute function completes (or errors).\n     */\n    experimental_onToolCallFinish?: GenerateTextOnToolCallFinishCallback<\n      NoInfer<TOOLS>\n    >;\n\n    /**\n     * Callback that is called when each step (LLM call) is finished, including intermediate steps.\n     */\n    onStepFinish?: GenerateTextOnStepFinishCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called when all steps are finished and the response is complete.\n     */\n    onFinish?: GenerateTextOnFinishCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Context that is passed into tool execution.\n     *\n     * Experimental (can break in patch releases).\n     *\n     * @default undefined\n     */\n    experimental_context?: unknown;\n\n    /**\n     * Settings for controlling what data is included in step results.\n     * Disabling inclusion can help reduce memory usage when processing\n     * large payloads like images.\n     *\n     * By default, all data is included for backwards compatibility.\n     */\n    experimental_include?: {\n      /**\n       * Whether to retain the request body in step results.\n       * The request body can be large when sending images or files.\n       * @default true\n       */\n      requestBody?: boolean;\n\n      /**\n       * Whether to retain the response body in step results.\n       * @default true\n       */\n      responseBody?: boolean;\n    };\n\n    /**\n     * Internal. For test use only. May change without notice.\n     */\n    _internal?: {\n      generateId?: IdGenerator;\n    };\n  }): Promise<GenerateTextResult<TOOLS, OUTPUT>> {\n  const model = resolveLanguageModel(modelArg);\n  const createGlobalTelemetry = getGlobalTelemetryIntegration<TOOLS, OUTPUT>();\n  const stopConditions = asArray(stopWhen);\n\n  const totalTimeoutMs = getTotalTimeoutMs(timeout);\n  const stepTimeoutMs = getStepTimeoutMs(timeout);\n  const stepAbortController =\n    stepTimeoutMs != null ? new AbortController() : undefined;\n  const mergedAbortSignal = mergeAbortSignals(\n    abortSignal,\n    totalTimeoutMs != null ? AbortSignal.timeout(totalTimeoutMs) : undefined,\n    stepAbortController?.signal,\n  );\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal: mergedAbortSignal,\n  });\n\n  const callSettings = prepareCallSettings(settings);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const baseTelemetryAttributes = getBaseTelemetryAttributes({\n    model,\n    telemetry,\n    headers: headersWithUserAgent,\n    settings: { ...callSettings, maxRetries },\n  });\n\n  const modelInfo = { provider: model.provider, modelId: model.modelId };\n\n  const initialPrompt = await standardizePrompt({\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n  } as Prompt);\n\n  const globalTelemetry = createGlobalTelemetry(telemetry?.integrations);\n\n  await notify({\n    event: {\n      model: modelInfo,\n      system,\n      prompt,\n      messages,\n      tools,\n      toolChoice,\n      activeTools,\n      maxOutputTokens: callSettings.maxOutputTokens,\n      temperature: callSettings.temperature,\n      topP: callSettings.topP,\n      topK: callSettings.topK,\n      presencePenalty: callSettings.presencePenalty,\n      frequencyPenalty: callSettings.frequencyPenalty,\n      stopSequences: callSettings.stopSequences,\n      seed: callSettings.seed,\n      maxRetries,\n      timeout,\n      headers,\n      providerOptions,\n      stopWhen,\n      output,\n      abortSignal,\n      include,\n      functionId: telemetry?.functionId,\n      metadata: telemetry?.metadata as Record<string, unknown> | undefined,\n      experimental_context,\n    },\n    callbacks: [\n      onStart,\n      globalTelemetry.onStart as\n        | undefined\n        | GenerateTextOnStartCallback<TOOLS, OUTPUT>,\n    ],\n  });\n\n  const tracer = getTracer(telemetry);\n\n  try {\n    return await recordSpan({\n      name: 'ai.generateText',\n      attributes: selectTelemetryAttributes({\n        telemetry,\n        attributes: {\n          ...assembleOperationName({\n            operationId: 'ai.generateText',\n            telemetry,\n          }),\n          ...baseTelemetryAttributes,\n          // model:\n          'ai.model.provider': model.provider,\n          'ai.model.id': model.modelId,\n          // specific settings that only make sense on the outer level:\n          'ai.prompt': {\n            input: () => JSON.stringify({ system, prompt, messages }),\n          },\n        },\n      }),\n      tracer,\n      fn: async span => {\n        const initialMessages = initialPrompt.messages;\n        const responseMessages: Array<ResponseMessage> = [];\n\n        const { approvedToolApprovals, deniedToolApprovals } =\n          collectToolApprovals<TOOLS>({ messages: initialMessages });\n\n        const localApprovedToolApprovals = approvedToolApprovals.filter(\n          toolApproval => !toolApproval.toolCall.providerExecuted,\n        );\n\n        if (\n          deniedToolApprovals.length > 0 ||\n          localApprovedToolApprovals.length > 0\n        ) {\n          const toolOutputs = await executeTools({\n            toolCalls: localApprovedToolApprovals.map(\n              toolApproval => toolApproval.toolCall,\n            ),\n            tools: tools as TOOLS,\n            tracer,\n            telemetry,\n            messages: initialMessages,\n            abortSignal: mergedAbortSignal,\n            experimental_context,\n            stepNumber: 0,\n            model: modelInfo,\n            onToolCallStart: [\n              onToolCallStart,\n              globalTelemetry.onToolCallStart as\n                | undefined\n                | GenerateTextOnToolCallStartCallback<TOOLS>,\n            ],\n            onToolCallFinish: [\n              onToolCallFinish,\n              globalTelemetry.onToolCallFinish as\n                | undefined\n                | GenerateTextOnToolCallFinishCallback<TOOLS>,\n            ],\n          });\n\n          const toolContent: Array<any> = [];\n\n          // add regular tool results for approved tool calls:\n          for (const output of toolOutputs) {\n            const modelOutput = await createToolModelOutput({\n              toolCallId: output.toolCallId,\n              input: output.input,\n              tool: tools?.[output.toolName],\n              output:\n                output.type === 'tool-result' ? output.output : output.error,\n              errorMode: output.type === 'tool-error' ? 'text' : 'none',\n            });\n\n            toolContent.push({\n              type: 'tool-result' as const,\n              toolCallId: output.toolCallId,\n              toolName: output.toolName,\n              output: modelOutput,\n            });\n          }\n\n          // add execution denied tool results for all denied tool approvals:\n          for (const toolApproval of deniedToolApprovals) {\n            toolContent.push({\n              type: 'tool-result' as const,\n              toolCallId: toolApproval.toolCall.toolCallId,\n              toolName: toolApproval.toolCall.toolName,\n              output: {\n                type: 'execution-denied' as const,\n                reason: toolApproval.approvalResponse.reason,\n                // For provider-executed tools, include approvalId so provider can correlate\n                ...(toolApproval.toolCall.providerExecuted && {\n                  providerOptions: {\n                    openai: {\n                      approvalId: toolApproval.approvalResponse.approvalId,\n                    },\n                  },\n                }),\n              },\n            });\n          }\n\n          responseMessages.push({\n            role: 'tool',\n            content: toolContent,\n          });\n        }\n\n        const callSettings = prepareCallSettings(settings);\n\n        let currentModelResponse: Awaited<\n          ReturnType<LanguageModelV3['doGenerate']>\n        > & { response: { id: string; timestamp: Date; modelId: string } };\n        let clientToolCalls: Array<TypedToolCall<TOOLS>> = [];\n        let clientToolOutputs: Array<ToolOutput<TOOLS>> = [];\n        const steps: GenerateTextResult<TOOLS, OUTPUT>['steps'] = [];\n\n        // Track provider-executed tool calls that support deferred results\n        // (e.g., code_execution in programmatic tool calling scenarios).\n        // These tools may not return their results in the same turn as their call.\n        const pendingDeferredToolCalls = new Map<\n          string,\n          { toolName: string }\n        >();\n\n        do {\n          // Set up step timeout if configured\n          const stepTimeoutId =\n            stepTimeoutMs != null\n              ? setTimeout(() => stepAbortController!.abort(), stepTimeoutMs)\n              : undefined;\n\n          try {\n            const stepInputMessages = [...initialMessages, ...responseMessages];\n\n            const prepareStepResult = await prepareStep?.({\n              model,\n              steps,\n              stepNumber: steps.length,\n              messages: stepInputMessages,\n              experimental_context,\n            });\n\n            const stepModel = resolveLanguageModel(\n              prepareStepResult?.model ?? model,\n            );\n            const stepModelInfo = {\n              provider: stepModel.provider,\n              modelId: stepModel.modelId,\n            };\n\n            const promptMessages = await convertToLanguageModelPrompt({\n              prompt: {\n                system: prepareStepResult?.system ?? initialPrompt.system,\n                messages: prepareStepResult?.messages ?? stepInputMessages,\n              },\n              supportedUrls: await stepModel.supportedUrls,\n              download,\n            });\n\n            experimental_context =\n              prepareStepResult?.experimental_context ?? experimental_context;\n\n            const stepActiveTools =\n              prepareStepResult?.activeTools ?? activeTools;\n\n            const { toolChoice: stepToolChoice, tools: stepTools } =\n              await prepareToolsAndToolChoice({\n                tools,\n                toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n                activeTools: stepActiveTools,\n              });\n\n            const stepMessages =\n              prepareStepResult?.messages ?? stepInputMessages;\n\n            const stepSystem =\n              prepareStepResult?.system ?? initialPrompt.system;\n\n            const stepProviderOptions = mergeObjects(\n              providerOptions,\n              prepareStepResult?.providerOptions,\n            );\n\n            await notify({\n              event: {\n                stepNumber: steps.length,\n                model: stepModelInfo,\n                system: stepSystem,\n                messages: stepMessages,\n                tools,\n                toolChoice: stepToolChoice,\n                activeTools: stepActiveTools,\n                steps: [...steps],\n                providerOptions: stepProviderOptions,\n                timeout,\n                headers,\n                stopWhen,\n                output,\n                abortSignal,\n                include,\n                functionId: telemetry?.functionId,\n                metadata: telemetry?.metadata as\n                  | Record<string, unknown>\n                  | undefined,\n                experimental_context,\n              },\n              callbacks: [\n                onStepStart,\n                globalTelemetry.onStepStart as\n                  | undefined\n                  | GenerateTextOnStepStartCallback<TOOLS, OUTPUT>,\n              ],\n            });\n\n            currentModelResponse = await retry(() =>\n              recordSpan({\n                name: 'ai.generateText.doGenerate',\n                attributes: selectTelemetryAttributes({\n                  telemetry,\n                  attributes: {\n                    ...assembleOperationName({\n                      operationId: 'ai.generateText.doGenerate',\n                      telemetry,\n                    }),\n                    ...baseTelemetryAttributes,\n                    // model:\n                    'ai.model.provider': stepModel.provider,\n                    'ai.model.id': stepModel.modelId,\n                    // prompt:\n                    'ai.prompt.messages': {\n                      input: () => stringifyForTelemetry(promptMessages),\n                    },\n                    'ai.prompt.tools': {\n                      // convert the language model level tools:\n                      input: () => stepTools?.map(tool => JSON.stringify(tool)),\n                    },\n                    'ai.prompt.toolChoice': {\n                      input: () =>\n                        stepToolChoice != null\n                          ? JSON.stringify(stepToolChoice)\n                          : undefined,\n                    },\n\n                    // standardized gen-ai llm span attributes:\n                    'gen_ai.system': stepModel.provider,\n                    'gen_ai.request.model': stepModel.modelId,\n                    'gen_ai.request.frequency_penalty':\n                      settings.frequencyPenalty,\n                    'gen_ai.request.max_tokens': settings.maxOutputTokens,\n                    'gen_ai.request.presence_penalty': settings.presencePenalty,\n                    'gen_ai.request.stop_sequences': settings.stopSequences,\n                    'gen_ai.request.temperature':\n                      settings.temperature ?? undefined,\n                    'gen_ai.request.top_k': settings.topK,\n                    'gen_ai.request.top_p': settings.topP,\n                  },\n                }),\n                tracer,\n                fn: async span => {\n                  const result = await stepModel.doGenerate({\n                    ...callSettings,\n                    tools: stepTools,\n                    toolChoice: stepToolChoice,\n                    responseFormat: await output?.responseFormat,\n                    prompt: promptMessages,\n                    providerOptions: stepProviderOptions,\n                    abortSignal: mergedAbortSignal,\n                    headers: headersWithUserAgent,\n                  });\n\n                  // Fill in default values:\n                  const responseData = {\n                    id: result.response?.id ?? generateId(),\n                    timestamp: result.response?.timestamp ?? new Date(),\n                    modelId: result.response?.modelId ?? stepModel.modelId,\n                    headers: result.response?.headers,\n                    body: result.response?.body,\n                  };\n                  const usage = asLanguageModelUsage(result.usage);\n\n                  // Add response information to the span:\n                  span.setAttributes(\n                    await selectTelemetryAttributes({\n                      telemetry,\n                      attributes: {\n                        'ai.response.finishReason': result.finishReason.unified,\n                        'ai.response.text': {\n                          output: () => extractTextContent(result.content),\n                        },\n                        'ai.response.reasoning': {\n                          output: () => extractReasoningContent(result.content),\n                        },\n                        'ai.response.toolCalls': {\n                          output: () => {\n                            const toolCalls = asToolCalls(result.content);\n                            return toolCalls == null\n                              ? undefined\n                              : JSON.stringify(toolCalls);\n                          },\n                        },\n                        'ai.response.id': responseData.id,\n                        'ai.response.model': responseData.modelId,\n                        'ai.response.timestamp':\n                          responseData.timestamp.toISOString(),\n                        'ai.response.providerMetadata': JSON.stringify(\n                          result.providerMetadata,\n                        ),\n\n                        'ai.usage.inputTokens': result.usage.inputTokens.total,\n                        'ai.usage.inputTokenDetails.noCacheTokens':\n                          result.usage.inputTokens.noCache,\n                        'ai.usage.inputTokenDetails.cacheReadTokens':\n                          result.usage.inputTokens.cacheRead,\n                        'ai.usage.inputTokenDetails.cacheWriteTokens':\n                          result.usage.inputTokens.cacheWrite,\n                        'ai.usage.outputTokens':\n                          result.usage.outputTokens.total,\n                        'ai.usage.outputTokenDetails.textTokens':\n                          result.usage.outputTokens.text,\n                        'ai.usage.outputTokenDetails.reasoningTokens':\n                          result.usage.outputTokens.reasoning,\n                        'ai.usage.totalTokens': usage.totalTokens,\n                        'ai.usage.reasoningTokens':\n                          result.usage.outputTokens.reasoning,\n                        'ai.usage.cachedInputTokens':\n                          result.usage.inputTokens.cacheRead,\n\n                        // standardized gen-ai llm span attributes:\n                        'gen_ai.response.finish_reasons': [\n                          result.finishReason.unified,\n                        ],\n                        'gen_ai.response.id': responseData.id,\n                        'gen_ai.response.model': responseData.modelId,\n                        'gen_ai.usage.input_tokens':\n                          result.usage.inputTokens.total,\n                        'gen_ai.usage.output_tokens':\n                          result.usage.outputTokens.total,\n                      },\n                    }),\n                  );\n\n                  return { ...result, response: responseData };\n                },\n              }),\n            );\n\n            // parse tool calls:\n            const stepToolCalls: TypedToolCall<TOOLS>[] = await Promise.all(\n              currentModelResponse.content\n                .filter(\n                  (part): part is LanguageModelV3ToolCall =>\n                    part.type === 'tool-call',\n                )\n                .map(toolCall =>\n                  parseToolCall({\n                    toolCall,\n                    tools,\n                    repairToolCall,\n                    system,\n                    messages: stepInputMessages,\n                  }),\n                ),\n            );\n            const toolApprovalRequests: Record<\n              string,\n              ToolApprovalRequestOutput<TOOLS>\n            > = {};\n\n            // notify the tools that the tool calls are available:\n            for (const toolCall of stepToolCalls) {\n              if (toolCall.invalid) {\n                continue; // ignore invalid tool calls\n              }\n\n              const tool = tools?.[toolCall.toolName];\n\n              if (tool == null) {\n                // ignore tool calls for tools that are not available,\n                // e.g. provider-executed dynamic tools\n                continue;\n              }\n\n              if (tool?.onInputAvailable != null) {\n                await tool.onInputAvailable({\n                  input: toolCall.input,\n                  toolCallId: toolCall.toolCallId,\n                  messages: stepInputMessages,\n                  abortSignal: mergedAbortSignal,\n                  experimental_context,\n                });\n              }\n\n              if (\n                await isApprovalNeeded({\n                  tool,\n                  toolCall,\n                  messages: stepInputMessages,\n                  experimental_context,\n                })\n              ) {\n                toolApprovalRequests[toolCall.toolCallId] = {\n                  type: 'tool-approval-request',\n                  approvalId: generateId(),\n                  toolCall,\n                };\n              }\n            }\n\n            // insert error tool outputs for invalid tool calls:\n            // TODO AI SDK 6: invalid inputs should not require output parts\n            const invalidToolCalls = stepToolCalls.filter(\n              toolCall => toolCall.invalid && toolCall.dynamic,\n            );\n\n            clientToolOutputs = [];\n\n            for (const toolCall of invalidToolCalls) {\n              clientToolOutputs.push({\n                type: 'tool-error',\n                toolCallId: toolCall.toolCallId,\n                toolName: toolCall.toolName,\n                input: toolCall.input,\n                error: getErrorMessage(toolCall.error!),\n                dynamic: true,\n              });\n            }\n\n            // execute client tool calls:\n            clientToolCalls = stepToolCalls.filter(\n              toolCall => !toolCall.providerExecuted,\n            );\n\n            if (tools != null) {\n              clientToolOutputs.push(\n                ...(await executeTools({\n                  toolCalls: clientToolCalls.filter(\n                    toolCall =>\n                      !toolCall.invalid &&\n                      toolApprovalRequests[toolCall.toolCallId] == null,\n                  ),\n                  tools,\n                  tracer,\n                  telemetry,\n                  messages: stepInputMessages,\n                  abortSignal: mergedAbortSignal,\n                  experimental_context,\n                  stepNumber: steps.length,\n                  model: stepModelInfo,\n                  onToolCallStart: [\n                    onToolCallStart,\n                    globalTelemetry.onToolCallStart as\n                      | undefined\n                      | GenerateTextOnToolCallStartCallback<TOOLS>,\n                  ],\n                  onToolCallFinish: [\n                    onToolCallFinish,\n                    globalTelemetry.onToolCallFinish,\n                  ],\n                })),\n              );\n            }\n\n            // Track provider-executed tool calls that support deferred results.\n            // In programmatic tool calling, a server tool (e.g., code_execution) may\n            // trigger a client tool, and the server tool's result is deferred until\n            // the client tool's result is sent back.\n            for (const toolCall of stepToolCalls) {\n              if (!toolCall.providerExecuted) continue;\n              const tool = tools?.[toolCall.toolName];\n              if (tool?.type === 'provider' && tool.supportsDeferredResults) {\n                // Check if this tool call already has a result in the current response\n                const hasResultInResponse = currentModelResponse.content.some(\n                  part =>\n                    part.type === 'tool-result' &&\n                    part.toolCallId === toolCall.toolCallId,\n                );\n                if (!hasResultInResponse) {\n                  pendingDeferredToolCalls.set(toolCall.toolCallId, {\n                    toolName: toolCall.toolName,\n                  });\n                }\n              }\n            }\n\n            // Mark deferred tool calls as resolved when we receive their results\n            for (const part of currentModelResponse.content) {\n              if (part.type === 'tool-result') {\n                pendingDeferredToolCalls.delete(part.toolCallId);\n              }\n            }\n\n            // content:\n            const stepContent = asContent({\n              content: currentModelResponse.content,\n              toolCalls: stepToolCalls,\n              toolOutputs: clientToolOutputs,\n              toolApprovalRequests: Object.values(toolApprovalRequests),\n              tools,\n            });\n\n            // append to messages for potential next step:\n            responseMessages.push(\n              ...(await toResponseMessages({\n                content: stepContent,\n                tools,\n              })),\n            );\n\n            // Add step information (after response messages are updated):\n            // Conditionally include request.body and response.body based on include settings.\n            // Large payloads (e.g., base64-encoded images) can cause memory issues.\n            const stepRequest: LanguageModelRequestMetadata =\n              (include?.requestBody ?? true)\n                ? (currentModelResponse.request ?? {})\n                : { ...currentModelResponse.request, body: undefined };\n\n            const stepResponse = {\n              ...currentModelResponse.response,\n              // deep clone msgs to avoid mutating past messages in multi-step:\n              messages: structuredClone(responseMessages),\n              // Conditionally include response body:\n              body:\n                (include?.responseBody ?? true)\n                  ? currentModelResponse.response?.body\n                  : undefined,\n            };\n\n            const stepNumber = steps.length;\n\n            const currentStepResult: StepResult<TOOLS> = new DefaultStepResult({\n              stepNumber,\n              model: stepModelInfo,\n              functionId: telemetry?.functionId,\n              metadata: telemetry?.metadata as\n                | Record<string, unknown>\n                | undefined,\n              experimental_context,\n              content: stepContent,\n              finishReason: currentModelResponse.finishReason.unified,\n              rawFinishReason: currentModelResponse.finishReason.raw,\n              usage: asLanguageModelUsage(currentModelResponse.usage),\n              warnings: currentModelResponse.warnings,\n              providerMetadata: currentModelResponse.providerMetadata,\n              request: stepRequest,\n              response: stepResponse,\n            });\n\n            logWarnings({\n              warnings: currentModelResponse.warnings ?? [],\n              provider: stepModelInfo.provider,\n              model: stepModelInfo.modelId,\n            });\n\n            steps.push(currentStepResult);\n\n            await notify({\n              event: currentStepResult,\n              callbacks: [onStepFinish, globalTelemetry.onStepFinish],\n            });\n          } finally {\n            if (stepTimeoutId != null) {\n              clearTimeout(stepTimeoutId);\n            }\n          }\n        } while (\n          // Continue if:\n          // 1. There are client tool calls that have all been executed, OR\n          // 2. There are pending deferred results from provider-executed tools\n          ((clientToolCalls.length > 0 &&\n            clientToolOutputs.length === clientToolCalls.length) ||\n            pendingDeferredToolCalls.size > 0) &&\n          // continue until a stop condition is met:\n          !(await isStopConditionMet({ stopConditions, steps }))\n        );\n\n        // Add response information to the span:\n        span.setAttributes(\n          await selectTelemetryAttributes({\n            telemetry,\n            attributes: {\n              'ai.response.finishReason':\n                currentModelResponse.finishReason.unified,\n              'ai.response.text': {\n                output: () => extractTextContent(currentModelResponse.content),\n              },\n              'ai.response.reasoning': {\n                output: () =>\n                  extractReasoningContent(currentModelResponse.content),\n              },\n              'ai.response.toolCalls': {\n                output: () => {\n                  const toolCalls = asToolCalls(currentModelResponse.content);\n                  return toolCalls == null\n                    ? undefined\n                    : JSON.stringify(toolCalls);\n                },\n              },\n              'ai.response.providerMetadata': JSON.stringify(\n                currentModelResponse.providerMetadata,\n              ),\n            },\n          }),\n        );\n\n        const lastStep = steps[steps.length - 1];\n\n        const totalUsage = steps.reduce(\n          (totalUsage, step) => {\n            return addLanguageModelUsage(totalUsage, step.usage);\n          },\n          {\n            inputTokens: undefined,\n            outputTokens: undefined,\n            totalTokens: undefined,\n            reasoningTokens: undefined,\n            cachedInputTokens: undefined,\n          } as LanguageModelUsage,\n        );\n\n        span.setAttributes(\n          await selectTelemetryAttributes({\n            telemetry,\n            attributes: {\n              'ai.usage.inputTokens': totalUsage.inputTokens,\n              'ai.usage.inputTokenDetails.noCacheTokens':\n                totalUsage.inputTokenDetails?.noCacheTokens,\n              'ai.usage.inputTokenDetails.cacheReadTokens':\n                totalUsage.inputTokenDetails?.cacheReadTokens,\n              'ai.usage.inputTokenDetails.cacheWriteTokens':\n                totalUsage.inputTokenDetails?.cacheWriteTokens,\n              'ai.usage.outputTokens': totalUsage.outputTokens,\n              'ai.usage.outputTokenDetails.textTokens':\n                totalUsage.outputTokenDetails?.textTokens,\n              'ai.usage.outputTokenDetails.reasoningTokens':\n                totalUsage.outputTokenDetails?.reasoningTokens,\n              'ai.usage.totalTokens': totalUsage.totalTokens,\n              'ai.usage.reasoningTokens':\n                totalUsage.outputTokenDetails?.reasoningTokens,\n              'ai.usage.cachedInputTokens':\n                totalUsage.inputTokenDetails?.cacheReadTokens,\n            },\n          }),\n        );\n\n        await notify({\n          event: {\n            stepNumber: lastStep.stepNumber,\n            model: lastStep.model,\n            functionId: lastStep.functionId,\n            metadata: lastStep.metadata,\n            experimental_context: lastStep.experimental_context,\n            finishReason: lastStep.finishReason,\n            rawFinishReason: lastStep.rawFinishReason,\n            usage: lastStep.usage,\n            content: lastStep.content,\n            text: lastStep.text,\n            reasoningText: lastStep.reasoningText,\n            reasoning: lastStep.reasoning,\n            files: lastStep.files,\n            sources: lastStep.sources,\n            toolCalls: lastStep.toolCalls,\n            staticToolCalls: lastStep.staticToolCalls,\n            dynamicToolCalls: lastStep.dynamicToolCalls,\n            toolResults: lastStep.toolResults,\n            staticToolResults: lastStep.staticToolResults,\n            dynamicToolResults: lastStep.dynamicToolResults,\n            request: lastStep.request,\n            response: lastStep.response,\n            warnings: lastStep.warnings,\n            providerMetadata: lastStep.providerMetadata,\n            steps,\n            totalUsage,\n          },\n          callbacks: [\n            onFinish,\n            globalTelemetry.onFinish as\n              | undefined\n              | GenerateTextOnFinishCallback<TOOLS>,\n          ],\n        });\n\n        // parse output only if the last step was finished with \"stop\":\n        let resolvedOutput;\n        if (lastStep.finishReason === 'stop') {\n          const outputSpecification = output ?? text();\n          resolvedOutput = await outputSpecification.parseCompleteOutput(\n            { text: lastStep.text },\n            {\n              response: lastStep.response,\n              usage: lastStep.usage,\n              finishReason: lastStep.finishReason,\n            },\n          );\n        }\n\n        return new DefaultGenerateTextResult({\n          steps,\n          totalUsage,\n          output: resolvedOutput,\n        });\n      },\n    });\n  } catch (error) {\n    throw wrapGatewayError(error);\n  }\n}\n\nasync function executeTools<TOOLS extends ToolSet>({\n  toolCalls,\n  tools,\n  tracer,\n  telemetry,\n  messages,\n  abortSignal,\n  experimental_context,\n  stepNumber,\n  model,\n  onToolCallStart,\n  onToolCallFinish,\n}: {\n  toolCalls: Array<TypedToolCall<TOOLS>>;\n  tools: TOOLS;\n  tracer: Tracer;\n  telemetry: TelemetrySettings | undefined;\n  messages: ModelMessage[];\n  abortSignal: AbortSignal | undefined;\n  experimental_context: unknown;\n  stepNumber: number;\n  model: { provider: string; modelId: string };\n  onToolCallStart:\n    | GenerateTextOnToolCallStartCallback<TOOLS>\n    | Array<GenerateTextOnToolCallStartCallback<TOOLS> | undefined | null>\n    | undefined;\n  onToolCallFinish:\n    | GenerateTextOnToolCallFinishCallback<TOOLS>\n    | Array<GenerateTextOnToolCallFinishCallback<TOOLS> | undefined | null>\n    | undefined;\n}): Promise<Array<ToolOutput<TOOLS>>> {\n  const toolOutputs = await Promise.all(\n    toolCalls.map(async toolCall =>\n      executeToolCall({\n        toolCall,\n        tools,\n        tracer,\n        telemetry,\n        messages,\n        abortSignal,\n        experimental_context,\n        stepNumber,\n        model,\n        onToolCallStart,\n        onToolCallFinish,\n      }),\n    ),\n  );\n\n  return toolOutputs.filter(\n    (output): output is NonNullable<typeof output> => output != null,\n  );\n}\n\nclass DefaultGenerateTextResult<\n  TOOLS extends ToolSet,\n  OUTPUT extends Output,\n> implements GenerateTextResult<TOOLS, OUTPUT> {\n  readonly steps: GenerateTextResult<TOOLS, OUTPUT>['steps'];\n  readonly totalUsage: LanguageModelUsage;\n  private readonly _output: InferCompleteOutput<OUTPUT> | undefined;\n\n  constructor(options: {\n    steps: GenerateTextResult<TOOLS, OUTPUT>['steps'];\n    output: InferCompleteOutput<OUTPUT> | undefined;\n    totalUsage: LanguageModelUsage;\n  }) {\n    this.steps = options.steps;\n    this._output = options.output;\n    this.totalUsage = options.totalUsage;\n  }\n\n  private get finalStep() {\n    return this.steps[this.steps.length - 1];\n  }\n\n  get content() {\n    return this.finalStep.content;\n  }\n\n  get text() {\n    return this.finalStep.text;\n  }\n\n  get files() {\n    return this.finalStep.files;\n  }\n\n  get reasoningText() {\n    return this.finalStep.reasoningText;\n  }\n\n  get reasoning() {\n    return this.finalStep.reasoning;\n  }\n\n  get toolCalls() {\n    return this.finalStep.toolCalls;\n  }\n\n  get staticToolCalls() {\n    return this.finalStep.staticToolCalls;\n  }\n\n  get dynamicToolCalls() {\n    return this.finalStep.dynamicToolCalls;\n  }\n\n  get toolResults() {\n    return this.finalStep.toolResults;\n  }\n\n  get staticToolResults() {\n    return this.finalStep.staticToolResults;\n  }\n\n  get dynamicToolResults() {\n    return this.finalStep.dynamicToolResults;\n  }\n\n  get sources() {\n    return this.finalStep.sources;\n  }\n\n  get finishReason() {\n    return this.finalStep.finishReason;\n  }\n\n  get rawFinishReason() {\n    return this.finalStep.rawFinishReason;\n  }\n\n  get warnings() {\n    return this.finalStep.warnings;\n  }\n\n  get providerMetadata() {\n    return this.finalStep.providerMetadata;\n  }\n\n  get response() {\n    return this.finalStep.response;\n  }\n\n  get request() {\n    return this.finalStep.request;\n  }\n\n  get usage() {\n    return this.finalStep.usage;\n  }\n\n  get experimental_output() {\n    return this.output;\n  }\n\n  get output() {\n    if (this._output == null) {\n      throw new NoOutputGeneratedError();\n    }\n\n    return this._output;\n  }\n}\n\nfunction asToolCalls(content: Array<LanguageModelV3Content>) {\n  const parts = content.filter(\n    (part): part is LanguageModelV3ToolCall => part.type === 'tool-call',\n  );\n\n  if (parts.length === 0) {\n    return undefined;\n  }\n\n  return parts.map(toolCall => ({\n    toolCallId: toolCall.toolCallId,\n    toolName: toolCall.toolName,\n    input: toolCall.input,\n  }));\n}\n\nfunction asContent<TOOLS extends ToolSet>({\n  content,\n  toolCalls,\n  toolOutputs,\n  toolApprovalRequests,\n  tools,\n}: {\n  content: Array<LanguageModelV3Content>;\n  toolCalls: Array<TypedToolCall<TOOLS>>;\n  toolOutputs: Array<ToolOutput<TOOLS>>;\n  toolApprovalRequests: Array<ToolApprovalRequestOutput<TOOLS>>;\n  tools: TOOLS | undefined;\n}): Array<ContentPart<TOOLS>> {\n  const contentParts: Array<ContentPart<TOOLS>> = [];\n\n  for (const part of content) {\n    switch (part.type) {\n      case 'text':\n      case 'reasoning':\n      case 'source':\n        contentParts.push(part);\n        break;\n\n      case 'file': {\n        contentParts.push({\n          type: 'file' as const,\n          file: new DefaultGeneratedFile(part),\n          ...(part.providerMetadata != null\n            ? { providerMetadata: part.providerMetadata }\n            : {}),\n        });\n        break;\n      }\n\n      case 'tool-call': {\n        contentParts.push(\n          toolCalls.find(toolCall => toolCall.toolCallId === part.toolCallId)!,\n        );\n        break;\n      }\n\n      case 'tool-result': {\n        const toolCall = toolCalls.find(\n          toolCall => toolCall.toolCallId === part.toolCallId,\n        );\n\n        // Handle deferred results for provider-executed tools (e.g., programmatic tool calling).\n        // When a server tool (like code_execution) triggers a client tool, the server tool's\n        // result may be deferred to a later turn. In this case, there's no matching tool-call\n        // in the current response.\n        if (toolCall == null) {\n          const tool = tools?.[part.toolName];\n          const supportsDeferredResults =\n            tool?.type === 'provider' && tool.supportsDeferredResults;\n\n          if (!supportsDeferredResults) {\n            throw new Error(`Tool call ${part.toolCallId} not found.`);\n          }\n\n          // Create tool result without tool call input (deferred result)\n          if (part.isError) {\n            contentParts.push({\n              type: 'tool-error' as const,\n              toolCallId: part.toolCallId,\n              toolName: part.toolName as keyof TOOLS & string,\n              input: undefined,\n              error: part.result,\n              providerExecuted: true,\n              dynamic: part.dynamic,\n              ...(part.providerMetadata != null\n                ? { providerMetadata: part.providerMetadata }\n                : {}),\n              ...(tool?.metadata != null\n                ? { toolMetadata: tool.metadata }\n                : {}),\n            } as TypedToolError<TOOLS>);\n          } else {\n            contentParts.push({\n              type: 'tool-result' as const,\n              toolCallId: part.toolCallId,\n              toolName: part.toolName as keyof TOOLS & string,\n              input: undefined,\n              output: part.result,\n              providerExecuted: true,\n              dynamic: part.dynamic,\n              ...(part.providerMetadata != null\n                ? { providerMetadata: part.providerMetadata }\n                : {}),\n              ...(tool?.metadata != null\n                ? { toolMetadata: tool.metadata }\n                : {}),\n            } as TypedToolResult<TOOLS>);\n          }\n          break;\n        }\n\n        if (part.isError) {\n          contentParts.push({\n            type: 'tool-error' as const,\n            toolCallId: part.toolCallId,\n            toolName: part.toolName as keyof TOOLS & string,\n            input: toolCall.input,\n            error: part.result,\n            providerExecuted: true,\n            dynamic: toolCall.dynamic,\n            ...(part.providerMetadata != null\n              ? { providerMetadata: part.providerMetadata }\n              : {}),\n            ...(toolCall.toolMetadata != null\n              ? { toolMetadata: toolCall.toolMetadata }\n              : {}),\n          } as TypedToolError<TOOLS>);\n        } else {\n          contentParts.push({\n            type: 'tool-result' as const,\n            toolCallId: part.toolCallId,\n            toolName: part.toolName as keyof TOOLS & string,\n            input: toolCall.input,\n            output: part.result,\n            providerExecuted: true,\n            dynamic: toolCall.dynamic,\n            ...(part.providerMetadata != null\n              ? { providerMetadata: part.providerMetadata }\n              : {}),\n            ...(toolCall.toolMetadata != null\n              ? { toolMetadata: toolCall.toolMetadata }\n              : {}),\n          } as TypedToolResult<TOOLS>);\n        }\n        break;\n      }\n\n      case 'tool-approval-request': {\n        const toolCall = toolCalls.find(\n          toolCall => toolCall.toolCallId === part.toolCallId,\n        );\n\n        if (toolCall == null) {\n          throw new ToolCallNotFoundForApprovalError({\n            toolCallId: part.toolCallId,\n            approvalId: part.approvalId,\n          });\n        }\n\n        contentParts.push({\n          type: 'tool-approval-request' as const,\n          approvalId: part.approvalId,\n          toolCall,\n        });\n        break;\n      }\n    }\n  }\n\n  return [...contentParts, ...toolOutputs, ...toolApprovalRequests];\n}\n", "export {\n  AISDKError,\n  APICallError,\n  EmptyResponseBodyError,\n  InvalidPromptError,\n  InvalidResponseDataError,\n  JSONParseError,\n  LoadAPIKeyError,\n  LoadSettingError,\n  NoContentGeneratedError,\n  NoSuchModelError,\n  TooManyEmbeddingValuesForCallError,\n  TypeValidationError,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\n\nexport { InvalidArgumentError } from './invalid-argument-error';\nexport { InvalidStreamPartError } from './invalid-stream-part-error';\nexport { InvalidToolApprovalError } from './invalid-tool-approval-error';\nexport { InvalidToolInputError } from './invalid-tool-input-error';\nexport { ToolCallNotFoundForApprovalError } from './tool-call-not-found-for-approval-error';\nexport { MissingToolResultsError } from './missing-tool-result-error';\nexport { NoImageGeneratedError } from './no-image-generated-error';\nexport { NoObjectGeneratedError } from './no-object-generated-error';\nexport { NoOutputGeneratedError } from './no-output-generated-error';\nexport { NoSpeechGeneratedError } from './no-speech-generated-error';\nexport { NoTranscriptGeneratedError } from './no-transcript-generated-error';\nexport { NoVideoGeneratedError } from './no-video-generated-error';\nexport { NoSuchToolError } from './no-such-tool-error';\nexport { ToolCallRepairError } from './tool-call-repair-error';\nexport { UnsupportedModelVersionError } from './unsupported-model-version-error';\nexport { UIMessageStreamError } from './ui-message-stream-error';\nexport { InvalidDataContentError } from '../prompt/invalid-data-content-error';\nexport { InvalidMessageRoleError } from '../prompt/invalid-message-role-error';\nexport { MessageConversionError } from '../prompt/message-conversion-error';\nexport { DownloadError } from '@ai-sdk/provider-utils';\nexport { RetryError } from '../util/retry-error';\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidArgumentError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly parameter: string;\n  readonly value: unknown;\n\n  constructor({\n    parameter,\n    value,\n    message,\n  }: {\n    parameter: string;\n    value: unknown;\n    message: string;\n  }) {\n    super({\n      name,\n      message: `Invalid argument for parameter ${parameter}: ${message}`,\n    });\n\n    this.parameter = parameter;\n    this.value = value;\n  }\n\n  static isInstance(error: unknown): error is InvalidArgumentError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\nimport type { SingleRequestTextStreamPart } from '../generate-text/run-tools-transformation';\n\nconst name = 'AI_InvalidStreamPartError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidStreamPartError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly chunk: SingleRequestTextStreamPart<any>;\n\n  constructor({\n    chunk,\n    message,\n  }: {\n    chunk: SingleRequestTextStreamPart<any>;\n    message: string;\n  }) {\n    super({ name, message });\n\n    this.chunk = chunk;\n  }\n\n  static isInstance(error: unknown): error is InvalidStreamPartError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolApprovalError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolApprovalError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly approvalId: string;\n\n  constructor({ approvalId }: { approvalId: string }) {\n    super({\n      name,\n      message:\n        `Tool approval response references unknown approvalId: \"${approvalId}\". ` +\n        `No matching tool-approval-request found in message history.`,\n    });\n\n    this.approvalId = approvalId;\n  }\n\n  static isInstance(error: unknown): error is InvalidToolApprovalError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolInputError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolInputError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly toolName: string;\n  readonly toolInput: string;\n\n  constructor({\n    toolInput,\n    toolName,\n    cause,\n    message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}`,\n  }: {\n    message?: string;\n    toolInput: string;\n    toolName: string;\n    cause: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.toolInput = toolInput;\n    this.toolName = toolName;\n  }\n\n  static isInstance(error: unknown): error is InvalidToolInputError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_ToolCallNotFoundForApprovalError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallNotFoundForApprovalError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly toolCallId: string;\n  readonly approvalId: string;\n\n  constructor({\n    toolCallId,\n    approvalId,\n  }: {\n    toolCallId: string;\n    approvalId: string;\n  }) {\n    super({\n      name,\n      message: `Tool call \"${toolCallId}\" not found for approval request \"${approvalId}\".`,\n    });\n\n    this.toolCallId = toolCallId;\n    this.approvalId = approvalId;\n  }\n\n  static isInstance(error: unknown): error is ToolCallNotFoundForApprovalError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_MissingToolResultsError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MissingToolResultsError extends AISDKError {\n  private readonly [symbol] = true;\n\n  readonly toolCallIds: string[];\n\n  constructor({ toolCallIds }: { toolCallIds: string[] }) {\n    super({\n      name,\n      message: `Tool result${\n        toolCallIds.length > 1 ? 's are' : ' is'\n      } missing for tool call${toolCallIds.length > 1 ? 's' : ''} ${toolCallIds.join(\n        ', ',\n      )}.`,\n    });\n\n    this.toolCallIds = toolCallIds;\n  }\n\n  static isInstance(error: unknown): error is MissingToolResultsError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\nimport type { ImageModelResponseMetadata } from '../types/image-model-response-metadata';\n\nconst name = 'AI_NoImageGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when no image could be generated. This can have multiple causes:\n *\n * - The model failed to generate a response.\n * - The model generated a response that could not be parsed.\n */\nexport class NoImageGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The response metadata for each call.\n   */\n  readonly responses: Array<ImageModelResponseMetadata> | undefined;\n\n  constructor({\n    message = 'No image generated.',\n    cause,\n    responses,\n  }: {\n    message?: string;\n    cause?: Error;\n    responses?: Array<ImageModelResponseMetadata>;\n  }) {\n    super({ name, message, cause });\n\n    this.responses = responses;\n  }\n\n  static isInstance(error: unknown): error is NoImageGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\nimport type { FinishReason } from '../types/language-model';\nimport type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport type { LanguageModelUsage } from '../types/usage';\n\nconst name = 'AI_NoObjectGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when no object could be generated. This can have several causes:\n *\n * - The model failed to generate a response.\n * - The model generated a response that could not be parsed.\n * - The model generated a response that could not be validated against the schema.\n *\n * The error contains the following properties:\n *\n * - `text`: The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.\n */\nexport class NoObjectGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.\n   */\n  readonly text: string | undefined;\n\n  /**\n   * The response metadata.\n   */\n  readonly response: LanguageModelResponseMetadata | undefined;\n\n  /**\n   * The usage of the model.\n   */\n  readonly usage: LanguageModelUsage | undefined;\n\n  /**\n   * Reason why the model finished generating a response.\n   */\n  readonly finishReason: FinishReason | undefined;\n\n  constructor({\n    message = 'No object generated.',\n    cause,\n    text,\n    response,\n    usage,\n    finishReason,\n  }: {\n    message?: string;\n    cause?: Error;\n    text?: string;\n    response: LanguageModelResponseMetadata;\n    usage: LanguageModelUsage;\n    finishReason: FinishReason;\n  }) {\n    super({ name, message, cause });\n\n    this.text = text;\n    this.response = response;\n    this.usage = usage;\n    this.finishReason = finishReason;\n  }\n\n  static isInstance(error: unknown): error is NoObjectGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoOutputGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when no LLM output was generated, e.g. because of errors.\n */\nexport class NoOutputGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({\n    message = 'No output generated.',\n    cause,\n  }: {\n    message?: string;\n    cause?: Error;\n  } = {}) {\n    super({ name, message, cause });\n  }\n\n  static isInstance(error: unknown): error is NoOutputGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\nimport type { SpeechModelResponseMetadata } from '../types/speech-model-response-metadata';\n\nconst name = 'AI_NoSpeechGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Error that is thrown when no speech audio was generated.\n */\nexport class NoSpeechGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly responses: Array<SpeechModelResponseMetadata>;\n\n  constructor(options: { responses: Array<SpeechModelResponseMetadata> }) {\n    super({\n      name,\n      message: 'No speech audio generated.',\n    });\n\n    this.responses = options.responses;\n  }\n\n  static isInstance(error: unknown): error is NoSpeechGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\nimport type { TranscriptionModelResponseMetadata } from '../types/transcription-model-response-metadata';\n\nconst name = 'AI_NoTranscriptGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Error that is thrown when no transcript was generated.\n */\nexport class NoTranscriptGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly responses: Array<TranscriptionModelResponseMetadata>;\n\n  constructor(options: {\n    responses: Array<TranscriptionModelResponseMetadata>;\n  }) {\n    super({\n      name,\n      message: 'No transcript generated.',\n    });\n\n    this.responses = options.responses;\n  }\n\n  static isInstance(error: unknown): error is NoTranscriptGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\nimport type { VideoModelResponseMetadata } from '../types/video-model-response-metadata';\n\nconst name = 'AI_NoVideoGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoVideoGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly responses: Array<VideoModelResponseMetadata>;\n\n  constructor({\n    message = 'No video generated.',\n    cause,\n    responses,\n  }: {\n    message?: string;\n    cause?: unknown;\n    responses: Array<VideoModelResponseMetadata>;\n  }) {\n    super({ name, message, cause });\n\n    this.responses = responses;\n  }\n\n  static isInstance(error: unknown): error is NoVideoGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  /**\n   * @deprecated use `isInstance` instead\n   */\n  static isNoVideoGeneratedError(\n    error: unknown,\n  ): error is NoVideoGeneratedError {\n    return error instanceof Error &&\n      error.name === name &&\n      typeof (error as NoVideoGeneratedError).responses !== 'undefined'\n      ? true\n      : false;\n  }\n\n  /**\n   * @deprecated Do not use this method. It will be removed in the next major version.\n   */\n  toJSON() {\n    return {\n      name: this.name,\n      message: this.message,\n      stack: this.stack,\n\n      cause: this.cause,\n      responses: this.responses,\n    };\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchToolError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchToolError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly toolName: string;\n  readonly availableTools: string[] | undefined;\n\n  constructor({\n    toolName,\n    availableTools = undefined,\n    message = `Model tried to call unavailable tool '${toolName}'. ${\n      availableTools === undefined\n        ? 'No tools are available.'\n        : `Available tools: ${availableTools.join(', ')}.`\n    }`,\n  }: {\n    toolName: string;\n    availableTools?: string[] | undefined;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.toolName = toolName;\n    this.availableTools = availableTools;\n  }\n\n  static isInstance(error: unknown): error is NoSuchToolError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\nimport type { InvalidToolInputError } from './invalid-tool-input-error';\nimport type { NoSuchToolError } from './no-such-tool-error';\n\nconst name = 'AI_ToolCallRepairError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallRepairError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly originalError: NoSuchToolError | InvalidToolInputError;\n\n  constructor({\n    cause,\n    originalError,\n    message = `Error repairing tool call: ${getErrorMessage(cause)}`,\n  }: {\n    message?: string;\n    cause: unknown;\n    originalError: NoSuchToolError | InvalidToolInputError;\n  }) {\n    super({ name, message, cause });\n    this.originalError = originalError;\n  }\n\n  static isInstance(error: unknown): error is ToolCallRepairError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\n/**\n * Error that is thrown when a model with an unsupported version is used.\n */\nexport class UnsupportedModelVersionError extends AISDKError {\n  readonly version: string;\n  readonly provider: string;\n  readonly modelId: string;\n\n  constructor(options: { version: string; provider: string; modelId: string }) {\n    super({\n      name: 'AI_UnsupportedModelVersionError',\n      message:\n        `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". ` +\n        `AI SDK 5 only supports models that implement specification version \"v2\".`,\n    });\n\n    this.version = options.version;\n    this.provider = options.provider;\n    this.modelId = options.modelId;\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_UIMessageStreamError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Error thrown when a UI message stream contains invalid or out-of-sequence chunks.\n *\n * This typically occurs when:\n * - A delta chunk is received without a corresponding start chunk\n * - An end chunk is received without a corresponding start chunk\n * - A tool invocation is not found for the given toolCallId\n *\n * @see https://ai-sdk.dev/docs/reference/ai-sdk-errors/ai-ui-message-stream-error\n */\nexport class UIMessageStreamError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The type of chunk that caused the error (e.g., 'text-delta', 'reasoning-end').\n   */\n  readonly chunkType: string;\n\n  /**\n   * The ID associated with the failing chunk (part ID or toolCallId).\n   */\n  readonly chunkId: string;\n\n  constructor({\n    chunkType,\n    chunkId,\n    message,\n  }: {\n    chunkType: string;\n    chunkId: string;\n    message: string;\n  }) {\n    super({ name, message });\n\n    this.chunkType = chunkType;\n    this.chunkId = chunkId;\n  }\n\n  static isInstance(error: unknown): error is UIMessageStreamError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidDataContentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidDataContentError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly content: unknown;\n\n  constructor({\n    content,\n    cause,\n    message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`,\n  }: {\n    content: unknown;\n    cause?: unknown;\n    message?: string;\n  }) {\n    super({ name, message, cause });\n\n    this.content = content;\n  }\n\n  static isInstance(error: unknown): error is InvalidDataContentError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidMessageRoleError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidMessageRoleError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly role: string;\n\n  constructor({\n    role,\n    message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`,\n  }: {\n    role: string;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.role = role;\n  }\n\n  static isInstance(error: unknown): error is InvalidMessageRoleError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\nimport type { UIMessage } from '../ui/ui-messages';\n\nconst name = 'AI_MessageConversionError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MessageConversionError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly originalMessage: Omit<UIMessage, 'id'>;\n\n  constructor({\n    originalMessage,\n    message,\n  }: {\n    originalMessage: Omit<UIMessage, 'id'>;\n    message: string;\n  }) {\n    super({ name, message });\n\n    this.originalMessage = originalMessage;\n  }\n\n  static isInstance(error: unknown): error is MessageConversionError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_RetryError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport type RetryErrorReason =\n  | 'maxRetriesExceeded'\n  | 'errorNotRetryable'\n  | 'abort';\n\nexport class RetryError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  // note: property order determines debugging output\n  readonly reason: RetryErrorReason;\n  readonly lastError: unknown;\n  readonly errors: Array<unknown>;\n\n  constructor({\n    message,\n    reason,\n    errors,\n  }: {\n    message: string;\n    reason: RetryErrorReason;\n    errors: Array<unknown>;\n  }) {\n    super({ name, message });\n\n    this.reason = reason;\n    this.errors = errors;\n\n    // separate our last error to make debugging via log easier:\n    this.lastError = errors[errors.length - 1];\n  }\n\n  static isInstance(error: unknown): error is RetryError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "export function asArray<T>(value: T | T[] | undefined): T[] {\n  return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n", "import { asArray } from './as-array';\n\n/**\n * A callback function that can be used to notify listeners.\n */\nexport type Listener<EVENT> = (event: EVENT) => PromiseLike<void> | void;\n\n/**\n * Notifies all provided callbacks with the given event.\n * Errors in callbacks do not break the generation flow.\n */\nexport async function notify<EVENT>(options: {\n  event: EVENT;\n  callbacks?: Listener<EVENT> | Array<Listener<EVENT> | undefined | null>;\n}): Promise<void> {\n  for (const callback of asArray(options.callbacks)) {\n    if (callback == null) continue;\n    try {\n      await callback(options.event);\n    } catch (_ignored) {}\n  }\n}\n", "import type { Warning } from '../types';\n\n/**\n * A function for logging warnings.\n *\n * You can assign it to the `AI_SDK_LOG_WARNINGS` global variable to use it as the default warning logger.\n *\n * @example\n * ```ts\n * globalThis.AI_SDK_LOG_WARNINGS = (options) => {\n *   console.log('WARNINGS:', options.warnings, options.provider, options.model);\n * };\n * ```\n */\nexport type LogWarningsFunction = (options: {\n  /**\n   * The warnings returned by the model provider.\n   */\n  warnings: Warning[];\n\n  /**\n   * The provider id used for the call.\n   */\n  provider: string;\n\n  /**\n   * The model id used for the call.\n   */\n  model: string;\n}) => void;\n\n/**\n * Formats a warning object into a human-readable string with clear AI SDK branding.\n *\n * @param options - The options for formatting the warning.\n * @param options.warning - The warning to format.\n * @param options.provider - The provider id used for the call.\n * @param options.model - The model id used for the call.\n * @returns A formatted warning message string.\n */\nfunction formatWarning({\n  warning,\n  provider,\n  model,\n}: {\n  warning: Warning;\n  provider: string;\n  model: string;\n}): string {\n  const prefix = `AI SDK Warning (${provider} / ${model}):`;\n\n  switch (warning.type) {\n    case 'unsupported': {\n      let message = `${prefix} The feature \"${warning.feature}\" is not supported.`;\n      if (warning.details) {\n        message += ` ${warning.details}`;\n      }\n      return message;\n    }\n\n    case 'compatibility': {\n      let message = `${prefix} The feature \"${warning.feature}\" is used in a compatibility mode.`;\n      if (warning.details) {\n        message += ` ${warning.details}`;\n      }\n      return message;\n    }\n\n    case 'other': {\n      return `${prefix} ${warning.message}`;\n    }\n\n    default: {\n      // Fallback for any unknown warning types\n      return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n    }\n  }\n}\n\nexport const FIRST_WARNING_INFO_MESSAGE =\n  'AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.';\n\nlet hasLoggedBefore = false;\n\n/**\n * Logs warnings to the console or uses a custom logger if configured.\n *\n * The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable:\n * - If set to `false`, warnings are suppressed.\n * - If set to a function, that function is called with the warnings.\n * - Otherwise, warnings are logged to the console using `console.warn`.\n *\n * @param options - The options containing warnings and context.\n * @param options.warnings - The warnings to log.\n * @param options.provider - The provider id used for the call.\n * @param options.model - The model id used for the call.\n */\nexport const logWarnings: LogWarningsFunction = options => {\n  // if the warnings array is empty, do nothing\n  if (options.warnings.length === 0) {\n    return;\n  }\n\n  const logger = globalThis.AI_SDK_LOG_WARNINGS;\n\n  // if the logger is set to false, do nothing\n  if (logger === false) {\n    return;\n  }\n\n  // use the provided logger if it is a function\n  if (typeof logger === 'function') {\n    logger(options);\n    return;\n  }\n\n  // display information note on first call\n  if (!hasLoggedBefore) {\n    hasLoggedBefore = true;\n    console.info(FIRST_WARNING_INFO_MESSAGE);\n  }\n\n  // default behavior: log warnings to the console\n  for (const warning of options.warnings) {\n    console.warn(\n      formatWarning({\n        warning,\n        provider: options.provider,\n        model: options.model,\n      }),\n    );\n  }\n};\n\n/**\n * Resets the internal logging state. Used for testing purposes.\n */\nexport const resetLogWarningsState = () => {\n  hasLoggedBefore = false;\n};\n", "import { gateway } from '@ai-sdk/gateway';\nimport type {\n  EmbeddingModelV3,\n  Experimental_VideoModelV3,\n  ImageModelV3,\n  LanguageModelV3,\n  ProviderV3,\n  RerankingModelV3,\n  SpeechModelV3,\n  TranscriptionModelV3,\n} from '@ai-sdk/provider';\nimport { UnsupportedModelVersionError } from '../error';\nimport type { EmbeddingModel } from '../types/embedding-model';\nimport type { LanguageModel } from '../types/language-model';\nimport type { SpeechModel } from '../types/speech-model';\nimport type { TranscriptionModel } from '../types/transcription-model';\nimport { asEmbeddingModelV3 } from './as-embedding-model-v3';\nimport { asImageModelV3 } from './as-image-model-v3';\nimport { asLanguageModelV3 } from './as-language-model-v3';\nimport { asSpeechModelV3 } from './as-speech-model-v3';\nimport { asTranscriptionModelV3 } from './as-transcription-model-v3';\nimport type { ImageModel } from '../types/image-model';\nimport type { RerankingModel } from '../types/reranking-model';\nimport type { VideoModel } from '../types/video-model';\n\nexport function resolveLanguageModel(model: LanguageModel): LanguageModelV3 {\n  if (typeof model !== 'string') {\n    if (\n      model.specificationVersion !== 'v3' &&\n      model.specificationVersion !== 'v2'\n    ) {\n      const unsupportedModel: any = model;\n      throw new UnsupportedModelVersionError({\n        version: unsupportedModel.specificationVersion,\n        provider: unsupportedModel.provider,\n        modelId: unsupportedModel.modelId,\n      });\n    }\n\n    return asLanguageModelV3(model);\n  }\n\n  return getGlobalProvider().languageModel(model);\n}\n\nexport function resolveEmbeddingModel(model: EmbeddingModel): EmbeddingModelV3 {\n  if (typeof model !== 'string') {\n    if (\n      model.specificationVersion !== 'v3' &&\n      model.specificationVersion !== 'v2'\n    ) {\n      const unsupportedModel: any = model;\n      throw new UnsupportedModelVersionError({\n        version: unsupportedModel.specificationVersion,\n        provider: unsupportedModel.provider,\n        modelId: unsupportedModel.modelId,\n      });\n    }\n\n    return asEmbeddingModelV3(model);\n  }\n\n  return getGlobalProvider().embeddingModel(model);\n}\n\nexport function resolveTranscriptionModel(\n  model: TranscriptionModel,\n): TranscriptionModelV3 | undefined {\n  if (typeof model !== 'string') {\n    if (\n      model.specificationVersion !== 'v3' &&\n      model.specificationVersion !== 'v2'\n    ) {\n      const unsupportedModel: any = model;\n      throw new UnsupportedModelVersionError({\n        version: unsupportedModel.specificationVersion,\n        provider: unsupportedModel.provider,\n        modelId: unsupportedModel.modelId,\n      });\n    }\n    return asTranscriptionModelV3(model);\n  }\n\n  return getGlobalProvider().transcriptionModel?.(model);\n}\n\nexport function resolveSpeechModel(\n  model: SpeechModel,\n): SpeechModelV3 | undefined {\n  if (typeof model !== 'string') {\n    if (\n      model.specificationVersion !== 'v3' &&\n      model.specificationVersion !== 'v2'\n    ) {\n      const unsupportedModel: any = model;\n      throw new UnsupportedModelVersionError({\n        version: unsupportedModel.specificationVersion,\n        provider: unsupportedModel.provider,\n        modelId: unsupportedModel.modelId,\n      });\n    }\n    return asSpeechModelV3(model);\n  }\n\n  return getGlobalProvider().speechModel?.(model);\n}\n\nexport function resolveImageModel(model: ImageModel): ImageModelV3 {\n  if (typeof model !== 'string') {\n    if (\n      model.specificationVersion !== 'v3' &&\n      model.specificationVersion !== 'v2'\n    ) {\n      const unsupportedModel: any = model;\n      throw new UnsupportedModelVersionError({\n        version: unsupportedModel.specificationVersion,\n        provider: unsupportedModel.provider,\n        modelId: unsupportedModel.modelId,\n      });\n    }\n\n    return asImageModelV3(model);\n  }\n\n  return getGlobalProvider().imageModel(model);\n}\n\nexport function resolveVideoModel(\n  model: VideoModel,\n): Experimental_VideoModelV3 {\n  if (typeof model === 'string') {\n    const provider = getGlobalProvider();\n    // TODO AI SDK v7\n    // @ts-expect-error - videoModel support is experimental\n    const videoModel = provider.videoModel;\n\n    if (!videoModel) {\n      throw new Error(\n        'The default provider does not support video models. ' +\n          'Please use a Experimental_VideoModelV3 object from a provider (e.g., vertex.video(\"model-id\")).',\n      );\n    }\n\n    return videoModel(model);\n  }\n\n  if (model.specificationVersion !== 'v3') {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return model;\n}\n\nexport function resolveRerankingModel(model: RerankingModel): RerankingModelV3 {\n  if (typeof model === 'string') {\n    const provider = getGlobalProvider();\n    const rerankingModel = provider.rerankingModel;\n\n    if (!rerankingModel) {\n      throw new Error(\n        'The default provider does not support reranking models. ' +\n          'Please use a RerankingModel object from a provider (e.g., gateway.rerankingModel(\"model-id\")).',\n      );\n    }\n\n    return rerankingModel(model);\n  }\n\n  if (model.specificationVersion !== 'v3') {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return model;\n}\n\nfunction getGlobalProvider(): ProviderV3 {\n  return globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;\n}\n", "import { logWarnings } from '../logger/log-warnings';\n\nexport function logV2CompatibilityWarning({\n  provider,\n  modelId,\n}: {\n  provider: string;\n  modelId: string;\n}): void {\n  logWarnings({\n    warnings: [\n      {\n        type: 'compatibility',\n        feature: 'specificationVersion',\n        details: `Using v2 specification compatibility mode. Some features may not be available.`,\n      },\n    ],\n    provider,\n    model: modelId,\n  });\n}\n", "import type { EmbeddingModelV2, EmbeddingModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asEmbeddingModelV3(\n  model: EmbeddingModelV2<string> | EmbeddingModelV3,\n): EmbeddingModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof EmbeddingModelV2<string>) {\n      if (prop === 'specificationVersion') return 'v3';\n      return target[prop];\n    },\n  }) as unknown as EmbeddingModelV3;\n}\n", "import type { ImageModelV2, ImageModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asImageModelV3(\n  model: ImageModelV2 | ImageModelV3,\n): ImageModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof ImageModelV2) {\n      if (prop === 'specificationVersion') return 'v3';\n      return target[prop];\n    },\n  }) as unknown as ImageModelV3;\n}\n", "import type {\n  LanguageModelV2,\n  LanguageModelV2FinishReason,\n  LanguageModelV2StreamPart,\n  LanguageModelV2Usage,\n  LanguageModelV3,\n  LanguageModelV3FinishReason,\n  LanguageModelV3StreamPart,\n  LanguageModelV3Usage,\n} from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asLanguageModelV3(\n  model: LanguageModelV2 | LanguageModelV3,\n): LanguageModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof LanguageModelV2) {\n      switch (prop) {\n        case 'specificationVersion':\n          return 'v3';\n        case 'doGenerate':\n          return async (...args: Parameters<LanguageModelV2['doGenerate']>) => {\n            const result = await target.doGenerate(...args);\n            return {\n              ...result,\n              finishReason: convertV2FinishReasonToV3(result.finishReason),\n              usage: convertV2UsageToV3(result.usage),\n            };\n          };\n        case 'doStream':\n          return async (...args: Parameters<LanguageModelV2['doStream']>) => {\n            const result = await target.doStream(...args);\n            return {\n              ...result,\n              stream: convertV2StreamToV3(result.stream),\n            };\n          };\n        default:\n          return target[prop];\n      }\n    },\n  }) as unknown as LanguageModelV3;\n}\n\nfunction convertV2StreamToV3(\n  stream: ReadableStream<LanguageModelV2StreamPart>,\n): ReadableStream<LanguageModelV3StreamPart> {\n  return stream.pipeThrough(\n    new TransformStream<LanguageModelV2StreamPart, LanguageModelV3StreamPart>({\n      transform(chunk, controller) {\n        switch (chunk.type) {\n          case 'finish':\n            controller.enqueue({\n              ...chunk,\n              finishReason: convertV2FinishReasonToV3(chunk.finishReason),\n              usage: convertV2UsageToV3(chunk.usage),\n            });\n            break;\n          default:\n            // TODO: AI SDK 6 - no casting (stream parts need to be mapped)\n            controller.enqueue(chunk as LanguageModelV3StreamPart);\n            break;\n        }\n      },\n    }),\n  );\n}\n\nfunction convertV2FinishReasonToV3(\n  finishReason: LanguageModelV2FinishReason,\n): LanguageModelV3FinishReason {\n  return {\n    unified: finishReason === 'unknown' ? 'other' : finishReason,\n    raw: undefined,\n  };\n}\n\nfunction convertV2UsageToV3(usage: LanguageModelV2Usage): LanguageModelV3Usage {\n  return {\n    inputTokens: {\n      total: usage.inputTokens,\n      noCache: undefined,\n      cacheRead: usage.cachedInputTokens,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: usage.outputTokens,\n      text: undefined,\n      reasoning: usage.reasoningTokens,\n    },\n  };\n}\n", "import type { SpeechModelV2, SpeechModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asSpeechModelV3(\n  model: SpeechModelV3 | SpeechModelV2,\n): SpeechModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof SpeechModelV2) {\n      if (prop === 'specificationVersion') return 'v3';\n      return target[prop];\n    },\n  }) as unknown as SpeechModelV3;\n}\n", "import type {\n  TranscriptionModelV2,\n  TranscriptionModelV3,\n} from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asTranscriptionModelV3(\n  model: TranscriptionModelV3 | TranscriptionModelV2,\n): TranscriptionModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof TranscriptionModelV2) {\n      if (prop === 'specificationVersion') return 'v3';\n      return target[prop];\n    },\n  }) as unknown as TranscriptionModelV3;\n}\n", "/**\n * Timeout configuration for API calls. Can be specified as:\n * - A number representing milliseconds\n * - An object with `totalMs` property for the total timeout in milliseconds\n * - An object with `stepMs` property for the timeout of each step in milliseconds\n * - An object with `chunkMs` property for the timeout between stream chunks (streaming only)\n */\nexport type TimeoutConfiguration =\n  | number\n  | { totalMs?: number; stepMs?: number; chunkMs?: number };\n\n/**\n * Extracts the total timeout value in milliseconds from a TimeoutConfiguration.\n *\n * @param timeout - The timeout configuration.\n * @returns The total timeout in milliseconds, or undefined if no timeout is configured.\n */\nexport function getTotalTimeoutMs(\n  timeout: TimeoutConfiguration | undefined,\n): number | undefined {\n  if (timeout == null) {\n    return undefined;\n  }\n  if (typeof timeout === 'number') {\n    return timeout;\n  }\n  return timeout.totalMs;\n}\n\n/**\n * Extracts the step timeout value in milliseconds from a TimeoutConfiguration.\n *\n * @param timeout - The timeout configuration.\n * @returns The step timeout in milliseconds, or undefined if no step timeout is configured.\n */\nexport function getStepTimeoutMs(\n  timeout: TimeoutConfiguration | undefined,\n): number | undefined {\n  if (timeout == null || typeof timeout === 'number') {\n    return undefined;\n  }\n  return timeout.stepMs;\n}\n\n/**\n * Extracts the chunk timeout value in milliseconds from a TimeoutConfiguration.\n * This timeout is for streaming only - it aborts if no new chunk is received within the specified duration.\n *\n * @param timeout - The timeout configuration.\n * @returns The chunk timeout in milliseconds, or undefined if no chunk timeout is configured.\n */\nexport function getChunkTimeoutMs(\n  timeout: TimeoutConfiguration | undefined,\n): number | undefined {\n  if (timeout == null || typeof timeout === 'number') {\n    return undefined;\n  }\n  return timeout.chunkMs;\n}\n\nexport type CallSettings = {\n  /**\n   * Maximum number of tokens to generate.\n   */\n  maxOutputTokens?: number;\n\n  /**\n   * Temperature setting. The range depends on the provider and model.\n   *\n   * It is recommended to set either `temperature` or `topP`, but not both.\n   */\n  temperature?: number;\n\n  /**\n   * Nucleus sampling. This is a number between 0 and 1.\n   *\n   * E.g. 0.1 would mean that only tokens with the top 10% probability mass\n   * are considered.\n   *\n   * It is recommended to set either `temperature` or `topP`, but not both.\n   */\n  topP?: number;\n\n  /**\n   * Only sample from the top K options for each subsequent token.\n   *\n   * Used to remove \"long tail\" low probability responses.\n   * Recommended for advanced use cases only. You usually only need to use temperature.\n   */\n  topK?: number;\n\n  /**\n   * Presence penalty setting. It affects the likelihood of the model to\n   * repeat information that is already in the prompt.\n   *\n   * The presence penalty is a number between -1 (increase repetition)\n   * and 1 (maximum penalty, decrease repetition). 0 means no penalty.\n   */\n  presencePenalty?: number;\n\n  /**\n   * Frequency penalty setting. It affects the likelihood of the model\n   * to repeatedly use the same words or phrases.\n   *\n   * The frequency penalty is a number between -1 (increase repetition)\n   * and 1 (maximum penalty, decrease repetition). 0 means no penalty.\n   */\n  frequencyPenalty?: number;\n\n  /**\n   * Stop sequences.\n   * If set, the model will stop generating text when one of the stop sequences is generated.\n   * Providers may have limits on the number of stop sequences.\n   */\n  stopSequences?: string[];\n\n  /**\n   * The seed (integer) to use for random sampling. If set and supported\n   * by the model, calls will generate deterministic results.\n   */\n  seed?: number;\n\n  /**\n   * Maximum number of retries. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Timeout in milliseconds. The call will be aborted if it takes longer\n   * than the specified timeout. Can be used alongside abortSignal.\n   *\n   * Can be specified as a number (milliseconds) or as an object with `totalMs`.\n   */\n  timeout?: TimeoutConfiguration;\n\n  /**\n   * Additional HTTP headers to be sent with the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string | undefined>;\n};\n", "import type {\n  LanguageModelV3FilePart,\n  LanguageModelV3Message,\n  LanguageModelV3Prompt,\n  LanguageModelV3TextPart,\n  LanguageModelV3ToolResultOutput,\n} from '@ai-sdk/provider';\nimport {\n  isUrlSupported,\n  type DataContent,\n  type FilePart,\n  type ImagePart,\n  type ModelMessage,\n  type ReasoningPart,\n  type TextPart,\n  type ToolCallPart,\n  type ToolResultOutput,\n  type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport {\n  detectMediaType,\n  imageMediaTypeSignatures,\n} from '../util/detect-media-type';\nimport {\n  createDefaultDownloadFunction,\n  type DownloadFunction,\n} from '../util/download/download-function';\nimport { convertToLanguageModelV3DataContent } from './data-content';\nimport { InvalidMessageRoleError } from './invalid-message-role-error';\nimport type { StandardizedPrompt } from './standardize-prompt';\nimport { asArray } from '../util/as-array';\nimport { MissingToolResultsError } from '../error/missing-tool-result-error';\n\nexport async function convertToLanguageModelPrompt({\n  prompt,\n  supportedUrls,\n  download = createDefaultDownloadFunction(),\n}: {\n  prompt: StandardizedPrompt;\n  supportedUrls: Record<string, RegExp[]>;\n  download: DownloadFunction | undefined;\n}): Promise<LanguageModelV3Prompt> {\n  const downloadedAssets = await downloadAssets(\n    prompt.messages,\n    download,\n    supportedUrls,\n  );\n\n  const approvalIdToToolCallId = new Map<string, string>();\n  for (const message of prompt.messages) {\n    if (message.role === 'assistant' && Array.isArray(message.content)) {\n      for (const part of message.content) {\n        if (\n          part.type === 'tool-approval-request' &&\n          'approvalId' in part &&\n          'toolCallId' in part\n        ) {\n          approvalIdToToolCallId.set(\n            part.approvalId as string,\n            part.toolCallId as string,\n          );\n        }\n      }\n    }\n  }\n\n  const approvedToolCallIds = new Set<string>();\n  for (const message of prompt.messages) {\n    if (message.role === 'tool') {\n      for (const part of message.content) {\n        if (part.type === 'tool-approval-response') {\n          const toolCallId = approvalIdToToolCallId.get(part.approvalId);\n          if (toolCallId) {\n            approvedToolCallIds.add(toolCallId);\n          }\n        }\n      }\n    }\n  }\n\n  const messages = [\n    ...(prompt.system != null\n      ? typeof prompt.system === 'string'\n        ? [{ role: 'system' as const, content: prompt.system }]\n        : asArray(prompt.system).map(message => ({\n            role: 'system' as const,\n            content: message.content,\n            providerOptions: message.providerOptions,\n          }))\n      : []),\n    ...prompt.messages.map(message =>\n      convertToLanguageModelMessage({ message, downloadedAssets }),\n    ),\n  ];\n\n  // combine consecutive tool messages into a single tool message\n  const combinedMessages = [];\n  for (const message of messages) {\n    if (message.role !== 'tool') {\n      combinedMessages.push(message);\n      continue;\n    }\n\n    const lastCombinedMessage = combinedMessages.at(-1);\n    if (lastCombinedMessage?.role === 'tool') {\n      lastCombinedMessage.content.push(...message.content);\n    } else {\n      combinedMessages.push(message);\n    }\n  }\n\n  const toolCallIds = new Set<string>();\n\n  for (const message of combinedMessages) {\n    switch (message.role) {\n      case 'assistant': {\n        for (const content of message.content) {\n          if (content.type === 'tool-call' && !content.providerExecuted) {\n            toolCallIds.add(content.toolCallId);\n          }\n        }\n        break;\n      }\n      case 'tool': {\n        for (const content of message.content) {\n          if (content.type === 'tool-result') {\n            toolCallIds.delete(content.toolCallId);\n          }\n        }\n        break;\n      }\n      case 'user':\n      case 'system':\n        // remove approved tool calls from the set before checking:\n        for (const id of approvedToolCallIds) {\n          toolCallIds.delete(id);\n        }\n\n        if (toolCallIds.size > 0) {\n          throw new MissingToolResultsError({\n            toolCallIds: Array.from(toolCallIds),\n          });\n        }\n        break;\n    }\n  }\n\n  // remove approved tool calls from the set before checking:\n  for (const id of approvedToolCallIds) {\n    toolCallIds.delete(id);\n  }\n\n  if (toolCallIds.size > 0) {\n    throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n  }\n\n  return combinedMessages.filter(\n    // Filter out empty tool messages (e.g. if they only contained\n    // tool-approval-response parts that were removed).\n    // This prevents sending invalid empty messages to the provider.\n    // Note: provider-executed tool-approval-response parts are preserved.\n    message => message.role !== 'tool' || message.content.length > 0,\n  );\n}\n\n/**\n * Convert a ModelMessage to a LanguageModelV3Message.\n *\n * @param message - The ModelMessage to convert.\n * @param downloadedAssets - A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n */\nexport function convertToLanguageModelMessage({\n  message,\n  downloadedAssets,\n}: {\n  message: ModelMessage;\n  downloadedAssets: Record<\n    string,\n    { mediaType: string | undefined; data: Uint8Array }\n  >;\n}): LanguageModelV3Message {\n  const role = message.role;\n  switch (role) {\n    case 'system': {\n      return {\n        role: 'system',\n        content: message.content,\n        providerOptions: message.providerOptions,\n      };\n    }\n\n    case 'user': {\n      if (typeof message.content === 'string') {\n        return {\n          role: 'user',\n          content: [{ type: 'text', text: message.content }],\n          providerOptions: message.providerOptions,\n        };\n      }\n\n      return {\n        role: 'user',\n        content: message.content\n          .map(part => convertPartToLanguageModelPart(part, downloadedAssets))\n          // remove empty text parts:\n          .filter(part => part.type !== 'text' || part.text !== ''),\n        providerOptions: message.providerOptions,\n      };\n    }\n\n    case 'assistant': {\n      if (typeof message.content === 'string') {\n        return {\n          role: 'assistant',\n          content: [{ type: 'text', text: message.content }],\n          providerOptions: message.providerOptions,\n        };\n      }\n\n      return {\n        role: 'assistant',\n        content: message.content\n          .filter(\n            // remove empty text parts (no text, and no provider options):\n            part =>\n              part.type !== 'text' ||\n              part.text !== '' ||\n              part.providerOptions != null,\n          )\n          .filter(\n            (\n              part,\n            ): part is\n              | TextPart\n              | FilePart\n              | ReasoningPart\n              | ToolCallPart\n              | ToolResultPart => part.type !== 'tool-approval-request',\n          )\n          .map(part => {\n            const providerOptions = part.providerOptions;\n\n            switch (part.type) {\n              case 'file': {\n                const { data, mediaType } = convertToLanguageModelV3DataContent(\n                  part.data,\n                );\n                return {\n                  type: 'file',\n                  data,\n                  filename: part.filename,\n                  mediaType: mediaType ?? part.mediaType,\n                  providerOptions,\n                };\n              }\n              case 'reasoning': {\n                return {\n                  type: 'reasoning',\n                  text: part.text,\n                  providerOptions,\n                };\n              }\n              case 'text': {\n                return {\n                  type: 'text' as const,\n                  text: part.text,\n                  providerOptions,\n                };\n              }\n              case 'tool-call': {\n                return {\n                  type: 'tool-call' as const,\n                  toolCallId: part.toolCallId,\n                  toolName: part.toolName,\n                  input: part.input,\n                  providerExecuted: part.providerExecuted,\n                  providerOptions,\n                };\n              }\n              case 'tool-result': {\n                return {\n                  type: 'tool-result' as const,\n                  toolCallId: part.toolCallId,\n                  toolName: part.toolName,\n                  output: mapToolResultOutput(part.output),\n                  providerOptions,\n                };\n              }\n            }\n          }),\n        providerOptions: message.providerOptions,\n      };\n    }\n\n    case 'tool': {\n      return {\n        role: 'tool',\n        content: message.content\n          .filter(\n            // Only include tool-approval-response for provider-executed tools\n            part =>\n              part.type !== 'tool-approval-response' || part.providerExecuted,\n          )\n          .map(part => {\n            switch (part.type) {\n              case 'tool-result': {\n                return {\n                  type: 'tool-result' as const,\n                  toolCallId: part.toolCallId,\n                  toolName: part.toolName,\n                  output: mapToolResultOutput(part.output),\n                  providerOptions: part.providerOptions,\n                };\n              }\n              case 'tool-approval-response': {\n                return {\n                  type: 'tool-approval-response' as const,\n                  approvalId: part.approvalId,\n                  approved: part.approved,\n                  reason: part.reason,\n                };\n              }\n            }\n          }),\n        providerOptions: message.providerOptions,\n      };\n    }\n\n    default: {\n      const _exhaustiveCheck: never = role;\n      throw new InvalidMessageRoleError({ role: _exhaustiveCheck });\n    }\n  }\n}\n\n/**\n * Downloads images and files from URLs in the messages.\n */\nasync function downloadAssets(\n  messages: ModelMessage[],\n  download: DownloadFunction,\n  supportedUrls: Record<string, RegExp[]>,\n): Promise<\n  Record<string, { mediaType: string | undefined; data: Uint8Array }>\n> {\n  const plannedDownloads = messages\n    .filter(message => message.role === 'user')\n    .map(message => message.content)\n    .filter((content): content is Array<TextPart | ImagePart | FilePart> =>\n      Array.isArray(content),\n    )\n    .flat()\n    .filter(\n      (part): part is ImagePart | FilePart =>\n        part.type === 'image' || part.type === 'file',\n    )\n    .map(part => {\n      const mediaType =\n        part.mediaType ?? (part.type === 'image' ? 'image/*' : undefined);\n\n      let data = part.type === 'image' ? part.image : part.data;\n      if (typeof data === 'string') {\n        try {\n          data = new URL(data);\n        } catch (ignored) {}\n      }\n\n      return { mediaType, data };\n    })\n\n    .filter(\n      (part): part is { mediaType: string | undefined; data: URL } =>\n        part.data instanceof URL,\n    )\n    .map(part => ({\n      url: part.data,\n      isUrlSupportedByModel:\n        part.mediaType != null &&\n        isUrlSupported({\n          url: part.data.toString(),\n          mediaType: part.mediaType,\n          supportedUrls,\n        }),\n    }));\n\n  // download in parallel:\n  const downloadedFiles = await download(plannedDownloads);\n\n  return Object.fromEntries(\n    downloadedFiles\n      .map((file, index) =>\n        file == null\n          ? null\n          : [\n              plannedDownloads[index].url.toString(),\n              { data: file.data, mediaType: file.mediaType },\n            ],\n      )\n      .filter(file => file != null),\n  );\n}\n\n/**\n * Convert part of a message to a LanguageModelV3Part.\n *\n * @param part - The part to convert.\n * @param downloadedAssets - A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n * @returns The converted part.\n */\nfunction convertPartToLanguageModelPart(\n  part: TextPart | ImagePart | FilePart,\n  downloadedAssets: Record<\n    string,\n    { mediaType: string | undefined; data: Uint8Array }\n  >,\n): LanguageModelV3TextPart | LanguageModelV3FilePart {\n  if (part.type === 'text') {\n    return {\n      type: 'text',\n      text: part.text,\n      providerOptions: part.providerOptions,\n    };\n  }\n\n  let originalData: DataContent | URL;\n  const type = part.type;\n  switch (type) {\n    case 'image':\n      originalData = part.image;\n      break;\n    case 'file':\n      originalData = part.data;\n\n      break;\n    default:\n      throw new Error(`Unsupported part type: ${type}`);\n  }\n\n  const { data: convertedData, mediaType: convertedMediaType } =\n    convertToLanguageModelV3DataContent(originalData);\n\n  let mediaType: string | undefined = convertedMediaType ?? part.mediaType;\n  let data: Uint8Array | string | URL = convertedData; // binary | base64 | url\n\n  // If the content is a URL, we check if it was downloaded:\n  if (data instanceof URL) {\n    const downloadedFile = downloadedAssets[data.toString()];\n    if (downloadedFile) {\n      data = downloadedFile.data;\n      mediaType ??= downloadedFile.mediaType;\n    }\n  }\n\n  // Now that we have the normalized data either as a URL or a Uint8Array,\n  // we can create the LanguageModelV3Part.\n  switch (type) {\n    case 'image': {\n      // When possible, try to detect the media type automatically\n      // to deal with incorrect media type inputs.\n      // When detection fails, use provided media type.\n      if (data instanceof Uint8Array || typeof data === 'string') {\n        mediaType =\n          detectMediaType({ data, signatures: imageMediaTypeSignatures }) ??\n          mediaType;\n      }\n\n      return {\n        type: 'file',\n        mediaType: mediaType ?? 'image/*', // any image\n        filename: undefined,\n        data,\n        providerOptions: part.providerOptions,\n      };\n    }\n\n    case 'file': {\n      // We must have a mediaType for files, if not, throw an error.\n      if (mediaType == null) {\n        throw new Error(`Media type is missing for file part`);\n      }\n\n      return {\n        type: 'file',\n        mediaType,\n        filename: part.filename,\n        data,\n        providerOptions: part.providerOptions,\n      };\n    }\n  }\n}\n\nfunction mapToolResultOutput(\n  output: ToolResultOutput,\n): LanguageModelV3ToolResultOutput {\n  if (output.type !== 'content') {\n    return output;\n  }\n\n  return {\n    type: 'content',\n    value: output.value.map(item => {\n      if (item.type !== 'media') {\n        return item;\n      }\n\n      // AI SDK 5 tool backwards compatibility:\n      // map media type to image-data or file-data\n      if (item.mediaType.startsWith('image/')) {\n        return {\n          type: 'image-data' as const,\n          data: item.data,\n          mediaType: item.mediaType,\n        };\n      }\n\n      return {\n        type: 'file-data' as const,\n        data: item.data,\n        mediaType: item.mediaType,\n      };\n    }),\n  };\n}\n", "import { convertBase64ToUint8Array } from '@ai-sdk/provider-utils';\n\nexport const imageMediaTypeSignatures = [\n  {\n    mediaType: 'image/gif' as const,\n    bytesPrefix: [0x47, 0x49, 0x46], // GIF\n  },\n  {\n    mediaType: 'image/png' as const,\n    bytesPrefix: [0x89, 0x50, 0x4e, 0x47], // PNG\n  },\n  {\n    mediaType: 'image/jpeg' as const,\n    bytesPrefix: [0xff, 0xd8], // JPEG\n  },\n  {\n    mediaType: 'image/webp' as const,\n    bytesPrefix: [\n      0x52,\n      0x49,\n      0x46,\n      0x46, // \"RIFF\"\n      null,\n      null,\n      null,\n      null, // file size (variable)\n      0x57,\n      0x45,\n      0x42,\n      0x50, // \"WEBP\"\n    ],\n  },\n  {\n    mediaType: 'image/bmp' as const,\n    bytesPrefix: [0x42, 0x4d],\n  },\n  {\n    mediaType: 'image/tiff' as const,\n    bytesPrefix: [0x49, 0x49, 0x2a, 0x00],\n  },\n  {\n    mediaType: 'image/tiff' as const,\n    bytesPrefix: [0x4d, 0x4d, 0x00, 0x2a],\n  },\n  {\n    mediaType: 'image/avif' as const,\n    bytesPrefix: [\n      0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66,\n    ],\n  },\n  {\n    mediaType: 'image/heic' as const,\n    bytesPrefix: [\n      0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63,\n    ],\n  },\n] as const;\n\nexport const audioMediaTypeSignatures = [\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xfb],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xfa],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xf3],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xf2],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xe3],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xe2],\n  },\n  {\n    mediaType: 'audio/wav' as const,\n    bytesPrefix: [\n      0x52, // R\n      0x49, // I\n      0x46, // F\n      0x46, // F\n      null,\n      null,\n      null,\n      null,\n      0x57, // W\n      0x41, // A\n      0x56, // V\n      0x45, // E\n    ],\n  },\n  {\n    mediaType: 'audio/ogg' as const,\n    bytesPrefix: [0x4f, 0x67, 0x67, 0x53],\n  },\n  {\n    mediaType: 'audio/flac' as const,\n    bytesPrefix: [0x66, 0x4c, 0x61, 0x43],\n  },\n  {\n    mediaType: 'audio/aac' as const,\n    bytesPrefix: [0x40, 0x15, 0x00, 0x00],\n  },\n  {\n    mediaType: 'audio/mp4' as const,\n    bytesPrefix: [0x66, 0x74, 0x79, 0x70],\n  },\n  {\n    mediaType: 'audio/webm',\n    bytesPrefix: [0x1a, 0x45, 0xdf, 0xa3],\n  },\n] as const;\n\nexport const videoMediaTypeSignatures = [\n  {\n    mediaType: 'video/mp4' as const,\n    bytesPrefix: [\n      0x00,\n      0x00,\n      0x00,\n      null,\n      0x66,\n      0x74,\n      0x79,\n      0x70, // ftyp\n    ],\n  },\n  {\n    mediaType: 'video/webm' as const,\n    bytesPrefix: [0x1a, 0x45, 0xdf, 0xa3], // EBML\n  },\n  {\n    mediaType: 'video/quicktime' as const,\n    bytesPrefix: [\n      0x00,\n      0x00,\n      0x00,\n      0x14,\n      0x66,\n      0x74,\n      0x79,\n      0x70,\n      0x71,\n      0x74, // ftypqt\n    ],\n  },\n  {\n    mediaType: 'video/x-msvideo' as const,\n    bytesPrefix: [0x52, 0x49, 0x46, 0x46], // RIFF (AVI)\n  },\n] as const;\n\nconst stripID3 = (data: Uint8Array | string) => {\n  const bytes =\n    typeof data === 'string' ? convertBase64ToUint8Array(data) : data;\n  const id3Size =\n    ((bytes[6] & 0x7f) << 21) |\n    ((bytes[7] & 0x7f) << 14) |\n    ((bytes[8] & 0x7f) << 7) |\n    (bytes[9] & 0x7f);\n\n  // The raw MP3 starts here\n  return bytes.slice(id3Size + 10);\n};\n\nfunction stripID3TagsIfPresent(data: Uint8Array | string): Uint8Array | string {\n  const hasId3 =\n    (typeof data === 'string' && data.startsWith('SUQz')) ||\n    (typeof data !== 'string' &&\n      data.length > 10 &&\n      data[0] === 0x49 && // 'I'\n      data[1] === 0x44 && // 'D'\n      data[2] === 0x33); // '3'\n\n  return hasId3 ? stripID3(data) : data;\n}\n\n/**\n * Detect the media IANA media type of a file using a list of signatures.\n *\n * @param data - The file data.\n * @param signatures - The signatures to use for detection.\n * @returns The media type of the file.\n */\nexport function detectMediaType({\n  data,\n  signatures,\n}: {\n  data: Uint8Array | string;\n  signatures:\n    | typeof audioMediaTypeSignatures\n    | typeof imageMediaTypeSignatures\n    | typeof videoMediaTypeSignatures;\n}): (typeof signatures)[number]['mediaType'] | undefined {\n  const processedData = stripID3TagsIfPresent(data);\n\n  // Convert the first ~18 bytes (24 base64 chars) for consistent detection logic:\n  const bytes =\n    typeof processedData === 'string'\n      ? convertBase64ToUint8Array(\n          processedData.substring(0, Math.min(processedData.length, 24)),\n        )\n      : processedData;\n\n  for (const signature of signatures) {\n    if (\n      bytes.length >= signature.bytesPrefix.length &&\n      signature.bytesPrefix.every(\n        (byte, index) => byte === null || bytes[index] === byte,\n      )\n    ) {\n      return signature.mediaType;\n    }\n  }\n\n  return undefined;\n}\n", "import {\n  DownloadError,\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n  validateDownloadUrl,\n  withUserAgentSuffix,\n  getRuntimeEnvironmentUserAgent,\n} from '@ai-sdk/provider-utils';\nimport { VERSION } from '../../version';\n\n/**\n * Download a file from a URL.\n *\n * @param url - The URL to download from.\n * @param maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n * @param abortSignal - An optional abort signal to cancel the download.\n * @returns The downloaded data and media type.\n *\n * @throws DownloadError if the download fails or exceeds maxBytes.\n */\nexport const download = async ({\n  url,\n  maxBytes,\n  abortSignal,\n}: {\n  url: URL;\n  maxBytes?: number;\n  abortSignal?: AbortSignal;\n}) => {\n  const urlText = url.toString();\n  validateDownloadUrl(urlText);\n  try {\n    const response = await fetch(urlText, {\n      headers: withUserAgentSuffix(\n        {},\n        `ai-sdk/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      signal: abortSignal,\n    });\n\n    // Validate final URL after redirects to prevent SSRF via open redirect\n    if (response.redirected) {\n      validateDownloadUrl(response.url);\n    }\n\n    if (!response.ok) {\n      throw new DownloadError({\n        url: urlText,\n        statusCode: response.status,\n        statusText: response.statusText,\n      });\n    }\n\n    const data = await readResponseWithSizeLimit({\n      response,\n      url: urlText,\n      maxBytes: maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE,\n    });\n\n    return {\n      data,\n      mediaType: response.headers.get('content-type') ?? undefined,\n    };\n  } catch (error) {\n    if (DownloadError.isInstance(error)) {\n      throw error;\n    }\n\n    throw new DownloadError({ url: urlText, cause: error });\n  }\n};\n", "declare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n", "import { download as originalDownload } from './download';\n\n/**\n * Experimental. Can change in patch versions without warning.\n *\n * Download function. Called with the array of URLs and a boolean indicating\n * whether the URL is supported by the model.\n *\n * The download function can decide for each URL:\n * - to return null (which means that the URL should be passed to the model)\n * - to download the asset and return the data (incl. retries, authentication, etc.)\n *\n * Should throw DownloadError if the download fails.\n *\n * Should return an array of objects sorted by the order of the requested downloads.\n * For each object, the data should be a Uint8Array if the URL was downloaded.\n * For each object, the mediaType should be the media type of the downloaded asset.\n * For each object, the data should be null if the URL should be passed through as is.\n */\nexport type DownloadFunction = (\n  options: Array<{\n    url: URL;\n    isUrlSupportedByModel: boolean;\n  }>,\n) => PromiseLike<\n  Array<{\n    data: Uint8Array;\n    mediaType: string | undefined;\n  } | null>\n>;\n\n/**\n * Default download function.\n * Downloads the file if it is not supported by the model.\n */\nexport const createDefaultDownloadFunction =\n  (download: typeof originalDownload = originalDownload): DownloadFunction =>\n  requestedDownloads =>\n    Promise.all(\n      requestedDownloads.map(async requestedDownload =>\n        requestedDownload.isUrlSupportedByModel\n          ? null\n          : download(requestedDownload),\n      ),\n    );\n", "import { AISDKError, type LanguageModelV3DataContent } from '@ai-sdk/provider';\nimport {\n  convertBase64ToUint8Array,\n  convertUint8ArrayToBase64,\n  type DataContent,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { InvalidDataContentError } from './invalid-data-content-error';\nimport { splitDataUrl } from './split-data-url';\n\n/**\n * @internal\n */\nexport const dataContentSchema: z.ZodType<DataContent> = z.union([\n  z.string(),\n  z.instanceof(Uint8Array),\n  z.instanceof(ArrayBuffer),\n  z.custom<Buffer>(\n    // Buffer might not be available in some environments such as CloudFlare:\n    (value: unknown): value is Buffer =>\n      globalThis.Buffer?.isBuffer(value) ?? false,\n    { message: 'Must be a Buffer' },\n  ),\n]);\n\nexport function convertToLanguageModelV3DataContent(\n  content: DataContent | URL,\n): {\n  data: LanguageModelV3DataContent;\n  mediaType: string | undefined;\n} {\n  // Buffer & Uint8Array:\n  if (content instanceof Uint8Array) {\n    return { data: content, mediaType: undefined };\n  }\n\n  // ArrayBuffer needs conversion to Uint8Array (lightweight):\n  if (content instanceof ArrayBuffer) {\n    return { data: new Uint8Array(content), mediaType: undefined };\n  }\n\n  // Attempt to create a URL from the data. If it fails, we can assume the data\n  // is not a URL and likely some other sort of data.\n  if (typeof content === 'string') {\n    try {\n      content = new URL(content);\n    } catch (error) {\n      // ignored\n    }\n  }\n\n  // Extract data from data URL:\n  if (content instanceof URL && content.protocol === 'data:') {\n    const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(\n      content.toString(),\n    );\n\n    if (dataUrlMediaType == null || base64Content == null) {\n      throw new AISDKError({\n        name: 'InvalidDataContentError',\n        message: `Invalid data URL format in content ${content.toString()}`,\n      });\n    }\n\n    return { data: base64Content, mediaType: dataUrlMediaType };\n  }\n\n  return { data: content, mediaType: undefined };\n}\n\n/**\n * Converts data content to a base64-encoded string.\n *\n * @param content - Data content to convert.\n * @returns Base64-encoded string.\n */\nexport function convertDataContentToBase64String(content: DataContent): string {\n  if (typeof content === 'string') {\n    return content;\n  }\n\n  if (content instanceof ArrayBuffer) {\n    return convertUint8ArrayToBase64(new Uint8Array(content));\n  }\n\n  return convertUint8ArrayToBase64(content);\n}\n\n/**\n * Converts data content to a Uint8Array.\n *\n * @param content - Data content to convert.\n * @returns Uint8Array.\n */\nexport function convertDataContentToUint8Array(\n  content: DataContent,\n): Uint8Array {\n  if (content instanceof Uint8Array) {\n    return content;\n  }\n\n  if (typeof content === 'string') {\n    try {\n      return convertBase64ToUint8Array(content);\n    } catch (error) {\n      throw new InvalidDataContentError({\n        message:\n          'Invalid data content. Content string is not a base64-encoded media.',\n        content,\n        cause: error,\n      });\n    }\n  }\n\n  if (content instanceof ArrayBuffer) {\n    return new Uint8Array(content);\n  }\n\n  throw new InvalidDataContentError({ content });\n}\n\n/**\n * Converts a Uint8Array to a string of text.\n *\n * @param uint8Array - The Uint8Array to convert.\n * @returns The converted string.\n */\nexport function convertUint8ArrayToText(uint8Array: Uint8Array): string {\n  try {\n    return new TextDecoder().decode(uint8Array);\n  } catch (error) {\n    throw new Error('Error decoding Uint8Array to text');\n  }\n}\n", "export function splitDataUrl(dataUrl: string): {\n  mediaType: string | undefined;\n  base64Content: string | undefined;\n} {\n  try {\n    const [header, base64Content] = dataUrl.split(',');\n    return {\n      mediaType: header.split(';')[0].split(':')[1],\n      base64Content,\n    };\n  } catch (error) {\n    return {\n      mediaType: undefined,\n      base64Content: undefined,\n    };\n  }\n}\n", "import { getErrorMessage, type JSONValue } from '@ai-sdk/provider';\nimport type { Tool, ToolResultOutput } from '@ai-sdk/provider-utils';\n\nexport async function createToolModelOutput({\n  toolCallId,\n  input,\n  output,\n  tool,\n  errorMode,\n}: {\n  toolCallId: string;\n  input: unknown;\n  output: unknown;\n  tool: Tool | undefined;\n  errorMode: 'none' | 'text' | 'json';\n}): Promise<ToolResultOutput> {\n  if (errorMode === 'text') {\n    return { type: 'error-text', value: getErrorMessage(output) };\n  } else if (errorMode === 'json') {\n    return { type: 'error-json', value: toJSONValue(output) };\n  }\n\n  if (tool?.toModelOutput) {\n    return await tool.toModelOutput({ toolCallId, input, output });\n  }\n\n  return typeof output === 'string'\n    ? { type: 'text', value: output }\n    : { type: 'json', value: toJSONValue(output) };\n}\n\nfunction toJSONValue(value: unknown): JSONValue {\n  return value === undefined ? null : (value as JSONValue);\n}\n", "import { InvalidArgumentError } from '../error/invalid-argument-error';\nimport type { CallSettings } from './call-settings';\n\n/**\n * Validates call settings and returns a new object with limited values.\n */\nexport function prepareCallSettings({\n  maxOutputTokens,\n  temperature,\n  topP,\n  topK,\n  presencePenalty,\n  frequencyPenalty,\n  seed,\n  stopSequences,\n}: Omit<CallSettings, 'abortSignal' | 'headers' | 'maxRetries'>): Omit<\n  CallSettings,\n  'abortSignal' | 'headers' | 'maxRetries'\n> {\n  if (maxOutputTokens != null) {\n    if (!Number.isInteger(maxOutputTokens)) {\n      throw new InvalidArgumentError({\n        parameter: 'maxOutputTokens',\n        value: maxOutputTokens,\n        message: 'maxOutputTokens must be an integer',\n      });\n    }\n\n    if (maxOutputTokens < 1) {\n      throw new InvalidArgumentError({\n        parameter: 'maxOutputTokens',\n        value: maxOutputTokens,\n        message: 'maxOutputTokens must be >= 1',\n      });\n    }\n  }\n\n  if (temperature != null) {\n    if (typeof temperature !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'temperature',\n        value: temperature,\n        message: 'temperature must be a number',\n      });\n    }\n  }\n\n  if (topP != null) {\n    if (typeof topP !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'topP',\n        value: topP,\n        message: 'topP must be a number',\n      });\n    }\n  }\n\n  if (topK != null) {\n    if (typeof topK !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'topK',\n        value: topK,\n        message: 'topK must be a number',\n      });\n    }\n  }\n\n  if (presencePenalty != null) {\n    if (typeof presencePenalty !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'presencePenalty',\n        value: presencePenalty,\n        message: 'presencePenalty must be a number',\n      });\n    }\n  }\n\n  if (frequencyPenalty != null) {\n    if (typeof frequencyPenalty !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'frequencyPenalty',\n        value: frequencyPenalty,\n        message: 'frequencyPenalty must be a number',\n      });\n    }\n  }\n\n  if (seed != null) {\n    if (!Number.isInteger(seed)) {\n      throw new InvalidArgumentError({\n        parameter: 'seed',\n        value: seed,\n        message: 'seed must be an integer',\n      });\n    }\n  }\n\n  return {\n    maxOutputTokens,\n    temperature,\n    topP,\n    topK,\n    presencePenalty,\n    frequencyPenalty,\n    stopSequences,\n    seed,\n  };\n}\n", "import type {\n  LanguageModelV3FunctionTool,\n  LanguageModelV3ProviderTool,\n  LanguageModelV3ToolChoice,\n} from '@ai-sdk/provider';\nimport { asSchema } from '@ai-sdk/provider-utils';\nimport { isNonEmptyObject } from '../util/is-non-empty-object';\nimport type { ToolSet } from '../generate-text';\nimport type { ToolChoice } from '../types/language-model';\n\nexport async function prepareToolsAndToolChoice<TOOLS extends ToolSet>({\n  tools,\n  toolChoice,\n  activeTools,\n}: {\n  tools: TOOLS | undefined;\n  toolChoice: ToolChoice<TOOLS> | undefined;\n  activeTools: Array<keyof TOOLS> | undefined;\n}): Promise<{\n  tools:\n    | Array<LanguageModelV3FunctionTool | LanguageModelV3ProviderTool>\n    | undefined;\n  toolChoice: LanguageModelV3ToolChoice | undefined;\n}> {\n  if (!isNonEmptyObject(tools)) {\n    return {\n      tools: undefined,\n      toolChoice: undefined,\n    };\n  }\n\n  // when activeTools is provided, we only include the tools that are in the list:\n  const filteredTools =\n    activeTools != null\n      ? Object.entries(tools).filter(([name]) =>\n          activeTools.includes(name as keyof TOOLS),\n        )\n      : Object.entries(tools);\n\n  const languageModelTools: Array<\n    LanguageModelV3FunctionTool | LanguageModelV3ProviderTool\n  > = [];\n  for (const [name, tool] of filteredTools) {\n    const toolType = tool.type;\n\n    switch (toolType) {\n      case undefined:\n      case 'dynamic':\n      case 'function':\n        languageModelTools.push({\n          type: 'function' as const,\n          name,\n          description: tool.description,\n          inputSchema: await asSchema(tool.inputSchema).jsonSchema,\n          ...(tool.inputExamples != null\n            ? { inputExamples: tool.inputExamples }\n            : {}),\n          providerOptions: tool.providerOptions,\n          ...(tool.strict != null ? { strict: tool.strict } : {}),\n        });\n        break;\n      case 'provider':\n        languageModelTools.push({\n          type: 'provider' as const,\n          name,\n          id: tool.id,\n          args: tool.args,\n        });\n        break;\n      default: {\n        const exhaustiveCheck: never = toolType as never;\n        throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n      }\n    }\n  }\n\n  return {\n    tools: languageModelTools,\n    toolChoice:\n      toolChoice == null\n        ? { type: 'auto' }\n        : typeof toolChoice === 'string'\n          ? { type: toolChoice }\n          : { type: 'tool' as const, toolName: toolChoice.toolName as string },\n  };\n}\n", "export function isNonEmptyObject(\n  object: Record<string, unknown> | undefined | null,\n): object is Record<string, unknown> {\n  return object != null && Object.keys(object).length > 0;\n}\n", "import { InvalidPromptError } from '@ai-sdk/provider';\nimport {\n  safeValidateTypes,\n  type ModelMessage,\n  type SystemModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { modelMessageSchema } from './message';\nimport type { Prompt } from './prompt';\nimport { asArray } from '../util/as-array';\n\nexport type StandardizedPrompt = {\n  /**\n   * System message.\n   */\n  system?: string | SystemModelMessage | Array<SystemModelMessage>;\n\n  /**\n   * Messages.\n   */\n  messages: ModelMessage[];\n};\n\n/**\n * Converts a prompt input into a standardized prompt with validated model\n * messages.\n *\n * @param prompt - The prompt definition to standardize.\n * Set `allowSystemInMessages` to false to reject system messages in the\n * `prompt` or `messages` fields. When unset, system messages are allowed with a\n * warning. System messages in the `system` option are always allowed.\n * @returns The standardized prompt.\n * @throws {InvalidPromptError} When the prompt is invalid.\n */\nexport async function standardizePrompt({\n  allowSystemInMessages,\n  system,\n  prompt,\n  messages,\n}: Prompt): Promise<StandardizedPrompt> {\n  if (prompt == null && messages == null) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'prompt or messages must be defined',\n    });\n  }\n\n  if (prompt != null && messages != null) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'prompt and messages cannot be defined at the same time',\n    });\n  }\n\n  // validate that system is a string or a SystemModelMessage\n  if (\n    typeof system !== 'string' &&\n    !asArray(system).every(message => message.role === 'system')\n  ) {\n    throw new InvalidPromptError({\n      prompt,\n      message:\n        'system must be a string, SystemModelMessage, or array of SystemModelMessage',\n    });\n  }\n\n  if (prompt != null && typeof prompt === 'string') {\n    messages = [{ role: 'user', content: prompt }];\n  } else if (prompt != null && Array.isArray(prompt)) {\n    messages = prompt;\n  } else if (messages == null) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'prompt or messages must be defined',\n    });\n  }\n\n  if (messages.length === 0) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'messages must not be empty',\n    });\n  }\n\n  if (messages.some(message => message.role === 'system')) {\n    if (allowSystemInMessages === false) {\n      throw new InvalidPromptError({\n        prompt,\n        message:\n          'System messages are not allowed in the prompt or messages fields. Use the system option instead.',\n      });\n    }\n\n    if (allowSystemInMessages === undefined) {\n      console.warn(\n        'AI SDK Warning: System messages in the prompt or messages fields ' +\n          'can be a security risk because they may enable prompt injection ' +\n          'attacks. Use the system option instead when possible. Set ' +\n          'allowSystemInMessages to true to suppress this warning, or false ' +\n          'to throw an error.',\n      );\n    }\n  }\n\n  const validationResult = await safeValidateTypes({\n    value: messages,\n    schema: z.array(modelMessageSchema),\n  });\n\n  if (!validationResult.success) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'The messages do not match the ModelMessage[] schema.',\n      cause: validationResult.error,\n    });\n  }\n\n  return { messages, system };\n}\n", "import type {\n  AssistantModelMessage,\n  ModelMessage,\n  SystemModelMessage,\n  ToolModelMessage,\n  UserModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport {\n  filePartSchema,\n  imagePartSchema,\n  reasoningPartSchema,\n  textPartSchema,\n  toolApprovalRequestSchema,\n  toolCallPartSchema,\n  toolApprovalResponseSchema,\n  toolResultPartSchema,\n} from './content-part';\n\nexport const systemModelMessageSchema: z.ZodType<SystemModelMessage> = z.object(\n  {\n    role: z.literal('system'),\n    content: z.string(),\n    providerOptions: providerMetadataSchema.optional(),\n  },\n);\n\nexport const userModelMessageSchema: z.ZodType<UserModelMessage> = z.object({\n  role: z.literal('user'),\n  content: z.union([\n    z.string(),\n    z.array(z.union([textPartSchema, imagePartSchema, filePartSchema])),\n  ]),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const assistantModelMessageSchema: z.ZodType<AssistantModelMessage> =\n  z.object({\n    role: z.literal('assistant'),\n    content: z.union([\n      z.string(),\n      z.array(\n        z.union([\n          textPartSchema,\n          filePartSchema,\n          reasoningPartSchema,\n          toolCallPartSchema,\n          toolResultPartSchema,\n          toolApprovalRequestSchema,\n        ]),\n      ),\n    ]),\n    providerOptions: providerMetadataSchema.optional(),\n  });\n\nexport const toolModelMessageSchema: z.ZodType<ToolModelMessage> = z.object({\n  role: z.literal('tool'),\n  content: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const modelMessageSchema: z.ZodType<ModelMessage> = z.union([\n  systemModelMessageSchema,\n  userModelMessageSchema,\n  assistantModelMessageSchema,\n  toolModelMessageSchema,\n]);\n", "import type { SharedV3ProviderMetadata } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\nimport { jsonValueSchema } from './json-value';\n\n/**\n * Additional provider-specific metadata that is returned from the provider.\n *\n * This is needed to enable provider-specific functionality that can be\n * fully encapsulated in the provider.\n */\nexport type ProviderMetadata = SharedV3ProviderMetadata;\n\nexport const providerMetadataSchema: z.ZodType<ProviderMetadata> = z.record(\n  z.string(),\n  z.record(z.string(), jsonValueSchema.optional()),\n);\n", "import type { JSONValue as OriginalJSONValue } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\n\nexport const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>\n  z.union([\n    z.null(),\n    z.string(),\n    z.number(),\n    z.boolean(),\n    z.record(z.string(), jsonValueSchema.optional()),\n    z.array(jsonValueSchema),\n  ]),\n);\n\nexport type JSONValue = OriginalJSONValue;\n", "import type {\n  FilePart,\n  ImagePart,\n  ProviderOptions,\n  ReasoningPart,\n  TextPart,\n  ToolApprovalRequest,\n  ToolApprovalResponse,\n  ToolResultOutput,\n  ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { jsonValueSchema } from '../types/json-value';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport { dataContentSchema } from './data-content';\n\n/**\n * @internal\n */\nexport const textPartSchema: z.ZodType<TextPart> = z.object({\n  type: z.literal('text'),\n  text: z.string(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const imagePartSchema: z.ZodType<ImagePart> = z.object({\n  type: z.literal('image'),\n  image: z.union([dataContentSchema, z.instanceof(URL)]),\n  mediaType: z.string().optional(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const filePartSchema: z.ZodType<FilePart> = z.object({\n  type: z.literal('file'),\n  data: z.union([dataContentSchema, z.instanceof(URL)]),\n  filename: z.string().optional(),\n  mediaType: z.string(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const reasoningPartSchema: z.ZodType<ReasoningPart> = z.object({\n  type: z.literal('reasoning'),\n  text: z.string(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n  type: 'tool-call';\n\n  /**\n   * ID of the tool call. This ID is used to match the tool call with the tool result.\n   */\n  toolCallId: string;\n\n  /**\n   * Name of the tool that is being called.\n   */\n  toolName: string;\n\n  /**\n   * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n   */\n  input: unknown;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n}\n\n/**\n * @internal\n */\nexport const toolCallPartSchema: z.ZodType<ToolCallPart> = z.object({\n  type: z.literal('tool-call'),\n  toolCallId: z.string(),\n  toolName: z.string(),\n  input: z.unknown(),\n  providerOptions: providerMetadataSchema.optional(),\n  providerExecuted: z.boolean().optional(),\n}) as z.ZodType<ToolCallPart>; // necessary bc input is optional on Zod type\n\n/**\n * @internal\n */\nexport const outputSchema: z.ZodType<ToolResultOutput> = z.discriminatedUnion(\n  'type',\n  [\n    z.object({\n      type: z.literal('text'),\n      value: z.string(),\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('json'),\n      value: jsonValueSchema,\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('execution-denied'),\n      reason: z.string().optional(),\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('error-text'),\n      value: z.string(),\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('error-json'),\n      value: jsonValueSchema,\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('content'),\n      value: z.array(\n        z.union([\n          z.object({\n            type: z.literal('text'),\n            text: z.string(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('media'),\n            data: z.string(),\n            mediaType: z.string(),\n          }),\n          z.object({\n            type: z.literal('file-data'),\n            data: z.string(),\n            mediaType: z.string(),\n            filename: z.string().optional(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('file-url'),\n            url: z.string(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('file-id'),\n            fileId: z.union([z.string(), z.record(z.string(), z.string())]),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('image-data'),\n            data: z.string(),\n            mediaType: z.string(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('image-url'),\n            url: z.string(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('image-file-id'),\n            fileId: z.union([z.string(), z.record(z.string(), z.string())]),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('custom'),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n        ]),\n      ),\n    }),\n  ],\n);\n\n/**\n * @internal\n */\nexport const toolResultPartSchema: z.ZodType<ToolResultPart> = z.object({\n  type: z.literal('tool-result'),\n  toolCallId: z.string(),\n  toolName: z.string(),\n  output: outputSchema,\n  providerOptions: providerMetadataSchema.optional(),\n}) as z.ZodType<ToolResultPart>; // necessary bc result is optional on Zod type\n\n/**\n * @internal\n */\nexport const toolApprovalRequestSchema: z.ZodType<ToolApprovalRequest> =\n  z.object({\n    type: z.literal('tool-approval-request'),\n    approvalId: z.string(),\n    toolCallId: z.string(),\n  });\n\n/**\n * @internal\n */\nexport const toolApprovalResponseSchema: z.ZodType<ToolApprovalResponse> =\n  z.object({\n    type: z.literal('tool-approval-response'),\n    approvalId: z.string(),\n    approved: z.boolean(),\n    reason: z.string().optional(),\n  });\n", "import { GatewayAuthenticationError } from '@ai-sdk/gateway';\nimport { AISDKError } from '@ai-sdk/provider';\n\nexport function wrapGatewayError(error: unknown): unknown {\n  if (!GatewayAuthenticationError.isInstance(error)) return error;\n\n  const isProductionEnv = process?.env.NODE_ENV === 'production';\n  const moreInfoURL = 'https://ai-sdk.dev/unauthenticated-ai-gateway';\n\n  if (isProductionEnv) {\n    return new AISDKError({\n      name: 'GatewayError',\n      message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`,\n    });\n  }\n\n  return Object.assign(\n    new Error(`\\u001b[1m\\u001b[31mUnauthenticated request to AI Gateway.\\u001b[0m\n\nTo authenticate, set the \\u001b[33mAI_GATEWAY_API_KEY\\u001b[0m environment variable with your API key.\n\nAlternatively, you can use a provider module instead of the AI Gateway.\n\nLearn more: \\u001b[34m${moreInfoURL}\\u001b[0m\n\n`),\n    { name: 'GatewayAuthenticationError' },\n  );\n}\n", "import type { TelemetrySettings } from './telemetry-settings';\n\nexport function assembleOperationName({\n  operationId,\n  telemetry,\n}: {\n  operationId: string;\n  telemetry?: TelemetrySettings;\n}) {\n  return {\n    // standardized operation and resource name:\n    'operation.name': `${operationId}${\n      telemetry?.functionId != null ? ` ${telemetry.functionId}` : ''\n    }`,\n    'resource.name': telemetry?.functionId,\n\n    // detailed, AI SDK specific data:\n    'ai.operationId': operationId,\n    'ai.telemetry.functionId': telemetry?.functionId,\n  };\n}\n", "import type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { getTotalTimeoutMs, type CallSettings } from '../prompt/call-settings';\nimport type { TelemetrySettings } from './telemetry-settings';\n\nexport function getBaseTelemetryAttributes({\n  model,\n  settings,\n  telemetry,\n  headers,\n}: {\n  model: { modelId: string; provider: string };\n  settings: Omit<CallSettings, 'abortSignal' | 'headers' | 'temperature'>;\n  telemetry: TelemetrySettings | undefined;\n  headers: Record<string, string | undefined> | undefined;\n}): Attributes {\n  return {\n    'ai.model.provider': model.provider,\n    'ai.model.id': model.modelId,\n\n    // settings:\n    ...Object.entries(settings).reduce((attributes, [key, value]) => {\n      // Handle timeout specially since it can be a number or object\n      if (key === 'timeout') {\n        const totalTimeoutMs = getTotalTimeoutMs(\n          value as Parameters<typeof getTotalTimeoutMs>[0],\n        );\n        if (totalTimeoutMs != null) {\n          attributes[`ai.settings.${key}`] = totalTimeoutMs;\n        }\n      } else {\n        attributes[`ai.settings.${key}`] = value as AttributeValue;\n      }\n      return attributes;\n    }, {} as Attributes),\n\n    // add metadata as attributes:\n    ...Object.entries(telemetry?.metadata ?? {}).reduce(\n      (attributes, [key, value]) => {\n        attributes[`ai.telemetry.metadata.${key}`] = value;\n        return attributes;\n      },\n      {} as Attributes,\n    ),\n\n    // request headers\n    ...Object.entries(headers ?? {}).reduce((attributes, [key, value]) => {\n      if (value !== undefined) {\n        attributes[`ai.request.headers.${key}`] = value;\n      }\n      return attributes;\n    }, {} as Attributes),\n  };\n}\n", "import { trace, type Tracer } from '@opentelemetry/api';\nimport { noopTracer } from './noop-tracer';\n\nexport function getTracer({\n  isEnabled = false,\n  tracer,\n}: {\n  isEnabled?: boolean;\n  tracer?: Tracer;\n} = {}): Tracer {\n  if (!isEnabled) {\n    return noopTracer;\n  }\n\n  if (tracer) {\n    return tracer;\n  }\n\n  return trace.getTracer('ai');\n}\n", "import type { Span, SpanContext, Tracer } from '@opentelemetry/api';\n\n/**\n * Tracer implementation that does nothing (null object).\n */\nexport const noopTracer: Tracer = {\n  startSpan(): Span {\n    return noopSpan;\n  },\n\n  startActiveSpan<F extends (span: Span) => unknown>(\n    name: unknown,\n    arg1: unknown,\n    arg2?: unknown,\n    arg3?: F,\n  ): ReturnType<any> {\n    if (typeof arg1 === 'function') {\n      return arg1(noopSpan);\n    }\n    if (typeof arg2 === 'function') {\n      return arg2(noopSpan);\n    }\n    if (typeof arg3 === 'function') {\n      return arg3(noopSpan);\n    }\n  },\n};\n\nconst noopSpan: Span = {\n  spanContext() {\n    return noopSpanContext;\n  },\n  setAttribute() {\n    return this;\n  },\n  setAttributes() {\n    return this;\n  },\n  addEvent() {\n    return this;\n  },\n  addLink() {\n    return this;\n  },\n  addLinks() {\n    return this;\n  },\n  setStatus() {\n    return this;\n  },\n  updateName() {\n    return this;\n  },\n  end() {\n    return this;\n  },\n  isRecording() {\n    return false;\n  },\n  recordException() {\n    return this;\n  },\n};\n\nconst noopSpanContext: SpanContext = {\n  traceId: '',\n  spanId: '',\n  traceFlags: 0,\n};\n", "import {\n  SpanStatusCode,\n  context,\n  type Attributes,\n  type Span,\n  type Tracer,\n} from '@opentelemetry/api';\n\nexport async function recordSpan<T>({\n  name,\n  tracer,\n  attributes,\n  fn,\n  endWhenDone = true,\n}: {\n  name: string;\n  tracer: Tracer;\n  attributes: Attributes | PromiseLike<Attributes>;\n  fn: (span: Span) => Promise<T>;\n  endWhenDone?: boolean;\n}) {\n  return tracer.startActiveSpan(\n    name,\n    { attributes: await attributes },\n    async span => {\n      // Capture the current context to maintain it across async generator yields\n      const ctx = context.active();\n\n      try {\n        // Execute within the captured context to ensure async generators\n        // don't lose the active span when they yield\n        const result = await context.with(ctx, () => fn(span));\n\n        if (endWhenDone) {\n          span.end();\n        }\n\n        return result;\n      } catch (error) {\n        try {\n          recordErrorOnSpan(span, error);\n        } finally {\n          // always stop the span when there is an error:\n          span.end();\n        }\n\n        throw error;\n      }\n    },\n  );\n}\n\n/**\n * Record an error on a span. Sets the span status to error. If the error is\n * an instance of Error, an exception event with name, message, and stack\n * will also be recorded.\n *\n * @param span - The span to record the error on.\n * @param error - The error to record on the span.\n */\nexport function recordErrorOnSpan(span: Span, error: unknown) {\n  if (error instanceof Error) {\n    span.recordException({\n      name: error.name,\n      message: error.message,\n      stack: error.stack,\n    });\n    span.setStatus({\n      code: SpanStatusCode.ERROR,\n      message: error.message,\n    });\n  } else {\n    span.setStatus({ code: SpanStatusCode.ERROR });\n  }\n}\n", "import type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport type { TelemetrySettings } from './telemetry-settings';\n\ntype ResolvableAttributeValue = () =>\n  | AttributeValue\n  | PromiseLike<AttributeValue>\n  | undefined;\n\nexport async function selectTelemetryAttributes({\n  telemetry,\n  attributes,\n}: {\n  telemetry?: TelemetrySettings;\n  attributes: {\n    [attributeKey: string]:\n      | AttributeValue\n      | { input: ResolvableAttributeValue }\n      | { output: ResolvableAttributeValue }\n      | undefined;\n  };\n}): Promise<Attributes> {\n  // when telemetry is disabled, return an empty object to avoid serialization overhead:\n  if (telemetry?.isEnabled !== true) {\n    return {};\n  }\n\n  const resultAttributes: Attributes = {};\n\n  for (const [key, value] of Object.entries(attributes)) {\n    if (value == null) {\n      continue;\n    }\n\n    // input value, check if it should be recorded:\n    if (\n      typeof value === 'object' &&\n      'input' in value &&\n      typeof value.input === 'function'\n    ) {\n      // default to true:\n      if (telemetry?.recordInputs === false) {\n        continue;\n      }\n\n      const result = await value.input();\n\n      if (result != null) {\n        resultAttributes[key] = result;\n      }\n\n      continue;\n    }\n\n    // output value, check if it should be recorded:\n    if (\n      typeof value === 'object' &&\n      'output' in value &&\n      typeof value.output === 'function'\n    ) {\n      // default to true:\n      if (telemetry?.recordOutputs === false) {\n        continue;\n      }\n\n      const result = await value.output();\n\n      if (result != null) {\n        resultAttributes[key] = result;\n      }\n      continue;\n    }\n\n    // value is an attribute value already:\n    resultAttributes[key] = value as AttributeValue;\n  }\n\n  return resultAttributes;\n}\n", "import type {\n  LanguageModelV3Message,\n  LanguageModelV3Prompt,\n} from '@ai-sdk/provider';\nimport { convertDataContentToBase64String } from '../prompt/data-content';\n\n/**\n * Helper utility to serialize prompt content for OpenTelemetry tracing.\n * It is initially created because normalized LanguageModelV3Prompt carries\n * images as Uint8Arrays, on which JSON.stringify acts weirdly, converting\n * them to objects with stringified indices as keys, e.g. {\"0\": 42, \"1\": 69 }.\n */\nexport function stringifyForTelemetry(prompt: LanguageModelV3Prompt): string {\n  return JSON.stringify(\n    prompt.map((message: LanguageModelV3Message) => ({\n      ...message,\n      content:\n        typeof message.content === 'string'\n          ? message.content\n          : message.content.map(part =>\n              part.type === 'file'\n                ? {\n                    ...part,\n                    data:\n                      part.data instanceof Uint8Array\n                        ? convertDataContentToBase64String(part.data)\n                        : part.data,\n                  }\n                : part,\n            ),\n    })),\n  );\n}\n", "import type { TelemetryIntegration } from './telemetry-integration';\n\n/**\n * Registers a telemetry integration globally.\n */\nexport function registerTelemetryIntegration(\n  integration: TelemetryIntegration,\n): void {\n  if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) {\n    globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n  }\n  globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(integration);\n}\n\nexport function getGlobalTelemetryIntegrations(): TelemetryIntegration[] {\n  return globalThis.AI_SDK_TELEMETRY_INTEGRATIONS ?? [];\n}\n", "import type { Output } from '../generate-text/output';\nimport type { ToolSet } from '../generate-text/tool-set';\nimport { asArray } from '../util/as-array';\nimport type { TelemetryIntegration } from './telemetry-integration';\nimport { getGlobalTelemetryIntegrations } from './telemetry-integration-registry';\n\n/**\n * Wraps a telemetry integration with bound methods.\n * Use this when creating class-based integrations to ensure methods\n * work correctly when passed as callbacks.\n */\nexport function bindTelemetryIntegration(\n  integration: TelemetryIntegration,\n): TelemetryIntegration {\n  return {\n    onStart: integration.onStart?.bind(integration),\n    onStepStart: integration.onStepStart?.bind(integration),\n    onToolCallStart: integration.onToolCallStart?.bind(integration),\n    onToolCallFinish: integration.onToolCallFinish?.bind(integration),\n    onStepFinish: integration.onStepFinish?.bind(integration),\n    onFinish: integration.onFinish?.bind(integration),\n  };\n}\n\n/**\n * Creates a factory that merges globally registered integrations\n * (via `registerTelemetryIntegration`) with per-call integrations\n * into a single composite integration.\n *\n * Returns a factory function that accepts local integrations and\n * returns the merged TelemetryIntegration.\n */\nexport function getGlobalTelemetryIntegration<\n  TOOLS extends ToolSet = ToolSet,\n  OUTPUT extends Output = Output,\n>(): (\n  integrations: TelemetryIntegration | Array<TelemetryIntegration> | undefined,\n) => TelemetryIntegration {\n  const globalIntegrations = getGlobalTelemetryIntegrations();\n\n  return (\n    integrations:\n      | TelemetryIntegration\n      | Array<TelemetryIntegration>\n      | undefined,\n  ): TelemetryIntegration => {\n    const localIntegrations = asArray(integrations);\n    const allIntegrations = [...globalIntegrations, ...localIntegrations];\n\n    function createTelemetryComposite<EVENT>(\n      getListenerFromIntegration: (\n        integration: TelemetryIntegration,\n      ) => ((event: EVENT) => PromiseLike<void> | void) | undefined,\n    ): ((event: EVENT) => Promise<void>) | undefined {\n      const listeners = allIntegrations\n        .map(getListenerFromIntegration)\n        .filter(Boolean) as Array<(event: EVENT) => PromiseLike<void> | void>;\n\n      return async (event: EVENT) => {\n        for (const listener of listeners) {\n          try {\n            await listener(event);\n          } catch (_ignored) {}\n        }\n      };\n    }\n\n    return {\n      onStart: createTelemetryComposite(integration => integration.onStart),\n      onStepStart: createTelemetryComposite(\n        integration => integration.onStepStart,\n      ),\n      onToolCallStart: createTelemetryComposite(\n        integration => integration.onToolCallStart,\n      ),\n      onToolCallFinish: createTelemetryComposite(\n        integration => integration.onToolCallFinish,\n      ),\n      onStepFinish: createTelemetryComposite(\n        integration => integration.onStepFinish,\n      ),\n      onFinish: createTelemetryComposite(integration => integration.onFinish),\n    };\n  };\n}\n", "import type {\n  ImageModelV3Usage,\n  JSONObject,\n  LanguageModelV3Usage,\n} from '@ai-sdk/provider';\n\n/**\n * Represents the number of tokens used in a prompt and completion.\n */\nexport type LanguageModelUsage = {\n  /**\n   * The total number of input (prompt) tokens used.\n   */\n  inputTokens: number | undefined;\n\n  /**\n   * Detailed information about the input tokens.\n   */\n  inputTokenDetails: {\n    /**\n     * The number of non-cached input (prompt) tokens used.\n     */\n    noCacheTokens: number | undefined;\n\n    /**\n     * The number of cached input (prompt) tokens read.\n     */\n    cacheReadTokens: number | undefined;\n\n    /**\n     * The number of cached input (prompt) tokens written.\n     */\n    cacheWriteTokens: number | undefined;\n  };\n\n  /**\n   * The number of total output (completion) tokens used.\n   */\n  outputTokens: number | undefined;\n\n  /**\n   * Detailed information about the output tokens.\n   */\n  outputTokenDetails: {\n    /**\n     * The number of text tokens used.\n     */\n    textTokens: number | undefined;\n\n    /**\n     * The number of reasoning tokens used.\n     */\n    reasoningTokens: number | undefined;\n  };\n\n  /**\n   * The total number of tokens used.\n   */\n  totalTokens: number | undefined;\n\n  /**\n   * @deprecated Use outputTokenDetails.reasoningTokens instead.\n   */\n  reasoningTokens?: number | undefined;\n\n  /**\n   * @deprecated Use inputTokenDetails.cacheReadTokens instead.\n   */\n  cachedInputTokens?: number | undefined;\n\n  /**\n   * Raw usage information from the provider.\n   *\n   * This is the usage information in the shape that the provider returns.\n   * It can include additional information that is not part of the standard usage information.\n   */\n  raw?: JSONObject;\n};\n\n/**\n * Represents the number of tokens used in an embedding.\n */\n// TODO replace with EmbeddingModelV3Usage\nexport type EmbeddingModelUsage = {\n  /**\n   * The number of tokens used in the embedding.\n   */\n  tokens: number;\n};\n\nexport function asLanguageModelUsage(\n  usage: LanguageModelV3Usage,\n): LanguageModelUsage {\n  return {\n    inputTokens: usage.inputTokens.total,\n    inputTokenDetails: {\n      noCacheTokens: usage.inputTokens.noCache,\n      cacheReadTokens: usage.inputTokens.cacheRead,\n      cacheWriteTokens: usage.inputTokens.cacheWrite,\n    },\n    outputTokens: usage.outputTokens.total,\n    outputTokenDetails: {\n      textTokens: usage.outputTokens.text,\n      reasoningTokens: usage.outputTokens.reasoning,\n    },\n    totalTokens: addTokenCounts(\n      usage.inputTokens.total,\n      usage.outputTokens.total,\n    ),\n    raw: usage.raw,\n    reasoningTokens: usage.outputTokens.reasoning,\n    cachedInputTokens: usage.inputTokens.cacheRead,\n  };\n}\n\nexport function createNullLanguageModelUsage(): LanguageModelUsage {\n  return {\n    inputTokens: undefined,\n    inputTokenDetails: {\n      noCacheTokens: undefined,\n      cacheReadTokens: undefined,\n      cacheWriteTokens: undefined,\n    },\n    outputTokens: undefined,\n    outputTokenDetails: {\n      textTokens: undefined,\n      reasoningTokens: undefined,\n    },\n    totalTokens: undefined,\n    raw: undefined,\n  };\n}\n\nexport function addLanguageModelUsage(\n  usage1: LanguageModelUsage,\n  usage2: LanguageModelUsage,\n): LanguageModelUsage {\n  return {\n    inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n    inputTokenDetails: {\n      noCacheTokens: addTokenCounts(\n        usage1.inputTokenDetails?.noCacheTokens,\n        usage2.inputTokenDetails?.noCacheTokens,\n      ),\n      cacheReadTokens: addTokenCounts(\n        usage1.inputTokenDetails?.cacheReadTokens,\n        usage2.inputTokenDetails?.cacheReadTokens,\n      ),\n      cacheWriteTokens: addTokenCounts(\n        usage1.inputTokenDetails?.cacheWriteTokens,\n        usage2.inputTokenDetails?.cacheWriteTokens,\n      ),\n    },\n    outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n    outputTokenDetails: {\n      textTokens: addTokenCounts(\n        usage1.outputTokenDetails?.textTokens,\n        usage2.outputTokenDetails?.textTokens,\n      ),\n      reasoningTokens: addTokenCounts(\n        usage1.outputTokenDetails?.reasoningTokens,\n        usage2.outputTokenDetails?.reasoningTokens,\n      ),\n    },\n    totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n    reasoningTokens: addTokenCounts(\n      usage1.reasoningTokens,\n      usage2.reasoningTokens,\n    ),\n    cachedInputTokens: addTokenCounts(\n      usage1.cachedInputTokens,\n      usage2.cachedInputTokens,\n    ),\n  };\n}\n\nfunction addTokenCounts(\n  tokenCount1: number | undefined,\n  tokenCount2: number | undefined,\n): number | undefined {\n  return tokenCount1 == null && tokenCount2 == null\n    ? undefined\n    : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);\n}\n\n/**\n * Usage information for an image model call.\n */\nexport type ImageModelUsage = ImageModelV3Usage;\n\nexport function addImageModelUsage(\n  usage1: ImageModelUsage,\n  usage2: ImageModelUsage,\n): ImageModelUsage {\n  return {\n    inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n    outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n    totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n  };\n}\n", "/**\n * Deeply merges two objects together.\n * - Properties from the `overrides` object override those in the `base` object with the same key.\n * - For nested objects, the merge is performed recursively (deep merge).\n * - Arrays are replaced, not merged.\n * - Primitive values are replaced.\n * - If both `base` and `overrides` are undefined, returns undefined.\n * - If one of `base` or `overrides` is undefined, returns the other.\n *\n * @param base The target object to merge into\n * @param overrides The source object to merge from\n * @returns A new object with the merged properties, or undefined if both inputs are undefined\n */\nexport function mergeObjects<T extends object, U extends object>(\n  base: T | undefined,\n  overrides: U | undefined,\n): (T & U) | T | U | undefined {\n  // If both inputs are undefined, return undefined\n  if (base === undefined && overrides === undefined) {\n    return undefined;\n  }\n\n  // If target is undefined, return source\n  if (base === undefined) {\n    return overrides;\n  }\n\n  // If source is undefined, return target\n  if (overrides === undefined) {\n    return base;\n  }\n\n  // Create a new object to avoid mutating the inputs\n  const result = { ...base } as T & U;\n\n  // Iterate through all keys in the source object\n  for (const key in overrides) {\n    // Skip prototype-polluting keys when merging untrusted input\n    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n      continue;\n    }\n\n    if (Object.prototype.hasOwnProperty.call(overrides, key)) {\n      const overridesValue = overrides[key];\n\n      // Skip if the overrides value is undefined\n      if (overridesValue === undefined) continue;\n\n      // Get the base value if it exists\n      const baseValue =\n        key in base ? base[key as unknown as keyof T] : undefined;\n\n      // Check if both values are objects that can be deeply merged\n      const isSourceObject =\n        overridesValue !== null &&\n        typeof overridesValue === 'object' &&\n        !Array.isArray(overridesValue) &&\n        !(overridesValue instanceof Date) &&\n        !(overridesValue instanceof RegExp);\n\n      const isTargetObject =\n        baseValue !== null &&\n        baseValue !== undefined &&\n        typeof baseValue === 'object' &&\n        !Array.isArray(baseValue) &&\n        !(baseValue instanceof Date) &&\n        !(baseValue instanceof RegExp);\n\n      // If both values are mergeable objects, merge them recursively\n      if (isSourceObject && isTargetObject) {\n        result[key as keyof (T & U)] = mergeObjects(\n          baseValue as object,\n          overridesValue as object,\n        ) as any;\n      } else {\n        // For primitives, arrays, or when one value is not a mergeable object,\n        // simply override with the source value\n        result[key as keyof (T & U)] = overridesValue as any;\n      }\n    }\n  }\n\n  return result;\n}\n", "import { APICallError } from '@ai-sdk/provider';\nimport { GatewayError } from '@ai-sdk/gateway';\nimport { delay, getErrorMessage, isAbortError } from '@ai-sdk/provider-utils';\nimport { RetryError } from './retry-error';\n\nexport type RetryFunction = <OUTPUT>(\n  fn: () => PromiseLike<OUTPUT>,\n) => PromiseLike<OUTPUT>;\n\nfunction getRetryDelayInMs({\n  error,\n  exponentialBackoffDelay,\n}: {\n  error: APICallError | GatewayError;\n  exponentialBackoffDelay: number;\n}): number {\n  const headers = APICallError.isInstance(error)\n    ? error.responseHeaders\n    : APICallError.isInstance(error.cause)\n      ? (error.cause as APICallError).responseHeaders\n      : undefined;\n\n  if (!headers) return exponentialBackoffDelay;\n\n  let ms: number | undefined;\n\n  // retry-ms is more precise than retry-after and used by e.g. OpenAI\n  const retryAfterMs = headers['retry-after-ms'];\n  if (retryAfterMs) {\n    const timeoutMs = parseFloat(retryAfterMs);\n    if (!Number.isNaN(timeoutMs)) {\n      ms = timeoutMs;\n    }\n  }\n\n  // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n  const retryAfter = headers['retry-after'];\n  if (retryAfter && ms === undefined) {\n    const timeoutSeconds = parseFloat(retryAfter);\n    if (!Number.isNaN(timeoutSeconds)) {\n      ms = timeoutSeconds * 1000;\n    } else {\n      ms = Date.parse(retryAfter) - Date.now();\n    }\n  }\n\n  // check that the delay is reasonable:\n  if (\n    ms != null &&\n    !Number.isNaN(ms) &&\n    0 <= ms &&\n    (ms < 60 * 1000 || ms < exponentialBackoffDelay)\n  ) {\n    return ms;\n  }\n\n  return exponentialBackoffDelay;\n}\n\n/**\n * The `retryWithExponentialBackoffRespectingRetryHeaders` strategy retries a failed API call with an exponential backoff,\n * while respecting rate limit headers (retry-after-ms and retry-after) if they are provided and reasonable (0-60 seconds).\n * You can configure the maximum number of retries, the initial delay, and the backoff factor.\n */\nexport const retryWithExponentialBackoffRespectingRetryHeaders =\n  ({\n    maxRetries = 2,\n    initialDelayInMs = 2000,\n    backoffFactor = 2,\n    abortSignal,\n  }: {\n    maxRetries?: number;\n    initialDelayInMs?: number;\n    backoffFactor?: number;\n    abortSignal?: AbortSignal;\n  } = {}): RetryFunction =>\n  async <OUTPUT>(f: () => PromiseLike<OUTPUT>) =>\n    _retryWithExponentialBackoff(f, {\n      maxRetries,\n      delayInMs: initialDelayInMs,\n      backoffFactor,\n      abortSignal,\n    });\n\nasync function _retryWithExponentialBackoff<OUTPUT>(\n  f: () => PromiseLike<OUTPUT>,\n  {\n    maxRetries,\n    delayInMs,\n    backoffFactor,\n    abortSignal,\n  }: {\n    maxRetries: number;\n    delayInMs: number;\n    backoffFactor: number;\n    abortSignal: AbortSignal | undefined;\n  },\n  errors: unknown[] = [],\n): Promise<OUTPUT> {\n  try {\n    return await f();\n  } catch (error) {\n    if (isAbortError(error)) {\n      throw error; // don't retry when the request was aborted\n    }\n\n    if (maxRetries === 0) {\n      throw error; // don't wrap the error when retries are disabled\n    }\n\n    const errorMessage = getErrorMessage(error);\n    const newErrors = [...errors, error];\n    const tryNumber = newErrors.length;\n\n    if (tryNumber > maxRetries) {\n      throw new RetryError({\n        message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n        reason: 'maxRetriesExceeded',\n        errors: newErrors,\n      });\n    }\n\n    if (\n      error instanceof Error &&\n      ((APICallError.isInstance(error) && error.isRetryable === true) ||\n        (GatewayError.isInstance(error) && error.isRetryable === true)) &&\n      tryNumber <= maxRetries\n    ) {\n      await delay(\n        getRetryDelayInMs({\n          error: error as APICallError | GatewayError,\n          exponentialBackoffDelay: delayInMs,\n        }),\n        { abortSignal },\n      );\n\n      return _retryWithExponentialBackoff(\n        f,\n        {\n          maxRetries,\n          delayInMs: backoffFactor * delayInMs,\n          backoffFactor,\n          abortSignal,\n        },\n        newErrors,\n      );\n    }\n\n    if (tryNumber === 1) {\n      throw error; // don't wrap the error when a non-retryable error occurs on the first try\n    }\n\n    throw new RetryError({\n      message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n      reason: 'errorNotRetryable',\n      errors: newErrors,\n    });\n  }\n}\n", "import { InvalidArgumentError } from '../error/invalid-argument-error';\nimport {\n  retryWithExponentialBackoffRespectingRetryHeaders,\n  type RetryFunction,\n} from '../util/retry-with-exponential-backoff';\n\n/**\n * Validate and prepare retries.\n */\nexport function prepareRetries({\n  maxRetries,\n  abortSignal,\n}: {\n  maxRetries: number | undefined;\n  abortSignal: AbortSignal | undefined;\n}): {\n  maxRetries: number;\n  retry: RetryFunction;\n} {\n  if (maxRetries != null) {\n    if (!Number.isInteger(maxRetries)) {\n      throw new InvalidArgumentError({\n        parameter: 'maxRetries',\n        value: maxRetries,\n        message: 'maxRetries must be an integer',\n      });\n    }\n\n    if (maxRetries < 0) {\n      throw new InvalidArgumentError({\n        parameter: 'maxRetries',\n        value: maxRetries,\n        message: 'maxRetries must be >= 0',\n      });\n    }\n  }\n\n  const maxRetriesResult = maxRetries ?? 2;\n\n  return {\n    maxRetries: maxRetriesResult,\n    retry: retryWithExponentialBackoffRespectingRetryHeaders({\n      maxRetries: maxRetriesResult,\n      abortSignal,\n    }),\n  };\n}\n", "import type {\n  ModelMessage,\n  ToolApprovalRequest,\n  ToolApprovalResponse,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolApprovalError } from '../error/invalid-tool-approval-error';\nimport { ToolCallNotFoundForApprovalError } from '../error/tool-call-not-found-for-approval-error';\nimport type { TypedToolCall } from './tool-call';\nimport type { TypedToolResult } from './tool-result';\nimport type { ToolSet } from './tool-set';\n\nexport type CollectedToolApprovals<TOOLS extends ToolSet> = {\n  approvalRequest: ToolApprovalRequest;\n  approvalResponse: ToolApprovalResponse;\n  toolCall: TypedToolCall<TOOLS>;\n};\n\n/**\n * If the last message is a tool message, this function collects all tool approvals\n * from that message.\n */\nexport function collectToolApprovals<TOOLS extends ToolSet>({\n  messages,\n}: {\n  messages: ModelMessage[];\n}): {\n  approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n  deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n} {\n  const lastMessage = messages.at(-1);\n\n  if (lastMessage?.role != 'tool') {\n    return {\n      approvedToolApprovals: [],\n      deniedToolApprovals: [],\n    };\n  }\n\n  // gather tool calls and prepare lookup\n  const toolCallsByToolCallId: Record<string, TypedToolCall<TOOLS>> = {};\n  for (const message of messages) {\n    if (message.role === 'assistant' && typeof message.content !== 'string') {\n      const content = message.content;\n      for (const part of content) {\n        if (part.type === 'tool-call') {\n          toolCallsByToolCallId[part.toolCallId] = part as TypedToolCall<TOOLS>;\n        }\n      }\n    }\n  }\n\n  // gather approval responses and prepare lookup\n  const toolApprovalRequestsByApprovalId: Record<string, ToolApprovalRequest> =\n    {};\n  for (const message of messages) {\n    if (message.role === 'assistant' && typeof message.content !== 'string') {\n      const content = message.content;\n      for (const part of content) {\n        if (part.type === 'tool-approval-request') {\n          toolApprovalRequestsByApprovalId[part.approvalId] = part;\n        }\n      }\n    }\n  }\n\n  // gather tool results from the last tool message\n  const toolResults: Record<string, TypedToolResult<TOOLS>> = {};\n  for (const part of lastMessage.content) {\n    if (part.type === 'tool-result') {\n      toolResults[part.toolCallId] = part as TypedToolResult<TOOLS>;\n    }\n  }\n\n  const approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>> = [];\n  const deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>> = [];\n\n  const approvalResponses = lastMessage.content.filter(\n    part => part.type === 'tool-approval-response',\n  );\n  for (const approvalResponse of approvalResponses) {\n    const approvalRequest =\n      toolApprovalRequestsByApprovalId[approvalResponse.approvalId];\n\n    if (approvalRequest == null) {\n      throw new InvalidToolApprovalError({\n        approvalId: approvalResponse.approvalId,\n      });\n    }\n\n    if (toolResults[approvalRequest.toolCallId] != null) {\n      continue;\n    }\n\n    const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];\n    if (toolCall == null) {\n      throw new ToolCallNotFoundForApprovalError({\n        toolCallId: approvalRequest.toolCallId,\n        approvalId: approvalRequest.approvalId,\n      });\n    }\n\n    const approval: CollectedToolApprovals<TOOLS> = {\n      approvalRequest,\n      approvalResponse,\n      toolCall,\n    };\n\n    if (approvalResponse.approved) {\n      approvedToolApprovals.push(approval);\n    } else {\n      deniedToolApprovals.push(approval);\n    }\n  }\n\n  return { approvedToolApprovals, deniedToolApprovals };\n}\n", "import { executeTool, type ModelMessage } from '@ai-sdk/provider-utils';\nimport type { Tracer } from '@opentelemetry/api';\nimport { notify } from '../util/notify';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { recordErrorOnSpan, recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport { now } from '../util/now';\nimport type {\n  GenerateTextOnToolCallFinishCallback,\n  GenerateTextOnToolCallStartCallback,\n} from './generate-text';\nimport type { TypedToolCall } from './tool-call';\nimport type { ToolOutput } from './tool-output';\nimport type { ToolSet } from './tool-set';\nimport type { TypedToolResult } from './tool-result';\nimport type { TypedToolError } from './tool-error';\n\n/**\n * Executes a single tool call and manages its lifecycle callbacks.\n *\n * This function handles the complete tool execution flow:\n * 1. Invokes `onToolCallStart` callback before execution\n * 2. Executes the tool's `execute` function with proper context\n * 3. Handles streaming outputs via `onPreliminaryToolResult`\n * 4. Invokes `onToolCallFinish` callback with success or error result\n *\n * @returns The tool output (result or error), or undefined if the tool has no execute function.\n */\nexport async function executeToolCall<TOOLS extends ToolSet>({\n  toolCall,\n  tools,\n  tracer,\n  telemetry,\n  messages,\n  abortSignal,\n  experimental_context,\n  stepNumber,\n  model,\n  onPreliminaryToolResult,\n  onToolCallStart,\n  onToolCallFinish,\n}: {\n  toolCall: TypedToolCall<TOOLS>;\n  tools: TOOLS | undefined;\n  tracer: Tracer;\n  telemetry: TelemetrySettings | undefined;\n  messages: ModelMessage[];\n  abortSignal: AbortSignal | undefined;\n  experimental_context: unknown;\n  stepNumber?: number;\n  model?: { provider: string; modelId: string };\n  onPreliminaryToolResult?: (result: TypedToolResult<TOOLS>) => void;\n  onToolCallStart?:\n    | GenerateTextOnToolCallStartCallback<TOOLS>\n    | Array<GenerateTextOnToolCallStartCallback<TOOLS> | undefined | null>;\n  onToolCallFinish?:\n    | GenerateTextOnToolCallFinishCallback<TOOLS>\n    | Array<GenerateTextOnToolCallFinishCallback<TOOLS> | undefined | null>;\n}): Promise<ToolOutput<TOOLS> | undefined> {\n  const { toolName, toolCallId, input } = toolCall;\n  const tool = tools?.[toolName];\n\n  if (tool?.execute == null) {\n    return undefined;\n  }\n\n  const baseCallbackEvent = {\n    stepNumber,\n    model,\n    toolCall,\n    messages,\n    abortSignal,\n    functionId: telemetry?.functionId,\n    metadata: telemetry?.metadata as Record<string, unknown> | undefined,\n    experimental_context,\n  };\n\n  return recordSpan({\n    name: 'ai.toolCall',\n    attributes: selectTelemetryAttributes({\n      telemetry,\n      attributes: {\n        ...assembleOperationName({\n          operationId: 'ai.toolCall',\n          telemetry,\n        }),\n        'ai.toolCall.name': toolName,\n        'ai.toolCall.id': toolCallId,\n        'ai.toolCall.args': {\n          output: () => JSON.stringify(input),\n        },\n      },\n    }),\n    tracer,\n    fn: async span => {\n      let output: unknown;\n\n      await notify({ event: baseCallbackEvent, callbacks: onToolCallStart });\n\n      const startTime = now();\n\n      try {\n        const stream = executeTool({\n          execute: tool.execute!.bind(tool),\n          input,\n          options: {\n            toolCallId,\n            messages,\n            abortSignal,\n            experimental_context,\n          },\n        });\n\n        for await (const part of stream) {\n          if (part.type === 'preliminary') {\n            onPreliminaryToolResult?.({\n              ...toolCall,\n              type: 'tool-result',\n              output: part.output,\n              preliminary: true,\n            });\n          } else {\n            output = part.output;\n          }\n        }\n      } catch (error) {\n        const durationMs = now() - startTime;\n\n        await notify({\n          event: {\n            ...baseCallbackEvent,\n            success: false as const,\n            error,\n            durationMs,\n          },\n          callbacks: onToolCallFinish,\n        });\n\n        recordErrorOnSpan(span, error);\n        return {\n          type: 'tool-error',\n          toolCallId,\n          toolName,\n          input,\n          error,\n          dynamic: tool.type === 'dynamic',\n          ...(toolCall.providerMetadata != null\n            ? { providerMetadata: toolCall.providerMetadata }\n            : {}),\n          ...(toolCall.toolMetadata != null\n            ? { toolMetadata: toolCall.toolMetadata }\n            : {}),\n        } as TypedToolError<TOOLS>;\n      }\n\n      const durationMs = now() - startTime;\n\n      await notify({\n        event: {\n          ...baseCallbackEvent,\n          success: true as const,\n          output,\n          durationMs,\n        },\n        callbacks: onToolCallFinish,\n      });\n\n      try {\n        span.setAttributes(\n          await selectTelemetryAttributes({\n            telemetry,\n            attributes: {\n              'ai.toolCall.result': {\n                output: () => JSON.stringify(output),\n              },\n            },\n          }),\n        );\n      } catch (ignored) {\n        // JSON stringify might fail if the result is not serializable,\n        // in which case we just ignore it. In the future we might want to\n        // add an optional serialize method to the tool interface and warn\n        // if the result is not serializable.\n      }\n\n      return {\n        type: 'tool-result',\n        toolCallId,\n        toolName,\n        input,\n        output,\n        dynamic: tool.type === 'dynamic',\n        ...(toolCall.providerMetadata != null\n          ? { providerMetadata: toolCall.providerMetadata }\n          : {}),\n        ...(toolCall.toolMetadata != null\n          ? { toolMetadata: toolCall.toolMetadata }\n          : {}),\n      } as TypedToolResult<TOOLS>;\n    },\n  });\n}\n", "// Shim for performance.now() to support environments that don't have it:\nexport function now(): number {\n  return globalThis?.performance?.now() ?? Date.now();\n}\n", "import type {\n  LanguageModelV3Content,\n  LanguageModelV3Reasoning,\n} from '@ai-sdk/provider';\n\nexport function extractReasoningContent(\n  content: LanguageModelV3Content[],\n): string | undefined {\n  const parts = content.filter(\n    (content): content is LanguageModelV3Reasoning =>\n      content.type === 'reasoning',\n  );\n\n  return parts.length === 0\n    ? undefined\n    : parts.map(content => content.text).join('\\n');\n}\n", "import type {\n  LanguageModelV3Content,\n  LanguageModelV3Text,\n} from '@ai-sdk/provider';\n\nexport function extractTextContent(\n  content: LanguageModelV3Content[],\n): string | undefined {\n  const parts = content.filter(\n    (content): content is LanguageModelV3Text => content.type === 'text',\n  );\n\n  if (parts.length === 0) {\n    return undefined;\n  }\n\n  return parts.map(content => content.text).join('');\n}\n", "import {\n  convertBase64ToUint8Array,\n  convertUint8ArrayToBase64,\n} from '@ai-sdk/provider-utils';\n\n/**\n * A generated file.\n */\nexport interface GeneratedFile {\n  /**\n   * File as a base64 encoded string.\n   */\n  readonly base64: string;\n\n  /**\n   * File as a Uint8Array.\n   */\n  readonly uint8Array: Uint8Array;\n\n  /**\n   * The IANA media type of the file.\n   *\n   * @see https://www.iana.org/assignments/media-types/media-types.xhtml\n   */\n  readonly mediaType: string;\n}\n\nexport class DefaultGeneratedFile implements GeneratedFile {\n  private base64Data: string | undefined;\n  private uint8ArrayData: Uint8Array | undefined;\n\n  readonly mediaType: string;\n\n  constructor({\n    data,\n    mediaType,\n  }: {\n    data: string | Uint8Array;\n    mediaType: string;\n  }) {\n    const isUint8Array = data instanceof Uint8Array;\n    this.base64Data = isUint8Array ? undefined : data;\n    this.uint8ArrayData = isUint8Array ? data : undefined;\n    this.mediaType = mediaType;\n  }\n\n  // lazy conversion with caching to avoid unnecessary conversion overhead:\n  get base64() {\n    if (this.base64Data == null) {\n      this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData!);\n    }\n    return this.base64Data;\n  }\n\n  // lazy conversion with caching to avoid unnecessary conversion overhead:\n  get uint8Array() {\n    if (this.uint8ArrayData == null) {\n      this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data!);\n    }\n    return this.uint8ArrayData;\n  }\n}\n\nexport class DefaultGeneratedFileWithType extends DefaultGeneratedFile {\n  readonly type = 'file';\n\n  constructor(options: { data: string | Uint8Array; mediaType: string }) {\n    super(options);\n  }\n}\n", "import type { ModelMessage } from '@ai-sdk/provider-utils';\nimport type { TypedToolCall } from './tool-call';\nimport type { ToolSet } from './tool-set';\n\nexport async function isApprovalNeeded<TOOLS extends ToolSet>({\n  tool,\n  toolCall,\n  messages,\n  experimental_context,\n}: {\n  tool: TOOLS[keyof TOOLS];\n  toolCall: TypedToolCall<TOOLS>;\n  messages: ModelMessage[];\n  experimental_context: unknown;\n}) {\n  if (tool.needsApproval == null) {\n    return false;\n  }\n\n  if (typeof tool.needsApproval === 'boolean') {\n    return tool.needsApproval;\n  }\n\n  return await tool.needsApproval(toolCall.input, {\n    toolCallId: toolCall.toolCallId,\n    messages,\n    experimental_context,\n  });\n}\n", "import {\n  TypeValidationError,\n  type JSONValue,\n  type LanguageModelV3CallOptions,\n} from '@ai-sdk/provider';\nimport {\n  asSchema,\n  resolve,\n  safeParseJSON,\n  safeValidateTypes,\n  type FlexibleSchema,\n} from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport type { FinishReason } from '../types/language-model';\nimport type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport type { LanguageModelUsage } from '../types/usage';\nimport type { DeepPartial } from '../util/deep-partial';\nimport { parsePartialJson } from '../util/parse-partial-json';\nimport type { EnrichedStreamPart } from './stream-text';\n\nexport interface Output<OUTPUT = any, PARTIAL = any, ELEMENT = any> {\n  /**\n   * The name of the output mode.\n   */\n  name: string;\n\n  /**\n   * The response format to use for the model.\n   */\n  responseFormat: PromiseLike<LanguageModelV3CallOptions['responseFormat']>;\n\n  /**\n   * Parses the complete output of the model.\n   */\n  parseCompleteOutput(\n    options: { text: string },\n    context: {\n      response: LanguageModelResponseMetadata;\n      usage: LanguageModelUsage;\n      finishReason: FinishReason;\n    },\n  ): Promise<OUTPUT>;\n\n  /**\n   * Parses the partial output of the model.\n   */\n  parsePartialOutput(options: {\n    text: string;\n  }): Promise<{ partial: PARTIAL } | undefined>;\n\n  /**\n   * Creates a stream transform that emits individual elements as they complete.\n   */\n  createElementStreamTransform():\n    | TransformStream<EnrichedStreamPart<any, PARTIAL>, ELEMENT>\n    | undefined;\n}\n\n/**\n * Output specification for text generation.\n * This is the default output mode that generates plain text.\n *\n * @returns An output specification for generating text.\n */\nexport const text = (): Output<string, string, never> => ({\n  name: 'text',\n  responseFormat: Promise.resolve({ type: 'text' }),\n\n  async parseCompleteOutput({ text }: { text: string }) {\n    return text;\n  },\n\n  async parsePartialOutput({ text }: { text: string }) {\n    return { partial: text };\n  },\n\n  createElementStreamTransform() {\n    return undefined;\n  },\n});\n\n/**\n * Output specification for typed object generation using schemas.\n * When the model generates a text response, it will return an object that matches the schema.\n *\n * @param schema - The schema of the object to generate.\n * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n *\n * @returns An output specification for generating objects with the specified schema.\n */\nexport const object = <OBJECT>({\n  schema: inputSchema,\n  name,\n  description,\n}: {\n  schema: FlexibleSchema<OBJECT>;\n  /**\n   * Optional name of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n   */\n  name?: string;\n  /**\n   * Optional description of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n   */\n  description?: string;\n}): Output<OBJECT, DeepPartial<OBJECT>, never> => {\n  const schema = asSchema(inputSchema);\n\n  return {\n    name: 'object',\n\n    responseFormat: resolve(schema.jsonSchema).then(jsonSchema => ({\n      type: 'json' as const,\n      schema: jsonSchema,\n      ...(name != null && { name }),\n      ...(description != null && { description }),\n    })),\n\n    async parseCompleteOutput(\n      { text }: { text: string },\n      context: {\n        response: LanguageModelResponseMetadata;\n        usage: LanguageModelUsage;\n        finishReason: FinishReason;\n      },\n    ) {\n      const parseResult = await safeParseJSON({ text });\n\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: could not parse the response.',\n          cause: parseResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      const validationResult = await safeValidateTypes({\n        value: parseResult.value,\n        schema,\n      });\n\n      if (!validationResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: response did not match schema.',\n          cause: validationResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      return validationResult.value;\n    },\n\n    async parsePartialOutput({ text }: { text: string }) {\n      const result = await parsePartialJson(text);\n\n      switch (result.state) {\n        case 'failed-parse':\n        case 'undefined-input': {\n          return undefined;\n        }\n\n        case 'repaired-parse':\n        case 'successful-parse': {\n          return {\n            // Note: currently no validation of partial results:\n            partial: result.value as DeepPartial<OBJECT>,\n          };\n        }\n      }\n    },\n\n    createElementStreamTransform() {\n      return undefined;\n    },\n  };\n};\n\n/**\n * Output specification for array generation.\n * When the model generates a text response, it will return an array of elements.\n *\n * @param element - The schema of the array elements to generate.\n * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n *\n * @returns An output specification for generating an array of elements.\n */\nexport const array = <ELEMENT>({\n  element: inputElementSchema,\n  name,\n  description,\n}: {\n  element: FlexibleSchema<ELEMENT>;\n  /**\n   * Optional name of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n   */\n  name?: string;\n  /**\n   * Optional description of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n   */\n  description?: string;\n}): Output<Array<ELEMENT>, Array<ELEMENT>, ELEMENT> => {\n  const elementSchema = asSchema(inputElementSchema);\n\n  return {\n    name: 'array',\n\n    // JSON schema that describes an array of elements:\n    responseFormat: resolve(elementSchema.jsonSchema).then(jsonSchema => {\n      // remove $schema from schema.jsonSchema:\n      const { $schema, ...itemSchema } = jsonSchema;\n\n      return {\n        type: 'json' as const,\n        schema: {\n          $schema: 'http://json-schema.org/draft-07/schema#',\n          type: 'object',\n          properties: {\n            elements: { type: 'array', items: itemSchema },\n          },\n          required: ['elements'],\n          additionalProperties: false,\n        },\n        ...(name != null && { name }),\n        ...(description != null && { description }),\n      };\n    }),\n\n    async parseCompleteOutput(\n      { text }: { text: string },\n      context: {\n        response: LanguageModelResponseMetadata;\n        usage: LanguageModelUsage;\n        finishReason: FinishReason;\n      },\n    ) {\n      const parseResult = await safeParseJSON({ text });\n\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: could not parse the response.',\n          cause: parseResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      const outerValue = parseResult.value;\n\n      if (\n        outerValue == null ||\n        typeof outerValue !== 'object' ||\n        !('elements' in outerValue) ||\n        !Array.isArray(outerValue.elements)\n      ) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: response did not match schema.',\n          cause: new TypeValidationError({\n            value: outerValue,\n            cause: 'response must be an object with an elements array',\n          }),\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      for (const element of outerValue.elements) {\n        const validationResult = await safeValidateTypes({\n          value: element,\n          schema: elementSchema,\n        });\n\n        if (!validationResult.success) {\n          throw new NoObjectGeneratedError({\n            message: 'No object generated: response did not match schema.',\n            cause: validationResult.error,\n            text,\n            response: context.response,\n            usage: context.usage,\n            finishReason: context.finishReason,\n          });\n        }\n      }\n\n      return outerValue.elements as Array<ELEMENT>;\n    },\n\n    async parsePartialOutput({ text }: { text: string }) {\n      const result = await parsePartialJson(text);\n\n      switch (result.state) {\n        case 'failed-parse':\n        case 'undefined-input': {\n          return undefined;\n        }\n\n        case 'repaired-parse':\n        case 'successful-parse': {\n          const outerValue = result.value;\n\n          // no parsable elements array\n          if (\n            outerValue == null ||\n            typeof outerValue !== 'object' ||\n            !('elements' in outerValue) ||\n            !Array.isArray(outerValue.elements)\n          ) {\n            return undefined;\n          }\n\n          const rawElements =\n            result.state === 'repaired-parse' && outerValue.elements.length > 0\n              ? outerValue.elements.slice(0, -1)\n              : outerValue.elements;\n\n          const parsedElements: Array<ELEMENT> = [];\n          for (const rawElement of rawElements) {\n            const validationResult = await safeValidateTypes({\n              value: rawElement,\n              schema: elementSchema,\n            });\n\n            if (validationResult.success) {\n              parsedElements.push(validationResult.value);\n            }\n          }\n\n          return { partial: parsedElements };\n        }\n      }\n    },\n\n    createElementStreamTransform() {\n      let publishedElements = 0;\n\n      return new TransformStream<\n        EnrichedStreamPart<any, Array<ELEMENT>>,\n        ELEMENT\n      >({\n        transform({ partialOutput }, controller) {\n          if (partialOutput != null) {\n            // Only enqueue new elements that haven't been published yet\n            for (\n              ;\n              publishedElements < partialOutput.length;\n              publishedElements++\n            ) {\n              controller.enqueue(partialOutput[publishedElements]);\n            }\n          }\n        },\n      });\n    },\n  };\n};\n\n/**\n * Output specification for choice generation.\n * When the model generates a text response, it will return a one of the choice options.\n *\n * @param options - The available choices.\n * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n *\n * @returns An output specification for generating a choice.\n */\nexport const choice = <CHOICE extends string>({\n  options: choiceOptions,\n  name,\n  description,\n}: {\n  options: Array<CHOICE>;\n  /**\n   * Optional name of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n   */\n  name?: string;\n  /**\n   * Optional description of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n   */\n  description?: string;\n}): Output<CHOICE, CHOICE, never> => {\n  return {\n    name: 'choice',\n\n    // JSON schema that describes an enumeration:\n    responseFormat: Promise.resolve({\n      type: 'json',\n      schema: {\n        $schema: 'http://json-schema.org/draft-07/schema#',\n        type: 'object',\n        properties: {\n          result: { type: 'string', enum: choiceOptions },\n        },\n        required: ['result'],\n        additionalProperties: false,\n      },\n      ...(name != null && { name }),\n      ...(description != null && { description }),\n    } as const),\n\n    async parseCompleteOutput(\n      { text }: { text: string },\n      context: {\n        response: LanguageModelResponseMetadata;\n        usage: LanguageModelUsage;\n        finishReason: FinishReason;\n      },\n    ) {\n      const parseResult = await safeParseJSON({ text });\n\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: could not parse the response.',\n          cause: parseResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      const outerValue = parseResult.value;\n\n      if (\n        outerValue == null ||\n        typeof outerValue !== 'object' ||\n        !('result' in outerValue) ||\n        typeof outerValue.result !== 'string' ||\n        !choiceOptions.includes(outerValue.result as any)\n      ) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: response did not match schema.',\n          cause: new TypeValidationError({\n            value: outerValue,\n            cause: 'response must be an object that contains a choice value.',\n          }),\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      return outerValue.result as CHOICE;\n    },\n\n    async parsePartialOutput({ text }: { text: string }) {\n      const result = await parsePartialJson(text);\n\n      switch (result.state) {\n        case 'failed-parse':\n        case 'undefined-input': {\n          return undefined;\n        }\n\n        case 'repaired-parse':\n        case 'successful-parse': {\n          const outerValue = result.value;\n\n          if (\n            outerValue == null ||\n            typeof outerValue !== 'object' ||\n            !('result' in outerValue) ||\n            typeof outerValue.result !== 'string'\n          ) {\n            return undefined;\n          }\n\n          // list of potential matches.\n          const potentialMatches = choiceOptions.filter(choiceOption =>\n            choiceOption.startsWith(outerValue.result as string),\n          );\n\n          if (result.state === 'successful-parse') {\n            // successful parse: exact choice value\n            return potentialMatches.includes(outerValue.result as any)\n              ? { partial: outerValue.result as CHOICE }\n              : undefined;\n          } else {\n            // repaired parse: only return if not ambiguous\n            return potentialMatches.length === 1\n              ? { partial: potentialMatches[0] as CHOICE }\n              : undefined;\n          }\n        }\n      }\n    },\n\n    createElementStreamTransform() {\n      return undefined;\n    },\n  };\n};\n\n/**\n * Output specification for unstructured JSON generation.\n * When the model generates a text response, it will return a JSON object.\n *\n * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n *\n * @returns An output specification for generating JSON.\n */\nexport const json = ({\n  name,\n  description,\n}: {\n  /**\n   * Optional name of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n   */\n  name?: string;\n  /**\n   * Optional description of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n   */\n  description?: string;\n} = {}): Output<JSONValue, JSONValue, never> => {\n  return {\n    name: 'json',\n\n    responseFormat: Promise.resolve({\n      type: 'json' as const,\n      ...(name != null && { name }),\n      ...(description != null && { description }),\n    }),\n\n    async parseCompleteOutput(\n      { text }: { text: string },\n      context: {\n        response: LanguageModelResponseMetadata;\n        usage: LanguageModelUsage;\n        finishReason: FinishReason;\n      },\n    ) {\n      const parseResult = await safeParseJSON({ text });\n\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: could not parse the response.',\n          cause: parseResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      return parseResult.value;\n    },\n\n    async parsePartialOutput({ text }: { text: string }) {\n      const result = await parsePartialJson(text);\n\n      switch (result.state) {\n        case 'failed-parse':\n        case 'undefined-input': {\n          return undefined;\n        }\n\n        case 'repaired-parse':\n        case 'successful-parse': {\n          return result.value === undefined\n            ? undefined\n            : { partial: result.value };\n        }\n      }\n    },\n\n    createElementStreamTransform() {\n      return undefined;\n    },\n  };\n};\n", "import type { JSONValue } from '@ai-sdk/provider';\nimport { safeParseJSON } from '@ai-sdk/provider-utils';\nimport { fixJson } from './fix-json';\n\nexport async function parsePartialJson(jsonText: string | undefined): Promise<{\n  value: JSONValue | undefined;\n  state:\n    | 'undefined-input'\n    | 'successful-parse'\n    | 'repaired-parse'\n    | 'failed-parse';\n}> {\n  if (jsonText === undefined) {\n    return { value: undefined, state: 'undefined-input' };\n  }\n\n  let result = await safeParseJSON({ text: jsonText });\n\n  if (result.success) {\n    return { value: result.value, state: 'successful-parse' };\n  }\n\n  result = await safeParseJSON({ text: fixJson(jsonText) });\n\n  if (result.success) {\n    return { value: result.value, state: 'repaired-parse' };\n  }\n\n  return { value: undefined, state: 'failed-parse' };\n}\n", "type State =\n  | 'ROOT'\n  | 'FINISH'\n  | 'INSIDE_STRING'\n  | 'INSIDE_STRING_ESCAPE'\n  | 'INSIDE_LITERAL'\n  | 'INSIDE_NUMBER'\n  | 'INSIDE_OBJECT_START'\n  | 'INSIDE_OBJECT_KEY'\n  | 'INSIDE_OBJECT_AFTER_KEY'\n  | 'INSIDE_OBJECT_BEFORE_VALUE'\n  | 'INSIDE_OBJECT_AFTER_VALUE'\n  | 'INSIDE_OBJECT_AFTER_COMMA'\n  | 'INSIDE_ARRAY_START'\n  | 'INSIDE_ARRAY_AFTER_VALUE'\n  | 'INSIDE_ARRAY_AFTER_COMMA';\n\n// Implemented as a scanner with additional fixing\n// that performs a single linear time scan pass over the partial JSON.\n//\n// The states should ideally match relevant states from the JSON spec:\n// https://www.json.org/json-en.html\n//\n// Please note that invalid JSON is not considered/covered, because it\n// is assumed that the resulting JSON will be processed by a standard\n// JSON parser that will detect any invalid JSON.\nexport function fixJson(input: string): string {\n  const stack: State[] = ['ROOT'];\n  let lastValidIndex = -1;\n  let literalStart: number | null = null;\n\n  function processValueStart(char: string, i: number, swapState: State) {\n    {\n      switch (char) {\n        case '\"': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_STRING');\n          break;\n        }\n\n        case 'f':\n        case 't':\n        case 'n': {\n          lastValidIndex = i;\n          literalStart = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_LITERAL');\n          break;\n        }\n\n        case '-': {\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_NUMBER');\n          break;\n        }\n        case '0':\n        case '1':\n        case '2':\n        case '3':\n        case '4':\n        case '5':\n        case '6':\n        case '7':\n        case '8':\n        case '9': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_NUMBER');\n          break;\n        }\n\n        case '{': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_OBJECT_START');\n          break;\n        }\n\n        case '[': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_ARRAY_START');\n          break;\n        }\n      }\n    }\n  }\n\n  function processAfterObjectValue(char: string, i: number) {\n    switch (char) {\n      case ',': {\n        stack.pop();\n        stack.push('INSIDE_OBJECT_AFTER_COMMA');\n        break;\n      }\n      case '}': {\n        lastValidIndex = i;\n        stack.pop();\n        break;\n      }\n    }\n  }\n\n  function processAfterArrayValue(char: string, i: number) {\n    switch (char) {\n      case ',': {\n        stack.pop();\n        stack.push('INSIDE_ARRAY_AFTER_COMMA');\n        break;\n      }\n      case ']': {\n        lastValidIndex = i;\n        stack.pop();\n        break;\n      }\n    }\n  }\n\n  for (let i = 0; i < input.length; i++) {\n    const char = input[i];\n    const currentState = stack[stack.length - 1];\n\n    switch (currentState) {\n      case 'ROOT':\n        processValueStart(char, i, 'FINISH');\n        break;\n\n      case 'INSIDE_OBJECT_START': {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push('INSIDE_OBJECT_KEY');\n            break;\n          }\n          case '}': {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_OBJECT_AFTER_COMMA': {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push('INSIDE_OBJECT_KEY');\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_OBJECT_KEY': {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push('INSIDE_OBJECT_AFTER_KEY');\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_OBJECT_AFTER_KEY': {\n        switch (char) {\n          case ':': {\n            stack.pop();\n            stack.push('INSIDE_OBJECT_BEFORE_VALUE');\n\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_OBJECT_BEFORE_VALUE': {\n        processValueStart(char, i, 'INSIDE_OBJECT_AFTER_VALUE');\n        break;\n      }\n\n      case 'INSIDE_OBJECT_AFTER_VALUE': {\n        processAfterObjectValue(char, i);\n        break;\n      }\n\n      case 'INSIDE_STRING': {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            lastValidIndex = i;\n            break;\n          }\n\n          case '\\\\': {\n            stack.push('INSIDE_STRING_ESCAPE');\n            break;\n          }\n\n          default: {\n            lastValidIndex = i;\n          }\n        }\n\n        break;\n      }\n\n      case 'INSIDE_ARRAY_START': {\n        switch (char) {\n          case ']': {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n\n          default: {\n            lastValidIndex = i;\n            processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE');\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_ARRAY_AFTER_VALUE': {\n        switch (char) {\n          case ',': {\n            stack.pop();\n            stack.push('INSIDE_ARRAY_AFTER_COMMA');\n            break;\n          }\n\n          case ']': {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n\n          default: {\n            lastValidIndex = i;\n            break;\n          }\n        }\n\n        break;\n      }\n\n      case 'INSIDE_ARRAY_AFTER_COMMA': {\n        processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE');\n        break;\n      }\n\n      case 'INSIDE_STRING_ESCAPE': {\n        stack.pop();\n        lastValidIndex = i;\n\n        break;\n      }\n\n      case 'INSIDE_NUMBER': {\n        switch (char) {\n          case '0':\n          case '1':\n          case '2':\n          case '3':\n          case '4':\n          case '5':\n          case '6':\n          case '7':\n          case '8':\n          case '9': {\n            lastValidIndex = i;\n            break;\n          }\n\n          case 'e':\n          case 'E':\n          case '-':\n          case '.': {\n            break;\n          }\n\n          case ',': {\n            stack.pop();\n\n            if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n              processAfterArrayValue(char, i);\n            }\n\n            if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n              processAfterObjectValue(char, i);\n            }\n\n            break;\n          }\n\n          case '}': {\n            stack.pop();\n\n            if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n              processAfterObjectValue(char, i);\n            }\n\n            break;\n          }\n\n          case ']': {\n            stack.pop();\n\n            if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n              processAfterArrayValue(char, i);\n            }\n\n            break;\n          }\n\n          default: {\n            stack.pop();\n            break;\n          }\n        }\n\n        break;\n      }\n\n      case 'INSIDE_LITERAL': {\n        const partialLiteral = input.substring(literalStart!, i + 1);\n\n        if (\n          !'false'.startsWith(partialLiteral) &&\n          !'true'.startsWith(partialLiteral) &&\n          !'null'.startsWith(partialLiteral)\n        ) {\n          stack.pop();\n\n          if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n            processAfterObjectValue(char, i);\n          } else if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n            processAfterArrayValue(char, i);\n          }\n        } else {\n          lastValidIndex = i;\n        }\n\n        break;\n      }\n    }\n  }\n\n  let result = input.slice(0, lastValidIndex + 1);\n\n  for (let i = stack.length - 1; i >= 0; i--) {\n    const state = stack[i];\n\n    switch (state) {\n      case 'INSIDE_STRING': {\n        result += '\"';\n        break;\n      }\n\n      case 'INSIDE_OBJECT_KEY':\n      case 'INSIDE_OBJECT_AFTER_KEY':\n      case 'INSIDE_OBJECT_AFTER_COMMA':\n      case 'INSIDE_OBJECT_START':\n      case 'INSIDE_OBJECT_BEFORE_VALUE':\n      case 'INSIDE_OBJECT_AFTER_VALUE': {\n        result += '}';\n        break;\n      }\n\n      case 'INSIDE_ARRAY_START':\n      case 'INSIDE_ARRAY_AFTER_COMMA':\n      case 'INSIDE_ARRAY_AFTER_VALUE': {\n        result += ']';\n        break;\n      }\n\n      case 'INSIDE_LITERAL': {\n        const partialLiteral = input.substring(literalStart!, input.length);\n\n        if ('true'.startsWith(partialLiteral)) {\n          result += 'true'.slice(partialLiteral.length);\n        } else if ('false'.startsWith(partialLiteral)) {\n          result += 'false'.slice(partialLiteral.length);\n        } else if ('null'.startsWith(partialLiteral)) {\n          result += 'null'.slice(partialLiteral.length);\n        }\n      }\n    }\n  }\n\n  return result;\n}\n", "import type { LanguageModelV3ToolCall } from '@ai-sdk/provider';\nimport {\n  asSchema,\n  safeParseJSON,\n  safeValidateTypes,\n  type ModelMessage,\n  type SystemModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolInputError } from '../error/invalid-tool-input-error';\nimport { NoSuchToolError } from '../error/no-such-tool-error';\nimport { ToolCallRepairError } from '../error/tool-call-repair-error';\nimport type { DynamicToolCall, TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type { ToolSet } from './tool-set';\n\nexport async function parseToolCall<TOOLS extends ToolSet>({\n  toolCall,\n  tools,\n  repairToolCall,\n  system,\n  messages,\n}: {\n  toolCall: LanguageModelV3ToolCall;\n  tools: TOOLS | undefined;\n  repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n  system: string | SystemModelMessage | Array<SystemModelMessage> | undefined;\n  messages: ModelMessage[];\n}): Promise<TypedToolCall<TOOLS>> {\n  try {\n    if (tools == null) {\n      // provider-executed dynamic tools are not part of our list of tools:\n      if (toolCall.providerExecuted && toolCall.dynamic) {\n        return await parseProviderExecutedDynamicToolCall(toolCall);\n      }\n\n      throw new NoSuchToolError({ toolName: toolCall.toolName });\n    }\n\n    try {\n      return await doParseToolCall({ toolCall, tools });\n    } catch (error) {\n      if (\n        repairToolCall == null ||\n        !(\n          NoSuchToolError.isInstance(error) ||\n          InvalidToolInputError.isInstance(error)\n        )\n      ) {\n        throw error;\n      }\n\n      let repairedToolCall: LanguageModelV3ToolCall | null = null;\n\n      try {\n        repairedToolCall = await repairToolCall({\n          toolCall,\n          tools,\n          inputSchema: async ({ toolName }) => {\n            const { inputSchema } = tools[toolName];\n            return await asSchema(inputSchema).jsonSchema;\n          },\n          system,\n          messages,\n          error,\n        });\n      } catch (repairError) {\n        throw new ToolCallRepairError({\n          cause: repairError,\n          originalError: error,\n        });\n      }\n\n      // no repaired tool call returned\n      if (repairedToolCall == null) {\n        throw error;\n      }\n\n      return await doParseToolCall({ toolCall: repairedToolCall, tools });\n    }\n  } catch (error) {\n    // use parsed input when possible\n    const parsedInput = await safeParseJSON({ text: toolCall.input });\n    const input = parsedInput.success ? parsedInput.value : toolCall.input;\n    const tool = tools?.[toolCall.toolName];\n\n    // TODO AI SDK 6: special invalid tool call parts\n    return {\n      type: 'tool-call',\n      toolCallId: toolCall.toolCallId,\n      toolName: toolCall.toolName,\n      input,\n      dynamic: true,\n      invalid: true,\n      error,\n      title: tool?.title,\n      providerExecuted: toolCall.providerExecuted,\n      providerMetadata: toolCall.providerMetadata,\n      ...(tool?.metadata != null ? { toolMetadata: tool.metadata } : {}),\n    };\n  }\n}\n\nasync function parseProviderExecutedDynamicToolCall(\n  toolCall: LanguageModelV3ToolCall,\n): Promise<DynamicToolCall> {\n  const parseResult =\n    toolCall.input.trim() === ''\n      ? { success: true as const, value: {} }\n      : await safeParseJSON({ text: toolCall.input });\n\n  if (parseResult.success === false) {\n    throw new InvalidToolInputError({\n      toolName: toolCall.toolName,\n      toolInput: toolCall.input,\n      cause: parseResult.error,\n    });\n  }\n\n  return {\n    type: 'tool-call',\n    toolCallId: toolCall.toolCallId,\n    toolName: toolCall.toolName,\n    input: parseResult.value,\n    providerExecuted: true,\n    dynamic: true,\n    providerMetadata: toolCall.providerMetadata,\n  };\n}\n\nasync function doParseToolCall<TOOLS extends ToolSet>({\n  toolCall,\n  tools,\n}: {\n  toolCall: LanguageModelV3ToolCall;\n  tools: TOOLS;\n}): Promise<TypedToolCall<TOOLS>> {\n  const toolName = toolCall.toolName as keyof TOOLS & string;\n\n  const tool = tools[toolName];\n\n  if (tool == null) {\n    // provider-executed dynamic tools are not part of our list of tools:\n    if (toolCall.providerExecuted && toolCall.dynamic) {\n      return await parseProviderExecutedDynamicToolCall(toolCall);\n    }\n\n    throw new NoSuchToolError({\n      toolName: toolCall.toolName,\n      availableTools: Object.keys(tools),\n    });\n  }\n\n  const schema = asSchema(tool.inputSchema);\n\n  // when the tool call has no arguments, we try passing an empty object to the schema\n  // (many LLMs generate empty strings for tool calls with no arguments)\n  const parseResult =\n    toolCall.input.trim() === ''\n      ? await safeValidateTypes({ value: {}, schema })\n      : await safeParseJSON({ text: toolCall.input, schema });\n\n  if (parseResult.success === false) {\n    throw new InvalidToolInputError({\n      toolName,\n      toolInput: toolCall.input,\n      cause: parseResult.error,\n    });\n  }\n\n  return tool.type === 'dynamic'\n    ? {\n        type: 'tool-call',\n        toolCallId: toolCall.toolCallId,\n        toolName: toolCall.toolName,\n        input: parseResult.value,\n        providerExecuted: toolCall.providerExecuted,\n        providerMetadata: toolCall.providerMetadata,\n        ...(tool.metadata != null ? { toolMetadata: tool.metadata } : {}),\n        dynamic: true,\n        title: tool.title,\n      }\n    : {\n        type: 'tool-call',\n        toolCallId: toolCall.toolCallId,\n        toolName,\n        input: parseResult.value,\n        providerExecuted: toolCall.providerExecuted,\n        providerMetadata: toolCall.providerMetadata,\n        ...(tool.metadata != null ? { toolMetadata: tool.metadata } : {}),\n        title: tool.title,\n      };\n}\n", "import type { ReasoningPart } from '@ai-sdk/provider-utils';\nimport type {\n  CallWarning,\n  FinishReason,\n  LanguageModelRequestMetadata,\n  LanguageModelResponseMetadata,\n  ProviderMetadata,\n} from '../types';\nimport type { Source } from '../types/language-model';\nimport type { LanguageModelUsage } from '../types/usage';\nimport type { ContentPart } from './content-part';\nimport type { GeneratedFile } from './generated-file';\nimport type { ResponseMessage } from './response-message';\nimport type {\n  DynamicToolCall,\n  StaticToolCall,\n  TypedToolCall,\n} from './tool-call';\nimport type {\n  DynamicToolResult,\n  StaticToolResult,\n  TypedToolResult,\n} from './tool-result';\nimport type { ToolSet } from './tool-set';\n\n/**\n * The result of a single step in the generation process.\n */\nexport type StepResult<TOOLS extends ToolSet> = {\n  /**\n   * Zero-based index of this step.\n   */\n  readonly stepNumber: number;\n\n  /**\n   * Information about the model that produced this step.\n   */\n  readonly model: {\n    /** The provider of the model. */\n    readonly provider: string;\n    /** The ID of the model. */\n    readonly modelId: string;\n  };\n\n  /**\n   * Identifier from telemetry settings for grouping related operations.\n   */\n  readonly functionId: string | undefined;\n\n  /**\n   * Additional metadata from telemetry settings.\n   */\n  readonly metadata: Record<string, unknown> | undefined;\n\n  /**\n   * User-defined context object flowing through the generation.\n   *\n   * Experimental (can break in patch releases).\n   */\n  readonly experimental_context: unknown;\n\n  /**\n   * The content that was generated in the last step.\n   */\n  readonly content: Array<ContentPart<TOOLS>>;\n\n  /**\n   * The generated text.\n   */\n  readonly text: string;\n\n  /**\n   * The reasoning that was generated during the generation.\n   */\n  readonly reasoning: Array<ReasoningPart>;\n\n  /**\n   * The reasoning text that was generated during the generation.\n   */\n  readonly reasoningText: string | undefined;\n\n  /**\n   * The files that were generated during the generation.\n   */\n  readonly files: Array<GeneratedFile>;\n\n  /**\n   * The sources that were used to generate the text.\n   */\n  readonly sources: Array<Source>;\n\n  /**\n   * The tool calls that were made during the generation.\n   */\n  readonly toolCalls: Array<TypedToolCall<TOOLS>>;\n\n  /**\n   * The static tool calls that were made in the last step.\n   */\n  readonly staticToolCalls: Array<StaticToolCall<TOOLS>>;\n\n  /**\n   * The dynamic tool calls that were made in the last step.\n   */\n  readonly dynamicToolCalls: Array<DynamicToolCall>;\n\n  /**\n   * The results of the tool calls.\n   */\n  readonly toolResults: Array<TypedToolResult<TOOLS>>;\n\n  /**\n   * The static tool results that were made in the last step.\n   */\n  readonly staticToolResults: Array<StaticToolResult<TOOLS>>;\n\n  /**\n   * The dynamic tool results that were made in the last step.\n   */\n  readonly dynamicToolResults: Array<DynamicToolResult>;\n\n  /**\n   * The unified reason why the generation finished.\n   */\n  readonly finishReason: FinishReason;\n\n  /**\n   * The raw reason why the generation finished (from the provider).\n   */\n  readonly rawFinishReason: string | undefined;\n\n  /**\n   * The token usage of the generated text.\n   */\n  readonly usage: LanguageModelUsage;\n\n  /**\n   * Warnings from the model provider (e.g. unsupported settings).\n   */\n  readonly warnings: CallWarning[] | undefined;\n\n  /**\n   * Additional request information.\n   */\n  readonly request: LanguageModelRequestMetadata;\n\n  /**\n   * Additional response information.\n   */\n  readonly response: LanguageModelResponseMetadata & {\n    /**\n     * The response messages that were generated during the call.\n     * Response messages can be either assistant messages or tool messages.\n     * They contain a generated id.\n     */\n    readonly messages: Array<ResponseMessage>;\n\n    /**\n     * Response body (available only for providers that use HTTP requests).\n     */\n    body?: unknown;\n  };\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * from the provider to the AI SDK and enable provider-specific\n   * results that can be fully encapsulated in the provider.\n   */\n  readonly providerMetadata: ProviderMetadata | undefined;\n};\n\nexport class DefaultStepResult<\n  TOOLS extends ToolSet,\n> implements StepResult<TOOLS> {\n  readonly stepNumber: StepResult<TOOLS>['stepNumber'];\n  readonly model: StepResult<TOOLS>['model'];\n  readonly functionId: StepResult<TOOLS>['functionId'];\n  readonly metadata: StepResult<TOOLS>['metadata'];\n  readonly experimental_context: StepResult<TOOLS>['experimental_context'];\n  readonly content: StepResult<TOOLS>['content'];\n  readonly finishReason: StepResult<TOOLS>['finishReason'];\n  readonly rawFinishReason: StepResult<TOOLS>['rawFinishReason'];\n  readonly usage: StepResult<TOOLS>['usage'];\n  readonly warnings: StepResult<TOOLS>['warnings'];\n  readonly request: StepResult<TOOLS>['request'];\n  readonly response: StepResult<TOOLS>['response'];\n  readonly providerMetadata: StepResult<TOOLS>['providerMetadata'];\n\n  constructor({\n    stepNumber,\n    model,\n    functionId,\n    metadata,\n    experimental_context,\n    content,\n    finishReason,\n    rawFinishReason,\n    usage,\n    warnings,\n    request,\n    response,\n    providerMetadata,\n  }: {\n    stepNumber: StepResult<TOOLS>['stepNumber'];\n    model: StepResult<TOOLS>['model'];\n    functionId: StepResult<TOOLS>['functionId'];\n    metadata: StepResult<TOOLS>['metadata'];\n    experimental_context: StepResult<TOOLS>['experimental_context'];\n    content: StepResult<TOOLS>['content'];\n    finishReason: StepResult<TOOLS>['finishReason'];\n    rawFinishReason: StepResult<TOOLS>['rawFinishReason'];\n    usage: StepResult<TOOLS>['usage'];\n    warnings: StepResult<TOOLS>['warnings'];\n    request: StepResult<TOOLS>['request'];\n    response: StepResult<TOOLS>['response'];\n    providerMetadata: StepResult<TOOLS>['providerMetadata'];\n  }) {\n    this.stepNumber = stepNumber;\n    this.model = model;\n    this.functionId = functionId;\n    this.metadata = metadata;\n    this.experimental_context = experimental_context;\n    this.content = content;\n    this.finishReason = finishReason;\n    this.rawFinishReason = rawFinishReason;\n    this.usage = usage;\n    this.warnings = warnings;\n    this.request = request;\n    this.response = response;\n    this.providerMetadata = providerMetadata;\n  }\n\n  get text() {\n    return this.content\n      .filter(part => part.type === 'text')\n      .map(part => part.text)\n      .join('');\n  }\n\n  get reasoning() {\n    return this.content.filter(part => part.type === 'reasoning');\n  }\n\n  get reasoningText() {\n    return this.reasoning.length === 0\n      ? undefined\n      : this.reasoning.map(part => part.text).join('');\n  }\n\n  get files() {\n    return this.content\n      .filter(part => part.type === 'file')\n      .map(part => part.file);\n  }\n\n  get sources() {\n    return this.content.filter(part => part.type === 'source');\n  }\n\n  get toolCalls() {\n    return this.content.filter(part => part.type === 'tool-call');\n  }\n\n  get staticToolCalls() {\n    return this.toolCalls.filter(\n      (toolCall): toolCall is StaticToolCall<TOOLS> =>\n        toolCall.dynamic !== true,\n    );\n  }\n\n  get dynamicToolCalls() {\n    return this.toolCalls.filter(\n      (toolCall): toolCall is DynamicToolCall => toolCall.dynamic === true,\n    );\n  }\n\n  get toolResults() {\n    return this.content.filter(part => part.type === 'tool-result');\n  }\n\n  get staticToolResults() {\n    return this.toolResults.filter(\n      (toolResult): toolResult is StaticToolResult<TOOLS> =>\n        toolResult.dynamic !== true,\n    );\n  }\n\n  get dynamicToolResults() {\n    return this.toolResults.filter(\n      (toolResult): toolResult is DynamicToolResult =>\n        toolResult.dynamic === true,\n    );\n  }\n}\n", "import type { StepResult } from './step-result';\nimport type { ToolSet } from './tool-set';\n\nexport type StopCondition<TOOLS extends ToolSet> = (options: {\n  steps: Array<StepResult<TOOLS>>;\n}) => PromiseLike<boolean> | boolean;\n\nexport function stepCountIs(stepCount: number): StopCondition<any> {\n  return ({ steps }) => steps.length === stepCount;\n}\n\nexport function isLoopFinished(): StopCondition<any> {\n  return () => false;\n}\n\nexport function hasToolCall(toolName: string): StopCondition<any> {\n  return ({ steps }) =>\n    steps[steps.length - 1]?.toolCalls?.some(\n      toolCall => toolCall.toolName === toolName,\n    ) ?? false;\n}\n\nexport async function isStopConditionMet<TOOLS extends ToolSet>({\n  stopConditions,\n  steps,\n}: {\n  stopConditions: Array<StopCondition<TOOLS>>;\n  steps: Array<StepResult<TOOLS>>;\n}): Promise<boolean> {\n  return (\n    await Promise.all(stopConditions.map(condition => condition({ steps })))\n  ).some(result => result);\n}\n", "import type {\n  AssistantContent,\n  AssistantModelMessage,\n  ToolContent,\n  ToolModelMessage,\n} from '../prompt';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport type { ContentPart } from './content-part';\nimport type { ToolSet } from './tool-set';\n\n/**\n * Converts the result of a `generateText` or `streamText` call to a list of response messages.\n */\nexport async function toResponseMessages<TOOLS extends ToolSet>({\n  content: inputContent,\n  tools,\n}: {\n  content: Array<ContentPart<TOOLS>>;\n  tools: TOOLS | undefined;\n}): Promise<Array<AssistantModelMessage | ToolModelMessage>> {\n  const responseMessages: Array<AssistantModelMessage | ToolModelMessage> = [];\n\n  const content: AssistantContent = [];\n  for (const part of inputContent) {\n    // Skip sources - they are response-only content that no provider expects back\n    if (part.type === 'source') {\n      continue;\n    }\n\n    // Skip non-provider-executed tool results/errors (they go in the tool message)\n    if (\n      (part.type === 'tool-result' || part.type === 'tool-error') &&\n      !part.providerExecuted\n    ) {\n      continue;\n    }\n\n    // Skip empty text\n    if (part.type === 'text' && part.text.length === 0) {\n      continue;\n    }\n\n    switch (part.type) {\n      case 'text':\n        content.push({\n          type: 'text',\n          text: part.text,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'reasoning':\n        content.push({\n          type: 'reasoning',\n          text: part.text,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'file':\n        content.push({\n          type: 'file',\n          data: part.file.base64,\n          mediaType: part.file.mediaType,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'tool-call':\n        content.push({\n          type: 'tool-call',\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          input:\n            part.invalid && typeof part.input !== 'object' ? {} : part.input,\n          providerExecuted: part.providerExecuted,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'tool-result': {\n        const output = await createToolModelOutput({\n          toolCallId: part.toolCallId,\n          input: part.input,\n          tool: tools?.[part.toolName],\n          output: part.output,\n          errorMode: 'none',\n        });\n        content.push({\n          type: 'tool-result',\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          output,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      }\n      case 'tool-error': {\n        const output = await createToolModelOutput({\n          toolCallId: part.toolCallId,\n          input: part.input,\n          tool: tools?.[part.toolName],\n          output: part.error,\n          errorMode: 'json',\n        });\n        content.push({\n          type: 'tool-result',\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          output,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      }\n      case 'tool-approval-request':\n        content.push({\n          type: 'tool-approval-request',\n          approvalId: part.approvalId,\n          toolCallId: part.toolCall.toolCallId,\n        });\n        break;\n    }\n  }\n\n  if (content.length > 0) {\n    responseMessages.push({\n      role: 'assistant',\n      content,\n    });\n  }\n\n  const toolResultContent: ToolContent = [];\n  for (const part of inputContent) {\n    if (\n      !(part.type === 'tool-result' || part.type === 'tool-error') ||\n      part.providerExecuted\n    ) {\n      continue;\n    }\n\n    const output = await createToolModelOutput({\n      toolCallId: part.toolCallId,\n      input: part.input,\n      tool: tools?.[part.toolName],\n      output: part.type === 'tool-result' ? part.output : part.error,\n      errorMode: part.type === 'tool-error' ? 'text' : 'none',\n    });\n\n    toolResultContent.push({\n      type: 'tool-result',\n      toolCallId: part.toolCallId,\n      toolName: part.toolName,\n      output,\n      ...(part.providerMetadata != null\n        ? { providerOptions: part.providerMetadata }\n        : {}),\n    });\n  }\n\n  if (toolResultContent.length > 0) {\n    responseMessages.push({\n      role: 'tool',\n      content: toolResultContent,\n    });\n  }\n\n  return responseMessages;\n}\n", "/**\n * Merges multiple AbortSignals into a single AbortSignal.\n * The returned signal will abort when any of the input signals abort,\n * with the same reason as the first signal to abort.\n *\n * @param signals - The AbortSignals to merge. Null and undefined values are filtered out.\n * @returns An AbortSignal that aborts when any of the input signals abort,\n *          or undefined if no valid signals are provided.\n */\nexport function mergeAbortSignals(\n  ...signals: (AbortSignal | null | undefined)[]\n): AbortSignal | undefined {\n  const validSignals = signals.filter(\n    (signal): signal is AbortSignal => signal != null,\n  );\n\n  if (validSignals.length === 0) {\n    return undefined;\n  }\n\n  if (validSignals.length === 1) {\n    return validSignals[0];\n  }\n\n  const controller = new AbortController();\n\n  for (const signal of validSignals) {\n    if (signal.aborted) {\n      controller.abort(signal.reason);\n      return controller.signal;\n    }\n\n    signal.addEventListener(\n      'abort',\n      () => {\n        controller.abort(signal.reason);\n      },\n      { once: true },\n    );\n  }\n\n  return controller.signal;\n}\n", "import {\n  getErrorMessage,\n  UnsupportedFunctionalityError,\n  type LanguageModelV3,\n  type SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  DelayedPromise,\n  isAbortError,\n  type IdGenerator,\n  type ProviderOptions,\n  type ToolContent,\n} from '@ai-sdk/provider-utils';\nimport type { Span } from '@opentelemetry/api';\nimport type { ServerResponse } from 'node:http';\nimport { NoOutputGeneratedError } from '../error';\nimport { notify } from '../util/notify';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport {\n  getChunkTimeoutMs,\n  getStepTimeoutMs,\n  getTotalTimeoutMs,\n  type CallSettings,\n  type TimeoutConfiguration,\n} from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport { prepareCallSettings } from '../prompt/prepare-call-settings';\nimport { prepareToolsAndToolChoice } from '../prompt/prepare-tools-and-tool-choice';\nimport type { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport { stringifyForTelemetry } from '../telemetry/stringify-for-telemetry';\nimport { getGlobalTelemetryIntegration } from '../telemetry/get-global-telemetry-integration';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport { createTextStreamResponse } from '../text-stream/create-text-stream-response';\nimport { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';\nimport type { LanguageModelRequestMetadata } from '../types';\nimport type {\n  CallWarning,\n  FinishReason,\n  LanguageModel,\n  ToolChoice,\n} from '../types/language-model';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport {\n  addLanguageModelUsage,\n  createNullLanguageModelUsage,\n  type LanguageModelUsage,\n} from '../types/usage';\nimport type { UIMessage } from '../ui';\nimport { createUIMessageStreamResponse } from '../ui-message-stream/create-ui-message-stream-response';\nimport { getResponseUIMessageId } from '../ui-message-stream/get-response-ui-message-id';\nimport { handleUIMessageStreamFinish } from '../ui-message-stream/handle-ui-message-stream-finish';\nimport { pipeUIMessageStreamToResponse } from '../ui-message-stream/pipe-ui-message-stream-to-response';\nimport type {\n  InferUIMessageChunk,\n  UIMessageChunk,\n} from '../ui-message-stream/ui-message-chunks';\nimport type { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';\nimport type {\n  InferUIMessageData,\n  InferUIMessageMetadata,\n} from '../ui/ui-messages';\nimport { asArray } from '../util/as-array';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport { consumeStream } from '../util/consume-stream';\nimport { createStitchableStream } from '../util/create-stitchable-stream';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\nimport { mergeObjects } from '../util/merge-objects';\nimport { now as originalNow } from '../util/now';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { collectToolApprovals } from './collect-tool-approvals';\nimport type {\n  OnFinishEvent,\n  OnStartEvent,\n  OnStepFinishEvent,\n  OnStepStartEvent,\n  OnToolCallFinishEvent,\n  OnToolCallStartEvent,\n} from './callback-events';\nimport type { ContentPart } from './content-part';\nimport { executeToolCall } from './execute-tool-call';\nimport { text, type Output } from './output';\nimport type {\n  InferCompleteOutput,\n  InferElementOutput,\n  InferPartialOutput,\n} from './output-utils';\nimport type { PrepareStepFunction } from './prepare-step';\nimport type { ResponseMessage } from './response-message';\nimport {\n  runToolsTransformation,\n  type SingleRequestTextStreamPart,\n} from './run-tools-transformation';\nimport { DefaultStepResult, type StepResult } from './step-result';\nimport {\n  isStopConditionMet,\n  stepCountIs,\n  type StopCondition,\n} from './stop-condition';\nimport type {\n  ConsumeStreamOptions,\n  StreamTextResult,\n  TextStreamPart,\n  UIMessageStreamOptions,\n} from './stream-text-result';\nimport { toResponseMessages } from './to-response-messages';\nimport type { TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type { ToolOutput } from './tool-output';\nimport type { StaticToolOutputDenied } from './tool-output-denied';\nimport type { ToolSet } from './tool-set';\n\nconst originalGenerateId = createIdGenerator({\n  prefix: 'aitxt',\n  size: 24,\n});\n\n/**\n * A transformation that is applied to the stream.\n *\n * @param stopStream - A function that stops the source stream.\n * @param tools - The tools that are accessible to and can be called by the model. The model needs to support calling tools.\n */\nexport type StreamTextTransform<TOOLS extends ToolSet> = (options: {\n  tools: TOOLS; // for type inference\n  stopStream: () => void;\n}) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>;\n\n/**\n * Callback that is set using the `onError` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamTextOnErrorCallback = (event: {\n  error: unknown;\n}) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `onStepFinish` option.\n *\n * @param stepResult - The result of the step.\n */\nexport type StreamTextOnStepFinishCallback<TOOLS extends ToolSet> = (\n  event: OnStepFinishEvent<TOOLS>,\n) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `onChunk` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamTextOnChunkCallback<TOOLS extends ToolSet> = (event: {\n  chunk: Extract<\n    TextStreamPart<TOOLS>,\n    {\n      type:\n        | 'text-delta'\n        | 'reasoning-delta'\n        | 'source'\n        | 'tool-call'\n        | 'tool-input-start'\n        | 'tool-input-delta'\n        | 'tool-result'\n        | 'raw';\n    }\n  >;\n}) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `onFinish` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamTextOnFinishCallback<TOOLS extends ToolSet> = (\n  event: OnFinishEvent<TOOLS>,\n) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `onAbort` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamTextOnAbortCallback<TOOLS extends ToolSet> = (event: {\n  /**\n   * Details for all previously finished steps.\n   */\n  readonly steps: StepResult<TOOLS>[];\n}) => PromiseLike<void> | void;\n\n/**\n * Include settings for streamText (requestBody only).\n */\ntype StreamTextIncludeSettings = { requestBody?: boolean };\n\n/**\n * Callback that is set using the `experimental_onStart` option.\n *\n * Called when the streamText operation begins, before any LLM calls.\n * Use this callback for logging, analytics, or initializing state at the\n * start of a generation.\n *\n * @param event - The event object containing generation configuration.\n */\nexport type StreamTextOnStartCallback<\n  TOOLS extends ToolSet = ToolSet,\n  OUTPUT extends Output = Output,\n> = (\n  event: OnStartEvent<TOOLS, OUTPUT, StreamTextIncludeSettings>,\n) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `experimental_onStepStart` option.\n *\n * Called when a step (LLM call) begins, before the provider is called.\n * Each step represents a single LLM invocation. Multiple steps occur when\n * using tool calls (the model may be called multiple times in a loop).\n *\n * @param event - The event object containing step configuration.\n */\nexport type StreamTextOnStepStartCallback<\n  TOOLS extends ToolSet = ToolSet,\n  OUTPUT extends Output = Output,\n> = (\n  event: OnStepStartEvent<TOOLS, OUTPUT, StreamTextIncludeSettings>,\n) => PromiseLike<void> | void;\n\nexport type StreamTextOnToolCallStartCallback<TOOLS extends ToolSet = ToolSet> =\n  (event: OnToolCallStartEvent<TOOLS>) => PromiseLike<void> | void;\n\nexport type StreamTextOnToolCallFinishCallback<\n  TOOLS extends ToolSet = ToolSet,\n> = (event: OnToolCallFinishEvent<TOOLS>) => PromiseLike<void> | void;\n\n/**\n * Generate a text and call tools for a given prompt using a language model.\n *\n * This function streams the output. If you do not want to stream the output, use `generateText` instead.\n *\n * @param model - The language model to use.\n * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. When unset, system messages are allowed with a warning.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.\n * @param onError - Callback that is called when an error occurs during streaming. You can use it to log errors.\n * @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.\n * @param onFinish - Callback that is called when all steps are finished and the response is complete.\n *\n * @returns\n * A result object for accessing different stream types and additional information.\n */\nexport function streamText<\n  TOOLS extends ToolSet,\n  OUTPUT extends Output = Output<string, string, never>,\n>({\n  model,\n  tools,\n  toolChoice,\n  system,\n  prompt,\n  messages,\n  allowSystemInMessages,\n  maxRetries,\n  abortSignal,\n  timeout,\n  headers,\n  stopWhen = stepCountIs(1),\n  experimental_output,\n  output = experimental_output,\n  experimental_telemetry: telemetry,\n  prepareStep,\n  providerOptions,\n  experimental_activeTools,\n  activeTools = experimental_activeTools,\n  experimental_repairToolCall: repairToolCall,\n  experimental_transform: transform,\n  experimental_download: download,\n  includeRawChunks = false,\n  onChunk,\n  onError = ({ error }) => {\n    console.error(error);\n  },\n  onFinish,\n  onAbort,\n  onStepFinish,\n  experimental_onStart: onStart,\n  experimental_onStepStart: onStepStart,\n  experimental_onToolCallStart: onToolCallStart,\n  experimental_onToolCallFinish: onToolCallFinish,\n  experimental_context,\n  experimental_include: include,\n  _internal: { now = originalNow, generateId = originalGenerateId } = {},\n  ...settings\n}: CallSettings &\n  Prompt & {\n    /**\n     * The language model to use.\n     */\n    model: LanguageModel;\n\n    /**\n     * The tools that the model can call. The model needs to support calling tools.\n     */\n    tools?: TOOLS;\n\n    /**\n     * The tool choice strategy. Default: 'auto'.\n     */\n    toolChoice?: ToolChoice<TOOLS>;\n\n    /**\n     * Condition for stopping the generation when there are tool results in the last step.\n     * When the condition is an array, any of the conditions can be met to stop the generation.\n     *\n     * @default stepCountIs(1)\n     */\n    stopWhen?:\n      | StopCondition<NoInfer<TOOLS>>\n      | Array<StopCondition<NoInfer<TOOLS>>>;\n\n    /**\n     * Optional telemetry configuration (experimental).\n     */\n    experimental_telemetry?: TelemetrySettings;\n\n    /**\n     * Additional provider-specific options. They are passed through\n     * to the provider from the AI SDK and enable provider-specific\n     * functionality that can be fully encapsulated in the provider.\n     */\n    providerOptions?: ProviderOptions;\n\n    /**\n     * @deprecated Use `activeTools` instead.\n     */\n    experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;\n\n    /**\n     * Limits the tools that are available for the model to call without\n     * changing the tool call and result types in the result.\n     */\n    activeTools?: Array<keyof NoInfer<TOOLS>>;\n\n    /**\n     * Optional specification for parsing structured outputs from the LLM response.\n     */\n    output?: OUTPUT;\n\n    /**\n     * Optional specification for parsing structured outputs from the LLM response.\n     *\n     * @deprecated Use `output` instead.\n     */\n    experimental_output?: OUTPUT;\n\n    /**\n     * Optional function that you can use to provide different settings for a step.\n     *\n     * @param options - The options for the step.\n     * @param options.steps - The steps that have been executed so far.\n     * @param options.stepNumber - The number of the step that is being executed.\n     * @param options.model - The model that is being used.\n     *\n     * @returns An object that contains the settings for the step.\n     * If you return undefined (or for undefined settings), the settings from the outer level will be used.\n     */\n    prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;\n\n    /**\n     * A function that attempts to repair a tool call that failed to parse.\n     */\n    experimental_repairToolCall?: ToolCallRepairFunction<TOOLS>;\n\n    /**\n     * Optional stream transformations.\n     * They are applied in the order they are provided.\n     * The stream transformations must maintain the stream structure for streamText to work correctly.\n     */\n    experimental_transform?:\n      | StreamTextTransform<TOOLS>\n      | Array<StreamTextTransform<TOOLS>>;\n\n    /**\n     * Custom download function to use for URLs.\n     *\n     * By default, files are downloaded if the model does not support the URL for the given media type.\n     */\n    experimental_download?: DownloadFunction | undefined;\n\n    /**\n     * Whether to include raw chunks from the provider in the stream.\n     * When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider.\n     * This allows access to cutting-edge provider features not yet wrapped by the AI SDK.\n     * Defaults to false.\n     */\n    includeRawChunks?: boolean;\n\n    /**\n     * Callback that is called for each chunk of the stream.\n     * The stream processing will pause until the callback promise is resolved.\n     */\n    onChunk?: StreamTextOnChunkCallback<TOOLS>;\n\n    /**\n     * Callback that is invoked when an error occurs during streaming.\n     * You can use it to log errors.\n     * The stream processing will pause until the callback promise is resolved.\n     */\n    onError?: StreamTextOnErrorCallback;\n\n    /**\n     * Callback that is called when the LLM response and all request tool executions\n     * (for tools that have an `execute` function) are finished.\n     *\n     * The usage is the combined usage of all steps.\n     */\n    onFinish?: StreamTextOnFinishCallback<TOOLS>;\n\n    onAbort?: StreamTextOnAbortCallback<TOOLS>;\n\n    /**\n     * Callback that is called when each step (LLM call) is finished, including intermediate steps.\n     */\n    onStepFinish?: StreamTextOnStepFinishCallback<TOOLS>;\n\n    /**\n     * Callback that is called when the streamText operation begins,\n     * before any LLM calls are made.\n     */\n    experimental_onStart?: StreamTextOnStartCallback<NoInfer<TOOLS>, OUTPUT>;\n\n    /**\n     * Callback that is called when a step (LLM call) begins,\n     * before the provider is called.\n     */\n    experimental_onStepStart?: StreamTextOnStepStartCallback<\n      NoInfer<TOOLS>,\n      OUTPUT\n    >;\n\n    /**\n     * Callback that is called right before a tool's execute function runs.\n     */\n    experimental_onToolCallStart?: StreamTextOnToolCallStartCallback<\n      NoInfer<TOOLS>\n    >;\n\n    /**\n     * Callback that is called right after a tool's execute function completes (or errors).\n     */\n    experimental_onToolCallFinish?: StreamTextOnToolCallFinishCallback<\n      NoInfer<TOOLS>\n    >;\n\n    /**\n     * Context that is passed into tool execution.\n     *\n     * Experimental (can break in patch releases).\n     *\n     * @default undefined\n     */\n    experimental_context?: unknown;\n\n    /**\n     * Settings for controlling what data is included in step results.\n     * Disabling inclusion can help reduce memory usage when processing\n     * large payloads like images.\n     *\n     * By default, all data is included for backwards compatibility.\n     */\n    experimental_include?: {\n      /**\n       * Whether to retain the request body in step results.\n       * The request body can be large when sending images or files.\n       * @default true\n       */\n      requestBody?: boolean;\n    };\n\n    /**\n     * Internal. For test use only. May change without notice.\n     */\n    _internal?: {\n      now?: () => number;\n      generateId?: IdGenerator;\n    };\n  }): StreamTextResult<TOOLS, OUTPUT> {\n  const totalTimeoutMs = getTotalTimeoutMs(timeout);\n  const stepTimeoutMs = getStepTimeoutMs(timeout);\n  const chunkTimeoutMs = getChunkTimeoutMs(timeout);\n  const stepAbortController =\n    stepTimeoutMs != null ? new AbortController() : undefined;\n  const chunkAbortController =\n    chunkTimeoutMs != null ? new AbortController() : undefined;\n  return new DefaultStreamTextResult<TOOLS, OUTPUT>({\n    model: resolveLanguageModel(model),\n    telemetry,\n    headers,\n    settings,\n    maxRetries,\n    abortSignal: mergeAbortSignals(\n      abortSignal,\n      totalTimeoutMs != null ? AbortSignal.timeout(totalTimeoutMs) : undefined,\n      stepAbortController?.signal,\n      chunkAbortController?.signal,\n    ),\n    stepTimeoutMs,\n    stepAbortController,\n    chunkTimeoutMs,\n    chunkAbortController,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    tools,\n    toolChoice,\n    transforms: asArray(transform),\n    activeTools,\n    repairToolCall,\n    stopConditions: asArray(stopWhen),\n    output,\n    providerOptions,\n    prepareStep,\n    includeRawChunks,\n    timeout,\n    stopWhen,\n    originalAbortSignal: abortSignal,\n    onChunk,\n    onError,\n    onFinish,\n    onAbort,\n    onStepFinish,\n    onStart,\n    onStepStart,\n    onToolCallStart,\n    onToolCallFinish,\n    now,\n    generateId,\n    experimental_context,\n    download,\n    include,\n  });\n}\n\nexport type EnrichedStreamPart<TOOLS extends ToolSet, PARTIAL_OUTPUT> = {\n  part: TextStreamPart<TOOLS>;\n  partialOutput: PARTIAL_OUTPUT | undefined;\n};\n\nfunction createOutputTransformStream<\n  TOOLS extends ToolSet,\n  OUTPUT extends Output,\n>(\n  output: OUTPUT,\n): TransformStream<\n  TextStreamPart<TOOLS>,\n  EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n> {\n  let firstTextChunkId: string | undefined = undefined;\n  let text = '';\n  let textChunk = '';\n  let textProviderMetadata: ProviderMetadata | undefined = undefined;\n  let lastPublishedValue = '';\n\n  function publishTextChunk({\n    controller,\n    partialOutput = undefined,\n  }: {\n    controller: TransformStreamDefaultController<\n      EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n    >;\n    partialOutput?: InferPartialOutput<OUTPUT>;\n  }) {\n    controller.enqueue({\n      part: {\n        type: 'text-delta',\n        id: firstTextChunkId!,\n        text: textChunk,\n        providerMetadata: textProviderMetadata,\n      },\n      partialOutput,\n    });\n    textChunk = '';\n  }\n\n  return new TransformStream<\n    TextStreamPart<TOOLS>,\n    EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n  >({\n    async transform(chunk, controller) {\n      // ensure that we publish the last text chunk before the step finish:\n      if (chunk.type === 'finish-step' && textChunk.length > 0) {\n        publishTextChunk({ controller });\n      }\n\n      if (\n        chunk.type !== 'text-delta' &&\n        chunk.type !== 'text-start' &&\n        chunk.type !== 'text-end'\n      ) {\n        controller.enqueue({ part: chunk, partialOutput: undefined });\n        return;\n      }\n\n      // we have to pick a text chunk which contains the json text\n      // since we are streaming, we have to pick the first text chunk\n      if (firstTextChunkId == null) {\n        firstTextChunkId = chunk.id;\n      } else if (chunk.id !== firstTextChunkId) {\n        controller.enqueue({ part: chunk, partialOutput: undefined });\n        return;\n      }\n\n      if (chunk.type === 'text-start') {\n        controller.enqueue({ part: chunk, partialOutput: undefined });\n        return;\n      }\n\n      if (chunk.type === 'text-end') {\n        if (textChunk.length > 0) {\n          publishTextChunk({ controller });\n        }\n        controller.enqueue({ part: chunk, partialOutput: undefined });\n        return;\n      }\n\n      text += chunk.text;\n      textChunk += chunk.text;\n      textProviderMetadata = chunk.providerMetadata ?? textProviderMetadata;\n\n      // only publish if partial json can be parsed:\n      const result = await output.parsePartialOutput({ text });\n\n      // null should be allowed (valid JSON value) but undefined should not:\n      if (result !== undefined) {\n        // only send new value if it has changed:\n        // For string partials (text output), compare directly to avoid unnecessary JSON.stringify overhead\n        const currentValue =\n          typeof result.partial === 'string'\n            ? result.partial\n            : JSON.stringify(result.partial);\n        if (currentValue !== lastPublishedValue) {\n          publishTextChunk({ controller, partialOutput: result.partial });\n          lastPublishedValue = currentValue;\n        }\n      }\n    },\n  });\n}\n\nclass DefaultStreamTextResult<\n  TOOLS extends ToolSet,\n  OUTPUT extends Output,\n> implements StreamTextResult<TOOLS, OUTPUT> {\n  private readonly _totalUsage = new DelayedPromise<\n    Awaited<StreamTextResult<TOOLS, OUTPUT>['usage']>\n  >();\n  private readonly _finishReason = new DelayedPromise<\n    Awaited<StreamTextResult<TOOLS, OUTPUT>['finishReason']>\n  >();\n  private readonly _rawFinishReason = new DelayedPromise<\n    Awaited<StreamTextResult<TOOLS, OUTPUT>['rawFinishReason']>\n  >();\n  private readonly _steps = new DelayedPromise<\n    Awaited<StreamTextResult<TOOLS, OUTPUT>['steps']>\n  >();\n\n  private readonly addStream: (\n    stream: ReadableStream<TextStreamPart<TOOLS>>,\n  ) => void;\n\n  private readonly closeStream: () => void;\n\n  private baseStream: ReadableStream<\n    EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n  >;\n\n  private outputSpecification: OUTPUT | undefined;\n\n  private includeRawChunks: boolean;\n\n  private tools: TOOLS | undefined;\n\n  constructor({\n    model,\n    telemetry,\n    headers,\n    settings,\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    stepTimeoutMs,\n    stepAbortController,\n    chunkTimeoutMs,\n    chunkAbortController,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    tools,\n    toolChoice,\n    transforms,\n    activeTools,\n    repairToolCall,\n    stopConditions,\n    output,\n    providerOptions,\n    prepareStep,\n    includeRawChunks,\n    now,\n    generateId,\n    timeout,\n    stopWhen,\n    originalAbortSignal,\n    onChunk,\n    onError,\n    onFinish,\n    onAbort,\n    onStepFinish,\n    onStart,\n    onStepStart,\n    onToolCallStart,\n    onToolCallFinish,\n    experimental_context,\n    download,\n    include,\n  }: {\n    model: LanguageModelV3;\n    telemetry: TelemetrySettings | undefined;\n    headers: Record<string, string | undefined> | undefined;\n    settings: Omit<CallSettings, 'abortSignal' | 'headers'>;\n    maxRetries: number | undefined;\n    abortSignal: AbortSignal | undefined;\n    stepTimeoutMs: number | undefined;\n    stepAbortController: AbortController | undefined;\n    chunkTimeoutMs: number | undefined;\n    chunkAbortController: AbortController | undefined;\n    system: Prompt['system'];\n    prompt: Prompt['prompt'];\n    messages: Prompt['messages'];\n    allowSystemInMessages: Prompt['allowSystemInMessages'];\n    tools: TOOLS | undefined;\n    toolChoice: ToolChoice<TOOLS> | undefined;\n    transforms: Array<StreamTextTransform<TOOLS>>;\n    activeTools: Array<keyof TOOLS> | undefined;\n    repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n    stopConditions: Array<StopCondition<NoInfer<TOOLS>>>;\n    output: OUTPUT | undefined;\n    providerOptions: ProviderOptions | undefined;\n    prepareStep: PrepareStepFunction<NoInfer<TOOLS>> | undefined;\n    includeRawChunks: boolean;\n    now: () => number;\n    generateId: () => string;\n    timeout: TimeoutConfiguration | undefined;\n    stopWhen:\n      | StopCondition<NoInfer<TOOLS>>\n      | Array<StopCondition<NoInfer<TOOLS>>>\n      | undefined;\n    originalAbortSignal: AbortSignal | undefined;\n    experimental_context: unknown;\n    download: DownloadFunction | undefined;\n    include: { requestBody?: boolean } | undefined;\n\n    // callbacks:\n    onChunk: undefined | StreamTextOnChunkCallback<TOOLS>;\n    onError: StreamTextOnErrorCallback;\n    onFinish: undefined | StreamTextOnFinishCallback<TOOLS>;\n    onAbort: undefined | StreamTextOnAbortCallback<TOOLS>;\n    onStepFinish: undefined | StreamTextOnStepFinishCallback<TOOLS>;\n    onStart: undefined | StreamTextOnStartCallback<TOOLS, OUTPUT>;\n    onStepStart: undefined | StreamTextOnStepStartCallback<TOOLS, OUTPUT>;\n    onToolCallStart: undefined | StreamTextOnToolCallStartCallback<TOOLS>;\n    onToolCallFinish: undefined | StreamTextOnToolCallFinishCallback<TOOLS>;\n  }) {\n    this.outputSpecification = output;\n    this.includeRawChunks = includeRawChunks;\n    this.tools = tools;\n\n    const createGlobalTelemetry = getGlobalTelemetryIntegration<\n      TOOLS,\n      OUTPUT\n    >();\n    const globalTelemetry = createGlobalTelemetry(telemetry?.integrations);\n\n    // promise to ensure that the step has been fully processed by the event processor\n    // before a new step is started. This is required because the continuation condition\n    // needs the updated steps to determine if another step is needed.\n    let stepFinish!: DelayedPromise<void>;\n\n    let recordedContent: Array<ContentPart<TOOLS>> = [];\n    const recordedResponseMessages: Array<ResponseMessage> = [];\n    let recordedFinishReason: FinishReason | undefined = undefined;\n    let recordedRawFinishReason: string | undefined = undefined;\n    let recordedTotalUsage: LanguageModelUsage | undefined = undefined;\n    let recordedRequest: LanguageModelRequestMetadata = {};\n    let recordedWarnings: Array<CallWarning> = [];\n    const recordedSteps: StepResult<TOOLS>[] = [];\n\n    // Track provider-executed tool calls that support deferred results\n    // (e.g., code_execution in programmatic tool calling scenarios).\n    // These tools may not return their results in the same turn as their call.\n    const pendingDeferredToolCalls = new Map<string, { toolName: string }>();\n\n    let rootSpan!: Span;\n\n    let activeTextContent: Record<\n      string,\n      {\n        type: 'text';\n        text: string;\n        providerMetadata: ProviderMetadata | undefined;\n      }\n    > = {};\n\n    let activeReasoningContent: Record<\n      string,\n      {\n        type: 'reasoning';\n        text: string;\n        providerMetadata: ProviderMetadata | undefined;\n      }\n    > = {};\n\n    const eventProcessor = new TransformStream<\n      EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,\n      EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n    >({\n      async transform(chunk, controller) {\n        controller.enqueue(chunk); // forward the chunk to the next stream\n\n        const { part } = chunk;\n\n        if (\n          part.type === 'text-delta' ||\n          part.type === 'reasoning-delta' ||\n          part.type === 'source' ||\n          part.type === 'tool-call' ||\n          part.type === 'tool-result' ||\n          part.type === 'tool-input-start' ||\n          part.type === 'tool-input-delta' ||\n          part.type === 'raw'\n        ) {\n          await onChunk?.({ chunk: part });\n        }\n\n        if (part.type === 'error') {\n          await onError({ error: wrapGatewayError(part.error) });\n        }\n\n        if (part.type === 'text-start') {\n          activeTextContent[part.id] = {\n            type: 'text',\n            text: '',\n            providerMetadata: part.providerMetadata,\n          };\n\n          recordedContent.push(activeTextContent[part.id]);\n        }\n\n        if (part.type === 'text-delta') {\n          const activeText = activeTextContent[part.id];\n\n          if (activeText == null) {\n            controller.enqueue({\n              part: {\n                type: 'error',\n                error: `text part ${part.id} not found`,\n              },\n              partialOutput: undefined,\n            });\n            return;\n          }\n\n          activeText.text += part.text;\n          activeText.providerMetadata =\n            part.providerMetadata ?? activeText.providerMetadata;\n        }\n\n        if (part.type === 'text-end') {\n          const activeText = activeTextContent[part.id];\n\n          if (activeText == null) {\n            controller.enqueue({\n              part: {\n                type: 'error',\n                error: `text part ${part.id} not found`,\n              },\n              partialOutput: undefined,\n            });\n            return;\n          }\n\n          activeText.providerMetadata =\n            part.providerMetadata ?? activeText.providerMetadata;\n\n          delete activeTextContent[part.id];\n        }\n\n        if (part.type === 'reasoning-start') {\n          activeReasoningContent[part.id] = {\n            type: 'reasoning',\n            text: '',\n            providerMetadata: part.providerMetadata,\n          };\n\n          recordedContent.push(activeReasoningContent[part.id]);\n        }\n\n        if (part.type === 'reasoning-delta') {\n          const activeReasoning = activeReasoningContent[part.id];\n\n          if (activeReasoning == null) {\n            controller.enqueue({\n              part: {\n                type: 'error',\n                error: `reasoning part ${part.id} not found`,\n              },\n              partialOutput: undefined,\n            });\n            return;\n          }\n\n          activeReasoning.text += part.text;\n          activeReasoning.providerMetadata =\n            part.providerMetadata ?? activeReasoning.providerMetadata;\n        }\n\n        if (part.type === 'reasoning-end') {\n          const activeReasoning = activeReasoningContent[part.id];\n\n          if (activeReasoning == null) {\n            controller.enqueue({\n              part: {\n                type: 'error',\n                error: `reasoning part ${part.id} not found`,\n              },\n              partialOutput: undefined,\n            });\n            return;\n          }\n\n          activeReasoning.providerMetadata =\n            part.providerMetadata ?? activeReasoning.providerMetadata;\n\n          delete activeReasoningContent[part.id];\n        }\n\n        if (part.type === 'file') {\n          recordedContent.push({\n            type: 'file',\n            file: part.file,\n            ...(part.providerMetadata != null\n              ? { providerMetadata: part.providerMetadata }\n              : {}),\n          });\n        }\n\n        if (part.type === 'source') {\n          recordedContent.push(part);\n        }\n\n        if (part.type === 'tool-call') {\n          recordedContent.push(part);\n        }\n\n        if (part.type === 'tool-result' && !part.preliminary) {\n          recordedContent.push(part);\n        }\n\n        if (part.type === 'tool-approval-request') {\n          recordedContent.push(part);\n        }\n\n        if (part.type === 'tool-error') {\n          recordedContent.push(part);\n        }\n\n        if (part.type === 'start-step') {\n          // reset the recorded data when a new step starts:\n          recordedContent = [];\n          activeReasoningContent = {};\n          activeTextContent = {};\n\n          recordedRequest = part.request;\n          recordedWarnings = part.warnings;\n        }\n\n        if (part.type === 'finish-step') {\n          const stepMessages = await toResponseMessages({\n            content: recordedContent,\n            tools,\n          });\n\n          // Add step information (after response messages are updated):\n          const currentStepResult: StepResult<TOOLS> = new DefaultStepResult({\n            stepNumber: recordedSteps.length,\n            model: modelInfo,\n            ...callbackTelemetryProps,\n            experimental_context,\n            content: recordedContent,\n            finishReason: part.finishReason,\n            rawFinishReason: part.rawFinishReason,\n            usage: part.usage,\n            warnings: recordedWarnings,\n            request: recordedRequest,\n            response: {\n              ...part.response,\n              messages: [...recordedResponseMessages, ...stepMessages],\n            },\n            providerMetadata: part.providerMetadata,\n          });\n\n          await notify({\n            event: currentStepResult,\n            callbacks: [onStepFinish, globalTelemetry.onStepFinish],\n          });\n\n          logWarnings({\n            warnings: recordedWarnings,\n            provider: modelInfo.provider,\n            model: modelInfo.modelId,\n          });\n\n          recordedSteps.push(currentStepResult);\n\n          recordedResponseMessages.push(...stepMessages);\n\n          // resolve the promise to signal that the step has been fully processed\n          // by the event processor:\n          stepFinish.resolve();\n        }\n\n        if (part.type === 'finish') {\n          recordedTotalUsage = part.totalUsage;\n          recordedFinishReason = part.finishReason;\n          recordedRawFinishReason = part.rawFinishReason;\n        }\n      },\n\n      async flush(controller) {\n        try {\n          if (recordedSteps.length === 0) {\n            const error = abortSignal?.aborted\n              ? abortSignal.reason\n              : new NoOutputGeneratedError({\n                  message: 'No output generated. Check the stream for errors.',\n                });\n\n            self._finishReason.reject(error);\n            self._rawFinishReason.reject(error);\n            self._totalUsage.reject(error);\n            self._steps.reject(error);\n\n            return; // no steps recorded (e.g. in error scenario)\n          }\n\n          // derived:\n          const finishReason = recordedFinishReason ?? 'other';\n          const totalUsage =\n            recordedTotalUsage ?? createNullLanguageModelUsage();\n\n          // from finish:\n          self._finishReason.resolve(finishReason);\n          self._rawFinishReason.resolve(recordedRawFinishReason);\n          self._totalUsage.resolve(totalUsage);\n\n          // aggregate results:\n          self._steps.resolve(recordedSteps);\n\n          // call onFinish callback:\n          const finalStep = recordedSteps[recordedSteps.length - 1];\n\n          await notify({\n            event: {\n              stepNumber: finalStep.stepNumber,\n              model: finalStep.model,\n              functionId: finalStep.functionId,\n              metadata: finalStep.metadata,\n              experimental_context: finalStep.experimental_context,\n              finishReason: finalStep.finishReason,\n              rawFinishReason: finalStep.rawFinishReason,\n              totalUsage,\n              usage: finalStep.usage,\n              content: finalStep.content,\n              text: finalStep.text,\n              reasoningText: finalStep.reasoningText,\n              reasoning: finalStep.reasoning,\n              files: finalStep.files,\n              sources: finalStep.sources,\n              toolCalls: finalStep.toolCalls,\n              staticToolCalls: finalStep.staticToolCalls,\n              dynamicToolCalls: finalStep.dynamicToolCalls,\n              toolResults: finalStep.toolResults,\n              staticToolResults: finalStep.staticToolResults,\n              dynamicToolResults: finalStep.dynamicToolResults,\n              request: finalStep.request,\n              response: finalStep.response,\n              warnings: finalStep.warnings,\n              providerMetadata: finalStep.providerMetadata,\n              steps: recordedSteps,\n            },\n            callbacks: [\n              onFinish,\n              globalTelemetry.onFinish as\n                | undefined\n                | StreamTextOnFinishCallback<TOOLS>,\n            ],\n          });\n\n          // Add response information to the root span:\n          rootSpan.setAttributes(\n            await selectTelemetryAttributes({\n              telemetry,\n              attributes: {\n                'ai.response.finishReason': finishReason,\n                'ai.response.text': { output: () => finalStep.text },\n                'ai.response.reasoning': {\n                  output: () => finalStep.reasoningText,\n                },\n                'ai.response.toolCalls': {\n                  output: () =>\n                    finalStep.toolCalls?.length\n                      ? JSON.stringify(finalStep.toolCalls)\n                      : undefined,\n                },\n                'ai.response.providerMetadata': JSON.stringify(\n                  finalStep.providerMetadata,\n                ),\n                'ai.usage.inputTokens': totalUsage.inputTokens,\n                'ai.usage.inputTokenDetails.noCacheTokens':\n                  totalUsage.inputTokenDetails?.noCacheTokens,\n                'ai.usage.inputTokenDetails.cacheReadTokens':\n                  totalUsage.inputTokenDetails?.cacheReadTokens,\n                'ai.usage.inputTokenDetails.cacheWriteTokens':\n                  totalUsage.inputTokenDetails?.cacheWriteTokens,\n                'ai.usage.outputTokens': totalUsage.outputTokens,\n                'ai.usage.outputTokenDetails.textTokens':\n                  totalUsage.outputTokenDetails?.textTokens,\n                'ai.usage.outputTokenDetails.reasoningTokens':\n                  totalUsage.outputTokenDetails?.reasoningTokens,\n                'ai.usage.totalTokens': totalUsage.totalTokens,\n                'ai.usage.reasoningTokens':\n                  totalUsage.outputTokenDetails?.reasoningTokens,\n                'ai.usage.cachedInputTokens':\n                  totalUsage.inputTokenDetails?.cacheReadTokens,\n              },\n            }),\n          );\n        } catch (error) {\n          controller.error(error);\n        } finally {\n          rootSpan.end();\n        }\n      },\n    });\n\n    // initialize the stitchable stream and the transformed stream:\n    const stitchableStream = createStitchableStream<TextStreamPart<TOOLS>>();\n    this.addStream = stitchableStream.addStream;\n    this.closeStream = stitchableStream.close;\n\n    // resilient stream that handles abort signals and errors:\n    const reader = stitchableStream.stream.getReader();\n    let stream = new ReadableStream<TextStreamPart<TOOLS>>({\n      async start(controller) {\n        // send start event:\n        controller.enqueue({ type: 'start' });\n      },\n\n      async pull(controller) {\n        // abort handling:\n        function abort() {\n          onAbort?.({ steps: recordedSteps });\n          controller.enqueue({\n            type: 'abort',\n            // The `reason` is usually of type DOMException, but it can also be of any type,\n            // so we use getErrorMessage for serialization because it is already designed to accept values of the unknown type.\n            // See: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason\n            ...(abortSignal?.reason !== undefined\n              ? { reason: getErrorMessage(abortSignal.reason) }\n              : {}),\n          });\n          controller.close();\n        }\n\n        try {\n          const { done, value } = await reader.read();\n\n          if (done) {\n            controller.close();\n            return;\n          }\n\n          if (abortSignal?.aborted) {\n            abort();\n            return;\n          }\n\n          controller.enqueue(value);\n        } catch (error) {\n          if (isAbortError(error) && abortSignal?.aborted) {\n            abort();\n          } else {\n            controller.error(error);\n          }\n        }\n      },\n\n      cancel(reason) {\n        return stitchableStream.stream.cancel(reason);\n      },\n    });\n\n    // transform the stream before output parsing\n    // to enable replacement of stream segments:\n    for (const transform of transforms) {\n      stream = stream.pipeThrough(\n        transform({\n          tools: tools as TOOLS,\n          stopStream() {\n            stitchableStream.terminate();\n          },\n        }),\n      );\n    }\n\n    this.baseStream = stream\n      .pipeThrough(createOutputTransformStream(output ?? text()))\n      .pipeThrough(eventProcessor);\n\n    const { maxRetries, retry } = prepareRetries({\n      maxRetries: maxRetriesArg,\n      abortSignal,\n    });\n\n    const tracer = getTracer(telemetry);\n\n    const callSettings = prepareCallSettings(settings);\n\n    const baseTelemetryAttributes = getBaseTelemetryAttributes({\n      model,\n      telemetry,\n      headers,\n      settings: { ...callSettings, maxRetries },\n    });\n\n    const self = this;\n\n    const modelInfo = { provider: model.provider, modelId: model.modelId };\n    const callbackTelemetryProps = {\n      functionId: telemetry?.functionId,\n      metadata: telemetry?.metadata as Record<string, unknown> | undefined,\n    };\n\n    recordSpan({\n      name: 'ai.streamText',\n      attributes: selectTelemetryAttributes({\n        telemetry,\n        attributes: {\n          ...assembleOperationName({ operationId: 'ai.streamText', telemetry }),\n          ...baseTelemetryAttributes,\n          // specific settings that only make sense on the outer level:\n          'ai.prompt': {\n            input: () => JSON.stringify({ system, prompt, messages }),\n          },\n        },\n      }),\n      tracer,\n      endWhenDone: false,\n      fn: async rootSpanArg => {\n        rootSpan = rootSpanArg;\n\n        const initialPrompt = await standardizePrompt({\n          system,\n          prompt,\n          messages,\n          allowSystemInMessages,\n        } as Prompt);\n\n        await notify({\n          event: {\n            model: modelInfo,\n            system,\n            prompt,\n            messages,\n            tools,\n            toolChoice,\n            activeTools,\n            maxOutputTokens: callSettings.maxOutputTokens,\n            temperature: callSettings.temperature,\n            topP: callSettings.topP,\n            topK: callSettings.topK,\n            presencePenalty: callSettings.presencePenalty,\n            frequencyPenalty: callSettings.frequencyPenalty,\n            stopSequences: callSettings.stopSequences,\n            seed: callSettings.seed,\n            maxRetries,\n            timeout,\n            headers,\n            providerOptions,\n            stopWhen,\n            output,\n            abortSignal: originalAbortSignal,\n            include,\n            ...callbackTelemetryProps,\n            experimental_context,\n          },\n          callbacks: [\n            onStart,\n            globalTelemetry.onStart as\n              | undefined\n              | StreamTextOnStartCallback<TOOLS, OUTPUT>,\n          ],\n        });\n\n        const initialMessages = initialPrompt.messages;\n        const initialResponseMessages: Array<ResponseMessage> = [];\n\n        const { approvedToolApprovals, deniedToolApprovals } =\n          collectToolApprovals<TOOLS>({ messages: initialMessages });\n\n        // initial tool execution step stream\n        if (\n          deniedToolApprovals.length > 0 ||\n          approvedToolApprovals.length > 0\n        ) {\n          const localApprovedToolApprovals = approvedToolApprovals.filter(\n            toolApproval => !toolApproval.toolCall.providerExecuted,\n          );\n          const localDeniedToolApprovals = deniedToolApprovals.filter(\n            toolApproval => !toolApproval.toolCall.providerExecuted,\n          );\n\n          const deniedProviderExecutedToolApprovals =\n            deniedToolApprovals.filter(\n              toolApproval => toolApproval.toolCall.providerExecuted,\n            );\n\n          let toolExecutionStepStreamController:\n            | ReadableStreamDefaultController<TextStreamPart<TOOLS>>\n            | undefined;\n          const toolExecutionStepStream = new ReadableStream<\n            TextStreamPart<TOOLS>\n          >({\n            start(controller) {\n              toolExecutionStepStreamController = controller;\n            },\n          });\n\n          self.addStream(toolExecutionStepStream);\n\n          try {\n            for (const toolApproval of [\n              ...localDeniedToolApprovals,\n              ...deniedProviderExecutedToolApprovals,\n            ]) {\n              toolExecutionStepStreamController?.enqueue({\n                type: 'tool-output-denied',\n                toolCallId: toolApproval.toolCall.toolCallId,\n                toolName: toolApproval.toolCall.toolName,\n              } as StaticToolOutputDenied<TOOLS>);\n            }\n\n            const toolOutputs: Array<ToolOutput<TOOLS>> = [];\n\n            await Promise.all(\n              localApprovedToolApprovals.map(async toolApproval => {\n                const result = await executeToolCall({\n                  toolCall: toolApproval.toolCall,\n                  tools,\n                  tracer,\n                  telemetry,\n                  messages: initialMessages,\n                  abortSignal,\n                  experimental_context,\n                  stepNumber: recordedSteps.length,\n                  model: modelInfo,\n                  onToolCallStart: [\n                    onToolCallStart,\n                    globalTelemetry.onToolCallStart as\n                      | undefined\n                      | StreamTextOnToolCallStartCallback<TOOLS>,\n                  ],\n                  onToolCallFinish: [\n                    onToolCallFinish,\n                    globalTelemetry.onToolCallFinish,\n                  ],\n                  onPreliminaryToolResult: result => {\n                    toolExecutionStepStreamController?.enqueue(result);\n                  },\n                });\n\n                if (result != null) {\n                  toolExecutionStepStreamController?.enqueue(result);\n                  toolOutputs.push(result);\n                }\n              }),\n            );\n\n            // Local tool results (approved + denied) are sent as tool results:\n            if (toolOutputs.length > 0 || localDeniedToolApprovals.length > 0) {\n              const localToolContent: ToolContent = [];\n\n              // add regular tool results for approved tool calls:\n              for (const output of toolOutputs) {\n                localToolContent.push({\n                  type: 'tool-result' as const,\n                  toolCallId: output.toolCallId,\n                  toolName: output.toolName,\n                  output: await createToolModelOutput({\n                    toolCallId: output.toolCallId,\n                    input: output.input,\n                    tool: tools?.[output.toolName],\n                    output:\n                      output.type === 'tool-result'\n                        ? output.output\n                        : output.error,\n                    errorMode: output.type === 'tool-error' ? 'text' : 'none',\n                  }),\n                });\n              }\n\n              // add execution denied tool results for denied local tool approvals:\n              for (const toolApproval of localDeniedToolApprovals) {\n                localToolContent.push({\n                  type: 'tool-result' as const,\n                  toolCallId: toolApproval.toolCall.toolCallId,\n                  toolName: toolApproval.toolCall.toolName,\n                  output: {\n                    type: 'execution-denied' as const,\n                    reason: toolApproval.approvalResponse.reason,\n                  },\n                });\n              }\n\n              initialResponseMessages.push({\n                role: 'tool',\n                content: localToolContent,\n              });\n            }\n          } finally {\n            toolExecutionStepStreamController?.close();\n          }\n        }\n\n        recordedResponseMessages.push(...initialResponseMessages);\n\n        async function streamStep({\n          currentStep,\n          responseMessages,\n          usage,\n        }: {\n          currentStep: number;\n          responseMessages: Array<ResponseMessage>;\n          usage: LanguageModelUsage;\n        }) {\n          const includeRawChunks = self.includeRawChunks;\n\n          // Set up step timeout if configured\n          const stepTimeoutId =\n            stepTimeoutMs != null\n              ? setTimeout(() => stepAbortController!.abort(), stepTimeoutMs)\n              : undefined;\n\n          // Set up chunk timeout tracking (will be reset on each chunk)\n          let chunkTimeoutId: ReturnType<typeof setTimeout> | undefined =\n            undefined;\n\n          function resetChunkTimeout() {\n            if (chunkTimeoutMs != null) {\n              if (chunkTimeoutId != null) {\n                clearTimeout(chunkTimeoutId);\n              }\n              chunkTimeoutId = setTimeout(\n                () => chunkAbortController!.abort(),\n                chunkTimeoutMs,\n              );\n            }\n          }\n\n          function clearChunkTimeout() {\n            if (chunkTimeoutId != null) {\n              clearTimeout(chunkTimeoutId);\n              chunkTimeoutId = undefined;\n            }\n          }\n\n          function clearStepTimeout() {\n            if (stepTimeoutId != null) {\n              clearTimeout(stepTimeoutId);\n            }\n          }\n\n          try {\n            stepFinish = new DelayedPromise<void>();\n\n            const stepInputMessages = [...initialMessages, ...responseMessages];\n\n            const prepareStepResult = await prepareStep?.({\n              model,\n              steps: recordedSteps,\n              stepNumber: recordedSteps.length,\n              messages: stepInputMessages,\n              experimental_context,\n            });\n\n            const stepModel = resolveLanguageModel(\n              prepareStepResult?.model ?? model,\n            );\n            const stepModelInfo = {\n              provider: stepModel.provider,\n              modelId: stepModel.modelId,\n            };\n\n            const promptMessages = await convertToLanguageModelPrompt({\n              prompt: {\n                system: prepareStepResult?.system ?? initialPrompt.system,\n                messages: prepareStepResult?.messages ?? stepInputMessages,\n              },\n              supportedUrls: await stepModel.supportedUrls,\n              download,\n            });\n\n            const stepActiveTools =\n              prepareStepResult?.activeTools ?? activeTools;\n\n            const { toolChoice: stepToolChoice, tools: stepTools } =\n              await prepareToolsAndToolChoice({\n                tools,\n                toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n                activeTools: stepActiveTools,\n              });\n\n            experimental_context =\n              prepareStepResult?.experimental_context ?? experimental_context;\n\n            const stepMessages =\n              prepareStepResult?.messages ?? stepInputMessages;\n\n            const stepSystem =\n              prepareStepResult?.system ?? initialPrompt.system;\n\n            const stepProviderOptions = mergeObjects(\n              providerOptions,\n              prepareStepResult?.providerOptions,\n            );\n\n            await notify({\n              event: {\n                stepNumber: recordedSteps.length,\n                model: stepModelInfo,\n                system: stepSystem,\n                messages: stepMessages,\n                tools,\n                toolChoice: stepToolChoice,\n                activeTools: stepActiveTools,\n                steps: [...recordedSteps],\n                providerOptions: stepProviderOptions,\n                timeout,\n                headers,\n                stopWhen,\n                output,\n                abortSignal: originalAbortSignal,\n                include,\n                ...callbackTelemetryProps,\n                experimental_context,\n              },\n              callbacks: [\n                onStepStart,\n                globalTelemetry.onStepStart as\n                  | undefined\n                  | StreamTextOnStepStartCallback<TOOLS, OUTPUT>,\n              ],\n            });\n\n            const {\n              result: { stream, response, request },\n              doStreamSpan,\n              startTimestampMs,\n            } = await retry(() =>\n              recordSpan({\n                name: 'ai.streamText.doStream',\n                attributes: selectTelemetryAttributes({\n                  telemetry,\n                  attributes: {\n                    ...assembleOperationName({\n                      operationId: 'ai.streamText.doStream',\n                      telemetry,\n                    }),\n                    ...baseTelemetryAttributes,\n                    // model:\n                    'ai.model.provider': stepModel.provider,\n                    'ai.model.id': stepModel.modelId,\n                    // prompt:\n                    'ai.prompt.messages': {\n                      input: () => stringifyForTelemetry(promptMessages),\n                    },\n                    'ai.prompt.tools': {\n                      // convert the language model level tools:\n                      input: () => stepTools?.map(tool => JSON.stringify(tool)),\n                    },\n                    'ai.prompt.toolChoice': {\n                      input: () =>\n                        stepToolChoice != null\n                          ? JSON.stringify(stepToolChoice)\n                          : undefined,\n                    },\n\n                    // standardized gen-ai llm span attributes:\n                    'gen_ai.system': stepModel.provider,\n                    'gen_ai.request.model': stepModel.modelId,\n                    'gen_ai.request.frequency_penalty':\n                      callSettings.frequencyPenalty,\n                    'gen_ai.request.max_tokens': callSettings.maxOutputTokens,\n                    'gen_ai.request.presence_penalty':\n                      callSettings.presencePenalty,\n                    'gen_ai.request.stop_sequences': callSettings.stopSequences,\n                    'gen_ai.request.temperature': callSettings.temperature,\n                    'gen_ai.request.top_k': callSettings.topK,\n                    'gen_ai.request.top_p': callSettings.topP,\n                  },\n                }),\n                tracer,\n                endWhenDone: false,\n                fn: async doStreamSpan => ({\n                  startTimestampMs: now(), // get before the call\n                  doStreamSpan,\n                  result: await stepModel.doStream({\n                    ...callSettings,\n                    tools: stepTools,\n                    toolChoice: stepToolChoice,\n                    responseFormat: await output?.responseFormat,\n                    prompt: promptMessages,\n                    providerOptions: stepProviderOptions,\n                    abortSignal,\n                    headers,\n                    includeRawChunks,\n                  }),\n                }),\n              }),\n            );\n\n            const streamWithToolResults = runToolsTransformation({\n              tools,\n              generatorStream: stream,\n              tracer,\n              telemetry,\n              system,\n              messages: stepInputMessages,\n              repairToolCall,\n              abortSignal,\n              experimental_context,\n              generateId,\n              stepNumber: recordedSteps.length,\n              model: stepModelInfo,\n              onToolCallStart: [\n                onToolCallStart,\n                globalTelemetry.onToolCallStart as\n                  | undefined\n                  | StreamTextOnToolCallStartCallback<TOOLS>,\n              ],\n              onToolCallFinish: [\n                onToolCallFinish,\n                globalTelemetry.onToolCallFinish,\n              ],\n            });\n\n            // Conditionally include request.body based on include settings.\n            // Large payloads (e.g., base64-encoded images) can cause memory issues.\n            const stepRequest: LanguageModelRequestMetadata =\n              (include?.requestBody ?? true)\n                ? (request ?? {})\n                : { ...request, body: undefined };\n            const stepToolCalls: TypedToolCall<TOOLS>[] = [];\n            const stepToolOutputs: ToolOutput<TOOLS>[] = [];\n            let warnings: SharedV3Warning[] | undefined;\n\n            const activeToolCallToolNames: Record<string, string> = {};\n\n            let stepFinishReason: FinishReason = 'other';\n            let stepRawFinishReason: string | undefined = undefined;\n\n            let stepUsage: LanguageModelUsage = createNullLanguageModelUsage();\n            let stepProviderMetadata: ProviderMetadata | undefined;\n            let stepFirstChunk = true;\n            let stepResponse: { id: string; timestamp: Date; modelId: string } =\n              {\n                id: generateId(),\n                timestamp: new Date(),\n                modelId: modelInfo.modelId,\n              };\n\n            // raw text as it comes from the provider. recorded for telemetry.\n            let activeText = '';\n\n            self.addStream(\n              streamWithToolResults.pipeThrough(\n                new TransformStream<\n                  SingleRequestTextStreamPart<TOOLS>,\n                  TextStreamPart<TOOLS>\n                >({\n                  async transform(chunk, controller): Promise<void> {\n                    resetChunkTimeout();\n\n                    if (chunk.type === 'stream-start') {\n                      warnings = chunk.warnings;\n                      return; // stream start chunks are sent immediately and do not count as first chunk\n                    }\n\n                    if (stepFirstChunk) {\n                      // Telemetry for first chunk:\n                      const msToFirstChunk = now() - startTimestampMs;\n\n                      stepFirstChunk = false;\n\n                      doStreamSpan.addEvent('ai.stream.firstChunk', {\n                        'ai.response.msToFirstChunk': msToFirstChunk,\n                      });\n\n                      doStreamSpan.setAttributes({\n                        'ai.response.msToFirstChunk': msToFirstChunk,\n                      });\n\n                      // Step start:\n                      controller.enqueue({\n                        type: 'start-step',\n                        request: stepRequest,\n                        warnings: warnings ?? [],\n                      });\n                    }\n\n                    const chunkType = chunk.type;\n                    switch (chunkType) {\n                      case 'tool-approval-request':\n                      case 'text-start':\n                      case 'text-end': {\n                        controller.enqueue(chunk);\n                        break;\n                      }\n\n                      case 'text-delta': {\n                        if (chunk.delta.length > 0) {\n                          controller.enqueue({\n                            type: 'text-delta',\n                            id: chunk.id,\n                            text: chunk.delta,\n                            providerMetadata: chunk.providerMetadata,\n                          });\n                          activeText += chunk.delta;\n                        }\n                        break;\n                      }\n\n                      case 'reasoning-start':\n                      case 'reasoning-end': {\n                        controller.enqueue(chunk);\n                        break;\n                      }\n\n                      case 'reasoning-delta': {\n                        controller.enqueue({\n                          type: 'reasoning-delta',\n                          id: chunk.id,\n                          text: chunk.delta,\n                          providerMetadata: chunk.providerMetadata,\n                        });\n                        break;\n                      }\n\n                      case 'tool-call': {\n                        controller.enqueue(chunk);\n                        // store tool calls for onFinish callback and toolCalls promise:\n                        stepToolCalls.push(chunk);\n                        break;\n                      }\n\n                      case 'tool-result': {\n                        controller.enqueue(chunk);\n\n                        if (!chunk.preliminary) {\n                          stepToolOutputs.push(chunk);\n                        }\n\n                        break;\n                      }\n\n                      case 'tool-error': {\n                        controller.enqueue(chunk);\n                        stepToolOutputs.push(chunk);\n                        break;\n                      }\n\n                      case 'response-metadata': {\n                        stepResponse = {\n                          id: chunk.id ?? stepResponse.id,\n                          timestamp: chunk.timestamp ?? stepResponse.timestamp,\n                          modelId: chunk.modelId ?? stepResponse.modelId,\n                        };\n                        break;\n                      }\n\n                      case 'finish': {\n                        // Note: tool executions might not be finished yet when the finish event is emitted.\n                        // store usage and finish reason for promises and onFinish callback:\n                        stepUsage = chunk.usage;\n                        stepFinishReason = chunk.finishReason;\n                        stepRawFinishReason = chunk.rawFinishReason;\n                        stepProviderMetadata = chunk.providerMetadata;\n\n                        // Telemetry for finish event timing\n                        // (since tool executions can take longer and distort calculations)\n                        const msToFinish = now() - startTimestampMs;\n                        doStreamSpan.addEvent('ai.stream.finish');\n                        doStreamSpan.setAttributes({\n                          'ai.response.msToFinish': msToFinish,\n                          'ai.response.avgOutputTokensPerSecond':\n                            (1000 * (stepUsage.outputTokens ?? 0)) / msToFinish,\n                        });\n\n                        break;\n                      }\n\n                      case 'file': {\n                        controller.enqueue(chunk);\n                        break;\n                      }\n\n                      case 'source': {\n                        controller.enqueue(chunk);\n                        break;\n                      }\n\n                      case 'tool-input-start': {\n                        activeToolCallToolNames[chunk.id] = chunk.toolName;\n\n                        const tool = tools?.[chunk.toolName];\n                        if (tool?.onInputStart != null) {\n                          await tool.onInputStart({\n                            toolCallId: chunk.id,\n                            messages: stepInputMessages,\n                            abortSignal,\n                            experimental_context,\n                          });\n                        }\n\n                        controller.enqueue({\n                          ...chunk,\n                          dynamic: chunk.dynamic ?? tool?.type === 'dynamic',\n                          title: tool?.title,\n                        });\n                        break;\n                      }\n\n                      case 'tool-input-end': {\n                        delete activeToolCallToolNames[chunk.id];\n                        controller.enqueue(chunk);\n                        break;\n                      }\n\n                      case 'tool-input-delta': {\n                        const toolName = activeToolCallToolNames[chunk.id];\n                        const tool = tools?.[toolName];\n\n                        if (tool?.onInputDelta != null) {\n                          await tool.onInputDelta({\n                            inputTextDelta: chunk.delta,\n                            toolCallId: chunk.id,\n                            messages: stepInputMessages,\n                            abortSignal,\n                            experimental_context,\n                          });\n                        }\n\n                        controller.enqueue(chunk);\n                        break;\n                      }\n\n                      case 'error': {\n                        controller.enqueue(chunk);\n                        stepFinishReason = 'error';\n                        break;\n                      }\n\n                      case 'raw': {\n                        if (includeRawChunks) {\n                          controller.enqueue(chunk);\n                        }\n                        break;\n                      }\n\n                      default: {\n                        const exhaustiveCheck: never = chunkType;\n                        throw new Error(\n                          `Unknown chunk type: ${exhaustiveCheck}`,\n                        );\n                      }\n                    }\n                  },\n\n                  // invoke onFinish callback and resolve toolResults promise when the stream is about to close:\n                  async flush(controller) {\n                    const stepToolCallsJson =\n                      stepToolCalls.length > 0\n                        ? JSON.stringify(stepToolCalls)\n                        : undefined;\n\n                    // record telemetry attributes that don't depend on transforms:\n                    try {\n                      doStreamSpan.setAttributes(\n                        await selectTelemetryAttributes({\n                          telemetry,\n                          attributes: {\n                            'ai.response.finishReason': stepFinishReason,\n                            'ai.response.toolCalls': {\n                              output: () => stepToolCallsJson,\n                            },\n                            'ai.response.id': stepResponse.id,\n                            'ai.response.model': stepResponse.modelId,\n                            'ai.response.timestamp':\n                              stepResponse.timestamp.toISOString(),\n                            'ai.usage.inputTokens': stepUsage.inputTokens,\n                            'ai.usage.inputTokenDetails.noCacheTokens':\n                              stepUsage.inputTokenDetails?.noCacheTokens,\n                            'ai.usage.inputTokenDetails.cacheReadTokens':\n                              stepUsage.inputTokenDetails?.cacheReadTokens,\n                            'ai.usage.inputTokenDetails.cacheWriteTokens':\n                              stepUsage.inputTokenDetails?.cacheWriteTokens,\n                            'ai.usage.outputTokens': stepUsage.outputTokens,\n                            'ai.usage.outputTokenDetails.textTokens':\n                              stepUsage.outputTokenDetails?.textTokens,\n                            'ai.usage.outputTokenDetails.reasoningTokens':\n                              stepUsage.outputTokenDetails?.reasoningTokens,\n                            'ai.usage.totalTokens': stepUsage.totalTokens,\n                            'ai.usage.reasoningTokens':\n                              stepUsage.outputTokenDetails?.reasoningTokens,\n                            'ai.usage.cachedInputTokens':\n                              stepUsage.inputTokenDetails?.cacheReadTokens,\n\n                            // standardized gen-ai llm span attributes:\n                            'gen_ai.response.finish_reasons': [\n                              stepFinishReason,\n                            ],\n                            'gen_ai.response.id': stepResponse.id,\n                            'gen_ai.response.model': stepResponse.modelId,\n                            'gen_ai.usage.input_tokens': stepUsage.inputTokens,\n                            'gen_ai.usage.output_tokens':\n                              stepUsage.outputTokens,\n                          },\n                        }),\n                      );\n                    } catch (error) {\n                      // ignore error setting telemetry attributes\n                    }\n\n                    controller.enqueue({\n                      type: 'finish-step',\n                      finishReason: stepFinishReason,\n                      rawFinishReason: stepRawFinishReason,\n                      usage: stepUsage,\n                      providerMetadata: stepProviderMetadata,\n                      response: {\n                        ...stepResponse,\n                        headers: response?.headers,\n                      },\n                    });\n\n                    const combinedUsage = addLanguageModelUsage(\n                      usage,\n                      stepUsage,\n                    );\n\n                    // wait for the step to be fully processed by the event processor\n                    // to ensure that the recorded steps are complete:\n                    await stepFinish.promise;\n\n                    // set transform-dependent attributes after the step has been\n                    // fully processed (post-transform) by the event processor:\n                    const processedStep =\n                      recordedSteps[recordedSteps.length - 1];\n                    try {\n                      doStreamSpan.setAttributes(\n                        await selectTelemetryAttributes({\n                          telemetry,\n                          attributes: {\n                            'ai.response.text': {\n                              output: () => processedStep.text,\n                            },\n                            'ai.response.reasoning': {\n                              output: () => processedStep.reasoningText,\n                            },\n                            'ai.response.providerMetadata': JSON.stringify(\n                              processedStep.providerMetadata,\n                            ),\n                          },\n                        }),\n                      );\n                    } catch (error) {\n                      // ignore error setting telemetry attributes\n                    } finally {\n                      doStreamSpan.end();\n                    }\n\n                    const clientToolCalls = stepToolCalls.filter(\n                      toolCall => toolCall.providerExecuted !== true,\n                    );\n                    const clientToolOutputs = stepToolOutputs.filter(\n                      toolOutput => toolOutput.providerExecuted !== true,\n                    );\n\n                    // Track provider-executed tool calls that support deferred results.\n                    // In programmatic tool calling, a server tool (e.g., code_execution) may\n                    // trigger a client tool, and the server tool's result is deferred until\n                    // the client tool's result is sent back.\n                    for (const toolCall of stepToolCalls) {\n                      if (toolCall.providerExecuted !== true) continue;\n                      const tool = tools?.[toolCall.toolName];\n                      if (\n                        tool?.type === 'provider' &&\n                        tool.supportsDeferredResults\n                      ) {\n                        // Check if this tool call already has a result in the current step\n                        const hasResultInStep = stepToolOutputs.some(\n                          output =>\n                            (output.type === 'tool-result' ||\n                              output.type === 'tool-error') &&\n                            output.toolCallId === toolCall.toolCallId,\n                        );\n                        if (!hasResultInStep) {\n                          pendingDeferredToolCalls.set(toolCall.toolCallId, {\n                            toolName: toolCall.toolName,\n                          });\n                        }\n                      }\n                    }\n\n                    // Mark deferred tool calls as resolved when we receive their results\n                    for (const output of stepToolOutputs) {\n                      if (\n                        output.type === 'tool-result' ||\n                        output.type === 'tool-error'\n                      ) {\n                        pendingDeferredToolCalls.delete(output.toolCallId);\n                      }\n                    }\n\n                    // Clear the step and chunk timeouts before the next step is started\n                    clearStepTimeout();\n                    clearChunkTimeout();\n\n                    if (\n                      // Continue if:\n                      // 1. There are client tool calls that have all been executed, OR\n                      // 2. There are pending deferred results from provider-executed tools\n                      ((clientToolCalls.length > 0 &&\n                        clientToolOutputs.length === clientToolCalls.length) ||\n                        pendingDeferredToolCalls.size > 0) &&\n                      // continue until a stop condition is met:\n                      !(await isStopConditionMet({\n                        stopConditions,\n                        steps: recordedSteps,\n                      }))\n                    ) {\n                      // append to messages for the next step:\n                      responseMessages.push(\n                        ...(await toResponseMessages({\n                          content:\n                            // use transformed content to create the messages for the next step:\n                            recordedSteps[recordedSteps.length - 1].content,\n                          tools,\n                        })),\n                      );\n\n                      try {\n                        await streamStep({\n                          currentStep: currentStep + 1,\n                          responseMessages,\n                          usage: combinedUsage,\n                        });\n                      } catch (error) {\n                        controller.enqueue({\n                          type: 'error',\n                          error,\n                        });\n\n                        self.closeStream();\n                      }\n                    } else {\n                      controller.enqueue({\n                        type: 'finish',\n                        finishReason: stepFinishReason,\n                        rawFinishReason: stepRawFinishReason,\n                        totalUsage: combinedUsage,\n                      });\n\n                      self.closeStream(); // close the stitchable stream\n                    }\n                  },\n                }),\n              ),\n            );\n          } finally {\n            clearStepTimeout();\n            clearChunkTimeout();\n          }\n        }\n\n        // add the initial stream to the stitchable stream\n        await streamStep({\n          currentStep: 0,\n          responseMessages: initialResponseMessages,\n          usage: createNullLanguageModelUsage(),\n        });\n      },\n    }).catch(error => {\n      // add an error stream part and close the streams:\n      self.addStream(\n        new ReadableStream({\n          start(controller) {\n            controller.enqueue({ type: 'error', error });\n            controller.close();\n          },\n        }),\n      );\n      self.closeStream();\n    });\n  }\n\n  get steps() {\n    // when any of the promises are accessed, the stream is consumed\n    // so it resolves without needing to consume the stream separately\n    this.consumeStream();\n\n    return this._steps.promise;\n  }\n\n  private get finalStep() {\n    return this.steps.then(steps => steps[steps.length - 1]);\n  }\n\n  get content() {\n    return this.finalStep.then(step => step.content);\n  }\n\n  get warnings() {\n    return this.finalStep.then(step => step.warnings);\n  }\n\n  get providerMetadata() {\n    return this.finalStep.then(step => step.providerMetadata);\n  }\n\n  get text() {\n    return this.finalStep.then(step => step.text);\n  }\n\n  get reasoningText() {\n    return this.finalStep.then(step => step.reasoningText);\n  }\n\n  get reasoning() {\n    return this.finalStep.then(step => step.reasoning);\n  }\n\n  get sources() {\n    return this.finalStep.then(step => step.sources);\n  }\n\n  get files() {\n    return this.finalStep.then(step => step.files);\n  }\n\n  get toolCalls() {\n    return this.finalStep.then(step => step.toolCalls);\n  }\n\n  get staticToolCalls() {\n    return this.finalStep.then(step => step.staticToolCalls);\n  }\n\n  get dynamicToolCalls() {\n    return this.finalStep.then(step => step.dynamicToolCalls);\n  }\n\n  get toolResults() {\n    return this.finalStep.then(step => step.toolResults);\n  }\n\n  get staticToolResults() {\n    return this.finalStep.then(step => step.staticToolResults);\n  }\n\n  get dynamicToolResults() {\n    return this.finalStep.then(step => step.dynamicToolResults);\n  }\n\n  get usage() {\n    return this.finalStep.then(step => step.usage);\n  }\n\n  get request() {\n    return this.finalStep.then(step => step.request);\n  }\n\n  get response() {\n    return this.finalStep.then(step => step.response);\n  }\n\n  get totalUsage() {\n    // when any of the promises are accessed, the stream is consumed\n    // so it resolves without needing to consume the stream separately\n    this.consumeStream();\n\n    return this._totalUsage.promise;\n  }\n\n  get finishReason() {\n    // when any of the promises are accessed, the stream is consumed\n    // so it resolves without needing to consume the stream separately\n    this.consumeStream();\n\n    return this._finishReason.promise;\n  }\n\n  get rawFinishReason() {\n    // when any of the promises are accessed, the stream is consumed\n    // so it resolves without needing to consume the stream separately\n    this.consumeStream();\n\n    return this._rawFinishReason.promise;\n  }\n\n  /**\n   * Split out a new stream from the original stream.\n   * The original stream is replaced to allow for further splitting,\n   * since we do not know how many times the stream will be split.\n   *\n   * Note: this leads to buffering the stream content on the server.\n   * However, the LLM results are expected to be small enough to not cause issues.\n   */\n  private teeStream() {\n    const [stream1, stream2] = this.baseStream.tee();\n    this.baseStream = stream2;\n    return stream1;\n  }\n\n  get textStream(): AsyncIterableStream<string> {\n    return createAsyncIterableStream(\n      this.teeStream().pipeThrough(\n        new TransformStream<\n          EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,\n          string\n        >({\n          transform({ part }, controller) {\n            if (part.type === 'text-delta') {\n              controller.enqueue(part.text);\n            }\n          },\n        }),\n      ),\n    );\n  }\n\n  get fullStream(): AsyncIterableStream<TextStreamPart<TOOLS>> {\n    return createAsyncIterableStream(\n      this.teeStream().pipeThrough(\n        new TransformStream<\n          EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,\n          TextStreamPart<TOOLS>\n        >({\n          transform({ part }, controller) {\n            controller.enqueue(part);\n          },\n        }),\n      ),\n    );\n  }\n\n  async consumeStream(options?: ConsumeStreamOptions): Promise<void> {\n    try {\n      await consumeStream({\n        stream: this.fullStream,\n        onError: options?.onError,\n      });\n    } catch (error) {\n      options?.onError?.(error);\n    }\n  }\n\n  get experimental_partialOutputStream(): AsyncIterableStream<\n    InferPartialOutput<OUTPUT>\n  > {\n    return this.partialOutputStream;\n  }\n\n  get partialOutputStream(): AsyncIterableStream<InferPartialOutput<OUTPUT>> {\n    return createAsyncIterableStream(\n      this.teeStream().pipeThrough(\n        new TransformStream<\n          EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,\n          InferPartialOutput<OUTPUT>\n        >({\n          transform({ partialOutput }, controller) {\n            if (partialOutput != null) {\n              controller.enqueue(partialOutput);\n            }\n          },\n        }),\n      ),\n    );\n  }\n\n  get elementStream(): AsyncIterableStream<InferElementOutput<OUTPUT>> {\n    const transform = this.outputSpecification?.createElementStreamTransform();\n\n    if (transform == null) {\n      throw new UnsupportedFunctionalityError({\n        functionality: `element streams in ${this.outputSpecification?.name ?? 'text'} mode`,\n      });\n    }\n\n    return createAsyncIterableStream(this.teeStream().pipeThrough(transform));\n  }\n\n  get output(): Promise<InferCompleteOutput<OUTPUT>> {\n    return this.finalStep.then(step => {\n      const output = this.outputSpecification ?? text();\n      return output.parseCompleteOutput(\n        { text: step.text },\n        {\n          response: step.response,\n          usage: step.usage,\n          finishReason: step.finishReason,\n        },\n      );\n    });\n  }\n\n  toUIMessageStream<UI_MESSAGE extends UIMessage>({\n    originalMessages,\n    generateMessageId,\n    onFinish,\n    messageMetadata,\n    sendReasoning = true,\n    sendSources = false,\n    sendStart = true,\n    sendFinish = true,\n    onError = getErrorMessage,\n  }: UIMessageStreamOptions<UI_MESSAGE> = {}): AsyncIterableStream<\n    InferUIMessageChunk<UI_MESSAGE>\n  > {\n    const responseMessageId =\n      generateMessageId != null\n        ? getResponseUIMessageId({\n            originalMessages,\n            responseMessageId: generateMessageId,\n          })\n        : undefined;\n\n    // TODO simplify once dynamic is no longer needed for invalid tool inputs\n    const isDynamic = (part: { toolName: string; dynamic?: boolean }) => {\n      const tool = this.tools?.[part.toolName];\n\n      // provider-executed, dynamic tools are not listed in the tools object\n      if (tool == null) {\n        return part.dynamic;\n      }\n\n      return tool?.type === 'dynamic' ? true : undefined;\n    };\n\n    const baseStream = this.fullStream.pipeThrough(\n      new TransformStream<\n        TextStreamPart<TOOLS>,\n        UIMessageChunk<\n          InferUIMessageMetadata<UI_MESSAGE>,\n          InferUIMessageData<UI_MESSAGE>\n        >\n      >({\n        transform: async (part, controller) => {\n          const messageMetadataValue = messageMetadata?.({ part });\n\n          const partType = part.type;\n          switch (partType) {\n            case 'text-start': {\n              controller.enqueue({\n                type: 'text-start',\n                id: part.id,\n                ...(part.providerMetadata != null\n                  ? { providerMetadata: part.providerMetadata }\n                  : {}),\n              });\n              break;\n            }\n\n            case 'text-delta': {\n              controller.enqueue({\n                type: 'text-delta',\n                id: part.id,\n                delta: part.text,\n                ...(part.providerMetadata != null\n                  ? { providerMetadata: part.providerMetadata }\n                  : {}),\n              });\n              break;\n            }\n\n            case 'text-end': {\n              controller.enqueue({\n                type: 'text-end',\n                id: part.id,\n                ...(part.providerMetadata != null\n                  ? { providerMetadata: part.providerMetadata }\n                  : {}),\n              });\n              break;\n            }\n\n            case 'reasoning-start':\n            case 'reasoning-end': {\n              if (sendReasoning) {\n                controller.enqueue({\n                  type: partType,\n                  id: part.id,\n                  ...(part.providerMetadata != null\n                    ? { providerMetadata: part.providerMetadata }\n                    : {}),\n                });\n              }\n              break;\n            }\n\n            case 'reasoning-delta': {\n              if (sendReasoning) {\n                controller.enqueue({\n                  type: 'reasoning-delta',\n                  id: part.id,\n                  delta: part.text,\n                  ...(part.providerMetadata != null\n                    ? { providerMetadata: part.providerMetadata }\n                    : {}),\n                });\n              }\n              break;\n            }\n\n            case 'file': {\n              controller.enqueue({\n                type: 'file',\n                mediaType: part.file.mediaType,\n                url: `data:${part.file.mediaType};base64,${part.file.base64}`,\n                ...(part.providerMetadata != null\n                  ? { providerMetadata: part.providerMetadata }\n                  : {}),\n              });\n              break;\n            }\n\n            case 'source': {\n              if (sendSources && part.sourceType === 'url') {\n                controller.enqueue({\n                  type: 'source-url',\n                  sourceId: part.id,\n                  url: part.url,\n                  title: part.title,\n                  ...(part.providerMetadata != null\n                    ? { providerMetadata: part.providerMetadata }\n                    : {}),\n                });\n              }\n\n              if (sendSources && part.sourceType === 'document') {\n                controller.enqueue({\n                  type: 'source-document',\n                  sourceId: part.id,\n                  mediaType: part.mediaType,\n                  title: part.title,\n                  filename: part.filename,\n                  ...(part.providerMetadata != null\n                    ? { providerMetadata: part.providerMetadata }\n                    : {}),\n                });\n              }\n              break;\n            }\n\n            case 'tool-input-start': {\n              const dynamic = isDynamic(part);\n\n              controller.enqueue({\n                type: 'tool-input-start',\n                toolCallId: part.id,\n                toolName: part.toolName,\n                ...(part.providerExecuted != null\n                  ? { providerExecuted: part.providerExecuted }\n                  : {}),\n                ...(part.providerMetadata != null\n                  ? { providerMetadata: part.providerMetadata }\n                  : {}),\n                ...(part.toolMetadata != null\n                  ? { toolMetadata: part.toolMetadata }\n                  : {}),\n                ...(dynamic != null ? { dynamic } : {}),\n                ...(part.title != null ? { title: part.title } : {}),\n              });\n              break;\n            }\n\n            case 'tool-input-delta': {\n              controller.enqueue({\n                type: 'tool-input-delta',\n                toolCallId: part.id,\n                inputTextDelta: part.delta,\n              });\n              break;\n            }\n\n            case 'tool-call': {\n              const dynamic = isDynamic(part);\n\n              if (part.invalid) {\n                controller.enqueue({\n                  type: 'tool-input-error',\n                  toolCallId: part.toolCallId,\n                  toolName: part.toolName,\n                  input: part.input,\n                  ...(part.providerExecuted != null\n                    ? { providerExecuted: part.providerExecuted }\n                    : {}),\n                  ...(part.providerMetadata != null\n                    ? { providerMetadata: part.providerMetadata }\n                    : {}),\n                  ...(part.toolMetadata != null\n                    ? { toolMetadata: part.toolMetadata }\n                    : {}),\n                  ...(dynamic != null ? { dynamic } : {}),\n                  errorText: onError(part.error),\n                  ...(part.title != null ? { title: part.title } : {}),\n                });\n              } else {\n                controller.enqueue({\n                  type: 'tool-input-available',\n                  toolCallId: part.toolCallId,\n                  toolName: part.toolName,\n                  input: part.input,\n                  ...(part.providerExecuted != null\n                    ? { providerExecuted: part.providerExecuted }\n                    : {}),\n                  ...(part.providerMetadata != null\n                    ? { providerMetadata: part.providerMetadata }\n                    : {}),\n                  ...(part.toolMetadata != null\n                    ? { toolMetadata: part.toolMetadata }\n                    : {}),\n                  ...(dynamic != null ? { dynamic } : {}),\n                  ...(part.title != null ? { title: part.title } : {}),\n                });\n              }\n\n              break;\n            }\n\n            case 'tool-approval-request': {\n              controller.enqueue({\n                type: 'tool-approval-request',\n                approvalId: part.approvalId,\n                toolCallId: part.toolCall.toolCallId,\n              });\n              break;\n            }\n\n            case 'tool-result': {\n              const dynamic = isDynamic(part);\n\n              controller.enqueue({\n                type: 'tool-output-available',\n                toolCallId: part.toolCallId,\n                output: part.output,\n                ...(part.providerExecuted != null\n                  ? { providerExecuted: part.providerExecuted }\n                  : {}),\n                ...(part.providerMetadata != null\n                  ? { providerMetadata: part.providerMetadata }\n                  : {}),\n                ...(part.toolMetadata != null\n                  ? { toolMetadata: part.toolMetadata }\n                  : {}),\n                ...(part.preliminary != null\n                  ? { preliminary: part.preliminary }\n                  : {}),\n                ...(dynamic != null ? { dynamic } : {}),\n              });\n              break;\n            }\n\n            case 'tool-error': {\n              const dynamic = isDynamic(part);\n\n              controller.enqueue({\n                type: 'tool-output-error',\n                toolCallId: part.toolCallId,\n                errorText: part.providerExecuted\n                  ? typeof part.error === 'string'\n                    ? part.error\n                    : JSON.stringify(part.error)\n                  : onError(part.error),\n                ...(part.providerExecuted != null\n                  ? { providerExecuted: part.providerExecuted }\n                  : {}),\n                ...(part.providerMetadata != null\n                  ? { providerMetadata: part.providerMetadata }\n                  : {}),\n                ...(part.toolMetadata != null\n                  ? { toolMetadata: part.toolMetadata }\n                  : {}),\n                ...(dynamic != null ? { dynamic } : {}),\n              });\n              break;\n            }\n\n            case 'tool-output-denied': {\n              controller.enqueue({\n                type: 'tool-output-denied',\n                toolCallId: part.toolCallId,\n              });\n              break;\n            }\n\n            case 'error': {\n              controller.enqueue({\n                type: 'error',\n                errorText: onError(part.error),\n              });\n              break;\n            }\n\n            case 'start-step': {\n              controller.enqueue({ type: 'start-step' });\n              break;\n            }\n\n            case 'finish-step': {\n              controller.enqueue({ type: 'finish-step' });\n              break;\n            }\n\n            case 'start': {\n              if (sendStart) {\n                controller.enqueue({\n                  type: 'start',\n                  ...(messageMetadataValue != null\n                    ? { messageMetadata: messageMetadataValue }\n                    : {}),\n                  ...(responseMessageId != null\n                    ? { messageId: responseMessageId }\n                    : {}),\n                });\n              }\n              break;\n            }\n\n            case 'finish': {\n              if (sendFinish) {\n                controller.enqueue({\n                  type: 'finish',\n                  finishReason: part.finishReason,\n                  ...(messageMetadataValue != null\n                    ? { messageMetadata: messageMetadataValue }\n                    : {}),\n                });\n              }\n              break;\n            }\n\n            case 'abort': {\n              controller.enqueue(part);\n              break;\n            }\n\n            case 'tool-input-end': {\n              break;\n            }\n\n            case 'raw': {\n              // Raw chunks are not included in UI message streams\n              // as they contain provider-specific data for developer use\n              break;\n            }\n\n            default: {\n              const exhaustiveCheck: never = partType;\n              throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n            }\n          }\n\n          // start and finish events already have metadata\n          // so we only need to send metadata for other parts\n          if (\n            messageMetadataValue != null &&\n            partType !== 'start' &&\n            partType !== 'finish'\n          ) {\n            controller.enqueue({\n              type: 'message-metadata',\n              messageMetadata: messageMetadataValue,\n            });\n          }\n        },\n      }),\n    );\n\n    return createAsyncIterableStream(\n      handleUIMessageStreamFinish<UI_MESSAGE>({\n        stream: baseStream,\n        messageId: responseMessageId ?? generateMessageId?.(),\n        originalMessages,\n        onFinish,\n        onError,\n      }),\n    );\n  }\n\n  pipeUIMessageStreamToResponse<UI_MESSAGE extends UIMessage>(\n    response: ServerResponse,\n    {\n      originalMessages,\n      generateMessageId,\n      onFinish,\n      messageMetadata,\n      sendReasoning,\n      sendSources,\n      sendFinish,\n      sendStart,\n      onError,\n      ...init\n    }: UIMessageStreamResponseInit & UIMessageStreamOptions<UI_MESSAGE> = {},\n  ) {\n    pipeUIMessageStreamToResponse({\n      response,\n      stream: this.toUIMessageStream({\n        originalMessages,\n        generateMessageId,\n        onFinish,\n        messageMetadata,\n        sendReasoning,\n        sendSources,\n        sendFinish,\n        sendStart,\n        onError,\n      }),\n      ...init,\n    });\n  }\n\n  pipeTextStreamToResponse(response: ServerResponse, init?: ResponseInit) {\n    pipeTextStreamToResponse({\n      response,\n      textStream: this.textStream,\n      ...init,\n    });\n  }\n\n  toUIMessageStreamResponse<UI_MESSAGE extends UIMessage>({\n    originalMessages,\n    generateMessageId,\n    onFinish,\n    messageMetadata,\n    sendReasoning,\n    sendSources,\n    sendFinish,\n    sendStart,\n    onError,\n    ...init\n  }: UIMessageStreamResponseInit &\n    UIMessageStreamOptions<UI_MESSAGE> = {}): Response {\n    return createUIMessageStreamResponse({\n      stream: this.toUIMessageStream({\n        originalMessages,\n        generateMessageId,\n        onFinish,\n        messageMetadata,\n        sendReasoning,\n        sendSources,\n        sendFinish,\n        sendStart,\n        onError,\n      }),\n      ...init,\n    });\n  }\n\n  toTextStreamResponse(init?: ResponseInit): Response {\n    return createTextStreamResponse({\n      textStream: this.textStream,\n      ...init,\n    });\n  }\n}\n", "export function prepareHeaders(\n  headers: HeadersInit | undefined,\n  defaultHeaders: Record<string, string>,\n): Headers {\n  const responseHeaders = new Headers(headers ?? {});\n\n  for (const [key, value] of Object.entries(defaultHeaders)) {\n    if (!responseHeaders.has(key)) {\n      responseHeaders.set(key, value);\n    }\n  }\n\n  return responseHeaders;\n}\n", "import { prepareHeaders } from '../util/prepare-headers';\n\n/**\n * Creates a Response object from a text stream.\n * Each text chunk is encoded as UTF-8 and sent as a separate chunk.\n * Sets a `Content-Type` header to `text/plain; charset=utf-8`.\n *\n * @param options - The options for creating the response.\n * @param options.status - Optional HTTP status code (default: 200).\n * @param options.statusText - Optional HTTP status text.\n * @param options.headers - Optional response headers.\n * @param options.textStream - The text stream to send.\n * @returns A Response object with the text stream body.\n */\nexport function createTextStreamResponse({\n  status,\n  statusText,\n  headers,\n  textStream,\n}: ResponseInit & {\n  textStream: ReadableStream<string>;\n}): Response {\n  return new Response(textStream.pipeThrough(new TextEncoderStream()), {\n    status: status ?? 200,\n    statusText,\n    headers: prepareHeaders(headers, {\n      'content-type': 'text/plain; charset=utf-8',\n    }),\n  });\n}\n", "import type { ServerResponse } from 'node:http';\n\n/**\n * Writes the content of a stream to a server response.\n */\nexport function writeToServerResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  stream,\n}: {\n  response: ServerResponse;\n  status?: number;\n  statusText?: string;\n  headers?: Record<string, string | number | string[]>;\n  stream: ReadableStream<Uint8Array>;\n}): void {\n  const statusCode = status ?? 200;\n  if (statusText !== undefined) {\n    response.writeHead(statusCode, statusText, headers);\n  } else {\n    response.writeHead(statusCode, headers);\n  }\n\n  const reader = stream.getReader();\n  const read = async () => {\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n\n        // Respect backpressure: if write() returns false, wait for 'drain' event\n        const canContinue = response.write(value);\n        if (!canContinue) {\n          await new Promise<void>(resolve => {\n            response.once('drain', resolve);\n          });\n        }\n      }\n    } catch (error) {\n      throw error;\n    } finally {\n      response.end();\n    }\n  };\n\n  read();\n}\n", "import type { ServerResponse } from 'node:http';\nimport { prepareHeaders } from '../util/prepare-headers';\nimport { writeToServerResponse } from '../util/write-to-server-response';\n\n/**\n * Writes a text stream to a Node.js ServerResponse object.\n * Each text chunk is encoded as UTF-8 and written as a separate chunk.\n * Sets a `Content-Type` header to `text/plain; charset=utf-8`.\n *\n * @param options - The options for piping the stream.\n * @param options.response - The Node.js ServerResponse to write to.\n * @param options.status - Optional HTTP status code.\n * @param options.statusText - Optional HTTP status text.\n * @param options.headers - Optional response headers.\n * @param options.textStream - The text stream to pipe.\n */\nexport function pipeTextStreamToResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  textStream,\n}: {\n  response: ServerResponse;\n  textStream: ReadableStream<string>;\n} & ResponseInit): void {\n  writeToServerResponse({\n    response,\n    status,\n    statusText,\n    headers: Object.fromEntries(\n      prepareHeaders(headers, {\n        'content-type': 'text/plain; charset=utf-8',\n      }).entries(),\n    ),\n    stream: textStream.pipeThrough(new TextEncoderStream()),\n  });\n}\n", "/**\n * A TransformStream that converts JSON objects to Server-Sent Events (SSE) format.\n * Each object is serialized to JSON and wrapped in `data: ...\\n\\n` format.\n * When the stream ends, a `data: [DONE]\\n\\n` message is sent.\n */\nexport class JsonToSseTransformStream extends TransformStream<unknown, string> {\n  constructor() {\n    super({\n      transform(part, controller) {\n        controller.enqueue(`data: ${JSON.stringify(part)}\\n\\n`);\n      },\n      flush(controller) {\n        controller.enqueue('data: [DONE]\\n\\n');\n      },\n    });\n  }\n}\n", "export const UI_MESSAGE_STREAM_HEADERS = {\n  'content-type': 'text/event-stream',\n  'cache-control': 'no-cache',\n  connection: 'keep-alive',\n  'x-vercel-ai-ui-message-stream': 'v1',\n  'x-accel-buffering': 'no', // disable nginx buffering\n};\n", "import { prepareHeaders } from '../util/prepare-headers';\nimport { JsonToSseTransformStream } from './json-to-sse-transform-stream';\nimport { UI_MESSAGE_STREAM_HEADERS } from './ui-message-stream-headers';\nimport type { UIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamResponseInit } from './ui-message-stream-response-init';\n\n/**\n * Creates a Response object from a UI message stream.\n * The stream is transformed to Server-Sent Events (SSE) format.\n *\n * @param options.status - The HTTP status code for the response.\n * @param options.statusText - The HTTP status text for the response.\n * @param options.headers - Additional HTTP headers to include in the response.\n * @param options.stream - The UI message chunk stream to send.\n * @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently.\n *\n * @returns A `Response` object with the UI message stream as the body.\n */\nexport function createUIMessageStreamResponse({\n  status,\n  statusText,\n  headers,\n  stream,\n  consumeSseStream,\n}: UIMessageStreamResponseInit & {\n  stream: ReadableStream<UIMessageChunk>;\n}): Response {\n  let sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n\n  // when the consumeSseStream is provided, we need to tee the stream\n  // and send the second part to the consumeSseStream function\n  // so that it can be consumed by the client independently\n  if (consumeSseStream) {\n    const [stream1, stream2] = sseStream.tee();\n    sseStream = stream1;\n    consumeSseStream({ stream: stream2 }); // no await (do not block the response)\n  }\n\n  return new Response(sseStream.pipeThrough(new TextEncoderStream()), {\n    status,\n    statusText,\n    headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS),\n  });\n}\n", "import type { IdGenerator } from '@ai-sdk/provider-utils';\nimport type { UIMessage } from '../ui/ui-messages';\n\n/**\n * Determines the message ID to use for a response message.\n * If the last message is an assistant message, its ID is reused (continuation).\n * Otherwise, a new ID is generated or the provided ID is used.\n *\n * @param options.originalMessages - The original messages. If not provided, returns `undefined`\n *   since client-side ID generation is used in non-persistence mode.\n * @param options.responseMessageId - The response message ID or an ID generator function.\n *\n * @returns The message ID to use, or `undefined` if no persistence mode.\n */\nexport function getResponseUIMessageId({\n  originalMessages,\n  responseMessageId,\n}: {\n  originalMessages: UIMessage[] | undefined;\n  responseMessageId: string | IdGenerator;\n}) {\n  // when there are no original messages (i.e. no persistence),\n  // the assistant message id generation is handled on the client side.\n  if (originalMessages == null) {\n    return undefined;\n  }\n\n  const lastMessage = originalMessages[originalMessages.length - 1];\n\n  return lastMessage?.role === 'assistant'\n    ? lastMessage.id\n    : typeof responseMessageId === 'function'\n      ? responseMessageId()\n      : responseMessageId;\n}\n", "import { TypeValidationContext, type JSONObject } from '@ai-sdk/provider';\nimport { validateTypes, type FlexibleSchema } from '@ai-sdk/provider-utils';\nimport { UIMessageStreamError } from '../error/ui-message-stream-error';\nimport type { ProviderMetadata } from '../types';\nimport type { FinishReason } from '../types/language-model';\nimport {\n  isDataUIMessageChunk,\n  type DataUIMessageChunk,\n  type InferUIMessageChunk,\n  type UIMessageChunk,\n} from '../ui-message-stream/ui-message-chunks';\nimport type { ErrorHandler } from '../util/error-handler';\nimport { mergeObjects } from '../util/merge-objects';\nimport { parsePartialJson } from '../util/parse-partial-json';\nimport type { UIDataTypesToSchemas } from './chat';\nimport {\n  getStaticToolName,\n  isStaticToolUIPart,\n  isToolUIPart,\n  type DataUIPart,\n  type DynamicToolUIPart,\n  type InferUIMessageData,\n  type InferUIMessageMetadata,\n  type InferUIMessageToolCall,\n  type InferUIMessageTools,\n  type ReasoningUIPart,\n  type TextUIPart,\n  type ToolUIPart,\n  type UIMessage,\n  type UIMessagePart,\n} from './ui-messages';\n\nexport type StreamingUIMessageState<UI_MESSAGE extends UIMessage> = {\n  message: UI_MESSAGE;\n  activeTextParts: Record<string, TextUIPart>;\n  activeReasoningParts: Record<string, ReasoningUIPart>;\n  partialToolCalls: Record<\n    string,\n    {\n      text: string;\n      index: number;\n      toolName: string;\n      dynamic?: boolean;\n      title?: string;\n      toolMetadata?: JSONObject;\n    }\n  >;\n  finishReason?: FinishReason;\n};\n\nexport function createStreamingUIMessageState<UI_MESSAGE extends UIMessage>({\n  lastMessage,\n  messageId,\n}: {\n  lastMessage: UI_MESSAGE | undefined;\n  messageId: string;\n}): StreamingUIMessageState<UI_MESSAGE> {\n  return {\n    message:\n      lastMessage?.role === 'assistant'\n        ? lastMessage\n        : ({\n            id: messageId,\n            metadata: undefined,\n            role: 'assistant',\n            parts: [] as UIMessagePart<\n              InferUIMessageData<UI_MESSAGE>,\n              InferUIMessageTools<UI_MESSAGE>\n            >[],\n          } as UI_MESSAGE),\n    activeTextParts: {},\n    activeReasoningParts: {},\n    partialToolCalls: {},\n  };\n}\n\nexport function processUIMessageStream<UI_MESSAGE extends UIMessage>({\n  stream,\n  messageMetadataSchema,\n  dataPartSchemas,\n  runUpdateMessageJob,\n  onError,\n  onToolCall,\n  onData,\n}: {\n  // input stream is not fully typed yet:\n  stream: ReadableStream<UIMessageChunk>;\n  messageMetadataSchema?: FlexibleSchema<InferUIMessageMetadata<UI_MESSAGE>>;\n  dataPartSchemas?: UIDataTypesToSchemas<InferUIMessageData<UI_MESSAGE>>;\n  onToolCall?: (options: {\n    toolCall: InferUIMessageToolCall<UI_MESSAGE>;\n  }) => void | PromiseLike<void>;\n  onData?: (dataPart: DataUIPart<InferUIMessageData<UI_MESSAGE>>) => void;\n  runUpdateMessageJob: (\n    job: (options: {\n      state: StreamingUIMessageState<UI_MESSAGE>;\n      write: () => void;\n    }) => Promise<void>,\n  ) => Promise<void>;\n  onError: ErrorHandler;\n}): ReadableStream<InferUIMessageChunk<UI_MESSAGE>> {\n  return stream.pipeThrough(\n    new TransformStream<UIMessageChunk, InferUIMessageChunk<UI_MESSAGE>>({\n      async transform(chunk, controller) {\n        await runUpdateMessageJob(async ({ state, write }) => {\n          function getToolInvocation(toolCallId: string) {\n            const toolInvocations = state.message.parts.filter(isToolUIPart);\n\n            const toolInvocation = toolInvocations.find(\n              invocation => invocation.toolCallId === toolCallId,\n            );\n\n            if (toolInvocation == null) {\n              throw new UIMessageStreamError({\n                chunkType: 'tool-invocation',\n                chunkId: toolCallId,\n                message: `No tool invocation found for tool call ID \"${toolCallId}\".`,\n              });\n            }\n\n            return toolInvocation;\n          }\n\n          function updateToolPart(\n            options: {\n              toolName: keyof InferUIMessageTools<UI_MESSAGE> & string;\n              toolCallId: string;\n              providerExecuted?: boolean;\n              title?: string;\n              toolMetadata?: JSONObject;\n            } & (\n              | {\n                  state: 'input-streaming';\n                  input: unknown;\n                  providerExecuted?: boolean;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'input-available';\n                  input: unknown;\n                  providerExecuted?: boolean;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'output-available';\n                  input: unknown;\n                  output: unknown;\n                  providerExecuted?: boolean;\n                  preliminary?: boolean;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'output-error';\n                  input: unknown;\n                  rawInput?: unknown;\n                  errorText: string;\n                  providerExecuted?: boolean;\n                  providerMetadata?: ProviderMetadata;\n                }\n            ),\n          ) {\n            const part = state.message.parts.find(\n              part =>\n                isStaticToolUIPart(part) &&\n                part.toolCallId === options.toolCallId,\n            ) as ToolUIPart<InferUIMessageTools<UI_MESSAGE>> | undefined;\n\n            const anyOptions = options as any;\n            const anyPart = part as any;\n\n            if (part != null) {\n              part.state = options.state;\n              anyPart.input = anyOptions.input;\n              anyPart.output = anyOptions.output;\n              anyPart.errorText = anyOptions.errorText;\n              anyPart.rawInput = anyOptions.rawInput;\n              anyPart.preliminary = anyOptions.preliminary;\n              if (options.title !== undefined) {\n                anyPart.title = options.title;\n              }\n              if (options.toolMetadata !== undefined) {\n                anyPart.toolMetadata = options.toolMetadata;\n              }\n              // once providerExecuted is set, it stays for streaming\n              anyPart.providerExecuted =\n                anyOptions.providerExecuted ?? part.providerExecuted;\n\n              const providerMetadata = anyOptions.providerMetadata;\n\n              if (providerMetadata != null) {\n                if (\n                  options.state === 'output-available' ||\n                  options.state === 'output-error'\n                ) {\n                  const resultPart = part as Extract<\n                    ToolUIPart<InferUIMessageTools<UI_MESSAGE>>,\n                    { state: 'output-available' | 'output-error' }\n                  >;\n\n                  resultPart.resultProviderMetadata = providerMetadata;\n                } else {\n                  part.callProviderMetadata = providerMetadata;\n                }\n              }\n            } else {\n              state.message.parts.push({\n                type: `tool-${options.toolName}`,\n                toolCallId: options.toolCallId,\n                state: options.state,\n                title: options.title,\n                ...(options.toolMetadata !== undefined\n                  ? { toolMetadata: options.toolMetadata }\n                  : {}),\n                input: anyOptions.input,\n                output: anyOptions.output,\n                rawInput: anyOptions.rawInput,\n                errorText: anyOptions.errorText,\n                providerExecuted: anyOptions.providerExecuted,\n                preliminary: anyOptions.preliminary,\n                ...(anyOptions.providerMetadata != null &&\n                (options.state === 'output-available' ||\n                  options.state === 'output-error')\n                  ? { resultProviderMetadata: anyOptions.providerMetadata }\n                  : {}),\n                ...(anyOptions.providerMetadata != null &&\n                !(\n                  options.state === 'output-available' ||\n                  options.state === 'output-error'\n                )\n                  ? { callProviderMetadata: anyOptions.providerMetadata }\n                  : {}),\n              } as ToolUIPart<InferUIMessageTools<UI_MESSAGE>>);\n            }\n          }\n\n          function updateDynamicToolPart(\n            options: {\n              toolName: keyof InferUIMessageTools<UI_MESSAGE> & string;\n              toolCallId: string;\n              providerExecuted?: boolean;\n              title?: string;\n              toolMetadata?: JSONObject;\n            } & (\n              | {\n                  state: 'input-streaming';\n                  input: unknown;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'input-available';\n                  input: unknown;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'output-available';\n                  input: unknown;\n                  output: unknown;\n                  preliminary: boolean | undefined;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'output-error';\n                  input: unknown;\n                  errorText: string;\n                  providerMetadata?: ProviderMetadata;\n                }\n            ),\n          ) {\n            const part = state.message.parts.find(\n              part =>\n                part.type === 'dynamic-tool' &&\n                part.toolCallId === options.toolCallId,\n            ) as DynamicToolUIPart | undefined;\n\n            const anyOptions = options as any;\n            const anyPart = part as any;\n\n            if (part != null) {\n              part.state = options.state;\n              anyPart.toolName = options.toolName;\n              anyPart.input = anyOptions.input;\n              anyPart.output = anyOptions.output;\n              anyPart.errorText = anyOptions.errorText;\n              anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;\n              anyPart.preliminary = anyOptions.preliminary;\n              if (options.title !== undefined) {\n                anyPart.title = options.title;\n              }\n              if (options.toolMetadata !== undefined) {\n                anyPart.toolMetadata = options.toolMetadata;\n              }\n              // once providerExecuted is set, it stays for streaming\n              anyPart.providerExecuted =\n                anyOptions.providerExecuted ?? part.providerExecuted;\n\n              const providerMetadata = anyOptions.providerMetadata;\n\n              if (providerMetadata != null) {\n                if (\n                  options.state === 'output-available' ||\n                  options.state === 'output-error'\n                ) {\n                  const resultPart = part as Extract<\n                    DynamicToolUIPart,\n                    { state: 'output-available' | 'output-error' }\n                  >;\n\n                  resultPart.resultProviderMetadata = providerMetadata;\n                } else {\n                  part.callProviderMetadata = providerMetadata;\n                }\n              }\n            } else {\n              state.message.parts.push({\n                type: 'dynamic-tool',\n                toolName: options.toolName,\n                toolCallId: options.toolCallId,\n                state: options.state,\n                input: anyOptions.input,\n                output: anyOptions.output,\n                errorText: anyOptions.errorText,\n                preliminary: anyOptions.preliminary,\n                providerExecuted: anyOptions.providerExecuted,\n                title: options.title,\n                ...(options.toolMetadata !== undefined\n                  ? { toolMetadata: options.toolMetadata }\n                  : {}),\n                ...(anyOptions.providerMetadata != null &&\n                (options.state === 'output-available' ||\n                  options.state === 'output-error')\n                  ? { resultProviderMetadata: anyOptions.providerMetadata }\n                  : {}),\n                ...(anyOptions.providerMetadata != null &&\n                !(\n                  options.state === 'output-available' ||\n                  options.state === 'output-error'\n                )\n                  ? { callProviderMetadata: anyOptions.providerMetadata }\n                  : {}),\n              } as DynamicToolUIPart);\n            }\n          }\n\n          async function updateMessageMetadata(metadata: unknown) {\n            if (metadata != null) {\n              const mergedMetadata =\n                state.message.metadata != null\n                  ? mergeObjects(state.message.metadata, metadata)\n                  : metadata;\n\n              if (messageMetadataSchema != null) {\n                await validateTypes({\n                  value: mergedMetadata,\n                  schema: messageMetadataSchema,\n                  context: {\n                    field: 'message.metadata',\n                    entityId: state.message.id,\n                  },\n                });\n              }\n\n              state.message.metadata =\n                mergedMetadata as InferUIMessageMetadata<UI_MESSAGE>;\n            }\n          }\n\n          switch (chunk.type) {\n            case 'text-start': {\n              const textPart: TextUIPart = {\n                type: 'text',\n                text: '',\n                providerMetadata: chunk.providerMetadata,\n                state: 'streaming',\n              };\n              state.activeTextParts[chunk.id] = textPart;\n              state.message.parts.push(textPart);\n              write();\n              break;\n            }\n\n            case 'text-delta': {\n              const textPart = state.activeTextParts[chunk.id];\n              if (textPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'text-delta',\n                  chunkId: chunk.id,\n                  message:\n                    `Received text-delta for missing text part with ID \"${chunk.id}\". ` +\n                    `Ensure a \"text-start\" chunk is sent before any \"text-delta\" chunks.`,\n                });\n              }\n              textPart.text += chunk.delta;\n              textPart.providerMetadata =\n                chunk.providerMetadata ?? textPart.providerMetadata;\n              write();\n              break;\n            }\n\n            case 'text-end': {\n              const textPart = state.activeTextParts[chunk.id];\n              if (textPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'text-end',\n                  chunkId: chunk.id,\n                  message:\n                    `Received text-end for missing text part with ID \"${chunk.id}\". ` +\n                    `Ensure a \"text-start\" chunk is sent before any \"text-end\" chunks.`,\n                });\n              }\n              textPart.state = 'done';\n              textPart.providerMetadata =\n                chunk.providerMetadata ?? textPart.providerMetadata;\n              delete state.activeTextParts[chunk.id];\n              write();\n              break;\n            }\n\n            case 'reasoning-start': {\n              const reasoningPart: ReasoningUIPart = {\n                type: 'reasoning',\n                text: '',\n                providerMetadata: chunk.providerMetadata,\n                state: 'streaming',\n              };\n              state.activeReasoningParts[chunk.id] = reasoningPart;\n              state.message.parts.push(reasoningPart);\n              write();\n              break;\n            }\n\n            case 'reasoning-delta': {\n              const reasoningPart = state.activeReasoningParts[chunk.id];\n              if (reasoningPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'reasoning-delta',\n                  chunkId: chunk.id,\n                  message:\n                    `Received reasoning-delta for missing reasoning part with ID \"${chunk.id}\". ` +\n                    `Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-delta\" chunks.`,\n                });\n              }\n              reasoningPart.text += chunk.delta;\n              reasoningPart.providerMetadata =\n                chunk.providerMetadata ?? reasoningPart.providerMetadata;\n              write();\n              break;\n            }\n\n            case 'reasoning-end': {\n              const reasoningPart = state.activeReasoningParts[chunk.id];\n              if (reasoningPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'reasoning-end',\n                  chunkId: chunk.id,\n                  message:\n                    `Received reasoning-end for missing reasoning part with ID \"${chunk.id}\". ` +\n                    `Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-end\" chunks.`,\n                });\n              }\n              reasoningPart.providerMetadata =\n                chunk.providerMetadata ?? reasoningPart.providerMetadata;\n              reasoningPart.state = 'done';\n              delete state.activeReasoningParts[chunk.id];\n\n              write();\n              break;\n            }\n\n            case 'file': {\n              state.message.parts.push({\n                type: 'file',\n                mediaType: chunk.mediaType,\n                url: chunk.url,\n                ...(chunk.providerMetadata != null\n                  ? { providerMetadata: chunk.providerMetadata }\n                  : {}),\n              });\n\n              write();\n              break;\n            }\n\n            case 'source-url': {\n              state.message.parts.push({\n                type: 'source-url',\n                sourceId: chunk.sourceId,\n                url: chunk.url,\n                title: chunk.title,\n                providerMetadata: chunk.providerMetadata,\n              });\n\n              write();\n              break;\n            }\n\n            case 'source-document': {\n              state.message.parts.push({\n                type: 'source-document',\n                sourceId: chunk.sourceId,\n                mediaType: chunk.mediaType,\n                title: chunk.title,\n                filename: chunk.filename,\n                providerMetadata: chunk.providerMetadata,\n              });\n\n              write();\n              break;\n            }\n\n            case 'tool-input-start': {\n              const toolInvocations =\n                state.message.parts.filter(isStaticToolUIPart);\n\n              // add the partial tool call to the map\n              state.partialToolCalls[chunk.toolCallId] = {\n                text: '',\n                toolName: chunk.toolName,\n                index: toolInvocations.length,\n                dynamic: chunk.dynamic,\n                title: chunk.title,\n                toolMetadata: chunk.toolMetadata,\n              };\n\n              if (chunk.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'input-streaming',\n                  input: undefined,\n                  providerExecuted: chunk.providerExecuted,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                  providerMetadata: chunk.providerMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'input-streaming',\n                  input: undefined,\n                  providerExecuted: chunk.providerExecuted,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                  providerMetadata: chunk.providerMetadata,\n                });\n              }\n\n              write();\n              break;\n            }\n\n            case 'tool-input-delta': {\n              const partialToolCall = state.partialToolCalls[chunk.toolCallId];\n              if (partialToolCall == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'tool-input-delta',\n                  chunkId: chunk.toolCallId,\n                  message:\n                    `Received tool-input-delta for missing tool call with ID \"${chunk.toolCallId}\". ` +\n                    `Ensure a \"tool-input-start\" chunk is sent before any \"tool-input-delta\" chunks.`,\n                });\n              }\n\n              partialToolCall.text += chunk.inputTextDelta;\n\n              const { value: partialArgs } = await parsePartialJson(\n                partialToolCall.text,\n              );\n\n              if (partialToolCall.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: partialToolCall.toolName,\n                  state: 'input-streaming',\n                  input: partialArgs,\n                  title: partialToolCall.title,\n                  toolMetadata: partialToolCall.toolMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: partialToolCall.toolName,\n                  state: 'input-streaming',\n                  input: partialArgs,\n                  title: partialToolCall.title,\n                  toolMetadata: partialToolCall.toolMetadata,\n                });\n              }\n\n              write();\n              break;\n            }\n\n            case 'tool-input-available': {\n              if (chunk.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'input-available',\n                  input: chunk.input,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'input-available',\n                  input: chunk.input,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                });\n              }\n\n              write();\n\n              // invoke the onToolCall callback if it exists. This is blocking.\n              // In the future we should make this non-blocking, which\n              // requires additional state management for error handling etc.\n              // Skip calling onToolCall for provider-executed tools since they are already executed\n              if (onToolCall && !chunk.providerExecuted) {\n                await onToolCall({\n                  toolCall: chunk as InferUIMessageToolCall<UI_MESSAGE>,\n                });\n              }\n              break;\n            }\n\n            case 'tool-input-error': {\n              // When a part already exists for this toolCallId (e.g. from\n              // tool-input-start), honour its type so we update in place\n              // instead of creating a duplicate with a mismatched type.\n              const existingPart = state.message.parts\n                .filter(isToolUIPart)\n                .find(p => p.toolCallId === chunk.toolCallId);\n              const isDynamic =\n                existingPart != null\n                  ? existingPart.type === 'dynamic-tool'\n                  : !!chunk.dynamic;\n\n              if (isDynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'output-error',\n                  input: chunk.input,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  toolMetadata: chunk.toolMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'output-error',\n                  input: undefined,\n                  rawInput: chunk.input,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  toolMetadata: chunk.toolMetadata,\n                });\n              }\n\n              write();\n              break;\n            }\n\n            case 'tool-approval-request': {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n              toolInvocation.state = 'approval-requested';\n              toolInvocation.approval = { id: chunk.approvalId };\n              write();\n              break;\n            }\n\n            case 'tool-output-denied': {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n              toolInvocation.state = 'output-denied';\n              write();\n              break;\n            }\n\n            case 'tool-output-available': {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n\n              if (toolInvocation.type === 'dynamic-tool') {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: toolInvocation.toolName,\n                  state: 'output-available',\n                  input: (toolInvocation as any).input,\n                  output: chunk.output,\n                  preliminary: chunk.preliminary,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: toolInvocation.title,\n                  toolMetadata: toolInvocation.toolMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: getStaticToolName(toolInvocation),\n                  state: 'output-available',\n                  input: (toolInvocation as any).input,\n                  output: chunk.output,\n                  providerExecuted: chunk.providerExecuted,\n                  preliminary: chunk.preliminary,\n                  providerMetadata: chunk.providerMetadata,\n                  title: toolInvocation.title,\n                  toolMetadata: toolInvocation.toolMetadata,\n                });\n              }\n\n              write();\n              break;\n            }\n\n            case 'tool-output-error': {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n\n              if (toolInvocation.type === 'dynamic-tool') {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: toolInvocation.toolName,\n                  state: 'output-error',\n                  input: (toolInvocation as any).input,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: toolInvocation.title,\n                  toolMetadata: toolInvocation.toolMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: getStaticToolName(toolInvocation),\n                  state: 'output-error',\n                  input: (toolInvocation as any).input,\n                  rawInput: (toolInvocation as any).rawInput,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: toolInvocation.title,\n                  toolMetadata: toolInvocation.toolMetadata,\n                });\n              }\n\n              write();\n              break;\n            }\n\n            case 'start-step': {\n              // add a step boundary part to the message\n              state.message.parts.push({ type: 'step-start' });\n              break;\n            }\n\n            case 'finish-step': {\n              // reset the current text and reasoning parts\n              state.activeTextParts = {};\n              state.activeReasoningParts = {};\n              break;\n            }\n\n            case 'start': {\n              if (chunk.messageId != null) {\n                state.message.id = chunk.messageId;\n              }\n\n              await updateMessageMetadata(chunk.messageMetadata);\n\n              if (chunk.messageId != null || chunk.messageMetadata != null) {\n                write();\n              }\n              break;\n            }\n\n            case 'finish': {\n              if (chunk.finishReason != null) {\n                state.finishReason = chunk.finishReason;\n              }\n              await updateMessageMetadata(chunk.messageMetadata);\n              if (chunk.messageMetadata != null) {\n                write();\n              }\n              break;\n            }\n\n            case 'message-metadata': {\n              await updateMessageMetadata(chunk.messageMetadata);\n              if (chunk.messageMetadata != null) {\n                write();\n              }\n              break;\n            }\n\n            case 'error': {\n              onError?.(new Error(chunk.errorText));\n              break;\n            }\n\n            default: {\n              if (isDataUIMessageChunk(chunk)) {\n                // validate data chunk if dataPartSchemas is provided\n                if (dataPartSchemas?.[chunk.type] != null) {\n                  const partIdx = state.message.parts.findIndex(\n                    p =>\n                      'id' in p &&\n                      'data' in p &&\n                      p.id === chunk.id &&\n                      p.type === chunk.type,\n                  );\n                  const actualPartIdx =\n                    partIdx >= 0 ? partIdx : state.message.parts.length;\n\n                  await validateTypes({\n                    value: chunk.data,\n                    schema: dataPartSchemas[chunk.type],\n                    context: {\n                      field: `message.parts[${actualPartIdx}].data`,\n                      entityName: chunk.type,\n                      entityId: chunk.id,\n                    },\n                  });\n                }\n\n                // cast, validation is done above\n                const dataChunk = chunk as DataUIMessageChunk<\n                  InferUIMessageData<UI_MESSAGE>\n                >;\n\n                // transient parts are not added to the message state\n                if (dataChunk.transient) {\n                  onData?.(dataChunk);\n                  break;\n                }\n\n                const existingUIPart =\n                  dataChunk.id != null\n                    ? (state.message.parts.find(\n                        chunkArg =>\n                          dataChunk.type === chunkArg.type &&\n                          dataChunk.id === chunkArg.id,\n                      ) as\n                        | DataUIPart<InferUIMessageData<UI_MESSAGE>>\n                        | undefined)\n                    : undefined;\n\n                if (existingUIPart != null) {\n                  existingUIPart.data = dataChunk.data;\n                } else {\n                  state.message.parts.push(dataChunk);\n                }\n\n                onData?.(dataChunk);\n\n                write();\n              }\n            }\n          }\n\n          controller.enqueue(chunk as InferUIMessageChunk<UI_MESSAGE>);\n        });\n      },\n    }),\n  );\n}\n", "import type { JSONObject } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\nimport {\n  providerMetadataSchema,\n  type ProviderMetadata,\n} from '../types/provider-metadata';\nimport { jsonValueSchema } from '../types/json-value';\nimport type { FinishReason } from '../types/language-model';\nimport type {\n  InferUIMessageData,\n  InferUIMessageMetadata,\n  UIDataTypes,\n  UIMessage,\n} from '../ui/ui-messages';\nimport type { ValueOf } from '../util/value-of';\nimport { lazySchema, zodSchema } from '@ai-sdk/provider-utils';\n\nconst toolMetadataSchema: z.ZodType<JSONObject> = z.record(\n  z.string(),\n  jsonValueSchema.optional(),\n);\n\nexport const uiMessageChunkSchema = lazySchema(() =>\n  zodSchema(\n    z.union([\n      z.strictObject({\n        type: z.literal('text-start'),\n        id: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.literal('text-delta'),\n        id: z.string(),\n        delta: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.literal('text-end'),\n        id: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.literal('error'),\n        errorText: z.string(),\n      }),\n      z.strictObject({\n        type: z.literal('tool-input-start'),\n        toolCallId: z.string(),\n        toolName: z.string(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n        title: z.string().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('tool-input-delta'),\n        toolCallId: z.string(),\n        inputTextDelta: z.string(),\n      }),\n      z.strictObject({\n        type: z.literal('tool-input-available'),\n        toolCallId: z.string(),\n        toolName: z.string(),\n        input: z.unknown(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n        title: z.string().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('tool-input-error'),\n        toolCallId: z.string(),\n        toolName: z.string(),\n        input: z.unknown(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n        errorText: z.string(),\n        title: z.string().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('tool-approval-request'),\n        approvalId: z.string(),\n        toolCallId: z.string(),\n      }),\n      z.strictObject({\n        type: z.literal('tool-output-available'),\n        toolCallId: z.string(),\n        output: z.unknown(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n        preliminary: z.boolean().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('tool-output-error'),\n        toolCallId: z.string(),\n        errorText: z.string(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('tool-output-denied'),\n        toolCallId: z.string(),\n      }),\n      z.strictObject({\n        type: z.literal('reasoning-start'),\n        id: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.literal('reasoning-delta'),\n        id: z.string(),\n        delta: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.literal('reasoning-end'),\n        id: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.literal('source-url'),\n        sourceId: z.string(),\n        url: z.string(),\n        title: z.string().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.literal('source-document'),\n        sourceId: z.string(),\n        mediaType: z.string(),\n        title: z.string(),\n        filename: z.string().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.literal('file'),\n        url: z.string(),\n        mediaType: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.strictObject({\n        type: z.custom<`data-${string}`>(\n          (value): value is `data-${string}` =>\n            typeof value === 'string' && value.startsWith('data-'),\n          { message: 'Type must start with \"data-\"' },\n        ),\n        id: z.string().optional(),\n        data: z.unknown(),\n        transient: z.boolean().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('start-step'),\n      }),\n      z.strictObject({\n        type: z.literal('finish-step'),\n      }),\n      z.strictObject({\n        type: z.literal('start'),\n        messageId: z.string().optional(),\n        messageMetadata: z.unknown().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('finish'),\n        finishReason: z\n          .enum([\n            'stop',\n            'length',\n            'content-filter',\n            'tool-calls',\n            'error',\n            'other',\n          ] as const satisfies readonly FinishReason[])\n          .optional(),\n        messageMetadata: z.unknown().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('abort'),\n        reason: z.string().optional(),\n      }),\n      z.strictObject({\n        type: z.literal('message-metadata'),\n        messageMetadata: z.unknown(),\n      }),\n    ]),\n  ),\n);\n\nexport type DataUIMessageChunk<DATA_TYPES extends UIDataTypes> = ValueOf<{\n  [NAME in keyof DATA_TYPES & string]: {\n    type: `data-${NAME}`;\n    id?: string;\n    data: DATA_TYPES[NAME];\n    transient?: boolean;\n  };\n}>;\n\nexport type UIMessageChunk<\n  METADATA = unknown,\n  DATA_TYPES extends UIDataTypes = UIDataTypes,\n> =\n  | {\n      type: 'text-start';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'text-delta';\n      delta: string;\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'text-end';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'reasoning-start';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'reasoning-delta';\n      id: string;\n      delta: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'reasoning-end';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'error';\n      errorText: string;\n    }\n  | {\n      type: 'tool-input-available';\n      toolCallId: string;\n      toolName: string;\n      input: unknown;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n      title?: string;\n    }\n  | {\n      type: 'tool-input-error';\n      toolCallId: string;\n      toolName: string;\n      input: unknown;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n      errorText: string;\n      title?: string;\n    }\n  | {\n      type: 'tool-approval-request';\n      approvalId: string;\n      toolCallId: string;\n    }\n  | {\n      type: 'tool-output-available';\n      toolCallId: string;\n      output: unknown;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n      preliminary?: boolean;\n    }\n  | {\n      type: 'tool-output-error';\n      toolCallId: string;\n      errorText: string;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n    }\n  | {\n      type: 'tool-output-denied';\n      toolCallId: string;\n    }\n  | {\n      type: 'tool-input-start';\n      toolCallId: string;\n      toolName: string;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n      title?: string;\n    }\n  | {\n      type: 'tool-input-delta';\n      toolCallId: string;\n      inputTextDelta: string;\n    }\n  | {\n      type: 'source-url';\n      sourceId: string;\n      url: string;\n      title?: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'source-document';\n      sourceId: string;\n      mediaType: string;\n      title: string;\n      filename?: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'file';\n      url: string;\n      mediaType: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | DataUIMessageChunk<DATA_TYPES>\n  | {\n      type: 'start-step';\n    }\n  | {\n      type: 'finish-step';\n    }\n  | {\n      type: 'start';\n      messageId?: string;\n      messageMetadata?: METADATA;\n    }\n  | {\n      type: 'finish';\n      finishReason?: FinishReason;\n      messageMetadata?: METADATA;\n    }\n  | {\n      type: 'abort';\n      reason?: string;\n    }\n  | {\n      type: 'message-metadata';\n      messageMetadata: METADATA;\n    };\n\nexport function isDataUIMessageChunk(\n  chunk: UIMessageChunk,\n): chunk is DataUIMessageChunk<UIDataTypes> {\n  return chunk.type.startsWith('data-');\n}\n\nexport type InferUIMessageChunk<T extends UIMessage> = UIMessageChunk<\n  InferUIMessageMetadata<T>,\n  InferUIMessageData<T>\n>;\n", "import type { JSONObject } from '@ai-sdk/provider';\nimport type {\n  InferToolInput,\n  InferToolOutput,\n  Tool,\n  ToolCall,\n} from '@ai-sdk/provider-utils';\nimport type { ToolSet } from '../generate-text';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport type { DeepPartial } from '../util/deep-partial';\nimport type { ValueOf } from '../util/value-of';\n\n/**\n * The data types that can be used in the UI message for the UI message data parts.\n */\nexport type UIDataTypes = Record<string, unknown>;\n\nexport type UITool = {\n  input: unknown;\n  output: unknown | undefined;\n};\n\n/**\n * Infer the input and output types of a tool so it can be used as a UI tool.\n */\nexport type InferUITool<TOOL extends Tool> = {\n  input: InferToolInput<TOOL>;\n  output: InferToolOutput<TOOL>;\n};\n\n/**\n * Infer the input and output types of a tool set so it can be used as a UI tool set.\n */\nexport type InferUITools<TOOLS extends ToolSet> = {\n  [NAME in keyof TOOLS & string]: InferUITool<TOOLS[NAME]>;\n};\n\nexport type UITools = Record<string, UITool>;\n\n/**\n * AI SDK UI Messages. They are used in the client and to communicate between the frontend and the API routes.\n */\nexport interface UIMessage<\n  METADATA = unknown,\n  DATA_PARTS extends UIDataTypes = UIDataTypes,\n  TOOLS extends UITools = UITools,\n> {\n  /**\n   * A unique identifier for the message.\n   */\n  id: string;\n\n  /**\n   * The role of the message.\n   */\n  role: 'system' | 'user' | 'assistant';\n\n  /**\n   * The metadata of the message.\n   */\n  metadata?: METADATA;\n\n  /**\n   * The parts of the message. Use this for rendering the message in the UI.\n   *\n   * System messages should be avoided (set the system prompt on the server instead).\n   * They can have text parts.\n   *\n   * User messages can have text parts and file parts.\n   *\n   * Assistant messages can have text, reasoning, tool invocation, and file parts.\n   */\n  parts: Array<UIMessagePart<DATA_PARTS, TOOLS>>;\n}\n\nexport type UIMessagePart<\n  DATA_TYPES extends UIDataTypes,\n  TOOLS extends UITools,\n> =\n  | TextUIPart\n  | ReasoningUIPart\n  | ToolUIPart<TOOLS>\n  | DynamicToolUIPart\n  | SourceUrlUIPart\n  | SourceDocumentUIPart\n  | FileUIPart\n  | DataUIPart<DATA_TYPES>\n  | StepStartUIPart;\n\n/**\n * A text part of a message.\n */\nexport type TextUIPart = {\n  type: 'text';\n\n  /**\n   * The text content.\n   */\n  text: string;\n\n  /**\n   * The state of the text part.\n   */\n  state?: 'streaming' | 'done';\n\n  /**\n   * The provider metadata.\n   */\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A reasoning part of a message.\n */\nexport type ReasoningUIPart = {\n  type: 'reasoning';\n\n  /**\n   * The reasoning text.\n   */\n  text: string;\n\n  /**\n   * The state of the reasoning part.\n   */\n  state?: 'streaming' | 'done';\n\n  /**\n   * The provider metadata.\n   */\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A source part of a message.\n */\nexport type SourceUrlUIPart = {\n  type: 'source-url';\n  sourceId: string;\n  url: string;\n  title?: string;\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A document source part of a message.\n */\nexport type SourceDocumentUIPart = {\n  type: 'source-document';\n  sourceId: string;\n  mediaType: string;\n  title: string;\n  filename?: string;\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A file part of a message.\n */\nexport type FileUIPart = {\n  type: 'file';\n\n  /**\n   * IANA media type of the file.\n   *\n   * @see https://www.iana.org/assignments/media-types/media-types.xhtml\n   */\n  mediaType: string;\n\n  /**\n   * Optional filename of the file.\n   */\n  filename?: string;\n\n  /**\n   * The URL of the file.\n   * It can either be a URL to a hosted file or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs).\n   */\n  url: string;\n\n  /**\n   * The provider metadata.\n   */\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A step boundary part of a message.\n */\nexport type StepStartUIPart = {\n  type: 'step-start';\n};\n\nexport type DataUIPart<DATA_TYPES extends UIDataTypes> = ValueOf<{\n  [NAME in keyof DATA_TYPES & string]: {\n    type: `data-${NAME}`;\n    id?: string;\n    data: DATA_TYPES[NAME];\n  };\n}>;\n\ntype asUITool<TOOL extends UITool | Tool> = TOOL extends Tool\n  ? InferUITool<TOOL>\n  : TOOL;\n\n/**\n * Check if a message part is a data part.\n */\nexport function isDataUIPart<DATA_TYPES extends UIDataTypes>(\n  part: UIMessagePart<DATA_TYPES, UITools>,\n): part is DataUIPart<DATA_TYPES> {\n  return part.type.startsWith('data-');\n}\n\n/**\n * A UI tool invocation contains all the information needed to render a tool invocation in the UI.\n * It can be derived from a tool without knowing the tool name, and can be used to define\n * UI components for the tool.\n */\nexport type UIToolInvocation<TOOL extends UITool | Tool> = {\n  /**\n   * ID of the tool call.\n   */\n  toolCallId: string;\n  title?: string;\n  toolMetadata?: JSONObject;\n\n  /**\n   * Whether the tool call was executed by the provider.\n   */\n  providerExecuted?: boolean;\n} & (\n  | {\n      state: 'input-streaming';\n      input: DeepPartial<asUITool<TOOL>['input']> | undefined;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval?: never;\n    }\n  | {\n      state: 'input-available';\n      input: asUITool<TOOL>['input'];\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval?: never;\n    }\n  | {\n      state: 'approval-requested';\n      input: asUITool<TOOL>['input'];\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved?: never;\n        reason?: never;\n      };\n    }\n  | {\n      state: 'approval-responded';\n      input: asUITool<TOOL>['input'];\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved: boolean;\n        reason?: string;\n      };\n    }\n  | {\n      state: 'output-available';\n      input: asUITool<TOOL>['input'];\n      output: asUITool<TOOL>['output'];\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      resultProviderMetadata?: ProviderMetadata;\n      preliminary?: boolean;\n      approval?: {\n        id: string;\n        approved: true;\n        reason?: string;\n      };\n    }\n  | {\n      state: 'output-error'; // TODO AI SDK 6: change to 'error' state\n      input: asUITool<TOOL>['input'] | undefined;\n      rawInput?: unknown; // TODO AI SDK 6: remove this field, input should be unknown\n      output?: never;\n      errorText: string;\n      callProviderMetadata?: ProviderMetadata;\n      resultProviderMetadata?: ProviderMetadata;\n      approval?: {\n        id: string;\n        approved: true;\n        reason?: string;\n      };\n    }\n  | {\n      state: 'output-denied';\n      input: asUITool<TOOL>['input'];\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved: false;\n        reason?: string;\n      };\n    }\n);\n\nexport type ToolUIPart<TOOLS extends UITools = UITools> = ValueOf<{\n  [NAME in keyof TOOLS & string]: {\n    type: `tool-${NAME}`;\n  } & UIToolInvocation<TOOLS[NAME]>;\n}>;\n\nexport type DynamicToolUIPart = {\n  type: 'dynamic-tool';\n\n  /**\n   * Name of the tool that is being called.\n   */\n  toolName: string;\n\n  /**\n   * ID of the tool call.\n   */\n  toolCallId: string;\n  title?: string;\n  toolMetadata?: JSONObject;\n\n  /**\n   * Whether the tool call was executed by the provider.\n   */\n  providerExecuted?: boolean;\n} & (\n  | {\n      state: 'input-streaming';\n      input: unknown | undefined;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval?: never;\n    }\n  | {\n      state: 'input-available';\n      input: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval?: never;\n    }\n  | {\n      state: 'approval-requested';\n      input: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved?: never;\n        reason?: never;\n      };\n    }\n  | {\n      state: 'approval-responded';\n      input: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved: boolean;\n        reason?: string;\n      };\n    }\n  | {\n      state: 'output-available';\n      input: unknown;\n      output: unknown;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      resultProviderMetadata?: ProviderMetadata;\n      preliminary?: boolean;\n      approval?: {\n        id: string;\n        approved: true;\n        reason?: string;\n      };\n    }\n  | {\n      state: 'output-error'; // TODO AI SDK 6: change to 'error' state\n      input: unknown;\n      output?: never;\n      errorText: string;\n      callProviderMetadata?: ProviderMetadata;\n      resultProviderMetadata?: ProviderMetadata;\n      approval?: {\n        id: string;\n        approved: true;\n        reason?: string;\n      };\n    }\n  | {\n      state: 'output-denied';\n      input: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved: false;\n        reason?: string;\n      };\n    }\n);\n\n/**\n * Type guard to check if a message part is a text part.\n */\nexport function isTextUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is TextUIPart {\n  return part.type === 'text';\n}\n\n/**\n * Type guard to check if a message part is a file part.\n */\nexport function isFileUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is FileUIPart {\n  return part.type === 'file';\n}\n\n/**\n * Type guard to check if a message part is a reasoning part.\n */\nexport function isReasoningUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is ReasoningUIPart {\n  return part.type === 'reasoning';\n}\n\n/**\n * Check if a message part is a static tool part.\n *\n * Static tools are tools for which the types are known at development time.\n */\nexport function isStaticToolUIPart<TOOLS extends UITools>(\n  part: UIMessagePart<UIDataTypes, TOOLS>,\n): part is ToolUIPart<TOOLS> {\n  return part.type.startsWith('tool-');\n}\n\n/**\n * Check if a message part is a dynamic tool part.\n *\n * Dynamic tools are tools for which the input and output types are unknown.\n */\nexport function isDynamicToolUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is DynamicToolUIPart {\n  return part.type === 'dynamic-tool';\n}\n\n/**\n * Check if a message part is a tool part.\n *\n * Tool parts are either static or dynamic tools.\n *\n * Use `isStaticToolUIPart` or `isDynamicToolUIPart` to check the type of the tool.\n */\nexport function isToolUIPart<TOOLS extends UITools>(\n  part: UIMessagePart<UIDataTypes, TOOLS>,\n): part is ToolUIPart<TOOLS> | DynamicToolUIPart {\n  return isStaticToolUIPart(part) || isDynamicToolUIPart(part);\n}\n\n/**\n * @deprecated Use isToolUIPart instead.\n */\nexport const isToolOrDynamicToolUIPart = isToolUIPart;\n\n/**\n * Returns the name of the static tool.\n *\n * The possible values are the keys of the tool set.\n */\nexport function getStaticToolName<TOOLS extends UITools>(\n  part: ToolUIPart<TOOLS>,\n): keyof TOOLS {\n  return part.type.split('-').slice(1).join('-') as keyof TOOLS;\n}\n\n/**\n * Returns the name of the tool (static or dynamic).\n *\n * This function will not restrict the name to the keys of the tool set.\n * If you need to restrict the name to the keys of the tool set, use `getStaticToolName` instead.\n */\nexport function getToolName(\n  part: ToolUIPart<UITools> | DynamicToolUIPart,\n): string {\n  return isDynamicToolUIPart(part) ? part.toolName : getStaticToolName(part);\n}\n\n/**\n * @deprecated Use getToolName instead.\n */\nexport const getToolOrDynamicToolName = getToolName;\n\nexport type InferUIMessageMetadata<T extends UIMessage> =\n  T extends UIMessage<infer METADATA> ? METADATA : unknown;\n\nexport type InferUIMessageData<T extends UIMessage> =\n  T extends UIMessage<unknown, infer DATA_TYPES> ? DATA_TYPES : UIDataTypes;\n\nexport type InferUIMessageTools<T extends UIMessage> =\n  T extends UIMessage<unknown, UIDataTypes, infer TOOLS> ? TOOLS : UITools;\n\nexport type InferUIMessageToolOutputs<UI_MESSAGE extends UIMessage> =\n  InferUIMessageTools<UI_MESSAGE>[keyof InferUIMessageTools<UI_MESSAGE>]['output'];\n\nexport type InferUIMessageToolCall<UI_MESSAGE extends UIMessage> =\n  | ValueOf<{\n      [NAME in keyof InferUIMessageTools<UI_MESSAGE>]: ToolCall<\n        NAME & string,\n        InferUIMessageTools<UI_MESSAGE>[NAME] extends { input: infer INPUT }\n          ? INPUT\n          : never\n      > & { dynamic?: false };\n    }>\n  | (ToolCall<string, unknown> & { dynamic: true });\n\nexport type InferUIMessagePart<UI_MESSAGE extends UIMessage> = UIMessagePart<\n  InferUIMessageData<UI_MESSAGE>,\n  InferUIMessageTools<UI_MESSAGE>\n>;\n", "import {\n  createStreamingUIMessageState,\n  processUIMessageStream,\n  type StreamingUIMessageState,\n} from '../ui/process-ui-message-stream';\nimport type { UIMessage } from '../ui/ui-messages';\nimport type { ErrorHandler } from '../util/error-handler';\nimport type { InferUIMessageChunk, UIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamOnFinishCallback } from './ui-message-stream-on-finish-callback';\nimport type { UIMessageStreamOnStepFinishCallback } from './ui-message-stream-on-step-finish-callback';\n\nexport function handleUIMessageStreamFinish<UI_MESSAGE extends UIMessage>({\n  messageId,\n  originalMessages = [],\n  onStepFinish,\n  onFinish,\n  onError,\n  stream,\n}: {\n  stream: ReadableStream<InferUIMessageChunk<UI_MESSAGE>>;\n\n  /**\n   * The message ID to use for the response message.\n   * If not provided, no id will be set for the response message.\n   */\n  messageId?: string;\n\n  /**\n   * The original messages.\n   */\n  originalMessages?: UI_MESSAGE[];\n\n  onError: ErrorHandler;\n\n  /**\n   * Callback that is called when each step finishes during multi-step agent runs.\n   */\n  onStepFinish?: UIMessageStreamOnStepFinishCallback<UI_MESSAGE>;\n\n  onFinish?: UIMessageStreamOnFinishCallback<UI_MESSAGE>;\n}): ReadableStream<InferUIMessageChunk<UI_MESSAGE>> {\n  // last message is only relevant for assistant messages\n  let lastMessage: UI_MESSAGE | undefined =\n    originalMessages?.[originalMessages.length - 1];\n  if (lastMessage?.role !== 'assistant') {\n    lastMessage = undefined;\n  } else {\n    // appending to the last message, so we need to use the same id\n    messageId = lastMessage.id;\n  }\n\n  let isAborted = false;\n\n  const idInjectedStream = stream.pipeThrough(\n    new TransformStream<\n      InferUIMessageChunk<UI_MESSAGE>,\n      InferUIMessageChunk<UI_MESSAGE>\n    >({\n      transform(chunk, controller) {\n        // when there is no messageId in the start chunk,\n        // but the user checked for persistence,\n        // inject the messageId into the chunk\n        if (chunk.type === 'start') {\n          const startChunk = chunk as UIMessageChunk & { type: 'start' };\n          if (startChunk.messageId == null && messageId != null) {\n            startChunk.messageId = messageId;\n          }\n        }\n\n        if (chunk.type === 'abort') {\n          isAborted = true;\n        }\n\n        controller.enqueue(chunk);\n      },\n    }),\n  );\n\n  // Only process the stream if we need to track state for callbacks\n  if (onFinish == null && onStepFinish == null) {\n    return idInjectedStream;\n  }\n\n  const state = createStreamingUIMessageState<UI_MESSAGE>({\n    lastMessage: lastMessage\n      ? (structuredClone(lastMessage) as UI_MESSAGE)\n      : undefined,\n    messageId: messageId ?? '', // will be overridden by the stream\n  });\n\n  const runUpdateMessageJob = async (\n    job: (options: {\n      state: StreamingUIMessageState<UI_MESSAGE>;\n      write: () => void;\n    }) => Promise<void>,\n  ) => {\n    await job({ state, write: () => {} });\n  };\n\n  let finishCalled = false;\n\n  const callOnFinish = async () => {\n    if (finishCalled || !onFinish) {\n      return;\n    }\n    finishCalled = true;\n\n    const isContinuation = state.message.id === lastMessage?.id;\n    await onFinish({\n      isAborted,\n      isContinuation,\n      responseMessage: state.message as UI_MESSAGE,\n      messages: [\n        ...(isContinuation ? originalMessages.slice(0, -1) : originalMessages),\n        state.message,\n      ] as UI_MESSAGE[],\n      finishReason: state.finishReason,\n    });\n  };\n\n  const callOnStepFinish = async () => {\n    if (!onStepFinish) {\n      return;\n    }\n\n    const isContinuation = state.message.id === lastMessage?.id;\n\n    try {\n      await onStepFinish({\n        isContinuation,\n        responseMessage: structuredClone(state.message) as UI_MESSAGE,\n        messages: [\n          ...(isContinuation\n            ? originalMessages.slice(0, -1)\n            : originalMessages),\n          structuredClone(state.message),\n        ] as UI_MESSAGE[],\n      });\n    } catch (error) {\n      onError(error);\n    }\n  };\n\n  return processUIMessageStream<UI_MESSAGE>({\n    stream: idInjectedStream,\n    runUpdateMessageJob,\n    onError,\n  }).pipeThrough(\n    new TransformStream<\n      InferUIMessageChunk<UI_MESSAGE>,\n      InferUIMessageChunk<UI_MESSAGE>\n    >({\n      async transform(chunk, controller) {\n        if (chunk.type === 'finish-step') {\n          await callOnStepFinish();\n        }\n\n        controller.enqueue(chunk);\n      },\n      // @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility\n      async cancel() {\n        await callOnFinish();\n      },\n\n      async flush() {\n        await callOnFinish();\n      },\n    }),\n  );\n}\n", "import type { ServerResponse } from 'node:http';\nimport { prepareHeaders } from '../util/prepare-headers';\nimport { writeToServerResponse } from '../util/write-to-server-response';\nimport { JsonToSseTransformStream } from './json-to-sse-transform-stream';\nimport { UI_MESSAGE_STREAM_HEADERS } from './ui-message-stream-headers';\nimport type { UIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamResponseInit } from './ui-message-stream-response-init';\n\n/**\n * Pipes a UI message stream to a Node.js ServerResponse object.\n * The stream is transformed to Server-Sent Events (SSE) format.\n *\n * @param options.response - The Node.js ServerResponse object to write to.\n * @param options.status - The HTTP status code for the response.\n * @param options.statusText - The HTTP status text for the response.\n * @param options.headers - Additional HTTP headers to include in the response.\n * @param options.stream - The UI message chunk stream to send.\n * @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently.\n */\nexport function pipeUIMessageStreamToResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  stream,\n  consumeSseStream,\n}: {\n  response: ServerResponse;\n  stream: ReadableStream<UIMessageChunk>;\n} & UIMessageStreamResponseInit): void {\n  let sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n\n  // when the consumeSseStream is provided, we need to tee the stream\n  // and send the second part to the consumeSseStream function\n  // so that it can be consumed by the client independently\n  if (consumeSseStream) {\n    const [stream1, stream2] = sseStream.tee();\n    sseStream = stream1;\n    consumeSseStream({ stream: stream2 }); // no await (do not block the response)\n  }\n\n  writeToServerResponse({\n    response,\n    status,\n    statusText,\n    headers: Object.fromEntries(\n      prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS).entries(),\n    ),\n    stream: sseStream.pipeThrough(new TextEncoderStream()),\n  });\n}\n", "/**\n * A type that combines AsyncIterable and ReadableStream.\n * This allows a ReadableStream to be consumed using for-await-of syntax.\n */\nexport type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;\n\n/**\n * Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.\n * This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.\n *\n * @template T The type of the stream's chunks.\n * @param source The source ReadableStream to wrap.\n * @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.\n */\nexport function createAsyncIterableStream<T>(\n  source: ReadableStream<T>,\n): AsyncIterableStream<T> {\n  // Pipe through a TransformStream to ensure a fresh, unlocked stream.\n  const stream = source.pipeThrough(new TransformStream<T, T>());\n\n  /**\n   * Implements the async iterator protocol for the stream.\n   * Ensures proper cleanup (cancelling and releasing the reader) on completion, early exit, or error.\n   */\n  (stream as AsyncIterableStream<T>)[Symbol.asyncIterator] = function (\n    this: ReadableStream<T>,\n  ): AsyncIterator<T> {\n    const reader = this.getReader();\n\n    let finished = false;\n\n    /**\n     * Cleans up the reader by cancelling and releasing the lock.\n     */\n    async function cleanup(cancelStream: boolean) {\n      if (finished) return;\n\n      finished = true;\n      try {\n        if (cancelStream) {\n          await reader.cancel?.();\n        }\n      } finally {\n        try {\n          reader.releaseLock();\n        } catch {}\n      }\n    }\n\n    return {\n      /**\n       * Reads the next chunk from the stream.\n       * @returns A promise resolving to the next IteratorResult.\n       */\n      async next(): Promise<IteratorResult<T>> {\n        if (finished) {\n          return { done: true, value: undefined };\n        }\n\n        const { done, value } = await reader.read();\n\n        if (done) {\n          await cleanup(true);\n          return { done: true, value: undefined };\n        }\n\n        return { done: false, value };\n      },\n\n      /**\n       * May be called on early exit (e.g., break from for-await) or after completion.\n       * Ensures the stream is cancelled and resources are released.\n       * @returns A promise resolving to a completed IteratorResult.\n       */\n      async return(): Promise<IteratorResult<T>> {\n        await cleanup(true);\n        return { done: true, value: undefined };\n      },\n\n      /**\n       * Called on early exit with error.\n       * Ensures the stream is cancelled and resources are released, then rethrows the error.\n       * @param err The error to throw.\n       * @returns A promise that rejects with the provided error.\n       */\n      async throw(err: unknown): Promise<IteratorResult<T>> {\n        await cleanup(true);\n        throw err;\n      },\n    };\n  };\n\n  return stream as AsyncIterableStream<T>;\n}\n", "/**\n * Consumes a ReadableStream until it's fully read.\n *\n * This function reads the stream chunk by chunk until the stream is exhausted.\n * It doesn't process or return the data from the stream; it simply ensures\n * that the entire stream is read.\n *\n * @param options - The options for consuming the stream.\n * @param options.stream - The ReadableStream to be consumed.\n * @param options.onError - Optional callback to handle errors that occur during consumption.\n * @returns A promise that resolves when the stream is fully consumed.\n */\nexport async function consumeStream({\n  stream,\n  onError,\n}: {\n  stream: ReadableStream;\n  onError?: (error: unknown) => void;\n}): Promise<void> {\n  const reader = stream.getReader();\n  try {\n    while (true) {\n      const { done } = await reader.read();\n      if (done) break;\n    }\n  } catch (error) {\n    onError?.(error);\n  } finally {\n    reader.releaseLock();\n  }\n}\n", "import type { ErrorHandler } from './error-handler';\n\n/**\n * Creates a Promise with externally accessible resolve and reject functions.\n *\n * @template T - The type of the value that the Promise will resolve to.\n * @returns An object containing:\n *   - promise: A Promise that can be resolved or rejected externally.\n *   - resolve: A function to resolve the Promise with a value of type T.\n *   - reject: A function to reject the Promise with an error.\n */\nexport function createResolvablePromise<T = any>(): {\n  promise: Promise<T>;\n  resolve: (value: T) => void;\n  reject: ErrorHandler;\n} {\n  let resolve: (value: T) => void;\n  let reject: ErrorHandler;\n\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n\n  return {\n    promise,\n    resolve: resolve!,\n    reject: reject!,\n  };\n}\n", "import { createResolvablePromise } from './create-resolvable-promise';\n\n/**\n * Creates a stitchable stream that can pipe one stream at a time.\n *\n * @template T - The type of values emitted by the streams.\n * @returns {Object} An object containing the stitchable stream and control methods.\n */\nexport function createStitchableStream<T>(): {\n  stream: ReadableStream<T>;\n  addStream: (innerStream: ReadableStream<T>) => void;\n  close: () => void;\n  terminate: () => void;\n} {\n  let innerStreamReaders: ReadableStreamDefaultReader<T>[] = [];\n  let controller: ReadableStreamDefaultController<T> | null = null;\n  let isClosed = false;\n  let waitForNewStream = createResolvablePromise<void>();\n\n  const terminate = () => {\n    isClosed = true;\n    waitForNewStream.resolve();\n\n    innerStreamReaders.forEach(reader => reader.cancel());\n    innerStreamReaders = [];\n    controller?.close();\n  };\n\n  const processPull = async () => {\n    // Case 1: Outer stream is closed and no more inner streams\n    if (isClosed && innerStreamReaders.length === 0) {\n      controller?.close();\n      return;\n    }\n\n    // Case 2: No inner streams available, but outer stream is open\n    // wait for a new inner stream to be added or the outer stream to close\n    if (innerStreamReaders.length === 0) {\n      waitForNewStream = createResolvablePromise<void>();\n      await waitForNewStream.promise;\n      return processPull();\n    }\n\n    try {\n      const { value, done } = await innerStreamReaders[0].read();\n\n      if (done) {\n        // Case 3: Current inner stream is done\n        innerStreamReaders.shift(); // Remove the finished stream\n\n        if (innerStreamReaders.length === 0 && isClosed) {\n          // when closed and no more inner streams, stop pulling\n          controller?.close();\n        } else {\n          // continue pulling from the next stream\n          await processPull();\n        }\n      } else {\n        // Case 4: Current inner stream returns an item\n        controller?.enqueue(value);\n      }\n    } catch (error) {\n      // Case 5: Current inner stream throws an error\n      controller?.error(error);\n      innerStreamReaders.shift(); // Remove the errored stream\n      terminate(); // we have errored, terminate all streams\n    }\n  };\n\n  return {\n    stream: new ReadableStream<T>({\n      start(controllerParam) {\n        controller = controllerParam;\n      },\n      pull: processPull,\n      async cancel() {\n        for (const reader of innerStreamReaders) {\n          await reader.cancel();\n        }\n        innerStreamReaders = [];\n        isClosed = true;\n      },\n    }),\n    addStream: (innerStream: ReadableStream<T>) => {\n      if (isClosed) {\n        throw new Error('Cannot add inner stream: outer stream is closed');\n      }\n\n      innerStreamReaders.push(innerStream.getReader());\n      waitForNewStream.resolve();\n    },\n\n    /**\n     * Gracefully close the outer stream. This will let the inner streams\n     * finish processing and then close the outer stream.\n     */\n    close: () => {\n      isClosed = true;\n      waitForNewStream.resolve();\n\n      if (innerStreamReaders.length === 0) {\n        controller?.close();\n      }\n    },\n\n    /**\n     * Immediately close the outer stream. This will cancel all inner streams\n     * and close the outer stream.\n     */\n    terminate,\n  };\n}\n", "import type {\n  LanguageModelV3StreamPart,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  getErrorMessage,\n  type IdGenerator,\n  type ModelMessage,\n  type SystemModelMessage,\n} from '@ai-sdk/provider-utils';\nimport type { Tracer } from '@opentelemetry/api';\nimport { ToolCallNotFoundForApprovalError } from '../error/tool-call-not-found-for-approval-error';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport type {\n  FinishReason,\n  LanguageModelUsage,\n  ProviderMetadata,\n} from '../types';\nimport type { Source } from '../types/language-model';\nimport { asLanguageModelUsage } from '../types/usage';\nimport { executeToolCall } from './execute-tool-call';\nimport type {\n  StreamTextOnToolCallFinishCallback,\n  StreamTextOnToolCallStartCallback,\n} from './stream-text';\nimport {\n  DefaultGeneratedFileWithType,\n  type GeneratedFile,\n} from './generated-file';\nimport { isApprovalNeeded } from './is-approval-needed';\nimport { parseToolCall } from './parse-tool-call';\nimport type { ToolApprovalRequestOutput } from './tool-approval-request-output';\nimport type { TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type { TypedToolError } from './tool-error';\nimport type { TypedToolResult } from './tool-result';\nimport type { ToolSet } from './tool-set';\n\nexport type SingleRequestTextStreamPart<TOOLS extends ToolSet> =\n  // Text blocks:\n  | {\n      type: 'text-start';\n      providerMetadata?: ProviderMetadata;\n      id: string;\n    }\n  | {\n      type: 'text-delta';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n      delta: string;\n    }\n  | {\n      type: 'text-end';\n      providerMetadata?: ProviderMetadata;\n      id: string;\n    }\n\n  // Reasoning blocks:\n  | {\n      type: 'reasoning-start';\n      providerMetadata?: ProviderMetadata;\n      id: string;\n    }\n  | {\n      type: 'reasoning-delta';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n      delta: string;\n    }\n  | {\n      type: 'reasoning-end';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n\n  // Tool calls:\n  | {\n      type: 'tool-input-start';\n      id: string;\n      toolName: string;\n      providerMetadata?: ProviderMetadata;\n      dynamic?: boolean;\n      title?: string;\n    }\n  | {\n      type: 'tool-input-delta';\n      id: string;\n      delta: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'tool-input-end';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | ToolApprovalRequestOutput<TOOLS>\n\n  // Other types:\n  | ({ type: 'source' } & Source)\n  | { type: 'file'; file: GeneratedFile; providerMetadata?: ProviderMetadata } // different because of GeneratedFile object\n  | ({ type: 'tool-call' } & TypedToolCall<TOOLS>)\n  | ({ type: 'tool-result' } & TypedToolResult<TOOLS>)\n  | ({ type: 'tool-error' } & TypedToolError<TOOLS>)\n  | { type: 'stream-start'; warnings: SharedV3Warning[] }\n  | {\n      type: 'response-metadata';\n      id?: string;\n      timestamp?: Date;\n      modelId?: string;\n    }\n  | {\n      type: 'finish';\n      finishReason: FinishReason;\n      rawFinishReason: string | undefined;\n      usage: LanguageModelUsage;\n      providerMetadata?: ProviderMetadata;\n    }\n  | { type: 'error'; error: unknown }\n  | { type: 'raw'; rawValue: unknown };\n\nexport function runToolsTransformation<TOOLS extends ToolSet>({\n  tools,\n  generatorStream,\n  tracer,\n  telemetry,\n  system,\n  messages,\n  abortSignal,\n  repairToolCall,\n  experimental_context,\n  generateId,\n  stepNumber,\n  model,\n  onToolCallStart,\n  onToolCallFinish,\n}: {\n  tools: TOOLS | undefined;\n  generatorStream: ReadableStream<LanguageModelV3StreamPart>;\n  tracer: Tracer;\n  telemetry: TelemetrySettings | undefined;\n  system: string | SystemModelMessage | Array<SystemModelMessage> | undefined;\n  messages: ModelMessage[];\n  abortSignal: AbortSignal | undefined;\n  repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n  experimental_context: unknown;\n  generateId: IdGenerator;\n  stepNumber?: number;\n  model?: { provider: string; modelId: string };\n  onToolCallStart?:\n    | StreamTextOnToolCallStartCallback<TOOLS>\n    | Array<StreamTextOnToolCallStartCallback<TOOLS> | undefined | null>;\n  onToolCallFinish?:\n    | StreamTextOnToolCallFinishCallback<TOOLS>\n    | Array<StreamTextOnToolCallFinishCallback<TOOLS> | undefined | null>;\n}): ReadableStream<SingleRequestTextStreamPart<TOOLS>> {\n  // tool results stream\n  let toolResultsStreamController: ReadableStreamDefaultController<\n    SingleRequestTextStreamPart<TOOLS>\n  > | null = null;\n  const toolResultsStream = new ReadableStream<\n    SingleRequestTextStreamPart<TOOLS>\n  >({\n    start(controller) {\n      toolResultsStreamController = controller;\n    },\n  });\n\n  // keep track of outstanding tool results for stream closing:\n  const outstandingToolResults = new Set<string>();\n\n  // keep track of tool inputs for provider-side tool results\n  const toolInputs = new Map<string, unknown>();\n\n  // keep track of parsed tool calls so provider-emitted approval requests can reference them\n  const toolCallsByToolCallId = new Map<string, TypedToolCall<TOOLS>>();\n\n  let canClose = false;\n  let finishChunk:\n    | (SingleRequestTextStreamPart<TOOLS> & { type: 'finish' })\n    | undefined = undefined;\n\n  function attemptClose() {\n    // close the tool results controller if no more outstanding tool calls\n    if (canClose && outstandingToolResults.size === 0) {\n      // we delay sending the finish chunk until all tool results (incl. delayed ones)\n      // are received to ensure that the frontend receives tool results before a message\n      // finish event arrives.\n      if (finishChunk != null) {\n        toolResultsStreamController!.enqueue(finishChunk);\n      }\n\n      toolResultsStreamController!.close();\n    }\n  }\n\n  // forward stream\n  const forwardStream = new TransformStream<\n    LanguageModelV3StreamPart,\n    SingleRequestTextStreamPart<TOOLS>\n  >({\n    async transform(\n      chunk: LanguageModelV3StreamPart,\n      controller: TransformStreamDefaultController<\n        SingleRequestTextStreamPart<TOOLS>\n      >,\n    ) {\n      const chunkType = chunk.type;\n\n      switch (chunkType) {\n        // forward:\n        case 'stream-start':\n        case 'text-start':\n        case 'text-delta':\n        case 'text-end':\n        case 'reasoning-start':\n        case 'reasoning-delta':\n        case 'reasoning-end':\n        case 'tool-input-start':\n        case 'tool-input-delta':\n        case 'tool-input-end':\n        case 'source':\n        case 'response-metadata':\n        case 'error':\n        case 'raw': {\n          controller.enqueue(chunk);\n          break;\n        }\n\n        case 'file': {\n          controller.enqueue({\n            type: 'file',\n            file: new DefaultGeneratedFileWithType({\n              data: chunk.data,\n              mediaType: chunk.mediaType,\n            }),\n            ...(chunk.providerMetadata != null\n              ? { providerMetadata: chunk.providerMetadata }\n              : {}),\n          });\n          break;\n        }\n\n        case 'finish': {\n          finishChunk = {\n            type: 'finish',\n            finishReason: chunk.finishReason.unified,\n            rawFinishReason: chunk.finishReason.raw,\n            usage: asLanguageModelUsage(chunk.usage),\n            providerMetadata: chunk.providerMetadata,\n          };\n          break;\n        }\n\n        case 'tool-approval-request': {\n          const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n          if (toolCall == null) {\n            toolResultsStreamController!.enqueue({\n              type: 'error',\n              error: new ToolCallNotFoundForApprovalError({\n                toolCallId: chunk.toolCallId,\n                approvalId: chunk.approvalId,\n              }),\n            });\n            break;\n          }\n\n          controller.enqueue({\n            type: 'tool-approval-request',\n            approvalId: chunk.approvalId,\n            toolCall,\n          });\n          break;\n        }\n\n        // process tool call:\n        case 'tool-call': {\n          try {\n            const toolCall = await parseToolCall({\n              toolCall: chunk,\n              tools,\n              repairToolCall,\n              system,\n              messages,\n            });\n\n            toolCallsByToolCallId.set(toolCall.toolCallId, toolCall);\n            controller.enqueue(toolCall);\n\n            if (toolCall.invalid) {\n              toolResultsStreamController!.enqueue({\n                type: 'tool-error',\n                toolCallId: toolCall.toolCallId,\n                toolName: toolCall.toolName,\n                input: toolCall.input,\n                error: getErrorMessage(toolCall.error!),\n                dynamic: true,\n                title: toolCall.title,\n                ...(toolCall.toolMetadata != null\n                  ? { toolMetadata: toolCall.toolMetadata }\n                  : {}),\n              });\n              break;\n            }\n\n            const tool = tools?.[toolCall.toolName];\n\n            if (tool == null) {\n              // ignore tool calls for tools that are not available,\n              // e.g. provider-executed dynamic tools\n              break;\n            }\n\n            if (tool.onInputAvailable != null) {\n              await tool.onInputAvailable({\n                input: toolCall.input,\n                toolCallId: toolCall.toolCallId,\n                messages,\n                abortSignal,\n                experimental_context,\n              });\n            }\n\n            if (\n              await isApprovalNeeded({\n                tool,\n                toolCall,\n                messages,\n                experimental_context,\n              })\n            ) {\n              toolResultsStreamController!.enqueue({\n                type: 'tool-approval-request',\n                approvalId: generateId(),\n                toolCall,\n              });\n              break;\n            }\n\n            toolInputs.set(toolCall.toolCallId, toolCall.input);\n\n            // Only execute tools that are not provider-executed:\n            if (tool.execute != null && toolCall.providerExecuted !== true) {\n              const toolExecutionId = generateId(); // use our own id to guarantee uniqueness\n              outstandingToolResults.add(toolExecutionId);\n\n              // Note: we don't await the tool execution here (by leaving out 'await' on recordSpan),\n              // because we want to process the next chunk as soon as possible.\n              // This is important for the case where the tool execution takes a long time.\n              executeToolCall({\n                toolCall,\n                tools,\n                tracer,\n                telemetry,\n                messages,\n                abortSignal,\n                experimental_context,\n                stepNumber,\n                model,\n                onToolCallStart,\n                onToolCallFinish,\n                onPreliminaryToolResult: result => {\n                  toolResultsStreamController!.enqueue(result);\n                },\n              })\n                .then(result => {\n                  toolResultsStreamController!.enqueue(result);\n                })\n                .catch(error => {\n                  toolResultsStreamController!.enqueue({\n                    type: 'error',\n                    error,\n                  });\n                })\n                .finally(() => {\n                  outstandingToolResults.delete(toolExecutionId);\n                  attemptClose();\n                });\n            }\n          } catch (error) {\n            toolResultsStreamController!.enqueue({ type: 'error', error });\n          }\n\n          break;\n        }\n\n        case 'tool-result': {\n          const toolName = chunk.toolName as keyof TOOLS & string;\n          const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n\n          if (chunk.isError) {\n            toolResultsStreamController!.enqueue({\n              type: 'tool-error',\n              toolCallId: chunk.toolCallId,\n              toolName,\n              input: toolInputs.get(chunk.toolCallId),\n              providerExecuted: true,\n              error: chunk.result,\n              dynamic: chunk.dynamic,\n              ...(chunk.providerMetadata != null\n                ? { providerMetadata: chunk.providerMetadata }\n                : {}),\n              ...(toolCall?.toolMetadata != null\n                ? { toolMetadata: toolCall.toolMetadata }\n                : {}),\n            } as TypedToolError<TOOLS>);\n          } else {\n            controller.enqueue({\n              type: 'tool-result',\n              toolCallId: chunk.toolCallId,\n              toolName,\n              input: toolInputs.get(chunk.toolCallId),\n              output: chunk.result,\n              providerExecuted: true,\n              dynamic: chunk.dynamic,\n              ...(chunk.providerMetadata != null\n                ? { providerMetadata: chunk.providerMetadata }\n                : {}),\n              ...(toolCall?.toolMetadata != null\n                ? { toolMetadata: toolCall.toolMetadata }\n                : {}),\n            } as TypedToolResult<TOOLS>);\n          }\n          break;\n        }\n\n        default: {\n          const _exhaustiveCheck: never = chunkType;\n          throw new Error(`Unhandled chunk type: ${_exhaustiveCheck}`);\n        }\n      }\n    },\n\n    flush() {\n      canClose = true;\n      attemptClose();\n    },\n  });\n\n  // combine the generator stream and the tool results stream\n  return new ReadableStream<SingleRequestTextStreamPart<TOOLS>>({\n    async start(controller) {\n      // need to wait for both pipes so there are no dangling promises that\n      // can cause uncaught promise rejections when the stream is aborted\n      return Promise.all([\n        generatorStream.pipeThrough(forwardStream).pipeTo(\n          new WritableStream({\n            write(chunk) {\n              controller.enqueue(chunk);\n            },\n            close() {\n              // the generator stream controller is automatically closed when it's consumed\n            },\n          }),\n        ),\n        toolResultsStream.pipeTo(\n          new WritableStream({\n            write(chunk) {\n              controller.enqueue(chunk);\n            },\n            close() {\n              controller.close();\n            },\n          }),\n        ),\n      ]);\n    },\n  });\n}\n", "import {\n  generateId as generateIdFunc,\n  getErrorMessage,\n  type IdGenerator,\n} from '@ai-sdk/provider-utils';\nimport type { UIMessage } from '../ui/ui-messages';\nimport { handleUIMessageStreamFinish } from './handle-ui-message-stream-finish';\nimport type { InferUIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamOnFinishCallback } from './ui-message-stream-on-finish-callback';\nimport type { UIMessageStreamOnStepFinishCallback } from './ui-message-stream-on-step-finish-callback';\nimport type { UIMessageStreamWriter } from './ui-message-stream-writer';\n\n/**\n * Creates a UI message stream that can be used to send messages to the client.\n *\n * @param options.execute - A function that is called with a writer to write UI message chunks to the stream.\n * @param options.onError - A function that extracts an error message from an error. Defaults to `getErrorMessage`.\n * @param options.originalMessages - The original messages. If provided, persistence mode is assumed\n *   and a message ID is provided for the response message.\n * @param options.onStepFinish - A callback that is called when each step finishes. Useful for persisting intermediate messages.\n * @param options.onFinish - A callback that is called when the stream finishes.\n * @param options.generateId - A function that generates a unique ID. Defaults to the built-in ID generator.\n *\n * @returns A `ReadableStream` of UI message chunks.\n */\nexport function createUIMessageStream<UI_MESSAGE extends UIMessage>({\n  execute,\n  onError = getErrorMessage,\n  originalMessages,\n  onStepFinish,\n  onFinish,\n  generateId = generateIdFunc,\n}: {\n  execute: (options: {\n    writer: UIMessageStreamWriter<UI_MESSAGE>;\n  }) => Promise<void> | void;\n  onError?: (error: unknown) => string;\n\n  /**\n   * The original messages. If they are provided, persistence mode is assumed,\n   * and a message ID is provided for the response message.\n   */\n  originalMessages?: UI_MESSAGE[];\n\n  /**\n   * Callback that is called when each step finishes during multi-step agent runs.\n   */\n  onStepFinish?: UIMessageStreamOnStepFinishCallback<UI_MESSAGE>;\n\n  onFinish?: UIMessageStreamOnFinishCallback<UI_MESSAGE>;\n\n  generateId?: IdGenerator;\n}): ReadableStream<InferUIMessageChunk<UI_MESSAGE>> {\n  let controller!: ReadableStreamDefaultController<\n    InferUIMessageChunk<UI_MESSAGE>\n  >;\n\n  const ongoingStreamPromises: Promise<void>[] = [];\n\n  const stream = new ReadableStream({\n    start(controllerArg) {\n      controller = controllerArg;\n    },\n  });\n\n  function safeEnqueue(data: InferUIMessageChunk<UI_MESSAGE>) {\n    try {\n      controller.enqueue(data);\n    } catch (error) {\n      // suppress errors when the stream has been closed\n    }\n  }\n\n  try {\n    const result = execute({\n      writer: {\n        write(part: InferUIMessageChunk<UI_MESSAGE>) {\n          safeEnqueue(part);\n        },\n        merge(streamArg) {\n          ongoingStreamPromises.push(\n            (async () => {\n              const reader = streamArg.getReader();\n              while (true) {\n                const { done, value } = await reader.read();\n                if (done) break;\n                safeEnqueue(value);\n              }\n            })().catch(error => {\n              safeEnqueue({\n                type: 'error',\n                errorText: onError(error),\n              } as InferUIMessageChunk<UI_MESSAGE>);\n            }),\n          );\n        },\n        onError,\n      },\n    });\n\n    if (result) {\n      ongoingStreamPromises.push(\n        result.catch(error => {\n          safeEnqueue({\n            type: 'error',\n            errorText: onError(error),\n          } as InferUIMessageChunk<UI_MESSAGE>);\n        }),\n      );\n    }\n  } catch (error) {\n    safeEnqueue({\n      type: 'error',\n      errorText: onError(error),\n    } as InferUIMessageChunk<UI_MESSAGE>);\n  }\n\n  // Wait until all ongoing streams are done. This approach enables merging\n  // streams even after execute has returned, as long as there is still an\n  // open merged stream. This is important to e.g. forward new streams and\n  // from callbacks.\n  const waitForStreams: Promise<void> = new Promise(async resolve => {\n    while (ongoingStreamPromises.length > 0) {\n      await ongoingStreamPromises.shift();\n    }\n    resolve();\n  });\n\n  waitForStreams.finally(() => {\n    try {\n      controller.close();\n    } catch (error) {\n      // suppress errors when the stream has been closed\n    }\n  });\n\n  return handleUIMessageStreamFinish<UI_MESSAGE>({\n    stream,\n    messageId: generateId(),\n    originalMessages,\n    onStepFinish,\n    onFinish,\n    onError,\n  });\n}\n", "import type { UIMessage } from '../ui/ui-messages';\nimport type { UIMessageChunk } from './ui-message-chunks';\nimport {\n  createStreamingUIMessageState,\n  processUIMessageStream,\n  type StreamingUIMessageState,\n} from '../ui/process-ui-message-stream';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport { consumeStream } from '../util/consume-stream';\n\n/**\n * Transforms a stream of `UIMessageChunk`s into an `AsyncIterableStream` of `UIMessage`s.\n *\n * @param options.message - The last assistant message to use as a starting point when the conversation is resumed. Otherwise undefined.\n * @param options.stream - The stream of `UIMessageChunk`s to read.\n * @param options.terminateOnError - Whether to terminate the stream if an error occurs.\n * @param options.onError - A function that is called when an error occurs.\n *\n * @returns An `AsyncIterableStream` of `UIMessage`s. Each stream part is a different state of the same message\n * as it is being completed.\n */\nexport function readUIMessageStream<UI_MESSAGE extends UIMessage>({\n  message,\n  stream,\n  onError,\n  terminateOnError = false,\n}: {\n  message?: UI_MESSAGE;\n  stream: ReadableStream<UIMessageChunk>;\n  onError?: (error: unknown) => void;\n  terminateOnError?: boolean;\n}): AsyncIterableStream<UI_MESSAGE> {\n  let controller: ReadableStreamDefaultController<UI_MESSAGE> | undefined;\n  let hasErrored = false;\n\n  const outputStream = new ReadableStream<UI_MESSAGE>({\n    start(controllerParam) {\n      controller = controllerParam;\n    },\n  });\n\n  const state = createStreamingUIMessageState<UI_MESSAGE>({\n    messageId: message?.id ?? '',\n    lastMessage: message,\n  });\n\n  const handleError = (error: unknown) => {\n    onError?.(error);\n\n    if (!hasErrored && terminateOnError) {\n      hasErrored = true;\n      controller?.error(error);\n    }\n  };\n\n  consumeStream({\n    stream: processUIMessageStream({\n      stream,\n      runUpdateMessageJob(\n        job: (options: {\n          state: StreamingUIMessageState<UI_MESSAGE>;\n          write: () => void;\n        }) => Promise<void>,\n      ) {\n        return job({\n          state,\n          write: () => {\n            controller?.enqueue(structuredClone(state.message));\n          },\n        });\n      },\n      onError: handleError,\n    }),\n    onError: handleError,\n  }).finally(() => {\n    // Only close if no error occurred. Calling close() on an errored controller\n    // throws \"Invalid state: Controller is already closed\" TypeError.\n    if (!hasErrored) {\n      controller?.close();\n    }\n  });\n\n  return createAsyncIterableStream(outputStream);\n}\n", "import {\n  isNonNullable,\n  type AssistantContent,\n  type FilePart,\n  type ModelMessage,\n  type TextPart,\n  type ToolApprovalResponse,\n  type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport type { ToolSet } from '../generate-text/tool-set';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport { MessageConversionError } from '../prompt/message-conversion-error';\nimport {\n  getToolName,\n  isDataUIPart,\n  isFileUIPart,\n  isReasoningUIPart,\n  isTextUIPart,\n  isToolUIPart,\n  type DataUIPart,\n  type DynamicToolUIPart,\n  type FileUIPart,\n  type InferUIMessageData,\n  type InferUIMessageTools,\n  type ReasoningUIPart,\n  type TextUIPart,\n  type ToolUIPart,\n  type UIMessage,\n} from './ui-messages';\n\n/**\n * Converts an array of UI messages from useChat into an array of ModelMessages that can be used\n * with the AI functions (e.g. `streamText`, `generateText`).\n *\n * @param messages - The UI messages to convert.\n * @param options.tools - The tools to use.\n * @param options.ignoreIncompleteToolCalls - Whether to ignore incomplete tool calls. Default is `false`.\n * @param options.convertDataPart - Optional function to convert data parts to text or file model message parts. Returns `undefined` if the part should be ignored.\n *\n * @returns An array of ModelMessages.\n */\nexport async function convertToModelMessages<UI_MESSAGE extends UIMessage>(\n  messages: Array<Omit<UI_MESSAGE, 'id'>>,\n  options?: {\n    tools?: ToolSet;\n    ignoreIncompleteToolCalls?: boolean;\n    convertDataPart?: (\n      part: DataUIPart<InferUIMessageData<UI_MESSAGE>>,\n    ) => TextPart | FilePart | undefined;\n  },\n): Promise<ModelMessage[]> {\n  const modelMessages: ModelMessage[] = [];\n\n  if (options?.ignoreIncompleteToolCalls) {\n    messages = messages.map(message => ({\n      ...message,\n      parts: message.parts.filter(\n        part =>\n          !isToolUIPart(part) ||\n          (part.state !== 'input-streaming' &&\n            part.state !== 'input-available'),\n      ),\n    }));\n  }\n\n  for (const message of messages) {\n    switch (message.role) {\n      case 'system': {\n        const textParts = message.parts.filter(\n          (part): part is TextUIPart => part.type === 'text',\n        );\n\n        const providerMetadata = textParts.reduce((acc, part) => {\n          if (part.providerMetadata != null) {\n            return { ...acc, ...part.providerMetadata };\n          }\n          return acc;\n        }, {});\n\n        modelMessages.push({\n          role: 'system',\n          content: textParts.map(part => part.text).join(''),\n          ...(Object.keys(providerMetadata).length > 0\n            ? { providerOptions: providerMetadata }\n            : {}),\n        });\n        break;\n      }\n\n      case 'user': {\n        modelMessages.push({\n          role: 'user',\n          content: message.parts\n            .map((part): TextPart | FilePart | undefined => {\n              // Process text parts\n              if (isTextUIPart(part)) {\n                return {\n                  type: 'text' as const,\n                  text: part.text,\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                };\n              }\n\n              // Process file parts\n              if (isFileUIPart(part)) {\n                return {\n                  type: 'file' as const,\n                  mediaType: part.mediaType,\n                  filename: part.filename,\n                  data: part.url,\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                };\n              }\n\n              // Process data parts with converter if provided\n              if (isDataUIPart(part)) {\n                return options?.convertDataPart?.(\n                  part as DataUIPart<InferUIMessageData<UI_MESSAGE>>,\n                );\n              }\n            })\n            .filter(isNonNullable),\n        });\n\n        break;\n      }\n\n      case 'assistant': {\n        if (message.parts != null) {\n          let block: Array<\n            | TextUIPart\n            | ToolUIPart<InferUIMessageTools<UI_MESSAGE>>\n            | ReasoningUIPart\n            | FileUIPart\n            | DynamicToolUIPart\n            | DataUIPart<InferUIMessageData<UI_MESSAGE>>\n          > = [];\n\n          async function processBlock() {\n            if (block.length === 0) {\n              return;\n            }\n\n            const content: AssistantContent = [];\n\n            for (const part of block) {\n              if (isTextUIPart(part)) {\n                content.push({\n                  type: 'text' as const,\n                  text: part.text,\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                });\n              } else if (isFileUIPart(part)) {\n                content.push({\n                  type: 'file' as const,\n                  mediaType: part.mediaType,\n                  filename: part.filename,\n                  data: part.url,\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                });\n              } else if (isReasoningUIPart(part)) {\n                content.push({\n                  type: 'reasoning' as const,\n                  text: part.text,\n                  providerOptions: part.providerMetadata,\n                });\n              } else if (isToolUIPart(part)) {\n                const toolName = getToolName(part);\n\n                if (part.state !== 'input-streaming') {\n                  content.push({\n                    type: 'tool-call' as const,\n                    toolCallId: part.toolCallId,\n                    toolName,\n                    input:\n                      part.state === 'output-error'\n                        ? (part.input ??\n                          ('rawInput' in part ? part.rawInput : undefined))\n                        : part.input,\n                    providerExecuted: part.providerExecuted,\n                    ...(part.callProviderMetadata != null\n                      ? { providerOptions: part.callProviderMetadata }\n                      : {}),\n                  });\n\n                  if (part.approval != null) {\n                    content.push({\n                      type: 'tool-approval-request' as const,\n                      approvalId: part.approval.id,\n                      toolCallId: part.toolCallId,\n                    });\n                  }\n\n                  if (\n                    part.providerExecuted === true &&\n                    part.state !== 'approval-responded' &&\n                    (part.state === 'output-available' ||\n                      part.state === 'output-error')\n                  ) {\n                    const resultProviderMetadata =\n                      part.resultProviderMetadata ?? part.callProviderMetadata;\n\n                    content.push({\n                      type: 'tool-result',\n                      toolCallId: part.toolCallId,\n                      toolName,\n                      output: await createToolModelOutput({\n                        toolCallId: part.toolCallId,\n                        input: part.input,\n                        output:\n                          part.state === 'output-error'\n                            ? part.errorText\n                            : part.output,\n                        tool: options?.tools?.[toolName],\n                        errorMode:\n                          part.state === 'output-error' ? 'json' : 'none',\n                      }),\n                      ...(resultProviderMetadata != null\n                        ? { providerOptions: resultProviderMetadata }\n                        : {}),\n                    });\n                  }\n                }\n              } else if (isDataUIPart(part)) {\n                const dataPart = options?.convertDataPart?.(\n                  part as DataUIPart<InferUIMessageData<UI_MESSAGE>>,\n                );\n\n                if (dataPart != null) {\n                  content.push(dataPart);\n                }\n              } else {\n                const _exhaustiveCheck: never = part;\n                throw new Error(`Unsupported part: ${_exhaustiveCheck}`);\n              }\n            }\n\n            modelMessages.push({\n              role: 'assistant',\n              content,\n            });\n\n            // check if there are tool invocations with results in the block\n            // Include non-provider-executed tools, OR provider-executed tools with approval responses\n            const toolParts = block.filter(\n              part =>\n                isToolUIPart(part) &&\n                (part.providerExecuted !== true ||\n                  part.approval?.approved != null),\n            ) as (\n              | ToolUIPart<InferUIMessageTools<UI_MESSAGE>>\n              | DynamicToolUIPart\n            )[];\n\n            // tool message with tool results\n            if (toolParts.length > 0) {\n              {\n                const content: Array<ToolResultPart | ToolApprovalResponse> =\n                  [];\n                for (const toolPart of toolParts) {\n                  // add approval response for approved tool calls:\n                  if (toolPart.approval?.approved != null) {\n                    content.push({\n                      type: 'tool-approval-response' as const,\n                      approvalId: toolPart.approval.id,\n                      approved: toolPart.approval.approved,\n                      reason: toolPart.approval.reason,\n                      providerExecuted: toolPart.providerExecuted,\n                    });\n                  }\n\n                  // For provider-executed tools, the tool result is already in the\n                  // assistant content. Skip adding to tool message to avoid duplicates\n                  // (which would create orphaned function_call_output entries).\n                  if (toolPart.providerExecuted === true) {\n                    continue;\n                  }\n\n                  switch (toolPart.state) {\n                    case 'output-denied': {\n                      content.push({\n                        type: 'tool-result',\n                        toolCallId: toolPart.toolCallId,\n                        toolName: getToolName(toolPart),\n                        output: {\n                          type: 'error-text' as const,\n                          value:\n                            toolPart.approval.reason ??\n                            'Tool execution denied.',\n                        },\n                        ...(toolPart.callProviderMetadata != null\n                          ? { providerOptions: toolPart.callProviderMetadata }\n                          : {}),\n                      });\n                      break;\n                    }\n\n                    case 'output-error':\n                    case 'output-available': {\n                      const toolName = getToolName(toolPart);\n                      content.push({\n                        type: 'tool-result',\n                        toolCallId: toolPart.toolCallId,\n                        toolName,\n                        output: await createToolModelOutput({\n                          toolCallId: toolPart.toolCallId,\n                          input: toolPart.input,\n                          output:\n                            toolPart.state === 'output-error'\n                              ? toolPart.errorText\n                              : toolPart.output,\n                          tool: options?.tools?.[toolName],\n                          errorMode:\n                            toolPart.state === 'output-error' ? 'text' : 'none',\n                        }),\n                        ...(toolPart.callProviderMetadata != null\n                          ? { providerOptions: toolPart.callProviderMetadata }\n                          : {}),\n                      });\n                      break;\n                    }\n                  }\n                }\n\n                if (content.length > 0) {\n                  modelMessages.push({\n                    role: 'tool',\n                    content,\n                  });\n                }\n              }\n            }\n\n            // updates for next block\n            block = [];\n          }\n\n          for (const part of message.parts) {\n            if (\n              isTextUIPart(part) ||\n              isReasoningUIPart(part) ||\n              isFileUIPart(part) ||\n              isToolUIPart(part) ||\n              isDataUIPart(part)\n            ) {\n              block.push(part as (typeof block)[number]);\n            } else if (part.type === 'step-start') {\n              await processBlock();\n            }\n          }\n\n          await processBlock();\n\n          break;\n        }\n\n        break;\n      }\n\n      default: {\n        const _exhaustiveCheck: never = message.role;\n        throw new MessageConversionError({\n          originalMessage: message,\n          message: `Unsupported role: ${_exhaustiveCheck}`,\n        });\n      }\n    }\n  }\n\n  return modelMessages;\n}\n", "import {\n  TypeValidationContext,\n  TypeValidationError,\n  type JSONObject,\n} from '@ai-sdk/provider';\nimport {\n  lazySchema,\n  StandardSchemaV1,\n  validateTypes,\n  zodSchema,\n  type FlexibleSchema,\n  type Tool,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { InvalidArgumentError } from '../error';\nimport { jsonValueSchema } from '../types/json-value';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport type {\n  DataUIPart,\n  InferUIMessageData,\n  InferUIMessageTools,\n  ToolUIPart,\n  UIMessage,\n} from './ui-messages';\n\nconst toolMetadataSchema: z.ZodType<JSONObject> = z.record(\n  z.string(),\n  jsonValueSchema.optional(),\n);\n\nconst uiMessagesSchema = lazySchema(() =>\n  zodSchema(\n    z\n      .array(\n        z.object({\n          id: z.string(),\n          role: z.enum(['system', 'user', 'assistant']),\n          metadata: z.unknown().optional(),\n          parts: z\n            .array(\n              z.union([\n                z.object({\n                  type: z.literal('text'),\n                  text: z.string(),\n                  state: z.enum(['streaming', 'done']).optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('reasoning'),\n                  text: z.string(),\n                  state: z.enum(['streaming', 'done']).optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('source-url'),\n                  sourceId: z.string(),\n                  url: z.string(),\n                  title: z.string().optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('source-document'),\n                  sourceId: z.string(),\n                  mediaType: z.string(),\n                  title: z.string(),\n                  filename: z.string().optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('file'),\n                  mediaType: z.string(),\n                  filename: z.string().optional(),\n                  url: z.string(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('step-start'),\n                }),\n                z.object({\n                  type: z.string().startsWith('data-'),\n                  id: z.string().optional(),\n                  data: z.unknown(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('input-streaming'),\n                  input: z.unknown().optional(),\n                  providerExecuted: z.boolean().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  approval: z.never().optional(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('input-available'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.never().optional(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('approval-requested'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.never().optional(),\n                    reason: z.never().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('approval-responded'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.boolean(),\n                    reason: z.string().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-available'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.unknown(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  resultProviderMetadata: providerMetadataSchema.optional(),\n                  preliminary: z.boolean().optional(),\n                  approval: z\n                    .object({\n                      id: z.string(),\n                      approved: z.literal(true),\n                      reason: z.string().optional(),\n                    })\n                    .optional(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-error'),\n                  input: z.unknown(),\n                  rawInput: z.unknown().optional(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.string(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  resultProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z\n                    .object({\n                      id: z.string(),\n                      approved: z.literal(true),\n                      reason: z.string().optional(),\n                    })\n                    .optional(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-denied'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.literal(false),\n                    reason: z.string().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('input-streaming'),\n                  providerExecuted: z.boolean().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  input: z.unknown().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  approval: z.never().optional(),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('input-available'),\n                  providerExecuted: z.boolean().optional(),\n                  input: z.unknown(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.never().optional(),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('approval-requested'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.never().optional(),\n                    reason: z.never().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('approval-responded'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.boolean(),\n                    reason: z.string().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-available'),\n                  providerExecuted: z.boolean().optional(),\n                  input: z.unknown(),\n                  output: z.unknown(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  resultProviderMetadata: providerMetadataSchema.optional(),\n                  preliminary: z.boolean().optional(),\n                  approval: z\n                    .object({\n                      id: z.string(),\n                      approved: z.literal(true),\n                      reason: z.string().optional(),\n                    })\n                    .optional(),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-error'),\n                  providerExecuted: z.boolean().optional(),\n                  input: z.unknown(),\n                  rawInput: z.unknown().optional(),\n                  output: z.never().optional(),\n                  errorText: z.string(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  resultProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z\n                    .object({\n                      id: z.string(),\n                      approved: z.literal(true),\n                      reason: z.string().optional(),\n                    })\n                    .optional(),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-denied'),\n                  providerExecuted: z.boolean().optional(),\n                  input: z.unknown(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.literal(false),\n                    reason: z.string().optional(),\n                  }),\n                }),\n              ]),\n            )\n            .nonempty('Message must contain at least one part'),\n        }),\n      )\n      .nonempty('Messages array must not be empty'),\n  ),\n);\n\nexport type SafeValidateUIMessagesResult<UI_MESSAGE extends UIMessage> =\n  | {\n      success: true;\n      data: Array<UI_MESSAGE>;\n    }\n  | {\n      success: false;\n      error: Error;\n    };\n\n/**\n * Validates a list of UI messages like `validateUIMessages`,\n * but instead of throwing it returns `{ success: true, data }`\n * or `{ success: false, error }`.\n */\nexport async function safeValidateUIMessages<UI_MESSAGE extends UIMessage>({\n  messages,\n  metadataSchema,\n  dataSchemas,\n  tools,\n}: {\n  messages: unknown;\n  metadataSchema?: FlexibleSchema<UIMessage['metadata']>;\n  dataSchemas?: {\n    [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?: FlexibleSchema<\n      InferUIMessageData<UI_MESSAGE>[NAME]\n    >;\n  };\n  tools?: {\n    [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<\n      InferUIMessageTools<UI_MESSAGE>[NAME]['input'],\n      InferUIMessageTools<UI_MESSAGE>[NAME]['output']\n    >;\n  };\n}): Promise<SafeValidateUIMessagesResult<UI_MESSAGE>> {\n  try {\n    if (messages == null) {\n      return {\n        success: false,\n        error: new InvalidArgumentError({\n          parameter: 'messages',\n          value: messages,\n          message: 'messages parameter must be provided',\n        }),\n      };\n    }\n\n    const validatedMessages = await validateTypes({\n      value: messages,\n      schema: uiMessagesSchema,\n    });\n\n    if (metadataSchema) {\n      for (const [msgIdx, message] of validatedMessages.entries()) {\n        await validateTypes({\n          value: message.metadata,\n          schema: metadataSchema,\n          context: {\n            field: `messages[${msgIdx}].metadata`,\n            entityId: message.id,\n          },\n        });\n      }\n    }\n\n    if (dataSchemas || tools) {\n      for (const [msgIdx, message] of validatedMessages.entries()) {\n        for (const [partIdx, part] of message.parts.entries()) {\n          // Data part validation\n          if (dataSchemas && part.type.startsWith('data-')) {\n            const dataPart = part as DataUIPart<InferUIMessageData<UI_MESSAGE>>;\n            const dataName = dataPart.type.slice(5);\n            const dataSchema = dataSchemas[dataName];\n\n            if (!dataSchema) {\n              return {\n                success: false,\n                error: new TypeValidationError({\n                  value: dataPart.data,\n                  cause: `No data schema found for data part ${dataName}`,\n                  context: {\n                    field: `messages[${msgIdx}].parts[${partIdx}].data`,\n                    entityName: dataName,\n                    entityId: dataPart.id,\n                  },\n                }),\n              };\n            }\n\n            await validateTypes({\n              value: dataPart.data,\n              schema: dataSchema,\n              context: {\n                field: `messages[${msgIdx}].parts[${partIdx}].data`,\n                entityName: dataName,\n                entityId: dataPart.id,\n              },\n            });\n          }\n\n          // Tool part validation\n          if (tools && part.type.startsWith('tool-')) {\n            const toolPart = part as ToolUIPart<\n              InferUIMessageTools<UI_MESSAGE>\n            >;\n            const toolName = toolPart.type.slice(5);\n            const tool = tools[toolName];\n\n            if (\n              !tool &&\n              (toolPart.state === 'output-available' ||\n                toolPart.state === 'output-error' ||\n                toolPart.state === 'output-denied')\n            ) {\n              continue;\n            }\n\n            // TODO support dynamic tools\n            if (!tool) {\n              return {\n                success: false,\n                error: new TypeValidationError({\n                  value: toolPart.input,\n                  cause: `No tool schema found for tool part ${toolName}`,\n                  context: {\n                    field: `messages[${msgIdx}].parts[${partIdx}].input`,\n                    entityName: toolName,\n                    entityId: toolPart.toolCallId,\n                  },\n                }),\n              };\n            }\n\n            // Tool input validation\n            if (\n              toolPart.state === 'input-available' ||\n              toolPart.state === 'output-available' ||\n              (toolPart.state === 'output-error' &&\n                toolPart.input !== undefined)\n            ) {\n              await validateTypes({\n                value: toolPart.input,\n                schema: tool.inputSchema,\n                context: {\n                  field: `messages[${msgIdx}].parts[${partIdx}].input`,\n                  entityName: toolName,\n                  entityId: toolPart.toolCallId,\n                },\n              });\n            }\n\n            // Tool output validation\n            if (toolPart.state === 'output-available' && tool.outputSchema) {\n              await validateTypes({\n                value: toolPart.output,\n                schema: tool.outputSchema,\n                context: {\n                  field: `messages[${msgIdx}].parts[${partIdx}].output`,\n                  entityName: toolName,\n                  entityId: toolPart.toolCallId,\n                },\n              });\n            }\n          }\n        }\n      }\n    }\n\n    return {\n      success: true,\n      data: validatedMessages as Array<UI_MESSAGE>,\n    };\n  } catch (error) {\n    const err = error as Error;\n\n    return {\n      success: false,\n      error: err,\n    };\n  }\n}\n\n/**\n * Validates a list of UI messages.\n *\n * Metadata, data parts, and generic tool call structures are only validated if\n * the corresponding schemas are provided. Otherwise, they are assumed to be\n * valid.\n */\nexport async function validateUIMessages<UI_MESSAGE extends UIMessage>({\n  messages,\n  metadataSchema,\n  dataSchemas,\n  tools,\n}: {\n  messages: unknown;\n  metadataSchema?: FlexibleSchema<UIMessage['metadata']>;\n  dataSchemas?: {\n    [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?: FlexibleSchema<\n      InferUIMessageData<UI_MESSAGE>[NAME]\n    >;\n  };\n  tools?: {\n    [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<\n      InferUIMessageTools<UI_MESSAGE>[NAME]['input'],\n      InferUIMessageTools<UI_MESSAGE>[NAME]['output']\n    >;\n  };\n}): Promise<Array<UI_MESSAGE>> {\n  const response = await safeValidateUIMessages({\n    messages,\n    metadataSchema,\n    dataSchemas,\n    tools,\n  });\n\n  if (!response.success) throw response.error;\n\n  return response.data;\n}\n", "import type {\n  StreamTextTransform,\n  UIMessageStreamOptions,\n} from '../generate-text';\nimport type { Output } from '../generate-text/output';\nimport type { ToolSet } from '../generate-text/tool-set';\nimport type { TimeoutConfiguration } from '../prompt/call-settings';\nimport type { InferUIMessageChunk } from '../ui-message-stream';\nimport { convertToModelMessages } from '../ui/convert-to-model-messages';\nimport type { InferUITools, UIMessage } from '../ui/ui-messages';\nimport { validateUIMessages } from '../ui/validate-ui-messages';\nimport type { AsyncIterableStream } from '../util/async-iterable-stream';\nimport type { Agent } from './agent';\nimport type { ToolLoopAgentOnStepFinishCallback } from './tool-loop-agent-settings';\n\n/**\n * Runs the agent and stream the output as a UI message stream.\n *\n * @param agent - The agent to run.\n * @param uiMessages - The input UI messages.\n * @param abortSignal - The abort signal. Optional.\n * @param timeout - Timeout in milliseconds. Optional.\n * @param options - The options for the agent.\n * @param experimental_transform - The stream transformations. Optional.\n * @param onStepFinish - Callback that is called when each step is finished. Optional.\n *\n * @returns The UI message stream.\n */\nexport async function createAgentUIStream<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  OUTPUT extends Output = never,\n  MESSAGE_METADATA = unknown,\n>({\n  agent,\n  uiMessages,\n  options,\n  abortSignal,\n  timeout,\n  experimental_transform,\n  onStepFinish,\n  ...uiMessageStreamOptions\n}: {\n  agent: Agent<CALL_OPTIONS, TOOLS, OUTPUT>;\n  uiMessages: unknown[];\n  abortSignal?: AbortSignal;\n  timeout?: TimeoutConfiguration;\n  options?: CALL_OPTIONS;\n  experimental_transform?:\n    | StreamTextTransform<TOOLS>\n    | Array<StreamTextTransform<TOOLS>>;\n  onStepFinish?: ToolLoopAgentOnStepFinishCallback<TOOLS>;\n  // TODO `originalMessages` is part of this for bc, omit in v7\n} & UIMessageStreamOptions<\n  UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>\n>): Promise<\n  AsyncIterableStream<\n    InferUIMessageChunk<UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>>\n  >\n> {\n  const validatedMessages = await validateUIMessages<\n    UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>\n  >({\n    messages: uiMessages,\n    tools: agent.tools,\n  });\n\n  const modelMessages = await convertToModelMessages(validatedMessages, {\n    tools: agent.tools,\n  });\n\n  const result = await agent.stream({\n    prompt: modelMessages,\n    options: options as CALL_OPTIONS,\n    abortSignal,\n    timeout,\n    experimental_transform,\n    onStepFinish,\n  });\n\n  return result.toUIMessageStream({\n    ...uiMessageStreamOptions,\n    // TODO reading `originalMessages` is here for bc, always use `validatedMessages` in v7\n    originalMessages:\n      uiMessageStreamOptions.originalMessages ?? validatedMessages,\n  });\n}\n", "import type {\n  StreamTextTransform,\n  UIMessageStreamOptions,\n} from '../generate-text';\nimport type { Output } from '../generate-text/output';\nimport type { ToolSet } from '../generate-text/tool-set';\nimport type { TimeoutConfiguration } from '../prompt/call-settings';\nimport { createUIMessageStreamResponse } from '../ui-message-stream';\nimport type { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';\nimport type { InferUITools, UIMessage } from '../ui/ui-messages';\nimport type { Agent } from './agent';\nimport { createAgentUIStream } from './create-agent-ui-stream';\nimport type { ToolLoopAgentOnStepFinishCallback } from './tool-loop-agent-settings';\n\n/**\n * Runs the agent and returns a response object with a UI message stream.\n *\n * @param agent - The agent to run.\n * @param uiMessages - The input UI messages.\n * @param abortSignal - Abort signal. Optional.\n * @param timeout - Timeout in milliseconds. Optional.\n * @param options - The options for the agent. Optional.\n * @param experimental_transform - Stream transformations. Optional.\n * @param onStepFinish - Callback that is called when each step is finished. Optional.\n * @param headers - Additional headers for the response. Optional.\n * @param status - The status code for the response. Optional.\n * @param statusText - The status text for the response. Optional.\n * @param consumeSseStream - Whether to consume the SSE stream. Optional.\n *\n * @returns The response object.\n */\nexport async function createAgentUIStreamResponse<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  OUTPUT extends Output = never,\n  MESSAGE_METADATA = unknown,\n>({\n  headers,\n  status,\n  statusText,\n  consumeSseStream,\n  ...options\n}: {\n  agent: Agent<CALL_OPTIONS, TOOLS, OUTPUT>;\n  uiMessages: unknown[];\n  abortSignal?: AbortSignal;\n  timeout?: TimeoutConfiguration;\n  options?: CALL_OPTIONS;\n  experimental_transform?:\n    | StreamTextTransform<TOOLS>\n    | Array<StreamTextTransform<TOOLS>>;\n  onStepFinish?: ToolLoopAgentOnStepFinishCallback<TOOLS>;\n} & UIMessageStreamResponseInit &\n  UIMessageStreamOptions<\n    UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>\n  >): Promise<Response> {\n  return createUIMessageStreamResponse({\n    headers,\n    status,\n    statusText,\n    consumeSseStream,\n    stream: await createAgentUIStream(options),\n  });\n}\n", "import type { ServerResponse } from 'node:http';\nimport type {\n  StreamTextTransform,\n  UIMessageStreamOptions,\n} from '../generate-text';\nimport type { Output } from '../generate-text/output';\nimport type { ToolSet } from '../generate-text/tool-set';\nimport type { TimeoutConfiguration } from '../prompt/call-settings';\nimport { pipeUIMessageStreamToResponse } from '../ui-message-stream';\nimport type { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';\nimport type { InferUITools, UIMessage } from '../ui/ui-messages';\nimport type { Agent } from './agent';\nimport { createAgentUIStream } from './create-agent-ui-stream';\nimport type { ToolLoopAgentOnStepFinishCallback } from './tool-loop-agent-settings';\n\n/**\n * Pipes the agent UI message stream to a Node.js ServerResponse object.\n *\n * @param response - The Node.js ServerResponse object to pipe to.\n * @param agent - The agent to run.\n * @param uiMessages - The input UI messages.\n * @param abortSignal - Abort signal. Optional.\n * @param timeout - Timeout in milliseconds. Optional.\n * @param options - The options for the agent. Optional.\n * @param experimental_transform - Stream transformations. Optional.\n * @param onStepFinish - Callback that is called when each step is finished. Optional.\n * @param headers - Additional headers for the response. Optional.\n * @param status - The status code for the response. Optional.\n * @param statusText - The status text for the response. Optional.\n * @param consumeSseStream - Whether to consume the SSE stream. Optional.\n */\nexport async function pipeAgentUIStreamToResponse<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  OUTPUT extends Output = never,\n  MESSAGE_METADATA = unknown,\n>({\n  response,\n  headers,\n  status,\n  statusText,\n  consumeSseStream,\n  ...options\n}: {\n  response: ServerResponse;\n  agent: Agent<CALL_OPTIONS, TOOLS, OUTPUT>;\n  uiMessages: unknown[];\n  abortSignal?: AbortSignal;\n  timeout?: TimeoutConfiguration;\n  options?: CALL_OPTIONS;\n  experimental_transform?:\n    | StreamTextTransform<TOOLS>\n    | Array<StreamTextTransform<TOOLS>>;\n  onStepFinish?: ToolLoopAgentOnStepFinishCallback<TOOLS>;\n} & UIMessageStreamResponseInit &\n  UIMessageStreamOptions<\n    UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>\n  >): Promise<void> {\n  pipeUIMessageStreamToResponse({\n    response,\n    headers,\n    status,\n    statusText,\n    consumeSseStream,\n    stream: await createAgentUIStream(options),\n  });\n}\n", "import {\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveEmbeddingModel } from '../model/resolve-model';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport type { EmbeddingModel } from '../types';\nimport { prepareRetries } from '../util/prepare-retries';\nimport type { EmbedResult } from './embed-result';\nimport { VERSION } from '../version';\n\n/**\n * Embed a value using an embedding model. The type of the value is defined by the embedding model.\n *\n * @param model - The embedding model to use.\n * @param value - The value that should be embedded.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param experimental_telemetry - Optional telemetry configuration (experimental).\n *\n * @param providerOptions - Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n *\n * @returns A result object that contains the embedding, the value, and additional information.\n */\nexport async function embed({\n  model: modelArg,\n  value,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  experimental_telemetry: telemetry,\n}: {\n  /**\n   * The embedding model to use.\n   */\n  model: EmbeddingModel;\n\n  /**\n   * The value that should be embedded.\n   */\n  value: string;\n\n  /**\n   * Maximum number of retries per embedding model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Additional provider-specific options. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Optional telemetry configuration (experimental).\n   */\n  experimental_telemetry?: TelemetrySettings;\n}): Promise<EmbedResult> {\n  const model = resolveEmbeddingModel(modelArg);\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const baseTelemetryAttributes = getBaseTelemetryAttributes({\n    model: model,\n    telemetry,\n    headers: headersWithUserAgent,\n    settings: { maxRetries },\n  });\n\n  const tracer = getTracer(telemetry);\n\n  return recordSpan({\n    name: 'ai.embed',\n    attributes: selectTelemetryAttributes({\n      telemetry,\n      attributes: {\n        ...assembleOperationName({ operationId: 'ai.embed', telemetry }),\n        ...baseTelemetryAttributes,\n        'ai.value': { input: () => JSON.stringify(value) },\n      },\n    }),\n    tracer,\n    fn: async span => {\n      const { embedding, usage, warnings, response, providerMetadata } =\n        await retry(() =>\n          // nested spans to align with the embedMany telemetry data:\n          recordSpan({\n            name: 'ai.embed.doEmbed',\n            attributes: selectTelemetryAttributes({\n              telemetry,\n              attributes: {\n                ...assembleOperationName({\n                  operationId: 'ai.embed.doEmbed',\n                  telemetry,\n                }),\n                ...baseTelemetryAttributes,\n                // specific settings that only make sense on the outer level:\n                'ai.values': { input: () => [JSON.stringify(value)] },\n              },\n            }),\n            tracer,\n            fn: async doEmbedSpan => {\n              const modelResponse = await model.doEmbed({\n                values: [value],\n                abortSignal,\n                headers: headersWithUserAgent,\n                providerOptions,\n              });\n\n              const embedding = modelResponse.embeddings[0];\n              const usage = modelResponse.usage ?? { tokens: NaN };\n\n              doEmbedSpan.setAttributes(\n                await selectTelemetryAttributes({\n                  telemetry,\n                  attributes: {\n                    'ai.embeddings': {\n                      output: () =>\n                        modelResponse.embeddings.map(embedding =>\n                          JSON.stringify(embedding),\n                        ),\n                    },\n                    'ai.usage.tokens': usage.tokens,\n                  },\n                }),\n              );\n\n              return {\n                embedding,\n                usage,\n                warnings: modelResponse.warnings,\n                providerMetadata: modelResponse.providerMetadata,\n                response: modelResponse.response,\n              };\n            },\n          }),\n        );\n\n      span.setAttributes(\n        await selectTelemetryAttributes({\n          telemetry,\n          attributes: {\n            'ai.embedding': { output: () => JSON.stringify(embedding) },\n            'ai.usage.tokens': usage.tokens,\n          },\n        }),\n      );\n\n      logWarnings({ warnings, provider: model.provider, model: model.modelId });\n\n      return new DefaultEmbedResult({\n        value,\n        embedding,\n        usage,\n        warnings,\n        providerMetadata,\n        response,\n      });\n    },\n  });\n}\n\nclass DefaultEmbedResult implements EmbedResult {\n  readonly value: EmbedResult['value'];\n  readonly embedding: EmbedResult['embedding'];\n  readonly usage: EmbedResult['usage'];\n  readonly warnings: EmbedResult['warnings'];\n  readonly providerMetadata: EmbedResult['providerMetadata'];\n  readonly response: EmbedResult['response'];\n\n  constructor(options: {\n    value: EmbedResult['value'];\n    embedding: EmbedResult['embedding'];\n    usage: EmbedResult['usage'];\n    warnings: EmbedResult['warnings'];\n    providerMetadata?: EmbedResult['providerMetadata'];\n    response?: EmbedResult['response'];\n  }) {\n    this.value = options.value;\n    this.embedding = options.embedding;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.response = options.response;\n  }\n}\n", "import {\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveEmbeddingModel } from '../model/resolve-model';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport type { Embedding, EmbeddingModel, ProviderMetadata } from '../types';\nimport type { Warning } from '../types/warning';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { splitArray } from '../util/split-array';\nimport type { EmbedManyResult } from './embed-many-result';\nimport { VERSION } from '../version';\n\n/**\n * Embed several values using an embedding model. The type of the value is defined\n * by the embedding model.\n *\n * `embedMany` automatically splits large requests into smaller chunks if the model\n * has a limit on how many embeddings can be generated in a single call.\n *\n * @param model - The embedding model to use.\n * @param values - The values that should be embedded.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param maxParallelCalls - Maximum number of concurrent requests. Default: Infinity.\n *\n * @param experimental_telemetry - Optional telemetry configuration (experimental).\n *\n * @param providerOptions - Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n *\n * @returns A result object that contains the embeddings, the value, and additional information.\n */\nexport async function embedMany({\n  model: modelArg,\n  values,\n  maxParallelCalls = Infinity,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  providerOptions,\n  experimental_telemetry: telemetry,\n}: {\n  /**\n   * The embedding model to use.\n   */\n  model: EmbeddingModel;\n\n  /**\n   * The values that should be embedded.\n   */\n  values: Array<string>;\n\n  /**\n   * Maximum number of retries per embedding model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Optional telemetry configuration (experimental).\n   */\n  experimental_telemetry?: TelemetrySettings;\n\n  /**\n   * Additional provider-specific options. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of concurrent requests.\n   *\n   * @default Infinity\n   */\n  maxParallelCalls?: number;\n}): Promise<EmbedManyResult> {\n  const model = resolveEmbeddingModel(modelArg);\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const baseTelemetryAttributes = getBaseTelemetryAttributes({\n    model,\n    telemetry,\n    headers: headersWithUserAgent,\n    settings: { maxRetries },\n  });\n\n  const tracer = getTracer(telemetry);\n\n  return recordSpan({\n    name: 'ai.embedMany',\n    attributes: selectTelemetryAttributes({\n      telemetry,\n      attributes: {\n        ...assembleOperationName({ operationId: 'ai.embedMany', telemetry }),\n        ...baseTelemetryAttributes,\n        // specific settings that only make sense on the outer level:\n        'ai.values': {\n          input: () => values.map(value => JSON.stringify(value)),\n        },\n      },\n    }),\n    tracer,\n    fn: async span => {\n      const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([\n        model.maxEmbeddingsPerCall,\n        model.supportsParallelCalls,\n      ]);\n\n      // the model has not specified limits on\n      // how many embeddings can be generated in a single call\n      if (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {\n        const { embeddings, usage, warnings, response, providerMetadata } =\n          await retry(() => {\n            // nested spans to align with the embedMany telemetry data:\n            return recordSpan({\n              name: 'ai.embedMany.doEmbed',\n              attributes: selectTelemetryAttributes({\n                telemetry,\n                attributes: {\n                  ...assembleOperationName({\n                    operationId: 'ai.embedMany.doEmbed',\n                    telemetry,\n                  }),\n                  ...baseTelemetryAttributes,\n                  // specific settings that only make sense on the outer level:\n                  'ai.values': {\n                    input: () => values.map(value => JSON.stringify(value)),\n                  },\n                },\n              }),\n              tracer,\n              fn: async doEmbedSpan => {\n                const modelResponse = await model.doEmbed({\n                  values,\n                  abortSignal,\n                  headers: headersWithUserAgent,\n                  providerOptions,\n                });\n\n                const embeddings = modelResponse.embeddings;\n                const usage = modelResponse.usage ?? { tokens: NaN };\n\n                doEmbedSpan.setAttributes(\n                  await selectTelemetryAttributes({\n                    telemetry,\n                    attributes: {\n                      'ai.embeddings': {\n                        output: () =>\n                          embeddings.map(embedding =>\n                            JSON.stringify(embedding),\n                          ),\n                      },\n                      'ai.usage.tokens': usage.tokens,\n                    },\n                  }),\n                );\n\n                return {\n                  embeddings,\n                  usage,\n                  warnings: modelResponse.warnings,\n                  providerMetadata: modelResponse.providerMetadata,\n                  response: modelResponse.response,\n                };\n              },\n            });\n          });\n\n        span.setAttributes(\n          await selectTelemetryAttributes({\n            telemetry,\n            attributes: {\n              'ai.embeddings': {\n                output: () =>\n                  embeddings.map(embedding => JSON.stringify(embedding)),\n              },\n              'ai.usage.tokens': usage.tokens,\n            },\n          }),\n        );\n\n        logWarnings({\n          warnings,\n          provider: model.provider,\n          model: model.modelId,\n        });\n\n        return new DefaultEmbedManyResult({\n          values,\n          embeddings,\n          usage,\n          warnings,\n          providerMetadata,\n          responses: [response],\n        });\n      }\n\n      // split the values into chunks that are small enough for the model:\n      const valueChunks = splitArray(values, maxEmbeddingsPerCall);\n\n      // serially embed the chunks:\n      const embeddings: Array<Embedding> = [];\n      const warnings: Array<Warning> = [];\n      const responses: Array<\n        | {\n            headers?: Record<string, string>;\n            body?: unknown;\n          }\n        | undefined\n      > = [];\n      let tokens = 0;\n      let providerMetadata: ProviderMetadata | undefined;\n\n      const parallelChunks = splitArray(\n        valueChunks,\n        supportsParallelCalls ? maxParallelCalls : 1,\n      );\n\n      for (const parallelChunk of parallelChunks) {\n        const results = await Promise.all(\n          parallelChunk.map(chunk => {\n            return retry(() => {\n              // nested spans to align with the embedMany telemetry data:\n              return recordSpan({\n                name: 'ai.embedMany.doEmbed',\n                attributes: selectTelemetryAttributes({\n                  telemetry,\n                  attributes: {\n                    ...assembleOperationName({\n                      operationId: 'ai.embedMany.doEmbed',\n                      telemetry,\n                    }),\n                    ...baseTelemetryAttributes,\n                    // specific settings that only make sense on the outer level:\n                    'ai.values': {\n                      input: () => chunk.map(value => JSON.stringify(value)),\n                    },\n                  },\n                }),\n                tracer,\n                fn: async doEmbedSpan => {\n                  const modelResponse = await model.doEmbed({\n                    values: chunk,\n                    abortSignal,\n                    headers: headersWithUserAgent,\n                    providerOptions,\n                  });\n\n                  const embeddings = modelResponse.embeddings;\n                  const usage = modelResponse.usage ?? { tokens: NaN };\n\n                  doEmbedSpan.setAttributes(\n                    await selectTelemetryAttributes({\n                      telemetry,\n                      attributes: {\n                        'ai.embeddings': {\n                          output: () =>\n                            embeddings.map(embedding =>\n                              JSON.stringify(embedding),\n                            ),\n                        },\n                        'ai.usage.tokens': usage.tokens,\n                      },\n                    }),\n                  );\n\n                  return {\n                    embeddings,\n                    usage,\n                    warnings: modelResponse.warnings,\n                    providerMetadata: modelResponse.providerMetadata,\n                    response: modelResponse.response,\n                  };\n                },\n              });\n            });\n          }),\n        );\n\n        for (const result of results) {\n          embeddings.push(...result.embeddings);\n          warnings.push(...result.warnings);\n          responses.push(result.response);\n          tokens += result.usage.tokens;\n          if (result.providerMetadata) {\n            if (!providerMetadata) {\n              providerMetadata = { ...result.providerMetadata };\n            } else {\n              for (const [providerName, metadata] of Object.entries(\n                result.providerMetadata,\n              )) {\n                providerMetadata[providerName] = {\n                  ...(providerMetadata[providerName] ?? {}),\n                  ...metadata,\n                };\n              }\n            }\n          }\n        }\n      }\n\n      span.setAttributes(\n        await selectTelemetryAttributes({\n          telemetry,\n          attributes: {\n            'ai.embeddings': {\n              output: () =>\n                embeddings.map(embedding => JSON.stringify(embedding)),\n            },\n            'ai.usage.tokens': tokens,\n          },\n        }),\n      );\n\n      logWarnings({\n        warnings,\n        provider: model.provider,\n        model: model.modelId,\n      });\n\n      return new DefaultEmbedManyResult({\n        values,\n        embeddings,\n        usage: { tokens },\n        warnings,\n        providerMetadata: providerMetadata,\n        responses,\n      });\n    },\n  });\n}\n\nclass DefaultEmbedManyResult implements EmbedManyResult {\n  readonly values: EmbedManyResult['values'];\n  readonly embeddings: EmbedManyResult['embeddings'];\n  readonly usage: EmbedManyResult['usage'];\n  readonly warnings: EmbedManyResult['warnings'];\n  readonly providerMetadata: EmbedManyResult['providerMetadata'];\n  readonly responses: EmbedManyResult['responses'];\n\n  constructor(options: {\n    values: EmbedManyResult['values'];\n    embeddings: EmbedManyResult['embeddings'];\n    usage: EmbedManyResult['usage'];\n    warnings: EmbedManyResult['warnings'];\n    providerMetadata?: EmbedManyResult['providerMetadata'];\n    responses?: EmbedManyResult['responses'];\n  }) {\n    this.values = options.values;\n    this.embeddings = options.embeddings;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.responses = options.responses;\n  }\n}\n", "/**\n * Splits an array into chunks of a specified size.\n *\n * @template T - The type of elements in the array.\n * @param {T[]} array - The array to split.\n * @param {number} chunkSize - The size of each chunk.\n * @returns {T[][]} - A new array containing the chunks.\n */\nexport function splitArray<T>(array: T[], chunkSize: number): T[][] {\n  if (chunkSize <= 0) {\n    throw new Error('chunkSize must be greater than 0');\n  }\n\n  const result = [];\n  for (let i = 0; i < array.length; i += chunkSize) {\n    result.push(array.slice(i, i + chunkSize));\n  }\n\n  return result;\n}\n", "import type {\n  ImageModelV3,\n  ImageModelV3CallOptions,\n  ImageModelV3File,\n  ImageModelV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport {\n  convertBase64ToUint8Array,\n  withUserAgentSuffix,\n  type DataContent,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoImageGeneratedError } from '../error/no-image-generated-error';\nimport {\n  DefaultGeneratedFile,\n  type GeneratedFile,\n} from '../generate-text/generated-file';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveImageModel } from '../model/resolve-model';\nimport type { ImageModel } from '../types/image-model';\nimport type { ImageModelResponseMetadata } from '../types/image-model-response-metadata';\nimport { addImageModelUsage, type ImageModelUsage } from '../types/usage';\nimport type { Warning } from '../types/warning';\nimport {\n  detectMediaType,\n  imageMediaTypeSignatures,\n} from '../util/detect-media-type';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type { GenerateImageResult } from './generate-image-result';\nimport { convertDataContentToUint8Array } from '../prompt/data-content';\nimport { splitDataUrl } from '../prompt/split-data-url';\n\nexport type GenerateImagePrompt =\n  | string\n  | {\n      images: Array<DataContent>;\n      text?: string;\n      mask?: DataContent;\n    };\n\n/**\n * Generates images using an image model.\n *\n * @param model - The image model to use.\n * @param prompt - The prompt that should be used to generate the image.\n * @param n - Number of images to generate. Default: 1.\n * @param maxImagesPerCall - Maximum number of images to generate in a single API call.\n * @param size - Size of the images to generate. Must have the format `{width}x{height}`.\n * @param aspectRatio - Aspect ratio of the images to generate. Must have the format `{width}:{height}`.\n * @param seed - Seed for the image generation.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @returns A result object that contains the generated images.\n */\nexport async function generateImage({\n  model: modelArg,\n  prompt: promptArg,\n  n = 1,\n  maxImagesPerCall,\n  size,\n  aspectRatio,\n  seed,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n}: {\n  /**\n   * The image model to use.\n   */\n  model: ImageModel;\n\n  /**\n   * The prompt that should be used to generate the image.\n   */\n  prompt: GenerateImagePrompt;\n\n  /**\n   * Number of images to generate.\n   */\n  n?: number;\n\n  /**\n   * Maximum number of images to generate in a single API call. If not provided, the model's default will be used.\n   */\n  maxImagesPerCall?: number;\n\n  /**\n   * Size of the images to generate. Must have the format `{width}x{height}`. If not provided, the default size will be used.\n   */\n  size?: `${number}x${number}`;\n\n  /**\n   * Aspect ratio of the images to generate. Must have the format `{width}:{height}`. If not provided, the default aspect ratio will be used.\n   */\n  aspectRatio?: `${number}:${number}`;\n\n  /**\n   * Seed for the image generation. If not provided, the default seed will be used.\n   */\n  seed?: number;\n\n  /**\n   * Additional provider-specific options that are passed through to the provider\n   * as body parameters.\n   *\n   * The outer record is keyed by the provider name, and the inner\n   * record is keyed by the provider-specific metadata key.\n   * ```ts\n   * {\n   * \"openai\": {\n   * \"style\": \"vivid\"\n   * }\n   * }\n   * ```\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of retries per image model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n}): Promise<GenerateImageResult> {\n  const model = resolveImageModel(modelArg);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  // default to 1 if the model has not specified limits on\n  // how many images can be generated in a single call\n  const maxImagesPerCallWithDefault =\n    maxImagesPerCall ?? (await invokeModelMaxImagesPerCall(model)) ?? 1;\n\n  // parallelize calls to the model:\n  const callCount = Math.ceil(n / maxImagesPerCallWithDefault);\n  const callImageCounts = Array.from({ length: callCount }, (_, i) => {\n    if (i < callCount - 1) {\n      return maxImagesPerCallWithDefault;\n    }\n\n    const remainder = n % maxImagesPerCallWithDefault;\n    return remainder === 0 ? maxImagesPerCallWithDefault : remainder;\n  });\n\n  const results = await Promise.all(\n    callImageCounts.map(async callImageCount =>\n      retry(() => {\n        const { prompt, files, mask } = normalizePrompt(promptArg);\n\n        return model.doGenerate({\n          prompt,\n          files,\n          mask,\n          n: callImageCount,\n          abortSignal,\n          headers: headersWithUserAgent,\n          size,\n          aspectRatio,\n          seed,\n          providerOptions: providerOptions ?? {},\n        });\n      }),\n    ),\n  );\n\n  // collect result images, warnings, and response metadata\n  const images: Array<DefaultGeneratedFile> = [];\n  const warnings: Array<Warning> = [];\n  const responses: Array<ImageModelResponseMetadata> = [];\n  const providerMetadata: ImageModelV3ProviderMetadata = {};\n  let totalUsage: ImageModelUsage = {\n    inputTokens: undefined,\n    outputTokens: undefined,\n    totalTokens: undefined,\n  };\n  for (const result of results) {\n    images.push(\n      ...result.images.map(\n        image =>\n          new DefaultGeneratedFile({\n            data: image,\n            mediaType:\n              detectMediaType({\n                data: image,\n                signatures: imageMediaTypeSignatures,\n              }) ?? 'image/png',\n          }),\n      ),\n    );\n    warnings.push(...result.warnings);\n\n    if (result.usage != null) {\n      totalUsage = addImageModelUsage(totalUsage, result.usage);\n    }\n\n    if (result.providerMetadata) {\n      for (const [providerName, metadata] of Object.entries<{\n        images: unknown;\n      }>(result.providerMetadata)) {\n        if (providerName === 'gateway') {\n          const currentEntry = providerMetadata[providerName];\n          if (currentEntry != null && typeof currentEntry === 'object') {\n            providerMetadata[providerName] = {\n              ...(currentEntry as object),\n              ...metadata,\n            } as ImageModelV3ProviderMetadata[string];\n          } else {\n            providerMetadata[providerName] =\n              metadata as ImageModelV3ProviderMetadata[string];\n          }\n          const imagesValue = (\n            providerMetadata[providerName] as { images?: unknown }\n          ).images;\n          if (Array.isArray(imagesValue) && imagesValue.length === 0) {\n            delete (providerMetadata[providerName] as { images?: unknown })\n              .images;\n          }\n        } else {\n          providerMetadata[providerName] ??= { images: [] };\n          providerMetadata[providerName].images.push(\n            ...result.providerMetadata[providerName].images,\n          );\n        }\n      }\n    }\n\n    responses.push(result.response);\n  }\n\n  logWarnings({ warnings, provider: model.provider, model: model.modelId });\n\n  if (!images.length) {\n    throw new NoImageGeneratedError({ responses });\n  }\n\n  return new DefaultGenerateImageResult({\n    images,\n    warnings,\n    responses,\n    providerMetadata,\n    usage: totalUsage,\n  });\n}\n\nclass DefaultGenerateImageResult implements GenerateImageResult {\n  readonly images: Array<GeneratedFile>;\n  readonly warnings: Array<Warning>;\n  readonly responses: Array<ImageModelResponseMetadata>;\n  readonly providerMetadata: ImageModelV3ProviderMetadata;\n  readonly usage: ImageModelUsage;\n\n  constructor(options: {\n    images: Array<GeneratedFile>;\n    warnings: Array<Warning>;\n    responses: Array<ImageModelResponseMetadata>;\n    providerMetadata: ImageModelV3ProviderMetadata;\n    usage: ImageModelUsage;\n  }) {\n    this.images = options.images;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = options.providerMetadata;\n    this.usage = options.usage;\n  }\n\n  get image() {\n    return this.images[0];\n  }\n}\n\nasync function invokeModelMaxImagesPerCall(model: ImageModelV3) {\n  const isFunction = model.maxImagesPerCall instanceof Function;\n\n  if (!isFunction) {\n    return model.maxImagesPerCall;\n  }\n\n  return model.maxImagesPerCall({\n    modelId: model.modelId,\n  });\n}\n\nfunction normalizePrompt(\n  prompt: GenerateImagePrompt,\n): Pick<ImageModelV3CallOptions, 'prompt' | 'files' | 'mask'> {\n  if (typeof prompt === 'string') {\n    return { prompt, files: undefined, mask: undefined };\n  }\n\n  return {\n    prompt: prompt.text,\n    files: prompt.images.map(toImageModelV3File),\n    mask: prompt.mask ? toImageModelV3File(prompt.mask) : undefined,\n  };\n}\n\nfunction toImageModelV3File(dataContent: DataContent): ImageModelV3File {\n  if (typeof dataContent === 'string' && dataContent.startsWith('http')) {\n    return {\n      type: 'url',\n      url: dataContent,\n    };\n  }\n\n  // Handle data URLs\n  if (typeof dataContent === 'string' && dataContent.startsWith('data:')) {\n    const { mediaType: dataUrlMediaType, base64Content } =\n      splitDataUrl(dataContent);\n\n    if (base64Content != null) {\n      const uint8Data = convertBase64ToUint8Array(base64Content);\n      return {\n        type: 'file',\n        data: uint8Data,\n        mediaType:\n          dataUrlMediaType ||\n          detectMediaType({\n            data: uint8Data,\n            signatures: imageMediaTypeSignatures,\n          }) ||\n          'image/png',\n      };\n    }\n  }\n\n  const uint8Data = convertDataContentToUint8Array(dataContent);\n  return {\n    type: 'file',\n    data: uint8Data,\n    mediaType:\n      detectMediaType({\n        data: uint8Data,\n        signatures: imageMediaTypeSignatures,\n      }) || 'image/png',\n  };\n}\n", "import type { GenerateImageResult } from './generate-image-result';\nimport { generateImage } from './generate-image';\n\nexport { generateImage } from './generate-image';\nexport type { GenerateImageResult } from './generate-image-result';\n\n// deprecated exports\n\n/**\n * @deprecated Use `generateImage` instead.\n */\nconst experimental_generateImage = generateImage;\nexport { experimental_generateImage };\n\n/**\n * @deprecated Use `GenerateImageResult` instead.\n */\ntype Experimental_GenerateImageResult = GenerateImageResult;\nexport type { Experimental_GenerateImageResult };\n", "import type { JSONValue } from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  withUserAgentSuffix,\n  type FlexibleSchema,\n  type InferSchema,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport { extractReasoningContent } from '../generate-text/extract-reasoning-content';\nimport { extractTextContent } from '../generate-text/extract-text-content';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport type { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { prepareCallSettings } from '../prompt/prepare-call-settings';\nimport type { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport { stringifyForTelemetry } from '../telemetry/stringify-for-telemetry';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport type {\n  CallWarning,\n  FinishReason,\n  LanguageModel,\n} from '../types/language-model';\nimport type { LanguageModelRequestMetadata } from '../types/language-model-request-metadata';\nimport type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport { asLanguageModelUsage, type LanguageModelUsage } from '../types/usage';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { prepareHeaders } from '../util/prepare-headers';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type { GenerateObjectResult } from './generate-object-result';\nimport { getOutputStrategy } from './output-strategy';\nimport { parseAndValidateObjectResultWithRepair } from './parse-and-validate-object-result';\nimport type { RepairTextFunction } from './repair-text';\nimport { validateObjectGenerationInput } from './validate-object-generation-input';\n\nconst originalGenerateId = createIdGenerator({ prefix: 'aiobj', size: 24 });\n\n/**\n * Generate a structured, typed object for a given prompt and schema using a language model.\n *\n * This function does not stream the output. If you want to stream the output, use `streamObject` instead.\n *\n * @param model - The language model to use.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. When unset, system messages are allowed with a warning.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param schema - The schema of the object that the model should generate.\n * @param schemaName - Optional name of the output that should be generated.\n * Used by some providers for additional LLM guidance, e.g.\n * via tool or schema name.\n * @param schemaDescription - Optional description of the output that should be generated.\n * Used by some providers for additional LLM guidance, e.g.\n * via tool or schema description.\n *\n * @param output - The type of the output.\n *\n * - 'object': The output is an object.\n * - 'array': The output is an array.\n * - 'enum': The output is an enum.\n * - 'no-schema': The output is not a schema.\n *\n * @param experimental_repairText - A function that attempts to repair the raw output of the model\n * to enable JSON parsing.\n *\n * @param experimental_telemetry - Optional telemetry configuration (experimental).\n *\n * @param providerOptions - Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n *\n * @returns\n * A result object that contains the generated object, the finish reason, the token usage, and additional information.\n *\n * @deprecated Use `generateText` with an `output` setting instead.\n */\nexport async function generateObject<\n  SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,\n  OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' =\n    InferSchema<SCHEMA> extends string ? 'enum' : 'object',\n  RESULT = OUTPUT extends 'array'\n    ? Array<InferSchema<SCHEMA>>\n    : InferSchema<SCHEMA>,\n>(\n  options: Omit<CallSettings, 'stopSequences'> &\n    Prompt &\n    (OUTPUT extends 'enum'\n      ? {\n          /**\n           * The enum values that the model should use.\n           */\n          enum: Array<RESULT>;\n          output: 'enum';\n        }\n      : OUTPUT extends 'no-schema'\n        ? {}\n        : {\n            /**\n             * The schema of the object that the model should generate.\n             */\n            schema: SCHEMA;\n\n            /**\n             * Optional name of the output that should be generated.\n             * Used by some providers for additional LLM guidance, e.g.\n             * via tool or schema name.\n             */\n            schemaName?: string;\n\n            /**\n             * Optional description of the output that should be generated.\n             * Used by some providers for additional LLM guidance, e.g.\n             * via tool or schema description.\n             */\n            schemaDescription?: string;\n          }) & {\n      output?: OUTPUT;\n\n      /**\n       * The language model to use.\n       */\n      model: LanguageModel;\n      /**\n       * A function that attempts to repair the raw output of the model\n       * to enable JSON parsing.\n       */\n      experimental_repairText?: RepairTextFunction;\n\n      /**\n       * Optional telemetry configuration (experimental).\n       */\n\n      experimental_telemetry?: TelemetrySettings;\n\n      /**\n       * Custom download function to use for URLs.\n       *\n       * By default, files are downloaded if the model does not support the URL for the given media type.\n       */\n      experimental_download?: DownloadFunction | undefined;\n\n      /**\n       * Additional provider-specific options. They are passed through\n       * to the provider from the AI SDK and enable provider-specific\n       * functionality that can be fully encapsulated in the provider.\n       */\n      providerOptions?: ProviderOptions;\n\n      /**\n       * Internal. For test use only. May change without notice.\n       */\n      _internal?: {\n        generateId?: () => string;\n        currentDate?: () => Date;\n      };\n    },\n): Promise<GenerateObjectResult<RESULT>> {\n  const {\n    model: modelArg,\n    output = 'object',\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    headers,\n    experimental_repairText: repairText,\n    experimental_telemetry: telemetry,\n    experimental_download: download,\n    providerOptions,\n    _internal: {\n      generateId = originalGenerateId,\n      currentDate = () => new Date(),\n    } = {},\n    ...settings\n  } = options;\n\n  const model = resolveLanguageModel(modelArg);\n\n  const enumValues = 'enum' in options ? options.enum : undefined;\n  const {\n    schema: inputSchema,\n    schemaDescription,\n    schemaName,\n  } = 'schema' in options ? options : {};\n\n  validateObjectGenerationInput({\n    output,\n    schema: inputSchema,\n    schemaName,\n    schemaDescription,\n    enumValues,\n  });\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const outputStrategy = getOutputStrategy({\n    output,\n    schema: inputSchema,\n    enumValues,\n  });\n\n  const callSettings = prepareCallSettings(settings);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const baseTelemetryAttributes = getBaseTelemetryAttributes({\n    model,\n    telemetry,\n    headers: headersWithUserAgent,\n    settings: { ...callSettings, maxRetries },\n  });\n\n  const tracer = getTracer(telemetry);\n  const jsonSchema = await outputStrategy.jsonSchema();\n\n  try {\n    return await recordSpan({\n      name: 'ai.generateObject',\n      attributes: selectTelemetryAttributes({\n        telemetry,\n        attributes: {\n          ...assembleOperationName({\n            operationId: 'ai.generateObject',\n            telemetry,\n          }),\n          ...baseTelemetryAttributes,\n          // specific settings that only make sense on the outer level:\n          'ai.prompt': {\n            input: () => JSON.stringify({ system, prompt, messages }),\n          },\n          'ai.schema':\n            jsonSchema != null\n              ? { input: () => JSON.stringify(jsonSchema) }\n              : undefined,\n          'ai.schema.name': schemaName,\n          'ai.schema.description': schemaDescription,\n          'ai.settings.output': outputStrategy.type,\n        },\n      }),\n      tracer,\n      fn: async span => {\n        let result: string;\n        let finishReason: FinishReason;\n        let usage: LanguageModelUsage;\n        let warnings: CallWarning[] | undefined;\n        let response: LanguageModelResponseMetadata;\n        let request: LanguageModelRequestMetadata;\n        let resultProviderMetadata: ProviderMetadata | undefined;\n        let reasoning: string | undefined;\n\n        const standardizedPrompt = await standardizePrompt({\n          system,\n          prompt,\n          messages,\n          allowSystemInMessages,\n        } as Prompt);\n\n        const promptMessages = await convertToLanguageModelPrompt({\n          prompt: standardizedPrompt,\n          supportedUrls: await model.supportedUrls,\n          download,\n        });\n\n        const generateResult = await retry(() =>\n          recordSpan({\n            name: 'ai.generateObject.doGenerate',\n            attributes: selectTelemetryAttributes({\n              telemetry,\n              attributes: {\n                ...assembleOperationName({\n                  operationId: 'ai.generateObject.doGenerate',\n                  telemetry,\n                }),\n                ...baseTelemetryAttributes,\n                'ai.prompt.messages': {\n                  input: () => stringifyForTelemetry(promptMessages),\n                },\n\n                // standardized gen-ai llm span attributes:\n                'gen_ai.system': model.provider,\n                'gen_ai.request.model': model.modelId,\n                'gen_ai.request.frequency_penalty':\n                  callSettings.frequencyPenalty,\n                'gen_ai.request.max_tokens': callSettings.maxOutputTokens,\n                'gen_ai.request.presence_penalty': callSettings.presencePenalty,\n                'gen_ai.request.temperature': callSettings.temperature,\n                'gen_ai.request.top_k': callSettings.topK,\n                'gen_ai.request.top_p': callSettings.topP,\n              },\n            }),\n            tracer,\n            fn: async span => {\n              const result = await model.doGenerate({\n                responseFormat: {\n                  type: 'json',\n                  schema: jsonSchema,\n                  name: schemaName,\n                  description: schemaDescription,\n                },\n                ...prepareCallSettings(settings),\n                prompt: promptMessages,\n                providerOptions,\n                abortSignal,\n                headers: headersWithUserAgent,\n              });\n\n              const responseData = {\n                id: result.response?.id ?? generateId(),\n                timestamp: result.response?.timestamp ?? currentDate(),\n                modelId: result.response?.modelId ?? model.modelId,\n                headers: result.response?.headers,\n                body: result.response?.body,\n              };\n\n              const text = extractTextContent(result.content);\n              const reasoning = extractReasoningContent(result.content);\n\n              if (text === undefined) {\n                throw new NoObjectGeneratedError({\n                  message:\n                    'No object generated: the model did not return a response.',\n                  response: responseData,\n                  usage: asLanguageModelUsage(result.usage),\n                  finishReason: result.finishReason.unified,\n                });\n              }\n\n              // Add response information to the span:\n              span.setAttributes(\n                await selectTelemetryAttributes({\n                  telemetry,\n                  attributes: {\n                    'ai.response.finishReason': result.finishReason.unified,\n                    'ai.response.object': { output: () => text },\n                    'ai.response.id': responseData.id,\n                    'ai.response.model': responseData.modelId,\n                    'ai.response.timestamp':\n                      responseData.timestamp.toISOString(),\n                    'ai.response.providerMetadata': JSON.stringify(\n                      result.providerMetadata,\n                    ),\n\n                    // TODO rename telemetry attributes to inputTokens and outputTokens\n                    'ai.usage.promptTokens': result.usage.inputTokens.total,\n                    'ai.usage.completionTokens':\n                      result.usage.outputTokens.total,\n\n                    // standardized gen-ai llm span attributes:\n                    'gen_ai.response.finish_reasons': [\n                      result.finishReason.unified,\n                    ],\n                    'gen_ai.response.id': responseData.id,\n                    'gen_ai.response.model': responseData.modelId,\n                    'gen_ai.usage.input_tokens': result.usage.inputTokens.total,\n                    'gen_ai.usage.output_tokens':\n                      result.usage.outputTokens.total,\n                  },\n                }),\n              );\n\n              return {\n                ...result,\n                objectText: text,\n                reasoning,\n                responseData,\n              };\n            },\n          }),\n        );\n\n        result = generateResult.objectText;\n        finishReason = generateResult.finishReason.unified;\n        usage = asLanguageModelUsage(generateResult.usage);\n        warnings = generateResult.warnings;\n        resultProviderMetadata = generateResult.providerMetadata;\n        request = generateResult.request ?? {};\n        response = generateResult.responseData;\n        reasoning = generateResult.reasoning;\n\n        logWarnings({\n          warnings,\n          provider: model.provider,\n          model: model.modelId,\n        });\n\n        const object = await parseAndValidateObjectResultWithRepair(\n          result,\n          outputStrategy,\n          repairText,\n          {\n            response,\n            usage,\n            finishReason,\n          },\n        );\n\n        // Add response information to the span:\n        span.setAttributes(\n          await selectTelemetryAttributes({\n            telemetry,\n            attributes: {\n              'ai.response.finishReason': finishReason,\n              'ai.response.object': {\n                output: () => JSON.stringify(object),\n              },\n              'ai.response.providerMetadata': JSON.stringify(\n                resultProviderMetadata,\n              ),\n\n              // TODO rename telemetry attributes to inputTokens and outputTokens\n              'ai.usage.promptTokens': usage.inputTokens,\n              'ai.usage.completionTokens': usage.outputTokens,\n            },\n          }),\n        );\n\n        return new DefaultGenerateObjectResult({\n          object,\n          reasoning,\n          finishReason,\n          usage,\n          warnings,\n          request,\n          response,\n          providerMetadata: resultProviderMetadata,\n        });\n      },\n    });\n  } catch (error) {\n    throw wrapGatewayError(error);\n  }\n}\n\nclass DefaultGenerateObjectResult<T> implements GenerateObjectResult<T> {\n  readonly object: GenerateObjectResult<T>['object'];\n  readonly finishReason: GenerateObjectResult<T>['finishReason'];\n  readonly usage: GenerateObjectResult<T>['usage'];\n  readonly warnings: GenerateObjectResult<T>['warnings'];\n  readonly providerMetadata: GenerateObjectResult<T>['providerMetadata'];\n  readonly response: GenerateObjectResult<T>['response'];\n  readonly request: GenerateObjectResult<T>['request'];\n  readonly reasoning: GenerateObjectResult<T>['reasoning'];\n\n  constructor(options: {\n    object: GenerateObjectResult<T>['object'];\n    finishReason: GenerateObjectResult<T>['finishReason'];\n    usage: GenerateObjectResult<T>['usage'];\n    warnings: GenerateObjectResult<T>['warnings'];\n    providerMetadata: GenerateObjectResult<T>['providerMetadata'];\n    response: GenerateObjectResult<T>['response'];\n    request: GenerateObjectResult<T>['request'];\n    reasoning: GenerateObjectResult<T>['reasoning'];\n  }) {\n    this.object = options.object;\n    this.finishReason = options.finishReason;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.response = options.response;\n    this.request = options.request;\n    this.reasoning = options.reasoning;\n  }\n\n  toJsonResponse(init?: ResponseInit): Response {\n    return new Response(JSON.stringify(this.object), {\n      status: init?.status ?? 200,\n      headers: prepareHeaders(init?.headers, {\n        'content-type': 'application/json; charset=utf-8',\n      }),\n    });\n  }\n}\n", "import {\n  isJSONArray,\n  isJSONObject,\n  TypeValidationError,\n  UnsupportedFunctionalityError,\n  type JSONObject,\n  type JSONSchema7,\n  type JSONValue,\n} from '@ai-sdk/provider';\nimport {\n  asSchema,\n  safeValidateTypes,\n  type FlexibleSchema,\n  type Schema,\n  type ValidationResult,\n} from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport type {\n  FinishReason,\n  LanguageModelResponseMetadata,\n  LanguageModelUsage,\n} from '../types';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport type { DeepPartial } from '../util/deep-partial';\nimport type { ObjectStreamPart } from './stream-object-result';\n\nexport interface OutputStrategy<PARTIAL, RESULT, ELEMENT_STREAM> {\n  readonly type: 'object' | 'array' | 'enum' | 'no-schema';\n\n  jsonSchema(): Promise<JSONSchema7 | undefined>;\n\n  validatePartialResult({\n    value,\n    textDelta,\n    isFinalDelta,\n  }: {\n    value: JSONValue;\n    textDelta: string;\n    isFirstDelta: boolean;\n    isFinalDelta: boolean;\n    latestObject: PARTIAL | undefined;\n  }): Promise<\n    ValidationResult<{\n      partial: PARTIAL;\n      textDelta: string;\n    }>\n  >;\n  validateFinalResult(\n    value: JSONValue | undefined,\n    context: {\n      text: string;\n      response: LanguageModelResponseMetadata;\n      usage: LanguageModelUsage;\n    },\n  ): Promise<ValidationResult<RESULT>>;\n\n  createElementStream(\n    originalStream: ReadableStream<ObjectStreamPart<PARTIAL>>,\n  ): ELEMENT_STREAM;\n}\n\nconst noSchemaOutputStrategy: OutputStrategy<JSONValue, JSONValue, never> = {\n  type: 'no-schema',\n  jsonSchema: async () => undefined,\n\n  async validatePartialResult({ value, textDelta }) {\n    return { success: true, value: { partial: value, textDelta } };\n  },\n\n  async validateFinalResult(\n    value: JSONValue | undefined,\n    context: {\n      text: string;\n      response: LanguageModelResponseMetadata;\n      usage: LanguageModelUsage;\n      finishReason: FinishReason;\n    },\n  ): Promise<ValidationResult<JSONValue>> {\n    return value === undefined\n      ? {\n          success: false,\n          error: new NoObjectGeneratedError({\n            message: 'No object generated: response did not match schema.',\n            text: context.text,\n            response: context.response,\n            usage: context.usage,\n            finishReason: context.finishReason,\n          }),\n        }\n      : { success: true, value };\n  },\n\n  createElementStream() {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'element streams in no-schema mode',\n    });\n  },\n};\n\nconst objectOutputStrategy = <OBJECT>(\n  schema: Schema<OBJECT>,\n): OutputStrategy<DeepPartial<OBJECT>, OBJECT, never> => ({\n  type: 'object',\n  jsonSchema: async () => await schema.jsonSchema,\n\n  async validatePartialResult({ value, textDelta }) {\n    return {\n      success: true,\n      value: {\n        // Note: currently no validation of partial results:\n        partial: value as DeepPartial<OBJECT>,\n        textDelta,\n      },\n    };\n  },\n\n  async validateFinalResult(\n    value: JSONValue | undefined,\n  ): Promise<ValidationResult<OBJECT>> {\n    return safeValidateTypes({ value, schema });\n  },\n\n  createElementStream() {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'element streams in object mode',\n    });\n  },\n});\n\nconst arrayOutputStrategy = <ELEMENT>(\n  schema: Schema<ELEMENT>,\n): OutputStrategy<ELEMENT[], ELEMENT[], AsyncIterableStream<ELEMENT>> => {\n  return {\n    type: 'array',\n\n    // wrap in object that contains array of elements, since most LLMs will not\n    // be able to generate an array directly:\n    // possible future optimization: use arrays directly when model supports grammar-guided generation\n    jsonSchema: async () => {\n      // remove $schema from schema.jsonSchema:\n      const { $schema, ...itemSchema } = await schema.jsonSchema;\n\n      return {\n        $schema: 'http://json-schema.org/draft-07/schema#',\n        type: 'object',\n        properties: {\n          elements: { type: 'array', items: itemSchema },\n        },\n        required: ['elements'],\n        additionalProperties: false,\n      };\n    },\n\n    async validatePartialResult({\n      value,\n      latestObject,\n      isFirstDelta,\n      isFinalDelta,\n    }) {\n      // check that the value is an object that contains an array of elements:\n      if (!isJSONObject(value) || !isJSONArray(value.elements)) {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause: 'value must be an object that contains an array of elements',\n          }),\n        };\n      }\n\n      const inputArray = value.elements as Array<JSONObject>;\n      const resultArray: Array<ELEMENT> = [];\n\n      for (let i = 0; i < inputArray.length; i++) {\n        const element = inputArray[i];\n        const result = await safeValidateTypes({ value: element, schema });\n\n        // special treatment for last processed element:\n        // ignore parse or validation failures, since they indicate that the\n        // last element is incomplete and should not be included in the result,\n        // unless it is the final delta\n        if (i === inputArray.length - 1 && !isFinalDelta) {\n          continue;\n        }\n\n        if (!result.success) {\n          return result;\n        }\n\n        resultArray.push(result.value);\n      }\n\n      // calculate delta:\n      const publishedElementCount = latestObject?.length ?? 0;\n\n      let textDelta = '';\n\n      if (isFirstDelta) {\n        textDelta += '[';\n      }\n\n      if (publishedElementCount > 0) {\n        textDelta += ',';\n      }\n\n      textDelta += resultArray\n        .slice(publishedElementCount) // only new elements\n        .map(element => JSON.stringify(element))\n        .join(',');\n\n      if (isFinalDelta) {\n        textDelta += ']';\n      }\n\n      return {\n        success: true,\n        value: {\n          partial: resultArray,\n          textDelta,\n        },\n      };\n    },\n\n    async validateFinalResult(\n      value: JSONValue | undefined,\n    ): Promise<ValidationResult<Array<ELEMENT>>> {\n      // check that the value is an object that contains an array of elements:\n      if (!isJSONObject(value) || !isJSONArray(value.elements)) {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause: 'value must be an object that contains an array of elements',\n          }),\n        };\n      }\n\n      const inputArray = value.elements as Array<JSONObject>;\n\n      // check that each element in the array is of the correct type:\n      for (const element of inputArray) {\n        const result = await safeValidateTypes({ value: element, schema });\n        if (!result.success) {\n          return result;\n        }\n      }\n\n      return { success: true, value: inputArray as Array<ELEMENT> };\n    },\n\n    createElementStream(\n      originalStream: ReadableStream<ObjectStreamPart<ELEMENT[]>>,\n    ) {\n      let publishedElements = 0;\n\n      return createAsyncIterableStream(\n        originalStream.pipeThrough(\n          new TransformStream<ObjectStreamPart<ELEMENT[]>, ELEMENT>({\n            transform(chunk, controller) {\n              switch (chunk.type) {\n                case 'object': {\n                  const array = chunk.object;\n\n                  // publish new elements one by one:\n                  for (\n                    ;\n                    publishedElements < array.length;\n                    publishedElements++\n                  ) {\n                    controller.enqueue(array[publishedElements]);\n                  }\n\n                  break;\n                }\n\n                case 'text-delta':\n                case 'finish':\n                case 'error': // suppress error (use onError instead)\n                  break;\n\n                default: {\n                  const _exhaustiveCheck: never = chunk;\n                  throw new Error(\n                    `Unsupported chunk type: ${_exhaustiveCheck}`,\n                  );\n                }\n              }\n            },\n          }),\n        ),\n      );\n    },\n  };\n};\n\nconst enumOutputStrategy = <ENUM extends string>(\n  enumValues: Array<ENUM>,\n): OutputStrategy<string, ENUM, never> => {\n  return {\n    type: 'enum',\n\n    // wrap in object that contains result, since most LLMs will not\n    // be able to generate an enum value directly:\n    // possible future optimization: use enums directly when model supports top-level enums\n    jsonSchema: async () => ({\n      $schema: 'http://json-schema.org/draft-07/schema#',\n      type: 'object',\n      properties: {\n        result: { type: 'string', enum: enumValues },\n      },\n      required: ['result'],\n      additionalProperties: false,\n    }),\n\n    async validateFinalResult(\n      value: JSONValue | undefined,\n    ): Promise<ValidationResult<ENUM>> {\n      // check that the value is an object that contains an array of elements:\n      if (!isJSONObject(value) || typeof value.result !== 'string') {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause:\n              'value must be an object that contains a string in the \"result\" property.',\n          }),\n        };\n      }\n\n      const result = value.result as string;\n\n      return enumValues.includes(result as ENUM)\n        ? { success: true, value: result as ENUM }\n        : {\n            success: false,\n            error: new TypeValidationError({\n              value,\n              cause: 'value must be a string in the enum',\n            }),\n          };\n    },\n\n    async validatePartialResult({ value, textDelta }) {\n      if (!isJSONObject(value) || typeof value.result !== 'string') {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause:\n              'value must be an object that contains a string in the \"result\" property.',\n          }),\n        };\n      }\n\n      const result = value.result as string;\n      const possibleEnumValues = enumValues.filter(enumValue =>\n        enumValue.startsWith(result),\n      );\n\n      if (value.result.length === 0 || possibleEnumValues.length === 0) {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause: 'value must be a string in the enum',\n          }),\n        };\n      }\n\n      return {\n        success: true,\n        value: {\n          partial:\n            possibleEnumValues.length > 1 ? result : possibleEnumValues[0],\n          textDelta,\n        },\n      };\n    },\n\n    createElementStream() {\n      // no streaming in enum mode\n      throw new UnsupportedFunctionalityError({\n        functionality: 'element streams in enum mode',\n      });\n    },\n  };\n};\n\nexport function getOutputStrategy<SCHEMA>({\n  output,\n  schema,\n  enumValues,\n}: {\n  output: 'object' | 'array' | 'enum' | 'no-schema';\n  schema?: FlexibleSchema<SCHEMA>;\n  enumValues?: Array<SCHEMA>;\n}): OutputStrategy<any, any, any> {\n  switch (output) {\n    case 'object':\n      return objectOutputStrategy(asSchema(schema!));\n    case 'array':\n      return arrayOutputStrategy(asSchema(schema!));\n    case 'enum':\n      return enumOutputStrategy(enumValues! as Array<string>);\n    case 'no-schema':\n      return noSchemaOutputStrategy;\n    default: {\n      const _exhaustiveCheck: never = output;\n      throw new Error(`Unsupported output: ${_exhaustiveCheck}`);\n    }\n  }\n}\n", "import { JSONParseError, TypeValidationError } from '@ai-sdk/provider';\nimport { safeParseJSON } from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport type {\n  FinishReason,\n  LanguageModelResponseMetadata,\n  LanguageModelUsage,\n} from '../types';\nimport type { OutputStrategy } from './output-strategy';\nimport type { RepairTextFunction } from './repair-text';\n\n/**\n * Parses and validates a result string by parsing it as JSON and validating against the output strategy.\n *\n * @param result - The result string to parse and validate\n * @param outputStrategy - The output strategy containing validation logic\n * @param context - Additional context for error reporting\n * @returns The validated result\n * @throws NoObjectGeneratedError if parsing or validation fails\n */\nasync function parseAndValidateObjectResult<RESULT>(\n  result: string,\n  outputStrategy: OutputStrategy<any, RESULT, any>,\n  context: {\n    response: LanguageModelResponseMetadata;\n    usage: LanguageModelUsage;\n    finishReason: FinishReason;\n  },\n): Promise<RESULT> {\n  const parseResult = await safeParseJSON({ text: result });\n\n  if (!parseResult.success) {\n    throw new NoObjectGeneratedError({\n      message: 'No object generated: could not parse the response.',\n      cause: parseResult.error,\n      text: result,\n      response: context.response,\n      usage: context.usage,\n      finishReason: context.finishReason,\n    });\n  }\n\n  const validationResult = await outputStrategy.validateFinalResult(\n    parseResult.value,\n    {\n      text: result,\n      response: context.response,\n      usage: context.usage,\n    },\n  );\n\n  if (!validationResult.success) {\n    throw new NoObjectGeneratedError({\n      message: 'No object generated: response did not match schema.',\n      cause: validationResult.error,\n      text: result,\n      response: context.response,\n      usage: context.usage,\n      finishReason: context.finishReason,\n    });\n  }\n\n  return validationResult.value;\n}\n\n/**\n * Parses and validates a result string by parsing it as JSON and validating against the output strategy.\n * If the result cannot be parsed, it attempts to repair the result using the repairText function.\n *\n * @param result - The result string to parse and validate\n * @param outputStrategy - The output strategy containing validation logic\n * @param repairText - A function that attempts to repair the result string\n * @param context - Additional context for error reporting\n * @returns The validated result\n * @throws NoObjectGeneratedError if parsing or validation fails\n */\nexport async function parseAndValidateObjectResultWithRepair<RESULT>(\n  result: string,\n  outputStrategy: OutputStrategy<any, RESULT, any>,\n  repairText: RepairTextFunction | undefined,\n  context: {\n    response: LanguageModelResponseMetadata;\n    usage: LanguageModelUsage;\n    finishReason: FinishReason;\n  },\n): Promise<RESULT> {\n  try {\n    return await parseAndValidateObjectResult(result, outputStrategy, context);\n  } catch (error) {\n    if (\n      repairText != null &&\n      NoObjectGeneratedError.isInstance(error) &&\n      (JSONParseError.isInstance(error.cause) ||\n        TypeValidationError.isInstance(error.cause))\n    ) {\n      const repairedText = await repairText({\n        text: result,\n        error: error.cause,\n      });\n      if (repairedText === null) {\n        throw error;\n      }\n      return await parseAndValidateObjectResult(\n        repairedText,\n        outputStrategy,\n        context,\n      );\n    }\n    throw error;\n  }\n}\n", "import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\n\nexport function validateObjectGenerationInput({\n  output,\n  schema,\n  schemaName,\n  schemaDescription,\n  enumValues,\n}: {\n  output?: 'object' | 'array' | 'enum' | 'no-schema';\n  schema?: FlexibleSchema<unknown>;\n  schemaName?: string;\n  schemaDescription?: string;\n  enumValues?: Array<unknown>;\n}) {\n  if (\n    output != null &&\n    output !== 'object' &&\n    output !== 'array' &&\n    output !== 'enum' &&\n    output !== 'no-schema'\n  ) {\n    throw new InvalidArgumentError({\n      parameter: 'output',\n      value: output,\n      message: 'Invalid output type.',\n    });\n  }\n\n  if (output === 'no-schema') {\n    if (schema != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schema',\n        value: schema,\n        message: 'Schema is not supported for no-schema output.',\n      });\n    }\n\n    if (schemaDescription != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schemaDescription',\n        value: schemaDescription,\n        message: 'Schema description is not supported for no-schema output.',\n      });\n    }\n\n    if (schemaName != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schemaName',\n        value: schemaName,\n        message: 'Schema name is not supported for no-schema output.',\n      });\n    }\n\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: 'enumValues',\n        value: enumValues,\n        message: 'Enum values are not supported for no-schema output.',\n      });\n    }\n  }\n\n  if (output === 'object') {\n    if (schema == null) {\n      throw new InvalidArgumentError({\n        parameter: 'schema',\n        value: schema,\n        message: 'Schema is required for object output.',\n      });\n    }\n\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: 'enumValues',\n        value: enumValues,\n        message: 'Enum values are not supported for object output.',\n      });\n    }\n  }\n\n  if (output === 'array') {\n    if (schema == null) {\n      throw new InvalidArgumentError({\n        parameter: 'schema',\n        value: schema,\n        message: 'Element schema is required for array output.',\n      });\n    }\n\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: 'enumValues',\n        value: enumValues,\n        message: 'Enum values are not supported for array output.',\n      });\n    }\n  }\n\n  if (output === 'enum') {\n    if (schema != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schema',\n        value: schema,\n        message: 'Schema is not supported for enum output.',\n      });\n    }\n\n    if (schemaDescription != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schemaDescription',\n        value: schemaDescription,\n        message: 'Schema description is not supported for enum output.',\n      });\n    }\n\n    if (schemaName != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schemaName',\n        value: schemaName,\n        message: 'Schema name is not supported for enum output.',\n      });\n    }\n\n    if (enumValues == null) {\n      throw new InvalidArgumentError({\n        parameter: 'enumValues',\n        value: enumValues,\n        message: 'Enum values are required for enum output.',\n      });\n    }\n\n    for (const value of enumValues) {\n      if (typeof value !== 'string') {\n        throw new InvalidArgumentError({\n          parameter: 'enumValues',\n          value,\n          message: 'Enum values must be strings.',\n        });\n      }\n    }\n  }\n}\n", "import type {\n  JSONValue,\n  LanguageModelV3FinishReason,\n  LanguageModelV3StreamPart,\n  LanguageModelV3Usage,\n  SharedV3ProviderMetadata,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  DelayedPromise,\n  type FlexibleSchema,\n  type ProviderOptions,\n  type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport type { ServerResponse } from 'http';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport type { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { prepareCallSettings } from '../prompt/prepare-call-settings';\nimport type { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport { stringifyForTelemetry } from '../telemetry/stringify-for-telemetry';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport { createTextStreamResponse } from '../text-stream/create-text-stream-response';\nimport { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';\nimport type {\n  CallWarning,\n  FinishReason,\n  LanguageModel,\n} from '../types/language-model';\nimport type { LanguageModelRequestMetadata } from '../types/language-model-request-metadata';\nimport type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport {\n  asLanguageModelUsage,\n  createNullLanguageModelUsage,\n  type LanguageModelUsage,\n} from '../types/usage';\nimport { isDeepEqualData, parsePartialJson, type DeepPartial } from '../util';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport { createStitchableStream } from '../util/create-stitchable-stream';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { now as originalNow } from '../util/now';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { getOutputStrategy, type OutputStrategy } from './output-strategy';\nimport { parseAndValidateObjectResultWithRepair } from './parse-and-validate-object-result';\nimport type { RepairTextFunction } from './repair-text';\nimport type {\n  ObjectStreamPart,\n  StreamObjectResult,\n} from './stream-object-result';\nimport { validateObjectGenerationInput } from './validate-object-generation-input';\n\nconst originalGenerateId = createIdGenerator({ prefix: 'aiobj', size: 24 });\n\n/**\n * Callback that is set using the `onError` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamObjectOnErrorCallback = (event: {\n  error: unknown;\n}) => Promise<void> | void;\n\n/**\n * Callback that is set using the `onFinish` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamObjectOnFinishCallback<RESULT> = (event: {\n  /**\n   * The token usage of the generated response.\n   */\n  usage: LanguageModelUsage;\n\n  /**\n   * The generated object. Can be undefined if the final object does not match the schema.\n   */\n  object: RESULT | undefined;\n\n  /**\n   * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n   */\n  error: unknown | undefined;\n\n  /**\n   * Response metadata.\n   */\n  response: LanguageModelResponseMetadata;\n\n  /**\n   * Warnings from the model provider (e.g. unsupported settings).\n   */\n  warnings?: CallWarning[];\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerMetadata: ProviderMetadata | undefined;\n}) => Promise<void> | void;\n\n/**\n * Generate a structured, typed object for a given prompt and schema using a language model.\n *\n * This function streams the output. If you do not want to stream the output, use `generateObject` instead.\n *\n * @param model - The language model to use.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. When unset, system messages are allowed with a warning.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param schema - The schema of the object that the model should generate.\n * @param schemaName - Optional name of the output that should be generated.\n * Used by some providers for additional LLM guidance, e.g.\n * via tool or schema name.\n * @param schemaDescription - Optional description of the output that should be generated.\n * Used by some providers for additional LLM guidance, e.g.\n * via tool or schema description.\n *\n * @param output - The type of the output.\n *\n * - 'object': The output is an object.\n * - 'array': The output is an array.\n * - 'enum': The output is an enum.\n * - 'no-schema': The output is not a schema.\n *\n * @param experimental_telemetry - Optional telemetry configuration (experimental).\n *\n * @param providerOptions - Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n *\n * @returns\n * A result object for accessing the partial object stream and additional information.\n *\n * @deprecated Use `streamText` with an `output` setting instead.\n */\nexport function streamObject<\n  SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,\n  OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' =\n    InferSchema<SCHEMA> extends string ? 'enum' : 'object',\n  RESULT = OUTPUT extends 'array'\n    ? Array<InferSchema<SCHEMA>>\n    : InferSchema<SCHEMA>,\n>(\n  options: Omit<CallSettings, 'stopSequences'> &\n    Prompt &\n    (OUTPUT extends 'enum'\n      ? {\n          /**\n           * The enum values that the model should use.\n           */\n          enum: Array<RESULT>;\n          output: 'enum';\n        }\n      : OUTPUT extends 'no-schema'\n        ? {}\n        : {\n            /**\n             * The schema of the object that the model should generate.\n             */\n            schema: SCHEMA;\n\n            /**\n             * Optional name of the output that should be generated.\n             * Used by some providers for additional LLM guidance, e.g.\n             * via tool or schema name.\n             */\n            schemaName?: string;\n\n            /**\n             * Optional description of the output that should be generated.\n             * Used by some providers for additional LLM guidance, e.g.\n             * via tool or schema description.\n             */\n            schemaDescription?: string;\n          }) & {\n      output?: OUTPUT;\n\n      /**\n       * The language model to use.\n       */\n      model: LanguageModel;\n\n      /**\n       * A function that attempts to repair the raw output of the model\n       * to enable JSON parsing.\n       */\n      experimental_repairText?: RepairTextFunction;\n\n      /**\n       * Optional telemetry configuration (experimental).\n       */\n\n      experimental_telemetry?: TelemetrySettings;\n\n      /**\n       * Custom download function to use for URLs.\n       *\n       * By default, files are downloaded if the model does not support the URL for the given media type.\n       */\n      experimental_download?: DownloadFunction | undefined;\n\n      /**\n       * Additional provider-specific options. They are passed through\n       * to the provider from the AI SDK and enable provider-specific\n       * functionality that can be fully encapsulated in the provider.\n       */\n      providerOptions?: ProviderOptions;\n\n      /**\n       * Callback that is invoked when an error occurs during streaming.\n       * You can use it to log errors.\n       * The stream processing will pause until the callback promise is resolved.\n       */\n      onError?: StreamObjectOnErrorCallback;\n\n      /**\n       * Callback that is called when the LLM response and the final object validation are finished.\n       */\n      onFinish?: StreamObjectOnFinishCallback<RESULT>;\n\n      /**\n       * Internal. For test use only. May change without notice.\n       */\n      _internal?: {\n        generateId?: () => string;\n        currentDate?: () => Date;\n        now?: () => number;\n      };\n    },\n): StreamObjectResult<\n  OUTPUT extends 'enum'\n    ? string\n    : OUTPUT extends 'array'\n      ? RESULT\n      : DeepPartial<RESULT>,\n  OUTPUT extends 'array' ? RESULT : RESULT,\n  OUTPUT extends 'array'\n    ? RESULT extends Array<infer U>\n      ? AsyncIterableStream<U>\n      : never\n    : never\n> {\n  const {\n    model,\n    output = 'object',\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    maxRetries,\n    abortSignal,\n    headers,\n    experimental_repairText: repairText,\n    experimental_telemetry: telemetry,\n    experimental_download: download,\n    providerOptions,\n    onError = ({ error }: { error: unknown }) => {\n      console.error(error);\n    },\n    onFinish,\n    _internal: {\n      generateId = originalGenerateId,\n      currentDate = () => new Date(),\n      now = originalNow,\n    } = {},\n    ...settings\n  } = options;\n\n  const enumValues =\n    'enum' in options && options.enum ? options.enum : undefined;\n\n  const {\n    schema: inputSchema,\n    schemaDescription,\n    schemaName,\n  } = 'schema' in options ? options : {};\n\n  validateObjectGenerationInput({\n    output,\n    schema: inputSchema,\n    schemaName,\n    schemaDescription,\n    enumValues,\n  });\n\n  const outputStrategy = getOutputStrategy({\n    output,\n    schema: inputSchema,\n    enumValues,\n  });\n\n  return new DefaultStreamObjectResult({\n    model,\n    telemetry,\n    headers,\n    settings,\n    maxRetries,\n    abortSignal,\n    outputStrategy,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    schemaName,\n    schemaDescription,\n    providerOptions,\n    repairText,\n    onError,\n    onFinish,\n    download,\n    generateId,\n    currentDate,\n    now,\n  });\n}\n\nclass DefaultStreamObjectResult<\n  PARTIAL,\n  RESULT,\n  ELEMENT_STREAM,\n> implements StreamObjectResult<PARTIAL, RESULT, ELEMENT_STREAM> {\n  private readonly _object = new DelayedPromise<RESULT>();\n  private readonly _usage = new DelayedPromise<LanguageModelUsage>();\n  private readonly _providerMetadata = new DelayedPromise<\n    ProviderMetadata | undefined\n  >();\n  private readonly _warnings = new DelayedPromise<CallWarning[] | undefined>();\n  private readonly _request =\n    new DelayedPromise<LanguageModelRequestMetadata>();\n  private readonly _response =\n    new DelayedPromise<LanguageModelResponseMetadata>();\n  private readonly _finishReason = new DelayedPromise<FinishReason>();\n\n  private readonly baseStream: ReadableStream<ObjectStreamPart<PARTIAL>>;\n\n  private readonly outputStrategy: OutputStrategy<\n    PARTIAL,\n    RESULT,\n    ELEMENT_STREAM\n  >;\n\n  constructor({\n    model: modelArg,\n    headers,\n    telemetry,\n    settings,\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    outputStrategy,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    schemaName,\n    schemaDescription,\n    providerOptions,\n    repairText,\n    onError,\n    onFinish,\n    download,\n    generateId,\n    currentDate,\n    now,\n  }: {\n    model: LanguageModel;\n    telemetry: TelemetrySettings | undefined;\n    headers: Record<string, string | undefined> | undefined;\n    settings: Omit<CallSettings, 'abortSignal' | 'headers'>;\n    maxRetries: number | undefined;\n    abortSignal: AbortSignal | undefined;\n    outputStrategy: OutputStrategy<PARTIAL, RESULT, ELEMENT_STREAM>;\n    system: Prompt['system'];\n    prompt: Prompt['prompt'];\n    messages: Prompt['messages'];\n    allowSystemInMessages: Prompt['allowSystemInMessages'];\n    schemaName: string | undefined;\n    schemaDescription: string | undefined;\n    providerOptions: ProviderOptions | undefined;\n    repairText: RepairTextFunction | undefined;\n    onError: StreamObjectOnErrorCallback;\n    onFinish: StreamObjectOnFinishCallback<RESULT> | undefined;\n    download: DownloadFunction | undefined;\n    generateId: () => string;\n    currentDate: () => Date;\n    now: () => number;\n  }) {\n    const model = resolveLanguageModel(modelArg);\n\n    const { maxRetries, retry } = prepareRetries({\n      maxRetries: maxRetriesArg,\n      abortSignal,\n    });\n\n    const callSettings = prepareCallSettings(settings);\n\n    const baseTelemetryAttributes = getBaseTelemetryAttributes({\n      model,\n      telemetry,\n      headers,\n      settings: { ...callSettings, maxRetries },\n    });\n\n    const tracer = getTracer(telemetry);\n    const self = this;\n\n    const stitchableStream =\n      createStitchableStream<ObjectStreamPart<PARTIAL>>();\n\n    const eventProcessor = new TransformStream<\n      ObjectStreamPart<PARTIAL>,\n      ObjectStreamPart<PARTIAL>\n    >({\n      transform(chunk, controller) {\n        controller.enqueue(chunk);\n\n        if (chunk.type === 'error') {\n          onError({ error: wrapGatewayError(chunk.error) });\n        }\n      },\n    });\n\n    this.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n\n    recordSpan({\n      name: 'ai.streamObject',\n      attributes: selectTelemetryAttributes({\n        telemetry,\n        attributes: {\n          ...assembleOperationName({\n            operationId: 'ai.streamObject',\n            telemetry,\n          }),\n          ...baseTelemetryAttributes,\n          // specific settings that only make sense on the outer level:\n          'ai.prompt': {\n            input: () => JSON.stringify({ system, prompt, messages }),\n          },\n          'ai.schema': {\n            input: async () =>\n              JSON.stringify(await outputStrategy.jsonSchema()),\n          },\n          'ai.schema.name': schemaName,\n          'ai.schema.description': schemaDescription,\n          'ai.settings.output': outputStrategy.type,\n        },\n      }),\n      tracer,\n      endWhenDone: false,\n      fn: async rootSpan => {\n        const standardizedPrompt = await standardizePrompt({\n          system,\n          prompt,\n          messages,\n          allowSystemInMessages,\n        } as Prompt);\n\n        const callOptions = {\n          responseFormat: {\n            type: 'json' as const,\n            schema: await outputStrategy.jsonSchema(),\n            name: schemaName,\n            description: schemaDescription,\n          },\n          ...prepareCallSettings(settings),\n          prompt: await convertToLanguageModelPrompt({\n            prompt: standardizedPrompt,\n            supportedUrls: await model.supportedUrls,\n            download,\n          }),\n          providerOptions,\n          abortSignal,\n          headers,\n          includeRawChunks: false,\n        };\n\n        const transformer: Transformer<\n          LanguageModelV3StreamPart,\n          ObjectStreamInputPart\n        > = {\n          transform: (chunk, controller) => {\n            switch (chunk.type) {\n              case 'text-delta':\n                controller.enqueue(chunk.delta);\n                break;\n              case 'response-metadata':\n              case 'finish':\n              case 'error':\n              case 'stream-start':\n                controller.enqueue(chunk);\n                break;\n            }\n          },\n        };\n\n        const {\n          result: { stream, response, request },\n          doStreamSpan,\n          startTimestampMs,\n        } = await retry(() =>\n          recordSpan({\n            name: 'ai.streamObject.doStream',\n            attributes: selectTelemetryAttributes({\n              telemetry,\n              attributes: {\n                ...assembleOperationName({\n                  operationId: 'ai.streamObject.doStream',\n                  telemetry,\n                }),\n                ...baseTelemetryAttributes,\n                'ai.prompt.messages': {\n                  input: () => stringifyForTelemetry(callOptions.prompt),\n                },\n\n                // standardized gen-ai llm span attributes:\n                'gen_ai.system': model.provider,\n                'gen_ai.request.model': model.modelId,\n                'gen_ai.request.frequency_penalty':\n                  callSettings.frequencyPenalty,\n                'gen_ai.request.max_tokens': callSettings.maxOutputTokens,\n                'gen_ai.request.presence_penalty': callSettings.presencePenalty,\n                'gen_ai.request.temperature': callSettings.temperature,\n                'gen_ai.request.top_k': callSettings.topK,\n                'gen_ai.request.top_p': callSettings.topP,\n              },\n            }),\n            tracer,\n            endWhenDone: false,\n            fn: async doStreamSpan => ({\n              startTimestampMs: now(),\n              doStreamSpan,\n              result: await model.doStream(callOptions),\n            }),\n          }),\n        );\n\n        self._request.resolve(request ?? {});\n\n        // store information for onFinish callback:\n        let warnings: SharedV3Warning[] | undefined;\n        let usage: LanguageModelUsage = createNullLanguageModelUsage();\n        let finishReason: FinishReason | undefined;\n        let providerMetadata: ProviderMetadata | undefined;\n        let object: RESULT | undefined;\n        let error: unknown | undefined;\n\n        // pipe chunks through a transformation stream that extracts metadata:\n        let accumulatedText = '';\n        let textDelta = '';\n        let fullResponse: {\n          id: string;\n          timestamp: Date;\n          modelId: string;\n        } = {\n          id: generateId(),\n          timestamp: currentDate(),\n          modelId: model.modelId,\n        };\n\n        // Keep track of raw parse result before type validation, since e.g. Zod might\n        // change the object by mapping properties.\n        let latestObjectJson: JSONValue | undefined = undefined;\n        let latestObject: PARTIAL | undefined = undefined;\n        let isFirstChunk = true;\n        let isFirstDelta = true;\n\n        const transformedStream = stream\n          .pipeThrough(new TransformStream(transformer))\n          .pipeThrough(\n            new TransformStream<\n              string | ObjectStreamInputPart,\n              ObjectStreamPart<PARTIAL>\n            >({\n              async transform(chunk, controller): Promise<void> {\n                if (\n                  typeof chunk === 'object' &&\n                  chunk.type === 'stream-start'\n                ) {\n                  warnings = chunk.warnings;\n                  return; // stream start chunks are sent immediately and do not count as first chunk\n                }\n\n                // Telemetry event for first chunk:\n                if (isFirstChunk) {\n                  const msToFirstChunk = now() - startTimestampMs;\n\n                  isFirstChunk = false;\n\n                  doStreamSpan.addEvent('ai.stream.firstChunk', {\n                    'ai.stream.msToFirstChunk': msToFirstChunk,\n                  });\n\n                  doStreamSpan.setAttributes({\n                    'ai.stream.msToFirstChunk': msToFirstChunk,\n                  });\n                }\n\n                // process partial text chunks\n                if (typeof chunk === 'string') {\n                  accumulatedText += chunk;\n                  textDelta += chunk;\n\n                  const { value: currentObjectJson, state: parseState } =\n                    await parsePartialJson(accumulatedText);\n\n                  if (\n                    currentObjectJson !== undefined &&\n                    !isDeepEqualData(latestObjectJson, currentObjectJson)\n                  ) {\n                    const validationResult =\n                      await outputStrategy.validatePartialResult({\n                        value: currentObjectJson,\n                        textDelta,\n                        latestObject,\n                        isFirstDelta,\n                        isFinalDelta: parseState === 'successful-parse',\n                      });\n\n                    if (\n                      validationResult.success &&\n                      !isDeepEqualData(\n                        latestObject,\n                        validationResult.value.partial,\n                      )\n                    ) {\n                      // inside inner check to correctly parse the final element in array mode:\n                      latestObjectJson = currentObjectJson;\n                      latestObject = validationResult.value.partial;\n\n                      controller.enqueue({\n                        type: 'object',\n                        object: latestObject,\n                      });\n\n                      controller.enqueue({\n                        type: 'text-delta',\n                        textDelta: validationResult.value.textDelta,\n                      });\n\n                      textDelta = '';\n                      isFirstDelta = false;\n                    }\n                  }\n\n                  return;\n                }\n\n                switch (chunk.type) {\n                  case 'response-metadata': {\n                    fullResponse = {\n                      id: chunk.id ?? fullResponse.id,\n                      timestamp: chunk.timestamp ?? fullResponse.timestamp,\n                      modelId: chunk.modelId ?? fullResponse.modelId,\n                    };\n                    break;\n                  }\n\n                  case 'finish': {\n                    // send final text delta:\n                    if (textDelta !== '') {\n                      controller.enqueue({ type: 'text-delta', textDelta });\n                    }\n\n                    // store finish reason for telemetry:\n                    finishReason = chunk.finishReason.unified;\n\n                    // store usage and metadata for promises and onFinish callback:\n                    usage = asLanguageModelUsage(chunk.usage);\n                    providerMetadata = chunk.providerMetadata;\n\n                    controller.enqueue({\n                      ...chunk,\n                      finishReason: chunk.finishReason.unified,\n                      usage,\n                      response: fullResponse,\n                    });\n\n                    // log warnings:\n                    logWarnings({\n                      warnings: warnings ?? [],\n                      provider: model.provider,\n                      model: model.modelId,\n                    });\n\n                    // resolve promises that can be resolved now:\n                    self._usage.resolve(usage);\n                    self._providerMetadata.resolve(providerMetadata);\n                    self._warnings.resolve(warnings);\n                    self._response.resolve({\n                      ...fullResponse,\n                      headers: response?.headers,\n                    });\n                    self._finishReason.resolve(finishReason ?? 'other');\n\n                    try {\n                      object = await parseAndValidateObjectResultWithRepair(\n                        accumulatedText,\n                        outputStrategy,\n                        repairText,\n                        {\n                          response: fullResponse,\n                          usage,\n                          finishReason,\n                        },\n                      );\n                      self._object.resolve(object);\n                    } catch (e) {\n                      error = e;\n                      self._object.reject(e);\n                    }\n                    break;\n                  }\n\n                  default: {\n                    controller.enqueue(chunk);\n                    break;\n                  }\n                }\n              },\n\n              // invoke onFinish callback and resolve toolResults promise when the stream is about to close:\n              async flush(controller) {\n                try {\n                  const finalUsage = usage ?? {\n                    promptTokens: NaN,\n                    completionTokens: NaN,\n                    totalTokens: NaN,\n                  };\n\n                  doStreamSpan.setAttributes(\n                    await selectTelemetryAttributes({\n                      telemetry,\n                      attributes: {\n                        'ai.response.finishReason': finishReason,\n                        'ai.response.object': {\n                          output: () => JSON.stringify(object),\n                        },\n                        'ai.response.id': fullResponse.id,\n                        'ai.response.model': fullResponse.modelId,\n                        'ai.response.timestamp':\n                          fullResponse.timestamp.toISOString(),\n                        'ai.response.providerMetadata':\n                          JSON.stringify(providerMetadata),\n\n                        'ai.usage.inputTokens': finalUsage.inputTokens,\n                        'ai.usage.outputTokens': finalUsage.outputTokens,\n                        'ai.usage.totalTokens': finalUsage.totalTokens,\n                        'ai.usage.reasoningTokens': finalUsage.reasoningTokens,\n                        'ai.usage.cachedInputTokens':\n                          finalUsage.cachedInputTokens,\n\n                        // standardized gen-ai llm span attributes:\n                        'gen_ai.response.finish_reasons': [finishReason],\n                        'gen_ai.response.id': fullResponse.id,\n                        'gen_ai.response.model': fullResponse.modelId,\n                        'gen_ai.usage.input_tokens': finalUsage.inputTokens,\n                        'gen_ai.usage.output_tokens': finalUsage.outputTokens,\n                      },\n                    }),\n                  );\n\n                  // finish doStreamSpan before other operations for correct timing:\n                  doStreamSpan.end();\n\n                  // Add response information to the root span:\n                  rootSpan.setAttributes(\n                    await selectTelemetryAttributes({\n                      telemetry,\n                      attributes: {\n                        'ai.usage.inputTokens': finalUsage.inputTokens,\n                        'ai.usage.outputTokens': finalUsage.outputTokens,\n                        'ai.usage.totalTokens': finalUsage.totalTokens,\n                        'ai.usage.reasoningTokens': finalUsage.reasoningTokens,\n                        'ai.usage.cachedInputTokens':\n                          finalUsage.cachedInputTokens,\n                        'ai.response.object': {\n                          output: () => JSON.stringify(object),\n                        },\n                        'ai.response.providerMetadata':\n                          JSON.stringify(providerMetadata),\n                      },\n                    }),\n                  );\n\n                  // call onFinish callback:\n                  await onFinish?.({\n                    usage: finalUsage,\n                    object,\n                    error,\n                    response: {\n                      ...fullResponse,\n                      headers: response?.headers,\n                    },\n                    warnings,\n                    providerMetadata,\n                  });\n                } catch (error) {\n                  controller.enqueue({ type: 'error', error });\n                } finally {\n                  rootSpan.end();\n                }\n              },\n            }),\n          );\n\n        stitchableStream.addStream(transformedStream);\n      },\n    })\n      .catch(error => {\n        // add an empty stream with an error to break the stream:\n        stitchableStream.addStream(\n          new ReadableStream({\n            start(controller) {\n              controller.enqueue({ type: 'error', error });\n              controller.close();\n            },\n          }),\n        );\n      })\n      .finally(() => {\n        stitchableStream.close();\n      });\n\n    this.outputStrategy = outputStrategy;\n  }\n\n  get object() {\n    return this._object.promise;\n  }\n\n  get usage() {\n    return this._usage.promise;\n  }\n\n  get providerMetadata() {\n    return this._providerMetadata.promise;\n  }\n\n  get warnings() {\n    return this._warnings.promise;\n  }\n\n  get request() {\n    return this._request.promise;\n  }\n\n  get response() {\n    return this._response.promise;\n  }\n\n  get finishReason() {\n    return this._finishReason.promise;\n  }\n\n  get partialObjectStream(): AsyncIterableStream<PARTIAL> {\n    return createAsyncIterableStream(\n      this.baseStream.pipeThrough(\n        new TransformStream<ObjectStreamPart<PARTIAL>, PARTIAL>({\n          transform(chunk, controller) {\n            switch (chunk.type) {\n              case 'object':\n                controller.enqueue(chunk.object);\n                break;\n\n              case 'text-delta':\n              case 'finish':\n              case 'error': // suppress error (use onError instead)\n                break;\n\n              default: {\n                const _exhaustiveCheck: never = chunk;\n                throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n              }\n            }\n          },\n        }),\n      ),\n    );\n  }\n\n  get elementStream(): ELEMENT_STREAM {\n    return this.outputStrategy.createElementStream(this.baseStream);\n  }\n\n  get textStream(): AsyncIterableStream<string> {\n    return createAsyncIterableStream(\n      this.baseStream.pipeThrough(\n        new TransformStream<ObjectStreamPart<PARTIAL>, string>({\n          transform(chunk, controller) {\n            switch (chunk.type) {\n              case 'text-delta':\n                controller.enqueue(chunk.textDelta);\n                break;\n\n              case 'object':\n              case 'finish':\n              case 'error': // suppress error (use onError instead)\n                break;\n\n              default: {\n                const _exhaustiveCheck: never = chunk;\n                throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n              }\n            }\n          },\n        }),\n      ),\n    );\n  }\n\n  get fullStream(): AsyncIterableStream<ObjectStreamPart<PARTIAL>> {\n    return createAsyncIterableStream(this.baseStream);\n  }\n\n  pipeTextStreamToResponse(response: ServerResponse, init?: ResponseInit) {\n    pipeTextStreamToResponse({\n      response,\n      textStream: this.textStream,\n      ...init,\n    });\n  }\n\n  toTextStreamResponse(init?: ResponseInit): Response {\n    return createTextStreamResponse({\n      textStream: this.textStream,\n      ...init,\n    });\n  }\n}\n\nexport type ObjectStreamInputPart =\n  | string\n  | {\n      type: 'stream-start';\n      warnings: SharedV3Warning[];\n    }\n  | {\n      type: 'error';\n      error: unknown;\n    }\n  | {\n      type: 'response-metadata';\n      id?: string;\n      timestamp?: Date;\n      modelId?: string;\n    }\n  | {\n      type: 'finish';\n      finishReason: LanguageModelV3FinishReason;\n      usage: LanguageModelV3Usage;\n      providerMetadata?: SharedV3ProviderMetadata;\n    };\n", "import { InvalidArgumentError } from '../error/invalid-argument-error';\n\n/**\n * Calculates the cosine similarity between two vectors. This is a useful metric for\n * comparing the similarity of two vectors such as embeddings.\n *\n * @param vector1 - The first vector.\n * @param vector2 - The second vector.\n *\n * @returns The cosine similarity between vector1 and vector2, or 0 if either vector is the zero vector.\n *\n * @throws {InvalidArgumentError} If the vectors do not have the same length.\n */\nexport function cosineSimilarity(vector1: number[], vector2: number[]): number {\n  if (vector1.length !== vector2.length) {\n    throw new InvalidArgumentError({\n      parameter: 'vector1,vector2',\n      value: { vector1Length: vector1.length, vector2Length: vector2.length },\n      message: `Vectors must have the same length`,\n    });\n  }\n\n  const n = vector1.length;\n\n  if (n === 0) {\n    return 0; // Return 0 for empty vectors if no error is thrown\n  }\n\n  let magnitudeSquared1 = 0;\n  let magnitudeSquared2 = 0;\n  let dotProduct = 0;\n\n  for (let i = 0; i < n; i++) {\n    const value1 = vector1[i];\n    const value2 = vector2[i];\n\n    magnitudeSquared1 += value1 * value1;\n    magnitudeSquared2 += value2 * value2;\n    dotProduct += value1 * value2;\n  }\n\n  return magnitudeSquared1 === 0 || magnitudeSquared2 === 0\n    ? 0\n    : dotProduct /\n        (Math.sqrt(magnitudeSquared1) * Math.sqrt(magnitudeSquared2));\n}\n", "import { download as internalDownload } from './download';\n\n/**\n * Creates a download function with configurable options.\n *\n * @param options - Configuration options for the download function.\n * @param options.maxBytes - Maximum allowed download size in bytes. Default: 2 GiB.\n * @returns A download function that can be passed to `transcribe()` or `experimental_generateVideo()`.\n */\nexport function createDownload(options?: { maxBytes?: number }) {\n  return ({ url, abortSignal }: { url: URL; abortSignal?: AbortSignal }) =>\n    internalDownload({ url, maxBytes: options?.maxBytes, abortSignal });\n}\n", "/**\n * Converts a data URL of type text/* to a text string.\n */\nexport function getTextFromDataUrl(dataUrl: string): string {\n  const [header, base64Content] = dataUrl.split(',');\n  const mediaType = header.split(';')[0].split(':')[1];\n\n  if (mediaType == null || base64Content == null) {\n    throw new Error('Invalid data URL format');\n  }\n\n  try {\n    return window.atob(base64Content);\n  } catch (error) {\n    throw new Error(`Error decoding data URL`);\n  }\n}\n", "/**\n * Performs a deep-equal comparison of two parsed JSON objects.\n *\n * @param {any} obj1 - The first object to compare.\n * @param {any} obj2 - The second object to compare.\n * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.\n */\nexport function isDeepEqualData(obj1: any, obj2: any): boolean {\n  // Check for strict equality first\n  if (obj1 === obj2) return true;\n\n  // Check if either is null or undefined\n  if (obj1 == null || obj2 == null) return false;\n\n  // Check if both are objects\n  if (typeof obj1 !== 'object' && typeof obj2 !== 'object')\n    return obj1 === obj2;\n\n  // If they are not strictly equal, they both need to be Objects\n  if (obj1.constructor !== obj2.constructor) return false;\n\n  // Special handling for Date objects\n  if (obj1 instanceof Date && obj2 instanceof Date) {\n    return obj1.getTime() === obj2.getTime();\n  }\n\n  // Handle arrays: compare length and then perform a recursive deep comparison on each item\n  if (Array.isArray(obj1)) {\n    if (obj1.length !== obj2.length) return false;\n    for (let i = 0; i < obj1.length; i++) {\n      if (!isDeepEqualData(obj1[i], obj2[i])) return false;\n    }\n    return true; // All array elements matched\n  }\n\n  // Compare the set of keys in each object\n  const keys1 = Object.keys(obj1);\n  const keys2 = Object.keys(obj2);\n  if (keys1.length !== keys2.length) return false;\n\n  // Check each key-value pair recursively\n  for (const key of keys1) {\n    if (!keys2.includes(key)) return false;\n    if (!isDeepEqualData(obj1[key], obj2[key])) return false;\n  }\n\n  return true; // All keys and values matched\n}\n", "import type { Job } from './job';\n\nexport class SerialJobExecutor {\n  private queue: Array<Job> = [];\n  private isProcessing = false;\n\n  private async processQueue() {\n    if (this.isProcessing) {\n      return;\n    }\n\n    this.isProcessing = true;\n\n    while (this.queue.length > 0) {\n      await this.queue[0]();\n      this.queue.shift();\n    }\n\n    this.isProcessing = false;\n  }\n\n  async run(job: Job): Promise<void> {\n    return new Promise<void>((resolve, reject) => {\n      this.queue.push(async () => {\n        try {\n          await job();\n          resolve();\n        } catch (error) {\n          reject(error);\n        }\n      });\n\n      void this.processQueue();\n    });\n  }\n}\n", "import { delay as delayFunction } from '@ai-sdk/provider-utils';\n\n/**\n * Creates a ReadableStream that emits the provided values with an optional delay between each value.\n *\n * @param options - The configuration options\n * @param options.chunks - Array of values to be emitted by the stream\n * @param options.initialDelayInMs - Optional initial delay in milliseconds before emitting the first value (default: 0). Can be set to `null` to skip the initial delay. The difference between `initialDelayInMs: null` and `initialDelayInMs: 0` is that `initialDelayInMs: null` will emit the values without any delay, while `initialDelayInMs: 0` will emit the values with a delay of 0 milliseconds.\n * @param options.chunkDelayInMs - Optional delay in milliseconds between emitting each value (default: 0). Can be set to `null` to skip the delay. The difference between `chunkDelayInMs: null` and `chunkDelayInMs: 0` is that `chunkDelayInMs: null` will emit the values without any delay, while `chunkDelayInMs: 0` will emit the values with a delay of 0 milliseconds.\n * @returns A ReadableStream that emits the provided values\n */\nexport function simulateReadableStream<T>({\n  chunks,\n  initialDelayInMs = 0,\n  chunkDelayInMs = 0,\n  _internal,\n}: {\n  chunks: T[];\n  initialDelayInMs?: number | null;\n  chunkDelayInMs?: number | null;\n  _internal?: {\n    delay?: (ms: number | null) => Promise<void>;\n  };\n}): ReadableStream<T> {\n  const delay = _internal?.delay ?? delayFunction;\n\n  let index = 0;\n\n  return new ReadableStream({\n    async pull(controller) {\n      if (index < chunks.length) {\n        await delay(index === 0 ? initialDelayInMs : chunkDelayInMs);\n        controller.enqueue(chunks[index++]);\n      } else {\n        controller.close();\n      }\n    },\n  });\n}\n", "import type { JSONObject } from '@ai-sdk/provider';\nimport {\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoSpeechGeneratedError } from '../error/no-speech-generated-error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveSpeechModel } from '../model/resolve-model';\nimport type { SpeechModel } from '../types/speech-model';\nimport type { SpeechModelResponseMetadata } from '../types/speech-model-response-metadata';\nimport type { Warning } from '../types/warning';\nimport {\n  audioMediaTypeSignatures,\n  detectMediaType,\n} from '../util/detect-media-type';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type { SpeechResult } from './generate-speech-result';\nimport {\n  DefaultGeneratedAudioFile,\n  type GeneratedAudioFile,\n} from './generated-audio-file';\n\n/**\n * Generates speech audio using a speech model.\n *\n * @param model - The speech model to use.\n * @param text - The text to convert to speech.\n * @param voice - The voice to use for speech generation.\n * @param outputFormat - The output format to use for speech generation e.g. \"mp3\", \"wav\", etc.\n * @param instructions - Instructions for the speech generation e.g. \"Speak in a slow and steady tone\".\n * @param speed - The speed of the speech generation.\n * @param language - The language for speech generation (ISO 639-1 code e.g. \"en\", \"es\", \"fr\") or \"auto\" for automatic detection.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @returns A result object that contains the generated audio data.\n */\nexport async function generateSpeech({\n  model,\n  text,\n  voice,\n  outputFormat,\n  instructions,\n  speed,\n  language,\n  providerOptions = {},\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n}: {\n  /**\n   * The speech model to use.\n   */\n  model: SpeechModel;\n\n  /**\n   * The text to convert to speech.\n   */\n  text: string;\n\n  /**\n   * The voice to use for speech generation.\n   */\n  voice?: string;\n\n  /**\n   * The desired output format for the audio e.g. \"mp3\", \"wav\", etc.\n   */\n  outputFormat?: 'mp3' | 'wav' | (string & {});\n\n  /**\n   * Instructions for the speech generation e.g. \"Speak in a slow and steady tone\".\n   */\n  instructions?: string;\n\n  /**\n   * The speed of the speech generation.\n   */\n  speed?: number;\n\n  /**\n   * The language for speech generation. This should be an ISO 639-1 language code (e.g. \"en\", \"es\", \"fr\")\n   * or \"auto\" for automatic language detection. Provider support varies.\n   */\n  language?: string;\n\n  /**\n   * Additional provider-specific options that are passed through to the provider\n   * as body parameters.\n   *\n   * The outer record is keyed by the provider name, and the inner\n   * record is keyed by the provider-specific metadata key.\n   * ```ts\n   * {\n   * \"openai\": {}\n   * }\n   * ```\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of retries per speech model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n}): Promise<SpeechResult> {\n  const resolvedModel = resolveSpeechModel(model);\n  if (!resolvedModel) {\n    throw new Error('Model could not be resolved');\n  }\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const result = await retry(() =>\n    resolvedModel.doGenerate({\n      text,\n      voice,\n      outputFormat,\n      instructions,\n      speed,\n      language,\n      abortSignal,\n      headers: headersWithUserAgent,\n      providerOptions,\n    }),\n  );\n\n  if (!result.audio || result.audio.length === 0) {\n    throw new NoSpeechGeneratedError({ responses: [result.response] });\n  }\n\n  logWarnings({\n    warnings: result.warnings,\n    provider: resolvedModel.provider,\n    model: resolvedModel.modelId,\n  });\n\n  return new DefaultSpeechResult({\n    audio: new DefaultGeneratedAudioFile({\n      data: result.audio,\n      mediaType:\n        detectMediaType({\n          data: result.audio,\n          signatures: audioMediaTypeSignatures,\n        }) ?? 'audio/mp3',\n    }),\n    warnings: result.warnings,\n    responses: [result.response],\n    providerMetadata: result.providerMetadata,\n  });\n}\n\nclass DefaultSpeechResult implements SpeechResult {\n  readonly audio: GeneratedAudioFile;\n  readonly warnings: Array<Warning>;\n  readonly responses: Array<SpeechModelResponseMetadata>;\n  readonly providerMetadata: Record<string, JSONObject>;\n\n  constructor(options: {\n    audio: GeneratedAudioFile;\n    warnings: Array<Warning>;\n    responses: Array<SpeechModelResponseMetadata>;\n    providerMetadata: Record<string, JSONObject> | undefined;\n  }) {\n    this.audio = options.audio;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = options.providerMetadata ?? {};\n  }\n}\n", "import {\n  DefaultGeneratedFile,\n  type GeneratedFile,\n} from '../generate-text/generated-file';\n\n/**\n * A generated audio file.\n */\nexport interface GeneratedAudioFile extends GeneratedFile {\n  /**\n   * Audio format of the file (e.g., 'mp3', 'wav', etc.)\n   */\n  readonly format: string;\n}\n\nexport class DefaultGeneratedAudioFile\n  extends DefaultGeneratedFile\n  implements GeneratedAudioFile\n{\n  readonly format: string;\n\n  constructor({\n    data,\n    mediaType,\n  }: {\n    data: string | Uint8Array;\n    mediaType: string;\n  }) {\n    super({ data, mediaType });\n    let format = 'mp3';\n\n    // If format is not provided, try to determine it from the media type\n    if (mediaType) {\n      const mediaTypeParts = mediaType.split('/');\n\n      if (mediaTypeParts.length === 2) {\n        // Handle special cases for audio formats\n        if (mediaType !== 'audio/mpeg') {\n          format = mediaTypeParts[1];\n        }\n      }\n    }\n\n    if (!format) {\n      // TODO this should be an AI SDK error\n      throw new Error(\n        'Audio format must be provided or determinable from media type',\n      );\n    }\n\n    this.format = format;\n  }\n}\n\nexport class DefaultGeneratedAudioFileWithType extends DefaultGeneratedAudioFile {\n  readonly type = 'audio';\n\n  constructor(options: {\n    data: string | Uint8Array;\n    mediaType: string;\n    format: string;\n  }) {\n    super(options);\n  }\n}\n", "import type {\n  AssistantModelMessage,\n  ModelMessage,\n  ToolModelMessage,\n} from '@ai-sdk/provider-utils';\n\n/**\n * Prunes model messages from a list of model messages.\n *\n * @param messages - The list of model messages to prune.\n * @param reasoning - How to remove reasoning content from assistant messages. Default is `'none'`.\n * @param toolCalls - How to prune tool call/results/approval content. Default is `[]`.\n * @param emptyMessages - Whether to keep or remove messages whose content is empty after pruning. Default is `'remove'`.\n *\n * @returns The pruned list of model messages.\n */\nexport function pruneMessages({\n  messages,\n  reasoning = 'none',\n  toolCalls = [],\n  emptyMessages = 'remove',\n}: {\n  messages: ModelMessage[];\n  reasoning?: 'all' | 'before-last-message' | 'none';\n  toolCalls?:\n    | 'all'\n    | 'before-last-message'\n    | `before-last-${number}-messages`\n    | 'none'\n    | Array<{\n        type: 'all' | 'before-last-message' | `before-last-${number}-messages`;\n        tools?: string[];\n      }>;\n  emptyMessages?: 'keep' | 'remove';\n}): ModelMessage[] {\n  // filter reasoning parts:\n  if (reasoning === 'all' || reasoning === 'before-last-message') {\n    messages = messages.map((message, messageIndex) => {\n      if (\n        message.role !== 'assistant' ||\n        typeof message.content === 'string' ||\n        (reasoning === 'before-last-message' &&\n          messageIndex === messages.length - 1)\n      ) {\n        return message;\n      }\n\n      return {\n        ...message,\n        content: message.content.filter(part => part.type !== 'reasoning'),\n      };\n    });\n  }\n\n  // filter tool calls, results, errors, and approvals:\n  if (toolCalls === 'none') {\n    toolCalls = [];\n  } else if (toolCalls === 'all') {\n    toolCalls = [{ type: 'all' }];\n  } else if (toolCalls === 'before-last-message') {\n    toolCalls = [{ type: 'before-last-message' }];\n  } else if (typeof toolCalls === 'string') {\n    toolCalls = [{ type: toolCalls }];\n  }\n\n  for (const toolCall of toolCalls) {\n    // determine how many trailing messages to keep:\n    const keepLastMessagesCount =\n      toolCall.type === 'all'\n        ? undefined\n        : toolCall.type === 'before-last-message'\n          ? 1\n          : Number(\n              toolCall.type\n                .slice('before-last-'.length)\n                .slice(0, -'-messages'.length),\n            );\n\n    // scan kept messages to identify tool calls and approvals that need to be kept:\n    const keptToolCallIds: Set<string> = new Set();\n    const keptApprovalIds: Set<string> = new Set();\n\n    if (keepLastMessagesCount != null) {\n      for (const message of messages.slice(-keepLastMessagesCount)) {\n        if (\n          (message.role === 'assistant' || message.role === 'tool') &&\n          typeof message.content !== 'string'\n        ) {\n          for (const part of message.content) {\n            if (part.type === 'tool-call' || part.type === 'tool-result') {\n              keptToolCallIds.add(part.toolCallId);\n            } else if (\n              part.type === 'tool-approval-request' ||\n              part.type === 'tool-approval-response'\n            ) {\n              keptApprovalIds.add(part.approvalId);\n            }\n          }\n        }\n      }\n    }\n\n    messages = messages.map((message, messageIndex) => {\n      if (\n        (message.role !== 'assistant' && message.role !== 'tool') ||\n        typeof message.content === 'string' ||\n        (keepLastMessagesCount &&\n          messageIndex >= messages.length - keepLastMessagesCount)\n      ) {\n        return message;\n      }\n\n      const toolCallIdToToolName: Record<string, string> = {};\n      const approvalIdToToolName: Record<string, string> = {};\n\n      return {\n        ...message,\n        content: message.content.filter(part => {\n          // keep non-tool parts:\n          if (\n            part.type !== 'tool-call' &&\n            part.type !== 'tool-result' &&\n            part.type !== 'tool-approval-request' &&\n            part.type !== 'tool-approval-response'\n          ) {\n            return true;\n          }\n\n          // track tool calls and approvals:\n          if (part.type === 'tool-call') {\n            toolCallIdToToolName[part.toolCallId] = part.toolName;\n          } else if (part.type === 'tool-approval-request') {\n            approvalIdToToolName[part.approvalId] =\n              toolCallIdToToolName[part.toolCallId];\n          }\n\n          // keep parts that are associated with a tool call or approval that needs to be kept:\n          if (\n            ((part.type === 'tool-call' || part.type === 'tool-result') &&\n              keptToolCallIds.has(part.toolCallId)) ||\n            ((part.type === 'tool-approval-request' ||\n              part.type === 'tool-approval-response') &&\n              keptApprovalIds.has(part.approvalId))\n          ) {\n            return true;\n          }\n\n          // keep parts that are not associated with a tool that should be removed:\n          return (\n            toolCall.tools != null &&\n            !toolCall.tools.includes(\n              part.type === 'tool-call' || part.type === 'tool-result'\n                ? part.toolName\n                : approvalIdToToolName[part.approvalId],\n            )\n          );\n        }),\n      } as AssistantModelMessage | ToolModelMessage;\n    });\n  }\n\n  if (emptyMessages === 'remove') {\n    messages = messages.filter(message => message.content.length > 0);\n  }\n\n  return messages;\n}\n", "import { delay as originalDelay } from '@ai-sdk/provider-utils';\nimport {\n  InvalidArgumentError,\n  type SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type { TextStreamPart } from './stream-text-result';\nimport type { ToolSet } from './tool-set';\n\nconst CHUNKING_REGEXPS = {\n  word: /\\S+\\s+/m,\n  line: /\\n+/m,\n};\n\n/**\n * Detects the first chunk in a buffer.\n *\n * @param buffer - The buffer to detect the first chunk in.\n *\n * @returns The first detected chunk, or `undefined` if no chunk was detected.\n */\nexport type ChunkDetector = (buffer: string) => string | undefined | null;\n\n/**\n * Smooths text and reasoning streaming output.\n *\n * @param delayInMs - The delay in milliseconds between each chunk. Defaults to 10ms. Can be set to `null` to skip the delay.\n * @param chunking - Controls how the text is chunked for streaming. Use \"word\" to stream word by word (default), \"line\" to stream line by line, provide a custom RegExp pattern for custom chunking, provide an Intl.Segmenter for locale-aware word segmentation (recommended for CJK languages), or provide a custom ChunkDetector function.\n *\n * @returns A transform stream that smooths text streaming output.\n */\nexport function smoothStream<TOOLS extends ToolSet>({\n  delayInMs = 10,\n  chunking = 'word',\n  _internal: { delay = originalDelay } = {},\n}: {\n  delayInMs?: number | null;\n  chunking?: 'word' | 'line' | RegExp | ChunkDetector | Intl.Segmenter;\n  /**\n   * Internal. For test use only. May change without notice.\n   */\n  _internal?: {\n    delay?: (delayInMs: number | null) => Promise<void>;\n  };\n} = {}): (options: {\n  tools: TOOLS;\n}) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>> {\n  let detectChunk: ChunkDetector;\n\n  // Check if chunking is an Intl.Segmenter (duck-typing for segment method)\n  if (\n    chunking != null &&\n    typeof chunking === 'object' &&\n    'segment' in chunking &&\n    typeof chunking.segment === 'function'\n  ) {\n    const segmenter = chunking as Intl.Segmenter;\n    detectChunk = (buffer: string) => {\n      if (buffer.length === 0) return null;\n      const iterator = segmenter.segment(buffer)[Symbol.iterator]();\n      const first = iterator.next().value;\n      return first?.segment || null;\n    };\n  } else if (typeof chunking === 'function') {\n    detectChunk = buffer => {\n      const match = chunking(buffer);\n\n      if (match == null) {\n        return null;\n      }\n\n      if (!match.length) {\n        throw new Error(`Chunking function must return a non-empty string.`);\n      }\n\n      if (!buffer.startsWith(match)) {\n        throw new Error(\n          `Chunking function must return a match that is a prefix of the buffer. Received: \"${match}\" expected to start with \"${buffer}\"`,\n        );\n      }\n\n      return match;\n    };\n  } else {\n    const chunkingRegex =\n      typeof chunking === 'string'\n        ? CHUNKING_REGEXPS[chunking]\n        : chunking instanceof RegExp\n          ? chunking\n          : undefined;\n\n    if (chunkingRegex == null) {\n      throw new InvalidArgumentError({\n        argument: 'chunking',\n        message: `Chunking must be \"word\", \"line\", a RegExp, an Intl.Segmenter, or a ChunkDetector function. Received: ${chunking}`,\n      });\n    }\n\n    detectChunk = buffer => {\n      const match = chunkingRegex.exec(buffer);\n\n      if (!match) {\n        return null;\n      }\n\n      return buffer.slice(0, match.index) + match?.[0];\n    };\n  }\n\n  return () => {\n    let buffer = '';\n    let id = '';\n    let type: 'text-delta' | 'reasoning-delta' | undefined = undefined;\n    let providerMetadata: SharedV3ProviderMetadata | undefined = undefined;\n\n    function flushBuffer(\n      controller: TransformStreamDefaultController<TextStreamPart<TOOLS>>,\n    ) {\n      if (buffer.length > 0 && type !== undefined) {\n        controller.enqueue({\n          type,\n          text: buffer,\n          id,\n          ...(providerMetadata != null ? { providerMetadata } : {}),\n        });\n        buffer = '';\n        providerMetadata = undefined;\n      }\n    }\n\n    return new TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>({\n      async transform(chunk, controller) {\n        // Handle non-smoothable chunks: flush buffer and pass through\n        if (chunk.type !== 'text-delta' && chunk.type !== 'reasoning-delta') {\n          flushBuffer(controller);\n          controller.enqueue(chunk);\n          return;\n        }\n\n        // Flush buffer when type or id changes\n        if ((chunk.type !== type || chunk.id !== id) && buffer.length > 0) {\n          flushBuffer(controller);\n        }\n\n        buffer += chunk.text;\n        id = chunk.id;\n        type = chunk.type;\n\n        // Preserve providerMetadata (e.g., Anthropic thinking signatures)\n        if (chunk.providerMetadata != null) {\n          providerMetadata = chunk.providerMetadata;\n        }\n\n        let match;\n\n        while ((match = detectChunk(buffer)) != null) {\n          controller.enqueue({ type, text: match, id });\n          buffer = buffer.slice(match.length);\n\n          await delay(delayInMs);\n        }\n      },\n    });\n  };\n}\n", "import type {\n  Experimental_VideoModelV3,\n  Experimental_VideoModelV3CallOptions,\n  Experimental_VideoModelV3File,\n  SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport {\n  convertBase64ToUint8Array,\n  type DataContent,\n  type ProviderOptions,\n  withUserAgentSuffix,\n} from '@ai-sdk/provider-utils';\nimport { NoVideoGeneratedError } from '../error/no-video-generated-error';\nimport {\n  DefaultGeneratedFile,\n  type GeneratedFile,\n} from '../generate-text/generated-file';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveVideoModel } from '../model/resolve-model';\nimport type { VideoModel } from '../types/video-model';\nimport type { VideoModelResponseMetadata } from '../types/video-model-response-metadata';\nimport type { Warning } from '../types/warning';\nimport {\n  detectMediaType,\n  imageMediaTypeSignatures,\n  videoMediaTypeSignatures,\n} from '../util/detect-media-type';\nimport { createDownload } from '../util/download/create-download';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type { GenerateVideoResult } from './generate-video-result';\nimport { splitDataUrl } from '../prompt/split-data-url';\n\nexport type GenerateVideoPrompt =\n  | string\n  | {\n      image: DataContent;\n      text?: string;\n    };\n\n/**\n * Generates videos using a video model.\n *\n * @param model - The video model to use.\n * @param prompt - The prompt that should be used to generate the video.\n * @param n - Number of videos to generate. Default: 1.\n * @param aspectRatio - Aspect ratio of the videos to generate. Must have the format `{width}:{height}`.\n * @param resolution - Resolution of the videos to generate. Must have the format `{width}x{height}`.\n * @param duration - Duration of the video in seconds.\n * @param fps - Frames per second for the video.\n * @param seed - Seed for the video generation.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @returns A result object that contains the generated videos.\n */\nconst defaultDownload = createDownload();\n\nexport async function experimental_generateVideo({\n  model: modelArg,\n  prompt: promptArg,\n  n = 1,\n  maxVideosPerCall,\n  aspectRatio,\n  resolution,\n  duration,\n  fps,\n  seed,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  download: downloadFn = defaultDownload,\n}: {\n  /**\n   * The video model to use.\n   */\n  model: VideoModel;\n\n  /**\n   * The prompt that should be used to generate the video.\n   */\n  prompt: GenerateVideoPrompt;\n\n  /**\n   * Number of videos to generate.\n   */\n  n?: number;\n\n  /**\n   * Maximum number of videos per API call. If not provided, the model's default will be used.\n   */\n  maxVideosPerCall?: number;\n\n  /**\n   * Aspect ratio of the videos to generate. Must have the format `{width}:{height}`.\n   */\n  aspectRatio?: `${number}:${number}`;\n\n  /**\n   * Resolution of the videos to generate. Must have the format `{width}x{height}`.\n   */\n  resolution?: `${number}x${number}`;\n\n  /**\n   * Duration of the video in seconds.\n   */\n  duration?: number;\n\n  /**\n   * Frames per second for the video.\n   */\n  fps?: number;\n\n  /**\n   * Seed for the video generation.\n   */\n  seed?: number;\n\n  /**\n   * Additional provider-specific options that are passed through to the provider\n   * as body parameters.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of retries per video model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Custom download function for fetching videos from URLs.\n   * Use `createDownload()` from `ai` to create a download function with custom size limits.\n   *\n   * @default createDownload() (2 GiB limit)\n   */\n  download?: (options: {\n    url: URL;\n    abortSignal?: AbortSignal;\n  }) => Promise<{ data: Uint8Array; mediaType: string | undefined }>;\n}): Promise<GenerateVideoResult> {\n  const model = resolveVideoModel(modelArg);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const { prompt, image } = normalizePrompt(promptArg);\n\n  const maxVideosPerCallWithDefault =\n    maxVideosPerCall ?? (await invokeModelMaxVideosPerCall(model)) ?? 1;\n\n  // parallelize calls to the model:\n  const callCount = Math.ceil(n / maxVideosPerCallWithDefault);\n  const callVideoCounts = Array.from({ length: callCount }, (_, index) => {\n    const remaining = n - index * maxVideosPerCallWithDefault;\n    return Math.min(remaining, maxVideosPerCallWithDefault);\n  });\n\n  const results = await Promise.all(\n    callVideoCounts.map(async callVideoCount =>\n      retry(() =>\n        model.doGenerate({\n          prompt,\n          n: callVideoCount,\n          aspectRatio,\n          resolution,\n          duration,\n          fps,\n          seed,\n          image,\n          providerOptions: providerOptions ?? {},\n          headers: headersWithUserAgent,\n          abortSignal,\n        } satisfies Experimental_VideoModelV3CallOptions),\n      ),\n    ),\n  );\n\n  // collect result videos, warnings, and response metadata\n  const videos: Array<GeneratedFile> = [];\n  const warnings: Array<Warning> = [];\n  const responses: Array<VideoModelResponseMetadata> = [];\n  const providerMetadata: SharedV3ProviderMetadata = {};\n\n  for (const result of results) {\n    for (const videoData of result.videos) {\n      switch (videoData.type) {\n        case 'url': {\n          const { data, mediaType: downloadedMediaType } = await downloadFn({\n            url: new URL(videoData.url),\n            abortSignal,\n          });\n\n          // Filter out generic/unknown media types that should fall through to detection\n          const isUsableMediaType = (type: string | undefined): boolean =>\n            !!type && type !== 'application/octet-stream';\n\n          const mediaType =\n            (isUsableMediaType(videoData.mediaType) && videoData.mediaType) ||\n            (isUsableMediaType(downloadedMediaType) && downloadedMediaType) ||\n            detectMediaType({\n              data,\n              signatures: videoMediaTypeSignatures,\n            }) ||\n            'video/mp4';\n\n          videos.push(\n            new DefaultGeneratedFile({\n              data,\n              mediaType,\n            }),\n          );\n          break;\n        }\n\n        case 'base64': {\n          videos.push(\n            new DefaultGeneratedFile({\n              data: videoData.data,\n              mediaType: videoData.mediaType || 'video/mp4',\n            }),\n          );\n          break;\n        }\n\n        case 'binary': {\n          const mediaType =\n            videoData.mediaType ||\n            detectMediaType({\n              data: videoData.data,\n              signatures: videoMediaTypeSignatures,\n            }) ||\n            'video/mp4';\n\n          videos.push(\n            new DefaultGeneratedFile({\n              data: videoData.data,\n              mediaType,\n            }),\n          );\n          break;\n        }\n      }\n    }\n\n    warnings.push(...result.warnings);\n\n    responses.push({\n      timestamp: result.response.timestamp,\n      modelId: result.response.modelId,\n      headers: result.response.headers,\n      providerMetadata: result.providerMetadata,\n    });\n\n    if (result.providerMetadata != null) {\n      for (const [providerName, metadata] of Object.entries(\n        result.providerMetadata,\n      )) {\n        const existingMetadata = providerMetadata[providerName];\n        if (existingMetadata != null && typeof existingMetadata === 'object') {\n          providerMetadata[providerName] = {\n            ...existingMetadata,\n            ...metadata,\n          };\n\n          // Merge videos arrays if both exist\n          if (\n            'videos' in existingMetadata &&\n            Array.isArray(existingMetadata.videos) &&\n            'videos' in metadata &&\n            Array.isArray(metadata.videos)\n          ) {\n            (providerMetadata[providerName] as { videos: unknown[] }).videos = [\n              ...existingMetadata.videos,\n              ...metadata.videos,\n            ];\n          }\n        } else {\n          providerMetadata[providerName] = metadata;\n        }\n      }\n    }\n  }\n\n  if (videos.length === 0) {\n    throw new NoVideoGeneratedError({ responses });\n  }\n\n  if (warnings.length > 0) {\n    logWarnings({\n      warnings,\n      provider: model.provider,\n      model: model.modelId,\n    });\n  }\n\n  return {\n    video: videos[0],\n    videos,\n    warnings,\n    responses,\n    providerMetadata,\n  };\n}\n\nfunction normalizePrompt(promptArg: GenerateVideoPrompt): {\n  prompt: string | undefined;\n  image: Experimental_VideoModelV3File | undefined;\n} {\n  if (typeof promptArg === 'string') {\n    return {\n      prompt: promptArg,\n      image: undefined,\n    };\n  }\n\n  let image: Experimental_VideoModelV3File | undefined;\n\n  if (promptArg.image != null) {\n    const dataContent = promptArg.image;\n\n    if (typeof dataContent === 'string') {\n      if (\n        dataContent.startsWith('http://') ||\n        dataContent.startsWith('https://')\n      ) {\n        image = {\n          type: 'url',\n          url: dataContent,\n        };\n      } else if (dataContent.startsWith('data:')) {\n        const { mediaType, base64Content } = splitDataUrl(dataContent);\n        image = {\n          type: 'file',\n          mediaType: mediaType ?? 'image/png',\n          data: convertBase64ToUint8Array(base64Content ?? ''),\n        };\n      } else {\n        const bytes = convertBase64ToUint8Array(dataContent);\n        const mediaType =\n          detectMediaType({\n            data: bytes,\n            signatures: imageMediaTypeSignatures,\n          }) ?? 'image/png';\n\n        image = {\n          type: 'file',\n          mediaType,\n          data: bytes,\n        };\n      }\n    } else if (dataContent instanceof Uint8Array) {\n      const mediaType =\n        detectMediaType({\n          data: dataContent,\n          signatures: imageMediaTypeSignatures,\n        }) ?? 'image/png';\n\n      image = {\n        type: 'file',\n        mediaType,\n        data: dataContent,\n      };\n    }\n  }\n\n  return {\n    prompt: promptArg.text,\n    image,\n  };\n}\n\nasync function invokeModelMaxVideosPerCall(model: Experimental_VideoModelV3) {\n  if (typeof model.maxVideosPerCall === 'function') {\n    return await model.maxVideosPerCall({ modelId: model.modelId });\n  }\n\n  return model.maxVideosPerCall;\n}\n", "import type { EmbeddingModelV3CallOptions } from '@ai-sdk/provider';\nimport type { EmbeddingModelMiddleware } from '../types';\nimport { mergeObjects } from '../util/merge-objects';\n\n/**\n * Applies default settings for an embedding model.\n */\nexport function defaultEmbeddingSettingsMiddleware({\n  settings,\n}: {\n  settings: Partial<{\n    headers?: EmbeddingModelV3CallOptions['headers'];\n    providerOptions?: EmbeddingModelV3CallOptions['providerOptions'];\n  }>;\n}): EmbeddingModelMiddleware {\n  return {\n    specificationVersion: 'v3',\n    transformParams: async ({ params }) => {\n      return mergeObjects(settings, params) as EmbeddingModelV3CallOptions;\n    },\n  };\n}\n", "import type { LanguageModelV3CallOptions } from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types';\nimport { mergeObjects } from '../util/merge-objects';\n\n/**\n * Applies default settings for a language model.\n */\nexport function defaultSettingsMiddleware({\n  settings,\n}: {\n  settings: Partial<{\n    maxOutputTokens?: LanguageModelV3CallOptions['maxOutputTokens'];\n    temperature?: LanguageModelV3CallOptions['temperature'];\n    stopSequences?: LanguageModelV3CallOptions['stopSequences'];\n    topP?: LanguageModelV3CallOptions['topP'];\n    topK?: LanguageModelV3CallOptions['topK'];\n    presencePenalty?: LanguageModelV3CallOptions['presencePenalty'];\n    frequencyPenalty?: LanguageModelV3CallOptions['frequencyPenalty'];\n    responseFormat?: LanguageModelV3CallOptions['responseFormat'];\n    seed?: LanguageModelV3CallOptions['seed'];\n    tools?: LanguageModelV3CallOptions['tools'];\n    toolChoice?: LanguageModelV3CallOptions['toolChoice'];\n    headers?: LanguageModelV3CallOptions['headers'];\n    providerOptions?: LanguageModelV3CallOptions['providerOptions'];\n  }>;\n}): LanguageModelMiddleware {\n  return {\n    specificationVersion: 'v3',\n    transformParams: async ({ params }) => {\n      return mergeObjects(settings, params) as LanguageModelV3CallOptions;\n    },\n  };\n}\n", "import type {\n  LanguageModelV3Content,\n  LanguageModelV3StreamPart,\n} from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types/language-model-middleware';\n\n/**\n * Default transform function that strips markdown code fences from text.\n */\nfunction defaultTransform(text: string): string {\n  return text\n    .replace(/^```(?:json)?\\s*\\n?/, '')\n    .replace(/\\n?```\\s*$/, '')\n    .trim();\n}\n\n/**\n * Middleware that extracts JSON from text content by stripping\n * markdown code fences and other formatting.\n *\n * This is useful when using Output.object() with models that wrap\n * JSON responses in markdown code blocks.\n *\n * @param options - Configuration options for the middleware.\n * @param options.transform - Custom transform function. If provided, this will be\n * used instead of the default markdown fence stripping.\n */\nexport function extractJsonMiddleware(options?: {\n  /**\n   * Custom transform function to apply to text content.\n   * Receives the raw text and should return the transformed text.\n   * If not provided, the default transform strips markdown code fences.\n   */\n  transform?: (text: string) => string;\n}): LanguageModelMiddleware {\n  const transform = options?.transform ?? defaultTransform;\n  const hasCustomTransform = options?.transform !== undefined;\n\n  return {\n    specificationVersion: 'v3',\n\n    wrapGenerate: async ({ doGenerate }) => {\n      const { content, ...rest } = await doGenerate();\n\n      const transformedContent: LanguageModelV3Content[] = [];\n      for (const part of content) {\n        if (part.type !== 'text') {\n          transformedContent.push(part);\n          continue;\n        }\n\n        transformedContent.push({\n          ...part,\n          text: transform(part.text),\n        });\n      }\n\n      return { content: transformedContent, ...rest };\n    },\n    wrapStream: async ({ doStream }) => {\n      const { stream, ...rest } = await doStream();\n\n      const textBlocks: Record<\n        string,\n        {\n          startEvent: LanguageModelV3StreamPart;\n          phase: 'prefix' | 'streaming' | 'buffering';\n          buffer: string;\n          prefixStripped: boolean;\n        }\n      > = {};\n\n      const SUFFIX_BUFFER_SIZE = 12;\n\n      return {\n        stream: stream.pipeThrough(\n          new TransformStream<\n            LanguageModelV3StreamPart,\n            LanguageModelV3StreamPart\n          >({\n            transform: (chunk, controller) => {\n              if (chunk.type === 'text-start') {\n                textBlocks[chunk.id] = {\n                  startEvent: chunk,\n                  // Custom transforms need to buffer all content\n                  phase: hasCustomTransform ? 'buffering' : 'prefix',\n                  buffer: '',\n                  prefixStripped: false,\n                };\n                return;\n              }\n\n              if (chunk.type === 'text-delta') {\n                const block = textBlocks[chunk.id];\n                if (!block) {\n                  controller.enqueue(chunk);\n                  return;\n                }\n\n                block.buffer += chunk.delta;\n\n                // Custom transform: buffer everything, transform at end\n                if (block.phase === 'buffering') {\n                  return;\n                }\n\n                if (block.phase === 'prefix') {\n                  // Check if we can determine prefix status\n                  if (\n                    block.buffer.length > 0 &&\n                    !block.buffer.startsWith('`')\n                  ) {\n                    block.phase = 'streaming';\n                    controller.enqueue(block.startEvent);\n                  } else if (block.buffer.startsWith('```')) {\n                    // Only strip prefix when we have a newline (fence is complete)\n                    if (block.buffer.includes('\\n')) {\n                      const prefixMatch =\n                        block.buffer.match(/^```(?:json)?\\s*\\n/);\n                      if (prefixMatch) {\n                        block.buffer = block.buffer.slice(\n                          prefixMatch[0].length,\n                        );\n                        block.prefixStripped = true;\n                        block.phase = 'streaming';\n                        controller.enqueue(block.startEvent);\n                      } else {\n                        // Has newline but doesn't match fence pattern\n                        block.phase = 'streaming';\n                        controller.enqueue(block.startEvent);\n                      }\n                    }\n                    // else keep buffering until we see a newline\n                  } else if (\n                    block.buffer.length >= 3 &&\n                    !block.buffer.startsWith('```')\n                  ) {\n                    block.phase = 'streaming';\n                    controller.enqueue(block.startEvent);\n                  }\n                }\n\n                // Stream content\n                if (\n                  block.phase === 'streaming' &&\n                  block.buffer.length > SUFFIX_BUFFER_SIZE\n                ) {\n                  const toStream = block.buffer.slice(0, -SUFFIX_BUFFER_SIZE);\n                  block.buffer = block.buffer.slice(-SUFFIX_BUFFER_SIZE);\n                  controller.enqueue({\n                    type: 'text-delta',\n                    id: chunk.id,\n                    delta: toStream,\n                  });\n                }\n                return;\n              }\n\n              if (chunk.type === 'text-end') {\n                const block = textBlocks[chunk.id];\n                if (block) {\n                  if (block.phase === 'prefix' || block.phase === 'buffering') {\n                    controller.enqueue(block.startEvent);\n                  }\n\n                  let remaining = block.buffer;\n                  if (block.phase === 'buffering') {\n                    remaining = transform(remaining);\n                  } else if (block.prefixStripped) {\n                    // strip suffix since prefix already handled\n                    remaining = remaining.replace(/\\n?```\\s*$/, '').trimEnd();\n                  } else {\n                    // Apply full transform (handles both prefix and suffix)\n                    remaining = transform(remaining);\n                  }\n\n                  if (remaining.length > 0) {\n                    controller.enqueue({\n                      type: 'text-delta',\n                      id: chunk.id,\n                      delta: remaining,\n                    });\n                  }\n                  controller.enqueue(chunk);\n                  delete textBlocks[chunk.id];\n                  return;\n                }\n              }\n              controller.enqueue(chunk);\n            },\n          }),\n        ),\n        ...rest,\n      };\n    },\n  };\n}\n", "/**\n * Finds the potential starting index where searchedText could begin in text.\n *\n * This function checks for both complete and partial matches:\n * - If searchedText is found as a complete substring, returns the index of the first occurrence.\n * - If the end of text matches the beginning of searchedText (partial match),\n *   returns the index where that partial match starts.\n *\n * @param text - The text to search within.\n * @param searchedText - The text to search for.\n * @returns The starting index of the match (complete or partial), or null if\n *          searchedText is empty or no match is found.\n */\nexport function getPotentialStartIndex(\n  text: string,\n  searchedText: string,\n): number | null {\n  // Return null immediately if searchedText is empty.\n  if (searchedText.length === 0) {\n    return null;\n  }\n\n  // Check if the searchedText exists as a direct substring of text.\n  const directIndex = text.indexOf(searchedText);\n  if (directIndex !== -1) {\n    return directIndex;\n  }\n\n  // Otherwise, look for the largest suffix of \"text\" that matches\n  // a prefix of \"searchedText\". We go from the end of text inward.\n  for (let i = text.length - 1; i >= 0; i--) {\n    const suffix = text.substring(i);\n    if (searchedText.startsWith(suffix)) {\n      return i;\n    }\n  }\n\n  return null;\n}\n", "import type {\n  LanguageModelV3Content,\n  LanguageModelV3StreamPart,\n} from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types/language-model-middleware';\nimport { getPotentialStartIndex } from '../util/get-potential-start-index';\n\n/**\n * Extracts an XML-tagged reasoning section from the generated text and exposes it\n * as a `reasoning` property on the result.\n *\n * @param tagName - The name of the XML tag to extract reasoning from.\n * @param separator - The separator to use between reasoning and text sections.\n * @param startWithReasoning - Whether to start with reasoning tokens.\n */\nexport function extractReasoningMiddleware({\n  tagName,\n  separator = '\\n',\n  startWithReasoning = false,\n}: {\n  tagName: string;\n  separator?: string;\n  startWithReasoning?: boolean;\n}): LanguageModelMiddleware {\n  const openingTag = `<${tagName}>`;\n  const closingTag = `<\\/${tagName}>`;\n\n  return {\n    specificationVersion: 'v3',\n    wrapGenerate: async ({ doGenerate }) => {\n      const { content, ...rest } = await doGenerate();\n\n      const transformedContent: LanguageModelV3Content[] = [];\n      for (const part of content) {\n        if (part.type !== 'text') {\n          transformedContent.push(part);\n          continue;\n        }\n\n        const text = startWithReasoning ? openingTag + part.text : part.text;\n\n        const regexp = new RegExp(`${openingTag}(.*?)${closingTag}`, 'gs');\n        const matches = Array.from(text.matchAll(regexp));\n\n        if (!matches.length) {\n          transformedContent.push(part);\n          continue;\n        }\n\n        const reasoningText = matches.map(match => match[1]).join(separator);\n\n        let textWithoutReasoning = text;\n        for (let i = matches.length - 1; i >= 0; i--) {\n          const match = matches[i];\n\n          const beforeMatch = textWithoutReasoning.slice(0, match.index);\n          const afterMatch = textWithoutReasoning.slice(\n            match.index! + match[0].length,\n          );\n\n          textWithoutReasoning =\n            beforeMatch +\n            (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : '') +\n            afterMatch;\n        }\n\n        transformedContent.push({\n          type: 'reasoning',\n          text: reasoningText,\n        });\n\n        transformedContent.push({\n          type: 'text',\n          text: textWithoutReasoning,\n        });\n      }\n\n      return { content: transformedContent, ...rest };\n    },\n\n    wrapStream: async ({ doStream }) => {\n      const { stream, ...rest } = await doStream();\n\n      const reasoningExtractions: Record<\n        string,\n        {\n          isFirstReasoning: boolean;\n          isFirstText: boolean;\n          afterSwitch: boolean;\n          isReasoning: boolean;\n          buffer: string;\n          idCounter: number;\n          textId: string;\n        }\n      > = {};\n\n      let delayedTextStart: LanguageModelV3StreamPart | undefined;\n\n      return {\n        stream: stream.pipeThrough(\n          new TransformStream<\n            LanguageModelV3StreamPart,\n            LanguageModelV3StreamPart\n          >({\n            transform: (chunk, controller) => {\n              // do not send `text-start` before `reasoning-start`\n              // https://github.com/vercel/ai/issues/7774\n              if (chunk.type === 'text-start') {\n                delayedTextStart = chunk;\n                return;\n              }\n\n              if (chunk.type === 'text-end' && delayedTextStart) {\n                controller.enqueue(delayedTextStart);\n                delayedTextStart = undefined;\n              }\n\n              if (chunk.type !== 'text-delta') {\n                controller.enqueue(chunk);\n                return;\n              }\n\n              if (reasoningExtractions[chunk.id] == null) {\n                reasoningExtractions[chunk.id] = {\n                  isFirstReasoning: true,\n                  isFirstText: true,\n                  afterSwitch: false,\n                  isReasoning: startWithReasoning,\n                  buffer: '',\n                  idCounter: 0,\n                  textId: chunk.id,\n                };\n              }\n\n              const activeExtraction = reasoningExtractions[chunk.id];\n\n              activeExtraction.buffer += chunk.delta;\n\n              function publish(text: string) {\n                if (text.length > 0) {\n                  const prefix =\n                    activeExtraction.afterSwitch &&\n                    (activeExtraction.isReasoning\n                      ? !activeExtraction.isFirstReasoning\n                      : !activeExtraction.isFirstText)\n                      ? separator\n                      : '';\n\n                  if (\n                    activeExtraction.isReasoning &&\n                    (activeExtraction.afterSwitch ||\n                      activeExtraction.isFirstReasoning)\n                  ) {\n                    controller.enqueue({\n                      type: 'reasoning-start',\n                      id: `reasoning-${activeExtraction.idCounter}`,\n                    });\n                  }\n\n                  if (activeExtraction.isReasoning) {\n                    controller.enqueue({\n                      type: 'reasoning-delta',\n                      delta: prefix + text,\n                      id: `reasoning-${activeExtraction.idCounter}`,\n                    });\n                  } else {\n                    if (delayedTextStart) {\n                      controller.enqueue(delayedTextStart);\n                      delayedTextStart = undefined;\n                    }\n                    controller.enqueue({\n                      type: 'text-delta',\n                      delta: prefix + text,\n                      id: activeExtraction.textId,\n                    });\n                  }\n                  activeExtraction.afterSwitch = false;\n\n                  if (activeExtraction.isReasoning) {\n                    activeExtraction.isFirstReasoning = false;\n                  } else {\n                    activeExtraction.isFirstText = false;\n                  }\n                }\n              }\n\n              do {\n                const nextTag = activeExtraction.isReasoning\n                  ? closingTag\n                  : openingTag;\n\n                const startIndex = getPotentialStartIndex(\n                  activeExtraction.buffer,\n                  nextTag,\n                );\n\n                // no opening or closing tag found, publish the buffer\n                if (startIndex == null) {\n                  publish(activeExtraction.buffer);\n                  activeExtraction.buffer = '';\n                  break;\n                }\n\n                // publish text before the tag\n                publish(activeExtraction.buffer.slice(0, startIndex));\n\n                const foundFullMatch =\n                  startIndex + nextTag.length <= activeExtraction.buffer.length;\n\n                if (foundFullMatch) {\n                  activeExtraction.buffer = activeExtraction.buffer.slice(\n                    startIndex + nextTag.length,\n                  );\n\n                  if (activeExtraction.isReasoning) {\n                    // Emit reasoning-start for empty reasoning blocks (no delta was published).\n                    // This handles both cases:\n                    // - startWithReasoning=false: <think></think> (afterSwitch=true)\n                    // - startWithReasoning=true: immediate </think> (afterSwitch=false)\n                    if (activeExtraction.isFirstReasoning) {\n                      controller.enqueue({\n                        type: 'reasoning-start',\n                        id: `reasoning-${activeExtraction.idCounter}`,\n                      });\n                    }\n\n                    // reasoning part finished:\n                    controller.enqueue({\n                      type: 'reasoning-end',\n                      id: `reasoning-${activeExtraction.idCounter++}`,\n                    });\n                  }\n\n                  activeExtraction.isReasoning = !activeExtraction.isReasoning;\n                  activeExtraction.afterSwitch = true;\n                } else {\n                  activeExtraction.buffer =\n                    activeExtraction.buffer.slice(startIndex);\n                  break;\n                }\n              } while (true);\n            },\n          }),\n        ),\n        ...rest,\n      };\n    },\n  };\n}\n", "import type { LanguageModelV3StreamPart } from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types';\n\n/**\n * Simulates streaming chunks with the response from a generate call.\n */\nexport function simulateStreamingMiddleware(): LanguageModelMiddleware {\n  return {\n    specificationVersion: 'v3',\n    wrapStream: async ({ doGenerate }) => {\n      const result = await doGenerate();\n\n      let id = 0;\n\n      const simulatedStream = new ReadableStream<LanguageModelV3StreamPart>({\n        start(controller) {\n          controller.enqueue({\n            type: 'stream-start',\n            warnings: result.warnings,\n          });\n\n          controller.enqueue({ type: 'response-metadata', ...result.response });\n\n          for (const part of result.content) {\n            switch (part.type) {\n              case 'text': {\n                if (part.text.length > 0) {\n                  controller.enqueue({ type: 'text-start', id: String(id) });\n                  controller.enqueue({\n                    type: 'text-delta',\n                    id: String(id),\n                    delta: part.text,\n                  });\n                  controller.enqueue({ type: 'text-end', id: String(id) });\n                  id++;\n                }\n                break;\n              }\n              case 'reasoning': {\n                controller.enqueue({\n                  type: 'reasoning-start',\n                  id: String(id),\n                  providerMetadata: part.providerMetadata,\n                });\n                controller.enqueue({\n                  type: 'reasoning-delta',\n                  id: String(id),\n                  delta: part.text,\n                });\n                controller.enqueue({ type: 'reasoning-end', id: String(id) });\n                id++;\n                break;\n              }\n              default: {\n                controller.enqueue(part);\n                break;\n              }\n            }\n          }\n\n          controller.enqueue({\n            type: 'finish',\n            finishReason: result.finishReason,\n            usage: result.usage,\n            providerMetadata: result.providerMetadata,\n          });\n\n          controller.close();\n        },\n      });\n\n      return {\n        stream: simulatedStream,\n        request: result.request,\n        response: result.response,\n      };\n    },\n  };\n}\n", "import type { JSONObject, LanguageModelV3FunctionTool } from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types';\n\nfunction defaultFormatExample(example: { input: JSONObject }): string {\n  return JSON.stringify(example.input);\n}\n\n/**\n * Middleware that appends input examples to tool descriptions.\n *\n * This is useful for providers that don't natively support the `inputExamples`\n * property. The middleware serializes examples into the tool's description text.\n *\n * @param options - Configuration options for the middleware.\n * @param options.prefix - A prefix to prepend before the examples. Default: 'Input Examples:'\n * @param options.format - Optional custom formatter for each example.\n *   Receives the example object and its index. Default: JSON.stringify(example.input)\n * @param options.remove - Whether to remove the inputExamples property\n *   after adding them to the description. Default: true\n *\n * @example\n * ```ts\n * import { wrapLanguageModel, addToolInputExamplesMiddleware } from 'ai';\n *\n * const model = wrapLanguageModel({\n *   model: yourModel,\n *   middleware: addToolInputExamplesMiddleware(),\n * });\n * ```\n */\nexport function addToolInputExamplesMiddleware({\n  prefix = 'Input Examples:',\n  format = defaultFormatExample,\n  remove = true,\n}: {\n  /**\n   * A prefix to prepend before the examples.\n   */\n  prefix?: string;\n\n  /**\n   * Optional custom formatter for each example.\n   * Receives the example object and its index.\n   * Default: JSON.stringify(example.input)\n   */\n  format?: (example: { input: JSONObject }, index: number) => string;\n\n  /**\n   * Whether to remove the inputExamples property after adding them to the description.\n   * Default: true\n   */\n  remove?: boolean;\n} = {}): LanguageModelMiddleware {\n  return {\n    specificationVersion: 'v3',\n    transformParams: async ({ params }) => {\n      if (!params.tools?.length) {\n        return params;\n      }\n\n      const transformedTools = params.tools.map(tool => {\n        // Only transform function tools that have inputExamples\n        if (tool.type !== 'function' || !tool.inputExamples?.length) {\n          return tool;\n        }\n\n        const formattedExamples = tool.inputExamples\n          .map((example, index) => format(example, index))\n          .join('\\n');\n\n        const examplesSection = `${prefix}\\n${formattedExamples}`;\n\n        const toolDescription = tool.description\n          ? `${tool.description}\\n\\n${examplesSection}`\n          : examplesSection;\n\n        return {\n          ...tool,\n          description: toolDescription,\n          inputExamples: remove ? undefined : tool.inputExamples,\n        } satisfies LanguageModelV3FunctionTool;\n      });\n\n      return {\n        ...params,\n        tools: transformedTools,\n      };\n    },\n  };\n}\n", "import type {\n  LanguageModelV3,\n  LanguageModelV3CallOptions,\n  LanguageModelV3GenerateResult,\n  LanguageModelV3StreamResult,\n} from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types';\nimport { asArray } from '../util/as-array';\n\n/**\n * Wraps a LanguageModelV3 instance with middleware functionality.\n * This function allows you to apply middleware to transform parameters,\n * wrap generate operations, and wrap stream operations of a language model.\n *\n * @param options - Configuration options for wrapping the language model.\n * @param options.model - The original LanguageModelV3 instance to be wrapped.\n * @param options.middleware - The middleware to be applied to the language model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.modelId - Optional custom model ID to override the original model's ID.\n * @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n * @returns A new LanguageModelV3 instance with middleware applied.\n */\nexport const wrapLanguageModel = ({\n  model,\n  middleware: middlewareArg,\n  modelId,\n  providerId,\n}: {\n  model: LanguageModelV3;\n  middleware: LanguageModelMiddleware | LanguageModelMiddleware[];\n  modelId?: string;\n  providerId?: string;\n}): LanguageModelV3 => {\n  return [...asArray(middlewareArg)]\n    .reverse()\n    .reduce((wrappedModel, middleware) => {\n      return doWrap({ model: wrappedModel, middleware, modelId, providerId });\n    }, model);\n};\n\nconst doWrap = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapGenerate,\n    wrapStream,\n    overrideProvider,\n    overrideModelId,\n    overrideSupportedUrls,\n  },\n  modelId,\n  providerId,\n}: {\n  model: LanguageModelV3;\n  middleware: LanguageModelMiddleware;\n  modelId?: string;\n  providerId?: string;\n}): LanguageModelV3 => {\n  async function doTransform({\n    params,\n    type,\n  }: {\n    params: LanguageModelV3CallOptions;\n    type: 'generate' | 'stream';\n  }) {\n    return transformParams\n      ? await transformParams({ params, type, model })\n      : params;\n  }\n\n  return {\n    specificationVersion: 'v3',\n\n    provider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n    modelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n    supportedUrls: overrideSupportedUrls?.({ model }) ?? model.supportedUrls,\n\n    async doGenerate(\n      params: LanguageModelV3CallOptions,\n    ): Promise<LanguageModelV3GenerateResult> {\n      const transformedParams = await doTransform({ params, type: 'generate' });\n      const doGenerate = async () => model.doGenerate(transformedParams);\n      const doStream = async () => model.doStream(transformedParams);\n      return wrapGenerate\n        ? wrapGenerate({\n            doGenerate,\n            doStream,\n            params: transformedParams,\n            model,\n          })\n        : doGenerate();\n    },\n\n    async doStream(\n      params: LanguageModelV3CallOptions,\n    ): Promise<LanguageModelV3StreamResult> {\n      const transformedParams = await doTransform({ params, type: 'stream' });\n      const doGenerate = async () => model.doGenerate(transformedParams);\n      const doStream = async () => model.doStream(transformedParams);\n      return wrapStream\n        ? wrapStream({ doGenerate, doStream, params: transformedParams, model })\n        : doStream();\n    },\n  };\n};\n", "import type {\n  EmbeddingModelV3,\n  EmbeddingModelV3CallOptions,\n} from '@ai-sdk/provider';\nimport type { EmbeddingModelMiddleware } from '../types';\nimport { asArray } from '../util/as-array';\n\n/**\n * Wraps an EmbeddingModelV3 instance with middleware functionality.\n * This function allows you to apply middleware to transform parameters,\n * wrap embed operations of an embedding model.\n *\n * @param options - Configuration options for wrapping the embedding model.\n * @param options.model - The original EmbeddingModelV3 instance to be wrapped.\n * @param options.middleware - The middleware to be applied to the embedding model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.modelId - Optional custom model ID to override the original model's ID.\n * @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n * @returns A new EmbeddingModelV3 instance with middleware applied.\n */\nexport const wrapEmbeddingModel = ({\n  model,\n  middleware: middlewareArg,\n  modelId,\n  providerId,\n}: {\n  model: EmbeddingModelV3;\n  middleware: EmbeddingModelMiddleware | EmbeddingModelMiddleware[];\n  modelId?: string;\n  providerId?: string;\n}): EmbeddingModelV3 => {\n  return [...asArray(middlewareArg)]\n    .reverse()\n    .reduce((wrappedModel, middleware) => {\n      return doWrap({ model: wrappedModel, middleware, modelId, providerId });\n    }, model);\n};\n\nconst doWrap = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapEmbed,\n    overrideProvider,\n    overrideModelId,\n    overrideMaxEmbeddingsPerCall,\n    overrideSupportsParallelCalls,\n  },\n  modelId,\n  providerId,\n}: {\n  model: EmbeddingModelV3;\n  middleware: EmbeddingModelMiddleware;\n  modelId?: string;\n  providerId?: string;\n}): EmbeddingModelV3 => {\n  async function doTransform({\n    params,\n  }: {\n    params: EmbeddingModelV3CallOptions;\n  }) {\n    return transformParams ? await transformParams({ params, model }) : params;\n  }\n\n  return {\n    specificationVersion: 'v3',\n    provider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n    modelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n    maxEmbeddingsPerCall:\n      overrideMaxEmbeddingsPerCall?.({ model }) ?? model.maxEmbeddingsPerCall,\n    supportsParallelCalls:\n      overrideSupportsParallelCalls?.({ model }) ?? model.supportsParallelCalls,\n    async doEmbed(\n      params: EmbeddingModelV3CallOptions,\n    ): Promise<Awaited<ReturnType<EmbeddingModelV3['doEmbed']>>> {\n      const transformedParams = await doTransform({ params });\n      const doEmbed = async () => model.doEmbed(transformedParams);\n      return wrapEmbed\n        ? wrapEmbed({\n            doEmbed,\n            params: transformedParams,\n            model,\n          })\n        : doEmbed();\n    },\n  };\n};\n", "import type { ImageModelV3, ImageModelV3CallOptions } from '@ai-sdk/provider';\nimport type { ImageModelMiddleware } from '../types';\nimport { asArray } from '../util/as-array';\n\n/**\n * Wraps an ImageModelV3 instance with middleware functionality.\n * This function allows you to apply middleware to transform parameters\n * and wrap generate operations of an image model.\n *\n * @param options - Configuration options for wrapping the image model.\n * @param options.model - The original ImageModelV3 instance to be wrapped.\n * @param options.middleware - The middleware to be applied to the image model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.modelId - Optional custom model ID to override the original model's ID.\n * @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n * @returns A new ImageModelV3 instance with middleware applied.\n */\nexport const wrapImageModel = ({\n  model,\n  middleware: middlewareArg,\n  modelId,\n  providerId,\n}: {\n  model: ImageModelV3;\n  middleware: ImageModelMiddleware | ImageModelMiddleware[];\n  modelId?: string;\n  providerId?: string;\n}): ImageModelV3 => {\n  return [...asArray(middlewareArg)]\n    .reverse()\n    .reduce((wrappedModel, middleware) => {\n      return doWrap({ model: wrappedModel, middleware, modelId, providerId });\n    }, model);\n};\n\nconst doWrap = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapGenerate,\n    overrideProvider,\n    overrideModelId,\n    overrideMaxImagesPerCall,\n  },\n  modelId,\n  providerId,\n}: {\n  model: ImageModelV3;\n  middleware: ImageModelMiddleware;\n  modelId?: string;\n  providerId?: string;\n}): ImageModelV3 => {\n  async function doTransform({ params }: { params: ImageModelV3CallOptions }) {\n    return transformParams ? await transformParams({ params, model }) : params;\n  }\n\n  const maxImagesPerCallRaw =\n    overrideMaxImagesPerCall?.({ model }) ?? model.maxImagesPerCall;\n\n  // Ensure provider implementations that rely on `this` inside `maxImagesPerCall`\n  // keep working after the value is copied onto the wrapper object.\n  const maxImagesPerCall =\n    maxImagesPerCallRaw instanceof Function\n      ? maxImagesPerCallRaw.bind(model)\n      : maxImagesPerCallRaw;\n\n  return {\n    specificationVersion: 'v3',\n    provider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n    modelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n    maxImagesPerCall,\n    async doGenerate(\n      params: ImageModelV3CallOptions,\n    ): Promise<Awaited<ReturnType<ImageModelV3['doGenerate']>>> {\n      const transformedParams = await doTransform({ params });\n      const doGenerate = async () => model.doGenerate(transformedParams);\n      return wrapGenerate\n        ? wrapGenerate({\n            doGenerate,\n            params: transformedParams,\n            model,\n          })\n        : doGenerate();\n    },\n  };\n};\n", "import type { ProviderV2, ProviderV3 } from '@ai-sdk/provider';\nimport { asEmbeddingModelV3 } from './as-embedding-model-v3';\nimport { asImageModelV3 } from './as-image-model-v3';\nimport { asLanguageModelV3 } from './as-language-model-v3';\nimport { asTranscriptionModelV3 } from './as-transcription-model-v3';\nimport { asSpeechModelV3 } from './as-speech-model-v3';\n\nexport function asProviderV3(provider: ProviderV2 | ProviderV3): ProviderV3 {\n  if (\n    'specificationVersion' in provider &&\n    provider.specificationVersion === 'v3'\n  ) {\n    return provider;\n  }\n\n  // v3 providers have already been returned\n  const v2Provider: ProviderV2 = provider as ProviderV2;\n\n  return {\n    specificationVersion: 'v3',\n    languageModel: (modelId: string) =>\n      asLanguageModelV3(v2Provider.languageModel(modelId)),\n    embeddingModel: (modelId: string) =>\n      asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),\n    imageModel: (modelId: string) =>\n      asImageModelV3(v2Provider.imageModel(modelId)),\n    transcriptionModel: v2Provider.transcriptionModel\n      ? (modelId: string) =>\n          asTranscriptionModelV3(v2Provider.transcriptionModel!(modelId))\n      : undefined,\n    speechModel: v2Provider.speechModel\n      ? (modelId: string) => asSpeechModelV3(v2Provider.speechModel!(modelId))\n      : undefined,\n    rerankingModel: undefined, // v2 providers don't have reranking models\n  };\n}\n", "import type { ProviderV2, ProviderV3 } from '@ai-sdk/provider';\nimport type { ImageModelMiddleware } from '../types/image-model-middleware';\nimport type { LanguageModelMiddleware } from '../types/language-model-middleware';\nimport { wrapImageModel } from './wrap-image-model';\nimport { wrapLanguageModel } from './wrap-language-model';\nimport { asProviderV3 } from '../model/as-provider-v3';\n\n/**\n * Wraps a ProviderV3 instance with middleware functionality.\n * This function allows you to apply middleware to all language models\n * from the provider, enabling you to transform parameters, wrap generate\n * operations, and wrap stream operations for every language model.\n *\n * @param options - Configuration options for wrapping the provider.\n * @param options.provider - The original ProviderV3 instance to be wrapped.\n * @param options.languageModelMiddleware - The middleware to be applied to all language models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @returns A new ProviderV3 instance with middleware applied to all language models.\n */\nexport function wrapProvider({\n  provider,\n  languageModelMiddleware,\n  imageModelMiddleware,\n}: {\n  provider: ProviderV3 | ProviderV2;\n  languageModelMiddleware: LanguageModelMiddleware | LanguageModelMiddleware[];\n  imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];\n}): ProviderV3 {\n  const providerV3 = asProviderV3(provider);\n  return {\n    specificationVersion: 'v3',\n    languageModel: (modelId: string) =>\n      wrapLanguageModel({\n        model: providerV3.languageModel(modelId),\n        middleware: languageModelMiddleware,\n      }),\n    embeddingModel: providerV3.embeddingModel,\n    imageModel: (modelId: string) => {\n      let model = providerV3.imageModel(modelId);\n\n      if (imageModelMiddleware != null) {\n        model = wrapImageModel({ model, middleware: imageModelMiddleware });\n      }\n\n      return model;\n    },\n    transcriptionModel: providerV3.transcriptionModel,\n    speechModel: providerV3.speechModel,\n    rerankingModel: providerV3.rerankingModel,\n  };\n}\n", "import {\n  NoSuchModelError,\n  type EmbeddingModelV3,\n  type Experimental_VideoModelV3,\n  type ImageModelV3,\n  type LanguageModelV3,\n  type ProviderV2,\n  type ProviderV3,\n  type RerankingModelV3,\n  type SpeechModelV3,\n  type TranscriptionModelV3,\n} from '@ai-sdk/provider';\nimport { asProviderV3 } from '../model/as-provider-v3';\n\n/**\n * Creates a custom provider with specified language models, text embedding models, image models, transcription models, speech models, and an optional fallback provider.\n *\n * @param {Object} options - The options for creating the custom provider.\n * @param {Record<string, LanguageModelV3>} [options.languageModels] - A record of language models, where keys are model IDs and values are LanguageModelV3 instances.\n * @param {Record<string, EmbeddingModelV3>} [options.embeddingModels] - A record of text embedding models, where keys are model IDs and values are EmbeddingModelV3 instances.\n * @param {Record<string, ImageModelV3>} [options.imageModels] - A record of image models, where keys are model IDs and values are ImageModelV3 instances.\n * @param {Record<string, TranscriptionModelV3>} [options.transcriptionModels] - A record of transcription models, where keys are model IDs and values are TranscriptionModelV3 instances.\n * @param {Record<string, SpeechModelV3>} [options.speechModels] - A record of speech models, where keys are model IDs and values are SpeechModelV3 instances.\n * @param {Record<string, RerankingModelV3>} [options.rerankingModels] - A record of reranking models, where keys are model IDs and values are RerankingModelV3 instances.\n * @param {ProviderV3} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider.\n * @returns {ProviderV3} A ProviderV3 object with languageModel, embeddingModel, imageModel, transcriptionModel, and speechModel methods.\n *\n * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available.\n */\nexport function customProvider<\n  LANGUAGE_MODELS extends Record<string, LanguageModelV3>,\n  EMBEDDING_MODELS extends Record<string, EmbeddingModelV3>,\n  IMAGE_MODELS extends Record<string, ImageModelV3>,\n  TRANSCRIPTION_MODELS extends Record<string, TranscriptionModelV3>,\n  SPEECH_MODELS extends Record<string, SpeechModelV3>,\n  RERANKING_MODELS extends Record<string, RerankingModelV3>,\n  VIDEO_MODELS extends Record<string, Experimental_VideoModelV3>,\n>({\n  languageModels,\n  embeddingModels,\n  imageModels,\n  transcriptionModels,\n  speechModels,\n  rerankingModels,\n  videoModels,\n  fallbackProvider: fallbackProviderArg,\n}: {\n  languageModels?: LANGUAGE_MODELS;\n  embeddingModels?: EMBEDDING_MODELS;\n  imageModels?: IMAGE_MODELS;\n  transcriptionModels?: TRANSCRIPTION_MODELS;\n  speechModels?: SPEECH_MODELS;\n  rerankingModels?: RERANKING_MODELS;\n  videoModels?: VIDEO_MODELS;\n  fallbackProvider?: ProviderV3 | ProviderV2;\n}): ProviderV3 & {\n  languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV3;\n  embeddingModel(modelId: ExtractModelId<EMBEDDING_MODELS>): EmbeddingModelV3;\n  imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModelV3;\n  transcriptionModel(\n    modelId: ExtractModelId<TRANSCRIPTION_MODELS>,\n  ): TranscriptionModelV3;\n  rerankingModel(modelId: ExtractModelId<RERANKING_MODELS>): RerankingModelV3;\n  speechModel(modelId: ExtractModelId<SPEECH_MODELS>): SpeechModelV3;\n  videoModel(modelId: ExtractModelId<VIDEO_MODELS>): Experimental_VideoModelV3;\n} {\n  const fallbackProvider = fallbackProviderArg\n    ? asProviderV3(fallbackProviderArg)\n    : undefined;\n\n  return {\n    specificationVersion: 'v3',\n    languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV3 {\n      if (languageModels != null && modelId in languageModels) {\n        return languageModels[modelId];\n      }\n\n      if (fallbackProvider) {\n        return (fallbackProvider as ProviderV3).languageModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'languageModel' });\n    },\n\n    embeddingModel(\n      modelId: ExtractModelId<EMBEDDING_MODELS>,\n    ): EmbeddingModelV3 {\n      if (embeddingModels != null && modelId in embeddingModels) {\n        return embeddingModels[modelId];\n      }\n\n      if (fallbackProvider) {\n        return (fallbackProvider as ProviderV3).embeddingModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n    },\n\n    imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModelV3 {\n      if (imageModels != null && modelId in imageModels) {\n        return imageModels[modelId];\n      }\n\n      if (fallbackProvider?.imageModel) {\n        return (fallbackProvider as ProviderV3).imageModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n    },\n\n    transcriptionModel(\n      modelId: ExtractModelId<TRANSCRIPTION_MODELS>,\n    ): TranscriptionModelV3 {\n      if (transcriptionModels != null && modelId in transcriptionModels) {\n        return transcriptionModels[modelId];\n      }\n\n      if (fallbackProvider?.transcriptionModel) {\n        return (fallbackProvider as ProviderV3).transcriptionModel!(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'transcriptionModel' });\n    },\n\n    speechModel(modelId: ExtractModelId<SPEECH_MODELS>): SpeechModelV3 {\n      if (speechModels != null && modelId in speechModels) {\n        return speechModels[modelId];\n      }\n\n      if (fallbackProvider?.speechModel) {\n        return (fallbackProvider as ProviderV3).speechModel!(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'speechModel' });\n    },\n    rerankingModel(\n      modelId: ExtractModelId<RERANKING_MODELS>,\n    ): RerankingModelV3 {\n      if (rerankingModels != null && modelId in rerankingModels) {\n        return rerankingModels[modelId];\n      }\n\n      if (fallbackProvider?.rerankingModel) {\n        return fallbackProvider.rerankingModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'rerankingModel' });\n    },\n    videoModel(\n      modelId: ExtractModelId<VIDEO_MODELS>,\n    ): Experimental_VideoModelV3 {\n      if (videoModels != null && modelId in videoModels) {\n        return videoModels[modelId];\n      }\n\n      // TODO AI SDK v7\n      // @ts-expect-error - videoModel support is experimental\n      const videoModel = fallbackProvider?.videoModel;\n      if (videoModel) {\n        return videoModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'videoModel' });\n    },\n  };\n}\n\n/**\n * @deprecated Use `customProvider` instead.\n */\nexport const experimental_customProvider = customProvider;\n\ntype ExtractModelId<MODELS extends Record<string, unknown>> = Extract<\n  keyof MODELS,\n  string\n>;\n", "import { AISDKError, NoSuchModelError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchProviderError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchProviderError extends NoSuchModelError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly providerId: string;\n  readonly availableProviders: string[];\n\n  constructor({\n    modelId,\n    modelType,\n    providerId,\n    availableProviders,\n    message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`,\n  }: {\n    modelId: string;\n    modelType:\n      | 'languageModel'\n      | 'embeddingModel'\n      | 'imageModel'\n      | 'transcriptionModel'\n      | 'speechModel'\n      | 'rerankingModel';\n    providerId: string;\n    availableProviders: string[];\n    message?: string;\n  }) {\n    super({ errorName: name, modelId, modelType, message });\n\n    this.providerId = providerId;\n    this.availableProviders = availableProviders;\n  }\n\n  static isInstance(error: unknown): error is NoSuchProviderError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import {\n  NoSuchModelError,\n  type EmbeddingModelV3,\n  type ImageModelV3,\n  type LanguageModelV3,\n  type ProviderV3,\n  type RerankingModelV3,\n  type SpeechModelV3,\n  type TranscriptionModelV3,\n} from '@ai-sdk/provider';\nimport { wrapImageModel } from '../middleware/wrap-image-model';\nimport { wrapLanguageModel } from '../middleware/wrap-language-model';\nimport type { ImageModelMiddleware, LanguageModelMiddleware } from '../types';\nimport { NoSuchProviderError } from './no-such-provider-error';\n\ntype ExtractLiteralUnion<T> = T extends string\n  ? string extends T\n    ? never\n    : T\n  : never;\n\nexport interface ProviderRegistryProvider<\n  PROVIDERS extends Record<string, ProviderV3> = Record<string, ProviderV3>,\n  SEPARATOR extends string = ':',\n> {\n  languageModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['languageModel']>>[0]>}`\n      : never,\n  ): LanguageModelV3;\n  languageModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): LanguageModelV3;\n\n  embeddingModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['embeddingModel']>>[0]>}`\n      : never,\n  ): EmbeddingModelV3;\n  embeddingModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): EmbeddingModelV3;\n\n  imageModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['imageModel']>>[0]>}`\n      : never,\n  ): ImageModelV3;\n  imageModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): ImageModelV3;\n\n  transcriptionModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['transcriptionModel']>>[0]>}`\n      : never,\n  ): TranscriptionModelV3;\n  transcriptionModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): TranscriptionModelV3;\n\n  speechModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['speechModel']>>[0]>}`\n      : never,\n  ): SpeechModelV3;\n  speechModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): SpeechModelV3;\n\n  rerankingModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['rerankingModel']>>[0]>}`\n      : never,\n  ): RerankingModelV3;\n  rerankingModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): RerankingModelV3;\n}\n\n/**\n * Creates a registry for the given providers with optional middleware functionality.\n * This function allows you to register multiple providers and optionally apply middleware\n * to all language models from the registry, enabling you to transform parameters, wrap generate\n * operations, and wrap stream operations for every language model accessed through the registry.\n *\n * @param providers - A record of provider instances to be registered in the registry.\n * @param options - Configuration options for the provider registry.\n * @param options.separator - The separator used between provider ID and model ID in the combined identifier. Defaults to ':'.\n * @param options.languageModelMiddleware - Optional middleware to be applied to all language models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @returns A new ProviderRegistryProvider instance that provides access to all registered providers with optional middleware applied to language and image models.\n */\nexport function createProviderRegistry<\n  PROVIDERS extends Record<string, ProviderV3>,\n  SEPARATOR extends string = ':',\n>(\n  providers: PROVIDERS,\n  {\n    separator = ':' as SEPARATOR,\n    languageModelMiddleware,\n    imageModelMiddleware,\n  }: {\n    separator?: SEPARATOR;\n    languageModelMiddleware?:\n      | LanguageModelMiddleware\n      | LanguageModelMiddleware[];\n    imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];\n  } = {},\n): ProviderRegistryProvider<PROVIDERS, SEPARATOR> {\n  const registry = new DefaultProviderRegistry<PROVIDERS, SEPARATOR>({\n    separator,\n    languageModelMiddleware,\n    imageModelMiddleware,\n  });\n\n  for (const [id, provider] of Object.entries(providers)) {\n    registry.registerProvider({ id, provider } as {\n      id: keyof PROVIDERS;\n      provider: PROVIDERS[keyof PROVIDERS];\n    });\n  }\n\n  return registry;\n}\n\n/**\n * @deprecated Use `createProviderRegistry` instead.\n */\nexport const experimental_createProviderRegistry = createProviderRegistry;\n\nclass DefaultProviderRegistry<\n  PROVIDERS extends Record<string, ProviderV3>,\n  SEPARATOR extends string,\n> implements ProviderRegistryProvider<PROVIDERS, SEPARATOR> {\n  private providers: PROVIDERS = {} as PROVIDERS;\n  private separator: SEPARATOR;\n  private languageModelMiddleware?:\n    | LanguageModelMiddleware\n    | LanguageModelMiddleware[];\n  private imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];\n\n  constructor({\n    separator,\n    languageModelMiddleware,\n    imageModelMiddleware,\n  }: {\n    separator: SEPARATOR;\n    languageModelMiddleware?:\n      | LanguageModelMiddleware\n      | LanguageModelMiddleware[];\n    imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];\n  }) {\n    this.separator = separator;\n    this.languageModelMiddleware = languageModelMiddleware;\n    this.imageModelMiddleware = imageModelMiddleware;\n  }\n\n  registerProvider<K extends keyof PROVIDERS>({\n    id,\n    provider,\n  }: {\n    id: K;\n    provider: PROVIDERS[K];\n  }): void {\n    this.providers[id] = provider;\n  }\n\n  private getProvider(\n    id: string,\n    modelType:\n      | 'languageModel'\n      | 'embeddingModel'\n      | 'imageModel'\n      | 'transcriptionModel'\n      | 'speechModel'\n      | 'rerankingModel',\n  ): ProviderV3 {\n    const provider = this.providers[id as keyof PROVIDERS];\n\n    if (provider == null) {\n      throw new NoSuchProviderError({\n        modelId: id,\n        modelType,\n        providerId: id,\n        availableProviders: Object.keys(this.providers),\n      });\n    }\n\n    return provider;\n  }\n\n  private splitId(\n    id: string,\n    modelType:\n      | 'languageModel'\n      | 'embeddingModel'\n      | 'imageModel'\n      | 'transcriptionModel'\n      | 'speechModel'\n      | 'rerankingModel',\n  ): [string, string] {\n    const index = id.indexOf(this.separator);\n\n    if (index === -1) {\n      throw new NoSuchModelError({\n        modelId: id,\n        modelType,\n        message:\n          `Invalid ${modelType} id for registry: ${id} ` +\n          `(must be in the format \"providerId${this.separator}modelId\")`,\n      });\n    }\n\n    return [id.slice(0, index), id.slice(index + this.separator.length)];\n  }\n\n  languageModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): LanguageModelV3 {\n    const [providerId, modelId] = this.splitId(id, 'languageModel');\n    let model = this.getProvider(providerId, 'languageModel').languageModel?.(\n      modelId,\n    );\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'languageModel' });\n    }\n\n    if (this.languageModelMiddleware != null) {\n      model = wrapLanguageModel({\n        model,\n        middleware: this.languageModelMiddleware,\n      });\n    }\n\n    return model;\n  }\n\n  embeddingModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): EmbeddingModelV3 {\n    const [providerId, modelId] = this.splitId(id, 'embeddingModel');\n    const provider = this.getProvider(providerId, 'embeddingModel');\n\n    const model = provider.embeddingModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({\n        modelId: id,\n        modelType: 'embeddingModel',\n      });\n    }\n\n    return model;\n  }\n\n  imageModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): ImageModelV3 {\n    const [providerId, modelId] = this.splitId(id, 'imageModel');\n    const provider = this.getProvider(providerId, 'imageModel');\n\n    let model = provider.imageModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'imageModel' });\n    }\n\n    if (this.imageModelMiddleware != null) {\n      model = wrapImageModel({\n        model,\n        middleware: this.imageModelMiddleware,\n      });\n    }\n\n    return model;\n  }\n\n  transcriptionModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): TranscriptionModelV3 {\n    const [providerId, modelId] = this.splitId(id, 'transcriptionModel');\n    const provider = this.getProvider(providerId, 'transcriptionModel');\n\n    const model = provider.transcriptionModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({\n        modelId: id,\n        modelType: 'transcriptionModel',\n      });\n    }\n\n    return model;\n  }\n\n  speechModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): SpeechModelV3 {\n    const [providerId, modelId] = this.splitId(id, 'speechModel');\n    const provider = this.getProvider(providerId, 'speechModel');\n\n    const model = provider.speechModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'speechModel' });\n    }\n\n    return model;\n  }\n\n  rerankingModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): RerankingModelV3 {\n    const [providerId, modelId] = this.splitId(id, 'rerankingModel');\n    const provider = this.getProvider(providerId, 'rerankingModel');\n\n    const model = provider.rerankingModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'rerankingModel' });\n    }\n\n    return model;\n  }\n}\n", "import type { JSONObject, RerankingModelV3CallOptions } from '@ai-sdk/provider';\nimport type { ProviderOptions } from '@ai-sdk/provider-utils';\nimport { prepareRetries } from '../../src/util/prepare-retries';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport type { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport { resolveRerankingModel } from '../model/resolve-model';\nimport type { RerankingModel } from '../types';\nimport type { RerankResult } from './rerank-result';\nimport { logWarnings } from '../logger/log-warnings';\n\n/**\n * Rerank documents using a reranking model. The type of the value is defined by the reranking model.\n *\n * @param model - The reranking model to use.\n * @param documents - The documents that should be reranked.\n * @param query - The query to rerank the documents against.\n * @param topN - Number of top documents to return.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n * @param providerOptions - Additional provider-specific options.\n * @param experimental_telemetry - Optional telemetry configuration (experimental).\n *\n * @returns A result object that contains the reranked documents, the reranked indices, and additional information.\n */\nexport async function rerank<VALUE extends JSONObject | string>({\n  model: modelArg,\n  documents,\n  query,\n  topN,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  providerOptions,\n  experimental_telemetry: telemetry,\n}: {\n  /**\n   * The reranking model to use.\n   */\n  model: RerankingModel;\n\n  /**\n   * The documents that should be reranked.\n   */\n  documents: Array<VALUE>;\n\n  /**\n   * The query to rerank the documents against.\n   */\n  query: string;\n\n  /**\n   * Number of top documents to return.\n   */\n  topN?: number;\n\n  /**\n   * Maximum number of retries per reranking model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Optional telemetry configuration (experimental).\n   */\n  experimental_telemetry?: TelemetrySettings;\n\n  /**\n   * Additional provider-specific options. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n}): Promise<RerankResult<VALUE>> {\n  const model = resolveRerankingModel(modelArg);\n\n  if (documents.length === 0) {\n    return new DefaultRerankResult({\n      originalDocuments: [],\n      ranking: [],\n      providerMetadata: undefined,\n      response: {\n        timestamp: new Date(),\n        modelId: model.modelId,\n      },\n    });\n  }\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  // detect the type of the documents:\n  const documentsToSend: RerankingModelV3CallOptions['documents'] =\n    typeof documents[0] === 'string'\n      ? { type: 'text', values: documents as string[] }\n      : { type: 'object', values: documents as JSONObject[] };\n\n  const baseTelemetryAttributes = getBaseTelemetryAttributes({\n    model,\n    telemetry,\n    headers,\n    settings: { maxRetries },\n  });\n\n  const tracer = getTracer(telemetry);\n\n  return recordSpan({\n    name: 'ai.rerank',\n    attributes: selectTelemetryAttributes({\n      telemetry,\n      attributes: {\n        ...assembleOperationName({ operationId: 'ai.rerank', telemetry }),\n        ...baseTelemetryAttributes,\n        'ai.documents': {\n          input: () => documents.map(document => JSON.stringify(document)),\n        },\n      },\n    }),\n    tracer,\n    fn: async () => {\n      const { ranking, response, providerMetadata, warnings } = await retry(\n        () =>\n          recordSpan({\n            name: 'ai.rerank.doRerank',\n            attributes: selectTelemetryAttributes({\n              telemetry,\n              attributes: {\n                ...assembleOperationName({\n                  operationId: 'ai.rerank.doRerank',\n                  telemetry,\n                }),\n                ...baseTelemetryAttributes,\n                // specific settings that only make sense on the outer level:\n                'ai.documents': {\n                  input: () =>\n                    documents.map(document => JSON.stringify(document)),\n                },\n              },\n            }),\n            tracer,\n            fn: async doRerankSpan => {\n              const modelResponse = await model.doRerank({\n                documents: documentsToSend,\n                query,\n                topN,\n                providerOptions,\n                abortSignal,\n                headers,\n              });\n\n              const ranking = modelResponse.ranking;\n\n              doRerankSpan.setAttributes(\n                await selectTelemetryAttributes({\n                  telemetry,\n                  attributes: {\n                    'ai.ranking.type': documentsToSend.type,\n                    'ai.ranking': {\n                      output: () =>\n                        ranking.map(ranking => JSON.stringify(ranking)),\n                    },\n                  },\n                }),\n              );\n\n              return {\n                ranking,\n                providerMetadata: modelResponse.providerMetadata,\n                response: modelResponse.response,\n                warnings: modelResponse.warnings,\n              };\n            },\n          }),\n      );\n\n      logWarnings({\n        warnings: warnings ?? [],\n        provider: model.provider,\n        model: model.modelId,\n      });\n\n      return new DefaultRerankResult({\n        originalDocuments: documents,\n        ranking: ranking.map(ranking => ({\n          originalIndex: ranking.index,\n          score: ranking.relevanceScore,\n          document: documents[ranking.index],\n        })),\n        providerMetadata,\n        response: {\n          id: response?.id,\n          timestamp: response?.timestamp ?? new Date(),\n          modelId: response?.modelId ?? model.modelId,\n          headers: response?.headers,\n          body: response?.body,\n        },\n      });\n    },\n  });\n}\n\nclass DefaultRerankResult<VALUE> implements RerankResult<VALUE> {\n  readonly originalDocuments: RerankResult<VALUE>['originalDocuments'];\n  readonly ranking: RerankResult<VALUE>['ranking'];\n  readonly response: RerankResult<VALUE>['response'];\n  readonly providerMetadata: RerankResult<VALUE>['providerMetadata'];\n\n  constructor(options: {\n    originalDocuments: RerankResult<VALUE>['originalDocuments'];\n    ranking: RerankResult<VALUE>['ranking'];\n    providerMetadata?: RerankResult<VALUE>['providerMetadata'];\n    response: RerankResult<VALUE>['response'];\n  }) {\n    this.originalDocuments = options.originalDocuments;\n    this.ranking = options.ranking;\n    this.response = options.response;\n    this.providerMetadata = options.providerMetadata;\n  }\n\n  get rerankedDocuments(): RerankResult<VALUE>['rerankedDocuments'] {\n    return this.ranking.map(ranking => ranking.document);\n  }\n}\n", "import type { JSONObject } from '@ai-sdk/provider';\nimport {\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoTranscriptGeneratedError } from '../error/no-transcript-generated-error';\nimport { logWarnings } from '../logger/log-warnings';\nimport type { DataContent } from '../prompt';\nimport { convertDataContentToUint8Array } from '../prompt/data-content';\nimport type { TranscriptionModel } from '../types/transcription-model';\nimport type { TranscriptionModelResponseMetadata } from '../types/transcription-model-response-metadata';\nimport {\n  audioMediaTypeSignatures,\n  detectMediaType,\n} from '../util/detect-media-type';\nimport { createDownload } from '../util/download/create-download';\nimport { prepareRetries } from '../util/prepare-retries';\nimport type { TranscriptionResult } from './transcribe-result';\nimport { VERSION } from '../version';\nimport { resolveTranscriptionModel } from '../model/resolve-model';\nimport type { Warning } from '../types';\n/**\n * Generates transcripts using a transcription model.\n *\n * @param model - The transcription model to use.\n * @param audio - The audio data to transcribe as DataContent (string | Uint8Array | ArrayBuffer | Buffer) or a URL.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @returns A result object that contains the generated transcript.\n */\nconst defaultDownload = createDownload();\n\nexport async function transcribe({\n  model,\n  audio,\n  providerOptions = {},\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  download: downloadFn = defaultDownload,\n}: {\n  /**\n   * The transcription model to use.\n   */\n  model: TranscriptionModel;\n\n  /**\n   * The audio data to transcribe.\n   */\n  audio: DataContent | URL;\n\n  /**\n   * Additional provider-specific options that are passed through to the provider\n   * as body parameters.\n   *\n   * The outer record is keyed by the provider name, and the inner\n   * record is keyed by the provider-specific metadata key.\n   * ```ts\n   * {\n   *   \"openai\": {\n   *     \"temperature\": 0\n   *   }\n   * }\n   * ```\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of retries per transcript model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Custom download function for fetching audio from URLs.\n   * Use `createDownload()` from `ai` to create a download function with custom size limits.\n   *\n   * @default createDownload() (2 GiB limit)\n   */\n  download?: (options: {\n    url: URL;\n    abortSignal?: AbortSignal;\n  }) => Promise<{ data: Uint8Array; mediaType: string | undefined }>;\n}): Promise<TranscriptionResult> {\n  const resolvedModel = resolveTranscriptionModel(model);\n  if (!resolvedModel) {\n    throw new Error('Model could not be resolved');\n  }\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const audioData =\n    audio instanceof URL\n      ? (await downloadFn({ url: audio, abortSignal })).data\n      : convertDataContentToUint8Array(audio);\n\n  const result = await retry(() =>\n    resolvedModel.doGenerate({\n      audio: audioData,\n      abortSignal,\n      headers: headersWithUserAgent,\n      providerOptions,\n      mediaType:\n        detectMediaType({\n          data: audioData,\n          signatures: audioMediaTypeSignatures,\n        }) ?? 'audio/wav',\n    }),\n  );\n\n  logWarnings({\n    warnings: result.warnings,\n    provider: resolvedModel.provider,\n    model: resolvedModel.modelId,\n  });\n\n  if (!result.text) {\n    throw new NoTranscriptGeneratedError({ responses: [result.response] });\n  }\n\n  return new DefaultTranscriptionResult({\n    text: result.text,\n    segments: result.segments,\n    language: result.language,\n    durationInSeconds: result.durationInSeconds,\n    warnings: result.warnings,\n    responses: [result.response],\n    providerMetadata: result.providerMetadata,\n  });\n}\n\nclass DefaultTranscriptionResult implements TranscriptionResult {\n  readonly text: string;\n  readonly segments: Array<{\n    text: string;\n    startSecond: number;\n    endSecond: number;\n  }>;\n  readonly language: string | undefined;\n  readonly durationInSeconds: number | undefined;\n  readonly warnings: Array<Warning>;\n  readonly responses: Array<TranscriptionModelResponseMetadata>;\n  readonly providerMetadata: Record<string, JSONObject>;\n\n  constructor(options: {\n    text: string;\n    segments: Array<{\n      text: string;\n      startSecond: number;\n      endSecond: number;\n    }>;\n    language: string | undefined;\n    durationInSeconds: number | undefined;\n    warnings: Array<Warning>;\n    responses: Array<TranscriptionModelResponseMetadata>;\n    providerMetadata: Record<string, JSONObject> | undefined;\n  }) {\n    this.text = options.text;\n    this.segments = options.segments;\n    this.language = options.language;\n    this.durationInSeconds = options.durationInSeconds;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = options.providerMetadata ?? {};\n  }\n}\n", "import {\n  parseJsonEventStream,\n  withUserAgentSuffix,\n  getRuntimeEnvironmentUserAgent,\n  type ParseResult,\n} from '@ai-sdk/provider-utils';\nimport {\n  uiMessageChunkSchema,\n  type UIMessageChunk,\n} from '../ui-message-stream/ui-message-chunks';\nimport { consumeStream } from '../util/consume-stream';\nimport { processTextStream } from './process-text-stream';\nimport { VERSION } from '../version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport async function callCompletionApi({\n  api,\n  prompt,\n  credentials,\n  headers,\n  body,\n  streamProtocol = 'data',\n  setCompletion,\n  setLoading,\n  setError,\n  setAbortController,\n  onFinish,\n  onError,\n  fetch = getOriginalFetch(),\n}: {\n  api: string;\n  prompt: string;\n  credentials: RequestCredentials | undefined;\n  headers: HeadersInit | undefined;\n  body: Record<string, any>;\n  streamProtocol: 'data' | 'text' | undefined;\n  setCompletion: (completion: string) => void;\n  setLoading: (loading: boolean) => void;\n  setError: (error: Error | undefined) => void;\n  setAbortController: (abortController: AbortController | null) => void;\n  onFinish: ((prompt: string, completion: string) => void) | undefined;\n  onError: ((error: Error) => void) | undefined;\n  fetch: ReturnType<typeof getOriginalFetch> | undefined;\n}) {\n  try {\n    setLoading(true);\n    setError(undefined);\n\n    const abortController = new AbortController();\n    setAbortController(abortController);\n\n    // Empty the completion immediately.\n    setCompletion('');\n\n    const response = await fetch(api, {\n      method: 'POST',\n      body: JSON.stringify({\n        prompt,\n        ...body,\n      }),\n      credentials,\n      headers: withUserAgentSuffix(\n        {\n          'Content-Type': 'application/json',\n          ...headers,\n        },\n        `ai-sdk/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      signal: abortController.signal,\n    }).catch(err => {\n      throw err;\n    });\n\n    if (!response.ok) {\n      throw new Error(\n        (await response.text()) ?? 'Failed to fetch the chat response.',\n      );\n    }\n\n    if (!response.body) {\n      throw new Error('The response body is empty.');\n    }\n\n    let result = '';\n\n    switch (streamProtocol) {\n      case 'text': {\n        await processTextStream({\n          stream: response.body,\n          onTextPart: chunk => {\n            result += chunk;\n            setCompletion(result);\n          },\n        });\n        break;\n      }\n      case 'data': {\n        await consumeStream({\n          stream: parseJsonEventStream({\n            stream: response.body,\n            schema: uiMessageChunkSchema,\n          }).pipeThrough(\n            new TransformStream<ParseResult<UIMessageChunk>, UIMessageChunk>({\n              async transform(part) {\n                if (!part.success) {\n                  throw part.error;\n                }\n\n                const streamPart = part.value;\n                if (streamPart.type === 'text-delta') {\n                  result += streamPart.delta;\n                  setCompletion(result);\n                } else if (streamPart.type === 'error') {\n                  throw new Error(streamPart.errorText);\n                }\n              },\n            }),\n          ),\n          onError: error => {\n            throw error;\n          },\n        });\n        break;\n      }\n      default: {\n        const exhaustiveCheck: never = streamProtocol;\n        throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);\n      }\n    }\n\n    if (onFinish) {\n      onFinish(prompt, result);\n    }\n\n    setAbortController(null);\n    return result;\n  } catch (err) {\n    // Ignore abort errors as they are expected.\n    if ((err as any).name === 'AbortError') {\n      setAbortController(null);\n      return null;\n    }\n\n    if (err instanceof Error) {\n      if (onError) {\n        onError(err);\n      }\n    }\n\n    setError(err as Error);\n  } finally {\n    setLoading(false);\n  }\n}\n", "export async function processTextStream({\n  stream,\n  onTextPart,\n}: {\n  stream: ReadableStream<Uint8Array>;\n  onTextPart: (chunk: string) => Promise<void> | void;\n}): Promise<void> {\n  const reader = stream.pipeThrough(new TextDecoderStream()).getReader();\n  while (true) {\n    const { done, value } = await reader.read();\n    if (done) {\n      break;\n    }\n    await onTextPart(value);\n  }\n}\n", "import {\n  generateId as generateIdFunc,\n  type FlexibleSchema,\n  type IdGenerator,\n  type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport type { FinishReason } from '../types/language-model';\nimport type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport { consumeStream } from '../util/consume-stream';\nimport { SerialJobExecutor } from '../util/serial-job-executor';\nimport type { ChatTransport } from './chat-transport';\nimport { convertFileListToFileUIParts } from './convert-file-list-to-file-ui-parts';\nimport { DefaultChatTransport } from './default-chat-transport';\nimport {\n  createStreamingUIMessageState,\n  processUIMessageStream,\n  type StreamingUIMessageState,\n} from './process-ui-message-stream';\nimport {\n  isToolUIPart,\n  type InferUIMessageToolCall,\n  type UIMessagePart,\n  type UITools,\n  type DataUIPart,\n  type FileUIPart,\n  type InferUIMessageData,\n  type InferUIMessageMetadata,\n  type InferUIMessageTools,\n  type UIDataTypes,\n  type UIMessage,\n} from './ui-messages';\n\nexport type CreateUIMessage<UI_MESSAGE extends UIMessage> = Omit<\n  UI_MESSAGE,\n  'id' | 'role'\n> & {\n  id?: UI_MESSAGE['id'];\n  role?: UI_MESSAGE['role'];\n};\n\nexport type UIDataPartSchemas = Record<string, FlexibleSchema>;\n\nexport type UIDataTypesToSchemas<T extends UIDataTypes> = {\n  [K in keyof T]: FlexibleSchema<T[K]>;\n};\n\nexport type InferUIDataParts<T extends UIDataPartSchemas> = {\n  [K in keyof T]: InferSchema<T[K]>;\n};\n\nexport type ChatRequestOptions = {\n  /**\n   * Additional headers that should be to be passed to the API endpoint.\n   */\n  headers?: Record<string, string> | Headers;\n\n  /**\n   * Additional body JSON properties that should be sent to the API endpoint.\n   */\n  body?: object; // TODO JSONStringifyable\n\n  metadata?: unknown;\n};\n\n/**\n * Function that can be called to add a tool approval response to the chat.\n */\nexport type ChatAddToolApproveResponseFunction = ({\n  id,\n  approved,\n  reason,\n  options,\n}: {\n  id: string;\n\n  /**\n   * Flag indicating whether the approval was granted or denied.\n   */\n  approved: boolean;\n\n  /**\n   * Optional reason for the approval or denial.\n   */\n  reason?: string;\n\n  /**\n   * Optional request options to be used if `sendAutomaticallyWhen` callback returns true.\n   */\n  options?: ChatRequestOptions;\n}) => void | PromiseLike<void>;\n\n/**\n * Function that can be called to add a tool output to the chat.\n */\nexport type ChatAddToolOutputFunction<UI_MESSAGE extends UIMessage> = <\n  TOOL extends keyof InferUIMessageTools<UI_MESSAGE>,\n>({\n  state,\n  tool,\n  toolCallId,\n  output,\n  errorText,\n  options,\n}: {\n  /**\n   * Name of the tool that was called.\n   */\n  tool: TOOL;\n\n  /**\n   * Identifier of the tool call to add output for.\n   */\n  toolCallId: string;\n\n  /**\n   * Optional request options to be used if `sendAutomaticallyWhen` callback returns true.\n   */\n  options?: ChatRequestOptions;\n} & (\n  | {\n      state?: 'output-available';\n      output: InferUIMessageTools<UI_MESSAGE>[TOOL]['output'];\n      errorText?: never;\n    }\n  | {\n      state: 'output-error';\n      output?: never;\n      errorText: string;\n    }\n)) => void | PromiseLike<void>;\n\nexport type ChatStatus = 'submitted' | 'streaming' | 'ready' | 'error';\n\ntype ActiveResponse<UI_MESSAGE extends UIMessage> = {\n  state: StreamingUIMessageState<UI_MESSAGE>;\n  abortController: AbortController;\n};\n\nexport interface ChatState<UI_MESSAGE extends UIMessage> {\n  status: ChatStatus;\n\n  error: Error | undefined;\n\n  messages: UI_MESSAGE[];\n  pushMessage: (message: UI_MESSAGE) => void;\n  popMessage: () => void;\n  replaceMessage: (index: number, message: UI_MESSAGE) => void;\n\n  snapshot: <T>(thing: T) => T;\n}\n\nexport type ChatOnErrorCallback = (error: Error) => void;\n\nexport type ChatOnToolCallCallback<UI_MESSAGE extends UIMessage = UIMessage> =\n  (options: {\n    toolCall: InferUIMessageToolCall<UI_MESSAGE>;\n  }) => void | PromiseLike<void>;\n\nexport type ChatOnDataCallback<UI_MESSAGE extends UIMessage> = (\n  dataPart: DataUIPart<InferUIMessageData<UI_MESSAGE>>,\n) => void;\n\n/**\n * Function that is called when the assistant response has finished streaming.\n *\n * @param message The assistant message that was streamed.\n * @param messages The full chat history, including the assistant message.\n *\n * @param isAbort Indicates whether the request has been aborted.\n * @param isDisconnect Indicates whether the request has been ended by a network error.\n * @param isError Indicates whether the request has been ended by an error.\n * @param finishReason The reason why the generation finished.\n */\nexport type ChatOnFinishCallback<UI_MESSAGE extends UIMessage> = (options: {\n  message: UI_MESSAGE;\n  messages: UI_MESSAGE[];\n  isAbort: boolean;\n  isDisconnect: boolean;\n  isError: boolean;\n  finishReason?: FinishReason;\n}) => void;\n\nexport interface ChatInit<UI_MESSAGE extends UIMessage> {\n  /**\n   * A unique identifier for the chat. If not provided, a random one will be\n   * generated.\n   */\n  id?: string;\n\n  messageMetadataSchema?: FlexibleSchema<InferUIMessageMetadata<UI_MESSAGE>>;\n  dataPartSchemas?: UIDataTypesToSchemas<InferUIMessageData<UI_MESSAGE>>;\n\n  messages?: UI_MESSAGE[];\n\n  /**\n   * A way to provide a function that is going to be used for ids for messages and the chat.\n   * If not provided the default AI SDK `generateId` is used.\n   */\n  generateId?: IdGenerator;\n\n  transport?: ChatTransport<UI_MESSAGE>;\n\n  /**\n   * Callback function to be called when an error is encountered.\n   */\n  onError?: ChatOnErrorCallback;\n\n  /**\n   * Optional callback function that is invoked when a tool call is received.\n   * Intended for automatic client-side tool execution.\n   *\n   * You can optionally return a result for the tool call,\n   * either synchronously or asynchronously.\n   */\n  onToolCall?: ChatOnToolCallCallback<UI_MESSAGE>;\n\n  /**\n   * Function that is called when the assistant response has finished streaming.\n   */\n  onFinish?: ChatOnFinishCallback<UI_MESSAGE>;\n\n  /**\n   * Optional callback function that is called when a data part is received.\n   *\n   * @param data The data part that was received.\n   */\n  onData?: ChatOnDataCallback<UI_MESSAGE>;\n\n  /**\n   * When provided, this function will be called when the stream is finished or a tool call is added\n   * to determine if the current messages should be resubmitted.\n   */\n  sendAutomaticallyWhen?: (options: {\n    messages: UI_MESSAGE[];\n  }) => boolean | PromiseLike<boolean>;\n}\n\nexport abstract class AbstractChat<UI_MESSAGE extends UIMessage> {\n  readonly id: string;\n  readonly generateId: IdGenerator;\n\n  protected state: ChatState<UI_MESSAGE>;\n\n  private messageMetadataSchema:\n    | FlexibleSchema<InferUIMessageMetadata<UI_MESSAGE>>\n    | undefined;\n  private dataPartSchemas:\n    | UIDataTypesToSchemas<InferUIMessageData<UI_MESSAGE>>\n    | undefined;\n  private readonly transport: ChatTransport<UI_MESSAGE>;\n  private onError?: ChatInit<UI_MESSAGE>['onError'];\n  private onToolCall?: ChatInit<UI_MESSAGE>['onToolCall'];\n  private onFinish?: ChatInit<UI_MESSAGE>['onFinish'];\n  private onData?: ChatInit<UI_MESSAGE>['onData'];\n  private sendAutomaticallyWhen?: ChatInit<UI_MESSAGE>['sendAutomaticallyWhen'];\n\n  private activeResponse: ActiveResponse<UI_MESSAGE> | undefined = undefined;\n  private jobExecutor = new SerialJobExecutor();\n\n  constructor({\n    generateId = generateIdFunc,\n    id = generateId(),\n    transport = new DefaultChatTransport(),\n    messageMetadataSchema,\n    dataPartSchemas,\n    state,\n    onError,\n    onToolCall,\n    onFinish,\n    onData,\n    sendAutomaticallyWhen,\n  }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {\n    state: ChatState<UI_MESSAGE>;\n  }) {\n    this.id = id;\n    this.transport = transport;\n    this.generateId = generateId;\n    this.messageMetadataSchema = messageMetadataSchema;\n    this.dataPartSchemas = dataPartSchemas;\n    this.state = state;\n    this.onError = onError;\n    this.onToolCall = onToolCall;\n    this.onFinish = onFinish;\n    this.onData = onData;\n    this.sendAutomaticallyWhen = sendAutomaticallyWhen;\n  }\n\n  /**\n   * Hook status:\n   *\n   * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n   * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n   * - `ready`: The full response has been received and processed; a new user message can be submitted.\n   * - `error`: An error occurred during the API request, preventing successful completion.\n   */\n  get status(): ChatStatus {\n    return this.state.status;\n  }\n\n  protected setStatus({\n    status,\n    error,\n  }: {\n    status: ChatStatus;\n    error?: Error;\n  }) {\n    if (this.status === status) return;\n\n    this.state.status = status;\n    this.state.error = error;\n  }\n\n  get error() {\n    return this.state.error;\n  }\n\n  get messages(): UI_MESSAGE[] {\n    return this.state.messages;\n  }\n\n  get lastMessage(): UI_MESSAGE | undefined {\n    return this.state.messages[this.state.messages.length - 1];\n  }\n\n  set messages(messages: UI_MESSAGE[]) {\n    this.state.messages = messages;\n  }\n\n  /**\n   * Appends or replaces a user message to the chat list. This triggers the API call to fetch\n   * the assistant's response.\n   *\n   * If a messageId is provided, the message will be replaced.\n   */\n  sendMessage = async (\n    message?:\n      | (CreateUIMessage<UI_MESSAGE> & {\n          text?: never;\n          files?: never;\n          messageId?: string;\n        })\n      | {\n          text: string;\n          files?: FileList | FileUIPart[];\n          metadata?: InferUIMessageMetadata<UI_MESSAGE>;\n          parts?: never;\n          messageId?: string;\n        }\n      | {\n          files: FileList | FileUIPart[];\n          metadata?: InferUIMessageMetadata<UI_MESSAGE>;\n          parts?: never;\n          messageId?: string;\n        },\n    options?: ChatRequestOptions,\n  ): Promise<void> => {\n    if (message == null) {\n      await this.makeRequest({\n        trigger: 'submit-message',\n        messageId: this.lastMessage?.id,\n        ...options,\n      });\n      return;\n    }\n\n    let uiMessage: CreateUIMessage<UI_MESSAGE>;\n\n    if ('text' in message || 'files' in message) {\n      const fileParts = Array.isArray(message.files)\n        ? message.files\n        : await convertFileListToFileUIParts(message.files);\n\n      uiMessage = {\n        parts: [\n          ...fileParts,\n          ...('text' in message && message.text != null\n            ? [{ type: 'text' as const, text: message.text }]\n            : []),\n        ],\n      } as UI_MESSAGE;\n    } else {\n      uiMessage = message;\n    }\n\n    if (message.messageId != null) {\n      const messageIndex = this.state.messages.findIndex(\n        m => m.id === message.messageId,\n      );\n\n      if (messageIndex === -1) {\n        throw new Error(`message with id ${message.messageId} not found`);\n      }\n\n      if (this.state.messages[messageIndex].role !== 'user') {\n        throw new Error(\n          `message with id ${message.messageId} is not a user message`,\n        );\n      }\n\n      // remove all messages after the message with the given id\n      this.state.messages = this.state.messages.slice(0, messageIndex + 1);\n\n      // update the message with the new content\n      this.state.replaceMessage(messageIndex, {\n        ...uiMessage,\n        id: message.messageId,\n        role: uiMessage.role ?? 'user',\n        metadata: message.metadata,\n      } as UI_MESSAGE);\n    } else {\n      this.state.pushMessage({\n        ...uiMessage,\n        id: uiMessage.id ?? this.generateId(),\n        role: uiMessage.role ?? 'user',\n        metadata: message.metadata,\n      } as UI_MESSAGE);\n    }\n\n    await this.makeRequest({\n      trigger: 'submit-message',\n      messageId: message.messageId,\n      ...options,\n    });\n  };\n\n  /**\n   * Regenerate the assistant message with the provided message id.\n   * If no message id is provided, the last assistant message will be regenerated.\n   */\n  regenerate = async ({\n    messageId,\n    ...options\n  }: {\n    messageId?: string;\n  } & ChatRequestOptions = {}): Promise<void> => {\n    const messageIndex =\n      messageId == null\n        ? this.state.messages.length - 1\n        : this.state.messages.findIndex(message => message.id === messageId);\n\n    if (messageIndex === -1) {\n      throw new Error(`message ${messageId} not found`);\n    }\n\n    // set the messages to the message before the assistant message\n    this.state.messages = this.state.messages.slice(\n      0,\n      // if the message is a user message, we need to include it in the request:\n      this.messages[messageIndex].role === 'assistant'\n        ? messageIndex\n        : messageIndex + 1,\n    );\n\n    await this.makeRequest({\n      trigger: 'regenerate-message',\n      messageId,\n      ...options,\n    });\n  };\n\n  /**\n   * Attempt to resume an ongoing streaming response.\n   */\n  resumeStream = async (options: ChatRequestOptions = {}): Promise<void> => {\n    await this.makeRequest({ trigger: 'resume-stream', ...options });\n  };\n\n  /**\n   * Clear the error state and set the status to ready if the chat is in an error state.\n   */\n  clearError = () => {\n    if (this.status === 'error') {\n      this.state.error = undefined;\n      this.setStatus({ status: 'ready' });\n    }\n  };\n\n  addToolApprovalResponse: ChatAddToolApproveResponseFunction = async ({\n    id,\n    approved,\n    reason,\n    options,\n  }) =>\n    this.jobExecutor.run(async () => {\n      const messages = this.state.messages;\n      const lastMessage = messages[messages.length - 1];\n\n      const updatePart = (\n        part: UIMessagePart<UIDataTypes, UITools>,\n      ): UIMessagePart<UIDataTypes, UITools> =>\n        isToolUIPart(part) &&\n        part.state === 'approval-requested' &&\n        part.approval.id === id\n          ? {\n              ...part,\n              state: 'approval-responded',\n              approval: { id, approved, reason },\n            }\n          : part;\n\n      // update the message to trigger an immediate UI update\n      this.state.replaceMessage(messages.length - 1, {\n        ...lastMessage,\n        parts: lastMessage.parts.map(updatePart),\n      });\n\n      // update the active response if it exists\n      if (this.activeResponse) {\n        this.activeResponse.state.message.parts =\n          this.activeResponse.state.message.parts.map(updatePart);\n      }\n\n      // automatically send the message if the sendAutomaticallyWhen function returns true\n      if (\n        this.status !== 'streaming' &&\n        this.status !== 'submitted' &&\n        this.sendAutomaticallyWhen\n      ) {\n        this.shouldSendAutomatically().then(shouldSend => {\n          if (shouldSend) {\n            // no await to avoid deadlocking\n            this.makeRequest({\n              trigger: 'submit-message',\n              messageId: this.lastMessage?.id,\n              ...options,\n            });\n          }\n        });\n      }\n    });\n\n  addToolOutput: ChatAddToolOutputFunction<UI_MESSAGE> = async ({\n    state = 'output-available',\n    toolCallId,\n    output,\n    errorText,\n    options,\n  }) =>\n    this.jobExecutor.run(async () => {\n      const messages = this.state.messages;\n      const lastMessage = messages[messages.length - 1];\n\n      const updatePart = (\n        part: UIMessagePart<UIDataTypes, UITools>,\n      ): UIMessagePart<UIDataTypes, UITools> =>\n        isToolUIPart(part) && part.toolCallId === toolCallId\n          ? ({ ...part, state, output, errorText } as typeof part)\n          : part;\n\n      // update the message to trigger an immediate UI update\n      this.state.replaceMessage(messages.length - 1, {\n        ...lastMessage,\n        parts: lastMessage.parts.map(updatePart),\n      });\n\n      // update the active response if it exists\n      if (this.activeResponse) {\n        this.activeResponse.state.message.parts =\n          this.activeResponse.state.message.parts.map(updatePart);\n      }\n\n      // automatically send the message if the sendAutomaticallyWhen function returns true\n      if (\n        this.status !== 'streaming' &&\n        this.status !== 'submitted' &&\n        this.sendAutomaticallyWhen\n      ) {\n        this.shouldSendAutomatically().then(shouldSend => {\n          if (shouldSend) {\n            // no await to avoid deadlocking\n            this.makeRequest({\n              trigger: 'submit-message',\n              messageId: this.lastMessage?.id,\n              ...options,\n            });\n          }\n        });\n      }\n    });\n\n  /** @deprecated Use addToolOutput */\n  addToolResult = this.addToolOutput;\n\n  /**\n   * Abort the current request immediately, keep the generated tokens if any.\n   */\n  stop = async () => {\n    if (this.status !== 'streaming' && this.status !== 'submitted') return;\n\n    if (this.activeResponse?.abortController) {\n      this.activeResponse.abortController.abort();\n    }\n  };\n\n  private async shouldSendAutomatically(): Promise<boolean> {\n    if (!this.sendAutomaticallyWhen) return false;\n\n    const result = this.sendAutomaticallyWhen({\n      messages: this.state.messages,\n    });\n\n    // Check if result is a promise\n    if (result && typeof result === 'object' && 'then' in result) {\n      return await result;\n    }\n\n    return result as boolean;\n  }\n\n  private async makeRequest({\n    trigger,\n    metadata,\n    headers,\n    body,\n    messageId,\n  }: {\n    trigger: 'submit-message' | 'resume-stream' | 'regenerate-message';\n    messageId?: string;\n  } & ChatRequestOptions) {\n    // For resume-stream, check if there's an active stream before\n    // changing status. This avoids a brief flash of 'submitted' status\n    // when there is no stream to resume (e.g. on page load).\n    let resumeStream: ReadableStream<UIMessageChunk> | undefined;\n    if (trigger === 'resume-stream') {\n      try {\n        const reconnect = await this.transport.reconnectToStream({\n          chatId: this.id,\n          metadata,\n          headers,\n          body,\n        });\n\n        if (reconnect == null) {\n          return; // no active stream found, so we do not resume\n        }\n\n        resumeStream = reconnect;\n      } catch (err) {\n        if (this.onError && err instanceof Error) {\n          this.onError(err);\n        }\n        this.setStatus({ status: 'error', error: err as Error });\n        return;\n      }\n    }\n\n    this.setStatus({ status: 'submitted', error: undefined });\n\n    const lastMessage = this.lastMessage;\n\n    let isAbort = false;\n    let isDisconnect = false;\n    let isError = false;\n\n    try {\n      const activeResponse = {\n        state: createStreamingUIMessageState({\n          lastMessage: this.state.snapshot(lastMessage),\n          messageId: this.generateId(),\n        }),\n        abortController: new AbortController(),\n      } as ActiveResponse<UI_MESSAGE>;\n\n      activeResponse.abortController.signal.addEventListener('abort', () => {\n        isAbort = true;\n      });\n\n      this.activeResponse = activeResponse;\n\n      let stream: ReadableStream<UIMessageChunk>;\n\n      if (trigger === 'resume-stream') {\n        stream = resumeStream!;\n      } else {\n        stream = await this.transport.sendMessages({\n          chatId: this.id,\n          messages: this.state.messages,\n          abortSignal: activeResponse.abortController.signal,\n          metadata,\n          headers,\n          body,\n          trigger,\n          messageId,\n        });\n      }\n\n      const runUpdateMessageJob = (\n        job: (options: {\n          state: StreamingUIMessageState<UI_MESSAGE>;\n          write: () => void;\n        }) => Promise<void>,\n      ) =>\n        // serialize the job execution to avoid race conditions:\n        this.jobExecutor.run(() =>\n          job({\n            state: activeResponse.state,\n            write: () => {\n              // streaming is set on first write (before it should be \"submitted\")\n              this.setStatus({ status: 'streaming' });\n\n              const replaceLastMessage =\n                activeResponse.state.message.id === this.lastMessage?.id;\n\n              if (replaceLastMessage) {\n                this.state.replaceMessage(\n                  this.state.messages.length - 1,\n                  activeResponse.state.message,\n                );\n              } else {\n                this.state.pushMessage(activeResponse.state.message);\n              }\n            },\n          }),\n        );\n\n      await consumeStream({\n        stream: processUIMessageStream({\n          stream,\n          onToolCall: this.onToolCall,\n          onData: this.onData,\n          messageMetadataSchema: this.messageMetadataSchema,\n          dataPartSchemas: this.dataPartSchemas,\n          runUpdateMessageJob,\n          onError: error => {\n            throw error;\n          },\n        }),\n        onError: error => {\n          throw error;\n        },\n      });\n\n      this.setStatus({ status: 'ready' });\n    } catch (err) {\n      // Ignore abort errors as they are expected.\n      if (isAbort || (err as any).name === 'AbortError') {\n        isAbort = true;\n        this.setStatus({ status: 'ready' });\n        return null;\n      }\n\n      isError = true;\n\n      // Network errors such as disconnected, timeout, etc.\n      if (\n        err instanceof TypeError &&\n        (err.message.toLowerCase().includes('fetch') ||\n          err.message.toLowerCase().includes('network'))\n      ) {\n        isDisconnect = true;\n      }\n\n      if (this.onError && err instanceof Error) {\n        this.onError(err);\n      }\n\n      this.setStatus({ status: 'error', error: err as Error });\n    } finally {\n      try {\n        this.onFinish?.({\n          message: this.activeResponse!.state.message,\n          messages: this.state.messages,\n          isAbort,\n          isDisconnect,\n          isError,\n          finishReason: this.activeResponse?.state.finishReason,\n        });\n      } catch (err) {\n        console.error(err);\n      }\n\n      this.activeResponse = undefined;\n    }\n\n    // automatically send the message if the sendAutomaticallyWhen function returns true\n    if (!isError && (await this.shouldSendAutomatically())) {\n      await this.makeRequest({\n        trigger: 'submit-message',\n        messageId: this.lastMessage?.id,\n        metadata,\n        headers,\n        body,\n      });\n    }\n  }\n}\n", "import type { FileUIPart } from './ui-messages';\n\nexport async function convertFileListToFileUIParts(\n  files: FileList | undefined,\n): Promise<Array<FileUIPart>> {\n  if (files == null) {\n    return [];\n  }\n\n  // React-native doesn't have a FileList global:\n  if (!globalThis.FileList || !(files instanceof globalThis.FileList)) {\n    throw new Error('FileList is not supported in the current environment');\n  }\n\n  return Promise.all(\n    Array.from(files).map(async file => {\n      const { name, type } = file;\n\n      const dataUrl = await new Promise<string>((resolve, reject) => {\n        const reader = new FileReader();\n        reader.onload = readerEvent => {\n          resolve(readerEvent.target?.result as string);\n        };\n        reader.onerror = error => reject(error);\n        reader.readAsDataURL(file);\n      });\n\n      return {\n        type: 'file',\n        mediaType: type,\n        filename: name,\n        url: dataUrl,\n      };\n    }),\n  );\n}\n", "import { parseJsonEventStream, type ParseResult } from '@ai-sdk/provider-utils';\nimport {\n  uiMessageChunkSchema,\n  type UIMessageChunk,\n} from '../ui-message-stream/ui-message-chunks';\nimport {\n  HttpChatTransport,\n  type HttpChatTransportInitOptions,\n} from './http-chat-transport';\nimport type { UIMessage } from './ui-messages';\n\nexport class DefaultChatTransport<\n  UI_MESSAGE extends UIMessage,\n> extends HttpChatTransport<UI_MESSAGE> {\n  constructor(options: HttpChatTransportInitOptions<UI_MESSAGE> = {}) {\n    super(options);\n  }\n\n  protected processResponseStream(\n    stream: ReadableStream<Uint8Array<ArrayBufferLike>>,\n  ): ReadableStream<UIMessageChunk> {\n    return parseJsonEventStream({\n      stream,\n      schema: uiMessageChunkSchema,\n    }).pipeThrough(\n      new TransformStream<ParseResult<UIMessageChunk>, UIMessageChunk>({\n        async transform(chunk, controller) {\n          if (!chunk.success) {\n            throw chunk.error;\n          }\n          controller.enqueue(chunk.value);\n        },\n      }),\n    );\n  }\n}\n", "import {\n  normalizeHeaders,\n  resolve,\n  type FetchFunction,\n  type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport type { ChatTransport } from './chat-transport';\nimport type { UIMessage } from './ui-messages';\n\nexport type PrepareSendMessagesRequest<UI_MESSAGE extends UIMessage> = (\n  options: {\n    id: string;\n    messages: UI_MESSAGE[];\n    requestMetadata: unknown;\n    body: Record<string, any> | undefined;\n    credentials: RequestCredentials | undefined;\n    headers: HeadersInit | undefined;\n    api: string;\n  } & {\n    trigger: 'submit-message' | 'regenerate-message';\n    messageId: string | undefined;\n  },\n) =>\n  | {\n      body: object;\n      headers?: HeadersInit;\n      credentials?: RequestCredentials;\n      api?: string;\n    }\n  | PromiseLike<{\n      body: object;\n      headers?: HeadersInit;\n      credentials?: RequestCredentials;\n      api?: string;\n    }>;\n\nexport type PrepareReconnectToStreamRequest = (options: {\n  id: string;\n  requestMetadata: unknown;\n  body: Record<string, any> | undefined;\n  credentials: RequestCredentials | undefined;\n  headers: HeadersInit | undefined;\n  api: string;\n}) =>\n  | {\n      headers?: HeadersInit;\n      credentials?: RequestCredentials;\n      api?: string;\n    }\n  | PromiseLike<{\n      headers?: HeadersInit;\n      credentials?: RequestCredentials;\n      api?: string;\n    }>;\n\n/**\n * Options for the `HttpChatTransport` class.\n *\n * @param UI_MESSAGE - The type of message to be used in the chat.\n */\nexport type HttpChatTransportInitOptions<UI_MESSAGE extends UIMessage> = {\n  /**\n   * The API URL to be used for the chat transport.\n   * Defaults to '/api/chat'.\n   */\n  api?: string;\n\n  /**\n   * The credentials mode to be used for the fetch request.\n   * Possible values are: 'omit', 'same-origin', 'include'.\n   * Defaults to 'same-origin'.\n   */\n  credentials?: Resolvable<RequestCredentials>;\n\n  /**\n   * HTTP headers to be sent with the API request.\n   */\n  headers?: Resolvable<Record<string, string> | Headers>;\n\n  /**\n   * Extra body object to be sent with the API request.\n   * @example\n   * Send a `sessionId` to the API along with the messages.\n   * ```js\n   * useChat({\n   *   body: {\n   *     sessionId: '123',\n   *   }\n   * })\n   * ```\n   */\n  body?: Resolvable<object>;\n\n  /**\n   * Custom fetch implementation. You can use it as a middleware to intercept requests,\n   * or to provide a custom fetch implementation for e.g. testing.\n   */\n  fetch?: FetchFunction;\n\n  /**\n   * When a function is provided, it will be used\n   * to prepare the request body for the chat API. This can be useful for\n   * customizing the request body based on the messages and data in the chat.\n   */\n  prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;\n\n  /**\n   * When a function is provided, it will be used\n   * to prepare the reconnect request for the chat API. This can be useful for\n   * customizing the request based on the chat session.\n   */\n  prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;\n};\n\nexport abstract class HttpChatTransport<\n  UI_MESSAGE extends UIMessage,\n> implements ChatTransport<UI_MESSAGE> {\n  protected api: string;\n  protected credentials: HttpChatTransportInitOptions<UI_MESSAGE>['credentials'];\n  protected headers: HttpChatTransportInitOptions<UI_MESSAGE>['headers'];\n  protected body: HttpChatTransportInitOptions<UI_MESSAGE>['body'];\n  protected fetch?: FetchFunction;\n  protected prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;\n  protected prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;\n\n  constructor({\n    api = '/api/chat',\n    credentials,\n    headers,\n    body,\n    fetch,\n    prepareSendMessagesRequest,\n    prepareReconnectToStreamRequest,\n  }: HttpChatTransportInitOptions<UI_MESSAGE>) {\n    this.api = api;\n    this.credentials = credentials;\n    this.headers = headers;\n    this.body = body;\n    this.fetch = fetch;\n    this.prepareSendMessagesRequest = prepareSendMessagesRequest;\n    this.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;\n  }\n\n  async sendMessages({\n    abortSignal,\n    ...options\n  }: Parameters<ChatTransport<UI_MESSAGE>['sendMessages']>[0]) {\n    const resolvedBody = await resolve(this.body);\n    const resolvedHeaders = await resolve(this.headers);\n    const resolvedCredentials = await resolve(this.credentials);\n\n    const baseHeaders = {\n      ...normalizeHeaders(resolvedHeaders),\n      ...normalizeHeaders(options.headers),\n    };\n\n    const preparedRequest = await this.prepareSendMessagesRequest?.({\n      api: this.api,\n      id: options.chatId,\n      messages: options.messages,\n      body: { ...resolvedBody, ...options.body },\n      headers: baseHeaders,\n      credentials: resolvedCredentials,\n      requestMetadata: options.metadata,\n      trigger: options.trigger,\n      messageId: options.messageId,\n    });\n\n    const api = preparedRequest?.api ?? this.api;\n    const headers =\n      preparedRequest?.headers !== undefined\n        ? normalizeHeaders(preparedRequest.headers)\n        : baseHeaders;\n    const body =\n      preparedRequest?.body !== undefined\n        ? preparedRequest.body\n        : {\n            ...resolvedBody,\n            ...options.body,\n            id: options.chatId,\n            messages: options.messages,\n            trigger: options.trigger,\n            messageId: options.messageId,\n          };\n    const credentials = preparedRequest?.credentials ?? resolvedCredentials;\n\n    // avoid caching globalThis.fetch in case it is patched by other libraries\n    const fetch = this.fetch ?? globalThis.fetch;\n\n    const response = await fetch(api, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        ...headers,\n      },\n      body: JSON.stringify(body),\n      credentials,\n      signal: abortSignal,\n    });\n\n    if (!response.ok) {\n      throw new Error(\n        (await response.text()) ?? 'Failed to fetch the chat response.',\n      );\n    }\n\n    if (!response.body) {\n      throw new Error('The response body is empty.');\n    }\n\n    return this.processResponseStream(response.body);\n  }\n\n  async reconnectToStream(\n    options: Parameters<ChatTransport<UI_MESSAGE>['reconnectToStream']>[0],\n  ): Promise<ReadableStream<UIMessageChunk> | null> {\n    const resolvedBody = await resolve(this.body);\n    const resolvedHeaders = await resolve(this.headers);\n    const resolvedCredentials = await resolve(this.credentials);\n\n    const baseHeaders = {\n      ...normalizeHeaders(resolvedHeaders),\n      ...normalizeHeaders(options.headers),\n    };\n\n    const preparedRequest = await this.prepareReconnectToStreamRequest?.({\n      api: this.api,\n      id: options.chatId,\n      body: { ...resolvedBody, ...options.body },\n      headers: baseHeaders,\n      credentials: resolvedCredentials,\n      requestMetadata: options.metadata,\n    });\n\n    const api = preparedRequest?.api ?? `${this.api}/${options.chatId}/stream`;\n    const headers =\n      preparedRequest?.headers !== undefined\n        ? normalizeHeaders(preparedRequest.headers)\n        : baseHeaders;\n    const credentials = preparedRequest?.credentials ?? resolvedCredentials;\n\n    // avoid caching globalThis.fetch in case it is patched by other libraries\n    const fetch = this.fetch ?? globalThis.fetch;\n\n    const response = await fetch(api, {\n      method: 'GET',\n      headers,\n      credentials,\n    });\n\n    // no active stream found, so we do not resume\n    if (response.status === 204) {\n      return null;\n    }\n\n    if (!response.ok) {\n      throw new Error(\n        (await response.text()) ?? 'Failed to fetch the chat response.',\n      );\n    }\n\n    if (!response.body) {\n      throw new Error('The response body is empty.');\n    }\n\n    return this.processResponseStream(response.body);\n  }\n\n  protected abstract processResponseStream(\n    stream: ReadableStream<Uint8Array<ArrayBufferLike>>,\n  ): ReadableStream<UIMessageChunk>;\n}\n", "import type { Output } from '../generate-text/output';\nimport type { UIMessageStreamOptions } from '../generate-text/stream-text-result';\nimport type { ToolSet } from '../generate-text/tool-set';\nimport type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport type { Agent } from '../agent/agent';\nimport type { ChatTransport } from './chat-transport';\nimport { convertToModelMessages } from './convert-to-model-messages';\nimport type { InferUITools, UIMessage } from './ui-messages';\nimport { validateUIMessages } from './validate-ui-messages';\n\n/**\n * Options for the `DirectChatTransport` class.\n */\nexport type DirectChatTransportOptions<\n  CALL_OPTIONS,\n  TOOLS extends ToolSet,\n  OUTPUT extends Output,\n  UI_MESSAGE extends UIMessage<unknown, never, InferUITools<TOOLS>>,\n> = {\n  /**\n   * The agent to use for generating responses.\n   */\n  agent: Agent<CALL_OPTIONS, TOOLS, OUTPUT>;\n\n  /**\n   * Options to pass to the agent when calling it.\n   */\n  options?: CALL_OPTIONS;\n} & Omit<UIMessageStreamOptions<UI_MESSAGE>, 'onFinish'>;\n\n/**\n * A transport that directly communicates with an Agent in-process,\n * without going through HTTP. This is useful for:\n * - Server-side rendering scenarios\n * - Testing without network\n * - Single-process applications\n *\n * @example\n * ```tsx\n * import { useChat } from '@ai-sdk/react';\n * import { DirectChatTransport } from 'ai';\n * import { myAgent } from './my-agent';\n *\n * const { messages, sendMessage } = useChat({\n *   transport: new DirectChatTransport({ agent: myAgent }),\n * });\n * ```\n */\nexport class DirectChatTransport<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  OUTPUT extends Output = never,\n  UI_MESSAGE extends UIMessage<unknown, never, InferUITools<TOOLS>> = UIMessage<\n    unknown,\n    never,\n    InferUITools<TOOLS>\n  >,\n> implements ChatTransport<UI_MESSAGE> {\n  private readonly agent: Agent<CALL_OPTIONS, TOOLS, OUTPUT>;\n  private readonly agentOptions: CALL_OPTIONS | undefined;\n  private readonly uiMessageStreamOptions: Omit<\n    UIMessageStreamOptions<UI_MESSAGE>,\n    'onFinish'\n  >;\n\n  constructor({\n    agent,\n    options,\n    ...uiMessageStreamOptions\n  }: DirectChatTransportOptions<CALL_OPTIONS, TOOLS, OUTPUT, UI_MESSAGE>) {\n    this.agent = agent;\n    this.agentOptions = options;\n    this.uiMessageStreamOptions = uiMessageStreamOptions;\n  }\n\n  async sendMessages({\n    messages,\n    abortSignal,\n  }: Parameters<ChatTransport<UI_MESSAGE>['sendMessages']>[0]): Promise<\n    ReadableStream<UIMessageChunk>\n  > {\n    // Validate the incoming UI messages\n    const validatedMessages = await validateUIMessages<UI_MESSAGE>({\n      messages,\n      tools: this.agent.tools,\n    });\n\n    // Convert UI messages to model messages\n    const modelMessages = await convertToModelMessages(validatedMessages, {\n      tools: this.agent.tools,\n    });\n\n    // Stream from the agent\n    const result = await this.agent.stream({\n      prompt: modelMessages,\n      abortSignal,\n      ...(this.agentOptions !== undefined\n        ? { options: this.agentOptions }\n        : {}),\n    } as Parameters<Agent<CALL_OPTIONS, TOOLS, OUTPUT>['stream']>[0]);\n\n    // Return the UI message stream\n    return result.toUIMessageStream(this.uiMessageStreamOptions);\n  }\n\n  /**\n   * Direct transport does not support reconnection since there is no\n   * persistent server-side stream to reconnect to.\n   *\n   * @returns Always returns `null`\n   */\n  async reconnectToStream(\n    _options: Parameters<ChatTransport<UI_MESSAGE>['reconnectToStream']>[0],\n  ): Promise<ReadableStream<UIMessageChunk> | null> {\n    return null;\n  }\n}\n", "import { isToolUIPart, type UIMessage } from './ui-messages';\n\n/**\n * Check if the last message is an assistant message with completed tool call approvals.\n * The last step of the message must have at least one tool approval response and\n * all tool approvals must have a response.\n */\nexport function lastAssistantMessageIsCompleteWithApprovalResponses({\n  messages,\n}: {\n  messages: UIMessage[];\n}): boolean {\n  const message = messages[messages.length - 1];\n\n  if (!message) {\n    return false;\n  }\n\n  if (message.role !== 'assistant') {\n    return false;\n  }\n\n  const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n    return part.type === 'step-start' ? index : lastIndex;\n  }, -1);\n\n  const lastStepToolInvocations = message.parts\n    .slice(lastStepStartIndex + 1)\n    .filter(isToolUIPart);\n\n  return (\n    // has at least one tool approval response\n    lastStepToolInvocations.filter(part => part.state === 'approval-responded')\n      .length > 0 &&\n    // all tool approvals must have a response\n    lastStepToolInvocations.every(\n      part =>\n        part.state === 'output-available' ||\n        part.state === 'output-error' ||\n        part.state === 'approval-responded',\n    )\n  );\n}\n", "import { isToolUIPart, type UIMessage } from './ui-messages';\n\n/**\n * Check if the last message is an assistant message with completed tool calls.\n * The last step of the message must have at least one tool invocation and\n * all tool invocations must have a result.\n */\nexport function lastAssistantMessageIsCompleteWithToolCalls({\n  messages,\n}: {\n  messages: UIMessage[];\n}): boolean {\n  const message = messages[messages.length - 1];\n\n  if (!message) {\n    return false;\n  }\n\n  if (message.role !== 'assistant') {\n    return false;\n  }\n\n  const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n    return part.type === 'step-start' ? index : lastIndex;\n  }, -1);\n\n  const lastStepToolInvocations = message.parts\n    .slice(lastStepStartIndex + 1)\n    .filter(isToolUIPart)\n    .filter(part => !part.providerExecuted);\n\n  return (\n    lastStepToolInvocations.length > 0 &&\n    lastStepToolInvocations.every(\n      part =>\n        part.state === 'output-available' || part.state === 'output-error',\n    )\n  );\n}\n", "import type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\n\nexport function transformTextToUiMessageStream({\n  stream,\n}: {\n  stream: ReadableStream<string>;\n}) {\n  return stream.pipeThrough(\n    new TransformStream<string, UIMessageChunk>({\n      start(controller) {\n        controller.enqueue({ type: 'start' });\n        controller.enqueue({ type: 'start-step' });\n        controller.enqueue({ type: 'text-start', id: 'text-1' });\n      },\n\n      async transform(part, controller) {\n        controller.enqueue({ type: 'text-delta', id: 'text-1', delta: part });\n      },\n\n      async flush(controller) {\n        controller.enqueue({ type: 'text-end', id: 'text-1' });\n        controller.enqueue({ type: 'finish-step' });\n        controller.enqueue({ type: 'finish' });\n      },\n    }),\n  );\n}\n", "import type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport {\n  HttpChatTransport,\n  type HttpChatTransportInitOptions,\n} from './http-chat-transport';\nimport { transformTextToUiMessageStream } from './transform-text-to-ui-message-stream';\nimport type { UIMessage } from './ui-messages';\n\nexport class TextStreamChatTransport<\n  UI_MESSAGE extends UIMessage,\n> extends HttpChatTransport<UI_MESSAGE> {\n  constructor(options: HttpChatTransportInitOptions<UI_MESSAGE> = {}) {\n    super(options);\n  }\n\n  protected processResponseStream(\n    stream: ReadableStream<Uint8Array<ArrayBufferLike>>,\n  ): ReadableStream<UIMessageChunk> {\n    return transformTextToUiMessageStream({\n      stream: stream.pipeThrough(new TextDecoderStream()),\n    });\n  }\n}\n", "import { isNull, isUndefined } from \"utils/typeChecks.ts\"\n\nexport interface RepairInfo {\n\tkind: \"unterminated-quote\"\n\toriginalRaw: string\n\trepairedRaw: string\n}\n\ninterface CommandBufferOptions {\n\tonAnnotation?: (annotation: string) => void\n\t/**\n\t * When isCommandStart is passed, the parser will lookahead in the buffer to see if the text\n\t * that follows is a command start. If it detects the start of a new command after a separator\n\t * whilst in a quote, it will repair the command by adding the unterminated quote to the end of\n\t * the command.\n\t */\n\tisCommandStart?: (text: string) => boolean\n\tonRepair?: (info: RepairInfo) => void\n}\n\ninterface StreamingDSLParserOptions extends CommandBufferOptions {\n\tonError?: (error: Error, raw: string) => void\n}\n\nfunction isWhitespace(char: string): boolean {\n\tswitch (char) {\n\t\tcase \" \":\n\t\tcase \"\\n\":\n\t\tcase \"\\r\":\n\t\tcase \"\\t\":\n\t\tcase \"\\f\":\n\t\tcase \"\\v\":\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\n/**\n * Stateful buffer scanner that efficiently finds command separators while respecting quoted\n * strings. Maintains scan position and quote state between calls to avoid re-scanning already\n * processed text. Supports inline annotations in between command strings.\n */\nclass CommandBuffer {\n\tprivate static readonly annotationStart = \"/**\"\n\tprivate static readonly annotationEnd = \"*/\"\n\tprivate buffer = \"\"\n\tprivate scanIndex = 0\n\tprivate inQuote: string | null = null\n\tprivate text = \"\"\n\tprivate inAnnotation = false\n\tprivate annotationBuffer = \"\"\n\tprivate atCommandBoundary = true\n\n\tconstructor(\n\t\tprivate readonly separator: string,\n\t\tprivate readonly options: CommandBufferOptions,\n\t) {}\n\n\t/**\n\t * Append new text to the buffer\n\t */\n\tappend(text: string): void {\n\t\tthis.text += text\n\t\tthis.buffer += text\n\t}\n\n\t/**\n\t * Get the full text that has been added to the buffer\n\t */\n\tgetText(): string {\n\t\treturn this.text\n\t}\n\n\t/**\n\t * Process the buffer and return the next complete command, or undefined if none available.\n\t * Maintains state so subsequent calls resume from where the last scan left off.\n\t */\n\tprocess(): string | undefined {\n\t\twhile (this.scanIndex < this.buffer.length) {\n\t\t\tif (this.inAnnotation && !this.tryCloseAnnotation()) return\n\t\t\tif (this.inAnnotation) continue\n\n\t\t\tconst char = this.buffer[this.scanIndex] ?? \"\"\n\t\t\tif (char === '\"' || char === \"'\") {\n\t\t\t\tif (!this.isEscaped(this.scanIndex)) {\n\t\t\t\t\tif (isNull(this.inQuote)) {\n\t\t\t\t\t\tthis.inQuote = char\n\t\t\t\t\t} else if (this.inQuote === char) {\n\t\t\t\t\t\tthis.inQuote = null\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.atCommandBoundary = false\n\t\t\t\tthis.scanIndex++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (this.tryOpenAnnotation()) continue\n\t\t\tif (this.shouldWaitForAnnotationStart()) return\n\n\t\t\tconst command = this.tryExtractCommand()\n\t\t\tif (!isUndefined(command)) return command\n\n\t\t\tif (\n\t\t\t\tisNull(this.inQuote) &&\n\t\t\t\tthis.separator.length > 1 &&\n\t\t\t\tthis.scanIndex >= this.buffer.length - this.separator.length + 1\n\t\t\t) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tthis.atCommandBoundary &&= isWhitespace(char)\n\t\t\tthis.scanIndex++\n\t\t}\n\t}\n\n\t/** Continue scanning an open annotation; emits when the close marker is reached. */\n\tprivate tryCloseAnnotation(): boolean {\n\t\tconst annotationEnd = this.buffer.indexOf(CommandBuffer.annotationEnd, this.scanIndex)\n\t\tif (annotationEnd < 0) {\n\t\t\tconst lastChar = this.buffer[this.buffer.length - 1]\n\t\t\tconst endExclusive = lastChar === \"*\" ? this.buffer.length - 1 : this.buffer.length\n\t\t\tif (endExclusive > this.scanIndex) {\n\t\t\t\tthis.annotationBuffer += this.buffer.slice(this.scanIndex, endExclusive)\n\t\t\t\tthis.scanIndex = endExclusive\n\t\t\t}\n\t\t\tthis.compactConsumedPrefix()\n\t\t\treturn false\n\t\t}\n\n\t\tthis.annotationBuffer += this.buffer.slice(this.scanIndex, annotationEnd)\n\t\tthis.scanIndex = annotationEnd + CommandBuffer.annotationEnd.length\n\t\tthis.inAnnotation = false\n\t\tthis.emitAnnotation()\n\n\t\tlet index = this.skipWhitespace(this.scanIndex)\n\t\tif (this.buffer.startsWith(this.separator, index)) index += this.separator.length\n\t\tthis.scanIndex = index\n\t\tthis.atCommandBoundary = true\n\t\tthis.compactConsumedPrefix()\n\t\treturn true\n\t}\n\n\t/** Opens annotation mode when an annotation marker appears at a command boundary. */\n\tprivate tryOpenAnnotation(): boolean {\n\t\tif (!isNull(this.inQuote) || !this.atCommandBoundary) return false\n\t\tif (!this.buffer.startsWith(CommandBuffer.annotationStart, this.scanIndex)) return false\n\n\t\tthis.inAnnotation = true\n\t\tthis.annotationBuffer = \"\"\n\t\tthis.scanIndex += CommandBuffer.annotationStart.length\n\t\treturn true\n\t}\n\n\t/** Returns true when the buffer tail may be a split annotation start marker. */\n\tprivate shouldWaitForAnnotationStart(): boolean {\n\t\tif (!isNull(this.inQuote) || !this.atCommandBoundary) return false\n\t\tconst remainingLength = this.buffer.length - this.scanIndex\n\t\tif (remainingLength >= CommandBuffer.annotationStart.length) return false\n\t\tfor (let i = 0; i < remainingLength; i++) {\n\t\t\tif (this.buffer[this.scanIndex + i] !== CommandBuffer.annotationStart[i]) return false\n\t\t}\n\t\treturn true\n\t}\n\n\t/** Extracts and removes the next command, optionally repairing unterminated trailing quotes. */\n\tprivate tryExtractCommand(): string | undefined {\n\t\tif (!this.buffer.startsWith(this.separator, this.scanIndex)) return\n\n\t\tconst commandBuffer = this.buffer.slice(0, this.scanIndex).trim()\n\n\t\tif (isNull(this.inQuote)) return this.extractCommand(commandBuffer)\n\n\t\t// We only attempt to repair commands if `isCommandStart` is provided\n\t\tif (isUndefined(this.options.isCommandStart)) return\n\n\t\tconst isCommandStartAfter = this.options.isCommandStart(this.buffer.slice(this.scanIndex + this.separator.length))\n\t\tif (!isCommandStartAfter) return\n\n\t\tconst repaired = this.repairCommand(commandBuffer, this.inQuote)\n\t\treturn this.extractCommand(repaired.repairedRaw)\n\t}\n\n\tprivate extractCommand(commandStr: string): string {\n\t\tthis.buffer = this.buffer.slice(this.scanIndex + this.separator.length)\n\t\tthis.scanIndex = 0\n\t\tthis.atCommandBoundary = true\n\t\treturn commandStr\n\t}\n\n\tprivate repairCommand(command: string, closingQuote: string): RepairInfo {\n\t\tconst repairedCommand = `${command}${closingQuote}`\n\t\tconst info: RepairInfo = {\n\t\t\tkind: \"unterminated-quote\",\n\t\t\toriginalRaw: command,\n\t\t\trepairedRaw: repairedCommand,\n\t\t}\n\n\t\tthis.inQuote = null\n\t\tthis.options.onRepair?.(info)\n\n\t\treturn info\n\t}\n\n\t/**\n\t * Check if the character at the given index is escaped by counting consecutive backslashes\n\t * before it. A character is escaped if there's an odd number of backslashes immediately before\n\t * it.\n\t */\n\tprivate isEscaped(index: number): boolean {\n\t\tlet backslashCount = 0\n\t\tlet i = index - 1\n\n\t\t// Count consecutive backslashes before this position\n\t\twhile (i >= 0 && this.buffer[i] === \"\\\\\") {\n\t\t\tbackslashCount++\n\t\t\ti--\n\t\t}\n\n\t\t// Odd number of backslashes means the character is escaped\n\t\treturn backslashCount % 2 === 1\n\t}\n\n\t/**\n\t * Finalize the buffer by ensuring any remaining content ends with the separator so the final\n\t * command can be parsed. When quote repair is enabled, finalize repairs a trailing\n\t * unterminated quote in place and advances scanIndex to the trailing separator so process()\n\t * can consume it without re-scanning the earlier command body.\n\t */\n\tfinalize(): void {\n\t\tif (this.buffer.trim().length === 0) return\n\t\tif (!this.buffer.endsWith(this.separator)) {\n\t\t\tthis.buffer += this.separator\n\t\t\tthis.text += this.separator\n\t\t}\n\n\t\tif (isNull(this.inQuote) || isUndefined(this.options.isCommandStart)) return\n\n\t\tconst commandBuffer = this.buffer.slice(0, this.buffer.length - this.separator.length).trim()\n\t\tconst repairInfo = this.repairCommand(commandBuffer, this.inQuote)\n\n\t\tthis.buffer = `${repairInfo.repairedRaw}${this.separator}`\n\t\tthis.scanIndex = repairInfo.repairedRaw.length\n\t}\n\n\tprivate emitAnnotation(): void {\n\t\tconst annotation = this.annotationBuffer.trim()\n\t\tthis.annotationBuffer = \"\"\n\t\tif (annotation.length > 0) this.options.onAnnotation?.(annotation)\n\t}\n\n\tprivate skipWhitespace(index: number): number {\n\t\tlet i = index\n\t\twhile (i < this.buffer.length && isWhitespace(this.buffer[i] ?? \"\")) i++\n\t\treturn i\n\t}\n\n\tprivate compactConsumedPrefix(): void {\n\t\tif (this.scanIndex === 0) return\n\t\tthis.buffer = this.buffer.slice(this.scanIndex)\n\t\tthis.scanIndex = 0\n\t}\n}\n\n/**\n * When streaming plain text instead of JSON, executes the onCommand callback whenever a complete\n * DSL command is completed.\n */\nexport class StreamingDSLParser<T> {\n\tprivate buffer: CommandBuffer\n\tprivate commands: T[] = []\n\n\tconstructor(\n\t\tprivate readonly separator: string,\n\t\t/**\n\t\t * Whenever the separator is detected, parse the buffer to get a command. Commands that\n\t\t * don't parse will throw and can be handled by onError.\n\t\t */\n\t\tprivate readonly parseCommand: (command: string) => T,\n\t\tprivate readonly onCommand: (parsed: T, raw: string) => void,\n\t\tprivate readonly options: StreamingDSLParserOptions = {},\n\t) {\n\t\tthis.buffer = new CommandBuffer(separator, options)\n\t}\n\n\t/**\n\t * Add a text token to the parser buffer\n\t */\n\taddToken(token: string): string {\n\t\tthis.buffer.append(token)\n\n\t\t// Process all complete commands in the buffer\n\t\tthis.processBuffer()\n\n\t\treturn this.buffer.getText()\n\t}\n\n\t/**\n\t * Process the buffer and extract complete commands\n\t */\n\tprivate processBuffer(): void {\n\t\tlet commandStr: string | undefined\n\n\t\t// Process all complete commands (those followed by the separator)\n\t\twhile ((commandStr = this.buffer.process()) !== undefined) {\n\t\t\ttry {\n\t\t\t\tconst command = this.parseCommand(commandStr)\n\t\t\t\tthis.commands.push(command)\n\t\t\t\tthis.onCommand(command, commandStr)\n\t\t\t} catch (error) {\n\t\t\t\t// Continue processing other commands.\n\t\t\t\tthis.options.onError?.(error instanceof Error ? error : new Error(String(error), { cause: error }), commandStr)\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The agent may perform multiple steps when calling tools. Each step should finalize the previous buffer. */\n\tfinalizeStep(): void {\n\t\tthis.buffer.finalize()\n\t\tthis.processBuffer()\n\t}\n\n\t/**\n\t * Finalize the parser and return all parsed commands along with the full text\n\t */\n\tfinalize(): { commands: T[]; text: string } {\n\t\t// Process any remaining command in the buffer by ensuring it ends with the separator.\n\t\tthis.buffer.finalize()\n\t\tthis.processBuffer()\n\n\t\treturn { commands: this.commands, text: this.buffer.getText() }\n\t}\n}\n", "/**\n * Symbol used for identifying AI SDK Error instances.\n * Enables checking if an error is an instance of AISDKError across package versions.\n */\nconst marker = 'vercel.ai.error';\nconst symbol = Symbol.for(marker);\n\n/**\n * Custom error class for AI SDK related errors.\n * @extends Error\n */\nexport class AISDKError extends Error {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The underlying cause of the error, if any.\n   */\n  readonly cause?: unknown;\n\n  /**\n   * Creates an AI SDK Error.\n   *\n   * @param {Object} params - The parameters for creating the error.\n   * @param {string} params.name - The name of the error.\n   * @param {string} params.message - The error message.\n   * @param {unknown} [params.cause] - The underlying cause of the error.\n   */\n  constructor({\n    name,\n    message,\n    cause,\n  }: {\n    name: string;\n    message: string;\n    cause?: unknown;\n  }) {\n    super(message);\n\n    this.name = name;\n    this.cause = cause;\n  }\n\n  /**\n   * Checks if the given error is an AI SDK Error.\n   * @param {unknown} error - The error to check.\n   * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n   */\n  static isInstance(error: unknown): error is AISDKError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  protected static hasMarker(error: unknown, marker: string): boolean {\n    const markerSymbol = Symbol.for(marker);\n    return (\n      error != null &&\n      typeof error === 'object' &&\n      markerSymbol in error &&\n      typeof error[markerSymbol] === 'boolean' &&\n      error[markerSymbol] === true\n    );\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_APICallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class APICallError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly url: string;\n  readonly requestBodyValues: unknown;\n  readonly statusCode?: number;\n\n  readonly responseHeaders?: Record<string, string>;\n  readonly responseBody?: string;\n\n  readonly isRetryable: boolean;\n  readonly data?: unknown;\n\n  constructor({\n    message,\n    url,\n    requestBodyValues,\n    statusCode,\n    responseHeaders,\n    responseBody,\n    cause,\n    isRetryable = statusCode != null &&\n      (statusCode === 408 || // request timeout\n        statusCode === 409 || // conflict\n        statusCode === 429 || // too many requests\n        statusCode >= 500), // server error\n    data,\n  }: {\n    message: string;\n    url: string;\n    requestBodyValues: unknown;\n    statusCode?: number;\n    responseHeaders?: Record<string, string>;\n    responseBody?: string;\n    cause?: unknown;\n    isRetryable?: boolean;\n    data?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.url = url;\n    this.requestBodyValues = requestBodyValues;\n    this.statusCode = statusCode;\n    this.responseHeaders = responseHeaders;\n    this.responseBody = responseBody;\n    this.isRetryable = isRetryable;\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is APICallError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_EmptyResponseBodyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class EmptyResponseBodyError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message = 'Empty response body' }: { message?: string } = {}) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is EmptyResponseBodyError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "export function getErrorMessage(error: unknown | undefined) {\n  if (error == null) {\n    return 'unknown error';\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return error.message;\n  }\n\n  return JSON.stringify(error);\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A function argument is invalid.\n */\nexport class InvalidArgumentError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly argument: string;\n\n  constructor({\n    message,\n    cause,\n    argument,\n  }: {\n    argument: string;\n    message: string;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.argument = argument;\n  }\n\n  static isInstance(error: unknown): error is InvalidArgumentError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidPromptError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A prompt is invalid. This error should be thrown by providers when they cannot\n * process a prompt.\n */\nexport class InvalidPromptError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly prompt: unknown;\n\n  constructor({\n    prompt,\n    message,\n    cause,\n  }: {\n    prompt: unknown;\n    message: string;\n    cause?: unknown;\n  }) {\n    super({ name, message: `Invalid prompt: ${message}`, cause });\n\n    this.prompt = prompt;\n  }\n\n  static isInstance(error: unknown): error is InvalidPromptError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidResponseDataError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Server returned a response with invalid data content.\n * This should be thrown by providers when they cannot parse the response from the API.\n */\nexport class InvalidResponseDataError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly data: unknown;\n\n  constructor({\n    data,\n    message = `Invalid response data: ${JSON.stringify(data)}.`,\n  }: {\n    data: unknown;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is InvalidResponseDataError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_JSONParseError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class JSONParseError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly text: string;\n\n  constructor({ text, cause }: { text: string; cause: unknown }) {\n    super({\n      name,\n      message:\n        `JSON parsing failed: ` +\n        `Text: ${text}.\\n` +\n        `Error message: ${getErrorMessage(cause)}`,\n      cause,\n    });\n\n    this.text = text;\n  }\n\n  static isInstance(error: unknown): error is JSONParseError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadAPIKeyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadAPIKeyError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message }: { message: string }) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is LoadAPIKeyError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadSettingError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadSettingError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message }: { message: string }) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is LoadSettingError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoContentGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when the AI provider fails to generate any content.\n */\nexport class NoContentGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({\n    message = 'No content generated.',\n  }: { message?: string } = {}) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is NoContentGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoSuchModelError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchModelError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly modelId: string;\n  readonly modelType:\n    | 'languageModel'\n    | 'embeddingModel'\n    | 'imageModel'\n    | 'transcriptionModel'\n    | 'speechModel'\n    | 'rerankingModel'\n    | 'videoModel';\n\n  constructor({\n    errorName = name,\n    modelId,\n    modelType,\n    message = `No such ${modelType}: ${modelId}`,\n  }: {\n    errorName?: string;\n    modelId: string;\n    modelType:\n      | 'languageModel'\n      | 'embeddingModel'\n      | 'imageModel'\n      | 'transcriptionModel'\n      | 'speechModel'\n      | 'rerankingModel'\n      | 'videoModel';\n    message?: string;\n  }) {\n    super({ name: errorName, message });\n\n    this.modelId = modelId;\n    this.modelType = modelType;\n  }\n\n  static isInstance(error: unknown): error is NoSuchModelError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_TooManyEmbeddingValuesForCallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class TooManyEmbeddingValuesForCallError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly provider: string;\n  readonly modelId: string;\n  readonly maxEmbeddingsPerCall: number;\n  readonly values: Array<unknown>;\n\n  constructor(options: {\n    provider: string;\n    modelId: string;\n    maxEmbeddingsPerCall: number;\n    values: Array<unknown>;\n  }) {\n    super({\n      name,\n      message:\n        `Too many values for a single embedding call. ` +\n        `The ${options.provider} model \"${options.modelId}\" can only embed up to ` +\n        `${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`,\n    });\n\n    this.provider = options.provider;\n    this.modelId = options.modelId;\n    this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n    this.values = options.values;\n  }\n\n  static isInstance(\n    error: unknown,\n  ): error is TooManyEmbeddingValuesForCallError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_TypeValidationError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport interface TypeValidationContext {\n  /**\n   * Field path in dot notation (e.g., \"message.metadata\", \"message.parts[3].data\")\n   */\n  field?: string;\n\n  /**\n   * Entity name (e.g., tool name, data type name)\n   */\n  entityName?: string;\n\n  /**\n   * Entity identifier (e.g., message ID, tool call ID)\n   */\n  entityId?: string;\n}\n\nexport class TypeValidationError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly value: unknown;\n  readonly context?: TypeValidationContext;\n\n  constructor({\n    value,\n    cause,\n    context,\n  }: {\n    value: unknown;\n    cause: unknown;\n    context?: TypeValidationContext;\n  }) {\n    let contextPrefix = 'Type validation failed';\n\n    if (context?.field) {\n      contextPrefix += ` for ${context.field}`;\n    }\n\n    if (context?.entityName || context?.entityId) {\n      contextPrefix += ' (';\n      const parts: string[] = [];\n      if (context.entityName) {\n        parts.push(context.entityName);\n      }\n      if (context.entityId) {\n        parts.push(`id: \"${context.entityId}\"`);\n      }\n      contextPrefix += parts.join(', ');\n      contextPrefix += ')';\n    }\n\n    super({\n      name,\n      message:\n        `${contextPrefix}: ` +\n        `Value: ${JSON.stringify(value)}.\\n` +\n        `Error message: ${getErrorMessage(cause)}`,\n      cause,\n    });\n\n    this.value = value;\n    this.context = context;\n  }\n\n  static isInstance(error: unknown): error is TypeValidationError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  /**\n   * Wraps an error into a TypeValidationError.\n   * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n   * Otherwise, it creates a new TypeValidationError.\n   *\n   * @param {Object} params - The parameters for wrapping the error.\n   * @param {unknown} params.value - The value that failed validation.\n   * @param {unknown} params.cause - The original error or cause of the validation failure.\n   * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n   * @returns {TypeValidationError} A TypeValidationError instance.\n   */\n  static wrap({\n    value,\n    cause,\n    context,\n  }: {\n    value: unknown;\n    cause: unknown;\n    context?: TypeValidationContext;\n  }): TypeValidationError {\n    if (\n      TypeValidationError.isInstance(cause) &&\n      cause.value === value &&\n      cause.context?.field === context?.field &&\n      cause.context?.entityName === context?.entityName &&\n      cause.context?.entityId === context?.entityId\n    ) {\n      return cause;\n    }\n\n    return new TypeValidationError({ value, cause, context });\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_UnsupportedFunctionalityError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class UnsupportedFunctionalityError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly functionality: string;\n\n  constructor({\n    functionality,\n    message = `'${functionality}' functionality not supported.`,\n  }: {\n    functionality: string;\n    message?: string;\n  }) {\n    super({ name, message });\n    this.functionality = functionality;\n  }\n\n  static isInstance(error: unknown): error is UnsupportedFunctionalityError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { JSONArray, JSONObject, JSONValue } from './json-value';\n\nexport function isJSONValue(value: unknown): value is JSONValue {\n  if (\n    value === null ||\n    typeof value === 'string' ||\n    typeof value === 'number' ||\n    typeof value === 'boolean'\n  ) {\n    return true;\n  }\n\n  if (Array.isArray(value)) {\n    return value.every(isJSONValue);\n  }\n\n  if (typeof value === 'object') {\n    return Object.entries(value).every(\n      ([key, val]) =>\n        typeof key === 'string' && (val === undefined || isJSONValue(val)),\n    );\n  }\n\n  return false;\n}\n\nexport function isJSONArray(value: unknown): value is JSONArray {\n  return Array.isArray(value) && value.every(isJSONValue);\n}\n\nexport function isJSONObject(value: unknown): value is JSONObject {\n  return (\n    value != null &&\n    typeof value === 'object' &&\n    Object.entries(value).every(\n      ([key, val]) =>\n        typeof key === 'string' && (val === undefined || isJSONValue(val)),\n    )\n  );\n}\n", "export function combineHeaders(\n  ...headers: Array<Record<string, string | undefined> | undefined>\n): Record<string, string | undefined> {\n  return headers.reduce(\n    (combinedHeaders, currentHeaders) => ({\n      ...combinedHeaders,\n      ...(currentHeaders ?? {}),\n    }),\n    {},\n  ) as Record<string, string | undefined>;\n}\n", "/**\n * Converts an AsyncIterator to a ReadableStream.\n *\n * @template T - The type of elements produced by the AsyncIterator.\n * @param { <T>} iterator - The AsyncIterator to convert.\n * @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.\n */\nexport function convertAsyncIteratorToReadableStream<T>(\n  iterator: AsyncIterator<T>,\n): ReadableStream<T> {\n  let cancelled = false;\n\n  return new ReadableStream<T>({\n    /**\n     * Called when the consumer wants to pull more data from the stream.\n     *\n     * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n     * @returns {Promise<void>}\n     */\n    async pull(controller) {\n      if (cancelled) return;\n      try {\n        const { value, done } = await iterator.next();\n        if (done) {\n          controller.close();\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (error) {\n        controller.error(error);\n      }\n    },\n    /**\n     * Called when the consumer cancels the stream.\n     */\n    async cancel(reason?: unknown) {\n      cancelled = true;\n      if (iterator.return) {\n        try {\n          await iterator.return(reason);\n        } catch {\n          // intentionally ignore errors during cancellation\n        }\n      }\n    },\n  });\n}\n", "import {\n  LanguageModelV3FunctionTool,\n  LanguageModelV3ProviderTool,\n} from '@ai-sdk/provider';\n\n/**\n * Interface for mapping between custom tool names and provider tool names.\n */\nexport interface ToolNameMapping {\n  /**\n   * Maps a custom tool name (used by the client) to the provider's tool name.\n   * If the custom tool name does not have a mapping, returns the input name.\n   *\n   * @param customToolName - The custom name of the tool defined by the client.\n   * @returns The corresponding provider tool name, or the input name if not mapped.\n   */\n  toProviderToolName: (customToolName: string) => string;\n\n  /**\n   * Maps a provider tool name to the custom tool name used by the client.\n   * If the provider tool name does not have a mapping, returns the input name.\n   *\n   * @param providerToolName - The name of the tool as understood by the provider.\n   * @returns The corresponding custom tool name, or the input name if not mapped.\n   */\n  toCustomToolName: (providerToolName: string) => string;\n}\n\n/**\n * @param tools - Tools that were passed to the language model.\n * @param providerToolNames - Maps the provider tool ids to the provider tool names.\n */\nexport function createToolNameMapping({\n  tools = [],\n  providerToolNames,\n  resolveProviderToolName,\n}: {\n  /**\n   * Tools that were passed to the language model.\n   */\n  tools:\n    | Array<LanguageModelV3FunctionTool | LanguageModelV3ProviderTool>\n    | undefined;\n\n  /**\n   * Maps the provider tool ids to the provider tool names.\n   */\n  providerToolNames: Record<`${string}.${string}`, string>;\n\n  /**\n   * Optional resolver for provider tool names that cannot be represented as\n   * static id -> name mappings (e.g. dynamic provider names).\n   */\n  resolveProviderToolName?: (\n    tool: LanguageModelV3ProviderTool,\n  ) => string | undefined;\n}): ToolNameMapping {\n  const customToolNameToProviderToolName: Record<string, string> = {};\n  const providerToolNameToCustomToolName: Record<string, string> = {};\n\n  for (const tool of tools) {\n    if (tool.type === 'provider') {\n      const providerToolName =\n        resolveProviderToolName?.(tool) ??\n        (tool.id in providerToolNames ? providerToolNames[tool.id] : undefined);\n\n      if (providerToolName == null) {\n        continue;\n      }\n\n      customToolNameToProviderToolName[tool.name] = providerToolName;\n      providerToolNameToCustomToolName[providerToolName] = tool.name;\n    }\n  }\n\n  return {\n    toProviderToolName: (customToolName: string) =>\n      customToolNameToProviderToolName[customToolName] ?? customToolName,\n    toCustomToolName: (providerToolName: string) =>\n      providerToolNameToCustomToolName[providerToolName] ?? providerToolName,\n  };\n}\n", "/**\n * Creates a Promise that resolves after a specified delay\n * @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.\n * @param signal - Optional AbortSignal to cancel the delay\n * @returns A Promise that resolves after the specified delay\n * @throws {DOMException} When the signal is aborted\n */\nexport async function delay(\n  delayInMs?: number | null,\n  options?: {\n    abortSignal?: AbortSignal;\n  },\n): Promise<void> {\n  if (delayInMs == null) {\n    return Promise.resolve();\n  }\n\n  const signal = options?.abortSignal;\n\n  return new Promise<void>((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(createAbortError());\n      return;\n    }\n\n    const timeoutId = setTimeout(() => {\n      cleanup();\n      resolve();\n    }, delayInMs);\n\n    const cleanup = () => {\n      clearTimeout(timeoutId);\n      signal?.removeEventListener('abort', onAbort);\n    };\n\n    const onAbort = () => {\n      cleanup();\n      reject(createAbortError());\n    };\n\n    signal?.addEventListener('abort', onAbort);\n  });\n}\n\nfunction createAbortError(): DOMException {\n  return new DOMException('Delay was aborted', 'AbortError');\n}\n", "/**\n * Delayed promise. It is only constructed once the value is accessed.\n * This is useful to avoid unhandled promise rejections when the promise is created\n * but not accessed.\n */\nexport class DelayedPromise<T> {\n  private status:\n    | { type: 'pending' }\n    | { type: 'resolved'; value: T }\n    | { type: 'rejected'; error: unknown } = { type: 'pending' };\n  private _promise: Promise<T> | undefined;\n  private _resolve: undefined | ((value: T) => void) = undefined;\n  private _reject: undefined | ((error: unknown) => void) = undefined;\n\n  get promise(): Promise<T> {\n    if (this._promise) {\n      return this._promise;\n    }\n\n    this._promise = new Promise<T>((resolve, reject) => {\n      if (this.status.type === 'resolved') {\n        resolve(this.status.value);\n      } else if (this.status.type === 'rejected') {\n        reject(this.status.error);\n      }\n\n      this._resolve = resolve;\n      this._reject = reject;\n    });\n\n    return this._promise;\n  }\n\n  resolve(value: T): void {\n    this.status = { type: 'resolved', value };\n\n    if (this._promise) {\n      this._resolve?.(value);\n    }\n  }\n\n  reject(error: unknown): void {\n    this.status = { type: 'rejected', error };\n\n    if (this._promise) {\n      this._reject?.(error);\n    }\n  }\n\n  isResolved(): boolean {\n    return this.status.type === 'resolved';\n  }\n\n  isRejected(): boolean {\n    return this.status.type === 'rejected';\n  }\n\n  isPending(): boolean {\n    return this.status.type === 'pending';\n  }\n}\n", "/**\n * Extracts the headers from a response object and returns them as a key-value object.\n *\n * @param response - The response object to extract headers from.\n * @returns The headers as a key-value object.\n */\nexport function extractResponseHeaders(response: Response) {\n  return Object.fromEntries<string>([...response.headers]);\n}\n", "// btoa and atob need to be invoked as a function call, not as a method call.\n// Otherwise CloudFlare will throw a\n// \"TypeError: Illegal invocation: function called with incorrect this reference\"\nconst { btoa, atob } = globalThis;\n\nexport function convertBase64ToUint8Array(base64String: string) {\n  const base64Url = base64String.replace(/-/g, '+').replace(/_/g, '/');\n  const latin1string = atob(base64Url);\n  return Uint8Array.from(latin1string, byte => byte.codePointAt(0)!);\n}\n\nexport function convertUint8ArrayToBase64(array: Uint8Array): string {\n  let latin1string = '';\n\n  // Note: regular for loop to support older JavaScript versions that\n  // do not support for..of on Uint8Array\n  for (let i = 0; i < array.length; i++) {\n    latin1string += String.fromCodePoint(array[i]);\n  }\n\n  return btoa(latin1string);\n}\n\nexport function convertToBase64(value: string | Uint8Array): string {\n  return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n", "import { ImageModelV3File } from '@ai-sdk/provider';\nimport { convertUint8ArrayToBase64 } from './uint8-utils';\n\n/**\n * Convert an ImageModelV3File to a URL or data URI string.\n *\n * If the file is a URL, it returns the URL as-is.\n * If the file is base64 data, it returns a data URI with the base64 data.\n * If the file is a Uint8Array, it converts it to base64 and returns a data URI.\n */\nexport function convertImageModelFileToDataUri(file: ImageModelV3File): string {\n  if (file.type === 'url') return file.url;\n\n  return `data:${file.mediaType};base64,${\n    typeof file.data === 'string'\n      ? file.data\n      : convertUint8ArrayToBase64(file.data)\n  }`;\n}\n", "/**\n * Converts an input object to FormData for multipart/form-data requests.\n *\n * Handles the following cases:\n * - `null` or `undefined` values are skipped\n * - Arrays with a single element are appended as a single value\n * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)\n *   unless `useArrayBrackets` is set to `false`\n * - All other values are appended directly\n *\n * @param input - The input object to convert. Use a generic type for type validation.\n * @param options - Optional configuration object.\n * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.\n *   Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.\n * @returns A FormData object containing the input values.\n *\n * @example\n * ```ts\n * type MyInput = {\n *   model: string;\n *   prompt: string;\n *   images: Blob[];\n * };\n *\n * const formData = convertToFormData<MyInput>({\n *   model: 'gpt-image-1',\n *   prompt: 'A cat',\n *   images: [blob1, blob2],\n * });\n * ```\n */\nexport function convertToFormData<T extends Record<string, unknown>>(\n  input: T,\n  options: { useArrayBrackets?: boolean } = {},\n): FormData {\n  const { useArrayBrackets = true } = options;\n  const formData = new FormData();\n\n  for (const [key, value] of Object.entries(input)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      if (value.length === 1) {\n        formData.append(key, value[0] as string | Blob);\n        continue;\n      }\n\n      const arrayKey = useArrayBrackets ? `${key}[]` : key;\n      for (const item of value) {\n        formData.append(arrayKey, item as string | Blob);\n      }\n      continue;\n    }\n\n    formData.append(key, value as string | Blob);\n  }\n\n  return formData;\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_DownloadError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class DownloadError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly url: string;\n  readonly statusCode?: number;\n  readonly statusText?: string;\n\n  constructor({\n    url,\n    statusCode,\n    statusText,\n    cause,\n    message = cause == null\n      ? `Failed to download ${url}: ${statusCode} ${statusText}`\n      : `Failed to download ${url}: ${cause}`,\n  }: {\n    url: string;\n    statusCode?: number;\n    statusText?: string;\n    message?: string;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.url = url;\n    this.statusCode = statusCode;\n    this.statusText = statusText;\n  }\n\n  static isInstance(error: unknown): error is DownloadError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { DownloadError } from './download-error';\n\n/**\n * Default maximum download size: 2 GiB.\n *\n * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the\n * body internally, then creates the JS ArrayBuffer), so very large downloads\n * risk exceeding the default V8 heap limit on 64-bit systems and terminating\n * the process with an out-of-memory error.\n *\n * Setting this limit converts an unrecoverable OOM crash into a catchable\n * `DownloadError`.\n */\nexport const DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\n\n/**\n * Reads a fetch Response body with a size limit to prevent memory exhaustion.\n *\n * Checks the Content-Length header for early rejection, then reads the body\n * incrementally via ReadableStream and aborts with a DownloadError when the\n * limit is exceeded.\n *\n * @param response - The fetch Response to read.\n * @param url - The URL being downloaded (used in error messages).\n * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.\n * @returns A Uint8Array containing the response body.\n * @throws DownloadError if the response exceeds maxBytes.\n */\nexport async function readResponseWithSizeLimit({\n  response,\n  url,\n  maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE,\n}: {\n  response: Response;\n  url: string;\n  maxBytes?: number;\n}): Promise<Uint8Array> {\n  // Early rejection based on Content-Length header\n  const contentLength = response.headers.get('content-length');\n  if (contentLength != null) {\n    const length = parseInt(contentLength, 10);\n    if (!isNaN(length) && length > maxBytes) {\n      throw new DownloadError({\n        url,\n        message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`,\n      });\n    }\n  }\n\n  const body = response.body;\n\n  // Handle missing body (empty responses)\n  if (body == null) {\n    return new Uint8Array(0);\n  }\n\n  const reader = body.getReader();\n  const chunks: Uint8Array[] = [];\n  let totalBytes = 0;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n\n      if (done) {\n        break;\n      }\n\n      totalBytes += value.length;\n\n      if (totalBytes > maxBytes) {\n        throw new DownloadError({\n          url,\n          message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`,\n        });\n      }\n\n      chunks.push(value);\n    }\n  } finally {\n    try {\n      await reader.cancel();\n    } finally {\n      reader.releaseLock();\n    }\n  }\n\n  // Concatenate chunks into a single Uint8Array\n  const result = new Uint8Array(totalBytes);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.length;\n  }\n\n  return result;\n}\n", "import { DownloadError } from './download-error';\n\n/**\n * Validates that a URL is safe to download from, blocking private/internal addresses\n * to prevent SSRF attacks.\n *\n * @param url - The URL string to validate.\n * @throws DownloadError if the URL is unsafe.\n */\nexport function validateDownloadUrl(url: string): void {\n  let parsed: URL;\n  try {\n    parsed = new URL(url);\n  } catch {\n    throw new DownloadError({\n      url,\n      message: `Invalid URL: ${url}`,\n    });\n  }\n\n  // Only allow http and https protocols\n  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n    throw new DownloadError({\n      url,\n      message: `URL scheme must be http or https, got ${parsed.protocol}`,\n    });\n  }\n\n  const hostname = parsed.hostname;\n\n  // Block empty hostname\n  if (!hostname) {\n    throw new DownloadError({\n      url,\n      message: `URL must have a hostname`,\n    });\n  }\n\n  // Block localhost and .local domains\n  if (\n    hostname === 'localhost' ||\n    hostname.endsWith('.local') ||\n    hostname.endsWith('.localhost')\n  ) {\n    throw new DownloadError({\n      url,\n      message: `URL with hostname ${hostname} is not allowed`,\n    });\n  }\n\n  // Check for IPv6 addresses (enclosed in brackets in URLs)\n  if (hostname.startsWith('[') && hostname.endsWith(']')) {\n    const ipv6 = hostname.slice(1, -1);\n    if (isPrivateIPv6(ipv6)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IPv6 address ${hostname} is not allowed`,\n      });\n    }\n    return;\n  }\n\n  // Check for IPv4 addresses\n  if (isIPv4(hostname)) {\n    if (isPrivateIPv4(hostname)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IP address ${hostname} is not allowed`,\n      });\n    }\n    return;\n  }\n}\n\nfunction isIPv4(hostname: string): boolean {\n  const parts = hostname.split('.');\n  if (parts.length !== 4) return false;\n  return parts.every(part => {\n    const num = Number(part);\n    return (\n      Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part\n    );\n  });\n}\n\nfunction isPrivateIPv4(ip: string): boolean {\n  const parts = ip.split('.').map(Number);\n  const [a, b] = parts;\n\n  // 0.0.0.0/8\n  if (a === 0) return true;\n  // 10.0.0.0/8\n  if (a === 10) return true;\n  // 127.0.0.0/8\n  if (a === 127) return true;\n  // 169.254.0.0/16\n  if (a === 169 && b === 254) return true;\n  // 172.16.0.0/12\n  if (a === 172 && b >= 16 && b <= 31) return true;\n  // 192.168.0.0/16\n  if (a === 192 && b === 168) return true;\n\n  return false;\n}\n\nfunction isPrivateIPv6(ip: string): boolean {\n  const normalized = ip.toLowerCase();\n\n  // ::1 (loopback)\n  if (normalized === '::1') return true;\n  // :: (unspecified)\n  if (normalized === '::') return true;\n\n  // Check for IPv4-mapped addresses (::ffff:x.x.x.x or ::ffff:HHHH:HHHH)\n  if (normalized.startsWith('::ffff:')) {\n    const mappedPart = normalized.slice(7);\n    // Dotted-decimal form: ::ffff:127.0.0.1\n    if (isIPv4(mappedPart)) {\n      return isPrivateIPv4(mappedPart);\n    }\n    // Hex form: ::ffff:7f00:1 (URL parser normalizes to this)\n    const hexParts = mappedPart.split(':');\n    if (hexParts.length === 2) {\n      const high = parseInt(hexParts[0], 16);\n      const low = parseInt(hexParts[1], 16);\n      if (!isNaN(high) && !isNaN(low)) {\n        const a = (high >> 8) & 0xff;\n        const b = high & 0xff;\n        const c = (low >> 8) & 0xff;\n        const d = low & 0xff;\n        return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n      }\n    }\n  }\n\n  // fc00::/7 (unique local addresses - fc00:: and fd00::)\n  if (normalized.startsWith('fc') || normalized.startsWith('fd')) return true;\n\n  // fe80::/10 (link-local)\n  if (normalized.startsWith('fe80')) return true;\n\n  return false;\n}\n", "import { DownloadError } from './download-error';\nimport {\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n} from './read-response-with-size-limit';\nimport { validateDownloadUrl } from './validate-download-url';\n\n/**\n * Download a file from a URL and return it as a Blob.\n *\n * @param url - The URL to download from.\n * @param options - Optional settings for the download.\n * @param options.maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n * @param options.abortSignal - An optional abort signal to cancel the download.\n * @returns A Promise that resolves to the downloaded Blob.\n *\n * @throws DownloadError if the download fails or exceeds maxBytes.\n */\nexport async function downloadBlob(\n  url: string,\n  options?: { maxBytes?: number; abortSignal?: AbortSignal },\n): Promise<Blob> {\n  validateDownloadUrl(url);\n  try {\n    const response = await fetch(url, {\n      signal: options?.abortSignal,\n    });\n\n    // Validate final URL after redirects to prevent SSRF via open redirect\n    if (response.redirected) {\n      validateDownloadUrl(response.url);\n    }\n\n    if (!response.ok) {\n      throw new DownloadError({\n        url,\n        statusCode: response.status,\n        statusText: response.statusText,\n      });\n    }\n\n    const data = await readResponseWithSizeLimit({\n      response,\n      url,\n      maxBytes: options?.maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE,\n    });\n\n    const contentType = response.headers.get('content-type') ?? undefined;\n    return new Blob([data], contentType ? { type: contentType } : undefined);\n  } catch (error) {\n    if (DownloadError.isInstance(error)) {\n      throw error;\n    }\n\n    throw new DownloadError({ url, cause: error });\n  }\n}\n", "import { InvalidArgumentError } from '@ai-sdk/provider';\n\n/**\n * Creates an ID generator.\n * The total length of the ID is the sum of the prefix, separator, and random part length.\n * Not cryptographically secure.\n *\n * @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.\n * @param prefix - The prefix of the ID to generate. Optional.\n * @param separator - The separator between the prefix and the random part of the ID. Default: '-'.\n * @param size - The size of the random part of the ID to generate. Default: 16.\n */\nexport const createIdGenerator = ({\n  prefix,\n  size = 16,\n  alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n  separator = '-',\n}: {\n  prefix?: string;\n  separator?: string;\n  size?: number;\n  alphabet?: string;\n} = {}): IdGenerator => {\n  const generator = () => {\n    const alphabetLength = alphabet.length;\n    const chars = new Array(size);\n    for (let i = 0; i < size; i++) {\n      chars[i] = alphabet[(Math.random() * alphabetLength) | 0];\n    }\n    return chars.join('');\n  };\n\n  if (prefix == null) {\n    return generator;\n  }\n\n  // check that the prefix is not part of the alphabet (otherwise prefix checking can fail randomly)\n  if (alphabet.includes(separator)) {\n    throw new InvalidArgumentError({\n      argument: 'separator',\n      message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`,\n    });\n  }\n\n  return () => `${prefix}${separator}${generator()}`;\n};\n\n/**\n * A function that generates an ID.\n */\nexport type IdGenerator = () => string;\n\n/**\n * Generates a 16-character random string to use for IDs.\n * Not cryptographically secure.\n */\nexport const generateId = createIdGenerator();\n", "export function getErrorMessage(error: unknown | undefined) {\n  if (error == null) {\n    return 'unknown error';\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return error.message;\n  }\n\n  return JSON.stringify(error);\n}\n", "import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport { ResponseHandler } from './response-handler';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\nimport { VERSION } from './version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const getFromApi = async <T>({\n  url,\n  headers = {},\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  try {\n    const response = await fetch(url, {\n      method: 'GET',\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      signal: abortSignal,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: {},\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: {},\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: {},\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: {},\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: {} });\n  }\n};\n", "import { APICallError } from '@ai-sdk/provider';\nimport { isAbortError } from './is-abort-error';\n\nconst FETCH_FAILED_ERROR_MESSAGES = ['fetch failed', 'failed to fetch'];\n\nconst BUN_ERROR_CODES = [\n  'ConnectionRefused',\n  'ConnectionClosed',\n  'FailedToOpenSocket',\n  'ECONNRESET',\n  'ECONNREFUSED',\n  'ETIMEDOUT',\n  'EPIPE',\n];\n\nfunction isBunNetworkError(error: unknown): error is Error & { code?: string } {\n  if (!(error instanceof Error)) {\n    return false;\n  }\n\n  const code = (error as any).code;\n  if (typeof code === 'string' && BUN_ERROR_CODES.includes(code)) {\n    return true;\n  }\n\n  return false;\n}\n\nexport function handleFetchError({\n  error,\n  url,\n  requestBodyValues,\n}: {\n  error: unknown;\n  url: string;\n  requestBodyValues: unknown;\n}) {\n  if (isAbortError(error)) {\n    return error;\n  }\n\n  // unwrap original error when fetch failed (for easier debugging):\n  if (\n    error instanceof TypeError &&\n    FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())\n  ) {\n    const cause = (error as any).cause;\n\n    if (cause != null) {\n      // Failed to connect to server:\n      return new APICallError({\n        message: `Cannot connect to API: ${cause.message}`,\n        cause,\n        url,\n        requestBodyValues,\n        isRetryable: true, // retry when network error\n      });\n    }\n  }\n\n  if (isBunNetworkError(error)) {\n    return new APICallError({\n      message: `Cannot connect to API: ${error.message}`,\n      cause: error,\n      url,\n      requestBodyValues,\n      isRetryable: true,\n    });\n  }\n\n  return error;\n}\n", "export function isAbortError(error: unknown): error is Error {\n  return (\n    (error instanceof Error || error instanceof DOMException) &&\n    (error.name === 'AbortError' ||\n      error.name === 'ResponseAborted' || // Next.js\n      error.name === 'TimeoutError')\n  );\n}\n", "export function getRuntimeEnvironmentUserAgent(\n  globalThisAny: any = globalThis as any,\n): string {\n  // Browsers\n  if (globalThisAny.window) {\n    return `runtime/browser`;\n  }\n\n  // Cloudflare Workers / Deno / Bun / Node.js >= 21.1\n  if (globalThisAny.navigator?.userAgent) {\n    return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n  }\n\n  // Nodes.js < 21.1\n  if (globalThisAny.process?.versions?.node) {\n    return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n  }\n\n  if (globalThisAny.EdgeRuntime) {\n    return `runtime/vercel-edge`;\n  }\n\n  return 'runtime/unknown';\n}\n", "/**\n * Normalizes different header inputs into a plain record with lower-case keys.\n * Entries with `undefined` or `null` values are removed.\n *\n * @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.\n * @returns A record containing the normalized header entries.\n */\nexport function normalizeHeaders(\n  headers:\n    | HeadersInit\n    | Record<string, string | undefined>\n    | Array<[string, string | undefined]>\n    | undefined,\n): Record<string, string> {\n  if (headers == null) {\n    return {};\n  }\n\n  const normalized: Record<string, string> = {};\n\n  if (headers instanceof Headers) {\n    headers.forEach((value, key) => {\n      normalized[key.toLowerCase()] = value;\n    });\n  } else {\n    if (!Array.isArray(headers)) {\n      headers = Object.entries(headers);\n    }\n\n    for (const [key, value] of headers) {\n      if (value != null) {\n        normalized[key.toLowerCase()] = value;\n      }\n    }\n  }\n\n  return normalized;\n}\n", "import { normalizeHeaders } from './normalize-headers';\n\n/**\n * Appends suffix parts to the `user-agent` header.\n * If a `user-agent` header already exists, the suffix parts are appended to it.\n * If no `user-agent` header exists, a new one is created with the suffix parts.\n * Automatically removes undefined entries from the headers.\n *\n * @param headers - The original headers.\n * @param userAgentSuffixParts - The parts to append to the `user-agent` header.\n * @returns The new headers with the `user-agent` header set or updated.\n */\nexport function withUserAgentSuffix(\n  headers: HeadersInit | Record<string, string | undefined> | undefined,\n  ...userAgentSuffixParts: string[]\n): Record<string, string> {\n  const normalizedHeaders = new Headers(normalizeHeaders(headers));\n\n  const currentUserAgentHeader = normalizedHeaders.get('user-agent') || '';\n\n  normalizedHeaders.set(\n    'user-agent',\n    [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(' '),\n  );\n\n  return Object.fromEntries(normalizedHeaders.entries());\n}\n", "// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n", "import {\n  JSONSchema7,\n  LanguageModelV3Message,\n  LanguageModelV3Prompt,\n} from '@ai-sdk/provider';\n\nconst DEFAULT_SCHEMA_PREFIX = 'JSON schema:';\nconst DEFAULT_SCHEMA_SUFFIX =\n  'You MUST answer with a JSON object that matches the JSON schema above.';\nconst DEFAULT_GENERIC_SUFFIX = 'You MUST answer with JSON.';\n\nexport function injectJsonInstruction({\n  prompt,\n  schema,\n  schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : undefined,\n  schemaSuffix = schema != null\n    ? DEFAULT_SCHEMA_SUFFIX\n    : DEFAULT_GENERIC_SUFFIX,\n}: {\n  prompt?: string;\n  schema?: JSONSchema7;\n  schemaPrefix?: string;\n  schemaSuffix?: string;\n}): string {\n  return [\n    prompt != null && prompt.length > 0 ? prompt : undefined,\n    prompt != null && prompt.length > 0 ? '' : undefined, // add a newline if prompt is not null\n    schemaPrefix,\n    schema != null ? JSON.stringify(schema) : undefined,\n    schemaSuffix,\n  ]\n    .filter(line => line != null)\n    .join('\\n');\n}\n\nexport function injectJsonInstructionIntoMessages({\n  messages,\n  schema,\n  schemaPrefix,\n  schemaSuffix,\n}: {\n  messages: LanguageModelV3Prompt;\n  schema?: JSONSchema7;\n  schemaPrefix?: string;\n  schemaSuffix?: string;\n}): LanguageModelV3Prompt {\n  const systemMessage: LanguageModelV3Message =\n    messages[0]?.role === 'system'\n      ? { ...messages[0] }\n      : { role: 'system', content: '' };\n\n  systemMessage.content = injectJsonInstruction({\n    prompt: systemMessage.content,\n    schema,\n    schemaPrefix,\n    schemaSuffix,\n  });\n\n  return [\n    systemMessage,\n    ...(messages[0]?.role === 'system' ? messages.slice(1) : messages),\n  ];\n}\n", "/**\n * Type guard that checks whether a value is not `null` or `undefined`.\n *\n * @template T - The type of the value to check.\n * @param value - The value to check.\n * @returns `true` if the value is neither `null` nor `undefined`, otherwise `false`.\n */\nexport function isNonNullable<T>(\n  value: T | undefined | null,\n): value is NonNullable<T> {\n  return value != null;\n}\n", "/**\n * Checks if the given URL is supported natively by the model.\n *\n * @param mediaType - The media type of the URL. Case-sensitive.\n * @param url - The URL to check.\n * @param supportedUrls - A record where keys are case-sensitive media types (or '*')\n *                        and values are arrays of RegExp patterns for URLs.\n *\n * @returns `true` if the URL matches a pattern under the specific media type\n *          or the wildcard '*', `false` otherwise.\n */\nexport function isUrlSupported({\n  mediaType,\n  url,\n  supportedUrls,\n}: {\n  mediaType: string;\n  url: string;\n  supportedUrls: Record<string, RegExp[]>;\n}): boolean {\n  // standardize media type and url to lower case\n  url = url.toLowerCase();\n  mediaType = mediaType.toLowerCase();\n\n  return (\n    Object.entries(supportedUrls)\n      // standardize supported url map into lowercase prefixes:\n      .map(([key, value]) => {\n        const mediaType = key.toLowerCase();\n        return mediaType === '*' || mediaType === '*/*'\n          ? { mediaTypePrefix: '', regexes: value }\n          : { mediaTypePrefix: mediaType.replace(/\\*/, ''), regexes: value };\n      })\n      // gather all regexp pattern from matched media type prefixes:\n      .filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix))\n      .flatMap(({ regexes }) => regexes)\n      // check if any pattern matches the url:\n      .some(pattern => pattern.test(url))\n  );\n}\n", "import { LoadAPIKeyError } from '@ai-sdk/provider';\n\nexport function loadApiKey({\n  apiKey,\n  environmentVariableName,\n  apiKeyParameterName = 'apiKey',\n  description,\n}: {\n  apiKey: string | undefined;\n  environmentVariableName: string;\n  apiKeyParameterName?: string;\n  description: string;\n}): string {\n  if (typeof apiKey === 'string') {\n    return apiKey;\n  }\n\n  if (apiKey != null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string.`,\n    });\n  }\n\n  if (typeof process === 'undefined') {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`,\n    });\n  }\n\n  apiKey = process.env[environmentVariableName];\n\n  if (apiKey == null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`,\n    });\n  }\n\n  if (typeof apiKey !== 'string') {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`,\n    });\n  }\n\n  return apiKey;\n}\n", "/**\n * Loads an optional `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @returns The setting value.\n */\nexport function loadOptionalSetting({\n  settingValue,\n  environmentVariableName,\n}: {\n  settingValue: string | undefined;\n  environmentVariableName: string;\n}): string | undefined {\n  if (typeof settingValue === 'string') {\n    return settingValue;\n  }\n\n  if (settingValue != null || typeof process === 'undefined') {\n    return undefined;\n  }\n\n  settingValue = process.env[environmentVariableName];\n\n  if (settingValue == null || typeof settingValue !== 'string') {\n    return undefined;\n  }\n\n  return settingValue;\n}\n", "import { LoadSettingError } from '@ai-sdk/provider';\n\n/**\n * Loads a `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @param settingName - The setting name.\n * @param description - The description of the setting.\n * @returns The setting value.\n */\nexport function loadSetting({\n  settingValue,\n  environmentVariableName,\n  settingName,\n  description,\n}: {\n  settingValue: string | undefined;\n  environmentVariableName: string;\n  settingName: string;\n  description: string;\n}): string {\n  if (typeof settingValue === 'string') {\n    return settingValue;\n  }\n\n  if (settingValue != null) {\n    throw new LoadSettingError({\n      message: `${description} setting must be a string.`,\n    });\n  }\n\n  if (typeof process === 'undefined') {\n    throw new LoadSettingError({\n      message:\n        `${description} setting is missing. ` +\n        `Pass it using the '${settingName}' parameter. ` +\n        `Environment variables is not supported in this environment.`,\n    });\n  }\n\n  settingValue = process.env[environmentVariableName];\n\n  if (settingValue == null) {\n    throw new LoadSettingError({\n      message:\n        `${description} setting is missing. ` +\n        `Pass it using the '${settingName}' parameter ` +\n        `or the ${environmentVariableName} environment variable.`,\n    });\n  }\n\n  if (typeof settingValue !== 'string') {\n    throw new LoadSettingError({\n      message:\n        `${description} setting must be a string. ` +\n        `The value of the ${environmentVariableName} environment variable is not a string.`,\n    });\n  }\n\n  return settingValue;\n}\n", "/**\n * Maps a media type to its corresponding file extension.\n * It was originally introduced to set a filename for audio file uploads\n * in https://github.com/vercel/ai/pull/8159.\n *\n * @param mediaType The media type to map.\n * @returns The corresponding file extension\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n */\nexport function mediaTypeToExtension(mediaType: string) {\n  const [_type, subtype = ''] = mediaType.toLowerCase().split('/');\n\n  return (\n    {\n      mpeg: 'mp3',\n      'x-wav': 'wav',\n      opus: 'ogg',\n      mp4: 'm4a',\n      'x-m4a': 'm4a',\n    }[subtype] ?? subtype\n  );\n}\n", "import {\n  JSONParseError,\n  JSONValue,\n  TypeValidationError,\n} from '@ai-sdk/provider';\nimport { secureJsonParse } from './secure-json-parse';\nimport { safeValidateTypes, validateTypes } from './validate-types';\nimport { FlexibleSchema } from './schema';\n\n/**\n * Parses a JSON string into an unknown object.\n *\n * @param text - The JSON string to parse.\n * @returns {JSONValue} - The parsed JSON object.\n */\nexport async function parseJSON(options: {\n  text: string;\n  schema?: undefined;\n}): Promise<JSONValue>;\n/**\n * Parses a JSON string into a strongly-typed object using the provided schema.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns {Promise<T>} - The parsed object.\n */\nexport async function parseJSON<T>(options: {\n  text: string;\n  schema: FlexibleSchema<T>;\n}): Promise<T>;\nexport async function parseJSON<T>({\n  text,\n  schema,\n}: {\n  text: string;\n  schema?: FlexibleSchema<T>;\n}): Promise<T> {\n  try {\n    const value = secureJsonParse(text);\n\n    if (schema == null) {\n      return value;\n    }\n\n    return validateTypes<T>({ value, schema });\n  } catch (error) {\n    if (\n      JSONParseError.isInstance(error) ||\n      TypeValidationError.isInstance(error)\n    ) {\n      throw error;\n    }\n\n    throw new JSONParseError({ text, cause: error });\n  }\n}\n\nexport type ParseResult<T> =\n  | { success: true; value: T; rawValue: unknown }\n  | {\n      success: false;\n      error: JSONParseError | TypeValidationError;\n      rawValue: unknown;\n    };\n\n/**\n * Safely parses a JSON string and returns the result as an object of type `unknown`.\n *\n * @param text - The JSON string to parse.\n * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.\n */\nexport async function safeParseJSON(options: {\n  text: string;\n  schema?: undefined;\n}): Promise<ParseResult<JSONValue>>;\n/**\n * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeParseJSON<T>(options: {\n  text: string;\n  schema: FlexibleSchema<T>;\n}): Promise<ParseResult<T>>;\nexport async function safeParseJSON<T>({\n  text,\n  schema,\n}: {\n  text: string;\n  schema?: FlexibleSchema<T>;\n}): Promise<ParseResult<T>> {\n  try {\n    const value = secureJsonParse(text);\n\n    if (schema == null) {\n      return { success: true, value: value as T, rawValue: value };\n    }\n\n    return await safeValidateTypes<T>({ value, schema });\n  } catch (error) {\n    return {\n      success: false,\n      error: JSONParseError.isInstance(error)\n        ? error\n        : new JSONParseError({ text, cause: error }),\n      rawValue: undefined,\n    };\n  }\n}\n\nexport function isParsableJson(input: string): boolean {\n  try {\n    secureJsonParse(input);\n    return true;\n  } catch {\n    return false;\n  }\n}\n", "// Licensed under BSD-3-Clause (this file only)\n// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js\n//\n// Copyright (c) Vercel, Inc. (https://vercel.com)\n// Copyright (c) 2019 The Fastify Team\n// Copyright (c) 2019, Sideway Inc, and project contributors\n// All rights reserved.\n//\n// The complete list of contributors can be found at:\n// - https://github.com/hapijs/bourne/graphs/contributors\n// - https://github.com/fastify/secure-json-parse/graphs/contributors\n// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.ts\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nconst suspectProtoRx =\n  /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nconst suspectConstructorRx =\n  /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\n\nfunction _parse(text: string) {\n  // Parse normally\n  const obj = JSON.parse(text);\n\n  // Ignore null and non-objects\n  if (obj === null || typeof obj !== 'object') {\n    return obj;\n  }\n\n  if (\n    suspectProtoRx.test(text) === false &&\n    suspectConstructorRx.test(text) === false\n  ) {\n    return obj;\n  }\n\n  // Scan result for proto keys\n  return filter(obj);\n}\n\nfunction filter(obj: any) {\n  let next = [obj];\n\n  while (next.length) {\n    const nodes = next;\n    next = [];\n\n    for (const node of nodes) {\n      if (Object.prototype.hasOwnProperty.call(node, '__proto__')) {\n        throw new SyntaxError('Object contains forbidden prototype property');\n      }\n\n      if (\n        Object.prototype.hasOwnProperty.call(node, 'constructor') &&\n        node.constructor !== null &&\n        typeof node.constructor === 'object' &&\n        Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')\n      ) {\n        throw new SyntaxError('Object contains forbidden prototype property');\n      }\n\n      for (const key in node) {\n        const value = node[key];\n        if (value && typeof value === 'object') {\n          next.push(value);\n        }\n      }\n    }\n  }\n  return obj;\n}\n\nexport function secureJsonParse(text: string) {\n  const { stackTraceLimit } = Error;\n  try {\n    // Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90\n    Error.stackTraceLimit = 0;\n  } catch (e) {\n    // Fallback in case Error is immutable (v8 readonly)\n    return _parse(text);\n  }\n\n  try {\n    return _parse(text);\n  } finally {\n    Error.stackTraceLimit = stackTraceLimit;\n  }\n}\n", "import { TypeValidationContext, TypeValidationError } from '@ai-sdk/provider';\nimport { FlexibleSchema, asSchema } from './schema';\n\n/**\n * Validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @param {TypeValidationContext} options.context - Optional context about what is being validated.\n * @returns {Promise<T>} - The typed object.\n */\nexport async function validateTypes<OBJECT>({\n  value,\n  schema,\n  context,\n}: {\n  value: unknown;\n  schema: FlexibleSchema<OBJECT>;\n  context?: TypeValidationContext;\n}): Promise<OBJECT> {\n  const result = await safeValidateTypes({ value, schema, context });\n\n  if (!result.success) {\n    throw TypeValidationError.wrap({ value, cause: result.error, context });\n  }\n\n  return result.value;\n}\n\n/**\n * Safely validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The JSON object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @param {TypeValidationContext} options.context - Optional context about what is being validated.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeValidateTypes<OBJECT>({\n  value,\n  schema,\n  context,\n}: {\n  value: unknown;\n  schema: FlexibleSchema<OBJECT>;\n  context?: TypeValidationContext;\n}): Promise<\n  | {\n      success: true;\n      value: OBJECT;\n      rawValue: unknown;\n    }\n  | {\n      success: false;\n      error: TypeValidationError;\n      rawValue: unknown;\n    }\n> {\n  const actualSchema = asSchema(schema);\n\n  try {\n    if (actualSchema.validate == null) {\n      return { success: true, value: value as OBJECT, rawValue: value };\n    }\n\n    const result = await actualSchema.validate(value);\n\n    if (result.success) {\n      return { success: true, value: result.value, rawValue: value };\n    }\n\n    return {\n      success: false,\n      error: TypeValidationError.wrap({ value, cause: result.error, context }),\n      rawValue: value,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: TypeValidationError.wrap({ value, cause: error, context }),\n      rawValue: value,\n    };\n  }\n}\n", "import { JSONSchema7, TypeValidationError } from '@ai-sdk/provider';\nimport { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport { addAdditionalPropertiesToJsonSchema } from './add-additional-properties-to-json-schema';\nimport { zod3ToJsonSchema } from './to-json-schema/zod3-to-json-schema';\n\n/**\n * Used to mark schemas so we can support both Zod and custom schemas.\n */\nconst schemaSymbol = Symbol.for('vercel.ai.schema');\n\nexport type ValidationResult<OBJECT> =\n  | { success: true; value: OBJECT }\n  | { success: false; error: Error };\n\nexport type Schema<OBJECT = unknown> = {\n  /**\n   * Used to mark schemas so we can support both Zod and custom schemas.\n   */\n  [schemaSymbol]: true;\n\n  /**\n   * Schema type for inference.\n   */\n  _type: OBJECT;\n\n  /**\n   * Optional. Validates that the structure of a value matches this schema,\n   * and returns a typed version of the value if it does.\n   */\n  readonly validate?: (\n    value: unknown,\n  ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n\n  /**\n   * The JSON Schema for the schema. It is passed to the providers.\n   */\n  readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;\n};\n\n/**\n * Creates a schema with deferred creation.\n * This is important to reduce the startup time of the library\n * and to avoid initializing unused validators.\n *\n * @param createValidator A function that creates a schema.\n * @returns A function that returns a schema.\n */\nexport function lazySchema<SCHEMA>(\n  createSchema: () => Schema<SCHEMA>,\n): LazySchema<SCHEMA> {\n  // cache the validator to avoid initializing it multiple times\n  let schema: Schema<SCHEMA> | undefined;\n  return () => {\n    if (schema == null) {\n      schema = createSchema();\n    }\n    return schema;\n  };\n}\n\nexport type LazySchema<SCHEMA> = () => Schema<SCHEMA>;\n\nexport type ZodSchema<SCHEMA = any> =\n  | z3.Schema<SCHEMA, z3.ZodTypeDef, any>\n  | z4.core.$ZodType<SCHEMA, any>;\n\nexport type StandardSchema<SCHEMA = any> = StandardSchemaV1<unknown, SCHEMA> &\n  StandardJSONSchemaV1<unknown, SCHEMA>;\n\nexport type FlexibleSchema<SCHEMA = any> =\n  | Schema<SCHEMA>\n  | LazySchema<SCHEMA>\n  | ZodSchema<SCHEMA>\n  | StandardSchema<SCHEMA>;\n\nexport type InferSchema<SCHEMA> =\n  SCHEMA extends ZodSchema<infer T>\n    ? T\n    : SCHEMA extends StandardSchema<infer T>\n      ? T\n      : SCHEMA extends LazySchema<infer T>\n        ? T\n        : SCHEMA extends Schema<infer T>\n          ? T\n          : never;\n\n/**\n * Create a schema using a JSON Schema.\n *\n * @param jsonSchema The JSON Schema for the schema.\n * @param options.validate Optional. A validation function for the schema.\n */\nexport function jsonSchema<OBJECT = unknown>(\n  jsonSchema:\n    | JSONSchema7\n    | PromiseLike<JSONSchema7>\n    | (() => JSONSchema7 | PromiseLike<JSONSchema7>),\n  {\n    validate,\n  }: {\n    validate?: (\n      value: unknown,\n    ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n  } = {},\n): Schema<OBJECT> {\n  return {\n    [schemaSymbol]: true,\n    _type: undefined as OBJECT, // should never be used directly\n    get jsonSchema() {\n      if (typeof jsonSchema === 'function') {\n        jsonSchema = jsonSchema(); // cache the function results\n      }\n      return jsonSchema;\n    },\n    validate,\n  };\n}\n\nfunction isSchema(value: unknown): value is Schema {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    schemaSymbol in value &&\n    value[schemaSymbol] === true &&\n    'jsonSchema' in value &&\n    'validate' in value\n  );\n}\n\nexport function asSchema<OBJECT>(\n  schema: FlexibleSchema<OBJECT> | undefined,\n): Schema<OBJECT> {\n  return schema == null\n    ? jsonSchema({ properties: {}, additionalProperties: false })\n    : isSchema(schema)\n      ? schema\n      : '~standard' in schema\n        ? schema['~standard'].vendor === 'zod'\n          ? zodSchema(schema as ZodSchema<OBJECT>)\n          : standardSchema(schema as StandardSchema<OBJECT>)\n        : schema();\n}\n\nfunction standardSchema<OBJECT>(\n  standardSchema: StandardSchema<OBJECT>,\n): Schema<OBJECT> {\n  return jsonSchema(\n    () =>\n      addAdditionalPropertiesToJsonSchema(\n        standardSchema['~standard'].jsonSchema.input({\n          target: 'draft-07',\n        }) as JSONSchema7,\n      ),\n    {\n      validate: async value => {\n        const result = await standardSchema['~standard'].validate(value);\n        return 'value' in result\n          ? { success: true, value: result.value }\n          : {\n              success: false,\n              error: new TypeValidationError({\n                value,\n                cause: result.issues,\n              }),\n            };\n      },\n    },\n  );\n}\n\nexport function zod3Schema<OBJECT>(\n  zodSchema: z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  // default to no references (to support openapi conversion for google)\n  const useReferences = options?.useReferences ?? false;\n\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () =>\n      zod3ToJsonSchema(zodSchema, {\n        $refStrategy: useReferences ? 'root' : 'none',\n      }) as JSONSchema7,\n    {\n      validate: async value => {\n        const result = await zodSchema.safeParseAsync(value);\n        return result.success\n          ? { success: true, value: result.data }\n          : { success: false, error: result.error };\n      },\n    },\n  );\n}\n\nexport function zod4Schema<OBJECT>(\n  zodSchema: z4.core.$ZodType<OBJECT, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  // default to no references (to support openapi conversion for google)\n  const useReferences = options?.useReferences ?? false;\n\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () =>\n      addAdditionalPropertiesToJsonSchema(\n        z4.toJSONSchema(zodSchema, {\n          target: 'draft-7',\n          io: 'input',\n          reused: useReferences ? 'ref' : 'inline',\n        }) as JSONSchema7,\n      ),\n    {\n      validate: async value => {\n        const result = await z4.safeParseAsync(zodSchema, value);\n        return result.success\n          ? { success: true, value: result.data }\n          : { success: false, error: result.error };\n      },\n    },\n  );\n}\n\nexport function isZod4Schema(\n  zodSchema: z4.core.$ZodType<any, any> | z3.Schema<any, z3.ZodTypeDef, any>,\n): zodSchema is z4.core.$ZodType<any, any> {\n  // https://zod.dev/library-authors?id=how-to-support-zod-3-and-zod-4-simultaneously\n  return '_zod' in zodSchema;\n}\n\nexport function zodSchema<OBJECT>(\n  zodSchema:\n    | z4.core.$ZodType<OBJECT, any>\n    | z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  if (isZod4Schema(zodSchema)) {\n    return zod4Schema(zodSchema, options);\n  } else {\n    return zod3Schema(zodSchema, options);\n  }\n}\n", "import { JSONSchema7, JSONSchema7Definition } from '@ai-sdk/provider';\n\n/**\n * Recursively adds additionalProperties: false to the JSON schema. This is necessary because some providers (e.g. OpenAI) do not support additionalProperties: true.\n */\nexport function addAdditionalPropertiesToJsonSchema(\n  jsonSchema: JSONSchema7,\n): JSONSchema7 {\n  if (\n    jsonSchema.type === 'object' ||\n    (Array.isArray(jsonSchema.type) && jsonSchema.type.includes('object'))\n  ) {\n    jsonSchema.additionalProperties = false;\n    const { properties } = jsonSchema;\n    if (properties != null) {\n      for (const key of Object.keys(properties)) {\n        properties[key] = visit(properties[key]);\n      }\n    }\n  }\n\n  if (jsonSchema.items != null) {\n    jsonSchema.items = Array.isArray(jsonSchema.items)\n      ? jsonSchema.items.map(visit)\n      : visit(jsonSchema.items);\n  }\n\n  if (jsonSchema.anyOf != null) {\n    jsonSchema.anyOf = jsonSchema.anyOf.map(visit);\n  }\n\n  if (jsonSchema.allOf != null) {\n    jsonSchema.allOf = jsonSchema.allOf.map(visit);\n  }\n\n  if (jsonSchema.oneOf != null) {\n    jsonSchema.oneOf = jsonSchema.oneOf.map(visit);\n  }\n\n  const { definitions } = jsonSchema;\n  if (definitions != null) {\n    for (const key of Object.keys(definitions)) {\n      definitions[key] = visit(definitions[key]);\n    }\n  }\n\n  return jsonSchema;\n}\n\nfunction visit(def: JSONSchema7Definition): JSONSchema7Definition {\n  if (typeof def === 'boolean') return def;\n  return addAdditionalPropertiesToJsonSchema(def);\n}\n", "import { ZodSchema, ZodTypeDef } from 'zod/v3';\nimport { Refs, Seen } from './refs';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type DateStrategy =\n  | 'format:date-time'\n  | 'format:date'\n  | 'string'\n  | 'integer';\n\nexport const ignoreOverride = Symbol(\n  'Let zodToJsonSchema decide on which parser to use',\n);\n\nexport type OverrideCallback = (\n  def: ZodTypeDef,\n  refs: Refs,\n  seen: Seen | undefined,\n  forceResolution?: boolean,\n) => JsonSchema7Type | undefined | typeof ignoreOverride;\n\nexport type PostProcessCallback = (\n  jsonSchema: JsonSchema7Type | undefined,\n  def: ZodTypeDef,\n  refs: Refs,\n) => JsonSchema7Type | undefined;\n\nexport const jsonDescription: PostProcessCallback = (jsonSchema, def) => {\n  if (def.description) {\n    try {\n      return {\n        ...jsonSchema,\n        ...JSON.parse(def.description),\n      };\n    } catch {}\n  }\n\n  return jsonSchema;\n};\n\nexport type Options = {\n  name: string | undefined;\n  $refStrategy: 'root' | 'relative' | 'none' | 'seen';\n  basePath: string[];\n  effectStrategy: 'input' | 'any';\n  pipeStrategy: 'input' | 'output' | 'all';\n  dateStrategy: DateStrategy | DateStrategy[];\n  mapStrategy: 'entries' | 'record';\n  removeAdditionalStrategy: 'passthrough' | 'strict';\n  allowedAdditionalProperties: true | undefined;\n  rejectedAdditionalProperties: false | undefined;\n  strictUnions: boolean;\n  definitionPath: string;\n  definitions: Record<string, ZodSchema>;\n  errorMessages: boolean;\n  patternStrategy: 'escape' | 'preserve';\n  applyRegexFlags: boolean;\n  emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod';\n  base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod';\n  nameStrategy: 'ref' | 'title';\n  override?: OverrideCallback;\n  postProcess?: PostProcessCallback;\n};\n\nexport const defaultOptions: Options = {\n  name: undefined,\n  $refStrategy: 'root',\n  basePath: ['#'],\n  effectStrategy: 'input',\n  pipeStrategy: 'all',\n  dateStrategy: 'format:date-time',\n  mapStrategy: 'entries',\n  removeAdditionalStrategy: 'passthrough',\n  allowedAdditionalProperties: true,\n  rejectedAdditionalProperties: false,\n  definitionPath: 'definitions',\n  strictUnions: false,\n  definitions: {},\n  errorMessages: false,\n  patternStrategy: 'escape',\n  applyRegexFlags: false,\n  emailStrategy: 'format:email',\n  base64Strategy: 'contentEncoding:base64',\n  nameStrategy: 'ref',\n};\n\nexport const getDefaultOptions = (\n  options: Partial<Options> | string | undefined,\n) =>\n  (typeof options === 'string'\n    ? {\n        ...defaultOptions,\n        name: options,\n      }\n    : {\n        ...defaultOptions,\n        ...options,\n      }) as Options;\n", "import { ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseAnyDef } from './parsers/any';\nimport { parseArrayDef } from './parsers/array';\nimport { parseBigintDef } from './parsers/bigint';\nimport { parseBooleanDef } from './parsers/boolean';\nimport { parseBrandedDef } from './parsers/branded';\nimport { parseCatchDef } from './parsers/catch';\nimport { parseDateDef } from './parsers/date';\nimport { parseDefaultDef } from './parsers/default';\nimport { parseEffectsDef } from './parsers/effects';\nimport { parseEnumDef } from './parsers/enum';\nimport { parseIntersectionDef } from './parsers/intersection';\nimport { parseLiteralDef } from './parsers/literal';\nimport { parseMapDef } from './parsers/map';\nimport { parseNativeEnumDef } from './parsers/native-enum';\nimport { parseNeverDef } from './parsers/never';\nimport { parseNullDef } from './parsers/null';\nimport { parseNullableDef } from './parsers/nullable';\nimport { parseNumberDef } from './parsers/number';\nimport { parseObjectDef } from './parsers/object';\nimport { parseOptionalDef } from './parsers/optional';\nimport { parsePipelineDef } from './parsers/pipeline';\nimport { parsePromiseDef } from './parsers/promise';\nimport { parseRecordDef } from './parsers/record';\nimport { parseSetDef } from './parsers/set';\nimport { parseStringDef } from './parsers/string';\nimport { parseTupleDef } from './parsers/tuple';\nimport { parseUndefinedDef } from './parsers/undefined';\nimport { parseUnionDef } from './parsers/union';\nimport { parseUnknownDef } from './parsers/unknown';\nimport { Refs } from './refs';\nimport { parseReadonlyDef } from './parsers/readonly';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type InnerDefGetter = () => any;\n\nexport const selectParser = (\n  def: any,\n  typeName: ZodFirstPartyTypeKind,\n  refs: Refs,\n): JsonSchema7Type | undefined | InnerDefGetter => {\n  switch (typeName) {\n    case ZodFirstPartyTypeKind.ZodString:\n      return parseStringDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodNumber:\n      return parseNumberDef(def);\n    case ZodFirstPartyTypeKind.ZodObject:\n      return parseObjectDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodBigInt:\n      return parseBigintDef(def);\n    case ZodFirstPartyTypeKind.ZodBoolean:\n      return parseBooleanDef();\n    case ZodFirstPartyTypeKind.ZodDate:\n      return parseDateDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodUndefined:\n      return parseUndefinedDef();\n    case ZodFirstPartyTypeKind.ZodNull:\n      return parseNullDef();\n    case ZodFirstPartyTypeKind.ZodArray:\n      return parseArrayDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodUnion:\n    case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n      return parseUnionDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodIntersection:\n      return parseIntersectionDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodTuple:\n      return parseTupleDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodRecord:\n      return parseRecordDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodLiteral:\n      return parseLiteralDef(def);\n    case ZodFirstPartyTypeKind.ZodEnum:\n      return parseEnumDef(def);\n    case ZodFirstPartyTypeKind.ZodNativeEnum:\n      return parseNativeEnumDef(def);\n    case ZodFirstPartyTypeKind.ZodNullable:\n      return parseNullableDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodOptional:\n      return parseOptionalDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodMap:\n      return parseMapDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodSet:\n      return parseSetDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodLazy:\n      return () => (def as any).getter()._def;\n    case ZodFirstPartyTypeKind.ZodPromise:\n      return parsePromiseDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodNaN:\n    case ZodFirstPartyTypeKind.ZodNever:\n      return parseNeverDef();\n    case ZodFirstPartyTypeKind.ZodEffects:\n      return parseEffectsDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodAny:\n      return parseAnyDef();\n    case ZodFirstPartyTypeKind.ZodUnknown:\n      return parseUnknownDef();\n    case ZodFirstPartyTypeKind.ZodDefault:\n      return parseDefaultDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodBranded:\n      return parseBrandedDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodReadonly:\n      return parseReadonlyDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodCatch:\n      return parseCatchDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodPipeline:\n      return parsePipelineDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodFunction:\n    case ZodFirstPartyTypeKind.ZodVoid:\n    case ZodFirstPartyTypeKind.ZodSymbol:\n      return undefined;\n    default:\n      /* c8 ignore next */\n      return ((_: never) => undefined)(typeName);\n  }\n};\n", "export type JsonSchema7AnyType = { $ref?: string };\n\nexport function parseAnyDef(): JsonSchema7AnyType {\n  return {};\n}\n", "import { ZodArrayDef, ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7ArrayType = {\n  type: 'array';\n  items?: JsonSchema7Type;\n  minItems?: number;\n  maxItems?: number;\n};\n\nexport function parseArrayDef(def: ZodArrayDef, refs: Refs) {\n  const res: JsonSchema7ArrayType = {\n    type: 'array',\n  };\n  if (\n    def.type?._def &&\n    def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny\n  ) {\n    res.items = parseDef(def.type._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items'],\n    });\n  }\n\n  if (def.minLength) {\n    res.minItems = def.minLength.value;\n  }\n  if (def.maxLength) {\n    res.maxItems = def.maxLength.value;\n  }\n  if (def.exactLength) {\n    res.minItems = def.exactLength.value;\n    res.maxItems = def.exactLength.value;\n  }\n  return res;\n}\n", "import { ZodBigIntDef } from 'zod/v3';\n\nexport type JsonSchema7BigintType = {\n  type: 'integer';\n  format: 'int64';\n  minimum?: BigInt;\n  exclusiveMinimum?: BigInt;\n  maximum?: BigInt;\n  exclusiveMaximum?: BigInt;\n  multipleOf?: BigInt;\n};\n\nexport function parseBigintDef(def: ZodBigIntDef): JsonSchema7BigintType {\n  const res: JsonSchema7BigintType = {\n    type: 'integer',\n    format: 'int64',\n  };\n\n  if (!def.checks) return res;\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'min':\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case 'max':\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n\n        break;\n      case 'multipleOf':\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n", "export type JsonSchema7BooleanType = {\n  type: 'boolean';\n};\n\nexport function parseBooleanDef(): JsonSchema7BooleanType {\n  return { type: 'boolean' };\n}\n", "import { ZodBrandedDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport function parseBrandedDef(_def: ZodBrandedDef<any>, refs: Refs) {\n  return parseDef(_def.type._def, refs);\n}\n", "import { ZodCatchDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport const parseCatchDef = (def: ZodCatchDef<any>, refs: Refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n", "import { ZodDateDef } from 'zod/v3';\nimport { Refs } from '../refs';\nimport { DateStrategy } from '../options';\n\nexport type JsonSchema7DateType =\n  | {\n      type: 'integer' | 'string';\n      format: 'unix-time' | 'date-time' | 'date';\n      minimum?: number;\n      maximum?: number;\n    }\n  | {\n      anyOf: JsonSchema7DateType[];\n    };\n\nexport function parseDateDef(\n  def: ZodDateDef,\n  refs: Refs,\n  overrideDateStrategy?: DateStrategy,\n): JsonSchema7DateType {\n  const strategy = overrideDateStrategy ?? refs.dateStrategy;\n\n  if (Array.isArray(strategy)) {\n    return {\n      anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n    };\n  }\n\n  switch (strategy) {\n    case 'string':\n    case 'format:date-time':\n      return {\n        type: 'string',\n        format: 'date-time',\n      };\n    case 'format:date':\n      return {\n        type: 'string',\n        format: 'date',\n      };\n    case 'integer':\n      return integerDateParser(def);\n  }\n}\n\nconst integerDateParser = (def: ZodDateDef) => {\n  const res: JsonSchema7DateType = {\n    type: 'integer',\n    format: 'unix-time',\n  };\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'min':\n        res.minimum = check.value;\n        break;\n      case 'max':\n        res.maximum = check.value;\n        break;\n    }\n  }\n\n  return res;\n};\n", "import { ZodDefaultDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport function parseDefaultDef(\n  _def: ZodDefaultDef,\n  refs: Refs,\n): JsonSchema7Type & { default: any } {\n  return {\n    ...parseDef(_def.innerType._def, refs),\n    default: _def.defaultValue(),\n  };\n}\n", "import { ZodEffectsDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport function parseEffectsDef(\n  _def: ZodEffectsDef,\n  refs: Refs,\n): JsonSchema7Type | undefined {\n  return refs.effectStrategy === 'input'\n    ? parseDef(_def.schema._def, refs)\n    : parseAnyDef();\n}\n", "import { ZodEnumDef } from 'zod/v3';\n\nexport type JsonSchema7EnumType = {\n  type: 'string';\n  enum: string[];\n};\n\nexport function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType {\n  return {\n    type: 'string',\n    enum: Array.from(def.values),\n  };\n}\n", "import { ZodIntersectionDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7StringType } from './string';\n\nexport type JsonSchema7AllOfType = {\n  allOf: JsonSchema7Type[];\n  unevaluatedProperties?: boolean;\n};\n\nconst isJsonSchema7AllOfType = (\n  type: JsonSchema7Type | JsonSchema7StringType,\n): type is JsonSchema7AllOfType => {\n  if ('type' in type && type.type === 'string') return false;\n  return 'allOf' in type;\n};\n\nexport function parseIntersectionDef(\n  def: ZodIntersectionDef,\n  refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined {\n  const allOf = [\n    parseDef(def.left._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'allOf', '0'],\n    }),\n    parseDef(def.right._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'allOf', '1'],\n    }),\n  ].filter((x): x is JsonSchema7Type => !!x);\n\n  const mergedAllOf: JsonSchema7Type[] = [];\n  // If either of the schemas is an allOf, merge them into a single allOf\n  allOf.forEach(schema => {\n    if (isJsonSchema7AllOfType(schema)) {\n      mergedAllOf.push(...schema.allOf);\n    } else {\n      let nestedSchema: JsonSchema7Type = schema;\n      if (\n        'additionalProperties' in schema &&\n        schema.additionalProperties === false\n      ) {\n        const { additionalProperties, ...rest } = schema;\n        nestedSchema = rest;\n      }\n      mergedAllOf.push(nestedSchema);\n    }\n  });\n  return mergedAllOf.length ? { allOf: mergedAllOf } : undefined;\n}\n", "import { ZodLiteralDef } from 'zod/v3';\n\nexport type JsonSchema7LiteralType =\n  | {\n      type: 'string' | 'number' | 'integer' | 'boolean';\n      const: string | number | boolean;\n    }\n  | {\n      type: 'object' | 'array';\n    };\n\nexport function parseLiteralDef(def: ZodLiteralDef): JsonSchema7LiteralType {\n  const parsedType = typeof def.value;\n  if (\n    parsedType !== 'bigint' &&\n    parsedType !== 'number' &&\n    parsedType !== 'boolean' &&\n    parsedType !== 'string'\n  ) {\n    return {\n      type: Array.isArray(def.value) ? 'array' : 'object',\n    };\n  }\n\n  return {\n    type: parsedType === 'bigint' ? 'integer' : parsedType,\n    const: def.value,\n  };\n}\n", "import {\n  ZodFirstPartyTypeKind,\n  ZodMapDef,\n  ZodRecordDef,\n  ZodTypeAny,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseBrandedDef } from './branded';\nimport { JsonSchema7EnumType } from './enum';\nimport { JsonSchema7StringType, parseStringDef } from './string';\n\ntype JsonSchema7RecordPropertyNamesType =\n  | Omit<JsonSchema7StringType, 'type'>\n  | Omit<JsonSchema7EnumType, 'type'>;\n\nexport type JsonSchema7RecordType = {\n  type: 'object';\n  additionalProperties?: JsonSchema7Type | true;\n  propertyNames?: JsonSchema7RecordPropertyNamesType;\n};\n\nexport function parseRecordDef(\n  def: ZodRecordDef<ZodTypeAny, ZodTypeAny> | ZodMapDef,\n  refs: Refs,\n): JsonSchema7RecordType {\n  const schema: JsonSchema7RecordType = {\n    type: 'object',\n    additionalProperties:\n      parseDef(def.valueType._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'additionalProperties'],\n      }) ?? refs.allowedAdditionalProperties,\n  };\n\n  if (\n    def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n    def.keyType._def.checks?.length\n  ) {\n    const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n\n    return {\n      ...schema,\n      propertyNames: keyType,\n    };\n  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n    return {\n      ...schema,\n      propertyNames: {\n        enum: def.keyType._def.values,\n      },\n    };\n  } else if (\n    def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&\n    def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n    def.keyType._def.type._def.checks?.length\n  ) {\n    const { type, ...keyType } = parseBrandedDef(\n      def.keyType._def,\n      refs,\n    ) as JsonSchema7StringType;\n\n    return {\n      ...schema,\n      propertyNames: keyType,\n    };\n  }\n\n  return schema;\n}\n", "import { ZodStringDef } from 'zod/v3';\nimport { Refs } from '../refs';\n\nlet emojiRegex: RegExp | undefined = undefined;\n\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n  /**\n   * `c` was changed to `[cC]` to replicate /i flag\n   */\n  cuid: /^[cC][^\\s-]{8,}$/,\n  cuid2: /^[0-9a-z]+$/,\n  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n  /**\n   * `a-z` was added to replicate /i flag\n   */\n  email:\n    /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n  /**\n   * Constructed a valid Unicode RegExp\n   *\n   * Lazily instantiate since this type of regex isn't supported\n   * in all envs (e.g. React Native).\n   *\n   * See:\n   * https://github.com/colinhacks/zod/issues/2433\n   * Fix in Zod:\n   * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n   */\n  emoji: () => {\n    if (emojiRegex === undefined) {\n      emojiRegex = RegExp(\n        '^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$',\n        'u',\n      );\n    }\n    return emojiRegex;\n  },\n  /**\n   * Unused\n   */\n  uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n  /**\n   * Unused\n   */\n  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])$/,\n  ipv4Cidr:\n    /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n  /**\n   * Unused\n   */\n  ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n  ipv6Cidr:\n    /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n  base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n  base64url:\n    /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n  nanoid: /^[a-zA-Z0-9_-]{21}$/,\n  jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n} as const;\n\nexport type JsonSchema7StringType = {\n  type: 'string';\n  minLength?: number;\n  maxLength?: number;\n  format?:\n    | 'email'\n    | 'idn-email'\n    | 'uri'\n    | 'uuid'\n    | 'date-time'\n    | 'ipv4'\n    | 'ipv6'\n    | 'date'\n    | 'time'\n    | 'duration';\n  pattern?: string;\n  allOf?: {\n    pattern: string;\n  }[];\n  anyOf?: {\n    format: string;\n  }[];\n  contentEncoding?: string;\n};\n\nexport function parseStringDef(\n  def: ZodStringDef,\n  refs: Refs,\n): JsonSchema7StringType {\n  const res: JsonSchema7StringType = {\n    type: 'string',\n  };\n\n  if (def.checks) {\n    for (const check of def.checks) {\n      switch (check.kind) {\n        case 'min':\n          res.minLength =\n            typeof res.minLength === 'number'\n              ? Math.max(res.minLength, check.value)\n              : check.value;\n          break;\n        case 'max':\n          res.maxLength =\n            typeof res.maxLength === 'number'\n              ? Math.min(res.maxLength, check.value)\n              : check.value;\n\n          break;\n        case 'email':\n          switch (refs.emailStrategy) {\n            case 'format:email':\n              addFormat(res, 'email', check.message, refs);\n              break;\n            case 'format:idn-email':\n              addFormat(res, 'idn-email', check.message, refs);\n              break;\n            case 'pattern:zod':\n              addPattern(res, zodPatterns.email, check.message, refs);\n              break;\n          }\n\n          break;\n        case 'url':\n          addFormat(res, 'uri', check.message, refs);\n          break;\n        case 'uuid':\n          addFormat(res, 'uuid', check.message, refs);\n          break;\n        case 'regex':\n          addPattern(res, check.regex, check.message, refs);\n          break;\n        case 'cuid':\n          addPattern(res, zodPatterns.cuid, check.message, refs);\n          break;\n        case 'cuid2':\n          addPattern(res, zodPatterns.cuid2, check.message, refs);\n          break;\n        case 'startsWith':\n          addPattern(\n            res,\n            RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n            check.message,\n            refs,\n          );\n          break;\n        case 'endsWith':\n          addPattern(\n            res,\n            RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n            check.message,\n            refs,\n          );\n          break;\n        case 'datetime':\n          addFormat(res, 'date-time', check.message, refs);\n          break;\n        case 'date':\n          addFormat(res, 'date', check.message, refs);\n          break;\n        case 'time':\n          addFormat(res, 'time', check.message, refs);\n          break;\n        case 'duration':\n          addFormat(res, 'duration', check.message, refs);\n          break;\n        case 'length':\n          res.minLength =\n            typeof res.minLength === 'number'\n              ? Math.max(res.minLength, check.value)\n              : check.value;\n          res.maxLength =\n            typeof res.maxLength === 'number'\n              ? Math.min(res.maxLength, check.value)\n              : check.value;\n          break;\n        case 'includes': {\n          addPattern(\n            res,\n            RegExp(escapeLiteralCheckValue(check.value, refs)),\n            check.message,\n            refs,\n          );\n          break;\n        }\n        case 'ip': {\n          if (check.version !== 'v6') {\n            addFormat(res, 'ipv4', check.message, refs);\n          }\n          if (check.version !== 'v4') {\n            addFormat(res, 'ipv6', check.message, refs);\n          }\n          break;\n        }\n        case 'base64url':\n          addPattern(res, zodPatterns.base64url, check.message, refs);\n          break;\n        case 'jwt':\n          addPattern(res, zodPatterns.jwt, check.message, refs);\n          break;\n        case 'cidr': {\n          if (check.version !== 'v6') {\n            addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n          }\n          if (check.version !== 'v4') {\n            addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n          }\n          break;\n        }\n        case 'emoji':\n          addPattern(res, zodPatterns.emoji(), check.message, refs);\n          break;\n        case 'ulid': {\n          addPattern(res, zodPatterns.ulid, check.message, refs);\n          break;\n        }\n        case 'base64': {\n          switch (refs.base64Strategy) {\n            case 'format:binary': {\n              addFormat(res, 'binary' as any, check.message, refs);\n              break;\n            }\n\n            case 'contentEncoding:base64': {\n              res.contentEncoding = 'base64';\n              break;\n            }\n\n            case 'pattern:zod': {\n              addPattern(res, zodPatterns.base64, check.message, refs);\n              break;\n            }\n          }\n          break;\n        }\n        case 'nanoid': {\n          addPattern(res, zodPatterns.nanoid, check.message, refs);\n        }\n        case 'toLowerCase':\n        case 'toUpperCase':\n        case 'trim':\n          break;\n        default:\n          /* c8 ignore next */\n          ((_: never) => {})(check);\n      }\n    }\n  }\n\n  return res;\n}\n\nfunction escapeLiteralCheckValue(literal: string, refs: Refs): string {\n  return refs.patternStrategy === 'escape'\n    ? escapeNonAlphaNumeric(literal)\n    : literal;\n}\n\nconst ALPHA_NUMERIC = new Set(\n  'ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789',\n);\n\nfunction escapeNonAlphaNumeric(source: string) {\n  let result = '';\n\n  for (let i = 0; i < source.length; i++) {\n    if (!ALPHA_NUMERIC.has(source[i])) {\n      result += '\\\\';\n    }\n\n    result += source[i];\n  }\n\n  return result;\n}\n\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(\n  schema: JsonSchema7StringType,\n  value: Required<JsonSchema7StringType>['format'],\n  message: string | undefined,\n  refs: Refs,\n) {\n  if (schema.format || schema.anyOf?.some(x => x.format)) {\n    if (!schema.anyOf) {\n      schema.anyOf = [];\n    }\n\n    if (schema.format) {\n      schema.anyOf!.push({\n        format: schema.format,\n      });\n      delete schema.format;\n    }\n\n    schema.anyOf!.push({\n      format: value,\n      ...(message &&\n        refs.errorMessages && { errorMessage: { format: message } }),\n    });\n  } else {\n    schema.format = value;\n  }\n}\n\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(\n  schema: JsonSchema7StringType,\n  regex: RegExp,\n  message: string | undefined,\n  refs: Refs,\n) {\n  if (schema.pattern || schema.allOf?.some(x => x.pattern)) {\n    if (!schema.allOf) {\n      schema.allOf = [];\n    }\n\n    if (schema.pattern) {\n      schema.allOf!.push({\n        pattern: schema.pattern,\n      });\n      delete schema.pattern;\n    }\n\n    schema.allOf!.push({\n      pattern: stringifyRegExpWithFlags(regex, refs),\n      ...(message &&\n        refs.errorMessages && { errorMessage: { pattern: message } }),\n    });\n  } else {\n    schema.pattern = stringifyRegExpWithFlags(regex, refs);\n  }\n}\n\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex: RegExp, refs: Refs): string {\n  if (!refs.applyRegexFlags || !regex.flags) {\n    return regex.source;\n  }\n\n  // Currently handled flags\n  const flags = {\n    i: regex.flags.includes('i'), // Case-insensitive\n    m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters\n    s: regex.flags.includes('s'), // `.` matches newlines\n  };\n\n  // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n  const source = flags.i ? regex.source.toLowerCase() : regex.source;\n  let pattern = '';\n  let isEscaped = false;\n  let inCharGroup = false;\n  let inCharRange = false;\n\n  for (let i = 0; i < source.length; i++) {\n    if (isEscaped) {\n      pattern += source[i];\n      isEscaped = false;\n      continue;\n    }\n\n    if (flags.i) {\n      if (inCharGroup) {\n        if (source[i].match(/[a-z]/)) {\n          if (inCharRange) {\n            pattern += source[i];\n            pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n            inCharRange = false;\n          } else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {\n            pattern += source[i];\n            inCharRange = true;\n          } else {\n            pattern += `${source[i]}${source[i].toUpperCase()}`;\n          }\n          continue;\n        }\n      } else if (source[i].match(/[a-z]/)) {\n        pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n        continue;\n      }\n    }\n\n    if (flags.m) {\n      if (source[i] === '^') {\n        pattern += `(^|(?<=[\\r\\n]))`;\n        continue;\n      } else if (source[i] === '$') {\n        pattern += `($|(?=[\\r\\n]))`;\n        continue;\n      }\n    }\n\n    if (flags.s && source[i] === '.') {\n      pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n      continue;\n    }\n\n    pattern += source[i];\n    if (source[i] === '\\\\') {\n      isEscaped = true;\n    } else if (inCharGroup && source[i] === ']') {\n      inCharGroup = false;\n    } else if (!inCharGroup && source[i] === '[') {\n      inCharGroup = true;\n    }\n  }\n\n  try {\n    new RegExp(pattern);\n  } catch {\n    console.warn(\n      `Could not convert regex pattern at ${refs.currentPath.join(\n        '/',\n      )} to a flag-independent form! Falling back to the flag-ignorant source`,\n    );\n    return regex.source;\n  }\n\n  return pattern;\n}\n", "import { ZodMapDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\nimport { JsonSchema7RecordType, parseRecordDef } from './record';\n\nexport type JsonSchema7MapType = {\n  type: 'array';\n  maxItems: 125;\n  items: {\n    type: 'array';\n    items: [JsonSchema7Type, JsonSchema7Type];\n    minItems: 2;\n    maxItems: 2;\n  };\n};\n\nexport function parseMapDef(\n  def: ZodMapDef,\n  refs: Refs,\n): JsonSchema7MapType | JsonSchema7RecordType {\n  if (refs.mapStrategy === 'record') {\n    return parseRecordDef(def, refs);\n  }\n\n  const keys =\n    parseDef(def.keyType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items', 'items', '0'],\n    }) || parseAnyDef();\n  const values =\n    parseDef(def.valueType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items', 'items', '1'],\n    }) || parseAnyDef();\n  return {\n    type: 'array',\n    maxItems: 125,\n    items: {\n      type: 'array',\n      items: [keys, values],\n      minItems: 2,\n      maxItems: 2,\n    },\n  };\n}\n", "import { ZodNativeEnumDef } from 'zod/v3';\n\nexport type JsonSchema7NativeEnumType = {\n  type: 'string' | 'number' | ['string', 'number'];\n  enum: (string | number)[];\n};\n\nexport function parseNativeEnumDef(\n  def: ZodNativeEnumDef,\n): JsonSchema7NativeEnumType {\n  const object = def.values;\n  const actualKeys = Object.keys(def.values).filter((key: string) => {\n    return typeof object[object[key]] !== 'number';\n  });\n\n  const actualValues = actualKeys.map((key: string) => object[key]);\n\n  const parsedTypes = Array.from(\n    new Set(actualValues.map((values: string | number) => typeof values)),\n  );\n\n  return {\n    type:\n      parsedTypes.length === 1\n        ? parsedTypes[0] === 'string'\n          ? 'string'\n          : 'number'\n        : ['string', 'number'],\n    enum: actualValues,\n  };\n}\n", "import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7NeverType = {\n  not: JsonSchema7AnyType;\n};\n\nexport function parseNeverDef(): JsonSchema7NeverType | undefined {\n  return { not: parseAnyDef() };\n}\n", "export type JsonSchema7NullType = {\n  type: 'null';\n};\n\nexport function parseNullDef(): JsonSchema7NullType {\n  return {\n    type: 'null',\n  };\n}\n", "import {\n  ZodDiscriminatedUnionDef,\n  ZodLiteralDef,\n  ZodTypeAny,\n  ZodUnionDef,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport const primitiveMappings = {\n  ZodString: 'string',\n  ZodNumber: 'number',\n  ZodBigInt: 'integer',\n  ZodBoolean: 'boolean',\n  ZodNull: 'null',\n} as const;\ntype ZodPrimitive = keyof typeof primitiveMappings;\ntype JsonSchema7Primitive =\n  (typeof primitiveMappings)[keyof typeof primitiveMappings];\n\nexport type JsonSchema7UnionType =\n  | JsonSchema7PrimitiveUnionType\n  | JsonSchema7AnyOfType;\n\ntype JsonSchema7PrimitiveUnionType =\n  | {\n      type: JsonSchema7Primitive | JsonSchema7Primitive[];\n    }\n  | {\n      type: JsonSchema7Primitive | JsonSchema7Primitive[];\n      enum: (string | number | bigint | boolean | null)[];\n    };\n\ntype JsonSchema7AnyOfType = {\n  anyOf: JsonSchema7Type[];\n};\n\nexport function parseUnionDef(\n  def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n  refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined {\n  const options: readonly ZodTypeAny[] =\n    def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\n  // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n  if (\n    options.every(\n      x =>\n        x._def.typeName in primitiveMappings &&\n        (!x._def.checks || !x._def.checks.length),\n    )\n  ) {\n    // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n\n    const types = options.reduce((types: JsonSchema7Primitive[], x) => {\n      const type = primitiveMappings[x._def.typeName as ZodPrimitive]; //Can be safely casted due to row 43\n      return type && !types.includes(type) ? [...types, type] : types;\n    }, []);\n\n    return {\n      type: types.length > 1 ? types : types[0],\n    };\n  } else if (\n    options.every(x => x._def.typeName === 'ZodLiteral' && !x.description)\n  ) {\n    // all options literals\n\n    const types = options.reduce(\n      (acc: JsonSchema7Primitive[], x: { _def: ZodLiteralDef }) => {\n        const type = typeof x._def.value;\n        switch (type) {\n          case 'string':\n          case 'number':\n          case 'boolean':\n            return [...acc, type];\n          case 'bigint':\n            return [...acc, 'integer' as const];\n          case 'object':\n            if (x._def.value === null) return [...acc, 'null' as const];\n          case 'symbol':\n          case 'undefined':\n          case 'function':\n          default:\n            return acc;\n        }\n      },\n      [],\n    );\n\n    if (types.length === options.length) {\n      // all the literals are primitive, as far as null can be considered primitive\n\n      const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n      return {\n        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n        enum: options.reduce(\n          (acc, x) => {\n            return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n          },\n          [] as (string | number | bigint | boolean | null)[],\n        ),\n      };\n    }\n  } else if (options.every(x => x._def.typeName === 'ZodEnum')) {\n    return {\n      type: 'string',\n      enum: options.reduce(\n        (acc: string[], x) => [\n          ...acc,\n          ...x._def.values.filter((x: string) => !acc.includes(x)),\n        ],\n        [],\n      ),\n    };\n  }\n\n  return asAnyOf(def, refs);\n}\n\nconst asAnyOf = (\n  def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n  refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined => {\n  const anyOf = (\n    (def.options instanceof Map\n      ? Array.from(def.options.values())\n      : def.options) as any[]\n  )\n    .map((x, i) =>\n      parseDef(x._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'anyOf', `${i}`],\n      }),\n    )\n    .filter(\n      (x): x is JsonSchema7Type =>\n        !!x &&\n        (!refs.strictUnions ||\n          (typeof x === 'object' && Object.keys(x).length > 0)),\n    );\n\n  return anyOf.length ? { anyOf } : undefined;\n};\n", "import { ZodNullableDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7NullType } from './null';\nimport { primitiveMappings } from './union';\n\nexport type JsonSchema7NullableType =\n  | {\n      anyOf: [JsonSchema7Type, JsonSchema7NullType];\n    }\n  | {\n      type: [string, 'null'];\n    };\n\nexport function parseNullableDef(\n  def: ZodNullableDef,\n  refs: Refs,\n): JsonSchema7NullableType | undefined {\n  if (\n    ['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(\n      def.innerType._def.typeName,\n    ) &&\n    (!def.innerType._def.checks || !def.innerType._def.checks.length)\n  ) {\n    return {\n      type: [\n        primitiveMappings[\n          def.innerType._def.typeName as keyof typeof primitiveMappings\n        ],\n        'null',\n      ],\n    };\n  }\n\n  const base = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'anyOf', '0'],\n  });\n\n  return base && { anyOf: [base, { type: 'null' }] };\n}\n", "import { ZodNumberDef } from 'zod/v3';\n\nexport type JsonSchema7NumberType = {\n  type: 'number' | 'integer';\n  minimum?: number;\n  exclusiveMinimum?: number;\n  maximum?: number;\n  exclusiveMaximum?: number;\n  multipleOf?: number;\n};\n\nexport function parseNumberDef(def: ZodNumberDef): JsonSchema7NumberType {\n  const res: JsonSchema7NumberType = {\n    type: 'number',\n  };\n\n  if (!def.checks) return res;\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'int':\n        res.type = 'integer';\n        break;\n      case 'min':\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case 'max':\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n        break;\n      case 'multipleOf':\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n", "import { ZodObjectDef, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7ObjectType = {\n  type: 'object';\n  properties: Record<string, JsonSchema7Type>;\n  additionalProperties?: boolean | JsonSchema7Type;\n  required?: string[];\n};\n\nexport function parseObjectDef(def: ZodObjectDef, refs: Refs) {\n  const result: JsonSchema7ObjectType = {\n    type: 'object',\n    properties: {},\n  };\n\n  const required: string[] = [];\n\n  const shape = def.shape();\n\n  for (const propName in shape) {\n    let propDef = shape[propName];\n\n    if (propDef === undefined || propDef._def === undefined) {\n      continue;\n    }\n\n    const propOptional = safeIsOptional(propDef);\n\n    const parsedDef = parseDef(propDef._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'properties', propName],\n      propertyPath: [...refs.currentPath, 'properties', propName],\n    });\n\n    if (parsedDef === undefined) {\n      continue;\n    }\n\n    result.properties[propName] = parsedDef;\n\n    if (!propOptional) {\n      required.push(propName);\n    }\n  }\n\n  if (required.length) {\n    result.required = required;\n  }\n\n  const additionalProperties = decideAdditionalProperties(def, refs);\n\n  if (additionalProperties !== undefined) {\n    result.additionalProperties = additionalProperties;\n  }\n\n  return result;\n}\n\nfunction decideAdditionalProperties(def: ZodObjectDef, refs: Refs) {\n  if (def.catchall._def.typeName !== 'ZodNever') {\n    return parseDef(def.catchall._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'additionalProperties'],\n    });\n  }\n\n  switch (def.unknownKeys) {\n    case 'passthrough':\n      return refs.allowedAdditionalProperties;\n    case 'strict':\n      return refs.rejectedAdditionalProperties;\n    case 'strip':\n      return refs.removeAdditionalStrategy === 'strict'\n        ? refs.allowedAdditionalProperties\n        : refs.rejectedAdditionalProperties;\n  }\n}\n\nfunction safeIsOptional(schema: ZodTypeAny): boolean {\n  try {\n    return schema.isOptional();\n  } catch {\n    return true;\n  }\n}\n", "import { ZodOptionalDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport const parseOptionalDef = (\n  def: ZodOptionalDef,\n  refs: Refs,\n): JsonSchema7Type | undefined => {\n  if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n    return parseDef(def.innerType._def, refs);\n  }\n\n  const innerSchema = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'anyOf', '1'],\n  });\n\n  return innerSchema\n    ? { anyOf: [{ not: parseAnyDef() }, innerSchema] }\n    : parseAnyDef();\n};\n", "import { ZodPipelineDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7AllOfType } from './intersection';\n\nexport const parsePipelineDef = (\n  def: ZodPipelineDef<any, any>,\n  refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined => {\n  if (refs.pipeStrategy === 'input') {\n    return parseDef(def.in._def, refs);\n  } else if (refs.pipeStrategy === 'output') {\n    return parseDef(def.out._def, refs);\n  }\n\n  const a = parseDef(def.in._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'allOf', '0'],\n  });\n  const b = parseDef(def.out._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],\n  });\n\n  return {\n    allOf: [a, b].filter((x): x is JsonSchema7Type => x !== undefined),\n  };\n};\n", "import { ZodPromiseDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport function parsePromiseDef(\n  def: ZodPromiseDef,\n  refs: Refs,\n): JsonSchema7Type | undefined {\n  return parseDef(def.type._def, refs);\n}\n", "import { ZodSetDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7SetType = {\n  type: 'array';\n  uniqueItems: true;\n  items?: JsonSchema7Type;\n  minItems?: number;\n  maxItems?: number;\n};\n\nexport function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType {\n  const items = parseDef(def.valueType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'items'],\n  });\n\n  const schema: JsonSchema7SetType = {\n    type: 'array',\n    uniqueItems: true,\n    items,\n  };\n\n  if (def.minSize) {\n    schema.minItems = def.minSize.value;\n  }\n\n  if (def.maxSize) {\n    schema.maxItems = def.maxSize.value;\n  }\n\n  return schema;\n}\n", "import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7TupleType = {\n  type: 'array';\n  minItems: number;\n  items: JsonSchema7Type[];\n} & (\n  | {\n      maxItems: number;\n    }\n  | {\n      additionalItems?: JsonSchema7Type;\n    }\n);\n\nexport function parseTupleDef(\n  def: ZodTupleDef<ZodTupleItems | [], ZodTypeAny | null>,\n  refs: Refs,\n): JsonSchema7TupleType {\n  if (def.rest) {\n    return {\n      type: 'array',\n      minItems: def.items.length,\n      items: def.items\n        .map((x, i) =>\n          parseDef(x._def, {\n            ...refs,\n            currentPath: [...refs.currentPath, 'items', `${i}`],\n          }),\n        )\n        .reduce(\n          (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n          [],\n        ),\n      additionalItems: parseDef(def.rest._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'additionalItems'],\n      }),\n    };\n  } else {\n    return {\n      type: 'array',\n      minItems: def.items.length,\n      maxItems: def.items.length,\n      items: def.items\n        .map((x, i) =>\n          parseDef(x._def, {\n            ...refs,\n            currentPath: [...refs.currentPath, 'items', `${i}`],\n          }),\n        )\n        .reduce(\n          (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n          [],\n        ),\n    };\n  }\n}\n", "import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7UndefinedType = {\n  not: JsonSchema7AnyType;\n};\n\nexport function parseUndefinedDef(): JsonSchema7UndefinedType {\n  return {\n    not: parseAnyDef(),\n  };\n}\n", "import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7UnknownType = JsonSchema7AnyType;\n\nexport function parseUnknownDef(): JsonSchema7UnknownType {\n  return parseAnyDef();\n}\n", "import { ZodReadonlyDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport const parseReadonlyDef = (def: ZodReadonlyDef<any>, refs: Refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n", "export const getRelativePath = (pathA: string[], pathB: string[]) => {\n  let i = 0;\n  for (; i < pathA.length && i < pathB.length; i++) {\n    if (pathA[i] !== pathB[i]) break;\n  }\n  return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');\n};\n", "import { ZodTypeDef } from 'zod/v3';\nimport { Refs, Seen } from './refs';\nimport { ignoreOverride } from './options';\nimport { JsonSchema7Type } from './parse-types';\nimport { selectParser } from './select-parser';\nimport { getRelativePath } from './get-relative-path';\nimport { parseAnyDef } from './parsers/any';\n\nexport function parseDef(\n  def: ZodTypeDef,\n  refs: Refs,\n  forceResolution = false, // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61.\n): JsonSchema7Type | undefined {\n  const seenItem = refs.seen.get(def);\n\n  if (refs.override) {\n    const overrideResult = refs.override?.(\n      def,\n      refs,\n      seenItem,\n      forceResolution,\n    );\n\n    if (overrideResult !== ignoreOverride) {\n      return overrideResult;\n    }\n  }\n\n  if (seenItem && !forceResolution) {\n    const seenSchema = get$ref(seenItem, refs);\n\n    if (seenSchema !== undefined) {\n      return seenSchema;\n    }\n  }\n\n  const newItem: Seen = { def, path: refs.currentPath, jsonSchema: undefined };\n\n  refs.seen.set(def, newItem);\n\n  const jsonSchemaOrGetter = selectParser(def, (def as any).typeName, refs);\n\n  // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n  const jsonSchema =\n    typeof jsonSchemaOrGetter === 'function'\n      ? parseDef(jsonSchemaOrGetter(), refs)\n      : jsonSchemaOrGetter;\n\n  if (jsonSchema) {\n    addMeta(def, refs, jsonSchema);\n  }\n\n  if (refs.postProcess) {\n    const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n\n    newItem.jsonSchema = jsonSchema;\n\n    return postProcessResult;\n  }\n\n  newItem.jsonSchema = jsonSchema;\n\n  return jsonSchema;\n}\n\nconst get$ref = (\n  item: Seen,\n  refs: Refs,\n):\n  | {\n      $ref: string;\n    }\n  | {}\n  | undefined => {\n  switch (refs.$refStrategy) {\n    case 'root':\n      return { $ref: item.path.join('/') };\n    case 'relative':\n      return { $ref: getRelativePath(refs.currentPath, item.path) };\n    case 'none':\n    case 'seen': {\n      if (\n        item.path.length < refs.currentPath.length &&\n        item.path.every((value, index) => refs.currentPath[index] === value)\n      ) {\n        console.warn(\n          `Recursive reference detected at ${refs.currentPath.join(\n            '/',\n          )}! Defaulting to any`,\n        );\n\n        return parseAnyDef();\n      }\n\n      return refs.$refStrategy === 'seen' ? parseAnyDef() : undefined;\n    }\n  }\n};\n\nconst addMeta = (\n  def: ZodTypeDef,\n  refs: Refs,\n  jsonSchema: JsonSchema7Type,\n): JsonSchema7Type => {\n  if (def.description) {\n    jsonSchema.description = def.description;\n  }\n  return jsonSchema;\n};\n", "import { ZodTypeDef } from 'zod/v3';\nimport { getDefaultOptions, Options } from './options';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type Refs = {\n  seen: Map<ZodTypeDef, Seen>;\n  currentPath: string[];\n  propertyPath: string[] | undefined;\n} & Options;\n\nexport type Seen = {\n  def: ZodTypeDef;\n  path: string[];\n  jsonSchema: JsonSchema7Type | undefined;\n};\n\nexport const getRefs = (options?: string | Partial<Options>): Refs => {\n  const _options = getDefaultOptions(options);\n  const currentPath =\n    _options.name !== undefined\n      ? [..._options.basePath, _options.definitionPath, _options.name]\n      : _options.basePath;\n  return {\n    ..._options,\n    currentPath: currentPath,\n    propertyPath: undefined,\n    seen: new Map(\n      Object.entries(_options.definitions).map(([name, def]) => [\n        def._def,\n        {\n          def: def._def,\n          path: [..._options.basePath, _options.definitionPath, name],\n          // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n          jsonSchema: undefined,\n        },\n      ]),\n    ),\n  };\n};\n", "import { ZodSchema } from 'zod/v3';\nimport { Options } from './options';\nimport { parseDef } from './parse-def';\nimport { JsonSchema7Type } from './parse-types';\nimport { getRefs } from './refs';\nimport { parseAnyDef } from './parsers/any';\n\nconst zod3ToJsonSchema = (\n  schema: ZodSchema<any>,\n  options?: Partial<Options> | string,\n): JsonSchema7Type & {\n  $schema?: string;\n  definitions?: {\n    [key: string]: JsonSchema7Type;\n  };\n} => {\n  const refs = getRefs(options);\n\n  let definitions =\n    typeof options === 'object' && options.definitions\n      ? Object.entries(options.definitions).reduce(\n          (acc: { [key: string]: JsonSchema7Type }, [name, schema]) => ({\n            ...acc,\n            [name]:\n              parseDef(\n                schema._def,\n                {\n                  ...refs,\n                  currentPath: [...refs.basePath, refs.definitionPath, name],\n                },\n                true,\n              ) ?? parseAnyDef(),\n          }),\n          {},\n        )\n      : undefined;\n\n  const name =\n    typeof options === 'string'\n      ? options\n      : options?.nameStrategy === 'title'\n        ? undefined\n        : options?.name;\n\n  const main =\n    parseDef(\n      schema._def,\n      name === undefined\n        ? refs\n        : {\n            ...refs,\n            currentPath: [...refs.basePath, refs.definitionPath, name],\n          },\n      false,\n    ) ?? (parseAnyDef() as JsonSchema7Type);\n\n  const title =\n    typeof options === 'object' &&\n    options.name !== undefined &&\n    options.nameStrategy === 'title'\n      ? options.name\n      : undefined;\n\n  if (title !== undefined) {\n    main.title = title;\n  }\n\n  const combined: ReturnType<typeof zod3ToJsonSchema> =\n    name === undefined\n      ? definitions\n        ? {\n            ...main,\n            [refs.definitionPath]: definitions,\n          }\n        : main\n      : {\n          $ref: [\n            ...(refs.$refStrategy === 'relative' ? [] : refs.basePath),\n            refs.definitionPath,\n            name,\n          ].join('/'),\n          [refs.definitionPath]: {\n            ...definitions,\n            [name]: main,\n          },\n        };\n\n  combined.$schema = 'http://json-schema.org/draft-07/schema#';\n\n  return combined;\n};\n\nexport { zod3ToJsonSchema };\n", "import {\n  EventSourceMessage,\n  EventSourceParserStream,\n} from 'eventsource-parser/stream';\nimport { ParseResult, safeParseJSON } from './parse-json';\nimport { FlexibleSchema } from './schema';\n\n/**\n * Parses a JSON event stream into a stream of parsed JSON objects.\n */\nexport function parseJsonEventStream<T>({\n  stream,\n  schema,\n}: {\n  stream: ReadableStream<Uint8Array>;\n  schema: FlexibleSchema<T>;\n}): ReadableStream<ParseResult<T>> {\n  return stream\n    .pipeThrough(new TextDecoderStream())\n    .pipeThrough(new EventSourceParserStream())\n    .pipeThrough(\n      new TransformStream<EventSourceMessage, ParseResult<T>>({\n        async transform({ data }, controller) {\n          // ignore the 'DONE' event that e.g. OpenAI sends:\n          if (data === '[DONE]') {\n            return;\n          }\n\n          controller.enqueue(await safeParseJSON({ text: data, schema }));\n        },\n      }),\n    );\n}\n", "import { InvalidArgumentError } from '@ai-sdk/provider';\nimport { safeValidateTypes } from './validate-types';\nimport { FlexibleSchema } from './schema';\n\nexport async function parseProviderOptions<OPTIONS>({\n  provider,\n  providerOptions,\n  schema,\n}: {\n  provider: string;\n  providerOptions: Record<string, unknown> | undefined;\n  schema: FlexibleSchema<OPTIONS>;\n}): Promise<OPTIONS | undefined> {\n  if (providerOptions?.[provider] == null) {\n    return undefined;\n  }\n\n  const parsedProviderOptions = await safeValidateTypes<OPTIONS | undefined>({\n    value: providerOptions[provider],\n    schema,\n  });\n\n  if (!parsedProviderOptions.success) {\n    throw new InvalidArgumentError({\n      argument: 'providerOptions',\n      message: `invalid ${provider} provider options`,\n      cause: parsedProviderOptions.error,\n    });\n  }\n\n  return parsedProviderOptions.value;\n}\n", "import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport { ResponseHandler } from './response-handler';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\nimport { VERSION } from './version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const postJsonToApi = async <T>({\n  url,\n  headers,\n  body,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  body: unknown;\n  failedResponseHandler: ResponseHandler<APICallError>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) =>\n  postToApi({\n    url,\n    headers: {\n      'Content-Type': 'application/json',\n      ...headers,\n    },\n    body: {\n      content: JSON.stringify(body),\n      values: body,\n    },\n    failedResponseHandler,\n    successfulResponseHandler,\n    abortSignal,\n    fetch,\n  });\n\nexport const postFormDataToApi = async <T>({\n  url,\n  headers,\n  formData,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  formData: FormData;\n  failedResponseHandler: ResponseHandler<APICallError>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) =>\n  postToApi({\n    url,\n    headers,\n    body: {\n      content: formData,\n      values: Object.fromEntries((formData as any).entries()),\n    },\n    failedResponseHandler,\n    successfulResponseHandler,\n    abortSignal,\n    fetch,\n  });\n\nexport const postToApi = async <T>({\n  url,\n  headers = {},\n  body,\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  body: {\n    content: string | FormData | Uint8Array;\n    values: unknown;\n  };\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  try {\n    const response = await fetch(url, {\n      method: 'POST',\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      body: body.content,\n      signal: abortSignal,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: body.values,\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: body.values,\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: body.values,\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: body.values,\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: body.values });\n  }\n};\n", "import { JSONValue } from '@ai-sdk/provider';\nimport { FlexibleSchema } from '../schema';\nimport { ToolResultOutput } from './content-part';\nimport { ModelMessage } from './model-message';\nimport { ProviderOptions } from './provider-options';\n\n/**\n * Additional options that are sent into each tool call.\n */\nexport interface ToolExecutionOptions {\n  /**\n   * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n   */\n  toolCallId: string;\n\n  /**\n   * Messages that were sent to the language model to initiate the response that contained the tool call.\n   * The messages **do not** include the system prompt nor the assistant response that contained the tool call.\n   */\n  messages: ModelMessage[];\n\n  /**\n   * An optional abort signal that indicates that the overall operation should be aborted.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * User-defined context.\n   *\n   * Treat the context object as immutable inside tools.\n   * Mutating the context object can lead to race conditions and unexpected results\n   * when tools are called in parallel.\n   *\n   * If you need to mutate the context, analyze the tool calls and results\n   * in `prepareStep` and update it there.\n   *\n   * Experimental (can break in patch releases).\n   */\n  experimental_context?: unknown;\n}\n\n/**\n * Function that is called to determine if the tool needs approval before it can be executed.\n */\nexport type ToolNeedsApprovalFunction<INPUT> = (\n  input: INPUT,\n  options: {\n    /**\n     * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n     */\n    toolCallId: string;\n\n    /**\n     * Messages that were sent to the language model to initiate the response that contained the tool call.\n     * The messages **do not** include the system prompt nor the assistant response that contained the tool call.\n     */\n    messages: ModelMessage[];\n\n    /**\n     * Additional context.\n     *\n     * Experimental (can break in patch releases).\n     */\n    experimental_context?: unknown;\n  },\n) => boolean | PromiseLike<boolean>;\n\nexport type ToolExecuteFunction<INPUT, OUTPUT> = (\n  input: INPUT,\n  options: ToolExecutionOptions,\n) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;\n\n// 0 extends 1 & N checks for any\n// [N] extends [never] checks for never\ntype NeverOptional<N, T> = 0 extends 1 & N\n  ? Partial<T>\n  : [N] extends [never]\n    ? Partial<Record<keyof T, undefined>>\n    : T;\n\ntype ToolOutputProperties<INPUT, OUTPUT> = NeverOptional<\n  OUTPUT,\n  | {\n      /**\n       * An async function that is called with the arguments from the tool call and produces a result.\n       * If not provided, the tool will not be executed automatically.\n       *\n       * @args is the input of the tool call.\n       * @options.abortSignal is a signal that can be used to abort the tool call.\n       */\n      execute: ToolExecuteFunction<INPUT, OUTPUT>;\n\n      outputSchema?: FlexibleSchema<OUTPUT>;\n    }\n  | {\n      outputSchema: FlexibleSchema<OUTPUT>;\n\n      execute?: never;\n    }\n>;\n\n/**\n * A tool contains the description and the schema of the input that the tool expects.\n * This enables the language model to generate the input.\n *\n * The tool can also contain an optional execute function for the actual execution function of the tool.\n */\nexport type Tool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n> = {\n  /**\n   * An optional description of what the tool does.\n   * Will be used by the language model to decide whether to use the tool.\n   * Not used for provider-defined tools.\n   */\n  description?: string;\n\n  /**\n   * An optional title of the tool.\n   */\n  title?: string;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * The schema of the input that the tool expects.\n   * The language model will use this to generate the input.\n   * It is also used to validate the output of the language model.\n   *\n   * You can use descriptions on the schema properties to make the input understandable for the language model.\n   */\n  inputSchema: FlexibleSchema<INPUT>;\n\n  /**\n   * An optional list of input examples that show the language\n   * model what the input should look like.\n   */\n  inputExamples?: Array<{ input: NoInfer<INPUT> }>;\n\n  /**\n   * Whether the tool needs approval before it can be executed.\n   */\n  needsApproval?:\n    | boolean\n    | ToolNeedsApprovalFunction<[INPUT] extends [never] ? unknown : INPUT>;\n\n  /**\n   * Strict mode setting for the tool.\n   *\n   * Providers that support strict mode will use this setting to determine\n   * how the input should be generated. Strict mode will always produce\n   * valid inputs, but it might limit what input schemas are supported.\n   */\n  strict?: boolean;\n\n  /**\n   * Optional function that is called when the argument streaming starts.\n   * Only called when the tool is used in a streaming context.\n   */\n  onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;\n\n  /**\n   * Optional function that is called when an argument streaming delta is available.\n   * Only called when the tool is used in a streaming context.\n   */\n  onInputDelta?: (\n    options: { inputTextDelta: string } & ToolExecutionOptions,\n  ) => void | PromiseLike<void>;\n\n  /**\n   * Optional function that is called when a tool call can be started,\n   * even if the execute function is not provided.\n   */\n  onInputAvailable?: (\n    options: {\n      input: [INPUT] extends [never] ? unknown : INPUT;\n    } & ToolExecutionOptions,\n  ) => void | PromiseLike<void>;\n} & ToolOutputProperties<INPUT, OUTPUT> & {\n    /**\n     * Optional conversion function that maps the tool result to an output that can be used by the language model.\n     *\n     * If not provided, the tool result will be sent as a JSON object.\n     */\n    toModelOutput?: (options: {\n      /**\n       * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n       */\n      toolCallId: string;\n\n      /**\n       * The input of the tool call.\n       */\n      input: [INPUT] extends [never] ? unknown : INPUT;\n\n      /**\n       * The output of the tool call.\n       */\n      output: 0 extends 1 & OUTPUT\n        ? any\n        : [OUTPUT] extends [never]\n          ? any\n          : NoInfer<OUTPUT>;\n    }) => ToolResultOutput | PromiseLike<ToolResultOutput>;\n  } & (\n    | {\n        /**\n         * Tool with user-defined input and output schemas.\n         */\n        type?: undefined | 'function';\n      }\n    | {\n        /**\n         * Tool that is defined at runtime (e.g. an MCP tool).\n         * The types of input and output are not known at development time.\n         */\n        type: 'dynamic';\n      }\n    | {\n        /**\n         * Tool with provider-defined input and output schemas.\n         */\n        type: 'provider';\n\n        /**\n         * The ID of the tool. Must follow the format `<provider-name>.<unique-tool-name>`.\n         */\n        id: `${string}.${string}`;\n\n        /**\n         * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.\n         */\n        args: Record<string, unknown>;\n\n        /**\n         * Whether this provider-executed tool supports deferred results.\n         *\n         * When true, the tool result may not be returned in the same turn as the\n         * tool call (e.g., when using programmatic tool calling where a server tool\n         * triggers a client-executed tool, and the server tool's result is deferred\n         * until the client tool is resolved).\n         *\n         * This flag allows the AI SDK to handle tool results that arrive without\n         * a matching tool call in the current response.\n         *\n         * @default false\n         */\n        supportsDeferredResults?: boolean;\n      }\n  );\n\n/**\n * Infer the input type of a tool.\n */\nexport type InferToolInput<TOOL extends Tool> =\n  TOOL extends Tool<infer INPUT, any> ? INPUT : never;\n\n/**\n * Infer the output type of a tool.\n */\nexport type InferToolOutput<TOOL extends Tool> =\n  TOOL extends Tool<any, infer OUTPUT> ? OUTPUT : never;\n\n/**\n * Helper function for inferring the execute args of a tool.\n */\n// Note: overload order is important for auto-completion\nexport function tool<INPUT, OUTPUT>(\n  tool: Tool<INPUT, OUTPUT>,\n): Tool<INPUT, OUTPUT>;\nexport function tool<INPUT>(tool: Tool<INPUT, never>): Tool<INPUT, never>;\nexport function tool<OUTPUT>(tool: Tool<never, OUTPUT>): Tool<never, OUTPUT>;\nexport function tool(tool: Tool<never, never>): Tool<never, never>;\nexport function tool(tool: any): any {\n  return tool;\n}\n\n/**\n * Defines a dynamic tool.\n */\nexport function dynamicTool(tool: {\n  description?: string;\n  title?: string;\n  providerOptions?: ProviderOptions;\n  inputSchema: FlexibleSchema<unknown>;\n  execute: ToolExecuteFunction<unknown, unknown>;\n\n  /**\n   * Optional conversion function that maps the tool result to an output that can be used by the language model.\n   *\n   * If not provided, the tool result will be sent as a JSON object.\n   */\n  toModelOutput?: (options: {\n    /**\n     * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n     */\n    toolCallId: string;\n\n    /**\n     * The input of the tool call.\n     */\n    input: unknown;\n\n    /**\n     * The output of the tool call.\n     */\n    output: unknown;\n  }) => ToolResultOutput | PromiseLike<ToolResultOutput>;\n\n  /**\n   * Whether the tool needs approval before it can be executed.\n   */\n  needsApproval?: boolean | ToolNeedsApprovalFunction<unknown>;\n}): Tool<unknown, unknown> & {\n  type: 'dynamic';\n} {\n  return { ...tool, type: 'dynamic' };\n}\n", "import { tool, Tool, ToolExecuteFunction } from './types/tool';\nimport { FlexibleSchema } from './schema';\n\nexport type ProviderToolFactory<INPUT, ARGS extends object> = <OUTPUT>(\n  options: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  },\n) => Tool<INPUT, OUTPUT>;\n\nexport function createProviderToolFactory<INPUT, ARGS extends object>({\n  id,\n  inputSchema,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n}): ProviderToolFactory<INPUT, ARGS> {\n  return <OUTPUT>({\n    execute,\n    outputSchema,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    outputSchema?: FlexibleSchema<OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  }): Tool<INPUT, OUTPUT> =>\n    tool({\n      type: 'provider',\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      execute,\n      needsApproval,\n      toModelOutput,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n    });\n}\n\nexport type ProviderToolFactoryWithOutputSchema<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n> = (\n  options: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  },\n) => Tool<INPUT, OUTPUT>;\n\nexport function createProviderToolFactoryWithOutputSchema<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n>({\n  id,\n  inputSchema,\n  outputSchema,\n  supportsDeferredResults,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n  outputSchema: FlexibleSchema<OUTPUT>;\n  /**\n   * Whether this provider-executed tool supports deferred results.\n   *\n   * When true, the tool result may not be returned in the same turn as the\n   * tool call (e.g., when using programmatic tool calling where a server tool\n   * triggers a client-executed tool, and the server tool's result is deferred\n   * until the client tool is resolved).\n   *\n   * @default false\n   */\n  supportsDeferredResults?: boolean;\n}): ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS> {\n  return ({\n    execute,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  }): Tool<INPUT, OUTPUT> =>\n    tool({\n      type: 'provider',\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      execute,\n      needsApproval,\n      toModelOutput,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n      supportsDeferredResults,\n    });\n}\n", "/**\n * Removes entries from a record where the value is null or undefined.\n * @param record - The input object whose entries may be null or undefined.\n * @returns A new object containing only entries with non-null and non-undefined values.\n */\nexport function removeUndefinedEntries<T>(\n  record: Record<string, T | undefined>,\n): Record<string, T> {\n  return Object.fromEntries(\n    Object.entries(record).filter(([_key, value]) => value != null),\n  ) as Record<string, T>;\n}\n", "import { MaybePromiseLike } from './maybe-promise-like';\n\nexport type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);\n\n/**\n * Resolves a value that could be a raw value, a Promise, a function returning a value,\n * or a function returning a Promise.\n */\nexport async function resolve<T>(value: Resolvable<T>): Promise<T> {\n  // If it's a function, call it to get the value/promise\n  if (typeof value === 'function') {\n    value = (value as Function)();\n  }\n\n  // Otherwise just resolve whatever we got (value or promise)\n  return Promise.resolve(value as T);\n}\n", "import { APICallError, EmptyResponseBodyError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { parseJSON, ParseResult, safeParseJSON } from './parse-json';\nimport { parseJsonEventStream } from './parse-json-event-stream';\nimport { FlexibleSchema } from './schema';\n\nexport type ResponseHandler<RETURN_TYPE> = (options: {\n  url: string;\n  requestBodyValues: unknown;\n  response: Response;\n}) => PromiseLike<{\n  value: RETURN_TYPE;\n  rawValue?: unknown;\n  responseHeaders?: Record<string, string>;\n}>;\n\nexport const createJsonErrorResponseHandler =\n  <T>({\n    errorSchema,\n    errorToMessage,\n    isRetryable,\n  }: {\n    errorSchema: FlexibleSchema<T>;\n    errorToMessage: (error: T) => string;\n    isRetryable?: (response: Response, error?: T) => boolean;\n  }): ResponseHandler<APICallError> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseBody = await response.text();\n    const responseHeaders = extractResponseHeaders(response);\n\n    // Some providers return an empty response body for some errors:\n    if (responseBody.trim() === '') {\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: response.statusText,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          isRetryable: isRetryable?.(response),\n        }),\n      };\n    }\n\n    // resilient parsing in case the response is not JSON or does not match the schema:\n    try {\n      const parsedError = await parseJSON({\n        text: responseBody,\n        schema: errorSchema,\n      });\n\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: errorToMessage(parsedError),\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          data: parsedError,\n          isRetryable: isRetryable?.(response, parsedError),\n        }),\n      };\n    } catch (parseError) {\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: response.statusText,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          isRetryable: isRetryable?.(response),\n        }),\n      };\n    }\n  };\n\nexport const createEventSourceResponseHandler =\n  <T>(\n    chunkSchema: FlexibleSchema<T>,\n  ): ResponseHandler<ReadableStream<ParseResult<T>>> =>\n  async ({ response }: { response: Response }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (response.body == null) {\n      throw new EmptyResponseBodyError({});\n    }\n\n    return {\n      responseHeaders,\n      value: parseJsonEventStream({\n        stream: response.body,\n        schema: chunkSchema,\n      }),\n    };\n  };\n\nexport const createJsonResponseHandler =\n  <T>(responseSchema: FlexibleSchema<T>): ResponseHandler<T> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseBody = await response.text();\n\n    const parsedResult = await safeParseJSON({\n      text: responseBody,\n      schema: responseSchema,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!parsedResult.success) {\n      throw new APICallError({\n        message: 'Invalid JSON response',\n        cause: parsedResult.error,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n        url,\n        requestBodyValues,\n      });\n    }\n\n    return {\n      responseHeaders,\n      value: parsedResult.value,\n      rawValue: parsedResult.rawValue,\n    };\n  };\n\nexport const createBinaryResponseHandler =\n  (): ResponseHandler<Uint8Array> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.body) {\n      throw new APICallError({\n        message: 'Response body is empty',\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody: undefined,\n      });\n    }\n\n    try {\n      const buffer = await response.arrayBuffer();\n      return {\n        responseHeaders,\n        value: new Uint8Array(buffer),\n      };\n    } catch (error) {\n      throw new APICallError({\n        message: 'Failed to read response as array buffer',\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody: undefined,\n        cause: error,\n      });\n    }\n  };\n\nexport const createStatusCodeErrorResponseHandler =\n  (): ResponseHandler<APICallError> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n    const responseBody = await response.text();\n\n    return {\n      responseHeaders,\n      value: new APICallError({\n        message: response.statusText,\n        url,\n        requestBodyValues: requestBodyValues as Record<string, unknown>,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n      }),\n    };\n  };\n", "/**\n * Strips file extension segments from a filename.\n *\n * Examples:\n * - \"report.pdf\" -> \"report\"\n * - \"archive.tar.gz\" -> \"archive\"\n * - \"filename\" -> \"filename\"\n */\nexport function stripFileExtension(filename: string): string {\n  const firstDotIndex = filename.indexOf('.');\n\n  return firstDotIndex === -1 ? filename : filename.slice(0, firstDotIndex);\n}\n", "export function withoutTrailingSlash(url: string | undefined) {\n  return url?.replace(/\\/$/, '');\n}\n", "export function isAsyncIterable<T = any>(obj: any): obj is AsyncIterable<T> {\n  return obj != null && typeof obj[Symbol.asyncIterator] === 'function';\n}\n", "import { isAsyncIterable } from '../is-async-iterable';\nimport { ToolExecutionOptions, ToolExecuteFunction } from './tool';\n\nexport async function* executeTool<INPUT, OUTPUT>({\n  execute,\n  input,\n  options,\n}: {\n  execute: ToolExecuteFunction<INPUT, OUTPUT>;\n  input: INPUT;\n  options: ToolExecutionOptions;\n}): AsyncGenerator<\n  { type: 'preliminary'; output: OUTPUT } | { type: 'final'; output: OUTPUT }\n> {\n  const result = execute(input, options);\n\n  if (isAsyncIterable(result)) {\n    let lastOutput: OUTPUT | undefined;\n    for await (const output of result) {\n      lastOutput = output;\n      yield { type: 'preliminary', output };\n    }\n    yield { type: 'final', output: lastOutput! };\n  } else {\n    yield { type: 'final', output: await result };\n  }\n}\n", "export * from './combine-headers';\nexport { convertAsyncIteratorToReadableStream } from './convert-async-iterator-to-readable-stream';\nexport {\n  createToolNameMapping,\n  type ToolNameMapping,\n} from './create-tool-name-mapping';\nexport * from './delay';\nexport { DelayedPromise } from './delayed-promise';\nexport * from './extract-response-headers';\nexport { convertImageModelFileToDataUri } from './convert-image-model-file-to-data-uri';\nexport { convertToFormData } from './convert-to-form-data';\nexport { downloadBlob } from './download-blob';\nexport { DownloadError } from './download-error';\nexport {\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n} from './read-response-with-size-limit';\nexport * from './fetch-function';\nexport { createIdGenerator, generateId, type IdGenerator } from './generate-id';\nexport * from './get-error-message';\nexport * from './get-from-api';\nexport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nexport { injectJsonInstructionIntoMessages } from './inject-json-instruction';\nexport * from './is-abort-error';\nexport { isNonNullable } from './is-non-nullable';\nexport { isUrlSupported } from './is-url-supported';\nexport * from './load-api-key';\nexport { loadOptionalSetting } from './load-optional-setting';\nexport { loadSetting } from './load-setting';\nexport { type MaybePromiseLike } from './maybe-promise-like';\nexport { mediaTypeToExtension } from './media-type-to-extension';\nexport { normalizeHeaders } from './normalize-headers';\nexport * from './parse-json';\nexport { parseJsonEventStream } from './parse-json-event-stream';\nexport { parseProviderOptions } from './parse-provider-options';\nexport * from './post-to-api';\nexport {\n  createProviderToolFactory,\n  createProviderToolFactoryWithOutputSchema,\n  type ProviderToolFactory,\n  type ProviderToolFactoryWithOutputSchema,\n} from './provider-tool-factory';\nexport * from './remove-undefined-entries';\nexport * from './resolve';\nexport * from './response-handler';\nexport {\n  asSchema,\n  jsonSchema,\n  lazySchema,\n  zodSchema,\n  type FlexibleSchema,\n  type InferSchema,\n  type LazySchema,\n  type Schema,\n  type ValidationResult,\n} from './schema';\nexport { stripFileExtension } from './strip-file-extension';\nexport * from './uint8-utils';\nexport { validateDownloadUrl } from './validate-download-url';\nexport * from './validate-types';\nexport { VERSION } from './version';\nexport { withUserAgentSuffix } from './with-user-agent-suffix';\nexport * from './without-trailing-slash';\n\n// folder re-exports\nexport * from './types';\n\n// external re-exports\nexport type * from '@standard-schema/spec';\nexport {\n  EventSourceParserStream,\n  type EventSourceMessage,\n} from 'eventsource-parser/stream';\n", "import {\n  EmbeddingModelV3,\n  ImageModelV3,\n  LanguageModelV3,\n  ProviderV3,\n  SpeechModelV3,\n  TranscriptionModelV3,\n} from '@ai-sdk/provider';\nimport {\n  FetchFunction,\n  loadApiKey,\n  loadOptionalSetting,\n  withoutTrailingSlash,\n  withUserAgentSuffix,\n} from '@ai-sdk/provider-utils';\nimport { OpenAIChatLanguageModel } from './chat/openai-chat-language-model';\nimport { OpenAIChatModelId } from './chat/openai-chat-options';\nimport { OpenAICompletionLanguageModel } from './completion/openai-completion-language-model';\nimport { OpenAICompletionModelId } from './completion/openai-completion-options';\nimport { OpenAIEmbeddingModel } from './embedding/openai-embedding-model';\nimport { OpenAIEmbeddingModelId } from './embedding/openai-embedding-options';\nimport { OpenAIImageModel } from './image/openai-image-model';\nimport { OpenAIImageModelId } from './image/openai-image-options';\nimport { openaiTools } from './openai-tools';\nimport { OpenAIResponsesLanguageModel } from './responses/openai-responses-language-model';\nimport { OpenAIResponsesModelId } from './responses/openai-responses-options';\nimport { OpenAISpeechModel } from './speech/openai-speech-model';\nimport { OpenAISpeechModelId } from './speech/openai-speech-options';\nimport { OpenAITranscriptionModel } from './transcription/openai-transcription-model';\nimport { OpenAITranscriptionModelId } from './transcription/openai-transcription-options';\nimport { VERSION } from './version';\n\nexport interface OpenAIProvider extends ProviderV3 {\n  (modelId: OpenAIResponsesModelId): LanguageModelV3;\n\n  /**\n   * Creates an OpenAI model for text generation.\n   */\n  languageModel(modelId: OpenAIResponsesModelId): LanguageModelV3;\n\n  /**\n   * Creates an OpenAI chat model for text generation.\n   */\n  chat(modelId: OpenAIChatModelId): LanguageModelV3;\n\n  /**\n   * Creates an OpenAI responses API model for text generation.\n   */\n  responses(modelId: OpenAIResponsesModelId): LanguageModelV3;\n\n  /**\n   * Creates an OpenAI completion model for text generation.\n   */\n  completion(modelId: OpenAICompletionModelId): LanguageModelV3;\n\n  /**\n   * Creates a model for text embeddings.\n   */\n  embedding(modelId: OpenAIEmbeddingModelId): EmbeddingModelV3;\n\n  /**\n   * Creates a model for text embeddings.\n   */\n  embeddingModel(modelId: OpenAIEmbeddingModelId): EmbeddingModelV3;\n\n  /**\n   * @deprecated Use `embedding` instead.\n   */\n  textEmbedding(modelId: OpenAIEmbeddingModelId): EmbeddingModelV3;\n\n  /**\n   * @deprecated Use `embeddingModel` instead.\n   */\n  textEmbeddingModel(modelId: OpenAIEmbeddingModelId): EmbeddingModelV3;\n\n  /**\n   * Creates a model for image generation.\n   */\n  image(modelId: OpenAIImageModelId): ImageModelV3;\n\n  /**\n   * Creates a model for image generation.\n   */\n  imageModel(modelId: OpenAIImageModelId): ImageModelV3;\n\n  /**\n   * Creates a model for transcription.\n   */\n  transcription(modelId: OpenAITranscriptionModelId): TranscriptionModelV3;\n\n  /**\n   * Creates a model for speech generation.\n   */\n  speech(modelId: OpenAISpeechModelId): SpeechModelV3;\n\n  /**\n   * OpenAI-specific tools.\n   */\n  tools: typeof openaiTools;\n}\n\nexport interface OpenAIProviderSettings {\n  /**\n   * Base URL for the OpenAI API calls.\n   */\n  baseURL?: string;\n\n  /**\n   * API key for authenticating requests.\n   */\n  apiKey?: string;\n\n  /**\n   * OpenAI Organization.\n   */\n  organization?: string;\n\n  /**\n   * OpenAI project.\n   */\n  project?: string;\n\n  /**\n   * Custom headers to include in the requests.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Provider name. Overrides the `openai` default name for 3rd party providers.\n   */\n  name?: string;\n\n  /**\n   * Custom fetch implementation. You can use it as a middleware to intercept requests,\n   * or to provide a custom fetch implementation for e.g. testing.\n   */\n  fetch?: FetchFunction;\n}\n\n/**\n * Create an OpenAI provider instance.\n */\nexport function createOpenAI(\n  options: OpenAIProviderSettings = {},\n): OpenAIProvider {\n  const baseURL =\n    withoutTrailingSlash(\n      loadOptionalSetting({\n        settingValue: options.baseURL,\n        environmentVariableName: 'OPENAI_BASE_URL',\n      }),\n    ) ?? 'https://api.openai.com/v1';\n\n  const providerName = options.name ?? 'openai';\n\n  const getHeaders = () =>\n    withUserAgentSuffix(\n      {\n        Authorization: `Bearer ${loadApiKey({\n          apiKey: options.apiKey,\n          environmentVariableName: 'OPENAI_API_KEY',\n          description: 'OpenAI',\n        })}`,\n        'OpenAI-Organization': options.organization,\n        'OpenAI-Project': options.project,\n        ...options.headers,\n      },\n      `ai-sdk/openai/${VERSION}`,\n    );\n\n  const createChatModel = (modelId: OpenAIChatModelId) =>\n    new OpenAIChatLanguageModel(modelId, {\n      provider: `${providerName}.chat`,\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n    });\n\n  const createCompletionModel = (modelId: OpenAICompletionModelId) =>\n    new OpenAICompletionLanguageModel(modelId, {\n      provider: `${providerName}.completion`,\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n    });\n\n  const createEmbeddingModel = (modelId: OpenAIEmbeddingModelId) =>\n    new OpenAIEmbeddingModel(modelId, {\n      provider: `${providerName}.embedding`,\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n    });\n\n  const createImageModel = (modelId: OpenAIImageModelId) =>\n    new OpenAIImageModel(modelId, {\n      provider: `${providerName}.image`,\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n    });\n\n  const createTranscriptionModel = (modelId: OpenAITranscriptionModelId) =>\n    new OpenAITranscriptionModel(modelId, {\n      provider: `${providerName}.transcription`,\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n    });\n\n  const createSpeechModel = (modelId: OpenAISpeechModelId) =>\n    new OpenAISpeechModel(modelId, {\n      provider: `${providerName}.speech`,\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n    });\n\n  const createLanguageModel = (modelId: OpenAIResponsesModelId) => {\n    if (new.target) {\n      throw new Error(\n        'The OpenAI model function cannot be called with the new keyword.',\n      );\n    }\n\n    return createResponsesModel(modelId);\n  };\n\n  const createResponsesModel = (modelId: OpenAIResponsesModelId) => {\n    return new OpenAIResponsesLanguageModel(modelId, {\n      provider: `${providerName}.responses`,\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n      fileIdPrefixes: ['file-'],\n    });\n  };\n\n  const provider = function (modelId: OpenAIResponsesModelId) {\n    return createLanguageModel(modelId);\n  };\n\n  provider.specificationVersion = 'v3' as const;\n  provider.languageModel = createLanguageModel;\n  provider.chat = createChatModel;\n  provider.completion = createCompletionModel;\n  provider.responses = createResponsesModel;\n  provider.embedding = createEmbeddingModel;\n  provider.embeddingModel = createEmbeddingModel;\n  provider.textEmbedding = createEmbeddingModel;\n  provider.textEmbeddingModel = createEmbeddingModel;\n\n  provider.image = createImageModel;\n  provider.imageModel = createImageModel;\n\n  provider.transcription = createTranscriptionModel;\n  provider.transcriptionModel = createTranscriptionModel;\n\n  provider.speech = createSpeechModel;\n  provider.speechModel = createSpeechModel;\n\n  provider.tools = openaiTools;\n\n  return provider as OpenAIProvider;\n}\n\n/**\n * Default OpenAI provider instance.\n */\nexport const openai = createOpenAI();\n", "import {\n  InvalidResponseDataError,\n  LanguageModelV3,\n  LanguageModelV3CallOptions,\n  LanguageModelV3Content,\n  LanguageModelV3FinishReason,\n  LanguageModelV3GenerateResult,\n  LanguageModelV3StreamPart,\n  LanguageModelV3StreamResult,\n  SharedV3ProviderMetadata,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  FetchFunction,\n  ParseResult,\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonResponseHandler,\n  generateId,\n  isParsableJson,\n  parseProviderOptions,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { openaiFailedResponseHandler } from '../openai-error';\nimport { getOpenAILanguageModelCapabilities } from '../openai-language-model-capabilities';\nimport {\n  OpenAIChatUsage,\n  convertOpenAIChatUsage,\n} from './convert-openai-chat-usage';\nimport { convertToOpenAIChatMessages } from './convert-to-openai-chat-messages';\nimport { getResponseMetadata } from './get-response-metadata';\nimport { mapOpenAIFinishReason } from './map-openai-finish-reason';\nimport {\n  OpenAIChatChunk,\n  openaiChatChunkSchema,\n  openaiChatResponseSchema,\n} from './openai-chat-api';\nimport {\n  OpenAIChatModelId,\n  openaiLanguageModelChatOptions,\n} from './openai-chat-options';\nimport { prepareChatTools } from './openai-chat-prepare-tools';\n\ntype OpenAIChatConfig = {\n  provider: string;\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: FetchFunction;\n};\n\nexport class OpenAIChatLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = 'v3';\n\n  readonly modelId: OpenAIChatModelId;\n\n  readonly supportedUrls = {\n    'image/*': [/^https?:\\/\\/.*$/],\n  };\n\n  private readonly config: OpenAIChatConfig;\n\n  constructor(modelId: OpenAIChatModelId, config: OpenAIChatConfig) {\n    this.modelId = modelId;\n    this.config = config;\n  }\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  private async getArgs({\n    prompt,\n    maxOutputTokens,\n    temperature,\n    topP,\n    topK,\n    frequencyPenalty,\n    presencePenalty,\n    stopSequences,\n    responseFormat,\n    seed,\n    tools,\n    toolChoice,\n    providerOptions,\n  }: LanguageModelV3CallOptions) {\n    const warnings: SharedV3Warning[] = [];\n\n    // Parse provider options\n    const openaiOptions =\n      (await parseProviderOptions({\n        provider: 'openai',\n        providerOptions,\n        schema: openaiLanguageModelChatOptions,\n      })) ?? {};\n\n    const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId);\n    const isReasoningModel =\n      openaiOptions.forceReasoning ?? modelCapabilities.isReasoningModel;\n\n    if (topK != null) {\n      warnings.push({ type: 'unsupported', feature: 'topK' });\n    }\n\n    const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages(\n      {\n        prompt,\n        systemMessageMode:\n          openaiOptions.systemMessageMode ??\n          (isReasoningModel\n            ? 'developer'\n            : modelCapabilities.systemMessageMode),\n      },\n    );\n\n    warnings.push(...messageWarnings);\n\n    const strictJsonSchema = openaiOptions.strictJsonSchema ?? true;\n\n    const baseArgs = {\n      // model id:\n      model: this.modelId,\n\n      // model specific settings:\n      logit_bias: openaiOptions.logitBias,\n      logprobs:\n        openaiOptions.logprobs === true ||\n        typeof openaiOptions.logprobs === 'number'\n          ? true\n          : undefined,\n      top_logprobs:\n        typeof openaiOptions.logprobs === 'number'\n          ? openaiOptions.logprobs\n          : typeof openaiOptions.logprobs === 'boolean'\n            ? openaiOptions.logprobs\n              ? 0\n              : undefined\n            : undefined,\n      user: openaiOptions.user,\n      parallel_tool_calls: openaiOptions.parallelToolCalls,\n\n      // standardized settings:\n      max_tokens: maxOutputTokens,\n      temperature,\n      top_p: topP,\n      frequency_penalty: frequencyPenalty,\n      presence_penalty: presencePenalty,\n      response_format:\n        responseFormat?.type === 'json'\n          ? responseFormat.schema != null\n            ? {\n                type: 'json_schema',\n                json_schema: {\n                  schema: responseFormat.schema,\n                  strict: strictJsonSchema,\n                  name: responseFormat.name ?? 'response',\n                  description: responseFormat.description,\n                },\n              }\n            : { type: 'json_object' }\n          : undefined,\n      stop: stopSequences,\n      seed,\n      verbosity: openaiOptions.textVerbosity,\n\n      // openai specific settings:\n      // TODO AI SDK 6: remove, we auto-map maxOutputTokens now\n      max_completion_tokens: openaiOptions.maxCompletionTokens,\n      store: openaiOptions.store,\n      metadata: openaiOptions.metadata,\n      prediction: openaiOptions.prediction,\n      reasoning_effort: openaiOptions.reasoningEffort,\n      service_tier: openaiOptions.serviceTier,\n      prompt_cache_key: openaiOptions.promptCacheKey,\n      prompt_cache_retention: openaiOptions.promptCacheRetention,\n      safety_identifier: openaiOptions.safetyIdentifier,\n\n      // messages:\n      messages,\n    };\n\n    // remove unsupported settings for reasoning models\n    // see https://platform.openai.com/docs/guides/reasoning#limitations\n    if (isReasoningModel) {\n      // when reasoning effort is none, gpt-5.1 models allow temperature, topP, logprobs\n      //  https://platform.openai.com/docs/guides/latest-model#gpt-5-1-parameter-compatibility\n      if (\n        openaiOptions.reasoningEffort !== 'none' ||\n        !modelCapabilities.supportsNonReasoningParameters\n      ) {\n        if (baseArgs.temperature != null) {\n          baseArgs.temperature = undefined;\n          warnings.push({\n            type: 'unsupported',\n            feature: 'temperature',\n            details: 'temperature is not supported for reasoning models',\n          });\n        }\n        if (baseArgs.top_p != null) {\n          baseArgs.top_p = undefined;\n          warnings.push({\n            type: 'unsupported',\n            feature: 'topP',\n            details: 'topP is not supported for reasoning models',\n          });\n        }\n        if (baseArgs.logprobs != null) {\n          baseArgs.logprobs = undefined;\n          warnings.push({\n            type: 'other',\n            message: 'logprobs is not supported for reasoning models',\n          });\n        }\n      }\n\n      if (baseArgs.frequency_penalty != null) {\n        baseArgs.frequency_penalty = undefined;\n        warnings.push({\n          type: 'unsupported',\n          feature: 'frequencyPenalty',\n          details: 'frequencyPenalty is not supported for reasoning models',\n        });\n      }\n      if (baseArgs.presence_penalty != null) {\n        baseArgs.presence_penalty = undefined;\n        warnings.push({\n          type: 'unsupported',\n          feature: 'presencePenalty',\n          details: 'presencePenalty is not supported for reasoning models',\n        });\n      }\n      if (baseArgs.logit_bias != null) {\n        baseArgs.logit_bias = undefined;\n        warnings.push({\n          type: 'other',\n          message: 'logitBias is not supported for reasoning models',\n        });\n      }\n\n      if (baseArgs.top_logprobs != null) {\n        baseArgs.top_logprobs = undefined;\n        warnings.push({\n          type: 'other',\n          message: 'topLogprobs is not supported for reasoning models',\n        });\n      }\n\n      // reasoning models use max_completion_tokens instead of max_tokens:\n      if (baseArgs.max_tokens != null) {\n        if (baseArgs.max_completion_tokens == null) {\n          baseArgs.max_completion_tokens = baseArgs.max_tokens;\n        }\n        baseArgs.max_tokens = undefined;\n      }\n    } else if (\n      this.modelId.startsWith('gpt-4o-search-preview') ||\n      this.modelId.startsWith('gpt-4o-mini-search-preview')\n    ) {\n      if (baseArgs.temperature != null) {\n        baseArgs.temperature = undefined;\n        warnings.push({\n          type: 'unsupported',\n          feature: 'temperature',\n          details:\n            'temperature is not supported for the search preview models and has been removed.',\n        });\n      }\n    }\n\n    // Validate flex processing support\n    if (\n      openaiOptions.serviceTier === 'flex' &&\n      !modelCapabilities.supportsFlexProcessing\n    ) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'serviceTier',\n        details:\n          'flex processing is only available for o3, o4-mini, and gpt-5 models',\n      });\n      baseArgs.service_tier = undefined;\n    }\n\n    // Validate priority processing support\n    if (\n      openaiOptions.serviceTier === 'priority' &&\n      !modelCapabilities.supportsPriorityProcessing\n    ) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'serviceTier',\n        details:\n          'priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported',\n      });\n      baseArgs.service_tier = undefined;\n    }\n\n    const {\n      tools: openaiTools,\n      toolChoice: openaiToolChoice,\n      toolWarnings,\n    } = prepareChatTools({\n      tools,\n      toolChoice,\n    });\n\n    return {\n      args: {\n        ...baseArgs,\n        tools: openaiTools,\n        tool_choice: openaiToolChoice,\n      },\n      warnings: [...warnings, ...toolWarnings],\n    };\n  }\n\n  async doGenerate(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3GenerateResult> {\n    const { args: body, warnings } = await this.getArgs(options);\n\n    const {\n      responseHeaders,\n      value: response,\n      rawValue: rawResponse,\n    } = await postJsonToApi({\n      url: this.config.url({\n        path: '/chat/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body,\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiChatResponseSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const choice = response.choices[0];\n    const content: Array<LanguageModelV3Content> = [];\n\n    // text content:\n    const text = choice.message.content;\n    if (text != null && text.length > 0) {\n      content.push({ type: 'text', text });\n    }\n\n    // tool calls:\n    for (const toolCall of choice.message.tool_calls ?? []) {\n      content.push({\n        type: 'tool-call' as const,\n        toolCallId: toolCall.id ?? generateId(),\n        toolName: toolCall.function.name,\n        input: toolCall.function.arguments!,\n      });\n    }\n\n    // annotations/citations:\n    for (const annotation of choice.message.annotations ?? []) {\n      content.push({\n        type: 'source',\n        sourceType: 'url',\n        id: generateId(),\n        url: annotation.url_citation.url,\n        title: annotation.url_citation.title,\n      });\n    }\n\n    // provider metadata:\n    const completionTokenDetails = response.usage?.completion_tokens_details;\n    const promptTokenDetails = response.usage?.prompt_tokens_details;\n    const providerMetadata: SharedV3ProviderMetadata = { openai: {} };\n    if (completionTokenDetails?.accepted_prediction_tokens != null) {\n      providerMetadata.openai.acceptedPredictionTokens =\n        completionTokenDetails?.accepted_prediction_tokens;\n    }\n    if (completionTokenDetails?.rejected_prediction_tokens != null) {\n      providerMetadata.openai.rejectedPredictionTokens =\n        completionTokenDetails?.rejected_prediction_tokens;\n    }\n    if (choice.logprobs?.content != null) {\n      providerMetadata.openai.logprobs = choice.logprobs.content;\n    }\n\n    return {\n      content,\n      finishReason: {\n        unified: mapOpenAIFinishReason(choice.finish_reason),\n        raw: choice.finish_reason ?? undefined,\n      },\n      usage: convertOpenAIChatUsage(response.usage),\n      request: { body },\n      response: {\n        ...getResponseMetadata(response),\n        headers: responseHeaders,\n        body: rawResponse,\n      },\n      warnings,\n      providerMetadata,\n    };\n  }\n\n  async doStream(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3StreamResult> {\n    const { args, warnings } = await this.getArgs(options);\n\n    const body = {\n      ...args,\n      stream: true,\n      stream_options: {\n        include_usage: true,\n      },\n    };\n\n    const { responseHeaders, value: response } = await postJsonToApi({\n      url: this.config.url({\n        path: '/chat/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body,\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createEventSourceResponseHandler(\n        openaiChatChunkSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const toolCalls: Array<{\n      id: string;\n      type: 'function';\n      function: {\n        name: string;\n        arguments: string;\n      };\n      hasFinished: boolean;\n    }> = [];\n\n    let finishReason: LanguageModelV3FinishReason = {\n      unified: 'other',\n      raw: undefined,\n    };\n    let usage: OpenAIChatUsage | undefined = undefined;\n    let metadataExtracted = false;\n    let isActiveText = false;\n\n    const providerMetadata: SharedV3ProviderMetadata = { openai: {} };\n\n    return {\n      stream: response.pipeThrough(\n        new TransformStream<\n          ParseResult<OpenAIChatChunk>,\n          LanguageModelV3StreamPart\n        >({\n          start(controller) {\n            controller.enqueue({ type: 'stream-start', warnings });\n          },\n\n          transform(chunk, controller) {\n            if (options.includeRawChunks) {\n              controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n            }\n\n            // handle failed chunk parsing / validation:\n            if (!chunk.success) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({ type: 'error', error: chunk.error });\n              return;\n            }\n\n            const value = chunk.value;\n\n            // handle error chunks:\n            if ('error' in value) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({ type: 'error', error: value.error });\n              return;\n            }\n\n            // extract and emit response metadata once. Usually it comes in the first chunk.\n            // Azure may prepend a chunk with a `\"prompt_filter_results\"` key which does not contain other metadata,\n            // https://learn.microsoft.com/en-us/azure/ai-foundry/openai/concepts/content-filter-annotations?tabs=powershell\n            if (!metadataExtracted) {\n              const metadata = getResponseMetadata(value);\n              if (Object.values(metadata).some(Boolean)) {\n                metadataExtracted = true;\n                controller.enqueue({\n                  type: 'response-metadata',\n                  ...getResponseMetadata(value),\n                });\n              }\n            }\n\n            if (value.usage != null) {\n              usage = value.usage;\n\n              if (\n                value.usage.completion_tokens_details\n                  ?.accepted_prediction_tokens != null\n              ) {\n                providerMetadata.openai.acceptedPredictionTokens =\n                  value.usage.completion_tokens_details?.accepted_prediction_tokens;\n              }\n              if (\n                value.usage.completion_tokens_details\n                  ?.rejected_prediction_tokens != null\n              ) {\n                providerMetadata.openai.rejectedPredictionTokens =\n                  value.usage.completion_tokens_details?.rejected_prediction_tokens;\n              }\n            }\n\n            const choice = value.choices[0];\n\n            if (choice?.finish_reason != null) {\n              finishReason = {\n                unified: mapOpenAIFinishReason(choice.finish_reason),\n                raw: choice.finish_reason,\n              };\n            }\n\n            if (choice?.logprobs?.content != null) {\n              providerMetadata.openai.logprobs = choice.logprobs.content;\n            }\n\n            if (choice?.delta == null) {\n              return;\n            }\n\n            const delta = choice.delta;\n\n            if (delta.content != null) {\n              if (!isActiveText) {\n                controller.enqueue({ type: 'text-start', id: '0' });\n                isActiveText = true;\n              }\n\n              controller.enqueue({\n                type: 'text-delta',\n                id: '0',\n                delta: delta.content,\n              });\n            }\n\n            if (delta.tool_calls != null) {\n              for (const toolCallDelta of delta.tool_calls) {\n                const index = toolCallDelta.index;\n\n                // Tool call start. OpenAI returns all information except the arguments in the first chunk.\n                if (toolCalls[index] == null) {\n                  if (\n                    toolCallDelta.type != null &&\n                    toolCallDelta.type !== 'function'\n                  ) {\n                    throw new InvalidResponseDataError({\n                      data: toolCallDelta,\n                      message: `Expected 'function' type.`,\n                    });\n                  }\n\n                  if (toolCallDelta.id == null) {\n                    throw new InvalidResponseDataError({\n                      data: toolCallDelta,\n                      message: `Expected 'id' to be a string.`,\n                    });\n                  }\n\n                  if (toolCallDelta.function?.name == null) {\n                    throw new InvalidResponseDataError({\n                      data: toolCallDelta,\n                      message: `Expected 'function.name' to be a string.`,\n                    });\n                  }\n\n                  controller.enqueue({\n                    type: 'tool-input-start',\n                    id: toolCallDelta.id,\n                    toolName: toolCallDelta.function.name,\n                  });\n\n                  toolCalls[index] = {\n                    id: toolCallDelta.id,\n                    type: 'function',\n                    function: {\n                      name: toolCallDelta.function.name,\n                      arguments: toolCallDelta.function.arguments ?? '',\n                    },\n                    hasFinished: false,\n                  };\n\n                  const toolCall = toolCalls[index];\n\n                  if (\n                    toolCall.function?.name != null &&\n                    toolCall.function?.arguments != null\n                  ) {\n                    // send delta if the argument text has already started:\n                    if (toolCall.function.arguments.length > 0) {\n                      controller.enqueue({\n                        type: 'tool-input-delta',\n                        id: toolCall.id,\n                        delta: toolCall.function.arguments,\n                      });\n                    }\n\n                    // check if tool call is complete\n                    // (some providers send the full tool call in one chunk):\n                    if (isParsableJson(toolCall.function.arguments)) {\n                      controller.enqueue({\n                        type: 'tool-input-end',\n                        id: toolCall.id,\n                      });\n\n                      controller.enqueue({\n                        type: 'tool-call',\n                        toolCallId: toolCall.id ?? generateId(),\n                        toolName: toolCall.function.name,\n                        input: toolCall.function.arguments,\n                      });\n                      toolCall.hasFinished = true;\n                    }\n                  }\n\n                  continue;\n                }\n\n                // existing tool call, merge if not finished\n                const toolCall = toolCalls[index];\n\n                if (toolCall.hasFinished) {\n                  continue;\n                }\n\n                if (toolCallDelta.function?.arguments != null) {\n                  toolCall.function!.arguments +=\n                    toolCallDelta.function?.arguments ?? '';\n                }\n\n                // send delta\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.id,\n                  delta: toolCallDelta.function.arguments ?? '',\n                });\n\n                // check if tool call is complete\n                if (\n                  toolCall.function?.name != null &&\n                  toolCall.function?.arguments != null &&\n                  isParsableJson(toolCall.function.arguments)\n                ) {\n                  controller.enqueue({\n                    type: 'tool-input-end',\n                    id: toolCall.id,\n                  });\n\n                  controller.enqueue({\n                    type: 'tool-call',\n                    toolCallId: toolCall.id ?? generateId(),\n                    toolName: toolCall.function.name,\n                    input: toolCall.function.arguments,\n                  });\n                  toolCall.hasFinished = true;\n                }\n              }\n            }\n\n            // annotations/citations:\n            if (delta.annotations != null) {\n              for (const annotation of delta.annotations) {\n                controller.enqueue({\n                  type: 'source',\n                  sourceType: 'url',\n                  id: generateId(),\n                  url: annotation.url_citation.url,\n                  title: annotation.url_citation.title,\n                });\n              }\n            }\n          },\n\n          flush(controller) {\n            if (isActiveText) {\n              controller.enqueue({ type: 'text-end', id: '0' });\n            }\n\n            controller.enqueue({\n              type: 'finish',\n              finishReason,\n              usage: convertOpenAIChatUsage(usage),\n              ...(providerMetadata != null ? { providerMetadata } : {}),\n            });\n          },\n        }),\n      ),\n      request: { body },\n      response: { headers: responseHeaders },\n    };\n  }\n}\n", "import { z } from 'zod/v4';\nimport { createJsonErrorResponseHandler } from '@ai-sdk/provider-utils';\n\nexport const openaiErrorDataSchema = z.object({\n  error: z.object({\n    message: z.string(),\n\n    // The additional information below is handled loosely to support\n    // OpenAI-compatible providers that have slightly different error\n    // responses:\n    type: z.string().nullish(),\n    param: z.any().nullish(),\n    code: z.union([z.string(), z.number()]).nullish(),\n  }),\n});\n\nexport type OpenAIErrorData = z.infer<typeof openaiErrorDataSchema>;\n\nexport const openaiFailedResponseHandler = createJsonErrorResponseHandler({\n  errorSchema: openaiErrorDataSchema,\n  errorToMessage: data => data.error.message,\n});\n", "export type OpenAILanguageModelCapabilities = {\n  isReasoningModel: boolean;\n  systemMessageMode: 'remove' | 'system' | 'developer';\n  supportsFlexProcessing: boolean;\n  supportsPriorityProcessing: boolean;\n\n  /**\n   * Allow temperature, topP, logProbs when reasoningEffort is none.\n   */\n  supportsNonReasoningParameters: boolean;\n};\n\nexport function getOpenAILanguageModelCapabilities(\n  modelId: string,\n): OpenAILanguageModelCapabilities {\n  const supportsFlexProcessing =\n    modelId.startsWith('o3') ||\n    modelId.startsWith('o4-mini') ||\n    (modelId.startsWith('gpt-5') && !modelId.startsWith('gpt-5-chat'));\n\n  const supportsPriorityProcessing =\n    modelId.startsWith('gpt-4') ||\n    (modelId.startsWith('gpt-5') &&\n      !modelId.startsWith('gpt-5-nano') &&\n      !modelId.startsWith('gpt-5-chat') &&\n      !modelId.startsWith('gpt-5.4-nano')) ||\n    modelId.startsWith('o3') ||\n    modelId.startsWith('o4-mini');\n\n  // Use allowlist approach: only known reasoning models should use 'developer' role\n  // This prevents issues with fine-tuned models, third-party models, and custom models\n  const isReasoningModel =\n    modelId.startsWith('o1') ||\n    modelId.startsWith('o3') ||\n    modelId.startsWith('o4-mini') ||\n    (modelId.startsWith('gpt-5') && !modelId.startsWith('gpt-5-chat'));\n\n  // https://platform.openai.com/docs/guides/latest-model#gpt-5-1-parameter-compatibility\n  // GPT-5.1, GPT-5.2, and GPT-5.4 support temperature, topP, logProbs when reasoningEffort is none\n  const supportsNonReasoningParameters =\n    modelId.startsWith('gpt-5.1') ||\n    modelId.startsWith('gpt-5.2') ||\n    modelId.startsWith('gpt-5.3') ||\n    modelId.startsWith('gpt-5.4');\n\n  const systemMessageMode = isReasoningModel ? 'developer' : 'system';\n\n  return {\n    supportsFlexProcessing,\n    supportsPriorityProcessing,\n    isReasoningModel,\n    systemMessageMode,\n    supportsNonReasoningParameters,\n  };\n}\n", "import { LanguageModelV3Usage } from '@ai-sdk/provider';\n\nexport type OpenAIChatUsage = {\n  prompt_tokens?: number | null;\n  completion_tokens?: number | null;\n  total_tokens?: number | null;\n  prompt_tokens_details?: {\n    cached_tokens?: number | null;\n  } | null;\n  completion_tokens_details?: {\n    reasoning_tokens?: number | null;\n    accepted_prediction_tokens?: number | null;\n    rejected_prediction_tokens?: number | null;\n  } | null;\n};\n\nexport function convertOpenAIChatUsage(\n  usage: OpenAIChatUsage | undefined | null,\n): LanguageModelV3Usage {\n  if (usage == null) {\n    return {\n      inputTokens: {\n        total: undefined,\n        noCache: undefined,\n        cacheRead: undefined,\n        cacheWrite: undefined,\n      },\n      outputTokens: {\n        total: undefined,\n        text: undefined,\n        reasoning: undefined,\n      },\n      raw: undefined,\n    };\n  }\n\n  const promptTokens = usage.prompt_tokens ?? 0;\n  const completionTokens = usage.completion_tokens ?? 0;\n  const cachedTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;\n  const reasoningTokens =\n    usage.completion_tokens_details?.reasoning_tokens ?? 0;\n\n  return {\n    inputTokens: {\n      total: promptTokens,\n      noCache: promptTokens - cachedTokens,\n      cacheRead: cachedTokens,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: completionTokens,\n      text: completionTokens - reasoningTokens,\n      reasoning: reasoningTokens,\n    },\n    raw: usage,\n  };\n}\n", "import {\n  SharedV3Warning,\n  LanguageModelV3Prompt,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\nimport { OpenAIChatPrompt } from './openai-chat-prompt';\nimport { convertToBase64 } from '@ai-sdk/provider-utils';\n\nexport function convertToOpenAIChatMessages({\n  prompt,\n  systemMessageMode = 'system',\n}: {\n  prompt: LanguageModelV3Prompt;\n  systemMessageMode?: 'system' | 'developer' | 'remove';\n}): {\n  messages: OpenAIChatPrompt;\n  warnings: Array<SharedV3Warning>;\n} {\n  const messages: OpenAIChatPrompt = [];\n  const warnings: Array<SharedV3Warning> = [];\n\n  for (const { role, content } of prompt) {\n    switch (role) {\n      case 'system': {\n        switch (systemMessageMode) {\n          case 'system': {\n            messages.push({ role: 'system', content });\n            break;\n          }\n          case 'developer': {\n            messages.push({ role: 'developer', content });\n            break;\n          }\n          case 'remove': {\n            warnings.push({\n              type: 'other',\n              message: 'system messages are removed for this model',\n            });\n            break;\n          }\n          default: {\n            const _exhaustiveCheck: never = systemMessageMode;\n            throw new Error(\n              `Unsupported system message mode: ${_exhaustiveCheck}`,\n            );\n          }\n        }\n        break;\n      }\n\n      case 'user': {\n        if (content.length === 1 && content[0].type === 'text') {\n          messages.push({ role: 'user', content: content[0].text });\n          break;\n        }\n\n        messages.push({\n          role: 'user',\n          content: content.map((part, index) => {\n            switch (part.type) {\n              case 'text': {\n                return { type: 'text', text: part.text };\n              }\n              case 'file': {\n                if (part.mediaType.startsWith('image/')) {\n                  const mediaType =\n                    part.mediaType === 'image/*'\n                      ? 'image/jpeg'\n                      : part.mediaType;\n\n                  return {\n                    type: 'image_url',\n                    image_url: {\n                      url:\n                        part.data instanceof URL\n                          ? part.data.toString()\n                          : `data:${mediaType};base64,${convertToBase64(part.data)}`,\n\n                      // OpenAI specific extension: image detail\n                      detail: part.providerOptions?.openai?.imageDetail,\n                    },\n                  };\n                } else if (part.mediaType.startsWith('audio/')) {\n                  if (part.data instanceof URL) {\n                    throw new UnsupportedFunctionalityError({\n                      functionality: 'audio file parts with URLs',\n                    });\n                  }\n\n                  switch (part.mediaType) {\n                    case 'audio/wav': {\n                      return {\n                        type: 'input_audio',\n                        input_audio: {\n                          data: convertToBase64(part.data),\n                          format: 'wav',\n                        },\n                      };\n                    }\n                    case 'audio/mp3':\n                    case 'audio/mpeg': {\n                      return {\n                        type: 'input_audio',\n                        input_audio: {\n                          data: convertToBase64(part.data),\n                          format: 'mp3',\n                        },\n                      };\n                    }\n\n                    default: {\n                      throw new UnsupportedFunctionalityError({\n                        functionality: `audio content parts with media type ${part.mediaType}`,\n                      });\n                    }\n                  }\n                } else if (part.mediaType === 'application/pdf') {\n                  if (part.data instanceof URL) {\n                    throw new UnsupportedFunctionalityError({\n                      functionality: 'PDF file parts with URLs',\n                    });\n                  }\n\n                  return {\n                    type: 'file',\n                    file:\n                      typeof part.data === 'string' &&\n                      part.data.startsWith('file-')\n                        ? { file_id: part.data }\n                        : {\n                            filename: part.filename ?? `part-${index}.pdf`,\n                            file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`,\n                          },\n                  };\n                } else {\n                  throw new UnsupportedFunctionalityError({\n                    functionality: `file part media type ${part.mediaType}`,\n                  });\n                }\n              }\n            }\n          }),\n        });\n\n        break;\n      }\n\n      case 'assistant': {\n        let text = '';\n        const toolCalls: Array<{\n          id: string;\n          type: 'function';\n          function: { name: string; arguments: string };\n        }> = [];\n\n        for (const part of content) {\n          switch (part.type) {\n            case 'text': {\n              text += part.text;\n              break;\n            }\n            case 'tool-call': {\n              toolCalls.push({\n                id: part.toolCallId,\n                type: 'function',\n                function: {\n                  name: part.toolName,\n                  arguments: JSON.stringify(part.input),\n                },\n              });\n              break;\n            }\n          }\n        }\n\n        messages.push({\n          role: 'assistant',\n          content: text,\n          tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n        });\n\n        break;\n      }\n\n      case 'tool': {\n        for (const toolResponse of content) {\n          if (toolResponse.type === 'tool-approval-response') {\n            continue;\n          }\n          const output = toolResponse.output;\n\n          let contentValue: string;\n          switch (output.type) {\n            case 'text':\n            case 'error-text':\n              contentValue = output.value;\n              break;\n            case 'execution-denied':\n              contentValue = output.reason ?? 'Tool execution denied.';\n              break;\n            case 'content':\n            case 'json':\n            case 'error-json':\n              contentValue = JSON.stringify(output.value);\n              break;\n          }\n\n          messages.push({\n            role: 'tool',\n            tool_call_id: toolResponse.toolCallId,\n            content: contentValue,\n          });\n        }\n        break;\n      }\n\n      default: {\n        const _exhaustiveCheck: never = role;\n        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n      }\n    }\n  }\n\n  return { messages, warnings };\n}\n", "export function getResponseMetadata({\n  id,\n  model,\n  created,\n}: {\n  id?: string | undefined | null;\n  created?: number | undefined | null;\n  model?: string | undefined | null;\n}) {\n  return {\n    id: id ?? undefined,\n    modelId: model ?? undefined,\n    timestamp: created ? new Date(created * 1000) : undefined,\n  };\n}\n", "import { LanguageModelV3FinishReason } from '@ai-sdk/provider';\n\nexport function mapOpenAIFinishReason(\n  finishReason: string | null | undefined,\n): LanguageModelV3FinishReason['unified'] {\n  switch (finishReason) {\n    case 'stop':\n      return 'stop';\n    case 'length':\n      return 'length';\n    case 'content_filter':\n      return 'content-filter';\n    case 'function_call':\n    case 'tool_calls':\n      return 'tool-calls';\n    default:\n      return 'other';\n  }\n}\n", "import { JSONSchema7 } from '@ai-sdk/provider';\nimport { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { openaiErrorDataSchema } from '../openai-error';\n\nexport interface OpenAIChatFunctionTool {\n  type: 'function';\n  function: {\n    name: string;\n    description: string | undefined;\n    parameters: JSONSchema7;\n    strict?: boolean;\n  };\n}\n\nexport type OpenAIChatToolChoice =\n  | 'auto'\n  | 'none'\n  | 'required'\n  | { type: 'function'; function: { name: string } };\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const openaiChatResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      id: z.string().nullish(),\n      created: z.number().nullish(),\n      model: z.string().nullish(),\n      choices: z.array(\n        z.object({\n          message: z.object({\n            role: z.literal('assistant').nullish(),\n            content: z.string().nullish(),\n            tool_calls: z\n              .array(\n                z.object({\n                  id: z.string().nullish(),\n                  type: z.literal('function'),\n                  function: z.object({\n                    name: z.string(),\n                    arguments: z.string(),\n                  }),\n                }),\n              )\n              .nullish(),\n            annotations: z\n              .array(\n                z.object({\n                  type: z.literal('url_citation'),\n                  url_citation: z.object({\n                    start_index: z.number(),\n                    end_index: z.number(),\n                    url: z.string(),\n                    title: z.string(),\n                  }),\n                }),\n              )\n              .nullish(),\n          }),\n          index: z.number(),\n          logprobs: z\n            .object({\n              content: z\n                .array(\n                  z.object({\n                    token: z.string(),\n                    logprob: z.number(),\n                    top_logprobs: z.array(\n                      z.object({\n                        token: z.string(),\n                        logprob: z.number(),\n                      }),\n                    ),\n                  }),\n                )\n                .nullish(),\n            })\n            .nullish(),\n          finish_reason: z.string().nullish(),\n        }),\n      ),\n      usage: z\n        .object({\n          prompt_tokens: z.number().nullish(),\n          completion_tokens: z.number().nullish(),\n          total_tokens: z.number().nullish(),\n          prompt_tokens_details: z\n            .object({\n              cached_tokens: z.number().nullish(),\n            })\n            .nullish(),\n          completion_tokens_details: z\n            .object({\n              reasoning_tokens: z.number().nullish(),\n              accepted_prediction_tokens: z.number().nullish(),\n              rejected_prediction_tokens: z.number().nullish(),\n            })\n            .nullish(),\n        })\n        .nullish(),\n    }),\n  ),\n);\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const openaiChatChunkSchema = lazySchema(() =>\n  zodSchema(\n    z.union([\n      z.object({\n        id: z.string().nullish(),\n        created: z.number().nullish(),\n        model: z.string().nullish(),\n        choices: z.array(\n          z.object({\n            delta: z\n              .object({\n                role: z.enum(['assistant']).nullish(),\n                content: z.string().nullish(),\n                tool_calls: z\n                  .array(\n                    z.object({\n                      index: z.number(),\n                      id: z.string().nullish(),\n                      type: z.literal('function').nullish(),\n                      function: z.object({\n                        name: z.string().nullish(),\n                        arguments: z.string().nullish(),\n                      }),\n                    }),\n                  )\n                  .nullish(),\n                annotations: z\n                  .array(\n                    z.object({\n                      type: z.literal('url_citation'),\n                      url_citation: z.object({\n                        start_index: z.number(),\n                        end_index: z.number(),\n                        url: z.string(),\n                        title: z.string(),\n                      }),\n                    }),\n                  )\n                  .nullish(),\n              })\n              .nullish(),\n            logprobs: z\n              .object({\n                content: z\n                  .array(\n                    z.object({\n                      token: z.string(),\n                      logprob: z.number(),\n                      top_logprobs: z.array(\n                        z.object({\n                          token: z.string(),\n                          logprob: z.number(),\n                        }),\n                      ),\n                    }),\n                  )\n                  .nullish(),\n              })\n              .nullish(),\n            finish_reason: z.string().nullish(),\n            index: z.number(),\n          }),\n        ),\n        usage: z\n          .object({\n            prompt_tokens: z.number().nullish(),\n            completion_tokens: z.number().nullish(),\n            total_tokens: z.number().nullish(),\n            prompt_tokens_details: z\n              .object({\n                cached_tokens: z.number().nullish(),\n              })\n              .nullish(),\n            completion_tokens_details: z\n              .object({\n                reasoning_tokens: z.number().nullish(),\n                accepted_prediction_tokens: z.number().nullish(),\n                rejected_prediction_tokens: z.number().nullish(),\n              })\n              .nullish(),\n          })\n          .nullish(),\n      }),\n      openaiErrorDataSchema,\n    ]),\n  ),\n);\n\nexport type OpenAIChatResponse = InferSchema<typeof openaiChatResponseSchema>;\n\nexport type OpenAIChatChunk = InferSchema<typeof openaiChatChunkSchema>;\n", "import { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://platform.openai.com/docs/models\nexport type OpenAIChatModelId =\n  | 'o1'\n  | 'o1-2024-12-17'\n  | 'o3-mini'\n  | 'o3-mini-2025-01-31'\n  | 'o3'\n  | 'o3-2025-04-16'\n  | 'o4-mini'\n  | 'o4-mini-2025-04-16'\n  | 'gpt-4.1'\n  | 'gpt-4.1-2025-04-14'\n  | 'gpt-4.1-mini'\n  | 'gpt-4.1-mini-2025-04-14'\n  | 'gpt-4.1-nano'\n  | 'gpt-4.1-nano-2025-04-14'\n  | 'gpt-4o'\n  | 'gpt-4o-2024-05-13'\n  | 'gpt-4o-2024-08-06'\n  | 'gpt-4o-2024-11-20'\n  | 'gpt-4o-audio-preview'\n  | 'gpt-4o-audio-preview-2024-12-17'\n  | 'gpt-4o-audio-preview-2025-06-03'\n  | 'gpt-4o-mini'\n  | 'gpt-4o-mini-2024-07-18'\n  | 'gpt-4o-mini-audio-preview'\n  | 'gpt-4o-mini-audio-preview-2024-12-17'\n  | 'gpt-4o-search-preview'\n  | 'gpt-4o-search-preview-2025-03-11'\n  | 'gpt-4o-mini-search-preview'\n  | 'gpt-4o-mini-search-preview-2025-03-11'\n  | 'gpt-3.5-turbo-0125'\n  | 'gpt-3.5-turbo'\n  | 'gpt-3.5-turbo-1106'\n  | 'gpt-3.5-turbo-16k'\n  | 'gpt-5'\n  | 'gpt-5-2025-08-07'\n  | 'gpt-5-mini'\n  | 'gpt-5-mini-2025-08-07'\n  | 'gpt-5-nano'\n  | 'gpt-5-nano-2025-08-07'\n  | 'gpt-5-chat-latest'\n  | 'gpt-5.1'\n  | 'gpt-5.1-2025-11-13'\n  | 'gpt-5.1-chat-latest'\n  | 'gpt-5.2'\n  | 'gpt-5.2-2025-12-11'\n  | 'gpt-5.2-chat-latest'\n  | 'gpt-5.2-pro'\n  | 'gpt-5.2-pro-2025-12-11'\n  | 'gpt-5.3-chat-latest'\n  | 'gpt-5.4'\n  | 'gpt-5.4-2026-03-05'\n  | 'gpt-5.4-mini'\n  | 'gpt-5.4-mini-2026-03-17'\n  | 'gpt-5.4-nano'\n  | 'gpt-5.4-nano-2026-03-17'\n  | 'gpt-5.4-pro'\n  | 'gpt-5.4-pro-2026-03-05'\n  | (string & {});\n\nexport const openaiLanguageModelChatOptions = lazySchema(() =>\n  zodSchema(\n    z.object({\n      /**\n       * Modify the likelihood of specified tokens appearing in the completion.\n       *\n       * Accepts a JSON object that maps tokens (specified by their token ID in\n       * the GPT tokenizer) to an associated bias value from -100 to 100.\n       */\n      logitBias: z.record(z.coerce.number<string>(), z.number()).optional(),\n\n      /**\n       * Return the log probabilities of the tokens.\n       *\n       * Setting to true will return the log probabilities of the tokens that\n       * were generated.\n       *\n       * Setting to a number will return the log probabilities of the top n\n       * tokens that were generated.\n       */\n      logprobs: z.union([z.boolean(), z.number()]).optional(),\n\n      /**\n       * Whether to enable parallel function calling during tool use. Default to true.\n       */\n      parallelToolCalls: z.boolean().optional(),\n\n      /**\n       * A unique identifier representing your end-user, which can help OpenAI to\n       * monitor and detect abuse.\n       */\n      user: z.string().optional(),\n\n      /**\n       * Reasoning effort for reasoning models. Defaults to `medium`.\n       */\n      reasoningEffort: z\n        .enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh'])\n        .optional(),\n\n      /**\n       * Maximum number of completion tokens to generate. Useful for reasoning models.\n       */\n      maxCompletionTokens: z.number().optional(),\n\n      /**\n       * Whether to enable persistence in responses API.\n       */\n      store: z.boolean().optional(),\n\n      /**\n       * Metadata to associate with the request.\n       */\n      metadata: z.record(z.string().max(64), z.string().max(512)).optional(),\n\n      /**\n       * Parameters for prediction mode.\n       */\n      prediction: z.record(z.string(), z.any()).optional(),\n\n      /**\n       * Service tier for the request.\n       * - 'auto': Default service tier. The request will be processed with the service tier configured in the\n       *           Project settings. Unless otherwise configured, the Project will use 'default'.\n       * - 'flex': 50% cheaper processing at the cost of increased latency. Only available for o3 and o4-mini models.\n       * - 'priority': Higher-speed processing with predictably low latency at premium cost. Available for Enterprise customers.\n       * - 'default': The request will be processed with the standard pricing and performance for the selected model.\n       *\n       * @default 'auto'\n       */\n      serviceTier: z.enum(['auto', 'flex', 'priority', 'default']).optional(),\n\n      /**\n       * Whether to use strict JSON schema validation.\n       *\n       * @default true\n       */\n      strictJsonSchema: z.boolean().optional(),\n\n      /**\n       * Controls the verbosity of the model's responses.\n       * Lower values will result in more concise responses, while higher values will result in more verbose responses.\n       */\n      textVerbosity: z.enum(['low', 'medium', 'high']).optional(),\n\n      /**\n       * A cache key for prompt caching. Allows manual control over prompt caching behavior.\n       * Useful for improving cache hit rates and working around automatic caching issues.\n       */\n      promptCacheKey: z.string().optional(),\n\n      /**\n       * The retention policy for the prompt cache.\n       * - 'in_memory': Default. Standard prompt caching behavior.\n       * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours.\n       *          Currently only available for 5.1 series models.\n       *\n       * @default 'in_memory'\n       */\n      promptCacheRetention: z.enum(['in_memory', '24h']).optional(),\n\n      /**\n       * A stable identifier used to help detect users of your application\n       * that may be violating OpenAI's usage policies. The IDs should be a\n       * string that uniquely identifies each user. We recommend hashing their\n       * username or email address, in order to avoid sending us any identifying\n       * information.\n       */\n      safetyIdentifier: z.string().optional(),\n\n      /**\n       * Override the system message mode for this model.\n       * - 'system': Use the 'system' role for system messages (default for most models)\n       * - 'developer': Use the 'developer' role for system messages (used by reasoning models)\n       * - 'remove': Remove system messages entirely\n       *\n       * If not specified, the mode is automatically determined based on the model.\n       */\n      systemMessageMode: z.enum(['system', 'developer', 'remove']).optional(),\n\n      /**\n       * Force treating this model as a reasoning model.\n       *\n       * This is useful for \"stealth\" reasoning models (e.g. via a custom baseURL)\n       * where the model ID is not recognized by the SDK's allowlist.\n       *\n       * When enabled, the SDK applies reasoning-model parameter compatibility rules\n       * and defaults `systemMessageMode` to `developer` unless overridden.\n       */\n      forceReasoning: z.boolean().optional(),\n    }),\n  ),\n);\n\nexport type OpenAILanguageModelChatOptions = InferSchema<\n  typeof openaiLanguageModelChatOptions\n>;\n", "import {\n  LanguageModelV3CallOptions,\n  SharedV3Warning,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\nimport {\n  OpenAIChatToolChoice,\n  OpenAIChatFunctionTool,\n} from './openai-chat-api';\n\nexport function prepareChatTools({\n  tools,\n  toolChoice,\n}: {\n  tools: LanguageModelV3CallOptions['tools'];\n  toolChoice?: LanguageModelV3CallOptions['toolChoice'];\n}): {\n  tools?: OpenAIChatFunctionTool[];\n  toolChoice?: OpenAIChatToolChoice;\n  toolWarnings: Array<SharedV3Warning>;\n} {\n  // when the tools array is empty, change it to undefined to prevent errors:\n  tools = tools?.length ? tools : undefined;\n\n  const toolWarnings: SharedV3Warning[] = [];\n\n  if (tools == null) {\n    return { tools: undefined, toolChoice: undefined, toolWarnings };\n  }\n\n  const openaiTools: OpenAIChatFunctionTool[] = [];\n\n  for (const tool of tools) {\n    switch (tool.type) {\n      case 'function':\n        openaiTools.push({\n          type: 'function',\n          function: {\n            name: tool.name,\n            description: tool.description,\n            parameters: tool.inputSchema,\n            ...(tool.strict != null ? { strict: tool.strict } : {}),\n          },\n        });\n        break;\n      default:\n        toolWarnings.push({\n          type: 'unsupported',\n          feature: `tool type: ${tool.type}`,\n        });\n        break;\n    }\n  }\n\n  if (toolChoice == null) {\n    return { tools: openaiTools, toolChoice: undefined, toolWarnings };\n  }\n\n  const type = toolChoice.type;\n\n  switch (type) {\n    case 'auto':\n    case 'none':\n    case 'required':\n      return { tools: openaiTools, toolChoice: type, toolWarnings };\n    case 'tool':\n      return {\n        tools: openaiTools,\n        toolChoice: {\n          type: 'function',\n          function: {\n            name: toolChoice.toolName,\n          },\n        },\n        toolWarnings,\n      };\n    default: {\n      const _exhaustiveCheck: never = type;\n      throw new UnsupportedFunctionalityError({\n        functionality: `tool choice type: ${_exhaustiveCheck}`,\n      });\n    }\n  }\n}\n", "import {\n  LanguageModelV3,\n  LanguageModelV3CallOptions,\n  LanguageModelV3FinishReason,\n  LanguageModelV3GenerateResult,\n  LanguageModelV3StreamPart,\n  LanguageModelV3StreamResult,\n  SharedV3ProviderMetadata,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonResponseHandler,\n  FetchFunction,\n  parseProviderOptions,\n  ParseResult,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { openaiFailedResponseHandler } from '../openai-error';\nimport {\n  convertOpenAICompletionUsage,\n  OpenAICompletionUsage,\n} from './convert-openai-completion-usage';\nimport { convertToOpenAICompletionPrompt } from './convert-to-openai-completion-prompt';\nimport { getResponseMetadata } from './get-response-metadata';\nimport { mapOpenAIFinishReason } from './map-openai-finish-reason';\nimport {\n  OpenAICompletionChunk,\n  openaiCompletionChunkSchema,\n  openaiCompletionResponseSchema,\n} from './openai-completion-api';\nimport {\n  OpenAICompletionModelId,\n  openaiLanguageModelCompletionOptions,\n} from './openai-completion-options';\n\ntype OpenAICompletionConfig = {\n  provider: string;\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: FetchFunction;\n};\n\nexport class OpenAICompletionLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = 'v3';\n\n  readonly modelId: OpenAICompletionModelId;\n\n  private readonly config: OpenAICompletionConfig;\n\n  private get providerOptionsName(): string {\n    return this.config.provider.split('.')[0].trim();\n  }\n\n  constructor(\n    modelId: OpenAICompletionModelId,\n    config: OpenAICompletionConfig,\n  ) {\n    this.modelId = modelId;\n    this.config = config;\n  }\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  readonly supportedUrls: Record<string, RegExp[]> = {\n    // No URLs are supported for completion models.\n  };\n\n  private async getArgs({\n    prompt,\n    maxOutputTokens,\n    temperature,\n    topP,\n    topK,\n    frequencyPenalty,\n    presencePenalty,\n    stopSequences: userStopSequences,\n    responseFormat,\n    tools,\n    toolChoice,\n    seed,\n    providerOptions,\n  }: LanguageModelV3CallOptions) {\n    const warnings: SharedV3Warning[] = [];\n\n    // Parse provider options\n    const openaiOptions = {\n      ...(await parseProviderOptions({\n        provider: 'openai',\n        providerOptions,\n        schema: openaiLanguageModelCompletionOptions,\n      })),\n      ...(await parseProviderOptions({\n        provider: this.providerOptionsName,\n        providerOptions,\n        schema: openaiLanguageModelCompletionOptions,\n      })),\n    };\n\n    if (topK != null) {\n      warnings.push({ type: 'unsupported', feature: 'topK' });\n    }\n\n    if (tools?.length) {\n      warnings.push({ type: 'unsupported', feature: 'tools' });\n    }\n\n    if (toolChoice != null) {\n      warnings.push({ type: 'unsupported', feature: 'toolChoice' });\n    }\n\n    if (responseFormat != null && responseFormat.type !== 'text') {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'responseFormat',\n        details: 'JSON response format is not supported.',\n      });\n    }\n\n    const { prompt: completionPrompt, stopSequences } =\n      convertToOpenAICompletionPrompt({ prompt });\n\n    const stop = [...(stopSequences ?? []), ...(userStopSequences ?? [])];\n\n    return {\n      args: {\n        // model id:\n        model: this.modelId,\n\n        // model specific settings:\n        echo: openaiOptions.echo,\n        logit_bias: openaiOptions.logitBias,\n        logprobs:\n          openaiOptions?.logprobs === true\n            ? 0\n            : openaiOptions?.logprobs === false\n              ? undefined\n              : openaiOptions?.logprobs,\n        suffix: openaiOptions.suffix,\n        user: openaiOptions.user,\n\n        // standardized settings:\n        max_tokens: maxOutputTokens,\n        temperature,\n        top_p: topP,\n        frequency_penalty: frequencyPenalty,\n        presence_penalty: presencePenalty,\n        seed,\n\n        // prompt:\n        prompt: completionPrompt,\n\n        // stop sequences:\n        stop: stop.length > 0 ? stop : undefined,\n      },\n      warnings,\n    };\n  }\n\n  async doGenerate(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3GenerateResult> {\n    const { args, warnings } = await this.getArgs(options);\n\n    const {\n      responseHeaders,\n      value: response,\n      rawValue: rawResponse,\n    } = await postJsonToApi({\n      url: this.config.url({\n        path: '/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: args,\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiCompletionResponseSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const choice = response.choices[0];\n\n    const providerMetadata: SharedV3ProviderMetadata = { openai: {} };\n\n    if (choice.logprobs != null) {\n      providerMetadata.openai.logprobs = choice.logprobs;\n    }\n\n    return {\n      content: [{ type: 'text', text: choice.text }],\n      usage: convertOpenAICompletionUsage(response.usage),\n      finishReason: {\n        unified: mapOpenAIFinishReason(choice.finish_reason),\n        raw: choice.finish_reason ?? undefined,\n      },\n      request: { body: args },\n      response: {\n        ...getResponseMetadata(response),\n        headers: responseHeaders,\n        body: rawResponse,\n      },\n      providerMetadata,\n      warnings,\n    };\n  }\n\n  async doStream(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3StreamResult> {\n    const { args, warnings } = await this.getArgs(options);\n\n    const body = {\n      ...args,\n      stream: true,\n\n      stream_options: {\n        include_usage: true,\n      },\n    };\n\n    const { responseHeaders, value: response } = await postJsonToApi({\n      url: this.config.url({\n        path: '/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body,\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createEventSourceResponseHandler(\n        openaiCompletionChunkSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    let finishReason: LanguageModelV3FinishReason = {\n      unified: 'other',\n      raw: undefined,\n    };\n    const providerMetadata: SharedV3ProviderMetadata = { openai: {} };\n    let usage: OpenAICompletionUsage | undefined = undefined;\n    let isFirstChunk = true;\n\n    return {\n      stream: response.pipeThrough(\n        new TransformStream<\n          ParseResult<OpenAICompletionChunk>,\n          LanguageModelV3StreamPart\n        >({\n          start(controller) {\n            controller.enqueue({ type: 'stream-start', warnings });\n          },\n\n          transform(chunk, controller) {\n            if (options.includeRawChunks) {\n              controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n            }\n\n            // handle failed chunk parsing / validation:\n            if (!chunk.success) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({ type: 'error', error: chunk.error });\n              return;\n            }\n\n            const value = chunk.value;\n\n            // handle error chunks:\n            if ('error' in value) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({ type: 'error', error: value.error });\n              return;\n            }\n\n            if (isFirstChunk) {\n              isFirstChunk = false;\n\n              controller.enqueue({\n                type: 'response-metadata',\n                ...getResponseMetadata(value),\n              });\n\n              controller.enqueue({ type: 'text-start', id: '0' });\n            }\n\n            if (value.usage != null) {\n              usage = value.usage;\n            }\n\n            const choice = value.choices[0];\n\n            if (choice?.finish_reason != null) {\n              finishReason = {\n                unified: mapOpenAIFinishReason(choice.finish_reason),\n                raw: choice.finish_reason,\n              };\n            }\n\n            if (choice?.logprobs != null) {\n              providerMetadata.openai.logprobs = choice.logprobs;\n            }\n\n            if (choice?.text != null && choice.text.length > 0) {\n              controller.enqueue({\n                type: 'text-delta',\n                id: '0',\n                delta: choice.text,\n              });\n            }\n          },\n\n          flush(controller) {\n            if (!isFirstChunk) {\n              controller.enqueue({ type: 'text-end', id: '0' });\n            }\n\n            controller.enqueue({\n              type: 'finish',\n              finishReason,\n              providerMetadata,\n              usage: convertOpenAICompletionUsage(usage),\n            });\n          },\n        }),\n      ),\n      request: { body },\n      response: { headers: responseHeaders },\n    };\n  }\n}\n", "import { LanguageModelV3Usage } from '@ai-sdk/provider';\n\nexport type OpenAICompletionUsage = {\n  prompt_tokens?: number | null;\n  completion_tokens?: number | null;\n  total_tokens?: number | null;\n};\n\nexport function convertOpenAICompletionUsage(\n  usage: OpenAICompletionUsage | undefined | null,\n): LanguageModelV3Usage {\n  if (usage == null) {\n    return {\n      inputTokens: {\n        total: undefined,\n        noCache: undefined,\n        cacheRead: undefined,\n        cacheWrite: undefined,\n      },\n      outputTokens: {\n        total: undefined,\n        text: undefined,\n        reasoning: undefined,\n      },\n      raw: undefined,\n    };\n  }\n\n  const promptTokens = usage.prompt_tokens ?? 0;\n  const completionTokens = usage.completion_tokens ?? 0;\n\n  return {\n    inputTokens: {\n      total: usage.prompt_tokens ?? undefined,\n      noCache: promptTokens,\n      cacheRead: undefined,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: usage.completion_tokens ?? undefined,\n      text: completionTokens,\n      reasoning: undefined,\n    },\n    raw: usage,\n  };\n}\n", "import {\n  InvalidPromptError,\n  LanguageModelV3Prompt,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\n\nexport function convertToOpenAICompletionPrompt({\n  prompt,\n  user = 'user',\n  assistant = 'assistant',\n}: {\n  prompt: LanguageModelV3Prompt;\n  user?: string;\n  assistant?: string;\n}): {\n  prompt: string;\n  stopSequences?: string[];\n} {\n  // transform to a chat message format:\n  let text = '';\n\n  // if first message is a system message, add it to the text:\n  if (prompt[0].role === 'system') {\n    text += `${prompt[0].content}\\n\\n`;\n    prompt = prompt.slice(1);\n  }\n\n  for (const { role, content } of prompt) {\n    switch (role) {\n      case 'system': {\n        throw new InvalidPromptError({\n          message: 'Unexpected system message in prompt: ${content}',\n          prompt,\n        });\n      }\n\n      case 'user': {\n        const userMessage = content\n          .map(part => {\n            switch (part.type) {\n              case 'text': {\n                return part.text;\n              }\n            }\n          })\n          .filter(Boolean)\n          .join('');\n\n        text += `${user}:\\n${userMessage}\\n\\n`;\n        break;\n      }\n\n      case 'assistant': {\n        const assistantMessage = content\n          .map(part => {\n            switch (part.type) {\n              case 'text': {\n                return part.text;\n              }\n              case 'tool-call': {\n                throw new UnsupportedFunctionalityError({\n                  functionality: 'tool-call messages',\n                });\n              }\n            }\n          })\n          .join('');\n\n        text += `${assistant}:\\n${assistantMessage}\\n\\n`;\n        break;\n      }\n\n      case 'tool': {\n        throw new UnsupportedFunctionalityError({\n          functionality: 'tool messages',\n        });\n      }\n\n      default: {\n        const _exhaustiveCheck: never = role;\n        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n      }\n    }\n  }\n\n  // Assistant message prefix:\n  text += `${assistant}:\\n`;\n\n  return {\n    prompt: text,\n    stopSequences: [`\\n${user}:`],\n  };\n}\n", "export function getResponseMetadata({\n  id,\n  model,\n  created,\n}: {\n  id?: string | undefined | null;\n  created?: number | undefined | null;\n  model?: string | undefined | null;\n}) {\n  return {\n    id: id ?? undefined,\n    modelId: model ?? undefined,\n    timestamp: created != null ? new Date(created * 1000) : undefined,\n  };\n}\n", "import { LanguageModelV3FinishReason } from '@ai-sdk/provider';\n\nexport function mapOpenAIFinishReason(\n  finishReason: string | null | undefined,\n): LanguageModelV3FinishReason['unified'] {\n  switch (finishReason) {\n    case 'stop':\n      return 'stop';\n    case 'length':\n      return 'length';\n    case 'content_filter':\n      return 'content-filter';\n    case 'function_call':\n    case 'tool_calls':\n      return 'tool-calls';\n    default:\n      return 'other';\n  }\n}\n", "import { z } from 'zod/v4';\nimport { openaiErrorDataSchema } from '../openai-error';\nimport { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const openaiCompletionResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      id: z.string().nullish(),\n      created: z.number().nullish(),\n      model: z.string().nullish(),\n      choices: z.array(\n        z.object({\n          text: z.string(),\n          finish_reason: z.string(),\n          logprobs: z\n            .object({\n              tokens: z.array(z.string()),\n              token_logprobs: z.array(z.number()),\n              top_logprobs: z.array(z.record(z.string(), z.number())).nullish(),\n            })\n            .nullish(),\n        }),\n      ),\n      usage: z\n        .object({\n          prompt_tokens: z.number(),\n          completion_tokens: z.number(),\n          total_tokens: z.number(),\n        })\n        .nullish(),\n    }),\n  ),\n);\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const openaiCompletionChunkSchema = lazySchema(() =>\n  zodSchema(\n    z.union([\n      z.object({\n        id: z.string().nullish(),\n        created: z.number().nullish(),\n        model: z.string().nullish(),\n        choices: z.array(\n          z.object({\n            text: z.string(),\n            finish_reason: z.string().nullish(),\n            index: z.number(),\n            logprobs: z\n              .object({\n                tokens: z.array(z.string()),\n                token_logprobs: z.array(z.number()),\n                top_logprobs: z\n                  .array(z.record(z.string(), z.number()))\n                  .nullish(),\n              })\n              .nullish(),\n          }),\n        ),\n        usage: z\n          .object({\n            prompt_tokens: z.number(),\n            completion_tokens: z.number(),\n            total_tokens: z.number(),\n          })\n          .nullish(),\n      }),\n      openaiErrorDataSchema,\n    ]),\n  ),\n);\n\nexport type OpenAICompletionChunk = InferSchema<\n  typeof openaiCompletionChunkSchema\n>;\n\nexport type OpenAICompletionResponse = InferSchema<\n  typeof openaiCompletionResponseSchema\n>;\n", "import { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://platform.openai.com/docs/models\nexport type OpenAICompletionModelId =\n  | 'gpt-3.5-turbo-instruct'\n  | 'gpt-3.5-turbo-instruct-0914'\n  | (string & {});\n\nexport const openaiLanguageModelCompletionOptions = lazySchema(() =>\n  zodSchema(\n    z.object({\n      /**\n       * Echo back the prompt in addition to the completion.\n       */\n      echo: z.boolean().optional(),\n\n      /**\n       * Modify the likelihood of specified tokens appearing in the completion.\n       *\n       * Accepts a JSON object that maps tokens (specified by their token ID in\n       * the GPT tokenizer) to an associated bias value from -100 to 100. You\n       * can use this tokenizer tool to convert text to token IDs. Mathematically,\n       * the bias is added to the logits generated by the model prior to sampling.\n       * The exact effect will vary per model, but values between -1 and 1 should\n       * decrease or increase likelihood of selection; values like -100 or 100\n       * should result in a ban or exclusive selection of the relevant token.\n       *\n       * As an example, you can pass {\"50256\": -100} to prevent the <|endoftext|>\n       * token from being generated.\n       */\n      logitBias: z.record(z.string(), z.number()).optional(),\n\n      /**\n       * The suffix that comes after a completion of inserted text.\n       */\n      suffix: z.string().optional(),\n\n      /**\n       * A unique identifier representing your end-user, which can help OpenAI to\n       * monitor and detect abuse. Learn more.\n       */\n      user: z.string().optional(),\n\n      /**\n       * Return the log probabilities of the tokens. Including logprobs will increase\n       * the response size and can slow down response times. However, it can\n       * be useful to better understand how the model is behaving.\n       * Setting to true will return the log probabilities of the tokens that\n       * were generated.\n       * Setting to a number will return the log probabilities of the top n\n       * tokens that were generated.\n       */\n      logprobs: z.union([z.boolean(), z.number()]).optional(),\n    }),\n  ),\n);\n\nexport type OpenAILanguageModelCompletionOptions = InferSchema<\n  typeof openaiLanguageModelCompletionOptions\n>;\n", "import {\n  EmbeddingModelV3,\n  TooManyEmbeddingValuesForCallError,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createJsonResponseHandler,\n  parseProviderOptions,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { OpenAIConfig } from '../openai-config';\nimport { openaiFailedResponseHandler } from '../openai-error';\nimport {\n  OpenAIEmbeddingModelId,\n  openaiEmbeddingModelOptions,\n} from './openai-embedding-options';\nimport { openaiTextEmbeddingResponseSchema } from './openai-embedding-api';\n\nexport class OpenAIEmbeddingModel implements EmbeddingModelV3 {\n  readonly specificationVersion = 'v3';\n  readonly modelId: OpenAIEmbeddingModelId;\n  readonly maxEmbeddingsPerCall = 2048;\n  readonly supportsParallelCalls = true;\n\n  private readonly config: OpenAIConfig;\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  constructor(modelId: OpenAIEmbeddingModelId, config: OpenAIConfig) {\n    this.modelId = modelId;\n    this.config = config;\n  }\n\n  async doEmbed({\n    values,\n    headers,\n    abortSignal,\n    providerOptions,\n  }: Parameters<EmbeddingModelV3['doEmbed']>[0]): Promise<\n    Awaited<ReturnType<EmbeddingModelV3['doEmbed']>>\n  > {\n    if (values.length > this.maxEmbeddingsPerCall) {\n      throw new TooManyEmbeddingValuesForCallError({\n        provider: this.provider,\n        modelId: this.modelId,\n        maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n        values,\n      });\n    }\n\n    // Parse provider options\n    const openaiOptions =\n      (await parseProviderOptions({\n        provider: 'openai',\n        providerOptions,\n        schema: openaiEmbeddingModelOptions,\n      })) ?? {};\n\n    const {\n      responseHeaders,\n      value: response,\n      rawValue,\n    } = await postJsonToApi({\n      url: this.config.url({\n        path: '/embeddings',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), headers),\n      body: {\n        model: this.modelId,\n        input: values,\n        encoding_format: 'float',\n        dimensions: openaiOptions.dimensions,\n        user: openaiOptions.user,\n      },\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiTextEmbeddingResponseSchema,\n      ),\n      abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    return {\n      warnings: [],\n      embeddings: response.data.map(item => item.embedding),\n      usage: response.usage\n        ? { tokens: response.usage.prompt_tokens }\n        : undefined,\n      response: { headers: responseHeaders, body: rawValue },\n    };\n  }\n}\n", "import { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport type OpenAIEmbeddingModelId =\n  | 'text-embedding-3-small'\n  | 'text-embedding-3-large'\n  | 'text-embedding-ada-002'\n  | (string & {});\n\nexport const openaiEmbeddingModelOptions = lazySchema(() =>\n  zodSchema(\n    z.object({\n      /**\n       * The number of dimensions the resulting output embeddings should have.\n       * Only supported in text-embedding-3 and later models.\n       */\n      dimensions: z.number().optional(),\n\n      /**\n       * A unique identifier representing your end-user, which can help OpenAI to\n       * monitor and detect abuse. Learn more.\n       */\n      user: z.string().optional(),\n    }),\n  ),\n);\n\nexport type OpenAIEmbeddingModelOptions = InferSchema<\n  typeof openaiEmbeddingModelOptions\n>;\n", "import { lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// minimal version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const openaiTextEmbeddingResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      data: z.array(z.object({ embedding: z.array(z.number()) })),\n      usage: z.object({ prompt_tokens: z.number() }).nullish(),\n    }),\n  ),\n);\n", "import {\n  ImageModelV3,\n  ImageModelV3File,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  convertBase64ToUint8Array,\n  convertToFormData,\n  createJsonResponseHandler,\n  downloadBlob,\n  postFormDataToApi,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { OpenAIConfig } from '../openai-config';\nimport { openaiFailedResponseHandler } from '../openai-error';\nimport { openaiImageResponseSchema } from './openai-image-api';\nimport {\n  OpenAIImageModelId,\n  hasDefaultResponseFormat,\n  modelMaxImagesPerCall,\n} from './openai-image-options';\n\ninterface OpenAIImageModelConfig extends OpenAIConfig {\n  _internal?: {\n    currentDate?: () => Date;\n  };\n}\n\nexport class OpenAIImageModel implements ImageModelV3 {\n  readonly specificationVersion = 'v3';\n\n  get maxImagesPerCall(): number {\n    return modelMaxImagesPerCall[this.modelId] ?? 1;\n  }\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  constructor(\n    readonly modelId: OpenAIImageModelId,\n    private readonly config: OpenAIImageModelConfig,\n  ) {}\n\n  async doGenerate({\n    prompt,\n    files,\n    mask,\n    n,\n    size,\n    aspectRatio,\n    seed,\n    providerOptions,\n    headers,\n    abortSignal,\n  }: Parameters<ImageModelV3['doGenerate']>[0]): Promise<\n    Awaited<ReturnType<ImageModelV3['doGenerate']>>\n  > {\n    const warnings: Array<SharedV3Warning> = [];\n\n    if (aspectRatio != null) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'aspectRatio',\n        details:\n          'This model does not support aspect ratio. Use `size` instead.',\n      });\n    }\n\n    if (seed != null) {\n      warnings.push({ type: 'unsupported', feature: 'seed' });\n    }\n\n    const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n\n    if (files != null) {\n      const { value: response, responseHeaders } = await postFormDataToApi({\n        url: this.config.url({\n          path: '/images/edits',\n          modelId: this.modelId,\n        }),\n        headers: combineHeaders(this.config.headers(), headers),\n        formData: convertToFormData<OpenAIImageEditInput>({\n          model: this.modelId,\n          prompt,\n          image: await Promise.all(\n            files.map(file =>\n              file.type === 'file'\n                ? new Blob(\n                    [\n                      file.data instanceof Uint8Array\n                        ? new Blob([file.data as BlobPart], {\n                            type: file.mediaType,\n                          })\n                        : new Blob([convertBase64ToUint8Array(file.data)], {\n                            type: file.mediaType,\n                          }),\n                    ],\n                    { type: file.mediaType },\n                  )\n                : downloadBlob(file.url),\n            ),\n          ),\n          mask: mask != null ? await fileToBlob(mask) : undefined,\n          n,\n          size,\n          ...(providerOptions.openai ?? {}),\n        }),\n        failedResponseHandler: openaiFailedResponseHandler,\n        successfulResponseHandler: createJsonResponseHandler(\n          openaiImageResponseSchema,\n        ),\n        abortSignal,\n        fetch: this.config.fetch,\n      });\n\n      return {\n        images: response.data.map(item => item.b64_json),\n        warnings,\n        usage:\n          response.usage != null\n            ? {\n                inputTokens: response.usage.input_tokens ?? undefined,\n                outputTokens: response.usage.output_tokens ?? undefined,\n                totalTokens: response.usage.total_tokens ?? undefined,\n              }\n            : undefined,\n        response: {\n          timestamp: currentDate,\n          modelId: this.modelId,\n          headers: responseHeaders,\n        },\n        providerMetadata: {\n          openai: {\n            images: response.data.map((item, index) => ({\n              ...(item.revised_prompt\n                ? { revisedPrompt: item.revised_prompt }\n                : {}),\n              created: response.created ?? undefined,\n              size: response.size ?? undefined,\n              quality: response.quality ?? undefined,\n              background: response.background ?? undefined,\n              outputFormat: response.output_format ?? undefined,\n              ...distributeTokenDetails(\n                response.usage?.input_tokens_details,\n                index,\n                response.data.length,\n              ),\n            })),\n          },\n        },\n      };\n    }\n\n    const { value: response, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/images/generations',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), headers),\n      body: {\n        model: this.modelId,\n        prompt,\n        n,\n        size,\n        ...(providerOptions.openai ?? {}),\n        ...(!hasDefaultResponseFormat(this.modelId)\n          ? { response_format: 'b64_json' }\n          : {}),\n      },\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiImageResponseSchema,\n      ),\n      abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    return {\n      images: response.data.map(item => item.b64_json),\n      warnings,\n      usage:\n        response.usage != null\n          ? {\n              inputTokens: response.usage.input_tokens ?? undefined,\n              outputTokens: response.usage.output_tokens ?? undefined,\n              totalTokens: response.usage.total_tokens ?? undefined,\n            }\n          : undefined,\n      response: {\n        timestamp: currentDate,\n        modelId: this.modelId,\n        headers: responseHeaders,\n      },\n      providerMetadata: {\n        openai: {\n          images: response.data.map((item, index) => ({\n            ...(item.revised_prompt\n              ? { revisedPrompt: item.revised_prompt }\n              : {}),\n            created: response.created ?? undefined,\n            size: response.size ?? undefined,\n            quality: response.quality ?? undefined,\n            background: response.background ?? undefined,\n            outputFormat: response.output_format ?? undefined,\n            ...distributeTokenDetails(\n              response.usage?.input_tokens_details,\n              index,\n              response.data.length,\n            ),\n          })),\n        },\n      },\n    };\n  }\n}\n\n/**\n * Distributes input token details evenly across images, with the remainder\n * assigned to the last image so that summing across all entries gives the\n * exact total.\n */\nfunction distributeTokenDetails(\n  details:\n    | { image_tokens?: number | null; text_tokens?: number | null }\n    | null\n    | undefined,\n  index: number,\n  total: number,\n): { imageTokens?: number; textTokens?: number } {\n  if (details == null) {\n    return {};\n  }\n\n  const result: { imageTokens?: number; textTokens?: number } = {};\n\n  if (details.image_tokens != null) {\n    const base = Math.floor(details.image_tokens / total);\n    const remainder = details.image_tokens - base * (total - 1);\n    result.imageTokens = index === total - 1 ? remainder : base;\n  }\n\n  if (details.text_tokens != null) {\n    const base = Math.floor(details.text_tokens / total);\n    const remainder = details.text_tokens - base * (total - 1);\n    result.textTokens = index === total - 1 ? remainder : base;\n  }\n\n  return result;\n}\n\ntype OpenAIImageEditInput = {\n  /**\n   * Allows to set transparency for the background of the generated image(s).\n   * This parameter is only supported for `gpt-image-1`. Must be one of\n   * `transparent`, `opaque` or `auto` (default value). When `auto` is used, the\n   * model will automatically determine the best background for the image.\n   *\n   * If `transparent`, the output format needs to support transparency, so it\n   * should be set to either `png` (default value) or `webp`.\n   *\n   */\n  background?: 'transparent' | 'opaque' | 'auto';\n  /**\n   * The image(s) to edit. Must be a supported image file or an array of images.\n   *\n   * For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less\n   * than 50MB. You can provide up to 16 images.\n   *\n   * For `dall-e-2`, you can only provide one image, and it should be a square\n   * `png` file less than 4MB.\n   *\n   */\n  image: Blob | Blob[];\n  input_fidelity?: ('high' | 'low') | null;\n  /**\n   * An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`.\n   */\n  mask?: Blob;\n  /**\n   * The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used.\n   */\n  model?: 'dall-e-2' | 'gpt-image-1' | 'gpt-image-1-mini' | (string & {});\n  /**\n   * The number of images to generate. Must be between 1 and 10.\n   */\n  n?: number;\n  /**\n   * The compression level (0-100%) for the generated images. This parameter\n   * is only supported for `gpt-image-1` with the `webp` or `jpeg` output\n   * formats, and defaults to 100.\n   *\n   */\n  output_compression?: number;\n  /**\n   * The format in which the generated images are returned. This parameter is\n   * only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\n   * The default value is `png`.\n   *\n   */\n  output_format?: 'png' | 'jpeg' | 'webp';\n  partial_images?: number | null;\n  /**\n   * A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`.\n   */\n  prompt?: string;\n  /**\n   * The quality of the image that will be generated. `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`.\n   *\n   */\n  quality?: 'standard' | 'low' | 'medium' | 'high' | 'auto';\n  /**\n   * The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images.\n   */\n  response_format?: 'url' | 'b64_json';\n  /**\n   * The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`.\n   */\n  size?: `${number}x${number}`;\n  /**\n   * Edit the image in streaming mode. Defaults to `false`. See the\n   * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\n   *\n   */\n  stream?: boolean;\n  /**\n   * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n   *\n   */\n  user?: string;\n};\n\nasync function fileToBlob(\n  file: ImageModelV3File | undefined,\n): Promise<Blob | undefined> {\n  if (!file) return undefined;\n\n  if (file.type === 'url') {\n    return downloadBlob(file.url);\n  }\n\n  const data =\n    file.data instanceof Uint8Array\n      ? file.data\n      : convertBase64ToUint8Array(file.data);\n\n  return new Blob([data as BlobPart], { type: file.mediaType });\n}\n", "import { lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// minimal version of the schema, focused on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const openaiImageResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      created: z.number().nullish(),\n      data: z.array(\n        z.object({\n          b64_json: z.string(),\n          revised_prompt: z.string().nullish(),\n        }),\n      ),\n      background: z.string().nullish(),\n      output_format: z.string().nullish(),\n      size: z.string().nullish(),\n      quality: z.string().nullish(),\n      usage: z\n        .object({\n          input_tokens: z.number().nullish(),\n          output_tokens: z.number().nullish(),\n          total_tokens: z.number().nullish(),\n          input_tokens_details: z\n            .object({\n              image_tokens: z.number().nullish(),\n              text_tokens: z.number().nullish(),\n            })\n            .nullish(),\n        })\n        .nullish(),\n    }),\n  ),\n);\n", "export type OpenAIImageModelId =\n  | 'dall-e-3'\n  | 'dall-e-2'\n  | 'gpt-image-1'\n  | 'gpt-image-1-mini'\n  | 'gpt-image-1.5'\n  | 'chatgpt-image-latest'\n  | (string & {});\n\n// https://platform.openai.com/docs/guides/images\nexport const modelMaxImagesPerCall: Record<OpenAIImageModelId, number> = {\n  'dall-e-3': 1,\n  'dall-e-2': 10,\n  'gpt-image-1': 10,\n  'gpt-image-1-mini': 10,\n  'gpt-image-1.5': 10,\n  'chatgpt-image-latest': 10,\n};\n\nconst defaultResponseFormatPrefixes = [\n  'chatgpt-image-',\n  'gpt-image-1-mini',\n  'gpt-image-1.5',\n  'gpt-image-1',\n];\n\nexport function hasDefaultResponseFormat(modelId: string): boolean {\n  return defaultResponseFormatPrefixes.some(prefix =>\n    modelId.startsWith(prefix),\n  );\n}\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n/**\n * Schema for the apply_patch input - what the model sends.\n *\n * Refer the official spec here: https://platform.openai.com/docs/api-reference/responses/create#responses_create-input-input_item_list-item-apply_patch_tool_call\n *\n */\nexport const applyPatchInputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      callId: z.string(),\n      operation: z.discriminatedUnion('type', [\n        z.object({\n          type: z.literal('create_file'),\n          path: z.string(),\n          diff: z.string(),\n        }),\n        z.object({\n          type: z.literal('delete_file'),\n          path: z.string(),\n        }),\n        z.object({\n          type: z.literal('update_file'),\n          path: z.string(),\n          diff: z.string(),\n        }),\n      ]),\n    }),\n  ),\n);\n\n/**\n * Schema for the apply_patch output - what we send back.\n */\nexport const applyPatchOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      status: z.enum(['completed', 'failed']),\n      output: z.string().optional(),\n    }),\n  ),\n);\n\n/**\n * Schema for tool arguments (configuration options).\n * The apply_patch tool doesn't require any configuration options.\n */\nexport const applyPatchArgsSchema = lazySchema(() => zodSchema(z.object({})));\n\n/**\n * Type definitions for the apply_patch operations.\n */\nexport type ApplyPatchOperation =\n  | {\n      type: 'create_file';\n      /**\n       * Path of the file to create relative to the workspace root.\n       */\n      path: string;\n      /**\n       * Unified diff content to apply when creating the file.\n       */\n      diff: string;\n    }\n  | {\n      type: 'delete_file';\n      /**\n       * Path of the file to delete relative to the workspace root.\n       */\n      path: string;\n    }\n  | {\n      type: 'update_file';\n      /**\n       * Path of the file to update relative to the workspace root.\n       */\n      path: string;\n      /**\n       * Unified diff content to apply to the existing file.\n       */\n      diff: string;\n    };\n\n/**\n * The apply_patch tool lets GPT-5.1 create, update, and delete files in your\n * codebase using structured diffs. Instead of just suggesting edits, the model\n * emits patch operations that your application applies and then reports back on,\n * enabling iterative, multi-step code editing workflows.\n *\n * The tool factory creates a provider-defined tool that:\n * - Receives patch operations from the model (create_file, update_file, delete_file)\n * - Returns the status of applying those patches (completed or failed)\n *\n */\nexport const applyPatchToolFactory = createProviderToolFactoryWithOutputSchema<\n  {\n    /**\n     * The unique ID of the apply patch tool call generated by the model.\n     */\n    callId: string;\n\n    /**\n     * The specific create, delete, or update instruction for the apply_patch tool call.\n     */\n    operation: ApplyPatchOperation;\n  },\n  {\n    /**\n     * The status of the apply patch tool call output.\n     * - 'completed': The patch was applied successfully.\n     * - 'failed': The patch failed to apply.\n     */\n    status: 'completed' | 'failed';\n\n    /**\n     * Optional human-readable log text from the apply patch tool\n     * (e.g., patch results or errors).\n     */\n    output?: string;\n  },\n  // No configuration options for apply_patch\n  {}\n>({\n  id: 'openai.apply_patch',\n  inputSchema: applyPatchInputSchema,\n  outputSchema: applyPatchOutputSchema,\n});\n\n/**\n * The apply_patch tool lets GPT-5.1 create, update, and delete files in your\n * codebase using structured diffs. Instead of just suggesting edits, the model\n * emits patch operations that your application applies and then reports back on,\n * enabling iterative, multi-step code editing workflows.\n */\nexport const applyPatch = applyPatchToolFactory;\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const codeInterpreterInputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      code: z.string().nullish(),\n      containerId: z.string(),\n    }),\n  ),\n);\n\nexport const codeInterpreterOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      outputs: z\n        .array(\n          z.discriminatedUnion('type', [\n            z.object({ type: z.literal('logs'), logs: z.string() }),\n            z.object({ type: z.literal('image'), url: z.string() }),\n          ]),\n        )\n        .nullish(),\n    }),\n  ),\n);\n\nexport const codeInterpreterArgsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      container: z\n        .union([\n          z.string(),\n          z.object({\n            fileIds: z.array(z.string()).optional(),\n          }),\n        ])\n        .optional(),\n    }),\n  ),\n);\n\ntype CodeInterpreterArgs = {\n  /**\n   * The code interpreter container.\n   * Can be a container ID\n   * or an object that specifies uploaded file IDs to make available to your code.\n   */\n  container?: string | { fileIds?: string[] };\n};\n\nexport const codeInterpreterToolFactory =\n  createProviderToolFactoryWithOutputSchema<\n    {\n      /**\n       * The code to run, or null if not available.\n       */\n      code?: string | null;\n\n      /**\n       * The ID of the container used to run the code.\n       */\n      containerId: string;\n    },\n    {\n      /**\n       * The outputs generated by the code interpreter, such as logs or images.\n       * Can be null if no outputs are available.\n       */\n      outputs?: Array<\n        | {\n            type: 'logs';\n\n            /**\n             * The logs output from the code interpreter.\n             */\n            logs: string;\n          }\n        | {\n            type: 'image';\n\n            /**\n             * The URL of the image output from the code interpreter.\n             */\n            url: string;\n          }\n      > | null;\n    },\n    CodeInterpreterArgs\n  >({\n    id: 'openai.code_interpreter',\n    inputSchema: codeInterpreterInputSchema,\n    outputSchema: codeInterpreterOutputSchema,\n  });\n\nexport const codeInterpreter = (\n  args: CodeInterpreterArgs = {}, // default\n) => {\n  return codeInterpreterToolFactory(args);\n};\n", "import {\n  createProviderToolFactory,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const customArgsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      name: z.string(),\n      description: z.string().optional(),\n      format: z\n        .union([\n          z.object({\n            type: z.literal('grammar'),\n            syntax: z.enum(['regex', 'lark']),\n            definition: z.string(),\n          }),\n          z.object({\n            type: z.literal('text'),\n          }),\n        ])\n        .optional(),\n    }),\n  ),\n);\n\nconst customInputSchema = lazySchema(() => zodSchema(z.string()));\n\nexport const customToolFactory = createProviderToolFactory<\n  string,\n  {\n    /**\n     * The name of the custom tool, used to identify it in the API.\n     */\n    name: string;\n\n    /**\n     * An optional description of what the tool does.\n     */\n    description?: string;\n\n    /**\n     * The output format specification for the tool.\n     * Omit for unconstrained text output.\n     */\n    format?:\n      | {\n          type: 'grammar';\n          syntax: 'regex' | 'lark';\n          definition: string;\n        }\n      | {\n          type: 'text';\n        };\n  }\n>({\n  id: 'openai.custom',\n  inputSchema: customInputSchema,\n});\n\nexport const customTool = (args: Parameters<typeof customToolFactory>[0]) =>\n  customToolFactory(args);\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport {\n  OpenAIResponsesFileSearchToolComparisonFilter,\n  OpenAIResponsesFileSearchToolCompoundFilter,\n} from '../responses/openai-responses-api';\n\nconst comparisonFilterSchema = z.object({\n  key: z.string(),\n  type: z.enum(['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'in', 'nin']),\n  value: z.union([z.string(), z.number(), z.boolean(), z.array(z.string())]),\n});\n\nconst compoundFilterSchema: z.ZodType<any> = z.object({\n  type: z.enum(['and', 'or']),\n  filters: z.array(\n    z.union([comparisonFilterSchema, z.lazy(() => compoundFilterSchema)]),\n  ),\n});\n\nexport const fileSearchArgsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      vectorStoreIds: z.array(z.string()),\n      maxNumResults: z.number().optional(),\n      ranking: z\n        .object({\n          ranker: z.string().optional(),\n          scoreThreshold: z.number().optional(),\n        })\n        .optional(),\n      filters: z\n        .union([comparisonFilterSchema, compoundFilterSchema])\n        .optional(),\n    }),\n  ),\n);\n\nexport const fileSearchOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      queries: z.array(z.string()),\n      results: z\n        .array(\n          z.object({\n            attributes: z.record(z.string(), z.unknown()),\n            fileId: z.string(),\n            filename: z.string(),\n            score: z.number(),\n            text: z.string(),\n          }),\n        )\n        .nullable(),\n    }),\n  ),\n);\n\nexport const fileSearch = createProviderToolFactoryWithOutputSchema<\n  {},\n  {\n    /**\n     * The search query to execute.\n     */\n    queries: string[];\n\n    /**\n     * The results of the file search tool call.\n     */\n    results:\n      | null\n      | {\n          /**\n           * Set of 16 key-value pairs that can be attached to an object.\n           * This can be useful for storing additional information about the object\n           * in a structured format, and querying for objects via API or the dashboard.\n           * Keys are strings with a maximum length of 64 characters.\n           * Values are strings with a maximum length of 512 characters, booleans, or numbers.\n           */\n          attributes: Record<string, unknown>;\n\n          /**\n           * The unique ID of the file.\n           */\n          fileId: string;\n\n          /**\n           * The name of the file.\n           */\n          filename: string;\n\n          /**\n           * The relevance score of the file - a value between 0 and 1.\n           */\n          score: number;\n\n          /**\n           * The text that was retrieved from the file.\n           */\n          text: string;\n        }[];\n  },\n  {\n    /**\n     * List of vector store IDs to search through.\n     */\n    vectorStoreIds: string[];\n\n    /**\n     * Maximum number of search results to return. Defaults to 10.\n     */\n    maxNumResults?: number;\n\n    /**\n     * Ranking options for the search.\n     */\n    ranking?: {\n      /**\n       * The ranker to use for the file search.\n       */\n      ranker?: string;\n\n      /**\n       * The score threshold for the file search, a number between 0 and 1.\n       * Numbers closer to 1 will attempt to return only the most relevant results,\n       * but may return fewer results.\n       */\n      scoreThreshold?: number;\n    };\n\n    /**\n     * A filter to apply.\n     */\n    filters?:\n      | OpenAIResponsesFileSearchToolComparisonFilter\n      | OpenAIResponsesFileSearchToolCompoundFilter;\n  }\n>({\n  id: 'openai.file_search',\n  inputSchema: z.object({}),\n  outputSchema: fileSearchOutputSchema,\n});\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const imageGenerationArgsSchema = lazySchema(() =>\n  zodSchema(\n    z\n      .object({\n        background: z.enum(['auto', 'opaque', 'transparent']).optional(),\n        inputFidelity: z.enum(['low', 'high']).optional(),\n        inputImageMask: z\n          .object({\n            fileId: z.string().optional(),\n            imageUrl: z.string().optional(),\n          })\n          .optional(),\n        model: z.string().optional(),\n        moderation: z.enum(['auto']).optional(),\n        outputCompression: z.number().int().min(0).max(100).optional(),\n        outputFormat: z.enum(['png', 'jpeg', 'webp']).optional(),\n        partialImages: z.number().int().min(0).max(3).optional(),\n        quality: z.enum(['auto', 'low', 'medium', 'high']).optional(),\n        size: z\n          .enum(['1024x1024', '1024x1536', '1536x1024', 'auto'])\n          .optional(),\n      })\n      .strict(),\n  ),\n);\n\nconst imageGenerationInputSchema = lazySchema(() => zodSchema(z.object({})));\n\nexport const imageGenerationOutputSchema = lazySchema(() =>\n  zodSchema(z.object({ result: z.string() })),\n);\n\ntype ImageGenerationArgs = {\n  /**\n   * Background type for the generated image. Default is 'auto'.\n   */\n  background?: 'auto' | 'opaque' | 'transparent';\n\n  /**\n   * Input fidelity for the generated image. Default is 'low'.\n   */\n  inputFidelity?: 'low' | 'high';\n\n  /**\n   * Optional mask for inpainting.\n   * Contains image_url (string, optional) and file_id (string, optional).\n   */\n  inputImageMask?: {\n    /**\n     * File ID for the mask image.\n     */\n    fileId?: string;\n\n    /**\n     * Base64-encoded mask image.\n     */\n    imageUrl?: string;\n  };\n\n  /**\n   * The image generation model to use. Default: gpt-image-1.\n   */\n  model?: string;\n\n  /**\n   * Moderation level for the generated image. Default: auto.\n   */\n  moderation?: 'auto';\n\n  /**\n   * Compression level for the output image. Default: 100.\n   */\n  outputCompression?: number;\n\n  /**\n   * The output format of the generated image. One of png, webp, or jpeg.\n   * Default: png\n   */\n  outputFormat?: 'png' | 'jpeg' | 'webp';\n\n  /**\n   * Number of partial images to generate in streaming mode, from 0 (default value) to 3.\n   */\n  partialImages?: number;\n\n  /**\n   * The quality of the generated image.\n   * One of low, medium, high, or auto. Default: auto.\n   */\n  quality?: 'auto' | 'low' | 'medium' | 'high';\n\n  /**\n   * The size of the generated image.\n   * One of 1024x1024, 1024x1536, 1536x1024, or auto.\n   * Default: auto.\n   */\n  size?: 'auto' | '1024x1024' | '1024x1536' | '1536x1024';\n};\n\nconst imageGenerationToolFactory = createProviderToolFactoryWithOutputSchema<\n  {},\n  {\n    /**\n     * The generated image encoded in base64.\n     */\n    result: string;\n  },\n  ImageGenerationArgs\n>({\n  id: 'openai.image_generation',\n  inputSchema: imageGenerationInputSchema,\n  outputSchema: imageGenerationOutputSchema,\n});\n\nexport const imageGeneration = (\n  args: ImageGenerationArgs = {}, // default\n) => {\n  return imageGenerationToolFactory(args);\n};\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const localShellInputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      action: z.object({\n        type: z.literal('exec'),\n        command: z.array(z.string()),\n        timeoutMs: z.number().optional(),\n        user: z.string().optional(),\n        workingDirectory: z.string().optional(),\n        env: z.record(z.string(), z.string()).optional(),\n      }),\n    }),\n  ),\n);\n\nexport const localShellOutputSchema = lazySchema(() =>\n  zodSchema(z.object({ output: z.string() })),\n);\n\nexport const localShell = createProviderToolFactoryWithOutputSchema<\n  {\n    /**\n     * Execute a shell command on the server.\n     */\n    action: {\n      type: 'exec';\n\n      /**\n       * The command to run.\n       */\n      command: string[];\n\n      /**\n       * Optional timeout in milliseconds for the command.\n       */\n      timeoutMs?: number;\n\n      /**\n       * Optional user to run the command as.\n       */\n      user?: string;\n\n      /**\n       * Optional working directory to run the command in.\n       */\n      workingDirectory?: string;\n\n      /**\n       * Environment variables to set for the command.\n       */\n      env?: Record<string, string>;\n    };\n  },\n  {\n    /**\n     * The output of local shell tool call.\n     */\n    output: string;\n  },\n  {}\n>({\n  id: 'openai.local_shell',\n  inputSchema: localShellInputSchema,\n  outputSchema: localShellOutputSchema,\n});\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const shellInputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      action: z.object({\n        commands: z.array(z.string()),\n        timeoutMs: z.number().optional(),\n        maxOutputLength: z.number().optional(),\n      }),\n    }),\n  ),\n);\n\nexport const shellOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      output: z.array(\n        z.object({\n          stdout: z.string(),\n          stderr: z.string(),\n          outcome: z.discriminatedUnion('type', [\n            z.object({ type: z.literal('timeout') }),\n            z.object({ type: z.literal('exit'), exitCode: z.number() }),\n          ]),\n        }),\n      ),\n    }),\n  ),\n);\n\nconst shellSkillsSchema = z\n  .array(\n    z.discriminatedUnion('type', [\n      z.object({\n        type: z.literal('skillReference'),\n        skillId: z.string(),\n        version: z.string().optional(),\n      }),\n      z.object({\n        type: z.literal('inline'),\n        name: z.string(),\n        description: z.string(),\n        source: z.object({\n          type: z.literal('base64'),\n          mediaType: z.literal('application/zip'),\n          data: z.string(),\n        }),\n      }),\n    ]),\n  )\n  .optional();\n\nexport const shellArgsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      environment: z\n        .union([\n          z.object({\n            type: z.literal('containerAuto'),\n            fileIds: z.array(z.string()).optional(),\n            memoryLimit: z.enum(['1g', '4g', '16g', '64g']).optional(),\n            networkPolicy: z\n              .discriminatedUnion('type', [\n                z.object({ type: z.literal('disabled') }),\n                z.object({\n                  type: z.literal('allowlist'),\n                  allowedDomains: z.array(z.string()),\n                  domainSecrets: z\n                    .array(\n                      z.object({\n                        domain: z.string(),\n                        name: z.string(),\n                        value: z.string(),\n                      }),\n                    )\n                    .optional(),\n                }),\n              ])\n              .optional(),\n            skills: shellSkillsSchema,\n          }),\n          z.object({\n            type: z.literal('containerReference'),\n            containerId: z.string(),\n          }),\n          z.object({\n            type: z.literal('local').optional(),\n            skills: z\n              .array(\n                z.object({\n                  name: z.string(),\n                  description: z.string(),\n                  path: z.string(),\n                }),\n              )\n              .optional(),\n          }),\n        ])\n        .optional(),\n    }),\n  ),\n);\n\ntype ShellArgs = {\n  environment?:\n    | {\n        type: 'containerAuto';\n        fileIds?: string[];\n        memoryLimit?: '1g' | '4g' | '16g' | '64g';\n        networkPolicy?:\n          | { type: 'disabled' }\n          | {\n              type: 'allowlist';\n              allowedDomains: string[];\n              domainSecrets?: Array<{\n                domain: string;\n                name: string;\n                value: string;\n              }>;\n            };\n        skills?: Array<\n          | { type: 'skillReference'; skillId: string; version?: string }\n          | {\n              type: 'inline';\n              name: string;\n              description: string;\n              source: {\n                type: 'base64';\n                mediaType: 'application/zip';\n                data: string;\n              };\n            }\n        >;\n      }\n    | {\n        type: 'containerReference';\n        containerId: string;\n      }\n    | {\n        type?: 'local';\n        skills?: Array<{\n          name: string;\n          description: string;\n          path: string;\n        }>;\n      };\n};\n\nexport const shell = createProviderToolFactoryWithOutputSchema<\n  {\n    /**\n     * Shell tool action containing commands to execute.\n     */\n    action: {\n      /**\n       * A list of shell commands to execute.\n       */\n      commands: string[];\n\n      /**\n       * Optional timeout in milliseconds for the commands.\n       */\n      timeoutMs?: number;\n\n      /**\n       * Optional maximum number of characters to return from each command.\n       */\n      maxOutputLength?: number;\n    };\n  },\n  {\n    /**\n     * An array of shell call output contents.\n     */\n    output: Array<{\n      /**\n       * Standard output from the command.\n       */\n      stdout: string;\n\n      /**\n       * Standard error from the command.\n       */\n      stderr: string;\n\n      /**\n       * The outcome of the shell execution - either timeout or exit with code.\n       */\n      outcome: { type: 'timeout' } | { type: 'exit'; exitCode: number };\n    }>;\n  },\n  ShellArgs\n>({\n  id: 'openai.shell',\n  inputSchema: shellInputSchema,\n  outputSchema: shellOutputSchema,\n});\n", "import { JSONObject } from '@ai-sdk/provider';\nimport {\n  createProviderToolFactoryWithOutputSchema,\n  FlexibleSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const toolSearchArgsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      execution: z.enum(['server', 'client']).optional(),\n      description: z.string().optional(),\n      parameters: z.record(z.string(), z.unknown()).optional(),\n    }),\n  ),\n);\n\nexport const toolSearchInputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      arguments: z.unknown().optional(),\n      call_id: z.string().nullish(),\n    }),\n  ),\n);\n\nexport const toolSearchOutputSchema: FlexibleSchema<{\n  tools: Array<JSONObject>;\n}> = lazySchema(() =>\n  zodSchema(\n    z.object({\n      tools: z.array(z.record(z.string(), z.unknown())),\n    }),\n  ),\n) as FlexibleSchema<{ tools: Array<JSONObject> }>;\n\nconst toolSearchToolFactory = createProviderToolFactoryWithOutputSchema<\n  {\n    /**\n     * The arguments from the tool_search_call.\n     * This is preserved for multi-turn conversation reconstruction.\n     */\n    arguments?: unknown;\n\n    /**\n     * The call ID from the tool_search_call.\n     * Present for client-executed tool search; null for hosted.\n     */\n    call_id?: string | null;\n  },\n  {\n    /**\n     * The tools that were loaded by the tool search.\n     * These are the deferred tools that the model requested to load.\n     * Each tool is represented as a JSON object with properties depending on its type.\n     *\n     * Common properties include:\n     * - `type`: The type of the tool (e.g., 'function', 'web_search', etc.)\n     * - `name`: The name of the tool (for function tools)\n     * - `description`: A description of the tool\n     * - `deferLoading`: Whether this tool was deferred (had defer_loading: true)\n     * - `parameters`: The JSON Schema for the function parameters (for function tools)\n     * - `strict`: Whether to enable strict schema adherence (for function tools)\n     */\n    tools: Array<JSONObject>;\n  },\n  {\n    /**\n     * Whether the tool search is executed by the server (hosted) or client.\n     * - `'server'` (default): OpenAI performs the search across deferred tools.\n     * - `'client'`: The model emits a `tool_search_call` and your `execute`\n     *   function performs the lookup, returning the tools to load.\n     */\n    execution?: 'server' | 'client';\n\n    /**\n     * A description of the tool search capability.\n     * Only used for client-executed tool search.\n     */\n    description?: string;\n\n    /**\n     * JSON Schema for the search arguments your application expects.\n     * Only used for client-executed tool search.\n     */\n    parameters?: Record<string, unknown>;\n  }\n>({\n  id: 'openai.tool_search',\n  inputSchema: toolSearchInputSchema,\n  outputSchema: toolSearchOutputSchema,\n});\n\nexport const toolSearch = (\n  args: Parameters<typeof toolSearchToolFactory>[0] = {},\n) => toolSearchToolFactory(args);\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const webSearchArgsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      externalWebAccess: z.boolean().optional(),\n      filters: z\n        .object({ allowedDomains: z.array(z.string()).optional() })\n        .optional(),\n      searchContextSize: z.enum(['low', 'medium', 'high']).optional(),\n      userLocation: z\n        .object({\n          type: z.literal('approximate'),\n          country: z.string().optional(),\n          city: z.string().optional(),\n          region: z.string().optional(),\n          timezone: z.string().optional(),\n        })\n        .optional(),\n    }),\n  ),\n);\n\nconst webSearchInputSchema = lazySchema(() => zodSchema(z.object({})));\n\nexport const webSearchOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      action: z\n        .discriminatedUnion('type', [\n          z.object({\n            type: z.literal('search'),\n            query: z.string().optional(),\n          }),\n          z.object({\n            type: z.literal('openPage'),\n            url: z.string().nullish(),\n          }),\n          z.object({\n            type: z.literal('findInPage'),\n            url: z.string().nullish(),\n            pattern: z.string().nullish(),\n          }),\n        ])\n        .optional(),\n      sources: z\n        .array(\n          z.discriminatedUnion('type', [\n            z.object({ type: z.literal('url'), url: z.string() }),\n            z.object({ type: z.literal('api'), name: z.string() }),\n          ]),\n        )\n        .optional(),\n    }),\n  ),\n);\n\nexport const webSearchToolFactory = createProviderToolFactoryWithOutputSchema<\n  {\n    // Web search doesn't take input parameters - it's controlled by the prompt\n  },\n  {\n    /**\n     * An object describing the specific action taken in this web search call.\n     * Includes details on how the model used the web (search, open_page, find_in_page).\n     */\n    action?:\n      | {\n          /**\n           * Action type \"search\" - Performs a web search query.\n           */\n          type: 'search';\n\n          /**\n           * The search query.\n           */\n          query?: string;\n        }\n      | {\n          /**\n           * Action type \"openPage\" - Opens a specific URL from search results.\n           */\n          type: 'openPage';\n\n          /**\n           * The URL opened by the model.\n           */\n          url?: string | null;\n        }\n      | {\n          /**\n           * Action type \"findInPage\": Searches for a pattern within a loaded page.\n           */\n          type: 'findInPage';\n\n          /**\n           * The URL of the page searched for the pattern.\n           */\n          url?: string | null;\n\n          /**\n           * The pattern or text to search for within the page.\n           */\n          pattern?: string | null;\n        };\n\n    /**\n     * Optional sources cited by the model for the web search call.\n     */\n    sources?: Array<\n      { type: 'url'; url: string } | { type: 'api'; name: string }\n    >;\n  },\n  {\n    /**\n     * Whether to use external web access for fetching live content.\n     * - true: Fetch live web content (default)\n     * - false: Use cached/indexed results\n     */\n    externalWebAccess?: boolean;\n\n    /**\n     * Filters for the search.\n     */\n    filters?: {\n      /**\n       * Allowed domains for the search.\n       * If not provided, all domains are allowed.\n       * Subdomains of the provided domains are allowed as well.\n       */\n      allowedDomains?: string[];\n    };\n\n    /**\n     * Search context size to use for the web search.\n     * - high: Most comprehensive context, highest cost, slower response\n     * - medium: Balanced context, cost, and latency (default)\n     * - low: Least context, lowest cost, fastest response\n     */\n    searchContextSize?: 'low' | 'medium' | 'high';\n\n    /**\n     * User location information to provide geographically relevant search results.\n     */\n    userLocation?: {\n      /**\n       * Type of location (always 'approximate')\n       */\n      type: 'approximate';\n      /**\n       * Two-letter ISO country code (e.g., 'US', 'GB')\n       */\n      country?: string;\n      /**\n       * City name (free text, e.g., 'Minneapolis')\n       */\n      city?: string;\n      /**\n       * Region name (free text, e.g., 'Minnesota')\n       */\n      region?: string;\n      /**\n       * IANA timezone (e.g., 'America/Chicago')\n       */\n      timezone?: string;\n    };\n  }\n>({\n  id: 'openai.web_search',\n  inputSchema: webSearchInputSchema,\n  outputSchema: webSearchOutputSchema,\n});\n\nexport const webSearch = (\n  args: Parameters<typeof webSearchToolFactory>[0] = {}, // default\n) => webSearchToolFactory(args);\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const webSearchPreviewArgsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      searchContextSize: z.enum(['low', 'medium', 'high']).optional(),\n      userLocation: z\n        .object({\n          type: z.literal('approximate'),\n          country: z.string().optional(),\n          city: z.string().optional(),\n          region: z.string().optional(),\n          timezone: z.string().optional(),\n        })\n        .optional(),\n    }),\n  ),\n);\n\nexport const webSearchPreviewInputSchema = lazySchema(() =>\n  zodSchema(z.object({})),\n);\n\nconst webSearchPreviewOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      action: z\n        .discriminatedUnion('type', [\n          z.object({\n            type: z.literal('search'),\n            query: z.string().optional(),\n          }),\n          z.object({\n            type: z.literal('openPage'),\n            url: z.string().nullish(),\n          }),\n          z.object({\n            type: z.literal('findInPage'),\n            url: z.string().nullish(),\n            pattern: z.string().nullish(),\n          }),\n        ])\n        .optional(),\n    }),\n  ),\n);\n\nexport const webSearchPreview = createProviderToolFactoryWithOutputSchema<\n  {\n    // Web search preview doesn't take input parameters - it's controlled by the prompt\n  },\n  {\n    /**\n     * An object describing the specific action taken in this web search call.\n     * Includes details on how the model used the web (search, open_page, find_in_page).\n     */\n    action?:\n      | {\n          /**\n           * Action type \"search\" - Performs a web search query.\n           */\n          type: 'search';\n\n          /**\n           * The search query.\n           */\n          query?: string;\n        }\n      | {\n          /**\n           * Action type \"openPage\" - Opens a specific URL from search results.\n           */\n          type: 'openPage';\n\n          /**\n           * The URL opened by the model.\n           */\n          url?: string | null;\n        }\n      | {\n          /**\n           * Action type \"findInPage\": Searches for a pattern within a loaded page.\n           */\n          type: 'findInPage';\n\n          /**\n           * The URL of the page searched for the pattern.\n           */\n          url?: string | null;\n\n          /**\n           * The pattern or text to search for within the page.\n           */\n          pattern?: string | null;\n        };\n  },\n  {\n    /**\n     * Search context size to use for the web search.\n     * - high: Most comprehensive context, highest cost, slower response\n     * - medium: Balanced context, cost, and latency (default)\n     * - low: Least context, lowest cost, fastest response\n     */\n    searchContextSize?: 'low' | 'medium' | 'high';\n\n    /**\n     * User location information to provide geographically relevant search results.\n     */\n    userLocation?: {\n      /**\n       * Type of location (always 'approximate')\n       */\n      type: 'approximate';\n      /**\n       * Two-letter ISO country code (e.g., 'US', 'GB')\n       */\n      country?: string;\n      /**\n       * City name (free text, e.g., 'Minneapolis')\n       */\n      city?: string;\n      /**\n       * Region name (free text, e.g., 'Minnesota')\n       */\n      region?: string;\n      /**\n       * IANA timezone (e.g., 'America/Chicago')\n       */\n      timezone?: string;\n    };\n  }\n>({\n  id: 'openai.web_search_preview',\n  inputSchema: webSearchPreviewInputSchema,\n  outputSchema: webSearchPreviewOutputSchema,\n});\n", "import {\n  createProviderToolFactoryWithOutputSchema,\n  lazySchema,\n  zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { JSONValue } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\n\nconst jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>\n  z.union([\n    z.string(),\n    z.number(),\n    z.boolean(),\n    z.null(),\n    z.array(jsonValueSchema),\n    z.record(z.string(), jsonValueSchema),\n  ]),\n);\n\nexport const mcpArgsSchema = lazySchema(() =>\n  zodSchema(\n    z\n      .object({\n        serverLabel: z.string(),\n        allowedTools: z\n          .union([\n            z.array(z.string()),\n            z.object({\n              readOnly: z.boolean().optional(),\n              toolNames: z.array(z.string()).optional(),\n            }),\n          ])\n          .optional(),\n        authorization: z.string().optional(),\n        connectorId: z.string().optional(),\n        headers: z.record(z.string(), z.string()).optional(),\n\n        requireApproval: z\n          .union([\n            z.enum(['always', 'never']),\n            z.object({\n              never: z\n                .object({\n                  toolNames: z.array(z.string()).optional(),\n                })\n                .optional(),\n            }),\n          ])\n          .optional(),\n        serverDescription: z.string().optional(),\n        serverUrl: z.string().optional(),\n      })\n      .refine(\n        v => v.serverUrl != null || v.connectorId != null,\n        'One of serverUrl or connectorId must be provided.',\n      ),\n  ),\n);\n\nconst mcpInputSchema = lazySchema(() => zodSchema(z.object({})));\n\nexport const mcpOutputSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      type: z.literal('call'),\n      serverLabel: z.string(),\n      name: z.string(),\n      arguments: z.string(),\n      output: z.string().nullish(),\n      error: z.union([z.string(), jsonValueSchema]).optional(),\n    }),\n  ),\n);\n\ntype McpArgs = {\n  /** A label for this MCP server, used to identify it in tool calls. */\n  serverLabel: string;\n  /** List of allowed tool names or a filter object. */\n  allowedTools?:\n    | string[]\n    | {\n        readOnly?: boolean;\n        toolNames?: string[];\n      };\n  /** OAuth access token usable with the remote MCP server or connector. */\n  authorization?: string;\n  /** Identifier for a service connector. */\n  connectorId?: string;\n  /** Optional HTTP headers to send to the MCP server. */\n  headers?: Record<string, string>;\n  /**\n   * Which tools require approval before execution.\n   */\n  requireApproval?:\n    | 'always'\n    | 'never'\n    | {\n        never?: {\n          toolNames?: string[];\n        };\n      };\n  /** Optional description of the MCP server. */\n  serverDescription?: string;\n  /** URL for the MCP server. One of serverUrl or connectorId must be provided. */\n  serverUrl?: string;\n};\n\nexport const mcpToolFactory = createProviderToolFactoryWithOutputSchema<\n  {},\n  {\n    type: 'call';\n    serverLabel: string;\n    name: string;\n    arguments: string;\n    output?: string | null;\n    error?: JSONValue;\n  },\n  McpArgs\n>({\n  id: 'openai.mcp',\n  inputSchema: mcpInputSchema,\n  outputSchema: mcpOutputSchema,\n});\n\nexport const mcp = (args: McpArgs) => mcpToolFactory(args);\n", "import { applyPatch } from './tool/apply-patch';\nimport { codeInterpreter } from './tool/code-interpreter';\nimport { customTool } from './tool/custom';\nimport { fileSearch } from './tool/file-search';\nimport { imageGeneration } from './tool/image-generation';\nimport { localShell } from './tool/local-shell';\nimport { shell } from './tool/shell';\nimport { toolSearch } from './tool/tool-search';\nimport { webSearch } from './tool/web-search';\nimport { webSearchPreview } from './tool/web-search-preview';\nimport { mcp } from './tool/mcp';\n\nexport const openaiTools = {\n  /**\n   * The apply_patch tool lets GPT-5.1 create, update, and delete files in your\n   * codebase using structured diffs. Instead of just suggesting edits, the model\n   * emits patch operations that your application applies and then reports back on,\n   * enabling iterative, multi-step code editing workflows.\n   *\n   */\n  applyPatch,\n\n  /**\n   * Custom tools let callers constrain model output to a grammar (regex or\n   * Lark syntax). The model returns a `custom_tool_call` output item whose\n   * `input` field is a string matching the specified grammar.\n   *\n   * @param name - The name of the custom tool.\n   * @param description - An optional description of the tool.\n   * @param format - The output format constraint (grammar type, syntax, and definition).\n   */\n  customTool,\n\n  /**\n   * The Code Interpreter tool allows models to write and run Python code in a\n   * sandboxed environment to solve complex problems in domains like data analysis,\n   * coding, and math.\n   *\n   * @param container - The container to use for the code interpreter.\n   */\n  codeInterpreter,\n\n  /**\n   * File search is a tool available in the Responses API. It enables models to\n   * retrieve information in a knowledge base of previously uploaded files through\n   * semantic and keyword search.\n   *\n   * @param vectorStoreIds - The vector store IDs to use for the file search.\n   * @param maxNumResults - The maximum number of results to return.\n   * @param ranking - The ranking options to use for the file search.\n   * @param filters - The filters to use for the file search.\n   */\n  fileSearch,\n\n  /**\n   * The image generation tool allows you to generate images using a text prompt,\n   * and optionally image inputs. It leverages the GPT Image model,\n   * and automatically optimizes text inputs for improved performance.\n   *\n   * @param background - Background type for the generated image. One of 'auto', 'opaque', or 'transparent'.\n   * @param inputFidelity - Input fidelity for the generated image. One of 'low' or 'high'.\n   * @param inputImageMask - Optional mask for inpainting. Contains fileId and/or imageUrl.\n   * @param model - The image generation model to use. Default: gpt-image-1.\n   * @param moderation - Moderation level for the generated image. Default: 'auto'.\n   * @param outputCompression - Compression level for the output image (0-100).\n   * @param outputFormat - The output format of the generated image. One of 'png', 'jpeg', or 'webp'.\n   * @param partialImages - Number of partial images to generate in streaming mode (0-3).\n   * @param quality - The quality of the generated image. One of 'auto', 'low', 'medium', or 'high'.\n   * @param size - The size of the generated image. One of 'auto', '1024x1024', '1024x1536', or '1536x1024'.\n   */\n  imageGeneration,\n\n  /**\n   * Local shell is a tool that allows agents to run shell commands locally\n   * on a machine you or the user provides.\n   *\n   * Supported models: `gpt-5-codex`\n   */\n  localShell,\n\n  /**\n   * The shell tool allows the model to interact with your local computer through\n   * a controlled command-line interface. The model proposes shell commands; your\n   * integration executes them and returns the outputs.\n   *\n   * Available through the Responses API for use with GPT-5.1.\n   *\n   * WARNING: Running arbitrary shell commands can be dangerous. Always sandbox\n   * execution or add strict allow-/deny-lists before forwarding a command to\n   * the system shell.\n   */\n  shell,\n\n  /**\n   * Web search allows models to access up-to-date information from the internet\n   * and provide answers with sourced citations.\n   *\n   * @param searchContextSize - The search context size to use for the web search.\n   * @param userLocation - The user location to use for the web search.\n   */\n  webSearchPreview,\n\n  /**\n   * Web search allows models to access up-to-date information from the internet\n   * and provide answers with sourced citations.\n   *\n   * @param filters - The filters to use for the web search.\n   * @param searchContextSize - The search context size to use for the web search.\n   * @param userLocation - The user location to use for the web search.\n   */\n  webSearch,\n\n  /**\n   * MCP (Model Context Protocol) allows models to call tools exposed by\n   * remote MCP servers or service connectors.\n   *\n   * @param serverLabel - Label to identify the MCP server.\n   * @param allowedTools - Allowed tool names or filter object.\n   * @param authorization - OAuth access token for the MCP server/connector.\n   * @param connectorId - Identifier for a service connector.\n   * @param headers - Optional headers to include in MCP requests.\n   * // param requireApproval - Approval policy ('always'|'never'|filter object). (Removed - always 'never')\n   * @param serverDescription - Optional description of the server.\n   * @param serverUrl - URL for the MCP server.\n   */\n  mcp,\n\n  /**\n   * Tool search allows the model to dynamically search for and load deferred\n   * tools into the model's context as needed. This helps reduce overall token\n   * usage, cost, and latency by only loading tools when the model needs them.\n   *\n   * To use tool search, mark functions or namespaces with `defer_loading: true`\n   * in the tools array. The model will use tool search to load these tools\n   * when it determines they are needed.\n   */\n  toolSearch,\n};\n", "import {\n  APICallError,\n  JSONValue,\n  LanguageModelV3,\n  LanguageModelV3Prompt,\n  LanguageModelV3CallOptions,\n  LanguageModelV3Content,\n  LanguageModelV3FinishReason,\n  LanguageModelV3GenerateResult,\n  LanguageModelV3ProviderTool,\n  LanguageModelV3StreamPart,\n  LanguageModelV3StreamResult,\n  LanguageModelV3ToolApprovalRequest,\n  SharedV3ProviderMetadata,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonResponseHandler,\n  createToolNameMapping,\n  generateId,\n  InferSchema,\n  parseProviderOptions,\n  ParseResult,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { OpenAIConfig } from '../openai-config';\nimport { openaiFailedResponseHandler } from '../openai-error';\nimport { getOpenAILanguageModelCapabilities } from '../openai-language-model-capabilities';\nimport { applyPatchInputSchema } from '../tool/apply-patch';\nimport {\n  codeInterpreterInputSchema,\n  codeInterpreterOutputSchema,\n} from '../tool/code-interpreter';\nimport { fileSearchOutputSchema } from '../tool/file-search';\nimport { imageGenerationOutputSchema } from '../tool/image-generation';\nimport { localShellInputSchema } from '../tool/local-shell';\nimport { mcpOutputSchema } from '../tool/mcp';\nimport { shellInputSchema, shellOutputSchema } from '../tool/shell';\nimport {\n  toolSearchInputSchema,\n  toolSearchOutputSchema,\n} from '../tool/tool-search';\nimport { webSearchOutputSchema } from '../tool/web-search';\nimport {\n  convertOpenAIResponsesUsage,\n  OpenAIResponsesUsage,\n} from './convert-openai-responses-usage';\nimport { convertToOpenAIResponsesInput } from './convert-to-openai-responses-input';\nimport { mapOpenAIResponseFinishReason } from './map-openai-responses-finish-reason';\nimport {\n  OpenAIResponsesChunk,\n  openaiResponsesChunkSchema,\n  OpenAIResponsesIncludeOptions,\n  OpenAIResponsesIncludeValue,\n  OpenAIResponsesLogprobs,\n  openaiResponsesResponseSchema,\n  OpenAIResponsesWebSearchAction,\n  OpenAIResponsesApplyPatchOperationDiffDeltaChunk,\n  OpenAIResponsesApplyPatchOperationDiffDoneChunk,\n} from './openai-responses-api';\nimport {\n  OpenAIResponsesModelId,\n  openaiLanguageModelResponsesOptionsSchema,\n  TOP_LOGPROBS_MAX,\n} from './openai-responses-options';\nimport { prepareResponsesTools } from './openai-responses-prepare-tools';\nimport {\n  ResponsesProviderMetadata,\n  ResponsesReasoningProviderMetadata,\n  ResponsesSourceDocumentProviderMetadata,\n  ResponsesTextProviderMetadata,\n} from './openai-responses-provider-metadata';\n\n/**\n * Extracts a mapping from MCP approval request IDs to their corresponding tool call IDs\n * from the prompt. When an MCP tool requires approval, we generate a tool call ID to track\n * the pending approval in our system. When the user responds to the approval (and we\n * continue the conversation), we need to map the approval request ID back to our tool call ID\n * so that tool results reference the correct tool call.\n */\nfunction extractApprovalRequestIdToToolCallIdMapping(\n  prompt: LanguageModelV3Prompt,\n): Record<string, string> {\n  const mapping: Record<string, string> = {};\n  for (const message of prompt) {\n    if (message.role !== 'assistant') continue;\n    for (const part of message.content) {\n      if (part.type !== 'tool-call') continue;\n      const approvalRequestId = part.providerOptions?.openai\n        ?.approvalRequestId as string | undefined;\n      if (approvalRequestId != null) {\n        mapping[approvalRequestId] = part.toolCallId;\n      }\n    }\n  }\n  return mapping;\n}\n\nexport class OpenAIResponsesLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = 'v3';\n\n  readonly modelId: OpenAIResponsesModelId;\n\n  private readonly config: OpenAIConfig;\n\n  constructor(modelId: OpenAIResponsesModelId, config: OpenAIConfig) {\n    this.modelId = modelId;\n    this.config = config;\n  }\n\n  readonly supportedUrls: Record<string, RegExp[]> = {\n    'image/*': [/^https?:\\/\\/.*$/],\n    'application/pdf': [/^https?:\\/\\/.*$/],\n  };\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  private async getArgs({\n    maxOutputTokens,\n    temperature,\n    stopSequences,\n    topP,\n    topK,\n    presencePenalty,\n    frequencyPenalty,\n    seed,\n    prompt,\n    providerOptions,\n    tools,\n    toolChoice,\n    responseFormat,\n  }: LanguageModelV3CallOptions) {\n    const warnings: SharedV3Warning[] = [];\n    const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId);\n\n    if (topK != null) {\n      warnings.push({ type: 'unsupported', feature: 'topK' });\n    }\n\n    if (seed != null) {\n      warnings.push({ type: 'unsupported', feature: 'seed' });\n    }\n\n    if (presencePenalty != null) {\n      warnings.push({ type: 'unsupported', feature: 'presencePenalty' });\n    }\n\n    if (frequencyPenalty != null) {\n      warnings.push({ type: 'unsupported', feature: 'frequencyPenalty' });\n    }\n\n    if (stopSequences != null) {\n      warnings.push({ type: 'unsupported', feature: 'stopSequences' });\n    }\n\n    const providerOptionsName = this.config.provider.includes('azure')\n      ? 'azure'\n      : 'openai';\n    let openaiOptions = await parseProviderOptions({\n      provider: providerOptionsName,\n      providerOptions,\n      schema: openaiLanguageModelResponsesOptionsSchema,\n    });\n\n    if (openaiOptions == null && providerOptionsName !== 'openai') {\n      openaiOptions = await parseProviderOptions({\n        provider: 'openai',\n        providerOptions,\n        schema: openaiLanguageModelResponsesOptionsSchema,\n      });\n    }\n\n    const isReasoningModel =\n      openaiOptions?.forceReasoning ?? modelCapabilities.isReasoningModel;\n\n    if (openaiOptions?.conversation && openaiOptions?.previousResponseId) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'conversation',\n        details: 'conversation and previousResponseId cannot be used together',\n      });\n    }\n\n    const toolNameMapping = createToolNameMapping({\n      tools,\n      providerToolNames: {\n        'openai.code_interpreter': 'code_interpreter',\n        'openai.file_search': 'file_search',\n        'openai.image_generation': 'image_generation',\n        'openai.local_shell': 'local_shell',\n        'openai.shell': 'shell',\n        'openai.web_search': 'web_search',\n        'openai.web_search_preview': 'web_search_preview',\n        'openai.mcp': 'mcp',\n        'openai.apply_patch': 'apply_patch',\n        'openai.tool_search': 'tool_search',\n      },\n      resolveProviderToolName: tool =>\n        tool.id === 'openai.custom'\n          ? (tool.args as { name?: string }).name\n          : undefined,\n    });\n\n    const customProviderToolNames = new Set<string>();\n    const {\n      tools: openaiTools,\n      toolChoice: openaiToolChoice,\n      toolWarnings,\n    } = await prepareResponsesTools({\n      tools,\n      toolChoice,\n      toolNameMapping,\n      customProviderToolNames,\n    });\n\n    const { input, warnings: inputWarnings } =\n      await convertToOpenAIResponsesInput({\n        prompt,\n        toolNameMapping,\n        systemMessageMode:\n          openaiOptions?.systemMessageMode ??\n          (isReasoningModel\n            ? 'developer'\n            : modelCapabilities.systemMessageMode),\n        providerOptionsName,\n        fileIdPrefixes: this.config.fileIdPrefixes,\n        store: openaiOptions?.store ?? true,\n        hasConversation: openaiOptions?.conversation != null,\n        hasLocalShellTool: hasOpenAITool('openai.local_shell'),\n        hasShellTool: hasOpenAITool('openai.shell'),\n        hasApplyPatchTool: hasOpenAITool('openai.apply_patch'),\n        customProviderToolNames:\n          customProviderToolNames.size > 0\n            ? customProviderToolNames\n            : undefined,\n      });\n\n    warnings.push(...inputWarnings);\n\n    const strictJsonSchema = openaiOptions?.strictJsonSchema ?? true;\n\n    let include: OpenAIResponsesIncludeOptions = openaiOptions?.include;\n\n    function addInclude(key: OpenAIResponsesIncludeValue) {\n      if (include == null) {\n        include = [key];\n      } else if (!include.includes(key)) {\n        include = [...include, key];\n      }\n    }\n\n    function hasOpenAITool(id: string) {\n      return (\n        tools?.find(tool => tool.type === 'provider' && tool.id === id) != null\n      );\n    }\n\n    // when logprobs are requested, automatically include them:\n    const topLogprobs =\n      typeof openaiOptions?.logprobs === 'number'\n        ? openaiOptions?.logprobs\n        : openaiOptions?.logprobs === true\n          ? TOP_LOGPROBS_MAX\n          : undefined;\n\n    if (topLogprobs) {\n      addInclude('message.output_text.logprobs');\n    }\n\n    // when a web search tool is present, automatically include the sources:\n    const webSearchToolName = (\n      tools?.find(\n        tool =>\n          tool.type === 'provider' &&\n          (tool.id === 'openai.web_search' ||\n            tool.id === 'openai.web_search_preview'),\n      ) as LanguageModelV3ProviderTool | undefined\n    )?.name;\n\n    if (webSearchToolName) {\n      addInclude('web_search_call.action.sources');\n    }\n\n    // when a code interpreter tool is present, automatically include the outputs:\n    if (hasOpenAITool('openai.code_interpreter')) {\n      addInclude('code_interpreter_call.outputs');\n    }\n\n    const store = openaiOptions?.store;\n\n    // store defaults to true in the OpenAI responses API, so check for false exactly:\n    if (store === false && isReasoningModel) {\n      addInclude('reasoning.encrypted_content');\n    }\n\n    const baseArgs = {\n      model: this.modelId,\n      input,\n      temperature,\n      top_p: topP,\n      max_output_tokens: maxOutputTokens,\n\n      ...((responseFormat?.type === 'json' || openaiOptions?.textVerbosity) && {\n        text: {\n          ...(responseFormat?.type === 'json' && {\n            format:\n              responseFormat.schema != null\n                ? {\n                    type: 'json_schema',\n                    strict: strictJsonSchema,\n                    name: responseFormat.name ?? 'response',\n                    description: responseFormat.description,\n                    schema: responseFormat.schema,\n                  }\n                : { type: 'json_object' },\n          }),\n          ...(openaiOptions?.textVerbosity && {\n            verbosity: openaiOptions.textVerbosity,\n          }),\n        },\n      }),\n\n      // provider options:\n      conversation: openaiOptions?.conversation,\n      max_tool_calls: openaiOptions?.maxToolCalls,\n      metadata: openaiOptions?.metadata,\n      parallel_tool_calls: openaiOptions?.parallelToolCalls,\n      previous_response_id: openaiOptions?.previousResponseId,\n      store,\n      user: openaiOptions?.user,\n      instructions: openaiOptions?.instructions,\n      service_tier: openaiOptions?.serviceTier,\n      include,\n      prompt_cache_key: openaiOptions?.promptCacheKey,\n      prompt_cache_retention: openaiOptions?.promptCacheRetention,\n      safety_identifier: openaiOptions?.safetyIdentifier,\n      top_logprobs: topLogprobs,\n      truncation: openaiOptions?.truncation,\n\n      // model-specific settings:\n      ...(isReasoningModel &&\n        (openaiOptions?.reasoningEffort != null ||\n          openaiOptions?.reasoningSummary != null) && {\n          reasoning: {\n            ...(openaiOptions?.reasoningEffort != null && {\n              effort: openaiOptions.reasoningEffort,\n            }),\n            ...(openaiOptions?.reasoningSummary != null && {\n              summary: openaiOptions.reasoningSummary,\n            }),\n          },\n        }),\n    };\n\n    // remove unsupported settings for reasoning models\n    // see https://platform.openai.com/docs/guides/reasoning#limitations\n    if (isReasoningModel) {\n      // when reasoning effort is none, gpt-5.1 models allow temperature, topP, logprobs\n      //  https://platform.openai.com/docs/guides/latest-model#gpt-5-1-parameter-compatibility\n      if (\n        !(\n          openaiOptions?.reasoningEffort === 'none' &&\n          modelCapabilities.supportsNonReasoningParameters\n        )\n      ) {\n        if (baseArgs.temperature != null) {\n          baseArgs.temperature = undefined;\n          warnings.push({\n            type: 'unsupported',\n            feature: 'temperature',\n            details: 'temperature is not supported for reasoning models',\n          });\n        }\n\n        if (baseArgs.top_p != null) {\n          baseArgs.top_p = undefined;\n          warnings.push({\n            type: 'unsupported',\n            feature: 'topP',\n            details: 'topP is not supported for reasoning models',\n          });\n        }\n      }\n    } else {\n      if (openaiOptions?.reasoningEffort != null) {\n        warnings.push({\n          type: 'unsupported',\n          feature: 'reasoningEffort',\n          details: 'reasoningEffort is not supported for non-reasoning models',\n        });\n      }\n\n      if (openaiOptions?.reasoningSummary != null) {\n        warnings.push({\n          type: 'unsupported',\n          feature: 'reasoningSummary',\n          details: 'reasoningSummary is not supported for non-reasoning models',\n        });\n      }\n    }\n\n    // Validate flex processing support\n    if (\n      openaiOptions?.serviceTier === 'flex' &&\n      !modelCapabilities.supportsFlexProcessing\n    ) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'serviceTier',\n        details:\n          'flex processing is only available for o3, o4-mini, and gpt-5 models',\n      });\n      // Remove from args if not supported\n      delete (baseArgs as any).service_tier;\n    }\n\n    // Validate priority processing support\n    if (\n      openaiOptions?.serviceTier === 'priority' &&\n      !modelCapabilities.supportsPriorityProcessing\n    ) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'serviceTier',\n        details:\n          'priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported',\n      });\n      // Remove from args if not supported\n      delete (baseArgs as any).service_tier;\n    }\n\n    const shellToolEnvType = (\n      tools?.find(\n        tool => tool.type === 'provider' && tool.id === 'openai.shell',\n      ) as { args?: { environment?: { type?: string } } } | undefined\n    )?.args?.environment?.type;\n\n    const isShellProviderExecuted =\n      shellToolEnvType === 'containerAuto' ||\n      shellToolEnvType === 'containerReference';\n\n    return {\n      webSearchToolName,\n      args: {\n        ...baseArgs,\n        tools: openaiTools,\n        tool_choice: openaiToolChoice,\n      },\n      warnings: [...warnings, ...toolWarnings],\n      store,\n      toolNameMapping,\n      providerOptionsName,\n      isShellProviderExecuted,\n    };\n  }\n\n  async doGenerate(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3GenerateResult> {\n    const {\n      args: body,\n      warnings,\n      webSearchToolName,\n      toolNameMapping,\n      providerOptionsName,\n      isShellProviderExecuted,\n    } = await this.getArgs(options);\n    const url = this.config.url({\n      path: '/responses',\n      modelId: this.modelId,\n    });\n\n    const approvalRequestIdToDummyToolCallIdFromPrompt =\n      extractApprovalRequestIdToToolCallIdMapping(options.prompt);\n\n    const {\n      responseHeaders,\n      value: response,\n      rawValue: rawResponse,\n    } = await postJsonToApi({\n      url,\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body,\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiResponsesResponseSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    if (response.error) {\n      throw new APICallError({\n        message: response.error.message,\n        url,\n        requestBodyValues: body,\n        statusCode: 400,\n        responseHeaders,\n        responseBody: rawResponse as string,\n        isRetryable: false,\n      });\n    }\n\n    const content: Array<LanguageModelV3Content> = [];\n    const logprobs: Array<OpenAIResponsesLogprobs> = [];\n\n    // flag that checks if there have been client-side tool calls (not executed by openai)\n    let hasFunctionCall = false;\n    const hostedToolSearchCallIds: string[] = [];\n\n    // map response content to content array (defined when there is no error)\n    for (const part of response.output!) {\n      switch (part.type) {\n        case 'reasoning': {\n          // when there are no summary parts, we need to add an empty reasoning part:\n          if (part.summary.length === 0) {\n            part.summary.push({ type: 'summary_text', text: '' });\n          }\n\n          for (const summary of part.summary) {\n            content.push({\n              type: 'reasoning' as const,\n              text: summary.text,\n              providerMetadata: {\n                [providerOptionsName]: {\n                  itemId: part.id,\n                  reasoningEncryptedContent: part.encrypted_content ?? null,\n                } satisfies ResponsesReasoningProviderMetadata,\n              },\n            });\n          }\n          break;\n        }\n\n        case 'image_generation_call': {\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName('image_generation'),\n            input: '{}',\n            providerExecuted: true,\n          });\n\n          content.push({\n            type: 'tool-result',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName('image_generation'),\n            result: {\n              result: part.result,\n            } satisfies InferSchema<typeof imageGenerationOutputSchema>,\n          });\n\n          break;\n        }\n\n        case 'tool_search_call': {\n          const toolCallId = part.call_id ?? part.id;\n          const isHosted = part.execution === 'server';\n\n          if (isHosted) {\n            hostedToolSearchCallIds.push(toolCallId);\n          }\n\n          content.push({\n            type: 'tool-call',\n            toolCallId,\n            toolName: toolNameMapping.toCustomToolName('tool_search'),\n            input: JSON.stringify({\n              arguments: part.arguments,\n              call_id: part.call_id,\n            } satisfies InferSchema<typeof toolSearchInputSchema>),\n            ...(isHosted ? { providerExecuted: true } : {}),\n            providerMetadata: {\n              [providerOptionsName]: {\n                itemId: part.id,\n              },\n            },\n          });\n\n          break;\n        }\n\n        case 'tool_search_output': {\n          const toolCallId =\n            part.call_id ?? hostedToolSearchCallIds.shift() ?? part.id;\n\n          content.push({\n            type: 'tool-result',\n            toolCallId,\n            toolName: toolNameMapping.toCustomToolName('tool_search'),\n            result: {\n              tools: part.tools,\n            } satisfies InferSchema<typeof toolSearchOutputSchema>,\n            providerMetadata: {\n              [providerOptionsName]: {\n                itemId: part.id,\n              },\n            },\n          });\n\n          break;\n        }\n\n        case 'local_shell_call': {\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.call_id,\n            toolName: toolNameMapping.toCustomToolName('local_shell'),\n            input: JSON.stringify({\n              action: part.action,\n            } satisfies InferSchema<typeof localShellInputSchema>),\n            providerMetadata: {\n              [providerOptionsName]: {\n                itemId: part.id,\n              },\n            },\n          });\n\n          break;\n        }\n\n        case 'shell_call': {\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.call_id,\n            toolName: toolNameMapping.toCustomToolName('shell'),\n            input: JSON.stringify({\n              action: {\n                commands: part.action.commands,\n              },\n            } satisfies InferSchema<typeof shellInputSchema>),\n            ...(isShellProviderExecuted && { providerExecuted: true }),\n            providerMetadata: {\n              [providerOptionsName]: {\n                itemId: part.id,\n              },\n            },\n          });\n\n          break;\n        }\n\n        case 'shell_call_output': {\n          content.push({\n            type: 'tool-result',\n            toolCallId: part.call_id,\n            toolName: toolNameMapping.toCustomToolName('shell'),\n            result: {\n              output: part.output.map(item => ({\n                stdout: item.stdout,\n                stderr: item.stderr,\n                outcome:\n                  item.outcome.type === 'exit'\n                    ? {\n                        type: 'exit' as const,\n                        exitCode: item.outcome.exit_code,\n                      }\n                    : { type: 'timeout' as const },\n              })),\n            } satisfies InferSchema<typeof shellOutputSchema>,\n          });\n          break;\n        }\n\n        case 'message': {\n          for (const contentPart of part.content) {\n            if (\n              options.providerOptions?.[providerOptionsName]?.logprobs &&\n              contentPart.logprobs\n            ) {\n              logprobs.push(contentPart.logprobs);\n            }\n\n            const providerMetadata: SharedV3ProviderMetadata[string] = {\n              itemId: part.id,\n              ...(part.phase != null && { phase: part.phase }),\n              ...(contentPart.annotations.length > 0 && {\n                annotations: contentPart.annotations,\n              }),\n            } satisfies ResponsesTextProviderMetadata;\n\n            content.push({\n              type: 'text',\n              text: contentPart.text,\n              providerMetadata: {\n                [providerOptionsName]: providerMetadata,\n              },\n            });\n\n            for (const annotation of contentPart.annotations) {\n              if (annotation.type === 'url_citation') {\n                content.push({\n                  type: 'source',\n                  sourceType: 'url',\n                  id: this.config.generateId?.() ?? generateId(),\n                  url: annotation.url,\n                  title: annotation.title,\n                });\n              } else if (annotation.type === 'file_citation') {\n                content.push({\n                  type: 'source',\n                  sourceType: 'document',\n                  id: this.config.generateId?.() ?? generateId(),\n                  mediaType: 'text/plain',\n                  title: annotation.filename,\n                  filename: annotation.filename,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      type: annotation.type,\n                      fileId: annotation.file_id,\n                      index: annotation.index,\n                    } satisfies Extract<\n                      ResponsesSourceDocumentProviderMetadata,\n                      { type: 'file_citation' }\n                    >,\n                  },\n                });\n              } else if (annotation.type === 'container_file_citation') {\n                content.push({\n                  type: 'source',\n                  sourceType: 'document',\n                  id: this.config.generateId?.() ?? generateId(),\n                  mediaType: 'text/plain',\n                  title: annotation.filename,\n                  filename: annotation.filename,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      type: annotation.type,\n                      fileId: annotation.file_id,\n                      containerId: annotation.container_id,\n                    } satisfies Extract<\n                      ResponsesSourceDocumentProviderMetadata,\n                      { type: 'container_file_citation' }\n                    >,\n                  },\n                });\n              } else if (annotation.type === 'file_path') {\n                content.push({\n                  type: 'source',\n                  sourceType: 'document',\n                  id: this.config.generateId?.() ?? generateId(),\n                  mediaType: 'application/octet-stream',\n                  title: annotation.file_id,\n                  filename: annotation.file_id,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      type: annotation.type,\n                      fileId: annotation.file_id,\n                      index: annotation.index,\n                    } satisfies Extract<\n                      ResponsesSourceDocumentProviderMetadata,\n                      { type: 'file_path' }\n                    >,\n                  },\n                });\n              }\n            }\n          }\n\n          break;\n        }\n\n        case 'function_call': {\n          hasFunctionCall = true;\n\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.call_id,\n            toolName: part.name,\n            input: part.arguments,\n            providerMetadata: {\n              [providerOptionsName]: {\n                itemId: part.id,\n              },\n            },\n          });\n          break;\n        }\n\n        case 'custom_tool_call': {\n          hasFunctionCall = true;\n          const toolName = toolNameMapping.toCustomToolName(part.name);\n\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.call_id,\n            toolName,\n            input: JSON.stringify(part.input),\n            providerMetadata: {\n              [providerOptionsName]: {\n                itemId: part.id,\n              },\n            },\n          });\n          break;\n        }\n\n        case 'web_search_call': {\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName(\n              webSearchToolName ?? 'web_search',\n            ),\n            input: JSON.stringify({}),\n            providerExecuted: true,\n          });\n\n          content.push({\n            type: 'tool-result',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName(\n              webSearchToolName ?? 'web_search',\n            ),\n            result: mapWebSearchOutput(part.action),\n          });\n\n          break;\n        }\n\n        case 'mcp_call': {\n          const toolCallId =\n            part.approval_request_id != null\n              ? (approvalRequestIdToDummyToolCallIdFromPrompt[\n                  part.approval_request_id\n                ] ?? part.id)\n              : part.id;\n\n          const toolName = `mcp.${part.name}`;\n\n          content.push({\n            type: 'tool-call',\n            toolCallId,\n            toolName,\n            input: part.arguments,\n            providerExecuted: true,\n            dynamic: true,\n          });\n\n          content.push({\n            type: 'tool-result',\n            toolCallId,\n            toolName,\n            result: {\n              type: 'call',\n              serverLabel: part.server_label,\n              name: part.name,\n              arguments: part.arguments,\n              ...(part.output != null ? { output: part.output } : {}),\n              ...(part.error != null\n                ? { error: part.error as unknown as JSONValue }\n                : {}),\n            } satisfies InferSchema<typeof mcpOutputSchema>,\n            providerMetadata: {\n              [providerOptionsName]: {\n                itemId: part.id,\n              },\n            },\n          });\n          break;\n        }\n\n        case 'mcp_list_tools': {\n          // skip\n          break;\n        }\n\n        case 'mcp_approval_request': {\n          const approvalRequestId = part.approval_request_id ?? part.id;\n          const dummyToolCallId = this.config.generateId?.() ?? generateId();\n          const toolName = `mcp.${part.name}`;\n\n          content.push({\n            type: 'tool-call',\n            toolCallId: dummyToolCallId,\n            toolName,\n            input: part.arguments,\n            providerExecuted: true,\n            dynamic: true,\n          });\n\n          content.push({\n            type: 'tool-approval-request',\n            approvalId: approvalRequestId,\n            toolCallId: dummyToolCallId,\n          } satisfies LanguageModelV3ToolApprovalRequest);\n          break;\n        }\n\n        case 'computer_call': {\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName('computer_use'),\n            input: '',\n            providerExecuted: true,\n          });\n\n          content.push({\n            type: 'tool-result',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName('computer_use'),\n            result: {\n              type: 'computer_use_tool_result',\n              status: part.status || 'completed',\n            },\n          });\n          break;\n        }\n\n        case 'file_search_call': {\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName('file_search'),\n            input: '{}',\n            providerExecuted: true,\n          });\n\n          content.push({\n            type: 'tool-result',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName('file_search'),\n            result: {\n              queries: part.queries,\n              results:\n                part.results?.map(result => ({\n                  attributes: result.attributes,\n                  fileId: result.file_id,\n                  filename: result.filename,\n                  score: result.score,\n                  text: result.text,\n                })) ?? null,\n            } satisfies InferSchema<typeof fileSearchOutputSchema>,\n          });\n          break;\n        }\n\n        case 'code_interpreter_call': {\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName('code_interpreter'),\n            input: JSON.stringify({\n              code: part.code,\n              containerId: part.container_id,\n            } satisfies InferSchema<typeof codeInterpreterInputSchema>),\n            providerExecuted: true,\n          });\n\n          content.push({\n            type: 'tool-result',\n            toolCallId: part.id,\n            toolName: toolNameMapping.toCustomToolName('code_interpreter'),\n            result: {\n              outputs: part.outputs,\n            } satisfies InferSchema<typeof codeInterpreterOutputSchema>,\n          });\n          break;\n        }\n\n        case 'apply_patch_call': {\n          content.push({\n            type: 'tool-call',\n            toolCallId: part.call_id,\n            toolName: toolNameMapping.toCustomToolName('apply_patch'),\n            input: JSON.stringify({\n              callId: part.call_id,\n              operation: part.operation,\n            } satisfies InferSchema<typeof applyPatchInputSchema>),\n            providerMetadata: {\n              [providerOptionsName]: {\n                itemId: part.id,\n              },\n            },\n          });\n\n          break;\n        }\n      }\n    }\n\n    const providerMetadata: SharedV3ProviderMetadata = {\n      [providerOptionsName]: {\n        responseId: response.id,\n        ...(logprobs.length > 0 ? { logprobs } : {}),\n        ...(typeof response.service_tier === 'string'\n          ? { serviceTier: response.service_tier }\n          : {}),\n      } satisfies ResponsesProviderMetadata,\n    };\n\n    const usage = response.usage!; // defined when there is no error\n\n    return {\n      content,\n      finishReason: {\n        unified: mapOpenAIResponseFinishReason({\n          finishReason: response.incomplete_details?.reason,\n          hasFunctionCall,\n        }),\n        raw: response.incomplete_details?.reason ?? undefined,\n      },\n      usage: convertOpenAIResponsesUsage(usage),\n      request: { body },\n      response: {\n        id: response.id,\n        timestamp: new Date(response.created_at! * 1000),\n        modelId: response.model,\n        headers: responseHeaders,\n        body: rawResponse,\n      },\n      providerMetadata,\n      warnings,\n    };\n  }\n\n  async doStream(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3StreamResult> {\n    const {\n      args: body,\n      warnings,\n      webSearchToolName,\n      toolNameMapping,\n      store,\n      providerOptionsName,\n      isShellProviderExecuted,\n    } = await this.getArgs(options);\n\n    const { responseHeaders, value: response } = await postJsonToApi({\n      url: this.config.url({\n        path: '/responses',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: {\n        ...body,\n        stream: true,\n      },\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createEventSourceResponseHandler(\n        openaiResponsesChunkSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const self = this;\n\n    const approvalRequestIdToDummyToolCallIdFromPrompt =\n      extractApprovalRequestIdToToolCallIdMapping(options.prompt);\n\n    const approvalRequestIdToDummyToolCallIdFromStream = new Map<\n      string,\n      string\n    >();\n\n    let finishReason: LanguageModelV3FinishReason = {\n      unified: 'other',\n      raw: undefined,\n    };\n    let usage: OpenAIResponsesUsage | undefined = undefined;\n    const logprobs: Array<OpenAIResponsesLogprobs> = [];\n    let responseId: string | null = null;\n\n    const ongoingToolCalls: Record<\n      number,\n      | {\n          toolName: string;\n          toolCallId: string;\n          codeInterpreter?: {\n            containerId: string;\n          };\n          applyPatch?: {\n            hasDiff: boolean;\n            endEmitted: boolean;\n          };\n          toolSearchExecution?: 'server' | 'client';\n        }\n      | undefined\n    > = {};\n\n    // set annotations in 'text-end' part providerMetadata.\n    const ongoingAnnotations: Array<\n      Extract<\n        OpenAIResponsesChunk,\n        { type: 'response.output_text.annotation.added' }\n      >['annotation']\n    > = [];\n\n    // track the phase of the current message being streamed\n    let activeMessagePhase: 'commentary' | 'final_answer' | undefined;\n\n    // flag that checks if there have been client-side tool calls (not executed by openai)\n    let hasFunctionCall = false;\n\n    const activeReasoning: Record<\n      string,\n      {\n        encryptedContent?: string | null;\n        // summary index as string to reasoning part state:\n        summaryParts: Record<string, 'active' | 'can-conclude' | 'concluded'>;\n      }\n    > = {};\n\n    let serviceTier: string | undefined;\n    const hostedToolSearchCallIds: string[] = [];\n\n    return {\n      stream: response.pipeThrough(\n        new TransformStream<\n          ParseResult<OpenAIResponsesChunk>,\n          LanguageModelV3StreamPart\n        >({\n          start(controller) {\n            controller.enqueue({ type: 'stream-start', warnings });\n          },\n\n          transform(chunk, controller) {\n            if (options.includeRawChunks) {\n              controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n            }\n\n            // handle failed chunk parsing / validation:\n            if (!chunk.success) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({ type: 'error', error: chunk.error });\n              return;\n            }\n\n            const value = chunk.value;\n\n            if (isResponseOutputItemAddedChunk(value)) {\n              if (value.item.type === 'function_call') {\n                ongoingToolCalls[value.output_index] = {\n                  toolName: value.item.name,\n                  toolCallId: value.item.call_id,\n                };\n\n                controller.enqueue({\n                  type: 'tool-input-start',\n                  id: value.item.call_id,\n                  toolName: value.item.name,\n                });\n              } else if (value.item.type === 'custom_tool_call') {\n                const toolName = toolNameMapping.toCustomToolName(\n                  value.item.name,\n                );\n                ongoingToolCalls[value.output_index] = {\n                  toolName,\n                  toolCallId: value.item.call_id,\n                };\n\n                controller.enqueue({\n                  type: 'tool-input-start',\n                  id: value.item.call_id,\n                  toolName,\n                });\n              } else if (value.item.type === 'web_search_call') {\n                ongoingToolCalls[value.output_index] = {\n                  toolName: toolNameMapping.toCustomToolName(\n                    webSearchToolName ?? 'web_search',\n                  ),\n                  toolCallId: value.item.id,\n                };\n\n                controller.enqueue({\n                  type: 'tool-input-start',\n                  id: value.item.id,\n                  toolName: toolNameMapping.toCustomToolName(\n                    webSearchToolName ?? 'web_search',\n                  ),\n                  providerExecuted: true,\n                });\n\n                controller.enqueue({\n                  type: 'tool-input-end',\n                  id: value.item.id,\n                });\n\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: value.item.id,\n                  toolName: toolNameMapping.toCustomToolName(\n                    webSearchToolName ?? 'web_search',\n                  ),\n                  input: JSON.stringify({}),\n                  providerExecuted: true,\n                });\n              } else if (value.item.type === 'computer_call') {\n                ongoingToolCalls[value.output_index] = {\n                  toolName: toolNameMapping.toCustomToolName('computer_use'),\n                  toolCallId: value.item.id,\n                };\n\n                controller.enqueue({\n                  type: 'tool-input-start',\n                  id: value.item.id,\n                  toolName: toolNameMapping.toCustomToolName('computer_use'),\n                  providerExecuted: true,\n                });\n              } else if (value.item.type === 'code_interpreter_call') {\n                ongoingToolCalls[value.output_index] = {\n                  toolName:\n                    toolNameMapping.toCustomToolName('code_interpreter'),\n                  toolCallId: value.item.id,\n                  codeInterpreter: {\n                    containerId: value.item.container_id,\n                  },\n                };\n\n                controller.enqueue({\n                  type: 'tool-input-start',\n                  id: value.item.id,\n                  toolName:\n                    toolNameMapping.toCustomToolName('code_interpreter'),\n                  providerExecuted: true,\n                });\n\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: value.item.id,\n                  delta: `{\"containerId\":\"${value.item.container_id}\",\"code\":\"`,\n                });\n              } else if (value.item.type === 'file_search_call') {\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: value.item.id,\n                  toolName: toolNameMapping.toCustomToolName('file_search'),\n                  input: '{}',\n                  providerExecuted: true,\n                });\n              } else if (value.item.type === 'image_generation_call') {\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: value.item.id,\n                  toolName:\n                    toolNameMapping.toCustomToolName('image_generation'),\n                  input: '{}',\n                  providerExecuted: true,\n                });\n              } else if (value.item.type === 'tool_search_call') {\n                const toolCallId = value.item.id;\n                const toolName =\n                  toolNameMapping.toCustomToolName('tool_search');\n                const isHosted = value.item.execution === 'server';\n\n                ongoingToolCalls[value.output_index] = {\n                  toolName,\n                  toolCallId,\n                  toolSearchExecution: value.item.execution ?? 'server',\n                };\n\n                if (isHosted) {\n                  controller.enqueue({\n                    type: 'tool-input-start',\n                    id: toolCallId,\n                    toolName,\n                    providerExecuted: true,\n                  });\n                }\n              } else if (value.item.type === 'tool_search_output') {\n                // handled on output_item.done so we can pair it with the call\n              } else if (\n                value.item.type === 'mcp_call' ||\n                value.item.type === 'mcp_list_tools' ||\n                value.item.type === 'mcp_approval_request'\n              ) {\n                // Emit MCP tool-call/approval parts on output_item.done instead, so we can:\n                // - alias mcp_call IDs when an approval_request_id is present\n                // - emit a proper tool-approval-request part for MCP approvals\n              } else if (value.item.type === 'apply_patch_call') {\n                const { call_id: callId, operation } = value.item;\n\n                ongoingToolCalls[value.output_index] = {\n                  toolName: toolNameMapping.toCustomToolName('apply_patch'),\n                  toolCallId: callId,\n                  applyPatch: {\n                    // delete_file doesn't have diff\n                    hasDiff: operation.type === 'delete_file',\n                    endEmitted: operation.type === 'delete_file',\n                  },\n                };\n\n                controller.enqueue({\n                  type: 'tool-input-start',\n                  id: callId,\n                  toolName: toolNameMapping.toCustomToolName('apply_patch'),\n                });\n\n                if (operation.type === 'delete_file') {\n                  const inputString = JSON.stringify({\n                    callId,\n                    operation,\n                  } satisfies InferSchema<typeof applyPatchInputSchema>);\n\n                  controller.enqueue({\n                    type: 'tool-input-delta',\n                    id: callId,\n                    delta: inputString,\n                  });\n\n                  controller.enqueue({\n                    type: 'tool-input-end',\n                    id: callId,\n                  });\n                } else {\n                  controller.enqueue({\n                    type: 'tool-input-delta',\n                    id: callId,\n                    delta: `{\"callId\":\"${escapeJSONDelta(callId)}\",\"operation\":{\"type\":\"${escapeJSONDelta(operation.type)}\",\"path\":\"${escapeJSONDelta(operation.path)}\",\"diff\":\"`,\n                  });\n                }\n              } else if (value.item.type === 'shell_call') {\n                ongoingToolCalls[value.output_index] = {\n                  toolName: toolNameMapping.toCustomToolName('shell'),\n                  toolCallId: value.item.call_id,\n                };\n              } else if (value.item.type === 'shell_call_output') {\n                // shell_call_output is handled in output_item.done\n              } else if (value.item.type === 'message') {\n                ongoingAnnotations.splice(0, ongoingAnnotations.length);\n                activeMessagePhase = value.item.phase ?? undefined;\n                controller.enqueue({\n                  type: 'text-start',\n                  id: value.item.id,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item.id,\n                      ...(value.item.phase != null && {\n                        phase: value.item.phase,\n                      }),\n                    },\n                  },\n                });\n              } else if (\n                isResponseOutputItemAddedChunk(value) &&\n                value.item.type === 'reasoning'\n              ) {\n                activeReasoning[value.item.id] = {\n                  encryptedContent: value.item.encrypted_content,\n                  summaryParts: { 0: 'active' },\n                };\n\n                controller.enqueue({\n                  type: 'reasoning-start',\n                  id: `${value.item.id}:0`,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item.id,\n                      reasoningEncryptedContent:\n                        value.item.encrypted_content ?? null,\n                    } satisfies ResponsesReasoningProviderMetadata,\n                  },\n                });\n              }\n            } else if (isResponseOutputItemDoneChunk(value)) {\n              if (value.item.type === 'message') {\n                const phase = value.item.phase ?? activeMessagePhase;\n                activeMessagePhase = undefined;\n                controller.enqueue({\n                  type: 'text-end',\n                  id: value.item.id,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item.id,\n                      ...(phase != null && { phase }),\n                      ...(ongoingAnnotations.length > 0 && {\n                        annotations: ongoingAnnotations,\n                      }),\n                    } satisfies ResponsesTextProviderMetadata,\n                  },\n                });\n              } else if (value.item.type === 'function_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n                hasFunctionCall = true;\n\n                controller.enqueue({\n                  type: 'tool-input-end',\n                  id: value.item.call_id,\n                });\n\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: value.item.call_id,\n                  toolName: value.item.name,\n                  input: value.item.arguments,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item.id,\n                    },\n                  },\n                });\n              } else if (value.item.type === 'custom_tool_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n                hasFunctionCall = true;\n                const toolName = toolNameMapping.toCustomToolName(\n                  value.item.name,\n                );\n\n                controller.enqueue({\n                  type: 'tool-input-end',\n                  id: value.item.call_id,\n                });\n\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: value.item.call_id,\n                  toolName,\n                  input: JSON.stringify(value.item.input),\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item.id,\n                    },\n                  },\n                });\n              } else if (value.item.type === 'web_search_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId: value.item.id,\n                  toolName: toolNameMapping.toCustomToolName(\n                    webSearchToolName ?? 'web_search',\n                  ),\n                  result: mapWebSearchOutput(value.item.action),\n                });\n              } else if (value.item.type === 'computer_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n\n                controller.enqueue({\n                  type: 'tool-input-end',\n                  id: value.item.id,\n                });\n\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: value.item.id,\n                  toolName: toolNameMapping.toCustomToolName('computer_use'),\n                  input: '',\n                  providerExecuted: true,\n                });\n\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId: value.item.id,\n                  toolName: toolNameMapping.toCustomToolName('computer_use'),\n                  result: {\n                    type: 'computer_use_tool_result',\n                    status: value.item.status || 'completed',\n                  },\n                });\n              } else if (value.item.type === 'file_search_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId: value.item.id,\n                  toolName: toolNameMapping.toCustomToolName('file_search'),\n                  result: {\n                    queries: value.item.queries,\n                    results:\n                      value.item.results?.map(result => ({\n                        attributes: result.attributes,\n                        fileId: result.file_id,\n                        filename: result.filename,\n                        score: result.score,\n                        text: result.text,\n                      })) ?? null,\n                  } satisfies InferSchema<typeof fileSearchOutputSchema>,\n                });\n              } else if (value.item.type === 'code_interpreter_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId: value.item.id,\n                  toolName:\n                    toolNameMapping.toCustomToolName('code_interpreter'),\n                  result: {\n                    outputs: value.item.outputs,\n                  } satisfies InferSchema<typeof codeInterpreterOutputSchema>,\n                });\n              } else if (value.item.type === 'image_generation_call') {\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId: value.item.id,\n                  toolName:\n                    toolNameMapping.toCustomToolName('image_generation'),\n                  result: {\n                    result: value.item.result,\n                  } satisfies InferSchema<typeof imageGenerationOutputSchema>,\n                });\n              } else if (value.item.type === 'tool_search_call') {\n                const toolCall = ongoingToolCalls[value.output_index];\n                const isHosted = value.item.execution === 'server';\n\n                if (toolCall != null) {\n                  const toolCallId = isHosted\n                    ? toolCall.toolCallId\n                    : (value.item.call_id ?? value.item.id);\n\n                  if (isHosted) {\n                    hostedToolSearchCallIds.push(toolCallId);\n                  } else {\n                    controller.enqueue({\n                      type: 'tool-input-start',\n                      id: toolCallId,\n                      toolName: toolCall.toolName,\n                    });\n                  }\n\n                  controller.enqueue({\n                    type: 'tool-input-end',\n                    id: toolCallId,\n                  });\n\n                  controller.enqueue({\n                    type: 'tool-call',\n                    toolCallId,\n                    toolName: toolCall.toolName,\n                    input: JSON.stringify({\n                      arguments: value.item.arguments,\n                      call_id: isHosted ? null : toolCallId,\n                    } satisfies InferSchema<typeof toolSearchInputSchema>),\n                    ...(isHosted ? { providerExecuted: true } : {}),\n                    providerMetadata: {\n                      [providerOptionsName]: {\n                        itemId: value.item.id,\n                      },\n                    },\n                  });\n                }\n\n                ongoingToolCalls[value.output_index] = undefined;\n              } else if (value.item.type === 'tool_search_output') {\n                const toolCallId =\n                  value.item.call_id ??\n                  hostedToolSearchCallIds.shift() ??\n                  value.item.id;\n\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId,\n                  toolName: toolNameMapping.toCustomToolName('tool_search'),\n                  result: {\n                    tools: value.item.tools,\n                  } satisfies InferSchema<typeof toolSearchOutputSchema>,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item.id,\n                    },\n                  },\n                });\n              } else if (value.item.type === 'mcp_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n\n                const approvalRequestId =\n                  value.item.approval_request_id ?? undefined;\n\n                // when MCP tools require approval, we track them with our own\n                // tool call IDs and then map OpenAI's approval_request_id back to our ID so results match.\n                const aliasedToolCallId =\n                  approvalRequestId != null\n                    ? (approvalRequestIdToDummyToolCallIdFromStream.get(\n                        approvalRequestId,\n                      ) ??\n                      approvalRequestIdToDummyToolCallIdFromPrompt[\n                        approvalRequestId\n                      ] ??\n                      value.item.id)\n                    : value.item.id;\n\n                const toolName = `mcp.${value.item.name}`;\n\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: aliasedToolCallId,\n                  toolName,\n                  input: value.item.arguments,\n                  providerExecuted: true,\n                  dynamic: true,\n                });\n\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId: aliasedToolCallId,\n                  toolName,\n                  result: {\n                    type: 'call',\n                    serverLabel: value.item.server_label,\n                    name: value.item.name,\n                    arguments: value.item.arguments,\n                    ...(value.item.output != null\n                      ? { output: value.item.output }\n                      : {}),\n                    ...(value.item.error != null\n                      ? { error: value.item.error as unknown as JSONValue }\n                      : {}),\n                  } satisfies InferSchema<typeof mcpOutputSchema>,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item.id,\n                    },\n                  },\n                });\n              } else if (value.item.type === 'mcp_list_tools') {\n                // Skip listTools - we don't expose this to the UI or send it back\n                ongoingToolCalls[value.output_index] = undefined;\n\n                // skip\n              } else if (value.item.type === 'apply_patch_call') {\n                const toolCall = ongoingToolCalls[value.output_index];\n                if (\n                  toolCall?.applyPatch &&\n                  !toolCall.applyPatch.endEmitted &&\n                  value.item.operation.type !== 'delete_file'\n                ) {\n                  if (!toolCall.applyPatch.hasDiff) {\n                    controller.enqueue({\n                      type: 'tool-input-delta',\n                      id: toolCall.toolCallId,\n                      delta: escapeJSONDelta(value.item.operation.diff),\n                    });\n                  }\n\n                  controller.enqueue({\n                    type: 'tool-input-delta',\n                    id: toolCall.toolCallId,\n                    delta: '\"}}',\n                  });\n\n                  controller.enqueue({\n                    type: 'tool-input-end',\n                    id: toolCall.toolCallId,\n                  });\n\n                  toolCall.applyPatch.endEmitted = true;\n                }\n\n                // Emit the final tool-call with complete diff when status is 'completed'\n                if (toolCall && value.item.status === 'completed') {\n                  controller.enqueue({\n                    type: 'tool-call',\n                    toolCallId: toolCall.toolCallId,\n                    toolName: toolNameMapping.toCustomToolName('apply_patch'),\n                    input: JSON.stringify({\n                      callId: value.item.call_id,\n                      operation: value.item.operation,\n                    } satisfies InferSchema<typeof applyPatchInputSchema>),\n                    providerMetadata: {\n                      [providerOptionsName]: {\n                        itemId: value.item.id,\n                      },\n                    },\n                  });\n                }\n\n                ongoingToolCalls[value.output_index] = undefined;\n              } else if (value.item.type === 'mcp_approval_request') {\n                ongoingToolCalls[value.output_index] = undefined;\n\n                const dummyToolCallId =\n                  self.config.generateId?.() ?? generateId();\n                const approvalRequestId =\n                  value.item.approval_request_id ?? value.item.id;\n                approvalRequestIdToDummyToolCallIdFromStream.set(\n                  approvalRequestId,\n                  dummyToolCallId,\n                );\n\n                const toolName = `mcp.${value.item.name}`;\n\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: dummyToolCallId,\n                  toolName,\n                  input: value.item.arguments,\n                  providerExecuted: true,\n                  dynamic: true,\n                });\n\n                controller.enqueue({\n                  type: 'tool-approval-request',\n                  approvalId: approvalRequestId,\n                  toolCallId: dummyToolCallId,\n                });\n              } else if (value.item.type === 'local_shell_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: value.item.call_id,\n                  toolName: toolNameMapping.toCustomToolName('local_shell'),\n                  input: JSON.stringify({\n                    action: {\n                      type: 'exec',\n                      command: value.item.action.command,\n                      timeoutMs: value.item.action.timeout_ms,\n                      user: value.item.action.user,\n                      workingDirectory: value.item.action.working_directory,\n                      env: value.item.action.env,\n                    },\n                  } satisfies InferSchema<typeof localShellInputSchema>),\n                  providerMetadata: {\n                    [providerOptionsName]: { itemId: value.item.id },\n                  },\n                });\n              } else if (value.item.type === 'shell_call') {\n                ongoingToolCalls[value.output_index] = undefined;\n\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: value.item.call_id,\n                  toolName: toolNameMapping.toCustomToolName('shell'),\n                  input: JSON.stringify({\n                    action: {\n                      commands: value.item.action.commands,\n                    },\n                  } satisfies InferSchema<typeof shellInputSchema>),\n                  ...(isShellProviderExecuted && {\n                    providerExecuted: true,\n                  }),\n                  providerMetadata: {\n                    [providerOptionsName]: { itemId: value.item.id },\n                  },\n                });\n              } else if (value.item.type === 'shell_call_output') {\n                controller.enqueue({\n                  type: 'tool-result',\n                  toolCallId: value.item.call_id,\n                  toolName: toolNameMapping.toCustomToolName('shell'),\n                  result: {\n                    output: value.item.output.map(\n                      (item: {\n                        stdout: string;\n                        stderr: string;\n                        outcome:\n                          | { type: 'exit'; exit_code: number }\n                          | { type: 'timeout' };\n                      }) => ({\n                        stdout: item.stdout,\n                        stderr: item.stderr,\n                        outcome:\n                          item.outcome.type === 'exit'\n                            ? {\n                                type: 'exit' as const,\n                                exitCode: item.outcome.exit_code,\n                              }\n                            : { type: 'timeout' as const },\n                      }),\n                    ),\n                  } satisfies InferSchema<typeof shellOutputSchema>,\n                });\n              } else if (value.item.type === 'reasoning') {\n                const activeReasoningPart = activeReasoning[value.item.id];\n\n                // get all active or can-conclude summary parts' ids\n                // to conclude ongoing reasoning parts:\n                const summaryPartIndices = Object.entries(\n                  activeReasoningPart.summaryParts,\n                )\n                  .filter(\n                    ([_, status]) =>\n                      status === 'active' || status === 'can-conclude',\n                  )\n                  .map(([summaryIndex]) => summaryIndex);\n\n                for (const summaryIndex of summaryPartIndices) {\n                  controller.enqueue({\n                    type: 'reasoning-end',\n                    id: `${value.item.id}:${summaryIndex}`,\n                    providerMetadata: {\n                      [providerOptionsName]: {\n                        itemId: value.item.id,\n                        reasoningEncryptedContent:\n                          value.item.encrypted_content ?? null,\n                      } satisfies ResponsesReasoningProviderMetadata,\n                    },\n                  });\n                }\n\n                delete activeReasoning[value.item.id];\n              }\n            } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) {\n              const toolCall = ongoingToolCalls[value.output_index];\n\n              if (toolCall != null) {\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.toolCallId,\n                  delta: value.delta,\n                });\n              }\n            } else if (isResponseCustomToolCallInputDeltaChunk(value)) {\n              const toolCall = ongoingToolCalls[value.output_index];\n\n              if (toolCall != null) {\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.toolCallId,\n                  delta: value.delta,\n                });\n              }\n            } else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value)) {\n              const toolCall = ongoingToolCalls[value.output_index];\n\n              if (toolCall?.applyPatch) {\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.toolCallId,\n                  delta: escapeJSONDelta(value.delta),\n                });\n\n                toolCall.applyPatch.hasDiff = true;\n              }\n            } else if (isResponseApplyPatchCallOperationDiffDoneChunk(value)) {\n              const toolCall = ongoingToolCalls[value.output_index];\n\n              if (toolCall?.applyPatch && !toolCall.applyPatch.endEmitted) {\n                if (!toolCall.applyPatch.hasDiff) {\n                  controller.enqueue({\n                    type: 'tool-input-delta',\n                    id: toolCall.toolCallId,\n                    delta: escapeJSONDelta(value.diff),\n                  });\n\n                  toolCall.applyPatch.hasDiff = true;\n                }\n\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.toolCallId,\n                  delta: '\"}}',\n                });\n\n                controller.enqueue({\n                  type: 'tool-input-end',\n                  id: toolCall.toolCallId,\n                });\n\n                toolCall.applyPatch.endEmitted = true;\n              }\n            } else if (isResponseImageGenerationCallPartialImageChunk(value)) {\n              controller.enqueue({\n                type: 'tool-result',\n                toolCallId: value.item_id,\n                toolName: toolNameMapping.toCustomToolName('image_generation'),\n                result: {\n                  result: value.partial_image_b64,\n                } satisfies InferSchema<typeof imageGenerationOutputSchema>,\n                preliminary: true,\n              });\n            } else if (isResponseCodeInterpreterCallCodeDeltaChunk(value)) {\n              const toolCall = ongoingToolCalls[value.output_index];\n\n              if (toolCall != null) {\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.toolCallId,\n                  delta: escapeJSONDelta(value.delta),\n                });\n              }\n            } else if (isResponseCodeInterpreterCallCodeDoneChunk(value)) {\n              const toolCall = ongoingToolCalls[value.output_index];\n\n              if (toolCall != null) {\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.toolCallId,\n                  delta: '\"}',\n                });\n\n                controller.enqueue({\n                  type: 'tool-input-end',\n                  id: toolCall.toolCallId,\n                });\n\n                // immediately send the tool call after the input end:\n                controller.enqueue({\n                  type: 'tool-call',\n                  toolCallId: toolCall.toolCallId,\n                  toolName:\n                    toolNameMapping.toCustomToolName('code_interpreter'),\n                  input: JSON.stringify({\n                    code: value.code,\n                    containerId: toolCall.codeInterpreter!.containerId,\n                  } satisfies InferSchema<typeof codeInterpreterInputSchema>),\n                  providerExecuted: true,\n                });\n              }\n            } else if (isResponseCreatedChunk(value)) {\n              responseId = value.response.id;\n              controller.enqueue({\n                type: 'response-metadata',\n                id: value.response.id,\n                timestamp: new Date(value.response.created_at * 1000),\n                modelId: value.response.model,\n              });\n            } else if (isTextDeltaChunk(value)) {\n              controller.enqueue({\n                type: 'text-delta',\n                id: value.item_id,\n                delta: value.delta,\n              });\n\n              if (\n                options.providerOptions?.[providerOptionsName]?.logprobs &&\n                value.logprobs\n              ) {\n                logprobs.push(value.logprobs);\n              }\n            } else if (value.type === 'response.reasoning_summary_part.added') {\n              // the first reasoning start is pushed in isResponseOutputItemAddedReasoningChunk\n              if (value.summary_index > 0) {\n                const activeReasoningPart = activeReasoning[value.item_id]!;\n\n                activeReasoningPart.summaryParts[value.summary_index] =\n                  'active';\n\n                // since there is a new active summary part, we can conclude all can-conclude summary parts\n                for (const summaryIndex of Object.keys(\n                  activeReasoningPart.summaryParts,\n                )) {\n                  if (\n                    activeReasoningPart.summaryParts[summaryIndex] ===\n                    'can-conclude'\n                  ) {\n                    controller.enqueue({\n                      type: 'reasoning-end',\n                      id: `${value.item_id}:${summaryIndex}`,\n                      providerMetadata: {\n                        [providerOptionsName]: {\n                          itemId: value.item_id,\n                        } satisfies ResponsesReasoningProviderMetadata,\n                      },\n                    });\n                    activeReasoningPart.summaryParts[summaryIndex] =\n                      'concluded';\n                  }\n                }\n\n                controller.enqueue({\n                  type: 'reasoning-start',\n                  id: `${value.item_id}:${value.summary_index}`,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item_id,\n                      reasoningEncryptedContent:\n                        activeReasoning[value.item_id]?.encryptedContent ??\n                        null,\n                    } satisfies ResponsesReasoningProviderMetadata,\n                  },\n                });\n              }\n            } else if (value.type === 'response.reasoning_summary_text.delta') {\n              controller.enqueue({\n                type: 'reasoning-delta',\n                id: `${value.item_id}:${value.summary_index}`,\n                delta: value.delta,\n                providerMetadata: {\n                  [providerOptionsName]: {\n                    itemId: value.item_id,\n                  } satisfies ResponsesReasoningProviderMetadata,\n                },\n              });\n            } else if (value.type === 'response.reasoning_summary_part.done') {\n              // when OpenAI stores the message data, we can immediately conclude the reasoning part\n              // since we do not need to send the encrypted content.\n              if (store) {\n                controller.enqueue({\n                  type: 'reasoning-end',\n                  id: `${value.item_id}:${value.summary_index}`,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      itemId: value.item_id,\n                    } satisfies ResponsesReasoningProviderMetadata,\n                  },\n                });\n\n                // mark the summary part as concluded\n                activeReasoning[value.item_id]!.summaryParts[\n                  value.summary_index\n                ] = 'concluded';\n              } else {\n                // mark the summary part as can-conclude only\n                // because we need to have a final summary part with the encrypted content\n                activeReasoning[value.item_id]!.summaryParts[\n                  value.summary_index\n                ] = 'can-conclude';\n              }\n            } else if (isResponseFinishedChunk(value)) {\n              finishReason = {\n                unified: mapOpenAIResponseFinishReason({\n                  finishReason: value.response.incomplete_details?.reason,\n                  hasFunctionCall,\n                }),\n                raw: value.response.incomplete_details?.reason ?? undefined,\n              };\n              usage = value.response.usage;\n              if (typeof value.response.service_tier === 'string') {\n                serviceTier = value.response.service_tier;\n              }\n            } else if (isResponseFailedChunk(value)) {\n              const incompleteReason =\n                value.response.incomplete_details?.reason;\n              finishReason = {\n                unified: incompleteReason\n                  ? mapOpenAIResponseFinishReason({\n                      finishReason: incompleteReason,\n                      hasFunctionCall,\n                    })\n                  : 'error',\n                raw: incompleteReason ?? 'error',\n              };\n              usage = value.response.usage ?? undefined;\n            } else if (isResponseAnnotationAddedChunk(value)) {\n              ongoingAnnotations.push(value.annotation);\n              if (value.annotation.type === 'url_citation') {\n                controller.enqueue({\n                  type: 'source',\n                  sourceType: 'url',\n                  id: self.config.generateId?.() ?? generateId(),\n                  url: value.annotation.url,\n                  title: value.annotation.title,\n                });\n              } else if (value.annotation.type === 'file_citation') {\n                controller.enqueue({\n                  type: 'source',\n                  sourceType: 'document',\n                  id: self.config.generateId?.() ?? generateId(),\n                  mediaType: 'text/plain',\n                  title: value.annotation.filename,\n                  filename: value.annotation.filename,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      type: value.annotation.type,\n                      fileId: value.annotation.file_id,\n                      index: value.annotation.index,\n                    } satisfies Extract<\n                      ResponsesSourceDocumentProviderMetadata,\n                      { type: 'file_citation' }\n                    >,\n                  },\n                });\n              } else if (value.annotation.type === 'container_file_citation') {\n                controller.enqueue({\n                  type: 'source',\n                  sourceType: 'document',\n                  id: self.config.generateId?.() ?? generateId(),\n                  mediaType: 'text/plain',\n                  title: value.annotation.filename,\n                  filename: value.annotation.filename,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      type: value.annotation.type,\n                      fileId: value.annotation.file_id,\n                      containerId: value.annotation.container_id,\n                    } satisfies Extract<\n                      ResponsesSourceDocumentProviderMetadata,\n                      { type: 'container_file_citation' }\n                    >,\n                  },\n                });\n              } else if (value.annotation.type === 'file_path') {\n                controller.enqueue({\n                  type: 'source',\n                  sourceType: 'document',\n                  id: self.config.generateId?.() ?? generateId(),\n                  mediaType: 'application/octet-stream',\n                  title: value.annotation.file_id,\n                  filename: value.annotation.file_id,\n                  providerMetadata: {\n                    [providerOptionsName]: {\n                      type: value.annotation.type,\n                      fileId: value.annotation.file_id,\n                      index: value.annotation.index,\n                    } satisfies Extract<\n                      ResponsesSourceDocumentProviderMetadata,\n                      { type: 'file_path' }\n                    >,\n                  },\n                });\n              }\n            } else if (isErrorChunk(value)) {\n              controller.enqueue({ type: 'error', error: value });\n            }\n          },\n\n          flush(controller) {\n            const providerMetadata: SharedV3ProviderMetadata = {\n              [providerOptionsName]: {\n                responseId: responseId,\n                ...(logprobs.length > 0 ? { logprobs } : {}),\n                ...(serviceTier !== undefined ? { serviceTier } : {}),\n              } satisfies ResponsesProviderMetadata,\n            };\n\n            controller.enqueue({\n              type: 'finish',\n              finishReason,\n              usage: convertOpenAIResponsesUsage(usage),\n              providerMetadata,\n            });\n          },\n        }),\n      ),\n      request: { body },\n      response: { headers: responseHeaders },\n    };\n  }\n}\n\nfunction isTextDeltaChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & { type: 'response.output_text.delta' } {\n  return chunk.type === 'response.output_text.delta';\n}\n\nfunction isResponseOutputItemDoneChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & { type: 'response.output_item.done' } {\n  return chunk.type === 'response.output_item.done';\n}\n\nfunction isResponseFinishedChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & {\n  type: 'response.completed' | 'response.incomplete';\n} {\n  return (\n    chunk.type === 'response.completed' || chunk.type === 'response.incomplete'\n  );\n}\n\nfunction isResponseFailedChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & { type: 'response.failed' } {\n  return chunk.type === 'response.failed';\n}\n\nfunction isResponseCreatedChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & { type: 'response.created' } {\n  return chunk.type === 'response.created';\n}\n\nfunction isResponseFunctionCallArgumentsDeltaChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & {\n  type: 'response.function_call_arguments.delta';\n} {\n  return chunk.type === 'response.function_call_arguments.delta';\n}\n\nfunction isResponseCustomToolCallInputDeltaChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & {\n  type: 'response.custom_tool_call_input.delta';\n} {\n  return chunk.type === 'response.custom_tool_call_input.delta';\n}\n\nfunction isResponseImageGenerationCallPartialImageChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & {\n  type: 'response.image_generation_call.partial_image';\n} {\n  return chunk.type === 'response.image_generation_call.partial_image';\n}\n\nfunction isResponseCodeInterpreterCallCodeDeltaChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & {\n  type: 'response.code_interpreter_call_code.delta';\n} {\n  return chunk.type === 'response.code_interpreter_call_code.delta';\n}\n\nfunction isResponseCodeInterpreterCallCodeDoneChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & {\n  type: 'response.code_interpreter_call_code.done';\n} {\n  return chunk.type === 'response.code_interpreter_call_code.done';\n}\n\nfunction isResponseApplyPatchCallOperationDiffDeltaChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesApplyPatchOperationDiffDeltaChunk {\n  return chunk.type === 'response.apply_patch_call_operation_diff.delta';\n}\n\nfunction isResponseApplyPatchCallOperationDiffDoneChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesApplyPatchOperationDiffDoneChunk {\n  return chunk.type === 'response.apply_patch_call_operation_diff.done';\n}\n\nfunction isResponseOutputItemAddedChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & { type: 'response.output_item.added' } {\n  return chunk.type === 'response.output_item.added';\n}\n\nfunction isResponseAnnotationAddedChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & {\n  type: 'response.output_text.annotation.added';\n} {\n  return chunk.type === 'response.output_text.annotation.added';\n}\n\nfunction isErrorChunk(\n  chunk: OpenAIResponsesChunk,\n): chunk is OpenAIResponsesChunk & { type: 'error' } {\n  return chunk.type === 'error';\n}\n\nfunction mapWebSearchOutput(\n  action: OpenAIResponsesWebSearchAction | null | undefined,\n): InferSchema<typeof webSearchOutputSchema> {\n  if (action == null) {\n    return {};\n  }\n\n  switch (action.type) {\n    case 'search':\n      return {\n        action: { type: 'search', query: action.query ?? undefined },\n        // include sources when provided by the Responses API (behind include flag)\n        ...(action.sources != null && { sources: action.sources }),\n      };\n    case 'open_page':\n      return { action: { type: 'openPage', url: action.url } };\n    case 'find_in_page':\n      return {\n        action: {\n          type: 'findInPage',\n          url: action.url,\n          pattern: action.pattern,\n        },\n      };\n  }\n}\n\n// The delta is embedded in a JSON string.\n// To escape it, we use JSON.stringify and slice to remove the outer quotes.\nfunction escapeJSONDelta(delta: string) {\n  return JSON.stringify(delta).slice(1, -1);\n}\n", "import { LanguageModelV3Usage } from '@ai-sdk/provider';\n\nexport type OpenAIResponsesUsage = {\n  input_tokens: number;\n  output_tokens: number;\n  input_tokens_details?: {\n    cached_tokens?: number | null;\n  } | null;\n  output_tokens_details?: {\n    reasoning_tokens?: number | null;\n  } | null;\n};\n\nexport function convertOpenAIResponsesUsage(\n  usage: OpenAIResponsesUsage | undefined | null,\n): LanguageModelV3Usage {\n  if (usage == null) {\n    return {\n      inputTokens: {\n        total: undefined,\n        noCache: undefined,\n        cacheRead: undefined,\n        cacheWrite: undefined,\n      },\n      outputTokens: {\n        total: undefined,\n        text: undefined,\n        reasoning: undefined,\n      },\n      raw: undefined,\n    };\n  }\n\n  const inputTokens = usage.input_tokens;\n  const outputTokens = usage.output_tokens;\n  const cachedTokens = usage.input_tokens_details?.cached_tokens ?? 0;\n  const reasoningTokens = usage.output_tokens_details?.reasoning_tokens ?? 0;\n\n  return {\n    inputTokens: {\n      total: inputTokens,\n      noCache: inputTokens - cachedTokens,\n      cacheRead: cachedTokens,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: outputTokens,\n      text: outputTokens - reasoningTokens,\n      reasoning: reasoningTokens,\n    },\n    raw: usage,\n  };\n}\n", "import {\n  LanguageModelV3Prompt,\n  LanguageModelV3ToolApprovalResponsePart,\n  SharedV3Warning,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\nimport {\n  convertToBase64,\n  isNonNullable,\n  parseJSON,\n  parseProviderOptions,\n  ToolNameMapping,\n  validateTypes,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport {\n  applyPatchInputSchema,\n  applyPatchOutputSchema,\n} from '../tool/apply-patch';\nimport {\n  localShellInputSchema,\n  localShellOutputSchema,\n} from '../tool/local-shell';\nimport { shellInputSchema, shellOutputSchema } from '../tool/shell';\nimport {\n  toolSearchInputSchema,\n  toolSearchOutputSchema,\n} from '../tool/tool-search';\nimport {\n  OpenAIResponsesCustomToolCallOutput,\n  OpenAIResponsesFunctionCallOutput,\n  OpenAIResponsesInput,\n  OpenAIResponsesReasoning,\n} from './openai-responses-api';\n\n/**\n * Check if a string is a file ID based on the given prefixes\n * Returns false if prefixes is undefined (disables file ID detection)\n */\nfunction isFileId(data: string, prefixes?: readonly string[]): boolean {\n  if (!prefixes) return false;\n  return prefixes.some(prefix => data.startsWith(prefix));\n}\n\nexport async function convertToOpenAIResponsesInput({\n  prompt,\n  toolNameMapping,\n  systemMessageMode,\n  providerOptionsName,\n  fileIdPrefixes,\n  store,\n  hasConversation = false,\n  hasLocalShellTool = false,\n  hasShellTool = false,\n  hasApplyPatchTool = false,\n  customProviderToolNames,\n}: {\n  prompt: LanguageModelV3Prompt;\n  toolNameMapping: ToolNameMapping;\n  systemMessageMode: 'system' | 'developer' | 'remove';\n  providerOptionsName: string;\n  fileIdPrefixes?: readonly string[];\n  store: boolean;\n  hasConversation?: boolean; // when true, skip assistant messages that already have item IDs\n  hasLocalShellTool?: boolean;\n  hasShellTool?: boolean;\n  hasApplyPatchTool?: boolean;\n  customProviderToolNames?: Set<string>;\n}): Promise<{\n  input: OpenAIResponsesInput;\n  warnings: Array<SharedV3Warning>;\n}> {\n  let input: OpenAIResponsesInput = [];\n  const warnings: Array<SharedV3Warning> = [];\n  const processedApprovalIds = new Set<string>();\n\n  for (const { role, content } of prompt) {\n    switch (role) {\n      case 'system': {\n        switch (systemMessageMode) {\n          case 'system': {\n            input.push({ role: 'system', content });\n            break;\n          }\n          case 'developer': {\n            input.push({ role: 'developer', content });\n            break;\n          }\n          case 'remove': {\n            warnings.push({\n              type: 'other',\n              message: 'system messages are removed for this model',\n            });\n            break;\n          }\n          default: {\n            const _exhaustiveCheck: never = systemMessageMode;\n            throw new Error(\n              `Unsupported system message mode: ${_exhaustiveCheck}`,\n            );\n          }\n        }\n        break;\n      }\n\n      case 'user': {\n        input.push({\n          role: 'user',\n          content: content.map((part, index) => {\n            switch (part.type) {\n              case 'text': {\n                return { type: 'input_text', text: part.text };\n              }\n              case 'file': {\n                if (part.mediaType.startsWith('image/')) {\n                  const mediaType =\n                    part.mediaType === 'image/*'\n                      ? 'image/jpeg'\n                      : part.mediaType;\n\n                  return {\n                    type: 'input_image',\n                    ...(part.data instanceof URL\n                      ? { image_url: part.data.toString() }\n                      : typeof part.data === 'string' &&\n                          isFileId(part.data, fileIdPrefixes)\n                        ? { file_id: part.data }\n                        : {\n                            image_url: `data:${mediaType};base64,${convertToBase64(part.data)}`,\n                          }),\n                    detail:\n                      part.providerOptions?.[providerOptionsName]?.imageDetail,\n                  };\n                } else if (part.mediaType === 'application/pdf') {\n                  if (part.data instanceof URL) {\n                    return {\n                      type: 'input_file',\n                      file_url: part.data.toString(),\n                    };\n                  }\n                  return {\n                    type: 'input_file',\n                    ...(typeof part.data === 'string' &&\n                    isFileId(part.data, fileIdPrefixes)\n                      ? { file_id: part.data }\n                      : {\n                          filename: part.filename ?? `part-${index}.pdf`,\n                          file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`,\n                        }),\n                  };\n                } else {\n                  throw new UnsupportedFunctionalityError({\n                    functionality: `file part media type ${part.mediaType}`,\n                  });\n                }\n              }\n            }\n          }),\n        });\n\n        break;\n      }\n\n      case 'assistant': {\n        const reasoningMessages: Record<string, OpenAIResponsesReasoning> = {};\n\n        for (const part of content) {\n          switch (part.type) {\n            case 'text': {\n              const providerOpts = part.providerOptions?.[providerOptionsName];\n              const id = providerOpts?.itemId as string | undefined;\n              const phase = providerOpts?.phase as\n                | 'commentary'\n                | 'final_answer'\n                | null\n                | undefined;\n\n              // when using conversation, skip items that already exist in the conversation context to avoid \"Duplicate item found\" errors\n              if (hasConversation && id != null) {\n                break;\n              }\n\n              // item references reduce the payload size\n              if (store && id != null) {\n                input.push({ type: 'item_reference', id });\n                break;\n              }\n\n              input.push({\n                role: 'assistant',\n                content: [{ type: 'output_text', text: part.text }],\n                id,\n                ...(phase != null && { phase }),\n              });\n\n              break;\n            }\n            case 'tool-call': {\n              const id = (part.providerOptions?.[providerOptionsName]?.itemId ??\n                (\n                  part as {\n                    providerMetadata?: {\n                      [providerOptionsName]?: { itemId?: string };\n                    };\n                  }\n                ).providerMetadata?.[providerOptionsName]?.itemId) as\n                | string\n                | undefined;\n\n              if (hasConversation && id != null) {\n                break;\n              }\n\n              const resolvedToolName = toolNameMapping.toProviderToolName(\n                part.toolName,\n              );\n\n              if (resolvedToolName === 'tool_search') {\n                if (store && id != null) {\n                  input.push({ type: 'item_reference', id });\n                  break;\n                }\n\n                const parsedInput =\n                  typeof part.input === 'string'\n                    ? await parseJSON({\n                        text: part.input,\n                        schema: toolSearchInputSchema,\n                      })\n                    : await validateTypes({\n                        value: part.input,\n                        schema: toolSearchInputSchema,\n                      });\n\n                const execution =\n                  parsedInput.call_id != null ? 'client' : 'server';\n\n                input.push({\n                  type: 'tool_search_call',\n                  id: id ?? part.toolCallId,\n                  execution,\n                  call_id: parsedInput.call_id ?? null,\n                  status: 'completed',\n                  arguments: parsedInput.arguments,\n                });\n                break;\n              }\n\n              if (part.providerExecuted) {\n                if (store && id != null) {\n                  input.push({ type: 'item_reference', id });\n                }\n                break;\n              }\n\n              if (store && id != null) {\n                input.push({ type: 'item_reference', id });\n                break;\n              }\n\n              if (hasLocalShellTool && resolvedToolName === 'local_shell') {\n                const parsedInput = await validateTypes({\n                  value: part.input,\n                  schema: localShellInputSchema,\n                });\n                input.push({\n                  type: 'local_shell_call',\n                  call_id: part.toolCallId,\n                  id: id!,\n                  action: {\n                    type: 'exec',\n                    command: parsedInput.action.command,\n                    timeout_ms: parsedInput.action.timeoutMs,\n                    user: parsedInput.action.user,\n                    working_directory: parsedInput.action.workingDirectory,\n                    env: parsedInput.action.env,\n                  },\n                });\n\n                break;\n              }\n\n              if (hasShellTool && resolvedToolName === 'shell') {\n                const parsedInput = await validateTypes({\n                  value: part.input,\n                  schema: shellInputSchema,\n                });\n                input.push({\n                  type: 'shell_call',\n                  call_id: part.toolCallId,\n                  id: id!,\n                  status: 'completed',\n                  action: {\n                    commands: parsedInput.action.commands,\n                    timeout_ms: parsedInput.action.timeoutMs,\n                    max_output_length: parsedInput.action.maxOutputLength,\n                  },\n                });\n\n                break;\n              }\n\n              if (hasApplyPatchTool && resolvedToolName === 'apply_patch') {\n                const parsedInput = await validateTypes({\n                  value: part.input,\n                  schema: applyPatchInputSchema,\n                });\n                input.push({\n                  type: 'apply_patch_call',\n                  call_id: parsedInput.callId,\n                  id: id!,\n                  status: 'completed',\n                  operation: parsedInput.operation,\n                });\n\n                break;\n              }\n\n              if (customProviderToolNames?.has(resolvedToolName)) {\n                input.push({\n                  type: 'custom_tool_call',\n                  call_id: part.toolCallId,\n                  name: resolvedToolName,\n                  input:\n                    typeof part.input === 'string'\n                      ? part.input\n                      : JSON.stringify(part.input),\n                  id,\n                });\n                break;\n              }\n\n              input.push({\n                type: 'function_call',\n                call_id: part.toolCallId,\n                name: resolvedToolName,\n                arguments: JSON.stringify(part.input),\n                id,\n              });\n              break;\n            }\n\n            // assistant tool result parts are from provider-executed tools:\n            case 'tool-result': {\n              // Skip execution-denied results - these are synthetic results from denied\n              // approvals and have no corresponding item in OpenAI's store.\n              // Check both the direct type and if it was transformed to json with execution-denied inside\n              if (\n                part.output.type === 'execution-denied' ||\n                (part.output.type === 'json' &&\n                  typeof part.output.value === 'object' &&\n                  part.output.value != null &&\n                  'type' in part.output.value &&\n                  part.output.value.type === 'execution-denied')\n              ) {\n                break;\n              }\n\n              if (hasConversation) {\n                break;\n              }\n\n              const resolvedResultToolName = toolNameMapping.toProviderToolName(\n                part.toolName,\n              );\n\n              if (resolvedResultToolName === 'tool_search') {\n                const itemId =\n                  (\n                    part.providerOptions?.[providerOptionsName] as\n                      | { itemId?: string }\n                      | undefined\n                  )?.itemId ?? part.toolCallId;\n\n                if (store) {\n                  input.push({ type: 'item_reference', id: itemId });\n                } else if (part.output.type === 'json') {\n                  const parsedOutput = await validateTypes({\n                    value: part.output.value,\n                    schema: toolSearchOutputSchema,\n                  });\n\n                  input.push({\n                    type: 'tool_search_output',\n                    id: itemId,\n                    execution: 'server',\n                    call_id: null,\n                    status: 'completed',\n                    tools: parsedOutput.tools,\n                  });\n                }\n\n                break;\n              }\n\n              /*\n               * Shell tool results are separate output items (shell_call_output)\n               * with their own item IDs distinct from the shell_call's item ID.\n               * Since the pipeline only preserves the shell_call's item ID in\n               * callProviderMetadata, we reconstruct the full shell_call_output\n               * instead of using an item_reference with the wrong ID.\n               */\n              if (hasShellTool && resolvedResultToolName === 'shell') {\n                if (part.output.type === 'json') {\n                  const parsedOutput = await validateTypes({\n                    value: part.output.value,\n                    schema: shellOutputSchema,\n                  });\n                  input.push({\n                    type: 'shell_call_output',\n                    call_id: part.toolCallId,\n                    output: parsedOutput.output.map(item => ({\n                      stdout: item.stdout,\n                      stderr: item.stderr,\n                      outcome:\n                        item.outcome.type === 'timeout'\n                          ? { type: 'timeout' as const }\n                          : {\n                              type: 'exit' as const,\n                              exit_code: item.outcome.exitCode,\n                            },\n                    })),\n                  });\n                }\n                break;\n              }\n\n              if (store) {\n                const itemId =\n                  (\n                    part.providerOptions?.[providerOptionsName] as\n                      | { itemId?: string }\n                      | undefined\n                  )?.itemId ?? part.toolCallId;\n                input.push({ type: 'item_reference', id: itemId });\n              } else {\n                warnings.push({\n                  type: 'other',\n                  message: `Results for OpenAI tool ${part.toolName} are not sent to the API when store is false`,\n                });\n              }\n\n              break;\n            }\n\n            case 'reasoning': {\n              const providerOptions = await parseProviderOptions({\n                provider: providerOptionsName,\n                providerOptions: part.providerOptions,\n                schema: openaiResponsesReasoningProviderOptionsSchema,\n              });\n\n              const reasoningId = providerOptions?.itemId;\n\n              if (hasConversation && reasoningId != null) {\n                break;\n              }\n\n              if (reasoningId != null) {\n                const reasoningMessage = reasoningMessages[reasoningId];\n\n                if (store) {\n                  // use item references to refer to reasoning (single reference)\n                  // when the first part is encountered\n                  if (reasoningMessage === undefined) {\n                    input.push({ type: 'item_reference', id: reasoningId });\n\n                    // store unused reasoning message to mark id as used\n                    reasoningMessages[reasoningId] = {\n                      type: 'reasoning',\n                      id: reasoningId,\n                      summary: [],\n                    };\n                  }\n                } else {\n                  const summaryParts: Array<{\n                    type: 'summary_text';\n                    text: string;\n                  }> = [];\n\n                  if (part.text.length > 0) {\n                    summaryParts.push({\n                      type: 'summary_text',\n                      text: part.text,\n                    });\n                  } else if (reasoningMessage !== undefined) {\n                    warnings.push({\n                      type: 'other',\n                      message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.`,\n                    });\n                  }\n\n                  if (reasoningMessage === undefined) {\n                    reasoningMessages[reasoningId] = {\n                      type: 'reasoning',\n                      id: reasoningId,\n                      encrypted_content:\n                        providerOptions?.reasoningEncryptedContent,\n                      summary: summaryParts,\n                    };\n                    input.push(reasoningMessages[reasoningId]);\n                  } else {\n                    reasoningMessage.summary.push(...summaryParts);\n\n                    // updated encrypted content to enable setting it in the last summary part:\n                    if (providerOptions?.reasoningEncryptedContent != null) {\n                      reasoningMessage.encrypted_content =\n                        providerOptions.reasoningEncryptedContent;\n                    }\n                  }\n                }\n              } else {\n                // No itemId — fall back to encrypted_content if available.\n                // The OpenAI Responses API accepts reasoning items without an\n                // id when encrypted_content is provided, enabling multi-turn\n                // reasoning even when server-side item persistence is not used\n                // or when itemId has been stripped from providerOptions.\n                const encryptedContent =\n                  providerOptions?.reasoningEncryptedContent;\n\n                if (encryptedContent != null) {\n                  const summaryParts: Array<{\n                    type: 'summary_text';\n                    text: string;\n                  }> = [];\n                  if (part.text.length > 0) {\n                    summaryParts.push({\n                      type: 'summary_text',\n                      text: part.text,\n                    });\n                  }\n                  input.push({\n                    type: 'reasoning',\n                    encrypted_content: encryptedContent,\n                    summary: summaryParts,\n                  });\n                } else {\n                  warnings.push({\n                    type: 'other',\n                    message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.`,\n                  });\n                }\n              }\n              break;\n            }\n          }\n        }\n\n        break;\n      }\n\n      case 'tool': {\n        for (const part of content) {\n          if (part.type === 'tool-approval-response') {\n            const approvalResponse =\n              part as LanguageModelV3ToolApprovalResponsePart;\n\n            if (processedApprovalIds.has(approvalResponse.approvalId)) {\n              continue;\n            }\n            processedApprovalIds.add(approvalResponse.approvalId);\n\n            if (store) {\n              input.push({\n                type: 'item_reference',\n                id: approvalResponse.approvalId,\n              });\n            }\n\n            input.push({\n              type: 'mcp_approval_response',\n              approval_request_id: approvalResponse.approvalId,\n              approve: approvalResponse.approved,\n            });\n            continue;\n          }\n\n          const output = part.output;\n\n          // Skip execution-denied with approvalId - already handled via tool-approval-response\n          if (output.type === 'execution-denied') {\n            const approvalId = (\n              output.providerOptions?.openai as { approvalId?: string }\n            )?.approvalId;\n\n            if (approvalId) {\n              continue;\n            }\n          }\n\n          const resolvedToolName = toolNameMapping.toProviderToolName(\n            part.toolName,\n          );\n\n          if (resolvedToolName === 'tool_search' && output.type === 'json') {\n            const parsedOutput = await validateTypes({\n              value: output.value,\n              schema: toolSearchOutputSchema,\n            });\n\n            input.push({\n              type: 'tool_search_output',\n              execution: 'client',\n              call_id: part.toolCallId,\n              status: 'completed',\n              tools: parsedOutput.tools,\n            });\n            continue;\n          }\n\n          if (\n            hasLocalShellTool &&\n            resolvedToolName === 'local_shell' &&\n            output.type === 'json'\n          ) {\n            const parsedOutput = await validateTypes({\n              value: output.value,\n              schema: localShellOutputSchema,\n            });\n\n            input.push({\n              type: 'local_shell_call_output',\n              call_id: part.toolCallId,\n              output: parsedOutput.output,\n            });\n            continue;\n          }\n\n          if (\n            hasShellTool &&\n            resolvedToolName === 'shell' &&\n            output.type === 'json'\n          ) {\n            const parsedOutput = await validateTypes({\n              value: output.value,\n              schema: shellOutputSchema,\n            });\n\n            input.push({\n              type: 'shell_call_output',\n              call_id: part.toolCallId,\n              output: parsedOutput.output.map(item => ({\n                stdout: item.stdout,\n                stderr: item.stderr,\n                outcome:\n                  item.outcome.type === 'timeout'\n                    ? { type: 'timeout' as const }\n                    : {\n                        type: 'exit' as const,\n                        exit_code: item.outcome.exitCode,\n                      },\n              })),\n            });\n            continue;\n          }\n\n          if (\n            hasApplyPatchTool &&\n            part.toolName === 'apply_patch' &&\n            output.type === 'json'\n          ) {\n            const parsedOutput = await validateTypes({\n              value: output.value,\n              schema: applyPatchOutputSchema,\n            });\n\n            input.push({\n              type: 'apply_patch_call_output',\n              call_id: part.toolCallId,\n              status: parsedOutput.status,\n              output: parsedOutput.output,\n            });\n            continue;\n          }\n\n          if (customProviderToolNames?.has(resolvedToolName)) {\n            let outputValue: OpenAIResponsesCustomToolCallOutput['output'];\n            switch (output.type) {\n              case 'text':\n              case 'error-text':\n                outputValue = output.value;\n                break;\n              case 'execution-denied':\n                outputValue = output.reason ?? 'Tool execution denied.';\n                break;\n              case 'json':\n              case 'error-json':\n                outputValue = JSON.stringify(output.value);\n                break;\n              case 'content':\n                outputValue = output.value\n                  .map(item => {\n                    switch (item.type) {\n                      case 'text':\n                        return { type: 'input_text' as const, text: item.text };\n                      case 'image-data':\n                        return {\n                          type: 'input_image' as const,\n                          image_url: `data:${item.mediaType};base64,${item.data}`,\n                        };\n                      case 'image-url':\n                        return {\n                          type: 'input_image' as const,\n                          image_url: item.url,\n                        };\n                      case 'file-data':\n                        return {\n                          type: 'input_file' as const,\n                          filename: item.filename ?? 'data',\n                          file_data: `data:${item.mediaType};base64,${item.data}`,\n                        };\n                      case 'file-url':\n                        return {\n                          type: 'input_file' as const,\n                          file_url: item.url,\n                        };\n                      default:\n                        warnings.push({\n                          type: 'other',\n                          message: `unsupported custom tool content part type: ${item.type}`,\n                        });\n                        return undefined;\n                    }\n                  })\n                  .filter(isNonNullable);\n                break;\n              default:\n                outputValue = '';\n            }\n            input.push({\n              type: 'custom_tool_call_output',\n              call_id: part.toolCallId,\n              output: outputValue,\n            } satisfies OpenAIResponsesCustomToolCallOutput);\n            continue;\n          }\n\n          let contentValue: OpenAIResponsesFunctionCallOutput['output'];\n          switch (output.type) {\n            case 'text':\n            case 'error-text':\n              contentValue = output.value;\n              break;\n            case 'execution-denied':\n              contentValue = output.reason ?? 'Tool execution denied.';\n              break;\n            case 'json':\n            case 'error-json':\n              contentValue = JSON.stringify(output.value);\n              break;\n            case 'content':\n              contentValue = output.value\n                .map(item => {\n                  switch (item.type) {\n                    case 'text': {\n                      return { type: 'input_text' as const, text: item.text };\n                    }\n\n                    case 'image-data': {\n                      return {\n                        type: 'input_image' as const,\n                        image_url: `data:${item.mediaType};base64,${item.data}`,\n                      };\n                    }\n\n                    case 'image-url': {\n                      return {\n                        type: 'input_image' as const,\n                        image_url: item.url,\n                      };\n                    }\n\n                    case 'file-data': {\n                      return {\n                        type: 'input_file' as const,\n                        filename: item.filename ?? 'data',\n                        file_data: `data:${item.mediaType};base64,${item.data}`,\n                      };\n                    }\n\n                    case 'file-url': {\n                      return {\n                        type: 'input_file' as const,\n                        file_url: item.url,\n                      };\n                    }\n\n                    default: {\n                      warnings.push({\n                        type: 'other',\n                        message: `unsupported tool content part type: ${item.type}`,\n                      });\n                      return undefined;\n                    }\n                  }\n                })\n                .filter(isNonNullable);\n              break;\n          }\n\n          input.push({\n            type: 'function_call_output',\n            call_id: part.toolCallId,\n            output: contentValue,\n          });\n        }\n\n        break;\n      }\n\n      default: {\n        const _exhaustiveCheck: never = role;\n        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n      }\n    }\n  }\n\n  // when store is false, remove reasoning parts without encrypted content\n  if (\n    !store &&\n    input.some(\n      item =>\n        'type' in item &&\n        item.type === 'reasoning' &&\n        item.encrypted_content == null,\n    )\n  ) {\n    warnings.push({\n      type: 'other',\n      message:\n        'Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts.',\n    });\n    input = input.filter(\n      item =>\n        !('type' in item) ||\n        item.type !== 'reasoning' ||\n        item.encrypted_content != null,\n    );\n  }\n\n  return { input, warnings };\n}\n\nconst openaiResponsesReasoningProviderOptionsSchema = z.object({\n  itemId: z.string().nullish(),\n  reasoningEncryptedContent: z.string().nullish(),\n});\n\nexport type OpenAIResponsesReasoningProviderOptions = z.infer<\n  typeof openaiResponsesReasoningProviderOptionsSchema\n>;\n", "import { LanguageModelV3FinishReason } from '@ai-sdk/provider';\n\nexport function mapOpenAIResponseFinishReason({\n  finishReason,\n  hasFunctionCall,\n}: {\n  finishReason: string | null | undefined;\n  // flag that checks if there have been client-side tool calls (not executed by openai)\n  hasFunctionCall: boolean;\n}): LanguageModelV3FinishReason['unified'] {\n  switch (finishReason) {\n    case undefined:\n    case null:\n      return hasFunctionCall ? 'tool-calls' : 'stop';\n    case 'max_output_tokens':\n      return 'length';\n    case 'content_filter':\n      return 'content-filter';\n    default:\n      return hasFunctionCall ? 'tool-calls' : 'other';\n  }\n}\n", "import { JSONObject, JSONSchema7, JSONValue } from '@ai-sdk/provider';\nimport { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nconst jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>\n  z.union([\n    z.string(),\n    z.number(),\n    z.boolean(),\n    z.null(),\n    z.array(jsonValueSchema),\n    z.record(z.string(), jsonValueSchema.optional()),\n  ]),\n);\n\nexport type OpenAIResponsesInput = Array<OpenAIResponsesInputItem>;\n\nexport type OpenAIResponsesInputItem =\n  | OpenAIResponsesSystemMessage\n  | OpenAIResponsesUserMessage\n  | OpenAIResponsesAssistantMessage\n  | OpenAIResponsesFunctionCall\n  | OpenAIResponsesFunctionCallOutput\n  | OpenAIResponsesCustomToolCall\n  | OpenAIResponsesCustomToolCallOutput\n  | OpenAIResponsesMcpApprovalResponse\n  | OpenAIResponsesComputerCall\n  | OpenAIResponsesLocalShellCall\n  | OpenAIResponsesLocalShellCallOutput\n  | OpenAIResponsesShellCall\n  | OpenAIResponsesShellCallOutput\n  | OpenAIResponsesApplyPatchCall\n  | OpenAIResponsesApplyPatchCallOutput\n  | OpenAIResponsesToolSearchCall\n  | OpenAIResponsesToolSearchOutput\n  | OpenAIResponsesReasoning\n  | OpenAIResponsesItemReference;\n\nexport type OpenAIResponsesIncludeValue =\n  | 'web_search_call.action.sources'\n  | 'code_interpreter_call.outputs'\n  | 'computer_call_output.output.image_url'\n  | 'file_search_call.results'\n  | 'message.input_image.image_url'\n  | 'message.output_text.logprobs'\n  | 'reasoning.encrypted_content';\n\nexport type OpenAIResponsesIncludeOptions =\n  | Array<OpenAIResponsesIncludeValue>\n  | undefined\n  | null;\n\nexport type OpenAIResponsesApplyPatchOperationDiffDeltaChunk = {\n  type: 'response.apply_patch_call_operation_diff.delta';\n  item_id: string;\n  output_index: number;\n  delta: string;\n  obfuscation?: string | null;\n};\n\nexport type OpenAIResponsesApplyPatchOperationDiffDoneChunk = {\n  type: 'response.apply_patch_call_operation_diff.done';\n  item_id: string;\n  output_index: number;\n  diff: string;\n};\n\nexport type OpenAIResponsesSystemMessage = {\n  role: 'system' | 'developer';\n  content: string;\n};\n\nexport type OpenAIResponsesUserMessage = {\n  role: 'user';\n  content: Array<\n    | { type: 'input_text'; text: string }\n    | { type: 'input_image'; image_url: string }\n    | { type: 'input_image'; file_id: string }\n    | { type: 'input_file'; file_url: string }\n    | { type: 'input_file'; filename: string; file_data: string }\n    | { type: 'input_file'; file_id: string }\n  >;\n};\n\nexport type OpenAIResponsesAssistantMessage = {\n  role: 'assistant';\n  content: Array<{ type: 'output_text'; text: string }>;\n  id?: string;\n  phase?: 'commentary' | 'final_answer' | null;\n};\n\nexport type OpenAIResponsesFunctionCall = {\n  type: 'function_call';\n  call_id: string;\n  name: string;\n  arguments: string;\n  id?: string;\n};\n\nexport type OpenAIResponsesFunctionCallOutput = {\n  type: 'function_call_output';\n  call_id: string;\n  output:\n    | string\n    | Array<\n        | { type: 'input_text'; text: string }\n        | { type: 'input_image'; image_url: string }\n        | { type: 'input_file'; filename: string; file_data: string }\n        | { type: 'input_file'; file_url: string }\n      >;\n};\n\nexport type OpenAIResponsesCustomToolCall = {\n  type: 'custom_tool_call';\n  id?: string;\n  call_id: string;\n  name: string;\n  input: string;\n};\n\nexport type OpenAIResponsesCustomToolCallOutput = {\n  type: 'custom_tool_call_output';\n  call_id: string;\n  output: OpenAIResponsesFunctionCallOutput['output'];\n};\n\nexport type OpenAIResponsesMcpApprovalResponse = {\n  type: 'mcp_approval_response';\n  approval_request_id: string;\n  approve: boolean;\n};\n\nexport type OpenAIResponsesComputerCall = {\n  type: 'computer_call';\n  id: string;\n  status?: string;\n};\n\nexport type OpenAIResponsesLocalShellCall = {\n  type: 'local_shell_call';\n  id: string;\n  call_id: string;\n  action: {\n    type: 'exec';\n    command: string[];\n    timeout_ms?: number;\n    user?: string;\n    working_directory?: string;\n    env?: Record<string, string>;\n  };\n};\n\nexport type OpenAIResponsesLocalShellCallOutput = {\n  type: 'local_shell_call_output';\n  call_id: string;\n  output: string;\n};\n\n/**\n * Official OpenAI API Specifications: https://platform.openai.com/docs/api-reference/responses/object#responses-object-output-shell_tool_call\n */\nexport type OpenAIResponsesShellCall = {\n  type: 'shell_call';\n  id: string;\n  call_id: string;\n  status: 'in_progress' | 'completed' | 'incomplete';\n  action: {\n    commands: string[];\n    timeout_ms?: number;\n    max_output_length?: number;\n  };\n};\n\nexport type OpenAIResponsesShellCallOutput = {\n  type: 'shell_call_output';\n  id?: string;\n  call_id: string;\n  status?: 'in_progress' | 'completed' | 'incomplete';\n  max_output_length?: number | null;\n  output: Array<{\n    stdout: string;\n    stderr: string;\n    outcome: { type: 'timeout' } | { type: 'exit'; exit_code: number };\n  }>;\n};\n\nexport type OpenAIResponsesApplyPatchCall = {\n  type: 'apply_patch_call';\n  id?: string;\n  call_id: string;\n  status: 'in_progress' | 'completed';\n  operation:\n    | {\n        type: 'create_file';\n        path: string;\n        diff: string;\n      }\n    | {\n        type: 'delete_file';\n        path: string;\n      }\n    | {\n        type: 'update_file';\n        path: string;\n        diff: string;\n      };\n};\n\nexport type OpenAIResponsesApplyPatchCallOutput = {\n  type: 'apply_patch_call_output';\n  call_id: string;\n  status: 'completed' | 'failed';\n  output?: string;\n};\n\nexport type OpenAIResponsesToolSearchCall = {\n  type: 'tool_search_call';\n  id: string;\n  execution: 'server' | 'client';\n  call_id: string | null;\n  status: 'in_progress' | 'completed' | 'incomplete';\n  arguments: unknown;\n};\n\nexport type OpenAIResponsesToolSearchOutput = {\n  type: 'tool_search_output';\n  id?: string;\n  execution: 'server' | 'client';\n  call_id: string | null;\n  status: 'in_progress' | 'completed' | 'incomplete';\n  tools: Array<JSONObject>;\n};\n\nexport type OpenAIResponsesItemReference = {\n  type: 'item_reference';\n  id: string;\n};\n\n/**\n * A filter used to compare a specified attribute key to a given value using a defined comparison operation.\n */\nexport type OpenAIResponsesFileSearchToolComparisonFilter = {\n  /**\n   * The key to compare against the value.\n   */\n  key: string;\n\n  /**\n   * Specifies the comparison operator: eq, ne, gt, gte, lt, lte, in, nin.\n   */\n  type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'nin';\n\n  /**\n   * The value to compare against the attribute key; supports string, number, boolean, or array of string types.\n   */\n  value: string | number | boolean | string[];\n};\n\n/**\n * Combine multiple filters using and or or.\n */\nexport type OpenAIResponsesFileSearchToolCompoundFilter = {\n  /**\n   * Type of operation: and or or.\n   */\n  type: 'and' | 'or';\n\n  /**\n   * Array of filters to combine. Items can be ComparisonFilter or CompoundFilter.\n   */\n  filters: Array<\n    | OpenAIResponsesFileSearchToolComparisonFilter\n    | OpenAIResponsesFileSearchToolCompoundFilter\n  >;\n};\n\nexport type OpenAIResponsesTool =\n  | {\n      type: 'function';\n      name: string;\n      description: string | undefined;\n      parameters: JSONSchema7;\n      strict?: boolean;\n      defer_loading?: boolean;\n    }\n  | {\n      type: 'apply_patch';\n    }\n  | {\n      type: 'web_search';\n      external_web_access: boolean | undefined;\n      filters: { allowed_domains: string[] | undefined } | undefined;\n      search_context_size: 'low' | 'medium' | 'high' | undefined;\n      user_location:\n        | {\n            type: 'approximate';\n            city?: string;\n            country?: string;\n            region?: string;\n            timezone?: string;\n          }\n        | undefined;\n    }\n  | {\n      type: 'web_search_preview';\n      search_context_size: 'low' | 'medium' | 'high' | undefined;\n      user_location:\n        | {\n            type: 'approximate';\n            city?: string;\n            country?: string;\n            region?: string;\n            timezone?: string;\n          }\n        | undefined;\n    }\n  | {\n      type: 'code_interpreter';\n      container: string | { type: 'auto'; file_ids: string[] | undefined };\n    }\n  | {\n      type: 'file_search';\n      vector_store_ids: string[];\n      max_num_results: number | undefined;\n      ranking_options:\n        | { ranker?: string; score_threshold?: number }\n        | undefined;\n      filters:\n        | OpenAIResponsesFileSearchToolComparisonFilter\n        | OpenAIResponsesFileSearchToolCompoundFilter\n        | undefined;\n    }\n  | {\n      type: 'image_generation';\n      background: 'auto' | 'opaque' | 'transparent' | undefined;\n      input_fidelity: 'low' | 'high' | undefined;\n      input_image_mask:\n        | {\n            file_id: string | undefined;\n            image_url: string | undefined;\n          }\n        | undefined;\n      model: string | undefined;\n      moderation: 'auto' | undefined;\n      output_compression: number | undefined;\n      output_format: 'png' | 'jpeg' | 'webp' | undefined;\n      partial_images: number | undefined;\n      quality: 'auto' | 'low' | 'medium' | 'high' | undefined;\n      size: 'auto' | '1024x1024' | '1024x1536' | '1536x1024' | undefined;\n    }\n\n  /**\n   * Official OpenAI API Specifications: https://platform.openai.com/docs/api-reference/responses/create#responses_create-tools-mcp_tool\n   */\n  | {\n      type: 'mcp';\n      server_label: string;\n      allowed_tools:\n        | string[]\n        | {\n            read_only?: boolean;\n            tool_names?: string[];\n          }\n        | undefined;\n      authorization: string | undefined;\n      connector_id: string | undefined;\n      headers: Record<string, string> | undefined;\n      require_approval:\n        | 'always'\n        | 'never'\n        | {\n            never?: { tool_names?: string[] };\n          }\n        | undefined;\n      server_description: string | undefined;\n      server_url: string | undefined;\n    }\n  | {\n      type: 'custom';\n      name: string;\n      description?: string;\n      format?:\n        | {\n            type: 'grammar';\n            syntax: 'regex' | 'lark';\n            definition: string;\n          }\n        | {\n            type: 'text';\n          };\n    }\n  | {\n      type: 'local_shell';\n    }\n  | {\n      type: 'shell';\n      environment?:\n        | {\n            type: 'container_auto';\n            file_ids?: string[];\n            memory_limit?: '1g' | '4g' | '16g' | '64g';\n            network_policy?:\n              | { type: 'disabled' }\n              | {\n                  type: 'allowlist';\n                  allowed_domains: string[];\n                  domain_secrets?: Array<{\n                    domain: string;\n                    name: string;\n                    value: string;\n                  }>;\n                };\n            skills?: Array<\n              | {\n                  type: 'skill_reference';\n                  skill_id: string;\n                  version?: string;\n                }\n              | {\n                  type: 'inline';\n                  name: string;\n                  description: string;\n                  source: {\n                    type: 'base64';\n                    media_type: 'application/zip';\n                    data: string;\n                  };\n                }\n            >;\n          }\n        | {\n            type: 'container_reference';\n            container_id: string;\n          }\n        | {\n            type: 'local';\n            skills?: Array<{\n              name: string;\n              description: string;\n              path: string;\n            }>;\n          };\n    }\n  | {\n      type: 'tool_search';\n      execution?: 'server' | 'client';\n      description?: string;\n      parameters?: Record<string, unknown>;\n    };\n\nexport type OpenAIResponsesReasoning = {\n  type: 'reasoning';\n  id?: string;\n  encrypted_content?: string | null;\n  summary: Array<{\n    type: 'summary_text';\n    text: string;\n  }>;\n};\n\nexport const openaiResponsesChunkSchema = lazySchema(() =>\n  zodSchema(\n    z.union([\n      z.object({\n        type: z.literal('response.output_text.delta'),\n        item_id: z.string(),\n        delta: z.string(),\n        logprobs: z\n          .array(\n            z.object({\n              token: z.string(),\n              logprob: z.number(),\n              top_logprobs: z.array(\n                z.object({\n                  token: z.string(),\n                  logprob: z.number(),\n                }),\n              ),\n            }),\n          )\n          .nullish(),\n      }),\n      z.object({\n        type: z.enum(['response.completed', 'response.incomplete']),\n        response: z.object({\n          incomplete_details: z.object({ reason: z.string() }).nullish(),\n          usage: z.object({\n            input_tokens: z.number(),\n            input_tokens_details: z\n              .object({ cached_tokens: z.number().nullish() })\n              .nullish(),\n            output_tokens: z.number(),\n            output_tokens_details: z\n              .object({ reasoning_tokens: z.number().nullish() })\n              .nullish(),\n          }),\n          service_tier: z.string().nullish(),\n        }),\n      }),\n      z.object({\n        type: z.literal('response.failed'),\n        response: z.object({\n          error: z\n            .object({\n              code: z.string().nullish(),\n              message: z.string(),\n            })\n            .nullish(),\n          incomplete_details: z.object({ reason: z.string() }).nullish(),\n          usage: z\n            .object({\n              input_tokens: z.number(),\n              input_tokens_details: z\n                .object({ cached_tokens: z.number().nullish() })\n                .nullish(),\n              output_tokens: z.number(),\n              output_tokens_details: z\n                .object({ reasoning_tokens: z.number().nullish() })\n                .nullish(),\n            })\n            .nullish(),\n          service_tier: z.string().nullish(),\n        }),\n      }),\n      z.object({\n        type: z.literal('response.created'),\n        response: z.object({\n          id: z.string(),\n          created_at: z.number(),\n          model: z.string(),\n          service_tier: z.string().nullish(),\n        }),\n      }),\n      z.object({\n        type: z.literal('response.output_item.added'),\n        output_index: z.number(),\n        item: z.discriminatedUnion('type', [\n          z.object({\n            type: z.literal('message'),\n            id: z.string(),\n            phase: z.enum(['commentary', 'final_answer']).nullish(),\n          }),\n          z.object({\n            type: z.literal('reasoning'),\n            id: z.string(),\n            encrypted_content: z.string().nullish(),\n          }),\n          z.object({\n            type: z.literal('function_call'),\n            id: z.string(),\n            call_id: z.string(),\n            name: z.string(),\n            arguments: z.string(),\n          }),\n          z.object({\n            type: z.literal('web_search_call'),\n            id: z.string(),\n            status: z.string(),\n          }),\n          z.object({\n            type: z.literal('computer_call'),\n            id: z.string(),\n            status: z.string(),\n          }),\n          z.object({\n            type: z.literal('file_search_call'),\n            id: z.string(),\n          }),\n          z.object({\n            type: z.literal('image_generation_call'),\n            id: z.string(),\n          }),\n          z.object({\n            type: z.literal('code_interpreter_call'),\n            id: z.string(),\n            container_id: z.string(),\n            code: z.string().nullable(),\n            outputs: z\n              .array(\n                z.discriminatedUnion('type', [\n                  z.object({ type: z.literal('logs'), logs: z.string() }),\n                  z.object({ type: z.literal('image'), url: z.string() }),\n                ]),\n              )\n              .nullable(),\n            status: z.string(),\n          }),\n          z.object({\n            type: z.literal('mcp_call'),\n            id: z.string(),\n            status: z.string(),\n            approval_request_id: z.string().nullish(),\n          }),\n          z.object({\n            type: z.literal('mcp_list_tools'),\n            id: z.string(),\n          }),\n          z.object({\n            type: z.literal('mcp_approval_request'),\n            id: z.string(),\n          }),\n          z.object({\n            type: z.literal('apply_patch_call'),\n            id: z.string(),\n            call_id: z.string(),\n            status: z.enum(['in_progress', 'completed']),\n            operation: z.discriminatedUnion('type', [\n              z.object({\n                type: z.literal('create_file'),\n                path: z.string(),\n                diff: z.string(),\n              }),\n              z.object({\n                type: z.literal('delete_file'),\n                path: z.string(),\n              }),\n              z.object({\n                type: z.literal('update_file'),\n                path: z.string(),\n                diff: z.string(),\n              }),\n            ]),\n          }),\n          z.object({\n            type: z.literal('custom_tool_call'),\n            id: z.string(),\n            call_id: z.string(),\n            name: z.string(),\n            input: z.string(),\n          }),\n          z.object({\n            type: z.literal('shell_call'),\n            id: z.string(),\n            call_id: z.string(),\n            status: z.enum(['in_progress', 'completed', 'incomplete']),\n            action: z.object({\n              commands: z.array(z.string()),\n            }),\n          }),\n          z.object({\n            type: z.literal('shell_call_output'),\n            id: z.string(),\n            call_id: z.string(),\n            status: z.enum(['in_progress', 'completed', 'incomplete']),\n            output: z.array(\n              z.object({\n                stdout: z.string(),\n                stderr: z.string(),\n                outcome: z.discriminatedUnion('type', [\n                  z.object({ type: z.literal('timeout') }),\n                  z.object({\n                    type: z.literal('exit'),\n                    exit_code: z.number(),\n                  }),\n                ]),\n              }),\n            ),\n          }),\n          z.object({\n            type: z.literal('tool_search_call'),\n            id: z.string(),\n            execution: z.enum(['server', 'client']),\n            call_id: z.string().nullable(),\n            status: z.enum(['in_progress', 'completed', 'incomplete']),\n            arguments: z.unknown(),\n          }),\n          z.object({\n            type: z.literal('tool_search_output'),\n            id: z.string(),\n            execution: z.enum(['server', 'client']),\n            call_id: z.string().nullable(),\n            status: z.enum(['in_progress', 'completed', 'incomplete']),\n            tools: z.array(z.record(z.string(), jsonValueSchema.optional())),\n          }),\n        ]),\n      }),\n      z.object({\n        type: z.literal('response.output_item.done'),\n        output_index: z.number(),\n        item: z.discriminatedUnion('type', [\n          z.object({\n            type: z.literal('message'),\n            id: z.string(),\n            phase: z.enum(['commentary', 'final_answer']).nullish(),\n          }),\n          z.object({\n            type: z.literal('reasoning'),\n            id: z.string(),\n            encrypted_content: z.string().nullish(),\n          }),\n          z.object({\n            type: z.literal('function_call'),\n            id: z.string(),\n            call_id: z.string(),\n            name: z.string(),\n            arguments: z.string(),\n            status: z.literal('completed'),\n          }),\n          z.object({\n            type: z.literal('custom_tool_call'),\n            id: z.string(),\n            call_id: z.string(),\n            name: z.string(),\n            input: z.string(),\n            status: z.literal('completed'),\n          }),\n          z.object({\n            type: z.literal('code_interpreter_call'),\n            id: z.string(),\n            code: z.string().nullable(),\n            container_id: z.string(),\n            outputs: z\n              .array(\n                z.discriminatedUnion('type', [\n                  z.object({ type: z.literal('logs'), logs: z.string() }),\n                  z.object({ type: z.literal('image'), url: z.string() }),\n                ]),\n              )\n              .nullable(),\n          }),\n          z.object({\n            type: z.literal('image_generation_call'),\n            id: z.string(),\n            result: z.string(),\n          }),\n          z.object({\n            type: z.literal('web_search_call'),\n            id: z.string(),\n            status: z.string(),\n            action: z\n              .discriminatedUnion('type', [\n                z.object({\n                  type: z.literal('search'),\n                  query: z.string().nullish(),\n                  sources: z\n                    .array(\n                      z.discriminatedUnion('type', [\n                        z.object({ type: z.literal('url'), url: z.string() }),\n                        z.object({ type: z.literal('api'), name: z.string() }),\n                      ]),\n                    )\n                    .nullish(),\n                }),\n                z.object({\n                  type: z.literal('open_page'),\n                  url: z.string().nullish(),\n                }),\n                z.object({\n                  type: z.literal('find_in_page'),\n                  url: z.string().nullish(),\n                  pattern: z.string().nullish(),\n                }),\n              ])\n              .nullish(),\n          }),\n          z.object({\n            type: z.literal('file_search_call'),\n            id: z.string(),\n            queries: z.array(z.string()),\n            results: z\n              .array(\n                z.object({\n                  attributes: z.record(\n                    z.string(),\n                    z.union([z.string(), z.number(), z.boolean()]),\n                  ),\n                  file_id: z.string(),\n                  filename: z.string(),\n                  score: z.number(),\n                  text: z.string(),\n                }),\n              )\n              .nullish(),\n          }),\n          z.object({\n            type: z.literal('local_shell_call'),\n            id: z.string(),\n            call_id: z.string(),\n            action: z.object({\n              type: z.literal('exec'),\n              command: z.array(z.string()),\n              timeout_ms: z.number().optional(),\n              user: z.string().optional(),\n              working_directory: z.string().optional(),\n              env: z.record(z.string(), z.string()).optional(),\n            }),\n          }),\n          z.object({\n            type: z.literal('computer_call'),\n            id: z.string(),\n            status: z.literal('completed'),\n          }),\n          z.object({\n            type: z.literal('mcp_call'),\n            id: z.string(),\n            status: z.string(),\n            arguments: z.string(),\n            name: z.string(),\n            server_label: z.string(),\n            output: z.string().nullish(),\n            error: z\n              .union([\n                z.string(),\n                z\n                  .object({\n                    type: z.string().optional(),\n                    code: z.union([z.number(), z.string()]).optional(),\n                    message: z.string().optional(),\n                  })\n                  .loose(),\n              ])\n              .nullish(),\n            approval_request_id: z.string().nullish(),\n          }),\n          z.object({\n            type: z.literal('mcp_list_tools'),\n            id: z.string(),\n            server_label: z.string(),\n            tools: z.array(\n              z.object({\n                name: z.string(),\n                description: z.string().optional(),\n                input_schema: z.any(),\n                annotations: z.record(z.string(), z.unknown()).optional(),\n              }),\n            ),\n            error: z\n              .union([\n                z.string(),\n                z\n                  .object({\n                    type: z.string().optional(),\n                    code: z.union([z.number(), z.string()]).optional(),\n                    message: z.string().optional(),\n                  })\n                  .loose(),\n              ])\n              .optional(),\n          }),\n          z.object({\n            type: z.literal('mcp_approval_request'),\n            id: z.string(),\n            server_label: z.string(),\n            name: z.string(),\n            arguments: z.string(),\n            approval_request_id: z.string().optional(),\n          }),\n          z.object({\n            type: z.literal('apply_patch_call'),\n            id: z.string(),\n            call_id: z.string(),\n            status: z.enum(['in_progress', 'completed']),\n            operation: z.discriminatedUnion('type', [\n              z.object({\n                type: z.literal('create_file'),\n                path: z.string(),\n                diff: z.string(),\n              }),\n              z.object({\n                type: z.literal('delete_file'),\n                path: z.string(),\n              }),\n              z.object({\n                type: z.literal('update_file'),\n                path: z.string(),\n                diff: z.string(),\n              }),\n            ]),\n          }),\n          z.object({\n            type: z.literal('shell_call'),\n            id: z.string(),\n            call_id: z.string(),\n            status: z.enum(['in_progress', 'completed', 'incomplete']),\n            action: z.object({\n              commands: z.array(z.string()),\n            }),\n          }),\n          z.object({\n            type: z.literal('shell_call_output'),\n            id: z.string(),\n            call_id: z.string(),\n            status: z.enum(['in_progress', 'completed', 'incomplete']),\n            output: z.array(\n              z.object({\n                stdout: z.string(),\n                stderr: z.string(),\n                outcome: z.discriminatedUnion('type', [\n                  z.object({ type: z.literal('timeout') }),\n                  z.object({\n                    type: z.literal('exit'),\n                    exit_code: z.number(),\n                  }),\n                ]),\n              }),\n            ),\n          }),\n          z.object({\n            type: z.literal('tool_search_call'),\n            id: z.string(),\n            execution: z.enum(['server', 'client']),\n            call_id: z.string().nullable(),\n            status: z.enum(['in_progress', 'completed', 'incomplete']),\n            arguments: z.unknown(),\n          }),\n          z.object({\n            type: z.literal('tool_search_output'),\n            id: z.string(),\n            execution: z.enum(['server', 'client']),\n            call_id: z.string().nullable(),\n            status: z.enum(['in_progress', 'completed', 'incomplete']),\n            tools: z.array(z.record(z.string(), jsonValueSchema.optional())),\n          }),\n        ]),\n      }),\n      z.object({\n        type: z.literal('response.function_call_arguments.delta'),\n        item_id: z.string(),\n        output_index: z.number(),\n        delta: z.string(),\n      }),\n      z.object({\n        type: z.literal('response.custom_tool_call_input.delta'),\n        item_id: z.string(),\n        output_index: z.number(),\n        delta: z.string(),\n      }),\n      z.object({\n        type: z.literal('response.image_generation_call.partial_image'),\n        item_id: z.string(),\n        output_index: z.number(),\n        partial_image_b64: z.string(),\n      }),\n      z.object({\n        type: z.literal('response.code_interpreter_call_code.delta'),\n        item_id: z.string(),\n        output_index: z.number(),\n        delta: z.string(),\n      }),\n      z.object({\n        type: z.literal('response.code_interpreter_call_code.done'),\n        item_id: z.string(),\n        output_index: z.number(),\n        code: z.string(),\n      }),\n      z.object({\n        type: z.literal('response.output_text.annotation.added'),\n        annotation: z.discriminatedUnion('type', [\n          z.object({\n            type: z.literal('url_citation'),\n            start_index: z.number(),\n            end_index: z.number(),\n            url: z.string(),\n            title: z.string(),\n          }),\n          z.object({\n            type: z.literal('file_citation'),\n            file_id: z.string(),\n            filename: z.string(),\n            index: z.number(),\n          }),\n          z.object({\n            type: z.literal('container_file_citation'),\n            container_id: z.string(),\n            file_id: z.string(),\n            filename: z.string(),\n            start_index: z.number(),\n            end_index: z.number(),\n          }),\n          z.object({\n            type: z.literal('file_path'),\n            file_id: z.string(),\n            index: z.number(),\n          }),\n        ]),\n      }),\n      z.object({\n        type: z.literal('response.reasoning_summary_part.added'),\n        item_id: z.string(),\n        summary_index: z.number(),\n      }),\n      z.object({\n        type: z.literal('response.reasoning_summary_text.delta'),\n        item_id: z.string(),\n        summary_index: z.number(),\n        delta: z.string(),\n      }),\n      z.object({\n        type: z.literal('response.reasoning_summary_part.done'),\n        item_id: z.string(),\n        summary_index: z.number(),\n      }),\n      z.object({\n        type: z.literal('response.apply_patch_call_operation_diff.delta'),\n        item_id: z.string(),\n        output_index: z.number(),\n        delta: z.string(),\n        obfuscation: z.string().nullish(),\n      }),\n      z.object({\n        type: z.literal('response.apply_patch_call_operation_diff.done'),\n        item_id: z.string(),\n        output_index: z.number(),\n        diff: z.string(),\n      }),\n      z.object({\n        type: z.literal('error'),\n        sequence_number: z.number(),\n        error: z.object({\n          type: z.string(),\n          code: z.string(),\n          message: z.string(),\n          param: z.string().nullish(),\n        }),\n      }),\n      z\n        .object({ type: z.string() })\n        .loose()\n        .transform(value => ({\n          type: 'unknown_chunk' as const,\n          message: value.type,\n        })), // fallback for unknown chunks\n    ]),\n  ),\n);\n\nexport type OpenAIResponsesChunk = InferSchema<\n  typeof openaiResponsesChunkSchema\n>;\n\nexport type OpenAIResponsesLogprobs = NonNullable<\n  (OpenAIResponsesChunk & {\n    type: 'response.output_text.delta';\n  })['logprobs']\n> | null;\n\nexport type OpenAIResponsesWebSearchAction = NonNullable<\n  ((OpenAIResponsesChunk & {\n    type: 'response.output_item.done';\n  })['item'] & {\n    type: 'web_search_call';\n  })['action']\n>;\n\nexport const openaiResponsesResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      id: z.string().optional(),\n      created_at: z.number().optional(),\n      error: z\n        .object({\n          message: z.string(),\n          type: z.string(),\n          param: z.string().nullish(),\n          code: z.string(),\n        })\n        .nullish(),\n      model: z.string().optional(),\n      output: z\n        .array(\n          z.discriminatedUnion('type', [\n            z.object({\n              type: z.literal('message'),\n              role: z.literal('assistant'),\n              id: z.string(),\n              phase: z.enum(['commentary', 'final_answer']).nullish(),\n              content: z.array(\n                z.object({\n                  type: z.literal('output_text'),\n                  text: z.string(),\n                  logprobs: z\n                    .array(\n                      z.object({\n                        token: z.string(),\n                        logprob: z.number(),\n                        top_logprobs: z.array(\n                          z.object({\n                            token: z.string(),\n                            logprob: z.number(),\n                          }),\n                        ),\n                      }),\n                    )\n                    .nullish(),\n                  annotations: z.array(\n                    z.discriminatedUnion('type', [\n                      z.object({\n                        type: z.literal('url_citation'),\n                        start_index: z.number(),\n                        end_index: z.number(),\n                        url: z.string(),\n                        title: z.string(),\n                      }),\n                      z.object({\n                        type: z.literal('file_citation'),\n                        file_id: z.string(),\n                        filename: z.string(),\n                        index: z.number(),\n                      }),\n                      z.object({\n                        type: z.literal('container_file_citation'),\n                        container_id: z.string(),\n                        file_id: z.string(),\n                        filename: z.string(),\n                        start_index: z.number(),\n                        end_index: z.number(),\n                      }),\n                      z.object({\n                        type: z.literal('file_path'),\n                        file_id: z.string(),\n                        index: z.number(),\n                      }),\n                    ]),\n                  ),\n                }),\n              ),\n            }),\n            z.object({\n              type: z.literal('web_search_call'),\n              id: z.string(),\n              status: z.string(),\n              action: z\n                .discriminatedUnion('type', [\n                  z.object({\n                    type: z.literal('search'),\n                    query: z.string().nullish(),\n                    sources: z\n                      .array(\n                        z.discriminatedUnion('type', [\n                          z.object({ type: z.literal('url'), url: z.string() }),\n                          z.object({\n                            type: z.literal('api'),\n                            name: z.string(),\n                          }),\n                        ]),\n                      )\n                      .nullish(),\n                  }),\n                  z.object({\n                    type: z.literal('open_page'),\n                    url: z.string().nullish(),\n                  }),\n                  z.object({\n                    type: z.literal('find_in_page'),\n                    url: z.string().nullish(),\n                    pattern: z.string().nullish(),\n                  }),\n                ])\n                .nullish(),\n            }),\n            z.object({\n              type: z.literal('file_search_call'),\n              id: z.string(),\n              queries: z.array(z.string()),\n              results: z\n                .array(\n                  z.object({\n                    attributes: z.record(\n                      z.string(),\n                      z.union([z.string(), z.number(), z.boolean()]),\n                    ),\n                    file_id: z.string(),\n                    filename: z.string(),\n                    score: z.number(),\n                    text: z.string(),\n                  }),\n                )\n                .nullish(),\n            }),\n            z.object({\n              type: z.literal('code_interpreter_call'),\n              id: z.string(),\n              code: z.string().nullable(),\n              container_id: z.string(),\n              outputs: z\n                .array(\n                  z.discriminatedUnion('type', [\n                    z.object({ type: z.literal('logs'), logs: z.string() }),\n                    z.object({ type: z.literal('image'), url: z.string() }),\n                  ]),\n                )\n                .nullable(),\n            }),\n            z.object({\n              type: z.literal('image_generation_call'),\n              id: z.string(),\n              result: z.string(),\n            }),\n            z.object({\n              type: z.literal('local_shell_call'),\n              id: z.string(),\n              call_id: z.string(),\n              action: z.object({\n                type: z.literal('exec'),\n                command: z.array(z.string()),\n                timeout_ms: z.number().optional(),\n                user: z.string().optional(),\n                working_directory: z.string().optional(),\n                env: z.record(z.string(), z.string()).optional(),\n              }),\n            }),\n            z.object({\n              type: z.literal('function_call'),\n              call_id: z.string(),\n              name: z.string(),\n              arguments: z.string(),\n              id: z.string(),\n            }),\n            z.object({\n              type: z.literal('custom_tool_call'),\n              call_id: z.string(),\n              name: z.string(),\n              input: z.string(),\n              id: z.string(),\n            }),\n            z.object({\n              type: z.literal('computer_call'),\n              id: z.string(),\n              status: z.string().optional(),\n            }),\n            z.object({\n              type: z.literal('reasoning'),\n              id: z.string(),\n              encrypted_content: z.string().nullish(),\n              summary: z.array(\n                z.object({\n                  type: z.literal('summary_text'),\n                  text: z.string(),\n                }),\n              ),\n            }),\n            z.object({\n              type: z.literal('mcp_call'),\n              id: z.string(),\n              status: z.string(),\n              arguments: z.string(),\n              name: z.string(),\n              server_label: z.string(),\n              output: z.string().nullish(),\n              error: z\n                .union([\n                  z.string(),\n                  z\n                    .object({\n                      type: z.string().optional(),\n                      code: z.union([z.number(), z.string()]).optional(),\n                      message: z.string().optional(),\n                    })\n                    .loose(),\n                ])\n                .nullish(),\n              approval_request_id: z.string().nullish(),\n            }),\n            z.object({\n              type: z.literal('mcp_list_tools'),\n              id: z.string(),\n              server_label: z.string(),\n              tools: z.array(\n                z.object({\n                  name: z.string(),\n                  description: z.string().optional(),\n                  input_schema: z.any(),\n                  annotations: z.record(z.string(), z.unknown()).optional(),\n                }),\n              ),\n              error: z\n                .union([\n                  z.string(),\n                  z\n                    .object({\n                      type: z.string().optional(),\n                      code: z.union([z.number(), z.string()]).optional(),\n                      message: z.string().optional(),\n                    })\n                    .loose(),\n                ])\n                .optional(),\n            }),\n            z.object({\n              type: z.literal('mcp_approval_request'),\n              id: z.string(),\n              server_label: z.string(),\n              name: z.string(),\n              arguments: z.string(),\n              approval_request_id: z.string().optional(),\n            }),\n            z.object({\n              type: z.literal('apply_patch_call'),\n              id: z.string(),\n              call_id: z.string(),\n              status: z.enum(['in_progress', 'completed']),\n              operation: z.discriminatedUnion('type', [\n                z.object({\n                  type: z.literal('create_file'),\n                  path: z.string(),\n                  diff: z.string(),\n                }),\n                z.object({\n                  type: z.literal('delete_file'),\n                  path: z.string(),\n                }),\n                z.object({\n                  type: z.literal('update_file'),\n                  path: z.string(),\n                  diff: z.string(),\n                }),\n              ]),\n            }),\n            z.object({\n              type: z.literal('shell_call'),\n              id: z.string(),\n              call_id: z.string(),\n              status: z.enum(['in_progress', 'completed', 'incomplete']),\n              action: z.object({\n                commands: z.array(z.string()),\n              }),\n            }),\n            z.object({\n              type: z.literal('shell_call_output'),\n              id: z.string(),\n              call_id: z.string(),\n              status: z.enum(['in_progress', 'completed', 'incomplete']),\n              output: z.array(\n                z.object({\n                  stdout: z.string(),\n                  stderr: z.string(),\n                  outcome: z.discriminatedUnion('type', [\n                    z.object({ type: z.literal('timeout') }),\n                    z.object({\n                      type: z.literal('exit'),\n                      exit_code: z.number(),\n                    }),\n                  ]),\n                }),\n              ),\n            }),\n            z.object({\n              type: z.literal('tool_search_call'),\n              id: z.string(),\n              execution: z.enum(['server', 'client']),\n              call_id: z.string().nullable(),\n              status: z.enum(['in_progress', 'completed', 'incomplete']),\n              arguments: z.unknown(),\n            }),\n            z.object({\n              type: z.literal('tool_search_output'),\n              id: z.string(),\n              execution: z.enum(['server', 'client']),\n              call_id: z.string().nullable(),\n              status: z.enum(['in_progress', 'completed', 'incomplete']),\n              tools: z.array(z.record(z.string(), jsonValueSchema.optional())),\n            }),\n          ]),\n        )\n        .optional(),\n      service_tier: z.string().nullish(),\n      incomplete_details: z.object({ reason: z.string() }).nullish(),\n      usage: z\n        .object({\n          input_tokens: z.number(),\n          input_tokens_details: z\n            .object({ cached_tokens: z.number().nullish() })\n            .nullish(),\n          output_tokens: z.number(),\n          output_tokens_details: z\n            .object({ reasoning_tokens: z.number().nullish() })\n            .nullish(),\n        })\n        .optional(),\n    }),\n  ),\n);\n", "import { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n/**\n * `top_logprobs` request body argument can be set to an integer between\n * 0 and 20 specifying the number of most likely tokens to return at each\n * token position, each with an associated log probability.\n *\n * @see https://platform.openai.com/docs/api-reference/responses/create#responses_create-top_logprobs\n */\nexport const TOP_LOGPROBS_MAX = 20;\n\nexport const openaiResponsesReasoningModelIds = [\n  'o1',\n  'o1-2024-12-17',\n  'o3',\n  'o3-2025-04-16',\n  'o3-mini',\n  'o3-mini-2025-01-31',\n  'o4-mini',\n  'o4-mini-2025-04-16',\n  'gpt-5',\n  'gpt-5-2025-08-07',\n  'gpt-5-codex',\n  'gpt-5-mini',\n  'gpt-5-mini-2025-08-07',\n  'gpt-5-nano',\n  'gpt-5-nano-2025-08-07',\n  'gpt-5-pro',\n  'gpt-5-pro-2025-10-06',\n  'gpt-5.1',\n  'gpt-5.1-chat-latest',\n  'gpt-5.1-codex-mini',\n  'gpt-5.1-codex',\n  'gpt-5.1-codex-max',\n  'gpt-5.2',\n  'gpt-5.2-chat-latest',\n  'gpt-5.2-pro',\n  'gpt-5.2-codex',\n  'gpt-5.3-chat-latest',\n  'gpt-5.3-codex',\n  'gpt-5.4',\n  'gpt-5.4-2026-03-05',\n  'gpt-5.4-mini',\n  'gpt-5.4-mini-2026-03-17',\n  'gpt-5.4-nano',\n  'gpt-5.4-nano-2026-03-17',\n  'gpt-5.4-pro',\n  'gpt-5.4-pro-2026-03-05',\n] as const;\n\nexport const openaiResponsesModelIds = [\n  'gpt-4.1',\n  'gpt-4.1-2025-04-14',\n  'gpt-4.1-mini',\n  'gpt-4.1-mini-2025-04-14',\n  'gpt-4.1-nano',\n  'gpt-4.1-nano-2025-04-14',\n  'gpt-4o',\n  'gpt-4o-2024-05-13',\n  'gpt-4o-2024-08-06',\n  'gpt-4o-2024-11-20',\n  'gpt-4o-audio-preview',\n  'gpt-4o-audio-preview-2024-12-17',\n  'gpt-4o-search-preview',\n  'gpt-4o-search-preview-2025-03-11',\n  'gpt-4o-mini-search-preview',\n  'gpt-4o-mini-search-preview-2025-03-11',\n  'gpt-4o-mini',\n  'gpt-4o-mini-2024-07-18',\n  'gpt-3.5-turbo-0125',\n  'gpt-3.5-turbo',\n  'gpt-3.5-turbo-1106',\n  'gpt-5-chat-latest',\n  ...openaiResponsesReasoningModelIds,\n] as const;\n\nexport type OpenAIResponsesModelId =\n  | 'gpt-3.5-turbo-0125'\n  | 'gpt-3.5-turbo-1106'\n  | 'gpt-3.5-turbo'\n  | 'gpt-4.1-2025-04-14'\n  | 'gpt-4.1-mini-2025-04-14'\n  | 'gpt-4.1-mini'\n  | 'gpt-4.1-nano-2025-04-14'\n  | 'gpt-4.1-nano'\n  | 'gpt-4.1'\n  | 'gpt-4o-2024-05-13'\n  | 'gpt-4o-2024-08-06'\n  | 'gpt-4o-2024-11-20'\n  | 'gpt-4o-mini-2024-07-18'\n  | 'gpt-4o-mini'\n  | 'gpt-4o'\n  | 'gpt-5.1'\n  | 'gpt-5.1-2025-11-13'\n  | 'gpt-5.1-chat-latest'\n  | 'gpt-5.1-codex-mini'\n  | 'gpt-5.1-codex'\n  | 'gpt-5.1-codex-max'\n  | 'gpt-5.2'\n  | 'gpt-5.2-2025-12-11'\n  | 'gpt-5.2-chat-latest'\n  | 'gpt-5.2-pro'\n  | 'gpt-5.2-pro-2025-12-11'\n  | 'gpt-5.2-codex'\n  | 'gpt-5.3-chat-latest'\n  | 'gpt-5.3-codex'\n  | 'gpt-5.4'\n  | 'gpt-5.4-2026-03-05'\n  | 'gpt-5.4-mini'\n  | 'gpt-5.4-mini-2026-03-17'\n  | 'gpt-5.4-nano'\n  | 'gpt-5.4-nano-2026-03-17'\n  | 'gpt-5.4-pro'\n  | 'gpt-5.4-pro-2026-03-05'\n  | 'gpt-5-2025-08-07'\n  | 'gpt-5-chat-latest'\n  | 'gpt-5-codex'\n  | 'gpt-5-mini-2025-08-07'\n  | 'gpt-5-mini'\n  | 'gpt-5-nano-2025-08-07'\n  | 'gpt-5-nano'\n  | 'gpt-5-pro-2025-10-06'\n  | 'gpt-5-pro'\n  | 'gpt-5'\n  | 'o1-2024-12-17'\n  | 'o1'\n  | 'o3-2025-04-16'\n  | 'o3-mini-2025-01-31'\n  | 'o3-mini'\n  | 'o3'\n  | 'o4-mini'\n  | 'o4-mini-2025-04-16'\n  | (string & {});\n\n// TODO AI SDK 6: use optional here instead of nullish\nexport const openaiLanguageModelResponsesOptionsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      /**\n       * The ID of the OpenAI Conversation to continue.\n       * You must create a conversation first via the OpenAI API.\n       * Cannot be used in conjunction with `previousResponseId`.\n       * Defaults to `undefined`.\n       * @see https://platform.openai.com/docs/api-reference/conversations/create\n       */\n      conversation: z.string().nullish(),\n\n      /**\n       * The set of extra fields to include in the response (advanced, usually not needed).\n       * Example values: 'reasoning.encrypted_content', 'file_search_call.results', 'message.output_text.logprobs'.\n       */\n      include: z\n        .array(\n          z.enum([\n            'reasoning.encrypted_content', // handled internally by default, only needed for unknown reasoning models\n            'file_search_call.results',\n            'message.output_text.logprobs',\n          ]),\n        )\n        .nullish(),\n\n      /**\n       * Instructions for the model.\n       * They can be used to change the system or developer message when continuing a conversation using the `previousResponseId` option.\n       * Defaults to `undefined`.\n       */\n      instructions: z.string().nullish(),\n\n      /**\n       * Return the log probabilities of the tokens. Including logprobs will increase\n       * the response size and can slow down response times. However, it can\n       * be useful to better understand how the model is behaving.\n       *\n       * Setting to true will return the log probabilities of the tokens that\n       * were generated.\n       *\n       * Setting to a number will return the log probabilities of the top n\n       * tokens that were generated.\n       *\n       * @see https://platform.openai.com/docs/api-reference/responses/create\n       * @see https://cookbook.openai.com/examples/using_logprobs\n       */\n      logprobs: z\n        .union([z.boolean(), z.number().min(1).max(TOP_LOGPROBS_MAX)])\n        .optional(),\n\n      /**\n       * The maximum number of total calls to built-in tools that can be processed in a response.\n       * This maximum number applies across all built-in tool calls, not per individual tool.\n       * Any further attempts to call a tool by the model will be ignored.\n       */\n      maxToolCalls: z.number().nullish(),\n\n      /**\n       * Additional metadata to store with the generation.\n       */\n      metadata: z.any().nullish(),\n\n      /**\n       * Whether to use parallel tool calls. Defaults to `true`.\n       */\n      parallelToolCalls: z.boolean().nullish(),\n\n      /**\n       * The ID of the previous response. You can use it to continue a conversation.\n       * Defaults to `undefined`.\n       */\n      previousResponseId: z.string().nullish(),\n\n      /**\n       * Sets a cache key to tie this prompt to cached prefixes for better caching performance.\n       */\n      promptCacheKey: z.string().nullish(),\n\n      /**\n       * The retention policy for the prompt cache.\n       * - 'in_memory': Default. Standard prompt caching behavior.\n       * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours.\n       *          Currently only available for 5.1 series models.\n       *\n       * @default 'in_memory'\n       */\n      promptCacheRetention: z.enum(['in_memory', '24h']).nullish(),\n\n      /**\n       * Reasoning effort for reasoning models. Defaults to `medium`. If you use\n       * `providerOptions` to set the `reasoningEffort` option, this model setting will be ignored.\n       * Valid values: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'\n       *\n       * The 'none' type for `reasoningEffort` is only available for OpenAI's GPT-5.1\n       * models. Also, the 'xhigh' type for `reasoningEffort` is only available for\n       * OpenAI's GPT-5.1-Codex-Max model. Setting `reasoningEffort` to 'none' or 'xhigh' with unsupported models will result in\n       * an error.\n       */\n      reasoningEffort: z.string().nullish(),\n\n      /**\n       * Controls reasoning summary output from the model.\n       * Set to \"auto\" to automatically receive the richest level available,\n       * or \"detailed\" for comprehensive summaries.\n       */\n      reasoningSummary: z.string().nullish(),\n\n      /**\n       * The identifier for safety monitoring and tracking.\n       */\n      safetyIdentifier: z.string().nullish(),\n\n      /**\n       * Service tier for the request.\n       * Set to 'flex' for 50% cheaper processing at the cost of increased latency (available for o3, o4-mini, and gpt-5 models).\n       * Set to 'priority' for faster processing with Enterprise access (available for gpt-4, gpt-5, gpt-5-mini, o3, o4-mini; gpt-5-nano is not supported).\n       *\n       * Defaults to 'auto'.\n       */\n      serviceTier: z.enum(['auto', 'flex', 'priority', 'default']).nullish(),\n\n      /**\n       * Whether to store the generation. Defaults to `true`.\n       */\n      store: z.boolean().nullish(),\n\n      /**\n       * Whether to use strict JSON schema validation.\n       * Defaults to `true`.\n       */\n      strictJsonSchema: z.boolean().nullish(),\n\n      /**\n       * Controls the verbosity of the model's responses. Lower values ('low') will result\n       * in more concise responses, while higher values ('high') will result in more verbose responses.\n       * Valid values: 'low', 'medium', 'high'.\n       */\n      textVerbosity: z.enum(['low', 'medium', 'high']).nullish(),\n\n      /**\n       * Controls output truncation. 'auto' (default) performs truncation automatically;\n       * 'disabled' turns truncation off.\n       */\n      truncation: z.enum(['auto', 'disabled']).nullish(),\n\n      /**\n       * A unique identifier representing your end-user, which can help OpenAI to\n       * monitor and detect abuse.\n       * Defaults to `undefined`.\n       * @see https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids\n       */\n      user: z.string().nullish(),\n\n      /**\n       * Override the system message mode for this model.\n       * - 'system': Use the 'system' role for system messages (default for most models)\n       * - 'developer': Use the 'developer' role for system messages (used by reasoning models)\n       * - 'remove': Remove system messages entirely\n       *\n       * If not specified, the mode is automatically determined based on the model.\n       */\n      systemMessageMode: z.enum(['system', 'developer', 'remove']).optional(),\n\n      /**\n       * Force treating this model as a reasoning model.\n       *\n       * This is useful for \"stealth\" reasoning models (e.g. via a custom baseURL)\n       * where the model ID is not recognized by the SDK's allowlist.\n       *\n       * When enabled, the SDK applies reasoning-model parameter compatibility rules\n       * and defaults `systemMessageMode` to `developer` unless overridden.\n       */\n      forceReasoning: z.boolean().optional(),\n    }),\n  ),\n);\n\nexport type OpenAILanguageModelResponsesOptions = InferSchema<\n  typeof openaiLanguageModelResponsesOptionsSchema\n>;\n", "import {\n  LanguageModelV3CallOptions,\n  SharedV3Warning,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\nimport { ToolNameMapping, validateTypes } from '@ai-sdk/provider-utils';\nimport { codeInterpreterArgsSchema } from '../tool/code-interpreter';\nimport { fileSearchArgsSchema } from '../tool/file-search';\nimport { imageGenerationArgsSchema } from '../tool/image-generation';\nimport { customArgsSchema } from '../tool/custom';\nimport { mcpArgsSchema } from '../tool/mcp';\nimport { shellArgsSchema } from '../tool/shell';\nimport { toolSearchArgsSchema } from '../tool/tool-search';\nimport { webSearchArgsSchema } from '../tool/web-search';\nimport { webSearchPreviewArgsSchema } from '../tool/web-search-preview';\nimport { OpenAIResponsesTool } from './openai-responses-api';\n\nexport async function prepareResponsesTools({\n  tools,\n  toolChoice,\n  toolNameMapping,\n  customProviderToolNames,\n}: {\n  tools: LanguageModelV3CallOptions['tools'];\n  toolChoice: LanguageModelV3CallOptions['toolChoice'] | undefined;\n  toolNameMapping?: ToolNameMapping;\n  customProviderToolNames?: Set<string>;\n}): Promise<{\n  tools?: Array<OpenAIResponsesTool>;\n  toolChoice?:\n    | 'auto'\n    | 'none'\n    | 'required'\n    | { type: 'file_search' }\n    | { type: 'web_search_preview' }\n    | { type: 'web_search' }\n    | { type: 'function'; name: string }\n    | { type: 'custom'; name: string }\n    | { type: 'code_interpreter' }\n    | { type: 'mcp' }\n    | { type: 'image_generation' }\n    | { type: 'apply_patch' };\n  toolWarnings: SharedV3Warning[];\n}> {\n  // when the tools array is empty, change it to undefined to prevent errors:\n  tools = tools?.length ? tools : undefined;\n\n  const toolWarnings: SharedV3Warning[] = [];\n\n  if (tools == null) {\n    return { tools: undefined, toolChoice: undefined, toolWarnings };\n  }\n\n  const openaiTools: Array<OpenAIResponsesTool> = [];\n  const resolvedCustomProviderToolNames =\n    customProviderToolNames ?? new Set<string>();\n\n  for (const tool of tools) {\n    switch (tool.type) {\n      case 'function': {\n        const openaiOptions = tool.providerOptions?.openai as\n          | { deferLoading?: boolean }\n          | undefined;\n        const deferLoading = openaiOptions?.deferLoading;\n\n        openaiTools.push({\n          type: 'function',\n          name: tool.name,\n          description: tool.description,\n          parameters: tool.inputSchema,\n          ...(tool.strict != null ? { strict: tool.strict } : {}),\n          ...(deferLoading != null ? { defer_loading: deferLoading } : {}),\n        });\n        break;\n      }\n      case 'provider': {\n        switch (tool.id) {\n          case 'openai.file_search': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: fileSearchArgsSchema,\n            });\n\n            openaiTools.push({\n              type: 'file_search',\n              vector_store_ids: args.vectorStoreIds,\n              max_num_results: args.maxNumResults,\n              ranking_options: args.ranking\n                ? {\n                    ranker: args.ranking.ranker,\n                    score_threshold: args.ranking.scoreThreshold,\n                  }\n                : undefined,\n              filters: args.filters,\n            });\n\n            break;\n          }\n          case 'openai.local_shell': {\n            openaiTools.push({\n              type: 'local_shell',\n            });\n            break;\n          }\n          case 'openai.shell': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: shellArgsSchema,\n            });\n\n            openaiTools.push({\n              type: 'shell',\n              ...(args.environment && {\n                environment: mapShellEnvironment(args.environment),\n              }),\n            });\n            break;\n          }\n          case 'openai.apply_patch': {\n            openaiTools.push({\n              type: 'apply_patch',\n            });\n            break;\n          }\n          case 'openai.web_search_preview': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: webSearchPreviewArgsSchema,\n            });\n            openaiTools.push({\n              type: 'web_search_preview',\n              search_context_size: args.searchContextSize,\n              user_location: args.userLocation,\n            });\n            break;\n          }\n          case 'openai.web_search': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: webSearchArgsSchema,\n            });\n            openaiTools.push({\n              type: 'web_search',\n              filters:\n                args.filters != null\n                  ? { allowed_domains: args.filters.allowedDomains }\n                  : undefined,\n              external_web_access: args.externalWebAccess,\n              search_context_size: args.searchContextSize,\n              user_location: args.userLocation,\n            });\n            break;\n          }\n          case 'openai.code_interpreter': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: codeInterpreterArgsSchema,\n            });\n\n            openaiTools.push({\n              type: 'code_interpreter',\n              container:\n                args.container == null\n                  ? { type: 'auto', file_ids: undefined }\n                  : typeof args.container === 'string'\n                    ? args.container\n                    : { type: 'auto', file_ids: args.container.fileIds },\n            });\n            break;\n          }\n          case 'openai.image_generation': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: imageGenerationArgsSchema,\n            });\n\n            openaiTools.push({\n              type: 'image_generation',\n              background: args.background,\n              input_fidelity: args.inputFidelity,\n              input_image_mask: args.inputImageMask\n                ? {\n                    file_id: args.inputImageMask.fileId,\n                    image_url: args.inputImageMask.imageUrl,\n                  }\n                : undefined,\n              model: args.model,\n              moderation: args.moderation,\n              partial_images: args.partialImages,\n              quality: args.quality,\n              output_compression: args.outputCompression,\n              output_format: args.outputFormat,\n              size: args.size,\n            });\n            break;\n          }\n          case 'openai.mcp': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: mcpArgsSchema,\n            });\n\n            const mapApprovalFilter = (filter: { toolNames?: string[] }) => ({\n              tool_names: filter.toolNames,\n            });\n\n            const requireApproval = args.requireApproval;\n            const requireApprovalParam:\n              | 'always'\n              | 'never'\n              | {\n                  never?: { tool_names?: string[] };\n                }\n              | undefined =\n              requireApproval == null\n                ? undefined\n                : typeof requireApproval === 'string'\n                  ? requireApproval\n                  : requireApproval.never != null\n                    ? { never: mapApprovalFilter(requireApproval.never) }\n                    : undefined;\n\n            openaiTools.push({\n              type: 'mcp',\n              server_label: args.serverLabel,\n              allowed_tools: Array.isArray(args.allowedTools)\n                ? args.allowedTools\n                : args.allowedTools\n                  ? {\n                      read_only: args.allowedTools.readOnly,\n                      tool_names: args.allowedTools.toolNames,\n                    }\n                  : undefined,\n              authorization: args.authorization,\n              connector_id: args.connectorId,\n              headers: args.headers,\n              require_approval: requireApprovalParam ?? 'never',\n              server_description: args.serverDescription,\n              server_url: args.serverUrl,\n            });\n\n            break;\n          }\n          case 'openai.custom': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: customArgsSchema,\n            });\n\n            openaiTools.push({\n              type: 'custom',\n              name: args.name,\n              description: args.description,\n              format: args.format,\n            });\n            resolvedCustomProviderToolNames.add(args.name);\n            break;\n          }\n          case 'openai.tool_search': {\n            const args = await validateTypes({\n              value: tool.args,\n              schema: toolSearchArgsSchema,\n            });\n            openaiTools.push({\n              type: 'tool_search',\n              ...(args.execution != null ? { execution: args.execution } : {}),\n              ...(args.description != null\n                ? { description: args.description }\n                : {}),\n              ...(args.parameters != null\n                ? { parameters: args.parameters }\n                : {}),\n            });\n            break;\n          }\n        }\n        break;\n      }\n      default:\n        toolWarnings.push({\n          type: 'unsupported',\n          feature: `function tool ${tool}`,\n        });\n        break;\n    }\n  }\n\n  if (toolChoice == null) {\n    return { tools: openaiTools, toolChoice: undefined, toolWarnings };\n  }\n\n  const type = toolChoice.type;\n\n  switch (type) {\n    case 'auto':\n    case 'none':\n    case 'required':\n      return { tools: openaiTools, toolChoice: type, toolWarnings };\n    case 'tool': {\n      const resolvedToolName =\n        toolNameMapping?.toProviderToolName(toolChoice.toolName) ??\n        toolChoice.toolName;\n\n      return {\n        tools: openaiTools,\n        toolChoice:\n          resolvedToolName === 'code_interpreter' ||\n          resolvedToolName === 'file_search' ||\n          resolvedToolName === 'image_generation' ||\n          resolvedToolName === 'web_search_preview' ||\n          resolvedToolName === 'web_search' ||\n          resolvedToolName === 'mcp' ||\n          resolvedToolName === 'apply_patch'\n            ? { type: resolvedToolName }\n            : resolvedCustomProviderToolNames.has(resolvedToolName)\n              ? { type: 'custom', name: resolvedToolName }\n              : { type: 'function', name: resolvedToolName },\n        toolWarnings,\n      };\n    }\n    default: {\n      const _exhaustiveCheck: never = type;\n      throw new UnsupportedFunctionalityError({\n        functionality: `tool choice type: ${_exhaustiveCheck}`,\n      });\n    }\n  }\n}\n\nfunction mapShellEnvironment(environment: {\n  type?: string;\n  [key: string]: unknown;\n}): NonNullable<\n  Extract<OpenAIResponsesTool, { type: 'shell' }>['environment']\n> {\n  if (environment.type === 'containerReference') {\n    const env = environment as {\n      type: 'containerReference';\n      containerId: string;\n    };\n    return {\n      type: 'container_reference',\n      container_id: env.containerId,\n    };\n  }\n\n  if (environment.type === 'containerAuto') {\n    const env = environment as {\n      type: 'containerAuto';\n      fileIds?: string[];\n      memoryLimit?: '1g' | '4g' | '16g' | '64g';\n      networkPolicy?: {\n        type: string;\n        allowedDomains?: string[];\n        domainSecrets?: Array<{\n          domain: string;\n          name: string;\n          value: string;\n        }>;\n      };\n      skills?: Array<{\n        type: string;\n        skillId?: string;\n        version?: string;\n        name?: string;\n        description?: string;\n        source?: { type: string; mediaType: string; data: string };\n      }>;\n    };\n\n    return {\n      type: 'container_auto',\n      file_ids: env.fileIds,\n      memory_limit: env.memoryLimit,\n      network_policy:\n        env.networkPolicy == null\n          ? undefined\n          : env.networkPolicy.type === 'disabled'\n            ? { type: 'disabled' as const }\n            : {\n                type: 'allowlist' as const,\n                allowed_domains: env.networkPolicy.allowedDomains!,\n                domain_secrets: env.networkPolicy.domainSecrets,\n              },\n      skills: mapShellSkills(env.skills),\n    };\n  }\n\n  const env = environment as {\n    type?: 'local';\n    skills?: Array<{\n      name: string;\n      description: string;\n      path: string;\n    }>;\n  };\n  return {\n    type: 'local',\n    skills: env.skills,\n  };\n}\n\nfunction mapShellSkills(\n  skills:\n    | Array<{\n        type: string;\n        skillId?: string;\n        version?: string;\n        name?: string;\n        description?: string;\n        source?: { type: string; mediaType: string; data: string };\n      }>\n    | undefined,\n) {\n  return skills?.map(skill =>\n    skill.type === 'skillReference'\n      ? {\n          type: 'skill_reference' as const,\n          skill_id: skill.skillId!,\n          version: skill.version,\n        }\n      : {\n          type: 'inline' as const,\n          name: skill.name!,\n          description: skill.description!,\n          source: {\n            type: 'base64' as const,\n            media_type: skill.source!.mediaType as 'application/zip',\n            data: skill.source!.data,\n          },\n        },\n  );\n}\n", "import { SpeechModelV3, SharedV3Warning } from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createBinaryResponseHandler,\n  parseProviderOptions,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { OpenAIConfig } from '../openai-config';\nimport { openaiFailedResponseHandler } from '../openai-error';\nimport { OpenAISpeechAPITypes } from './openai-speech-api';\nimport {\n  openaiSpeechModelOptionsSchema,\n  OpenAISpeechModelId,\n} from './openai-speech-options';\n\ninterface OpenAISpeechModelConfig extends OpenAIConfig {\n  _internal?: {\n    currentDate?: () => Date;\n  };\n}\n\nexport class OpenAISpeechModel implements SpeechModelV3 {\n  readonly specificationVersion = 'v3';\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  constructor(\n    readonly modelId: OpenAISpeechModelId,\n    private readonly config: OpenAISpeechModelConfig,\n  ) {}\n\n  private async getArgs({\n    text,\n    voice = 'alloy',\n    outputFormat = 'mp3',\n    speed,\n    instructions,\n    language,\n    providerOptions,\n  }: Parameters<SpeechModelV3['doGenerate']>[0]) {\n    const warnings: SharedV3Warning[] = [];\n\n    // Parse provider options\n    const openAIOptions = await parseProviderOptions({\n      provider: 'openai',\n      providerOptions,\n      schema: openaiSpeechModelOptionsSchema,\n    });\n\n    // Create request body\n    const requestBody: Record<string, unknown> = {\n      model: this.modelId,\n      input: text,\n      voice,\n      response_format: 'mp3',\n      speed,\n      instructions,\n    };\n\n    if (outputFormat) {\n      if (['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm'].includes(outputFormat)) {\n        requestBody.response_format = outputFormat;\n      } else {\n        warnings.push({\n          type: 'unsupported',\n          feature: 'outputFormat',\n          details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`,\n        });\n      }\n    }\n\n    // Add provider-specific options\n    if (openAIOptions) {\n      const speechModelOptions: OpenAISpeechAPITypes = {};\n\n      for (const key in speechModelOptions) {\n        const value = speechModelOptions[key as keyof OpenAISpeechAPITypes];\n        if (value !== undefined) {\n          requestBody[key] = value;\n        }\n      }\n    }\n\n    if (language) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'language',\n        details: `OpenAI speech models do not support language selection. Language parameter \"${language}\" was ignored.`,\n      });\n    }\n\n    return {\n      requestBody,\n      warnings,\n    };\n  }\n\n  async doGenerate(\n    options: Parameters<SpeechModelV3['doGenerate']>[0],\n  ): Promise<Awaited<ReturnType<SpeechModelV3['doGenerate']>>> {\n    const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n    const { requestBody, warnings } = await this.getArgs(options);\n\n    const {\n      value: audio,\n      responseHeaders,\n      rawValue: rawResponse,\n    } = await postJsonToApi({\n      url: this.config.url({\n        path: '/audio/speech',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: requestBody,\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createBinaryResponseHandler(),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    return {\n      audio,\n      warnings,\n      request: {\n        body: JSON.stringify(requestBody),\n      },\n      response: {\n        timestamp: currentDate,\n        modelId: this.modelId,\n        headers: responseHeaders,\n        body: rawResponse,\n      },\n    };\n  }\n}\n", "import { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport type OpenAISpeechModelId =\n  | 'tts-1'\n  | 'tts-1-1106'\n  | 'tts-1-hd'\n  | 'tts-1-hd-1106'\n  | 'gpt-4o-mini-tts'\n  | 'gpt-4o-mini-tts-2025-03-20'\n  | 'gpt-4o-mini-tts-2025-12-15'\n  | (string & {});\n\n// https://platform.openai.com/docs/api-reference/audio/createSpeech\nexport const openaiSpeechModelOptionsSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      instructions: z.string().nullish(),\n      speed: z.number().min(0.25).max(4.0).default(1.0).nullish(),\n    }),\n  ),\n);\n\nexport type OpenAISpeechModelOptions = InferSchema<\n  typeof openaiSpeechModelOptionsSchema\n>;\n", "import {\n  TranscriptionModelV3,\n  TranscriptionModelV3CallOptions,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  convertBase64ToUint8Array,\n  createJsonResponseHandler,\n  mediaTypeToExtension,\n  parseProviderOptions,\n  postFormDataToApi,\n} from '@ai-sdk/provider-utils';\nimport { OpenAIConfig } from '../openai-config';\nimport { openaiFailedResponseHandler } from '../openai-error';\nimport { openaiTranscriptionResponseSchema } from './openai-transcription-api';\nimport {\n  OpenAITranscriptionModelId,\n  openAITranscriptionModelOptions,\n  OpenAITranscriptionModelOptions,\n} from './openai-transcription-options';\n\nexport type OpenAITranscriptionCallOptions = Omit<\n  TranscriptionModelV3CallOptions,\n  'providerOptions'\n> & {\n  providerOptions?: {\n    openai?: OpenAITranscriptionModelOptions;\n  };\n};\n\ninterface OpenAITranscriptionModelConfig extends OpenAIConfig {\n  _internal?: {\n    currentDate?: () => Date;\n  };\n}\n\n// https://platform.openai.com/docs/guides/speech-to-text#supported-languages\nconst languageMap = {\n  afrikaans: 'af',\n  arabic: 'ar',\n  armenian: 'hy',\n  azerbaijani: 'az',\n  belarusian: 'be',\n  bosnian: 'bs',\n  bulgarian: 'bg',\n  catalan: 'ca',\n  chinese: 'zh',\n  croatian: 'hr',\n  czech: 'cs',\n  danish: 'da',\n  dutch: 'nl',\n  english: 'en',\n  estonian: 'et',\n  finnish: 'fi',\n  french: 'fr',\n  galician: 'gl',\n  german: 'de',\n  greek: 'el',\n  hebrew: 'he',\n  hindi: 'hi',\n  hungarian: 'hu',\n  icelandic: 'is',\n  indonesian: 'id',\n  italian: 'it',\n  japanese: 'ja',\n  kannada: 'kn',\n  kazakh: 'kk',\n  korean: 'ko',\n  latvian: 'lv',\n  lithuanian: 'lt',\n  macedonian: 'mk',\n  malay: 'ms',\n  marathi: 'mr',\n  maori: 'mi',\n  nepali: 'ne',\n  norwegian: 'no',\n  persian: 'fa',\n  polish: 'pl',\n  portuguese: 'pt',\n  romanian: 'ro',\n  russian: 'ru',\n  serbian: 'sr',\n  slovak: 'sk',\n  slovenian: 'sl',\n  spanish: 'es',\n  swahili: 'sw',\n  swedish: 'sv',\n  tagalog: 'tl',\n  tamil: 'ta',\n  thai: 'th',\n  turkish: 'tr',\n  ukrainian: 'uk',\n  urdu: 'ur',\n  vietnamese: 'vi',\n  welsh: 'cy',\n};\n\nexport class OpenAITranscriptionModel implements TranscriptionModelV3 {\n  readonly specificationVersion = 'v3';\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  constructor(\n    readonly modelId: OpenAITranscriptionModelId,\n    private readonly config: OpenAITranscriptionModelConfig,\n  ) {}\n\n  private async getArgs({\n    audio,\n    mediaType,\n    providerOptions,\n  }: OpenAITranscriptionCallOptions) {\n    const warnings: SharedV3Warning[] = [];\n\n    // Parse provider options\n    const openAIOptions = await parseProviderOptions({\n      provider: 'openai',\n      providerOptions,\n      schema: openAITranscriptionModelOptions,\n    });\n\n    // Create form data with base fields\n    const formData = new FormData();\n    const blob =\n      audio instanceof Uint8Array\n        ? new Blob([audio])\n        : new Blob([convertBase64ToUint8Array(audio)]);\n\n    formData.append('model', this.modelId);\n    const fileExtension = mediaTypeToExtension(mediaType);\n    formData.append(\n      'file',\n      new File([blob], 'audio', { type: mediaType }),\n      `audio.${fileExtension}`,\n    );\n\n    // Add provider-specific options\n    if (openAIOptions) {\n      const transcriptionModelOptions = {\n        include: openAIOptions.include,\n        language: openAIOptions.language,\n        prompt: openAIOptions.prompt,\n        // https://platform.openai.com/docs/api-reference/audio/createTranscription#audio_createtranscription-response_format\n        // prefer verbose_json to get segments for models that support it\n        response_format: [\n          'gpt-4o-transcribe',\n          'gpt-4o-mini-transcribe',\n        ].includes(this.modelId)\n          ? 'json'\n          : 'verbose_json',\n        temperature: openAIOptions.temperature,\n        timestamp_granularities: openAIOptions.timestampGranularities,\n      };\n\n      for (const [key, value] of Object.entries(transcriptionModelOptions)) {\n        if (value != null) {\n          if (Array.isArray(value)) {\n            for (const item of value) {\n              formData.append(`${key}[]`, String(item));\n            }\n          } else {\n            formData.append(key, String(value));\n          }\n        }\n      }\n    }\n\n    return {\n      formData,\n      warnings,\n    };\n  }\n\n  async doGenerate(\n    options: OpenAITranscriptionCallOptions,\n  ): Promise<Awaited<ReturnType<TranscriptionModelV3['doGenerate']>>> {\n    const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n    const { formData, warnings } = await this.getArgs(options);\n\n    const {\n      value: response,\n      responseHeaders,\n      rawValue: rawResponse,\n    } = await postFormDataToApi({\n      url: this.config.url({\n        path: '/audio/transcriptions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      formData,\n      failedResponseHandler: openaiFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiTranscriptionResponseSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const language =\n      response.language != null && response.language in languageMap\n        ? languageMap[response.language as keyof typeof languageMap]\n        : undefined;\n\n    return {\n      text: response.text,\n      segments:\n        response.segments?.map(segment => ({\n          text: segment.text,\n          startSecond: segment.start,\n          endSecond: segment.end,\n        })) ??\n        response.words?.map(word => ({\n          text: word.word,\n          startSecond: word.start,\n          endSecond: word.end,\n        })) ??\n        [],\n      language,\n      durationInSeconds: response.duration ?? undefined,\n      warnings,\n      response: {\n        timestamp: currentDate,\n        modelId: this.modelId,\n        headers: responseHeaders,\n        body: rawResponse,\n      },\n    };\n  }\n}\n", "import { lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const openaiTranscriptionResponseSchema = lazySchema(() =>\n  zodSchema(\n    z.object({\n      text: z.string(),\n      language: z.string().nullish(),\n      duration: z.number().nullish(),\n      words: z\n        .array(\n          z.object({\n            word: z.string(),\n            start: z.number(),\n            end: z.number(),\n          }),\n        )\n        .nullish(),\n      segments: z\n        .array(\n          z.object({\n            id: z.number(),\n            seek: z.number(),\n            start: z.number(),\n            end: z.number(),\n            text: z.string(),\n            tokens: z.array(z.number()),\n            temperature: z.number(),\n            avg_logprob: z.number(),\n            compression_ratio: z.number(),\n            no_speech_prob: z.number(),\n          }),\n        )\n        .nullish(),\n    }),\n  ),\n);\n", "import { InferSchema, lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport type OpenAITranscriptionModelId =\n  | 'whisper-1'\n  | 'gpt-4o-mini-transcribe'\n  | 'gpt-4o-mini-transcribe-2025-03-20'\n  | 'gpt-4o-mini-transcribe-2025-12-15'\n  | 'gpt-4o-transcribe'\n  | 'gpt-4o-transcribe-diarize'\n  | (string & {});\n\n// https://platform.openai.com/docs/api-reference/audio/createTranscription\nexport const openAITranscriptionModelOptions = lazySchema(() =>\n  zodSchema(\n    z.object({\n      /**\n       * Additional information to include in the transcription response.\n       */\n\n      include: z.array(z.string()).optional(),\n\n      /**\n       * The language of the input audio in ISO-639-1 format.\n       */\n      language: z.string().optional(),\n\n      /**\n       * An optional text to guide the model's style or continue a previous audio segment.\n       */\n      prompt: z.string().optional(),\n\n      /**\n       * The sampling temperature, between 0 and 1.\n       * @default 0\n       */\n      temperature: z.number().min(0).max(1).default(0).optional(),\n\n      /**\n       * The timestamp granularities to populate for this transcription.\n       * @default ['segment']\n       */\n      timestampGranularities: z\n        .array(z.enum(['word', 'segment']))\n        .default(['segment'])\n        .optional(),\n    }),\n  ),\n);\n\nexport type OpenAITranscriptionModelOptions = InferSchema<\n  typeof openAITranscriptionModelOptions\n>;\n", "// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n", "import {\n  InvalidResponseDataError,\n  type APICallError,\n  type LanguageModelV3,\n  type LanguageModelV3CallOptions,\n  type LanguageModelV3Content,\n  type LanguageModelV3FinishReason,\n  type LanguageModelV3GenerateResult,\n  type LanguageModelV3StreamPart,\n  type LanguageModelV3StreamResult,\n  type LanguageModelV3Usage,\n  type SharedV3ProviderMetadata,\n  type SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  generateId,\n  isParsableJson,\n  parseProviderOptions,\n  postJsonToApi,\n  type FetchFunction,\n  type ParseResult,\n  type ResponseHandler,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { resolveProviderOptionsKey, toCamelCase } from '../utils/to-camel-case';\nimport {\n  defaultOpenAICompatibleErrorStructure,\n  type ProviderErrorStructure,\n} from '../openai-compatible-error';\nimport { convertOpenAICompatibleChatUsage } from './convert-openai-compatible-chat-usage';\nimport { convertToOpenAICompatibleChatMessages } from './convert-to-openai-compatible-chat-messages';\nimport { getResponseMetadata } from './get-response-metadata';\nimport { mapOpenAICompatibleFinishReason } from './map-openai-compatible-finish-reason';\nimport {\n  openaiCompatibleLanguageModelChatOptions,\n  type OpenAICompatibleChatModelId,\n} from './openai-compatible-chat-options';\nimport type { MetadataExtractor } from './openai-compatible-metadata-extractor';\nimport { prepareTools } from './openai-compatible-prepare-tools';\n\nexport type OpenAICompatibleChatConfig = {\n  provider: string;\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: FetchFunction;\n  includeUsage?: boolean;\n  errorStructure?: ProviderErrorStructure<any>;\n  metadataExtractor?: MetadataExtractor;\n\n  /**\n   * Whether the model supports structured outputs.\n   */\n  supportsStructuredOutputs?: boolean;\n\n  /**\n   * The supported URLs for the model.\n   */\n  supportedUrls?: () => LanguageModelV3['supportedUrls'];\n\n  /**\n   * Optional function to transform the request body before sending it to the API.\n   * This is useful for proxy providers that may require a different request format\n   * than the official OpenAI API.\n   */\n  transformRequestBody?: (args: Record<string, any>) => Record<string, any>;\n\n  /**\n   * Optional usage converter for OpenAI-compatible providers with different\n   * token accounting semantics.\n   */\n  convertUsage?: (\n    usage: z.infer<typeof openaiCompatibleTokenUsageSchema>,\n  ) => LanguageModelV3Usage;\n};\n\nexport class OpenAICompatibleChatLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = 'v3';\n\n  readonly supportsStructuredOutputs: boolean;\n\n  readonly modelId: OpenAICompatibleChatModelId;\n  private readonly config: OpenAICompatibleChatConfig;\n  private readonly failedResponseHandler: ResponseHandler<APICallError>;\n  private readonly chunkSchema; // type inferred via constructor\n\n  constructor(\n    modelId: OpenAICompatibleChatModelId,\n    config: OpenAICompatibleChatConfig,\n  ) {\n    this.modelId = modelId;\n    this.config = config;\n\n    // initialize error handling:\n    const errorStructure =\n      config.errorStructure ?? defaultOpenAICompatibleErrorStructure;\n    this.chunkSchema = createOpenAICompatibleChatChunkSchema(\n      errorStructure.errorSchema,\n    );\n    this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);\n\n    this.supportsStructuredOutputs = config.supportsStructuredOutputs ?? false;\n  }\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  private get providerOptionsName(): string {\n    return this.config.provider.split('.')[0].trim();\n  }\n\n  get supportedUrls() {\n    return this.config.supportedUrls?.() ?? {};\n  }\n\n  private transformRequestBody(args: Record<string, any>): Record<string, any> {\n    return this.config.transformRequestBody?.(args) ?? args;\n  }\n\n  private convertUsage(\n    usage: z.infer<typeof openaiCompatibleTokenUsageSchema>,\n  ): LanguageModelV3Usage {\n    return (\n      this.config.convertUsage?.(usage) ??\n      convertOpenAICompatibleChatUsage(usage)\n    );\n  }\n\n  private async getArgs({\n    prompt,\n    maxOutputTokens,\n    temperature,\n    topP,\n    topK,\n    frequencyPenalty,\n    presencePenalty,\n    providerOptions,\n    stopSequences,\n    responseFormat,\n    seed,\n    toolChoice,\n    tools,\n  }: LanguageModelV3CallOptions) {\n    const warnings: SharedV3Warning[] = [];\n\n    // Parse provider options - check for deprecated 'openai-compatible' key\n    const deprecatedOptions = await parseProviderOptions({\n      provider: 'openai-compatible',\n      providerOptions,\n      schema: openaiCompatibleLanguageModelChatOptions,\n    });\n\n    if (deprecatedOptions != null) {\n      warnings.push({\n        type: 'other',\n        message: `The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead.`,\n      });\n    }\n\n    const compatibleOptions = Object.assign(\n      deprecatedOptions ?? {},\n      (await parseProviderOptions({\n        provider: 'openaiCompatible',\n        providerOptions,\n        schema: openaiCompatibleLanguageModelChatOptions,\n      })) ?? {},\n      (await parseProviderOptions({\n        provider: this.providerOptionsName,\n        providerOptions,\n        schema: openaiCompatibleLanguageModelChatOptions,\n      })) ?? {},\n      (await parseProviderOptions({\n        provider: toCamelCase(this.providerOptionsName),\n        providerOptions,\n        schema: openaiCompatibleLanguageModelChatOptions,\n      })) ?? {},\n    );\n\n    const strictJsonSchema = compatibleOptions?.strictJsonSchema ?? true;\n\n    if (topK != null) {\n      warnings.push({ type: 'unsupported', feature: 'topK' });\n    }\n\n    if (\n      responseFormat?.type === 'json' &&\n      responseFormat.schema != null &&\n      !this.supportsStructuredOutputs\n    ) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'responseFormat',\n        details:\n          'JSON response format schema is only supported with structuredOutputs',\n      });\n    }\n\n    const {\n      tools: openaiTools,\n      toolChoice: openaiToolChoice,\n      toolWarnings,\n    } = prepareTools({\n      tools,\n      toolChoice,\n    });\n\n    const metadataKey = resolveProviderOptionsKey(\n      this.providerOptionsName,\n      providerOptions,\n    );\n\n    return {\n      metadataKey,\n      args: {\n        // model id:\n        model: this.modelId,\n\n        // model specific settings:\n        user: compatibleOptions.user,\n\n        // standardized settings:\n        max_tokens: maxOutputTokens,\n        temperature,\n        top_p: topP,\n        frequency_penalty: frequencyPenalty,\n        presence_penalty: presencePenalty,\n        response_format:\n          responseFormat?.type === 'json'\n            ? this.supportsStructuredOutputs === true &&\n              responseFormat.schema != null\n              ? {\n                  type: 'json_schema',\n                  json_schema: {\n                    schema: responseFormat.schema,\n                    strict: strictJsonSchema,\n                    name: responseFormat.name ?? 'response',\n                    description: responseFormat.description,\n                  },\n                }\n              : { type: 'json_object' }\n            : undefined,\n\n        stop: stopSequences,\n        seed,\n        ...Object.fromEntries(\n          Object.entries({\n            ...providerOptions?.[this.providerOptionsName],\n            ...providerOptions?.[toCamelCase(this.providerOptionsName)],\n          }).filter(\n            ([key]) =>\n              !Object.keys(\n                openaiCompatibleLanguageModelChatOptions.shape,\n              ).includes(key),\n          ),\n        ),\n\n        reasoning_effort: compatibleOptions.reasoningEffort,\n        verbosity: compatibleOptions.textVerbosity,\n\n        // messages:\n        messages: convertToOpenAICompatibleChatMessages(prompt),\n\n        // tools:\n        tools: openaiTools,\n        tool_choice: openaiToolChoice,\n      },\n      warnings: [...warnings, ...toolWarnings],\n    };\n  }\n\n  async doGenerate(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3GenerateResult> {\n    const { args, warnings, metadataKey } = await this.getArgs({ ...options });\n\n    const transformedBody = this.transformRequestBody(args);\n    const body = JSON.stringify(transformedBody);\n\n    const {\n      responseHeaders,\n      value: responseBody,\n      rawValue: rawResponse,\n    } = await postJsonToApi({\n      url: this.config.url({\n        path: '/chat/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: transformedBody,\n      failedResponseHandler: this.failedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        OpenAICompatibleChatResponseSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const choice = responseBody.choices[0];\n    const content: Array<LanguageModelV3Content> = [];\n\n    // text content:\n    const text = choice.message.content;\n    if (text != null && text.length > 0) {\n      content.push({ type: 'text', text });\n    }\n\n    // reasoning content:\n    const reasoning =\n      choice.message.reasoning_content ?? choice.message.reasoning;\n    if (reasoning != null && reasoning.length > 0) {\n      content.push({\n        type: 'reasoning',\n        text: reasoning,\n      });\n    }\n\n    // tool calls:\n    if (choice.message.tool_calls != null) {\n      for (const toolCall of choice.message.tool_calls) {\n        const thoughtSignature =\n          toolCall.extra_content?.google?.thought_signature;\n        content.push({\n          type: 'tool-call',\n          toolCallId: toolCall.id ?? generateId(),\n          toolName: toolCall.function.name,\n          input: toolCall.function.arguments!,\n          ...(thoughtSignature\n            ? {\n                providerMetadata: {\n                  [metadataKey]: { thoughtSignature },\n                },\n              }\n            : {}),\n        });\n      }\n    }\n\n    // provider metadata:\n    const providerMetadata: SharedV3ProviderMetadata = {\n      [metadataKey]: {},\n      ...(await this.config.metadataExtractor?.extractMetadata?.({\n        parsedBody: rawResponse,\n      })),\n    };\n    const completionTokenDetails =\n      responseBody.usage?.completion_tokens_details;\n    if (completionTokenDetails?.accepted_prediction_tokens != null) {\n      providerMetadata[metadataKey].acceptedPredictionTokens =\n        completionTokenDetails?.accepted_prediction_tokens;\n    }\n    if (completionTokenDetails?.rejected_prediction_tokens != null) {\n      providerMetadata[metadataKey].rejectedPredictionTokens =\n        completionTokenDetails?.rejected_prediction_tokens;\n    }\n\n    return {\n      content,\n      finishReason: {\n        unified: mapOpenAICompatibleFinishReason(choice.finish_reason),\n        raw: choice.finish_reason ?? undefined,\n      },\n      usage: this.convertUsage(responseBody.usage),\n      providerMetadata,\n      request: { body },\n      response: {\n        ...getResponseMetadata(responseBody),\n        headers: responseHeaders,\n        body: rawResponse,\n      },\n      warnings,\n    };\n  }\n\n  async doStream(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3StreamResult> {\n    const { args, warnings, metadataKey } = await this.getArgs({ ...options });\n\n    const body = this.transformRequestBody({\n      ...args,\n      stream: true,\n\n      // only include stream_options when in strict compatibility mode:\n      stream_options: this.config.includeUsage\n        ? { include_usage: true }\n        : undefined,\n    });\n\n    const metadataExtractor =\n      this.config.metadataExtractor?.createStreamExtractor();\n\n    const { responseHeaders, value: response } = await postJsonToApi({\n      url: this.config.url({\n        path: '/chat/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body,\n      failedResponseHandler: this.failedResponseHandler,\n      successfulResponseHandler: createEventSourceResponseHandler(\n        this.chunkSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const toolCalls: Array<{\n      id: string;\n      type: 'function';\n      function: {\n        name: string;\n        arguments: string;\n      };\n      hasFinished: boolean;\n      thoughtSignature?: string;\n    }> = [];\n\n    let finishReason: LanguageModelV3FinishReason = {\n      unified: 'other',\n      raw: undefined,\n    };\n    let usage: z.infer<typeof openaiCompatibleTokenUsageSchema> | undefined =\n      undefined;\n    let isFirstChunk = true;\n    const providerOptionsName = metadataKey;\n    let isActiveReasoning = false;\n    let isActiveText = false;\n    const convertUsage = (\n      usage: z.infer<typeof openaiCompatibleTokenUsageSchema>,\n    ) => this.convertUsage(usage);\n\n    return {\n      stream: response.pipeThrough(\n        new TransformStream<\n          ParseResult<z.infer<typeof this.chunkSchema>>,\n          LanguageModelV3StreamPart\n        >({\n          start(controller) {\n            controller.enqueue({ type: 'stream-start', warnings });\n          },\n\n          transform(chunk, controller) {\n            // Emit raw chunk if requested (before anything else)\n            if (options.includeRawChunks) {\n              controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n            }\n\n            // handle failed chunk parsing / validation:\n            if (!chunk.success) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({ type: 'error', error: chunk.error });\n              return;\n            }\n\n            metadataExtractor?.processChunk(chunk.rawValue);\n\n            // handle error chunks:\n            if ('error' in chunk.value) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({\n                type: 'error',\n                error: chunk.value.error.message,\n              });\n              return;\n            }\n\n            // TODO we lost type safety on Chunk, most likely due to the error schema. MUST FIX\n            // remove this workaround when the issue is fixed\n            const value = chunk.value as z.infer<typeof chunkBaseSchema>;\n\n            if (isFirstChunk) {\n              isFirstChunk = false;\n\n              controller.enqueue({\n                type: 'response-metadata',\n                ...getResponseMetadata(value),\n              });\n            }\n\n            if (value.usage != null) {\n              usage = value.usage;\n            }\n\n            const choice = value.choices[0];\n\n            if (choice?.finish_reason != null) {\n              finishReason = {\n                unified: mapOpenAICompatibleFinishReason(choice.finish_reason),\n                raw: choice.finish_reason ?? undefined,\n              };\n            }\n\n            if (choice?.delta == null) {\n              return;\n            }\n\n            const delta = choice.delta;\n\n            // enqueue reasoning before text deltas:\n            const reasoningContent = delta.reasoning_content ?? delta.reasoning;\n            if (reasoningContent) {\n              if (!isActiveReasoning) {\n                controller.enqueue({\n                  type: 'reasoning-start',\n                  id: 'reasoning-0',\n                });\n                isActiveReasoning = true;\n              }\n\n              controller.enqueue({\n                type: 'reasoning-delta',\n                id: 'reasoning-0',\n                delta: reasoningContent,\n              });\n            }\n\n            if (delta.content) {\n              // end active reasoning block before text starts\n              if (isActiveReasoning) {\n                controller.enqueue({\n                  type: 'reasoning-end',\n                  id: 'reasoning-0',\n                });\n                isActiveReasoning = false;\n              }\n\n              if (!isActiveText) {\n                controller.enqueue({ type: 'text-start', id: 'txt-0' });\n                isActiveText = true;\n              }\n\n              controller.enqueue({\n                type: 'text-delta',\n                id: 'txt-0',\n                delta: delta.content,\n              });\n            }\n\n            if (delta.tool_calls != null) {\n              // end active reasoning block before tool calls start\n              if (isActiveReasoning) {\n                controller.enqueue({\n                  type: 'reasoning-end',\n                  id: 'reasoning-0',\n                });\n                isActiveReasoning = false;\n              }\n\n              for (const toolCallDelta of delta.tool_calls) {\n                const index = toolCallDelta.index ?? toolCalls.length;\n\n                if (toolCalls[index] == null) {\n                  if (toolCallDelta.id == null) {\n                    throw new InvalidResponseDataError({\n                      data: toolCallDelta,\n                      message: `Expected 'id' to be a string.`,\n                    });\n                  }\n\n                  if (toolCallDelta.function?.name == null) {\n                    throw new InvalidResponseDataError({\n                      data: toolCallDelta,\n                      message: `Expected 'function.name' to be a string.`,\n                    });\n                  }\n\n                  controller.enqueue({\n                    type: 'tool-input-start',\n                    id: toolCallDelta.id,\n                    toolName: toolCallDelta.function.name,\n                  });\n\n                  toolCalls[index] = {\n                    id: toolCallDelta.id,\n                    type: 'function',\n                    function: {\n                      name: toolCallDelta.function.name,\n                      arguments: toolCallDelta.function.arguments ?? '',\n                    },\n                    hasFinished: false,\n                    thoughtSignature:\n                      toolCallDelta.extra_content?.google?.thought_signature ??\n                      undefined,\n                  };\n\n                  const toolCall = toolCalls[index];\n\n                  if (\n                    toolCall.function?.name != null &&\n                    toolCall.function?.arguments != null\n                  ) {\n                    // send delta if the argument text has already started:\n                    if (toolCall.function.arguments.length > 0) {\n                      controller.enqueue({\n                        type: 'tool-input-delta',\n                        id: toolCall.id,\n                        delta: toolCall.function.arguments,\n                      });\n                    }\n\n                    // check if tool call is complete\n                    // (some providers send the full tool call in one chunk):\n                    if (isParsableJson(toolCall.function.arguments)) {\n                      controller.enqueue({\n                        type: 'tool-input-end',\n                        id: toolCall.id,\n                      });\n\n                      controller.enqueue({\n                        type: 'tool-call',\n                        toolCallId: toolCall.id ?? generateId(),\n                        toolName: toolCall.function.name,\n                        input: toolCall.function.arguments,\n                        ...(toolCall.thoughtSignature\n                          ? {\n                              providerMetadata: {\n                                [providerOptionsName]: {\n                                  thoughtSignature: toolCall.thoughtSignature,\n                                },\n                              },\n                            }\n                          : {}),\n                      });\n                      toolCall.hasFinished = true;\n                    }\n                  }\n\n                  continue;\n                }\n\n                // existing tool call, merge if not finished\n                const toolCall = toolCalls[index];\n\n                if (toolCall.hasFinished) {\n                  continue;\n                }\n\n                if (toolCallDelta.function?.arguments != null) {\n                  toolCall.function!.arguments +=\n                    toolCallDelta.function?.arguments ?? '';\n                }\n\n                // send delta\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.id,\n                  delta: toolCallDelta.function.arguments ?? '',\n                });\n\n                // check if tool call is complete\n                if (\n                  toolCall.function?.name != null &&\n                  toolCall.function?.arguments != null &&\n                  isParsableJson(toolCall.function.arguments)\n                ) {\n                  controller.enqueue({\n                    type: 'tool-input-end',\n                    id: toolCall.id,\n                  });\n\n                  controller.enqueue({\n                    type: 'tool-call',\n                    toolCallId: toolCall.id ?? generateId(),\n                    toolName: toolCall.function.name,\n                    input: toolCall.function.arguments,\n                    ...(toolCall.thoughtSignature\n                      ? {\n                          providerMetadata: {\n                            [providerOptionsName]: {\n                              thoughtSignature: toolCall.thoughtSignature,\n                            },\n                          },\n                        }\n                      : {}),\n                  });\n                  toolCall.hasFinished = true;\n                }\n              }\n            }\n          },\n\n          flush(controller) {\n            if (isActiveReasoning) {\n              controller.enqueue({ type: 'reasoning-end', id: 'reasoning-0' });\n            }\n\n            if (isActiveText) {\n              controller.enqueue({ type: 'text-end', id: 'txt-0' });\n            }\n\n            // go through all tool calls and send the ones that are not finished\n            for (const toolCall of toolCalls.filter(\n              toolCall => !toolCall.hasFinished,\n            )) {\n              controller.enqueue({\n                type: 'tool-input-end',\n                id: toolCall.id,\n              });\n\n              controller.enqueue({\n                type: 'tool-call',\n                toolCallId: toolCall.id ?? generateId(),\n                toolName: toolCall.function.name,\n                input: toolCall.function.arguments,\n                ...(toolCall.thoughtSignature\n                  ? {\n                      providerMetadata: {\n                        [providerOptionsName]: {\n                          thoughtSignature: toolCall.thoughtSignature,\n                        },\n                      },\n                    }\n                  : {}),\n              });\n            }\n\n            const providerMetadata: SharedV3ProviderMetadata = {\n              [providerOptionsName]: {},\n              ...metadataExtractor?.buildMetadata(),\n            };\n            if (\n              usage?.completion_tokens_details?.accepted_prediction_tokens !=\n              null\n            ) {\n              providerMetadata[providerOptionsName].acceptedPredictionTokens =\n                usage?.completion_tokens_details?.accepted_prediction_tokens;\n            }\n            if (\n              usage?.completion_tokens_details?.rejected_prediction_tokens !=\n              null\n            ) {\n              providerMetadata[providerOptionsName].rejectedPredictionTokens =\n                usage?.completion_tokens_details?.rejected_prediction_tokens;\n            }\n\n            controller.enqueue({\n              type: 'finish',\n              finishReason,\n              usage: convertUsage(usage),\n              providerMetadata,\n            });\n          },\n        }),\n      ),\n      request: { body },\n      response: { headers: responseHeaders },\n    };\n  }\n}\n\nconst openaiCompatibleTokenUsageSchema = z\n  .looseObject({\n    prompt_tokens: z.number().nullish(),\n    completion_tokens: z.number().nullish(),\n    total_tokens: z.number().nullish(),\n    prompt_tokens_details: z\n      .object({\n        cached_tokens: z.number().nullish(),\n      })\n      .nullish(),\n    completion_tokens_details: z\n      .object({\n        reasoning_tokens: z.number().nullish(),\n        accepted_prediction_tokens: z.number().nullish(),\n        rejected_prediction_tokens: z.number().nullish(),\n      })\n      .nullish(),\n  })\n  .nullish();\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst OpenAICompatibleChatResponseSchema = z.looseObject({\n  id: z.string().nullish(),\n  created: z.number().nullish(),\n  model: z.string().nullish(),\n  choices: z.array(\n    z.object({\n      message: z.object({\n        role: z.literal('assistant').nullish(),\n        content: z.string().nullish(),\n        reasoning_content: z.string().nullish(),\n        reasoning: z.string().nullish(),\n        tool_calls: z\n          .array(\n            z.object({\n              id: z.string().nullish(),\n              function: z.object({\n                name: z.string(),\n                arguments: z.string(),\n              }),\n              // Support for Google Gemini thought signatures via OpenAI compatibility\n              extra_content: z\n                .object({\n                  google: z\n                    .object({\n                      thought_signature: z.string().nullish(),\n                    })\n                    .nullish(),\n                })\n                .nullish(),\n            }),\n          )\n          .nullish(),\n      }),\n      finish_reason: z.string().nullish(),\n    }),\n  ),\n  usage: openaiCompatibleTokenUsageSchema,\n});\n\nconst chunkBaseSchema = z.looseObject({\n  id: z.string().nullish(),\n  created: z.number().nullish(),\n  model: z.string().nullish(),\n  choices: z.array(\n    z.object({\n      delta: z\n        .object({\n          role: z.enum(['assistant']).nullish(),\n          content: z.string().nullish(),\n          // Most openai-compatible models set `reasoning_content`, but some\n          // providers serving `gpt-oss` set `reasoning`. See #7866\n          reasoning_content: z.string().nullish(),\n          reasoning: z.string().nullish(),\n          tool_calls: z\n            .array(\n              z.object({\n                index: z.number().nullish(), //google does not send index\n                id: z.string().nullish(),\n                function: z.object({\n                  name: z.string().nullish(),\n                  arguments: z.string().nullish(),\n                }),\n                // Support for Google Gemini thought signatures via OpenAI compatibility\n                extra_content: z\n                  .object({\n                    google: z\n                      .object({\n                        thought_signature: z.string().nullish(),\n                      })\n                      .nullish(),\n                  })\n                  .nullish(),\n              }),\n            )\n            .nullish(),\n        })\n        .nullish(),\n      finish_reason: z.string().nullish(),\n    }),\n  ),\n  usage: openaiCompatibleTokenUsageSchema,\n});\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst createOpenAICompatibleChatChunkSchema = <\n  ERROR_SCHEMA extends z.core.$ZodType,\n>(\n  errorSchema: ERROR_SCHEMA,\n) => z.union([chunkBaseSchema, errorSchema]);\n", "export function toCamelCase(str: string): string {\n  return str.replace(/[_-]([a-z])/g, g => g[1].toUpperCase());\n}\n\n/**\nResolves which key to use for providerMetadata based on what the caller\npassed in providerOptions. Returns the camelCase variant when the caller\nsupplied it, otherwise falls back to the raw name.\n*/\nexport function resolveProviderOptionsKey(\n  rawName: string,\n  providerOptions: Record<string, unknown> | undefined,\n): string {\n  const camelName = toCamelCase(rawName);\n  if (camelName !== rawName && providerOptions?.[camelName] != null) {\n    return camelName;\n  }\n  return rawName;\n}\n", "import { z, type ZodType } from 'zod/v4';\n\nexport const openaiCompatibleErrorDataSchema = z.object({\n  error: z.object({\n    message: z.string(),\n\n    // The additional information below is handled loosely to support\n    // OpenAI-compatible providers that have slightly different error\n    // responses:\n    type: z.string().nullish(),\n    param: z.any().nullish(),\n    code: z.union([z.string(), z.number()]).nullish(),\n  }),\n});\n\nexport type OpenAICompatibleErrorData = z.infer<\n  typeof openaiCompatibleErrorDataSchema\n>;\n\nexport type ProviderErrorStructure<T> = {\n  errorSchema: ZodType<T>;\n  errorToMessage: (error: T) => string;\n  isRetryable?: (response: Response, error?: T) => boolean;\n};\n\nexport const defaultOpenAICompatibleErrorStructure: ProviderErrorStructure<OpenAICompatibleErrorData> =\n  {\n    errorSchema: openaiCompatibleErrorDataSchema,\n    errorToMessage: data => data.error.message,\n  };\n", "import type { LanguageModelV3Usage } from '@ai-sdk/provider';\n\nexport function convertOpenAICompatibleChatUsage(\n  usage:\n    | {\n        prompt_tokens?: number | null;\n        completion_tokens?: number | null;\n        prompt_tokens_details?: {\n          cached_tokens?: number | null;\n        } | null;\n        completion_tokens_details?: {\n          reasoning_tokens?: number | null;\n        } | null;\n      }\n    | undefined\n    | null,\n): LanguageModelV3Usage {\n  if (usage == null) {\n    return {\n      inputTokens: {\n        total: undefined,\n        noCache: undefined,\n        cacheRead: undefined,\n        cacheWrite: undefined,\n      },\n      outputTokens: {\n        total: undefined,\n        text: undefined,\n        reasoning: undefined,\n      },\n      raw: undefined,\n    };\n  }\n\n  const promptTokens = usage.prompt_tokens ?? 0;\n  const completionTokens = usage.completion_tokens ?? 0;\n  const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;\n  const reasoningTokens =\n    usage.completion_tokens_details?.reasoning_tokens ?? 0;\n\n  return {\n    inputTokens: {\n      total: promptTokens,\n      noCache: promptTokens - cacheReadTokens,\n      cacheRead: cacheReadTokens,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: completionTokens,\n      text: completionTokens - reasoningTokens,\n      reasoning: reasoningTokens,\n    },\n    raw: usage,\n  };\n}\n", "import {\n  UnsupportedFunctionalityError,\n  type LanguageModelV3Prompt,\n  type SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type { OpenAICompatibleChatPrompt } from './openai-compatible-api-types';\nimport {\n  convertBase64ToUint8Array,\n  convertToBase64,\n} from '@ai-sdk/provider-utils';\n\nfunction getOpenAIMetadata(message: {\n  providerOptions?: SharedV3ProviderMetadata;\n}) {\n  return message?.providerOptions?.openaiCompatible ?? {};\n}\n\nfunction getAudioFormat(mediaType: string): 'wav' | 'mp3' | null {\n  switch (mediaType) {\n    case 'audio/wav':\n      return 'wav';\n    case 'audio/mp3':\n    case 'audio/mpeg':\n      return 'mp3';\n    default:\n      return null;\n  }\n}\n\nexport function convertToOpenAICompatibleChatMessages(\n  prompt: LanguageModelV3Prompt,\n): OpenAICompatibleChatPrompt {\n  const messages: OpenAICompatibleChatPrompt = [];\n  for (const { role, content, ...message } of prompt) {\n    const metadata = getOpenAIMetadata({ ...message });\n    switch (role) {\n      case 'system': {\n        messages.push({ role: 'system', content, ...metadata });\n        break;\n      }\n\n      case 'user': {\n        if (content.length === 1 && content[0].type === 'text') {\n          messages.push({\n            role: 'user',\n            content: content[0].text,\n            ...getOpenAIMetadata(content[0]),\n          });\n          break;\n        }\n\n        messages.push({\n          role: 'user',\n          content: content.map(part => {\n            const partMetadata = getOpenAIMetadata(part);\n            switch (part.type) {\n              case 'text': {\n                return { type: 'text', text: part.text, ...partMetadata };\n              }\n              case 'file': {\n                if (part.mediaType.startsWith('image/')) {\n                  const mediaType =\n                    part.mediaType === 'image/*'\n                      ? 'image/jpeg'\n                      : part.mediaType;\n\n                  return {\n                    type: 'image_url',\n                    image_url: {\n                      url:\n                        part.data instanceof URL\n                          ? part.data.toString()\n                          : `data:${mediaType};base64,${convertToBase64(part.data)}`,\n                    },\n                    ...partMetadata,\n                  };\n                }\n\n                if (part.mediaType.startsWith('audio/')) {\n                  if (part.data instanceof URL) {\n                    throw new UnsupportedFunctionalityError({\n                      functionality: 'audio file parts with URLs',\n                    });\n                  }\n\n                  const format = getAudioFormat(part.mediaType);\n                  if (format === null) {\n                    throw new UnsupportedFunctionalityError({\n                      functionality: `audio media type ${part.mediaType}`,\n                    });\n                  }\n\n                  return {\n                    type: 'input_audio',\n                    input_audio: {\n                      data: convertToBase64(part.data),\n                      format,\n                    },\n                    ...partMetadata,\n                  };\n                }\n\n                if (part.mediaType === 'application/pdf') {\n                  if (part.data instanceof URL) {\n                    throw new UnsupportedFunctionalityError({\n                      functionality: 'PDF file parts with URLs',\n                    });\n                  }\n\n                  return {\n                    type: 'file',\n                    file: {\n                      filename: part.filename ?? 'document.pdf',\n                      file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`,\n                    },\n                    ...partMetadata,\n                  };\n                }\n\n                if (part.mediaType.startsWith('text/')) {\n                  const textContent =\n                    part.data instanceof URL\n                      ? part.data.toString()\n                      : typeof part.data === 'string'\n                        ? new TextDecoder().decode(\n                            convertBase64ToUint8Array(part.data),\n                          )\n                        : new TextDecoder().decode(part.data);\n\n                  return {\n                    type: 'text',\n                    text: textContent,\n                    ...partMetadata,\n                  };\n                }\n\n                // Unsupported type\n                throw new UnsupportedFunctionalityError({\n                  functionality: `file part media type ${part.mediaType}`,\n                });\n              }\n            }\n          }),\n          ...metadata,\n        });\n\n        break;\n      }\n\n      case 'assistant': {\n        let text = '';\n        let reasoning = '';\n        const toolCalls: Array<{\n          id: string;\n          type: 'function';\n          function: { name: string; arguments: string };\n          extra_content?: {\n            google?: {\n              thought_signature?: string;\n            };\n          };\n        }> = [];\n\n        for (const part of content) {\n          const partMetadata = getOpenAIMetadata(part);\n          switch (part.type) {\n            case 'text': {\n              text += part.text;\n              break;\n            }\n            case 'reasoning': {\n              reasoning += part.text;\n              break;\n            }\n            case 'tool-call': {\n              // TODO: thoughtSignature should be abstracted once we add support for other providers\n              const thoughtSignature =\n                part.providerOptions?.google?.thoughtSignature;\n              toolCalls.push({\n                id: part.toolCallId,\n                type: 'function',\n                function: {\n                  name: part.toolName,\n                  arguments: JSON.stringify(part.input),\n                },\n                ...partMetadata,\n                // Include extra_content for Google Gemini thought signatures\n                ...(thoughtSignature\n                  ? {\n                      extra_content: {\n                        google: {\n                          thought_signature: String(thoughtSignature),\n                        },\n                      },\n                    }\n                  : {}),\n              });\n              break;\n            }\n          }\n        }\n\n        messages.push({\n          role: 'assistant',\n          content: toolCalls.length > 0 ? text || null : text,\n          ...(reasoning.length > 0 ? { reasoning_content: reasoning } : {}),\n          tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n          ...metadata,\n        });\n\n        break;\n      }\n\n      case 'tool': {\n        for (const toolResponse of content) {\n          if (toolResponse.type === 'tool-approval-response') {\n            continue;\n          }\n\n          const output = toolResponse.output;\n\n          let contentValue: string;\n          switch (output.type) {\n            case 'text':\n            case 'error-text':\n              contentValue = output.value;\n              break;\n            case 'execution-denied':\n              contentValue = output.reason ?? 'Tool execution denied.';\n              break;\n            case 'content':\n            case 'json':\n            case 'error-json':\n              contentValue = JSON.stringify(output.value);\n              break;\n          }\n\n          const toolResponseMetadata = getOpenAIMetadata(toolResponse);\n          messages.push({\n            role: 'tool',\n            tool_call_id: toolResponse.toolCallId,\n            content: contentValue,\n            ...toolResponseMetadata,\n          });\n        }\n        break;\n      }\n\n      default: {\n        const _exhaustiveCheck: never = role;\n        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n      }\n    }\n  }\n\n  return messages;\n}\n", "export function getResponseMetadata({\n  id,\n  model,\n  created,\n}: {\n  id?: string | undefined | null;\n  created?: number | undefined | null;\n  model?: string | undefined | null;\n}) {\n  return {\n    id: id ?? undefined,\n    modelId: model ?? undefined,\n    timestamp: created != null ? new Date(created * 1000) : undefined,\n  };\n}\n", "import type { LanguageModelV3FinishReason } from '@ai-sdk/provider';\n\nexport function mapOpenAICompatibleFinishReason(\n  finishReason: string | null | undefined,\n): LanguageModelV3FinishReason['unified'] {\n  switch (finishReason) {\n    case 'stop':\n      return 'stop';\n    case 'length':\n      return 'length';\n    case 'content_filter':\n      return 'content-filter';\n    case 'function_call':\n    case 'tool_calls':\n      return 'tool-calls';\n    default:\n      return 'other';\n  }\n}\n", "import { z } from 'zod/v4';\n\nexport type OpenAICompatibleChatModelId = string;\n\nexport const openaiCompatibleLanguageModelChatOptions = z.object({\n  /**\n   * A unique identifier representing your end-user, which can help the provider to\n   * monitor and detect abuse.\n   */\n  user: z.string().optional(),\n\n  /**\n   * Reasoning effort for reasoning models. Defaults to `medium`.\n   */\n  reasoningEffort: z.string().optional(),\n\n  /**\n   * Controls the verbosity of the generated text. Defaults to `medium`.\n   */\n  textVerbosity: z.string().optional(),\n\n  /**\n   * Whether to use strict JSON schema validation.\n   * When true, the model uses constrained decoding to guarantee schema compliance.\n   * Only used when the provider supports structured outputs and a schema is provided.\n   *\n   * @default true\n   */\n  strictJsonSchema: z.boolean().optional(),\n});\n\nexport type OpenAICompatibleLanguageModelChatOptions = z.infer<\n  typeof openaiCompatibleLanguageModelChatOptions\n>;\n", "import {\n  UnsupportedFunctionalityError,\n  type LanguageModelV3CallOptions,\n  type SharedV3Warning,\n} from '@ai-sdk/provider';\n\nexport function prepareTools({\n  tools,\n  toolChoice,\n}: {\n  tools: LanguageModelV3CallOptions['tools'];\n  toolChoice?: LanguageModelV3CallOptions['toolChoice'];\n}): {\n  tools:\n    | undefined\n    | Array<{\n        type: 'function';\n        function: {\n          name: string;\n          description: string | undefined;\n          parameters: unknown;\n          strict?: boolean;\n        };\n      }>;\n  toolChoice:\n    | { type: 'function'; function: { name: string } }\n    | 'auto'\n    | 'none'\n    | 'required'\n    | undefined;\n  toolWarnings: SharedV3Warning[];\n} {\n  // when the tools array is empty, change it to undefined to prevent errors:\n  tools = tools?.length ? tools : undefined;\n\n  const toolWarnings: SharedV3Warning[] = [];\n\n  if (tools == null) {\n    return { tools: undefined, toolChoice: undefined, toolWarnings };\n  }\n\n  const openaiCompatTools: Array<{\n    type: 'function';\n    function: {\n      name: string;\n      description: string | undefined;\n      parameters: unknown;\n      strict?: boolean;\n    };\n  }> = [];\n\n  for (const tool of tools) {\n    if (tool.type === 'provider') {\n      toolWarnings.push({\n        type: 'unsupported',\n        feature: `provider-defined tool ${tool.id}`,\n      });\n    } else {\n      openaiCompatTools.push({\n        type: 'function',\n        function: {\n          name: tool.name,\n          description: tool.description,\n          parameters: tool.inputSchema,\n          ...(tool.strict != null ? { strict: tool.strict } : {}),\n        },\n      });\n    }\n  }\n\n  if (toolChoice == null) {\n    return { tools: openaiCompatTools, toolChoice: undefined, toolWarnings };\n  }\n\n  const type = toolChoice.type;\n\n  switch (type) {\n    case 'auto':\n    case 'none':\n    case 'required':\n      return { tools: openaiCompatTools, toolChoice: type, toolWarnings };\n    case 'tool':\n      return {\n        tools: openaiCompatTools,\n        toolChoice: {\n          type: 'function',\n          function: { name: toolChoice.toolName },\n        },\n        toolWarnings,\n      };\n    default: {\n      const _exhaustiveCheck: never = type;\n      throw new UnsupportedFunctionalityError({\n        functionality: `tool choice type: ${_exhaustiveCheck}`,\n      });\n    }\n  }\n}\n", "import type {\n  APICallError,\n  LanguageModelV3,\n  LanguageModelV3CallOptions,\n  LanguageModelV3Content,\n  LanguageModelV3FinishReason,\n  LanguageModelV3GenerateResult,\n  LanguageModelV3StreamPart,\n  LanguageModelV3StreamResult,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  parseProviderOptions,\n  postJsonToApi,\n  type FetchFunction,\n  type ParseResult,\n  type ResponseHandler,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { toCamelCase } from '../utils/to-camel-case';\nimport {\n  defaultOpenAICompatibleErrorStructure,\n  type ProviderErrorStructure,\n} from '../openai-compatible-error';\nimport { convertOpenAICompatibleCompletionUsage } from './convert-openai-compatible-completion-usage';\nimport { convertToOpenAICompatibleCompletionPrompt } from './convert-to-openai-compatible-completion-prompt';\nimport { getResponseMetadata } from './get-response-metadata';\nimport { mapOpenAICompatibleFinishReason } from './map-openai-compatible-finish-reason';\nimport {\n  openaiCompatibleLanguageModelCompletionOptions,\n  type OpenAICompatibleCompletionModelId,\n} from './openai-compatible-completion-options';\n\ntype OpenAICompatibleCompletionConfig = {\n  provider: string;\n  includeUsage?: boolean;\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: FetchFunction;\n  errorStructure?: ProviderErrorStructure<any>;\n\n  /**\n   * The supported URLs for the model.\n   */\n  supportedUrls?: () => LanguageModelV3['supportedUrls'];\n};\n\nexport class OpenAICompatibleCompletionLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = 'v3';\n\n  readonly modelId: OpenAICompatibleCompletionModelId;\n  private readonly config: OpenAICompatibleCompletionConfig;\n  private readonly failedResponseHandler: ResponseHandler<APICallError>;\n  private readonly chunkSchema; // type inferred via constructor\n\n  constructor(\n    modelId: OpenAICompatibleCompletionModelId,\n    config: OpenAICompatibleCompletionConfig,\n  ) {\n    this.modelId = modelId;\n    this.config = config;\n\n    // initialize error handling:\n    const errorStructure =\n      config.errorStructure ?? defaultOpenAICompatibleErrorStructure;\n    this.chunkSchema = createOpenAICompatibleCompletionChunkSchema(\n      errorStructure.errorSchema,\n    );\n    this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);\n  }\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  private get providerOptionsName(): string {\n    return this.config.provider.split('.')[0].trim();\n  }\n\n  get supportedUrls() {\n    return this.config.supportedUrls?.() ?? {};\n  }\n\n  private async getArgs({\n    prompt,\n    maxOutputTokens,\n    temperature,\n    topP,\n    topK,\n    frequencyPenalty,\n    presencePenalty,\n    stopSequences: userStopSequences,\n    responseFormat,\n    seed,\n    providerOptions,\n    tools,\n    toolChoice,\n  }: LanguageModelV3CallOptions) {\n    const warnings: SharedV3Warning[] = [];\n\n    // Parse provider options (support both raw and camelCase keys)\n    const completionOptions = Object.assign(\n      (await parseProviderOptions({\n        provider: this.providerOptionsName,\n        providerOptions,\n        schema: openaiCompatibleLanguageModelCompletionOptions,\n      })) ?? {},\n      (await parseProviderOptions({\n        provider: toCamelCase(this.providerOptionsName),\n        providerOptions,\n        schema: openaiCompatibleLanguageModelCompletionOptions,\n      })) ?? {},\n    );\n\n    if (topK != null) {\n      warnings.push({ type: 'unsupported', feature: 'topK' });\n    }\n\n    if (tools?.length) {\n      warnings.push({ type: 'unsupported', feature: 'tools' });\n    }\n\n    if (toolChoice != null) {\n      warnings.push({ type: 'unsupported', feature: 'toolChoice' });\n    }\n\n    if (responseFormat != null && responseFormat.type !== 'text') {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'responseFormat',\n        details: 'JSON response format is not supported.',\n      });\n    }\n\n    const { prompt: completionPrompt, stopSequences } =\n      convertToOpenAICompatibleCompletionPrompt({ prompt });\n\n    const stop = [...(stopSequences ?? []), ...(userStopSequences ?? [])];\n\n    return {\n      args: {\n        // model id:\n        model: this.modelId,\n\n        // model specific settings:\n        echo: completionOptions.echo,\n        logit_bias: completionOptions.logitBias,\n        suffix: completionOptions.suffix,\n        user: completionOptions.user,\n\n        // standardized settings:\n        max_tokens: maxOutputTokens,\n        temperature,\n        top_p: topP,\n        frequency_penalty: frequencyPenalty,\n        presence_penalty: presencePenalty,\n        seed,\n        ...providerOptions?.[this.providerOptionsName],\n        ...providerOptions?.[toCamelCase(this.providerOptionsName)],\n\n        // prompt:\n        prompt: completionPrompt,\n\n        // stop sequences:\n        stop: stop.length > 0 ? stop : undefined,\n      },\n      warnings,\n    };\n  }\n\n  async doGenerate(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3GenerateResult> {\n    const { args, warnings } = await this.getArgs(options);\n\n    const {\n      responseHeaders,\n      value: response,\n      rawValue: rawResponse,\n    } = await postJsonToApi({\n      url: this.config.url({\n        path: '/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: args,\n      failedResponseHandler: this.failedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiCompatibleCompletionResponseSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const choice = response.choices[0];\n    const content: Array<LanguageModelV3Content> = [];\n\n    // text content:\n    if (choice.text != null && choice.text.length > 0) {\n      content.push({ type: 'text', text: choice.text });\n    }\n\n    return {\n      content,\n      usage: convertOpenAICompatibleCompletionUsage(response.usage),\n      finishReason: {\n        unified: mapOpenAICompatibleFinishReason(choice.finish_reason),\n        raw: choice.finish_reason,\n      },\n      request: { body: args },\n      response: {\n        ...getResponseMetadata(response),\n        headers: responseHeaders,\n        body: rawResponse,\n      },\n      warnings,\n    };\n  }\n\n  async doStream(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3StreamResult> {\n    const { args, warnings } = await this.getArgs(options);\n\n    const body = {\n      ...args,\n      stream: true,\n\n      // only include stream_options when in strict compatibility mode:\n      stream_options: this.config.includeUsage\n        ? { include_usage: true }\n        : undefined,\n    };\n\n    const { responseHeaders, value: response } = await postJsonToApi({\n      url: this.config.url({\n        path: '/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body,\n      failedResponseHandler: this.failedResponseHandler,\n      successfulResponseHandler: createEventSourceResponseHandler(\n        this.chunkSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    let finishReason: LanguageModelV3FinishReason = {\n      unified: 'other',\n      raw: undefined,\n    };\n    let usage:\n      | {\n          prompt_tokens: number | undefined;\n          completion_tokens: number | undefined;\n          total_tokens: number | undefined;\n        }\n      | undefined = undefined;\n    let isFirstChunk = true;\n\n    return {\n      stream: response.pipeThrough(\n        new TransformStream<\n          ParseResult<z.infer<typeof this.chunkSchema>>,\n          LanguageModelV3StreamPart\n        >({\n          start(controller) {\n            controller.enqueue({ type: 'stream-start', warnings });\n          },\n\n          transform(chunk, controller) {\n            if (options.includeRawChunks) {\n              controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n            }\n\n            // handle failed chunk parsing / validation:\n            if (!chunk.success) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({ type: 'error', error: chunk.error });\n              return;\n            }\n\n            const value = chunk.value;\n\n            // handle error chunks:\n            if ('error' in value) {\n              finishReason = { unified: 'error', raw: undefined };\n              controller.enqueue({ type: 'error', error: value.error });\n              return;\n            }\n\n            if (isFirstChunk) {\n              isFirstChunk = false;\n\n              controller.enqueue({\n                type: 'response-metadata',\n                ...getResponseMetadata(value),\n              });\n\n              controller.enqueue({\n                type: 'text-start',\n                id: '0',\n              });\n            }\n\n            if (value.usage != null) {\n              usage = value.usage;\n            }\n\n            const choice = value.choices[0];\n\n            if (choice?.finish_reason != null) {\n              finishReason = {\n                unified: mapOpenAICompatibleFinishReason(choice.finish_reason),\n                raw: choice.finish_reason ?? undefined,\n              };\n            }\n\n            if (choice?.text != null) {\n              controller.enqueue({\n                type: 'text-delta',\n                id: '0',\n                delta: choice.text,\n              });\n            }\n          },\n\n          flush(controller) {\n            if (!isFirstChunk) {\n              controller.enqueue({ type: 'text-end', id: '0' });\n            }\n\n            controller.enqueue({\n              type: 'finish',\n              finishReason,\n              usage: convertOpenAICompatibleCompletionUsage(usage),\n            });\n          },\n        }),\n      ),\n      request: { body },\n      response: { headers: responseHeaders },\n    };\n  }\n}\n\nconst usageSchema = z.object({\n  prompt_tokens: z.number(),\n  completion_tokens: z.number(),\n  total_tokens: z.number(),\n});\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst openaiCompatibleCompletionResponseSchema = z.object({\n  id: z.string().nullish(),\n  created: z.number().nullish(),\n  model: z.string().nullish(),\n  choices: z.array(\n    z.object({\n      text: z.string(),\n      finish_reason: z.string(),\n    }),\n  ),\n  usage: usageSchema.nullish(),\n});\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst createOpenAICompatibleCompletionChunkSchema = <\n  ERROR_SCHEMA extends z.core.$ZodType,\n>(\n  errorSchema: ERROR_SCHEMA,\n) =>\n  z.union([\n    z.object({\n      id: z.string().nullish(),\n      created: z.number().nullish(),\n      model: z.string().nullish(),\n      choices: z.array(\n        z.object({\n          text: z.string(),\n          finish_reason: z.string().nullish(),\n          index: z.number(),\n        }),\n      ),\n      usage: usageSchema.nullish(),\n    }),\n    errorSchema,\n  ]);\n", "import type { LanguageModelV3Usage } from '@ai-sdk/provider';\n\nexport function convertOpenAICompatibleCompletionUsage(\n  usage:\n    | {\n        prompt_tokens?: number | null;\n        completion_tokens?: number | null;\n      }\n    | undefined\n    | null,\n): LanguageModelV3Usage {\n  if (usage == null) {\n    return {\n      inputTokens: {\n        total: undefined,\n        noCache: undefined,\n        cacheRead: undefined,\n        cacheWrite: undefined,\n      },\n      outputTokens: {\n        total: undefined,\n        text: undefined,\n        reasoning: undefined,\n      },\n      raw: undefined,\n    };\n  }\n\n  const promptTokens = usage.prompt_tokens ?? 0;\n  const completionTokens = usage.completion_tokens ?? 0;\n\n  return {\n    inputTokens: {\n      total: promptTokens,\n      noCache: promptTokens,\n      cacheRead: undefined,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: completionTokens,\n      text: completionTokens,\n      reasoning: undefined,\n    },\n    raw: usage,\n  };\n}\n", "import {\n  InvalidPromptError,\n  UnsupportedFunctionalityError,\n  type LanguageModelV3Prompt,\n} from '@ai-sdk/provider';\n\nexport function convertToOpenAICompatibleCompletionPrompt({\n  prompt,\n  user = 'user',\n  assistant = 'assistant',\n}: {\n  prompt: LanguageModelV3Prompt;\n  user?: string;\n  assistant?: string;\n}): {\n  prompt: string;\n  stopSequences?: string[];\n} {\n  // transform to a chat message format:\n  let text = '';\n\n  // if first message is a system message, add it to the text:\n  if (prompt[0].role === 'system') {\n    text += `${prompt[0].content}\\n\\n`;\n    prompt = prompt.slice(1);\n  }\n\n  for (const { role, content } of prompt) {\n    switch (role) {\n      case 'system': {\n        throw new InvalidPromptError({\n          message: 'Unexpected system message in prompt: ${content}',\n          prompt,\n        });\n      }\n\n      case 'user': {\n        const userMessage = content\n          .map(part => {\n            switch (part.type) {\n              case 'text': {\n                return part.text;\n              }\n            }\n          })\n          .filter(Boolean)\n          .join('');\n\n        text += `${user}:\\n${userMessage}\\n\\n`;\n        break;\n      }\n\n      case 'assistant': {\n        const assistantMessage = content\n          .map(part => {\n            switch (part.type) {\n              case 'text': {\n                return part.text;\n              }\n              case 'tool-call': {\n                throw new UnsupportedFunctionalityError({\n                  functionality: 'tool-call messages',\n                });\n              }\n            }\n          })\n          .join('');\n\n        text += `${assistant}:\\n${assistantMessage}\\n\\n`;\n        break;\n      }\n\n      case 'tool': {\n        throw new UnsupportedFunctionalityError({\n          functionality: 'tool messages',\n        });\n      }\n\n      default: {\n        const _exhaustiveCheck: never = role;\n        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n      }\n    }\n  }\n\n  // Assistant message prefix:\n  text += `${assistant}:\\n`;\n\n  return {\n    prompt: text,\n    stopSequences: [`\\n${user}:`],\n  };\n}\n", "export function getResponseMetadata({\n  id,\n  model,\n  created,\n}: {\n  id?: string | undefined | null;\n  created?: number | undefined | null;\n  model?: string | undefined | null;\n}) {\n  return {\n    id: id ?? undefined,\n    modelId: model ?? undefined,\n    timestamp: created != null ? new Date(created * 1000) : undefined,\n  };\n}\n", "import type { LanguageModelV3FinishReason } from '@ai-sdk/provider';\n\nexport function mapOpenAICompatibleFinishReason(\n  finishReason: string | null | undefined,\n): LanguageModelV3FinishReason['unified'] {\n  switch (finishReason) {\n    case 'stop':\n      return 'stop';\n    case 'length':\n      return 'length';\n    case 'content_filter':\n      return 'content-filter';\n    case 'function_call':\n    case 'tool_calls':\n      return 'tool-calls';\n    default:\n      return 'other';\n  }\n}\n", "import { z } from 'zod/v4';\n\nexport type OpenAICompatibleCompletionModelId = string;\n\nexport const openaiCompatibleLanguageModelCompletionOptions = z.object({\n  /**\n   * Echo back the prompt in addition to the completion.\n   */\n  echo: z.boolean().optional(),\n\n  /**\n   * Modify the likelihood of specified tokens appearing in the completion.\n   *\n   * Accepts a JSON object that maps tokens (specified by their token ID in\n   * the GPT tokenizer) to an associated bias value from -100 to 100.\n   */\n  logitBias: z.record(z.string(), z.number()).optional(),\n\n  /**\n   * The suffix that comes after a completion of inserted text.\n   */\n  suffix: z.string().optional(),\n\n  /**\n   * A unique identifier representing your end-user, which can help providers to\n   * monitor and detect abuse.\n   */\n  user: z.string().optional(),\n});\n\nexport type OpenAICompatibleLanguageModelCompletionOptions = z.infer<\n  typeof openaiCompatibleLanguageModelCompletionOptions\n>;\n", "import {\n  TooManyEmbeddingValuesForCallError,\n  type EmbeddingModelV3,\n  type SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  parseProviderOptions,\n  postJsonToApi,\n  type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport {\n  openaiCompatibleEmbeddingModelOptions,\n  type OpenAICompatibleEmbeddingModelId,\n} from './openai-compatible-embedding-options';\nimport {\n  defaultOpenAICompatibleErrorStructure,\n  type ProviderErrorStructure,\n} from '../openai-compatible-error';\n\ntype OpenAICompatibleEmbeddingConfig = {\n  /**\n   * Override the maximum number of embeddings per call.\n   */\n  maxEmbeddingsPerCall?: number;\n\n  /**\n   * Override the parallelism of embedding calls.\n   */\n  supportsParallelCalls?: boolean;\n\n  provider: string;\n  url: (options: { modelId: string; path: string }) => string;\n  headers: () => Record<string, string | undefined>;\n  fetch?: FetchFunction;\n  errorStructure?: ProviderErrorStructure<any>;\n};\n\nexport class OpenAICompatibleEmbeddingModel implements EmbeddingModelV3 {\n  readonly specificationVersion = 'v3';\n  readonly modelId: OpenAICompatibleEmbeddingModelId;\n\n  private readonly config: OpenAICompatibleEmbeddingConfig;\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  get maxEmbeddingsPerCall(): number {\n    return this.config.maxEmbeddingsPerCall ?? 2048;\n  }\n\n  get supportsParallelCalls(): boolean {\n    return this.config.supportsParallelCalls ?? true;\n  }\n\n  constructor(\n    modelId: OpenAICompatibleEmbeddingModelId,\n    config: OpenAICompatibleEmbeddingConfig,\n  ) {\n    this.modelId = modelId;\n    this.config = config;\n  }\n\n  private get providerOptionsName(): string {\n    return this.config.provider.split('.')[0].trim();\n  }\n\n  async doEmbed({\n    values,\n    headers,\n    abortSignal,\n    providerOptions,\n  }: Parameters<EmbeddingModelV3['doEmbed']>[0]): Promise<\n    Awaited<ReturnType<EmbeddingModelV3['doEmbed']>>\n  > {\n    const warnings: SharedV3Warning[] = [];\n\n    // Parse provider options - check for deprecated 'openai-compatible' key\n    const deprecatedOptions = await parseProviderOptions({\n      provider: 'openai-compatible',\n      providerOptions,\n      schema: openaiCompatibleEmbeddingModelOptions,\n    });\n\n    if (deprecatedOptions != null) {\n      warnings.push({\n        type: 'other',\n        message: `The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead.`,\n      });\n    }\n\n    const compatibleOptions = Object.assign(\n      deprecatedOptions ?? {},\n      (await parseProviderOptions({\n        provider: 'openaiCompatible',\n        providerOptions,\n        schema: openaiCompatibleEmbeddingModelOptions,\n      })) ?? {},\n      (await parseProviderOptions({\n        provider: this.providerOptionsName,\n        providerOptions,\n        schema: openaiCompatibleEmbeddingModelOptions,\n      })) ?? {},\n    );\n\n    if (values.length > this.maxEmbeddingsPerCall) {\n      throw new TooManyEmbeddingValuesForCallError({\n        provider: this.provider,\n        modelId: this.modelId,\n        maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n        values,\n      });\n    }\n\n    const {\n      responseHeaders,\n      value: response,\n      rawValue,\n    } = await postJsonToApi({\n      url: this.config.url({\n        path: '/embeddings',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), headers),\n      body: {\n        model: this.modelId,\n        input: values,\n        encoding_format: 'float',\n        dimensions: compatibleOptions.dimensions,\n        user: compatibleOptions.user,\n      },\n      failedResponseHandler: createJsonErrorResponseHandler(\n        this.config.errorStructure ?? defaultOpenAICompatibleErrorStructure,\n      ),\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiTextEmbeddingResponseSchema,\n      ),\n      abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    return {\n      warnings,\n      embeddings: response.data.map(item => item.embedding),\n      usage: response.usage\n        ? { tokens: response.usage.prompt_tokens }\n        : undefined,\n      providerMetadata: response.providerMetadata,\n      response: { headers: responseHeaders, body: rawValue },\n    };\n  }\n}\n\n// minimal version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst openaiTextEmbeddingResponseSchema = z.object({\n  data: z.array(z.object({ embedding: z.array(z.number()) })),\n  usage: z.object({ prompt_tokens: z.number() }).nullish(),\n  providerMetadata: z\n    .record(z.string(), z.record(z.string(), z.any()))\n    .optional(),\n});\n", "import { z } from 'zod/v4';\n\nexport type OpenAICompatibleEmbeddingModelId = string;\n\nexport const openaiCompatibleEmbeddingModelOptions = z.object({\n  /**\n   * The number of dimensions the resulting output embeddings should have.\n   * Only supported in text-embedding-3 and later models.\n   */\n  dimensions: z.number().optional(),\n\n  /**\n   * A unique identifier representing your end-user, which can help providers to\n   * monitor and detect abuse.\n   */\n  user: z.string().optional(),\n});\n\nexport type OpenAICompatibleEmbeddingModelOptions = z.infer<\n  typeof openaiCompatibleEmbeddingModelOptions\n>;\n", "import type {\n  ImageModelV3,\n  ImageModelV3File,\n  SharedV3ProviderOptions,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport { toCamelCase } from '../utils/to-camel-case';\nimport {\n  combineHeaders,\n  convertBase64ToUint8Array,\n  convertToFormData,\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  downloadBlob,\n  postFormDataToApi,\n  postJsonToApi,\n  type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport {\n  defaultOpenAICompatibleErrorStructure,\n  type ProviderErrorStructure,\n} from '../openai-compatible-error';\nimport type { OpenAICompatibleImageModelId } from './openai-compatible-image-settings';\n\nexport type OpenAICompatibleImageModelConfig = {\n  provider: string;\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: FetchFunction;\n  errorStructure?: ProviderErrorStructure<any>;\n  _internal?: {\n    currentDate?: () => Date;\n  };\n};\n\nexport class OpenAICompatibleImageModel implements ImageModelV3 {\n  readonly specificationVersion = 'v3';\n  readonly maxImagesPerCall = 10;\n\n  get provider(): string {\n    return this.config.provider;\n  }\n\n  /**\n   * The provider options key used to extract provider-specific options.\n   */\n  private get providerOptionsKey(): string {\n    return this.config.provider.split('.')[0].trim();\n  }\n\n  constructor(\n    readonly modelId: OpenAICompatibleImageModelId,\n    private readonly config: OpenAICompatibleImageModelConfig,\n  ) {}\n\n  // TODO: deprecate non-camelCase keys and remove in future major version\n  private getArgs(\n    providerOptions: SharedV3ProviderOptions,\n  ): Record<string, unknown> {\n    return {\n      ...providerOptions[this.providerOptionsKey],\n      ...providerOptions[toCamelCase(this.providerOptionsKey)],\n    };\n  }\n\n  async doGenerate({\n    prompt,\n    n,\n    size,\n    aspectRatio,\n    seed,\n    providerOptions,\n    headers,\n    abortSignal,\n    files,\n    mask,\n  }: Parameters<ImageModelV3['doGenerate']>[0]): Promise<\n    Awaited<ReturnType<ImageModelV3['doGenerate']>>\n  > {\n    const warnings: Array<SharedV3Warning> = [];\n\n    if (aspectRatio != null) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'aspectRatio',\n        details:\n          'This model does not support aspect ratio. Use `size` instead.',\n      });\n    }\n\n    if (seed != null) {\n      warnings.push({ type: 'unsupported', feature: 'seed' });\n    }\n\n    const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n\n    const args = this.getArgs(providerOptions);\n\n    // Image editing mode - use form data and /images/edits endpoint\n    if (files != null && files.length > 0) {\n      const { value: response, responseHeaders } = await postFormDataToApi({\n        url: this.config.url({\n          path: '/images/edits',\n          modelId: this.modelId,\n        }),\n        headers: combineHeaders(this.config.headers(), headers),\n        formData: convertToFormData<OpenAICompatibleFormDataInput>({\n          model: this.modelId,\n          prompt,\n          image: await Promise.all(files.map(file => fileToBlob(file))),\n          mask: mask != null ? await fileToBlob(mask) : undefined,\n          n,\n          size,\n          ...args,\n        }),\n        failedResponseHandler: createJsonErrorResponseHandler(\n          this.config.errorStructure ?? defaultOpenAICompatibleErrorStructure,\n        ),\n        successfulResponseHandler: createJsonResponseHandler(\n          openaiCompatibleImageResponseSchema,\n        ),\n        abortSignal,\n        fetch: this.config.fetch,\n      });\n\n      return {\n        images: response.data.map(item => item.b64_json),\n        warnings,\n        response: {\n          timestamp: currentDate,\n          modelId: this.modelId,\n          headers: responseHeaders,\n        },\n      };\n    }\n\n    // Standard image generation mode - use JSON and /images/generations endpoint\n    const { value: response, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/images/generations',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), headers),\n      body: {\n        model: this.modelId,\n        prompt,\n        n,\n        size,\n        ...args,\n        response_format: 'b64_json',\n      },\n      failedResponseHandler: createJsonErrorResponseHandler(\n        this.config.errorStructure ?? defaultOpenAICompatibleErrorStructure,\n      ),\n      successfulResponseHandler: createJsonResponseHandler(\n        openaiCompatibleImageResponseSchema,\n      ),\n      abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    return {\n      images: response.data.map(item => item.b64_json),\n      warnings,\n      response: {\n        timestamp: currentDate,\n        modelId: this.modelId,\n        headers: responseHeaders,\n      },\n    };\n  }\n}\n\n// minimal version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst openaiCompatibleImageResponseSchema = z.object({\n  data: z.array(z.object({ b64_json: z.string() })),\n});\n\ntype OpenAICompatibleFormDataInput = {\n  model: string;\n  prompt: string | undefined;\n  image: Blob | Blob[];\n  mask?: Blob;\n  n: number;\n  size: `${number}x${number}` | undefined;\n  [key: string]: unknown;\n};\n\nasync function fileToBlob(file: ImageModelV3File): Promise<Blob> {\n  if (file.type === 'url') {\n    return downloadBlob(file.url);\n  }\n\n  const data =\n    file.data instanceof Uint8Array\n      ? file.data\n      : convertBase64ToUint8Array(file.data);\n\n  return new Blob([data as BlobPart], { type: file.mediaType });\n}\n", "import type {\n  EmbeddingModelV3,\n  ImageModelV3,\n  LanguageModelV3,\n  ProviderV3,\n} from '@ai-sdk/provider';\nimport {\n  withoutTrailingSlash,\n  withUserAgentSuffix,\n  type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n  OpenAICompatibleChatLanguageModel,\n  type OpenAICompatibleChatConfig,\n} from './chat/openai-compatible-chat-language-model';\nimport type { MetadataExtractor } from './chat/openai-compatible-metadata-extractor';\nimport { OpenAICompatibleCompletionLanguageModel } from './completion/openai-compatible-completion-language-model';\nimport { OpenAICompatibleEmbeddingModel } from './embedding/openai-compatible-embedding-model';\nimport { OpenAICompatibleImageModel } from './image/openai-compatible-image-model';\nimport { VERSION } from './version';\n\nexport interface OpenAICompatibleProvider<\n  CHAT_MODEL_IDS extends string = string,\n  COMPLETION_MODEL_IDS extends string = string,\n  EMBEDDING_MODEL_IDS extends string = string,\n  IMAGE_MODEL_IDS extends string = string,\n> extends Omit<ProviderV3, 'imageModel'> {\n  (modelId: CHAT_MODEL_IDS): LanguageModelV3;\n\n  languageModel(\n    modelId: CHAT_MODEL_IDS,\n    config?: Partial<OpenAICompatibleChatConfig>,\n  ): LanguageModelV3;\n\n  chatModel(modelId: CHAT_MODEL_IDS): LanguageModelV3;\n\n  completionModel(modelId: COMPLETION_MODEL_IDS): LanguageModelV3;\n\n  embeddingModel(modelId: EMBEDDING_MODEL_IDS): EmbeddingModelV3;\n\n  /**\n   * @deprecated Use `embeddingModel` instead.\n   */\n  textEmbeddingModel(modelId: EMBEDDING_MODEL_IDS): EmbeddingModelV3;\n\n  imageModel(modelId: IMAGE_MODEL_IDS): ImageModelV3;\n}\n\nexport interface OpenAICompatibleProviderSettings {\n  /**\n   * Base URL for the API calls.\n   */\n  baseURL: string;\n\n  /**\n   * Provider name.\n   */\n  name: string;\n\n  /**\n   * API key for authenticating requests. If specified, adds an `Authorization`\n   * header to request headers with the value `Bearer <apiKey>`. This will be added\n   * before any headers potentially specified in the `headers` option.\n   */\n  apiKey?: string;\n\n  /**\n   * Optional custom headers to include in requests. These will be added to request headers\n   * after any headers potentially added by use of the `apiKey` option.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Optional custom url query parameters to include in request urls.\n   */\n  queryParams?: Record<string, string>;\n\n  /**\n   * Custom fetch implementation. You can use it as a middleware to intercept requests,\n   * or to provide a custom fetch implementation for e.g. testing.\n   */\n  fetch?: FetchFunction;\n\n  /**\n   * Include usage information in streaming responses.\n   */\n  includeUsage?: boolean;\n\n  /**\n   * Whether the provider supports structured outputs in chat models.\n   */\n  supportsStructuredOutputs?: boolean;\n\n  /**\n   * Optional function to transform the request body before sending it to the API.\n   * This is useful for proxy providers that may require a different request format\n   * than the official OpenAI API.\n   */\n  transformRequestBody?: (args: Record<string, any>) => Record<string, any>;\n\n  /**\n   * Optional metadata extractor to capture provider-specific metadata from API responses.\n   * This is useful for extracting non-standard fields, experimental features,\n   * or provider-specific metrics from both streaming and non-streaming responses.\n   */\n  metadataExtractor?: MetadataExtractor;\n\n  /**\n   * The supported URLs for chat models.\n   */\n  supportedUrls?: OpenAICompatibleChatConfig['supportedUrls'];\n\n  /**\n   * Optional usage converter for providers with token accounting semantics that\n   * differ from the default OpenAI-compatible shape.\n   */\n  convertUsage?: OpenAICompatibleChatConfig['convertUsage'];\n}\n\n/**\n * Create an OpenAICompatible provider instance.\n */\nexport function createOpenAICompatible<\n  CHAT_MODEL_IDS extends string,\n  COMPLETION_MODEL_IDS extends string,\n  EMBEDDING_MODEL_IDS extends string,\n  IMAGE_MODEL_IDS extends string,\n>(\n  options: OpenAICompatibleProviderSettings,\n): OpenAICompatibleProvider<\n  CHAT_MODEL_IDS,\n  COMPLETION_MODEL_IDS,\n  EMBEDDING_MODEL_IDS,\n  IMAGE_MODEL_IDS\n> {\n  const baseURL = withoutTrailingSlash(options.baseURL);\n  const providerName = options.name;\n\n  interface CommonModelConfig {\n    provider: string;\n    url: ({ path }: { path: string }) => string;\n    headers: () => Record<string, string>;\n    fetch?: FetchFunction;\n  }\n\n  const headers = {\n    ...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }),\n    ...options.headers,\n  };\n\n  const getHeaders = () =>\n    withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION}`);\n\n  const getCommonModelConfig = (modelType: string): CommonModelConfig => ({\n    provider: `${providerName}.${modelType}`,\n    url: ({ path }) => {\n      const url = new URL(`${baseURL}${path}`);\n      if (options.queryParams) {\n        url.search = new URLSearchParams(options.queryParams).toString();\n      }\n      return url.toString();\n    },\n    headers: getHeaders,\n    fetch: options.fetch,\n  });\n\n  const createLanguageModel = (modelId: CHAT_MODEL_IDS) =>\n    createChatModel(modelId);\n\n  const createChatModel = (modelId: CHAT_MODEL_IDS) =>\n    new OpenAICompatibleChatLanguageModel(modelId, {\n      ...getCommonModelConfig('chat'),\n      includeUsage: options.includeUsage,\n      supportsStructuredOutputs: options.supportsStructuredOutputs,\n      supportedUrls: options.supportedUrls,\n      transformRequestBody: options.transformRequestBody,\n      metadataExtractor: options.metadataExtractor,\n      convertUsage: options.convertUsage,\n    });\n\n  const createCompletionModel = (modelId: COMPLETION_MODEL_IDS) =>\n    new OpenAICompatibleCompletionLanguageModel(modelId, {\n      ...getCommonModelConfig('completion'),\n      includeUsage: options.includeUsage,\n    });\n\n  const createEmbeddingModel = (modelId: EMBEDDING_MODEL_IDS) =>\n    new OpenAICompatibleEmbeddingModel(modelId, {\n      ...getCommonModelConfig('embedding'),\n    });\n\n  const createImageModel = (modelId: IMAGE_MODEL_IDS) =>\n    new OpenAICompatibleImageModel(modelId, getCommonModelConfig('image'));\n\n  const provider = (modelId: CHAT_MODEL_IDS) => createLanguageModel(modelId);\n\n  provider.specificationVersion = 'v3' as const;\n  provider.languageModel = createLanguageModel;\n  provider.chatModel = createChatModel;\n  provider.completionModel = createCompletionModel;\n  provider.embeddingModel = createEmbeddingModel;\n  provider.textEmbeddingModel = createEmbeddingModel;\n  provider.imageModel = createImageModel;\n\n  return provider as OpenAICompatibleProvider<\n    CHAT_MODEL_IDS,\n    COMPLETION_MODEL_IDS,\n    EMBEDDING_MODEL_IDS,\n    IMAGE_MODEL_IDS\n  >;\n}\n", "declare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n", "/**\n * Symbol used for identifying AI SDK Error instances.\n * Enables checking if an error is an instance of AISDKError across package versions.\n */\nconst marker = 'vercel.ai.error';\nconst symbol = Symbol.for(marker);\n\n/**\n * Custom error class for AI SDK related errors.\n * @extends Error\n */\nexport class AISDKError extends Error {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The underlying cause of the error, if any.\n   */\n  readonly cause?: unknown;\n\n  /**\n   * Creates an AI SDK Error.\n   *\n   * @param {Object} params - The parameters for creating the error.\n   * @param {string} params.name - The name of the error.\n   * @param {string} params.message - The error message.\n   * @param {unknown} [params.cause] - The underlying cause of the error.\n   */\n  constructor({\n    name,\n    message,\n    cause,\n  }: {\n    name: string;\n    message: string;\n    cause?: unknown;\n  }) {\n    super(message);\n\n    this.name = name;\n    this.cause = cause;\n  }\n\n  /**\n   * Checks if the given error is an AI SDK Error.\n   * @param {unknown} error - The error to check.\n   * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n   */\n  static isInstance(error: unknown): error is AISDKError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  protected static hasMarker(error: unknown, marker: string): boolean {\n    const markerSymbol = Symbol.for(marker);\n    return (\n      error != null &&\n      typeof error === 'object' &&\n      markerSymbol in error &&\n      typeof error[markerSymbol] === 'boolean' &&\n      error[markerSymbol] === true\n    );\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_APICallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class APICallError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly url: string;\n  readonly requestBodyValues: unknown;\n  readonly statusCode?: number;\n\n  readonly responseHeaders?: Record<string, string>;\n  readonly responseBody?: string;\n\n  readonly isRetryable: boolean;\n  readonly data?: unknown;\n\n  constructor({\n    message,\n    url,\n    requestBodyValues,\n    statusCode,\n    responseHeaders,\n    responseBody,\n    cause,\n    isRetryable = statusCode != null &&\n      (statusCode === 408 || // request timeout\n        statusCode === 409 || // conflict\n        statusCode === 429 || // too many requests\n        statusCode >= 500), // server error\n    data,\n  }: {\n    message: string;\n    url: string;\n    requestBodyValues: unknown;\n    statusCode?: number;\n    responseHeaders?: Record<string, string>;\n    responseBody?: string;\n    cause?: unknown;\n    isRetryable?: boolean;\n    data?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.url = url;\n    this.requestBodyValues = requestBodyValues;\n    this.statusCode = statusCode;\n    this.responseHeaders = responseHeaders;\n    this.responseBody = responseBody;\n    this.isRetryable = isRetryable;\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is APICallError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_EmptyResponseBodyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class EmptyResponseBodyError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message = 'Empty response body' }: { message?: string } = {}) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is EmptyResponseBodyError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "export function getErrorMessage(error: unknown | undefined) {\n  if (error == null) {\n    return 'unknown error';\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return error.message;\n  }\n\n  return JSON.stringify(error);\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A function argument is invalid.\n */\nexport class InvalidArgumentError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly argument: string;\n\n  constructor({\n    message,\n    cause,\n    argument,\n  }: {\n    argument: string;\n    message: string;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.argument = argument;\n  }\n\n  static isInstance(error: unknown): error is InvalidArgumentError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidPromptError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A prompt is invalid. This error should be thrown by providers when they cannot\n * process a prompt.\n */\nexport class InvalidPromptError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly prompt: unknown;\n\n  constructor({\n    prompt,\n    message,\n    cause,\n  }: {\n    prompt: unknown;\n    message: string;\n    cause?: unknown;\n  }) {\n    super({ name, message: `Invalid prompt: ${message}`, cause });\n\n    this.prompt = prompt;\n  }\n\n  static isInstance(error: unknown): error is InvalidPromptError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidResponseDataError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Server returned a response with invalid data content.\n * This should be thrown by providers when they cannot parse the response from the API.\n */\nexport class InvalidResponseDataError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly data: unknown;\n\n  constructor({\n    data,\n    message = `Invalid response data: ${JSON.stringify(data)}.`,\n  }: {\n    data: unknown;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is InvalidResponseDataError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_JSONParseError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class JSONParseError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly text: string;\n\n  constructor({ text, cause }: { text: string; cause: unknown }) {\n    super({\n      name,\n      message:\n        `JSON parsing failed: ` +\n        `Text: ${text}.\\n` +\n        `Error message: ${getErrorMessage(cause)}`,\n      cause,\n    });\n\n    this.text = text;\n  }\n\n  static isInstance(error: unknown): error is JSONParseError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadAPIKeyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadAPIKeyError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message }: { message: string }) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is LoadAPIKeyError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadSettingError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadSettingError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message }: { message: string }) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is LoadSettingError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoContentGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when the AI provider fails to generate any content.\n */\nexport class NoContentGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({\n    message = 'No content generated.',\n  }: { message?: string } = {}) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is NoContentGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoSuchModelError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchModelError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly modelId: string;\n  readonly modelType:\n    | 'languageModel'\n    | 'embeddingModel'\n    | 'imageModel'\n    | 'transcriptionModel'\n    | 'speechModel'\n    | 'rerankingModel'\n    | 'videoModel';\n\n  constructor({\n    errorName = name,\n    modelId,\n    modelType,\n    message = `No such ${modelType}: ${modelId}`,\n  }: {\n    errorName?: string;\n    modelId: string;\n    modelType:\n      | 'languageModel'\n      | 'embeddingModel'\n      | 'imageModel'\n      | 'transcriptionModel'\n      | 'speechModel'\n      | 'rerankingModel'\n      | 'videoModel';\n    message?: string;\n  }) {\n    super({ name: errorName, message });\n\n    this.modelId = modelId;\n    this.modelType = modelType;\n  }\n\n  static isInstance(error: unknown): error is NoSuchModelError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_TooManyEmbeddingValuesForCallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class TooManyEmbeddingValuesForCallError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly provider: string;\n  readonly modelId: string;\n  readonly maxEmbeddingsPerCall: number;\n  readonly values: Array<unknown>;\n\n  constructor(options: {\n    provider: string;\n    modelId: string;\n    maxEmbeddingsPerCall: number;\n    values: Array<unknown>;\n  }) {\n    super({\n      name,\n      message:\n        `Too many values for a single embedding call. ` +\n        `The ${options.provider} model \"${options.modelId}\" can only embed up to ` +\n        `${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`,\n    });\n\n    this.provider = options.provider;\n    this.modelId = options.modelId;\n    this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n    this.values = options.values;\n  }\n\n  static isInstance(\n    error: unknown,\n  ): error is TooManyEmbeddingValuesForCallError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_TypeValidationError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport interface TypeValidationContext {\n  /**\n   * Field path in dot notation (e.g., \"message.metadata\", \"message.parts[3].data\")\n   */\n  field?: string;\n\n  /**\n   * Entity name (e.g., tool name, data type name)\n   */\n  entityName?: string;\n\n  /**\n   * Entity identifier (e.g., message ID, tool call ID)\n   */\n  entityId?: string;\n}\n\nexport class TypeValidationError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly value: unknown;\n  readonly context?: TypeValidationContext;\n\n  constructor({\n    value,\n    cause,\n    context,\n  }: {\n    value: unknown;\n    cause: unknown;\n    context?: TypeValidationContext;\n  }) {\n    let contextPrefix = 'Type validation failed';\n\n    if (context?.field) {\n      contextPrefix += ` for ${context.field}`;\n    }\n\n    if (context?.entityName || context?.entityId) {\n      contextPrefix += ' (';\n      const parts: string[] = [];\n      if (context.entityName) {\n        parts.push(context.entityName);\n      }\n      if (context.entityId) {\n        parts.push(`id: \"${context.entityId}\"`);\n      }\n      contextPrefix += parts.join(', ');\n      contextPrefix += ')';\n    }\n\n    super({\n      name,\n      message:\n        `${contextPrefix}: ` +\n        `Value: ${JSON.stringify(value)}.\\n` +\n        `Error message: ${getErrorMessage(cause)}`,\n      cause,\n    });\n\n    this.value = value;\n    this.context = context;\n  }\n\n  static isInstance(error: unknown): error is TypeValidationError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  /**\n   * Wraps an error into a TypeValidationError.\n   * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n   * Otherwise, it creates a new TypeValidationError.\n   *\n   * @param {Object} params - The parameters for wrapping the error.\n   * @param {unknown} params.value - The value that failed validation.\n   * @param {unknown} params.cause - The original error or cause of the validation failure.\n   * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n   * @returns {TypeValidationError} A TypeValidationError instance.\n   */\n  static wrap({\n    value,\n    cause,\n    context,\n  }: {\n    value: unknown;\n    cause: unknown;\n    context?: TypeValidationContext;\n  }): TypeValidationError {\n    if (\n      TypeValidationError.isInstance(cause) &&\n      cause.value === value &&\n      cause.context?.field === context?.field &&\n      cause.context?.entityName === context?.entityName &&\n      cause.context?.entityId === context?.entityId\n    ) {\n      return cause;\n    }\n\n    return new TypeValidationError({ value, cause, context });\n  }\n}\n", "import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_UnsupportedFunctionalityError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class UnsupportedFunctionalityError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly functionality: string;\n\n  constructor({\n    functionality,\n    message = `'${functionality}' functionality not supported.`,\n  }: {\n    functionality: string;\n    message?: string;\n  }) {\n    super({ name, message });\n    this.functionality = functionality;\n  }\n\n  static isInstance(error: unknown): error is UnsupportedFunctionalityError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { JSONArray, JSONObject, JSONValue } from './json-value';\n\nexport function isJSONValue(value: unknown): value is JSONValue {\n  if (\n    value === null ||\n    typeof value === 'string' ||\n    typeof value === 'number' ||\n    typeof value === 'boolean'\n  ) {\n    return true;\n  }\n\n  if (Array.isArray(value)) {\n    return value.every(isJSONValue);\n  }\n\n  if (typeof value === 'object') {\n    return Object.entries(value).every(\n      ([key, val]) =>\n        typeof key === 'string' && (val === undefined || isJSONValue(val)),\n    );\n  }\n\n  return false;\n}\n\nexport function isJSONArray(value: unknown): value is JSONArray {\n  return Array.isArray(value) && value.every(isJSONValue);\n}\n\nexport function isJSONObject(value: unknown): value is JSONObject {\n  return (\n    value != null &&\n    typeof value === 'object' &&\n    Object.entries(value).every(\n      ([key, val]) =>\n        typeof key === 'string' && (val === undefined || isJSONValue(val)),\n    )\n  );\n}\n", "export function combineHeaders(\n  ...headers: Array<Record<string, string | undefined> | undefined>\n): Record<string, string | undefined> {\n  return headers.reduce(\n    (combinedHeaders, currentHeaders) => ({\n      ...combinedHeaders,\n      ...(currentHeaders ?? {}),\n    }),\n    {},\n  ) as Record<string, string | undefined>;\n}\n", "/**\n * Converts an AsyncIterator to a ReadableStream.\n *\n * @template T - The type of elements produced by the AsyncIterator.\n * @param { <T>} iterator - The AsyncIterator to convert.\n * @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.\n */\nexport function convertAsyncIteratorToReadableStream<T>(\n  iterator: AsyncIterator<T>,\n): ReadableStream<T> {\n  let cancelled = false;\n\n  return new ReadableStream<T>({\n    /**\n     * Called when the consumer wants to pull more data from the stream.\n     *\n     * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n     * @returns {Promise<void>}\n     */\n    async pull(controller) {\n      if (cancelled) return;\n      try {\n        const { value, done } = await iterator.next();\n        if (done) {\n          controller.close();\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (error) {\n        controller.error(error);\n      }\n    },\n    /**\n     * Called when the consumer cancels the stream.\n     */\n    async cancel(reason?: unknown) {\n      cancelled = true;\n      if (iterator.return) {\n        try {\n          await iterator.return(reason);\n        } catch {\n          // intentionally ignore errors during cancellation\n        }\n      }\n    },\n  });\n}\n", "import {\n  LanguageModelV3FunctionTool,\n  LanguageModelV3ProviderTool,\n} from '@ai-sdk/provider';\n\n/**\n * Interface for mapping between custom tool names and provider tool names.\n */\nexport interface ToolNameMapping {\n  /**\n   * Maps a custom tool name (used by the client) to the provider's tool name.\n   * If the custom tool name does not have a mapping, returns the input name.\n   *\n   * @param customToolName - The custom name of the tool defined by the client.\n   * @returns The corresponding provider tool name, or the input name if not mapped.\n   */\n  toProviderToolName: (customToolName: string) => string;\n\n  /**\n   * Maps a provider tool name to the custom tool name used by the client.\n   * If the provider tool name does not have a mapping, returns the input name.\n   *\n   * @param providerToolName - The name of the tool as understood by the provider.\n   * @returns The corresponding custom tool name, or the input name if not mapped.\n   */\n  toCustomToolName: (providerToolName: string) => string;\n}\n\n/**\n * @param tools - Tools that were passed to the language model.\n * @param providerToolNames - Maps the provider tool ids to the provider tool names.\n */\nexport function createToolNameMapping({\n  tools = [],\n  providerToolNames,\n  resolveProviderToolName,\n}: {\n  /**\n   * Tools that were passed to the language model.\n   */\n  tools:\n    | Array<LanguageModelV3FunctionTool | LanguageModelV3ProviderTool>\n    | undefined;\n\n  /**\n   * Maps the provider tool ids to the provider tool names.\n   */\n  providerToolNames: Record<`${string}.${string}`, string>;\n\n  /**\n   * Optional resolver for provider tool names that cannot be represented as\n   * static id -> name mappings (e.g. dynamic provider names).\n   */\n  resolveProviderToolName?: (\n    tool: LanguageModelV3ProviderTool,\n  ) => string | undefined;\n}): ToolNameMapping {\n  const customToolNameToProviderToolName: Record<string, string> = {};\n  const providerToolNameToCustomToolName: Record<string, string> = {};\n\n  for (const tool of tools) {\n    if (tool.type === 'provider') {\n      const providerToolName =\n        resolveProviderToolName?.(tool) ??\n        (tool.id in providerToolNames ? providerToolNames[tool.id] : undefined);\n\n      if (providerToolName == null) {\n        continue;\n      }\n\n      customToolNameToProviderToolName[tool.name] = providerToolName;\n      providerToolNameToCustomToolName[providerToolName] = tool.name;\n    }\n  }\n\n  return {\n    toProviderToolName: (customToolName: string) =>\n      customToolNameToProviderToolName[customToolName] ?? customToolName,\n    toCustomToolName: (providerToolName: string) =>\n      providerToolNameToCustomToolName[providerToolName] ?? providerToolName,\n  };\n}\n", "/**\n * Creates a Promise that resolves after a specified delay\n * @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.\n * @param signal - Optional AbortSignal to cancel the delay\n * @returns A Promise that resolves after the specified delay\n * @throws {DOMException} When the signal is aborted\n */\nexport async function delay(\n  delayInMs?: number | null,\n  options?: {\n    abortSignal?: AbortSignal;\n  },\n): Promise<void> {\n  if (delayInMs == null) {\n    return Promise.resolve();\n  }\n\n  const signal = options?.abortSignal;\n\n  return new Promise<void>((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(createAbortError());\n      return;\n    }\n\n    const timeoutId = setTimeout(() => {\n      cleanup();\n      resolve();\n    }, delayInMs);\n\n    const cleanup = () => {\n      clearTimeout(timeoutId);\n      signal?.removeEventListener('abort', onAbort);\n    };\n\n    const onAbort = () => {\n      cleanup();\n      reject(createAbortError());\n    };\n\n    signal?.addEventListener('abort', onAbort);\n  });\n}\n\nfunction createAbortError(): DOMException {\n  return new DOMException('Delay was aborted', 'AbortError');\n}\n", "/**\n * Delayed promise. It is only constructed once the value is accessed.\n * This is useful to avoid unhandled promise rejections when the promise is created\n * but not accessed.\n */\nexport class DelayedPromise<T> {\n  private status:\n    | { type: 'pending' }\n    | { type: 'resolved'; value: T }\n    | { type: 'rejected'; error: unknown } = { type: 'pending' };\n  private _promise: Promise<T> | undefined;\n  private _resolve: undefined | ((value: T) => void) = undefined;\n  private _reject: undefined | ((error: unknown) => void) = undefined;\n\n  get promise(): Promise<T> {\n    if (this._promise) {\n      return this._promise;\n    }\n\n    this._promise = new Promise<T>((resolve, reject) => {\n      if (this.status.type === 'resolved') {\n        resolve(this.status.value);\n      } else if (this.status.type === 'rejected') {\n        reject(this.status.error);\n      }\n\n      this._resolve = resolve;\n      this._reject = reject;\n    });\n\n    return this._promise;\n  }\n\n  resolve(value: T): void {\n    this.status = { type: 'resolved', value };\n\n    if (this._promise) {\n      this._resolve?.(value);\n    }\n  }\n\n  reject(error: unknown): void {\n    this.status = { type: 'rejected', error };\n\n    if (this._promise) {\n      this._reject?.(error);\n    }\n  }\n\n  isResolved(): boolean {\n    return this.status.type === 'resolved';\n  }\n\n  isRejected(): boolean {\n    return this.status.type === 'rejected';\n  }\n\n  isPending(): boolean {\n    return this.status.type === 'pending';\n  }\n}\n", "/**\n * Extracts the headers from a response object and returns them as a key-value object.\n *\n * @param response - The response object to extract headers from.\n * @returns The headers as a key-value object.\n */\nexport function extractResponseHeaders(response: Response) {\n  return Object.fromEntries<string>([...response.headers]);\n}\n", "// btoa and atob need to be invoked as a function call, not as a method call.\n// Otherwise CloudFlare will throw a\n// \"TypeError: Illegal invocation: function called with incorrect this reference\"\nconst { btoa, atob } = globalThis;\n\nexport function convertBase64ToUint8Array(base64String: string) {\n  const base64Url = base64String.replace(/-/g, '+').replace(/_/g, '/');\n  const latin1string = atob(base64Url);\n  return Uint8Array.from(latin1string, byte => byte.codePointAt(0)!);\n}\n\nexport function convertUint8ArrayToBase64(array: Uint8Array): string {\n  let latin1string = '';\n\n  // Note: regular for loop to support older JavaScript versions that\n  // do not support for..of on Uint8Array\n  for (let i = 0; i < array.length; i++) {\n    latin1string += String.fromCodePoint(array[i]);\n  }\n\n  return btoa(latin1string);\n}\n\nexport function convertToBase64(value: string | Uint8Array): string {\n  return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n", "import { ImageModelV3File } from '@ai-sdk/provider';\nimport { convertUint8ArrayToBase64 } from './uint8-utils';\n\n/**\n * Convert an ImageModelV3File to a URL or data URI string.\n *\n * If the file is a URL, it returns the URL as-is.\n * If the file is base64 data, it returns a data URI with the base64 data.\n * If the file is a Uint8Array, it converts it to base64 and returns a data URI.\n */\nexport function convertImageModelFileToDataUri(file: ImageModelV3File): string {\n  if (file.type === 'url') return file.url;\n\n  return `data:${file.mediaType};base64,${\n    typeof file.data === 'string'\n      ? file.data\n      : convertUint8ArrayToBase64(file.data)\n  }`;\n}\n", "/**\n * Converts an input object to FormData for multipart/form-data requests.\n *\n * Handles the following cases:\n * - `null` or `undefined` values are skipped\n * - Arrays with a single element are appended as a single value\n * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)\n *   unless `useArrayBrackets` is set to `false`\n * - All other values are appended directly\n *\n * @param input - The input object to convert. Use a generic type for type validation.\n * @param options - Optional configuration object.\n * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.\n *   Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.\n * @returns A FormData object containing the input values.\n *\n * @example\n * ```ts\n * type MyInput = {\n *   model: string;\n *   prompt: string;\n *   images: Blob[];\n * };\n *\n * const formData = convertToFormData<MyInput>({\n *   model: 'gpt-image-1',\n *   prompt: 'A cat',\n *   images: [blob1, blob2],\n * });\n * ```\n */\nexport function convertToFormData<T extends Record<string, unknown>>(\n  input: T,\n  options: { useArrayBrackets?: boolean } = {},\n): FormData {\n  const { useArrayBrackets = true } = options;\n  const formData = new FormData();\n\n  for (const [key, value] of Object.entries(input)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      if (value.length === 1) {\n        formData.append(key, value[0] as string | Blob);\n        continue;\n      }\n\n      const arrayKey = useArrayBrackets ? `${key}[]` : key;\n      for (const item of value) {\n        formData.append(arrayKey, item as string | Blob);\n      }\n      continue;\n    }\n\n    formData.append(key, value as string | Blob);\n  }\n\n  return formData;\n}\n", "import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_DownloadError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class DownloadError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly url: string;\n  readonly statusCode?: number;\n  readonly statusText?: string;\n\n  constructor({\n    url,\n    statusCode,\n    statusText,\n    cause,\n    message = cause == null\n      ? `Failed to download ${url}: ${statusCode} ${statusText}`\n      : `Failed to download ${url}: ${cause}`,\n  }: {\n    url: string;\n    statusCode?: number;\n    statusText?: string;\n    message?: string;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.url = url;\n    this.statusCode = statusCode;\n    this.statusText = statusText;\n  }\n\n  static isInstance(error: unknown): error is DownloadError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n", "import { DownloadError } from './download-error';\n\n/**\n * Default maximum download size: 2 GiB.\n *\n * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the\n * body internally, then creates the JS ArrayBuffer), so very large downloads\n * risk exceeding the default V8 heap limit on 64-bit systems and terminating\n * the process with an out-of-memory error.\n *\n * Setting this limit converts an unrecoverable OOM crash into a catchable\n * `DownloadError`.\n */\nexport const DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\n\n/**\n * Reads a fetch Response body with a size limit to prevent memory exhaustion.\n *\n * Checks the Content-Length header for early rejection, then reads the body\n * incrementally via ReadableStream and aborts with a DownloadError when the\n * limit is exceeded.\n *\n * @param response - The fetch Response to read.\n * @param url - The URL being downloaded (used in error messages).\n * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.\n * @returns A Uint8Array containing the response body.\n * @throws DownloadError if the response exceeds maxBytes.\n */\nexport async function readResponseWithSizeLimit({\n  response,\n  url,\n  maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE,\n}: {\n  response: Response;\n  url: string;\n  maxBytes?: number;\n}): Promise<Uint8Array> {\n  // Early rejection based on Content-Length header\n  const contentLength = response.headers.get('content-length');\n  if (contentLength != null) {\n    const length = parseInt(contentLength, 10);\n    if (!isNaN(length) && length > maxBytes) {\n      throw new DownloadError({\n        url,\n        message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`,\n      });\n    }\n  }\n\n  const body = response.body;\n\n  // Handle missing body (empty responses)\n  if (body == null) {\n    return new Uint8Array(0);\n  }\n\n  const reader = body.getReader();\n  const chunks: Uint8Array[] = [];\n  let totalBytes = 0;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n\n      if (done) {\n        break;\n      }\n\n      totalBytes += value.length;\n\n      if (totalBytes > maxBytes) {\n        throw new DownloadError({\n          url,\n          message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`,\n        });\n      }\n\n      chunks.push(value);\n    }\n  } finally {\n    try {\n      await reader.cancel();\n    } finally {\n      reader.releaseLock();\n    }\n  }\n\n  // Concatenate chunks into a single Uint8Array\n  const result = new Uint8Array(totalBytes);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.length;\n  }\n\n  return result;\n}\n", "import { DownloadError } from './download-error';\n\n/**\n * Validates that a URL is safe to download from, blocking private/internal addresses\n * to prevent SSRF attacks.\n *\n * @param url - The URL string to validate.\n * @throws DownloadError if the URL is unsafe.\n */\nexport function validateDownloadUrl(url: string): void {\n  let parsed: URL;\n  try {\n    parsed = new URL(url);\n  } catch {\n    throw new DownloadError({\n      url,\n      message: `Invalid URL: ${url}`,\n    });\n  }\n\n  // data: URLs are inline content, so they do not trigger a network fetch or SSRF risk.\n  if (parsed.protocol === 'data:') {\n    return;\n  }\n\n  // Only allow http and https network protocols\n  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n    throw new DownloadError({\n      url,\n      message: `URL scheme must be http, https, or data, got ${parsed.protocol}`,\n    });\n  }\n\n  const hostname = parsed.hostname;\n\n  // Block empty hostname\n  if (!hostname) {\n    throw new DownloadError({\n      url,\n      message: `URL must have a hostname`,\n    });\n  }\n\n  // Block localhost and .local domains\n  if (\n    hostname === 'localhost' ||\n    hostname.endsWith('.local') ||\n    hostname.endsWith('.localhost')\n  ) {\n    throw new DownloadError({\n      url,\n      message: `URL with hostname ${hostname} is not allowed`,\n    });\n  }\n\n  // Check for IPv6 addresses (enclosed in brackets in URLs)\n  if (hostname.startsWith('[') && hostname.endsWith(']')) {\n    const ipv6 = hostname.slice(1, -1);\n    if (isPrivateIPv6(ipv6)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IPv6 address ${hostname} is not allowed`,\n      });\n    }\n    return;\n  }\n\n  // Check for IPv4 addresses\n  if (isIPv4(hostname)) {\n    if (isPrivateIPv4(hostname)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IP address ${hostname} is not allowed`,\n      });\n    }\n    return;\n  }\n}\n\nfunction isIPv4(hostname: string): boolean {\n  const parts = hostname.split('.');\n  if (parts.length !== 4) return false;\n  return parts.every(part => {\n    const num = Number(part);\n    return (\n      Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part\n    );\n  });\n}\n\nfunction isPrivateIPv4(ip: string): boolean {\n  const parts = ip.split('.').map(Number);\n  const [a, b] = parts;\n\n  // 0.0.0.0/8\n  if (a === 0) return true;\n  // 10.0.0.0/8\n  if (a === 10) return true;\n  // 127.0.0.0/8\n  if (a === 127) return true;\n  // 169.254.0.0/16\n  if (a === 169 && b === 254) return true;\n  // 172.16.0.0/12\n  if (a === 172 && b >= 16 && b <= 31) return true;\n  // 192.168.0.0/16\n  if (a === 192 && b === 168) return true;\n\n  return false;\n}\n\nfunction isPrivateIPv6(ip: string): boolean {\n  const normalized = ip.toLowerCase();\n\n  // ::1 (loopback)\n  if (normalized === '::1') return true;\n  // :: (unspecified)\n  if (normalized === '::') return true;\n\n  // Check for IPv4-mapped addresses (::ffff:x.x.x.x or ::ffff:HHHH:HHHH)\n  if (normalized.startsWith('::ffff:')) {\n    const mappedPart = normalized.slice(7);\n    // Dotted-decimal form: ::ffff:127.0.0.1\n    if (isIPv4(mappedPart)) {\n      return isPrivateIPv4(mappedPart);\n    }\n    // Hex form: ::ffff:7f00:1 (URL parser normalizes to this)\n    const hexParts = mappedPart.split(':');\n    if (hexParts.length === 2) {\n      const high = parseInt(hexParts[0], 16);\n      const low = parseInt(hexParts[1], 16);\n      if (!isNaN(high) && !isNaN(low)) {\n        const a = (high >> 8) & 0xff;\n        const b = high & 0xff;\n        const c = (low >> 8) & 0xff;\n        const d = low & 0xff;\n        return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n      }\n    }\n  }\n\n  // fc00::/7 (unique local addresses - fc00:: and fd00::)\n  if (normalized.startsWith('fc') || normalized.startsWith('fd')) return true;\n\n  // fe80::/10 (link-local)\n  if (normalized.startsWith('fe80')) return true;\n\n  return false;\n}\n", "import { DownloadError } from './download-error';\nimport {\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n} from './read-response-with-size-limit';\nimport { validateDownloadUrl } from './validate-download-url';\n\n/**\n * Download a file from a URL and return it as a Blob.\n *\n * @param url - The URL to download from.\n * @param options - Optional settings for the download.\n * @param options.maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n * @param options.abortSignal - An optional abort signal to cancel the download.\n * @returns A Promise that resolves to the downloaded Blob.\n *\n * @throws DownloadError if the download fails or exceeds maxBytes.\n */\nexport async function downloadBlob(\n  url: string,\n  options?: { maxBytes?: number; abortSignal?: AbortSignal },\n): Promise<Blob> {\n  validateDownloadUrl(url);\n  try {\n    const response = await fetch(url, {\n      signal: options?.abortSignal,\n    });\n\n    // Validate final URL after redirects to prevent SSRF via open redirect\n    if (response.redirected) {\n      validateDownloadUrl(response.url);\n    }\n\n    if (!response.ok) {\n      throw new DownloadError({\n        url,\n        statusCode: response.status,\n        statusText: response.statusText,\n      });\n    }\n\n    const data = await readResponseWithSizeLimit({\n      response,\n      url,\n      maxBytes: options?.maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE,\n    });\n\n    const contentType = response.headers.get('content-type') ?? undefined;\n    return new Blob([data], contentType ? { type: contentType } : undefined);\n  } catch (error) {\n    if (DownloadError.isInstance(error)) {\n      throw error;\n    }\n\n    throw new DownloadError({ url, cause: error });\n  }\n}\n", "import { InvalidArgumentError } from '@ai-sdk/provider';\n\n/**\n * Creates an ID generator.\n * The total length of the ID is the sum of the prefix, separator, and random part length.\n * Not cryptographically secure.\n *\n * @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.\n * @param prefix - The prefix of the ID to generate. Optional.\n * @param separator - The separator between the prefix and the random part of the ID. Default: '-'.\n * @param size - The size of the random part of the ID to generate. Default: 16.\n */\nexport const createIdGenerator = ({\n  prefix,\n  size = 16,\n  alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n  separator = '-',\n}: {\n  prefix?: string;\n  separator?: string;\n  size?: number;\n  alphabet?: string;\n} = {}): IdGenerator => {\n  const generator = () => {\n    const alphabetLength = alphabet.length;\n    const chars = new Array(size);\n    for (let i = 0; i < size; i++) {\n      chars[i] = alphabet[(Math.random() * alphabetLength) | 0];\n    }\n    return chars.join('');\n  };\n\n  if (prefix == null) {\n    return generator;\n  }\n\n  // check that the prefix is not part of the alphabet (otherwise prefix checking can fail randomly)\n  if (alphabet.includes(separator)) {\n    throw new InvalidArgumentError({\n      argument: 'separator',\n      message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`,\n    });\n  }\n\n  return () => `${prefix}${separator}${generator()}`;\n};\n\n/**\n * A function that generates an ID.\n */\nexport type IdGenerator = () => string;\n\n/**\n * Generates a 16-character random string to use for IDs.\n * Not cryptographically secure.\n */\nexport const generateId = createIdGenerator();\n", "export function getErrorMessage(error: unknown | undefined) {\n  if (error == null) {\n    return 'unknown error';\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return error.message;\n  }\n\n  return JSON.stringify(error);\n}\n", "import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport { ResponseHandler } from './response-handler';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\nimport { VERSION } from './version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const getFromApi = async <T>({\n  url,\n  headers = {},\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  try {\n    const response = await fetch(url, {\n      method: 'GET',\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      signal: abortSignal,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: {},\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: {},\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: {},\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: {},\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: {} });\n  }\n};\n", "import { APICallError } from '@ai-sdk/provider';\nimport { isAbortError } from './is-abort-error';\n\nconst FETCH_FAILED_ERROR_MESSAGES = ['fetch failed', 'failed to fetch'];\n\nconst BUN_ERROR_CODES = [\n  'ConnectionRefused',\n  'ConnectionClosed',\n  'FailedToOpenSocket',\n  'ECONNRESET',\n  'ECONNREFUSED',\n  'ETIMEDOUT',\n  'EPIPE',\n];\n\nfunction isBunNetworkError(error: unknown): error is Error & { code?: string } {\n  if (!(error instanceof Error)) {\n    return false;\n  }\n\n  const code = (error as any).code;\n  if (typeof code === 'string' && BUN_ERROR_CODES.includes(code)) {\n    return true;\n  }\n\n  return false;\n}\n\nexport function handleFetchError({\n  error,\n  url,\n  requestBodyValues,\n}: {\n  error: unknown;\n  url: string;\n  requestBodyValues: unknown;\n}) {\n  if (isAbortError(error)) {\n    return error;\n  }\n\n  // unwrap original error when fetch failed (for easier debugging):\n  if (\n    error instanceof TypeError &&\n    FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())\n  ) {\n    const cause = (error as any).cause;\n\n    if (cause != null) {\n      // Failed to connect to server:\n      return new APICallError({\n        message: `Cannot connect to API: ${cause.message}`,\n        cause,\n        url,\n        requestBodyValues,\n        isRetryable: true, // retry when network error\n      });\n    }\n  }\n\n  if (isBunNetworkError(error)) {\n    return new APICallError({\n      message: `Cannot connect to API: ${error.message}`,\n      cause: error,\n      url,\n      requestBodyValues,\n      isRetryable: true,\n    });\n  }\n\n  return error;\n}\n", "export function isAbortError(error: unknown): error is Error {\n  return (\n    (error instanceof Error || error instanceof DOMException) &&\n    (error.name === 'AbortError' ||\n      error.name === 'ResponseAborted' || // Next.js\n      error.name === 'TimeoutError')\n  );\n}\n", "export function getRuntimeEnvironmentUserAgent(\n  globalThisAny: any = globalThis as any,\n): string {\n  // Browsers\n  if (globalThisAny.window) {\n    return `runtime/browser`;\n  }\n\n  // Cloudflare Workers / Deno / Bun / Node.js >= 21.1\n  if (globalThisAny.navigator?.userAgent) {\n    return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n  }\n\n  // Nodes.js < 21.1\n  if (globalThisAny.process?.versions?.node) {\n    return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n  }\n\n  if (globalThisAny.EdgeRuntime) {\n    return `runtime/vercel-edge`;\n  }\n\n  return 'runtime/unknown';\n}\n", "/**\n * Normalizes different header inputs into a plain record with lower-case keys.\n * Entries with `undefined` or `null` values are removed.\n *\n * @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.\n * @returns A record containing the normalized header entries.\n */\nexport function normalizeHeaders(\n  headers:\n    | HeadersInit\n    | Record<string, string | undefined>\n    | Array<[string, string | undefined]>\n    | undefined,\n): Record<string, string> {\n  if (headers == null) {\n    return {};\n  }\n\n  const normalized: Record<string, string> = {};\n\n  if (headers instanceof Headers) {\n    headers.forEach((value, key) => {\n      normalized[key.toLowerCase()] = value;\n    });\n  } else {\n    if (!Array.isArray(headers)) {\n      headers = Object.entries(headers);\n    }\n\n    for (const [key, value] of headers) {\n      if (value != null) {\n        normalized[key.toLowerCase()] = value;\n      }\n    }\n  }\n\n  return normalized;\n}\n", "import { normalizeHeaders } from './normalize-headers';\n\n/**\n * Appends suffix parts to the `user-agent` header.\n * If a `user-agent` header already exists, the suffix parts are appended to it.\n * If no `user-agent` header exists, a new one is created with the suffix parts.\n * Automatically removes undefined entries from the headers.\n *\n * @param headers - The original headers.\n * @param userAgentSuffixParts - The parts to append to the `user-agent` header.\n * @returns The new headers with the `user-agent` header set or updated.\n */\nexport function withUserAgentSuffix(\n  headers: HeadersInit | Record<string, string | undefined> | undefined,\n  ...userAgentSuffixParts: string[]\n): Record<string, string> {\n  const normalizedHeaders = new Headers(normalizeHeaders(headers));\n\n  const currentUserAgentHeader = normalizedHeaders.get('user-agent') || '';\n\n  normalizedHeaders.set(\n    'user-agent',\n    [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(' '),\n  );\n\n  return Object.fromEntries(normalizedHeaders.entries());\n}\n", "// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n", "import {\n  JSONSchema7,\n  LanguageModelV3Message,\n  LanguageModelV3Prompt,\n} from '@ai-sdk/provider';\n\nconst DEFAULT_SCHEMA_PREFIX = 'JSON schema:';\nconst DEFAULT_SCHEMA_SUFFIX =\n  'You MUST answer with a JSON object that matches the JSON schema above.';\nconst DEFAULT_GENERIC_SUFFIX = 'You MUST answer with JSON.';\n\nexport function injectJsonInstruction({\n  prompt,\n  schema,\n  schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : undefined,\n  schemaSuffix = schema != null\n    ? DEFAULT_SCHEMA_SUFFIX\n    : DEFAULT_GENERIC_SUFFIX,\n}: {\n  prompt?: string;\n  schema?: JSONSchema7;\n  schemaPrefix?: string;\n  schemaSuffix?: string;\n}): string {\n  return [\n    prompt != null && prompt.length > 0 ? prompt : undefined,\n    prompt != null && prompt.length > 0 ? '' : undefined, // add a newline if prompt is not null\n    schemaPrefix,\n    schema != null ? JSON.stringify(schema) : undefined,\n    schemaSuffix,\n  ]\n    .filter(line => line != null)\n    .join('\\n');\n}\n\nexport function injectJsonInstructionIntoMessages({\n  messages,\n  schema,\n  schemaPrefix,\n  schemaSuffix,\n}: {\n  messages: LanguageModelV3Prompt;\n  schema?: JSONSchema7;\n  schemaPrefix?: string;\n  schemaSuffix?: string;\n}): LanguageModelV3Prompt {\n  const systemMessage: LanguageModelV3Message =\n    messages[0]?.role === 'system'\n      ? { ...messages[0] }\n      : { role: 'system', content: '' };\n\n  systemMessage.content = injectJsonInstruction({\n    prompt: systemMessage.content,\n    schema,\n    schemaPrefix,\n    schemaSuffix,\n  });\n\n  return [\n    systemMessage,\n    ...(messages[0]?.role === 'system' ? messages.slice(1) : messages),\n  ];\n}\n", "/**\n * Type guard that checks whether a value is not `null` or `undefined`.\n *\n * @template T - The type of the value to check.\n * @param value - The value to check.\n * @returns `true` if the value is neither `null` nor `undefined`, otherwise `false`.\n */\nexport function isNonNullable<T>(\n  value: T | undefined | null,\n): value is NonNullable<T> {\n  return value != null;\n}\n", "/**\n * Checks if the given URL is supported natively by the model.\n *\n * @param mediaType - The media type of the URL. Case-sensitive.\n * @param url - The URL to check.\n * @param supportedUrls - A record where keys are case-sensitive media types (or '*')\n *                        and values are arrays of RegExp patterns for URLs.\n *\n * @returns `true` if the URL matches a pattern under the specific media type\n *          or the wildcard '*', `false` otherwise.\n */\nexport function isUrlSupported({\n  mediaType,\n  url,\n  supportedUrls,\n}: {\n  mediaType: string;\n  url: string;\n  supportedUrls: Record<string, RegExp[]>;\n}): boolean {\n  // standardize media type and url to lower case\n  url = url.toLowerCase();\n  mediaType = mediaType.toLowerCase();\n\n  return (\n    Object.entries(supportedUrls)\n      // standardize supported url map into lowercase prefixes:\n      .map(([key, value]) => {\n        const mediaType = key.toLowerCase();\n        return mediaType === '*' || mediaType === '*/*'\n          ? { mediaTypePrefix: '', regexes: value }\n          : { mediaTypePrefix: mediaType.replace(/\\*/, ''), regexes: value };\n      })\n      // gather all regexp pattern from matched media type prefixes:\n      .filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix))\n      .flatMap(({ regexes }) => regexes)\n      // check if any pattern matches the url:\n      .some(pattern => pattern.test(url))\n  );\n}\n", "import { LoadAPIKeyError } from '@ai-sdk/provider';\n\nexport function loadApiKey({\n  apiKey,\n  environmentVariableName,\n  apiKeyParameterName = 'apiKey',\n  description,\n}: {\n  apiKey: string | undefined;\n  environmentVariableName: string;\n  apiKeyParameterName?: string;\n  description: string;\n}): string {\n  if (typeof apiKey === 'string') {\n    return apiKey;\n  }\n\n  if (apiKey != null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string.`,\n    });\n  }\n\n  if (typeof process === 'undefined') {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.`,\n    });\n  }\n\n  apiKey = process.env[environmentVariableName];\n\n  if (apiKey == null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`,\n    });\n  }\n\n  if (typeof apiKey !== 'string') {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`,\n    });\n  }\n\n  return apiKey;\n}\n", "/**\n * Loads an optional `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @returns The setting value.\n */\nexport function loadOptionalSetting({\n  settingValue,\n  environmentVariableName,\n}: {\n  settingValue: string | undefined;\n  environmentVariableName: string;\n}): string | undefined {\n  if (typeof settingValue === 'string') {\n    return settingValue;\n  }\n\n  if (settingValue != null || typeof process === 'undefined') {\n    return undefined;\n  }\n\n  settingValue = process.env[environmentVariableName];\n\n  if (settingValue == null || typeof settingValue !== 'string') {\n    return undefined;\n  }\n\n  return settingValue;\n}\n", "import { LoadSettingError } from '@ai-sdk/provider';\n\n/**\n * Loads a `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @param settingName - The setting name.\n * @param description - The description of the setting.\n * @returns The setting value.\n */\nexport function loadSetting({\n  settingValue,\n  environmentVariableName,\n  settingName,\n  description,\n}: {\n  settingValue: string | undefined;\n  environmentVariableName: string;\n  settingName: string;\n  description: string;\n}): string {\n  if (typeof settingValue === 'string') {\n    return settingValue;\n  }\n\n  if (settingValue != null) {\n    throw new LoadSettingError({\n      message: `${description} setting must be a string.`,\n    });\n  }\n\n  if (typeof process === 'undefined') {\n    throw new LoadSettingError({\n      message:\n        `${description} setting is missing. ` +\n        `Pass it using the '${settingName}' parameter. ` +\n        `Environment variables are not supported in this environment.`,\n    });\n  }\n\n  settingValue = process.env[environmentVariableName];\n\n  if (settingValue == null) {\n    throw new LoadSettingError({\n      message:\n        `${description} setting is missing. ` +\n        `Pass it using the '${settingName}' parameter ` +\n        `or the ${environmentVariableName} environment variable.`,\n    });\n  }\n\n  if (typeof settingValue !== 'string') {\n    throw new LoadSettingError({\n      message:\n        `${description} setting must be a string. ` +\n        `The value of the ${environmentVariableName} environment variable is not a string.`,\n    });\n  }\n\n  return settingValue;\n}\n", "/**\n * Maps a media type to its corresponding file extension.\n * It was originally introduced to set a filename for audio file uploads\n * in https://github.com/vercel/ai/pull/8159.\n *\n * @param mediaType The media type to map.\n * @returns The corresponding file extension\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n */\nexport function mediaTypeToExtension(mediaType: string) {\n  const [_type, subtype = ''] = mediaType.toLowerCase().split('/');\n\n  return (\n    {\n      mpeg: 'mp3',\n      'x-wav': 'wav',\n      opus: 'ogg',\n      mp4: 'm4a',\n      'x-m4a': 'm4a',\n    }[subtype] ?? subtype\n  );\n}\n", "import {\n  JSONParseError,\n  JSONValue,\n  TypeValidationError,\n} from '@ai-sdk/provider';\nimport { secureJsonParse } from './secure-json-parse';\nimport { safeValidateTypes, validateTypes } from './validate-types';\nimport { FlexibleSchema } from './schema';\n\n/**\n * Parses a JSON string into an unknown object.\n *\n * @param text - The JSON string to parse.\n * @returns {JSONValue} - The parsed JSON object.\n */\nexport async function parseJSON(options: {\n  text: string;\n  schema?: undefined;\n}): Promise<JSONValue>;\n/**\n * Parses a JSON string into a strongly-typed object using the provided schema.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns {Promise<T>} - The parsed object.\n */\nexport async function parseJSON<T>(options: {\n  text: string;\n  schema: FlexibleSchema<T>;\n}): Promise<T>;\nexport async function parseJSON<T>({\n  text,\n  schema,\n}: {\n  text: string;\n  schema?: FlexibleSchema<T>;\n}): Promise<T> {\n  try {\n    const value = secureJsonParse(text);\n\n    if (schema == null) {\n      return value;\n    }\n\n    return validateTypes<T>({ value, schema });\n  } catch (error) {\n    if (\n      JSONParseError.isInstance(error) ||\n      TypeValidationError.isInstance(error)\n    ) {\n      throw error;\n    }\n\n    throw new JSONParseError({ text, cause: error });\n  }\n}\n\nexport type ParseResult<T> =\n  | { success: true; value: T; rawValue: unknown }\n  | {\n      success: false;\n      error: JSONParseError | TypeValidationError;\n      rawValue: unknown;\n    };\n\n/**\n * Safely parses a JSON string and returns the result as an object of type `unknown`.\n *\n * @param text - The JSON string to parse.\n * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.\n */\nexport async function safeParseJSON(options: {\n  text: string;\n  schema?: undefined;\n}): Promise<ParseResult<JSONValue>>;\n/**\n * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeParseJSON<T>(options: {\n  text: string;\n  schema: FlexibleSchema<T>;\n}): Promise<ParseResult<T>>;\nexport async function safeParseJSON<T>({\n  text,\n  schema,\n}: {\n  text: string;\n  schema?: FlexibleSchema<T>;\n}): Promise<ParseResult<T>> {\n  try {\n    const value = secureJsonParse(text);\n\n    if (schema == null) {\n      return { success: true, value: value as T, rawValue: value };\n    }\n\n    return await safeValidateTypes<T>({ value, schema });\n  } catch (error) {\n    return {\n      success: false,\n      error: JSONParseError.isInstance(error)\n        ? error\n        : new JSONParseError({ text, cause: error }),\n      rawValue: undefined,\n    };\n  }\n}\n\nexport function isParsableJson(input: string): boolean {\n  try {\n    secureJsonParse(input);\n    return true;\n  } catch {\n    return false;\n  }\n}\n", "// Licensed under BSD-3-Clause (this file only)\n// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js\n//\n// Copyright (c) Vercel, Inc. (https://vercel.com)\n// Copyright (c) 2019 The Fastify Team\n// Copyright (c) 2019, Sideway Inc, and project contributors\n// All rights reserved.\n//\n// The complete list of contributors can be found at:\n// - https://github.com/hapijs/bourne/graphs/contributors\n// - https://github.com/fastify/secure-json-parse/graphs/contributors\n// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.ts\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nconst suspectProtoRx =\n  /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nconst suspectConstructorRx =\n  /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\n\nfunction _parse(text: string) {\n  // Parse normally\n  const obj = JSON.parse(text);\n\n  // Ignore null and non-objects\n  if (obj === null || typeof obj !== 'object') {\n    return obj;\n  }\n\n  if (\n    suspectProtoRx.test(text) === false &&\n    suspectConstructorRx.test(text) === false\n  ) {\n    return obj;\n  }\n\n  // Scan result for proto keys\n  return filter(obj);\n}\n\nfunction filter(obj: any) {\n  let next = [obj];\n\n  while (next.length) {\n    const nodes = next;\n    next = [];\n\n    for (const node of nodes) {\n      if (Object.prototype.hasOwnProperty.call(node, '__proto__')) {\n        throw new SyntaxError('Object contains forbidden prototype property');\n      }\n\n      if (\n        Object.prototype.hasOwnProperty.call(node, 'constructor') &&\n        node.constructor !== null &&\n        typeof node.constructor === 'object' &&\n        Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')\n      ) {\n        throw new SyntaxError('Object contains forbidden prototype property');\n      }\n\n      for (const key in node) {\n        const value = node[key];\n        if (value && typeof value === 'object') {\n          next.push(value);\n        }\n      }\n    }\n  }\n  return obj;\n}\n\nexport function secureJsonParse(text: string) {\n  const { stackTraceLimit } = Error;\n  try {\n    // Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90\n    Error.stackTraceLimit = 0;\n  } catch (e) {\n    // Fallback in case Error is immutable (v8 readonly)\n    return _parse(text);\n  }\n\n  try {\n    return _parse(text);\n  } finally {\n    Error.stackTraceLimit = stackTraceLimit;\n  }\n}\n", "import { TypeValidationContext, TypeValidationError } from '@ai-sdk/provider';\nimport { FlexibleSchema, asSchema } from './schema';\n\n/**\n * Validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @param {TypeValidationContext} options.context - Optional context about what is being validated.\n * @returns {Promise<T>} - The typed object.\n */\nexport async function validateTypes<OBJECT>({\n  value,\n  schema,\n  context,\n}: {\n  value: unknown;\n  schema: FlexibleSchema<OBJECT>;\n  context?: TypeValidationContext;\n}): Promise<OBJECT> {\n  const result = await safeValidateTypes({ value, schema, context });\n\n  if (!result.success) {\n    throw TypeValidationError.wrap({ value, cause: result.error, context });\n  }\n\n  return result.value;\n}\n\n/**\n * Safely validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The JSON object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @param {TypeValidationContext} options.context - Optional context about what is being validated.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeValidateTypes<OBJECT>({\n  value,\n  schema,\n  context,\n}: {\n  value: unknown;\n  schema: FlexibleSchema<OBJECT>;\n  context?: TypeValidationContext;\n}): Promise<\n  | {\n      success: true;\n      value: OBJECT;\n      rawValue: unknown;\n    }\n  | {\n      success: false;\n      error: TypeValidationError;\n      rawValue: unknown;\n    }\n> {\n  const actualSchema = asSchema(schema);\n\n  try {\n    if (actualSchema.validate == null) {\n      return { success: true, value: value as OBJECT, rawValue: value };\n    }\n\n    const result = await actualSchema.validate(value);\n\n    if (result.success) {\n      return { success: true, value: result.value, rawValue: value };\n    }\n\n    return {\n      success: false,\n      error: TypeValidationError.wrap({ value, cause: result.error, context }),\n      rawValue: value,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: TypeValidationError.wrap({ value, cause: error, context }),\n      rawValue: value,\n    };\n  }\n}\n", "import { JSONSchema7, TypeValidationError } from '@ai-sdk/provider';\nimport { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport { addAdditionalPropertiesToJsonSchema } from './add-additional-properties-to-json-schema';\nimport { zod3ToJsonSchema } from './to-json-schema/zod3-to-json-schema';\n\n/**\n * Used to mark schemas so we can support both Zod and custom schemas.\n */\nconst schemaSymbol = Symbol.for('vercel.ai.schema');\n\nexport type ValidationResult<OBJECT> =\n  | { success: true; value: OBJECT }\n  | { success: false; error: Error };\n\nexport type Schema<OBJECT = unknown> = {\n  /**\n   * Used to mark schemas so we can support both Zod and custom schemas.\n   */\n  [schemaSymbol]: true;\n\n  /**\n   * Schema type for inference.\n   */\n  _type: OBJECT;\n\n  /**\n   * Optional. Validates that the structure of a value matches this schema,\n   * and returns a typed version of the value if it does.\n   */\n  readonly validate?: (\n    value: unknown,\n  ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n\n  /**\n   * The JSON Schema for the schema. It is passed to the providers.\n   */\n  readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;\n};\n\n/**\n * Creates a schema with deferred creation.\n * This is important to reduce the startup time of the library\n * and to avoid initializing unused validators.\n *\n * @param createValidator A function that creates a schema.\n * @returns A function that returns a schema.\n */\nexport function lazySchema<SCHEMA>(\n  createSchema: () => Schema<SCHEMA>,\n): LazySchema<SCHEMA> {\n  // cache the validator to avoid initializing it multiple times\n  let schema: Schema<SCHEMA> | undefined;\n  return () => {\n    if (schema == null) {\n      schema = createSchema();\n    }\n    return schema;\n  };\n}\n\nexport type LazySchema<SCHEMA> = () => Schema<SCHEMA>;\n\nexport type ZodSchema<SCHEMA = any> =\n  | z3.Schema<SCHEMA, z3.ZodTypeDef, any>\n  | z4.core.$ZodType<SCHEMA, any>;\n\nexport type StandardSchema<SCHEMA = any> = StandardSchemaV1<unknown, SCHEMA> &\n  StandardJSONSchemaV1<unknown, SCHEMA>;\n\nexport type FlexibleSchema<SCHEMA = any> =\n  | Schema<SCHEMA>\n  | LazySchema<SCHEMA>\n  | ZodSchema<SCHEMA>\n  | StandardSchema<SCHEMA>;\n\nexport type InferSchema<SCHEMA> =\n  SCHEMA extends ZodSchema<infer T>\n    ? T\n    : SCHEMA extends StandardSchema<infer T>\n      ? T\n      : SCHEMA extends LazySchema<infer T>\n        ? T\n        : SCHEMA extends Schema<infer T>\n          ? T\n          : never;\n\n/**\n * Create a schema using a JSON Schema.\n *\n * @param jsonSchema The JSON Schema for the schema.\n * @param options.validate Optional. A validation function for the schema.\n */\nexport function jsonSchema<OBJECT = unknown>(\n  jsonSchema:\n    | JSONSchema7\n    | PromiseLike<JSONSchema7>\n    | (() => JSONSchema7 | PromiseLike<JSONSchema7>),\n  {\n    validate,\n  }: {\n    validate?: (\n      value: unknown,\n    ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n  } = {},\n): Schema<OBJECT> {\n  return {\n    [schemaSymbol]: true,\n    _type: undefined as OBJECT, // should never be used directly\n    get jsonSchema() {\n      if (typeof jsonSchema === 'function') {\n        jsonSchema = jsonSchema(); // cache the function results\n      }\n      return jsonSchema;\n    },\n    validate,\n  };\n}\n\nfunction isSchema(value: unknown): value is Schema {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    schemaSymbol in value &&\n    value[schemaSymbol] === true &&\n    'jsonSchema' in value &&\n    'validate' in value\n  );\n}\n\nexport function asSchema<OBJECT>(\n  schema: FlexibleSchema<OBJECT> | undefined,\n): Schema<OBJECT> {\n  return schema == null\n    ? jsonSchema({ properties: {}, additionalProperties: false })\n    : isSchema(schema)\n      ? schema\n      : '~standard' in schema\n        ? schema['~standard'].vendor === 'zod'\n          ? zodSchema(schema as ZodSchema<OBJECT>)\n          : standardSchema(schema as StandardSchema<OBJECT>)\n        : schema();\n}\n\nfunction standardSchema<OBJECT>(\n  standardSchema: StandardSchema<OBJECT>,\n): Schema<OBJECT> {\n  return jsonSchema(\n    () =>\n      addAdditionalPropertiesToJsonSchema(\n        standardSchema['~standard'].jsonSchema.input({\n          target: 'draft-07',\n        }) as JSONSchema7,\n      ),\n    {\n      validate: async value => {\n        const result = await standardSchema['~standard'].validate(value);\n        return 'value' in result\n          ? { success: true, value: result.value }\n          : {\n              success: false,\n              error: new TypeValidationError({\n                value,\n                cause: result.issues,\n              }),\n            };\n      },\n    },\n  );\n}\n\nexport function zod3Schema<OBJECT>(\n  zodSchema: z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  // default to no references (to support openapi conversion for google)\n  const useReferences = options?.useReferences ?? false;\n\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () =>\n      zod3ToJsonSchema(zodSchema, {\n        $refStrategy: useReferences ? 'root' : 'none',\n      }) as JSONSchema7,\n    {\n      validate: async value => {\n        const result = await zodSchema.safeParseAsync(value);\n        return result.success\n          ? { success: true, value: result.data }\n          : { success: false, error: result.error };\n      },\n    },\n  );\n}\n\nexport function zod4Schema<OBJECT>(\n  zodSchema: z4.core.$ZodType<OBJECT, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  // default to no references (to support openapi conversion for google)\n  const useReferences = options?.useReferences ?? false;\n\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () =>\n      addAdditionalPropertiesToJsonSchema(\n        z4.toJSONSchema(zodSchema, {\n          target: 'draft-7',\n          io: 'input',\n          reused: useReferences ? 'ref' : 'inline',\n        }) as JSONSchema7,\n      ),\n    {\n      validate: async value => {\n        const result = await z4.safeParseAsync(zodSchema, value);\n        return result.success\n          ? { success: true, value: result.data }\n          : { success: false, error: result.error };\n      },\n    },\n  );\n}\n\nexport function isZod4Schema(\n  zodSchema: z4.core.$ZodType<any, any> | z3.Schema<any, z3.ZodTypeDef, any>,\n): zodSchema is z4.core.$ZodType<any, any> {\n  // https://zod.dev/library-authors?id=how-to-support-zod-3-and-zod-4-simultaneously\n  return '_zod' in zodSchema;\n}\n\nexport function zodSchema<OBJECT>(\n  zodSchema:\n    | z4.core.$ZodType<OBJECT, any>\n    | z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  if (isZod4Schema(zodSchema)) {\n    return zod4Schema(zodSchema, options);\n  } else {\n    return zod3Schema(zodSchema, options);\n  }\n}\n", "import { JSONSchema7, JSONSchema7Definition } from '@ai-sdk/provider';\n\n/**\n * Recursively adds additionalProperties: false to the JSON schema. This is necessary because some providers (e.g. OpenAI) do not support additionalProperties: true.\n */\nexport function addAdditionalPropertiesToJsonSchema(\n  jsonSchema: JSONSchema7,\n): JSONSchema7 {\n  if (\n    jsonSchema.type === 'object' ||\n    (Array.isArray(jsonSchema.type) && jsonSchema.type.includes('object'))\n  ) {\n    jsonSchema.additionalProperties = false;\n    const { properties } = jsonSchema;\n    if (properties != null) {\n      for (const key of Object.keys(properties)) {\n        properties[key] = visit(properties[key]);\n      }\n    }\n  }\n\n  if (jsonSchema.items != null) {\n    jsonSchema.items = Array.isArray(jsonSchema.items)\n      ? jsonSchema.items.map(visit)\n      : visit(jsonSchema.items);\n  }\n\n  if (jsonSchema.anyOf != null) {\n    jsonSchema.anyOf = jsonSchema.anyOf.map(visit);\n  }\n\n  if (jsonSchema.allOf != null) {\n    jsonSchema.allOf = jsonSchema.allOf.map(visit);\n  }\n\n  if (jsonSchema.oneOf != null) {\n    jsonSchema.oneOf = jsonSchema.oneOf.map(visit);\n  }\n\n  const { definitions } = jsonSchema;\n  if (definitions != null) {\n    for (const key of Object.keys(definitions)) {\n      definitions[key] = visit(definitions[key]);\n    }\n  }\n\n  return jsonSchema;\n}\n\nfunction visit(def: JSONSchema7Definition): JSONSchema7Definition {\n  if (typeof def === 'boolean') return def;\n  return addAdditionalPropertiesToJsonSchema(def);\n}\n", "import { ZodSchema, ZodTypeDef } from 'zod/v3';\nimport { Refs, Seen } from './refs';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type DateStrategy =\n  | 'format:date-time'\n  | 'format:date'\n  | 'string'\n  | 'integer';\n\nexport const ignoreOverride = Symbol(\n  'Let zodToJsonSchema decide on which parser to use',\n);\n\nexport type OverrideCallback = (\n  def: ZodTypeDef,\n  refs: Refs,\n  seen: Seen | undefined,\n  forceResolution?: boolean,\n) => JsonSchema7Type | undefined | typeof ignoreOverride;\n\nexport type PostProcessCallback = (\n  jsonSchema: JsonSchema7Type | undefined,\n  def: ZodTypeDef,\n  refs: Refs,\n) => JsonSchema7Type | undefined;\n\nexport const jsonDescription: PostProcessCallback = (jsonSchema, def) => {\n  if (def.description) {\n    try {\n      return {\n        ...jsonSchema,\n        ...JSON.parse(def.description),\n      };\n    } catch {}\n  }\n\n  return jsonSchema;\n};\n\nexport type Options = {\n  name: string | undefined;\n  $refStrategy: 'root' | 'relative' | 'none' | 'seen';\n  basePath: string[];\n  effectStrategy: 'input' | 'any';\n  pipeStrategy: 'input' | 'output' | 'all';\n  dateStrategy: DateStrategy | DateStrategy[];\n  mapStrategy: 'entries' | 'record';\n  removeAdditionalStrategy: 'passthrough' | 'strict';\n  allowedAdditionalProperties: true | undefined;\n  rejectedAdditionalProperties: false | undefined;\n  strictUnions: boolean;\n  definitionPath: string;\n  definitions: Record<string, ZodSchema>;\n  errorMessages: boolean;\n  patternStrategy: 'escape' | 'preserve';\n  applyRegexFlags: boolean;\n  emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod';\n  base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod';\n  nameStrategy: 'ref' | 'title';\n  override?: OverrideCallback;\n  postProcess?: PostProcessCallback;\n};\n\nexport const defaultOptions: Options = {\n  name: undefined,\n  $refStrategy: 'root',\n  basePath: ['#'],\n  effectStrategy: 'input',\n  pipeStrategy: 'all',\n  dateStrategy: 'format:date-time',\n  mapStrategy: 'entries',\n  removeAdditionalStrategy: 'passthrough',\n  allowedAdditionalProperties: true,\n  rejectedAdditionalProperties: false,\n  definitionPath: 'definitions',\n  strictUnions: false,\n  definitions: {},\n  errorMessages: false,\n  patternStrategy: 'escape',\n  applyRegexFlags: false,\n  emailStrategy: 'format:email',\n  base64Strategy: 'contentEncoding:base64',\n  nameStrategy: 'ref',\n};\n\nexport const getDefaultOptions = (\n  options: Partial<Options> | string | undefined,\n) =>\n  (typeof options === 'string'\n    ? {\n        ...defaultOptions,\n        name: options,\n      }\n    : {\n        ...defaultOptions,\n        ...options,\n      }) as Options;\n", "import { ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseAnyDef } from './parsers/any';\nimport { parseArrayDef } from './parsers/array';\nimport { parseBigintDef } from './parsers/bigint';\nimport { parseBooleanDef } from './parsers/boolean';\nimport { parseBrandedDef } from './parsers/branded';\nimport { parseCatchDef } from './parsers/catch';\nimport { parseDateDef } from './parsers/date';\nimport { parseDefaultDef } from './parsers/default';\nimport { parseEffectsDef } from './parsers/effects';\nimport { parseEnumDef } from './parsers/enum';\nimport { parseIntersectionDef } from './parsers/intersection';\nimport { parseLiteralDef } from './parsers/literal';\nimport { parseMapDef } from './parsers/map';\nimport { parseNativeEnumDef } from './parsers/native-enum';\nimport { parseNeverDef } from './parsers/never';\nimport { parseNullDef } from './parsers/null';\nimport { parseNullableDef } from './parsers/nullable';\nimport { parseNumberDef } from './parsers/number';\nimport { parseObjectDef } from './parsers/object';\nimport { parseOptionalDef } from './parsers/optional';\nimport { parsePipelineDef } from './parsers/pipeline';\nimport { parsePromiseDef } from './parsers/promise';\nimport { parseRecordDef } from './parsers/record';\nimport { parseSetDef } from './parsers/set';\nimport { parseStringDef } from './parsers/string';\nimport { parseTupleDef } from './parsers/tuple';\nimport { parseUndefinedDef } from './parsers/undefined';\nimport { parseUnionDef } from './parsers/union';\nimport { parseUnknownDef } from './parsers/unknown';\nimport { Refs } from './refs';\nimport { parseReadonlyDef } from './parsers/readonly';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type InnerDefGetter = () => any;\n\nexport const selectParser = (\n  def: any,\n  typeName: ZodFirstPartyTypeKind,\n  refs: Refs,\n): JsonSchema7Type | undefined | InnerDefGetter => {\n  switch (typeName) {\n    case ZodFirstPartyTypeKind.ZodString:\n      return parseStringDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodNumber:\n      return parseNumberDef(def);\n    case ZodFirstPartyTypeKind.ZodObject:\n      return parseObjectDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodBigInt:\n      return parseBigintDef(def);\n    case ZodFirstPartyTypeKind.ZodBoolean:\n      return parseBooleanDef();\n    case ZodFirstPartyTypeKind.ZodDate:\n      return parseDateDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodUndefined:\n      return parseUndefinedDef();\n    case ZodFirstPartyTypeKind.ZodNull:\n      return parseNullDef();\n    case ZodFirstPartyTypeKind.ZodArray:\n      return parseArrayDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodUnion:\n    case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n      return parseUnionDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodIntersection:\n      return parseIntersectionDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodTuple:\n      return parseTupleDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodRecord:\n      return parseRecordDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodLiteral:\n      return parseLiteralDef(def);\n    case ZodFirstPartyTypeKind.ZodEnum:\n      return parseEnumDef(def);\n    case ZodFirstPartyTypeKind.ZodNativeEnum:\n      return parseNativeEnumDef(def);\n    case ZodFirstPartyTypeKind.ZodNullable:\n      return parseNullableDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodOptional:\n      return parseOptionalDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodMap:\n      return parseMapDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodSet:\n      return parseSetDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodLazy:\n      return () => (def as any).getter()._def;\n    case ZodFirstPartyTypeKind.ZodPromise:\n      return parsePromiseDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodNaN:\n    case ZodFirstPartyTypeKind.ZodNever:\n      return parseNeverDef();\n    case ZodFirstPartyTypeKind.ZodEffects:\n      return parseEffectsDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodAny:\n      return parseAnyDef();\n    case ZodFirstPartyTypeKind.ZodUnknown:\n      return parseUnknownDef();\n    case ZodFirstPartyTypeKind.ZodDefault:\n      return parseDefaultDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodBranded:\n      return parseBrandedDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodReadonly:\n      return parseReadonlyDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodCatch:\n      return parseCatchDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodPipeline:\n      return parsePipelineDef(def, refs);\n    case ZodFirstPartyTypeKind.ZodFunction:\n    case ZodFirstPartyTypeKind.ZodVoid:\n    case ZodFirstPartyTypeKind.ZodSymbol:\n      return undefined;\n    default:\n      /* c8 ignore next */\n      return ((_: never) => undefined)(typeName);\n  }\n};\n", "export type JsonSchema7AnyType = { $ref?: string };\n\nexport function parseAnyDef(): JsonSchema7AnyType {\n  return {};\n}\n", "import { ZodArrayDef, ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7ArrayType = {\n  type: 'array';\n  items?: JsonSchema7Type;\n  minItems?: number;\n  maxItems?: number;\n};\n\nexport function parseArrayDef(def: ZodArrayDef, refs: Refs) {\n  const res: JsonSchema7ArrayType = {\n    type: 'array',\n  };\n  if (\n    def.type?._def &&\n    def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny\n  ) {\n    res.items = parseDef(def.type._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items'],\n    });\n  }\n\n  if (def.minLength) {\n    res.minItems = def.minLength.value;\n  }\n  if (def.maxLength) {\n    res.maxItems = def.maxLength.value;\n  }\n  if (def.exactLength) {\n    res.minItems = def.exactLength.value;\n    res.maxItems = def.exactLength.value;\n  }\n  return res;\n}\n", "import { ZodBigIntDef } from 'zod/v3';\n\nexport type JsonSchema7BigintType = {\n  type: 'integer';\n  format: 'int64';\n  minimum?: BigInt;\n  exclusiveMinimum?: BigInt;\n  maximum?: BigInt;\n  exclusiveMaximum?: BigInt;\n  multipleOf?: BigInt;\n};\n\nexport function parseBigintDef(def: ZodBigIntDef): JsonSchema7BigintType {\n  const res: JsonSchema7BigintType = {\n    type: 'integer',\n    format: 'int64',\n  };\n\n  if (!def.checks) return res;\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'min':\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case 'max':\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n\n        break;\n      case 'multipleOf':\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n", "export type JsonSchema7BooleanType = {\n  type: 'boolean';\n};\n\nexport function parseBooleanDef(): JsonSchema7BooleanType {\n  return { type: 'boolean' };\n}\n", "import { ZodBrandedDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport function parseBrandedDef(_def: ZodBrandedDef<any>, refs: Refs) {\n  return parseDef(_def.type._def, refs);\n}\n", "import { ZodCatchDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport const parseCatchDef = (def: ZodCatchDef<any>, refs: Refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n", "import { ZodDateDef } from 'zod/v3';\nimport { Refs } from '../refs';\nimport { DateStrategy } from '../options';\n\nexport type JsonSchema7DateType =\n  | {\n      type: 'integer' | 'string';\n      format: 'unix-time' | 'date-time' | 'date';\n      minimum?: number;\n      maximum?: number;\n    }\n  | {\n      anyOf: JsonSchema7DateType[];\n    };\n\nexport function parseDateDef(\n  def: ZodDateDef,\n  refs: Refs,\n  overrideDateStrategy?: DateStrategy,\n): JsonSchema7DateType {\n  const strategy = overrideDateStrategy ?? refs.dateStrategy;\n\n  if (Array.isArray(strategy)) {\n    return {\n      anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n    };\n  }\n\n  switch (strategy) {\n    case 'string':\n    case 'format:date-time':\n      return {\n        type: 'string',\n        format: 'date-time',\n      };\n    case 'format:date':\n      return {\n        type: 'string',\n        format: 'date',\n      };\n    case 'integer':\n      return integerDateParser(def);\n  }\n}\n\nconst integerDateParser = (def: ZodDateDef) => {\n  const res: JsonSchema7DateType = {\n    type: 'integer',\n    format: 'unix-time',\n  };\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'min':\n        res.minimum = check.value;\n        break;\n      case 'max':\n        res.maximum = check.value;\n        break;\n    }\n  }\n\n  return res;\n};\n", "import { ZodDefaultDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport function parseDefaultDef(\n  _def: ZodDefaultDef,\n  refs: Refs,\n): JsonSchema7Type & { default: any } {\n  return {\n    ...parseDef(_def.innerType._def, refs),\n    default: _def.defaultValue(),\n  };\n}\n", "import { ZodEffectsDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport function parseEffectsDef(\n  _def: ZodEffectsDef,\n  refs: Refs,\n): JsonSchema7Type | undefined {\n  return refs.effectStrategy === 'input'\n    ? parseDef(_def.schema._def, refs)\n    : parseAnyDef();\n}\n", "import { ZodEnumDef } from 'zod/v3';\n\nexport type JsonSchema7EnumType = {\n  type: 'string';\n  enum: string[];\n};\n\nexport function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType {\n  return {\n    type: 'string',\n    enum: Array.from(def.values),\n  };\n}\n", "import { ZodIntersectionDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7StringType } from './string';\n\nexport type JsonSchema7AllOfType = {\n  allOf: JsonSchema7Type[];\n  unevaluatedProperties?: boolean;\n};\n\nconst isJsonSchema7AllOfType = (\n  type: JsonSchema7Type | JsonSchema7StringType,\n): type is JsonSchema7AllOfType => {\n  if ('type' in type && type.type === 'string') return false;\n  return 'allOf' in type;\n};\n\nexport function parseIntersectionDef(\n  def: ZodIntersectionDef,\n  refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined {\n  const allOf = [\n    parseDef(def.left._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'allOf', '0'],\n    }),\n    parseDef(def.right._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'allOf', '1'],\n    }),\n  ].filter((x): x is JsonSchema7Type => !!x);\n\n  const mergedAllOf: JsonSchema7Type[] = [];\n  // If either of the schemas is an allOf, merge them into a single allOf\n  allOf.forEach(schema => {\n    if (isJsonSchema7AllOfType(schema)) {\n      mergedAllOf.push(...schema.allOf);\n    } else {\n      let nestedSchema: JsonSchema7Type = schema;\n      if (\n        'additionalProperties' in schema &&\n        schema.additionalProperties === false\n      ) {\n        const { additionalProperties, ...rest } = schema;\n        nestedSchema = rest;\n      }\n      mergedAllOf.push(nestedSchema);\n    }\n  });\n  return mergedAllOf.length ? { allOf: mergedAllOf } : undefined;\n}\n", "import { ZodLiteralDef } from 'zod/v3';\n\nexport type JsonSchema7LiteralType =\n  | {\n      type: 'string' | 'number' | 'integer' | 'boolean';\n      const: string | number | boolean;\n    }\n  | {\n      type: 'object' | 'array';\n    };\n\nexport function parseLiteralDef(def: ZodLiteralDef): JsonSchema7LiteralType {\n  const parsedType = typeof def.value;\n  if (\n    parsedType !== 'bigint' &&\n    parsedType !== 'number' &&\n    parsedType !== 'boolean' &&\n    parsedType !== 'string'\n  ) {\n    return {\n      type: Array.isArray(def.value) ? 'array' : 'object',\n    };\n  }\n\n  return {\n    type: parsedType === 'bigint' ? 'integer' : parsedType,\n    const: def.value,\n  };\n}\n", "import {\n  ZodFirstPartyTypeKind,\n  ZodMapDef,\n  ZodRecordDef,\n  ZodTypeAny,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseBrandedDef } from './branded';\nimport { JsonSchema7EnumType } from './enum';\nimport { JsonSchema7StringType, parseStringDef } from './string';\n\ntype JsonSchema7RecordPropertyNamesType =\n  | Omit<JsonSchema7StringType, 'type'>\n  | Omit<JsonSchema7EnumType, 'type'>;\n\nexport type JsonSchema7RecordType = {\n  type: 'object';\n  additionalProperties?: JsonSchema7Type | true;\n  propertyNames?: JsonSchema7RecordPropertyNamesType;\n};\n\nexport function parseRecordDef(\n  def: ZodRecordDef<ZodTypeAny, ZodTypeAny> | ZodMapDef,\n  refs: Refs,\n): JsonSchema7RecordType {\n  const schema: JsonSchema7RecordType = {\n    type: 'object',\n    additionalProperties:\n      parseDef(def.valueType._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'additionalProperties'],\n      }) ?? refs.allowedAdditionalProperties,\n  };\n\n  if (\n    def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n    def.keyType._def.checks?.length\n  ) {\n    const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n\n    return {\n      ...schema,\n      propertyNames: keyType,\n    };\n  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n    return {\n      ...schema,\n      propertyNames: {\n        enum: def.keyType._def.values,\n      },\n    };\n  } else if (\n    def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&\n    def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n    def.keyType._def.type._def.checks?.length\n  ) {\n    const { type, ...keyType } = parseBrandedDef(\n      def.keyType._def,\n      refs,\n    ) as JsonSchema7StringType;\n\n    return {\n      ...schema,\n      propertyNames: keyType,\n    };\n  }\n\n  return schema;\n}\n", "import { ZodStringDef } from 'zod/v3';\nimport { Refs } from '../refs';\n\nlet emojiRegex: RegExp | undefined = undefined;\n\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n  /**\n   * `c` was changed to `[cC]` to replicate /i flag\n   */\n  cuid: /^[cC][^\\s-]{8,}$/,\n  cuid2: /^[0-9a-z]+$/,\n  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n  /**\n   * `a-z` was added to replicate /i flag\n   */\n  email:\n    /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n  /**\n   * Constructed a valid Unicode RegExp\n   *\n   * Lazily instantiate since this type of regex isn't supported\n   * in all envs (e.g. React Native).\n   *\n   * See:\n   * https://github.com/colinhacks/zod/issues/2433\n   * Fix in Zod:\n   * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n   */\n  emoji: () => {\n    if (emojiRegex === undefined) {\n      emojiRegex = RegExp(\n        '^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$',\n        'u',\n      );\n    }\n    return emojiRegex;\n  },\n  /**\n   * Unused\n   */\n  uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n  /**\n   * Unused\n   */\n  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])$/,\n  ipv4Cidr:\n    /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n  /**\n   * Unused\n   */\n  ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n  ipv6Cidr:\n    /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n  base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n  base64url:\n    /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n  nanoid: /^[a-zA-Z0-9_-]{21}$/,\n  jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n} as const;\n\nexport type JsonSchema7StringType = {\n  type: 'string';\n  minLength?: number;\n  maxLength?: number;\n  format?:\n    | 'email'\n    | 'idn-email'\n    | 'uri'\n    | 'uuid'\n    | 'date-time'\n    | 'ipv4'\n    | 'ipv6'\n    | 'date'\n    | 'time'\n    | 'duration';\n  pattern?: string;\n  allOf?: {\n    pattern: string;\n  }[];\n  anyOf?: {\n    format: string;\n  }[];\n  contentEncoding?: string;\n};\n\nexport function parseStringDef(\n  def: ZodStringDef,\n  refs: Refs,\n): JsonSchema7StringType {\n  const res: JsonSchema7StringType = {\n    type: 'string',\n  };\n\n  if (def.checks) {\n    for (const check of def.checks) {\n      switch (check.kind) {\n        case 'min':\n          res.minLength =\n            typeof res.minLength === 'number'\n              ? Math.max(res.minLength, check.value)\n              : check.value;\n          break;\n        case 'max':\n          res.maxLength =\n            typeof res.maxLength === 'number'\n              ? Math.min(res.maxLength, check.value)\n              : check.value;\n\n          break;\n        case 'email':\n          switch (refs.emailStrategy) {\n            case 'format:email':\n              addFormat(res, 'email', check.message, refs);\n              break;\n            case 'format:idn-email':\n              addFormat(res, 'idn-email', check.message, refs);\n              break;\n            case 'pattern:zod':\n              addPattern(res, zodPatterns.email, check.message, refs);\n              break;\n          }\n\n          break;\n        case 'url':\n          addFormat(res, 'uri', check.message, refs);\n          break;\n        case 'uuid':\n          addFormat(res, 'uuid', check.message, refs);\n          break;\n        case 'regex':\n          addPattern(res, check.regex, check.message, refs);\n          break;\n        case 'cuid':\n          addPattern(res, zodPatterns.cuid, check.message, refs);\n          break;\n        case 'cuid2':\n          addPattern(res, zodPatterns.cuid2, check.message, refs);\n          break;\n        case 'startsWith':\n          addPattern(\n            res,\n            RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n            check.message,\n            refs,\n          );\n          break;\n        case 'endsWith':\n          addPattern(\n            res,\n            RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n            check.message,\n            refs,\n          );\n          break;\n        case 'datetime':\n          addFormat(res, 'date-time', check.message, refs);\n          break;\n        case 'date':\n          addFormat(res, 'date', check.message, refs);\n          break;\n        case 'time':\n          addFormat(res, 'time', check.message, refs);\n          break;\n        case 'duration':\n          addFormat(res, 'duration', check.message, refs);\n          break;\n        case 'length':\n          res.minLength =\n            typeof res.minLength === 'number'\n              ? Math.max(res.minLength, check.value)\n              : check.value;\n          res.maxLength =\n            typeof res.maxLength === 'number'\n              ? Math.min(res.maxLength, check.value)\n              : check.value;\n          break;\n        case 'includes': {\n          addPattern(\n            res,\n            RegExp(escapeLiteralCheckValue(check.value, refs)),\n            check.message,\n            refs,\n          );\n          break;\n        }\n        case 'ip': {\n          if (check.version !== 'v6') {\n            addFormat(res, 'ipv4', check.message, refs);\n          }\n          if (check.version !== 'v4') {\n            addFormat(res, 'ipv6', check.message, refs);\n          }\n          break;\n        }\n        case 'base64url':\n          addPattern(res, zodPatterns.base64url, check.message, refs);\n          break;\n        case 'jwt':\n          addPattern(res, zodPatterns.jwt, check.message, refs);\n          break;\n        case 'cidr': {\n          if (check.version !== 'v6') {\n            addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n          }\n          if (check.version !== 'v4') {\n            addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n          }\n          break;\n        }\n        case 'emoji':\n          addPattern(res, zodPatterns.emoji(), check.message, refs);\n          break;\n        case 'ulid': {\n          addPattern(res, zodPatterns.ulid, check.message, refs);\n          break;\n        }\n        case 'base64': {\n          switch (refs.base64Strategy) {\n            case 'format:binary': {\n              addFormat(res, 'binary' as any, check.message, refs);\n              break;\n            }\n\n            case 'contentEncoding:base64': {\n              res.contentEncoding = 'base64';\n              break;\n            }\n\n            case 'pattern:zod': {\n              addPattern(res, zodPatterns.base64, check.message, refs);\n              break;\n            }\n          }\n          break;\n        }\n        case 'nanoid': {\n          addPattern(res, zodPatterns.nanoid, check.message, refs);\n        }\n        case 'toLowerCase':\n        case 'toUpperCase':\n        case 'trim':\n          break;\n        default:\n          /* c8 ignore next */\n          ((_: never) => {})(check);\n      }\n    }\n  }\n\n  return res;\n}\n\nfunction escapeLiteralCheckValue(literal: string, refs: Refs): string {\n  return refs.patternStrategy === 'escape'\n    ? escapeNonAlphaNumeric(literal)\n    : literal;\n}\n\nconst ALPHA_NUMERIC = new Set(\n  'ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789',\n);\n\nfunction escapeNonAlphaNumeric(source: string) {\n  let result = '';\n\n  for (let i = 0; i < source.length; i++) {\n    if (!ALPHA_NUMERIC.has(source[i])) {\n      result += '\\\\';\n    }\n\n    result += source[i];\n  }\n\n  return result;\n}\n\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(\n  schema: JsonSchema7StringType,\n  value: Required<JsonSchema7StringType>['format'],\n  message: string | undefined,\n  refs: Refs,\n) {\n  if (schema.format || schema.anyOf?.some(x => x.format)) {\n    if (!schema.anyOf) {\n      schema.anyOf = [];\n    }\n\n    if (schema.format) {\n      schema.anyOf!.push({\n        format: schema.format,\n      });\n      delete schema.format;\n    }\n\n    schema.anyOf!.push({\n      format: value,\n      ...(message &&\n        refs.errorMessages && { errorMessage: { format: message } }),\n    });\n  } else {\n    schema.format = value;\n  }\n}\n\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(\n  schema: JsonSchema7StringType,\n  regex: RegExp,\n  message: string | undefined,\n  refs: Refs,\n) {\n  if (schema.pattern || schema.allOf?.some(x => x.pattern)) {\n    if (!schema.allOf) {\n      schema.allOf = [];\n    }\n\n    if (schema.pattern) {\n      schema.allOf!.push({\n        pattern: schema.pattern,\n      });\n      delete schema.pattern;\n    }\n\n    schema.allOf!.push({\n      pattern: stringifyRegExpWithFlags(regex, refs),\n      ...(message &&\n        refs.errorMessages && { errorMessage: { pattern: message } }),\n    });\n  } else {\n    schema.pattern = stringifyRegExpWithFlags(regex, refs);\n  }\n}\n\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex: RegExp, refs: Refs): string {\n  if (!refs.applyRegexFlags || !regex.flags) {\n    return regex.source;\n  }\n\n  // Currently handled flags\n  const flags = {\n    i: regex.flags.includes('i'), // Case-insensitive\n    m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters\n    s: regex.flags.includes('s'), // `.` matches newlines\n  };\n\n  // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n  const source = flags.i ? regex.source.toLowerCase() : regex.source;\n  let pattern = '';\n  let isEscaped = false;\n  let inCharGroup = false;\n  let inCharRange = false;\n\n  for (let i = 0; i < source.length; i++) {\n    if (isEscaped) {\n      pattern += source[i];\n      isEscaped = false;\n      continue;\n    }\n\n    if (flags.i) {\n      if (inCharGroup) {\n        if (source[i].match(/[a-z]/)) {\n          if (inCharRange) {\n            pattern += source[i];\n            pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n            inCharRange = false;\n          } else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {\n            pattern += source[i];\n            inCharRange = true;\n          } else {\n            pattern += `${source[i]}${source[i].toUpperCase()}`;\n          }\n          continue;\n        }\n      } else if (source[i].match(/[a-z]/)) {\n        pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n        continue;\n      }\n    }\n\n    if (flags.m) {\n      if (source[i] === '^') {\n        pattern += `(^|(?<=[\\r\\n]))`;\n        continue;\n      } else if (source[i] === '$') {\n        pattern += `($|(?=[\\r\\n]))`;\n        continue;\n      }\n    }\n\n    if (flags.s && source[i] === '.') {\n      pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n      continue;\n    }\n\n    pattern += source[i];\n    if (source[i] === '\\\\') {\n      isEscaped = true;\n    } else if (inCharGroup && source[i] === ']') {\n      inCharGroup = false;\n    } else if (!inCharGroup && source[i] === '[') {\n      inCharGroup = true;\n    }\n  }\n\n  try {\n    new RegExp(pattern);\n  } catch {\n    console.warn(\n      `Could not convert regex pattern at ${refs.currentPath.join(\n        '/',\n      )} to a flag-independent form! Falling back to the flag-ignorant source`,\n    );\n    return regex.source;\n  }\n\n  return pattern;\n}\n", "import { ZodMapDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\nimport { JsonSchema7RecordType, parseRecordDef } from './record';\n\nexport type JsonSchema7MapType = {\n  type: 'array';\n  maxItems: 125;\n  items: {\n    type: 'array';\n    items: [JsonSchema7Type, JsonSchema7Type];\n    minItems: 2;\n    maxItems: 2;\n  };\n};\n\nexport function parseMapDef(\n  def: ZodMapDef,\n  refs: Refs,\n): JsonSchema7MapType | JsonSchema7RecordType {\n  if (refs.mapStrategy === 'record') {\n    return parseRecordDef(def, refs);\n  }\n\n  const keys =\n    parseDef(def.keyType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items', 'items', '0'],\n    }) || parseAnyDef();\n  const values =\n    parseDef(def.valueType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items', 'items', '1'],\n    }) || parseAnyDef();\n  return {\n    type: 'array',\n    maxItems: 125,\n    items: {\n      type: 'array',\n      items: [keys, values],\n      minItems: 2,\n      maxItems: 2,\n    },\n  };\n}\n", "import { ZodNativeEnumDef } from 'zod/v3';\n\nexport type JsonSchema7NativeEnumType = {\n  type: 'string' | 'number' | ['string', 'number'];\n  enum: (string | number)[];\n};\n\nexport function parseNativeEnumDef(\n  def: ZodNativeEnumDef,\n): JsonSchema7NativeEnumType {\n  const object = def.values;\n  const actualKeys = Object.keys(def.values).filter((key: string) => {\n    return typeof object[object[key]] !== 'number';\n  });\n\n  const actualValues = actualKeys.map((key: string) => object[key]);\n\n  const parsedTypes = Array.from(\n    new Set(actualValues.map((values: string | number) => typeof values)),\n  );\n\n  return {\n    type:\n      parsedTypes.length === 1\n        ? parsedTypes[0] === 'string'\n          ? 'string'\n          : 'number'\n        : ['string', 'number'],\n    enum: actualValues,\n  };\n}\n", "import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7NeverType = {\n  not: JsonSchema7AnyType;\n};\n\nexport function parseNeverDef(): JsonSchema7NeverType | undefined {\n  return { not: parseAnyDef() };\n}\n", "export type JsonSchema7NullType = {\n  type: 'null';\n};\n\nexport function parseNullDef(): JsonSchema7NullType {\n  return {\n    type: 'null',\n  };\n}\n", "import {\n  ZodDiscriminatedUnionDef,\n  ZodLiteralDef,\n  ZodTypeAny,\n  ZodUnionDef,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport const primitiveMappings = {\n  ZodString: 'string',\n  ZodNumber: 'number',\n  ZodBigInt: 'integer',\n  ZodBoolean: 'boolean',\n  ZodNull: 'null',\n} as const;\ntype ZodPrimitive = keyof typeof primitiveMappings;\ntype JsonSchema7Primitive =\n  (typeof primitiveMappings)[keyof typeof primitiveMappings];\n\nexport type JsonSchema7UnionType =\n  | JsonSchema7PrimitiveUnionType\n  | JsonSchema7AnyOfType;\n\ntype JsonSchema7PrimitiveUnionType =\n  | {\n      type: JsonSchema7Primitive | JsonSchema7Primitive[];\n    }\n  | {\n      type: JsonSchema7Primitive | JsonSchema7Primitive[];\n      enum: (string | number | bigint | boolean | null)[];\n    };\n\ntype JsonSchema7AnyOfType = {\n  anyOf: JsonSchema7Type[];\n};\n\nexport function parseUnionDef(\n  def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n  refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined {\n  const options: readonly ZodTypeAny[] =\n    def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\n  // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n  if (\n    options.every(\n      x =>\n        x._def.typeName in primitiveMappings &&\n        (!x._def.checks || !x._def.checks.length),\n    )\n  ) {\n    // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n\n    const types = options.reduce((types: JsonSchema7Primitive[], x) => {\n      const type = primitiveMappings[x._def.typeName as ZodPrimitive]; //Can be safely casted due to row 43\n      return type && !types.includes(type) ? [...types, type] : types;\n    }, []);\n\n    return {\n      type: types.length > 1 ? types : types[0],\n    };\n  } else if (\n    options.every(x => x._def.typeName === 'ZodLiteral' && !x.description)\n  ) {\n    // all options literals\n\n    const types = options.reduce(\n      (acc: JsonSchema7Primitive[], x: { _def: ZodLiteralDef }) => {\n        const type = typeof x._def.value;\n        switch (type) {\n          case 'string':\n          case 'number':\n          case 'boolean':\n            return [...acc, type];\n          case 'bigint':\n            return [...acc, 'integer' as const];\n          case 'object':\n            if (x._def.value === null) return [...acc, 'null' as const];\n          case 'symbol':\n          case 'undefined':\n          case 'function':\n          default:\n            return acc;\n        }\n      },\n      [],\n    );\n\n    if (types.length === options.length) {\n      // all the literals are primitive, as far as null can be considered primitive\n\n      const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n      return {\n        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n        enum: options.reduce(\n          (acc, x) => {\n            return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n          },\n          [] as (string | number | bigint | boolean | null)[],\n        ),\n      };\n    }\n  } else if (options.every(x => x._def.typeName === 'ZodEnum')) {\n    return {\n      type: 'string',\n      enum: options.reduce(\n        (acc: string[], x) => [\n          ...acc,\n          ...x._def.values.filter((x: string) => !acc.includes(x)),\n        ],\n        [],\n      ),\n    };\n  }\n\n  return asAnyOf(def, refs);\n}\n\nconst asAnyOf = (\n  def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n  refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined => {\n  const anyOf = (\n    (def.options instanceof Map\n      ? Array.from(def.options.values())\n      : def.options) as any[]\n  )\n    .map((x, i) =>\n      parseDef(x._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'anyOf', `${i}`],\n      }),\n    )\n    .filter(\n      (x): x is JsonSchema7Type =>\n        !!x &&\n        (!refs.strictUnions ||\n          (typeof x === 'object' && Object.keys(x).length > 0)),\n    );\n\n  return anyOf.length ? { anyOf } : undefined;\n};\n", "import { ZodNullableDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7NullType } from './null';\nimport { primitiveMappings } from './union';\n\nexport type JsonSchema7NullableType =\n  | {\n      anyOf: [JsonSchema7Type, JsonSchema7NullType];\n    }\n  | {\n      type: [string, 'null'];\n    };\n\nexport function parseNullableDef(\n  def: ZodNullableDef,\n  refs: Refs,\n): JsonSchema7NullableType | undefined {\n  if (\n    ['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(\n      def.innerType._def.typeName,\n    ) &&\n    (!def.innerType._def.checks || !def.innerType._def.checks.length)\n  ) {\n    return {\n      type: [\n        primitiveMappings[\n          def.innerType._def.typeName as keyof typeof primitiveMappings\n        ],\n        'null',\n      ],\n    };\n  }\n\n  const base = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'anyOf', '0'],\n  });\n\n  return base && { anyOf: [base, { type: 'null' }] };\n}\n", "import { ZodNumberDef } from 'zod/v3';\n\nexport type JsonSchema7NumberType = {\n  type: 'number' | 'integer';\n  minimum?: number;\n  exclusiveMinimum?: number;\n  maximum?: number;\n  exclusiveMaximum?: number;\n  multipleOf?: number;\n};\n\nexport function parseNumberDef(def: ZodNumberDef): JsonSchema7NumberType {\n  const res: JsonSchema7NumberType = {\n    type: 'number',\n  };\n\n  if (!def.checks) return res;\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'int':\n        res.type = 'integer';\n        break;\n      case 'min':\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case 'max':\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n        break;\n      case 'multipleOf':\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n", "import { ZodObjectDef, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7ObjectType = {\n  type: 'object';\n  properties: Record<string, JsonSchema7Type>;\n  additionalProperties?: boolean | JsonSchema7Type;\n  required?: string[];\n};\n\nexport function parseObjectDef(def: ZodObjectDef, refs: Refs) {\n  const result: JsonSchema7ObjectType = {\n    type: 'object',\n    properties: {},\n  };\n\n  const required: string[] = [];\n\n  const shape = def.shape();\n\n  for (const propName in shape) {\n    let propDef = shape[propName];\n\n    if (propDef === undefined || propDef._def === undefined) {\n      continue;\n    }\n\n    const propOptional = safeIsOptional(propDef);\n\n    const parsedDef = parseDef(propDef._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'properties', propName],\n      propertyPath: [...refs.currentPath, 'properties', propName],\n    });\n\n    if (parsedDef === undefined) {\n      continue;\n    }\n\n    result.properties[propName] = parsedDef;\n\n    if (!propOptional) {\n      required.push(propName);\n    }\n  }\n\n  if (required.length) {\n    result.required = required;\n  }\n\n  const additionalProperties = decideAdditionalProperties(def, refs);\n\n  if (additionalProperties !== undefined) {\n    result.additionalProperties = additionalProperties;\n  }\n\n  return result;\n}\n\nfunction decideAdditionalProperties(def: ZodObjectDef, refs: Refs) {\n  if (def.catchall._def.typeName !== 'ZodNever') {\n    return parseDef(def.catchall._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'additionalProperties'],\n    });\n  }\n\n  switch (def.unknownKeys) {\n    case 'passthrough':\n      return refs.allowedAdditionalProperties;\n    case 'strict':\n      return refs.rejectedAdditionalProperties;\n    case 'strip':\n      return refs.removeAdditionalStrategy === 'strict'\n        ? refs.allowedAdditionalProperties\n        : refs.rejectedAdditionalProperties;\n  }\n}\n\nfunction safeIsOptional(schema: ZodTypeAny): boolean {\n  try {\n    return schema.isOptional();\n  } catch {\n    return true;\n  }\n}\n", "import { ZodOptionalDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport const parseOptionalDef = (\n  def: ZodOptionalDef,\n  refs: Refs,\n): JsonSchema7Type | undefined => {\n  if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n    return parseDef(def.innerType._def, refs);\n  }\n\n  const innerSchema = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'anyOf', '1'],\n  });\n\n  return innerSchema\n    ? { anyOf: [{ not: parseAnyDef() }, innerSchema] }\n    : parseAnyDef();\n};\n", "import { ZodPipelineDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7AllOfType } from './intersection';\n\nexport const parsePipelineDef = (\n  def: ZodPipelineDef<any, any>,\n  refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined => {\n  if (refs.pipeStrategy === 'input') {\n    return parseDef(def.in._def, refs);\n  } else if (refs.pipeStrategy === 'output') {\n    return parseDef(def.out._def, refs);\n  }\n\n  const a = parseDef(def.in._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'allOf', '0'],\n  });\n  const b = parseDef(def.out._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],\n  });\n\n  return {\n    allOf: [a, b].filter((x): x is JsonSchema7Type => x !== undefined),\n  };\n};\n", "import { ZodPromiseDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport function parsePromiseDef(\n  def: ZodPromiseDef,\n  refs: Refs,\n): JsonSchema7Type | undefined {\n  return parseDef(def.type._def, refs);\n}\n", "import { ZodSetDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7SetType = {\n  type: 'array';\n  uniqueItems: true;\n  items?: JsonSchema7Type;\n  minItems?: number;\n  maxItems?: number;\n};\n\nexport function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType {\n  const items = parseDef(def.valueType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'items'],\n  });\n\n  const schema: JsonSchema7SetType = {\n    type: 'array',\n    uniqueItems: true,\n    items,\n  };\n\n  if (def.minSize) {\n    schema.minItems = def.minSize.value;\n  }\n\n  if (def.maxSize) {\n    schema.maxItems = def.maxSize.value;\n  }\n\n  return schema;\n}\n", "import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7TupleType = {\n  type: 'array';\n  minItems: number;\n  items: JsonSchema7Type[];\n} & (\n  | {\n      maxItems: number;\n    }\n  | {\n      additionalItems?: JsonSchema7Type;\n    }\n);\n\nexport function parseTupleDef(\n  def: ZodTupleDef<ZodTupleItems | [], ZodTypeAny | null>,\n  refs: Refs,\n): JsonSchema7TupleType {\n  if (def.rest) {\n    return {\n      type: 'array',\n      minItems: def.items.length,\n      items: def.items\n        .map((x, i) =>\n          parseDef(x._def, {\n            ...refs,\n            currentPath: [...refs.currentPath, 'items', `${i}`],\n          }),\n        )\n        .reduce(\n          (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n          [],\n        ),\n      additionalItems: parseDef(def.rest._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'additionalItems'],\n      }),\n    };\n  } else {\n    return {\n      type: 'array',\n      minItems: def.items.length,\n      maxItems: def.items.length,\n      items: def.items\n        .map((x, i) =>\n          parseDef(x._def, {\n            ...refs,\n            currentPath: [...refs.currentPath, 'items', `${i}`],\n          }),\n        )\n        .reduce(\n          (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n          [],\n        ),\n    };\n  }\n}\n", "import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7UndefinedType = {\n  not: JsonSchema7AnyType;\n};\n\nexport function parseUndefinedDef(): JsonSchema7UndefinedType {\n  return {\n    not: parseAnyDef(),\n  };\n}\n", "import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7UnknownType = JsonSchema7AnyType;\n\nexport function parseUnknownDef(): JsonSchema7UnknownType {\n  return parseAnyDef();\n}\n", "import { ZodReadonlyDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport const parseReadonlyDef = (def: ZodReadonlyDef<any>, refs: Refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n", "export const getRelativePath = (pathA: string[], pathB: string[]) => {\n  let i = 0;\n  for (; i < pathA.length && i < pathB.length; i++) {\n    if (pathA[i] !== pathB[i]) break;\n  }\n  return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');\n};\n", "import { ZodTypeDef } from 'zod/v3';\nimport { Refs, Seen } from './refs';\nimport { ignoreOverride } from './options';\nimport { JsonSchema7Type } from './parse-types';\nimport { selectParser } from './select-parser';\nimport { getRelativePath } from './get-relative-path';\nimport { parseAnyDef } from './parsers/any';\n\nexport function parseDef(\n  def: ZodTypeDef,\n  refs: Refs,\n  forceResolution = false, // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61.\n): JsonSchema7Type | undefined {\n  const seenItem = refs.seen.get(def);\n\n  if (refs.override) {\n    const overrideResult = refs.override?.(\n      def,\n      refs,\n      seenItem,\n      forceResolution,\n    );\n\n    if (overrideResult !== ignoreOverride) {\n      return overrideResult;\n    }\n  }\n\n  if (seenItem && !forceResolution) {\n    const seenSchema = get$ref(seenItem, refs);\n\n    if (seenSchema !== undefined) {\n      return seenSchema;\n    }\n  }\n\n  const newItem: Seen = { def, path: refs.currentPath, jsonSchema: undefined };\n\n  refs.seen.set(def, newItem);\n\n  const jsonSchemaOrGetter = selectParser(def, (def as any).typeName, refs);\n\n  // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n  const jsonSchema =\n    typeof jsonSchemaOrGetter === 'function'\n      ? parseDef(jsonSchemaOrGetter(), refs)\n      : jsonSchemaOrGetter;\n\n  if (jsonSchema) {\n    addMeta(def, refs, jsonSchema);\n  }\n\n  if (refs.postProcess) {\n    const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n\n    newItem.jsonSchema = jsonSchema;\n\n    return postProcessResult;\n  }\n\n  newItem.jsonSchema = jsonSchema;\n\n  return jsonSchema;\n}\n\nconst get$ref = (\n  item: Seen,\n  refs: Refs,\n):\n  | {\n      $ref: string;\n    }\n  | {}\n  | undefined => {\n  switch (refs.$refStrategy) {\n    case 'root':\n      return { $ref: item.path.join('/') };\n    case 'relative':\n      return { $ref: getRelativePath(refs.currentPath, item.path) };\n    case 'none':\n    case 'seen': {\n      if (\n        item.path.length < refs.currentPath.length &&\n        item.path.every((value, index) => refs.currentPath[index] === value)\n      ) {\n        console.warn(\n          `Recursive reference detected at ${refs.currentPath.join(\n            '/',\n          )}! Defaulting to any`,\n        );\n\n        return parseAnyDef();\n      }\n\n      return refs.$refStrategy === 'seen' ? parseAnyDef() : undefined;\n    }\n  }\n};\n\nconst addMeta = (\n  def: ZodTypeDef,\n  refs: Refs,\n  jsonSchema: JsonSchema7Type,\n): JsonSchema7Type => {\n  if (def.description) {\n    jsonSchema.description = def.description;\n  }\n  return jsonSchema;\n};\n", "import { ZodTypeDef } from 'zod/v3';\nimport { getDefaultOptions, Options } from './options';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type Refs = {\n  seen: Map<ZodTypeDef, Seen>;\n  currentPath: string[];\n  propertyPath: string[] | undefined;\n} & Options;\n\nexport type Seen = {\n  def: ZodTypeDef;\n  path: string[];\n  jsonSchema: JsonSchema7Type | undefined;\n};\n\nexport const getRefs = (options?: string | Partial<Options>): Refs => {\n  const _options = getDefaultOptions(options);\n  const currentPath =\n    _options.name !== undefined\n      ? [..._options.basePath, _options.definitionPath, _options.name]\n      : _options.basePath;\n  return {\n    ..._options,\n    currentPath: currentPath,\n    propertyPath: undefined,\n    seen: new Map(\n      Object.entries(_options.definitions).map(([name, def]) => [\n        def._def,\n        {\n          def: def._def,\n          path: [..._options.basePath, _options.definitionPath, name],\n          // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n          jsonSchema: undefined,\n        },\n      ]),\n    ),\n  };\n};\n", "import { ZodSchema } from 'zod/v3';\nimport { Options } from './options';\nimport { parseDef } from './parse-def';\nimport { JsonSchema7Type } from './parse-types';\nimport { getRefs } from './refs';\nimport { parseAnyDef } from './parsers/any';\n\nconst zod3ToJsonSchema = (\n  schema: ZodSchema<any>,\n  options?: Partial<Options> | string,\n): JsonSchema7Type & {\n  $schema?: string;\n  definitions?: {\n    [key: string]: JsonSchema7Type;\n  };\n} => {\n  const refs = getRefs(options);\n\n  let definitions =\n    typeof options === 'object' && options.definitions\n      ? Object.entries(options.definitions).reduce(\n          (acc: { [key: string]: JsonSchema7Type }, [name, schema]) => ({\n            ...acc,\n            [name]:\n              parseDef(\n                schema._def,\n                {\n                  ...refs,\n                  currentPath: [...refs.basePath, refs.definitionPath, name],\n                },\n                true,\n              ) ?? parseAnyDef(),\n          }),\n          {},\n        )\n      : undefined;\n\n  const name =\n    typeof options === 'string'\n      ? options\n      : options?.nameStrategy === 'title'\n        ? undefined\n        : options?.name;\n\n  const main =\n    parseDef(\n      schema._def,\n      name === undefined\n        ? refs\n        : {\n            ...refs,\n            currentPath: [...refs.basePath, refs.definitionPath, name],\n          },\n      false,\n    ) ?? (parseAnyDef() as JsonSchema7Type);\n\n  const title =\n    typeof options === 'object' &&\n    options.name !== undefined &&\n    options.nameStrategy === 'title'\n      ? options.name\n      : undefined;\n\n  if (title !== undefined) {\n    main.title = title;\n  }\n\n  const combined: ReturnType<typeof zod3ToJsonSchema> =\n    name === undefined\n      ? definitions\n        ? {\n            ...main,\n            [refs.definitionPath]: definitions,\n          }\n        : main\n      : {\n          $ref: [\n            ...(refs.$refStrategy === 'relative' ? [] : refs.basePath),\n            refs.definitionPath,\n            name,\n          ].join('/'),\n          [refs.definitionPath]: {\n            ...definitions,\n            [name]: main,\n          },\n        };\n\n  combined.$schema = 'http://json-schema.org/draft-07/schema#';\n\n  return combined;\n};\n\nexport { zod3ToJsonSchema };\n", "import {\n  EventSourceMessage,\n  EventSourceParserStream,\n} from 'eventsource-parser/stream';\nimport { ParseResult, safeParseJSON } from './parse-json';\nimport { FlexibleSchema } from './schema';\n\n/**\n * Parses a JSON event stream into a stream of parsed JSON objects.\n */\nexport function parseJsonEventStream<T>({\n  stream,\n  schema,\n}: {\n  stream: ReadableStream<Uint8Array>;\n  schema: FlexibleSchema<T>;\n}): ReadableStream<ParseResult<T>> {\n  return stream\n    .pipeThrough(new TextDecoderStream())\n    .pipeThrough(new EventSourceParserStream())\n    .pipeThrough(\n      new TransformStream<EventSourceMessage, ParseResult<T>>({\n        async transform({ data }, controller) {\n          // ignore the 'DONE' event that e.g. OpenAI sends:\n          if (data === '[DONE]') {\n            return;\n          }\n\n          controller.enqueue(await safeParseJSON({ text: data, schema }));\n        },\n      }),\n    );\n}\n", "import { InvalidArgumentError } from '@ai-sdk/provider';\nimport { safeValidateTypes } from './validate-types';\nimport { FlexibleSchema } from './schema';\n\nexport async function parseProviderOptions<OPTIONS>({\n  provider,\n  providerOptions,\n  schema,\n}: {\n  provider: string;\n  providerOptions: Record<string, unknown> | undefined;\n  schema: FlexibleSchema<OPTIONS>;\n}): Promise<OPTIONS | undefined> {\n  if (providerOptions?.[provider] == null) {\n    return undefined;\n  }\n\n  const parsedProviderOptions = await safeValidateTypes<OPTIONS | undefined>({\n    value: providerOptions[provider],\n    schema,\n  });\n\n  if (!parsedProviderOptions.success) {\n    throw new InvalidArgumentError({\n      argument: 'providerOptions',\n      message: `invalid ${provider} provider options`,\n      cause: parsedProviderOptions.error,\n    });\n  }\n\n  return parsedProviderOptions.value;\n}\n", "import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport { ResponseHandler } from './response-handler';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\nimport { VERSION } from './version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const postJsonToApi = async <T>({\n  url,\n  headers,\n  body,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  body: unknown;\n  failedResponseHandler: ResponseHandler<APICallError>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) =>\n  postToApi({\n    url,\n    headers: {\n      'Content-Type': 'application/json',\n      ...headers,\n    },\n    body: {\n      content: JSON.stringify(body),\n      values: body,\n    },\n    failedResponseHandler,\n    successfulResponseHandler,\n    abortSignal,\n    fetch,\n  });\n\nexport const postFormDataToApi = async <T>({\n  url,\n  headers,\n  formData,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  formData: FormData;\n  failedResponseHandler: ResponseHandler<APICallError>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) =>\n  postToApi({\n    url,\n    headers,\n    body: {\n      content: formData,\n      values: Object.fromEntries((formData as any).entries()),\n    },\n    failedResponseHandler,\n    successfulResponseHandler,\n    abortSignal,\n    fetch,\n  });\n\nexport const postToApi = async <T>({\n  url,\n  headers = {},\n  body,\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  body: {\n    content: string | FormData | Uint8Array;\n    values: unknown;\n  };\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  try {\n    const response = await fetch(url, {\n      method: 'POST',\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      body: body.content,\n      signal: abortSignal,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: body.values,\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: body.values,\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: body.values,\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: body.values,\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: body.values });\n  }\n};\n", "import { JSONValue } from '@ai-sdk/provider';\nimport { FlexibleSchema } from '../schema';\nimport { ToolResultOutput } from './content-part';\nimport { ModelMessage } from './model-message';\nimport { ProviderOptions } from './provider-options';\n\n/**\n * Additional options that are sent into each tool call.\n */\nexport interface ToolExecutionOptions {\n  /**\n   * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n   */\n  toolCallId: string;\n\n  /**\n   * Messages that were sent to the language model to initiate the response that contained the tool call.\n   * The messages **do not** include the system prompt nor the assistant response that contained the tool call.\n   */\n  messages: ModelMessage[];\n\n  /**\n   * An optional abort signal that indicates that the overall operation should be aborted.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * User-defined context.\n   *\n   * Treat the context object as immutable inside tools.\n   * Mutating the context object can lead to race conditions and unexpected results\n   * when tools are called in parallel.\n   *\n   * If you need to mutate the context, analyze the tool calls and results\n   * in `prepareStep` and update it there.\n   *\n   * Experimental (can break in patch releases).\n   */\n  experimental_context?: unknown;\n}\n\n/**\n * Function that is called to determine if the tool needs approval before it can be executed.\n */\nexport type ToolNeedsApprovalFunction<INPUT> = (\n  input: INPUT,\n  options: {\n    /**\n     * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n     */\n    toolCallId: string;\n\n    /**\n     * Messages that were sent to the language model to initiate the response that contained the tool call.\n     * The messages **do not** include the system prompt nor the assistant response that contained the tool call.\n     */\n    messages: ModelMessage[];\n\n    /**\n     * Additional context.\n     *\n     * Experimental (can break in patch releases).\n     */\n    experimental_context?: unknown;\n  },\n) => boolean | PromiseLike<boolean>;\n\nexport type ToolExecuteFunction<INPUT, OUTPUT> = (\n  input: INPUT,\n  options: ToolExecutionOptions,\n) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;\n\n// 0 extends 1 & N checks for any\n// [N] extends [never] checks for never\ntype NeverOptional<N, T> = 0 extends 1 & N\n  ? Partial<T>\n  : [N] extends [never]\n    ? Partial<Record<keyof T, undefined>>\n    : T;\n\ntype ToolOutputProperties<INPUT, OUTPUT> = NeverOptional<\n  OUTPUT,\n  | {\n      /**\n       * An async function that is called with the arguments from the tool call and produces a result.\n       * If not provided, the tool will not be executed automatically.\n       *\n       * @args is the input of the tool call.\n       * @options.abortSignal is a signal that can be used to abort the tool call.\n       */\n      execute: ToolExecuteFunction<INPUT, OUTPUT>;\n\n      outputSchema?: FlexibleSchema<OUTPUT>;\n    }\n  | {\n      outputSchema: FlexibleSchema<OUTPUT>;\n\n      execute?: never;\n    }\n>;\n\n/**\n * A tool contains the description and the schema of the input that the tool expects.\n * This enables the language model to generate the input.\n *\n * The tool can also contain an optional execute function for the actual execution function of the tool.\n */\nexport type Tool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n> = {\n  /**\n   * An optional description of what the tool does.\n   * Will be used by the language model to decide whether to use the tool.\n   * Not used for provider-defined tools.\n   */\n  description?: string;\n\n  /**\n   * An optional title of the tool.\n   */\n  title?: string;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * The schema of the input that the tool expects.\n   * The language model will use this to generate the input.\n   * It is also used to validate the output of the language model.\n   *\n   * You can use descriptions on the schema properties to make the input understandable for the language model.\n   */\n  inputSchema: FlexibleSchema<INPUT>;\n\n  /**\n   * An optional list of input examples that show the language\n   * model what the input should look like.\n   */\n  inputExamples?: Array<{ input: NoInfer<INPUT> }>;\n\n  /**\n   * Whether the tool needs approval before it can be executed.\n   */\n  needsApproval?:\n    | boolean\n    | ToolNeedsApprovalFunction<[INPUT] extends [never] ? unknown : INPUT>;\n\n  /**\n   * Strict mode setting for the tool.\n   *\n   * Providers that support strict mode will use this setting to determine\n   * how the input should be generated. Strict mode will always produce\n   * valid inputs, but it might limit what input schemas are supported.\n   */\n  strict?: boolean;\n\n  /**\n   * Optional function that is called when the argument streaming starts.\n   * Only called when the tool is used in a streaming context.\n   */\n  onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;\n\n  /**\n   * Optional function that is called when an argument streaming delta is available.\n   * Only called when the tool is used in a streaming context.\n   */\n  onInputDelta?: (\n    options: { inputTextDelta: string } & ToolExecutionOptions,\n  ) => void | PromiseLike<void>;\n\n  /**\n   * Optional function that is called when a tool call can be started,\n   * even if the execute function is not provided.\n   */\n  onInputAvailable?: (\n    options: {\n      input: [INPUT] extends [never] ? unknown : INPUT;\n    } & ToolExecutionOptions,\n  ) => void | PromiseLike<void>;\n} & ToolOutputProperties<INPUT, OUTPUT> & {\n    /**\n     * Optional conversion function that maps the tool result to an output that can be used by the language model.\n     *\n     * If not provided, the tool result will be sent as a JSON object.\n     */\n    toModelOutput?: (options: {\n      /**\n       * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n       */\n      toolCallId: string;\n\n      /**\n       * The input of the tool call.\n       */\n      input: [INPUT] extends [never] ? unknown : INPUT;\n\n      /**\n       * The output of the tool call.\n       */\n      output: 0 extends 1 & OUTPUT\n        ? any\n        : [OUTPUT] extends [never]\n          ? any\n          : NoInfer<OUTPUT>;\n    }) => ToolResultOutput | PromiseLike<ToolResultOutput>;\n  } & (\n    | {\n        /**\n         * Tool with user-defined input and output schemas.\n         */\n        type?: undefined | 'function';\n      }\n    | {\n        /**\n         * Tool that is defined at runtime (e.g. an MCP tool).\n         * The types of input and output are not known at development time.\n         */\n        type: 'dynamic';\n      }\n    | {\n        /**\n         * Tool with provider-defined input and output schemas.\n         */\n        type: 'provider';\n\n        /**\n         * The ID of the tool. Must follow the format `<provider-name>.<unique-tool-name>`.\n         */\n        id: `${string}.${string}`;\n\n        /**\n         * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.\n         */\n        args: Record<string, unknown>;\n\n        /**\n         * Whether this provider-executed tool supports deferred results.\n         *\n         * When true, the tool result may not be returned in the same turn as the\n         * tool call (e.g., when using programmatic tool calling where a server tool\n         * triggers a client-executed tool, and the server tool's result is deferred\n         * until the client tool is resolved).\n         *\n         * This flag allows the AI SDK to handle tool results that arrive without\n         * a matching tool call in the current response.\n         *\n         * @default false\n         */\n        supportsDeferredResults?: boolean;\n      }\n  );\n\n/**\n * Infer the input type of a tool.\n */\nexport type InferToolInput<TOOL extends Tool> =\n  TOOL extends Tool<infer INPUT, any> ? INPUT : never;\n\n/**\n * Infer the output type of a tool.\n */\nexport type InferToolOutput<TOOL extends Tool> =\n  TOOL extends Tool<any, infer OUTPUT> ? OUTPUT : never;\n\n/**\n * Helper function for inferring the execute args of a tool.\n */\n// Note: overload order is important for auto-completion\nexport function tool<INPUT, OUTPUT>(\n  tool: Tool<INPUT, OUTPUT>,\n): Tool<INPUT, OUTPUT>;\nexport function tool<INPUT>(tool: Tool<INPUT, never>): Tool<INPUT, never>;\nexport function tool<OUTPUT>(tool: Tool<never, OUTPUT>): Tool<never, OUTPUT>;\nexport function tool(tool: Tool<never, never>): Tool<never, never>;\nexport function tool(tool: any): any {\n  return tool;\n}\n\n/**\n * Defines a dynamic tool.\n */\nexport function dynamicTool(tool: {\n  description?: string;\n  title?: string;\n  providerOptions?: ProviderOptions;\n  inputSchema: FlexibleSchema<unknown>;\n  execute: ToolExecuteFunction<unknown, unknown>;\n\n  /**\n   * Optional conversion function that maps the tool result to an output that can be used by the language model.\n   *\n   * If not provided, the tool result will be sent as a JSON object.\n   */\n  toModelOutput?: (options: {\n    /**\n     * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n     */\n    toolCallId: string;\n\n    /**\n     * The input of the tool call.\n     */\n    input: unknown;\n\n    /**\n     * The output of the tool call.\n     */\n    output: unknown;\n  }) => ToolResultOutput | PromiseLike<ToolResultOutput>;\n\n  /**\n   * Whether the tool needs approval before it can be executed.\n   */\n  needsApproval?: boolean | ToolNeedsApprovalFunction<unknown>;\n}): Tool<unknown, unknown> & {\n  type: 'dynamic';\n} {\n  return { ...tool, type: 'dynamic' };\n}\n", "import { tool, Tool, ToolExecuteFunction } from './types/tool';\nimport { FlexibleSchema } from './schema';\n\nexport type ProviderToolFactory<INPUT, ARGS extends object> = <OUTPUT>(\n  options: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  },\n) => Tool<INPUT, OUTPUT>;\n\nexport function createProviderToolFactory<INPUT, ARGS extends object>({\n  id,\n  inputSchema,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n}): ProviderToolFactory<INPUT, ARGS> {\n  return <OUTPUT>({\n    execute,\n    outputSchema,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    outputSchema?: FlexibleSchema<OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  }): Tool<INPUT, OUTPUT> =>\n    tool({\n      type: 'provider',\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      execute,\n      needsApproval,\n      toModelOutput,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n    });\n}\n\nexport type ProviderToolFactoryWithOutputSchema<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n> = (\n  options: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  },\n) => Tool<INPUT, OUTPUT>;\n\nexport function createProviderToolFactoryWithOutputSchema<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n>({\n  id,\n  inputSchema,\n  outputSchema,\n  supportsDeferredResults,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n  outputSchema: FlexibleSchema<OUTPUT>;\n  /**\n   * Whether this provider-executed tool supports deferred results.\n   *\n   * When true, the tool result may not be returned in the same turn as the\n   * tool call (e.g., when using programmatic tool calling where a server tool\n   * triggers a client-executed tool, and the server tool's result is deferred\n   * until the client tool is resolved).\n   *\n   * @default false\n   */\n  supportsDeferredResults?: boolean;\n}): ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS> {\n  return ({\n    execute,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];\n  }): Tool<INPUT, OUTPUT> =>\n    tool({\n      type: 'provider',\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      execute,\n      needsApproval,\n      toModelOutput,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n      supportsDeferredResults,\n    });\n}\n", "/**\n * Removes entries from a record where the value is null or undefined.\n * @param record - The input object whose entries may be null or undefined.\n * @returns A new object containing only entries with non-null and non-undefined values.\n */\nexport function removeUndefinedEntries<T>(\n  record: Record<string, T | undefined>,\n): Record<string, T> {\n  return Object.fromEntries(\n    Object.entries(record).filter(([_key, value]) => value != null),\n  ) as Record<string, T>;\n}\n", "import { MaybePromiseLike } from './maybe-promise-like';\n\nexport type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);\n\n/**\n * Resolves a value that could be a raw value, a Promise, a function returning a value,\n * or a function returning a Promise.\n */\nexport async function resolve<T>(value: Resolvable<T>): Promise<T> {\n  // If it's a function, call it to get the value/promise\n  if (typeof value === 'function') {\n    value = (value as Function)();\n  }\n\n  // Otherwise just resolve whatever we got (value or promise)\n  return Promise.resolve(value as T);\n}\n", "import { APICallError, EmptyResponseBodyError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { parseJSON, ParseResult, safeParseJSON } from './parse-json';\nimport { parseJsonEventStream } from './parse-json-event-stream';\nimport { FlexibleSchema } from './schema';\n\nexport type ResponseHandler<RETURN_TYPE> = (options: {\n  url: string;\n  requestBodyValues: unknown;\n  response: Response;\n}) => PromiseLike<{\n  value: RETURN_TYPE;\n  rawValue?: unknown;\n  responseHeaders?: Record<string, string>;\n}>;\n\nexport const createJsonErrorResponseHandler =\n  <T>({\n    errorSchema,\n    errorToMessage,\n    isRetryable,\n  }: {\n    errorSchema: FlexibleSchema<T>;\n    errorToMessage: (error: T) => string;\n    isRetryable?: (response: Response, error?: T) => boolean;\n  }): ResponseHandler<APICallError> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseBody = await response.text();\n    const responseHeaders = extractResponseHeaders(response);\n\n    // Some providers return an empty response body for some errors:\n    if (responseBody.trim() === '') {\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: response.statusText,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          isRetryable: isRetryable?.(response),\n        }),\n      };\n    }\n\n    // resilient parsing in case the response is not JSON or does not match the schema:\n    try {\n      const parsedError = await parseJSON({\n        text: responseBody,\n        schema: errorSchema,\n      });\n\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: errorToMessage(parsedError),\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          data: parsedError,\n          isRetryable: isRetryable?.(response, parsedError),\n        }),\n      };\n    } catch (parseError) {\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: response.statusText,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          isRetryable: isRetryable?.(response),\n        }),\n      };\n    }\n  };\n\nexport const createEventSourceResponseHandler =\n  <T>(\n    chunkSchema: FlexibleSchema<T>,\n  ): ResponseHandler<ReadableStream<ParseResult<T>>> =>\n  async ({ response }: { response: Response }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (response.body == null) {\n      throw new EmptyResponseBodyError({});\n    }\n\n    return {\n      responseHeaders,\n      value: parseJsonEventStream({\n        stream: response.body,\n        schema: chunkSchema,\n      }),\n    };\n  };\n\nexport const createJsonResponseHandler =\n  <T>(responseSchema: FlexibleSchema<T>): ResponseHandler<T> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseBody = await response.text();\n\n    const parsedResult = await safeParseJSON({\n      text: responseBody,\n      schema: responseSchema,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!parsedResult.success) {\n      throw new APICallError({\n        message: 'Invalid JSON response',\n        cause: parsedResult.error,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n        url,\n        requestBodyValues,\n      });\n    }\n\n    return {\n      responseHeaders,\n      value: parsedResult.value,\n      rawValue: parsedResult.rawValue,\n    };\n  };\n\nexport const createBinaryResponseHandler =\n  (): ResponseHandler<Uint8Array> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.body) {\n      throw new APICallError({\n        message: 'Response body is empty',\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody: undefined,\n      });\n    }\n\n    try {\n      const buffer = await response.arrayBuffer();\n      return {\n        responseHeaders,\n        value: new Uint8Array(buffer),\n      };\n    } catch (error) {\n      throw new APICallError({\n        message: 'Failed to read response as array buffer',\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody: undefined,\n        cause: error,\n      });\n    }\n  };\n\nexport const createStatusCodeErrorResponseHandler =\n  (): ResponseHandler<APICallError> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n    const responseBody = await response.text();\n\n    return {\n      responseHeaders,\n      value: new APICallError({\n        message: response.statusText,\n        url,\n        requestBodyValues: requestBodyValues as Record<string, unknown>,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n      }),\n    };\n  };\n", "/**\n * Strips file extension segments from a filename.\n *\n * Examples:\n * - \"report.pdf\" -> \"report\"\n * - \"archive.tar.gz\" -> \"archive\"\n * - \"filename\" -> \"filename\"\n */\nexport function stripFileExtension(filename: string): string {\n  const firstDotIndex = filename.indexOf('.');\n\n  return firstDotIndex === -1 ? filename : filename.slice(0, firstDotIndex);\n}\n", "export function withoutTrailingSlash(url: string | undefined) {\n  return url?.replace(/\\/$/, '');\n}\n", "export function isAsyncIterable<T = any>(obj: any): obj is AsyncIterable<T> {\n  return obj != null && typeof obj[Symbol.asyncIterator] === 'function';\n}\n", "import { isAsyncIterable } from '../is-async-iterable';\nimport { ToolExecutionOptions, ToolExecuteFunction } from './tool';\n\nexport async function* executeTool<INPUT, OUTPUT>({\n  execute,\n  input,\n  options,\n}: {\n  execute: ToolExecuteFunction<INPUT, OUTPUT>;\n  input: INPUT;\n  options: ToolExecutionOptions;\n}): AsyncGenerator<\n  { type: 'preliminary'; output: OUTPUT } | { type: 'final'; output: OUTPUT }\n> {\n  const result = execute(input, options);\n\n  if (isAsyncIterable(result)) {\n    let lastOutput: OUTPUT | undefined;\n    for await (const output of result) {\n      lastOutput = output;\n      yield { type: 'preliminary', output };\n    }\n    yield { type: 'final', output: lastOutput! };\n  } else {\n    yield { type: 'final', output: await result };\n  }\n}\n", "export * from './combine-headers';\nexport { convertAsyncIteratorToReadableStream } from './convert-async-iterator-to-readable-stream';\nexport {\n  createToolNameMapping,\n  type ToolNameMapping,\n} from './create-tool-name-mapping';\nexport * from './delay';\nexport { DelayedPromise } from './delayed-promise';\nexport * from './extract-response-headers';\nexport { convertImageModelFileToDataUri } from './convert-image-model-file-to-data-uri';\nexport { convertToFormData } from './convert-to-form-data';\nexport { downloadBlob } from './download-blob';\nexport { DownloadError } from './download-error';\nexport {\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n} from './read-response-with-size-limit';\nexport * from './fetch-function';\nexport { createIdGenerator, generateId, type IdGenerator } from './generate-id';\nexport * from './get-error-message';\nexport * from './get-from-api';\nexport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nexport { injectJsonInstructionIntoMessages } from './inject-json-instruction';\nexport * from './is-abort-error';\nexport { isNonNullable } from './is-non-nullable';\nexport { isUrlSupported } from './is-url-supported';\nexport * from './load-api-key';\nexport { loadOptionalSetting } from './load-optional-setting';\nexport { loadSetting } from './load-setting';\nexport { type MaybePromiseLike } from './maybe-promise-like';\nexport { mediaTypeToExtension } from './media-type-to-extension';\nexport { normalizeHeaders } from './normalize-headers';\nexport * from './parse-json';\nexport { parseJsonEventStream } from './parse-json-event-stream';\nexport { parseProviderOptions } from './parse-provider-options';\nexport * from './post-to-api';\nexport {\n  createProviderToolFactory,\n  createProviderToolFactoryWithOutputSchema,\n  type ProviderToolFactory,\n  type ProviderToolFactoryWithOutputSchema,\n} from './provider-tool-factory';\nexport * from './remove-undefined-entries';\nexport * from './resolve';\nexport * from './response-handler';\nexport {\n  asSchema,\n  jsonSchema,\n  lazySchema,\n  zodSchema,\n  type FlexibleSchema,\n  type InferSchema,\n  type LazySchema,\n  type Schema,\n  type ValidationResult,\n} from './schema';\nexport { stripFileExtension } from './strip-file-extension';\nexport * from './uint8-utils';\nexport { validateDownloadUrl } from './validate-download-url';\nexport * from './validate-types';\nexport { VERSION } from './version';\nexport { withUserAgentSuffix } from './with-user-agent-suffix';\nexport * from './without-trailing-slash';\n\n// folder re-exports\nexport * from './types';\n\n// external re-exports\nexport type * from '@standard-schema/spec';\nexport {\n  EventSourceParserStream,\n  type EventSourceMessage,\n} from 'eventsource-parser/stream';\n", "/**\n * The type of error that occurred.\n * @public\n */\nexport type ErrorType = 'invalid-retry' | 'unknown-field'\n\n/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n  /**\n   * The type of error that occurred.\n   */\n  type: ErrorType\n\n  /**\n   * In the case of an unknown field encountered in the stream, this will be the field name.\n   */\n  field?: string | undefined\n\n  /**\n   * In the case of an unknown field encountered in the stream, this will be the value of the field.\n   */\n  value?: string | undefined\n\n  /**\n   * The line that caused the error, if available.\n   */\n  line?: string | undefined\n\n  constructor(\n    message: string,\n    options: {type: ErrorType; field?: string; value?: string; line?: string},\n  ) {\n    super(message)\n    this.name = 'ParseError'\n    this.type = options.type\n    this.field = options.field\n    this.value = options.value\n    this.line = options.line\n  }\n}\n", "/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport {ParseError} from './errors.ts'\nimport type {EventSourceParser, ParserCallbacks} from './types.ts'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction noop(_arg: unknown) {\n  // intentional noop\n}\n\n/**\n * Creates a new EventSource parser.\n *\n * @param callbacks - Callbacks to invoke on different parsing events:\n *   - `onEvent` when a new event is parsed\n *   - `onError` when an error occurs\n *   - `onRetry` when a new reconnection interval has been sent from the server\n *   - `onComment` when a comment is encountered in the stream\n *\n * @returns A new EventSource parser, with `parse` and `reset` methods.\n * @public\n */\nexport function createParser(callbacks: ParserCallbacks): EventSourceParser {\n  if (typeof callbacks === 'function') {\n    throw new TypeError(\n      '`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?',\n    )\n  }\n\n  const {onEvent = noop, onError = noop, onRetry = noop, onComment} = callbacks\n\n  let incompleteLine = ''\n\n  let isFirstChunk = true\n  let id: string | undefined\n  let data = ''\n  let eventType = ''\n\n  function feed(newChunk: string) {\n    // Strip any UTF8 byte order mark (BOM) at the start of the stream\n    const chunk = isFirstChunk ? newChunk.replace(/^\\xEF\\xBB\\xBF/, '') : newChunk\n\n    // If there was a previous incomplete line, append it to the new chunk,\n    // so we may process it together as a new (hopefully complete) chunk.\n    const [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`)\n\n    for (const line of complete) {\n      parseLine(line)\n    }\n\n    incompleteLine = incomplete\n    isFirstChunk = false\n  }\n\n  function parseLine(line: string) {\n    // If the line is empty (a blank line), dispatch the event\n    if (line === '') {\n      dispatchEvent()\n      return\n    }\n\n    // If the line starts with a U+003A COLON character (:), ignore the line.\n    if (line.startsWith(':')) {\n      if (onComment) {\n        onComment(line.slice(line.startsWith(': ') ? 2 : 1))\n      }\n      return\n    }\n\n    // If the line contains a U+003A COLON character (:)\n    const fieldSeparatorIndex = line.indexOf(':')\n    if (fieldSeparatorIndex !== -1) {\n      // Collect the characters on the line before the first U+003A COLON character (:),\n      // and let `field` be that string.\n      const field = line.slice(0, fieldSeparatorIndex)\n\n      // Collect the characters on the line after the first U+003A COLON character (:),\n      // and let `value` be that string. If value starts with a U+0020 SPACE character,\n      // remove it from value.\n      const offset = line[fieldSeparatorIndex + 1] === ' ' ? 2 : 1\n      const value = line.slice(fieldSeparatorIndex + offset)\n\n      processField(field, value, line)\n      return\n    }\n\n    // Otherwise, the string is not empty but does not contain a U+003A COLON character (:)\n    // Process the field using the whole line as the field name, and an empty string as the field value.\n    // 👆 This is according to spec. That means that a line that has the value `data` will result in\n    // a newline being added to the current `data` buffer, for instance.\n    processField(line, '', line)\n  }\n\n  function processField(field: string, value: string, line: string) {\n    // Field names must be compared literally, with no case folding performed.\n    switch (field) {\n      case 'event':\n        // Set the `event type` buffer to field value\n        eventType = value\n        break\n      case 'data':\n        // Append the field value to the `data` buffer, then append a single U+000A LINE FEED(LF)\n        // character to the `data` buffer.\n        data = `${data}${value}\\n`\n        break\n      case 'id':\n        // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n        // the field value. Otherwise, ignore the field.\n        id = value.includes('\\0') ? undefined : value\n        break\n      case 'retry':\n        // If the field value consists of only ASCII digits, then interpret the field value as an\n        // integer in base ten, and set the event stream's reconnection time to that integer.\n        // Otherwise, ignore the field.\n        if (/^\\d+$/.test(value)) {\n          onRetry(parseInt(value, 10))\n        } else {\n          onError(\n            new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n              type: 'invalid-retry',\n              value,\n              line,\n            }),\n          )\n        }\n        break\n      default:\n        // Otherwise, the field is ignored.\n        onError(\n          new ParseError(\n            `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`,\n            {type: 'unknown-field', field, value, line},\n          ),\n        )\n        break\n    }\n  }\n\n  function dispatchEvent() {\n    const shouldDispatch = data.length > 0\n    if (shouldDispatch) {\n      onEvent({\n        id,\n        event: eventType || undefined,\n        // If the data buffer's last character is a U+000A LINE FEED (LF) character,\n        // then remove the last character from the data buffer.\n        data: data.endsWith('\\n') ? data.slice(0, -1) : data,\n      })\n    }\n\n    // Reset for the next event\n    id = undefined\n    data = ''\n    eventType = ''\n  }\n\n  function reset(options: {consume?: boolean} = {}) {\n    if (incompleteLine && options.consume) {\n      parseLine(incompleteLine)\n    }\n\n    isFirstChunk = true\n    id = undefined\n    data = ''\n    eventType = ''\n    incompleteLine = ''\n  }\n\n  return {feed, reset}\n}\n\n/**\n * For the given `chunk`, split it into lines according to spec, and return any remaining incomplete line.\n *\n * @param chunk - The chunk to split into lines\n * @returns A tuple containing an array of complete lines, and any remaining incomplete line\n * @internal\n */\nfunction splitLines(chunk: string): [complete: Array<string>, incomplete: string] {\n  /**\n   * According to the spec, a line is terminated by either:\n   * - U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair\n   * - a single U+000A LINE FEED(LF) character not preceded by a U+000D CARRIAGE RETURN(CR) character\n   * - a single U+000D CARRIAGE RETURN(CR) character not followed by a U+000A LINE FEED(LF) character\n   */\n  const lines: Array<string> = []\n  let incompleteLine = ''\n  let searchIndex = 0\n\n  while (searchIndex < chunk.length) {\n    // Find next line terminator\n    const crIndex = chunk.indexOf('\\r', searchIndex)\n    const lfIndex = chunk.indexOf('\\n', searchIndex)\n\n    // Determine line end\n    let lineEnd = -1\n    if (crIndex !== -1 && lfIndex !== -1) {\n      // CRLF case\n      lineEnd = Math.min(crIndex, lfIndex)\n    } else if (crIndex !== -1) {\n      // CR at the end of a chunk might be part of a CRLF sequence that spans chunks,\n      // so we shouldn't treat it as a line terminator (yet)\n      if (crIndex === chunk.length - 1) {\n        lineEnd = -1\n      } else {\n        lineEnd = crIndex\n      }\n    } else if (lfIndex !== -1) {\n      lineEnd = lfIndex\n    }\n\n    // Extract line if terminator found\n    if (lineEnd === -1) {\n      // No terminator found, rest is incomplete\n      incompleteLine = chunk.slice(searchIndex)\n      break\n    } else {\n      const line = chunk.slice(searchIndex, lineEnd)\n      lines.push(line)\n\n      // Move past line terminator\n      searchIndex = lineEnd + 1\n      if (chunk[searchIndex - 1] === '\\r' && chunk[searchIndex] === '\\n') {\n        searchIndex++\n      }\n    }\n  }\n\n  return [lines, incompleteLine]\n}\n", "import {createParser} from './parse.ts'\nimport type {EventSourceMessage, EventSourceParser} from './types.ts'\n\n/**\n * Options for the EventSourceParserStream.\n *\n * @public\n */\nexport interface StreamOptions {\n  /**\n   * Behavior when a parsing error occurs.\n   *\n   * - A custom function can be provided to handle the error.\n   * - `'terminate'` will error the stream and stop parsing.\n   * - Any other value will ignore the error and continue parsing.\n   *\n   * @defaultValue `undefined`\n   */\n  onError?: ('terminate' | ((error: Error) => void)) | undefined\n\n  /**\n   * Callback for when a reconnection interval is sent from the server.\n   *\n   * @param retry - The number of milliseconds to wait before reconnecting.\n   */\n  onRetry?: ((retry: number) => void) | undefined\n\n  /**\n   * Callback for when a comment is encountered in the stream.\n   *\n   * @param comment - The comment encountered in the stream.\n   */\n  onComment?: ((comment: string) => void) | undefined\n}\n\n/**\n * A TransformStream that ingests a stream of strings and produces a stream of `EventSourceMessage`.\n *\n * @example Basic usage\n * ```\n * const eventStream =\n *   response.body\n *     .pipeThrough(new TextDecoderStream())\n *     .pipeThrough(new EventSourceParserStream())\n * ```\n *\n * @example Terminate stream on parsing errors\n * ```\n * const eventStream =\n *  response.body\n *   .pipeThrough(new TextDecoderStream())\n *   .pipeThrough(new EventSourceParserStream({terminateOnError: true}))\n * ```\n *\n * @public\n */\nexport class EventSourceParserStream extends TransformStream<string, EventSourceMessage> {\n  constructor({onError, onRetry, onComment}: StreamOptions = {}) {\n    let parser!: EventSourceParser\n\n    super({\n      start(controller) {\n        parser = createParser({\n          onEvent: (event) => {\n            controller.enqueue(event)\n          },\n          onError(error) {\n            if (onError === 'terminate') {\n              controller.error(error)\n            } else if (typeof onError === 'function') {\n              onError(error)\n            }\n\n            // Ignore by default\n          },\n          onRetry,\n          onComment,\n        })\n      },\n      transform(chunk) {\n        parser.feed(chunk)\n      },\n    })\n  }\n}\n\nexport {type ErrorType, ParseError} from './errors.ts'\nexport type {EventSourceMessage} from './types.ts'\n", "import { z } from 'zod/v4';\nimport { isDefinedOrNotNull } from '../utils/type-guards';\nimport { ReasoningFormat } from './format';\n\nexport enum ReasoningDetailType {\n  Summary = 'reasoning.summary',\n  Encrypted = 'reasoning.encrypted',\n  Text = 'reasoning.text',\n}\n\nexport const CommonReasoningDetailSchema = z\n  .object({\n    id: z.string().nullish(),\n    format: z.enum(ReasoningFormat).nullish(),\n    index: z.number().optional(),\n  })\n  .loose();\n\nexport const ReasoningDetailSummarySchema = z\n  .object({\n    type: z.literal(ReasoningDetailType.Summary),\n    summary: z.string(),\n  })\n  .extend(CommonReasoningDetailSchema.shape);\nexport type ReasoningDetailSummary = z.infer<\n  typeof ReasoningDetailSummarySchema\n>;\n\nexport const ReasoningDetailEncryptedSchema = z\n  .object({\n    type: z.literal(ReasoningDetailType.Encrypted),\n    data: z.string(),\n  })\n  .extend(CommonReasoningDetailSchema.shape);\n\nexport type ReasoningDetailEncrypted = z.infer<\n  typeof ReasoningDetailEncryptedSchema\n>;\n\nexport const ReasoningDetailTextSchema = z\n  .object({\n    type: z.literal(ReasoningDetailType.Text),\n    text: z.string().nullish(),\n    signature: z.string().nullish(),\n  })\n  .extend(CommonReasoningDetailSchema.shape);\n\nexport type ReasoningDetailText = z.infer<typeof ReasoningDetailTextSchema>;\n\nexport const ReasoningDetailUnionSchema = z.union([\n  ReasoningDetailSummarySchema,\n  ReasoningDetailEncryptedSchema,\n  ReasoningDetailTextSchema,\n]);\n\nexport type ReasoningDetailUnion = z.infer<typeof ReasoningDetailUnionSchema>;\n\nconst ReasoningDetailsWithUnknownSchema = z.union([\n  ReasoningDetailUnionSchema,\n  z.unknown().transform(() => null),\n]);\n\nexport const ReasoningDetailArraySchema = z\n  .array(ReasoningDetailsWithUnknownSchema)\n  .transform((d) => d.filter((d): d is ReasoningDetailUnion => !!d));\n\nexport const OutputUnionToReasoningDetailsSchema = z.union([\n  z\n    .object({\n      delta: z.object({\n        reasoning_details: z.array(ReasoningDetailsWithUnknownSchema),\n      }),\n    })\n    .transform((data) =>\n      data.delta.reasoning_details.filter(isDefinedOrNotNull),\n    ),\n  z\n    .object({\n      message: z.object({\n        reasoning_details: z.array(ReasoningDetailsWithUnknownSchema),\n      }),\n    })\n    .transform((data) =>\n      data.message.reasoning_details.filter(isDefinedOrNotNull),\n    ),\n  z\n    .object({\n      text: z.string(),\n      reasoning_details: z.array(ReasoningDetailsWithUnknownSchema),\n    })\n    .transform((data) => data.reasoning_details.filter(isDefinedOrNotNull)),\n]);\n", "/**\n * Type guard to check if a value is defined and not null\n */\nexport function isDefinedOrNotNull<T>(value: T | null | undefined): value is T {\n  return value !== null && value !== undefined;\n}\n", "export enum ReasoningFormat {\n  Unknown = 'unknown',\n  OpenAIResponsesV1 = 'openai-responses-v1',\n  AzureOpenAIResponsesV1 = 'azure-openai-responses-v1',\n  XAIResponsesV1 = 'xai-responses-v1',\n  AnthropicClaudeV1 = 'anthropic-claude-v1',\n  GoogleGeminiV1 = 'google-gemini-v1',\n}\n\n// Anthropic Claude was the first reasoning that we're\n// passing back and forth\nexport const DEFAULT_REASONING_FORMAT = ReasoningFormat.AnthropicClaudeV1;\n", "import type { ChatErrorError } from '../types/openrouter-api-types';\n\nimport { createJsonErrorResponseHandler } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const OpenRouterErrorResponseSchema = z\n  .object({\n    error: z\n      .object({\n        code: z\n          .union([z.string(), z.number()])\n          .nullable()\n          .optional()\n          .default(null),\n        message: z.string(),\n        type: z.string().nullable().optional().default(null),\n        param: z.any().nullable().optional().default(null),\n      })\n      .passthrough() satisfies z.ZodType<\n      Omit<ChatErrorError, 'code'> & { code: string | number | null }\n    >,\n  })\n  .passthrough();\n\nexport type OpenRouterErrorData = z.infer<typeof OpenRouterErrorResponseSchema>;\n\n/**\n * Extract a human-readable error message from the error response.\n * The top-level `error.message` is often generic (e.g. \"Provider returned error\"),\n * while `error.metadata.raw` contains the actual upstream provider error details.\n */\nexport function extractErrorMessage(data: OpenRouterErrorData): string {\n  const error = data.error as Record<string, unknown>;\n  const metadata = error.metadata as Record<string, unknown> | undefined;\n\n  if (!metadata) {\n    return data.error.message;\n  }\n\n  const parts: string[] = [];\n\n  // Include the provider name for context when available\n  if (typeof metadata.provider_name === 'string' && metadata.provider_name) {\n    parts.push(`[${metadata.provider_name}]`);\n  }\n\n  // Extract meaningful message from the raw upstream error\n  const raw = metadata.raw;\n  const rawMessage = extractRawMessage(raw);\n\n  if (rawMessage && rawMessage !== data.error.message) {\n    parts.push(rawMessage);\n  } else {\n    parts.push(data.error.message);\n  }\n\n  return parts.join(' ');\n}\n\n/**\n * Recursively extract a message string from the raw upstream error.\n * The raw field can be a string, a JSON string, or a nested object.\n */\nfunction extractRawMessage(raw: unknown): string | undefined {\n  if (typeof raw === 'string') {\n    // Try parsing as JSON in case it's a stringified error object\n    try {\n      const parsed: unknown = JSON.parse(raw);\n      if (typeof parsed === 'object' && parsed !== null) {\n        return extractRawMessage(parsed);\n      }\n      return raw;\n    } catch {\n      return raw;\n    }\n  }\n\n  if (typeof raw !== 'object' || raw === null) {\n    return undefined;\n  }\n\n  const obj = raw as Record<string, unknown>;\n\n  // Check common error message fields\n  for (const field of ['message', 'error', 'detail', 'details', 'msg']) {\n    const value = obj[field];\n    if (typeof value === 'string' && value.length > 0) {\n      return value;\n    }\n    // Handle nested error objects (e.g. { error: { message: \"...\" } })\n    if (typeof value === 'object' && value !== null) {\n      const nested = extractRawMessage(value);\n      if (nested) {\n        return nested;\n      }\n    }\n  }\n\n  return undefined;\n}\n\nexport const openrouterFailedResponseHandler = createJsonErrorResponseHandler({\n  errorSchema: OpenRouterErrorResponseSchema,\n  errorToMessage: extractErrorMessage,\n});\n", "import { z } from 'zod/v4';\nimport {\n  ReasoningDetailArraySchema,\n  ReasoningDetailUnionSchema,\n} from './reasoning-details';\n\n/**\n * Schema for file annotations from FileParserPlugin\n */\nexport const FileAnnotationSchema = z\n  .object({\n    type: z.literal('file'),\n    file: z\n      .object({\n        hash: z.string(),\n        name: z.string(),\n        content: z\n          .array(\n            z\n              .object({\n                type: z.string(),\n                text: z.string().optional(),\n              })\n              .catchall(z.any()),\n          )\n          .optional(),\n      })\n      .catchall(z.any()),\n  })\n  .catchall(z.any());\n\nexport type FileAnnotation = z.infer<typeof FileAnnotationSchema>;\n\n/**\n * Schema for OpenRouter provider metadata attached to responses\n */\nexport const OpenRouterProviderMetadataSchema = z\n  .object({\n    provider: z.string(),\n    reasoning_details: z.array(ReasoningDetailUnionSchema).optional(),\n    annotations: z.array(FileAnnotationSchema).optional(),\n    usage: z\n      .object({\n        promptTokens: z.number(),\n        promptTokensDetails: z\n          .object({\n            cachedTokens: z.number(),\n          })\n          .catchall(z.any())\n          .optional(),\n        completionTokens: z.number(),\n        completionTokensDetails: z\n          .object({\n            reasoningTokens: z.number(),\n          })\n          .catchall(z.any())\n          .optional(),\n        totalTokens: z.number(),\n        cost: z.number().optional(),\n        costDetails: z\n          .object({\n            upstreamInferenceCost: z.number(),\n          })\n          .catchall(z.any())\n          .optional(),\n      })\n      .catchall(z.any()),\n  })\n  .catchall(z.any());\n\nexport type OpenRouterProviderMetadata = z.infer<\n  typeof OpenRouterProviderMetadataSchema\n>;\n\n/**\n * Schema for parsing provider options that may contain reasoning_details and annotations\n */\nexport const OpenRouterProviderOptionsSchema = z\n  .object({\n    openrouter: z\n      .object({\n        // Use ReasoningDetailArraySchema (with unknown fallback) instead of\n        // z.array(ReasoningDetailUnionSchema) so that a single malformed entry\n        // (e.g., a future format not yet in the enum) is individually dropped\n        // rather than causing the entire array to fail parsing.\n        reasoning_details: ReasoningDetailArraySchema.optional(),\n        annotations: z.array(FileAnnotationSchema).optional(),\n      })\n      .optional(),\n  })\n  .optional();\n", "import type { JSONObject, LanguageModelV3Usage } from '@ai-sdk/provider';\n\ninterface UsageData {\n  prompt_tokens?: number | null;\n  completion_tokens?: number | null;\n  prompt_tokens_details?: {\n    cached_tokens?: number;\n    cache_write_tokens?: number | null;\n  } | null;\n  completion_tokens_details?: {\n    reasoning_tokens?: number;\n  } | null;\n}\n\nexport function computeTokenUsage(usage: UsageData): LanguageModelV3Usage {\n  const promptTokens = usage.prompt_tokens ?? 0;\n  const completionTokens = usage.completion_tokens ?? 0;\n  const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;\n  const cacheWriteTokens =\n    usage.prompt_tokens_details?.cache_write_tokens ?? undefined;\n  const reasoningTokens =\n    usage.completion_tokens_details?.reasoning_tokens ?? 0;\n\n  return {\n    inputTokens: {\n      total: promptTokens,\n      noCache: promptTokens - cacheReadTokens,\n      cacheRead: cacheReadTokens,\n      cacheWrite: cacheWriteTokens,\n    },\n    outputTokens: {\n      total: completionTokens,\n      text: completionTokens - reasoningTokens,\n      reasoning: reasoningTokens,\n    },\n    raw: usage as JSONObject,\n  };\n}\n\nexport function emptyUsage(): LanguageModelV3Usage {\n  return {\n    inputTokens: {\n      total: 0,\n      noCache: undefined,\n      cacheRead: undefined,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: 0,\n      text: undefined,\n      reasoning: undefined,\n    },\n    raw: undefined,\n  };\n}\n", "import type { LanguageModelV3FinishReason } from '@ai-sdk/provider';\n\ntype UnifiedFinishReason =\n  | 'stop'\n  | 'length'\n  | 'content-filter'\n  | 'tool-calls'\n  | 'error'\n  | 'other';\n\nfunction mapToUnified(\n  finishReason: string | null | undefined,\n): UnifiedFinishReason {\n  switch (finishReason) {\n    case 'stop':\n      return 'stop';\n    case 'length':\n      return 'length';\n    case 'content_filter':\n      return 'content-filter';\n    case 'function_call':\n    case 'tool_calls':\n      return 'tool-calls';\n    default:\n      return 'other';\n  }\n}\n\nexport function mapOpenRouterFinishReason(\n  finishReason: string | null | undefined,\n): LanguageModelV3FinishReason {\n  return {\n    unified: mapToUnified(finishReason),\n    raw: finishReason ?? undefined,\n  };\n}\n\nexport function createFinishReason(\n  unified: UnifiedFinishReason,\n  raw?: string,\n): LanguageModelV3FinishReason {\n  return { unified, raw };\n}\n", "export function withStreamErrorHandling<T>(\n  source: ReadableStream<T>,\n  onError: (error: unknown) => void,\n): ReadableStream<T> {\n  const reader = source.getReader();\n  return new ReadableStream<T>({\n    async pull(controller) {\n      try {\n        const { done, value } = await reader.read();\n        if (done) {\n          controller.close();\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (err) {\n        onError(err);\n        reader.cancel().catch(() => {});\n        controller.close();\n      }\n    },\n    cancel(reason) {\n      reader.cancel(reason);\n    },\n  });\n}\n", "/**\n * Serializes a value to JSON with object keys sorted alphabetically at every\n * nesting level. This produces deterministic output regardless of the\n * insertion order of object keys, which is important for prompt caching —\n * the cache key includes serialized tool call arguments verbatim, so\n * different key orderings for semantically identical objects would cause\n * cache misses.\n *\n * Arrays preserve element order. Primitives and null pass through unchanged.\n */\nexport function deterministicStringify(value: unknown): string {\n  return JSON.stringify(sortKeys(value));\n}\n\nfunction sortKeys(value: unknown): unknown {\n  if (value === null || value === undefined) {\n    return value;\n  }\n\n  if (Array.isArray(value)) {\n    return value.map(sortKeys);\n  }\n\n  if (typeof value === 'object') {\n    const sorted: Record<string, unknown> = {};\n    const entries = Object.entries(value);\n    entries.sort(([a], [b]) => a.localeCompare(b));\n    for (const [key, val] of entries) {\n      sorted[key] = sortKeys(val);\n    }\n    return sorted;\n  }\n\n  return value;\n}\n", "import type { ReasoningDetailUnion } from '../schemas/reasoning-details';\n\nimport { ReasoningDetailType } from '../schemas/reasoning-details';\n\n/**\n * Tracks ReasoningDetailUnion entries and deduplicates them based\n * on a derived canonical key.\n *\n * This is used when converting messages to ensure the API request only\n * contains unique reasoning details, preventing \"Duplicate item found with id\"\n * errors in multi-turn conversations.\n *\n * The canonical key logic matches the OpenRouter API's deduplication exactly\n * (see openrouter-web/packages/llm-interfaces/reasonings/duplicate-tracker.ts):\n * - Summary: key = summary field\n * - Encrypted: key = id field (if truthy) or data field\n * - Text: key = text field (if truthy) or signature field (if truthy)\n */\nexport class ReasoningDetailsDuplicateTracker {\n  readonly #seenKeys = new Set<string>();\n\n  /**\n   * Attempts to track a detail.\n   * Returns true if this is a NEW detail (not seen before and has valid key),\n   * false if it was skipped (no valid key) or already seen (duplicate).\n   */\n  upsert(detail: ReasoningDetailUnion): boolean {\n    const key = this.getCanonicalKey(detail);\n    if (key === null) {\n      return false;\n    }\n\n    if (this.#seenKeys.has(key)) {\n      return false;\n    }\n\n    this.#seenKeys.add(key);\n    return true;\n  }\n\n  private getCanonicalKey(detail: ReasoningDetailUnion): string | null {\n    // This logic matches the OpenRouter API's deduplication exactly.\n    // See: openrouter-web/packages/llm-interfaces/reasonings/duplicate-tracker.ts\n    switch (detail.type) {\n      case ReasoningDetailType.Summary:\n        return detail.summary;\n\n      case ReasoningDetailType.Encrypted:\n        if (detail.id) {\n          return detail.id;\n        }\n        return detail.data;\n\n      case ReasoningDetailType.Text: {\n        if (detail.text) {\n          return detail.text;\n        }\n        if (detail.signature) {\n          return detail.signature;\n        }\n        return null;\n      }\n\n      default: {\n        // Handle unknown types gracefully\n        return null;\n      }\n    }\n  }\n}\n", "import type { FileAnnotation } from '@/src/schemas/provider-metadata';\nimport type { ReasoningDetailUnion } from '@/src/schemas/reasoning-details';\n\n// Type for OpenRouter Cache Control following Anthropic's pattern\nexport type OpenRouterCacheControl = { type: 'ephemeral' };\n\nexport type OpenRouterChatCompletionsInput = Array<ChatCompletionMessageParam>;\n\nexport type ChatCompletionMessageParam =\n  | ChatCompletionSystemMessageParam\n  | ChatCompletionUserMessageParam\n  | ChatCompletionAssistantMessageParam\n  | ChatCompletionToolMessageParam;\n\nexport interface ChatCompletionSystemMessageParam {\n  role: 'system';\n  content: Array<ChatCompletionContentPartText>;\n}\n\nexport interface ChatCompletionUserMessageParam {\n  role: 'user';\n  content: string | Array<ChatCompletionContentPart>;\n  cache_control?: OpenRouterCacheControl;\n}\n\nexport type ChatCompletionContentPart =\n  | ChatCompletionContentPartText\n  | ChatCompletionContentPartImage\n  | ChatCompletionContentPartFile\n  | ChatCompletionContentPartInputAudio\n  | ChatCompletionContentPartVideo;\n\nexport interface ChatCompletionContentPartFile {\n  type: 'file';\n  file: {\n    filename?: string;\n    file_data?: string;\n    file_id?: string;\n  };\n  cache_control?: OpenRouterCacheControl;\n}\n\nexport interface ChatCompletionContentPartImage {\n  type: 'image_url';\n  image_url: {\n    url: string;\n  };\n  cache_control?: OpenRouterCacheControl;\n}\n\nexport interface ChatCompletionContentPartText {\n  type: 'text';\n  text: string;\n  reasoning?: string | null;\n  cache_control?: OpenRouterCacheControl;\n}\n\n/** https://openrouter.ai/docs/guides/overview/multimodal/videos */\nexport interface ChatCompletionContentPartVideo {\n  type: 'video_url';\n  video_url: {\n    url: string;\n  };\n  cache_control?: OpenRouterCacheControl;\n}\n\n/** https://openrouter.ai/docs/guides/overview/multimodal/audio */\nexport const OPENROUTER_AUDIO_FORMATS = [\n  'wav',\n  'mp3',\n  'aiff',\n  'aac',\n  'ogg',\n  'flac',\n  'm4a',\n  'pcm16',\n  'pcm24',\n] as const;\n\nexport type OpenRouterAudioFormat = (typeof OPENROUTER_AUDIO_FORMATS)[number];\n\nexport interface ChatCompletionContentPartInputAudio {\n  type: 'input_audio';\n  input_audio: {\n    data: string;\n    format: OpenRouterAudioFormat;\n  };\n  cache_control?: OpenRouterCacheControl;\n}\n\nexport interface ChatCompletionAssistantMessageParam {\n  role: 'assistant';\n  content?: string | null;\n  reasoning?: string | null;\n  reasoning_details?: ReasoningDetailUnion[];\n  annotations?: FileAnnotation[];\n  tool_calls?: Array<ChatCompletionMessageToolCall>;\n  cache_control?: OpenRouterCacheControl;\n}\n\nexport interface ChatCompletionMessageToolCall {\n  type: 'function';\n  id: string;\n  function: {\n    arguments: string;\n    name: string;\n  };\n}\n\nexport interface ChatCompletionToolMessageParam {\n  role: 'tool';\n  content: string | Array<ChatCompletionContentPart>;\n  tool_call_id: string;\n  name?: string;\n  cache_control?: OpenRouterCacheControl;\n}\n", "export function isUrl({\n  url,\n  protocols,\n}: {\n  url: string | URL;\n  protocols: Set<`${string}:`>;\n}): boolean {\n  try {\n    const urlObj = new URL(url);\n    // Cast to the literal string due to Set inferred input type\n    return protocols.has(urlObj.protocol as `${string}:`);\n  } catch (_) {\n    return false;\n  }\n}\n", "import type { LanguageModelV3FilePart } from '@ai-sdk/provider';\nimport type { OpenRouterAudioFormat } from '../types/openrouter-chat-completions-input';\n\nimport { convertUint8ArrayToBase64 } from '@ai-sdk/provider-utils';\nimport { OPENROUTER_AUDIO_FORMATS } from '../types/openrouter-chat-completions-input';\nimport { isUrl } from './is-url';\n\nexport function buildFileDataUrl({\n  data,\n  mediaType,\n  defaultMediaType,\n}: {\n  data: string | Uint8Array;\n  mediaType?: string;\n  defaultMediaType: string;\n}): string {\n  if (data instanceof Uint8Array) {\n    const base64 = convertUint8ArrayToBase64(data);\n    return `data:${mediaType ?? defaultMediaType};base64,${base64}`;\n  }\n\n  const stringData = data.toString();\n\n  if (\n    isUrl({\n      url: stringData,\n      protocols: new Set(['http:', 'https:'] as const),\n    })\n  ) {\n    return stringData;\n  }\n\n  return stringData.startsWith('data:')\n    ? stringData\n    : `data:${mediaType ?? defaultMediaType};base64,${stringData}`;\n}\n\nexport function getFileUrl({\n  part,\n  defaultMediaType,\n}: {\n  part: LanguageModelV3FilePart;\n  defaultMediaType: string;\n}) {\n  const data = part.data instanceof URL ? part.data.toString() : part.data;\n  return buildFileDataUrl({\n    data,\n    mediaType: part.mediaType,\n    defaultMediaType,\n  });\n}\n\nexport function getMediaType(\n  dataUrl: string,\n  defaultMediaType: string,\n): string {\n  const match = dataUrl.match(/^data:([^;]+)/);\n  return match ? (match[1] ?? defaultMediaType) : defaultMediaType;\n}\n\nexport function getBase64FromDataUrl(dataUrl: string): string {\n  const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);\n  return match ? match[1]! : dataUrl;\n}\n\n/** MIME type to format mapping for normalization */\nexport const MIME_TO_FORMAT: Record<string, OpenRouterAudioFormat> = {\n  // MP3 variants\n  mpeg: 'mp3',\n  mp3: 'mp3',\n  // WAV variants\n  'x-wav': 'wav',\n  wave: 'wav',\n  wav: 'wav',\n  // OGG variants\n  ogg: 'ogg',\n  vorbis: 'ogg',\n  // AAC variants\n  aac: 'aac',\n  'x-aac': 'aac',\n  // M4A variants\n  m4a: 'm4a',\n  'x-m4a': 'm4a',\n  mp4: 'm4a',\n  // AIFF variants\n  aiff: 'aiff',\n  'x-aiff': 'aiff',\n  // FLAC\n  flac: 'flac',\n  'x-flac': 'flac',\n  // PCM variants\n  pcm16: 'pcm16',\n  pcm24: 'pcm24',\n};\n\n/**\n * Converts an audio file part to OpenRouter's input_audio data format.\n *\n * This function extracts base64-encoded audio data from a file part and\n * normalizes the format to one of the supported OpenRouter audio formats.\n *\n * @param part - The file part containing audio data. Must have a mediaType\n *   starting with \"audio/\" and contain either base64 data or a data URL.\n *\n * @returns An object with `data` (base64-encoded audio) and `format`\n *   suitable for use in OpenRouter's `input_audio` field.\n *\n * @throws {Error} When audio is provided as an HTTP/HTTPS URL. OpenRouter requires\n *   audio to be base64-encoded inline. The error message includes instructions for\n *   downloading and encoding the audio locally.\n *\n * @throws {Error} When the audio format is not supported.\n *\n * @example\n * ```ts\n * const audioData = getInputAudioData(filePart);\n * // Returns: { data: \"base64string...\", format: \"mp3\" }\n * ```\n */\nexport function getInputAudioData(part: LanguageModelV3FilePart): {\n  data: string;\n  format: OpenRouterAudioFormat;\n} {\n  const fileData = getFileUrl({\n    part,\n    defaultMediaType: 'audio/mpeg',\n  });\n\n  // OpenRouter's input_audio doesn't support URLs directly\n  if (\n    isUrl({\n      url: fileData,\n      protocols: new Set(['http:', 'https:'] as const),\n    })\n  ) {\n    throw new Error(\n      `Audio files cannot be provided as URLs.\\n\\n` +\n        `OpenRouter requires audio to be base64-encoded. Please:\\n` +\n        `1. Download the audio file locally\\n` +\n        `2. Read it as a Buffer or Uint8Array\\n` +\n        `3. Pass it as the data parameter\\n\\n` +\n        `The AI SDK will automatically handle base64 encoding.\\n\\n` +\n        `Learn more: https://openrouter.ai/docs/features/multimodal/audio`,\n    );\n  }\n\n  // Extract base64 data (handles both data URLs and raw base64)\n  const data = getBase64FromDataUrl(fileData);\n\n  // Map media type to format\n  const mediaType = part.mediaType || 'audio/mpeg';\n  const rawFormat = mediaType.replace('audio/', '');\n\n  // Normalize format names for OpenRouter using MIME type mapping\n  const format = MIME_TO_FORMAT[rawFormat];\n\n  if (format === undefined) {\n    const supportedList = OPENROUTER_AUDIO_FORMATS.join(', ');\n    throw new Error(\n      `Unsupported audio format: \"${mediaType}\"\\n\\n` +\n        `OpenRouter supports the following audio formats: ${supportedList}\\n\\n` +\n        `Learn more: https://openrouter.ai/docs/features/multimodal/audio`,\n    );\n  }\n\n  return { data, format };\n}\n", "import type {\n  LanguageModelV3FilePart,\n  LanguageModelV3Prompt,\n  LanguageModelV3TextPart,\n  LanguageModelV3ToolResultOutput,\n  LanguageModelV3ToolResultPart,\n  SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type { ReasoningDetailUnion } from '../schemas/reasoning-details';\nimport type {\n  ChatCompletionContentPart,\n  OpenRouterChatCompletionsInput,\n} from '../types/openrouter-chat-completions-input';\n\nimport { DEFAULT_REASONING_FORMAT, ReasoningFormat } from '../schemas/format';\nimport { OpenRouterProviderOptionsSchema } from '../schemas/provider-metadata';\nimport { ReasoningDetailType } from '../schemas/reasoning-details';\nimport { deterministicStringify } from '../utils/deterministic-stringify';\nimport { ReasoningDetailsDuplicateTracker } from '../utils/reasoning-details-duplicate-tracker';\nimport {\n  buildFileDataUrl,\n  getBase64FromDataUrl,\n  getFileUrl,\n  getInputAudioData,\n  MIME_TO_FORMAT,\n} from './file-url-utils';\nimport { isUrl } from './is-url';\n\n// Type for OpenRouter Cache Control following Anthropic's pattern\nexport type OpenRouterCacheControl = { type: 'ephemeral' };\n\nfunction getCacheControl(\n  providerMetadata: SharedV3ProviderMetadata | undefined,\n): OpenRouterCacheControl | undefined {\n  const anthropic = providerMetadata?.anthropic;\n  const openrouter = providerMetadata?.openrouter;\n\n  // Allow both cacheControl and cache_control:\n  return (openrouter?.cacheControl ??\n    openrouter?.cache_control ??\n    anthropic?.cacheControl ??\n    anthropic?.cache_control) as OpenRouterCacheControl | undefined;\n}\n\nexport function convertToOpenRouterChatMessages(\n  prompt: LanguageModelV3Prompt,\n): OpenRouterChatCompletionsInput {\n  const messages: OpenRouterChatCompletionsInput = [];\n\n  // Track reasoning_details across all messages in this conversion to prevent duplicates.\n  // This fixes issue #254 where the same reasoning ID appears in multiple\n  // assistant messages during multi-turn conversations, causing the API\n  // to reject the request with \"Duplicate item found with id\" error.\n  const reasoningDetailsTracker = new ReasoningDetailsDuplicateTracker();\n\n  for (const { role, content, providerOptions } of prompt) {\n    switch (role) {\n      case 'system': {\n        const cacheControl = getCacheControl(providerOptions);\n        messages.push({\n          role: 'system',\n          content: [\n            {\n              type: 'text' as const,\n              text: content,\n              ...(cacheControl && { cache_control: cacheControl }),\n            },\n          ],\n        });\n        break;\n      }\n\n      case 'user': {\n        if (content.length === 1 && content[0]?.type === 'text') {\n          const cacheControl =\n            getCacheControl(providerOptions) ??\n            getCacheControl(content[0].providerOptions);\n          const contentWithCacheControl: string | ChatCompletionContentPart[] =\n            cacheControl\n              ? [\n                  {\n                    type: 'text',\n                    text: content[0].text,\n                    cache_control: cacheControl,\n                  },\n                ]\n              : content[0].text;\n          messages.push({\n            role: 'user',\n            content: contentWithCacheControl,\n          });\n          break;\n        }\n\n        // Get message level cache control\n        const messageCacheControl = getCacheControl(providerOptions);\n\n        // Find the index of the last text part for applying message-level cache control\n        let lastTextPartIndex = -1;\n        for (let i = content.length - 1; i >= 0; i--) {\n          if (content[i]?.type === 'text') {\n            lastTextPartIndex = i;\n            break;\n          }\n        }\n\n        const contentParts: ChatCompletionContentPart[] = content.map(\n          (part: LanguageModelV3TextPart | LanguageModelV3FilePart, index) => {\n            const isLastTextPart =\n              part.type === 'text' && index === lastTextPartIndex;\n            const partCacheControl = getCacheControl(part.providerOptions);\n\n            const cacheControl =\n              part.type === 'text'\n                ? (partCacheControl ??\n                  (isLastTextPart ? messageCacheControl : undefined))\n                : partCacheControl;\n\n            switch (part.type) {\n              case 'text':\n                return {\n                  type: 'text' as const,\n                  text: part.text,\n                  ...(cacheControl && { cache_control: cacheControl }),\n                };\n              case 'file': {\n                if (part.mediaType?.startsWith('image/')) {\n                  const url = getFileUrl({\n                    part,\n                    defaultMediaType: 'image/jpeg',\n                  });\n                  return {\n                    type: 'image_url' as const,\n                    image_url: {\n                      url,\n                    },\n                    ...(cacheControl && { cache_control: cacheControl }),\n                  };\n                }\n\n                // Handle video files for video_url format\n                if (part.mediaType?.startsWith('video/')) {\n                  const url = getFileUrl({\n                    part,\n                    defaultMediaType: 'video/mp4',\n                  });\n                  return {\n                    type: 'video_url' as const,\n                    video_url: {\n                      url,\n                    },\n                    ...(cacheControl && { cache_control: cacheControl }),\n                  };\n                }\n\n                // Handle audio files for input_audio format\n                if (part.mediaType?.startsWith('audio/')) {\n                  return {\n                    type: 'input_audio' as const,\n                    input_audio: getInputAudioData(part),\n                    ...(cacheControl && { cache_control: cacheControl }),\n                  };\n                }\n\n                const fileName = String(\n                  part.providerOptions?.openrouter?.filename ??\n                    part.filename ??\n                    '',\n                );\n\n                const fileData = getFileUrl({\n                  part,\n                  defaultMediaType: 'application/pdf',\n                });\n\n                if (\n                  isUrl({\n                    url: fileData,\n                    protocols: new Set(['http:', 'https:'] as const),\n                  })\n                ) {\n                  return {\n                    type: 'file' as const,\n                    file: {\n                      filename: fileName,\n                      file_data: fileData,\n                    },\n                  } satisfies ChatCompletionContentPart;\n                }\n\n                return {\n                  type: 'file' as const,\n                  file: {\n                    filename: fileName,\n                    file_data: fileData,\n                  },\n                  ...(cacheControl && { cache_control: cacheControl }),\n                } satisfies ChatCompletionContentPart;\n              }\n              default: {\n                return {\n                  type: 'text' as const,\n                  text: '',\n                  ...(cacheControl && { cache_control: cacheControl }),\n                };\n              }\n            }\n          },\n        );\n\n        // For multi-part messages, don't add cache_control at the root level\n        messages.push({\n          role: 'user',\n          content: contentParts,\n        });\n\n        break;\n      }\n\n      case 'assistant': {\n        let text = '';\n        let reasoning = '';\n        const toolCalls: Array<{\n          id: string;\n          type: 'function';\n          function: { name: string; arguments: string };\n        }> = [];\n\n        for (const part of content) {\n          switch (part.type) {\n            case 'text': {\n              text += part.text;\n              break;\n            }\n            case 'tool-call': {\n              toolCalls.push({\n                id: part.toolCallId,\n                type: 'function',\n                function: {\n                  name: part.toolName,\n                  arguments: deterministicStringify(part.input),\n                },\n              });\n              break;\n            }\n            case 'reasoning': {\n              reasoning += part.text;\n              break;\n            }\n            case 'file':\n              break;\n            default: {\n              break;\n            }\n          }\n        }\n\n        // Check message-level providerOptions for preserved reasoning_details and annotations\n        const parsedProviderOptions =\n          OpenRouterProviderOptionsSchema.safeParse(providerOptions);\n        const messageReasoningDetails = parsedProviderOptions.success\n          ? parsedProviderOptions.data?.openrouter?.reasoning_details\n          : undefined;\n        const messageAnnotations = parsedProviderOptions.success\n          ? parsedProviderOptions.data?.openrouter?.annotations\n          : undefined;\n\n        // Use message-level reasoning_details if available, otherwise find from parts\n        // Priority: message-level > first tool call > first reasoning part\n        // This prevents duplicate thinking blocks when Claude makes parallel tool calls\n        //\n        // NOTE: treat an empty array as a meaningful signal — some providers (e.g.\n        // DeepSeek V4) return `reasoning_details: []` on turns where they produced no\n        // visible reasoning tokens, and they expect to receive that empty array back in\n        // subsequent turns to maintain the conversation state.  Falling back to\n        // `findFirstReasoningDetails` when the array exists-but-is-empty would silently\n        // drop this signal and cause those providers to error on follow-up requests.\n        const candidateReasoningDetails =\n          messageReasoningDetails && Array.isArray(messageReasoningDetails)\n            ? messageReasoningDetails\n            : findFirstReasoningDetails(content);\n\n        // Strip reasoning.text entries that would cause signature errors\n        // when sent back to the upstream provider.\n        //\n        // Anthropic (issue #423): Uses an explicit `signature` field on\n        // reasoning.text entries. When the signature is lost during message\n        // serialization, custom pruning, or DB storage, sending the entry\n        // back causes \"Invalid signature in thinking block\".\n        //\n        // Google Gemini (issue #418): Does NOT use the SDK `signature`\n        // field, but Google internally signs thought tokens. When\n        // reasoning text is modified during roundtripping (serialization,\n        // encoding changes, field reordering), Google rejects with\n        // \"Corrupted thought signature\". Since the SDK cannot verify\n        // whether the text is intact, Gemini reasoning.text entries are\n        // always stripped on roundtrip — the encrypted reasoning blob\n        // (reasoning.encrypted) handles multi-turn continuity instead.\n        //\n        // Other formats (OpenAI, xAI, Azure) and non-text detail types\n        // pass through unchanged.\n        //\n        // This runs BEFORE deduplication so that signatureless entries are\n        // never registered in the tracker — otherwise a signatureless entry\n        // in an earlier turn would suppress a valid signed copy in a later turn.\n        let finalReasoningDetails: ReasoningDetailUnion[] | undefined;\n        if (candidateReasoningDetails) {\n          const validDetails = candidateReasoningDetails.filter((detail) => {\n            if (detail.type !== ReasoningDetailType.Text) {\n              return true;\n            }\n            const format = detail.format ?? DEFAULT_REASONING_FORMAT;\n            if (\n              format !== ReasoningFormat.AnthropicClaudeV1 &&\n              format !== ReasoningFormat.GoogleGeminiV1\n            ) {\n              return true;\n            }\n            return !!detail.signature;\n          });\n\n          if (validDetails.length < candidateReasoningDetails.length) {\n            // Respect the AI SDK's warning suppression system.\n            // When false, warnings are fully suppressed.\n            // When a function, the app has a custom handler — suppress\n            // console output since our plain-text warning doesn't match\n            // the structured format the handler expects.\n            const logger = globalThis.AI_SDK_LOG_WARNINGS;\n            if (logger !== false && typeof logger !== 'function') {\n              // biome-ignore lint/suspicious/noConsole: intentional warning for stripped reasoning data\n              console.warn(\n                '[openrouter] Some reasoning_details entries were removed because they were missing signatures. See https://github.com/OpenRouterTeam/ai-sdk-provider/issues/423 and https://github.com/OpenRouterTeam/ai-sdk-provider/issues/418 for more details.',\n              );\n            }\n          }\n\n          // Deduplicate reasoning_details across all messages to prevent\n          // \"Duplicate item found with id\" errors in multi-turn conversations.\n          // upsert() returns true only for NEW details (not seen before and has valid key).\n          // Details without valid keys or duplicates are skipped.\n          const uniqueDetails: ReasoningDetailUnion[] = [];\n          for (const detail of validDetails) {\n            if (reasoningDetailsTracker.upsert(detail)) {\n              uniqueDetails.push(detail);\n            }\n          }\n          // Preserve the empty-array signal: when candidateReasoningDetails existed but\n          // all entries were duplicate or signature-stripped, still emit [] so downstream\n          // providers that require the field (e.g. DeepSeek) receive it.\n          finalReasoningDetails = uniqueDetails;\n        }\n\n        // Only include reasoning text if we have valid, non-empty reasoning_details.\n        // When providerMetadata is lost during message serialization or\n        // custom pruning (e.g., stripping providerOptions from reasoning\n        // parts), or when switching between models mid-conversation,\n        // reasoning text may exist without corresponding reasoning_details.\n        // Sending reasoning without reasoning_details causes the API to\n        // construct thinking blocks without valid signatures, which\n        // Anthropic rejects with \"Invalid signature in thinking block\"\n        // (issue #423).\n        //\n        // Note: an empty finalReasoningDetails ([]) means the provider explicitly\n        // returned no reasoning tokens this turn — do not send reasoning text in\n        // that case either.\n        const effectiveReasoning =\n          reasoning && finalReasoningDetails && finalReasoningDetails.length > 0\n            ? reasoning\n            : undefined;\n\n        messages.push({\n          role: 'assistant',\n          content: text,\n          tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n          reasoning: effectiveReasoning,\n          reasoning_details: finalReasoningDetails,\n          annotations: messageAnnotations,\n          cache_control: getCacheControl(providerOptions),\n        });\n\n        break;\n      }\n\n      case 'tool': {\n        for (const toolResponse of content) {\n          // Skip tool approval responses - only process tool results\n          if (toolResponse.type === 'tool-approval-response') {\n            continue;\n          }\n          const content = getToolResultContent(toolResponse);\n\n          messages.push({\n            role: 'tool',\n            tool_call_id: toolResponse.toolCallId,\n            content,\n            name: toolResponse.toolName,\n            cache_control:\n              getCacheControl(providerOptions) ??\n              getCacheControl(toolResponse.providerOptions),\n          });\n        }\n        break;\n      }\n\n      default: {\n        break;\n      }\n    }\n  }\n\n  return messages;\n}\n\nfunction getToolResultContent(\n  input: LanguageModelV3ToolResultPart,\n): string | ChatCompletionContentPart[] {\n  switch (input.output.type) {\n    case 'text':\n    case 'error-text':\n      return input.output.value;\n    case 'json':\n    case 'error-json':\n      return JSON.stringify(input.output.value);\n    case 'content':\n      return mapToolResultContentParts(input.output.value);\n    case 'execution-denied':\n      return input.output.reason ?? 'Tool execution denied';\n  }\n}\n\ntype ToolResultContentPart = Extract<\n  LanguageModelV3ToolResultOutput,\n  { type: 'content' }\n>['value'][number];\n\nfunction mapToolResultContentParts(\n  parts: ReadonlyArray<ToolResultContentPart>,\n): ChatCompletionContentPart[] {\n  return parts.map((part): ChatCompletionContentPart => {\n    switch (part.type) {\n      case 'text':\n        return { type: 'text', text: part.text };\n\n      case 'image-data':\n        return {\n          type: 'image_url',\n          image_url: {\n            url: buildFileDataUrl({\n              data: part.data,\n              mediaType: part.mediaType,\n              defaultMediaType: 'image/jpeg',\n            }),\n          },\n        };\n\n      case 'image-url':\n        return {\n          type: 'image_url',\n          image_url: { url: part.url },\n        };\n\n      case 'file-data': {\n        const dataUrl = buildFileDataUrl({\n          data: part.data,\n          mediaType: part.mediaType,\n          defaultMediaType: 'application/octet-stream',\n        });\n\n        if (part.mediaType?.startsWith('image/')) {\n          return {\n            type: 'image_url',\n            image_url: { url: dataUrl },\n          };\n        }\n\n        if (part.mediaType?.startsWith('video/')) {\n          return {\n            type: 'video_url',\n            video_url: { url: dataUrl },\n          };\n        }\n\n        if (part.mediaType?.startsWith('audio/')) {\n          const rawFormat = part.mediaType.replace('audio/', '');\n          const format = MIME_TO_FORMAT[rawFormat];\n          if (format !== undefined) {\n            return {\n              type: 'input_audio',\n              input_audio: {\n                data: getBase64FromDataUrl(dataUrl),\n                format,\n              },\n            };\n          }\n        }\n\n        return {\n          type: 'file',\n          file: {\n            filename: part.filename ?? '',\n            file_data: dataUrl,\n          },\n        };\n      }\n\n      case 'file-url': {\n        // file-url parts don't carry a mediaType field in the SDK,\n        // so we infer from the URL path extension to route correctly.\n        if (looksLikeImageUrl(part.url)) {\n          return {\n            type: 'image_url',\n            image_url: { url: part.url },\n          };\n        }\n\n        return {\n          type: 'file',\n          file: {\n            filename: filenameFromUrl(part.url),\n            file_data: part.url,\n          },\n        };\n      }\n\n      case 'file-id':\n      case 'image-file-id':\n      case 'custom':\n        return { type: 'text', text: JSON.stringify(part) };\n\n      default: {\n        const _exhaustiveCheck: never = part;\n        return { type: 'text', text: JSON.stringify(_exhaustiveCheck) };\n      }\n    }\n  });\n}\n\nconst IMAGE_EXTENSIONS = new Set([\n  'jpg',\n  'jpeg',\n  'png',\n  'gif',\n  'webp',\n  'svg',\n  'bmp',\n  'ico',\n  'tif',\n  'tiff',\n  'avif',\n]);\n\nfunction looksLikeImageUrl(url: string): boolean {\n  try {\n    const pathname = new URL(url).pathname;\n    const ext = pathname.split('.').pop()?.toLowerCase();\n    return ext !== undefined && IMAGE_EXTENSIONS.has(ext);\n  } catch {\n    return false;\n  }\n}\n\nfunction filenameFromUrl(url: string): string {\n  try {\n    const pathname = new URL(url).pathname;\n    const last = pathname.split('/').pop();\n    return last?.includes('.') ? last : '';\n  } catch {\n    return '';\n  }\n}\n\n/**\n * Find the first reasoning_details from content parts.\n * Priority: tool calls (complete accumulated data) > reasoning parts (delta data)\n *\n * This prevents duplicate thinking blocks when Claude makes parallel tool calls,\n * as each tool call may have the same reasoning_details attached.\n */\nfunction findFirstReasoningDetails(\n  content: Array<{\n    type: string;\n    providerOptions?: Record<string, unknown>;\n  }>,\n): ReasoningDetailUnion[] | undefined {\n  // First, try tool calls - they have complete accumulated reasoning_details\n  for (const part of content) {\n    if (part.type === 'tool-call') {\n      const parsed = OpenRouterProviderOptionsSchema.safeParse(\n        part.providerOptions,\n      );\n      if (\n        parsed.success &&\n        parsed.data?.openrouter?.reasoning_details &&\n        parsed.data.openrouter.reasoning_details.length > 0\n      ) {\n        return parsed.data.openrouter.reasoning_details;\n      }\n    }\n  }\n\n  // Fall back to reasoning parts - they have delta reasoning_details\n  for (const part of content) {\n    if (part.type === 'reasoning') {\n      const parsed = OpenRouterProviderOptionsSchema.safeParse(\n        part.providerOptions,\n      );\n      if (\n        parsed.success &&\n        parsed.data?.openrouter?.reasoning_details &&\n        parsed.data.openrouter.reasoning_details.length > 0\n      ) {\n        return parsed.data.openrouter.reasoning_details;\n      }\n    }\n  }\n\n  return undefined;\n}\n", "import type { LanguageModelV3ToolChoice } from '@ai-sdk/provider';\n\nimport { InvalidArgumentError } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\n\nconst ChatCompletionToolChoiceSchema = z.union([\n  z.literal('auto'),\n  z.literal('none'),\n  z.literal('required'),\n  z.object({\n    type: z.literal('function'),\n    function: z.object({\n      name: z.string(),\n    }),\n  }),\n]);\n\ntype ChatCompletionToolChoice = z.infer<typeof ChatCompletionToolChoiceSchema>;\n\nexport function getChatCompletionToolChoice(\n  toolChoice: LanguageModelV3ToolChoice,\n): ChatCompletionToolChoice {\n  switch (toolChoice.type) {\n    case 'auto':\n    case 'none':\n    case 'required':\n      return toolChoice.type;\n    case 'tool': {\n      return {\n        type: 'function',\n        function: { name: toolChoice.toolName },\n      };\n    }\n    default: {\n      toolChoice satisfies never;\n      throw new InvalidArgumentError({\n        argument: 'toolChoice',\n        message: `Invalid tool choice type: ${JSON.stringify(toolChoice)}`,\n      });\n    }\n  }\n}\n", "import { z } from 'zod/v4';\nimport { OpenRouterErrorResponseSchema } from '../schemas/error-response';\nimport { ImageResponseArraySchema } from '../schemas/image';\nimport { ReasoningDetailArraySchema } from '../schemas/reasoning-details';\n\nconst OpenRouterChatCompletionBaseResponseSchema = z\n  .object({\n    id: z.string().optional(),\n    model: z.string().optional(),\n    provider: z.string().optional(),\n    usage: z\n      .object({\n        prompt_tokens: z.number(),\n        prompt_tokens_details: z\n          .object({\n            cached_tokens: z.number(),\n            cache_write_tokens: z.number().nullish(),\n          })\n          .passthrough()\n          .nullish(),\n        completion_tokens: z.number(),\n        completion_tokens_details: z\n          .object({\n            reasoning_tokens: z.number(),\n          })\n          .passthrough()\n          .nullish(),\n        total_tokens: z.number(),\n        cost: z.number().optional(),\n        cost_details: z\n          .object({\n            upstream_inference_cost: z.number().nullish(),\n          })\n          .passthrough()\n          .nullish(),\n      })\n      .passthrough()\n      .nullish(),\n  })\n  .passthrough();\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const OpenRouterNonStreamChatCompletionResponseSchema = z.union([\n  // Success response with choices\n  OpenRouterChatCompletionBaseResponseSchema.extend({\n    choices: z.array(\n      z\n        .object({\n          message: z\n            .object({\n              role: z.literal('assistant'),\n              content: z.string().nullable().optional(),\n              reasoning: z.string().nullable().optional(),\n              reasoning_details: ReasoningDetailArraySchema.nullish(),\n              images: ImageResponseArraySchema.nullish(),\n\n              tool_calls: z\n                .array(\n                  z\n                    .object({\n                      id: z.string().optional().nullable(),\n                      type: z.literal('function'),\n                      function: z\n                        .object({\n                          name: z.string(),\n                          arguments: z.string().optional(),\n                        })\n                        .passthrough(),\n                    })\n                    .passthrough(),\n                )\n                .optional(),\n\n              annotations: z\n                .array(\n                  z.union([\n                    // URL citation from web search\n                    // title, start_index, end_index are optional as some upstream providers may omit them\n                    z\n                      .object({\n                        type: z.literal('url_citation'),\n                        url_citation: z\n                          .object({\n                            url: z.string(),\n                            title: z.string().optional(),\n                            start_index: z.number().optional(),\n                            end_index: z.number().optional(),\n                            content: z.string().optional(),\n                          })\n                          .passthrough(),\n                      })\n                      .passthrough(),\n                    // File annotation from FileParserPlugin (old format)\n                    z\n                      .object({\n                        type: z.literal('file_annotation'),\n                        file_annotation: z\n                          .object({\n                            file_id: z.string(),\n                            quote: z.string().optional(),\n                          })\n                          .passthrough(),\n                      })\n                      .passthrough(),\n                    // File annotation from FileParserPlugin (new format)\n                    z\n                      .object({\n                        type: z.literal('file'),\n                        file: z\n                          .object({\n                            hash: z.string(),\n                            name: z.string(),\n                            content: z\n                              .array(\n                                z\n                                  .object({\n                                    type: z.string(),\n                                    text: z.string().optional(),\n                                  })\n                                  .passthrough(),\n                              )\n                              .optional(),\n                          })\n                          .passthrough(),\n                      })\n                      .passthrough(),\n                  ]),\n                )\n                .nullish(),\n            })\n            .passthrough(),\n          index: z.number().nullish(),\n          logprobs: z\n            .object({\n              content: z\n                .array(\n                  z\n                    .object({\n                      token: z.string(),\n                      logprob: z.number(),\n                      top_logprobs: z.array(\n                        z\n                          .object({\n                            token: z.string(),\n                            logprob: z.number(),\n                          })\n                          .passthrough(),\n                      ),\n                    })\n                    .passthrough(),\n                )\n                .nullable(),\n            })\n            .passthrough()\n            .nullable()\n            .optional(),\n          finish_reason: z.string().optional().nullable(),\n        })\n        .passthrough(),\n    ),\n  }),\n  // Error response (HTTP 200 with error payload)\n  OpenRouterErrorResponseSchema.extend({\n    user_id: z.string().optional(),\n  }),\n]);\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const OpenRouterStreamChatCompletionChunkSchema = z.union([\n  OpenRouterChatCompletionBaseResponseSchema.extend({\n    choices: z.array(\n      z\n        .object({\n          delta: z\n            .object({\n              role: z.enum(['assistant']).optional(),\n              content: z.string().nullish(),\n              reasoning: z.string().nullish().optional(),\n              reasoning_details: ReasoningDetailArraySchema.nullish(),\n              images: ImageResponseArraySchema.nullish(),\n              tool_calls: z\n                .array(\n                  z\n                    .object({\n                      index: z.number().nullish(),\n                      id: z.string().nullish(),\n                      type: z.literal('function').optional(),\n                      function: z\n                        .object({\n                          name: z.string().nullish(),\n                          arguments: z.string().nullish(),\n                        })\n                        .passthrough(),\n                    })\n                    .passthrough(),\n                )\n                .nullish(),\n\n              annotations: z\n                .array(\n                  z.union([\n                    // URL citation from web search\n                    // title, start_index, end_index are optional as some upstream providers may omit them\n                    z\n                      .object({\n                        type: z.literal('url_citation'),\n                        url_citation: z\n                          .object({\n                            url: z.string(),\n                            title: z.string().optional(),\n                            start_index: z.number().optional(),\n                            end_index: z.number().optional(),\n                            content: z.string().optional(),\n                          })\n                          .passthrough(),\n                      })\n                      .passthrough(),\n                    // File annotation from FileParserPlugin (old format)\n                    z\n                      .object({\n                        type: z.literal('file_annotation'),\n                        file_annotation: z\n                          .object({\n                            file_id: z.string(),\n                            quote: z.string().optional(),\n                          })\n                          .passthrough(),\n                      })\n                      .passthrough(),\n                    // File annotation from FileParserPlugin (new format)\n                    z\n                      .object({\n                        type: z.literal('file'),\n                        file: z\n                          .object({\n                            hash: z.string(),\n                            name: z.string(),\n                            content: z\n                              .array(\n                                z\n                                  .object({\n                                    type: z.string(),\n                                    text: z.string().optional(),\n                                  })\n                                  .passthrough(),\n                              )\n                              .optional(),\n                          })\n                          .passthrough(),\n                      })\n                      .passthrough(),\n                  ]),\n                )\n                .nullish(),\n            })\n            .passthrough()\n            .nullish(),\n          logprobs: z\n            .object({\n              content: z\n                .array(\n                  z\n                    .object({\n                      token: z.string(),\n                      logprob: z.number(),\n                      top_logprobs: z.array(\n                        z\n                          .object({\n                            token: z.string(),\n                            logprob: z.number(),\n                          })\n                          .passthrough(),\n                      ),\n                    })\n                    .passthrough(),\n                )\n                .nullable(),\n            })\n            .passthrough()\n            .nullish(),\n          finish_reason: z.string().nullable().optional(),\n          index: z.number().nullish(),\n        })\n        .passthrough(),\n    ),\n  }),\n  OpenRouterErrorResponseSchema,\n]);\n", "import { z } from 'zod/v4';\n\nconst ImageResponseSchema = z\n  .object({\n    type: z.literal('image_url'),\n    image_url: z\n      .object({\n        url: z.string(),\n      })\n      .passthrough(),\n  })\n  .passthrough();\n\nexport type ImageResponse = z.infer<typeof ImageResponseSchema>;\n\nconst ImageResponseWithUnknownSchema = z.union([\n  ImageResponseSchema,\n  z.unknown().transform(() => null),\n]);\n\nexport const ImageResponseArraySchema = z\n  .array(ImageResponseWithUnknownSchema)\n  .transform((d) => d.filter((d): d is ImageResponse => !!d));\n", "import type {\n  JSONObject,\n  LanguageModelV3,\n  LanguageModelV3CallOptions,\n  LanguageModelV3Content,\n  LanguageModelV3FinishReason,\n  LanguageModelV3ProviderTool,\n  LanguageModelV3ResponseMetadata,\n  LanguageModelV3StreamPart,\n  LanguageModelV3Usage,\n  SharedV3Headers,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport type { ParseResult } from '@ai-sdk/provider-utils';\nimport type { z } from 'zod/v4';\nimport type { ReasoningDetailUnion } from '@/src/schemas/reasoning-details';\nimport type { OpenRouterUsageAccounting } from '@/src/types/index';\nimport type { FileAnnotation } from '../schemas/provider-metadata';\nimport type {\n  OpenRouterChatModelId,\n  OpenRouterChatSettings,\n} from '../types/openrouter-chat-settings';\n\nimport {\n  APICallError,\n  InvalidResponseDataError,\n  NoContentGeneratedError,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonResponseHandler,\n  generateId,\n  isParsableJson,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { ReasoningDetailType } from '@/src/schemas/reasoning-details';\nimport { openrouterFailedResponseHandler } from '../schemas/error-response';\nimport { OpenRouterProviderMetadataSchema } from '../schemas/provider-metadata';\nimport { computeTokenUsage, emptyUsage } from '../utils/compute-token-usage';\nimport {\n  createFinishReason,\n  mapOpenRouterFinishReason,\n} from '../utils/map-finish-reason';\nimport { withStreamErrorHandling } from '../utils/with-stream-error-handling';\nimport { convertToOpenRouterChatMessages } from './convert-to-openrouter-chat-messages';\nimport { getBase64FromDataUrl, getMediaType } from './file-url-utils';\nimport { getChatCompletionToolChoice } from './get-tool-choice';\nimport {\n  OpenRouterNonStreamChatCompletionResponseSchema,\n  OpenRouterStreamChatCompletionChunkSchema,\n} from './schemas';\n\ntype OpenRouterChatConfig = {\n  provider: string;\n  compatibility: 'strict' | 'compatible';\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: typeof fetch;\n  extraBody?: Record<string, unknown>;\n};\n\nexport class OpenRouterChatLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = 'v3' as const;\n  readonly provider = 'openrouter';\n  readonly defaultObjectGenerationMode = 'tool' as const;\n\n  readonly modelId: OpenRouterChatModelId;\n  readonly supportsImageUrls = true;\n  readonly supportedUrls: Record<string, RegExp[]> = {\n    'image/*': [\n      /^data:image\\/[a-zA-Z]+;base64,/,\n      /^https?:\\/\\/.+\\.(jpg|jpeg|png|gif|webp)(?:[?#].*)?$/i,\n    ],\n    // 'text/*': [/^data:text\\//, /^https?:\\/\\/.+$/],\n    'application/*': [/^data:application\\//, /^https?:\\/\\/.+$/],\n  };\n  readonly settings: OpenRouterChatSettings;\n\n  private readonly config: OpenRouterChatConfig;\n\n  constructor(\n    modelId: OpenRouterChatModelId,\n    settings: OpenRouterChatSettings,\n    config: OpenRouterChatConfig,\n  ) {\n    this.modelId = modelId;\n    this.settings = settings;\n    this.config = config;\n  }\n\n  private getArgs({\n    prompt,\n    maxOutputTokens,\n    temperature,\n    topP,\n    frequencyPenalty,\n    presencePenalty,\n    seed,\n    stopSequences,\n    responseFormat,\n    topK,\n    tools,\n    toolChoice,\n  }: LanguageModelV3CallOptions) {\n    const baseArgs = {\n      // model id:\n      model: this.modelId,\n      models: this.settings.models,\n\n      // model specific settings:\n      logit_bias: this.settings.logitBias,\n      logprobs:\n        this.settings.logprobs === true ||\n        typeof this.settings.logprobs === 'number'\n          ? true\n          : undefined,\n      top_logprobs:\n        typeof this.settings.logprobs === 'number'\n          ? this.settings.logprobs\n          : typeof this.settings.logprobs === 'boolean'\n            ? this.settings.logprobs\n              ? 0\n              : undefined\n            : undefined,\n      user: this.settings.user,\n      parallel_tool_calls: this.settings.parallelToolCalls,\n\n      // standardized settings (call-level options override model-level settings):\n      max_tokens: maxOutputTokens ?? this.settings.maxTokens,\n      temperature: temperature ?? this.settings.temperature,\n      top_p: topP ?? this.settings.topP,\n      frequency_penalty: frequencyPenalty ?? this.settings.frequencyPenalty,\n      presence_penalty: presencePenalty ?? this.settings.presencePenalty,\n      seed,\n\n      stop: stopSequences,\n      response_format:\n        responseFormat?.type === 'json'\n          ? responseFormat.schema != null\n            ? {\n                type: 'json_schema',\n                json_schema: {\n                  schema: responseFormat.schema,\n                  strict: this.settings.structuredOutputs?.strict ?? true,\n                  name: responseFormat.name ?? 'response',\n                  ...(responseFormat.description && {\n                    description: responseFormat.description,\n                  }),\n                },\n              }\n            : { type: 'json_object' }\n          : undefined,\n      top_k: topK ?? this.settings.topK,\n\n      // messages:\n      messages: convertToOpenRouterChatMessages(prompt),\n\n      // OpenRouter specific settings:\n      include_reasoning: this.settings.includeReasoning,\n      reasoning: this.settings.reasoning,\n      usage: this.settings.usage,\n\n      // Web search settings:\n      plugins: this.settings.plugins,\n      web_search_options: this.settings.web_search_options,\n      // Provider routing settings:\n      provider: this.settings.provider,\n      // Debug settings:\n      debug: this.settings.debug,\n\n      // Anthropic automatic caching:\n      cache_control: this.settings.cache_control,\n\n      // extra body:\n      ...this.config.extraBody,\n      ...this.settings.extraBody,\n    };\n\n    if (tools && tools.length > 0) {\n      const mappedTools: Array<Record<string, unknown>> = [];\n\n      for (const tool of tools) {\n        if (tool.type === 'function') {\n          const openrouterOptions = tool.providerOptions?.openrouter as\n            | Record<string, unknown>\n            | undefined;\n          const eagerInputStreaming = openrouterOptions?.eager_input_streaming;\n\n          mappedTools.push({\n            type: 'function' as const,\n            function: {\n              name: tool.name,\n              description: tool.description,\n              parameters: tool.inputSchema,\n            },\n            ...(eagerInputStreaming != null && {\n              eager_input_streaming: eagerInputStreaming,\n            }),\n          });\n        } else if (tool.type === 'provider') {\n          mappedTools.push(mapProviderTool(tool));\n        }\n      }\n\n      return {\n        ...baseArgs,\n        tools: mappedTools,\n        tool_choice: toolChoice\n          ? getChatCompletionToolChoice(toolChoice)\n          : undefined,\n      };\n    }\n\n    return baseArgs;\n  }\n\n  async doGenerate(options: LanguageModelV3CallOptions): Promise<{\n    content: Array<LanguageModelV3Content>;\n    finishReason: LanguageModelV3FinishReason;\n    usage: LanguageModelV3Usage;\n    warnings: Array<SharedV3Warning>;\n    providerMetadata?: {\n      openrouter: {\n        provider: string;\n        reasoning_details?: ReasoningDetailUnion[];\n        usage: OpenRouterUsageAccounting;\n      };\n    };\n    request?: { body?: unknown };\n    response?: LanguageModelV3ResponseMetadata & {\n      headers?: SharedV3Headers;\n      body?: unknown;\n    };\n  }> {\n    const providerOptions = options.providerOptions || {};\n    const openrouterOptions = providerOptions.openrouter || {};\n\n    // Extract cacheControl (camelCase) and normalize to cache_control (snake_case)\n    const { cacheControl, ...restOpenrouterOptions } =\n      openrouterOptions as Record<string, unknown>;\n\n    const args = {\n      ...this.getArgs(options),\n      ...restOpenrouterOptions,\n      // Support both cacheControl (camelCase) and cache_control (snake_case)\n      // from providerOptions, in addition to settings.cache_control\n      ...(cacheControl != null && !('cache_control' in restOpenrouterOptions)\n        ? { cache_control: cacheControl }\n        : {}),\n    };\n\n    const { value: responseValue, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/chat/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: args,\n      failedResponseHandler: openrouterFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        OpenRouterNonStreamChatCompletionResponseSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    // Check if response is an error (HTTP 200 with error payload)\n    if ('error' in responseValue) {\n      const errorData = responseValue.error as {\n        message: string;\n        code?: string;\n      };\n      throw new APICallError({\n        message: errorData.message,\n        url: this.config.url({\n          path: '/chat/completions',\n          modelId: this.modelId,\n        }),\n        requestBodyValues: args,\n        statusCode: 200,\n        responseHeaders,\n        data: errorData,\n      });\n    }\n\n    // Now TypeScript knows this is the success response\n    const response = responseValue;\n\n    const choice = response.choices[0];\n\n    if (!choice) {\n      throw new NoContentGeneratedError({\n        message: 'No choice in response',\n      });\n    }\n\n    const usageInfo: LanguageModelV3Usage = response.usage\n      ? computeTokenUsage(response.usage)\n      : emptyUsage();\n\n    const reasoningDetails = choice.message.reasoning_details ?? [];\n\n    const reasoning: Array<LanguageModelV3Content> =\n      reasoningDetails.length > 0\n        ? (reasoningDetails\n            .map((detail) => {\n              switch (detail.type) {\n                case ReasoningDetailType.Text: {\n                  if (detail.text) {\n                    return {\n                      type: 'reasoning' as const,\n                      text: detail.text,\n                      providerMetadata: {\n                        openrouter: {\n                          reasoning_details: [detail],\n                        },\n                      },\n                    };\n                  }\n                  break;\n                }\n                case ReasoningDetailType.Summary: {\n                  if (detail.summary) {\n                    return {\n                      type: 'reasoning' as const,\n                      text: detail.summary,\n                      providerMetadata: {\n                        openrouter: {\n                          reasoning_details: [detail],\n                        },\n                      },\n                    };\n                  }\n                  break;\n                }\n                case ReasoningDetailType.Encrypted: {\n                  // Encrypted reasoning is an opaque blob for multi-turn\n                  // roundtripping. It is preserved in response-level\n                  // providerMetadata.openrouter.reasoning_details and does\n                  // not produce a visible reasoning content part.\n                  break;\n                }\n                default: {\n                  detail satisfies never;\n                }\n              }\n              return null;\n            })\n            .filter((p) => p !== null) as Array<LanguageModelV3Content>)\n        : choice.message.reasoning\n          ? [\n              {\n                type: 'reasoning' as const,\n                text: choice.message.reasoning,\n              },\n            ]\n          : [];\n\n    const content: Array<LanguageModelV3Content> = [];\n\n    // Add reasoning content first\n    content.push(...reasoning);\n\n    if (choice.message.content) {\n      content.push({\n        type: 'text' as const,\n        text: choice.message.content,\n      });\n    }\n\n    if (choice.message.tool_calls) {\n      // Only attach reasoning_details to the first tool call to avoid\n      // duplicating thinking blocks for parallel tool calls (Claude)\n      let reasoningDetailsAttachedToToolCall = false;\n\n      // Track seen tool call IDs to ensure uniqueness. Some providers\n      // return empty, null, or duplicate IDs for parallel tool calls.\n      const seenToolCallIds = new Set<string>();\n\n      for (const toolCall of choice.message.tool_calls) {\n        let toolCallId = toolCall.id;\n\n        if (!toolCallId || seenToolCallIds.has(toolCallId)) {\n          toolCallId = generateId();\n        }\n\n        seenToolCallIds.add(toolCallId);\n\n        content.push({\n          type: 'tool-call' as const,\n          toolCallId,\n          toolName: toolCall.function.name,\n          input: toolCall.function.arguments ?? '{}',\n          providerMetadata: !reasoningDetailsAttachedToToolCall\n            ? {\n                openrouter: {\n                  reasoning_details: reasoningDetails,\n                },\n              }\n            : undefined,\n        });\n        reasoningDetailsAttachedToToolCall = true;\n      }\n    }\n\n    if (choice.message.images) {\n      for (const image of choice.message.images) {\n        content.push({\n          type: 'file' as const,\n          mediaType: getMediaType(image.image_url.url, 'image/jpeg'),\n          data: getBase64FromDataUrl(image.image_url.url),\n        });\n      }\n    }\n\n    if (choice.message.annotations) {\n      for (const annotation of choice.message.annotations) {\n        if (annotation.type === 'url_citation') {\n          content.push({\n            type: 'source' as const,\n            sourceType: 'url' as const,\n            id: annotation.url_citation.url,\n            url: annotation.url_citation.url,\n            title: annotation.url_citation.title ?? '',\n            providerMetadata: {\n              openrouter: {\n                content: annotation.url_citation.content ?? '',\n                startIndex: annotation.url_citation.start_index ?? 0,\n                endIndex: annotation.url_citation.end_index ?? 0,\n              },\n            },\n          });\n        }\n      }\n    }\n\n    // Extract file annotations to expose in providerMetadata\n    const fileAnnotations = choice.message.annotations?.filter(\n      (\n        a,\n      ): a is {\n        type: 'file';\n        file: {\n          hash: string;\n          name: string;\n          content?: Array<{ type: string; text?: string }>;\n        };\n      } => a.type === 'file',\n    );\n\n    // Fix for Gemini 3 thoughtSignature: when there are tool calls with encrypted\n    // reasoning (thoughtSignature), the model returns 'stop' but expects continuation.\n    // Override to 'tool-calls' so the SDK knows to continue the conversation.\n    const hasToolCalls =\n      choice.message.tool_calls && choice.message.tool_calls.length > 0;\n    const hasEncryptedReasoning = reasoningDetails.some(\n      (d) => d.type === ReasoningDetailType.Encrypted && d.data,\n    );\n    const shouldOverrideFinishReason =\n      hasToolCalls && hasEncryptedReasoning && choice.finish_reason === 'stop';\n\n    const mappedFinishReason = shouldOverrideFinishReason\n      ? createFinishReason('tool-calls', choice.finish_reason ?? undefined)\n      : mapOpenRouterFinishReason(choice.finish_reason);\n\n    // Fix for #420: When finishReason is 'other' (unknown/missing) but tool calls\n    // were made, infer 'tool-calls' so agentic loops continue correctly.\n    const effectiveFinishReason =\n      hasToolCalls && mappedFinishReason.unified === 'other'\n        ? createFinishReason('tool-calls', mappedFinishReason.raw)\n        : mappedFinishReason;\n\n    return {\n      content,\n      finishReason: effectiveFinishReason,\n      usage: usageInfo,\n      warnings: [],\n      providerMetadata: {\n        openrouter: OpenRouterProviderMetadataSchema.parse({\n          provider: response.provider ?? '',\n          reasoning_details: choice.message.reasoning_details ?? [],\n          annotations:\n            fileAnnotations && fileAnnotations.length > 0\n              ? fileAnnotations\n              : undefined,\n          usage: {\n            promptTokens: usageInfo.inputTokens.total ?? 0,\n            completionTokens: usageInfo.outputTokens.total ?? 0,\n            totalTokens:\n              (usageInfo.inputTokens.total ?? 0) +\n              (usageInfo.outputTokens.total ?? 0),\n            ...(response.usage?.cost != null\n              ? { cost: response.usage.cost }\n              : {}),\n            ...(response.usage?.prompt_tokens_details?.cached_tokens != null\n              ? {\n                  promptTokensDetails: {\n                    cachedTokens:\n                      response.usage.prompt_tokens_details.cached_tokens,\n                  },\n                }\n              : {}),\n            ...(response.usage?.completion_tokens_details?.reasoning_tokens !=\n            null\n              ? {\n                  completionTokensDetails: {\n                    reasoningTokens:\n                      response.usage.completion_tokens_details.reasoning_tokens,\n                  },\n                }\n              : {}),\n            ...(response.usage?.cost_details?.upstream_inference_cost != null\n              ? {\n                  costDetails: {\n                    upstreamInferenceCost:\n                      response.usage.cost_details.upstream_inference_cost,\n                  },\n                }\n              : {}),\n          },\n        }),\n      },\n      request: { body: args },\n      response: {\n        id: response.id,\n        modelId: response.model,\n        headers: responseHeaders,\n        body: response,\n      },\n    };\n  }\n\n  async doStream(options: LanguageModelV3CallOptions): Promise<{\n    stream: ReadableStream<LanguageModelV3StreamPart>;\n    warnings: Array<SharedV3Warning>;\n    request?: { body?: unknown };\n    response?: LanguageModelV3ResponseMetadata & {\n      headers?: SharedV3Headers;\n      body?: unknown;\n    };\n  }> {\n    const providerOptions = options.providerOptions || {};\n    const openrouterOptions = providerOptions.openrouter || {};\n\n    // Extract cacheControl (camelCase) and normalize to cache_control (snake_case)\n    const { cacheControl, ...restOpenrouterOptions } =\n      openrouterOptions as Record<string, unknown>;\n\n    const args = {\n      ...this.getArgs(options),\n      ...restOpenrouterOptions,\n      // Support both cacheControl (camelCase) and cache_control (snake_case)\n      // from providerOptions, in addition to settings.cache_control\n      ...(cacheControl != null && !('cache_control' in restOpenrouterOptions)\n        ? { cache_control: cacheControl }\n        : {}),\n    };\n\n    const { value: response, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/chat/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: {\n        ...args,\n        stream: true,\n\n        // only include stream_options when in strict compatibility mode:\n        stream_options:\n          this.config.compatibility === 'strict'\n            ? {\n                include_usage: true,\n                // If user has requested usage accounting, make sure we get it in the stream\n                ...(this.settings.usage?.include\n                  ? { include_usage: true }\n                  : {}),\n              }\n            : undefined,\n      },\n      failedResponseHandler: openrouterFailedResponseHandler,\n      successfulResponseHandler: createEventSourceResponseHandler(\n        OpenRouterStreamChatCompletionChunkSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    let streamError: unknown;\n    const safeResponse = withStreamErrorHandling(response, (err) => {\n      streamError = err;\n    });\n\n    const toolCalls: Array<{\n      id: string;\n      type: 'function';\n      function: {\n        name: string;\n        arguments: string;\n      };\n      inputStarted: boolean;\n      sent: boolean;\n    }> = [];\n\n    // Track seen tool call IDs to ensure uniqueness. Some providers\n    // return empty, null, or duplicate IDs for parallel tool calls.\n    const seenToolCallIds = new Set<string>();\n\n    let finishReason: LanguageModelV3FinishReason = createFinishReason('other');\n    const usage: LanguageModelV3Usage = {\n      inputTokens: {\n        total: undefined,\n        noCache: undefined,\n        cacheRead: undefined,\n        cacheWrite: undefined,\n      },\n      outputTokens: {\n        total: undefined,\n        text: undefined,\n        reasoning: undefined,\n      },\n      raw: undefined,\n    };\n\n    // Track provider-specific usage information\n    const openrouterUsage: Partial<OpenRouterUsageAccounting> = {};\n\n    // Track raw usage from the API response for usage.raw\n    let rawUsage: JSONObject | undefined;\n\n    // Track reasoning details to preserve for multi-turn conversations\n    const accumulatedReasoningDetails: ReasoningDetailUnion[] = [];\n\n    // Track whether reasoning_details have been attached to a tool call\n    // For parallel tool calls (e.g., Claude with thinking), only the first tool call\n    // should have reasoning_details to avoid duplicating thinking blocks\n    let reasoningDetailsAttachedToToolCall = false;\n\n    // Track file annotations to expose in providerMetadata\n    const accumulatedFileAnnotations: FileAnnotation[] = [];\n\n    let textStarted = false;\n    let reasoningStarted = false;\n    let textId: string | undefined;\n    let reasoningId: string | undefined;\n    let openrouterResponseId: string | undefined;\n    let provider: string | undefined;\n\n    return {\n      stream: safeResponse.pipeThrough(\n        new TransformStream<\n          ParseResult<\n            z.infer<typeof OpenRouterStreamChatCompletionChunkSchema>\n          >,\n          LanguageModelV3StreamPart\n        >({\n          transform(chunk, controller) {\n            // Emit raw chunk if requested (before anything else)\n            if (options.includeRawChunks) {\n              controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n            }\n\n            // handle failed chunk parsing / validation:\n            if (!chunk.success) {\n              finishReason = createFinishReason('error');\n              controller.enqueue({ type: 'error', error: chunk.error });\n              return;\n            }\n\n            const value = chunk.value;\n\n            // handle error chunks:\n            if ('error' in value) {\n              finishReason = createFinishReason('error');\n              controller.enqueue({ type: 'error', error: value.error });\n              return;\n            }\n\n            if (value.provider) {\n              provider = value.provider;\n            }\n\n            if (value.id) {\n              openrouterResponseId = value.id;\n              controller.enqueue({\n                type: 'response-metadata',\n                id: value.id,\n              });\n            }\n\n            if (value.model) {\n              controller.enqueue({\n                type: 'response-metadata',\n                modelId: value.model,\n              });\n            }\n\n            if (value.usage != null) {\n              const computed = computeTokenUsage(value.usage);\n              Object.assign(usage.inputTokens, computed.inputTokens);\n              Object.assign(usage.outputTokens, computed.outputTokens);\n\n              rawUsage = value.usage as JSONObject;\n\n              const promptTokens = value.usage.prompt_tokens ?? 0;\n              const completionTokens = value.usage.completion_tokens ?? 0;\n              openrouterUsage.promptTokens = promptTokens;\n\n              if (value.usage.prompt_tokens_details) {\n                openrouterUsage.promptTokensDetails = {\n                  cachedTokens:\n                    value.usage.prompt_tokens_details.cached_tokens ?? 0,\n                };\n              }\n\n              openrouterUsage.completionTokens = completionTokens;\n              if (value.usage.completion_tokens_details) {\n                openrouterUsage.completionTokensDetails = {\n                  reasoningTokens:\n                    value.usage.completion_tokens_details.reasoning_tokens ?? 0,\n                };\n              }\n\n              if (value.usage.cost != null) {\n                openrouterUsage.cost = value.usage.cost;\n              }\n              openrouterUsage.totalTokens = value.usage.total_tokens;\n              const upstreamInferenceCost =\n                value.usage.cost_details?.upstream_inference_cost;\n              if (upstreamInferenceCost != null) {\n                openrouterUsage.costDetails = {\n                  upstreamInferenceCost,\n                };\n              }\n            }\n\n            const choice = value.choices[0];\n\n            if (choice?.finish_reason != null) {\n              finishReason = mapOpenRouterFinishReason(choice.finish_reason);\n            }\n\n            if (choice?.delta == null) {\n              return;\n            }\n\n            const delta = choice.delta;\n\n            const emitReasoningChunk = (chunkText: string) => {\n              if (!reasoningStarted) {\n                reasoningId = generateId();\n                controller.enqueue({\n                  type: 'reasoning-start',\n                  id: reasoningId,\n                });\n                reasoningStarted = true;\n              }\n              controller.enqueue({\n                type: 'reasoning-delta',\n                delta: chunkText,\n                id: reasoningId || generateId(),\n              });\n            };\n\n            if (delta.reasoning_details && delta.reasoning_details.length > 0) {\n              // Accumulate reasoning_details to preserve for multi-turn conversations\n              // Merge consecutive reasoning.text items into a single entry\n              for (const detail of delta.reasoning_details) {\n                if (detail.type === ReasoningDetailType.Text) {\n                  const lastDetail =\n                    accumulatedReasoningDetails[\n                      accumulatedReasoningDetails.length - 1\n                    ];\n                  if (lastDetail?.type === ReasoningDetailType.Text) {\n                    // Merge with the previous text detail\n                    lastDetail.text =\n                      (lastDetail.text || '') + (detail.text || '');\n\n                    lastDetail.signature =\n                      lastDetail.signature || detail.signature;\n\n                    lastDetail.format = lastDetail.format || detail.format;\n                  } else {\n                    // Start a new text detail\n                    accumulatedReasoningDetails.push({ ...detail });\n                  }\n                } else {\n                  // Non-text details (encrypted, summary) are pushed as-is\n                  accumulatedReasoningDetails.push(detail);\n                }\n              }\n\n              // Only emit reasoning events if text content has not started yet.\n              // Late-arriving reasoning_details (e.g. a signature-only delta\n              // after text has begun) are still accumulated above for multi-turn\n              // roundtrip via the finish event's providerMetadata, but must not\n              // start a new reasoning block — doing so would create duplicate\n              // reasoning parts in the UIMessage.\n              if (!textStarted) {\n                for (const detail of delta.reasoning_details) {\n                  switch (detail.type) {\n                    case ReasoningDetailType.Text: {\n                      // Emit even when detail.text is empty/undefined — a signature-only\n                      // delta (no text, just signature) must still be emitted so that\n                      // the signature propagates to the reasoning part's providerMetadata.\n                      emitReasoningChunk(detail.text || '');\n                      break;\n                    }\n                    case ReasoningDetailType.Encrypted: {\n                      // Encrypted reasoning is an opaque blob for multi-turn\n                      // roundtripping. It is accumulated in\n                      // accumulatedReasoningDetails but does not produce a\n                      // visible reasoning delta.\n                      break;\n                    }\n                    case ReasoningDetailType.Summary: {\n                      if (detail.summary) {\n                        emitReasoningChunk(detail.summary);\n                      }\n                      break;\n                    }\n                    default: {\n                      detail satisfies never;\n                      break;\n                    }\n                  }\n                }\n              }\n            } else if (delta.reasoning && !textStarted) {\n              emitReasoningChunk(delta.reasoning);\n            }\n\n            if (delta.content) {\n              // If reasoning was previously active and now we're starting text content,\n              // we should end the reasoning first to maintain proper order\n              if (reasoningStarted && !textStarted) {\n                controller.enqueue({\n                  type: 'reasoning-end',\n                  id: reasoningId || generateId(),\n                  // Always include accumulated reasoning_details so the AI SDK can\n                  // update the reasoning part's providerMetadata with the correct\n                  // signature.  The signature typically arrives in the last delta,\n                  // but reasoning-start only carries the first delta's metadata.\n                  // An empty array is intentional — it signals the provider produced\n                  // no reasoning tokens this turn (e.g. DeepSeek V4).\n                  providerMetadata: {\n                    openrouter: {\n                      reasoning_details: accumulatedReasoningDetails,\n                    },\n                  },\n                });\n                reasoningStarted = false; // Mark as ended so we don't end it again in flush\n              }\n\n              if (!textStarted) {\n                textId = openrouterResponseId || generateId();\n                controller.enqueue({\n                  type: 'text-start',\n                  id: textId,\n                });\n                textStarted = true;\n              }\n              controller.enqueue({\n                type: 'text-delta',\n                delta: delta.content,\n                id: textId || generateId(),\n              });\n            }\n\n            if (delta.annotations) {\n              for (const annotation of delta.annotations) {\n                if (annotation.type === 'url_citation') {\n                  controller.enqueue({\n                    type: 'source',\n                    sourceType: 'url' as const,\n                    id: annotation.url_citation.url,\n                    url: annotation.url_citation.url,\n                    title: annotation.url_citation.title ?? '',\n                    providerMetadata: {\n                      openrouter: {\n                        content: annotation.url_citation.content ?? '',\n                        startIndex: annotation.url_citation.start_index ?? 0,\n                        endIndex: annotation.url_citation.end_index ?? 0,\n                      },\n                    },\n                  });\n                } else if (annotation.type === 'file') {\n                  // Accumulate file annotations to expose in providerMetadata\n                  // Type guard to validate structure matches expected shape\n                  const file = (annotation as { file?: unknown }).file;\n                  if (\n                    file &&\n                    typeof file === 'object' &&\n                    'hash' in file &&\n                    'name' in file\n                  ) {\n                    accumulatedFileAnnotations.push(\n                      annotation as FileAnnotation,\n                    );\n                  }\n                }\n              }\n            }\n\n            if (delta.tool_calls != null) {\n              for (const toolCallDelta of delta.tool_calls) {\n                const index = toolCallDelta.index ?? toolCalls.length - 1;\n\n                // Tool call start. OpenRouter returns all information except the arguments in the first chunk.\n                if (toolCalls[index] == null) {\n                  if (toolCallDelta.type !== 'function') {\n                    throw new InvalidResponseDataError({\n                      data: toolCallDelta,\n                      message: `Expected 'function' type.`,\n                    });\n                  }\n\n                  if (toolCallDelta.function?.name == null) {\n                    throw new InvalidResponseDataError({\n                      data: toolCallDelta,\n                      message: `Expected 'function.name' to be a string.`,\n                    });\n                  }\n\n                  // Ensure the tool call ID is non-empty and unique.\n                  // Some providers return empty, null, or duplicate IDs\n                  // for parallel tool calls.\n                  let toolCallId = toolCallDelta.id ?? '';\n                  if (!toolCallId || seenToolCallIds.has(toolCallId)) {\n                    toolCallId = generateId();\n                  }\n                  seenToolCallIds.add(toolCallId);\n\n                  toolCalls[index] = {\n                    id: toolCallId,\n                    type: 'function',\n                    function: {\n                      name: toolCallDelta.function.name,\n                      arguments: toolCallDelta.function.arguments ?? '',\n                    },\n                    inputStarted: false,\n                    sent: false,\n                  };\n\n                  const toolCall = toolCalls[index];\n\n                  if (toolCall == null) {\n                    throw new InvalidResponseDataError({\n                      data: { index, toolCallsLength: toolCalls.length },\n                      message: `Tool call at index ${index} is missing after creation.`,\n                    });\n                  }\n\n                  // check if tool call is complete (some providers send the full tool call in one chunk)\n                  if (\n                    toolCall.function?.name != null &&\n                    toolCall.function?.arguments != null &&\n                    isParsableJson(toolCall.function.arguments)\n                  ) {\n                    toolCall.inputStarted = true;\n\n                    controller.enqueue({\n                      type: 'tool-input-start',\n                      id: toolCall.id,\n                      toolName: toolCall.function.name,\n                    });\n\n                    // send delta\n                    controller.enqueue({\n                      type: 'tool-input-delta',\n                      id: toolCall.id,\n                      delta: toolCall.function.arguments,\n                    });\n\n                    controller.enqueue({\n                      type: 'tool-input-end',\n                      id: toolCall.id,\n                    });\n\n                    // send tool call\n                    // Only attach reasoning_details to the first tool call to avoid\n                    // duplicating thinking blocks for parallel tool calls (Claude)\n                    controller.enqueue({\n                      type: 'tool-call',\n                      toolCallId: toolCall.id,\n                      toolName: toolCall.function.name,\n                      input: toolCall.function.arguments,\n                      providerMetadata: !reasoningDetailsAttachedToToolCall\n                        ? {\n                            openrouter: {\n                              reasoning_details: accumulatedReasoningDetails,\n                            },\n                          }\n                        : undefined,\n                    });\n\n                    reasoningDetailsAttachedToToolCall = true;\n                    toolCall.sent = true;\n                  }\n\n                  continue;\n                }\n\n                // existing tool call, merge\n                const toolCall = toolCalls[index];\n\n                if (toolCall == null) {\n                  throw new InvalidResponseDataError({\n                    data: {\n                      index,\n                      toolCallsLength: toolCalls.length,\n                      toolCallDelta,\n                    },\n                    message: `Tool call at index ${index} is missing during merge.`,\n                  });\n                }\n\n                if (!toolCall.inputStarted) {\n                  toolCall.inputStarted = true;\n                  controller.enqueue({\n                    type: 'tool-input-start',\n                    id: toolCall.id,\n                    toolName: toolCall.function.name,\n                  });\n\n                  // Emit the initial chunk's arguments as a delta so they are\n                  // not silently dropped when the tool call spans multiple chunks.\n                  if (toolCall.function.arguments) {\n                    controller.enqueue({\n                      type: 'tool-input-delta',\n                      id: toolCall.id,\n                      delta: toolCall.function.arguments,\n                    });\n                  }\n                }\n\n                if (toolCallDelta.function?.arguments != null) {\n                  toolCall.function.arguments +=\n                    toolCallDelta.function?.arguments ?? '';\n                }\n\n                // send delta\n                controller.enqueue({\n                  type: 'tool-input-delta',\n                  id: toolCall.id,\n                  delta: toolCallDelta.function.arguments ?? '',\n                });\n\n                // check if tool call is complete. Skip if already sent so\n                // that trailing-whitespace or other no-op deltas after a\n                // complete tool call don't trigger a duplicate `tool-call`\n                // event with the same toolCallId. JSON.parse accepts trailing\n                // whitespace, so `'{...}'` and `'{...} '` are both parsable\n                // and the merge path would otherwise re-emit on each chunk.\n                if (\n                  !toolCall.sent &&\n                  toolCall.function?.name != null &&\n                  toolCall.function?.arguments != null &&\n                  isParsableJson(toolCall.function.arguments)\n                ) {\n                  // Emit tool-input-end before tool-call to complete the\n                  // tool-input lifecycle (start → delta... → end → call).\n                  controller.enqueue({\n                    type: 'tool-input-end',\n                    id: toolCall.id,\n                  });\n\n                  // Only attach reasoning_details to the first tool call to avoid\n                  // duplicating thinking blocks for parallel tool calls (Claude)\n                  controller.enqueue({\n                    type: 'tool-call',\n                    toolCallId: toolCall.id,\n                    toolName: toolCall.function.name,\n                    input: toolCall.function.arguments,\n                    providerMetadata: !reasoningDetailsAttachedToToolCall\n                      ? {\n                          openrouter: {\n                            reasoning_details: accumulatedReasoningDetails,\n                          },\n                        }\n                      : undefined,\n                  });\n\n                  reasoningDetailsAttachedToToolCall = true;\n                  toolCall.sent = true;\n                }\n              }\n            }\n\n            if (delta.images != null) {\n              for (const image of delta.images) {\n                controller.enqueue({\n                  type: 'file',\n                  mediaType: getMediaType(image.image_url.url, 'image/jpeg'),\n                  data: getBase64FromDataUrl(image.image_url.url),\n                });\n              }\n            }\n          },\n\n          flush(controller) {\n            const hasToolCalls = toolCalls.length > 0;\n\n            if (streamError != null) {\n              finishReason = createFinishReason('error');\n              controller.enqueue({ type: 'error', error: streamError });\n            }\n\n            // Fix for Gemini 3 thoughtSignature: when there are tool calls with encrypted\n            // reasoning (thoughtSignature), the model returns 'stop' but expects continuation.\n            // Override to 'tool-calls' so the SDK knows to continue the conversation.\n            const hasEncryptedReasoning = accumulatedReasoningDetails.some(\n              (d) => d.type === ReasoningDetailType.Encrypted && d.data,\n            );\n            if (\n              hasToolCalls &&\n              hasEncryptedReasoning &&\n              finishReason.unified === 'stop'\n            ) {\n              finishReason = createFinishReason('tool-calls', finishReason.raw);\n            }\n\n            // Fix for #420: When finishReason is 'other' (unknown/missing) but tool calls\n            // were made, infer 'tool-calls' so agentic loops continue correctly.\n            if (hasToolCalls && finishReason.unified === 'other') {\n              finishReason = createFinishReason('tool-calls', finishReason.raw);\n            }\n\n            // Forward any unsent tool calls if finish reason is 'tool-calls'\n            if (finishReason.unified === 'tool-calls') {\n              for (const toolCall of toolCalls) {\n                if (toolCall && !toolCall.sent) {\n                  const input = isParsableJson(toolCall.function.arguments)\n                    ? toolCall.function.arguments\n                    : '{}';\n\n                  // Emit the full tool-input lifecycle for unsent tool calls.\n                  // If inputStarted is false, the tool call was never partially\n                  // streamed — emit start + delta + end.\n                  // If inputStarted is true, start and deltas were already\n                  // emitted during streaming — only emit end.\n                  if (!toolCall.inputStarted) {\n                    controller.enqueue({\n                      type: 'tool-input-start',\n                      id: toolCall.id,\n                      toolName: toolCall.function.name,\n                    });\n                    controller.enqueue({\n                      type: 'tool-input-delta',\n                      id: toolCall.id,\n                      delta: input,\n                    });\n                  }\n\n                  controller.enqueue({\n                    type: 'tool-input-end',\n                    id: toolCall.id,\n                  });\n\n                  // Only attach reasoning_details to the first tool call to avoid\n                  // duplicating thinking blocks for parallel tool calls (Claude)\n                  controller.enqueue({\n                    type: 'tool-call',\n                    toolCallId: toolCall.id,\n                    toolName: toolCall.function.name,\n                    input,\n                    providerMetadata: !reasoningDetailsAttachedToToolCall\n                      ? {\n                          openrouter: {\n                            reasoning_details: accumulatedReasoningDetails,\n                          },\n                        }\n                      : undefined,\n                  });\n                  reasoningDetailsAttachedToToolCall = true;\n                  toolCall.sent = true;\n                }\n              }\n            }\n\n            // End reasoning first if it was started, to maintain proper order\n            if (reasoningStarted) {\n              controller.enqueue({\n                type: 'reasoning-end',\n                id: reasoningId || generateId(),\n                // Always include accumulated reasoning_details so the AI SDK can\n                // update the reasoning part's providerMetadata.  An empty array is\n                // intentional — it signals the provider produced no reasoning tokens.\n                providerMetadata: {\n                  openrouter: {\n                    reasoning_details: accumulatedReasoningDetails,\n                  },\n                },\n              });\n            }\n            if (textStarted) {\n              controller.enqueue({\n                type: 'text-end',\n                id: textId || generateId(),\n              });\n            }\n\n            const openrouterMetadata: {\n              usage: Partial<OpenRouterUsageAccounting>;\n              provider?: string;\n              reasoning_details?: ReasoningDetailUnion[];\n              annotations?: FileAnnotation[];\n            } = {\n              usage: openrouterUsage,\n            };\n\n            // Only include provider if it's actually set\n            if (provider !== undefined) {\n              openrouterMetadata.provider = provider;\n            }\n\n            // Always include reasoning_details in finish metadata, even when empty.\n            // Some providers (e.g. DeepSeek V4) return reasoning_details: [] on turns\n            // where they produced no visible reasoning tokens, and they require the\n            // field to be sent back in subsequent turns to maintain conversation state.\n            openrouterMetadata.reasoning_details = accumulatedReasoningDetails;\n\n            // Include accumulated file annotations if any were received\n            if (accumulatedFileAnnotations.length > 0) {\n              openrouterMetadata.annotations = accumulatedFileAnnotations;\n            }\n\n            // Fix for #419: When standard usage totals are still undefined but\n            // openrouterUsage has valid token data, copy values as a fallback.\n            // Some providers may deliver usage in a format where the standard\n            // usage fields don't get populated through computeTokenUsage().\n            if (\n              usage.inputTokens.total === undefined &&\n              openrouterUsage.promptTokens !== undefined\n            ) {\n              usage.inputTokens.total = openrouterUsage.promptTokens;\n            }\n            if (\n              usage.outputTokens.total === undefined &&\n              openrouterUsage.completionTokens !== undefined\n            ) {\n              usage.outputTokens.total = openrouterUsage.completionTokens;\n            }\n\n            // Set raw usage before emitting finish event\n            usage.raw = rawUsage;\n\n            controller.enqueue({\n              type: 'finish',\n              finishReason,\n              usage,\n              providerMetadata: {\n                openrouter: openrouterMetadata,\n              },\n            });\n          },\n        }),\n      ),\n      warnings: [],\n      request: { body: args },\n      response: { headers: responseHeaders },\n    };\n  }\n}\n\n/**\n * Maps a provider-defined tool to the OpenRouter API server tool format.\n *\n * Provider tool IDs follow the format `openrouter.<tool_name>`, which maps\n * to `openrouter:<tool_name>` in the API request tools array.\n */\nfunction mapProviderTool(\n  tool: LanguageModelV3ProviderTool,\n): Record<string, unknown> {\n  // Convert provider tool ID format (openrouter.web_search)\n  // to OpenRouter API format (openrouter:web_search)\n  const [provider, toolName] = tool.id.split('.');\n  const apiToolType = `${provider}:${toolName}`;\n\n  // Map camelCase args to snake_case for the API\n  const mappedArgs: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(tool.args)) {\n    if (value !== undefined) {\n      mappedArgs[camelToSnake(key)] = value;\n    }\n  }\n\n  return {\n    type: apiToolType,\n    ...mappedArgs,\n  };\n}\n\n/**\n * Converts a camelCase string to snake_case.\n */\nfunction camelToSnake(str: string): string {\n  return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n}\n", "import type {\n  LanguageModelV3FilePart,\n  LanguageModelV3Prompt,\n  LanguageModelV3ReasoningPart,\n  LanguageModelV3TextPart,\n  LanguageModelV3ToolCallPart,\n  LanguageModelV3ToolResultPart,\n} from '@ai-sdk/provider';\n\nimport {\n  InvalidPromptError,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\n\nexport function convertToOpenRouterCompletionPrompt({\n  prompt,\n  inputFormat,\n  user = 'user',\n  assistant = 'assistant',\n}: {\n  prompt: LanguageModelV3Prompt;\n  inputFormat: 'prompt' | 'messages';\n  user?: string;\n  assistant?: string;\n}): {\n  prompt: string;\n} {\n  // When the user supplied a prompt input, we don't transform it:\n  if (\n    inputFormat === 'prompt' &&\n    prompt.length === 1 &&\n    prompt[0] &&\n    prompt[0].role === 'user' &&\n    prompt[0].content.length === 1 &&\n    prompt[0].content[0] &&\n    prompt[0].content[0].type === 'text'\n  ) {\n    return { prompt: prompt[0].content[0].text };\n  }\n\n  // otherwise transform to a chat message format:\n  let text = '';\n\n  // if first message is a system message, add it to the text:\n  if (prompt[0] && prompt[0].role === 'system') {\n    text += `${prompt[0].content}\\n\\n`;\n    prompt = prompt.slice(1);\n  }\n\n  for (const { role, content } of prompt) {\n    switch (role) {\n      case 'system': {\n        throw new InvalidPromptError({\n          message: `Unexpected system message in prompt: ${content}`,\n          prompt,\n        });\n      }\n\n      case 'user': {\n        const userMessage = content\n          .map((part: LanguageModelV3TextPart | LanguageModelV3FilePart) => {\n            switch (part.type) {\n              case 'text': {\n                return part.text;\n              }\n\n              case 'file': {\n                throw new UnsupportedFunctionalityError({\n                  functionality: 'file attachments',\n                });\n              }\n              default: {\n                return '';\n              }\n            }\n          })\n          .join('');\n\n        text += `${user}:\\n${userMessage}\\n\\n`;\n        break;\n      }\n\n      case 'assistant': {\n        const assistantMessage = content\n          .map(\n            (\n              part:\n                | LanguageModelV3TextPart\n                | LanguageModelV3FilePart\n                | LanguageModelV3ReasoningPart\n                | LanguageModelV3ToolCallPart\n                | LanguageModelV3ToolResultPart,\n            ) => {\n              switch (part.type) {\n                case 'text': {\n                  return part.text;\n                }\n                case 'tool-call': {\n                  throw new UnsupportedFunctionalityError({\n                    functionality: 'tool-call messages',\n                  });\n                }\n                case 'tool-result': {\n                  throw new UnsupportedFunctionalityError({\n                    functionality: 'tool-result messages',\n                  });\n                }\n                case 'reasoning': {\n                  throw new UnsupportedFunctionalityError({\n                    functionality: 'reasoning messages',\n                  });\n                }\n\n                case 'file': {\n                  throw new UnsupportedFunctionalityError({\n                    functionality: 'file attachments',\n                  });\n                }\n\n                default: {\n                  return '';\n                }\n              }\n            },\n          )\n          .join('');\n\n        text += `${assistant}:\\n${assistantMessage}\\n\\n`;\n        break;\n      }\n\n      case 'tool': {\n        throw new UnsupportedFunctionalityError({\n          functionality: 'tool messages',\n        });\n      }\n\n      default: {\n        break;\n      }\n    }\n  }\n\n  // Assistant message prefix:\n  text += `${assistant}:\\n`;\n\n  return {\n    prompt: text,\n  };\n}\n", "import { z } from 'zod/v4';\nimport { OpenRouterErrorResponseSchema } from '../schemas/error-response';\nimport { ReasoningDetailArraySchema } from '../schemas/reasoning-details';\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const OpenRouterCompletionChunkSchema = z.union([\n  z\n    .object({\n      id: z.string().optional(),\n      model: z.string().optional(),\n      provider: z.string().optional(),\n      choices: z.array(\n        z\n          .object({\n            text: z.string(),\n            reasoning: z.string().nullish().optional(),\n            reasoning_details: ReasoningDetailArraySchema.nullish(),\n\n            finish_reason: z.string().nullish(),\n            index: z.number().nullish(),\n            logprobs: z\n              .object({\n                tokens: z.array(z.string()),\n                token_logprobs: z.array(z.number()),\n                top_logprobs: z\n                  .array(z.record(z.string(), z.number()))\n                  .nullable(),\n              })\n              .passthrough()\n              .nullable()\n              .optional(),\n          })\n          .passthrough(),\n      ),\n      usage: z\n        .object({\n          prompt_tokens: z.number(),\n          prompt_tokens_details: z\n            .object({\n              cached_tokens: z.number(),\n              cache_write_tokens: z.number().nullish(),\n            })\n            .passthrough()\n            .nullish(),\n          completion_tokens: z.number(),\n          completion_tokens_details: z\n            .object({\n              reasoning_tokens: z.number(),\n            })\n            .passthrough()\n            .nullish(),\n          total_tokens: z.number(),\n          cost: z.number().optional(),\n          cost_details: z\n            .object({\n              upstream_inference_cost: z.number().nullish(),\n            })\n            .passthrough()\n            .nullish(),\n        })\n        .passthrough()\n        .nullish(),\n    })\n    .passthrough(),\n  OpenRouterErrorResponseSchema,\n]);\n", "import type {\n  JSONObject,\n  LanguageModelV3,\n  LanguageModelV3CallOptions,\n  LanguageModelV3FinishReason,\n  LanguageModelV3StreamPart,\n  LanguageModelV3Usage,\n} from '@ai-sdk/provider';\nimport type { ParseResult } from '@ai-sdk/provider-utils';\nimport type { z } from 'zod/v4';\nimport type { OpenRouterUsageAccounting } from '../types';\nimport type {\n  OpenRouterCompletionModelId,\n  OpenRouterCompletionSettings,\n} from '../types/openrouter-completion-settings';\n\nimport {\n  APICallError,\n  NoContentGeneratedError,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonResponseHandler,\n  generateId,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { openrouterFailedResponseHandler } from '../schemas/error-response';\nimport { OpenRouterProviderMetadataSchema } from '../schemas/provider-metadata';\nimport { computeTokenUsage, emptyUsage } from '../utils/compute-token-usage';\nimport {\n  createFinishReason,\n  mapOpenRouterFinishReason,\n} from '../utils/map-finish-reason';\nimport { withStreamErrorHandling } from '../utils/with-stream-error-handling';\nimport { convertToOpenRouterCompletionPrompt } from './convert-to-openrouter-completion-prompt';\nimport { OpenRouterCompletionChunkSchema } from './schemas';\n\ntype OpenRouterCompletionConfig = {\n  provider: string;\n  compatibility: 'strict' | 'compatible';\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: typeof fetch;\n  extraBody?: Record<string, unknown>;\n};\n\nexport class OpenRouterCompletionLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = 'v3' as const;\n  readonly provider = 'openrouter';\n  readonly modelId: OpenRouterCompletionModelId;\n  readonly supportsImageUrls = true;\n  readonly supportedUrls: Record<string, RegExp[]> = {\n    'image/*': [\n      /^data:image\\/[a-zA-Z]+;base64,/,\n      /^https?:\\/\\/.+\\.(jpg|jpeg|png|gif|webp)(?:[?#].*)?$/i,\n    ],\n    'text/*': [/^data:text\\//, /^https?:\\/\\/.+$/],\n    'application/*': [/^data:application\\//, /^https?:\\/\\/.+$/],\n  };\n  readonly defaultObjectGenerationMode = undefined;\n  readonly settings: OpenRouterCompletionSettings;\n\n  private readonly config: OpenRouterCompletionConfig;\n\n  constructor(\n    modelId: OpenRouterCompletionModelId,\n    settings: OpenRouterCompletionSettings,\n    config: OpenRouterCompletionConfig,\n  ) {\n    this.modelId = modelId;\n    this.settings = settings;\n    this.config = config;\n  }\n\n  private getArgs({\n    prompt,\n    maxOutputTokens,\n    temperature,\n    topP,\n    frequencyPenalty,\n    presencePenalty,\n    seed,\n    responseFormat,\n    topK,\n    stopSequences,\n    tools,\n    toolChoice,\n  }: LanguageModelV3CallOptions) {\n    const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({\n      prompt,\n      inputFormat: 'prompt',\n    });\n\n    if (tools?.length) {\n      throw new UnsupportedFunctionalityError({\n        functionality: 'tools',\n      });\n    }\n\n    if (toolChoice) {\n      throw new UnsupportedFunctionalityError({\n        functionality: 'toolChoice',\n      });\n    }\n\n    return {\n      // model id:\n      model: this.modelId,\n      models: this.settings.models,\n\n      // model specific settings:\n      logit_bias: this.settings.logitBias,\n      logprobs:\n        typeof this.settings.logprobs === 'number'\n          ? this.settings.logprobs\n          : typeof this.settings.logprobs === 'boolean'\n            ? this.settings.logprobs\n              ? 0\n              : undefined\n            : undefined,\n      suffix: this.settings.suffix,\n      user: this.settings.user,\n\n      // standardized settings (call-level options override model-level settings):\n      max_tokens: maxOutputTokens ?? this.settings.maxTokens,\n      temperature: temperature ?? this.settings.temperature,\n      top_p: topP ?? this.settings.topP,\n      frequency_penalty: frequencyPenalty ?? this.settings.frequencyPenalty,\n      presence_penalty: presencePenalty ?? this.settings.presencePenalty,\n      seed,\n\n      stop: stopSequences,\n      response_format: responseFormat,\n      top_k: topK ?? this.settings.topK,\n\n      // prompt:\n      prompt: completionPrompt,\n\n      // OpenRouter specific settings:\n      include_reasoning: this.settings.includeReasoning,\n      reasoning: this.settings.reasoning,\n\n      // extra body:\n      ...this.config.extraBody,\n      ...this.settings.extraBody,\n    };\n  }\n\n  async doGenerate(\n    options: LanguageModelV3CallOptions,\n  ): Promise<Awaited<ReturnType<LanguageModelV3['doGenerate']>>> {\n    const providerOptions = options.providerOptions || {};\n    const openrouterOptions = providerOptions.openrouter || {};\n\n    const args = {\n      ...this.getArgs(options),\n      ...openrouterOptions,\n    };\n\n    const { value: response, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: args,\n      failedResponseHandler: openrouterFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        OpenRouterCompletionChunkSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    if ('error' in response) {\n      const errorData = response.error as { message: string; code?: string };\n      throw new APICallError({\n        message: errorData.message,\n        url: this.config.url({\n          path: '/completions',\n          modelId: this.modelId,\n        }),\n        requestBodyValues: args,\n        statusCode: 200,\n        responseHeaders,\n        data: errorData,\n      });\n    }\n\n    const choice = response.choices[0];\n\n    if (!choice) {\n      throw new NoContentGeneratedError({\n        message: 'No choice in OpenRouter completion response',\n      });\n    }\n\n    return {\n      content: [\n        {\n          type: 'text',\n          text: choice.text ?? '',\n        },\n      ],\n      finishReason: mapOpenRouterFinishReason(choice.finish_reason),\n      usage: response.usage ? computeTokenUsage(response.usage) : emptyUsage(),\n      warnings: [],\n      providerMetadata: {\n        openrouter: OpenRouterProviderMetadataSchema.parse({\n          provider: response.provider ?? '',\n          usage: {\n            promptTokens: response.usage?.prompt_tokens ?? 0,\n            completionTokens: response.usage?.completion_tokens ?? 0,\n            totalTokens:\n              (response.usage?.prompt_tokens ?? 0) +\n              (response.usage?.completion_tokens ?? 0),\n            ...(response.usage?.cost != null\n              ? { cost: response.usage.cost }\n              : {}),\n            ...(response.usage?.prompt_tokens_details?.cached_tokens != null\n              ? {\n                  promptTokensDetails: {\n                    cachedTokens:\n                      response.usage.prompt_tokens_details.cached_tokens,\n                  },\n                }\n              : {}),\n            ...(response.usage?.completion_tokens_details?.reasoning_tokens !=\n            null\n              ? {\n                  completionTokensDetails: {\n                    reasoningTokens:\n                      response.usage.completion_tokens_details.reasoning_tokens,\n                  },\n                }\n              : {}),\n            ...(response.usage?.cost_details?.upstream_inference_cost != null\n              ? {\n                  costDetails: {\n                    upstreamInferenceCost:\n                      response.usage.cost_details.upstream_inference_cost,\n                  },\n                }\n              : {}),\n          },\n        }),\n      },\n      response: {\n        headers: responseHeaders,\n      },\n    };\n  }\n\n  async doStream(\n    options: LanguageModelV3CallOptions,\n  ): Promise<Awaited<ReturnType<LanguageModelV3['doStream']>>> {\n    const providerOptions = options.providerOptions || {};\n    const openrouterOptions = providerOptions.openrouter || {};\n\n    const args = {\n      ...this.getArgs(options),\n      ...openrouterOptions,\n    };\n\n    const { value: response, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), options.headers),\n      body: {\n        ...args,\n        stream: true,\n\n        // only include stream_options when in strict compatibility mode:\n        stream_options:\n          this.config.compatibility === 'strict'\n            ? { include_usage: true }\n            : undefined,\n      },\n      failedResponseHandler: openrouterFailedResponseHandler,\n      successfulResponseHandler: createEventSourceResponseHandler(\n        OpenRouterCompletionChunkSchema,\n      ),\n      abortSignal: options.abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    let streamError: unknown;\n    const safeResponse = withStreamErrorHandling(response, (err) => {\n      streamError = err;\n    });\n\n    let finishReason: LanguageModelV3FinishReason = createFinishReason('other');\n    const usage: LanguageModelV3Usage = {\n      inputTokens: {\n        total: undefined,\n        noCache: undefined,\n        cacheRead: undefined,\n        cacheWrite: undefined,\n      },\n      outputTokens: {\n        total: undefined,\n        text: undefined,\n        reasoning: undefined,\n      },\n      raw: undefined,\n    };\n\n    const openrouterUsage: Partial<OpenRouterUsageAccounting> = {};\n    let provider: string | undefined;\n\n    // Track raw usage from the API response for usage.raw\n    let rawUsage: JSONObject | undefined;\n\n    return {\n      stream: safeResponse.pipeThrough(\n        new TransformStream<\n          ParseResult<z.infer<typeof OpenRouterCompletionChunkSchema>>,\n          LanguageModelV3StreamPart\n        >({\n          transform(chunk, controller) {\n            // Emit raw chunk if requested (before anything else)\n            if (options.includeRawChunks) {\n              controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n            }\n\n            // handle failed chunk parsing / validation:\n            if (!chunk.success) {\n              finishReason = createFinishReason('error');\n              controller.enqueue({ type: 'error', error: chunk.error });\n              return;\n            }\n\n            const value = chunk.value;\n\n            // handle error chunks:\n            if ('error' in value) {\n              finishReason = createFinishReason('error');\n              controller.enqueue({ type: 'error', error: value.error });\n              return;\n            }\n\n            if (value.provider) {\n              provider = value.provider;\n            }\n\n            if (value.usage != null) {\n              const computed = computeTokenUsage(value.usage);\n              Object.assign(usage.inputTokens, computed.inputTokens);\n              Object.assign(usage.outputTokens, computed.outputTokens);\n\n              rawUsage = value.usage as JSONObject;\n\n              const promptTokens = value.usage.prompt_tokens ?? 0;\n              const completionTokens = value.usage.completion_tokens ?? 0;\n              openrouterUsage.promptTokens = promptTokens;\n\n              if (value.usage.prompt_tokens_details) {\n                openrouterUsage.promptTokensDetails = {\n                  cachedTokens:\n                    value.usage.prompt_tokens_details.cached_tokens ?? 0,\n                };\n              }\n\n              openrouterUsage.completionTokens = completionTokens;\n              if (value.usage.completion_tokens_details) {\n                openrouterUsage.completionTokensDetails = {\n                  reasoningTokens:\n                    value.usage.completion_tokens_details.reasoning_tokens ?? 0,\n                };\n              }\n\n              if (value.usage.cost != null) {\n                openrouterUsage.cost = value.usage.cost;\n              }\n              openrouterUsage.totalTokens = value.usage.total_tokens;\n              const upstreamInferenceCost =\n                value.usage.cost_details?.upstream_inference_cost;\n              if (upstreamInferenceCost != null) {\n                openrouterUsage.costDetails = {\n                  upstreamInferenceCost,\n                };\n              }\n            }\n\n            const choice = value.choices[0];\n\n            if (choice?.finish_reason != null) {\n              finishReason = mapOpenRouterFinishReason(choice.finish_reason);\n            }\n\n            if (choice?.text != null) {\n              controller.enqueue({\n                type: 'text-delta',\n                delta: choice.text,\n                id: generateId(),\n              });\n            }\n          },\n\n          flush(controller) {\n            if (streamError != null) {\n              finishReason = createFinishReason('error');\n              controller.enqueue({ type: 'error', error: streamError });\n            }\n\n            // Set raw usage before emitting finish event\n            usage.raw = rawUsage;\n\n            const openrouterMetadata: {\n              usage: Partial<OpenRouterUsageAccounting>;\n              provider?: string;\n            } = {\n              usage: openrouterUsage,\n            };\n\n            // Only include provider if it's actually set\n            if (provider !== undefined) {\n              openrouterMetadata.provider = provider;\n            }\n\n            controller.enqueue({\n              type: 'finish',\n              finishReason,\n              usage,\n              providerMetadata: {\n                openrouter: openrouterMetadata,\n              },\n            });\n          },\n        }),\n      ),\n      response: {\n        headers: responseHeaders,\n      },\n    };\n  }\n}\n", "import { z } from 'zod/v4';\n\nconst openrouterEmbeddingUsageSchema = z.object({\n  prompt_tokens: z.number(),\n  total_tokens: z.number(),\n  cost: z.number().optional(),\n});\n\nconst openrouterEmbeddingDataSchema = z.object({\n  object: z.literal('embedding'),\n  embedding: z.array(z.number()),\n  index: z.number().optional(),\n});\n\nexport const OpenRouterEmbeddingResponseSchema = z.object({\n  id: z.string().optional(),\n  object: z.literal('list'),\n  data: z.array(openrouterEmbeddingDataSchema),\n  model: z.string(),\n  provider: z.string().optional(),\n  usage: openrouterEmbeddingUsageSchema.optional(),\n});\n\nexport type OpenRouterEmbeddingResponse = z.infer<\n  typeof OpenRouterEmbeddingResponseSchema\n>;\n", "import type {\n  EmbeddingModelV3,\n  SharedV3Headers,\n  SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type {\n  OpenRouterEmbeddingModelId,\n  OpenRouterEmbeddingSettings,\n} from '../types/openrouter-embedding-settings';\n\nimport {\n  combineHeaders,\n  createJsonResponseHandler,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { openrouterFailedResponseHandler } from '../schemas/error-response';\nimport { OpenRouterProviderMetadataSchema } from '../schemas/provider-metadata';\nimport { OpenRouterEmbeddingResponseSchema } from './schemas';\n\ntype OpenRouterEmbeddingConfig = {\n  provider: string;\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: typeof fetch;\n  extraBody?: Record<string, unknown>;\n};\n\nexport class OpenRouterEmbeddingModel implements EmbeddingModelV3 {\n  readonly specificationVersion = 'v3' as const;\n  readonly provider = 'openrouter';\n  readonly modelId: OpenRouterEmbeddingModelId;\n  readonly settings: OpenRouterEmbeddingSettings;\n  readonly maxEmbeddingsPerCall = undefined;\n  readonly supportsParallelCalls = true;\n\n  private readonly config: OpenRouterEmbeddingConfig;\n\n  constructor(\n    modelId: OpenRouterEmbeddingModelId,\n    settings: OpenRouterEmbeddingSettings,\n    config: OpenRouterEmbeddingConfig,\n  ) {\n    this.modelId = modelId;\n    this.settings = settings;\n    this.config = config;\n  }\n\n  async doEmbed(options: {\n    values: Array<string>;\n    abortSignal?: AbortSignal;\n    headers?: Record<string, string | undefined>;\n  }): Promise<{\n    embeddings: Array<Array<number>>;\n    usage?: { tokens: number };\n    providerMetadata?: SharedV3ProviderMetadata;\n    response?: {\n      headers?: SharedV3Headers;\n      body?: unknown;\n    };\n    warnings: Array<import('@ai-sdk/provider').SharedV3Warning>;\n  }> {\n    const { values, abortSignal, headers } = options;\n\n    const args = {\n      model: this.modelId,\n      input: values,\n      user: this.settings.user,\n      provider: this.settings.provider,\n      ...this.config.extraBody,\n      ...this.settings.extraBody,\n    };\n\n    const { value: responseValue, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/embeddings',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), headers),\n      body: args,\n      failedResponseHandler: openrouterFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        OpenRouterEmbeddingResponseSchema,\n      ),\n      abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    return {\n      embeddings: responseValue.data.map((item) => item.embedding),\n      usage: responseValue.usage\n        ? { tokens: responseValue.usage.prompt_tokens }\n        : undefined,\n      providerMetadata: {\n        openrouter: OpenRouterProviderMetadataSchema.parse({\n          provider: responseValue.provider ?? '',\n          usage: {\n            promptTokens: responseValue.usage?.prompt_tokens ?? 0,\n            completionTokens: 0,\n            totalTokens: responseValue.usage?.total_tokens ?? 0,\n            ...(responseValue.usage?.cost != null\n              ? { cost: responseValue.usage.cost }\n              : {}),\n          },\n        }),\n      },\n      response: {\n        headers: responseHeaders,\n        body: responseValue,\n      },\n      warnings: [],\n    };\n  }\n}\n", "import type { OpenRouterProviderSettings } from './provider';\nimport type {\n  OpenRouterChatModelId,\n  OpenRouterChatSettings,\n} from './types/openrouter-chat-settings';\nimport type {\n  OpenRouterCompletionModelId,\n  OpenRouterCompletionSettings,\n} from './types/openrouter-completion-settings';\nimport type {\n  OpenRouterEmbeddingModelId,\n  OpenRouterEmbeddingSettings,\n} from './types/openrouter-embedding-settings';\n\nimport { loadApiKey, withoutTrailingSlash } from '@ai-sdk/provider-utils';\nimport { OpenRouterChatLanguageModel } from './chat';\nimport { OpenRouterCompletionLanguageModel } from './completion';\nimport { OpenRouterEmbeddingModel } from './embedding';\n\n/**\n@deprecated Use `createOpenRouter` instead.\n */\nexport class OpenRouter {\n  /**\nUse a different URL prefix for API calls, e.g. to use proxy servers.\nThe default prefix is `https://openrouter.ai/api/v1`.\n   */\n  readonly baseURL: string;\n\n  /**\nAPI key that is being sent using the `Authorization` header.\nIt defaults to the `OPENROUTER_API_KEY` environment variable.\n */\n  readonly apiKey?: string;\n\n  /**\nCustom headers to include in the requests.\n   */\n  readonly headers?: Record<string, string>;\n\n  /**\n   * Record of provider slugs to API keys for injecting into provider routing.\n   */\n  readonly api_keys?: Record<string, string>;\n\n  /**\n   * App display name for the `X-OpenRouter-Title` header.\n   */\n  readonly appName?: string;\n\n  /**\n   * App URL for the `HTTP-Referer` header.\n   */\n  readonly appUrl?: string;\n\n  /**\n   * Creates a new OpenRouter provider instance.\n   */\n  constructor(options: OpenRouterProviderSettings = {}) {\n    this.baseURL =\n      withoutTrailingSlash(options.baseURL ?? options.baseUrl) ??\n      'https://openrouter.ai/api/v1';\n    this.apiKey = options.apiKey;\n    this.headers = options.headers;\n    this.api_keys = options.api_keys;\n    this.appName = options.appName;\n    this.appUrl = options.appUrl;\n  }\n\n  private get baseConfig() {\n    return {\n      baseURL: this.baseURL,\n      headers: () => ({\n        Authorization: `Bearer ${loadApiKey({\n          apiKey: this.apiKey,\n          environmentVariableName: 'OPENROUTER_API_KEY',\n          description: 'OpenRouter',\n        })}`,\n        ...(this.appName && { 'X-OpenRouter-Title': this.appName }),\n        ...(this.appUrl && { 'HTTP-Referer': this.appUrl }),\n        ...this.headers,\n        ...(this.api_keys &&\n          Object.keys(this.api_keys).length > 0 && {\n            'X-Provider-API-Keys': JSON.stringify(this.api_keys),\n          }),\n      }),\n    };\n  }\n\n  chat(modelId: OpenRouterChatModelId, settings: OpenRouterChatSettings = {}) {\n    return new OpenRouterChatLanguageModel(modelId, settings, {\n      provider: 'openrouter.chat',\n      ...this.baseConfig,\n      compatibility: 'strict',\n      url: ({ path }) => `${this.baseURL}${path}`,\n    });\n  }\n\n  completion(\n    modelId: OpenRouterCompletionModelId,\n    settings: OpenRouterCompletionSettings = {},\n  ) {\n    return new OpenRouterCompletionLanguageModel(modelId, settings, {\n      provider: 'openrouter.completion',\n      ...this.baseConfig,\n      compatibility: 'strict',\n      url: ({ path }) => `${this.baseURL}${path}`,\n    });\n  }\n\n  textEmbeddingModel(\n    modelId: OpenRouterEmbeddingModelId,\n    settings: OpenRouterEmbeddingSettings = {},\n  ) {\n    return new OpenRouterEmbeddingModel(modelId, settings, {\n      provider: 'openrouter.embedding',\n      ...this.baseConfig,\n      url: ({ path }) => `${this.baseURL}${path}`,\n    });\n  }\n\n  /**\n   * @deprecated Use textEmbeddingModel instead\n   */\n  embedding(\n    modelId: OpenRouterEmbeddingModelId,\n    settings: OpenRouterEmbeddingSettings = {},\n  ) {\n    return this.textEmbeddingModel(modelId, settings);\n  }\n}\n", "import { z } from 'zod/v4';\n\nexport const OpenRouterImageResponseSchema = z\n  .object({\n    id: z.string().optional(),\n    object: z.string().optional(),\n    created: z.number().optional(),\n    model: z.string(),\n    choices: z.array(\n      z\n        .object({\n          index: z.number(),\n          message: z\n            .object({\n              role: z.string(),\n              content: z.string().nullable().optional(),\n              images: z\n                .array(\n                  z\n                    .object({\n                      type: z.literal('image_url'),\n                      image_url: z.object({\n                        url: z.string(),\n                      }),\n                    })\n                    .passthrough(),\n                )\n                .optional(),\n            })\n            .passthrough(),\n          finish_reason: z.string().nullable().optional(),\n        })\n        .passthrough(),\n    ),\n    usage: z\n      .object({\n        prompt_tokens: z.number(),\n        completion_tokens: z.number(),\n        total_tokens: z.number(),\n      })\n      .passthrough()\n      .optional(),\n  })\n  .passthrough();\n\nexport type OpenRouterImageResponse = z.infer<\n  typeof OpenRouterImageResponseSchema\n>;\n", "import type {\n  ImageModelV3,\n  ImageModelV3CallOptions,\n  ImageModelV3File,\n  ImageModelV3ProviderMetadata,\n  ImageModelV3Usage,\n  SharedV3Warning,\n} from '@ai-sdk/provider';\nimport type {\n  OpenRouterImageModelId,\n  OpenRouterImageSettings,\n} from '../types/openrouter-image-settings';\n\nimport {\n  NoContentGeneratedError,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createJsonResponseHandler,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { buildFileDataUrl, getBase64FromDataUrl } from '../chat/file-url-utils';\nimport { openrouterFailedResponseHandler } from '../schemas/error-response';\nimport { OpenRouterImageResponseSchema } from './schemas';\n\ntype OpenRouterImageConfig = {\n  provider: string;\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: typeof fetch;\n  extraBody?: Record<string, unknown>;\n};\n\nexport class OpenRouterImageModel implements ImageModelV3 {\n  readonly specificationVersion = 'v3' as const;\n  readonly provider = 'openrouter';\n  readonly modelId: OpenRouterImageModelId;\n  readonly settings: OpenRouterImageSettings;\n  readonly maxImagesPerCall = 1;\n\n  private readonly config: OpenRouterImageConfig;\n\n  constructor(\n    modelId: OpenRouterImageModelId,\n    settings: OpenRouterImageSettings,\n    config: OpenRouterImageConfig,\n  ) {\n    this.modelId = modelId;\n    this.settings = settings;\n    this.config = config;\n  }\n\n  async doGenerate(options: ImageModelV3CallOptions): Promise<{\n    images: Array<string>;\n    warnings: Array<SharedV3Warning>;\n    providerMetadata?: ImageModelV3ProviderMetadata;\n    response: {\n      timestamp: Date;\n      modelId: string;\n      headers: Record<string, string> | undefined;\n    };\n    usage?: ImageModelV3Usage;\n  }> {\n    const {\n      prompt,\n      n,\n      size,\n      aspectRatio,\n      seed,\n      files,\n      mask,\n      abortSignal,\n      headers,\n      providerOptions,\n    } = options;\n\n    const openrouterOptions =\n      (providerOptions?.openrouter as Record<string, unknown>) || {};\n\n    const warnings: SharedV3Warning[] = [];\n\n    if (mask !== undefined) {\n      throw new UnsupportedFunctionalityError({\n        functionality: 'image inpainting (mask parameter)',\n      });\n    }\n\n    if (n > 1) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'n > 1',\n        details: `OpenRouter image generation returns 1 image per call. Requested ${n} images.`,\n      });\n    }\n\n    if (size !== undefined) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'size',\n        details:\n          'Use aspectRatio instead. Size parameter is not supported by OpenRouter image generation.',\n      });\n    }\n\n    const imageConfig: Record<string, string> | undefined =\n      aspectRatio !== undefined ? { aspect_ratio: aspectRatio } : undefined;\n\n    const hasFiles = files !== undefined && files.length > 0;\n\n    const userContent: string | Array<Record<string, unknown>> = hasFiles\n      ? [\n          ...files.map((file: ImageModelV3File) =>\n            convertImageFileToContentPart(file),\n          ),\n          { type: 'text', text: prompt ?? '' },\n        ]\n      : (prompt ?? '');\n\n    const body: Record<string, unknown> = {\n      model: this.modelId,\n      messages: [\n        {\n          role: 'user',\n          content: userContent,\n        },\n      ],\n      modalities: ['image', 'text'],\n      ...(imageConfig !== undefined && { image_config: imageConfig }),\n      ...(seed !== undefined && { seed }),\n      ...(this.settings.user !== undefined && { user: this.settings.user }),\n      ...(this.settings.provider !== undefined && {\n        provider: this.settings.provider,\n      }),\n      ...this.config.extraBody,\n      ...this.settings.extraBody,\n      ...openrouterOptions,\n    };\n\n    const { value: responseValue, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/chat/completions',\n        modelId: this.modelId,\n      }),\n      headers: combineHeaders(this.config.headers(), headers),\n      body,\n      failedResponseHandler: openrouterFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        OpenRouterImageResponseSchema,\n      ),\n      abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const choice = responseValue.choices[0];\n\n    if (!choice) {\n      throw new NoContentGeneratedError({\n        message: 'No choice in response',\n      });\n    }\n\n    const images: string[] = [];\n\n    if (choice.message?.images) {\n      for (const image of choice.message.images) {\n        const dataUrl = image.image_url.url;\n        images.push(getBase64FromDataUrl(dataUrl));\n      }\n    }\n\n    const usage: ImageModelV3Usage | undefined = responseValue.usage\n      ? {\n          inputTokens: responseValue.usage.prompt_tokens,\n          outputTokens: responseValue.usage.completion_tokens,\n          totalTokens: responseValue.usage.total_tokens,\n        }\n      : undefined;\n\n    return {\n      images,\n      warnings,\n      response: {\n        timestamp: new Date(),\n        modelId: responseValue.model,\n        headers: responseHeaders as Record<string, string> | undefined,\n      },\n      usage,\n    };\n  }\n}\n\nconst DEFAULT_IMAGE_MEDIA_TYPE = 'image/png';\n\nfunction convertImageFileToContentPart(\n  file: ImageModelV3File,\n): Record<string, unknown> {\n  if (file.type === 'url') {\n    return {\n      type: 'image_url',\n      image_url: { url: file.url },\n    };\n  }\n\n  const url = buildFileDataUrl({\n    data: file.data,\n    mediaType: file.mediaType,\n    defaultMediaType: DEFAULT_IMAGE_MEDIA_TYPE,\n  });\n\n  return {\n    type: 'image_url',\n    image_url: { url },\n  };\n}\n", "import type { Engine } from '../types/openrouter-api-types';\n\nimport { createProviderToolFactory } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n/**\n * Input schema for the OpenRouter web search server tool.\n *\n * @see https://openrouter.ai/docs/guides/features/server-tools/web-search\n */\nconst webSearchInputSchema = z.object({\n  /** Search results returned by the server tool */\n  results: z.array(z.unknown()).optional(),\n});\n\ntype WebSearchInput = z.infer<typeof webSearchInputSchema>;\n\n/**\n * Configuration args for the web search provider tool.\n * These are mapped to snake_case in the API request.\n */\ntype WebSearchArgs = {\n  /** Maximum number of search results to include */\n  maxResults?: number;\n  /** Custom search prompt to guide the search query */\n  searchPrompt?: string;\n  /** Search engine to use: 'auto', 'native', or 'exa' */\n  engine?: 'auto' | Engine;\n};\n\n/**\n * Creates the `openrouter.tools.webSearch` provider tool factory.\n *\n * Usage:\n * ```ts\n * const openrouter = createOpenRouter();\n * const result = await generateText({\n *   model: openrouter('openai/gpt-4o'),\n *   tools: {\n *     web_search: openrouter.tools.webSearch({ maxResults: 5 }),\n *   },\n *   prompt: 'What are the latest news?',\n * });\n * ```\n */\nexport const webSearch = createProviderToolFactory<\n  WebSearchInput,\n  WebSearchArgs\n>({\n  id: 'openrouter.web_search',\n  inputSchema: webSearchInputSchema,\n});\n", "/**\n * Removes entries from a record where the value is null or undefined.\n * @param record - The input object whose entries may be null or undefined.\n * @returns A new object containing only entries with non-null and non-undefined values.\n */\nexport function removeUndefinedEntries<T>(\n  record: Record<string, T | undefined>,\n): Record<string, T> {\n  return Object.fromEntries(\n    Object.entries(record).filter(([, value]) => value != null),\n  ) as Record<string, T>;\n}\n", "import { removeUndefinedEntries } from '@/src/utils/remove-undefined';\n\n/**\n * Normalizes HeadersInit to a plain object.\n * Handles Headers objects, array-of-tuples, and plain objects.\n * @param headers - The headers in any HeadersInit format.\n * @returns A plain object with string keys and values.\n */\nfunction normalizeHeaders(\n  headers: HeadersInit | Record<string, string | undefined> | undefined,\n): Record<string, string | undefined> {\n  if (!headers) {\n    return {};\n  }\n  if (headers instanceof Headers) {\n    return Object.fromEntries(headers.entries());\n  }\n  if (Array.isArray(headers)) {\n    return Object.fromEntries(headers);\n  }\n  return headers as Record<string, string | undefined>;\n}\n\n/**\n * Finds a header key in a case-insensitive manner.\n * @param headers - The headers object to search.\n * @param targetKey - The key to find (case-insensitive).\n * @returns The actual key in the headers object, or undefined if not found.\n */\nfunction findHeaderKey(\n  headers: Record<string, string>,\n  targetKey: string,\n): string | undefined {\n  const lowerTarget = targetKey.toLowerCase();\n  return Object.keys(headers).find((key) => key.toLowerCase() === lowerTarget);\n}\n\n/**\n * Sets the user-agent header, respecting user-specified values.\n * If a user explicitly provides a User-Agent header (any case), it is used verbatim.\n * If no User-Agent header is provided, the suffix parts are used as the default.\n * Automatically removes undefined entries from the headers.\n *\n * @param headers - The original headers.\n * @param userAgentSuffixParts - The parts to use as the default user-agent if none is provided.\n * @returns The new headers with the `user-agent` header set.\n */\nexport function withUserAgentSuffix(\n  headers: HeadersInit | Record<string, string | undefined> | undefined,\n  ...userAgentSuffixParts: string[]\n): Record<string, string> {\n  const normalizedHeaders = normalizeHeaders(headers);\n  const cleanedHeaders = removeUndefinedEntries(normalizedHeaders);\n\n  // Find user-agent header with case-insensitive lookup\n  const existingUserAgentKey = findHeaderKey(cleanedHeaders, 'user-agent');\n  const existingUserAgentValue = existingUserAgentKey\n    ? cleanedHeaders[existingUserAgentKey]\n    : undefined;\n\n  // If user provided a non-empty User-Agent, use it verbatim\n  // Otherwise, use the SDK identifier as the default\n  const userAgent = existingUserAgentValue?.trim()\n    ? existingUserAgentValue\n    : userAgentSuffixParts.filter(Boolean).join(' ');\n\n  // Remove any existing user-agent header (regardless of case) and add normalized one\n  const headersWithoutUserAgent = Object.fromEntries(\n    Object.entries(cleanedHeaders).filter(\n      ([key]) => key.toLowerCase() !== 'user-agent',\n    ),\n  );\n\n  return {\n    ...headersWithoutUserAgent,\n    'user-agent': userAgent,\n  };\n}\n", "// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  __PACKAGE_VERSION__ === undefined ? '0.0.0-test' : __PACKAGE_VERSION__;\n", "import { z } from 'zod/v4';\n\nexport const VideoGenerationSubmitResponseSchema = z\n  .object({\n    id: z.string(),\n    generation_id: z.string().optional(),\n    polling_url: z.string(),\n    status: z.string(),\n  })\n  .passthrough();\n\nexport type VideoGenerationSubmitResponse = z.infer<\n  typeof VideoGenerationSubmitResponseSchema\n>;\n\nexport const VideoGenerationPollResponseSchema = z\n  .object({\n    id: z.string(),\n    generation_id: z.string().optional(),\n    polling_url: z.string(),\n    status: z.string(),\n    unsigned_urls: z.array(z.string()).optional(),\n    usage: z\n      .object({\n        cost: z.number().optional(),\n        is_byok: z.boolean().optional(),\n      })\n      .passthrough()\n      .optional(),\n    error: z.string().optional(),\n  })\n  .passthrough();\n\nexport type VideoGenerationPollResponse = z.infer<\n  typeof VideoGenerationPollResponseSchema\n>;\n", "import type {\n  SharedV3ProviderMetadata,\n  SharedV3Warning,\n  Experimental_VideoModelV3 as VideoModelV3,\n  Experimental_VideoModelV3CallOptions as VideoModelV3CallOptions,\n  Experimental_VideoModelV3File as VideoModelV3File,\n  Experimental_VideoModelV3VideoData as VideoModelV3VideoData,\n} from '@ai-sdk/provider';\nimport type {\n  OpenRouterVideoModelId,\n  OpenRouterVideoSettings,\n} from '../types/openrouter-video-settings';\n\nimport { APICallError } from '@ai-sdk/provider';\nimport {\n  combineHeaders,\n  createJsonResponseHandler,\n  delay,\n  getFromApi,\n  postJsonToApi,\n} from '@ai-sdk/provider-utils';\nimport { buildFileDataUrl } from '../chat/file-url-utils';\nimport { openrouterFailedResponseHandler } from '../schemas/error-response';\nimport {\n  VideoGenerationPollResponseSchema,\n  VideoGenerationSubmitResponseSchema,\n} from './schemas';\n\ntype OpenRouterVideoConfig = {\n  provider: string;\n  headers: () => Record<string, string | undefined>;\n  url: (options: { modelId: string; path: string }) => string;\n  fetch?: typeof fetch;\n  extraBody?: Record<string, unknown>;\n};\n\nconst DEFAULT_POLL_INTERVAL_MS = 2000;\nconst DEFAULT_MAX_POLL_TIME_MS = 600_000;\n\nexport class OpenRouterVideoModel implements VideoModelV3 {\n  readonly specificationVersion = 'v3';\n  readonly provider = 'openrouter';\n  readonly modelId: OpenRouterVideoModelId;\n  readonly settings: OpenRouterVideoSettings;\n  readonly maxVideosPerCall = 1;\n\n  private readonly config: OpenRouterVideoConfig;\n\n  constructor(\n    modelId: OpenRouterVideoModelId,\n    settings: OpenRouterVideoSettings,\n    config: OpenRouterVideoConfig,\n  ) {\n    this.modelId = modelId;\n    this.settings = settings;\n    this.config = config;\n  }\n\n  async doGenerate(options: VideoModelV3CallOptions): Promise<{\n    videos: Array<VideoModelV3VideoData>;\n    warnings: Array<SharedV3Warning>;\n    providerMetadata?: SharedV3ProviderMetadata;\n    response: {\n      timestamp: Date;\n      modelId: string;\n      headers: Record<string, string> | undefined;\n    };\n  }> {\n    const {\n      prompt,\n      n,\n      aspectRatio,\n      resolution,\n      duration,\n      seed,\n      image,\n      abortSignal,\n      headers,\n      providerOptions,\n    } = options;\n\n    const warnings: SharedV3Warning[] = [];\n\n    if (n > 1) {\n      warnings.push({\n        type: 'unsupported',\n        feature: 'n > 1',\n        details: `OpenRouter video generation returns 1 video per call. Requested ${n} videos.`,\n      });\n    }\n\n    const body: Record<string, unknown> = {\n      model: this.modelId,\n      prompt: prompt ?? '',\n      ...(aspectRatio !== undefined && { aspect_ratio: aspectRatio }),\n      ...(resolution !== undefined && { size: resolution }),\n      ...(duration !== undefined && { duration }),\n      ...(seed !== undefined && { seed }),\n      ...(this.settings.generateAudio !== undefined && {\n        generate_audio: this.settings.generateAudio,\n      }),\n      ...(image !== undefined && {\n        frame_images: [convertImageToFrameImage(image)],\n      }),\n      ...this.config.extraBody,\n      ...this.settings.extraBody,\n      ...providerOptions.openrouter,\n    };\n\n    const mergedHeaders = combineHeaders(this.config.headers(), headers);\n\n    const { value: submitResponse, responseHeaders } = await postJsonToApi({\n      url: this.config.url({\n        path: '/videos',\n        modelId: this.modelId,\n      }),\n      headers: mergedHeaders,\n      body,\n      failedResponseHandler: openrouterFailedResponseHandler,\n      successfulResponseHandler: createJsonResponseHandler(\n        VideoGenerationSubmitResponseSchema,\n      ),\n      abortSignal,\n      fetch: this.config.fetch,\n    });\n\n    const pollIntervalMs =\n      this.settings.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n    const maxPollTimeMs =\n      this.settings.maxPollTimeMs ?? DEFAULT_MAX_POLL_TIME_MS;\n\n    const pollResult = await this.pollUntilComplete({\n      jobId: submitResponse.id,\n      headers: mergedHeaders,\n      abortSignal,\n      pollIntervalMs,\n      maxPollTimeMs,\n    });\n\n    const videos: VideoModelV3VideoData[] = [];\n\n    if (pollResult.unsigned_urls) {\n      for (const url of pollResult.unsigned_urls) {\n        videos.push({\n          type: 'url',\n          url,\n          mediaType: 'video/mp4',\n        });\n      }\n    }\n\n    const providerMetadata: SharedV3ProviderMetadata = {\n      openrouter: {\n        generationId: pollResult.generation_id ?? null,\n        cost: pollResult.usage?.cost ?? null,\n      },\n    };\n\n    return {\n      videos,\n      warnings,\n      providerMetadata,\n      response: {\n        timestamp: new Date(),\n        modelId: this.modelId,\n        headers: responseHeaders,\n      },\n    };\n  }\n\n  private async pollUntilComplete({\n    jobId,\n    headers,\n    abortSignal,\n    pollIntervalMs,\n    maxPollTimeMs,\n  }: {\n    jobId: string;\n    headers: Record<string, string | undefined>;\n    abortSignal?: AbortSignal;\n    pollIntervalMs: number;\n    maxPollTimeMs: number;\n  }): Promise<{\n    generation_id?: string;\n    unsigned_urls?: string[];\n    usage?: { cost?: number; is_byok?: boolean };\n  }> {\n    const startTime = Date.now();\n\n    while (Date.now() - startTime < maxPollTimeMs) {\n      abortSignal?.throwIfAborted();\n\n      await delay(pollIntervalMs);\n\n      abortSignal?.throwIfAborted();\n\n      const { value: pollResponse } = await getFromApi({\n        url: this.config.url({\n          path: `/videos/${jobId}`,\n          modelId: this.modelId,\n        }),\n        headers,\n        failedResponseHandler: openrouterFailedResponseHandler,\n        successfulResponseHandler: createJsonResponseHandler(\n          VideoGenerationPollResponseSchema,\n        ),\n        abortSignal,\n        fetch: this.config.fetch,\n      });\n\n      if (pollResponse.status === 'completed') {\n        return {\n          generation_id: pollResponse.generation_id,\n          unsigned_urls: pollResponse.unsigned_urls,\n          usage: pollResponse.usage,\n        };\n      }\n\n      if (\n        pollResponse.status === 'failed' ||\n        pollResponse.status === 'dead' ||\n        pollResponse.status === 'cancelled' ||\n        pollResponse.status === 'expired'\n      ) {\n        throw new APICallError({\n          message:\n            pollResponse.error ??\n            `Video generation failed with status: ${pollResponse.status}`,\n          url: this.config.url({\n            path: `/videos/${jobId}`,\n            modelId: this.modelId,\n          }),\n          requestBodyValues: {},\n          statusCode: 500,\n          isRetryable: false,\n        });\n      }\n    }\n\n    throw new APICallError({\n      message: `Video generation timed out after ${maxPollTimeMs}ms`,\n      url: this.config.url({\n        path: `/videos/${jobId}`,\n        modelId: this.modelId,\n      }),\n      requestBodyValues: {},\n      statusCode: 408,\n      isRetryable: true,\n    });\n  }\n}\n\nfunction convertImageToFrameImage(\n  file: VideoModelV3File,\n): Record<string, unknown> {\n  if (file.type === 'url') {\n    return {\n      type: 'image_url',\n      image_url: { url: file.url },\n      frame_type: 'first_frame',\n    };\n  }\n\n  const url = buildFileDataUrl({\n    data: file.data,\n    mediaType: file.mediaType,\n    defaultMediaType: 'image/png',\n  });\n\n  return {\n    type: 'image_url',\n    image_url: { url },\n    frame_type: 'first_frame',\n  };\n}\n", "import type { ProviderV3 } from '@ai-sdk/provider';\nimport type { ProviderToolFactory } from '@ai-sdk/provider-utils';\nimport type { Engine } from './types/openrouter-api-types';\nimport type {\n  OpenRouterChatModelId,\n  OpenRouterChatSettings,\n} from './types/openrouter-chat-settings';\nimport type {\n  OpenRouterCompletionModelId,\n  OpenRouterCompletionSettings,\n} from './types/openrouter-completion-settings';\nimport type {\n  OpenRouterEmbeddingModelId,\n  OpenRouterEmbeddingSettings,\n} from './types/openrouter-embedding-settings';\nimport type {\n  OpenRouterImageModelId,\n  OpenRouterImageSettings,\n} from './types/openrouter-image-settings';\nimport type {\n  OpenRouterVideoModelId,\n  OpenRouterVideoSettings,\n} from './types/openrouter-video-settings';\n\nimport { loadApiKey, withoutTrailingSlash } from '@ai-sdk/provider-utils';\nimport { OpenRouterChatLanguageModel } from './chat';\nimport { OpenRouterCompletionLanguageModel } from './completion';\nimport { OpenRouterEmbeddingModel } from './embedding';\nimport { OpenRouterImageModel } from './image';\nimport { webSearch } from './tool/web-search';\nimport { withUserAgentSuffix } from './utils/with-user-agent-suffix';\nimport { VERSION } from './version';\nimport { OpenRouterVideoModel } from './video';\n\n/**\n * Configuration args for the web search provider tool.\n * These are mapped to snake_case in the API request.\n */\ntype WebSearchToolArgs = {\n  /** Maximum number of search results to include */\n  maxResults?: number;\n  /** Custom search prompt to guide the search query */\n  searchPrompt?: string;\n  /** Search engine to use: 'auto', 'native', or 'exa' */\n  engine?: 'auto' | Engine;\n};\n\nexport type { OpenRouterChatSettings, OpenRouterCompletionSettings };\n\nexport interface OpenRouterProvider extends ProviderV3 {\n  (\n    modelId: OpenRouterChatModelId,\n    settings?: OpenRouterCompletionSettings,\n  ): OpenRouterCompletionLanguageModel;\n  (\n    modelId: OpenRouterChatModelId,\n    settings?: OpenRouterChatSettings,\n  ): OpenRouterChatLanguageModel;\n\n  languageModel(\n    modelId: OpenRouterChatModelId,\n    settings?: OpenRouterCompletionSettings,\n  ): OpenRouterCompletionLanguageModel;\n  languageModel(\n    modelId: OpenRouterChatModelId,\n    settings?: OpenRouterChatSettings,\n  ): OpenRouterChatLanguageModel;\n\n  /**\nCreates an OpenRouter chat model for text generation.\n   */\n  chat(\n    modelId: OpenRouterChatModelId,\n    settings?: OpenRouterChatSettings,\n  ): OpenRouterChatLanguageModel;\n\n  /**\nCreates an OpenRouter completion model for text generation.\n   */\n  completion(\n    modelId: OpenRouterCompletionModelId,\n    settings?: OpenRouterCompletionSettings,\n  ): OpenRouterCompletionLanguageModel;\n\n  /**\nCreates an OpenRouter text embedding model. (AI SDK v5)\n   */\n  textEmbeddingModel(\n    modelId: OpenRouterEmbeddingModelId,\n    settings?: OpenRouterEmbeddingSettings,\n  ): OpenRouterEmbeddingModel;\n\n  /**\nCreates an OpenRouter text embedding model. (AI SDK v4 - deprecated, use textEmbeddingModel instead)\n@deprecated Use textEmbeddingModel instead\n   */\n  embedding(\n    modelId: OpenRouterEmbeddingModelId,\n    settings?: OpenRouterEmbeddingSettings,\n  ): OpenRouterEmbeddingModel;\n\n  /**\nCreates an OpenRouter image model for image generation.\n   */\n  imageModel(\n    modelId: OpenRouterImageModelId,\n    settings?: OpenRouterImageSettings,\n  ): OpenRouterImageModel;\n\n  /**\nCreates an OpenRouter video model for video generation.\n   */\n  videoModel(\n    modelId: OpenRouterVideoModelId,\n    settings?: OpenRouterVideoSettings,\n  ): OpenRouterVideoModel;\n\n  /**\n   * Provider-defined tools for OpenRouter server tools.\n   */\n  readonly tools: {\n    /**\n     * Creates an OpenRouter web search server tool.\n     *\n     * @see https://openrouter.ai/docs/guides/features/server-tools/web-search\n     */\n    webSearch: ProviderToolFactory<unknown, WebSearchToolArgs>;\n  };\n}\n\nexport interface OpenRouterProviderSettings {\n  /**\nBase URL for the OpenRouter API calls.\n     */\n  baseURL?: string;\n\n  /**\n@deprecated Use `baseURL` instead.\n     */\n  baseUrl?: string;\n\n  /**\nAPI key for authenticating requests.\n     */\n  apiKey?: string;\n\n  /**\nCustom headers to include in the requests.\n     */\n  headers?: Record<string, string>;\n\n  /**\nOpenRouter compatibility mode. Should be set to `strict` when using the OpenRouter API,\nand `compatible` when using 3rd party providers. In `compatible` mode, newer\ninformation such as streamOptions are not being sent. Defaults to 'compatible'.\n   */\n  compatibility?: 'strict' | 'compatible';\n\n  /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n    */\n  fetch?: typeof fetch;\n\n  /**\nA JSON object to send as the request body to access OpenRouter features & upstream provider features.\n  */\n  extraBody?: Record<string, unknown>;\n\n  /**\n   * Record of provider slugs to API keys for injecting into provider routing.\n   * Maps provider slugs (e.g. \"anthropic\", \"openai\") to their respective API keys.\n   */\n  api_keys?: Record<string, string>;\n\n  /**\n   * Your app's display name. Sets the `X-OpenRouter-Title` header on\n   * every request for app attribution on the openrouter.ai dashboard.\n   */\n  appName?: string;\n\n  /**\n   * Your app's URL or identifier. Sets the `HTTP-Referer` header on every request,\n   * used to identify your app on the openrouter.ai dashboard.\n   */\n  appUrl?: string;\n}\n\n/**\nCreate an OpenRouter provider instance.\n */\nexport function createOpenRouter(\n  options: OpenRouterProviderSettings = {},\n): OpenRouterProvider {\n  const baseURL =\n    withoutTrailingSlash(options.baseURL ?? options.baseUrl) ??\n    'https://openrouter.ai/api/v1';\n\n  // we default to compatible, because strict breaks providers like Groq:\n  const compatibility = options.compatibility ?? 'compatible';\n\n  const getHeaders = () =>\n    withUserAgentSuffix(\n      {\n        Authorization: `Bearer ${loadApiKey({\n          apiKey: options.apiKey,\n          environmentVariableName: 'OPENROUTER_API_KEY',\n          description: 'OpenRouter',\n        })}`,\n        ...(options.appName && { 'X-OpenRouter-Title': options.appName }),\n        ...(options.appUrl && { 'HTTP-Referer': options.appUrl }),\n        ...options.headers,\n        ...(options.api_keys &&\n          Object.keys(options.api_keys).length > 0 && {\n            'X-Provider-API-Keys': JSON.stringify(options.api_keys),\n          }),\n      },\n      `ai-sdk/openrouter/${VERSION}`,\n    );\n\n  const createChatModel = (\n    modelId: OpenRouterChatModelId,\n    settings: OpenRouterChatSettings = {},\n  ) =>\n    new OpenRouterChatLanguageModel(modelId, settings, {\n      provider: 'openrouter.chat',\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      compatibility,\n      fetch: options.fetch,\n      extraBody: options.extraBody,\n    });\n\n  const createCompletionModel = (\n    modelId: OpenRouterCompletionModelId,\n    settings: OpenRouterCompletionSettings = {},\n  ) =>\n    new OpenRouterCompletionLanguageModel(modelId, settings, {\n      provider: 'openrouter.completion',\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      compatibility,\n      fetch: options.fetch,\n      extraBody: options.extraBody,\n    });\n\n  const createEmbeddingModel = (\n    modelId: OpenRouterEmbeddingModelId,\n    settings: OpenRouterEmbeddingSettings = {},\n  ) =>\n    new OpenRouterEmbeddingModel(modelId, settings, {\n      provider: 'openrouter.embedding',\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n      extraBody: options.extraBody,\n    });\n\n  const createImageModel = (\n    modelId: OpenRouterImageModelId,\n    settings: OpenRouterImageSettings = {},\n  ) =>\n    new OpenRouterImageModel(modelId, settings, {\n      provider: 'openrouter.image',\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n      extraBody: options.extraBody,\n    });\n\n  const createVideoModel = (\n    modelId: OpenRouterVideoModelId,\n    settings: OpenRouterVideoSettings = {},\n  ) =>\n    new OpenRouterVideoModel(modelId, settings, {\n      provider: 'openrouter.video',\n      url: ({ path }) => `${baseURL}${path}`,\n      headers: getHeaders,\n      fetch: options.fetch,\n      extraBody: options.extraBody,\n    });\n\n  const createLanguageModel = (\n    modelId: OpenRouterChatModelId | OpenRouterCompletionModelId,\n    settings?: OpenRouterChatSettings | OpenRouterCompletionSettings,\n  ) => {\n    if (new.target) {\n      throw new Error(\n        'The OpenRouter model function cannot be called with the new keyword.',\n      );\n    }\n\n    if (modelId === 'openai/gpt-3.5-turbo-instruct') {\n      return createCompletionModel(\n        modelId,\n        settings as OpenRouterCompletionSettings,\n      );\n    }\n\n    return createChatModel(modelId, settings as OpenRouterChatSettings);\n  };\n\n  const provider = (\n    modelId: OpenRouterChatModelId | OpenRouterCompletionModelId,\n    settings?: OpenRouterChatSettings | OpenRouterCompletionSettings,\n  ) => createLanguageModel(modelId, settings);\n\n  provider.languageModel = createLanguageModel;\n  provider.chat = createChatModel;\n  provider.completion = createCompletionModel;\n  provider.textEmbeddingModel = createEmbeddingModel;\n  provider.embedding = createEmbeddingModel; // deprecated alias for v4 compatibility\n  provider.imageModel = createImageModel;\n  provider.videoModel = createVideoModel;\n  provider.tools = {\n    webSearch: webSearch,\n  };\n\n  return provider as OpenRouterProvider;\n}\n\n/**\nDefault OpenRouter provider instance. It uses 'strict' compatibility mode.\n */\nexport const openrouter = createOpenRouter({\n  compatibility: 'strict', // strict for OpenRouter API\n});\n", "import { APICallError } from \"ai\"\nimport { isNumber, isObject } from \"utils/typeChecks.ts\"\n\nconst aiCreditLimitReasons = [\"team_monthly_credit_limit_reached\", \"team_daily_credit_limit_reached\"] as const\n\nexport type AiCreditLimitReason = (typeof aiCreditLimitReasons)[number]\n\ninterface AiCreditLimitError {\n\treason: AiCreditLimitReason\n\tmessage: string\n\tusage: number\n\tlimit: number\n}\n\nfunction isCreditLimitReason(value: unknown): value is AiCreditLimitReason {\n\treturn aiCreditLimitReasons.some(r => r === value)\n}\n\n/** Parses a credit-limit error from a parsed JSON response body. */\nexport function parseAiCreditLimitError(body: unknown): AiCreditLimitError | undefined {\n\tif (!isObject(body) || !isObject(body.error)) return undefined\n\tconst data = body.error.data\n\tif (!isObject(data) || !isCreditLimitReason(data.reason) || !isNumber(data.usage) || !isNumber(data.limit)) {\n\t\treturn undefined\n\t}\n\treturn {\n\t\treason: data.reason,\n\t\tmessage: typeof body.error.message === \"string\" ? body.error.message : \"AI credit limit reached\",\n\t\tusage: data.usage,\n\t\tlimit: data.limit,\n\t}\n}\n\n/** Whether the given error is an AI credit-limit error thrown by the AI SDK. */\nexport function isAiCreditLimitError(error: unknown): boolean {\n\tif (!APICallError.isInstance(error)) return false\n\treturn parseAiCreditLimitError(error.data) !== undefined\n}\n", "import { isObject, isString } from \"utils/typeChecks.ts\"\nimport { LanguageModel } from \"./languageModels.ts\"\n\nexport interface ContourOverride {\n\tmodelId: string\n\tenvironment: string\n\tdeployment: string\n}\n\nconst [defaultContourModelId, defaultContourEnvironment] = LanguageModel.Contour.split(\":\")\n\nexport const defaultContourOverride = {\n\tmodelId: defaultContourModelId,\n\tenvironment: defaultContourEnvironment ?? \"production\",\n\tdeployment: \"\",\n} satisfies ContourOverride\n\nfunction getStringField(value: Record<string, unknown>, key: keyof ContourOverride, fallback: string): string {\n\tconst fieldValue = value[key]\n\treturn isString(fieldValue) ? fieldValue : fallback\n}\n\nexport function resolveContourOverride(value: unknown): ContourOverride {\n\tif (!isObject(value)) return { ...defaultContourOverride }\n\n\treturn {\n\t\tmodelId: getStringField(value, \"modelId\", defaultContourOverride.modelId),\n\t\tenvironment: getStringField(value, \"environment\", defaultContourOverride.environment),\n\t\tdeployment: getStringField(value, \"deployment\", defaultContourOverride.deployment),\n\t}\n}\n\nfunction getResolvedValue(value: string, fallback: string): string {\n\tconst trimmed = value.trim()\n\treturn trimmed || fallback\n}\n\nfunction getContourModelId(override: ContourOverride = defaultContourOverride): string {\n\treturn getResolvedValue(override.modelId, defaultContourOverride.modelId)\n}\n\nexport function getContourTarget(override: ContourOverride = defaultContourOverride): string {\n\tconst modelId = getContourModelId(override)\n\tconst deployment = override.deployment.trim()\n\tconst environment = getResolvedValue(override.environment, defaultContourOverride.environment)\n\n\tif (deployment) return `${modelId}:${deployment}`\n\tif (environment === \"production\") return modelId\n\treturn `${modelId}:${environment}`\n}\n\nexport function hasContourDeploymentOverride(override: ContourOverride = defaultContourOverride): boolean {\n\treturn override.deployment.trim().length > 0\n}\n\nexport function hasContourOverride(override: ContourOverride = defaultContourOverride): boolean {\n\treturn (\n\t\tgetContourModelId(override) !== defaultContourOverride.modelId ||\n\t\tgetResolvedValue(override.environment, defaultContourOverride.environment) !== defaultContourOverride.environment ||\n\t\thasContourDeploymentOverride(override)\n\t)\n}\n", "export function tryParseJSON(value: string): unknown {\n\ttry {\n\t\treturn JSON.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n", "import type { ToolResultPart } from \"ai\"\nimport { tryParseJSON } from \"utils/tryParseJSON.ts\"\nimport { isObject, isString } from \"utils/typeChecks.ts\"\n\ntype AISDKToolContentPart = Extract<ToolResultPart[\"output\"], { type: \"content\" }>[\"value\"][number]\ntype AISDKTextContentPart = Extract<AISDKToolContentPart, { type: \"text\" }>\ntype AISDKImageUrlContentPart = Extract<AISDKToolContentPart, { type: \"image-url\" }>\n\ntype OpenAICompatibleTextContentPart = AISDKTextContentPart\ninterface OpenAICompatibleImageUrlContentPart {\n\ttype: \"image_url\"\n\timage_url: { url: AISDKImageUrlContentPart[\"url\"] }\n}\ntype OpenAICompatibleMultimodalContentPart = OpenAICompatibleTextContentPart | OpenAICompatibleImageUrlContentPart\n\n/**\n * The AI SDK OpenAI-compatible provider stringifies `tool` message content arrays\n * before they hit our AI service, which strips vision from tool results. The backend\n * does accept multimodal `tool` message arrays when we keep the OpenAI-style\n * `image_url` parts on the wire, so we repair just that broken serialization\n * step here before sending the request.\n *\n * Temporary workaround: remove this once the OpenAI-compatible SDK provider preserves\n * multimodal tool-result serialization.\n * Issue: https://github.com/OpenRouterTeam/ai-sdk-provider/issues/181#issuecomment-4023238608\n */\nexport function rewriteOpenAICompatibleRequestBody(body: RequestInit[\"body\"]): RequestInit[\"body\"] {\n\tif (!isString(body)) return body\n\n\tconst parsedBody = tryParseJSON(body)\n\tif (!isObject(parsedBody)) return body\n\n\tconst messages = parsedBody.messages\n\tif (!Array.isArray(messages)) return body\n\n\tlet changed = false\n\tconst rewrittenMessages = messages.map(message => {\n\t\tif (!isObject(message) || message.role !== \"tool\") return message\n\n\t\tconst rewrittenContent = rewriteToolMessageContent(message.content)\n\t\tif (rewrittenContent === undefined) return message\n\n\t\tchanged = true\n\t\treturn {\n\t\t\t...message,\n\t\t\tcontent: rewrittenContent,\n\t\t}\n\t})\n\n\tif (!changed) return body\n\n\treturn JSON.stringify({\n\t\t...parsedBody,\n\t\tmessages: rewrittenMessages,\n\t})\n}\n\nfunction rewriteToolMessageContent(content: unknown): OpenAICompatibleMultimodalContentPart[] | undefined {\n\tif (!isString(content)) return undefined\n\n\tconst parsedContent = tryParseJSON(content)\n\tif (!Array.isArray(parsedContent)) return undefined\n\n\tconst rewrittenParts: OpenAICompatibleMultimodalContentPart[] = []\n\tlet hasImage = false\n\n\tfor (const part of parsedContent) {\n\t\tconst rewrittenPart = rewriteToolContentPart(part)\n\t\tif (rewrittenPart === undefined) return undefined\n\t\tif (rewrittenPart === null) continue\n\t\tif (rewrittenPart.type === \"image_url\") hasImage = true\n\t\trewrittenParts.push(rewrittenPart)\n\t}\n\n\treturn hasImage ? rewrittenParts : undefined\n}\n\nfunction rewriteToolContentPart(part: unknown): OpenAICompatibleMultimodalContentPart | null | undefined {\n\tif (!isObject(part)) return undefined\n\n\tswitch (part.type) {\n\t\tcase \"text\":\n\t\t\tif (!isString(part.text)) return undefined\n\t\t\treturn { type: \"text\", text: part.text }\n\t\tcase \"image-url\":\n\t\t\tif (!isString(part.url)) return undefined\n\t\t\treturn { type: \"image_url\", image_url: { url: part.url } }\n\t\tcase \"custom\":\n\t\t\t// Internal structured payload used by transformers. Exclude from provider request body.\n\t\t\treturn null\n\t\tdefault:\n\t\t\treturn undefined\n\t}\n}\n", "import { isProduction } from \"@framerjs/shared\"\nimport { getEngine } from \"document/getEngine.ts\"\nimport type { AIFeatureName } from \"../features.ts\"\n\n/**\n * Full options for creating an OpenRouter trace, including the agent step name.\n */\nexport interface OpenRouterFeatureTraceConfig {\n\t/**\n\t * The feature/use-case being traced, e.g. \"agents\", \"wireframer\", etc. This maps to the \"application\" key in OpenRouter.\n\t */\n\tfeatureName: AIFeatureName\n\t/**\n\t * The specific step or action being traced, e.g. \"wireframer-plan\", \"generate-section-customisations\", etc. This maps to the \"generation_name\" key in OpenRouter.\n\t */\n\tstep: string\n\t/**\n\t * Session ID to group related traces together. This maps to the \"session_id\" key in OpenRouter.\n\t */\n\tsessionId: string\n}\n\n/**\n * Partial options that omit the agent step \u2014 used when drilling through layers\n * before the step name is known. Includes agentName since that is typically\n * known at the session/orchestrator level.\n */\nexport type OpenRouterFeatureStepTraceConfig = Omit<OpenRouterFeatureTraceConfig, \"step\">\n\n/**\n * Standard OpenTelemetry Mapped metadata supported by OpenRouter:\n *\n * https://openrouter.ai/docs/guides/features/broadcast/otel-collector#supported-metadata-keys\n */\nexport interface OpenRouterTraceExtraBody extends Record<string, unknown> {\n\t/**\n\t * Additional metadata and 1st party OTEL keys which OpenRouter will map\n\t */\n\ttrace: OpenRouterVekterTrace\n\n\t/**\n\t * Maps to session.id in OTEL\n\t */\n\tsession_id: string\n\n\t/**\n\t * Maps to user.id in OTEL\n\t */\n\tuser: string\n}\n\nexport function getOpenRouterTraceProjectId(): string {\n\tconst engineProjectId = getEngine()?.stores.projectStore.projectId\n\tif (engineProjectId) return engineProjectId\n\tif (typeof process !== \"undefined\" && process.env.FRAMER_AI_PROJECT_ID) return process.env.FRAMER_AI_PROJECT_ID\n\treturn \"no-engine-exists\"\n}\n\n/**\n * Standard OpenTelemetry Mapped metadata supported by OpenRouter:\n *\n * https://openrouter.ai/docs/guides/features/broadcast/otel-collector#supported-metadata-keys\n */\ninterface OpenRouterStandardMetadata {\n\t/**\n\t * Group multiple requests into a single trace\n\t */\n\ttrace_id: string\n\n\t/**\n\t * Custom name for the root span\n\t */\n\ttrace_name: string\n\n\t/**\n\t * Name for intermediate spans in the hierarchy\n\t */\n\tspan_name?: string\n\n\t/**\n\t * Name for the LLM generation span\n\t */\n\tgeneration_name?: string\n\n\t/**\n\t * Link to an existing span in your trace hierarchy\n\t */\n\tparent_span_id?: string\n}\n\n/**\n * Framer specific metadata for Vekter\n */\ninterface OpenRouterVekterTrace extends OpenRouterStandardMetadata {\n\tapplication: string\n\tenvironment: \"production\" | \"development\"\n\trelease: string\n\n\tstep: string\n\tprojectId: string\n}\n\n/**\n * Creates an OpenRouter OpenTelemetry trace object from the given options.\n *\n * Docs on 1st party keys and usage are here:\n * https://openrouter.ai/docs/guides/features/broadcast/otel-collector#supported-metadata-keys\n */\nexport function createOpenRouterTrace(config: OpenRouterFeatureTraceConfig): OpenRouterTraceExtraBody {\n\tconst engine = getEngine()\n\n\tconst projectId = getOpenRouterTraceProjectId()\n\tconst userId = engine?.stores.sessionStore.user.id ?? \"no-engine-exists\"\n\tconst sessionId = config.sessionId\n\n\treturn {\n\t\tuser: userId,\n\t\tsession_id: sessionId,\n\n\t\ttrace: {\n\t\t\t//\n\t\t\t// OpenRouter/OTEL keys\n\n\t\t\ttrace_id: `${config.featureName}/project-${projectId}/session-${sessionId}`,\n\t\t\ttrace_name: `${config.featureName} ${sessionId}`,\n\t\t\tgeneration_name: config.step,\n\n\t\t\t//\n\t\t\t// Framer keys\n\n\t\t\tapplication: `framer-studio/${config.featureName}`,\n\t\t\tenvironment: isProduction() ? \"production\" : \"development\",\n\t\t\trelease: process.env.VERSION || \"dev\",\n\t\t\tprojectId,\n\n\t\t\t//\n\t\t\t// Vekter specific metadata\n\n\t\t\tstep: config.step,\n\t\t},\n\t}\n}\n", "import { createOpenAI, type OpenAIProvider } from \"@ai-sdk/openai\"\nimport { createOpenAICompatible, type OpenAICompatibleProvider } from \"@ai-sdk/openai-compatible\"\nimport type { JSONObject } from \"@ai-sdk/provider\"\nimport { ApiError } from \"@framerjs/app-shared\"\nimport { assertNever } from \"@framerjs/shared\"\nimport type { OpenRouterChatSettings, OpenRouterProvider } from \"@openrouter/ai-sdk-provider\"\nimport { createOpenRouter } from \"@openrouter/ai-sdk-provider\"\nimport { getEngine } from \"document/getEngine.ts\"\nimport { getServiceMap } from \"environment/domains.ts\"\nimport { assert } from \"library/utils/assert.ts\"\nimport { isObject, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { parseAiCreditLimitError } from \"../aiServiceError.ts\"\nimport {\n\tdefaultContourOverride,\n\tgetContourTarget,\n\thasContourDeploymentOverride,\n\ttype ContourOverride,\n} from \"../contourOverride.ts\"\nimport type { AIFeatureCategory, AIFeatureName } from \"../features.ts\"\nimport { LanguageModel } from \"../languageModels.ts\"\nimport {\n\tgetDefaultReasoningEffortForModel,\n\tgetOpenRouterExtraBodyForEffort,\n\ttype AgentReasoningEffort,\n\ttype OpenRouterExtraBodyForEffort,\n\ttype ProviderForModel,\n} from \"../models.ts\"\nimport { rewriteOpenAICompatibleRequestBody } from \"../openAICompatibleRequestBody.ts\"\nimport {\n\ttype OpenRouterFeatureTraceConfig,\n\ttype OpenRouterTraceExtraBody,\n\tcreateOpenRouterTrace,\n\tgetOpenRouterTraceProjectId,\n} from \"../tracing/openRouterTrace.ts\"\nimport { AiDisabledError, isAiDisabled } from \"./disableAi.ts\"\n\nexport const aiServiceEndpoint = \"/ai/v3/chat/\"\nconst aiServiceBasetenEndpoint = \"/ai/v3/baseten/\"\n\ninterface AIServiceMetadata {\n\tprojectId: string\n\tfeatureCategory: AIFeatureCategory\n\tfeatureName?: AIFeatureName\n\tstep?: string\n\tstepIndex?: number\n\tsessionId?: string\n\tturnId?: string\n\tuserPrompt?: string\n}\n\ninterface OpenRouterTraceExtraBodyV3 extends OpenRouterTraceExtraBody {\n\taiService: AIServiceMetadata\n}\n\ninterface AIServiceRequestBody extends AIServiceMetadata {\n\trequest: Record<string, unknown>\n}\n\ntype AIServiceEnvelopeMetadata = Omit<AIServiceMetadata, \"projectId\"> & { projectId?: string }\n\ntype VekterOpenRouterExtraBody = (OpenRouterTraceExtraBody | OpenRouterTraceExtraBodyV3) & OpenRouterExtraBodyForEffort\n\ninterface VekterOpenRouterExtraBodyConfig extends OpenRouterFeatureTraceConfig {\n\tfeatureCategory?: AIServiceMetadata[\"featureCategory\"]\n\tstepIndex?: AIServiceMetadata[\"stepIndex\"]\n\tturnId?: AIServiceMetadata[\"turnId\"]\n\tuserPrompt?: AIServiceMetadata[\"userPrompt\"]\n\tmodel?: LanguageModel\n\treasoningEffort?: AgentReasoningEffort\n}\n\nexport function createVekterOpenRouterExtraBody(config: VekterOpenRouterExtraBodyConfig): VekterOpenRouterExtraBody {\n\tconst projectId = getOpenRouterTraceProjectId()\n\tconst traceExtraBody = createOpenRouterTrace(config)\n\tconst effortExtraBody = !isUndefined(config.model)\n\t\t? getOpenRouterExtraBodyForEffort(config.reasoningEffort, config.model)\n\t\t: undefined\n\n\treturn {\n\t\t...traceExtraBody,\n\t\t...effortExtraBody,\n\t\taiService: {\n\t\t\tprojectId: projectId,\n\t\t\tfeatureCategory: config.featureCategory ?? \"canvas\",\n\t\t\tfeatureName: config.featureName,\n\t\t\tstep: config.step,\n\t\t\tstepIndex: config.stepIndex,\n\t\t\t// Only agent turn metadata needs aiService.sessionId; all requests already carry session_id via traceExtraBody.\n\t\t\tsessionId: config.turnId || config.userPrompt ? config.sessionId : undefined,\n\t\t\tturnId: config.turnId,\n\t\t\tuserPrompt: config.userPrompt,\n\t\t},\n\t}\n}\n\nfunction isOpenRouterTraceExtraBodyV3(body: Record<string, unknown>): body is OpenRouterTraceExtraBodyV3 {\n\treturn \"aiService\" in body && body.aiService !== null && typeof body.aiService === \"object\"\n}\n\nexport function wrapAIServiceRequestBody(body: BodyInit | null | undefined) {\n\tif (!isString(body)) return body\n\n\tconst parsedBody = JSON.parse(body) as Record<string, unknown>\n\tif (!isOpenRouterTraceExtraBodyV3(parsedBody)) {\n\t\tthrow new Error(\"Expected OpenRouter requests to include aiService metadata when using the v3 AI service endpoint.\")\n\t}\n\n\tconst { aiService, ...rest } = parsedBody\n\treturn JSON.stringify({\n\t\t...aiService,\n\t\trequest: rest,\n\t} satisfies AIServiceRequestBody)\n}\n\ninterface CachedAccessToken {\n\taccessToken: string\n\texpiresAt: Date\n}\n\nlet cachedAccessToken: CachedAccessToken | null = null\n\nconst EXPIRATION_BUFFER = 30_000\n\nfunction getAccessTokenFromEnvironment(): { apiHost: string; accessToken: string } | undefined {\n\tif (typeof process === \"undefined\") return undefined\n\tconst accessToken = process.env.FRAMER_AI_ACCESS_TOKEN\n\tif (!accessToken) return undefined\n\n\treturn {\n\t\tapiHost: process.env.FRAMER_AI_API_BASE_URL ?? getServiceMap().api,\n\t\taccessToken,\n\t}\n}\n\nasync function getAccessToken() {\n\tconst apiHost = getServiceMap().api\n\n\tconst environmentAccessToken = getAccessTokenFromEnvironment()\n\tif (environmentAccessToken) {\n\t\treturn environmentAccessToken\n\t}\n\n\tif (cachedAccessToken && cachedAccessToken.expiresAt > new Date(Date.now() + EXPIRATION_BUFFER)) {\n\t\treturn { apiHost, accessToken: cachedAccessToken.accessToken }\n\t}\n\n\tconst response = await fetch(`${apiHost}/auth/ai/access-token`, { credentials: \"include\" })\n\tif (!response.ok) throw new ApiError({ status: response.status, message: response.statusText })\n\tconst { accessToken, expiresAt } = await response.json()\n\tassert(isString(accessToken) && isString(expiresAt), \"Bad authentication service response\")\n\n\tconst expiresAtDate = new Date(expiresAt)\n\n\tif (!Number.isNaN(expiresAtDate.getTime())) {\n\t\tcachedAccessToken = { accessToken, expiresAt: expiresAtDate }\n\t}\n\n\treturn { apiHost, accessToken }\n}\n\nfunction createAIServiceRequestHeaders(initHeaders: HeadersInit | undefined, accessToken: string) {\n\tconst headers = new Headers(initHeaders)\n\tconst requestHeaders = new Headers({\n\t\tAuthorization: `Bearer ${accessToken}`,\n\t\t\"Content-Type\": headers.get(\"Content-Type\") ?? \"application/json\",\n\t})\n\tconst anthropicBetaHeader = headers.get(\"x-anthropic-beta\")\n\n\tif (anthropicBetaHeader) requestHeaders.set(\"x-anthropic-beta\", anthropicBetaHeader)\n\n\treturn requestHeaders\n}\n\n/** Parses the X-Framer-AI-Usage header value `daily=123&monthly=321`\n * and updates the project AI Usage\n */\nfunction applyAiUsageFromHeader(header: string) {\n\tconst params = new URLSearchParams(header)\n\tconst currentDay = parseInt(params.get(\"daily\") ?? \"\", 10)\n\tconst currentMonth = parseInt(params.get(\"monthly\") ?? \"\", 10)\n\tif (Number.isNaN(currentDay) || Number.isNaN(currentMonth)) return\n\tgetEngine()?.stores.projectStore.updateAiUsage({ currentDay, currentMonth })\n}\n\n/** Parses the team_*_credit_limit_reached response error and\n * and updates the project AI Usage.\n * Additionally sets `projectStore.aiCreditLimitReachedPending = true`,\n * that makes other clients refetch the project to keep the usage up-to-date\n */\nasync function applyAiCreditLimitFromError(response: Response) {\n\ttry {\n\t\tconst body = await response.json()\n\t\tconst error = parseAiCreditLimitError(body)\n\t\tif (!error) return\n\n\t\tconst projectStore = getEngine()?.stores.projectStore\n\t\tif (!projectStore) return\n\n\t\tswitch (error.reason) {\n\t\t\tcase \"team_daily_credit_limit_reached\":\n\t\t\t\tprojectStore.updateAiUsage({ currentDay: error.usage })\n\t\t\t\tprojectStore.updateAiCreditLimits({ aiCreditsDaily: error.limit })\n\t\t\t\tbreak\n\t\t\tcase \"team_monthly_credit_limit_reached\":\n\t\t\t\tprojectStore.updateAiUsage({ currentMonth: error.usage })\n\t\t\t\tprojectStore.updateAiCreditLimits({ aiCredits: error.limit })\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tassertNever(error.reason, \"Unknown credit limit reason\")\n\t\t}\n\n\t\tprojectStore.aiCreditLimitReachedPending = true\n\t} catch {\n\t\t// Response body isn't JSON \u2014 ignore.\n\t}\n}\n\nfunction assertAiEnabledForWorkspace() {\n\tconst engine = getEngine()\n\n\tif (engine && isAiDisabled(engine)) {\n\t\tthrow new AiDisabledError()\n\t}\n}\n\nexport async function fetchWithAccessToken(_: unknown, init: RequestInit) {\n\tassertAiEnabledForWorkspace()\n\n\tconst { apiHost, accessToken } = await getAccessToken()\n\n\tconst response = await fetch(`${apiHost}${aiServiceEndpoint}`, {\n\t\tmethod: \"POST\",\n\t\theaders: createAIServiceRequestHeaders(init.headers, accessToken),\n\t\tbody: wrapAIServiceRequestBody(rewriteOpenAICompatibleRequestBody(init?.body)),\n\t})\n\n\tif (response.status === 401) resetAccessTokenCache()\n\t// Clone because reading json() consumes the body; the caller still needs the original.\n\tif (response.status === 402) await applyAiCreditLimitFromError(response.clone())\n\n\tconst usageHeader = response.ok ? response.headers.get(\"X-Framer-AI-Usage\") : null\n\tif (usageHeader) applyAiUsageFromHeader(usageHeader)\n\n\treturn response\n}\n\nexport function resetAccessTokenCache() {\n\tcachedAccessToken = null\n}\n\ntype OpenRouterChatLanguageModel = ReturnType<OpenRouterProvider>\n\ntype VekterOpenRouterChatSettings = {\n\textraBody: VekterOpenRouterExtraBody\n} & OpenRouterChatSettings\n\ntype VekterOpenRouterProvider = (modelId: string, settings: VekterOpenRouterChatSettings) => OpenRouterChatLanguageModel\n\nexport const openRouter = createOpenRouter({\n\tfetch: fetchWithAccessToken,\n\tapiKey: \"bearer 123\", // This is only for type checking, we don't need to set the api key here, `apiFetcher` handles auth for us.\n\theaders: {\n\t\t\"x-anthropic-beta\": \"fine-grained-tool-streaming-2025-05-14,interleaved-thinking-2025-05-14\",\n\t},\n\textraBody: { usage: { include: true } },\n}) as VekterOpenRouterProvider\n\ntype BasetenModelId = LanguageModel.KimiK25 | LanguageModel.KimiK26\ntype BasetenCustomModelId = LanguageModel.Contour\ntype BasetenRoutedModelId = BasetenModelId | BasetenCustomModelId\n\ninterface BasetenReasoningProviderOptions extends JSONObject {\n\tchat_template_args: {\n\t\tenable_thinking: true\n\t}\n}\n\nfunction createBasetenCustomEndpoint(isDeployment: boolean) {\n\t// Use a custom endpoint instead of Baseten's base API endpoint (used for Kimi models).\n\tconst params = new URLSearchParams({ custom: \"1\" })\n\tif (isDeployment) params.set(\"deployment\", \"1\")\n\treturn `${aiServiceBasetenEndpoint}?${params}`\n}\n\ntype BasetenEndpointProvider = () => string\n\nfunction getBasetenEndpoint(endpoint: string | BasetenEndpointProvider) {\n\treturn typeof endpoint === \"function\" ? endpoint() : endpoint\n}\n\nfunction createBasetenFetch(endpoint: string | BasetenEndpointProvider) {\n\treturn async function fetchBasetenWithAccessToken(_: unknown, init: RequestInit) {\n\t\tassertAiEnabledForWorkspace()\n\n\t\tconst { apiHost, accessToken } = await getAccessToken()\n\n\t\tconst response = await fetch(`${apiHost}${getBasetenEndpoint(endpoint)}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: createAIServiceRequestHeaders(init.headers, accessToken),\n\t\t\tbody: rewriteOpenAICompatibleRequestBody(init?.body),\n\t\t\tsignal: init.signal,\n\t\t})\n\n\t\tif (response.status === 401) resetAccessTokenCache()\n\t\t// Clone because reading json() consumes the body; the caller still needs the original.\n\t\tif (response.status === 402) await applyAiCreditLimitFromError(response.clone())\n\n\t\tconst usageHeader = response.ok ? response.headers.get(\"X-Framer-AI-Usage\") : null\n\t\tif (usageHeader) applyAiUsageFromHeader(usageHeader)\n\n\t\treturn response\n\t}\n}\n\nfunction createBasetenProvider(endpoint: string | BasetenEndpointProvider) {\n\treturn createOpenAICompatible({\n\t\tbaseURL: \"https://framer.com\",\n\t\tname: \"baseten\",\n\t\tfetch: createBasetenFetch(endpoint),\n\t\tincludeUsage: true,\n\t})\n}\n\nfunction getPersistedContourOverride(): ContourOverride {\n\treturn getEngine()?.stores.persistedUserDefaults.contourOverride ?? defaultContourOverride\n}\n\nconst baseten = createBasetenProvider(aiServiceBasetenEndpoint)\nconst basetenCustom = createBasetenProvider(() =>\n\tcreateBasetenCustomEndpoint(hasContourDeploymentOverride(getPersistedContourOverride())),\n)\n\nconst basetenRouters = {\n\t[LanguageModel.KimiK25]: baseten,\n\t[LanguageModel.KimiK26]: baseten,\n\t[LanguageModel.Contour]: basetenCustom,\n} satisfies Record<BasetenRoutedModelId, OpenAICompatibleProvider>\n\n/**\n * Narrows a `LanguageModel` to the subset that the Baseten proxy can serve directly.\n */\nexport function isBasetenModelId(modelId: LanguageModel): modelId is keyof typeof basetenRouters {\n\treturn Object.prototype.hasOwnProperty.call(basetenRouters, modelId)\n}\n\nexport function createBasetenLanguageModel(modelId: keyof typeof basetenRouters) {\n\tif (modelId === LanguageModel.Contour) {\n\t\treturn basetenRouters[modelId](getContourTarget(getPersistedContourOverride()))\n\t}\n\treturn basetenRouters[modelId](modelId)\n}\n\nexport function getBasetenProviderOptionsForEffort(\n\teffort: AgentReasoningEffort | undefined,\n\tmodel: BasetenRoutedModelId,\n): BasetenReasoningProviderOptions | undefined {\n\tconst resolvedEffort = effort ?? getDefaultReasoningEffortForModel(model)\n\tassert(\n\t\tresolvedEffort === \"enabled\" || resolvedEffort === \"none\",\n\t\t`Unsupported Baseten reasoning effort: ${resolvedEffort}`,\n\t)\n\tif (resolvedEffort === \"none\") return\n\n\treturn {\n\t\tchat_template_args: {\n\t\t\tenable_thinking: true,\n\t\t},\n\t}\n}\n\nconst OPENROUTER_RESPONSES_ENDPOINT = \"/ai/v3/responses/\"\n// AI Proxy endpoint which goes directly to the OpenAI Responses API instead of OpenRouter.\nconst OPENAI_RESPONSES_ENDPOINT = \"/ai/v3/openai/responses/\"\n\ntype OpenAIProviderModelId = Parameters<OpenAIProvider>[0]\ntype ResponsesLanguageModel = ReturnType<OpenAIProvider>\ntype ResponsesProviderTools = OpenAIProvider[\"tools\"]\n\ntype OpenRouterResponsesModelId =\n\t| LanguageModel.GPT51\n\t| LanguageModel.GPT52\n\t| LanguageModel.GPT52Codex\n\t| LanguageModel.GPT51CodexMini\n\t| LanguageModel.GPT53Codex\n\t| LanguageModel.GPT54\n\t| LanguageModel.GPT55\n\t| LanguageModel.GPTNEXT\n\ntype StripOpenAIProviderPrefix<T extends string> = T extends `openai/${infer ModelId}` ? ModelId : never\n\n/** AGENT @TODO: Remove when `@ai-sdk/openai` bumps its model-id union. */\ntype PendingOpenAIResponsesModelId = StripOpenAIProviderPrefix<LanguageModel.GPT55 | LanguageModel.GPTNEXT>\n\ntype OpenAIResponsesModelId =\n\t| Extract<OpenAIProviderModelId, StripOpenAIProviderPrefix<OpenRouterResponsesModelId>>\n\t| PendingOpenAIResponsesModelId\n\nconst openAIResponsesModelIdByLanguageModel = {\n\t[LanguageModel.GPT51]: \"gpt-5.1\",\n\t[LanguageModel.GPT52]: \"gpt-5.2\",\n\t[LanguageModel.GPT52Codex]: \"gpt-5.2-codex\",\n\t[LanguageModel.GPT51CodexMini]: \"gpt-5.1-codex-mini\",\n\t[LanguageModel.GPT53Codex]: \"gpt-5.3-codex\",\n\t[LanguageModel.GPT54]: \"gpt-5.4\",\n\t[LanguageModel.GPT55]: \"gpt-5.5\",\n\t[LanguageModel.GPTNEXT]: \"iris-alpha\",\n} satisfies Record<OpenRouterResponsesModelId, OpenAIResponsesModelId>\n\n/**\n * Narrows a `LanguageModel` to the subset that the OpenAI Responses API can serve directly.\n * Used to pick between the direct `/ai/v3/openai/responses/` route and the OpenRouter-backed route.\n */\nexport function isOpenAIResponsesModelId(modelId: LanguageModel): modelId is OpenRouterResponsesModelId {\n\treturn Object.prototype.hasOwnProperty.call(openAIResponsesModelIdByLanguageModel, modelId)\n}\n\ninterface ResponsesProvider<TModelId extends string> {\n\ttools: ResponsesProviderTools\n\tmodel(modelId: TModelId): ResponsesLanguageModel\n}\n\nexport const enum ResponsesProviderRoute {\n\tOpenAI = \"openai\",\n\tOpenRouter = \"openrouter\",\n}\n\ninterface OpenAIResponsesProviderOptions {\n\troute: ResponsesProviderRoute.OpenAI\n}\n\ninterface OpenRouterResponsesProviderOptions {\n\troute: ResponsesProviderRoute.OpenRouter\n\tmetadata: AIServiceEnvelopeMetadata\n\tprovider?: ProviderForModel\n}\n\ntype ResponsesProviderOptions = OpenAIResponsesProviderOptions | OpenRouterResponsesProviderOptions\n\n// The AI SDK may omit the Responses item type on assistant messages, while our proxy schema\n// validates array-content assistant messages as explicit `message` items.\nfunction normalizeOpenRouterResponsesInputItem(item: unknown): unknown {\n\tif (!isObject(item) || item.role !== \"assistant\" || \"type\" in item) return item\n\treturn {\n\t\ttype: \"message\",\n\t\t...item,\n\t}\n}\n\nfunction normalizeOpenRouterResponsesRequestBody(body: Record<string, unknown>): Record<string, unknown> {\n\t// The OpenAI SDK needs unprefixed `gpt-*` ids for Responses capability detection, but the\n\t// OpenRouter proxy endpoint needs the provider-prefixed model id in the serialized request.\n\tconst model = toOpenRouterResponsesRequestModelId(body.model)\n\n\treturn {\n\t\t...body,\n\t\tmodel,\n\t\t...(Array.isArray(body.input) ? { input: body.input.map(normalizeOpenRouterResponsesInputItem) } : {}),\n\t}\n}\n\nfunction wrapOpenRouterResponsesRequestBody(\n\tbody: BodyInit | null | undefined,\n\tmetadata: AIServiceEnvelopeMetadata,\n\tprovider: ProviderForModel | undefined,\n): BodyInit | null | undefined {\n\tif (!isString(body)) {\n\t\tthrow new Error(\"Expected Responses request body to be a JSON string.\")\n\t}\n\n\tconst parsedBody = JSON.parse(body) as Record<string, unknown>\n\tconst normalizedBody = normalizeOpenRouterResponsesRequestBody(parsedBody)\n\tconst request = provider ? { ...normalizedBody, provider } : normalizedBody\n\tconst { projectId, ...restMetadata } = metadata\n\treturn JSON.stringify({\n\t\tprojectId: projectId ?? getOpenRouterTraceProjectId(),\n\t\t...restMetadata,\n\t\trequest,\n\t} satisfies AIServiceRequestBody)\n}\n\nfunction getResponsesEndpoint(options: ResponsesProviderOptions) {\n\tswitch (options.route) {\n\t\tcase ResponsesProviderRoute.OpenAI:\n\t\t\treturn OPENAI_RESPONSES_ENDPOINT\n\t\tcase ResponsesProviderRoute.OpenRouter:\n\t\t\treturn OPENROUTER_RESPONSES_ENDPOINT\n\t\tdefault:\n\t\t\tassertNever(options, \"Unknown responses provider route\")\n\t}\n}\n\nfunction getResponsesRequestBody(body: BodyInit | null | undefined, options: ResponsesProviderOptions) {\n\tswitch (options.route) {\n\t\tcase ResponsesProviderRoute.OpenAI:\n\t\t\treturn body\n\t\tcase ResponsesProviderRoute.OpenRouter:\n\t\t\treturn wrapOpenRouterResponsesRequestBody(body, options.metadata, options.provider)\n\t\tdefault:\n\t\t\tassertNever(options, \"Unknown responses provider route\")\n\t}\n}\n\nfunction createResponsesFetch(options: ResponsesProviderOptions) {\n\treturn async function fetchResponsesWithAccessToken(_: unknown, init: RequestInit) {\n\t\tassertAiEnabledForWorkspace()\n\n\t\tconst { apiHost, accessToken } = await getAccessToken()\n\t\tconst headers = new Headers(init?.headers)\n\n\t\tconst response = await fetch(`${apiHost}${getResponsesEndpoint(options)}`, {\n\t\t\tmethod: init.method ?? \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"Content-Type\": headers.get(\"Content-Type\") ?? \"application/json\",\n\t\t\t},\n\t\t\tbody: getResponsesRequestBody(init.body, options),\n\t\t\tsignal: init.signal,\n\t\t})\n\n\t\tif (response.status === 401) resetAccessTokenCache()\n\n\t\t// Clone because reading json() consumes the body; the caller still needs the original.\n\t\tif (response.status === 402) await applyAiCreditLimitFromError(response.clone())\n\n\t\tconst usageHeader = response.ok ? response.headers.get(\"X-Framer-AI-Usage\") : null\n\t\tif (usageHeader) applyAiUsageFromHeader(usageHeader)\n\n\t\treturn response\n\t}\n}\n\nexport function toOpenAIResponsesModelId(modelId: OpenRouterResponsesModelId): OpenAIResponsesModelId {\n\treturn openAIResponsesModelIdByLanguageModel[modelId]\n}\n\nfunction toOpenRouterResponsesRequestModelId(modelId: unknown): unknown {\n\tswitch (modelId) {\n\t\tcase \"gpt-5.1\":\n\t\t\treturn LanguageModel.GPT51\n\t\tcase \"gpt-5.2\":\n\t\t\treturn LanguageModel.GPT52\n\t\tcase \"gpt-5.2-codex\":\n\t\t\treturn LanguageModel.GPT52Codex\n\t\tcase \"gpt-5.1-codex-mini\":\n\t\t\treturn LanguageModel.GPT51CodexMini\n\t\tcase \"gpt-5.3-codex\":\n\t\t\treturn LanguageModel.GPT53Codex\n\t\tcase \"gpt-5.4\":\n\t\t\treturn LanguageModel.GPT54\n\t\tcase \"gpt-5.5\":\n\t\t\treturn LanguageModel.GPT55\n\t\tcase \"iris-alpha\":\n\t\t\treturn LanguageModel.GPTNEXT\n\t\tdefault:\n\t\t\treturn modelId\n\t}\n}\n\nfunction createOpenAIResponsesProvider(provider: OpenAIProvider): ResponsesProvider<OpenAIResponsesModelId> {\n\treturn {\n\t\ttools: provider.tools,\n\t\tmodel(modelId) {\n\t\t\treturn provider(modelId)\n\t\t},\n\t}\n}\n\nfunction createOpenRouterResponsesProvider(provider: OpenAIProvider): ResponsesProvider<OpenRouterResponsesModelId> {\n\treturn {\n\t\ttools: provider.tools,\n\t\tmodel(modelId) {\n\t\t\treturn provider(toOpenAIResponsesModelId(modelId))\n\t\t},\n\t}\n}\n\n/**\n * Creates a Responses provider whose transport is selected explicitly by the caller.\n *\n * `openrouter` is the normal path and routes through Framer AI service's\n * `/ai/v3/responses/` endpoint using the AI-service envelope.\n *\n * `openai` is the escape hatch and routes through the employee-only\n * `/ai/v3/openai/responses/` proxy, forwarding the raw OpenAI Responses body.\n * Some flows intentionally choose this route by default when they rely on\n * OpenAI Responses semantics that are not yet behaving correctly via OpenRouter.\n */\nexport function createResponsesProvider(\n\toptions: OpenAIResponsesProviderOptions,\n): ResponsesProvider<OpenAIResponsesModelId>\nexport function createResponsesProvider(\n\toptions: OpenRouterResponsesProviderOptions,\n): ResponsesProvider<OpenRouterResponsesModelId>\nexport function createResponsesProvider(options: ResponsesProviderOptions) {\n\tconst provider = createOpenAI({\n\t\tfetch: createResponsesFetch(options),\n\t\tapiKey: \"bearer 123\", // Placeholder \u2014 fetch handles auth.\n\t})\n\n\tswitch (options.route) {\n\t\tcase ResponsesProviderRoute.OpenAI:\n\t\t\treturn createOpenAIResponsesProvider(provider)\n\t\tcase ResponsesProviderRoute.OpenRouter:\n\t\t\treturn createOpenRouterResponsesProvider(provider)\n\t\tdefault:\n\t\t\tassertNever(options, \"Unknown responses provider route\")\n\t}\n}\n", "import { assert, getLogger } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { CanvasNode, CanvasTree, MaybeNodeID, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isFixedOrRelativeOverlay, nodeIsInOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { hasFloatingPosition } from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { BindingCollector } from \"./BindingCollector.ts\"\n\nconst log = getLogger(\"OverlayCollector\")\n\ntype OverlayTriggerNodeID = NodeID\ninterface OverlayCollectorOptions {\n\ttree: CanvasTree\n\tbindings: BindingCollector\n}\nexport class OverlayCollector {\n\tprivate readonly tree: CanvasTree\n\tprivate readonly bindings: BindingCollector\n\tstatic OverlayBinding = js`overlay`\n\tstatic Api = {\n\t\tvisible: \"visible\",\n\t\tshow: \"show\",\n\t\thide: \"hide\",\n\t\ttoggle: \"toggle\",\n\t} as const\n\n\tstatic overlayMethod(binding: SafeJS, method: keyof typeof OverlayCollector.Api) {\n\t\treturn new SafeJS(`${binding}.${method}`)\n\t}\n\n\tconstructor(options: OverlayCollectorOptions) {\n\t\tthis.tree = options.tree\n\t\tthis.bindings = options.bindings\n\t}\n\tbindingsByOverlayId = new Map<NodeID, SafeJS>()\n\tbindingsByOverlayTriggerId = new Map<OverlayTriggerNodeID, Map<NodeID, SafeJS>>()\n\t/**\n\t * Record the originalid or id of all nodes that trigger a relative\n\t * overlay. Used later to ensure this layer has a `ref`.\n\t */\n\trelativeOverlayTriggerIds = new Set<NodeID>()\n\n\taddOverlayTrigger(overlayId: NodeID, triggerId: NodeID): SafeJS | undefined {\n\t\tconst overlayNode = this.tree.get(overlayId)\n\t\tif (!overlayNode) return\n\n\t\tconst trigger = this.tree.get(triggerId)\n\t\tif (!trigger) return\n\n\t\tconst originalTrigger = this.tree.get(trigger.getPrimaryId())\n\t\tif (!originalTrigger) return\n\n\t\tconst hasOverlayChild = trigger?.children?.find(child => {\n\t\t\tconst childId = child.getPrimaryId()\n\t\t\treturn childId === overlayId && isFixedOrRelativeOverlay(child)\n\t\t})\n\t\tif (!hasOverlayChild) {\n\t\t\tlog.reportError(\n\t\t\t\t\"OverlayCollector: Tried to create a event handler to show an overlay which is not a descendant of the trigger.\",\n\t\t\t\t{\n\t\t\t\t\ttriggerId,\n\t\t\t\t\toverlayId,\n\t\t\t\t},\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tconst overlayBinding = this.bindingsByOverlayId.get(overlayId) ?? this.bindings.create(\"overlay\")\n\n\t\t// Overlays can only have one trigger...\n\t\tthis.bindingsByOverlayId.set(overlayId, overlayBinding)\n\n\t\t// ...but the node that triggers an overlay can trigger multiple overlays.\n\t\tconst triggerOverlays = this.bindingsByOverlayTriggerId.get(originalTrigger.id) ?? new Map()\n\t\ttriggerOverlays.set(overlayNode.getPrimaryId(), overlayBinding)\n\n\t\tthis.bindingsByOverlayTriggerId.set(originalTrigger.id, triggerOverlays)\n\n\t\tif (hasFloatingPosition(overlayNode)) this.relativeOverlayTriggerIds.add(originalTrigger.id)\n\n\t\treturn SafeJS.fn(\n\t\t\tOverlayCollector.overlayMethod(\n\t\t\t\tOverlayCollector.OverlayBinding,\n\t\t\t\thasFloatingPosition(overlayNode) ? \"show\" : \"toggle\",\n\t\t\t),\n\t\t)\n\t}\n\n\thasAncestorOverlayBinding(node: CanvasNode): boolean {\n\t\tif (!nodeIsInOverlay(node)) return false\n\t\tconst overlayId = this.getOverlayIdForNode(node)\n\t\tassert(overlayId, \"overlayAncestorId must not be null when nodeIsInOverlay is true\")\n\n\t\treturn this.bindingsByOverlayId.has(overlayId)\n\t}\n\n\t/**\n\t * We use `node.cache.overlayAncestorId` to know the overlay an action\n\t * should control. However, in replicas, this id is the id of the replica\n\t * overlay. To make sure we always refer to the overlay created by the\n\t * primary variant, we must lookup the node and use its original id.\n\t */\n\tgetOverlayIdForNode(node: CanvasNode): MaybeNodeID {\n\t\treturn isReplicaOrReplicaChild(node)\n\t\t\t? this.tree.get(node.cache.overlayAncestorId)?.originalid\n\t\t\t: node.cache.overlayAncestorId\n\t}\n}\n", "import type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode, isShaderNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { WithCodeComponent } from \"document/models/CanvasTree/traits/WithCodeComponent.ts\"\nimport { HardCodedCodeIdentifier } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\n\ninterface ComponentWithoutContainer extends WithCodeComponent {\n\tcodeComponentIdentifier: HardCodedCodeIdentifier.page | HardCodedCodeIdentifier.scroll\n}\n\ninterface BuiltInComponent extends WithCodeComponent {\n\tcodeComponentIdentifier:\n\t\t| HardCodedCodeIdentifier.page\n\t\t| HardCodedCodeIdentifier.scroll\n\t\t| HardCodedCodeIdentifier.prototype\n}\n\n/**\n * @deprecated Creating new Page and Scroll components in Framer is no longer supported as of July\n * 2025. Existing Page and Scroll components will continue to work, but please use alternative\n * solutions for new projects.\n */\nexport function isBuiltInComponentWithoutContainer(node: WithCodeComponent): node is ComponentWithoutContainer {\n\tswitch (node.codeComponentIdentifier) {\n\t\tcase HardCodedCodeIdentifier.page:\n\t\tcase HardCodedCodeIdentifier.scroll:\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\nexport function nodeNeedsContainer(node: CanvasNode) {\n\tif (isCodeComponentNode(node) && !isBuiltInComponentWithoutContainer(node) && !node.isVectorInstance) return true\n\tif (isShaderNode(node)) return true\n\treturn false\n}\n\nexport function isBuiltInComponent(node: WithCodeComponent): node is BuiltInComponent {\n\tswitch (node.codeComponentIdentifier) {\n\t\tcase HardCodedCodeIdentifier.page:\n\t\tcase HardCodedCodeIdentifier.scroll:\n\t\tcase HardCodedCodeIdentifier.prototype:\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\nexport function builtInComponentName(node: BuiltInComponent): string {\n\tswitch (node.codeComponentIdentifier) {\n\t\tcase HardCodedCodeIdentifier.page:\n\t\t\treturn \"Page\"\n\t\tcase HardCodedCodeIdentifier.scroll:\n\t\t\treturn \"Scroll\"\n\t\tcase HardCodedCodeIdentifier.prototype:\n\t\t\treturn \"DeviceCodeComponent\"\n\t}\n}\n", "import {\n\tassert,\n\ttype ModuleExportIdentifierString,\n\tModuleType,\n\tisExternalModuleIdentifier,\n\tlocalModuleIdForStableName,\n\tparseModuleIdentifier,\n\tunhandledError,\n} from \"@framerjs/shared\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport type { CanvasTree, RichTextNode } from \"document/models/CanvasTree/index.ts\"\nimport { ComponentPresetNode } from \"document/models/CanvasTree/nodes/ComponentPresetNode.ts\"\nimport { PresetsListNode } from \"document/models/CanvasTree/nodes/PresetsListNode.ts\"\nimport { isComponentPresetNode, isRichTextNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { prefixComponentPresetKey } from \"document/models/CanvasTree/traits/WithComponentPresets.ts\"\nimport { isVekterEngine } from \"document/useVekterEngine.ts\"\nimport { uniqueName } from \"document/utils/uniqueName.ts\"\nimport type { ComponentWithPreset } from \"./getComponentsWithPresets.ts\"\nimport { isKeySetAndNotInherited } from \"./isKeySetAndNotInherited.ts\"\nimport { ClassDiscriminator } from \"./withClassDiscriminator.ts\"\n\n// Component presets have a different module ID from style presets because they\n// are code generated in different ways. See comments in `PresetListNode` for\n// more info on why.\nexport const COMPONENT_PRESETS_MODULE_ID = localModuleIdForStableName(ModuleType.ComponentPresets, \"componentPresets\")\n\nexport function getDefaultComponentPreset(tree: CanvasTree, componentIdentifier: ModuleExportIdentifierString) {\n\tconst listNode = PresetsListNode.get(tree)\n\tif (!listNode) return null\n\n\treturn listNode.getComponentPresets().find(preset => preset.componentIdentifier === componentIdentifier) ?? null\n}\n\nexport function insertComponentPreset(engine: BaseEngine, preset: ComponentPresetNode) {\n\tconst { treeStore } = engine.stores\n\tif (treeStore.tree.has(preset.id)) return\n\n\tconst defaultPreset = getDefaultComponentPreset(treeStore.tree, preset.componentIdentifier)\n\tconst listNode = PresetsListNode.ensure(treeStore.tree)\n\n\tlet insertPosition = listNode.children.findLastIndex(\n\t\tchild => isComponentPresetNode(child) && child.componentIdentifier !== preset.componentIdentifier,\n\t)\n\tif (insertPosition !== -1) insertPosition += 1\n\n\ttreeStore.tree.insertNode(preset, listNode.id, insertPosition)\n\n\tif (isVekterEngine(engine)) {\n\t\tengine.stores.codeGenerationStore.createModuleFromComponentSource(listNode).catch(unhandledError)\n\t}\n\n\tif (isExternalModuleIdentifier(preset.componentIdentifier)) {\n\t\tvoid engine.stores.modulesStore.addExternalModulesToProject([preset.componentIdentifier], {\n\t\t\tonTreeUpdate() {},\n\t\t})\n\t}\n\n\tconst key = prefixComponentPresetKey(preset.componentIdentifier)\n\n\t// If we didn't have a preset before, we use the new preset on all nodes\n\t// that have a RichText variable assigned.\n\tif (defaultPreset) return\n\n\tif (!treeStore.getDataTree()) {\n\t\tengine.scheduler.runWithFullyLoadedTree(\n\t\t\t() => {\n\t\t\t\tconst treeIndexes = treeStore.getLoadedIndexes()\n\t\t\t\tfor (const node of treeIndexes.richTextNodes) {\n\t\t\t\t\tif (!node.htmlContent) continue\n\t\t\t\t\tif (!isKeySetAndNotInherited(treeStore.tree, node, key)) continue\n\t\t\t\t\tnode.setComponentPreset(preset.componentIdentifier, preset.id)\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ runInBackground: true, name: \"insertComponentPreset\" },\n\t\t)\n\t} else {\n\t\tconst richTextNodes = treeStore.tree.query().whereClassName<RichTextNode>(ClassDiscriminator.RichTextNode).iterate()\n\t\tfor (const node of richTextNodes) {\n\t\t\tif (!node.htmlContent) continue\n\t\t\tif (!isKeySetAndNotInherited(treeStore.tree, node, key)) continue\n\t\t\tnode.setComponentPreset(preset.componentIdentifier, preset.id)\n\t\t}\n\t}\n}\n\nfunction ensureComponentPreset(engine: BaseEngine, component: ComponentWithPreset) {\n\tconst defaultPreset = getDefaultComponentPreset(engine.tree, component.componentIdentifier)\n\tif (defaultPreset) return\n\n\tconst newPreset = ComponentPresetNode.createDefault(component)\n\tinsertComponentPreset(engine, newPreset)\n}\n\nexport function createComponentPreset(\n\tengine: BaseEngine,\n\tcomponent: ComponentWithPreset,\n\tonCreate?: (preset: ComponentPresetNode) => void,\n) {\n\tengine.scheduler.processWhenReady(() => {\n\t\tconst listNode = PresetsListNode.ensure(engine.tree)\n\t\tconst componentPresets = listNode.getComponentPresets()\n\n\t\tconst existingNames = new Set<string>()\n\t\tfor (const preset of componentPresets) {\n\t\t\tconst name = preset.resolveValue(\"name\")\n\t\t\tif (name) existingNames.add(name)\n\t\t}\n\n\t\tconst newPreset = ComponentPresetNode.createDefault(component, {\n\t\t\tname: uniqueName(component.name, existingNames),\n\t\t})\n\n\t\tinsertComponentPreset(engine, newPreset)\n\n\t\ttry {\n\t\t\tif (onCreate) onCreate(newPreset)\n\t\t} catch {\n\t\t\t// Ignore error\n\t\t}\n\t})\n}\n\nexport function getComponentPresetsForModule(tree: CanvasTree, componentIdentifier: ModuleExportIdentifierString) {\n\tconst listNode = PresetsListNode.get(tree)\n\treturn listNode?.getComponentPresets().filter(node => node.componentIdentifier === componentIdentifier) ?? []\n}\n\nexport function updateModuleIdentifiersInComponentPresets(\n\ttree: CanvasTree,\n\tfromIdentifier: ModuleExportIdentifierString,\n\ttoIdentifier: ModuleExportIdentifierString,\n) {\n\tconst parsedFromId = parseModuleIdentifier(fromIdentifier)\n\n\tfunction shouldUpdateIdentifier(componentIdentifier: ModuleExportIdentifierString) {\n\t\tconst parsedId = parseModuleIdentifier(componentIdentifier)\n\n\t\treturn (\n\t\t\tparsedId.kind === \"externalModuleExport\" &&\n\t\t\tparsedFromId.kind === \"externalModuleExport\" &&\n\t\t\tparsedId.moduleId === parsedFromId.moduleId &&\n\t\t\tparsedId.exportSpecifier === parsedFromId.exportSpecifier\n\t\t)\n\t}\n\n\tconst listNode = PresetsListNode.get(tree)\n\tif (listNode) {\n\t\tconst componentPresets = listNode.getComponentPresets()\n\t\tfor (const node of componentPresets) {\n\t\t\tif (shouldUpdateIdentifier(node.componentIdentifier)) {\n\t\t\t\tnode.set({ componentIdentifier: toIdentifier })\n\t\t\t}\n\t\t}\n\t}\n\tassert(tree.isLoaded(), \"Tree should be fully loaded or to be a data tree\")\n\n\tfor (const node of tree.root.walk()) {\n\t\tif (!isRichTextNode(node)) continue\n\n\t\tconst componentPresets = node.getComponentPresets()\n\t\tfor (const [componentIdentifier, presetId] of componentPresets) {\n\t\t\tconst key = prefixComponentPresetKey(componentIdentifier) as keyof RichTextNode\n\t\t\tif (shouldUpdateIdentifier(componentIdentifier) && isKeySetAndNotInherited(tree, node, key)) {\n\t\t\t\tnode.setComponentPreset(toIdentifier, presetId)\n\t\t\t\tnode.setComponentPreset(componentIdentifier, undefined)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Ensures that a component preset exists for the identifier. */\nexport function ensureComponentPresetForIdentifier(\n\tengine: BaseEngine,\n\tcomponents: ComponentWithPreset[],\n\tcomponentIdentifier: ModuleExportIdentifierString,\n) {\n\tconst component = components.find(component => component.componentIdentifier === componentIdentifier)\n\tif (!component) return\n\n\tensureComponentPreset(engine, component)\n}\n", "import hash from \"@emotion/hash\"\nimport { isString } from \"@framerjs/assets/src/utils.ts\"\nimport type { JSXContext } from \"code-generation/jsx/types.ts\"\nimport type { CollectorEntryNode, SerializableMotionStyle } from \"code-generation/types.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isOverlayNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { GestureType } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { createCSSDeclarationBlock } from \"document/models/CanvasTree/traits/utils/getCSSDeclarationBlock.ts\"\nimport { VariantSelector } from \"library/modules/useVariantState.ts\"\nimport type { CSSVariableDefinitionCollector } from \"./CSSVariableDefinitionCollector.ts\"\nimport { COMPONENT_PREFIX, RuleType, createFramerClassName } from \"./createFramerClassName.ts\"\n\ninterface Options {\n\tscope?: NodeID\n\tgesture?: GestureType\n\tcontainer?: boolean\n\truleType?: RuleType\n\tvariant?: CanvasNode\n\thasScopingSelector?: boolean\n}\n\ntype CSSRules = Map<string, string>\n\nexport interface CollectedVariantCSS {\n\trules: CSSRules\n}\n\ntype VariantId = NodeID\n\n/**\n * ConditionalRule represents a set of CSS rules that are only applied to the\n * generated module when a certain condition is met. For example, the \"border\"\n * rule is only applied when the node has a border, and the \"hideScrollbars\"\n * rule is only applied when the node has this value set.\n */\nexport enum ConditionalRule {\n\tBorder,\n\tHideScrollbars,\n\tTextSelection,\n}\n\ntype ConditionalRuleFn = (serializationId: string) => string[]\n\nconst borderRules = (serializationId: string): string[] => [\n\t`.${serializationId}[data-border=\"true\"]::after, .${serializationId} [data-border=\"true\"]::after { content: \"\"; border-width: var(--border-top-width, 0) var(--border-right-width, 0) var(--border-bottom-width, 0) var(--border-left-width, 0); border-color: var(--border-color, none); border-style: var(--border-style, none); width: 100%; height: 100%; position: absolute; box-sizing: border-box; left: 0; top: 0; border-radius: inherit; corner-shape: inherit; pointer-events: none; }`,\n]\n\nconst selectionRules = (serializationId: string): string[] => [\n\t`.${serializationId}[data-selection=\"true\"] * ::selection, .${serializationId} [data-selection=\"true\"] * ::selection { color: var(--selection-color, none); background-color: var(--selection-background-color, none); }`,\n]\n\nconst hideScrollbarRules = (serializationId: string): string[] => [\n\t// We need to also target child elements of the root layer that is marked\n\t// with the serializationId too, so that they receive the same hide\n\t// scrollbars treatment, hence why we have two selectors on each line here.\n\t`.${serializationId}[data-hide-scrollbars=\"true\"]::-webkit-scrollbar, .${serializationId} [data-hide-scrollbars=\"true\"]::-webkit-scrollbar { width: 0px; height: 0px; }`,\n\t`.${serializationId}[data-hide-scrollbars=\"true\"]::-webkit-scrollbar-thumb, .${serializationId} [data-hide-scrollbars=\"true\"]::-webkit-scrollbar-thumb { background: transparent; }`,\n\t// Firefox\n\t`.${serializationId}[data-hide-scrollbars=\"true\"], .${serializationId} [data-hide-scrollbars=\"true\"] { scrollbar-width: none; }`,\n]\n\nexport const LAYOUT_TEMPLATE_ATTRIBUTE = \"data-layout-template\"\n\nconst conditionalRuleToFnMapping: Record<ConditionalRule, ConditionalRuleFn> = {\n\t[ConditionalRule.Border]: borderRules,\n\t[ConditionalRule.HideScrollbars]: hideScrollbarRules,\n\t[ConditionalRule.TextSelection]: selectionRules,\n}\n\nconst componentContainerClassNamePostfix = \"-container\"\n\nexport class CSSCollector {\n\tsharedStyleIds = new Set<NodeID>()\n\n\trules: Partial<Record<VariantId, CSSRules>> = {}\n\n\tprivate nodeClassNames = new Map<string, NodeID>()\n\n\t/**\n\t * Given a class name from generated code, return the node id that it was generated from.\n\t */\n\tgetNodeIdForClassName(className: string): NodeID | undefined {\n\t\tconst name = className.endsWith(componentContainerClassNamePostfix)\n\t\t\t? className.slice(0, -componentContainerClassNamePostfix.length)\n\t\t\t: className\n\t\treturn this.nodeClassNames.get(name)\n\t}\n\n\t#conditionalRules: Set<ConditionalRule> = new Set()\n\n\tconstructor(\n\t\tprivate readonly entryNode: CollectorEntryNode,\n\t\tprivate readonly sourceNode: CanvasNode,\n\t\tprivate readonly serializationId: string,\n\t\tprivate readonly cssVariableDefinitions: CSSVariableDefinitionCollector,\n\t) {}\n\n\tget(variantId: VariantId = this.sourceNode.id): CollectedVariantCSS {\n\t\tif (variantId === this.sourceNode.id) this.getWideGamutColorRule()\n\n\t\treturn {\n\t\t\trules: this.rules[variantId] ?? new Map(),\n\t\t}\n\t}\n\n\tprivate createScopingSelector(scope?: NodeID, gesture?: GestureType): string {\n\t\tif (scope) {\n\t\t\t// Unlike with the css from the primary variant, the result looks\n\t\t\t// like '.framer-${serializationId}.framer-v-${variant.id}.hover'.\n\t\t\tconst selector = `.${this.serializationId}.${COMPONENT_PREFIX}${VariantSelector.Variant}-${hash(scope)}`\n\t\t\tif (gesture) return `${selector}.${gesture}`\n\t\t\treturn selector\n\t\t}\n\n\t\treturn `.${this.serializationId}`\n\t}\n\n\tprivate createSelector(\n\t\tid: string,\n\t\tclassName: string,\n\t\tscope?: NodeID,\n\t\tgesture?: GestureType,\n\t\thasScopingSelector: boolean = id === this.sourceNode.id,\n\t): string {\n\t\tconst scopingSelector = this.createScopingSelector(scope, gesture)\n\t\t// Prefix rules with the serialization id so that they can't interfere\n\t\t// with older versions of this component. The result looks like\n\t\t// '.framer-123 .framer-456' or '.framer-123.framer-456', where the\n\t\t// second selector is a class assigned to an element. There is a space\n\t\t// when creating selectors for the ground node so that the serialization\n\t\t// class, which is applied to that same html element in the component,\n\t\t// scopes the selectors correctly. When creating selectors for the scope\n\t\t// node, we need to create 2 selectors so that any layer can receive the\n\t\t// component-wide styles.\n\t\tif (id === this.entryNode.id) return `${scopingSelector}.${className}, ${scopingSelector} .${className}`\n\t\treturn hasScopingSelector ? `${scopingSelector}.${className}` : `${scopingSelector} .${className}`\n\t}\n\tprivate selectorsByNodeId = new Map<NodeID, string>()\n\taddRule(style: SerializableMotionStyle, node: CanvasNode, options: Options = {}) {\n\t\tconst { scope, gesture, container, ruleType = RuleType.Component, hasScopingSelector } = options\n\n\t\tconst id = node.getPrimaryId()\n\t\tlet className = createFramerClassName(ruleType, id)\n\t\t// Track the classname for the first time. Use `node.id` instead of `id` to allow jsx\n\t\t// generated from just a replica to be looked up.\n\t\tif (!this.nodeClassNames.has(className)) this.nodeClassNames.set(className, node.id)\n\t\tif (container) className += componentContainerClassNamePostfix\n\n\t\tconst selector = this.createSelector(id, className, scope, gesture, hasScopingSelector)\n\t\tthis.selectorsByNodeId.set(id, selector)\n\n\t\tconst variantId = options.variant?.id ?? this.sourceNode.id\n\t\tthis.createRule(selector, createCSSDeclarationBlock(style), variantId)\n\n\t\tif (styleRequiresViewTransitionNameSelector(style)) {\n\t\t\tconst rules = viewTransitionExcludedNameRules(node, this.serializationId)\n\t\t\tfor (const key in rules) this.createRule(key, createCSSDeclarationBlock(rules[key]!), variantId)\n\t\t}\n\n\t\treturn className\n\t}\n\n\t/**\n\t * Indicate to the code generation that the given ConditionalRule\n\t * (representing some additional CSS selectors that need to be included)\n\t * should be code generated into the module.\n\t */\n\taddConditionalRule(rule: ConditionalRule): void {\n\t\tthis.#conditionalRules.add(rule)\n\t}\n\n\t/**\n\t * Returns a boolean to indicate if the collector has been told to include\n\t * the given additional CSS selectors rules in the generated module.\n\t */\n\thasConditionalRule(rule: ConditionalRule): boolean {\n\t\treturn this.#conditionalRules.has(rule)\n\t}\n\n\t/**\n\t * Returns any additional CSS selectors that need to be included in the\n\t * generated module, based on the conditional rules that have been added to\n\t * the collector.\n\t */\n\tconditionalRules(serializationId: string): string[] {\n\t\tconst rules: string[] = []\n\n\t\tthis.#conditionalRules.forEach(rule => {\n\t\t\tconst ruleFn = conditionalRuleToFnMapping[rule]\n\t\t\tconst ruleResult = ruleFn(serializationId)\n\t\t\trules.push(...ruleResult)\n\t\t})\n\n\t\treturn rules\n\t}\n\n\taddSharedStyle(id: NodeID) {\n\t\tthis.sharedStyleIds.add(id)\n\t}\n\n\tcreateRule(selector: string, declaration: string, variantId: VariantId = this.sourceNode.id) {\n\t\tconst variantRules = this.rules[variantId]\n\t\tif (variantRules) {\n\t\t\tvariantRules.set(selector, declaration)\n\t\t\treturn\n\t\t}\n\n\t\tthis.rules[variantId] = new Map([[selector, declaration]])\n\t}\n\n\tprivate getWideGamutColorRule() {\n\t\tconst rules = this.cssVariableDefinitions.getWideGamutColorRules(`.${this.serializationId}`, this.selectorsByNodeId)\n\n\t\tif (rules.length === 0) return\n\n\t\t// If we have any rules, create an @supports selector that will only\n\t\t// apply to browsers that support the P3 color syntax..\n\t\tthis.createRule(`@supports (color: color(display-p3 1 1 1))`, rules.join(\" \"))\n\t}\n}\n\nconst viewTransitionNameKey = \"viewTransitionName\" satisfies keyof SerializableMotionStyle\nfunction styleRequiresViewTransitionNameSelector(style: SerializableMotionStyle) {\n\treturn viewTransitionNameKey in style && viewTransitionExcluded(style)\n}\n\nconst postFix = \"-exclude\"\nfunction viewTransitionExcluded(style: SerializableMotionStyle) {\n\treturn isString(style.viewTransitionName) && style.viewTransitionName.endsWith(postFix)\n}\n\n/**\n * If the node is excluded from the view transition, we will also add rules\n * to prevent it from animating. In this we need to include the serialization\n * hash to ensure that the rules do not clash with previously generated\n * rules. This gives us confidence we can change the declaration for these\n * rules without polluting old code-generation.\n */\nexport function viewTransitionName(node: CanvasNode, serializationId: string, exclude: boolean) {\n\tconst key = hash(node.getPrimaryId())\n\n\treturn exclude ? `${serializationId}-${key}${postFix}` : key\n}\n\n/**\n * When an element is excluded from the view transition, we need to add rules\n * to prevent it from animating. The name in the selector must be unique to an\n * entire site. For this reason we include the serialization hash to ensure that\n * future generations which may change the declaration are safe.\n */\nfunction viewTransitionExcludedNameRules(node: CanvasNode, serializationId: string) {\n\tconst name = viewTransitionName(node, serializationId, true)\n\n\treturn {\n\t\t[`::view-transition-group(${name})`]: { animation: \"none !important\" },\n\t\t[`::view-transition-new(${name})`]: { animation: \"none !important\" },\n\t\t[`::view-transition-old(${name})`]: { animation: \"none !important\" },\n\t}\n}\n\n/**\n * Nodes that are generated into elements that may render outside of the root\n * element, or are the root element themselves, have the serialization hash as\n * one of their class names. In these cases we need to format the css\n * declaration selector appropriately.\n */\nexport function nodeHasSerializationHashClassName(\n\tnode: CanvasNode,\n\tparent: CanvasNode | null,\n\tctx: JSXContext,\n): boolean {\n\tif (isOverlayNode(node)) return true\n\tif (isOverlayNode(parent)) return true\n\tif (node.id === ctx.rootId) return true\n\treturn false\n}\n", "import type { NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { DataRepeater } from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { Query } from \"library/modules/cms/types.ts\"\n\ntype RepeaterId = NodeID\ntype VariantId = NodeID\n\ntype VariantSubqueries = Map<RepeaterId, Query>\ntype VariableDependencies = VariableReference[]\n\nexport class SubqueryCollector {\n\treadonly subqueries = new Map<VariantId, VariantSubqueries>()\n\treadonly variableDependencies = new Map<VariantId, VariableDependencies>()\n\treadonly childRepeaterIds = new Set<RepeaterId>()\n\n\tconstructor(\n\t\treadonly repeaterNode: DataRepeater,\n\t\treadonly parent?: SubqueryCollector,\n\t) {}\n\n\taddSubquery(variantId: VariantId, childRepeaterId: RepeaterId, subquery: Query) {\n\t\tconst variantSubqueries = this.getSubqueries(variantId)\n\t\tvariantSubqueries.set(childRepeaterId, subquery)\n\t\tthis.subqueries.set(variantId, variantSubqueries)\n\n\t\tthis.childRepeaterIds.add(childRepeaterId)\n\t}\n\n\tgetSubqueries(variantId: VariantId): VariantSubqueries {\n\t\treturn this.subqueries.get(variantId) ?? new Map()\n\t}\n\n\taddVariableDependencies(variantId: VariantId, variableDependencies: VariableDependencies) {\n\t\tconst variantVariableDependencies = this.getVariableDependencies(variantId)\n\t\tvariantVariableDependencies.push(...variableDependencies)\n\t\tthis.variableDependencies.set(variantId, variantVariableDependencies)\n\t}\n\n\tgetVariableDependencies(variantId: VariantId): VariableDependencies {\n\t\treturn this.variableDependencies.get(variantId) ?? []\n\t}\n}\n", "import { js } from \"code-generation/js/js.ts\"\nimport type { JSXContext } from \"code-generation/jsx/types.ts\"\nimport type { Visibility } from \"code-generation/types.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { withVisibility } from \"document/models/CanvasTree/traits/WithVisibility.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\n\nexport function getVisibility(node: CanvasNode, context: JSXContext): Visibility {\n\tif (!withVisibility(node) || isUndefined(node.visible)) return true\n\n\tif (isDynamicValue(node.visible)) {\n\t\tconst condition = context.createDeduplicatedDynamicValueBinding(node.visible, node, \"visible\")\n\t\t// When an optional boolean variable is undefined it's expected that the node is visible.\n\t\treturn js`${condition} !== false`\n\t}\n\n\treturn node.isVisible()\n}\n", "import type { Logger } from \"@framerjs/shared\"\nimport type { JSXContext } from \"code-generation/jsx/types.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\n\nconst message = (scopeType: string, scopeId: string) =>\n\t`Node in ${scopeType} ${scopeId} cache is outdated, generated module may be incorrect`\n\nexport function logOutdatedCacheError(logger: Logger, node: CanvasNode, ctx: JSXContext) {\n\tlogger.reportWithoutLogging(new Error(message(ctx.scopeType, ctx.scopeId)), {\n\t\tnodeId: node.id,\n\t\tscopeType: ctx.scopeType,\n\t\tscopeId: ctx.scopeId,\n\t})\n}\n", "import { experiments } from \"app/experiments.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isChildOfBreakpoint } from \"document/models/CanvasTree/nodes/utils/breakpointHelpers.ts\"\nimport { isAnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport { isRichTextNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { hasImageFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { hasFloatingPosition } from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport {\n\thasFlowEffect,\n\tisFlowEffectSupportedScopeType,\n\tisNodeFlowEffectItem,\n\twithFlowEffect,\n} from \"document/models/CanvasTree/traits/WithFlowEffect.ts\"\nimport { frameMotionEventKeys, withFrameEvents } from \"document/models/CanvasTree/traits/WithFrameEvents.ts\"\nimport { hasColumnMasonryLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { hasLink } from \"document/models/CanvasTree/traits/WithLink.ts\"\nimport { withRotation } from \"document/models/CanvasTree/traits/WithRotation.ts\"\nimport { hasNonIdentityTransforms } from \"document/models/CanvasTree/traits/WithTransforms.ts\"\nimport { isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { hasAnyEffect } from \"document/models/CanvasTree/traits/utils/effects.ts\"\nimport { isPositionFixed } from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { assertNever } from \"library/utils/assert.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\nimport type { AncestorInfo, JSXContext } from \"./types.ts\"\n\nexport function computeRendersWithMotion(\n\tnodeInPrimaryOrVariant: CanvasNode,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n\tinCodeOverride: boolean,\n): boolean {\n\tif (ancestorInfo.inComponentSlot || inCodeOverride) {\n\t\t// All the following nodes:\n\t\t// - nodes inside code component slots, and their descendants\n\t\t// - nodes that have code overrides, and their descendants\n\t\t// must stay Motion elements. Code components and overrides can iterate\n\t\t// over any JSX they receive as props. Historically, all JSX we passed\n\t\t// to code overrides was Motion elements, so we need to keep doing that\n\t\t// to maintain a consistent API, and for backwards compatibility.\n\t\treturn true\n\t}\n\n\t// Rich Text and Images are hardcoded to render with motion.divs in their\n\t// implementation in the framer library. To ensure they get the appropriate\n\t// props, ensure we don't try to render them with plain divs.\n\tif (isRichTextNode(nodeInPrimaryOrVariant) || hasImageFill(nodeInPrimaryOrVariant)) return true\n\n\t// Relative Overlays expect to be able to set originX/originY on motion\n\t// style, so must be motion elements.\n\tif (hasFloatingPosition(nodeInPrimaryOrVariant)) return true\n\n\t// Column masonry layout requires motion elements to apply the HOC\n\tif (hasColumnMasonryLayout(nodeInPrimaryOrVariant)) return true\n\n\t// Fixed position layers need to provide a layoutScroll prop for layout transition calculations.\n\tif (isPositionFixed(nodeInPrimaryOrVariant) && experiments.isOn(\"layoutScroll\")) {\n\t\treturn true\n\t}\n\n\tconst hasMotionEvents =\n\t\twithFrameEvents(nodeInPrimaryOrVariant) &&\n\t\tframeMotionEventKeys.some(eventName => (nodeInPrimaryOrVariant[eventName]?.length ?? 0) > 0)\n\tif (hasMotionEvents) {\n\t\t// Nodes with Motion-specific events always need to be Motion components.\n\t\treturn true\n\t}\n\n\t// If the node is a link, use a motion element so we can bind `onTap`.\n\tif (hasLink(nodeInPrimaryOrVariant) && !isAnyTextNode(nodeInPrimaryOrVariant)) {\n\t\treturn true\n\t}\n\n\tif (isFlowEffectSupportedScopeType(ctx.scopeType)) {\n\t\t// FlowEffect will pass `layout` prop to its children, they must be motion elements to use the layout prop.\n\t\tif (isNodeFlowEffectItem(nodeInPrimaryOrVariant)) return true\n\t\tif (hasFlowEffect(nodeInPrimaryOrVariant)) return true\n\t\tif (isChildOfBreakpoint(ctx.tree, nodeInPrimaryOrVariant) && withFlowEffect(nodeInPrimaryOrVariant)) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tswitch (ctx.scopeType) {\n\t\tcase ScopeType.CanvasPage:\n\t\t\t// Canvas pages *can* be published to the web (as a part of a\n\t\t\t// prototype), but\n\t\t\t// 1) it\u2019s rare so we don\u2019t really care about Core Web Vitals there,\n\t\t\t// 2) canvas pages can transition between each other, which means\n\t\t\t// they all have to use Motion.\n\t\t\treturn true\n\t\tcase ScopeType.SmartComponent:\n\t\t\t// Normally, this would be something like\n\t\t\t//\n\t\t\t//   if (isVariant(nodeInPrimaryOrVariant)) return true\n\t\t\t//   return ctx.variants.length > 0\n\t\t\t//\n\t\t\t// like it was in the original version of motion.div \u2192 div\n\t\t\t// optimization (https://github.com/framer/FramerStudio/pull/15036).\n\t\t\t// However, smart component have an edge case around variables\n\t\t\t// (https://framer-team.slack.com/archives/CR3CYA1D4/p1692144042802409)\n\t\t\t// that\u2019s too tricky to solve quickly, so we\u2019re completely disabling\n\t\t\t// the optimization for smart components for now.\n\t\t\treturn true\n\t\tcase ScopeType.LayoutTemplate:\n\t\tcase ScopeType.WebPage:\n\t\tcase ScopeType.DesignPage:\n\t\t\t// We keep the root node of a webpage as a motion.div for future compatibility\n\t\t\t// (eg in case we introduce webpage transitions in the router, etc).\n\t\t\t// https://framer-team.slack.com/archives/CR3CYA1D4/p1687335963587549?thread_ts=1687282640.591669&cid=CR3CYA1D4\n\t\t\tif (isVariant(nodeInPrimaryOrVariant)) return true\n\n\t\t\t// Any layer with transforms needs to be a motion.div to ensure that\n\t\t\t// descendant smart components that perform layout animations can\n\t\t\t// properly determine their size.\n\t\t\tif (hasNonIdentityTransforms(nodeInPrimaryOrVariant)) return true\n\n\t\t\t// Rotation is rendered in framer-motion's enhanced style.\n\t\t\tif (withRotation(nodeInPrimaryOrVariant)) {\n\t\t\t\tconst rotation = nodeInPrimaryOrVariant.rotation\n\t\t\t\tif (isDynamicValue(rotation)) return true\n\t\t\t\tif (isNumber(rotation) && rotation !== 0) return true\n\t\t\t}\n\t\t\t// Nodes *have* to use Motion components if they are animated \u2013\n\t\t\t// since only Motion components can do animations. For web pages,\n\t\t\t// that means nodes with effects on them.\n\t\t\treturn hasAnyEffect(nodeInPrimaryOrVariant)\n\t\tcase ScopeType.VectorSet:\n\t\t\t// VECTOR @TODO: depends on what we do with animations\n\t\t\treturn false\n\t\tdefault:\n\t\t\tassertNever(ctx.scopeType)\n\t}\n}\n", "import type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { SerializableObject, isSafeJS, isSerializableObject, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport { isArray, isBoolean, isNull, isNumber, isObject, isString, isSymbol, isUndefined } from \"utils/typeChecks.ts\"\n\n/**\n * A deep equality check that additionally resolves SafeJS.\n */\nexport function serializesToSameValue(a: unknown, b: unknown): boolean {\n\tif (Number.isNaN(a) && Number.isNaN(b)) return true\n\n\tif (a === b) return true\n\n\t// Comparison above will mean that the primitive values must be different.\n\tif (isNull(a) || isNull(b)) return false\n\tif (isString(a) || isString(b)) return false\n\tif (isUndefined(a) || isUndefined(b)) return false\n\tif (isNumber(a) || isNumber(b)) return false\n\tif (isBoolean(a) || isBoolean(b)) return false\n\tif (isSymbol(a) || isSymbol(b)) return false\n\n\tif (isSafeJS(a) || isSafeJS(b)) {\n\t\tif (isSafeJS(a) && isSafeJS(b)) return serializeJS(a) === serializeJS(b)\n\t\treturn false\n\t}\n\n\tif (isArray(a) || isArray(b)) {\n\t\tif (isArray(a) && isArray(b)) {\n\t\t\tif (a.length !== b.length) return false\n\n\t\t\tfor (let index = 0; index < a.length; index++) {\n\t\t\t\tif (!serializesToSameValue(a[index], b[index])) return false\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\tif (isObject(a) || isObject(b)) {\n\t\tif (isObject(a) && isObject(b)) {\n\t\t\tfor (const key in a) {\n\t\t\t\tif (!serializesToSameValue(a[key], b[key])) return false\n\t\t\t}\n\t\t\tif (Object.keys(a).length !== Object.keys(b).length) return false\n\n\t\t\tlet aSpreadsAtStart,\n\t\t\t\taSpreadsAtEnd,\n\t\t\t\tbSpreadsAtStart,\n\t\t\t\tbSpreadsAtEnd: SafeJS[] | undefined = undefined\n\n\t\t\tif (isSerializableObject(a)) {\n\t\t\t\taSpreadsAtStart = SerializableObject.spreadsAtStart(a)\n\t\t\t\taSpreadsAtEnd = SerializableObject.spreadsAtEnd(a)\n\t\t\t}\n\n\t\t\tif (isSerializableObject(b)) {\n\t\t\t\tbSpreadsAtStart = SerializableObject.spreadsAtStart(b)\n\t\t\t\tbSpreadsAtEnd = SerializableObject.spreadsAtEnd(b)\n\t\t\t}\n\n\t\t\tif (!serializesToSameValue(aSpreadsAtStart, bSpreadsAtStart)) return false\n\t\t\tif (!serializesToSameValue(aSpreadsAtEnd, bSpreadsAtEnd)) return false\n\n\t\t\tif (isSerializableObject(a) && isSerializableObject(b)) {\n\t\t\t\treturn SerializableObject.isSorted(a) === SerializableObject.isSorted(b)\n\t\t\t}\n\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\tthrow new Error(`Tried to compare unsupported primitive types. ${typeof a} / ${typeof b}`)\n}\n", "import { assertNever } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { serializesToSameValue } from \"./serializesToSameValue.ts\"\n\nfunction getDefaultUnsetValue(\n\tkey: string,\n\ttarget: \"css\" | \"js\",\n\t/** Different node types might have different default CSS values. */\n\tdefaultCSSValues?: Record<string, string | SafeJS>,\n) {\n\tswitch (target) {\n\t\tcase \"js\":\n\t\t\treturn js`undefined`\n\t\tcase \"css\": {\n\t\t\tif (defaultCSSValues && key in defaultCSSValues) return defaultCSSValues[key]\n\t\t\treturn \"unset\"\n\t\t}\n\t\tdefault:\n\t\t\tassertNever(target, `target is not a defined enum: ${target}`)\n\t}\n}\n\n/**\n * Return the difference between an input object and a comparison object. The\n * return object will be a new object which is a subset of the keys from the\n * input object with values that are different than the comparison object.\n * SafeJS values that serialize to the same string are considered equal.\n */\nexport function difference<T extends Record<string, unknown>>(\n\tinput: T | undefined,\n\tcomparison: T | undefined,\n\t/** If no target enum is provided, we will use plain `undefined`. */\n\ttarget?: \"css\" | \"js\",\n\t/** Different node types might have different default CSS values. */\n\tdefaultCSSValues?: Record<string, string | SafeJS>,\n): Partial<T> | undefined {\n\tif (!input) return undefined\n\tif (!comparison) return input\n\n\tconst output: Partial<T> = {}\n\tlet hasOverrides = false\n\n\tfor (const key in input) {\n\t\tconst inputValue = input[key]\n\t\tconst comparisonValue = comparison[key]\n\n\t\tif (serializesToSameValue(inputValue, comparisonValue)) continue\n\n\t\tif (!isUndefined(inputValue)) {\n\t\t\toutput[key] = inputValue\n\t\t\thasOverrides = true\n\t\t} else if (key in comparison) {\n\t\t\toutput[key as keyof T] = target ? (getDefaultUnsetValue(key, target, defaultCSSValues) as T[keyof T]) : undefined\n\t\t\thasOverrides = true\n\t\t}\n\t}\n\n\tif (!hasOverrides) return undefined\n\n\treturn output\n}\n", "import { isHocDefinition } from \"@framerjs/framer-runtime\"\nimport { isModuleExportIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport type { ComposedImport } from \"code-generation/utils/ImportCollector.ts\"\nimport { moduleImportSpecifiers } from \"code-generation/utils/ImportCollector.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { withCodeOverride } from \"document/models/CanvasTree/traits/WithCodeOverride.ts\"\nimport {\n\tcontrolValuesFromOverride,\n\twithCodeOverridesExperiment,\n} from \"document/models/CanvasTree/traits/WithCodeOverrides.ts\"\nimport type { JSXContext } from \"./types.ts\"\n\n/**\n * Returns the import and export specifiers for the code override component of a node,\n * performing the necessary checks to ensure that the override is valid.\n */\nexport const getValidOverrideImportSpecifiers = (\n\tnode: CanvasNode,\n\tctx: Pick<JSXContext, \"componentLoader\" | \"moduleType\" | \"modulesStore\" | \"imports\">,\n) => {\n\tif (!withCodeOverride(node) || !node.codeOverrideEnabled || !node.codeOverrideIdentifier) return\n\n\tconst overrideComponent = ctx.componentLoader.componentForIdentifier(node.codeOverrideIdentifier)\n\tif (!(overrideComponent && isHocDefinition(overrideComponent))) return\n\n\tconst overrideModuleIdentifier = parseModuleIdentifier(node.codeOverrideIdentifier)\n\tif (!isModuleExportIdentifier(overrideModuleIdentifier)) return\n\n\tconst { importSpecifier, exportSpecifier } = moduleImportSpecifiers(\n\t\toverrideModuleIdentifier,\n\t\tctx.moduleType,\n\t\tctx.componentLoader,\n\t\tctx.modulesStore,\n\t)\n\n\tif (!importSpecifier || !exportSpecifier) return\n\n\treturn { importSpecifier, exportSpecifier }\n}\n\nexport function createCodeOverrides(\n\tnode: CanvasNode,\n\tctx: Pick<JSXContext, \"componentLoader\" | \"moduleType\" | \"modulesStore\" | \"imports\">,\n): ComposedImport[] {\n\tconst bindings: ComposedImport[] = []\n\tif (experiments.isOn(\"overridesWithPropertyControls\") && withCodeOverridesExperiment(node) && node.codeOverrides) {\n\t\tfor (const override of node.codeOverrides) {\n\t\t\tconst overrideComponent = ctx.componentLoader.componentForIdentifier(override.identifier)\n\t\t\tif (!(overrideComponent && isHocDefinition(overrideComponent))) continue\n\n\t\t\tconst overrideModuleIdentifier = parseModuleIdentifier(override.identifier)\n\n\t\t\tif (!isModuleExportIdentifier(overrideModuleIdentifier)) continue\n\n\t\t\tconst binding = ctx.imports.addModuleImport(overrideModuleIdentifier)\n\t\t\tif (!binding) continue\n\n\t\t\tconst controls = controlValuesFromOverride(override)\n\t\t\tconst hasControls = Object.keys(controls).length > 0 && isSerializableValue(controls)\n\t\t\tbindings.push(hasControls ? [binding, controls] : binding)\n\t\t}\n\t}\n\n\treturn bindings\n}\n", "import { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport type { VariableType } from \"./WithVariables.ts\"\n\n/**\n * A map of variable types that are supported in the CMS. Inclusion / exclusion\n * here is probably more of a product decision. Some variable types will make more sense\n * than others to support.\n */\nconst supportedCollectionVariableTypes = {\n\t[ControlType.Array]: true,\n\t[ControlType.Boolean]: true,\n\t[ControlType.Border]: false,\n\t[ControlType.BorderRadius]: false,\n\t[ControlType.BoxShadow]: false,\n\t[ControlType.CollectionReference]: true,\n\t[ControlType.Color]: true,\n\t[ControlType.Cursor]: false,\n\t[ControlType.CustomCursor]: false,\n\t[ControlType.Date]: true,\n\t[ControlType.Enum]: true,\n\t[ControlType.EventHandler]: false,\n\t[ControlType.File]: true,\n\t[ControlType.Gap]: false,\n\t[ControlType.Image]: true,\n\t[ControlType.Link]: true,\n\t[ControlType.LinkRelValues]: false,\n\t[ControlType.Location]: false,\n\t[ControlType.MultiCollectionReference]: true,\n\t[ControlType.Number]: true,\n\t[ControlType.Padding]: false,\n\t[ControlType.RichText]: true,\n\t[ControlType.ScrollSectionRef]: false,\n\t[ControlType.String]: true,\n\t[ControlType.TrackingId]: false,\n\t[ControlType.Transition]: false,\n\t[ControlType.VectorSetItem]: true,\n\t[\"controlReference\"]: false,\n\t[\"nodePropertyControlReference\"]: false,\n\t[\"slug\"]: true,\n} as const satisfies Record<VariableType, boolean>\n\ntype SupportedCollectionVariableTypeMap = typeof supportedCollectionVariableTypes\n\nexport type CollectionVariableType = keyof {\n\t[Key in keyof SupportedCollectionVariableTypeMap as SupportedCollectionVariableTypeMap[Key] extends true\n\t\t? Key\n\t\t: never]: Key\n}\n\nexport function isCollectionVariableType(\n\tvariableType: VariableType | null | undefined,\n): variableType is CollectionVariableType {\n\treturn isString(variableType) && supportedCollectionVariableTypes[variableType] === true\n}\n", "import { isObject } from \"utils/typeChecks.ts\"\nimport { isCollectionVariableType, type CollectionVariableType } from \"./CollectionVariableType.ts\"\nimport type { VariableDefinition, VariableDivider, VariableOrDivider } from \"./WithVariables.ts\"\n\nexport type CollectionVariableDefinition = Extract<VariableDefinition, { type: CollectionVariableType }>\n\nexport function isCollectionVariableDefinition(\n\tdefinition: VariableDefinition | null | undefined,\n): definition is CollectionVariableDefinition {\n\treturn isObject(definition) && isCollectionVariableType(definition.type)\n}\n\nexport function isCollectionVariableDefinitionOrDivider(\n\tdefinition: VariableOrDivider | VariableDivider | null | undefined,\n): definition is CollectionVariableDefinition | VariableDivider {\n\treturn definition?.type === \"divider\" || isCollectionVariableDefinition(definition)\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { createContentManagementNodeIfNeeded } from \"document/components/chrome/contentManagement/utils/createContentManagementNodeIfNeeded.ts\"\nimport { createVariable } from \"document/components/chrome/properties/utils/createVariable.ts\"\nimport type {\n\tCanvasTree,\n\tCollectionItemNode,\n\tLoadedContentManagementNode,\n\tNodeID,\n} from \"document/models/CanvasTree/index.ts\"\nimport { CollectionNode } from \"document/models/CanvasTree/index.ts\"\nimport { getContentManagementNode } from \"document/models/CanvasTree/nodes/ContentManagementNode.utils.ts\"\nimport {\n\tisCollectionVariableDefinition,\n\ttype CollectionVariableDefinition,\n} from \"document/models/CanvasTree/traits/CollectionVariableDefinition.ts\"\nimport type { VariableType } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isVariableDefinition } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { getCollectionItemSlug } from \"utils/collectionUtils.ts\"\nimport { getCollectionForIdentifier } from \"utils/getCollectionForIdentifier.ts\"\nimport { isNull } from \"utils/typeChecks.ts\"\nimport type { KitCollectionTemplate, KitCollectionTemplateReference } from \"../sections/types.ts\"\nimport type { CollectionBinding } from \"../workers/generateWebPage/schema.ts\"\nimport type { KitSectionMeta, WireframerKit } from \"./wireframerKit.ts\"\n\ninterface CollectionReference {\n\tfield: string\n\tfromTemplate: string\n\tname: string\n}\n\nexport interface CollectionItemSnapshot {\n\tslug: string\n\t[controlPropKey: string]: unknown\n}\n\ninterface CollectionVariable {\n\tname: string\n\ttype: VariableType\n\treference?: { collection: string; kind: \"single\" | \"multi\" }\n}\n\nexport interface Collection {\n\tname: string\n\tvariables: CollectionVariable[]\n\titems: CollectionItemSnapshot[]\n\tcreatedFromKitTemplate?: string\n}\n\ninterface SnapshotOptions {\n\tfilterOnItemIds?: Set<NodeID>\n\tfullSnapshot?: boolean\n}\n\nexport function getExistingCollections(\n\ttree: CanvasTree,\n\tkit: WireframerKit,\n\tsnapshotOptions: SnapshotOptions = {},\n): Collection[] {\n\tconst contentManagementNode = ensureContentManagementNode(tree)\n\tconst snapshot = getCollectionsItemsSnapshot(tree, snapshotOptions)\n\n\tconst collectionNodes = contentManagementNode.children\n\n\t// Build a map of the template collections by id so we can easily lookup the template name by the collection id.\n\tconst templateCollectionsMap = new Map<NodeID, KitCollectionTemplate>()\n\tfor (const collection of kit.collections) {\n\t\ttemplateCollectionsMap.set(collection.id, collection)\n\t}\n\n\t// Build the collections array.\n\tconst collections: Collection[] = []\n\tfor (const collection of collectionNodes) {\n\t\tconst name = collection.resolveValue(\"name\")\n\t\tif (isNull(name)) continue\n\n\t\t// We map the collection to the template collection name if it was created from a template. This is because\n\t\t// we avoid using ids with the LLM.\n\t\tconst createdFromKitTemplate = collection.createdFromKitSchemaId\n\t\t\t? templateCollectionsMap.get(collection.createdFromKitSchemaId)\n\t\t\t: templateCollectionsMap.get(collection.id)\n\n\t\tconst variables: CollectionVariable[] = []\n\t\tfor (const variable of collection.variables) {\n\t\t\tif (!isVariableDefinition(variable)) continue\n\n\t\t\tif (variable.type !== ControlType.CollectionReference && variable.type !== ControlType.MultiCollectionReference) {\n\t\t\t\tvariables.push({\n\t\t\t\t\tname: variable.name,\n\t\t\t\t\ttype: variable.type,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// For references lets make sure we use the collection name so the LLM understands the relationship.\n\t\t\tconst targetCollection = getCollectionForIdentifier(tree, variable.dataIdentifier)\n\t\t\tassert(targetCollection, \"Target collection not found for variable\")\n\n\t\t\tconst collectionName = targetCollection.resolveValue(\"name\")\n\t\t\tassert(collectionName, \"Collection name not found\")\n\n\t\t\tvariables.push({\n\t\t\t\tname: variable.name,\n\t\t\t\ttype: variable.type,\n\t\t\t\treference: {\n\t\t\t\t\tcollection: collectionName,\n\t\t\t\t\tkind: variable.type === ControlType.CollectionReference ? \"single\" : \"multi\",\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\n\t\tcollections.push({\n\t\t\tname,\n\t\t\tvariables,\n\t\t\titems: snapshot.get(name) ?? [],\n\t\t\tcreatedFromKitTemplate: createdFromKitTemplate?.name,\n\t\t})\n\t}\n\n\treturn collections\n}\n\nexport function createCollectionLookup(tree: CanvasTree): Map<string, NodeID> {\n\tconst contentManagementNode = ensureContentManagementNode(tree)\n\n\tconst collectionLookup = new Map<string, NodeID>()\n\tfor (const collectionNode of contentManagementNode.children) {\n\t\tconst name = collectionNode.resolveValue(\"name\")\n\t\tif (isNull(name)) continue\n\n\t\tcollectionLookup.set(name, collectionNode.id)\n\t}\n\n\treturn collectionLookup\n}\n\nfunction ensureContentManagementNode(tree: CanvasTree): LoadedContentManagementNode {\n\tconst contentManagementNode = getContentManagementNode(tree)\n\tassert(contentManagementNode, \"Content management node not found\")\n\n\t// Fix if content management node ever becomes shallow.\n\tconst loadedContentManagementNode = contentManagementNode.loaded\n\tassert(loadedContentManagementNode, \"Content management node not loaded\")\n\n\treturn loadedContentManagementNode\n}\n\nfunction getCollectionsItemsSnapshot(\n\ttree: CanvasTree,\n\tsnapshotOptions: SnapshotOptions = {},\n): Map<string, CollectionItemSnapshot[]> {\n\tconst contentManagementNode = ensureContentManagementNode(tree)\n\n\tconst result = new Map<string, CollectionItemSnapshot[]>()\n\tconst { filterOnItemIds } = snapshotOptions\n\n\tfor (const collectionNode of contentManagementNode.children) {\n\t\tconst name = collectionNode.resolveValue(\"name\")\n\t\tif (isNull(name)) continue\n\n\t\tconst slugVariable = collectionNode.getSlugVariable()\n\t\tconst snapshots: CollectionItemSnapshot[] = []\n\n\t\tfor (const item of collectionNode.getUnsortedChildren()) {\n\t\t\tif (filterOnItemIds && !filterOnItemIds.has(item.id)) continue\n\n\t\t\tconst itemSlug = getCollectionItemSlug(item, slugVariable)\n\t\t\tif (!itemSlug) continue\n\n\t\t\tif (!snapshotOptions?.fullSnapshot) {\n\t\t\t\tsnapshots.push({ slug: itemSlug })\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsnapshots.push({ ...getFieldValuesByName(collectionNode, item), slug: itemSlug })\n\t\t}\n\n\t\tresult.set(name, snapshots)\n\t}\n\n\treturn result\n}\n\nfunction getFieldValuesByName(collection: CollectionNode, item: CollectionItemNode): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {}\n\tfor (const variable of collection.variables) {\n\t\tif (!isVariableDefinition(variable)) continue\n\t\tconst controlProp = item.getControlProp(variable.id)\n\t\tresult[variable.name.toLowerCase()] = controlProp?.value ?? variable.initialValue ?? null\n\t}\n\treturn result\n}\n\nexport function getCollectionsBuiltFromTemplate(tree: CanvasTree, collectionTemplateId: string): string[] {\n\tconst contentManagementNode = ensureContentManagementNode(tree)\n\n\tconst collectionNames: string[] = []\n\tfor (const collectionNode of contentManagementNode.children) {\n\t\tif (isNull(collectionNode.name)) continue\n\n\t\t// If the collection is not the same template (local kits) or is not built from the template, skip it.\n\t\tif (collectionNode.id !== collectionTemplateId && collectionNode.createdFromKitSchemaId !== collectionTemplateId) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst collectionName = collectionNode.resolveValue(\"name\")\n\t\tassert(collectionName, \"Collection name not found\")\n\t\tcollectionNames.push(collectionName)\n\t}\n\n\treturn collectionNames\n}\n\nexport function getReferencedCollections(tree: CanvasTree, collection: CollectionNode): CollectionNode[] {\n\tconst referenced: CollectionNode[] = []\n\n\tfor (const variable of collection.variables) {\n\t\tif (!isVariableDefinition(variable)) continue\n\t\tif (variable.type !== ControlType.CollectionReference && variable.type !== ControlType.MultiCollectionReference) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst targetCollection = getCollectionForIdentifier(tree, variable.dataIdentifier)\n\t\tassert(targetCollection, `Referenced collection for field \"${variable.name}\" not found`)\n\t\treferenced.push(targetCollection)\n\t}\n\n\treturn referenced\n}\n\nfunction getReferenceCollectionFromKitOrTree(\n\ttree: CanvasTree,\n\tkit: WireframerKit,\n\tname: string,\n\tvariableReference: KitCollectionTemplateReference,\n\treferences: CollectionReference[],\n) {\n\tconst templateCollection = kit.getCollectionTemplate(variableReference.collection)\n\tassert(templateCollection, `Collection with alias ${variableReference.collection} not found`)\n\n\t// Find the actual collection name from the action's references array\n\tconst taskReference = references.find(\n\t\treference => reference.field === name && variableReference.collection === reference.fromTemplate,\n\t)\n\n\tconst targetCollectionName = taskReference?.name\n\tif (!targetCollectionName) return\n\n\tconst targetCollection = findCollection(tree, templateCollection.id, targetCollectionName)\n\tassert(\n\t\ttargetCollection,\n\t\t`Referenced collection for template \"${templateCollection.name}\" not found. Plan must create it first.`,\n\t)\n\treturn targetCollection\n}\n\nexport function createCollection(\n\ttree: CanvasTree,\n\tkit: WireframerKit,\n\tname: string,\n\ttemplateCollection: KitCollectionTemplate,\n\treferences: CollectionReference[] = [],\n\tgetReferenceCollection?: (collection: string) => CollectionNode | undefined,\n): CollectionNode {\n\tconst variables: CollectionVariableDefinition[] = []\n\tfor (const variable of templateCollection.variables) {\n\t\tconst { defaultValueSuggestions, reference: variableReference, ...variableDefinition } = variable\n\n\t\t// For references we need to create the variables for the referenced collections.\n\t\tif (\n\t\t\tvariableDefinition.type === ControlType.CollectionReference ||\n\t\t\tvariableDefinition.type === ControlType.MultiCollectionReference\n\t\t) {\n\t\t\tassert(variableReference, \"Reference is required\")\n\n\t\t\t// When a callback is provided to get the appropriate reference collection, skip\n\t\t\t// creating a reference if the callback returns undefined.\n\t\t\tconst targetCollection = getReferenceCollection\n\t\t\t\t? getReferenceCollection(variableReference.collection)\n\t\t\t\t: getReferenceCollectionFromKitOrTree(tree, kit, variable.name, variableReference, references)\n\t\t\tif (!targetCollection) continue\n\n\t\t\tconst newVariableDefinition = createVariable(\n\t\t\t\t{\n\t\t\t\t\t...variableDefinition,\n\t\t\t\t\tdataIdentifier: targetCollection.instanceIdentifier,\n\t\t\t\t},\n\t\t\t\t\"collection\",\n\t\t\t)\n\t\t\tassert(isCollectionVariableDefinition(newVariableDefinition), \"Invalid collection variable definition\")\n\t\t\tvariables.push(newVariableDefinition)\n\t\t\tcontinue\n\t\t}\n\n\t\tconst newVariableDefinition = createVariable(variableDefinition, \"collection\")\n\t\tassert(isCollectionVariableDefinition(newVariableDefinition), \"Invalid collection variable definition\")\n\t\tvariables.push(newVariableDefinition)\n\t}\n\n\treturn new CollectionNode({\n\t\tname,\n\t\tvariables,\n\t\t// KITS @TODO: Add kit id to the collection node to avoid clashing with other kits template collections.\n\t\tcreatedFromKitSchemaId: templateCollection.id,\n\t})\n}\n\nfunction findCollection(tree: CanvasTree, templateCollectionId: NodeID, name: string): CollectionNode | undefined {\n\tconst contentManagementNode = createContentManagementNodeIfNeeded(tree)\n\n\treturn contentManagementNode.children.find(\n\t\tchild =>\n\t\t\t(child.id === templateCollectionId || child.createdFromKitSchemaId === templateCollectionId) &&\n\t\t\tchild.resolveValue(\"name\") === name,\n\t)\n}\n\ninterface CollectionDependency {\n\tid: string\n\tname: string\n\tnew: boolean\n}\n\n/**\n * Given a section (fields) and the bindings (CollectionBindings) selected by the worker, determine the order they should\n * be created by establishing the dependency graph.\n */\nexport function createCollectionDependencyMap(\n\tsection: KitSectionMeta,\n\tbindings: CollectionBinding[],\n\tkit: WireframerKit,\n): CollectionDependency[] {\n\t// Create a map from template collection name to actual collection name\n\tconst templateToCollectionMap = new Map<string, Pick<CollectionDependency, \"name\" | \"new\">>()\n\tfor (const binding of bindings) {\n\t\ttemplateToCollectionMap.set(binding.fromTemplateCollection, { name: binding.collectionName, new: binding.new })\n\t}\n\n\tconst dependencies = new Map<string, Set<string>>()\n\n\t// Iterate through the cms connected fields of the section to create the dependency graph.\n\tfor (const field of section.fields) {\n\t\tif (!field.isCMSConnectedField) continue\n\n\t\tconst collectionTemplateName = kit.getCollectionTemplateById(field.collectionId)?.name\n\t\tif (!collectionTemplateName) continue\n\n\t\tconst deps = dependencies.get(collectionTemplateName) ?? new Set()\n\t\tif (field.reference?.collectionId) {\n\t\t\tconst referenceCollectionTemplateName = kit.getCollectionTemplateById(field.reference.collectionId)?.name\n\t\t\tif (!referenceCollectionTemplateName) continue\n\n\t\t\tdeps.add(referenceCollectionTemplateName)\n\n\t\t\t// Ensure referenced collections are also tracked, even if they don't have fields\n\t\t\tif (!dependencies.has(referenceCollectionTemplateName)) {\n\t\t\t\tdependencies.set(referenceCollectionTemplateName, new Set())\n\t\t\t}\n\t\t}\n\t\tdependencies.set(collectionTemplateName, deps)\n\t}\n\n\t// Build reverse dependency graph.\n\tconst reverseDeps = new Map<string, Set<string>>()\n\tfor (const [collectionId, deps] of dependencies) {\n\t\tfor (const dep of deps) {\n\t\t\tconst reverse = reverseDeps.get(dep) ?? new Set()\n\t\t\treverse.add(collectionId)\n\t\t\treverseDeps.set(dep, reverse)\n\t\t}\n\t}\n\n\t// Calculate the number of dependencies for each collection\n\tconst dependencyCount = new Map<string, number>()\n\tfor (const collectionId of dependencies.keys()) {\n\t\tconst deps = dependencies.get(collectionId)\n\t\tdependencyCount.set(collectionId, deps?.size ?? 0)\n\t}\n\n\t// Topological sort: start with collections that have no dependencies\n\tconst orderedCollectionIds: string[] = []\n\tconst queue: string[] = []\n\n\tfor (const [collectionId, count] of dependencyCount) {\n\t\tif (count !== 0) continue\n\t\tqueue.push(collectionId)\n\t}\n\n\twhile (queue.length > 0) {\n\t\tconst collectionId = queue.shift()\n\t\tassert(collectionId, \"Collection ID must exist when the queue is not empty\")\n\t\torderedCollectionIds.push(collectionId)\n\n\t\t// Reduce count of collections that depend on this one\n\t\tconst dependents = reverseDeps.get(collectionId)\n\t\tif (!dependents) continue\n\n\t\tfor (const dependent of dependents) {\n\t\t\tconst currentCount = dependencyCount.get(dependent) ?? 0\n\t\t\tif (currentCount === 0) continue\n\n\t\t\tconst nextCount = currentCount - 1\n\t\t\tdependencyCount.set(dependent, nextCount)\n\n\t\t\tif (nextCount !== 0) continue\n\t\t\tqueue.push(dependent)\n\t\t}\n\t}\n\n\t// Map the sorted collections to the CollectionBindings from the LLM.\n\tconst result: CollectionDependency[] = []\n\tfor (const collectionId of orderedCollectionIds) {\n\t\tconst collectionInfo = templateToCollectionMap.get(collectionId)\n\t\tif (!collectionInfo) continue\n\n\t\tresult.push({\n\t\t\tid: collectionId,\n\t\t\tname: collectionInfo.name,\n\t\t\tnew: collectionInfo.new,\n\t\t})\n\t}\n\n\treturn result\n}\n\nexport function getExistingCollectionSnapshot(\n\ttree: CanvasTree,\n\tkit: WireframerKit,\n\tcollection: CollectionNode,\n\tsnapshotOptions: SnapshotOptions = {},\n): Collection {\n\tconst collectionName = collection.resolveValue(\"name\")\n\tassert(collectionName, \"Collection must have a name\")\n\n\tconst collectionsWithSnapshots = getExistingCollections(tree, kit, snapshotOptions)\n\tconst snapshot = collectionsWithSnapshots.find(entry => entry.name === collectionName)\n\tassert(snapshot, `Collection snapshot for \"${collectionName}\" not found`)\n\treturn snapshot\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isKitPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { type WithCustomizations, withCustomizations } from \"document/models/CanvasTree/traits/WithCustomizations.ts\"\nimport { withKitSectionSource } from \"document/models/CanvasTree/traits/WithKitSectionSource.ts\"\nimport { isBreakpointVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport type { KitCollectionTemplate } from \"../sections/types.ts\"\nimport { getCollectionsBuiltFromTemplate } from \"./collections.ts\"\nimport type { AvailableKitSectionField, KitSectionMeta } from \"./wireframerKit.ts\"\n\n/**\n * Gets a kit section node id.\n * This method enabled backwards compatibility with the customizationsSectionId logic.\n *\n * TODO: Remove this method once we migrate fAI Wireframer kit to a real kit. Use section.id instead.\n *\n * @param section The kit section node.\n * @returns The kit section id.\n */\nexport function getKitSectionId(section: CanvasNode & WithCustomizations): string {\n\treturn section.customizationsSectionId ?? section.id\n}\n\n/**\n * Gets a kit section id used to generate given section.\n * This method enabled backwards compatibility with the customizationsSectionId logic.\n *\n * TODO: Remove this method once we migrate fAI Wireframer kit to a real kit. Access section.kitSectionSource?.section.\n *\n * @param section The generated section node.\n * @returns The kit section id.\n */\nexport function getKitSectionIdFromGeneratedSection(node: CanvasNode): NodeID | string | undefined {\n\tif (withKitSectionSource(node) && node.kitSectionSource) {\n\t\treturn node.kitSectionSource?.section\n\t}\n\n\tif (!withCustomizations(node)) return\n\n\treturn node.customizationsSectionId\n}\n\n/**\n * Checks if a node is a kit section node. A node is a kit section node if it supports the with customizations trait,\n * if is direct child of a breakpoint variant in a kit web page node.\n *\n * @param tree The canvas tree.\n * @param node The node to check.\n * @returns True if the node is a kit section node, false otherwise.\n */\nexport function isKitSectionNode(tree: CanvasTree, node: CanvasNode): boolean {\n\tif (!withCustomizations(node)) return false\n\n\tconst parent = tree.getParent(node.id)\n\tif (!isBreakpointVariant(parent)) return false\n\n\tconst webPageNode = tree.getScopeNodeFor(parent)\n\n\treturn isKitPageNode(webPageNode)\n}\n\nexport const CREATE_NEW_COLLECTION_ALIAS = \"$NEW\"\n\ninterface SerializedKitSection {\n\tid: string\n\tdescription: string\n\trules: readonly string[] | undefined\n\tfields: readonly Omit<AvailableKitSectionField, \"collectionId\">[]\n\tsupportedCollections: Record<string, string[]>\n\tdetailPageTemplateId: string | undefined\n\tlayoutId: string | undefined\n\tsingleton: boolean | undefined\n}\n\nexport function serializeKitSection(\n\ttree: CanvasTree,\n\tcollectionTemplates: KitCollectionTemplate[],\n\tsection: KitSectionMeta,\n): SerializedKitSection {\n\tconst collectionTemplatesUsed = new Map<string, string>()\n\n\t// 1. Collect collection template names from fields\n\tfor (const field of section.fields) {\n\t\tif (!field.isCMSConnectedField) continue\n\t\tif (collectionTemplatesUsed.has(field.collectionId)) continue\n\n\t\tconst collectionTemplate = collectionTemplates.find(template => template.id === field.collectionId)\n\t\tassert(collectionTemplate, \"Collection template must be defined\")\n\n\t\tcollectionTemplatesUsed.set(field.collectionId, collectionTemplate.name)\n\t}\n\n\t// 2. Build a supported collections map by template id alias to collection names.\n\tconst supportedCollections: Record<string, string[]> = {}\n\tfor (const [collectionTemplateId, alias] of collectionTemplatesUsed) {\n\t\tconst existingCollectionNames = getCollectionsBuiltFromTemplate(tree, collectionTemplateId)\n\t\t// Append \"$NEW\" to every template's supported collections list to ensure it is not\n\t\t// ambiguous whether or not the LLM must choose an existing collection.\n\t\tsupportedCollections[alias] = [...existingCollectionNames, CREATE_NEW_COLLECTION_ALIAS]\n\t}\n\n\t// 3. Add collection property to CMS fields to reference the collection alias.\n\tconst serializedFields = section.fields.map(field => {\n\t\tif (!field.isCMSConnectedField) return field\n\n\t\tconst alias = collectionTemplatesUsed.get(field.collectionId)\n\t\tassert(alias, \"Alias must be defined\")\n\t\t// Extract collectionId to avoid serializing it.\n\t\tconst { collectionId, reference, ...rest } = field\n\n\t\t// Update references to use the collection alias instead of the target collection id.\n\t\tconst newReference = reference\n\t\t\t? { ...reference, collection: collectionTemplatesUsed.get(reference.collectionId) }\n\t\t\t: undefined\n\n\t\treturn {\n\t\t\t...rest,\n\t\t\tcollection: alias,\n\t\t\treference: newReference,\n\t\t}\n\t})\n\n\treturn {\n\t\tid: section.id,\n\t\tdescription: section.description,\n\t\trules: section.rules,\n\t\tsupportedCollections,\n\t\tsingleton: section.moduleIdentifier ? true : undefined,\n\t\tfields: serializedFields,\n\t\tdetailPageTemplateId: collectionTemplates.find(template => template.id === section.detailPageCollectionId)?.name,\n\t\tlayoutId: section.layoutId,\n\t}\n}\n", "import type { SetVariableValueOptions } from \"@framerjs/framer-runtime\"\nimport { type EventAction, isEventAction } from \"document/models/EventAction.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport type { CanvasNode } from \"../nodes/CanvasNode.ts\"\nimport { isSmartComponentNode, isWebPageNode } from \"../nodes/utils/nodeCheck.ts\"\nimport {\n\ttype VariableDefinition,\n\ttype VariableOrDivider,\n\ttype VariableType,\n\tisVariableDefinition,\n} from \"../traits/WithVariables.ts\"\nimport { HardCodedCodeIdentifier } from \"../traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport type { ActionControlValues } from \"./actions.ts\"\n\ntype SetVariableValueActionControls = ActionControlValues<SetVariableValueOptions>\n\nexport interface SetVariableValueAction extends EventAction {\n\tcontrols: SetVariableValueActionControls\n}\n\nexport function isSetVariableValueAction(value: unknown): value is SetVariableValueAction {\n\treturn isEventAction(value) && value.actionIdentifier === HardCodedCodeIdentifier.setVariableValueAction\n}\n\nexport function isValidScopeNodeForSetVariableValueAction(node: CanvasNode | null | undefined) {\n\treturn isWebPageNode(node) || isSmartComponentNode(node)\n}\n\nconst supportedVariableTypes = {\n\t[ControlType.Array]: false,\n\t[ControlType.Boolean]: true,\n\t[ControlType.Color]: false,\n\t[ControlType.EventHandler]: false,\n\t[ControlType.Image]: false,\n\t[ControlType.Number]: true,\n\t[ControlType.String]: true,\n\t[ControlType.RichText]: false,\n\t[ControlType.Link]: false,\n\t[ControlType.LinkRelValues]: false,\n\t[ControlType.Date]: true,\n\t[ControlType.Enum]: true,\n\t[ControlType.File]: false,\n\t[ControlType.ScrollSectionRef]: false,\n\t[ControlType.CustomCursor]: false,\n\t[ControlType.Cursor]: false,\n\t[ControlType.Transition]: false,\n\t[ControlType.Border]: false,\n\t[ControlType.BoxShadow]: false,\n\t[ControlType.Gap]: false,\n\t[ControlType.Padding]: false,\n\t[ControlType.BorderRadius]: false,\n\t[ControlType.CollectionReference]: true,\n\t[ControlType.MultiCollectionReference]: true,\n\t[ControlType.TrackingId]: false,\n\t[ControlType.VectorSetItem]: false,\n\t[ControlType.Location]: false,\n\tcontrolReference: true,\n\tnodePropertyControlReference: false,\n\tslug: false,\n} as const satisfies Record<VariableType, boolean>\n\ntype SupportedVariableTypeMap = typeof supportedVariableTypes\n\ntype SupportedVariableType = keyof {\n\t[key in keyof SupportedVariableTypeMap as SupportedVariableTypeMap[key] extends true ? key : never]: key\n}\n\nexport function isValidVariableTypeForSetVariableValueAction(\n\ttype: VariableType | null | undefined,\n): type is SupportedVariableType {\n\treturn isString(type) && supportedVariableTypes[type] === true\n}\n\nexport type SetVariableActionSupportedVariableDefinition = Extract<VariableDefinition, { type: SupportedVariableType }>\n\nexport function isValidVariableForSetVariableValueAction(\n\tvariable: VariableOrDivider | null | undefined,\n): variable is SetVariableActionSupportedVariableDefinition {\n\treturn isVariableDefinition(variable) && isValidVariableTypeForSetVariableValueAction(variable.type)\n}\n", "import type { VerifiedControlDescription, VerifiedPropertyControls } from \"@framerjs/framer-runtime\"\nimport { hasDefaultAssetReference, hasVekterDefault, isDefaultResponsiveImage } from \"@framerjs/framer-runtime/sandbox\"\nimport { assert, shouldBeNever } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { RepeaterInfo } from \"code-generation/jsx/types.ts\"\nimport type { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport type { CSSVariableDefinitionCollector } from \"code-generation/utils/CSSVariableDefinitionCollector.ts\"\nimport type { CustomCursorCollector } from \"code-generation/utils/CustomCursorCollector.ts\"\nimport type { ElementIdCollector } from \"code-generation/utils/ElementIdCollector.ts\"\nimport type { FetchDataCollector } from \"code-generation/utils/FetchDataCollector.ts\"\nimport type { FontCollector } from \"code-generation/utils/FontCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport type { LocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type { VectorSetCollector } from \"code-generation/utils/VectorSetCollector.ts\"\nimport type { ValueTransformCollector } from \"code-generation/utils/valueTransformCollector/ValueTransformCollector.ts\"\nimport type { ScopeType } from \"document/utils/scopeType.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport type { RelativeNumber } from \"library/render/types/RelativeNumber.ts\"\nimport { isString, isUndefined } from \"utils/typeChecks.ts\"\nimport type { CanvasNode } from \"../CanvasTree/index.ts\"\nimport { compileRichTextForCodeGeneration } from \"../CanvasTree/nodes/utils/compileRichText.tsx\"\nimport { isComputedValue } from \"../CanvasTree/traits/ComputedValue.ts\"\nimport { isVariableReference } from \"../CanvasTree/traits/VariableReference.ts\"\nimport { fallbackAltText } from \"../CanvasTree/traits/WithAltText.ts\"\nimport type { LocaleId } from \"../CanvasTree/traits/WithLocales.ts\"\nimport { getLink, isLinkToURL } from \"../CanvasTree/traits/utils/Link.ts\"\nimport { hasAppliedOpenTypeFeatures } from \"../CanvasTree/utils/openType.ts\"\nimport { isNonNullLocalizedValue, type LocalizedTextValue, type LocalizedValues } from \"../LocalizedValue.ts\"\nimport { isRichTextDocument } from \"../richText/richTextStorage.ts\"\nimport type { ControlProp, ControlProps } from \"./ControlProp.ts\"\nimport { withLocalizableControlPropValue } from \"./ControlProp.ts\"\nimport { isFontValue, styleForFontValue } from \"./FontControlPropValue.ts\"\nimport {\n\ttype ControlPropResolvers,\n\tgetResolvedControlPropValue,\n\tgetResolvedControlPropValues,\n} from \"./getResolvedControlPropValues.ts\"\n\ninterface ControlPropContext {\n\timports: ImportCollector\n\tassets: AssetCollector\n\tlinks: LinkCollector\n\tfonts: FontCollector\n\tfetches: FetchDataCollector\n\tvariables?: VariableCollector\n\tvalueTransforms?: ValueTransformCollector\n\tlocalizedValues?: LocalizedValueCollector\n\telementIds?: ElementIdCollector\n\tcustomCursors?: CustomCursorCollector\n\tvectorSets?: VectorSetCollector\n\tcssVariableDefinitions?: CSSVariableDefinitionCollector\n\tscopeType?: ScopeType\n}\n\ninterface ControlPropOptions {\n\tcontext: ControlPropContext\n\trepeaterInfo?: RepeaterInfo\n\tresolveDefaults?: boolean\n}\n\nfunction getLocalizedStringValue(\n\tlocalizedValues: LocalizedValues<LocalizedTextValue> | undefined,\n\tlocaleId: LocaleId,\n): string | undefined {\n\tconst localizedValue = localizedValues?.[localeId]?.value\n\treturn isString(localizedValue) ? localizedValue : undefined\n}\n\nexport function getControlPropValuesForCodeGeneration(\n\tnode: CanvasNode,\n\tcontrols: VerifiedPropertyControls,\n\tcontrolProps: ControlProps,\n\toptions: ControlPropOptions,\n) {\n\tconst resolvers = getControlPropResolversForCodeGeneration(node, options)\n\treturn getResolvedControlPropValues(controls, controlProps, resolvers)\n}\n\nexport function getControlPropValueForCodeGeneration(\n\tnode: CanvasNode,\n\tcontrol: VerifiedControlDescription,\n\tcontrolProp: ControlProp,\n\toptions: ControlPropOptions,\n) {\n\tconst resolvers = getControlPropResolversForCodeGeneration(node, options)\n\treturn getResolvedControlPropValue(control, controlProp, resolvers)\n}\n\nfunction getControlPropResolversForCodeGeneration(\n\tnode: CanvasNode,\n\t{ context, repeaterInfo, resolveDefaults }: ControlPropOptions,\n): ControlPropResolvers<unknown, unknown, unknown> {\n\treturn {\n\t\tresolveAsset(value, control, controlProp, resolveImage) {\n\t\t\tlet src: string | undefined\n\n\t\t\tconst defaultAssetReference = hasDefaultAssetReference(control) ? control.__defaultAssetReference : undefined\n\n\t\t\t// Components will handle their own defaults, but shaders need defaults resolved.\n\t\t\tif (resolveDefaults || value !== defaultAssetReference) {\n\t\t\t\tconst asset = resolveImage ? context.assets.resolveResponsiveImage(value) : context.assets.resolve(value)\n\t\t\t\tsrc = asset?.src\n\t\t\t}\n\n\t\t\tif (!withLocalizableControlPropValue(controlProp) || !context.localizedValues) {\n\t\t\t\treturn src\n\t\t\t}\n\n\t\t\treturn context.localizedValues.add(src, controlProp.valueLocalized, localeId => {\n\t\t\t\tconst localizedValue = controlProp.valueLocalized?.[localeId]?.value\n\t\t\t\tif (!isString(localizedValue)) return\n\n\t\t\t\t// Components will handle their own defaults.\n\t\t\t\tif (localizedValue === defaultAssetReference) return js`undefined`\n\n\t\t\t\tconst asset = resolveImage\n\t\t\t\t\t? context.assets.resolveResponsiveImage(localizedValue)\n\t\t\t\t\t: context.assets.resolve(localizedValue)\n\t\t\t\treturn asset?.src\n\t\t\t})\n\t\t},\n\t\tresolveResponsiveImage(value, control, controlProp) {\n\t\t\tlet localizedAsset: SafeJS | undefined\n\n\t\t\tlet defaultAssetReference: string | undefined\n\t\t\tlet defaultPositionX: RelativeNumber | undefined\n\t\t\tlet defaultPositionY: RelativeNumber | undefined\n\n\t\t\tif (hasVekterDefault(control) && isDefaultResponsiveImage(control.__vekterDefault)) {\n\t\t\t\tdefaultAssetReference = control.__vekterDefault.assetReference\n\t\t\t\tdefaultPositionX = control.__vekterDefault.positionX\n\t\t\t\tdefaultPositionY = control.__vekterDefault.positionY\n\t\t\t} else if (hasDefaultAssetReference(control)) {\n\t\t\t\tdefaultAssetReference = control.__defaultAssetReference\n\t\t\t}\n\n\t\t\t// Components will handle their own defaults, but shaders need defaults resolved.\n\t\t\tif (\n\t\t\t\tresolveDefaults ||\n\t\t\t\tvalue !== defaultAssetReference ||\n\t\t\t\tcontrolProp.positionX !== defaultPositionX ||\n\t\t\t\tcontrolProp.positionY !== defaultPositionY\n\t\t\t) {\n\t\t\t\tlocalizedAsset = SafeJS.fromValue(context.assets.resolveResponsiveImage(value, { focalPoint: controlProp }))\n\t\t\t}\n\n\t\t\tif (context.localizedValues) {\n\t\t\t\tlocalizedAsset = context.localizedValues.add(localizedAsset, controlProp.valueLocalized, localeId => {\n\t\t\t\t\tconst localizedValue = controlProp.valueLocalized?.[localeId]\n\t\t\t\t\tif (!isNonNullLocalizedValue(localizedValue)) return\n\t\t\t\t\tif (!isString(localizedValue.value)) return\n\n\t\t\t\t\t// Components will handle their own defaults.\n\t\t\t\t\tif (\n\t\t\t\t\t\tlocalizedValue.value === defaultAssetReference &&\n\t\t\t\t\t\tlocalizedValue.imageFocalPoint?.positionX === defaultPositionX &&\n\t\t\t\t\t\tlocalizedValue.imageFocalPoint?.positionY === defaultPositionY\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn js`undefined`\n\t\t\t\t\t}\n\n\t\t\t\t\tconst resolvedAsset = context.assets.resolveResponsiveImage(localizedValue.value, {\n\t\t\t\t\t\tfocalPoint: localizedValue.imageFocalPoint,\n\t\t\t\t\t})\n\t\t\t\t\treturn SafeJS.fromValue(resolvedAsset)\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (!localizedAsset) return\n\t\t\tif (!context.valueTransforms) return localizedAsset\n\n\t\t\tlet localizedAlt: SafeJS | string = controlProp.alt ?? fallbackAltText\n\n\t\t\tif (context.localizedValues) {\n\t\t\t\tlocalizedAlt = context.localizedValues.add(localizedAlt, controlProp.altLocalized, localeId =>\n\t\t\t\t\tgetLocalizedStringValue(controlProp.altLocalized, localeId),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn context.valueTransforms.wrapInAddImageAlt(localizedAsset, SafeJS.fromValue(localizedAlt))\n\t\t},\n\t\tresolveDynamicValue(dynamicValue, control) {\n\t\t\tlet value: SafeJS | undefined\n\n\t\t\tif (isVariableReference(dynamicValue)) {\n\t\t\t\tassert(context.variables, \"Variables are not supported\")\n\t\t\t\tvalue = context.variables.create(dynamicValue)\n\t\t\t} else if (isComputedValue(dynamicValue)) {\n\t\t\t\tif (!context.valueTransforms) return\n\t\t\t\tassert(node.cache, \"Node cache must be passed in when computed values can be created\")\n\t\t\t\tvalue = context.valueTransforms.createComputedValue(dynamicValue, node, control)\n\t\t\t} else {\n\t\t\t\tshouldBeNever(dynamicValue)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (!context.valueTransforms) return value\n\n\t\t\tswitch (control.type) {\n\t\t\t\tcase ControlType.Image:\n\t\t\t\t\treturn context.valueTransforms.wrapInToImageSrc(value)\n\t\t\t\tcase ControlType.ResponsiveImage:\n\t\t\t\t\treturn context.valueTransforms.wrapInToResponsiveImage(value)\n\t\t\t\tcase ControlType.Gap:\n\t\t\t\tcase ControlType.Padding:\n\t\t\t\tcase ControlType.BorderRadius:\n\t\t\t\t\t// We are wrapping the value in a number to pixel string conversion, so users\n\t\t\t\t\t// always receive a string value. Should prevent some confusion.\n\t\t\t\t\treturn context.valueTransforms.wrapInNumberToPixelString(value)\n\t\t\t\tdefault:\n\t\t\t\t\treturn value\n\t\t\t}\n\t\t},\n\t\tresolveLink(_controlKey, controlProp, control) {\n\t\t\tconst linkValue = getLink(controlProp.value)\n\n\t\t\tif (isLinkToURL(linkValue) && context.localizedValues) {\n\t\t\t\tconst localizedValues = controlProp.valueLocalized\n\n\t\t\t\treturn context.localizedValues.add(linkValue.url, localizedValues, localeId =>\n\t\t\t\t\tgetLocalizedStringValue(localizedValues, localeId),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (isComputedValue(linkValue)) {\n\t\t\t\tif (!context.valueTransforms) return\n\t\t\t\tassert(node.cache, \"Node cache must be passed in when computed values can be created\")\n\t\t\t\tconst computedValueBinding = context.valueTransforms.createComputedValue(linkValue, node, control)\n\n\t\t\t\treturn context.links.createResolvedBinding(node, computedValueBinding)\n\t\t\t}\n\n\t\t\treturn context.links.resolve(node, linkValue, repeaterInfo)\n\t\t},\n\t\tresolvePageScope(link) {\n\t\t\treturn context.links.resolvePageScope(getLink(link))\n\t\t},\n\t\tresolveLocalizedValue(value, localizedValues) {\n\t\t\tassert(!isRichTextDocument(value), \"Rich text documents must be resolved through resolveRichText.\")\n\t\t\tif (!context.localizedValues) return value\n\t\t\treturn context.localizedValues.add(value, localizedValues, localeId =>\n\t\t\t\tgetLocalizedStringValue(localizedValues, localeId),\n\t\t\t)\n\t\t},\n\t\tresolveRichText(value, htmlLocalized) {\n\t\t\tconst defaultJSX = compileRichTextForCodeGeneration(value, {\n\t\t\t\tcollectors: context,\n\t\t\t\tnodeId: node.getPrimaryId(),\n\t\t\t})\n\t\t\tif (!context.localizedValues) return defaultJSX\n\n\t\t\treturn context.localizedValues.add(defaultJSX, htmlLocalized, (localeId, collectors) => {\n\t\t\t\tif (!htmlLocalized) return\n\n\t\t\t\tconst localizedValue = htmlLocalized[localeId]\n\t\t\t\tif (!isNonNullLocalizedValue(localizedValue)) return\n\n\t\t\t\treturn compileRichTextForCodeGeneration(localizedValue.value, {\n\t\t\t\t\tcollectors: {\n\t\t\t\t\t\t...context,\n\t\t\t\t\t\t...collectors,\n\t\t\t\t\t},\n\t\t\t\t\tnodeId: node.getPrimaryId(),\n\t\t\t\t})\n\t\t\t})\n\t\t},\n\t\tresolveFont(_controlKey, value) {\n\t\t\tif (!isFontValue(value)) return {}\n\t\t\tconst openType = hasAppliedOpenTypeFeatures(node)\n\t\t\tcontext.fonts.addFontObjectBySelector(value.fontSelector, openType)\n\t\t\treturn styleForFontValue(value)\n\t\t},\n\t\tresolveScrollSectionRef(_controlKey, value) {\n\t\t\tif (isUndefined(value)) return undefined\n\t\t\tif (isVariableReference(value)) return context.variables?.create(value)\n\t\t\tif (isString(value.target)) {\n\t\t\t\tconst info = context.elementIds?.scrollTargetInfo(value)\n\t\t\t\tif (info?.ref) return info.ref\n\t\t\t}\n\t\t\treturn undefined\n\t\t},\n\t\tresolveCustomCursor(controlKey, value) {\n\t\t\tif (isUndefined(value)) return undefined\n\t\t\tif (isVariableReference(value)) return context.variables?.create(value)\n\t\t\treturn context.customCursors?.addControl(controlKey, node, value)\n\t\t},\n\t\tresolveVectorSetItem(value, control) {\n\t\t\tif (isUndefined(value)) return undefined\n\t\t\treturn context.vectorSets?.resolveControl(value, control, node)\n\t\t},\n\t\tresolveColor(value) {\n\t\t\tif (!isString(value)) return value\n\t\t\treturn context.cssVariableDefinitions?.resolveColor(value) ?? value\n\t\t},\n\t}\n}\n", "import hash from \"@emotion/hash\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { type SafeJS, isSafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { type JSXContext, isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { getControlPropValuesForCodeGeneration } from \"document/models/controlProps/getControlPropValuesForCodeGeneration.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport type { CSSVariableName } from \"prosemirror/variables.ts\"\nimport { isNull, isNumber, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { isCodeComponentNode } from \"../../nodes/utils/nodeCheck.ts\"\n\nfunction isCSSCustomPropertyValue(value: unknown): value is string | number | null | undefined {\n\treturn !isSafeJS(value) && (isString(value) || isNumber(value) || isNull(value) || isUndefined(value))\n}\n\nexport function isVectorInstanceVariantProps(\n\tvalue: unknown,\n\tctx: JSXContext,\n): value is SafeJS | string | number | null | undefined {\n\tif (ctx.scopeType !== ScopeType.SmartComponent) return isCSSCustomPropertyValue(value)\n\treturn isSerializableValue(value)\n}\n\nexport const collectVectorInstanceVariables = styleCollector((node, style, ctx) => {\n\tif (!isCodeComponentNode(node) || !node.isVectorInstance || !isJSXContext(ctx)) return\n\tconst component = ctx.componentLoader.reactComponentForIdentifier(node.codeComponentIdentifier)\n\tif (!component) return\n\n\tconst controlProps = getControlPropValuesForCodeGeneration(\n\t\tnode,\n\t\tcomponent.properties,\n\t\tnode.getControlProps(component.properties),\n\t\t{\n\t\t\tcontext: ctx,\n\t\t\trepeaterInfo: undefined,\n\t\t},\n\t)\n\n\tfor (const key in controlProps) {\n\t\tconst value = controlProps[key]\n\t\tconst binding: CSSVariableName = `--${hash(key)}`\n\t\tif (!isVectorInstanceVariantProps(value, ctx)) continue\n\t\tstyle[binding] = value ?? undefined\n\t}\n})\n", "import type { SerializedVerifiedControlDescription } from \"@framerjs/framer-runtime\"\nimport { ModuleType } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { JSXContext } from \"code-generation/jsx/types.ts\"\nimport {\n\tisValidScopeNodeForSetVariableValueAction,\n\tisValidVariableForSetVariableValueAction,\n\tisValidVariableTypeForSetVariableValueAction,\n} from \"document/models/CanvasTree/actions/setVariableValueActions.ts\"\nimport type { CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { mapVariableProps } from \"document/models/CanvasTree/nodes/CodeComponentNode.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { withVariables } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isVectorInstanceVariantProps } from \"document/models/CanvasTree/traits/collectStyles/collectVectorInstanceVariables.ts\"\nimport type { UnknownProps } from \"document/models/CanvasTree/traits/utils/UnknownProps.ts\"\nimport { isStylableNode } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifierChecks.ts\"\nimport { ALL_IDENTIFIERS } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport { isVariableType } from \"document/models/CanvasTree/traits/utils/isVariableType.ts\"\nimport { getStyleForSupportedLayout } from \"document/models/CanvasTree/utils/getStyleForSupportedLayout.ts\"\nimport { getControlPropValuesForCodeGeneration } from \"document/models/controlProps/getControlPropValuesForCodeGeneration.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { objectKeys } from \"library/utils/objectKeys.ts\"\nimport { isObject, isUndefined } from \"utils/typeChecks.ts\"\nimport { attributesFromProps } from \"./attributesFromProps.ts\"\n\nexport function getAttributesFromCodeComponent(\n\tnode: CodeComponentNode,\n\tadditionalProps: UnknownProps | undefined,\n\tcontext: JSXContext,\n\tlastRepeaterId: string | undefined,\n) {\n\tconst unmappedProps = { ...additionalProps }\n\n\tif (ALL_IDENTIFIERS.has(node.codeComponentIdentifier)) {\n\t\tunmappedProps.__fromCodeComponentNode = true\n\t}\n\n\tconst component = context.componentLoader.reactComponentForIdentifier(node.codeComponentIdentifier)\n\tconst propertyControls = component?.properties\n\tif (propertyControls) {\n\t\tconst controlProps = node.getControlProps(propertyControls)\n\t\tconst controlPropValues = getControlPropValuesForCodeGeneration(node, propertyControls, controlProps, {\n\t\t\tcontext,\n\t\t\trepeaterInfo: lastRepeaterId ? context.repeaterInfo.get(lastRepeaterId) : undefined,\n\t\t})\n\n\t\tconst mutableVariableProvider = context.tree.getNodeWithTrait(context.scopeId, withVariables)\n\n\t\tif (\n\t\t\tnode.codeComponentIdentifier.includes(ModuleType.Canvas) &&\n\t\t\tisValidScopeNodeForSetVariableValueAction(mutableVariableProvider)\n\t\t) {\n\t\t\tfor (const eventKey in propertyControls) {\n\t\t\t\tconst control: SerializedVerifiedControlDescription | undefined = propertyControls[eventKey]\n\t\t\t\tif (control?.type !== ControlType.ChangeHandler) continue\n\n\t\t\t\tconst changedControlKey = control.changes\n\t\t\t\tconst changedControl = propertyControls[changedControlKey]\n\t\t\t\tif (!isVariableType(changedControl?.type)) continue\n\t\t\t\tif (!isValidVariableTypeForSetVariableValueAction(changedControl.type)) continue\n\n\t\t\t\tconst changedControlProp = controlProps[changedControlKey]\n\t\t\t\tconst variableReference = changedControlProp?.value\n\t\t\t\tif (!isVariableReference(variableReference)) continue\n\n\t\t\t\tconst providerId = variableReference.providerId ?? context.scopeId\n\t\t\t\tif (providerId !== mutableVariableProvider.id) continue\n\n\t\t\t\tconst variable = mutableVariableProvider.getVariable(variableReference.id)\n\t\t\t\tif (!isValidVariableForSetVariableValueAction(variable)) continue\n\n\t\t\t\tcontrolPropValues[eventKey] = context.variables.createSetter(variable.id)\n\t\t\t}\n\t\t}\n\n\t\t// Vector instances with properties that can be expressed as css custom properties don't\n\t\t// need to be provided as React props. Instead we can create custom property definitions in\n\t\t// the css rule of the container. This allows the values to be animated with variants, or\n\t\t// avoids having to duplicate the DOM for SSG differences.\n\t\tif (node.isVectorInstance) {\n\t\t\tfor (const key in controlPropValues) {\n\t\t\t\tconst value = controlPropValues[key]\n\t\t\t\t// CSS Variables don't support `true` values. This will cause React to unset the\n\t\t\t\t// default inline style custom property definition, allowing parent styles to apply\n\t\t\t\t// without rerendering via props.\n\t\t\t\tconst unset = context.scopeType !== ScopeType.SmartComponent ? true : undefined\n\t\t\t\tunmappedProps[key] = !isVectorInstanceVariantProps(value, context) ? value : unset\n\t\t\t}\n\t\t} else {\n\t\t\tObject.assign(unmappedProps, controlPropValues)\n\t\t}\n\t}\n\n\tconst props = mapVariableProps(context.componentLoader, node.codeComponentIdentifier, unmappedProps)\n\n\tconst actions = node.getActions(context.componentLoader)\n\tfor (const key in actions) {\n\t\tprops[key] = context.events?.addHandler({\n\t\t\tnode,\n\t\t\ttrigger: key,\n\t\t\tactionInfo: actions[key],\n\t\t})\n\t}\n\n\t// Vector instances don't need to respond to the style prop.\n\tif (node.isVectorInstance) return attributesFromProps(props)\n\n\tconst style = getStyleForSupportedLayout(node, context.componentLoader)\n\n\tif (isStylableNode(node)) {\n\t\t// Set styling props (e.g. background, border), but exclude the style\n\t\t// prop. The style value has already been provided via\n\t\t// `additionalProps`. We don't need to collect it again.\n\t\tObject.assign(props, node.getStylingProps(context.componentLoader, style, false))\n\t}\n\n\tconst mustRespondToStyleProp = node.id === context.rootId && context.scopeType !== ScopeType.SmartComponent\n\n\tconst styleKeys = style ? objectKeys(style) : []\n\tlet hasOverrideStyles = isObject(style) && styleKeys.length > 0 && styleKeys.some(key => !isUndefined(style[key]))\n\tif (isObject(style) && (hasOverrideStyles || mustRespondToStyleProp)) {\n\t\tif (mustRespondToStyleProp) {\n\t\t\tstyle.width = js`style?.width`\n\t\t\tstyle.height = js`style?.heigh`\n\t\t\thasOverrideStyles = true\n\t\t}\n\t}\n\n\t// We may have already provided an inline `style` prop via the\n\t// `additionalProps` argument. In that case, and if the code component\n\t// supports a `style` prop (if it is not a user-implemented code component\n\t// property control), we can augment those styles with some layout style.\n\tif (hasOverrideStyles) {\n\t\tif (props.style) {\n\t\t\tObject.assign(props.style as Record<string, unknown>, style)\n\t\t} else {\n\t\t\tprops.style = style\n\t\t}\n\t}\n\n\treturn attributesFromProps(props)\n}\n", "import { createAbsoluteImageAssetURL } from \"@framerjs/assets\"\nimport type { UnknownProps } from \"document/models/CanvasTree/traits/utils/UnknownProps.ts\"\nimport { domParser } from \"library/render/utils/dom.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport type { AssetCollector } from \"./AssetCollector.ts\"\n\nexport const assetRegex = /\\/assets\\/(?:(\\d+)\\/)?([^?]+)\\?/u\n\n// For SVGs that use images as their background, we have to make those assets public, and use the\n// correct href which is only known at runtime. This rewrites a static svg string into active\n// javascript that, when evaluated, will become the svg string.\nfunction processSvgImageAssets(svg: string, assets?: AssetCollector): string | undefined {\n\tif (typeof DOMParser === \"undefined\") return\n\n\tif (svg.indexOf(\"image\") < 0) return\n\n\tconst doc = domParser(svg)\n\tconst svgElement = doc.querySelector(\"svg\")\n\tif (!svgElement) return\n\n\tconst replacements = new Map<string, string>()\n\tdoc.querySelectorAll(\"image\").forEach(image => {\n\t\t// Find images pointing to assets.\n\t\tconst href = image.getAttribute(\"xlink:href\")\n\t\tif (!href) return\n\n\t\tconst match = assetRegex.exec(href)\n\t\tif (!match) return\n\n\t\tconst assetSize = Number.parseInt(match[1]!, 10)\n\t\tconst assetKeyWithExtension = match[2]!\n\t\tconst key = \"::ASSET::\" + replacements.size + \"::\"\n\t\tconst resolvedAsset = assets?.resolveResponsiveImage(assetKeyWithExtension)\n\t\tconst url = resolvedAsset?.src ?? createAbsoluteImageAssetURL(assetKeyWithExtension, assetSize)\n\t\treplacements.set(key, url)\n\n\t\t// Update the href here to a recognizable key. Because the template itself will be mangled by\n\t\t// uri encoding. We replace the key with the actual template after turning the SVG into a\n\t\t// string.\n\t\timage.setAttribute(\"xlink:href\", key)\n\t})\n\n\t// No actual asset reference was found. We can use the SVG string as is, no need to upgrade to\n\t// dynamic javascript.\n\tif (replacements.size === 0) return\n\n\t// Replace any template key with the actual template.\n\treturn svgElement.outerHTML.replace(/::ASSET::\\d+::/gu, key => replacements.get(key) ?? `missing:${key}`)\n}\n\nexport function processSvgImageAssetsAttribute(attributes: UnknownProps, assets?: AssetCollector) {\n\tconst svg = attributes.svg\n\tif (!isString(svg)) return\n\n\tattributes.svg = processSvgImageAssets(svg, assets) ?? svg\n}\n", "import { createAbsoluteImageAssetURL, parseAssetReference } from \"@framerjs/assets\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { ScopeNode } from \"document/models/CanvasTree/nodes/ScopeNode.ts\"\nimport { isShaderNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isPinnable } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { isPositionRelative } from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { isNull } from \"library/utils/utils.ts\"\n\n/** Determines if a shader's width is expected to change when the viewport width changes. */\nexport function doesShaderScaleWithViewport(node: CanvasNode): boolean {\n\tif (!isShaderNode(node)) return false\n\treturn hasViewportResponsiveWidth(node)\n}\n\nfunction hasViewportResponsiveWidth(node: CanvasNode): boolean {\n\tconst tree = node.tree()\n\tconst parent = tree?.getParent(node.id)\n\n\tif (node instanceof ScopeNode || tree?.isGroundNode(node)) return true\n\tif (withSizeDimensionType(node) && node.widthType === DimensionType.Viewport) return true\n\n\tif (widthDependsOnParent(node, parent)) {\n\t\tif (!parent) return true\n\t\treturn hasViewportResponsiveWidth(parent)\n\t}\n\n\treturn false\n}\n\nfunction widthDependsOnParent(node: CanvasNode, parent?: CanvasNode | null): boolean {\n\tif (\n\t\twithSizeDimensionType(node) &&\n\t\t(node.widthType === DimensionType.Percentage || node.widthType === DimensionType.FractionOfFreeSpace)\n\t) {\n\t\treturn true\n\t}\n\n\treturn isPinnable(node) && !isNull(node.left) && !isNull(node.right) && !isPositionRelative(node, parent)\n}\n\n/** Scales down a shader fallback image by half */\nexport function scaleDownShaderFallbackImage(shaderFallbackImage: string | undefined, src: string): string {\n\tif (!shaderFallbackImage) return src\n\tconst assetReference = parseAssetReference(shaderFallbackImage)\n\tconst intrinsicSize = assetReference?.intrinsicSize\n\tif (!assetReference || !intrinsicSize) return src\n\tconst maxSideSize = Math.max(intrinsicSize.width, intrinsicSize.height)\n\n\treturn createAbsoluteImageAssetURL(\n\t\tassetReference.identifier,\n\t\tMath.ceil(maxSideSize / 2),\n\t\tassetReference.preferredSize === \"lossless\",\n\t\tintrinsicSize,\n\t)\n}\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { hasAltText } from \"../WithAltText.ts\"\nimport { withAriaLabel } from \"../WithAriaLabel.ts\"\nimport { hasImageFill } from \"../WithFill.ts\"\nimport { scopeTypeSupportsA11yFeatures } from \"../utils/scopeTypeSupportsA11yFeatures.ts\"\n\nexport const collectAriaLabel = propCollector((node, props, context) => {\n\tif (!withAriaLabel(node)) return\n\tif (!scopeTypeSupportsA11yFeatures(context.scopeType)) return\n\n\t// An alt attribute is higher priority than an aria label, and we want to\n\t// avoid having both. When a dynamic value is assigned to an image it can\n\t// contain the alt text.\n\tif (hasAltText(node) || (hasImageFill(node) && isDynamicValue(node.fillImage))) {\n\t\tprops[\"aria-label\"] = undefined\n\t\treturn\n\t}\n\n\tif (isJSXContext(context) && isDynamicValue(node.ariaLabel)) {\n\t\tprops[\"aria-label\"] = context.createDeduplicatedDynamicValueBinding(node.ariaLabel, node, \"ariaLabel\")\n\t\treturn\n\t}\n\n\t// In general empty strings should be avoided for aria labels. Without an\n\t// aria-label, screen readers will try to use the content inside of the\n\t// element, which is likely to be better than nothing. So we avoid\n\t// explicitly setting it to an empty string.\n\tconst ariaLabel = node.resolveValue(\"ariaLabel\", context.variableOverrides)\n\tif (isString(ariaLabel) && ariaLabel !== \"\") {\n\t\t// The collector must transform our camel case prop into kebab case\n\t\t// in order for React to set the attribute on mount.\n\t\tprops[\"aria-label\"] = ariaLabel\n\t\treturn\n\t}\n\n\tprops[\"aria-label\"] = undefined\n})\n", "import { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isAnyTextNode } from \"../../nodes/utils/isAnyTextNode.ts\"\nimport { isFrameNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { hasImageFill } from \"../WithFill.ts\"\nimport { defaultHTMLTag } from \"../WithHTMLTag.ts\"\nimport { hasLink } from \"../WithLink.ts\"\n\nexport const collectAsProp = propCollector((node, props, ctx) => {\n\tconst nodeHasLink = hasLink(node)\n\tconst shouldRenderAsList = Boolean(node.parentid && ctx.renderAsListNodes?.has(node.parentid))\n\tconst rendersAsImageInAnyVariant = Boolean(ctx.nodesRenderedAsImageInAnyVariant?.has(node.getPrimaryId()))\n\n\t// We only support custom tags for frame nodes.\n\tif (!isFrameNode(node)) {\n\t\t// But SVG and ShapeContainers do support links and as: \"a\"\n\t\tif (!isAnyTextNode(node) && nodeHasLink) {\n\t\t\tprops.as = \"a\"\n\t\t}\n\n\t\tif (shouldRenderAsList) {\n\t\t\tprops.as = \"li\"\n\t\t\treturn\n\t\t}\n\n\t\treturn\n\t}\n\n\tconst frameNode = node\n\n\t// If this frame is linked and rendered through the Image component, it must be an anchor tag.\n\tif (nodeHasLink && (hasImageFill(frameNode) || rendersAsImageInAnyVariant)) {\n\t\tprops.as = \"a\"\n\t\treturn\n\t}\n\n\tconst htmlTag = frameNode.htmlTag ?? defaultHTMLTag\n\n\t// Currently we are only passing non-link custom tags via `as` to the\n\t// Image component.\n\tif (!hasImageFill(frameNode)) return\n\n\tif (shouldRenderAsList) {\n\t\tprops.as = \"li\"\n\t\treturn\n\t}\n\n\tif (htmlTag === \"div\") return\n\n\tprops.as = htmlTag\n})\n", "import { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { toMotionTransition } from \"document/models/Transition.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { fallbackBackdropTransition, withBackdrop } from \"../WithBackdrop.ts\"\n\nexport const collectBackdrop = propCollector((node, props, context) => {\n\tif (!withBackdrop(node)) return\n\tif (!isJSXContext(context)) return\n\n\tconst overlayId = node.getPrimaryId()\n\tconst binding = context.overlays.bindingsByOverlayId.get(overlayId)\n\tif (!binding) return\n\n\tif (isDynamicValue(node.backdropDismissible)) {\n\t\tprops.onTap = js`() => ${context.createDeduplicatedDynamicValueBinding(\n\t\t\tnode.backdropDismissible,\n\t\t\tnode,\n\t\t\t\"backdropDismissible\",\n\t\t)} && ${SafeJS.fn(js`${binding}.hide`)}`\n\t} else {\n\t\tprops.onTap = node.resolveValue(\"backdropDismissible\") ? js`() => ${SafeJS.fn(js`${binding}.hide`)}` : undefined\n\t}\n\n\tprops.initial = { opacity: 0 }\n\tprops.key = overlayId\n\n\t// If the backdrop transition is locked, we can reduce the number of\n\t// properties we write to the template, since the transition can be set on\n\t// the backdrop and reused for both enter and exit.\n\tif (node.backdropTransitionLocked) {\n\t\tprops.transition = toMotionTransition(node.backdropEnterTransition ?? fallbackBackdropTransition)\n\t\tprops.animate = { opacity: 1 }\n\t\tprops.exit = { opacity: 0 }\n\t} else {\n\t\t// Otherwise we must create a unique transition for each target.\n\t\tprops.animate = {\n\t\t\topacity: 1,\n\t\t\ttransition: toMotionTransition(node.backdropEnterTransition ?? fallbackBackdropTransition),\n\t\t}\n\t\tprops.exit = {\n\t\t\topacity: 0,\n\t\t\ttransition: toMotionTransition(node.backdropExitTransition ?? fallbackBackdropTransition),\n\t\t}\n\t}\n})\n", "import { propCollector } from \"code-generation/utils/collector.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { DimensionType } from \"library/index.ts\"\nimport { withFill, withOptionalFill } from \"../WithFill.ts\"\nimport { withShape } from \"../WithShape.ts\"\nimport { getBackgroundAttributes } from \"../utils/collectBackgroundForNode.ts\"\n\nexport const collectBackgroundImage = propCollector((node, props, context) => {\n\tif (withShape(node)) return\n\tif (!withFill(node)) return\n\n\tif (withOptionalFill(node) && !node.fillEnabled) {\n\t\tprops.background = undefined\n\t\treturn\n\t}\n\n\tprops.background = getBackgroundAttributes(node, true, context)\n\tif (props.background && withSizeDimensionType(node)) {\n\t\tif (node.heightType === DimensionType.FitImage) {\n\t\t\tprops.fitImageDimension = \"height\"\n\t\t} else if (node.widthType === DimensionType.FitImage) {\n\t\t\tprops.fitImageDimension = \"width\"\n\t\t} else {\n\t\t\tprops.fitImageDimension = undefined\n\t\t}\n\t}\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { ConditionalRule } from \"code-generation/utils/CSSCollector.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { withBorder } from \"../WithBorder.ts\"\nimport { withFormInput } from \"../forms/WithFormInput.ts\"\n\nexport const collectBorder = propCollector((node, props, context) => {\n\tif (!withBorder(node) || !node.borderEnabled) return\n\n\t// We do not want to apply the data-border attribute (which would result in the\n\t// global border rules being applied) to form plain text inputs, as the FormPlainTextInput\n\t// render component in library is responsible for rendering the border on inputs.\n\tif (withFormInput(node)) return\n\n\tprops[\"data-border\"] = true\n\n\t// If we're in a JSX context, we need to add a conditional rule to the CSS\n\t// collector, so that the CSS collector knows to include the border rules in\n\t// the generated module. See borderRules in\n\t// src/app/vekter/src/code-generation/components/shared.ts\n\tif (isJSXContext(context)) context.css.addConditionalRule(ConditionalRule.Border)\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { HTMLTag, isHTMLTag, withHTMLTag } from \"../WithHTMLTag.ts\"\n\nexport const RESET_ATT_KEY = \"data-reset\"\n\nexport const collectCSSResetAttribute = propCollector((node, props, context) => {\n\tif (!isJSXContext(context)) return\n\tif (context.scopeType === ScopeType.CanvasPage || context.scopeType === ScopeType.DesignPage) return\n\tif (!withHTMLTag(node)) return\n\n\tif (!isHTMLTag(node.htmlTag)) {\n\t\tprops[RESET_ATT_KEY] = undefined\n\t\treturn\n\t}\n\n\t// * So far we only need to set a CSS reset attribute to the button\n\t// * tag to fix browser native display, but other tags could be\n\t// * extended too.\n\tif (node.htmlTag !== HTMLTag.button) return\n\n\tprops[RESET_ATT_KEY] = HTMLTag.button\n})\n", "import { type ModuleIdentifier, asLocalId, isExternalModuleIdentifier, isLocalModuleIdentifier } from \"@framerjs/shared\"\nimport type { CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isLocalModuleNode } from \"document/models/CanvasTree/nodes/LocalModuleNode.ts\"\nimport { isExternalModuleNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport type { PluginStore } from \"document/stores/PluginStore.ts\"\nimport type { TreeStore } from \"document/stores/TreeStore.ts\"\nimport type { PersistedModule } from \"modules/ModulesStorage.ts\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport type { VekterPluginManifest } from \"plugins/plugins.ts\"\nimport { isString, isUndefined } from \"utils/typeChecks.ts\"\n\nexport function getPluginIdFromModuleIdentifier(\n\ttree: CanvasTree,\n\tmodulesStore: ModulesStore,\n\tmoduleIdentifier: ModuleIdentifier | undefined,\n): string | undefined {\n\tconst nodeId = isLocalModuleIdentifier(moduleIdentifier) ? moduleIdentifier.localId : moduleIdentifier?.moduleId\n\tconst node = tree.get(nodeId)\n\tif (isExternalModuleNode(node)) return node.pluginId\n\tif (!isLocalModuleNode(node)) return\n\tif (!isUndefined(node.save.pluginId)) return node.save.pluginId\n\tconst persistedModule = modulesStore.getPersistedModuleByLocalId(asLocalId(node.id))\n\tif (!persistedModule) return\n\tconst pluginId = persistedModule.metadata[ModuleMetadata.PluginId]\n\tif (isString(pluginId)) return pluginId\n}\n\nexport function getPluginManifestFromModuleIdentifier(\n\ttreeStore: TreeStore,\n\tmodulesStore: ModulesStore,\n\tpluginStore: PluginStore,\n\tmoduleIdentifier: ModuleIdentifier | undefined,\n): VekterPluginManifest | undefined {\n\tconst pluginId = getPluginIdFromModuleIdentifier(treeStore.tree, modulesStore, moduleIdentifier)\n\tif (!isUndefined(pluginId)) return pluginStore.manifestById.get(pluginId)\n}\n\nexport function getEditInPluginLabel(pluginManifest: VekterPluginManifest): string {\n\treturn `Edit in ${pluginManifest.name}`\n}\n\nexport function shouldEditViaPlugin(\n\tmodulesStore: ModulesStore,\n\tmoduleIdentifier: ModuleIdentifier | undefined,\n): boolean {\n\tlet module: PersistedModule | undefined = undefined\n\tif (isExternalModuleIdentifier(moduleIdentifier)) {\n\t\tmodule = modulesStore.getPersistedModuleByGlobalId(moduleIdentifier.moduleId)\n\t} else if (isLocalModuleIdentifier(moduleIdentifier)) {\n\t\tmodule = modulesStore.getPersistedModuleByLocalId(moduleIdentifier.localId)\n\t}\n\n\tif (!module) return true\n\tif (module.metadata[ModuleMetadata.EditViaPlugin] === false) return false\n\n\treturn true\n}\n", "import type { ModuleType } from \"@framerjs/shared\"\nimport { isExternalModuleIdentifier, isLocalModuleIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport type { CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { ExternalModulesListNode } from \"document/models/CanvasTree/nodes/ExternalModuleNode.ts\"\n\n/**\n * Gets the ModuleType for a given identifier by checking if it\u2019s a local or external module\n */\nexport function moduleTypeForIdentifier(identifier: string, tree: CanvasTree): ModuleType | undefined {\n\tif (isLocalModuleIdentifier(identifier)) {\n\t\treturn parseModuleIdentifier(identifier).type\n\t}\n\n\tif (isExternalModuleIdentifier(identifier)) {\n\t\tconst nodes = ExternalModulesListNode.getModuleNodes(tree)\n\n\t\tconst entry = nodes.find(entry => entry.codeComponentIdentifier === identifier)\n\t\tif (!entry) return\n\n\t\treturn entry.type as ModuleType\n\t}\n\n\t// There should generally never be other types of identifiers, but we\u2019re\n\t// being defensive and not asserting.\n}\n", "import { ModuleType, isExternalModuleIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { nodeNeedsContainer } from \"code-generation/utils/builtInCodeComponents.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { getPluginIdFromModuleIdentifier } from \"document/components/utils/plugins.ts\"\nimport { moduleTypeForIdentifier } from \"utils/moduleTypeForIdentifier.ts\"\nimport { isCodeComponentNode } from \"../../nodes/utils/nodeCheck.ts\"\n\nexport const collectCodeComponentContainerProps = propCollector((node, props, ctx) => {\n\tif (!isCodeComponentNode(node)) return\n\tif (!isJSXContext(ctx)) return\n\tif (!nodeNeedsContainer(node)) return\n\n\t// scopeId and nodeId are used by the <Container> and <SmartComponentScopedContainer>\n\t// to log the broken node when <CodeComponentBoundary> catches an error.\n\t// More details: https://www.notion.so/framer/Code-Boundaries-153adf6e8c96803dbd27ffe5cfd1e874?pvs=4#153adf6e8c96807a877bd553559ee055\n\tprops.scopeId = ctx.scopeId\n\tprops.nodeId = node.getPrimaryId()\n\n\t// moduleType, isModuleExternal, and inComponentSlot are used by the <Container>\n\t// and <SmartComponentScopedContainer> to figure out if the component\n\t// should be wrapped in a <CodeComponentBoundary>\n\tprops.isAuthoredByUser =\n\t\tmoduleTypeForIdentifier(node.codeComponentIdentifier, ctx.tree) === ModuleType.Code ? true : undefined\n\n\tconst isModuleExternal = isExternalModuleIdentifier(node.codeComponentIdentifier)\n\tif (isModuleExternal) props.isModuleExternal = isModuleExternal\n\n\t// rendersWithMotion is used by the <SmartComponentScopedContainer> to know\n\t// how to render the smart component wrapper.\n\tconst rendersWithMotion = ctx.nodeRendersWithMotion.get(node)\n\tif (rendersWithMotion) props.rendersWithMotion = rendersWithMotion\n\n\tconst moduleIdentifier = parseModuleIdentifier(node.codeComponentIdentifier)\n\tprops[\"data-code-component-plugin-id\"] = getPluginIdFromModuleIdentifier(ctx.tree, ctx.modulesStore, moduleIdentifier)\n})\n", "import { propCollector } from \"code-generation/utils/collector.ts\"\nimport { hasDataNosnippet, withDataNosnippet } from \"../WithDataNosnippet.ts\"\nimport { scopeTypeSupportsA11yFeatures } from \"../utils/scopeTypeSupportsA11yFeatures.ts\"\n\nexport const collectDataNosnippet = propCollector((node, props, context) => {\n\tif (!withDataNosnippet(node)) return\n\tif (!scopeTypeSupportsA11yFeatures(context.scopeType)) return\n\n\tprops[\"data-nosnippet\"] = hasDataNosnippet(node) ? node.dataNosnippet : undefined\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { draggableDefaultValueFor, withDraggable } from \"../WithDraggable.ts\"\n\nexport const collectDraggable = propCollector((node, props, ctx) => {\n\tif (!withDraggable(node)) return\n\n\tconst draggable =\n\t\tisJSXContext(ctx) && isDynamicValue(node.draggable)\n\t\t\t? ctx.createDeduplicatedDynamicValueBinding(node.draggable, node, \"draggable\")\n\t\t\t: (node.resolveValue(\"draggable\") ?? draggableDefaultValueFor(node))\n\n\tprops.draggable = !isUndefined(draggable) && !isDynamicValue(node.draggable) ? draggable.toString() : draggable\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { scopeSupportsEventActions } from \"document/components/chrome/properties/utils/eventActions.ts\"\nimport { isScopeNode } from \"../../nodes/ScopeNode.ts\"\nimport { withCodeComponent } from \"../WithCodeComponent.ts\"\nimport { withEventActions } from \"../WithEventActions.ts\"\nimport { withFormInputEvents } from \"../forms/WithFormInputEvents.ts\"\n\nexport const collectEvents = propCollector((node, props, context) => {\n\tif (!isJSXContext(context)) return\n\tif (withCodeComponent(node)) return\n\tif (!withEventActions(node) && !withFormInputEvents(node)) return\n\n\tconst scope = context.tree.get(context.scopeId)\n\tif (!isScopeNode(scope)) return\n\tif (!scopeSupportsEventActions(scope)) return\n\n\tObject.assign(props, context.events?.eventHandlersForNode(node))\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { toMotionTransition } from \"document/models/Transition.ts\"\nimport { isFixedOrRelativeOverlay } from \"../../nodes/utils/overlayHelpers.ts\"\nimport {\n\tflowEffectEnabledDefaults,\n\thasFlowEffect,\n\tisFlowEffectSupportedScopeType,\n\tisNodeInFlowEffect,\n\twithFlowEffect,\n} from \"../WithFlowEffect.ts\"\n\nexport const collectFlowEffect = propCollector((node, props, context) => {\n\tif (\n\t\t!withFlowEffect(node) ||\n\t\t!isJSXContext(context) ||\n\t\t!isFlowEffectSupportedScopeType(context.scopeType) ||\n\t\tisFixedOrRelativeOverlay(node)\n\t) {\n\t\treturn\n\t}\n\n\tif (!hasFlowEffect(node)) {\n\t\tprops.flowEffectEnabled = undefined\n\t\tprops.flowEffectTransition = undefined\n\t\treturn\n\t}\n\n\tprops.flowEffectEnabled = true\n\tprops.isNestedFlowEffect = isNodeInFlowEffect(node)\n\tconst transition =\n\t\tnode.flowEffectTransition ?? (props.isNestedFlowEffect ? undefined : flowEffectEnabledDefaults.flowEffectTransition)\n\tprops.flowEffectTransition = transition\n\t\t? context.declarations.file.dedupe(\"transition\", toMotionTransition(transition))\n\t\t: undefined\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isAnyTextNode } from \"../../nodes/utils/isAnyTextNode.ts\"\nimport { hasAppliedOpenTypeFeatures } from \"../../utils/openType.ts\"\n\nexport const collectFonts = propCollector((node, props, context) => {\n\tif (!isAnyTextNode(node)) return\n\n\tconst fonts = node.getFontsForLoading()\n\n\tif (isJSXContext(context)) {\n\t\tconst openType = hasAppliedOpenTypeFeatures(node)\n\t\tfor (const selector of fonts) context.fonts?.addFontObjectBySelector(selector, openType)\n\t}\n\n\tprops.fonts = fonts.length > 0 ? fonts : undefined\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { withFormInputStep } from \"../forms/WithFormInputStep.ts\"\n\nexport const collectFormInputStep = propCollector((node, props, ctx) => {\n\tif (!withFormInputStep(node)) return\n\n\tprops.step =\n\t\tisJSXContext(ctx) && isDynamicValue(node.formInputStep)\n\t\t\t? ctx.createDeduplicatedDynamicValueBinding(node.formInputStep, node, \"step\")\n\t\t\t: node.resolveValue(\"formInputStep\")\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { ConditionalRule } from \"code-generation/utils/CSSCollector.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { withScrollbars } from \"../WithScrollbars.ts\"\n\nexport const collectHideScrollbarsDataAttribute = propCollector((node, props, context) => {\n\tif (!withScrollbars(node)) return\n\n\tif (isJSXContext(context)) {\n\t\tprops[\"data-hide-scrollbars\"] = isDynamicValue(node.hideScrollbars)\n\t\t\t? context.createDeduplicatedDynamicValueBinding(node.hideScrollbars, node, \"hideScrollbars\")\n\t\t\t: node.hideScrollbars || undefined\n\n\t\t// We need to add a conditional rule to the CSS collector, so that the\n\t\t// CSS collector knows to include the webkit scrollbar CSS scrollbar\n\t\t// hiding styles in the generated module. See hideScrollbarRules in\n\t\t// src/app/vekter/src/code-generation/components/shared.ts\n\t\tif (!isUndefined(node.hideScrollbars)) context.css.addConditionalRule(ConditionalRule.HideScrollbars)\n\t\treturn\n\t}\n\n\tprops[\"data-hide-scrollbars\"] = node.resolveValue(\"hideScrollbars\", context.variableOverrides) ? true : undefined\n})\n", "import { propCollector } from \"code-generation/utils/collector.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { hasActions } from \"../../actions/actions.ts\"\nimport { withFrameEvents } from \"../WithFrameEvents.ts\"\n\nexport const collectHighlight = propCollector((node, props, context) => {\n\tif (!withFrameEvents(node) || context.scopeType === ScopeType.WebPage) return\n\n\tprops[\"data-highlight\"] = hasActions(node, context.componentLoader) || undefined\n})\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport type { CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport type CodeComponentNode from \"../../nodes/CodeComponentNode.ts\"\nimport type { RichTextNode } from \"../../nodes/RichTextNode.ts\"\nimport { isCodeComponentNode, isRichTextNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"../../traits/DynamicValue.ts\"\nimport { isVariableReference } from \"../../traits/VariableReference.ts\"\nimport { hasAnyFillImageAlts } from \"../WithFill.ts\"\n\n/**\n * Collects additional DOM attributes when generating an LLM snapshot.\n */\nexport const collectLLMSnapshotAttributes = propCollector((node, props, ctx) => {\n\tif (!isJSXContext(ctx) || !ctx.llmSnapshot) return\n\n\tconst dataType = getDataTypeForLLM(node)\n\tif (dataType) props[\"data-type\"] = dataType\n\n\tif (isCodeComponentNode(node) && !node.isVectorInstance) {\n\t\tconst customizable = getCustomizableControlPropsAndLabels(ctx.componentLoader, node)\n\t\tif (!customizable) return\n\n\t\tconst { keys, labels } = customizable\n\t\tif (keys.length > 0) props[\"data-prop-keys\"] = keys.join(\",\")\n\t\tif (labels.length === keys.length && labels.length > 0) props[\"data-prop-labels\"] = labels.join(\",\")\n\t}\n})\n\nfunction getDataTypeForLLM(node: CanvasNode) {\n\tif (isRichTextNode(node) && !isRichTextContentNonStatic(node)) return \"text\"\n\tif (hasAnyFillImageAlts(node)) return \"image\"\n\tif (isCodeComponentNode(node)) {\n\t\tif (node.isVectorInstance && !isDynamicValue(node.dynamicVectorSetIdentifier)) return \"icon\"\n\t\treturn \"component\"\n\t}\n\n\treturn undefined\n}\n\n/**\n * Returns true when the rich text content is not a literal/static string.\n * This includes CMS/data bindings and Smart Component variable references.\n */\nfunction isRichTextContentNonStatic(node: RichTextNode): boolean {\n\tif (isVariableReference(node.htmlContent)) return true\n\treturn isDynamicValue(node.textContent) || isVariableReference(node.textContent)\n}\n\nfunction getCustomizableControlPropsAndLabels(\n\tcomponentLoader: ComponentLoader,\n\tnode: CodeComponentNode,\n): { keys: string[]; labels: string[] } | undefined {\n\tconst component = componentLoader.componentForIdentifier(node.codeComponentIdentifier)\n\tif (!component?.properties) return undefined\n\n\tconst controlProps = node.getControlProps(component.properties)\n\tconst keys: string[] = []\n\tconst labels: string[] = []\n\n\tfor (const key in controlProps) {\n\t\tconst control = controlProps[key]\n\t\tif (!control) continue\n\n\t\tconst { type, value } = control\n\t\tif (type !== ControlType.String && type !== ControlType.VectorSetItem) continue\n\n\t\t// Skip if the value is dynamic or a variable reference\n\t\tif (isDynamicValue(value) || isVariableReference(value)) continue\n\n\t\tkeys.push(key)\n\t\tconst title = component.properties?.[key]?.title\n\t\tlabels.push(title ?? key)\n\t}\n\n\treturn keys.length > 0 ? { keys, labels } : undefined\n}\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { collectLayoutHintDataProps } from \"library/render/utils/layoutHintDataPropsForCenter.ts\"\nimport { isPinnable } from \"../WithPins.ts\"\nimport { withSize } from \"../WithSize.ts\"\nimport { isBreakpointVariant } from \"../WithVariant.ts\"\nimport { centersWithTransforms } from \"../collectStyles/collectLayout.ts\"\nimport { newConstraintProperties } from \"../utils/newConstraintProperties.ts\"\n\n/**\n * Direct descendants of Layout Template breakpoints will be measured on a Web\n * Page canvas to show outlines and do hit testing. To ensure that the\n * measurements of elements that are centered with transforms are rounded\n * correctly in some browsers, we serialize the same data attributes we would\n * normally add in canvas rendering to inform the measure system.\n */\nexport const collectLayoutHintDataAttributes = propCollector((node, props, context) => {\n\tif (!isPinnable(node) || !withSize(node) || !isJSXContext(context)) return\n\tif (context.scopeType !== ScopeType.LayoutTemplate) return\n\n\tconst parent = node.tree()?.getParent(node.id)\n\tif (!isBreakpointVariant(parent)) return\n\tconst { center } = newConstraintProperties(node)\n\n\tcollectLayoutHintDataProps(props, centersWithTransforms(node) ? center : undefined)\n})\n", "import { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isSupportedLinkRelValueArray } from \"document/models/SupportedRelValue.ts\"\nimport { isFramerPageLink, parseFramerPageLink } from \"library/modules/framerPageLink.ts\"\nimport { isBoolean, isString } from \"utils/typeChecks.ts\"\nimport { isAnyTextNode } from \"../../nodes/utils/isAnyTextNode.ts\"\nimport { isTextNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { isComputedValue } from \"../ComputedValue.ts\"\nimport { isVariableReference } from \"../VariableReference.ts\"\nimport { hasLink, withLink } from \"../WithLink.ts\"\nimport { isLinkToURL } from \"../utils/Link.ts\"\n\nexport const collectAnchorLinkTarget = propCollector((node, props, context) => {\n\tif (!hasLink(node) || isAnyTextNode(node)) return\n\n\tif (context.variables && isVariableReference(node.linkOpenInNewTab)) {\n\t\tprops.openInNewTab = context.variables.create(node.linkOpenInNewTab)\n\t\treturn\n\t}\n\n\tconst linkOpenInNewTab = node.resolveValue(\"linkOpenInNewTab\", context.variableOverrides)\n\tif (isBoolean(linkOpenInNewTab)) {\n\t\tprops.openInNewTab = linkOpenInNewTab\n\t}\n})\n\nexport const collectLinkSmoothScroll = propCollector((node, props, context) => {\n\tif (!hasLink(node) || isAnyTextNode(node)) return\n\n\tif (context.variables && isVariableReference(node.linkSmoothScroll)) {\n\t\tprops.smoothScroll = context.variables.create(node.linkSmoothScroll)\n\t\treturn\n\t}\n\n\tconst linkSmoothScroll = node.resolveValue(\"linkSmoothScroll\", context.variableOverrides)\n\tif (isBoolean(linkSmoothScroll)) {\n\t\tprops.smoothScroll = linkSmoothScroll\n\t}\n})\n\nexport const collectLinkClickTrackingId = propCollector((node, props, context) => {\n\tif (!hasLink(node) || isAnyTextNode(node)) return\n\n\tif (context.variables && isVariableReference(node.linkClickTrackingId)) {\n\t\tprops.clickTrackingId = context.variables.create(node.linkClickTrackingId)\n\t\treturn\n\t}\n\n\tconst linkClickTrackingId = node.resolveValue(\"linkClickTrackingId\", context.variableOverrides)\n\tif (isString(linkClickTrackingId)) {\n\t\tprops.clickTrackingId = linkClickTrackingId\n\t}\n})\n\nexport const collectLinkRel = propCollector((node, props, context) => {\n\tif (!hasLink(node) || isAnyTextNode(node)) return\n\tconst linkRelValues = node.resolveValue(\"linkRelValues\", context.variableOverrides)\n\n\tif (context.variables && isVariableReference(node.linkRelValues)) {\n\t\tprops.relValues = context.variables.create(node.linkRelValues)\n\t\treturn\n\t}\n\n\tif (isSupportedLinkRelValueArray(linkRelValues)) {\n\t\tprops.relValues = linkRelValues\n\t}\n})\n\nexport const collectLinkPreserveParams = propCollector((node, props, context) => {\n\tif (!hasLink(node) || isAnyTextNode(node)) return\n\n\tif (context.variables && isVariableReference(node.linkPreserveParams)) {\n\t\tprops.preserveParams = context.variables.create(node.linkPreserveParams)\n\t\treturn\n\t}\n\n\tconst linkPreserveParams = node.resolveValue(\"linkPreserveParams\", context.variableOverrides)\n\tif (isBoolean(linkPreserveParams)) {\n\t\tprops.preserveParams = linkPreserveParams\n\t}\n})\n\nexport const collectHref = propCollector((node, props, context) => {\n\tif (!withLink(node) || isAnyTextNode(node)) return\n\n\tif (!hasLink(node)) {\n\t\tprops.href = undefined\n\t\treturn\n\t}\n\n\tconst link = node.getLink()\n\tif (isComputedValue(link)) {\n\t\tprops.href = context.valueTransforms?.createComputedValue(link, node, undefined)\n\t} else if (isLinkToURL(link) && node.linkLocalized && context.localizedValues) {\n\t\tprops.href = context.localizedValues.add(\n\t\t\tlink.url,\n\t\t\tnode.linkLocalized,\n\t\t\tlocaleId => node.linkLocalized?.[localeId]?.value,\n\t\t)\n\t} else {\n\t\tprops.href = context.links?.create(link)\n\t}\n})\n\nexport const collectLinkPreload = propCollector((node, props) => {\n\tif (isTextNode(node)) {\n\t\tconst linkTargetIds = new Set<string>()\n\t\tconst links = node.getInlineLinks(false)\n\n\t\tif (isString(node.link)) links.push(node.link)\n\n\t\tlinks.forEach(link => {\n\t\t\tif (!link || !isFramerPageLink(link)) return\n\t\t\tconst target = parseFramerPageLink(link)?.target\n\t\t\tif (target) linkTargetIds.add(target)\n\t\t})\n\n\t\tprops.__link = node.link\n\t\tif (linkTargetIds.size) props.preload = Array.from(linkTargetIds)\n\t}\n})\n\n// We do the preference for originalid because a link will always be a link regardless of the breakpoints\n// otherwise we will have a performance issue since it will add a lot of property overrides\n// https://github.com/framer/FramerStudio/pull/19034#discussion_r1776096947\nexport const collectNodeId = propCollector((node, props) => {\n\tprops.nodeId = node.getPrimaryId()\n})\n\nexport const collectScopeId = propCollector((_node, props, context) => {\n\tprops.scopeId = context.scopeId\n})\n", "import { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport type { MakeSerializable } from \"code-generation/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { toMotionTransition } from \"document/models/Transition.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport type { MotionProps } from \"framer-motion\"\nimport { isFixedOrRelativeOverlay } from \"../../nodes/utils/overlayHelpers.ts\"\nimport { hasDragEffect, withDragEffect } from \"../WithDragEffect.ts\"\nimport { isSupportedEffectScopeType } from \"../utils/effects.ts\"\n\ntype SerializableMotionDragProps = Partial<MakeSerializable<MotionProps>> & {\n\tonMouseDown?: SafeJS\n}\n\nexport const collectMotionDrag = propCollector((node, props, context) => {\n\tif (\n\t\t!withDragEffect(node) ||\n\t\t!isJSXContext(context) ||\n\t\t!isSupportedEffectScopeType(context.scopeType) ||\n\t\tisFixedOrRelativeOverlay(node)\n\t) {\n\t\treturn\n\t}\n\n\tif (!hasDragEffect(node)) {\n\t\tprops.drag = undefined\n\t\treturn\n\t}\n\n\tlet dragConstraints: SafeJS | undefined = undefined\n\tlet dragSnapToOrigin: boolean | undefined = undefined\n\t// Drag constraints are not currently supported in Smart Components.\n\tif (!node.dragEffectFreeform && context.scopeType !== ScopeType.SmartComponent) {\n\t\tdragConstraints = context.elementIds.scrollTargetInfo({\n\t\t\ttarget: node.dragEffectConstraintElement,\n\t\t\tcollectionItem: node.dragEffectConstraintItem,\n\t\t})?.ref\n\t} else if (node.dragEffectSnapBack) {\n\t\tdragSnapToOrigin = true\n\t}\n\n\tconst inertia = node.dragEffectTransition ? toMotionTransition(node.dragEffectTransition) : undefined\n\tconst dragTransition = inertia ? context.declarations.file.dedupe(\"inertia\", inertia) : undefined\n\tconst requiresDragTransition = dragConstraints || dragSnapToOrigin\n\n\tconst event = js`e`\n\tconst settings: SerializableMotionDragProps = {\n\t\tdrag: true,\n\t\tdragConstraints,\n\t\tdragMomentum: Boolean(node.dragEffectMomentum),\n\t\tdragTransition: requiresDragTransition ? dragTransition : undefined,\n\t\tdragSnapToOrigin,\n\t\t// Add a function that prevents the default event behavior. This ensures\n\t\t// that safari doesn't show a text selection cursor.\n\t\tonMouseDown: context.declarations.file.dedupe(\"preventDefault\", js`(${event}) => ${event}.preventDefault()`),\n\t}\n\n\tObject.assign(props, settings)\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { withChildren } from \"../WithChildren.ts\"\nimport { hasFloatingPosition } from \"../WithFloatingPosition.ts\"\nimport { hasTriggerActions } from \"../WithTriggerActions.ts\"\n\n/**\n * Ensures all relative overlays are collected before the ref prop of the trigger is collected.\n * These would later be collected as part of collecting trigger actions, but that occurs on the child\n * and is too late.\n */\nexport const collectRelativeOverlaysWithTriggerActions = propCollector((node, _props, context) => {\n\tif (!isJSXContext(context)) return\n\tif (!withChildren(node)) return\n\tfor (const child of node.children) {\n\t\tif (!hasFloatingPosition(child)) continue\n\t\tif (!hasTriggerActions(child)) continue\n\n\t\tcontext.overlays.addOverlayTrigger(child.id, node.id)\n\t}\n})\n", "import hash from \"@emotion/hash\"\nimport { parseHTML } from \"utils/parseHTML.ts\"\n\nconst EXTRACTED_PREFIX = \"--extracted-\"\n\n// An allow list of the allowed custom properties to extract\nconst propertiesToExtract = [\n\t\"--framer-text-color\",\n\t\"--framer-text-stroke-width\",\n\t\"--framer-text-stroke-color\",\n\t\"--framer-font-variation-axes\",\n]\n\n/**\n * @TODO - this is an expensive operation, consider caching it on the\n * node.cache.\n */\nexport function extractInlineStyles(html: string, style?: Partial<Record<string, unknown>>) {\n\tconst container = parseHTML(html)\n\n\twalkDOM(container, (element, path) => {\n\t\tfor (const property of propertiesToExtract) {\n\t\t\tconst value = element.style.getPropertyValue(property)\n\t\t\tif (!value) continue\n\n\t\t\tconst name = createCustomPropertyName(path, property)\n\t\t\tconst variable = createCustomPropertyVariable(name, value)\n\n\t\t\tif (style) style[name] = value\n\t\t\telement.style.setProperty(property, variable)\n\t\t}\n\t})\n\n\treturn container.innerHTML\n}\n\nexport function createCustomPropertyName(path: string, property: string) {\n\treturn EXTRACTED_PREFIX + hash(path + property)\n}\n\nexport function createCustomPropertyVariable(name: string, value: string) {\n\treturn `var(${name}, ${value})`\n}\n\nexport function walkDOM(element: HTMLElement, callback: (element: HTMLElement, path: string) => void, parentPath = \"\") {\n\tfor (let i = 0; i < element.children.length; i++) {\n\t\tconst child = element.children[i]\n\t\tif (child instanceof HTMLElement) {\n\t\t\tconst p = parentPath + child.tagName + i\n\t\t\tcallback(child, p)\n\t\t\twalkDOM(child, callback, p)\n\t\t}\n\t}\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { getCompatibleNonNullLocalizedValue } from \"document/components/chrome/localization/getCompatibleLocalizedValue.ts\"\nimport { getLocalizationSourceTextType } from \"document/components/chrome/localization/getLocalizationSourceTextType.ts\"\nimport { getStyledLocalizedRichTextHTML } from \"document/components/chrome/localization/getStyledLocalizedRichTextHTML.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { isDefined } from \"utils/typeChecks.ts\"\nimport { compileRichTextForCodeGeneration } from \"../../nodes/utils/compileRichText.tsx\"\nimport { extractInlineStyles } from \"../../nodes/utils/extractInlineStyles.ts\"\nimport { isRichTextNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { isVariableReference } from \"../VariableReference.ts\"\nimport { withRichText } from \"../WithRichText.ts\"\n\nexport const collectRichText = propCollector((node, props, context) => {\n\tif (!withRichText(node) || !isJSXContext(context)) return\n\n\tconst insideSmartComponent = context.scopeType === ScopeType.SmartComponent\n\tconst html = insideSmartComponent ? extractInlineStyles(node.html) : node.html\n\n\t// TODO: Currently collectRichText is only called from code-generation.\n\t// We should remove the cast and also call it from\n\t// RichTextNode.getProps.\n\tconst { assets, imports, variables, links, cssVariableDefinitions } = context || {}\n\t// TODO clean up as part of the code generation refactor\n\tassert(assets && imports && links, \"assets, imports, links must exist at this point\")\n\n\tif (isVariableReference(node.htmlContent)) {\n\t\tassert(variables, \"context.variables should exist if we are dealing with variables references\")\n\t\tprops.children = variables.create(node.htmlContent)\n\t} else {\n\t\tconst defaultJSX = compileRichTextForCodeGeneration(html, {\n\t\t\tcollectors: { assets, imports, links, variables, cssVariableDefinitions },\n\t\t\tuseFramerMotion: insideSmartComponent,\n\t\t\tnodeId: node.getPrimaryId(),\n\t\t\tscopeId: context.scopeId,\n\t\t})\n\n\t\tconst textType = getLocalizationSourceTextType(html)\n\n\t\tprops.children = context.localizedValues.add(defaultJSX, node.htmlLocalized, (localeId, collectors) => {\n\t\t\tconst localizedValue = getCompatibleNonNullLocalizedValue(textType, node.htmlLocalized?.[localeId], html)\n\t\t\tif (!localizedValue) return\n\n\t\t\tlet localizedHTML = getStyledLocalizedRichTextHTML(\n\t\t\t\tlocalizedValue.type === \"rich-text\" ? node.html : html,\n\t\t\t\tlocalizedValue,\n\t\t\t)\n\t\t\t// If we are inside a smart component, we need to extract the\n\t\t\t// inline styles from the localized HTML so magic motion can\n\t\t\t// animate the values.\n\t\t\tif (insideSmartComponent && localizedValue.type === \"rich-text\") {\n\t\t\t\tlocalizedHTML = extractInlineStyles(localizedHTML)\n\t\t\t}\n\n\t\t\treturn compileRichTextForCodeGeneration(localizedHTML, {\n\t\t\t\tcollectors: { assets, ...collectors },\n\t\t\t\tuseFramerMotion: insideSmartComponent,\n\t\t\t\tnodeId: node.getPrimaryId(),\n\t\t\t\tscopeId: context.scopeId,\n\t\t\t})\n\t\t})\n\t}\n\n\tif (isRichTextNode(node) && isDefined(node.anchorLinkOffsetY)) {\n\t\tprops.anchorLinkOffsetY = node.anchorLinkOffsetY\n\t}\n\n\tcontext.metrics?.measureLength(\"textBytes\", props.__htmlStructure)\n\tcontext.metrics?.measureLength(\"textBytes\", props.htmlFromDesign)\n\tcontext.metrics?.measureLength(\"textBytes\", props.children)\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { withFill, withOptionalFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { isSVGNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { createBackgroundImage } from \"../utils/createBackgroundImage.ts\"\n\nexport const collectSVGFill = propCollector((node, props, context) => {\n\tif (!isSVGNode(node) || !node.colorable) return\n\n\tif (withOptionalFill(node) && !node.fillEnabled) {\n\t\tprops.fill = null\n\t\treturn\n\t}\n\tif (!withFill(node)) return\n\n\tif (\n\t\t(node.fillType === \"linear-gradient\" && node.fillLinearGradient) ||\n\t\t(node.fillType === \"radial-gradient\" && node.fillRadialGradient) ||\n\t\t(node.fillType === \"conic-gradient\" && node.fillConicGradient)\n\t) {\n\t\t// We don't currently support gradients in svg/shape containers because\n\t\t// they expect a class instance which we can't serialize at this time.\n\t\treturn\n\t}\n\n\tif (node.fillType === \"image\" && node.fillImage) {\n\t\tprops.fill = createBackgroundImage(node, context)\n\t\treturn\n\t}\n\n\tif (node.fillColor) {\n\t\tif (isDynamicValue(node.fillColor) && isJSXContext(context)) {\n\t\t\tprops.fill = context.createDeduplicatedDynamicValueBinding(node.fillColor, node, \"fillColor\")\n\t\t\treturn\n\t\t}\n\n\t\tprops.fill = node.resolveValue(\"fillColor\", context.variableOverrides)\n\t}\n})\n", "import { js } from \"code-generation/js/js.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { withHTMLTextTag } from \"../WithHTMLTextTag.ts\"\nimport { withLink } from \"../WithLink.ts\"\nimport { withStyledText } from \"../WithStyledText.ts\"\nimport { withTextStyle } from \"../WithTextStyle.ts\"\n\nexport const collectStyledText = propCollector((node, props, context) => {\n\tif (!withStyledText(node) || !withTextStyle(node)) return\n\n\t// TextNode's supported Links in the past, but don't know. If a link is\n\t// added or edited they will be migrated in place to RichText. To ensure\n\t// existing TextNode's with links continue to work until they are touched,\n\t// we pass through string links.\n\tconst link = withLink(node) && isString(node.link) ? node.link : undefined\n\tconst htmlTextTag = withHTMLTextTag(node) ? node.htmlTextTag : undefined\n\n\tconst { alignment, rawHTML } = node.getStyledText().getProps(node, link, htmlTextTag, () => {})\n\n\tprops.alignment = alignment\n\tprops.rawHTML = rawHTML ? js`${rawHTML}` : undefined\n\n\tcontext.metrics?.measureLength(\"textBytes\", props.rawHTML)\n})\n", "import { assertNever } from \"@framerjs/shared\"\nimport { jsx } from \"code-generation/js/js.ts\"\nimport { SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport {\n\tisComputedValueFromVariableReference,\n\tisNonRelativeDateStringComputedValue,\n\tisRelativeDateComputedValue,\n} from \"../ComputedValue.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { withTextContent } from \"../WithTextContent.ts\"\n\nexport const collectTextContent = propCollector((node, props, context) => {\n\tif (!withTextContent(node)) return\n\n\tconst textContent = node.textContent\n\n\tif (!textContent) {\n\t\tprops.text = undefined\n\t\treturn\n\t}\n\n\tif (!isJSXContext(context)) return\n\n\tif (isRelativeDateComputedValue(textContent)) {\n\t\tconst transform = textContent.transforms[0]\n\n\t\tconst RelativeDateBinding = context.imports.addImport(\"framer\", {\n\t\t\texportSpecifier: \"RelativeDate\",\n\t\t})\n\n\t\tprops.text = jsx.tag(\n\t\t\tRelativeDateBinding,\n\t\t\tnew SerializableObject({\n\t\t\t\tdate: isComputedValueFromVariableReference(textContent)\n\t\t\t\t\t? context.variables.create(textContent.startValue)\n\t\t\t\t\t: context.fetches.createFetchBinding(node, textContent.startValue),\n\t\t\t\tdateFormat: transform.format,\n\t\t\t\tdateStyle: transform.dateStyle,\n\t\t\t\tdateCapitalize: transform.capitalize ?? false,\n\t\t\t\tlocale: transform.locale,\n\t\t\t}),\n\t\t)\n\t} else if (isNonRelativeDateStringComputedValue(textContent)) {\n\t\tconst dateBinding = isComputedValueFromVariableReference(textContent)\n\t\t\t? context.variables.create(textContent.startValue)\n\t\t\t: context.fetches.createFetchBinding(node, textContent.startValue)\n\t\tconst textBinding = context.createDeduplicatedDynamicValueBinding(textContent, node, \"textContent\")\n\t\tprops.text = jsx.tag(\"time\", new SerializableObject({ dateTime: dateBinding }), textBinding)\n\t} else if (isDynamicValue(textContent)) {\n\t\tprops.text = context.createDeduplicatedDynamicValueBinding(textContent, node, \"textContent\")\n\t} else {\n\t\tassertNever(textContent, \"text content must be a variable or a computed value\")\n\t}\n\n\tcontext.metrics?.measureLength(\"textBytes\", props.text)\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { ConditionalRule } from \"code-generation/utils/CSSCollector.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { withTextSelection } from \"../WithTextSelection.ts\"\n\nexport const collectTextSelection = propCollector((node, props, context) => {\n\tif (!withTextSelection(node)) {\n\t\treturn\n\t}\n\n\tconst textSelection = node.resolveValue(\"textSelection\")\n\n\tif (!textSelection) {\n\t\treturn\n\t}\n\n\tprops[\"data-selection\"] = true\n\n\tif (isJSXContext(context)) context.css.addConditionalRule(ConditionalRule.TextSelection)\n})\n", "import { propCollector } from \"code-generation/utils/collector.ts\"\nimport { withTextVerticalAlignment } from \"../WithTextVerticalAlignment.ts\"\n\nexport const collectTextVerticalAlignment = propCollector((node, props) => {\n\tif (!withTextVerticalAlignment(node)) return\n\n\tprops.verticalAlignment = node.textVerticalAlignment\n})\n", "import { propCollector } from \"code-generation/utils/collector.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { withTitleAndDescription } from \"../WithTitleAndDescription.ts\"\n\nexport const collectTitleAndDescription = propCollector((node, props) => {\n\tif (!withTitleAndDescription(node)) return\n\n\tprops.description = isString(node.description) && node.description !== \"\" ? node.description : undefined\n\tprops.title = isString(node.title) && node.title !== \"\" ? node.title : undefined\n})\n", "import type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { JSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { toMotionTransition } from \"document/models/Transition.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport type { UnknownProps } from \"library/modules/GeneratedComponentContext.ts\"\nimport type { CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { withTransition } from \"../WithTransition.ts\"\nimport { isVariant } from \"../WithVariant.ts\"\n\nexport type TransitionProps = Pick<UnknownProps, \"value\"> & {\n\tvalue: SafeJS | undefined\n}\n\nfunction getTransition(node: CanvasNode) {\n\tif (isVariant(node)) return node.variantTransition\n\tif (withTransition(node)) return node.transition\n\treturn undefined\n}\n\nexport const collectTransition = propCollector((node, props: TransitionProps, context: JSXContext) => {\n\tif (context.scopeType !== ScopeType.SmartComponent) return\n\n\tconst transition = getTransition(node)\n\n\tif (isDynamicValue(transition)) {\n\t\tprops.value = context.createDeduplicatedDynamicValueBinding(transition, node, \"transition\")\n\t\treturn\n\t}\n\n\tif (!transition) {\n\t\tprops.value = undefined\n\t\treturn\n\t}\n\n\tconst motionTransition = toMotionTransition(transition)\n\tprops.value = context.declarations.file.dedupe(\"transition\", motionTransition)\n})\n", "import { experiments } from \"app/experiments.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { type JSXContext, isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { propCollector } from \"code-generation/utils/collector.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport type { MotionProps } from \"framer-motion\"\nimport { isChildOfBreakpoint } from \"../../nodes/utils/breakpointHelpers.ts\"\nimport { isShapeContainerNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { isNodeFlowEffectItem } from \"../WithFlowEffect.ts\"\nimport { withPositionType } from \"../WithPositionType.ts\"\nimport { isPositionFixed, isPositionSticky } from \"../utils/positionTypeHelpers.ts\"\n\n/**\n * Collects framer-motion layout prop and other related props.\n *\n * Uses:\n * - Collect layout=\"position\" prop for children of flow effect nodes.\n * - Collect layout={getRootLayoutProp(hasLayoutTemplate, hasInheritedFlowEffect, fallback)} prop for children of webpage breakpoints.\n * - Collect layoutScroll and layout prop for fixed or sticky position nodes.\n *\n * @see https://motion.dev/docs/react-layout-animations\n */\nexport const collectMotionLayoutProps = propCollector((node, props, ctx) => {\n\tif (!isJSXContext(ctx)) return\n\n\t// position is used to avoid layout animations scaling elements\n\tprops.layout =\n\t\tisNodeFlowEffectItem(node) || (isShapeContainerNode(node) && ctx.scopeType === ScopeType.SmartComponent)\n\t\t\t? \"position\"\n\t\t\t: props.layout\n\n\t// When a web page has a layout template we need to dynamically apply the layout prop to the direct children of the page breakpoints.\n\t// This needs to be applied always but at runtime we will only override the collected value if the page has a layout template.\n\t// This also correctly removes the flow effect from the page if it is not present in the layout template but present on the page breakpoint.\n\tif (ctx.scopeType === ScopeType.WebPage && isChildOfBreakpoint(ctx.tree, node)) {\n\t\tprops.layout = getLayoutPropForMaybeInheritedFlowEffect(ctx, props.layout as MotionProps[\"layout\"])\n\t}\n\n\tif (!experiments.isOn(\"layoutScroll\") || !withPositionType(node)) return\n\n\tconst needsLayoutScroll =\n\t\tctx.scopeType === ScopeType.LayoutTemplate && (isPositionFixed(node) || isPositionSticky(node))\n\n\tprops.layoutScroll = needsLayoutScroll ? true : undefined\n\tprops.layout = needsLayoutScroll ? true : props.layout\n})\n\nfunction getLayoutPropForMaybeInheritedFlowEffect(ctx: JSXContext, fallback: MotionProps[\"layout\"]) {\n\tconst React = ctx.imports.addImport(\"react\", { exportSpecifier: \"*\", importBinding: \"React\" })\n\tconst MotionConfigContext = ctx.imports.addImport(\"framer-motion\", { exportSpecifier: \"MotionConfigContext\" })\n\tconst GeneratedComponentContext = ctx.imports.addImport(\"framer\", {\n\t\texportSpecifier: \"GeneratedComponentContext\",\n\t})\n\tconst getRootLayoutProp = ctx.declarations.file.dedupe(\n\t\t\"getRootLayoutProp\",\n\t\tjs`(hasLayoutTemplate, hasInheritedFlowEffect, fallback) => {${js.joinLines(\n\t\t\tjs`if (!hasLayoutTemplate) return fallback`,\n\t\t\tjs`return hasInheritedFlowEffect ? \"position\" : fallback`,\n\t\t)}}`,\n\t)\n\tconst hasLayoutTemplate = ctx.declarations.component.dedupe(\n\t\t\"hasLayoutTemplate\",\n\t\tjs`${SafeJS.fn(js`${React}.useContext`, GeneratedComponentContext)}?.isLayoutTemplate`,\n\t)\n\tconst hasInheritedFlowEffect = ctx.declarations.component.dedupe(\n\t\t\"hasInheritedFlowEffect\",\n\t\tjs`Boolean(${SafeJS.fn(js`${React}.useContext`, MotionConfigContext)}?.transition?.layout)`,\n\t)\n\n\treturn ctx.declarations.component.dedupe(\n\t\t\"motionLayout\",\n\t\tSafeJS.fn(getRootLayoutProp, hasLayoutTemplate, hasInheritedFlowEffect, fallback),\n\t)\n}\n", "import { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport { assert, isEmptyObject, isModuleExportIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { isKitSectionNode } from \"app/ai/utils/kitSection.ts\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { type SerializableValue, isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport type { SerializableMotionStyle } from \"code-generation/types.ts\"\nimport { LAYOUT_TEMPLATE_ATTRIBUTE } from \"code-generation/utils/CSSCollector.ts\"\nimport { moduleImportSpecifiers } from \"code-generation/utils/ImportCollector.ts\"\nimport { OverlayCollector } from \"code-generation/utils/OverlayCollector.ts\"\nimport { isBuiltInComponentWithoutContainer, nodeNeedsContainer } from \"code-generation/utils/builtInCodeComponents.ts\"\nimport { mergeCollectors, propCollector } from \"code-generation/utils/collector.ts\"\nimport { getAttributesFromCodeComponent } from \"code-generation/utils/getAttributesFromCodeComponent.ts\"\nimport { processSvgImageAssetsAttribute } from \"code-generation/utils/processSvgImageAssets.ts\"\nimport {\n\tdoesShaderScaleWithViewport,\n\tscaleDownShaderFallbackImage,\n} from \"code-generation/utils/shaderFallbackImages.ts\"\nimport { hasLoadMoreActions } from \"document/models/CanvasTree/actions/paginationActions.ts\"\nimport { type CanvasNode, type CodeComponentNode, isVectorNode } from \"document/models/CanvasTree/index.ts\"\nimport { isAnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport {\n\tisCodeComponentNode,\n\tisCollectionRepeater,\n\tisDynamicVectorInstance,\n\tisOverlayNode,\n\tisSVGNode,\n\tisShaderNode,\n\tisShapeContainerNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { iterateShaderUniforms } from \"document/models/CanvasTree/nodes/utils/shaderUniforms.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { isGeneratedValue } from \"document/models/CanvasTree/traits/Generated.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { WithCodeComponent } from \"document/models/CanvasTree/traits/WithCodeComponent.ts\"\nimport { withCodeComponent } from \"document/models/CanvasTree/traits/WithCodeComponent.ts\"\nimport { hasPaginationEnabled } from \"document/models/CanvasTree/traits/WithCollectionOptions.ts\"\nimport {\n\thasAnyDataLoaderVariants,\n\tisRepeaterLoaderInstance,\n} from \"document/models/CanvasTree/traits/WithDataLoaderVariants.ts\"\nimport {\n\tDEFAULT_FLOATING_COLLISION_PADDING,\n\thasFloatingPosition,\n\twithFloatingPosition,\n} from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { hasAnyFormVariants, isFormSubmitButtonInstance } from \"document/models/CanvasTree/traits/WithFormVariants.ts\"\nimport { hasLightboxEffect } from \"document/models/CanvasTree/traits/WithLightboxEffect.ts\"\nimport { withRotation } from \"document/models/CanvasTree/traits/WithRotation.ts\"\nimport { withScrollTarget } from \"document/models/CanvasTree/traits/WithScrollTarget.ts\"\nimport { withShaderMouse } from \"document/models/CanvasTree/traits/WithShaderMouse.ts\"\nimport { withSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { isNodeTickerItem } from \"document/models/CanvasTree/traits/WithTickerEffect.ts\"\nimport { hasNonIdentityTransforms } from \"document/models/CanvasTree/traits/WithTransforms.ts\"\nimport { isBreakpointVariant, isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { hasWhileOpenEffect } from \"document/models/CanvasTree/traits/WithWhileOpenEffect.ts\"\nimport { hasZIndex } from \"document/models/CanvasTree/traits/WithZIndex.ts\"\nimport { collectAriaLabel } from \"document/models/CanvasTree/traits/collectProps/collectAriaLabel.ts\"\nimport { collectAsProp } from \"document/models/CanvasTree/traits/collectProps/collectAsProp.ts\"\nimport { collectBackdrop } from \"document/models/CanvasTree/traits/collectProps/collectBackdrop.ts\"\nimport { collectBackgroundImage } from \"document/models/CanvasTree/traits/collectProps/collectBackgroundImage.ts\"\nimport { collectBorder } from \"document/models/CanvasTree/traits/collectProps/collectBorder.ts\"\nimport { collectCSSResetAttribute } from \"document/models/CanvasTree/traits/collectProps/collectCSSResetAttribute.ts\"\nimport { collectCodeComponentContainerProps } from \"document/models/CanvasTree/traits/collectProps/collectCodeComponentContainerProps.ts\"\nimport { collectColumnMasonryLayoutProps } from \"document/models/CanvasTree/traits/collectProps/collectColumnMasonryLayoutProps.ts\"\nimport { collectDataNosnippet } from \"document/models/CanvasTree/traits/collectProps/collectDataNosnippet.ts\"\nimport { collectDraggable } from \"document/models/CanvasTree/traits/collectProps/collectDraggable.ts\"\nimport { collectFX, collectVariantAppearEffect } from \"document/models/CanvasTree/traits/collectProps/collectEffects.ts\"\nimport { collectEvents } from \"document/models/CanvasTree/traits/collectProps/collectEvents.ts\"\nimport { collectFlowEffect } from \"document/models/CanvasTree/traits/collectProps/collectFlowEffect.ts\"\nimport { collectFonts } from \"document/models/CanvasTree/traits/collectProps/collectFonts.ts\"\nimport { collectFormBooleanInputType } from \"document/models/CanvasTree/traits/collectProps/collectFormBooleanInputType.ts\"\nimport { collectFormContainer } from \"document/models/CanvasTree/traits/collectProps/collectFormContainer.ts\"\nimport { collectFormInputAttributes } from \"document/models/CanvasTree/traits/collectProps/collectFormInputAttributes.ts\"\nimport { collectFormInputAutofillEnabled } from \"document/models/CanvasTree/traits/collectProps/collectFormInputAutofillEnabled.ts\"\nimport { collectFormInputStep } from \"document/models/CanvasTree/traits/collectProps/collectFormInputStep.ts\"\nimport { collectFormSelectBinding } from \"document/models/CanvasTree/traits/collectProps/collectFormSelectBinding.ts\"\nimport { collectFormSelectOptions } from \"document/models/CanvasTree/traits/collectProps/collectFormSelectOptions.ts\"\nimport { collectFormTextInput } from \"document/models/CanvasTree/traits/collectProps/collectFormTextInput.ts\"\nimport { collectFormTextInputPlaceholder } from \"document/models/CanvasTree/traits/collectProps/collectFormTextInputPlaceholder.ts\"\nimport { collectFramerName } from \"document/models/CanvasTree/traits/collectProps/collectFramerName.ts\"\nimport { collectHideScrollbarsDataAttribute } from \"document/models/CanvasTree/traits/collectProps/collectHideScrollbarsDataAttribute.ts\"\nimport { collectHighlight } from \"document/models/CanvasTree/traits/collectProps/collectHighlight.ts\"\nimport { collectLLMSnapshotAttributes } from \"document/models/CanvasTree/traits/collectProps/collectLLMSnapshotAttributes.ts\"\nimport { collectLayoutHintDataAttributes } from \"document/models/CanvasTree/traits/collectProps/collectLayoutHintDataAttributes.ts\"\nimport {\n\tcollectAnchorLinkTarget,\n\tcollectHref,\n\tcollectLinkClickTrackingId,\n\tcollectLinkPreload,\n\tcollectLinkPreserveParams,\n\tcollectLinkRel,\n\tcollectLinkSmoothScroll,\n\tcollectNodeId,\n\tcollectScopeId,\n} from \"document/models/CanvasTree/traits/collectProps/collectLink.ts\"\nimport { collectLoopEffect } from \"document/models/CanvasTree/traits/collectProps/collectLoopEffect.ts\"\nimport { collectMotionDrag } from \"document/models/CanvasTree/traits/collectProps/collectMotionDrag.ts\"\nimport { collectMotionExit } from \"document/models/CanvasTree/traits/collectProps/collectMotionExit.ts\"\nimport { collectMotionWhileHover } from \"document/models/CanvasTree/traits/collectProps/collectMotionWhileHover.ts\"\nimport { collectMotionWhileTap } from \"document/models/CanvasTree/traits/collectProps/collectMotionWhileTap.ts\"\nimport { collectOptimizedMotionProps } from \"document/models/CanvasTree/traits/collectProps/collectOptimizedMotionProps.ts\"\nimport { collectRelativeOverlaysWithTriggerActions } from \"document/models/CanvasTree/traits/collectProps/collectRelativeOverlaysWithTriggerActions.ts\"\nimport { collectRichText } from \"document/models/CanvasTree/traits/collectProps/collectRichText.ts\"\nimport { collectSVGFill } from \"document/models/CanvasTree/traits/collectProps/collectSVGFill.ts\"\nimport { collectStylePresets } from \"document/models/CanvasTree/traits/collectProps/collectStylePresets.ts\"\nimport { collectStyledText } from \"document/models/CanvasTree/traits/collectProps/collectStyledText.ts\"\nimport { collectTabIndex } from \"document/models/CanvasTree/traits/collectProps/collectTabIndex.ts\"\nimport { collectTextContent } from \"document/models/CanvasTree/traits/collectProps/collectTextContent.ts\"\nimport { collectTextEffect } from \"document/models/CanvasTree/traits/collectProps/collectTextEffect.ts\"\nimport { collectTextFit } from \"document/models/CanvasTree/traits/collectProps/collectTextFit.ts\"\nimport { collectTextSelection } from \"document/models/CanvasTree/traits/collectProps/collectTextSelection.ts\"\nimport { collectTextVerticalAlignment } from \"document/models/CanvasTree/traits/collectProps/collectTextVerticalAlignment.ts\"\nimport { collectTitleAndDescription } from \"document/models/CanvasTree/traits/collectProps/collectTitleAndDescription.ts\"\nimport { collectTransition } from \"document/models/CanvasTree/traits/collectProps/collectTransition.ts\"\nimport { collectMotionLayoutProps } from \"document/models/CanvasTree/traits/collectStyles/collectMotionLayoutProps.ts\"\nimport { createCSSDimension } from \"document/models/CanvasTree/traits/utils/CSSDimension.ts\"\nimport { collectVisualPropertiesForNode } from \"document/models/CanvasTree/traits/utils/collectVisualPropertiesForNode.ts\"\nimport { hasAnyEffect } from \"document/models/CanvasTree/traits/utils/effects.ts\"\nimport { HardCodedCodeIdentifier } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport { isPositionFixed } from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { tickerItemFractionalUnitFallback } from \"document/models/CanvasTree/traits/utils/tickerItemFractionalUnitFallback.ts\"\nimport { getControlPropValuesForCodeGeneration } from \"document/models/controlProps/getControlPropValuesForCodeGeneration.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { DimensionType } from \"library/index.ts\"\nimport { portalIdAttribute } from \"library/modules/CustomCursor.tsx\"\nimport { SVGRenderer, requiresSVGToBeOverflowVisible } from \"renderer/staticSVGRenderer.tsx\"\nimport { isNonNull, isNumber, isObject, isUndefined } from \"utils/typeChecks.ts\"\nimport { ANIMATED_PROP_NAME } from \"./svg/svgContext.ts\"\nimport type { AncestorInfo, JSXContext, ProcessedVariantsFlags } from \"./types.ts\"\n\nconst CONTAINER_POSTFIX = \"-container\"\n\n/**\n * Forms cannot contain other forms, so we can use the same binding in each form\n * without deduplicating the bindings.\n */\nexport const FORM_STATE_BINDING = js`formState`\n\ninterface InitialProps {\n\tclassName?: string\n\tstyle?: SerializableValue\n}\n\n// @FIXME collectSVGProps and collectShapeContainerProps don't really follow the\n// pattern of all other nodes which are collected via traits. ShapeContainer\n// doesn't even follow the pattern of other nodes and defines all styles via\n// props. This is a relic of our push to get smart components out the door,\n// where SVG and shapes were afterthoughts. A future PR should try to improve\n// shape container prop collection.\n\nconst collectSVGProps = propCollector((node, props, context) => {\n\tif (!isSVGNode(node)) return\n\tprops.withExternalLayout = true\n\tprops.intrinsicHeight = node.intrinsicHeight || undefined\n\tprops.intrinsicWidth = node.intrinsicWidth || undefined\n\tprops.svg = js`${node.svg}`\n\tprocessSvgImageAssetsAttribute(props, context?.assets)\n\tcontext?.metrics?.measureLength(\"svgBytes\", props.svg)\n})\n\nconst collectShapeContainerProps = propCollector((node, props, context) => {\n\tif (!isShapeContainerNode(node)) return\n\tassert(props instanceof SerializableObject, \"\")\n\n\tconst svg = SVGRenderer.shared().getSVGStringForNode(context.componentLoader, node)\n\tconst svgContentId = node.contentHash\n\n\tSerializableObject.assign(props, {\n\t\tintrinsicWidth: undefined,\n\t\tintrinsicHeight: undefined,\n\t\t...collectVisualPropertiesForNode(node),\n\t\twithExternalLayout: true,\n\t\tsvgContentId,\n\t\tsvg,\n\t})\n\n\t// For some reason `props.style.opacity` is ignored and must exist on props directly.\n\tconst opacity = (props.style as any)?.opacity\n\tif (opacity || Number.isFinite(Number(opacity))) {\n\t\tprops.opacity = opacity\n\t}\n\n\tprocessSvgImageAssetsAttribute(props, context?.assets)\n\tcontext?.metrics?.measureLength(\"svgBytes\", props.svg)\n})\n\n// VECTOR @TODO: this would be obsolete if we use the SVG serializer for inline shapes.\nconst collectVectorProps = propCollector((node, props, context) => {\n\tif (!isVectorNode(node)) return\n\n\tconst svg = SVGRenderer.shared().getSVGStringForNode(context.componentLoader, node)\n\tObject.assign(props, {\n\t\tintrinsicWidth: undefined,\n\t\tintrinsicHeight: undefined,\n\t\t...collectVisualPropertiesForNode(node),\n\t\tsvg,\n\t\t// Unset opacity collected in collectVisualPropertiesForNode. Any opacity set on the vector\n\t\t// node would be encoded into the svg string already.\n\t\topacity: undefined,\n\t\twithExternalLayout: true,\n\t\trequiresOverflowVisible: requiresSVGToBeOverflowVisible(node),\n\t})\n\n\tprocessSvgImageAssetsAttribute(props, context?.assets)\n\tcontext?.metrics?.measureLength(\"svgBytes\", props.svg)\n})\n\nfunction collectShaderProps(node: CanvasNode, props: SerializableObject, ctx: JSXContext) {\n\tif (!isShaderNode(node)) return\n\tprops.__fromCanvasComponent = true\n\n\tif (!node.shaderModuleIdentifier) return\n\n\tconst moduleIdentifier = parseModuleIdentifier(node.shaderModuleIdentifier)\n\tif (!isModuleExportIdentifier(moduleIdentifier)) return\n\n\tconst { importSpecifier } = moduleImportSpecifiers(\n\t\tmoduleIdentifier,\n\t\tctx.moduleType,\n\t\tctx.componentLoader,\n\t\tctx.modulesStore,\n\t)\n\n\tif (!importSpecifier) return\n\n\tconst shaderModuleImport = ctx.imports.addImport(importSpecifier, {\n\t\texportSpecifier: \"default\",\n\t\timportBinding: \"shaderConfig\",\n\t})\n\n\tprops.fragmentShader = js`${shaderModuleImport}.fragment`\n\tprops.vertexShader = js`${shaderModuleImport}.vertex`\n\tprops.resolutionScale = js`${shaderModuleImport}.resolutionScale`\n\tprops.heightmapSource = js`${shaderModuleImport}.heightmapSource`\n\tprops.animated = js`${shaderModuleImport}.animated`\n\tprops.buffers = js`${shaderModuleImport}.buffers`\n\n\tif (withShaderMouse(node)) {\n\t\tconst mouse = js`${shaderModuleImport}.mouse`\n\n\t\tlet enabled: SerializableValue\n\t\tif (node.shaderMouseEnabled === true) {\n\t\t\tenabled = js`true`\n\t\t} else if (node.shaderMouseEnabled === false) {\n\t\t\tenabled = js`false`\n\t\t} else {\n\t\t\tenabled = js`${mouse} === \"enabledByDefault\"`\n\t\t}\n\n\t\tif (node.shaderMouseSpringOptions) {\n\t\t\tconst springOptions = js`${{ ...node.shaderMouseSpringOptions }}`\n\t\t\tprops.mouse = js`${mouse} && { enabled: ${enabled}, springOptions: ${springOptions} }`\n\t\t} else {\n\t\t\tprops.mouse = js`${mouse} && { enabled: ${enabled} }`\n\t\t}\n\t}\n\n\tif (node.shaderFallbackImage) {\n\t\t// Shaders inside components/templates skip the initial fallback at runtime\n\t\t// because variable overrides on instances can change the shader's appearance,\n\t\t// producing a mismatch with the master's fallback image.\n\t\tconst isInsideReusableScope =\n\t\t\tctx.scopeType === ScopeType.SmartComponent || ctx.scopeType === ScopeType.LayoutTemplate\n\t\tconst isRelativelySized = doesShaderScaleWithViewport(node)\n\t\tconst shouldSkipInitialFallback = isInsideReusableScope || isRelativelySized\n\n\t\tconst resolved = ctx.assets.resolveResponsiveImage(node.shaderFallbackImage)\n\t\tif (resolved?.src) {\n\t\t\tprops.fallbackImage = isRelativelySized\n\t\t\t\t? scaleDownShaderFallbackImage(node.shaderFallbackImage, resolved.src)\n\t\t\t\t: resolved.src\n\t\t\tprops.skipInitialFallback = shouldSkipInitialFallback\n\t\t\tprops.mode = \"progressive\"\n\t\t} else {\n\t\t\tprops.mode = \"instant\"\n\t\t}\n\t}\n\n\tconst shaderDefinition = ctx.componentLoader.shaderForIdentifier(node.shaderModuleIdentifier)\n\tif (!shaderDefinition) return\n\n\tconst resolvedControlProps = getControlPropValuesForCodeGeneration(\n\t\tnode,\n\t\tshaderDefinition.properties,\n\t\tnode.getControlProps(shaderDefinition.properties),\n\t\t{ context: ctx, resolveDefaults: true },\n\t)\n\n\tlet uniforms: SerializableObject | undefined\n\tfor (const { name, uniform } of iterateShaderUniforms(shaderDefinition.properties, resolvedControlProps)) {\n\t\tif (!uniforms) uniforms = new SerializableObject()\n\t\tuniforms[name] = new SerializableObject(uniform)\n\t}\n\n\tprops.uniforms = uniforms\n}\n\nfunction isPrototypeComponent(node: CodeComponentNode) {\n\treturn node.codeComponentIdentifier === HardCodedCodeIdentifier.prototype\n}\n\nfunction collectCodeComponentProps(\n\tnode: CanvasNode,\n\tprops: SerializableObject,\n\tctx: JSXContext,\n\tflags: ProcessedVariantsFlags,\n\tancestorInfo: AncestorInfo,\n) {\n\tif (!isCodeComponentNode(node)) return\n\n\tconst { lastRepeaterId, layoutId } = ancestorInfo\n\n\tSerializableObject.assign(props, getAttributesFromCodeComponent(node, undefined, ctx, lastRepeaterId))\n\n\tif (isPrototypeComponent(node)) {\n\t\tprops.scaleTo = \"dynamic\"\n\t} else if (isBuiltInComponentWithoutContainer(node)) {\n\t\tprops.__fromCanvasComponent = true\n\t} else if (!node.isVectorInstance) {\n\t\tprops.width = \"100%\"\n\t\tprops.height = \"100%\"\n\t\tprops.id = node.getPrimaryId()\n\t\tif (isNonNull(node.name) && !props.name && !isGeneratedValue(node.name)) props.name = node.name\n\t} else {\n\t\t// Inside a Smart Component, a Vector Instance should render with a motion element so that\n\t\t// it can receive `variants` and a `layout` prop, and animate when the containing Smart\n\t\t// Component changes its variants. Otherwise we render with plain html elements whenever\n\t\t// possible to reduce performance impact of motion elements. We must use a motion element\n\t\t// when we have transforms.\n\t\tconst hasRotation =\n\t\t\twithRotation(node) && (isDynamicValue(node.rotation) || (isNumber(node.rotation) && node.rotation !== 0))\n\t\tprops[ANIMATED_PROP_NAME] =\n\t\t\tctx.scopeType === ScopeType.SmartComponent\n\t\t\t\t? true\n\t\t\t\t: hasNonIdentityTransforms(node) || hasRotation || hasAnyEffect(node)\n\t}\n\n\tcollectVariantAppearEffect(node, props, ctx)\n\n\t// collect potential variant conditions as `someCondition && variant`\n\t// wrap in a function like cx that takes the first not-falsey variant and returns it\n\tconst variantConditions: SafeJS[] = []\n\n\tconst overlayBindings = ctx.overlays.bindingsByOverlayTriggerId.get(node.getPrimaryId())\n\tif (hasWhileOpenEffect(node) && overlayBindings?.size) {\n\t\tconst statement = new SafeJS(\n\t\t\tArray.from(overlayBindings.values())\n\t\t\t\t?.map(binding => js`${binding}.visible`)\n\t\t\t\t?.join(\" || \"),\n\t\t)\n\t\tprops.variant = js`(${statement}) ? ${node.whileOpenEffectVariant} : ${props.variant ?? js`undefined`}`\n\t\tvariantConditions.push(js`(${statement}) && ${node.whileOpenEffectVariant}`)\n\t}\n\n\tfor (const trigger of ctx.triggerActions.triggerActionByNode.get(node.getPrimaryId()) ?? []) {\n\t\tif (!trigger.setVariantBinding) continue\n\n\t\tvariantConditions.push(trigger.setVariantBinding)\n\t}\n\n\tif (props.variant) {\n\t\tvariantConditions.push(SafeJS.fromValue(props.variant))\n\t}\n\n\tprops.variant =\n\t\tvariantConditions.length > 0\n\t\t\t? SafeJS.fn(\n\t\t\t\t\tctx.declarations.file.dedupe(\n\t\t\t\t\t\t\"matchVariant\",\n\t\t\t\t\t\tjs.joinLines(\n\t\t\t\t\t\t\tjs`(...args) => {  `,\n\t\t\t\t\t\t\tjs`  for (const arg of args) {`,\n\t\t\t\t\t\t\tjs`    if (arg && typeof arg === \"string\") return arg`,\n\t\t\t\t\t\t\tjs`  }`,\n\t\t\t\t\t\t\tjs`  return undefined`,\n\t\t\t\t\t\t\tjs`}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t\t...variantConditions,\n\t\t\t\t)\n\t\t\t: undefined\n\n\t// If the component instance configures variants based on the state of a\n\t// form ancestor, and is the submit button for the ancestor form, create a\n\t// function that sets the desired variants based on the form state, falling\n\t// through to the current variant.\n\tif (isFormSubmitButtonInstance(ctx.tree, node)) {\n\t\tprops.type = \"submit\"\n\t\tif (hasAnyFormVariants(node)) {\n\t\t\tprops.variant = SafeJS.fn(\n\t\t\t\tctx.declarations.file.dedupe(\n\t\t\t\t\t\"formVariants\",\n\t\t\t\t\tjs`(form, variants, currentVariant) => { ${js.joinLines(\n\t\t\t\t\t\tjs`switch(form.state) {${js.joinLines(\n\t\t\t\t\t\t\tjs`case \"success\": return variants.success ?? currentVariant`,\n\t\t\t\t\t\t\tjs`case \"pending\": return variants.pending ?? currentVariant`,\n\t\t\t\t\t\t\tjs`case \"error\": return variants.error ?? currentVariant`,\n\t\t\t\t\t\t\tjs`case \"incomplete\": return variants.incomplete ?? currentVariant`,\n\t\t\t\t\t\t\tjs`default: return currentVariant`,\n\t\t\t\t\t\t)}}`,\n\t\t\t\t\t)} }`,\n\t\t\t\t),\n\t\t\t\tFORM_STATE_BINDING,\n\t\t\t\t{\n\t\t\t\t\tsuccess: node.formButtonSuccessVariantEnabled ? node.formButtonSuccessVariant : undefined,\n\t\t\t\t\terror: node.formButtonErrorVariantEnabled ? node.formButtonErrorVariant : undefined,\n\t\t\t\t\tpending: node.formButtonPendingVariantEnabled ? node.formButtonPendingVariant : undefined,\n\t\t\t\t\tincomplete: node.formButtonIncompleteVariantEnabled ? node.formButtonIncompleteVariant : undefined,\n\t\t\t\t},\n\t\t\t\tprops.variant ?? js`undefined`,\n\t\t\t)\n\t\t}\n\t}\n\n\t// If the component instance configures variants based on the state of a\n\t// data repeater ancestor, and is the load more button for the ancestor\n\t// repeater, create a function that sets the desired variants based on the\n\t// repeater state, falling through to the current variant.\n\tconst repeater = ctx.tree.get(ancestorInfo.lastRepeaterId)\n\tif (\n\t\tisCollectionRepeater(repeater) &&\n\t\thasPaginationEnabled(repeater) &&\n\t\t(isRepeaterLoaderInstance(node, repeater) || hasLoadMoreActions(ctx.componentLoader, node))\n\t) {\n\t\tprops.variant =\n\t\t\trepeater && hasAnyDataLoaderVariants(node)\n\t\t\t\t? SafeJS.fn(\n\t\t\t\t\t\tctx.declarations.file.dedupe(\n\t\t\t\t\t\t\t\"loaderVariants\",\n\t\t\t\t\t\t\tjs`(repeaterState, variants, currentVariant) => { ${js.joinLines(\n\t\t\t\t\t\t\t\tjs`if (repeaterState.currentPage >= repeaterState.totalPages) return variants.disabled ?? currentVariant`,\n\t\t\t\t\t\t\t\tjs`if (repeaterState.isLoading) return variants.loading ?? currentVariant`,\n\t\t\t\t\t\t\t\tjs`return currentVariant`,\n\t\t\t\t\t\t\t)} }`,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tctx.bindings.createWithNode(\"paginationInfo\", repeater),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdisabled: node.dataLoaderDisabledVariantEnabled ? node.dataLoaderDisabledVariant : undefined,\n\t\t\t\t\t\t\tloading: node.dataLoaderLoadingVariantEnabled ? node.dataLoaderLoadingVariant : undefined,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprops.variant ?? js`undefined`,\n\t\t\t\t\t)\n\t\t\t\t: undefined\n\t}\n\n\t// When the code component is a dynamic vector instance, or when there are multiple identifiers,\n\t// we set the imported ComponentType as a property so that it can change across variants.\n\tif (isDynamicVectorInstance(node) || (flags.identifiers && flags.identifiers.size > 1)) {\n\t\tconst moduleIdentifier = parseModuleIdentifier(node.codeComponentIdentifier)\n\t\tassert(isModuleExportIdentifier(moduleIdentifier), `Expected a module export identifier, got ${moduleIdentifier}`)\n\t\tconst { importSpecifier, exportSpecifier, importBinding } = moduleImportSpecifiers(\n\t\t\tmoduleIdentifier,\n\t\t\tctx.moduleType,\n\t\t\tctx.componentLoader,\n\t\t\tctx.modulesStore,\n\t\t)\n\n\t\tassert(importSpecifier, \"A module must have an import specifier.\")\n\n\t\tprops.Component = isVariableReference(node.dynamicVectorSetIdentifier)\n\t\t\t? ctx.vectorSets.resolveVariableInstance(node)\n\t\t\t: ctx.imports.addImport(importSpecifier, {\n\t\t\t\t\texportSpecifier,\n\t\t\t\t\timportBinding,\n\t\t\t\t})\n\t}\n\n\tprops.layoutId = layoutId ?? node.getPrimaryId()\n}\n\nconst createCodeComponentProps = (\n\tnode: CanvasNode & WithCodeComponent,\n\tcontext: JSXContext,\n\tflags: ProcessedVariantsFlags,\n\tancestorInfo: AncestorInfo,\n) => {\n\tconst props = new SerializableObject()\n\tcollectCodeComponentProps(node, props, context, flags, ancestorInfo)\n\tcollectLLMSnapshotAttributes(node, props, context)\n\n\treturn props\n}\n\n/**\n * Most props can be collected from specific traits. If the node supports the\n * trait, we can collect properties for it by providing the node, and a context.\n */\nconst collectTraitProps = mergeCollectors(\n\tcollectAriaLabel,\n\tcollectAsProp,\n\tcollectBackdrop,\n\tcollectBackgroundImage,\n\tcollectBorder,\n\tcollectCodeComponentContainerProps,\n\tcollectColumnMasonryLayoutProps,\n\tcollectCSSResetAttribute,\n\tcollectDataNosnippet,\n\tcollectDraggable,\n\tcollectEvents,\n\tcollectFonts,\n\tcollectFormBooleanInputType,\n\tcollectFormContainer,\n\tcollectFormInputAttributes,\n\tcollectFormInputAutofillEnabled,\n\tcollectFormInputStep,\n\tcollectFormSelectBinding,\n\tcollectFormSelectOptions,\n\tcollectFormTextInput,\n\tcollectFormTextInputPlaceholder,\n\tcollectFramerName,\n\tcollectFX,\n\tcollectHideScrollbarsDataAttribute,\n\tcollectHighlight,\n\tcollectLayoutHintDataAttributes,\n\tcollectLinkPreload,\n\tcollectFlowEffect,\n\tcollectLoopEffect,\n\tcollectMotionDrag,\n\tcollectMotionExit,\n\tcollectMotionLayoutProps,\n\tcollectMotionWhileHover,\n\tcollectMotionWhileTap,\n\tcollectOptimizedMotionProps,\n\tcollectRelativeOverlaysWithTriggerActions,\n\tcollectRichText,\n\tcollectShapeContainerProps,\n\tcollectStyledText,\n\tcollectStylePresets,\n\tcollectSVGFill,\n\tcollectSVGProps,\n\tcollectTabIndex,\n\tcollectTextContent,\n\tcollectTextEffect,\n\tcollectTextFit,\n\tcollectTextSelection,\n\tcollectTextVerticalAlignment,\n\tcollectTitleAndDescription,\n\tcollectVectorProps,\n)\n\n/**\n * If the style we collect only contains `undefined` values, we can drop the\n * entire object and replace it with `undefined` so we don't add `style={{}}` to\n * code generation.\n */\nfunction maybeDropEmptyStyleObject(style?: SerializableMotionStyle): SerializableMotionStyle | undefined {\n\tif (isUndefined(style)) return style\n\tif (style instanceof SerializableObject && SerializableObject.hasSpreads(style)) return style\n\n\tfor (const value of Object.values(style)) {\n\t\tif (!isUndefined(value)) return style\n\t}\n\n\treturn undefined\n}\n\nfunction referenceScopingClassNames(ctx: JSXContext) {\n\treturn ctx.declarations.component.dedupe(\n\t\t\"scopingClassNames\",\n\t\tSafeJS.fn(\n\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"cx\" }),\n\t\t\tVar.serializationHash,\n\t\t\tjs`...${Var.sharedStyleClassNames}`,\n\t\t),\n\t)\n}\n\nconst createElementProps = (\n\tnode: CanvasNode,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n\tflags: ProcessedVariantsFlags,\n\t{ style, className }: InitialProps,\n) => {\n\tconst props = new SerializableObject()\n\t// Get all props that are based off of generic traits that any node can\n\t// technically support.\n\tcollectTraitProps(node, props, ctx)\n\n\t// For code components that need a container, LLM attributes should be on the\n\t// component element itself, not the container. Skip collecting them here.\n\tif (!(withCodeComponent(node) && nodeNeedsContainer(node))) {\n\t\tcollectLLMSnapshotAttributes(node, props, ctx)\n\t}\n\n\t// We must combine all inline style we have collected, and finally if the\n\t// node is the primary variant, add a style spread at the end of the object\n\t// to support adding additional styles.\n\tconst isRootNode = node.getPrimaryId() === ctx.rootId\n\tif (props.style || style || isRootNode) {\n\t\tconst combinedStyle: SerializableMotionStyle = {}\n\t\tif (isObject(props.style)) Object.assign(combinedStyle, props.style)\n\t\tif (style) Object.assign(combinedStyle, style)\n\n\t\tprops.style = maybeDropEmptyStyleObject(combinedStyle)\n\n\t\tif (isRootNode) {\n\t\t\tconst safeJSStyle = new SerializableObject(props.style)\n\t\t\tSerializableObject.addSpreadAtEnd(safeJSStyle, js`style`)\n\t\t\tprops.style = safeJSStyle\n\t\t}\n\t}\n\n\t// We also have to combine all the classnames we have collected, finally\n\t// adding a SafeJS binding to a className prop that we can use to style the\n\t// component.\n\tconst classNames: SerializableValue[] = []\n\t// We don't currently collect classnames onto props, but just in case we do\n\t// in future, lets make sure we don't drop them, just like style.\n\tif (props.className) classNames.push(props.className)\n\tif (className) classNames.push(className)\n\tif (isRootNode) {\n\t\tclassNames.unshift(referenceScopingClassNames(ctx))\n\t\tclassNames.push(Var.className)\n\n\t\t// The root primary variant node always receives a ref binding, as well\n\t\t// as a spread of props from the component function's props to allow\n\t\t// additional user overrides.\n\t\tprops.ref = Var.refBinding\n\t\tSerializableObject.addSpreadAtStart(props, Var.restProps)\n\n\t\t// We do this after spreading the rest props to ensure that gestures are\n\t\t// spread after the props, to prevent customers from unsetting the\n\t\t// handlers.\n\t\tif (ctx.scopeType === ScopeType.SmartComponent) {\n\t\t\tclassNames.push(Var.classNames)\n\t\t\tSerializableObject.addSpreadAtStart(props, Var.gestureHandlers)\n\t\t}\n\t}\n\n\t// A kit section is a node that supports customizations and is a direct child of a breakpoint node\n\t// in a kit page.\n\tif (ctx.scopeType === ScopeType.WebPage && isKitSectionNode(ctx.tree, node)) {\n\t\tprops[\"data-section-id\"] = node.getPrimaryId()\n\t}\n\n\t// Fixed Overlay backdrops (OverlayNode), and the Fixed Overlay Contents\n\t// (OverlayNode.children) are all rendered in a portal container that may or\n\t// may not be a descendant of the element that provides the shared style\n\t// class and serialization names. To ensure they can be mounted anywhere\n\t// without losing styles, theses class names are also appended to each of\n\t// these elements.\n\tif (isOverlayNode(node) || isOverlayNode(ctx.tree.getParent(node.id))) {\n\t\tclassNames.unshift(referenceScopingClassNames(ctx))\n\t}\n\n\tif (classNames.length === 1) {\n\t\t// If after all this we only have a single classname, we can just assign it.\n\t\tprops.className = classNames[0]\n\t} else if (classNames.length > 1) {\n\t\t// Otherwise we need to use the `cx` helper to combine classnames,\n\t\t// filtering out falsy ones.\n\t\tprops.className = SafeJS.fn(ctx.imports.addImport(\"framer\", { exportSpecifier: \"cx\" }), ...classNames)\n\t}\n\n\tif (ctx.scopeType === ScopeType.LayoutTemplate && isBreakpointVariant(node)) {\n\t\t// Layout Templates attach an attribute to the root element that allows\n\t\t// wrapped Web Pages to render with position: relative contents, even if\n\t\t// designed as absolute.\n\t\tprops[LAYOUT_TEMPLATE_ATTRIBUTE] = true\n\t}\n\n\tconst { withKey, layoutId } = ancestorInfo\n\tconst id = layoutId ?? node.getPrimaryId()\n\t// If the parent has updated the mutable context to flag that its children\n\t// need keys, add the node id as the key.\n\tif (withKey) props.key = id\n\n\t// Depending on the type of component we are serializing we need to add\n\t// different props to support layout animations.\n\tif (ctx.scopeType === ScopeType.SmartComponent) {\n\t\t// Smart components use layoutIds based on their node id.\n\t\tprops.layoutId = nodeNeedsContainer(node) ? id + CONTAINER_POSTFIX : id\n\t\tprops.layoutDependency = js`layoutDependency`\n\t} else if (ctx.scopeType === ScopeType.CanvasPage) {\n\t\t// Prototype screens use our dynamic layout id generation based on\n\t\t// duplication and name.\n\t\tprops.layoutIdKey = id\n\t\tif (node.duplicatedFrom && node.duplicatedFrom.length > 0) {\n\t\t\tprops.duplicatedFrom = node.duplicatedFrom\n\t\t}\n\t}\n\n\t// We must flag to code component containers that they are fixed. This\n\t// enables framer-motion to inform layout animation calculations.\n\t// Additionally if the node we are collecting for is a code component node\n\t// that does not need a container (in practice, Scroll or Page), add those\n\t// props to the target.\n\tif (isCodeComponentNode(node)) {\n\t\tif (nodeNeedsContainer(node)) {\n\t\t\tif (ancestorInfo.inComponentSlot) props.inComponentSlot = ancestorInfo.inComponentSlot\n\t\t} else if (isBuiltInComponentWithoutContainer(node)) {\n\t\t\tprops.__fromCanvasComponent = true\n\t\t\tcollectCodeComponentProps(node, props, ctx, flags, ancestorInfo)\n\t\t} else {\n\t\t\tcollectCodeComponentProps(node, props, ctx, flags, ancestorInfo)\n\t\t}\n\t\tif (isPositionFixed(node)) props.layoutScroll = true\n\t}\n\n\t// Build Shader component props by importing and reading the shader module config.\n\tif (isShaderNode(node) && !nodeNeedsContainer(node)) {\n\t\tcollectShaderProps(node, props, ctx)\n\t}\n\n\t// Our text components currently require 2 flags to let them know they are\n\t// rendering with style or css classnames.\n\tif (isAnyTextNode(node)) {\n\t\tprops.withExternalLayout = true\n\t\tprops.__fromCanvasComponent = true\n\t}\n\n\tif (withScrollTarget(node) && ctx?.scopeType === ScopeType.WebPage && !isVariant(node)) {\n\t\tprops.id = node.scrollTargetEnabled ? ctx.elementIds.id(node) : undefined\n\t}\n\n\tprops[\"data-framer-cursor\"] = ctx.customCursors.add(node)\n\n\tif (hasFloatingPosition(node)) {\n\t\t// Set the role to `dialog` for general best practices for screen\n\t\t// readers and floating elements. This may not be the perfect role\n\t\t// always but should capture the majority of use cases. In future we\n\t\t// allow users to use the native <dialog> element, or define the role\n\t\t// manually.\n\t\tObject.assign(props, { role: \"dialog\" })\n\t} else {\n\t\tprops[portalIdAttribute] = ctx.elementIds.portalId(node)\n\t}\n\n\t// To ensure that custom cursors declared in an ancestor apply to the popped lightbox, we must\n\t// have an id to reference the lightbox trigger. The classname ensures that the serialization\n\t// hash of the containing component is also applied to the portal contents.\n\tif (hasLightboxEffect(node)) {\n\t\tprops.id = props.id ?? ctx.elementIds.id(node)\n\t\tprops.lightboxClassName = referenceScopingClassNames(ctx)\n\t}\n\n\tconst repeater = ctx.tree.get(ancestorInfo.lastRepeaterId)\n\tif (repeater && isCodeComponentNode(node) && isRepeaterLoaderInstance(node, repeater)) {\n\t\tObject.assign(props, {\n\t\t\t__paginationInfo: ctx.bindings.createWithNode(\"paginationInfo\", repeater),\n\t\t\t__loadMore: ctx.bindings.createWithNode(\"loadMore\", repeater),\n\t\t})\n\t}\n\n\t// For column masonry children, we're assigning an order-id data attribute to nodes\n\t// that we can later use to override the column masonry layout order.\n\tif (\n\t\tancestorInfo.isColumnMasonryLayout &&\n\t\tisObject(ancestorInfo.itemsOrderOverrides) &&\n\t\t!isEmptyObject(ancestorInfo.itemsOrderOverrides)\n\t) {\n\t\tprops[\"data-framer-order-id\"] = id\n\t}\n\n\treturn props\n}\n\nconst collectLinkProps = mergeCollectors(\n\tcollectHref,\n\tcollectAnchorLinkTarget,\n\tcollectLinkSmoothScroll,\n\tcollectLinkClickTrackingId,\n\tcollectLinkRel,\n\tcollectLinkPreserveParams,\n\tcollectNodeId,\n\tcollectScopeId,\n)\n\nfunction createLinkProps(node: CanvasNode, context: JSXContext) {\n\tconst props = new SerializableObject({\n\t\t// Flag that the <Link> can assume its child is a motion element, and can safely bind `onTap`.\n\t\tmotionChild: true,\n\t})\n\tcollectLinkProps(node, props, context)\n\treturn props\n}\n\nfunction createTransitionProps(node: CanvasNode, context: JSXContext) {\n\tconst props = new SerializableObject()\n\tcollectTransition(node, props, context)\n\treturn props\n}\n\nconst defaultFloatingPositionProps = new SerializableObject({\n\tplacement: undefined,\n\talignment: undefined,\n\toffsetX: undefined,\n\toffsetY: undefined,\n\tclassName: undefined,\n\tanchorRef: undefined,\n\tfloatingRef: undefined,\n\tonDismiss: undefined,\n\tportalSelector: undefined,\n\tsafeArea: undefined,\n\tcollisionDetection: undefined,\n})\n\nfunction createFloatingProps(node: CanvasNode, ctx: JSXContext) {\n\tif (!withFloatingPosition(node)) return\n\tif (!hasFloatingPosition(node)) return defaultFloatingPositionProps\n\n\tconst overlayBinding = ctx.overlays.bindingsByOverlayId.get(node.getPrimaryId())\n\tif (!overlayBinding) return\n\tconst parent = ctx.tree.getParent(node.getPrimaryId())\n\tif (!parent) return\n\n\treturn new SerializableObject({\n\t\tplacement: node.floatingPlacement,\n\t\talignment: node.floatingAlignment,\n\t\toffsetX: node.floatingOffsetX,\n\t\toffsetY: node.floatingOffsetY,\n\t\tanchorRef: ctx.rootId === parent.id ? js`${Var.refBinding}` : ctx.elementIds.ref(parent),\n\t\tonDismiss: js`${OverlayCollector.overlayMethod(overlayBinding, \"hide\")}`,\n\t\tsafeArea: node.floatingSafeArea ?? true,\n\t\tzIndex: hasZIndex(node) ? node.zIndex : undefined,\n\t\tcollisionDetection: node.floatingCollisionDetection ?? false,\n\t\tcollisionDetectionPadding: node.floatingCollisionDetection\n\t\t\t? (node.floatingCollisionPadding ?? DEFAULT_FLOATING_COLLISION_PADDING)\n\t\t\t: undefined,\n\t\t[portalIdAttribute]: ctx.elementIds.portalId(node),\n\t\t// Smart Components need to set the serialization hash, and the active\n\t\t// variant classes around the floating content. This is because the\n\t\t// floating content is rendered in a portal, but the css needs to be\n\t\t// scoped to the active variant, and the serialization hash of the\n\t\t// instance.\n\t\tclassName: SafeJS.fn(\n\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"cx\" }),\n\t\t\treferenceScopingClassNames(ctx),\n\t\t\tctx.scopeType === ScopeType.SmartComponent ? Var.classNames : undefined,\n\t\t),\n\t})\n}\n\nfunction createOverlayProps(node: CanvasNode, ctx: JSXContext) {\n\tif (!isOverlayNode(node)) return\n\n\tlet dismissWithEsc: SerializableValue = false\n\tif (isSerializableValue(node.backdropDismissible)) {\n\t\tdismissWithEsc = node.backdropDismissible\n\t} else if (isDynamicValue(node.backdropDismissible)) {\n\t\tdismissWithEsc =\n\t\t\tctx.createDeduplicatedDynamicValueBinding(node.backdropDismissible, node, \"backdropDismissible\") ?? false\n\t}\n\n\treturn new SerializableObject({\n\t\tblockDocumentScrolling: node.blockDocumentScrolling,\n\t\tdismissWithEsc,\n\t})\n}\n\nfunction createFetcherProps(node: CanvasNode, ctx: JSXContext) {\n\tconst fetchesForNode = ctx.fetches.getFetchesForNode(node)\n\n\treturn new SerializableObject({\n\t\trequests: fetchesForNode ?? [],\n\t\tdisabled: ctx.scopeType === ScopeType.SmartComponent ? Var.isLoading : undefined,\n\t})\n}\n\nfunction createCodeComponentViewportProps(node: CanvasNode, ctx: JSXContext) {\n\tif (!isCodeComponentNode(node)) return\n\n\tconst props = new SerializableObject()\n\tconst component = ctx.componentLoader.reactComponentForIdentifier(node.codeComponentIdentifier)\n\n\tconst supportsComponentViewportWidth = component?.annotations?.[AnnotationKey.FramerComponentViewportWidth] === \"true\"\n\tif (supportsComponentViewportWidth) {\n\t\tconst viewportProps = ctx.simulatedDOM.getComponentViewportContext(node)\n\t\tObject.assign(props, viewportProps)\n\t}\n\n\treturn props\n}\n\nfunction createTickerItemProps(node: CanvasNode) {\n\tif (!isNodeTickerItem(node)) return undefined\n\tif (!withSizeDimensionType(node) || !withSize(node)) return undefined\n\n\tconst props: SerializableMotionStyle = {\n\t\twidth: undefined,\n\t\theight: undefined,\n\t}\n\n\tif (node.widthType === DimensionType.Percentage && Number.isFinite(node.width)) {\n\t\tprops.width = `${node.width * 100}%`\n\t}\n\n\tif (node.widthType === DimensionType.FractionOfFreeSpace && Number.isFinite(node.width)) {\n\t\tprops.width =\n\t\t\tnode.cache.parentDirection === \"horizontal\"\n\t\t\t\t? tickerItemFractionalUnitFallback(node.width)\n\t\t\t\t: createCSSDimension(node.width * 100, \"%\")\n\t}\n\n\tif (node.heightType === DimensionType.Percentage && Number.isFinite(node.height)) {\n\t\tprops.height = `${node.height * 100}%`\n\t}\n\n\tif (node.heightType === DimensionType.FractionOfFreeSpace && Number.isFinite(node.height)) {\n\t\tprops.height =\n\t\t\tnode.cache.parentDirection === \"vertical\"\n\t\t\t\t? tickerItemFractionalUnitFallback(node.height)\n\t\t\t\t: createCSSDimension(node.height * 100, \"%\")\n\t}\n\n\treturn new SerializableObject(props)\n}\n\nexport interface PropsForNode {\n\telement: SerializableObject\n\tcontainer?: SerializableObject | undefined\n\tlink?: SerializableObject | undefined\n\ttransition: SerializableObject | undefined\n\tfloating?: SerializableObject | undefined\n\toverlay?: SerializableObject | undefined\n\tfetcher?: SerializableObject | undefined\n\tcomponentViewport?: SerializableObject | undefined\n\ttickerItem?: SerializableObject | undefined\n}\n/**\n * Determine all React props for a canvas node for code-generation. Props will\n * be collected to up to 3 different targets depending on the context. Code\n * components will have props for themselves, as well as a container, while\n * other canvas nodes that are links will have props for themselves, as well as\n * the wrapping <Link> provider.\n *\n * In the future, this function should allow only returning the diff of props\n * that are required by a replica variant.\n */\nexport function propsForNode(\n\tnode: CanvasNode,\n\tctx: JSXContext,\n\tflags: ProcessedVariantsFlags,\n\tancestorInfo: AncestorInfo,\n\t{ className, style }: InitialProps = {},\n): PropsForNode {\n\t// Once code generated, there are a couple of scenarios where a canvas node\n\t// can be represented by 2 separate React components.\n\t// - If the canvas node is a code component (but not a framer page or scroll\n\t//   component), it will rendered inside of a motion.div that will handle\n\t//   styling and positioning, while the component itself will receive its\n\t//   property controls.\n\t// - If the canvas node is a node and has a link (and is not text), it will\n\t//   be rendered inside a <Link> component that will handle providing the\n\t//   href, and anchor scrolling behaviors.\n\t//\n\t// To simplify the application of these different props, we build separate\n\t// collection targets intended for each component.\n\tconst props = createElementProps(node, ctx, ancestorInfo, flags, { style, className })\n\tconst transition = createTransitionProps(node, ctx)\n\tconst floating = createFloatingProps(node, ctx)\n\tconst overlay = createOverlayProps(node, ctx)\n\n\tif (withCodeComponent(node) && nodeNeedsContainer(node)) {\n\t\t// IMPORTANT: Because code component props can contain fetches, its props must be collected\n\t\t// Before the fetcher props are collected or the fetches will not be included.\n\t\tconst codeComponentProps = createCodeComponentProps(node, ctx, flags, ancestorInfo)\n\t\tconst fetcherProps = createFetcherProps(node, ctx)\n\n\t\treturn {\n\t\t\tcontainer: props,\n\t\t\ttransition,\n\t\t\tfloating,\n\t\t\toverlay,\n\t\t\tfetcher: fetcherProps,\n\t\t\telement: codeComponentProps,\n\t\t\tcomponentViewport: createCodeComponentViewportProps(node, ctx),\n\t\t\ttickerItem: createTickerItemProps(node),\n\t\t}\n\t}\n\n\tif (isShaderNode(node)) {\n\t\tif (ctx.scopeType === ScopeType.SmartComponent) {\n\t\t\tprops.rendersWithMotion = true\n\t\t}\n\n\t\tconst shaderElementProps = new SerializableObject({\n\t\t\t__fromCanvasComponent: true,\n\t\t\twidth: \"100%\",\n\t\t\theight: \"100%\",\n\t\t})\n\t\tcollectShaderProps(node, shaderElementProps, ctx)\n\n\t\treturn {\n\t\t\tcontainer: props,\n\t\t\telement: shaderElementProps,\n\t\t\ttransition,\n\t\t\tfloating,\n\t\t\toverlay,\n\t\t\tlink: createLinkProps(node, ctx),\n\t\t\tfetcher: createFetcherProps(node, ctx),\n\t\t\ttickerItem: createTickerItemProps(node),\n\t\t}\n\t}\n\n\treturn {\n\t\telement: props,\n\t\ttransition,\n\t\tfloating,\n\t\toverlay,\n\t\tlink: createLinkProps(node, ctx),\n\t\tfetcher: createFetcherProps(node, ctx),\n\t\ttickerItem: createTickerItemProps(node),\n\t}\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { nodeSupportsEventActions } from \"document/components/chrome/properties/utils/eventActions.ts\"\nimport type { CanvasTree } from \"../../CanvasTree.ts\"\nimport type { CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport { isRichTextNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { CUSTOM_CURSORS_CSS_VARIABLE, isCSSCursor, withCursor } from \"../WithCursor.ts\"\nimport type { WithFrameEvents } from \"../WithFrameEvents.ts\"\nimport { withFrameEvents } from \"../WithFrameEvents.ts\"\nimport { isGestureVariant, isVariant } from \"../WithVariant.ts\"\n\nconst eventTriggersRequireCursor: (keyof WithFrameEvents)[] = [\n\t\"onTap\",\n\t\"onTapStart\",\n\t\"onClick\",\n\t\"onMouseDown\",\n\t\"onMouseUp\",\n]\n\nconst hasActionsWithCursor = (tree: CanvasTree, componentLoader: AnyComponentLoader, node: CanvasNode) => {\n\tif (!withFrameEvents(node)) return false\n\tif (!nodeSupportsEventActions(tree, node)) return false\n\n\tconst actions = node.getActions(componentLoader)\n\treturn eventTriggersRequireCursor.some(triggerKey => {\n\t\tif (triggerKey in actions) {\n\t\t\tconst action = actions[triggerKey]\n\t\t\treturn action ? action.length > 0 : false\n\t\t}\n\n\t\treturn false\n\t})\n}\n\nexport const collectCursor = styleCollector((node, style, context) => {\n\tif (!withCursor(node)) return\n\tif (isGestureVariant(node)) return\n\n\tif (isDynamicValue(node.cursor) && isJSXContext(context)) {\n\t\tstyle.cursor = context.cssVariableDefinitions.create(node, \"cursor\")\n\t\treturn\n\t}\n\n\tif (node.cursor && isCSSCursor(node.cursor)) {\n\t\tstyle.cursor = node.resolveValue(\"cursor\", context.variableOverrides)\n\n\t\t// RichTextNodes can have multiple nested links. Those links are handled\n\t\t// internally by LinkStylePresets and ProseMirror. As a result, we can\n\t\t// no longer just set the CSS style declaration at the root level\n\t\t// because those links would use the user agent style for anchors.\n\t\t// Instead, we store the cursor value in a CSS Custom Property and use\n\t\t// it in the anchors directly.\n\t\tif (isRichTextNode(node) && node.hasLinks()) {\n\t\t\tstyle.cursor = undefined\n\t\t\tstyle[CUSTOM_CURSORS_CSS_VARIABLE] = node.cursor\n\t\t}\n\n\t\treturn\n\t}\n\n\tif (!isJSXContext(context)) return\n\n\tconst isVariantWithGesture = isVariant(node) && context.topLevelVariantsWithGestures[node.id]\n\tstyle.cursor =\n\t\tisVariantWithGesture || hasActionsWithCursor(context.tree, context.componentLoader, node) ? \"pointer\" : undefined\n})\n", "import { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { hasLink } from \"../WithLink.ts\"\n\nexport const collectLink = styleCollector((node, style) => {\n\tif (!hasLink(node)) return\n\tstyle.textDecoration = \"none\"\n})\n", "import { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { withHTMLTag } from \"../WithHTMLTag.ts\"\nimport { isPinnable } from \"../WithPins.ts\"\n\n/**\n * Collects all of the nodes set to use <ul> as the underlying html tag\n * and applies a CSS reset of sorts so that default <ul> styles do not apply.\n */\nexport const collectList = styleCollector((node, style, ctx) => {\n\tif (!isPinnable(node)) return\n\tif (!withHTMLTag(node)) return\n\n\t// ctx.renderAsListNodes is a precomputed Map<NodeID, true> that indicates which nodes are lists\n\tif (!ctx.renderAsListNodes?.has(node.id)) return\n\n\tstyle.listStyle = \"none\"\n\tstyle.margin = 0\n\n\t// padding needs to be set to 0 (in order to override default browser\n\t// styles) in the case where a node doesn't have an explicit layout set,\n\t// but that is handled in collectPadding\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { isAnyOverflowAuto, withOverflow } from \"../WithOverflow.ts\"\nimport { withOverscrollBehavior } from \"../WithOverscrollBehavior.ts\"\n\nexport const collectOverscrollBehavior = styleCollector((node, style, context) => {\n\tif (!withOverscrollBehavior(node) || !withOverflow(node)) return\n\tif (!isAnyOverflowAuto(node)) return\n\n\tif (isDynamicValue(node.overscrollBehavior) && isJSXContext(context)) {\n\t\tstyle.overscrollBehavior = context.cssVariableDefinitions.create(node, \"overscrollBehavior\")\n\n\t\treturn\n\t}\n\n\tstyle.overscrollBehavior = node.resolveValue(\"overscrollBehavior\", context.variableOverrides)\n})\n", "import { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\nimport { withScrollTarget } from \"../WithScrollTarget.ts\"\n\nexport const collectScrollMargin = styleCollector((node, style) => {\n\tif (!withScrollTarget(node)) return\n\n\tstyle.scrollMarginTop =\n\t\tisNumber(node.scrollMarginTop) && node.scrollTargetEnabled && node.scrollMarginTop > 0\n\t\t\t? node.scrollMarginTop\n\t\t\t: undefined\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { ConvertColor } from \"library/index.ts\"\nimport { isTokenCSSVariable, stripMetadataFromCSSVariable } from \"../../utils/tokens.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { withTapHighlight } from \"../WithTapHighlight.ts\"\n\nexport const collectTapHighlight = styleCollector((node, style, context) => {\n\tif (!withTapHighlight(node)) return\n\n\tif (isDynamicValue(node.tapHighlightColor) && isJSXContext(context)) {\n\t\tstyle.WebkitTapHighlightColor = context.cssVariableDefinitions.create(node, \"tapHighlightColor\")\n\t\treturn\n\t}\n\n\tconst tapHighlightColor = node.resolveValue(\"tapHighlightColor\", context.variableOverrides)\n\n\tif (isTokenCSSVariable(tapHighlightColor)) {\n\t\tstyle.WebkitTapHighlightColor = stripMetadataFromCSSVariable(tapHighlightColor)\n\t\treturn\n\t}\n\n\tstyle.WebkitTapHighlightColor = tapHighlightColor ? ConvertColor.toRgbString(tapHighlightColor) : undefined\n})\n", "import { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { withTextSelection } from \"../WithTextSelection.ts\"\n\nexport const collectTextSelection = styleCollector((node, style, context) => {\n\tif (!withTextSelection(node)) {\n\t\treturn\n\t}\n\n\tconst textSelection = node.resolveValue(\"textSelection\")\n\n\tstyle[\"--selection-color\"] = textSelection?.color\n\tstyle[\"--selection-background-color\"] = textSelection?.backgroundColor\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { isDynamicValue } from \"../DynamicValue.ts\"\nimport { hasUserSelect, withUserSelect } from \"../WithUserSelect.ts\"\n\nexport const collectUserSelect = styleCollector((node, style, context) => {\n\tif (!withUserSelect(node)) return\n\tif (isDynamicValue(node.userSelect) && isJSXContext(context)) {\n\t\tstyle.userSelect = style.WebkitUserSelect = context.cssVariableDefinitions.create(node, \"userSelect\")\n\t\treturn\n\t}\n\tstyle.userSelect = style.WebkitUserSelect = hasUserSelect(node)\n\t\t? node.resolveValue(\"userSelect\", context.variableOverrides)\n\t\t: undefined\n})\n", "import { isJSXContext } from \"code-generation/jsx/types.ts\"\nimport { viewTransitionName } from \"code-generation/utils/CSSCollector.ts\"\nimport { styleCollector } from \"code-generation/utils/collector.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { isBreakpointVariant } from \"../WithVariant.ts\"\nimport { withViewTransitionNone } from \"../WithViewTransitionNone.ts\"\n\nexport const collectViewTransitionName = styleCollector((node, style, context) => {\n\tif (!withViewTransitionNone(node) || !isJSXContext(context) || context.scopeType !== ScopeType.LayoutTemplate) {\n\t\treturn\n\t}\n\n\tconst parent = context.tree.getParent(node.id)\n\tif (!isBreakpointVariant(parent)) return\n\n\tstyle.viewTransitionName =\n\t\tnode.viewTransitionNone === true ? viewTransitionName(node, context.serializationId, true) : undefined\n})\n", "import { type CollectorContext, styleCollector } from \"code-generation/utils/collector.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport {\n\twillChangeEffectOverrideCSSVariable,\n\twillChangeFilterOverrideCSSVariable,\n\twillChangeOverrideCSSVariable,\n} from \"library/render/utils/injectComponentCSSRules.ts\"\nimport type { CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport { withChildren } from \"../WithChildren.ts\"\nimport { isClippingOverflowValue, withOverflow } from \"../WithOverflow.ts\"\nimport { hasStyleAppearEffect } from \"../WithStyleAppearEffect.ts\"\nimport { hasWhileHover } from \"../WithWhileHover.ts\"\nimport { hasWhileTap } from \"../WithWhileTap.ts\"\nimport { EffectTrigger, effectTriggerStringToEnumMember } from \"../utils/EffectTrigger.ts\"\nimport { isSupportedEffectScopeType, nodeSupportsGestureEffects } from \"../utils/effects.ts\"\nimport { hasNonDefaultRadius } from \"../utils/radius.ts\"\nimport { shouldRenderShadowUsingFilter } from \"../utils/wantsFilterShadow.ts\"\n\nexport const collectWillChange = styleCollector((node, style, ctx) => {\n\tconst willChange = willChangeValue(node, ctx)\n\n\tstyle.willChange = willChange\n})\n\nconst effectWillChangeVarReference = `var(${willChangeEffectOverrideCSSVariable}, transform)`\n\nfunction willChangeValue(node: CanvasNode, ctx: CollectorContext): string | undefined {\n\tif (isSupportedEffectScopeType(ctx.scopeType)) {\n\t\tif (nodeSupportsGestureEffects(node) && (hasWhileHover(node) || hasWhileTap(node))) {\n\t\t\treturn effectWillChangeVarReference\n\t\t}\n\n\t\tif (\n\t\t\t// In Smart Components, presence animations are run with a higher order component, that can\n\t\t\t// also control `will-change`.\n\t\t\tctx.scopeType !== ScopeType.SmartComponent &&\n\t\t\thasStyleAppearEffect(node) &&\n\t\t\teffectTriggerStringToEnumMember(node.styleAppearEffectTrigger) === EffectTrigger.OnMount\n\t\t) {\n\t\t\treturn effectWillChangeVarReference\n\t\t}\n\t}\n\n\t// For Safari 15, if overflow hidden is set, and there is a border radius, the element must be layer\n\t// backed. Otherwise the border radius will be ignored by child elements that are themselves layer\n\t// backed. This can be some component with will-change set, but also happens when children animate.\n\t// Note this was fixed with Safari 16.\n\tif (!withChildren(node)) return\n\tif (!withOverflow(node)) return\n\t// Overflow \"clip\" will fallback to \"hidden\" in Safari 15\n\tif (!isClippingOverflowValue(node.overflow)) return\n\n\tif (hasNonDefaultRadius(node)) {\n\t\t// This will be compiled into the module, and will run the same anywhere. But the canvas\n\t\t// needs more control over layers being created, so we use a variable that can be used to\n\t\t// disable the will-change.\n\t\treturn `var(${willChangeOverrideCSSVariable}, transform)`\n\t}\n\n\t/**\n\t * NOTE: Workaround for Safari \u226418.\n\t * Safari misrenders filter drop-shadows when combined with overflow clipping,\n\t * because it rasterizes the filtered content before applying the clip.\n\t * Setting `will-change: filter` forces Safari to promote the element to its own\n\t * compositing layer, ensuring shadows render correctly without being clipped.\n\t * Safe to remove once Safari \u226418 is no longer supported.\n\t */\n\tif (shouldRenderShadowUsingFilter(node)) {\n\t\treturn `var(${willChangeFilterOverrideCSSVariable}, filter)`\n\t}\n\n\treturn undefined\n}\n", "import { isEmptyObject } from \"@framerjs/shared\"\nimport type { SerializableMotionStyle } from \"code-generation/types.ts\"\nimport { mergeCollectors } from \"code-generation/utils/collector.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { extractInlineStyles } from \"document/models/CanvasTree/nodes/utils/extractInlineStyles.ts\"\nimport {\n\tisCodeComponentNode,\n\tisOverlayNode,\n\tisSlotPropertyNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasFloatingPosition } from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { hasAnyLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { withRichText } from \"document/models/CanvasTree/traits/WithRichText.ts\"\nimport { collectMasks } from \"document/models/CanvasTree/traits/collectProps/collectMasks.ts\"\nimport {\n\tcollectBackdropFill,\n\tcollectBackdropLayout,\n} from \"document/models/CanvasTree/traits/collectStyles/collectBackdrop.ts\"\nimport { collectBackgroundFill } from \"document/models/CanvasTree/traits/collectStyles/collectBackgroundFill.ts\"\nimport { collectBackgroundFilters } from \"document/models/CanvasTree/traits/collectStyles/collectBackgroundFilters.ts\"\nimport { collectBlending } from \"document/models/CanvasTree/traits/collectStyles/collectBlending.ts\"\nimport { collectBorderVariables } from \"document/models/CanvasTree/traits/collectStyles/collectBorder.ts\"\nimport { collectBoxShadow } from \"document/models/CanvasTree/traits/collectStyles/collectBoxShadow.ts\"\nimport { collectCorner } from \"document/models/CanvasTree/traits/collectStyles/collectCorner.ts\"\nimport { collectCursor } from \"document/models/CanvasTree/traits/collectStyles/collectCursor.ts\"\nimport { collectFilters } from \"document/models/CanvasTree/traits/collectStyles/collectFilters.ts\"\nimport { collectFlexLayout } from \"document/models/CanvasTree/traits/collectStyles/collectFlexLayout.ts\"\nimport { collectFontVariants } from \"document/models/CanvasTree/traits/collectStyles/collectFontVariants.ts\"\nimport {\n\tcollectBooleanInputStyleVariables,\n\tcollectBooleanInputTransitionVariable,\n} from \"document/models/CanvasTree/traits/collectStyles/collectFormBooleanInputStyles.ts\"\nimport { collectFormInputFocusedStyleVariables } from \"document/models/CanvasTree/traits/collectStyles/collectFormInputFocusedStyleVariables.ts\"\nimport { collectFormInputIcon } from \"document/models/CanvasTree/traits/collectStyles/collectFormInputIcon.ts\"\nimport {\n\tcollectInputFontColorVariable,\n\tcollectInputFontStyleVariables,\n\tcollectInputInvalidColorVariable,\n\tcollectInputPlaceholderColorVariable,\n\tcollectTextAreaStyleVariables,\n} from \"document/models/CanvasTree/traits/collectStyles/collectFormInputStyleVariables.ts\"\nimport { collectGap } from \"document/models/CanvasTree/traits/collectStyles/collectGap.ts\"\nimport { collectGridItemLayout } from \"document/models/CanvasTree/traits/collectStyles/collectGridItemLayout.ts\"\nimport { collectGridLayout } from \"document/models/CanvasTree/traits/collectStyles/collectGridLayout.ts\"\nimport { collectImageRendering } from \"document/models/CanvasTree/traits/collectStyles/collectImageRendering.ts\"\nimport { collectLayout } from \"document/models/CanvasTree/traits/collectStyles/collectLayout.ts\"\nimport { collectLink } from \"document/models/CanvasTree/traits/collectStyles/collectLink.ts\"\nimport { collectList } from \"document/models/CanvasTree/traits/collectStyles/collectList.ts\"\nimport { collectOpacity } from \"document/models/CanvasTree/traits/collectStyles/collectOpacity.ts\"\nimport { collectOverflow } from \"document/models/CanvasTree/traits/collectStyles/collectOverflow.ts\"\nimport { collectOverscrollBehavior } from \"document/models/CanvasTree/traits/collectStyles/collectOverscrollBehavior.ts\"\nimport { collectPadding } from \"document/models/CanvasTree/traits/collectStyles/collectPadding.ts\"\nimport { collectParagraphSpacing } from \"document/models/CanvasTree/traits/collectStyles/collectParagraphSpacing.ts\"\nimport { collectPointerEvents } from \"document/models/CanvasTree/traits/collectStyles/collectPointerEvents.ts\"\nimport { collectRichTextVariables } from \"document/models/CanvasTree/traits/collectStyles/collectRichTextVariables.ts\"\nimport { collectRotate } from \"document/models/CanvasTree/traits/collectStyles/collectRotate.ts\"\nimport { collectScrollMargin } from \"document/models/CanvasTree/traits/collectStyles/collectScrollMargin.ts\"\nimport { collectSizeConstraints } from \"document/models/CanvasTree/traits/collectStyles/collectSizeConstraints.ts\"\nimport { collectTapHighlight } from \"document/models/CanvasTree/traits/collectStyles/collectTapHighlight.ts\"\nimport { collectTextSelection } from \"document/models/CanvasTree/traits/collectStyles/collectTextSelection.ts\"\nimport { collectTextShadow } from \"document/models/CanvasTree/traits/collectStyles/collectTextShadow.ts\"\nimport {\n\tcollectLinkStyleVariables,\n\tcollectTextStyleVariables,\n} from \"document/models/CanvasTree/traits/collectStyles/collectTextStyleVariables.ts\"\nimport { collectTextTruncation } from \"document/models/CanvasTree/traits/collectStyles/collectTextTruncation.ts\"\nimport { collectTickerCustomProperties } from \"document/models/CanvasTree/traits/collectStyles/collectTickerCustomProperties.ts\"\nimport { collectTokenOverrides } from \"document/models/CanvasTree/traits/collectStyles/collectTokenOverrides.ts\"\nimport {\n\tcollectTransformStyle,\n\tcollectTransforms,\n} from \"document/models/CanvasTree/traits/collectStyles/collectTransforms.ts\"\nimport { collectUserSelect } from \"document/models/CanvasTree/traits/collectStyles/collectUserSelect.ts\"\nimport { collectVectorInstanceVariables } from \"document/models/CanvasTree/traits/collectStyles/collectVectorInstanceVariables.ts\"\nimport { collectViewTransitionName } from \"document/models/CanvasTree/traits/collectStyles/collectViewTransitionName.ts\"\nimport { collectWillChange } from \"document/models/CanvasTree/traits/collectStyles/collectWillChange.ts\"\nimport { collectZIndex, getZIndex } from \"document/models/CanvasTree/traits/collectStyles/collectZIndex.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { isNull } from \"utils/typeChecks.ts\"\nimport type { JSXContext } from \"./types.ts\"\n\n/**\n * This function includes all collectors that can always be included in a css\n * class because they are never animated with framer-motion variants.\n */\nconst collectStaticStyle = mergeCollectors(\n\tcollectBackdropLayout,\n\tcollectBlending,\n\tcollectBooleanInputTransitionVariable,\n\tcollectCursor,\n\tcollectFlexLayout,\n\tcollectFormInputFocusedStyleVariables,\n\tcollectGap,\n\tcollectGridItemLayout,\n\tcollectGridLayout,\n\tcollectImageRendering,\n\tcollectInputFontStyleVariables,\n\tcollectLayout,\n\tcollectLink,\n\tcollectList,\n\tcollectOverflow,\n\tcollectOverscrollBehavior,\n\tcollectPadding,\n\tcollectPointerEvents,\n\tcollectScrollMargin,\n\tcollectTextSelection,\n\tcollectTickerCustomProperties,\n\tcollectSizeConstraints,\n\tcollectTapHighlight,\n\tcollectTextAreaStyleVariables,\n\tcollectTextTruncation,\n\tcollectTokenOverrides,\n\tcollectTransformStyle,\n\tcollectUserSelect,\n\tcollectViewTransitionName,\n\tcollectWillChange,\n\tcollectZIndex,\n)\n\n/**\n * This function includes all collectors that may be animated with framer-motion\n * variants.\n */\nexport const collectAnimatableStyle = mergeCollectors(\n\tcollectBackdropFill,\n\tcollectBackgroundFill,\n\tcollectBackgroundFilters,\n\tcollectBooleanInputStyleVariables,\n\tcollectBorderVariables,\n\tcollectBoxShadow,\n\tcollectFilters,\n\tcollectFontVariants,\n\tcollectFormInputIcon,\n\tcollectInputFontColorVariable,\n\tcollectInputInvalidColorVariable,\n\tcollectInputPlaceholderColorVariable,\n\tcollectLinkStyleVariables,\n\tcollectMasks,\n\tcollectOpacity,\n\tcollectParagraphSpacing,\n\tcollectCorner,\n\tcollectRichTextVariables,\n\tcollectTextShadow,\n\tcollectTextStyleVariables,\n\tcollectVectorInstanceVariables,\n)\n\n/**\n * This function includes all collectors whose styles are always set in the inline style attribute.\n */\nexport const collectInlineStyle = mergeCollectors(\n\t// Regardless of the scope type, motion transforms are always set in inline style.\n\tcollectTransforms,\n\tcollectRotate,\n)\n\ninterface StyleForNode {\n\t/** CSS rules that go into `<style>` */\n\tcss: SerializableMotionStyle\n\t/** CSS rules that are set directly on the element through the `style` attribute */\n\tstyle: SerializableMotionStyle | undefined\n}\n\nfunction parentDirectedPosition(parent: CanvasNode | null, node: CanvasNode) {\n\tif (isNull(parent) || hasAnyLayout(parent) || isCodeComponentNode(parent)) return \"relative\"\n\tif (isOverlayNode(parent)) return \"fixed\"\n\tif (isSlotPropertyNode(parent)) return \"relative\"\n\tif (hasFloatingPosition(node)) return \"relative\"\n\treturn \"absolute\"\n}\n\nexport function styleForNode(\n\tnode: CanvasNode,\n\tparent: CanvasNode | null,\n\tcontext: JSXContext,\n\toverrides?: SerializableMotionStyle,\n): StyleForNode {\n\tconst css: SerializableMotionStyle = {\n\t\tposition: parentDirectedPosition(parent, node),\n\t\t// Overlay children inherit their parent's z-index unless they specify\n\t\t// their own.\n\t\tzIndex: isOverlayNode(parent) ? getZIndex(parent, context) : undefined,\n\t\t...overrides,\n\t}\n\n\t// Webpages don't store animatable styles as inline style but instead\n\t// include all style in a single css declaration. To support that, we point\n\t// the collection functions to the appropriate target (css for webpages and\n\t// for plain HTML elements, inline style for everything else).\n\tconst useStaticCSSForStaticStyle =\n\t\tcontext.scopeType === ScopeType.WebPage ||\n\t\tcontext.scopeType === ScopeType.LayoutTemplate ||\n\t\tcontext.nodeRendersWithMotion?.get(node) === false\n\n\tconst inlineStyle: SerializableMotionStyle = {}\n\tif (context.llmSnapshot) Object.assign(inlineStyle, css)\n\tcollectStaticStyle(node, !context.llmSnapshot ? css : inlineStyle, context)\n\tcollectAnimatableStyle(node, !context.llmSnapshot && useStaticCSSForStaticStyle ? css : inlineStyle, context)\n\n\t/**\n\t * @FIXME - We should try to cache this expensive HTML walk, since we are\n\t * going to perform it again when we get the props for the node.\n\t */\n\tif (withRichText(node) && context.scopeType === ScopeType.SmartComponent) {\n\t\textractInlineStyles(node.html, inlineStyle)\n\t}\n\n\tcollectInlineStyle(node, inlineStyle, context)\n\n\treturn {\n\t\tcss,\n\t\t// Style may be undefined in 2 cases:\n\t\t// 1. We are collecting for a non-webpage, but the layer has no inline\n\t\t//    style\n\t\t// 2. We are collecting for a webpage, so all the styles were collected\n\t\t//    to the css target\n\t\tstyle: isEmptyObject(inlineStyle) ? undefined : inlineStyle,\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { collectAnimatableStyle, collectInlineStyle } from \"code-generation/jsx/styleForNode.ts\"\nimport type { SerializableMotionStyle } from \"code-generation/types.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tCodeComponentNode,\n\tFrameNode,\n\tRichTextNode,\n\tSVGNode,\n\tShapeContainerNode,\n\tTextNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { cornerShapeBrowserDefault } from \"document/models/CanvasTree/traits/WithCornerShape.ts\"\nimport { HardCodedCodeIdentifier } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport { ClassDiscriminator } from \"utils/withClassDiscriminator.ts\"\nimport type { CollectorContext } from \"./collector.ts\"\n\n// Collectors skip browser defaults to avoid adding lots of unnecessary styles\n// to the output of code-generation. However, we need to know browser style\n// defaults so we can add them where required to support framer-motion (see\n// code-generation/jsx/utils.ts).\nconst browserDefaults: SerializableMotionStyle = {\n\topacity: 1,\n\trotate: 0,\n\tborderTopLeftRadius: 0,\n\tborderTopRightRadius: 0,\n\tborderBottomRightRadius: 0,\n\tborderBottomLeftRadius: 0,\n\tcornerShape: `superellipse(${cornerShapeBrowserDefault})`,\n\tbackgroundColor: \"rgba(0, 0, 0, 0)\",\n\tbackground: \"rgba(0, 0, 0, 0)\",\n\tboxShadow: \"none\",\n\tfilter: \"none\",\n\tWebkitFilter: \"none\",\n\tbackdropFilter: \"none\",\n\tWebkitBackdropFilter: \"none\",\n\tmask: \"none\",\n\tWebkitMask: \"none\",\n\ttextShadow: \"none\",\n\tscale: 1,\n\trotateX: 0,\n\trotateY: 0,\n\tskewX: 0,\n\tskewY: 0,\n\tz: 0,\n\tpadding: 0,\n}\n\nfunction makeDefaults(componentLoader: ComponentLoader): Partial<Record<ClassDiscriminator, SerializableMotionStyle>> {\n\tconst frame = {}\n\tconst text = {}\n\tconst richText = {}\n\tconst component = {}\n\tconst svg = {}\n\tconst shapeContainer = {}\n\n\tconst nodeAndStyleTarget: [CanvasNode, SerializableMotionStyle][] = [\n\t\t// Default frame nodes so that a `transparent`\n\t\t// default is collected for it, this is the HTML default that generation\n\t\t// expects.\n\t\t[\n\t\t\tnew FrameNode({\n\t\t\t\tfillEnabled: true,\n\t\t\t\tfillType: \"color\",\n\t\t\t\tfillColor: \"rgba(0, 0, 0, 0)\",\n\t\t\t\tborderWidth: 0,\n\t\t\t\tborderEnabled: true,\n\t\t\t\tborderColor: \"rgba(0, 0, 0, 0)\",\n\t\t\t\tborderStyle: \"solid\",\n\t\t\t}),\n\t\t\tframe,\n\t\t],\n\t\t[new TextNode(), text],\n\t\t[new RichTextNode(), richText],\n\t\t[new CodeComponentNode({ codeComponentIdentifier: HardCodedCodeIdentifier.page }), component],\n\t\t[new SVGNode(), svg],\n\t\t[new ShapeContainerNode(), shapeContainer],\n\t]\n\n\tconst context: CollectorContext = { componentLoader }\n\n\tnodeAndStyleTarget.forEach(([node, styleTarget]) => {\n\t\tcollectAnimatableStyle(node, styleTarget, context)\n\t\tcollectInlineStyle(node, styleTarget, context)\n\t})\n\n\treturn {\n\t\t[ClassDiscriminator.FrameNode]: Object.assign(frame, browserDefaults),\n\t\t[ClassDiscriminator.TextNode]: Object.assign(text, browserDefaults),\n\t\t[ClassDiscriminator.RichTextNode]: Object.assign(richText, browserDefaults),\n\t\t[ClassDiscriminator.CodeComponentNode]: Object.assign(component, browserDefaults),\n\t\t[ClassDiscriminator.SVGNode]: Object.assign(svg, browserDefaults),\n\t\t[ClassDiscriminator.ShapeContainerNode]: Object.assign(shapeContainer, browserDefaults),\n\t}\n}\n\nlet styleDefaults: ReturnType<typeof makeDefaults> | undefined\n\nexport function getStyleDefaults(componentLoader: ComponentLoader) {\n\tstyleDefaults ??= makeDefaults(componentLoader)\n\treturn styleDefaults\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { SerializableRecord, SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { type SafeJS, isSafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { SerializableMotionStyle } from \"code-generation/types.ts\"\nimport { getStyleDefaults } from \"code-generation/utils/styleDefaults.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { generateReplicaChildId } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport { isObject, isUndefined } from \"utils/typeChecks.ts\"\n\n/**\n * This helper ensures that framer-motion can always animate between `style` and\n * a variant. framer-motion doesn't know what the default browser values are, so\n * can't animate from {opacity: 0} --> {opacity: undefined}, and we can't use\n * tricks to work around this since the initial variant can be the one with\n * opacity: 0. To work around this, we must replace undefined values with\n * defaults. In the future, if we use the WAAPI to drive motion variants this\n * would become obsolete because the browser *can* animate from {opacity: 0} -->\n * {opacity: \"unset\"}.\n */\nexport function upgradeStyleForMotionVariants(\n\tcomponentLoader: ComponentLoader,\n\tnode: CanvasNode,\n\tprops: SerializableRecord,\n\tvariant?: SerializableMotionStyle,\n): void {\n\tif (!variant || isUndefined(node.__class) || isSafeJS(props.style)) return\n\tif (!isUndefined(props.style) && !isObject(props.style)) return\n\n\t// Used in loop, will never not be initialized\n\t// eslint-disable-next-line framer-studio/no-implicit-undefined-let\n\tlet key: keyof SerializableMotionStyle\n\tfor (key in variant) {\n\t\t// If both variant and style have undefined values, there is no need to\n\t\t// set their defaults. This shouldn't realistically happen.\n\t\tif (isUndefined(props.style?.[key]) && isUndefined(variant[key])) continue\n\t\t// If both style and variant have a value for the key, we don't need to\n\t\t// replace undefined values with defaults.\n\t\tif (props.style && key in props.style && !isUndefined(props.style[key]) && !isUndefined(variant[key])) continue\n\n\t\tconst styleDefaults = getStyleDefaults(componentLoader)\n\t\tconst defaultForNodeType = styleDefaults?.[node.__class]\n\t\tif (!defaultForNodeType || !(key in defaultForNodeType)) {\n\t\t\t// If the variant has an undefined value, but there is no style\n\t\t\t// default, and the primary has a value, that means we probably\n\t\t\t// don't know how to animate the difference. To ensure that the end\n\t\t\t// result is still correct, we set the value to js`undefined` to\n\t\t\t// ensure that we still remove whatever value is set in the primary\n\t\t\t// variant.\n\t\t\tif (isUndefined(variant[key])) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: type is too complex for TypeScript to evaluate here\n\t\t\t\tvariant[key as any] = js`undefined`\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tconst defaultValue = defaultForNodeType[key]\n\t\t// Both the style from the primary variant, and the style for the\n\t\t// replica motion variant can have an undefined value if the value is\n\t\t// the default (e.g. opacity: 1), so we must fill that in in either\n\t\t// case.\n\t\tif (isUndefined(props.style?.[key])) {\n\t\t\tconst style: SerializableValue = props.style ?? {}\n\t\t\tstyle[key] = defaultValue\n\t\t\tprops.style = style\n\t\t}\n\t\tif (isUndefined(variant[key])) {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: type is too complex for TypeScript to evaluate here\n\t\t\tvariant[key as any] = defaultValue as SafeJS\n\t\t}\n\t}\n}\n\nexport function getReplicaNode(variant: CanvasNode, primaryId: NodeID, tree: CanvasTree) {\n\tconst id = variant.originalid === primaryId ? variant.id : generateReplicaChildId(variant.id, primaryId)\n\treturn tree.get(id)\n}\n", "import { assert, getLogger, isEmptyObject } from \"@framerjs/shared\"\nimport type { SerializableRecord, SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { jst } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport type { RenderConditions, SerializableMotionStyle } from \"code-generation/types.ts\"\nimport { nodeHasSerializationHashClassName } from \"code-generation/utils/CSSCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport { SubqueryCollector } from \"code-generation/utils/SubqueryCollector.ts\"\nimport { nodeNeedsContainer } from \"code-generation/utils/builtInCodeComponents.ts\"\nimport { getVisibility } from \"code-generation/utils/getVisibility.ts\"\nimport { logOutdatedCacheError } from \"code-generation/utils/outdatedCacheError.ts\"\nimport type { CanvasNode, CodeComponentNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type FrameNode from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport type { SlotNode } from \"document/models/CanvasTree/nodes/SlotNode.ts\"\nimport { isAnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport {\n\tisCodeComponentNode,\n\tisDataRepeater,\n\tisDynamicVectorInstance,\n\tisRichTextNode,\n\tisSlotNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { hasPaginationEnabled } from \"document/models/CanvasTree/traits/WithCollectionOptions.ts\"\nimport { isRepeaterLoaderInstance } from \"document/models/CanvasTree/traits/WithDataLoaderVariants.ts\"\nimport { getGradientInfo, hasImageFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { hasFloatingPosition } from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { isListTag, withHTMLTag } from \"document/models/CanvasTree/traits/WithHTMLTag.ts\"\nimport {\n\ttype WithItemsOrder,\n\thasItemsOrderOverride,\n\twithItemsOrder,\n} from \"document/models/CanvasTree/traits/WithItemsOrder.ts\"\nimport { hasColumnMasonryLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { hasLink } from \"document/models/CanvasTree/traits/WithLink.ts\"\nimport { hasDataRepeaterArray } from \"document/models/CanvasTree/traits/WithRepeaterDataSource.ts\"\nimport { hasScrollTarget } from \"document/models/CanvasTree/traits/WithScrollTarget.ts\"\nimport type { IsReplica } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { hasTickerEffect, isNodeTickerItem } from \"document/models/CanvasTree/traits/WithTickerEffect.ts\"\nimport { hasTransition } from \"document/models/CanvasTree/traits/WithTransition.ts\"\nimport { hasTriggerActions } from \"document/models/CanvasTree/traits/WithTriggerActions.ts\"\nimport type { IsVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport {\n\thasVariantTransition,\n\tisBreakpointVariant,\n\tisGestureVariant,\n} from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { hasVariantAppearEffect } from \"document/models/CanvasTree/traits/WithVariantAppearEffect.ts\"\nimport {\n\thasAnyHOCEffect,\n\thasSmartComponentPresenceEffect,\n} from \"document/models/CanvasTree/traits/collectProps/collectEffects.ts\"\nimport { coerceToNegativeColumnGap } from \"document/models/CanvasTree/traits/collectStyles/collectGap.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport { hasOptimizedAppearEffect } from \"document/models/CanvasTree/traits/utils/supportsAppearEffectOptimization.ts\"\nimport { nextDescendantRepeaterIds } from \"document/models/updateTreeCacheForVekter.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { framerAppearIdKey } from \"library/index.ts\"\nimport { defaultRichTextContainerStyle } from \"library/render/utils/injectRichTextRules.ts\"\nimport { updateStackAndGridChildCacheForCodeGeneration } from \"renderer/updateStackAndGridChildCache.ts\"\nimport { isNumber, isObject, isUndefined } from \"utils/typeChecks.ts\"\nimport { computeRendersWithMotion } from \"./computeRendersWithMotion.ts\"\nimport { difference } from \"./difference.ts\"\nimport { createCodeOverrides, getValidOverrideImportSpecifiers } from \"./getValidOverrideImportSpecifiers.ts\"\nimport type { PropsForNode } from \"./propsForNode.ts\"\nimport { propsForNode } from \"./propsForNode.ts\"\nimport { serializesToSameValue } from \"./serializesToSameValue.ts\"\nimport { styleForNode } from \"./styleForNode.ts\"\nimport type { AncestorInfo, JSXContext, ProcessedVariantsFlags } from \"./types.ts\"\nimport { VariableInstance } from \"./types.ts\"\nimport { getReplicaNode, upgradeStyleForMotionVariants } from \"./utils.ts\"\n\ntype OrderMap = Map<NodeID, number>\n\n/**\n * Content on a web page is wrapped in a display:contents div, which means `order` on the slot itself won't have an\n * effect, plus any nested `order`s on the content children will leak. For example, if you have a layout template:\n *  Desktop             Mobile\n * [Slot   ]           [B    0 ]\n * [A      ]           [A    1 ]\n * [B      ]           [Slot 2 ]\n *\n * And a web page like this:\n *  Desktop             Mobile\n * [C      ]           [D    0 ]\n * [D      ]           [C    1 ]\n *\n * When the layout template is applied, both the orders in the layout template and the orders on the content descendants\n * will be mixed together because of the lack of boundaries (display: contents simply let orders fall through):\n *  Desktop             Mobile\n * [C      ]           [B    0 ]\n * [D      ]           [D    0 ]\n * [A      ]           [A    1 ]  <- unexepcted, should never get in-between the content\n * [B      ]           [C    1 ]\n *\n * Which is not expected. Therefore, when generating orders for breakpoint descendants in a layout template, we\n * subtract anything before the slot by 1000, and increase anything after the slot by 1000, so that they never\n * get mixed with the content descendant orders, while maintaining their relative order within siblings:\n *  Desktop             Mobile\n * [C      ]           [B -1000]\n * [D      ]           [A -999 ]\n * [A      ]           [D    0 ]\n * [B      ]           [C    1 ]\n *\n * Note that we need to do this even if the layout template has no order overrides. Because as soon as the web\n * page starts using order overrides, we need to make sure that elements beneath the slot (e.g. a footer) stays below\n * whatever content comes in-between. We also always do this for elements before the slot because we fall back order\n * if an order map is present *and* the element is not in the order map, if the elements before the slot were not present\n * in the map then they would receive an incorrect fallback order.\n */\nfunction createOrderMapForLayoutTemplateBreakpoint(node: CanvasNode & WithItemsOrder): OrderMap | undefined {\n\tconst slot = node.children?.find(child => isSlotNode(child))\n\tif (!slot) return\n\n\tconst slotIndex = node.itemsOrder ? node.itemsOrder.indexOf(slot.getPrimaryId()) : node.children?.indexOf(slot)\n\n\tif (!isNumber(slotIndex) || slotIndex < 0) return\n\t// If the slot is the last child and there are no order overrides, we don't need an order map.\n\tif (!node.itemsOrder && node.children && slotIndex === node.children.length - 1) return\n\n\t// If the layout template breakpoint doesn't have any itemsOrder override, we just need to make sure anything after\n\t// the slot has a large order.\n\tconst map: OrderMap = new Map()\n\tif (node.itemsOrder) {\n\t\tnode.itemsOrder.forEach((id, index) => {\n\t\t\t// itemsOrder stores only original IDs.\n\t\t\tif (id === slot.originalid) return\n\t\t\tconst delta = index < slotIndex ? -1000 : 1000\n\t\t\tmap.set(id, index + delta)\n\t\t})\n\t} else {\n\t\tnode.children?.forEach((child, index) => {\n\t\t\tif (child === slot) return\n\t\t\tconst delta = index < slotIndex ? -1000 : 1000\n\t\t\tmap.set(child.getPrimaryId(), index + delta)\n\t\t})\n\t}\n\treturn map\n}\n\nfunction createOrderMapIfOverridden(node: CanvasNode & WithItemsOrder, scopeType: ScopeType): OrderMap | undefined {\n\tif (scopeType === ScopeType.LayoutTemplate && isBreakpointVariant(node)) {\n\t\treturn createOrderMapForLayoutTemplateBreakpoint(node)\n\t}\n\n\tconst itemsOrder = node.itemsOrder\n\tif (!itemsOrder || itemsOrder.length < 1) return undefined\n\n\tconst map = new Map()\n\titemsOrder.forEach((id, index) => {\n\t\tmap.set(id, index)\n\t})\n\n\treturn map\n}\n\n/**\n * Create a partially applied function with the id of the variant that a gesture\n * variant inherits from. When calling the returned function, if the variant is\n * not a gesture variant, and does not inherit additional props, simply return\n * the primary props, otherwise combine the props that the gesture variant\n * inherits from, on top of the props from the primary variant.\n */\nconst makeCreateComparison =\n\t(topLevelVariantIdForGesture?: NodeID) =>\n\t(primaryProps: SerializableRecord | undefined, variantOverrides?: Record<NodeID, SerializableRecord | undefined>) => {\n\t\tif (!variantOverrides || !topLevelVariantIdForGesture) return primaryProps\n\t\treturn { ...primaryProps, ...variantOverrides[topLevelVariantIdForGesture] }\n\t}\n\nexport interface JSXElementProps {\n\tprops?: SerializableObject\n\toverrides?: Record<NodeID, SerializableRecord>\n}\n\nexport interface PrimaryJSXElementProps extends JSXElementProps {\n\tprops: SerializableObject\n}\n\nexport interface ProcessedVariantProps {\n\treadonly propsForElement: PrimaryJSXElementProps\n\treadonly propsForContainer: JSXElementProps\n\treadonly propsForLink: JSXElementProps\n\treadonly propsForTransition: JSXElementProps\n\treadonly propsForFetcher: JSXElementProps\n\treadonly propsForFloating: JSXElementProps\n\treadonly propsForOverlay: JSXElementProps\n\treadonly propsForComponentViewport: JSXElementProps\n\treadonly propsForTickerItem: JSXElementProps\n\treadonly renderCondition: SafeJS | boolean\n}\n\ntype VariantOverrides = Record<keyof PropsForNode, Record<NodeID, SerializableRecord> | undefined>\n\ninterface VariantStyle {\n\tvariants: Record<NodeID, SerializableRecord | undefined> | undefined\n\tcss: Record<NodeID, SerializableRecord | undefined> | undefined\n}\n\nconst logger = getLogger(\"jsxAttributesForNode\")\n\nexport function jsxAttributesForNode(\n\tnodeInPrimary: CanvasNode,\n\tparent: CanvasNode | null,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n): (ProcessedVariantsFlags & ProcessedVariantProps) | undefined {\n\tif (nodeInPrimary.parentid === ctx.scopeId && !isNodeCacheUpdated(nodeInPrimary)) {\n\t\t// Log potential generations with outdated cache\n\t\t// - https://framer-team.slack.com/archives/CJKJM8A4T/p1777568576297689\n\t\t// - https://framer-team.slack.com/archives/C064S2N6MJM/p1776182017818749\n\t\tlogOutdatedCacheError(logger, nodeInPrimary, ctx)\n\t}\n\n\tconst { combinedVariableControlMap } = nodeInPrimary.combineVariableControlMap(\n\t\tctx.tree,\n\t\tundefined,\n\t\tancestorInfo.inheritedControlMap,\n\t\tctx.componentLoader,\n\t\tctx.componentLoader.activeBundleHash,\n\t)\n\n\tif (parent) {\n\t\t/**\n\t\t * @FIXME - We need to make sure the cache is up to date because we rely on\n\t\t * it for calculating layout. We should instead just provide the parent to\n\t\t * our layout generation.\n\t\t */\n\t\tupdateStackAndGridChildCacheForCodeGeneration(parent, nodeInPrimary)\n\t\tupdateRepeaterAncestorCache(parent, nodeInPrimary)\n\t}\n\n\tconst isAnyVariantPaginated = hasPaginationEnabled(nodeInPrimary)\n\tlet subqueries = ancestorInfo.subqueries\n\t// FIXME: We shouldn't need to check isDataRepeater and hasDataSource here. This will be\n\t//        resolved by https://github.com/framer/company/issues/31161\n\tif (isDataRepeater(nodeInPrimary) && hasCollectionDataSource(nodeInPrimary)) {\n\t\tsubqueries = new SubqueryCollector(\n\t\t\tnodeInPrimary,\n\t\t\t// We don't inline subqueries if they are paginated because\n\t\t\t// the pagination state is not available in the parent query.\n\t\t\t// For example, if we have three nested queries: A, B, C.\n\t\t\t// - If A is paginated, then B can be inlined into A, and C\n\t\t\t//   can be inline into B.\n\t\t\t// - If B is paginated, then B can't be inlined into A, but C\n\t\t\t//   can be inlined into B.\n\t\t\t// - If C is paginated, then B can inlined into A, but C can't\n\t\t\t//   be inlined into B.\n\t\t\tisAnyVariantPaginated ? undefined : ancestorInfo.subqueries,\n\t\t)\n\t} else if (hasDataRepeaterArray(nodeInPrimary)) {\n\t\t// An array repeater doesn't query the CMS so it can't have subqueries.\n\t\tsubqueries = undefined\n\t}\n\n\t// Step 1 - Collect flags: walk over variants and capture the\n\t// lowest-common-denominator requirements for this node.\n\tconst isWebPage = ctx.scopeType === ScopeType.WebPage\n\tconst isSmartComponent = ctx.scopeType === ScopeType.SmartComponent\n\tconst inCodeOverride =\n\t\tancestorInfo.inCodeOverride ||\n\t\t// This returns an object when the current node has code overrides\n\t\t!isUndefined(getValidOverrideImportSpecifiers(nodeInPrimary, ctx)) ||\n\t\tcreateCodeOverrides(nodeInPrimary, ctx).length > 0\n\tconst repeaterNode = ctx.tree.get(ancestorInfo.lastRepeaterId)\n\n\t// Collect kit sections structure from the primary node\n\tconst kitSectionNodeId = ctx.kitSectionsStructure.addSection(nodeInPrimary)\n\n\tconst flags: ProcessedVariantsFlags = {\n\t\tisAnyVariantAnImage: hasImageFill(nodeInPrimary),\n\t\tisAnyVariantALink: hasLink(nodeInPrimary) && !isAnyTextNode(nodeInPrimary),\n\t\tisAnyVariantAnEffect: hasAnyHOCEffect(nodeInPrimary, ctx.scopeType),\n\t\tisAnyVariantAVariantAppearEffect: hasVariantAppearEffect(nodeInPrimary),\n\t\tisAnyVariantATickerEffect: hasTickerEffect(nodeInPrimary),\n\t\tisAnyVariantATickerItem: isNodeTickerItem(nodeInPrimary),\n\t\tisAnyVariantARef:\n\t\t\t(isWebPage && hasScrollTarget(nodeInPrimary)) ||\n\t\t\thasFloatingPosition(nodeInPrimary) ||\n\t\t\t(isCodeComponentNode(nodeInPrimary) &&\n\t\t\t\tisDataRepeater(repeaterNode) &&\n\t\t\t\tisRepeaterLoaderInstance(nodeInPrimary, repeaterNode)),\n\t\tisAnyVariantATransitionOverride:\n\t\t\tisSmartComponent && (hasTransition(nodeInPrimary) || hasVariantTransition(nodeInPrimary)),\n\t\tisAnyVariantOptimizedAppearEffect: hasOptimizedAppearEffect(nodeInPrimary, ctx),\n\t\titemsOrderOverrides: {},\n\t\thiddenInVariants: new Set<string>(ancestorInfo.hiddenInVariants),\n\t\tinCodeOverride,\n\t\tinheritedControlMap: combinedVariableControlMap,\n\t\tisAnyVariantFloating: hasFloatingPosition(nodeInPrimary),\n\t\tisAnyVariantPaginated,\n\t\tisAnyVariantColumnMasonryLayout: hasColumnMasonryLayout(nodeInPrimary),\n\t\tidentifiers: isCodeComponentNode(nodeInPrimary) ? new Set([identifierForNode(nodeInPrimary)]) : undefined,\n\t\tsubqueries,\n\t\tkitSectionNodeId,\n\t}\n\n\t// Collect tracking IDs from the primary node\n\tctx.trackingIds.add(nodeInPrimary)\n\n\t// Add customizations to the ancestor's kit section.\n\tctx.kitSectionsStructure.addCustomizations(nodeInPrimary, ancestorInfo.kitSectionNodeId)\n\n\tif (isFormContainer(nodeInPrimary)) ctx.formIds.add(nodeInPrimary.id)\n\tif (hasTriggerActions(nodeInPrimary)) ctx.triggerActions.collectTriggerActionsForNode(nodeInPrimary)\n\n\t// Always try to generate orders for elements in a layout template, see createOrderMapForLayoutTemplateBreakpoint.\n\tif (\n\t\tctx.scopeType === ScopeType.LayoutTemplate &&\n\t\twithItemsOrder(nodeInPrimary) &&\n\t\tisBreakpointVariant(nodeInPrimary)\n\t) {\n\t\tflags.itemsOrderOverrides[nodeInPrimary.id] = createOrderMapIfOverridden(nodeInPrimary, ctx.scopeType)\n\t}\n\n\tconst primaryRenderCondition = getVisibility(nodeInPrimary, ctx)\n\tconst variantRenderConditions: RenderConditions = new Map()\n\tlet rendersWithMotion = computeRendersWithMotion(nodeInPrimary, ctx, ancestorInfo, inCodeOverride)\n\n\tconst visibleNodesInVariants: {\n\t\tnodeInVariant: CanvasNode\n\t\tvariant: FrameNode & IsReplica & IsVariant\n\t}[] = []\n\tlet variantGradientInfo = getGradientInfo(nodeInPrimary)\n\tfor (const variant of ctx.variants) {\n\t\tconst nodeInVariant = getReplicaNode(variant, nodeInPrimary.id, ctx.tree)\n\t\tif (!nodeInVariant) continue\n\n\t\tnodeInVariant.combineVariableControlMap(\n\t\t\tctx.tree,\n\t\t\tundefined,\n\t\t\tancestorInfo.inheritedControlMap,\n\t\t\tctx.componentLoader,\n\t\t\tctx.componentLoader.activeBundleHash,\n\t\t)\n\n\t\tconst parentInVariant = ctx.tree.getParent(nodeInVariant.id)\n\n\t\tif (flags.hiddenInVariants.has(variant.id)) continue\n\t\tif (parentInVariant) updateStackAndGridChildCacheForCodeGeneration(parentInVariant, nodeInVariant)\n\n\t\tconst variantName = getVariantName(variant)\n\t\tconst visibility = getVisibility(nodeInVariant, ctx)\n\t\tconst hasUniqueVisibility = !serializesToSameValue(\n\t\t\tvisibility,\n\t\t\tvariantRenderConditions.get(variant.replicaInfo?.inheritsFrom ?? \"\") ?? primaryRenderCondition,\n\t\t)\n\t\tif (hasUniqueVisibility) {\n\t\t\tconst isGesture = isGestureVariant(variant)\n\t\t\tvariantRenderConditions.set(variantName, { value: visibility, isGesture })\n\t\t} else if (\n\t\t\t(ctx.scopeType === ScopeType.WebPage || ctx.scopeType === ScopeType.LayoutTemplate) &&\n\t\t\tprimaryRenderCondition !== true\n\t\t) {\n\t\t\t// When generating code for web pages or layout templates, we create a css class that\n\t\t\t// conditionally hides hidden layers with display: none. To do this,\n\t\t\t// we need to know every case where a breakpoint variant is hidden,\n\t\t\t// even if it's hidden because it's hidden in the primary variant.\n\t\t\tvariantRenderConditions.set(variantName, { value: primaryRenderCondition })\n\t\t}\n\n\t\tif (visibility === false) {\n\t\t\tflags.hiddenInVariants.add(variant.id)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (hasLink(nodeInVariant) && !isAnyTextNode(nodeInVariant)) flags.isAnyVariantALink = true\n\t\tif (hasImageFill(nodeInVariant)) flags.isAnyVariantAnImage = true\n\t\tif (hasAnyHOCEffect(nodeInVariant, ctx.scopeType)) flags.isAnyVariantAnEffect = true\n\t\tif (hasVariantAppearEffect(nodeInVariant)) flags.isAnyVariantAVariantAppearEffect = true\n\t\tif (hasOptimizedAppearEffect(nodeInVariant, ctx)) flags.isAnyVariantOptimizedAppearEffect = true\n\t\tif (hasTickerEffect(nodeInVariant)) flags.isAnyVariantATickerEffect = true\n\t\tif (isNodeTickerItem(nodeInVariant)) flags.isAnyVariantATickerItem = true\n\t\tif (hasPaginationEnabled(nodeInVariant)) flags.isAnyVariantPaginated = true\n\t\tif (isCodeComponentNode(nodeInVariant)) flags.identifiers?.add(identifierForNode(nodeInVariant))\n\t\tif (hasColumnMasonryLayout(nodeInVariant)) flags.isAnyVariantColumnMasonryLayout = true\n\n\t\t// Collect tracking IDs from the variant node\n\t\tctx.trackingIds.add(nodeInVariant)\n\n\t\tconst gradientInfo = getGradientInfo(nodeInVariant)\n\t\tif (gradientInfo) {\n\t\t\tvariantGradientInfo ||= gradientInfo\n\t\t\tconst { stops, info } = gradientInfo\n\t\t\tvariantGradientInfo.stops = Math.max(variantGradientInfo?.stops, stops ?? 0)\n\t\t\tvariantGradientInfo.info ||= info\n\t\t}\n\n\t\tif (ctx.scopeType === ScopeType.WebPage) {\n\t\t\tif (hasScrollTarget(nodeInVariant)) flags.isAnyVariantARef = true\n\t\t} else if (ctx.scopeType === ScopeType.SmartComponent) {\n\t\t\tif (hasSmartComponentPresenceEffect(nodeInVariant)) flags.isAnyVariantAnEffect = true\n\t\t\tif (hasTransition(nodeInVariant) || hasVariantTransition(nodeInVariant)) {\n\t\t\t\tflags.isAnyVariantATransitionOverride = true\n\t\t\t}\n\t\t}\n\n\t\tif (hasItemsOrderOverride(nodeInVariant)) {\n\t\t\tflags.itemsOrderOverrides[variant.id] = createOrderMapIfOverridden(nodeInVariant, ctx.scopeType)\n\t\t}\n\n\t\t// If any variant must render with Motion, *all* variants must. That\u2019s\n\t\t// because we can\u2019t transition between `motion.div` in one variant and\n\t\t// `div` in another\n\t\trendersWithMotion = rendersWithMotion || computeRendersWithMotion(nodeInVariant, ctx, ancestorInfo, inCodeOverride)\n\n\t\tvisibleNodesInVariants.push({ nodeInVariant, variant })\n\t}\n\n\tif (!isUndefined(variantGradientInfo)) {\n\t\tctx.nodesWithAnyGradientFill.set(nodeInPrimary.id, variantGradientInfo)\n\t}\n\n\tconst {\n\t\tcondition: finalRenderCondition,\n\t\tclassNames: conditionalRenderingClassNames,\n\t\tclassNameExpressions: conditionalRenderingClassNameExpressions,\n\t} = ctx.renderFunctions.create(primaryRenderCondition, variantRenderConditions)\n\n\t// If none of the variants are visible we do not need to render it or its descendants.\n\tif (finalRenderCondition === false) return\n\n\tctx.nodeRendersWithMotion.set(nodeInPrimary, rendersWithMotion)\n\n\t// Add the node to ctx.renderAsListNodes if it is a list prior to collecting styles which depend on\n\t// checking ctx.renderAsListNodes\n\t// ctx.renderAsListNodes is a Map<NodeID, true> that contains all nodes that should be rendered as <ul>.\n\tconst parentIsList = nodeInPrimary.parentid ? ctx.renderAsListNodes.get(nodeInPrimary.parentid) : false\n\t// The node should not be added to the map if its parent is already in the map so we avoid\n\t// rendering non semantic markup (e.g ul > ul).\n\tconst nodeIsList = withHTMLTag(nodeInPrimary) && isListTag(nodeInPrimary.htmlTag) && !parentIsList\n\tif (nodeIsList) ctx.renderAsListNodes.set(nodeInPrimary.id, true)\n\tif (flags.isAnyVariantAnImage) ctx.nodesRenderedAsImageInAnyVariant.add(nodeInPrimary.getPrimaryId())\n\n\t// Step 2: collect styles and props: knowing flags (= which features this\n\t// node must support across all variants), collect styles and props in a way\n\t// that supports all features.\n\tconst omitOrder = parent && hasColumnMasonryLayout(parent)\n\tconst orders = ancestorInfo?.itemsOrderOverrides?.[ctx.rootId]\n\tconst { css, style } = styleForNode(\n\t\tnodeInPrimary,\n\t\tparent,\n\t\tctx,\n\t\t!omitOrder && orders ? { order: orderOverrideForNode(nodeInPrimary, orders) } : undefined,\n\t)\n\n\tconst needsContainer = nodeNeedsContainer(nodeInPrimary)\n\tconst hasScopingSelector = nodeHasSerializationHashClassName(nodeInPrimary, parent, ctx)\n\tconst className = ctx.css.addRule(css, nodeInPrimary, {\n\t\tcontainer: needsContainer,\n\t\thasScopingSelector,\n\t})\n\n\tconst props = propsForNode(nodeInPrimary, ctx, flags, ancestorInfo, { className, style })\n\tctx.hitTargets.recordClassName(nodeInPrimary, ctx.rootId, className)\n\n\tconst overrides: VariantOverrides = {\n\t\tlink: undefined,\n\t\tcontainer: undefined,\n\t\telement: undefined,\n\t\tfloating: undefined,\n\t\toverlay: undefined,\n\t\ttransition: undefined,\n\t\tfetcher: undefined,\n\t\tcomponentViewport: undefined,\n\t\ttickerItem: undefined,\n\t}\n\n\tconst variantStyle: VariantStyle = {\n\t\tvariants: undefined,\n\t\tcss: undefined,\n\t}\n\n\tif (isRichTextNode(nodeInPrimary)) {\n\t\tfor (const preset of nodeInPrimary.getStylePresetsForCodeGeneration(ctx.tree)) {\n\t\t\tctx.css.addSharedStyle(preset.id)\n\t\t}\n\t}\n\n\tconst target = needsContainer ? props.container : props.element\n\tassert(!isUndefined(target), \"Target will always be defined if the node needs a container\")\n\n\tfor (const { nodeInVariant, variant } of visibleNodesInVariants) {\n\t\tconst variantName = getVariantName(variant)\n\t\tctx.hitTargets.recordClassName(nodeInVariant, variant.id, className)\n\n\t\tif (isRichTextNode(nodeInVariant)) {\n\t\t\tfor (const preset of nodeInVariant.getStylePresetsForCodeGeneration(ctx.tree)) {\n\t\t\t\tctx.css.addSharedStyle(preset.id)\n\t\t\t}\n\t\t}\n\n\t\tconst parentInVariant = ctx.tree.getParent(nodeInVariant.id)\n\t\tconst { itemsOrderOverrides } = ancestorInfo\n\t\tconst orderOverride = itemsOrderOverrides?.[variant.id]\n\t\tconst omitOrder = parentInVariant && hasColumnMasonryLayout(parentInVariant)\n\t\tconst styleForVariant = styleForNode(\n\t\t\tnodeInVariant,\n\t\t\tparentInVariant,\n\t\t\tctx,\n\t\t\t!omitOrder && orderOverride ? { order: orderOverrideForNode(nodeInPrimary, orderOverride) } : undefined,\n\t\t)\n\n\t\tconst createComparison = makeCreateComparison(variant.replicaInfo?.inheritsFrom)\n\n\t\tconst defaultCSSValues = {\n\t\t\t// When properties get removed in variants, the collected styles should get set to `undefined`\n\t\t\t// and normally converted to `unset` by the difference function. However, some node types have different\n\t\t\t// default values. This object defines those values.\n\t\t\t//\n\t\t\t// For example, if any of the variants is a link, the node will be rendered as a\n\t\t\t// motion.a tag. By default, it will receive `display: block` from a\n\t\t\t// class for all links, this ensures that it renders correctly on\n\t\t\t// the canvas. However, if a replica variant removes flex or grid\n\t\t\t// `display` from the primary, `display: undefined` should not be\n\t\t\t// set as `display: unset`, see:\n\t\t\t// https://github.com/framer/company/issues/26106.\n\t\t\t// Instead we specifically handle this case by defaulting to\n\t\t\t// `block`, since \"block\" is the default browser value for all other\n\t\t\t// elements in Framer.\n\n\t\t\t// On the other hand, text truncation sets `display: -webkit-box`, but when removing it in a variant,\n\t\t\t// we should restore display to the RichTextNode's default value, not `unset`.\n\t\t\t// See: https://github.com/framer/company/issues/35158\n\t\t\t//\n\t\t\t// We should consider generalizing this specific solution if it becomes a common pattern.\n\t\t\tdisplay: isRichTextNode(nodeInVariant) ? defaultRichTextContainerStyle.display : \"block\",\n\t\t}\n\n\t\tconst cssRulesForVariant = difference<SerializableMotionStyle>(\n\t\t\tstyleForVariant.css,\n\t\t\tcreateComparison(css, variantStyle.css) as SerializableMotionStyle,\n\t\t\t\"css\",\n\t\t\tdefaultCSSValues,\n\t\t)\n\t\tif (cssRulesForVariant) {\n\t\t\tconst isGesture = isGestureVariant(variant)\n\n\t\t\tif (!variantStyle.css) variantStyle.css = {}\n\t\t\t// Usage of `variant.id` instead of `variantName` here is intentional: https://github.com/framer/FramerStudio/pull/14427#discussion_r1247725856\n\t\t\tvariantStyle.css[variant.id] = cssRulesForVariant\n\t\t\tctx.css.addRule(cssRulesForVariant, nodeInVariant, {\n\t\t\t\tvariant,\n\t\t\t\thasScopingSelector,\n\t\t\t\tcontainer: needsContainer,\n\t\t\t\tgesture: isGesture ? variant.gesture : undefined,\n\t\t\t\tscope: isGesture\n\t\t\t\t\t? variant.replicaInfo?.inheritsFrom\n\t\t\t\t\t: ctx.scopeType === ScopeType.SmartComponent\n\t\t\t\t\t\t? variant.id\n\t\t\t\t\t\t: undefined,\n\t\t\t})\n\t\t}\n\n\t\t// Before diffing props (including style), if we are in a smart\n\t\t// component, we need to upgrade the style for motion variants so that\n\t\t// we know to animate from opacity: 1 (default) to some non default\n\t\t// value.\n\t\tif (ctx.scopeType === ScopeType.SmartComponent) {\n\t\t\tupgradeStyleForMotionVariants(ctx.componentLoader, nodeInVariant, target, styleForVariant.style)\n\t\t}\n\n\t\t// Provide the same initial props as the primary variant to ensure that\n\t\t// classNames and inline style are the same so no unintentional diffs\n\t\t// are created.\n\t\tconst variantProps = propsForNode(nodeInVariant, ctx, flags, ancestorInfo, {\n\t\t\tclassName,\n\t\t\t// We use `target.style` here because it may have been upgraded for\n\t\t\t// motion variants. We need to use the same value so that the diff\n\t\t\t// is accurate.\n\t\t\tstyle: target.style,\n\t\t})\n\n\t\tconst inlineStyleForVariant = difference<SerializableMotionStyle>(\n\t\t\tstyleForVariant.style,\n\t\t\tcreateComparison(style, variantStyle.variants) as SerializableMotionStyle,\n\t\t)\n\t\tif (inlineStyleForVariant) {\n\t\t\tif (ctx.scopeType === ScopeType.SmartComponent || ctx.llmSnapshot) {\n\t\t\t\tif (!variantStyle.variants) variantStyle.variants = {}\n\t\t\t\tvariantStyle.variants[variantName] = inlineStyleForVariant\n\t\t\t} else {\n\t\t\t\t// If we are not in a smart component, we don't use\n\t\t\t\t// motion-variants. However, for transforms (like rotation), we\n\t\t\t\t// need to use motion style to ensure that descendants can\n\t\t\t\t// perform layout animations accurately. So when we know we have\n\t\t\t\t// inline styles outside of a smart component (because there is\n\t\t\t\t// a diff), we must add all of the style as an override.\n\t\t\t\tconst key: keyof PropsForNode = needsContainer ? \"container\" : \"element\"\n\t\t\t\toverrides[key] = updateStyle(styleForVariant.style, overrides[key], variantName)\n\t\t\t}\n\t\t}\n\n\t\tfor (const element in variantProps) {\n\t\t\tconst elementKey = element as keyof PropsForNode\n\t\t\tconst diff = difference(\n\t\t\t\tvariantProps[elementKey],\n\t\t\t\tcreateComparison(props[elementKey], overrides[elementKey] ?? {}),\n\t\t\t\t\"js\",\n\t\t\t)\n\t\t\tif (!diff) continue\n\t\t\tif (!overrides[elementKey]) overrides[elementKey] = { [variantName]: {} }\n\t\t\t// There may already be some overrides for this variant if we inlined style. Be sure to\n\t\t\t// merge them.\n\t\t\tconst value = overrides[elementKey][variantName]\n\t\t\toverrides[elementKey][variantName] = isObject(value) ? Object.assign(value, diff) : diff\n\t\t}\n\t}\n\n\tconst additionalClassNames = new Set(conditionalRenderingClassNames)\n\tif (flags.isAnyVariantALink) additionalClassNames.add(ctx.linkClassName)\n\n\tconst additionalClassNameExpressions = new SafeJS.Set(conditionalRenderingClassNameExpressions)\n\n\tconst requiresRef = flags.isAnyVariantARef || ctx.overlays.relativeOverlayTriggerIds.has(nodeInPrimary.id)\n\n\tSerializableObject.assign(target, {\n\t\tvariants: variantStyle.variants,\n\t\tclassName: appendRenderingClassNames(\n\t\t\ttarget.className,\n\t\t\tadditionalClassNames,\n\t\t\tadditionalClassNameExpressions,\n\t\t\tctx.imports,\n\t\t),\n\t\t// Refs can be added in any variant but must be present across all\n\t\t// variants to ensure FX don't break.\n\t\tref: target.ref ?? (requiresRef ? ctx.elementIds.ref(nodeInPrimary) : target.ref),\n\t\t[framerAppearIdKey]: flags.isAnyVariantOptimizedAppearEffect ? ctx.appearIds.create(nodeInPrimary.id) : undefined,\n\t})\n\n\tctx.renderConditions.set(nodeInPrimary.id, finalRenderCondition)\n\n\treturn {\n\t\t...flags,\n\t\tpropsForLink: {\n\t\t\tprops: props.link,\n\t\t\toverrides: overrides.link,\n\t\t},\n\t\tpropsForElement: {\n\t\t\tprops: props.element,\n\t\t\toverrides: overrides.element,\n\t\t},\n\t\tpropsForContainer: {\n\t\t\tprops: props.container,\n\t\t\toverrides: overrides.container,\n\t\t},\n\t\tpropsForTransition: {\n\t\t\tprops: props.transition,\n\t\t\toverrides: overrides.transition,\n\t\t},\n\t\tpropsForFetcher: {\n\t\t\tprops: props.fetcher,\n\t\t\toverrides: overrides.fetcher,\n\t\t},\n\t\trenderCondition: finalRenderCondition,\n\t\tpropsForFloating: {\n\t\t\tprops: props.floating,\n\t\t\toverrides: overrides.floating,\n\t\t},\n\t\tpropsForOverlay: {\n\t\t\tprops: props.overlay,\n\t\t\toverrides: overrides.overlay,\n\t\t},\n\t\tpropsForComponentViewport: {\n\t\t\tprops: props.componentViewport,\n\t\t\toverrides: overrides.componentViewport,\n\t\t},\n\t\tpropsForTickerItem: {\n\t\t\tprops: props.tickerItem,\n\t\t\toverrides: overrides.tickerItem,\n\t\t},\n\t}\n}\n\nfunction appendRenderingClassNames(\n\tcurrentClassName: SerializableValue | undefined,\n\tclassNames: Set<string>,\n\tclassNameExpressions: SafeJS.Set,\n\timports: ImportCollector,\n): SerializableValue | undefined {\n\t// Short-circuit the most common scenario.\n\tif (classNames.size === 0 && classNameExpressions.size === 0) {\n\t\treturn currentClassName\n\t}\n\n\tif (classNameExpressions.size === 0) {\n\t\tconst classNameString = Array.from(classNames).join(\" \")\n\t\tif (currentClassName) {\n\t\t\t// XXX: This could end up being `class=\" second third\" if `currentClassName` is a `cx` expression that\n\t\t\t// evaluates to an empty string. But in practice, unlike below, our \"primary\" `cx` expressions always seem\n\t\t\t// to have at least one static string, so this should be fine. And of course *if* this happens, it doesn't\n\t\t\t// break anything, just looks weird.\n\t\t\treturn jst`${currentClassName} ${classNameString}`\n\t\t} else {\n\t\t\treturn classNameString\n\t\t}\n\t} else {\n\t\t// The primary use case for SafeJS class names is `condition && \"class-name\"`, so we wrap everything in `cx`.\n\t\t//\n\t\t// We wrap *everything* in `cx` to avoid e.g. `class=\"primary \"` in case all \"additional\" class names are\n\t\t// conditional expressions and end up falsy.\n\t\t//\n\t\t// Note that the `currentClassName` might already be a `cx` expression, so we might end up with a nested one.\n\t\tconst cx = imports.addImport(\"framer\", { exportSpecifier: \"cx\" })\n\t\tif (currentClassName) {\n\t\t\treturn SafeJS.fn(cx, currentClassName, ...classNames, ...classNameExpressions)\n\t\t} else {\n\t\t\treturn SafeJS.fn(cx, ...classNames, ...classNameExpressions)\n\t\t}\n\t}\n}\n\nfunction updateRepeaterAncestorCache(parent: CanvasNode, child: CanvasNode) {\n\tchild.cache.ancestorRepeaterIds = nextDescendantRepeaterIds(parent, parent.cache.ancestorRepeaterIds ?? [])\n}\n\nfunction getVariantName(variant: CanvasNode): string {\n\t// Smart component gesture variants do not use the variant.id, but use a\n\t// special named version of the top-level variant. This aids in runtime\n\t// logic. This means we must build our objects against these keys.\n\tconst isGesture = isGestureVariant(variant)\n\treturn isGesture ? `${variant.replicaInfo.inheritsFrom}-${variant.gesture}` : variant.id\n}\n\nfunction updateStyle<T extends Record<string, { style?: object }>>(\n\tstyle: unknown,\n\toverrides: T | undefined,\n\tvariantName: keyof T,\n): T | undefined {\n\tconst target: T = overrides ?? ({} as T)\n\ttarget[variantName] = target[variantName] ?? ({} as T[keyof T])\n\ttarget[variantName].style = target[variantName].style ?? {}\n\tObject.assign(target[variantName].style, style)\n\treturn target\n}\n\n/**\n * Layout Templates add SlotNode's as {children}. The contents of the {children}\n * slot are rendered inside a display: contents element. To ensure that the slot\n * is never smaller than the screen, we add a spacer div that pushes the content\n * below the slot down to fill the entire screen.\n */\nexport function classNameForSlotSpacer(node: SlotNode, parent: CanvasNode, ctx: JSXContext) {\n\tconst style: SerializableMotionStyle = {\n\t\tbackground: \"transparent\",\n\t\theight: 0,\n\t\twidth: 0,\n\t\tposition: \"relative\",\n\t\tflexGrow: 1,\n\t\tmargin: 0,\n\t\tmarginBottom: coerceToNegativeColumnGap(parent, ctx),\n\t}\n\n\tfor (const variant of ctx.variants) {\n\t\tconst nodeInVariant = getReplicaNode(variant, node.id, ctx.tree)\n\t\tif (!nodeInVariant) continue\n\n\t\tconst diff = difference<SerializableMotionStyle>(\n\t\t\t{\n\t\t\t\t...style,\n\t\t\t\tmarginBottom: coerceToNegativeColumnGap(variant, ctx),\n\t\t\t},\n\t\t\tstyle,\n\t\t)\n\t\tif (!diff || isEmptyObject(diff)) continue\n\t\tctx.css.addRule(diff, nodeInVariant, { variant })\n\t}\n\n\treturn ctx.css.addRule(style, node)\n}\n\nfunction identifierForNode(node: CodeComponentNode): string | typeof VariableInstance {\n\tif (isDynamicVectorInstance(node)) return VariableInstance\n\treturn node.codeComponentIdentifier\n}\n\nfunction orderOverrideForNode(node: CanvasNode, orderOverrides: OrderMap): number {\n\t// Order is an integer >= 0 and if ordered every node should have an order present\n\t// however in some unexpected cases the an order is not present for one or more children.\n\t// To keep the rendered order consistent between canvas and preview/publish we have to\n\t// push all unordered children to the end. If we don't do this then they would take the\n\t// default of 0 and the browser would order them first.\n\treturn orderOverrides.get(node.id) ?? orderOverrides.size\n}\n\nfunction isNodeCacheUpdated(node: CanvasNode): boolean {\n\treturn node.update === node.cache.lastUpdate\n}\n", "import type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { CollectorEntryNode } from \"code-generation/types.ts\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { getVariantForNode } from \"document/models/CanvasTree/nodes/utils/breakpointHelpers.ts\"\nimport type { AssetCollector } from \"../utils/AssetCollector.ts\"\nimport type { BindingCollector } from \"../utils/BindingCollector.ts\"\nimport type { FileDeclarationCollector } from \"../utils/DeclarationCollector.ts\"\nimport type { ImportCollector } from \"../utils/ImportCollector.ts\"\nimport type { VariableCollector } from \"../utils/VariableCollector.ts\"\n\ntype PreloadCommand = \"query\" | \"fetch\"\n\nexport class PreloadCollectorContext {\n\t#cmdBindings = new Map<PreloadCommand, SafeJS>()\n\n\tconstructor(\n\t\treadonly entryNode: CollectorEntryNode,\n\t\treadonly tree: CanvasTree,\n\t\treadonly variables: VariableCollector,\n\t\treadonly declarations: FileDeclarationCollector,\n\t\treadonly bindings: BindingCollector,\n\t\treadonly imports: ImportCollector,\n\t\treadonly assets: AssetCollector,\n\t) {}\n\n\t/**\n\t * Since the functions to preload some content are deduplicated into the\n\t * module file, the hook value that allows making the query must be injected\n\t * from the component function. For simplicity, we reuse these bindings\n\t * everywhere except where they are injected.\n\t */\n\tcommand(type: PreloadCommand): SafeJS {\n\t\tconst existingBinding = this.#cmdBindings.get(type)\n\t\tif (existingBinding) return existingBinding\n\t\tconst binding = this.bindings.create(`pre${type}`)\n\t\tthis.#cmdBindings.set(type, binding)\n\t\treturn binding\n\t}\n\n\t/**\n\t * Helper for code-generation that needs the variant ground node id.\n\t */\n\tgetVariantIdFor(node: CanvasNode) {\n\t\treturn getVariantForNode(this.tree, node.id, true)?.id\n\t}\n}\n", "import type { VariableDefinition, WithQueryParam } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { slugify } from \"library/utils/slugify.ts\"\n\nexport function getQueryParamNameOfVariable(variable: VariableDefinition & WithQueryParam) {\n\treturn variable.queryParam || generateQueryParamNameForVariableName(variable.name)\n}\n\nexport function generateQueryParamNameForVariableName(variableName: string) {\n\treturn slugify(variableName)\n}\n", "import { assertNever } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isArray, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport type { PreloadCollectorContext } from \"./PreloadCollectorContext.ts\"\nimport type {\n\tChildComponentInfo,\n\tLoaderCode,\n\tRouteLoaderPlan,\n\tRouteLoaderQuery,\n\tURLVariableInfo,\n} from \"./buildRouteLoaderPlan.ts\"\n\nexport class RouteLoaderSerializer {\n\tconstructor(private readonly ctx: PreloadCollectorContext) {}\n\n\tserialize(plan: RouteLoaderPlan): LoaderCode {\n\t\tconst {\n\t\t\trepeaterToQuery,\n\t\t\tindependentQueries,\n\t\t\turlOnlyQueries,\n\t\t\tdetailOnlyQueries,\n\t\t\tmixedQueries,\n\t\t\trepeaterDependentQueries,\n\t\t\tindependentChildComponents,\n\t\t\trepeaterDependentChildComponents,\n\t\t\tdetailPageQuery,\n\t\t} = plan\n\n\t\tconst hoistedCacheEntries = new Map<string, SafeJS>()\n\t\tconst hoistedCacheStatements: SafeJS[] = []\n\t\tconst localeBinding = js`locale`\n\t\thoistedCacheStatements.push(js`const ${localeBinding} = context.locale`)\n\n\t\tconst hasDetailPageQuery = !isUndefined(detailPageQuery)\n\t\tconst hasAnyQueries =\n\t\t\tindependentQueries.length > 0 ||\n\t\t\turlOnlyQueries.length > 0 ||\n\t\t\thasDetailPageQuery ||\n\t\t\tdetailOnlyQueries.length > 0 ||\n\t\t\tmixedQueries.length > 0 ||\n\t\t\trepeaterDependentQueries.length > 0\n\t\tconst hasChildComponents = independentChildComponents.length > 0 || repeaterDependentChildComponents.length > 0\n\t\tconst hasRepeaterChains = repeaterDependentQueries.length > 0 || repeaterDependentChildComponents.length > 0\n\n\t\tif (!hasAnyQueries && !hasChildComponents) return\n\n\t\tconst queryCacheBinding = this.#getQueryCacheBinding(hasAnyQueries, hasRepeaterChains)\n\t\tconst allURLVariables = this.#collectAllURLVariables(urlOnlyQueries, mixedQueries, repeaterDependentQueries)\n\t\tconst {\n\t\t\tresolutions: urlVarResolutions,\n\t\t\tbindings,\n\t\t\tbindingsById,\n\t\t\tbindingsObject: urlVarBindingsObject,\n\t\t} = this.#generateURLVariableResolutions(allURLVariables, localeBinding)\n\t\tconst urlVarsPromiseBinding = allURLVariables.size > 0 ? this.ctx.bindings.create(\"urlVarsPromise\") : undefined\n\n\t\tif (urlVarsPromiseBinding) {\n\t\t\tconst urlVarIIFE = js`(async () => {${js.joinLines(...urlVarResolutions, js`return ${urlVarBindingsObject}`)}})()`\n\t\t\thoistedCacheStatements.push(js`const ${urlVarsPromiseBinding} = ${urlVarIIFE}`)\n\t\t}\n\n\t\tconst independentCalls = this.#buildIndependentCalls(\n\t\t\tqueryCacheBinding,\n\t\t\tindependentQueries,\n\t\t\turlOnlyQueries,\n\t\t\tindependentChildComponents,\n\t\t\turlVarsPromiseBinding,\n\t\t\tbindingsById,\n\t\t\thoistedCacheEntries,\n\t\t\thoistedCacheStatements,\n\t\t\tlocaleBinding,\n\t\t)\n\n\t\tconst hasAnyDetailConsumers = hasDetailPageQuery && this.#usesDetailArguments(Array.from(repeaterToQuery.values()))\n\n\t\tif (hasDetailPageQuery && detailPageQuery?.constantBinding && queryCacheBinding) {\n\t\t\tconst getWhereBinding = this.ctx.imports.addImport(\"framer\", {\n\t\t\t\texportSpecifier: \"getWhereExpressionFromPathVariables\",\n\t\t\t})\n\n\t\t\tconst detailQueryCall = SafeJS.fn(\n\t\t\t\tdetailPageQuery.constantBinding,\n\t\t\t\tSafeJS.fn(getWhereBinding, js`context.pathVariables`, detailPageQuery.collectionAlias),\n\t\t\t)\n\t\t\tconst detailQueryCacheGet = this.#queryCacheGet(queryCacheBinding, detailQueryCall, localeBinding)\n\t\t\tconst detailResultPromiseBinding = hasAnyDetailConsumers\n\t\t\t\t? this.ctx.bindings.create(\"detailResultPromise\")\n\t\t\t\t: undefined\n\t\t\tif (detailResultPromiseBinding) {\n\t\t\t\thoistedCacheStatements.push(\n\t\t\t\t\tjs`const ${detailResultPromiseBinding} = ${SafeJS.fn(js`${detailQueryCacheGet}.readMaybeAsync`)}`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst repeaterChains = this.#generateRepeaterChains(\n\t\t\t\trepeaterToQuery,\n\t\t\t\trepeaterDependentQueries,\n\t\t\t\trepeaterDependentChildComponents,\n\t\t\t\tqueryCacheBinding,\n\t\t\t\turlVarsPromiseBinding,\n\t\t\t\tbindingsById,\n\t\t\t\tdetailResultPromiseBinding,\n\t\t\t\thoistedCacheEntries,\n\t\t\t\thoistedCacheStatements,\n\t\t\t\tlocaleBinding,\n\t\t\t)\n\n\t\t\tconst hasDetailDependentQueries = detailOnlyQueries.length > 0 || mixedQueries.length > 0\n\n\t\t\tif (hasDetailDependentQueries) {\n\t\t\t\tconst chainedCalls: SafeJS[] = []\n\n\t\t\t\tfor (const q of detailOnlyQueries) {\n\t\t\t\t\tconst args = this.#buildQueryArgs(q, {\n\t\t\t\t\t\turlVarBindingsById: bindingsById,\n\t\t\t\t\t\tdetailDataBinding: js`detailData`,\n\t\t\t\t\t\titemVarByRepeaterId: new Map(),\n\t\t\t\t\t})\n\t\t\t\t\tconst queryCall = SafeJS.fn(q.constantBinding, ...args)\n\t\t\t\t\tconst cacheGetCall = this.#queryCacheGet(queryCacheBinding, queryCall, localeBinding)\n\t\t\t\t\tchainedCalls.push(SafeJS.fn(js`${cacheGetCall}.preload`))\n\t\t\t\t}\n\n\t\t\t\tfor (const q of mixedQueries) {\n\t\t\t\t\tconst args = this.#buildQueryArgs(q, {\n\t\t\t\t\t\turlVarBindingsById: bindingsById,\n\t\t\t\t\t\tdetailDataBinding: js`detailData`,\n\t\t\t\t\t\titemVarByRepeaterId: new Map(),\n\t\t\t\t\t})\n\t\t\t\t\tconst queryCall = SafeJS.fn(q.constantBinding, ...args)\n\t\t\t\t\tconst cacheGetCall = this.#queryCacheGet(queryCacheBinding, queryCall, localeBinding)\n\t\t\t\t\tchainedCalls.push(SafeJS.fn(js`${cacheGetCall}.preload`))\n\t\t\t\t}\n\n\t\t\t\tconst firstChainedCall = chainedCalls[0]\n\t\t\t\tconst chainedCallsResult =\n\t\t\t\t\tchainedCalls.length > 1 || !firstChainedCall\n\t\t\t\t\t\t? SafeJS.fn(js`Promise.allSettled`, chainedCalls)\n\t\t\t\t\t\t: firstChainedCall\n\n\t\t\t\tconst detailChain = this.#generateParallelizedDetailChain(\n\t\t\t\t\turlVarsPromiseBinding,\n\t\t\t\t\tbindings,\n\t\t\t\t\tdetailResultPromiseBinding ?? SafeJS.fn(js`${detailQueryCacheGet}.readMaybeAsync`),\n\t\t\t\t\tchainedCallsResult,\n\t\t\t\t)\n\n\t\t\t\tindependentCalls.push(detailChain, ...repeaterChains)\n\t\t\t\treturn this.#wrapLoaderCode(hoistedCacheStatements, SafeJS.fn(js`Promise.allSettled`, independentCalls))\n\t\t\t}\n\n\t\t\t// No direct detail-dependent queries. If something else needs detail data, the promise is already hoisted.\n\t\t\tif (!detailResultPromiseBinding) {\n\t\t\t\tindependentCalls.unshift(SafeJS.fn(js`${detailQueryCacheGet}.preload`))\n\t\t\t}\n\t\t\tindependentCalls.push(...repeaterChains)\n\t\t\treturn this.#wrapLoaderCode(hoistedCacheStatements, SafeJS.fn(js`Promise.allSettled`, independentCalls))\n\t\t}\n\n\t\tconst repeaterChains = this.#generateRepeaterChains(\n\t\t\trepeaterToQuery,\n\t\t\trepeaterDependentQueries,\n\t\t\trepeaterDependentChildComponents,\n\t\t\tqueryCacheBinding,\n\t\t\turlVarsPromiseBinding,\n\t\t\tbindingsById,\n\t\t\tundefined,\n\t\t\thoistedCacheEntries,\n\t\t\thoistedCacheStatements,\n\t\t\tlocaleBinding,\n\t\t)\n\n\t\tindependentCalls.push(...repeaterChains)\n\n\t\tif (independentCalls.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\treturn this.#wrapLoaderCode(hoistedCacheStatements, SafeJS.fn(js`Promise.allSettled`, independentCalls))\n\t}\n\n\t#getQueryCacheBinding(hasAnyQueries: boolean, hasRepeaterChains: boolean): SafeJS | undefined {\n\t\treturn hasAnyQueries || hasRepeaterChains\n\t\t\t? this.ctx.imports.addImport(\"framer\", { exportSpecifier: \"queryCache\" })\n\t\t\t: undefined\n\t}\n\n\t#collectAllURLVariables(...queries: readonly RouteLoaderQuery[][]): Map<string, URLVariableInfo> {\n\t\tconst allURLVariables = new Map<string, URLVariableInfo>()\n\t\tconst allQueries = queries.flat()\n\t\tfor (const q of allQueries) {\n\t\t\tfor (const urlVar of q.urlVariables) allURLVariables.set(urlVar.id, urlVar)\n\t\t}\n\t\treturn allURLVariables\n\t}\n\n\t#buildIndependentCalls(\n\t\tqueryCacheBinding: SafeJS | undefined,\n\t\tindependentQueries: RouteLoaderQuery[],\n\t\turlOnlyQueries: RouteLoaderQuery[],\n\t\tindependentChildComponents: ChildComponentInfo[],\n\t\turlVarsPromiseBinding: SafeJS | undefined,\n\t\turlVarBindingsById: Map<string, SafeJS>,\n\t\thoistedCacheEntries: Map<string, SafeJS>,\n\t\thoistedCacheStatements: SafeJS[],\n\t\tlocaleBinding: SafeJS,\n\t): SafeJS[] {\n\t\tconst independentCalls: SafeJS[] = []\n\t\tif (queryCacheBinding) {\n\t\t\tfor (const { constantBinding } of independentQueries) {\n\t\t\t\tconst cacheEntry = this.#getQueryCacheEntryBinding(\n\t\t\t\t\tconstantBinding,\n\t\t\t\t\tqueryCacheBinding,\n\t\t\t\t\thoistedCacheEntries,\n\t\t\t\t\thoistedCacheStatements,\n\t\t\t\t\tlocaleBinding,\n\t\t\t\t)\n\t\t\t\tindependentCalls.push(SafeJS.fn(js`${cacheEntry}.preload`))\n\t\t\t}\n\n\t\t\tfor (const { constantBinding, urlVariables } of urlOnlyQueries) {\n\t\t\t\tconst args = urlVariables.map(v => urlVarBindingsById.get(v.id)).filter(Boolean)\n\t\t\t\tif (!urlVarsPromiseBinding) continue\n\t\t\t\tconst queryCall = SafeJS.fn(constantBinding, ...args)\n\t\t\t\tconst cacheGetCall = this.#queryCacheGet(queryCacheBinding, queryCall, localeBinding)\n\t\t\t\tconst preloadCall = SafeJS.fn(js`${cacheGetCall}.preload`)\n\t\t\t\tindependentCalls.push(\n\t\t\t\t\tSafeJS.fn(js`${urlVarsPromiseBinding}.then`, js`({ ${js.listFrom(args)} }) => ${preloadCall}`),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tindependentCalls.push(...this.#generateForwardLoaderCalls(independentChildComponents))\n\t\treturn independentCalls\n\t}\n\n\t#generateURLVariableResolutions(\n\t\turlVariables: Map<string, URLVariableInfo>,\n\t\tlocaleBinding: SafeJS,\n\t): {\n\t\tresolutions: SafeJS[]\n\t\tbindings: SafeJS[]\n\t\tbindingsById: Map<string, SafeJS>\n\t\tbindingsObject: Record<string, SafeJS>\n\t} {\n\t\tconst resolutions: SafeJS[] = []\n\t\tconst bindings: SafeJS[] = []\n\t\tconst bindingsById = new Map<string, SafeJS>()\n\n\t\tfor (const [id, urlVar] of urlVariables) {\n\t\t\tconst binding = this.ctx.bindings.create(id)\n\t\t\tbindings.push(binding)\n\t\t\tbindingsById.set(id, binding)\n\n\t\t\tswitch (urlVar.type) {\n\t\t\t\tcase ControlType.String: {\n\t\t\t\t\tconst defaultValue = isString(urlVar.initialValue) ? urlVar.initialValue : js`undefined`\n\t\t\t\t\tresolutions.push(js`const ${binding} = context.pathVariables?.[${urlVar.parameterName}] ?? ${defaultValue}`)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase ControlType.CollectionReference: {\n\t\t\t\t\tconst defaultValue = isString(urlVar.initialValue) ? urlVar.initialValue : js`undefined`\n\t\t\t\t\tresolutions.push(\n\t\t\t\t\t\tjs`const ${binding} = await (async () => {${js.joinLines(\n\t\t\t\t\t\t\tjs`const slug = context.pathVariables?.[${urlVar.parameterName}] ?? \"\"`,\n\t\t\t\t\t\t\tjs`if (!slug) return ${defaultValue}`,\n\t\t\t\t\t\t\tjs`const cache = ${SafeJS.fn(js`context.collectionUtils?.get`, urlVar.collectionId ?? \"\")}`,\n\t\t\t\t\t\t\tjs`if (!cache) return ${defaultValue}`,\n\t\t\t\t\t\t\tjs`return (await ${SafeJS.fn(js`cache.getRecordIdBySlug`, js`slug`, localeBinding)}) ?? ${defaultValue}`,\n\t\t\t\t\t\t)}})()`,\n\t\t\t\t\t)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase ControlType.MultiCollectionReference: {\n\t\t\t\t\tconst defaultValue = isArray(urlVar.initialValue) ? urlVar.initialValue : js`undefined`\n\t\t\t\t\tresolutions.push(\n\t\t\t\t\t\tjs`const ${binding} = await (async () => {${js.joinLines(\n\t\t\t\t\t\t\tjs`const slugs = Array.isArray(context.pathVariables?.[${urlVar.parameterName}]) ? context.pathVariables[${urlVar.parameterName}] : []`,\n\t\t\t\t\t\t\tjs`if (slugs.length === 0) return ${defaultValue}`,\n\t\t\t\t\t\t\tjs`const cache = ${SafeJS.fn(js`context.collectionUtils?.get`, urlVar.collectionId ?? \"\")}`,\n\t\t\t\t\t\t\tjs`if (!cache) return ${defaultValue}`,\n\t\t\t\t\t\t\tjs`const ids = await ${SafeJS.fn(\n\t\t\t\t\t\t\t\tjs`Promise.all`,\n\t\t\t\t\t\t\t\tjs`slugs.map(slug => ${SafeJS.fn(js`cache.getRecordIdBySlug`, js`slug`, localeBinding)})`,\n\t\t\t\t\t\t\t)}`,\n\t\t\t\t\t\t\tjs`return ${SafeJS.fn(js`ids.filter`, js`Boolean`)}`,\n\t\t\t\t\t\t)}})()`,\n\t\t\t\t\t)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(urlVar.type, \"Unexpected URL variable type\")\n\t\t\t}\n\t\t}\n\n\t\tconst bindingsObject: Record<string, SafeJS> = {}\n\t\tfor (const binding of bindings) {\n\t\t\tbindingsObject[serializeJS(binding)] = binding\n\t\t}\n\t\treturn { resolutions, bindings, bindingsById, bindingsObject }\n\t}\n\n\t#generateParallelizedDetailChain(\n\t\turlVarsPromiseBinding: SafeJS | undefined,\n\t\turlVarBindings: SafeJS[],\n\t\tdetailResultPromise: SafeJS,\n\t\tchainedCallsResult: SafeJS,\n\t): SafeJS {\n\t\tif (!urlVarsPromiseBinding || urlVarBindings.length === 0) {\n\t\t\treturn js`(async () => {${js.joinLines(\n\t\t\t\tjs`const [detailData] = (await ${detailResultPromise}) ?? []`,\n\t\t\t\tjs`return ${chainedCallsResult}`,\n\t\t\t)}})()`\n\t\t}\n\n\t\treturn js`(async () => {${js.joinLines(\n\t\t\tjs`const [urlVars, detailResult] = await ${SafeJS.fn(js`Promise.all`, [\n\t\t\t\turlVarsPromiseBinding,\n\t\t\t\tdetailResultPromise,\n\t\t\t])}`,\n\t\t\tjs`const { ${js.listFrom(urlVarBindings)} } = urlVars`,\n\t\t\tjs`const [detailData] = detailResult ?? []`,\n\t\t\tjs`return ${chainedCallsResult}`,\n\t\t)}})()`\n\t}\n\n\t#generateRepeaterChains(\n\t\trepeaterToQuery: Map<NodeID, RouteLoaderQuery>,\n\t\trepeaterDependentQueries: RouteLoaderQuery[],\n\t\trepeaterDependentChildComponents: ChildComponentInfo[],\n\t\tqueryCacheBinding: SafeJS | undefined,\n\t\turlVarsPromiseBinding: SafeJS | undefined,\n\t\turlVarBindingsById: Map<string, SafeJS>,\n\t\tdetailResultPromiseBinding: SafeJS | undefined,\n\t\thoistedCacheEntries: Map<string, SafeJS>,\n\t\thoistedCacheStatements: SafeJS[],\n\t\tlocaleBinding: SafeJS,\n\t): SafeJS[] {\n\t\tif (repeaterDependentQueries.length === 0 && repeaterDependentChildComponents.length === 0) {\n\t\t\treturn []\n\t\t}\n\n\t\tconst chainGroups = new Map<\n\t\t\tNodeID,\n\t\t\t{ queries: RouteLoaderQuery[]; components: ChildComponentInfo[]; parentQuery: RouteLoaderQuery | undefined }\n\t\t>()\n\n\t\tconst multiProviderQueries: RouteLoaderQuery[] = []\n\n\t\tfor (const query of repeaterDependentQueries) {\n\t\t\tconst orderedProviders = this.#getOrderedRepeaterProviders(query)\n\t\t\tif (orderedProviders.length > 1) {\n\t\t\t\tmultiProviderQueries.push(query)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst parentRepeaterId = query.repeaterVariables[0]?.repeaterId\n\t\t\tif (!parentRepeaterId) continue\n\n\t\t\tconst existing = chainGroups.get(parentRepeaterId)\n\t\t\tconst parentQuery = repeaterToQuery.get(parentRepeaterId)\n\n\t\t\tif (existing) {\n\t\t\t\texisting.queries.push(query)\n\t\t\t} else {\n\t\t\t\tchainGroups.set(parentRepeaterId, { queries: [query], components: [], parentQuery })\n\t\t\t}\n\t\t}\n\n\t\tfor (const component of repeaterDependentChildComponents) {\n\t\t\tconst parentRepeaterId = component.ancestorRepeaterId\n\t\t\tif (!parentRepeaterId) continue\n\n\t\t\tconst existing = chainGroups.get(parentRepeaterId)\n\t\t\tconst parentQuery = repeaterToQuery.get(parentRepeaterId)\n\n\t\t\tif (existing) {\n\t\t\t\texisting.components.push(component)\n\t\t\t} else {\n\t\t\t\tchainGroups.set(parentRepeaterId, { queries: [], components: [component], parentQuery })\n\t\t\t}\n\t\t}\n\n\t\tconst chains: SafeJS[] = []\n\t\tconst forwardLoaderBinding =\n\t\t\trepeaterDependentChildComponents.length > 0\n\t\t\t\t? this.ctx.imports.addImport(\"framer\", { exportSpecifier: \"forwardLoader\" })\n\t\t\t\t: undefined\n\n\t\tfor (const [, { queries, components, parentQuery }] of chainGroups) {\n\t\t\tif (!parentQuery || !queryCacheBinding) continue\n\n\t\t\t// If the parent repeater query itself depends on an outer repeater,\n\t\t\t// we must build a nested chain so the parent query receives the\n\t\t\t// correct outer item bindings.\n\t\t\tif (parentQuery.repeaterVariables.length > 0) {\n\t\t\t\tconst nested = this.#buildNestedParentRepeaterChain({\n\t\t\t\t\tparentQuery,\n\t\t\t\t\tqueries,\n\t\t\t\t\tcomponents,\n\t\t\t\t\trepeaterToQuery,\n\t\t\t\t\tqueryCacheBinding,\n\t\t\t\t\turlVarsPromiseBinding,\n\t\t\t\t\turlVarBindingsById,\n\t\t\t\t\tdetailResultPromiseBinding,\n\t\t\t\t\thoistedCacheEntries,\n\t\t\t\t\thoistedCacheStatements,\n\t\t\t\t\tlocaleBinding,\n\t\t\t\t\tforwardLoaderBinding,\n\t\t\t\t})\n\t\t\t\tif (nested) chains.push(nested)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst urlBindingsInUse = this.#collectUrlBindingsForQueries([parentQuery, ...queries], urlVarBindingsById)\n\t\t\tconst needsUrlVars = urlBindingsInUse.length > 0 && !!urlVarsPromiseBinding\n\t\t\tconst needsDetailData = this.#usesDetailArguments(parentQuery, queries) && !!detailResultPromiseBinding\n\t\t\tconst detailDataBinding = needsDetailData ? js`detailData` : js`undefined`\n\n\t\t\tconst mappedCalls: SafeJS[] = []\n\n\t\t\tfor (const childQuery of queries) {\n\t\t\t\tconst args = this.#buildQueryArgs(childQuery, {\n\t\t\t\t\turlVarBindingsById,\n\t\t\t\t\tdetailDataBinding,\n\t\t\t\t\titemVarByRepeaterId: new Map([[parentQuery.nodeId, js`item`]]),\n\t\t\t\t})\n\t\t\t\tconst childQueryCall = SafeJS.fn(childQuery.constantBinding, ...args)\n\t\t\t\tconst childQueryCacheGet = this.#queryCacheGet(queryCacheBinding, childQueryCall, localeBinding)\n\t\t\t\tmappedCalls.push(SafeJS.fn(js`${childQueryCacheGet}.preload`))\n\t\t\t}\n\n\t\t\tif (forwardLoaderBinding) {\n\t\t\t\tfor (const child of components) {\n\t\t\t\t\tconst componentBinding = this.ctx.imports.addModuleImport(child.moduleIdentifier)\n\t\t\t\t\tif (!componentBinding) continue\n\t\t\t\t\tconst propsExpr =\n\t\t\t\t\t\tObject.keys(child.staticProps).length > 0 ? new SerializableObject(child.staticProps) : js`{}`\n\t\t\t\t\tmappedCalls.push(SafeJS.fn(forwardLoaderBinding, componentBinding, propsExpr, js`context`))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (mappedCalls.length === 0) continue\n\n\t\t\tconst parentArgs = this.#buildQueryArgs(parentQuery, {\n\t\t\t\turlVarBindingsById,\n\t\t\t\tdetailDataBinding,\n\t\t\t\titemVarByRepeaterId: new Map(),\n\t\t\t})\n\t\t\tconst parentQueryCall = SafeJS.fn(parentQuery.constantBinding, ...parentArgs)\n\t\t\tconst parentQueryCacheGet = this.#queryCacheGet(queryCacheBinding, parentQueryCall, localeBinding)\n\t\t\tconst parentDataExpr =\n\t\t\t\tparentArgs.length === 0\n\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\tconst entry = this.#getQueryCacheEntryBinding(\n\t\t\t\t\t\t\t\tparentQuery.constantBinding,\n\t\t\t\t\t\t\t\tqueryCacheBinding,\n\t\t\t\t\t\t\t\thoistedCacheEntries,\n\t\t\t\t\t\t\t\thoistedCacheStatements,\n\t\t\t\t\t\t\t\tlocaleBinding,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn SafeJS.fn(js`${entry}.readMaybeAsync`)\n\t\t\t\t\t\t})()\n\t\t\t\t\t: SafeJS.fn(js`${parentQueryCacheGet}.readMaybeAsync`)\n\n\t\t\tconst firstMappedCall = mappedCalls[0]\n\t\t\tconst mappedCallsExpr = mappedCalls.length === 1 && firstMappedCall ? firstMappedCall : js`${mappedCalls}`\n\n\t\t\tconst prelude: SafeJS[] = []\n\t\t\tif (needsUrlVars && urlVarsPromiseBinding) {\n\t\t\t\tprelude.push(js`const { ${js.listFrom(urlBindingsInUse)} } = await ${urlVarsPromiseBinding}`)\n\t\t\t}\n\t\t\tif (needsDetailData && detailResultPromiseBinding) {\n\t\t\t\tprelude.push(js`const [detailData] = (await ${detailResultPromiseBinding}) ?? []`)\n\t\t\t}\n\n\t\t\tconst chain = js`(async () => {${js.joinLines(\n\t\t\t\t...prelude,\n\t\t\t\tjs`const parentData = await ${parentDataExpr} ?? []`,\n\t\t\t\tjs`return ${SafeJS.fn(\n\t\t\t\t\tjs`Promise.allSettled`,\n\t\t\t\t\tSafeJS.fn(js`parentData.flatMap`, js`item => ${mappedCallsExpr}`),\n\t\t\t\t)}`,\n\t\t\t)}})()`\n\n\t\t\tchains.push(chain)\n\t\t}\n\n\t\tfor (const query of multiProviderQueries) {\n\t\t\tconst chain = this.#buildMultiRepeaterChain(\n\t\t\t\tquery,\n\t\t\t\trepeaterToQuery,\n\t\t\t\tqueryCacheBinding,\n\t\t\t\turlVarsPromiseBinding,\n\t\t\t\turlVarBindingsById,\n\t\t\t\tdetailResultPromiseBinding,\n\t\t\t\thoistedCacheEntries,\n\t\t\t\thoistedCacheStatements,\n\t\t\t\tlocaleBinding,\n\t\t\t)\n\t\t\tif (chain) chains.push(chain)\n\t\t}\n\n\t\treturn chains\n\t}\n\n\t#getOrderedRepeaterProviders(query: RouteLoaderQuery): NodeID[] {\n\t\tconst providerIds = new Set(query.repeaterVariables.map(rv => rv.repeaterId))\n\t\tif (providerIds.size === 0) return []\n\n\t\tconst node = this.ctx.tree.get(query.nodeId)\n\t\tconst orderedFromAncestors = node?.cache?.ancestorRepeaterIds?.filter(id => id && providerIds.has(id)) ?? []\n\n\t\tif (orderedFromAncestors.length === providerIds.size) return orderedFromAncestors\n\n\t\tconst ordered = [...orderedFromAncestors]\n\t\tfor (const id of providerIds) {\n\t\t\tif (!ordered.includes(id)) ordered.push(id)\n\t\t}\n\t\treturn ordered\n\t}\n\n\t#expandRepeaterProviders(\n\t\tinitialProviders: readonly NodeID[],\n\t\trepeaterToQuery: Map<NodeID, RouteLoaderQuery>,\n\t): NodeID[] {\n\t\tconst ordered: NodeID[] = []\n\t\tconst seen = new Set<NodeID>()\n\n\t\tconst visit = (providerId: NodeID) => {\n\t\t\tif (seen.has(providerId)) return\n\t\t\tseen.add(providerId)\n\n\t\t\tconst providerQuery = repeaterToQuery.get(providerId)\n\t\t\tif (providerQuery) {\n\t\t\t\tconst deps = this.#getOrderedRepeaterProviders(providerQuery)\n\t\t\t\tfor (const dep of deps) visit(dep)\n\t\t\t}\n\n\t\t\tordered.push(providerId)\n\t\t}\n\n\t\tfor (const id of initialProviders) visit(id)\n\t\treturn ordered\n\t}\n\n\t#buildMultiRepeaterChain(\n\t\tquery: RouteLoaderQuery,\n\t\trepeaterToQuery: Map<NodeID, RouteLoaderQuery>,\n\t\tqueryCacheBinding: SafeJS | undefined,\n\t\turlVarsPromiseBinding: SafeJS | undefined,\n\t\turlVarBindingsById: Map<string, SafeJS>,\n\t\tdetailResultPromiseBinding: SafeJS | undefined,\n\t\thoistedCacheEntries: Map<string, SafeJS>,\n\t\thoistedCacheStatements: SafeJS[],\n\t\tlocaleBinding: SafeJS,\n\t): SafeJS | undefined {\n\t\tif (!queryCacheBinding) return\n\n\t\tconst providers = this.#expandRepeaterProviders(this.#getOrderedRepeaterProviders(query), repeaterToQuery)\n\t\tif (providers.length === 0) return\n\n\t\tconst providerInfo = this.#resolveRepeaterProviders(providers, repeaterToQuery)\n\t\tif (!providerInfo) return\n\t\tconst { providerQueries, dataVars, itemVars } = providerInfo\n\n\t\tconst tasksVar = js`tasks`\n\t\tconst lines: SafeJS[] = []\n\n\t\tconst { detailDataBinding } = this.#emitUrlAndDetailPrelude(lines, {\n\t\t\tqueriesForUrlBindings: [query, ...providerQueries],\n\t\t\turlVarBindingsById,\n\t\t\turlVarsPromiseBinding,\n\t\t\tneedsDetailData: this.#usesDetailArguments(query),\n\t\t\tdetailResultPromiseBinding,\n\t\t})\n\n\t\tconst outerProviderQuery = providerQueries[0]\n\t\tconst outerDataVar = dataVars[0]\n\t\tif (!outerProviderQuery || !outerDataVar) return\n\n\t\tconst outerArgs = this.#buildQueryArgs(outerProviderQuery, {\n\t\t\turlVarBindingsById,\n\t\t\tdetailDataBinding,\n\t\t\titemVarByRepeaterId: new Map(),\n\t\t})\n\t\tconst shouldHoistOuter = outerArgs.length === 0\n\t\tif (shouldHoistOuter) {\n\t\t\tconst entry = this.#getQueryCacheEntryBinding(\n\t\t\t\touterProviderQuery.constantBinding,\n\t\t\t\tqueryCacheBinding,\n\t\t\t\thoistedCacheEntries,\n\t\t\t\thoistedCacheStatements,\n\t\t\t\tlocaleBinding,\n\t\t\t)\n\t\t\tlines.push(\n\t\t\t\tjs`const ${outerDataVar} = await ${SafeJS.fn(js`${entry}.readMaybeAsync`)} ?? []`,\n\t\t\t\tjs`const ${tasksVar} = []`,\n\t\t\t)\n\t\t} else {\n\t\t\tconst outerQueryCall = SafeJS.fn(outerProviderQuery.constantBinding, ...outerArgs)\n\t\t\tconst outerCacheGetCall = this.#queryCacheGet(queryCacheBinding, outerQueryCall, localeBinding)\n\t\t\tlines.push(\n\t\t\t\tjs`const ${outerDataVar} = await ${SafeJS.fn(js`${outerCacheGetCall}.readMaybeAsync`)} ?? []`,\n\t\t\t\tjs`const ${tasksVar} = []`,\n\t\t\t)\n\t\t}\n\n\t\tfor (let level = 0; level < providers.length; level++) {\n\t\t\tconst currentItemVar = itemVars[level]\n\t\t\tconst currentDataVar = dataVars[level]\n\t\t\tif (!currentItemVar || !currentDataVar) continue\n\n\t\t\tlines.push(js`for (const ${currentItemVar} of ${currentDataVar}) {`)\n\n\t\t\tconst nextLevel = level + 1\n\t\t\tif (nextLevel < providers.length) {\n\t\t\t\tconst nextDataVar = dataVars[nextLevel]\n\t\t\t\tconst nextProviderQuery = providerQueries[nextLevel]\n\t\t\t\tif (!nextDataVar || !nextProviderQuery) continue\n\n\t\t\t\tconst itemVarByRepeaterId = new Map<NodeID, SafeJS>()\n\t\t\t\tproviders.slice(0, nextLevel + 1).forEach((id, idx) => itemVarByRepeaterId.set(id, itemVars[idx]!))\n\t\t\t\tconst args = this.#buildQueryArgs(nextProviderQuery, {\n\t\t\t\t\turlVarBindingsById,\n\t\t\t\t\tdetailDataBinding,\n\t\t\t\t\titemVarByRepeaterId,\n\t\t\t\t})\n\t\t\t\tconst nextCall = SafeJS.fn(nextProviderQuery.constantBinding, ...args)\n\t\t\t\tconst nextCacheGetCall = this.#queryCacheGet(queryCacheBinding, nextCall, localeBinding)\n\t\t\t\tlines.push(js`const ${nextDataVar} = await ${SafeJS.fn(js`${nextCacheGetCall}.readMaybeAsync`)} ?? []`)\n\t\t\t} else {\n\t\t\t\tconst itemVarByRepeaterId = new Map<NodeID, SafeJS>()\n\t\t\t\tproviders.forEach((id, idx) => itemVarByRepeaterId.set(id, itemVars[idx]!))\n\t\t\t\tconst childArgs = this.#buildQueryArgs(query, {\n\t\t\t\t\turlVarBindingsById,\n\t\t\t\t\tdetailDataBinding,\n\t\t\t\t\titemVarByRepeaterId,\n\t\t\t\t})\n\t\t\t\tconst childCall = SafeJS.fn(query.constantBinding, ...childArgs)\n\t\t\t\tconst childCacheGetCall = this.#queryCacheGet(queryCacheBinding, childCall, localeBinding)\n\t\t\t\tconst childPreloadCall = SafeJS.fn(js`${childCacheGetCall}.preload`)\n\t\t\t\tlines.push(SafeJS.fn(js`${tasksVar}.push`, childPreloadCall))\n\t\t\t}\n\t\t}\n\n\t\tfor (let level = providers.length - 1; level >= 0; level--) {\n\t\t\tlines.push(js`}`)\n\t\t}\n\n\t\tlines.push(js`return ${SafeJS.fn(js`Promise.allSettled`, tasksVar)}`)\n\t\treturn js`(async () => {${js.joinLines(...lines)}})()`\n\t}\n\n\t#buildNestedParentRepeaterChain(args: {\n\t\tparentQuery: RouteLoaderQuery\n\t\tqueries: RouteLoaderQuery[]\n\t\tcomponents: ChildComponentInfo[]\n\t\trepeaterToQuery: Map<NodeID, RouteLoaderQuery>\n\t\tqueryCacheBinding: SafeJS\n\t\turlVarsPromiseBinding: SafeJS | undefined\n\t\turlVarBindingsById: Map<string, SafeJS>\n\t\tdetailResultPromiseBinding: SafeJS | undefined\n\t\thoistedCacheEntries: Map<string, SafeJS>\n\t\thoistedCacheStatements: SafeJS[]\n\t\tlocaleBinding: SafeJS\n\t\tforwardLoaderBinding: SafeJS | undefined\n\t}): SafeJS | undefined {\n\t\tconst {\n\t\t\tparentQuery,\n\t\t\tqueries,\n\t\t\tcomponents,\n\t\t\trepeaterToQuery,\n\t\t\tqueryCacheBinding,\n\t\t\turlVarsPromiseBinding,\n\t\t\turlVarBindingsById,\n\t\t\tdetailResultPromiseBinding,\n\t\t\thoistedCacheEntries,\n\t\t\thoistedCacheStatements,\n\t\t\tlocaleBinding,\n\t\t\tforwardLoaderBinding,\n\t\t} = args\n\n\t\tconst providers = this.#expandRepeaterProviders(this.#getOrderedRepeaterProviders(parentQuery), repeaterToQuery)\n\t\tif (providers.length === 0) return\n\n\t\tconst providerInfo = this.#resolveRepeaterProviders(providers, repeaterToQuery)\n\t\tif (!providerInfo) return\n\t\tconst { providerQueries, dataVars, itemVars } = providerInfo\n\n\t\tconst needsDetailData =\n\t\t\tthis.#usesDetailArguments(parentQuery, queries, providerQueries) && !!detailResultPromiseBinding\n\t\tconst detailDataBinding = needsDetailData ? js`detailData` : js`undefined`\n\n\t\t// Build mapped calls for each item in parent results\n\t\tconst mappedCalls: SafeJS[] = []\n\t\tfor (const childQuery of queries) {\n\t\t\tconst itemVarByRepeaterId = new Map<NodeID, SafeJS>()\n\t\t\t// Parent repeater item (inner) is named `item`.\n\t\t\titemVarByRepeaterId.set(parentQuery.nodeId, js`item`)\n\t\t\t// Outer provider items will be named item0, item1, ... matching providers order.\n\t\t\tproviders.forEach((id, idx) => itemVarByRepeaterId.set(id, itemVars[idx]!))\n\n\t\t\tconst callArgs = this.#buildQueryArgs(childQuery, {\n\t\t\t\turlVarBindingsById,\n\t\t\t\tdetailDataBinding,\n\t\t\t\titemVarByRepeaterId,\n\t\t\t})\n\t\t\tconst childQueryCall = SafeJS.fn(childQuery.constantBinding, ...callArgs)\n\t\t\tconst cacheGetCall = this.#queryCacheGet(queryCacheBinding, childQueryCall, localeBinding)\n\t\t\tmappedCalls.push(SafeJS.fn(js`${cacheGetCall}.preload`))\n\t\t}\n\n\t\tif (forwardLoaderBinding) {\n\t\t\tfor (const child of components) {\n\t\t\t\tconst componentBinding = this.ctx.imports.addModuleImport(child.moduleIdentifier)\n\t\t\t\tif (!componentBinding) continue\n\t\t\t\tconst propsExpr = Object.keys(child.staticProps).length > 0 ? new SerializableObject(child.staticProps) : js`{}`\n\t\t\t\tmappedCalls.push(SafeJS.fn(forwardLoaderBinding, componentBinding, propsExpr, js`context`))\n\t\t\t}\n\t\t}\n\n\t\tif (mappedCalls.length === 0) return\n\n\t\tconst firstMappedCall = mappedCalls[0]\n\t\tconst mappedCallsExpr = mappedCalls.length === 1 && firstMappedCall ? firstMappedCall : js`${mappedCalls}`\n\n\t\tconst lines: SafeJS[] = []\n\n\t\tthis.#emitUrlAndDetailPrelude(lines, {\n\t\t\tqueriesForUrlBindings: [parentQuery, ...queries, ...providerQueries],\n\t\t\turlVarBindingsById,\n\t\t\turlVarsPromiseBinding,\n\t\t\tneedsDetailData,\n\t\t\tdetailResultPromiseBinding,\n\t\t})\n\n\t\t// Outer provider fetch (supports hoisting when possible)\n\t\tconst outerProviderQuery = providerQueries[0]\n\t\tconst outerDataVar = dataVars[0]\n\t\tif (!outerProviderQuery || !outerDataVar) return\n\n\t\tconst outerArgs = this.#buildQueryArgs(outerProviderQuery, {\n\t\t\turlVarBindingsById,\n\t\t\tdetailDataBinding,\n\t\t\titemVarByRepeaterId: new Map(),\n\t\t})\n\t\tif (outerArgs.length === 0) {\n\t\t\tconst entry = this.#getQueryCacheEntryBinding(\n\t\t\t\touterProviderQuery.constantBinding,\n\t\t\t\tqueryCacheBinding,\n\t\t\t\thoistedCacheEntries,\n\t\t\t\thoistedCacheStatements,\n\t\t\t\tlocaleBinding,\n\t\t\t)\n\t\t\tlines.push(js`const ${outerDataVar} = await ${SafeJS.fn(js`${entry}.readMaybeAsync`)} ?? []`)\n\t\t} else {\n\t\t\tconst call = SafeJS.fn(outerProviderQuery.constantBinding, ...outerArgs)\n\t\t\tconst outerCacheGetCall = this.#queryCacheGet(queryCacheBinding, call, localeBinding)\n\t\t\tlines.push(js`const ${outerDataVar} = await ${SafeJS.fn(js`${outerCacheGetCall}.readMaybeAsync`)} ?? []`)\n\t\t}\n\n\t\t// Nested loops for providers\n\t\tfor (let level = 0; level < providers.length; level++) {\n\t\t\tconst currentItemVar = itemVars[level]\n\t\t\tconst currentDataVar = dataVars[level]\n\t\t\tif (!currentItemVar || !currentDataVar) continue\n\n\t\t\tlines.push(js`for (const ${currentItemVar} of ${currentDataVar}) {`)\n\n\t\t\tconst nextLevel = level + 1\n\t\t\tif (nextLevel < providers.length) {\n\t\t\t\tconst nextDataVar = dataVars[nextLevel]\n\t\t\t\tconst nextProviderQuery = providerQueries[nextLevel]\n\t\t\t\tif (!nextDataVar || !nextProviderQuery) continue\n\n\t\t\t\tconst itemVarByRepeaterId = new Map<NodeID, SafeJS>()\n\t\t\t\tproviders.slice(0, nextLevel + 1).forEach((id, idx) => itemVarByRepeaterId.set(id, itemVars[idx]!))\n\t\t\t\tconst nextArgs = this.#buildQueryArgs(nextProviderQuery, {\n\t\t\t\t\turlVarBindingsById,\n\t\t\t\t\tdetailDataBinding,\n\t\t\t\t\titemVarByRepeaterId,\n\t\t\t\t})\n\t\t\t\tconst nextCall = SafeJS.fn(nextProviderQuery.constantBinding, ...nextArgs)\n\t\t\t\tconst nextCacheGetCall = this.#queryCacheGet(queryCacheBinding, nextCall, localeBinding)\n\t\t\t\tlines.push(js`const ${nextDataVar} = await ${SafeJS.fn(js`${nextCacheGetCall}.readMaybeAsync`)} ?? []`)\n\t\t\t} else {\n\t\t\t\t// Final level: fetch parentData for this provider combination and run mappedCalls for each item.\n\t\t\t\tconst itemVarByRepeaterId = new Map<NodeID, SafeJS>()\n\t\t\t\tproviders.forEach((id, idx) => itemVarByRepeaterId.set(id, itemVars[idx]!))\n\t\t\t\tconst parentArgs = this.#buildQueryArgs(parentQuery, {\n\t\t\t\t\turlVarBindingsById,\n\t\t\t\t\tdetailDataBinding,\n\t\t\t\t\titemVarByRepeaterId,\n\t\t\t\t})\n\t\t\t\tconst parentCall = SafeJS.fn(parentQuery.constantBinding, ...parentArgs)\n\t\t\t\tconst parentCacheGetCall = this.#queryCacheGet(queryCacheBinding, parentCall, localeBinding)\n\t\t\t\tlines.push(\n\t\t\t\t\tjs`const parentData = (await ${SafeJS.fn(js`${parentCacheGetCall}.readMaybeAsync`)}) ?? []`,\n\t\t\t\t\tjs`await ${SafeJS.fn(\n\t\t\t\t\t\tjs`Promise.allSettled`,\n\t\t\t\t\t\tSafeJS.fn(js`parentData.flatMap`, js`item => ${mappedCallsExpr}`),\n\t\t\t\t\t)}`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Close loops\n\t\tfor (let level = providers.length - 1; level >= 0; level--) lines.push(js`}`)\n\n\t\t// Return value: Promise that resolves when nested work completes\n\t\tlines.push(js`return undefined`)\n\n\t\treturn js`(async () => {${js.joinLines(...lines)}})()`\n\t}\n\n\t#resolveRepeaterProviders(\n\t\tproviders: readonly NodeID[],\n\t\trepeaterToQuery: Map<NodeID, RouteLoaderQuery>,\n\t): { providerQueries: RouteLoaderQuery[]; dataVars: SafeJS[]; itemVars: SafeJS[] } | undefined {\n\t\tconst providerQueries: RouteLoaderQuery[] = []\n\t\tconst dataVars: SafeJS[] = []\n\t\tconst itemVars: SafeJS[] = []\n\t\tfor (let i = 0; i < providers.length; i++) {\n\t\t\tconst providerId = providers[i]!\n\t\t\tconst providerQuery = repeaterToQuery.get(providerId)\n\t\t\tif (!providerQuery) return\n\t\t\tproviderQueries.push(providerQuery)\n\t\t\tdataVars.push(js`data${i}`)\n\t\t\titemVars.push(js`item${i}`)\n\t\t}\n\t\treturn { providerQueries, dataVars, itemVars }\n\t}\n\n\t#emitUrlAndDetailPrelude(\n\t\tlines: SafeJS[],\n\t\targs: {\n\t\t\tqueriesForUrlBindings: RouteLoaderQuery[]\n\t\t\turlVarBindingsById: Map<string, SafeJS>\n\t\t\turlVarsPromiseBinding: SafeJS | undefined\n\t\t\tneedsDetailData: boolean\n\t\t\tdetailResultPromiseBinding: SafeJS | undefined\n\t\t},\n\t): { detailDataBinding: SafeJS } {\n\t\tconst urlBindingsInUse = this.#collectUrlBindingsForQueries(args.queriesForUrlBindings, args.urlVarBindingsById)\n\t\tconst needsUrlVars = urlBindingsInUse.length > 0 && !!args.urlVarsPromiseBinding\n\t\tconst needsDetailData = args.needsDetailData && !!args.detailResultPromiseBinding\n\t\tconst detailDataBinding = needsDetailData ? js`detailData` : js`undefined`\n\n\t\tif (needsUrlVars && args.urlVarsPromiseBinding) {\n\t\t\tlines.push(js`const { ${js.listFrom(urlBindingsInUse)} } = await ${args.urlVarsPromiseBinding}`)\n\t\t}\n\t\tif (needsDetailData && args.detailResultPromiseBinding) {\n\t\t\tlines.push(js`const [detailData] = (await ${args.detailResultPromiseBinding}) ?? []`)\n\t\t}\n\n\t\treturn { detailDataBinding }\n\t}\n\n\t#collectUrlBindingsForQueries(queries: RouteLoaderQuery[], urlVarBindingsById: Map<string, SafeJS>): SafeJS[] {\n\t\tconst bindings = new SafeJS.Set()\n\t\tconst ordered: SafeJS[] = []\n\t\tfor (const query of queries) {\n\t\t\tfor (const arg of query.argumentOrder) {\n\t\t\t\tif (arg.kind !== \"url\") continue\n\t\t\t\tconst binding = urlVarBindingsById.get(arg.id)\n\t\t\t\tif (!binding) continue\n\t\t\t\tif (bindings.has(binding)) continue\n\t\t\t\tbindings.add(binding)\n\t\t\t\tordered.push(binding)\n\t\t\t}\n\t\t}\n\t\treturn ordered\n\t}\n\n\t#usesDetailArguments(...queries: readonly (RouteLoaderQuery | RouteLoaderQuery[])[]): boolean {\n\t\tfor (const query of queries) {\n\t\t\tif (isArray(query)) {\n\t\t\t\treturn this.#usesDetailArguments(...query)\n\t\t\t}\n\n\t\t\tfor (const arg of query.argumentOrder) {\n\t\t\t\tif (arg.kind === \"detail\") return true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t#buildQueryArgs(\n\t\tquery: RouteLoaderQuery,\n\t\targs: {\n\t\t\turlVarBindingsById: Map<string, SafeJS>\n\t\t\tdetailDataBinding: SafeJS\n\t\t\titemVarByRepeaterId: Map<NodeID, SafeJS>\n\t\t},\n\t): SafeJS[] {\n\t\tconst result: SafeJS[] = []\n\t\tfor (const arg of query.argumentOrder) {\n\t\t\tswitch (arg.kind) {\n\t\t\t\tcase \"url\": {\n\t\t\t\t\tconst binding = args.urlVarBindingsById.get(arg.id)\n\t\t\t\t\tresult.push(binding ?? js`undefined`)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase \"detail\":\n\t\t\t\t\tresult.push(js`${args.detailDataBinding}?.[${arg.id}]`)\n\t\t\t\t\tbreak\n\n\t\t\t\tcase \"repeater\": {\n\t\t\t\t\tconst itemVar = args.itemVarByRepeaterId.get(arg.repeaterId)\n\t\t\t\t\tresult.push(itemVar ? js`${itemVar}[${arg.id}]` : js`undefined`)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(arg)\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\t#getQueryCacheEntryBinding(\n\t\tconstantBinding: SafeJS,\n\t\tqueryCacheBinding: SafeJS,\n\t\thoistedCacheEntries: Map<string, SafeJS>,\n\t\thoistedCacheStatements: SafeJS[],\n\t\tlocaleBinding: SafeJS,\n\t): SafeJS {\n\t\tconst key = serializeJS(constantBinding)\n\t\tconst existing = hoistedCacheEntries.get(key)\n\t\tif (existing) return existing\n\n\t\tconst binding = this.ctx.bindings.create(\"queryCacheEntry\")\n\t\thoistedCacheEntries.set(key, binding)\n\t\tconst constantCall = SafeJS.fn(constantBinding)\n\t\tconst cacheGetCall = this.#queryCacheGet(queryCacheBinding, constantCall, localeBinding)\n\t\thoistedCacheStatements.push(js`const ${binding} = ${cacheGetCall}`)\n\t\treturn binding\n\t}\n\n\t#queryCacheGet(queryCacheBinding: SafeJS, queryCall: SafeJS, localeBinding: SafeJS): SafeJS {\n\t\treturn SafeJS.fn(js`${queryCacheBinding}.get`, queryCall, localeBinding)\n\t}\n\n\t#generateForwardLoaderCalls(childComponents: ChildComponentInfo[]): SafeJS[] {\n\t\tif (childComponents.length === 0) return []\n\n\t\tconst forwardLoaderBinding = this.ctx.imports.addImport(\"framer\", { exportSpecifier: \"forwardLoader\" })\n\t\tconst calls: SafeJS[] = []\n\t\tconst seen = new Set<string>()\n\n\t\tfor (const child of childComponents) {\n\t\t\tconst componentBinding = this.ctx.imports.addModuleImport(child.moduleIdentifier)\n\t\t\tif (!componentBinding) continue\n\n\t\t\tconst propsExpr = Object.keys(child.staticProps).length > 0 ? new SerializableObject(child.staticProps) : js`{}`\n\t\t\tconst dedupeKey = `${serializeJS(componentBinding)}|${serializeJS(propsExpr)}`\n\t\t\tif (seen.has(dedupeKey)) continue\n\t\t\tseen.add(dedupeKey)\n\t\t\tcalls.push(SafeJS.fn(forwardLoaderBinding, componentBinding, propsExpr, js`context`))\n\t\t}\n\n\t\treturn calls\n\t}\n\n\t#wrapLoaderCode(setupStatements: SafeJS[], returnStatement: SafeJS): LoaderCode {\n\t\tconst setup = js.joinLines(...setupStatements)\n\t\tconst body = setup ? js.joinLines(setup, js`return ${returnStatement}`) : js`return ${returnStatement}`\n\t\treturn { load: js`(props, context) => {${body}}` }\n\t}\n}\n", "import type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport type { SerializableRecord } from \"code-generation/js/SerializableValue.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { MakeSerializable } from \"code-generation/types.ts\"\nimport type { NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { From, SelectExpression } from \"library/modules/cms/types.ts\"\nimport type { getWhereExpressionFromPathVariables } from \"library/modules/useQueryData.ts\"\nimport type { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\n\nexport type LoaderCode = { load: SafeJS } | undefined\n\nexport interface URLVariableInfo {\n\t/** Variable ID */\n\tid: string\n\t/** Path variable name (from URL path segment) */\n\tparameterName: string\n\t/** Variable type */\n\ttype: ControlType.String | ControlType.CollectionReference | ControlType.MultiCollectionReference\n\t/** Collection ID for collection reference types */\n\tcollectionId?: string\n\t/** Whether this URL variable is optional (only supported for ControlType.String). */\n\toptional?: boolean\n\t/** Initial/default value */\n\tinitialValue: string | string[] | undefined\n}\n\ninterface RepeaterVariableInfo {\n\t/** Variable ID */\n\tid: string\n\t/** Node ID of the repeater that provides this variable */\n\trepeaterId: NodeID\n}\n\nexport type RouteLoaderArgument =\n\t| { kind: \"url\"; id: string }\n\t| { kind: \"detail\"; id: string }\n\t| { kind: \"repeater\"; id: string; repeaterId: NodeID }\n\nexport interface RouteLoaderQuery {\n\t/** Unique key for deduplication */\n\tkey: string\n\t/** The query constant binding (e.g., `query_abc123`) */\n\tconstantBinding: SafeJS\n\t/** The serialized query object */\n\tquery: SerializableRecord\n\t/** Node ID that originated this query */\n\tnodeId: NodeID\n\t/** Node IDs that share this deduped query */\n\tnodeIds: NodeID[]\n\t/** Variable IDs from the detail page that this query depends on */\n\tdetailPageVariableIds: string[]\n\t/** URL variables that this query depends on (resolved via slugs from pathVariables) */\n\turlVariables: URLVariableInfo[]\n\t/** Variables from parent repeaters (can be chained via parent query results) */\n\trepeaterVariables: RepeaterVariableInfo[]\n\t/** Whether the query has variables that can't be resolved in the loader context */\n\thasUnresolvableVariables: boolean\n\t/** Full argument list (deduped) in stable order for invocation */\n\targumentOrder: RouteLoaderArgument[]\n}\n\ntype SerializableFrom = MakeSerializable<From>\ntype SerializableSelectExpression = MakeSerializable<SelectExpression>\n\nexport interface DetailPageQuery {\n\t/** The from clause (collection definition with joins) */\n\tfrom: SerializableFrom\n\t/** The select clause */\n\tselect: SerializableSelectExpression[]\n\t/** Collection alias used in getWhereExpressionFromPathVariables */\n\tcollectionAlias: Parameters<typeof getWhereExpressionFromPathVariables>[1]\n\t/** File-level constant binding for the query function (set during finalization) */\n\tconstantBinding?: SafeJS\n}\n\nexport interface ChildComponentInfo {\n\t/** Module identifier for the component (used for import) */\n\tmoduleIdentifier: ModuleExportIdentifierString\n\t/** Static props to pass to the loader */\n\tstaticProps: SerializableRecord\n\t/** Node ID for deduplication */\n\tnodeId: NodeID\n\t/** If set, this component loader should be run once per item in the parent repeater. */\n\tancestorRepeaterId?: NodeID\n}\n\nexport interface RouteLoaderPlan {\n\trepeaterToQuery: Map<NodeID, RouteLoaderQuery>\n\tindependentQueries: RouteLoaderQuery[]\n\turlOnlyQueries: RouteLoaderQuery[]\n\tdetailOnlyQueries: RouteLoaderQuery[]\n\tmixedQueries: RouteLoaderQuery[]\n\trepeaterDependentQueries: RouteLoaderQuery[]\n\tindependentChildComponents: ChildComponentInfo[]\n\trepeaterDependentChildComponents: ChildComponentInfo[]\n\tdetailPageQuery: DetailPageQuery | undefined\n}\n\nexport function buildRouteLoaderPlan(args: {\n\trouteLoaderQueries: Map<string, RouteLoaderQuery>\n\tdetailPageQuery: DetailPageQuery | undefined\n\tchildComponents: Map<NodeID, ChildComponentInfo>\n}): RouteLoaderPlan | undefined {\n\tconst categorized = categorizeRouteLoaderQueries(args.routeLoaderQueries, args.detailPageQuery)\n\tconst grouped = groupChildComponents(args.childComponents)\n\n\tconst hasDetailPageQuery = !isUndefined(args.detailPageQuery)\n\tconst hasAnyQueries =\n\t\tcategorized.independentQueries.length > 0 ||\n\t\tcategorized.urlOnlyQueries.length > 0 ||\n\t\thasDetailPageQuery ||\n\t\tcategorized.detailOnlyQueries.length > 0 ||\n\t\tcategorized.mixedQueries.length > 0 ||\n\t\tcategorized.repeaterDependentQueries.length > 0\n\tconst hasChildComponents =\n\t\tgrouped.independentChildComponents.length > 0 || grouped.repeaterDependentChildComponents.length > 0\n\n\tif (!hasAnyQueries && !hasChildComponents) return\n\n\treturn {\n\t\t...categorized,\n\t\t...grouped,\n\t\tdetailPageQuery: args.detailPageQuery,\n\t}\n}\n\nfunction categorizeRouteLoaderQueries(\n\trouteLoaderQueries: Map<string, RouteLoaderQuery>,\n\tdetailPageQuery: DetailPageQuery | undefined,\n): {\n\trepeaterToQuery: Map<NodeID, RouteLoaderQuery>\n\tindependentQueries: RouteLoaderQuery[]\n\turlOnlyQueries: RouteLoaderQuery[]\n\tdetailOnlyQueries: RouteLoaderQuery[]\n\tmixedQueries: RouteLoaderQuery[]\n\trepeaterDependentQueries: RouteLoaderQuery[]\n} {\n\tconst repeaterToQuery = new Map<NodeID, RouteLoaderQuery>()\n\tconst independentQueries: RouteLoaderQuery[] = []\n\tconst urlOnlyQueries: RouteLoaderQuery[] = []\n\tconst detailOnlyQueries: RouteLoaderQuery[] = []\n\tconst mixedQueries: RouteLoaderQuery[] = []\n\tconst repeaterDependentQueries: RouteLoaderQuery[] = []\n\n\tfor (const query of routeLoaderQueries.values()) {\n\t\tif (query.hasUnresolvableVariables) continue\n\t\t// Detail page variables require a registered detail page query.\n\t\tif (query.detailPageVariableIds.length > 0 && isUndefined(detailPageQuery)) continue\n\n\t\tfor (const nodeId of query.nodeIds) repeaterToQuery.set(nodeId, query)\n\n\t\tconst hasDetail = query.detailPageVariableIds.length > 0\n\t\tconst hasURL = query.urlVariables.length > 0\n\t\tconst hasRepeater = query.repeaterVariables.length > 0\n\n\t\tif (hasRepeater) {\n\t\t\trepeaterDependentQueries.push(query)\n\t\t} else if (hasDetail && hasURL) {\n\t\t\tmixedQueries.push(query)\n\t\t} else if (hasDetail) {\n\t\t\tdetailOnlyQueries.push(query)\n\t\t} else if (hasURL) {\n\t\t\turlOnlyQueries.push(query)\n\t\t} else {\n\t\t\tindependentQueries.push(query)\n\t\t}\n\t}\n\n\treturn {\n\t\trepeaterToQuery,\n\t\tindependentQueries,\n\t\turlOnlyQueries,\n\t\tdetailOnlyQueries,\n\t\tmixedQueries,\n\t\trepeaterDependentQueries,\n\t}\n}\n\nfunction groupChildComponents(childComponents: Map<NodeID, ChildComponentInfo>): {\n\tindependentChildComponents: ChildComponentInfo[]\n\trepeaterDependentChildComponents: ChildComponentInfo[]\n} {\n\tconst independentChildComponents: ChildComponentInfo[] = []\n\tconst repeaterDependentChildComponents: ChildComponentInfo[] = []\n\tfor (const component of childComponents.values()) {\n\t\tif (component.ancestorRepeaterId) {\n\t\t\trepeaterDependentChildComponents.push(component)\n\t\t} else {\n\t\t\tindependentChildComponents.push(component)\n\t\t}\n\t}\n\n\treturn { independentChildComponents, repeaterDependentChildComponents }\n}\n", "import type { SerializableRecord } from \"code-generation/js/SerializableValue.ts\"\nimport { serializeJS } from \"code-generation/js/serializeJS.ts\"\n\nexport function getRouteLoaderQueryKey(query: SerializableRecord): string {\n\t// Prefer JS serialization over JSON.stringify:\n\t// - stable key ordering\n\t// - includes SafeJS / SerializableObject content\n\treturn serializeJS(query)\n}\n", "import { type ModuleIdentifierString, assertNever, isModuleExportIdentifier } from \"@framerjs/shared\"\nimport { ModuleType, parseModuleIdentifier } from \"@framerjs/shared/src/moduleIdentifiers.ts\"\nimport type { SerializableRecord } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport { getQueryParamNameOfVariable } from \"document/components/chrome/properties/utils/getQueryParamNameOfVariable.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isDataRepeater, isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isVariableDefinition, withQueryParam } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isArray, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport type { PreloadCollectorContext } from \"./PreloadCollectorContext.ts\"\nimport { RouteLoaderSerializer } from \"./RouteLoaderSerializer.ts\"\nimport { buildRouteLoaderPlan } from \"./buildRouteLoaderPlan.ts\"\nimport type {\n\tChildComponentInfo,\n\tDetailPageQuery,\n\tLoaderCode,\n\tRouteLoaderArgument,\n\tRouteLoaderQuery,\n\tURLVariableInfo,\n} from \"./buildRouteLoaderPlan.ts\"\nimport { getRouteLoaderQueryKey } from \"./getRouteLoaderQueryKey.ts\"\nexport type { LoaderCode } from \"./buildRouteLoaderPlan.ts\"\n\nexport class RouteLoaderCollector {\n\t// Route loader queries - collected during JSX traversal for Component.loader generation\n\t#routeLoaderQueries = new Map<string, RouteLoaderQuery>()\n\n\t// Detail page query - for CMS detail pages that query data based on path variables\n\t#detailPageQuery: DetailPageQuery | undefined\n\n\t// Child components with loaders - collected during JSX traversal for forwardLoader calls\n\t#childComponents = new Map<NodeID, ChildComponentInfo>()\n\n\t#urlVariableDefinitions: Map<string, URLVariableInfo> | undefined\n\n\tconstructor(private readonly ctx: PreloadCollectorContext) {}\n\n\t/**\n\t * Adds the detail page query (CMS detail page with path variable filtering).\n\t * Creates a file-level constant function that accepts a `where` parameter.\n\t * This allows the object to be GC'd after use.\n\t */\n\taddDetailPageQuery(\n\t\tfrom: DetailPageQuery[\"from\"],\n\t\tselect: DetailPageQuery[\"select\"],\n\t\tcollectionAlias: DetailPageQuery[\"collectionAlias\"],\n\t): void {\n\t\tconst where = js`where`\n\t\tconst queryFn = js`(${where}) => (${new SerializableObject({ from, select, where })})`\n\t\tconst constantBinding = this.ctx.declarations.dedupe(\"detailQuery\", queryFn)\n\n\t\tthis.#detailPageQuery = { from, select, collectionAlias, constantBinding }\n\t}\n\n\t/**\n\t * Adds a query to the route loader collection and returns an invocation expression.\n\t * The query is wrapped in a function so the object can be GC'd after use.\n\t */\n\taddRouteLoaderQuery(\n\t\tnode: CanvasNode,\n\t\tquery: SerializableRecord,\n\t\tvariableDependencies: VariableReference[] = [],\n\t): SafeJS {\n\t\tconst key = getRouteLoaderQueryKey(query)\n\t\tconst existing = this.#routeLoaderQueries.get(key)\n\t\tif (existing) {\n\t\t\t// Preserve the first nodeId for ordering heuristics but track all node ids\n\t\t\tif (!existing.nodeIds.includes(node.id)) existing.nodeIds.push(node.id)\n\n\t\t\t// Recreate the invocation args without rebuilding query metadata.\n\t\t\tconst seenBindings = new SafeJS.Set()\n\t\t\tconst orderedBindings: SafeJS[] = []\n\t\t\tfor (const v of variableDependencies) {\n\t\t\t\tconst binding = this.ctx.variables.create(v)\n\t\t\t\tif (seenBindings.has(binding)) continue\n\t\t\t\tseenBindings.add(binding)\n\t\t\t\torderedBindings.push(binding)\n\t\t\t}\n\n\t\t\treturn orderedBindings.length > 0\n\t\t\t\t? SafeJS.fn(existing.constantBinding, ...orderedBindings)\n\t\t\t\t: SafeJS.fn(existing.constantBinding)\n\t\t}\n\n\t\t// Get URL variable definitions from entry node (if it's a WebPage)\n\t\tconst urlVariableDefinitions = this.#getURLVariableDefinitions()\n\n\t\tconst detailPageVariableIds: string[] = []\n\t\tconst seenBindings = new SafeJS.Set()\n\t\tconst orderedBindings: SafeJS[] = []\n\t\tconst argumentOrder: RouteLoaderArgument[] = []\n\t\tconst urlVariables: URLVariableInfo[] = []\n\t\tconst repeaterVariables: { id: string; repeaterId: NodeID }[] = []\n\t\tlet hasUnresolvableVariables = false\n\n\t\tfor (const v of variableDependencies) {\n\t\t\tconst binding = this.ctx.variables.create(v)\n\t\t\tif (seenBindings.has(binding)) continue\n\t\t\tseenBindings.add(binding)\n\t\t\torderedBindings.push(binding)\n\n\t\t\t// Check if this variable is provided by the entry node\n\t\t\tif (v.providerId === this.ctx.entryNode.id) {\n\t\t\t\t// Check if it's a URL variable (collection reference with path segment)\n\t\t\t\tconst urlVarDef = urlVariableDefinitions.get(v.id)\n\t\t\t\tif (urlVarDef) {\n\t\t\t\t\t// Only collection reference types are supported (not String)\n\t\t\t\t\turlVariables.push(urlVarDef)\n\t\t\t\t\targumentOrder.push({ kind: \"url\", id: v.id })\n\t\t\t\t} else {\n\t\t\t\t\t// It's a detail page variable (from CMS data)\n\t\t\t\t\tdetailPageVariableIds.push(v.id)\n\t\t\t\t\targumentOrder.push({ kind: \"detail\", id: v.id })\n\t\t\t\t}\n\t\t\t} else if (v.providerId) {\n\t\t\t\t// Check if the provider is a repeater\n\t\t\t\tconst providerNode = this.ctx.tree.get(v.providerId)\n\t\t\t\tif (providerNode && isDataRepeater(providerNode)) {\n\t\t\t\t\trepeaterVariables.push({ id: v.id, repeaterId: v.providerId })\n\t\t\t\t\targumentOrder.push({ kind: \"repeater\", id: v.id, repeaterId: v.providerId })\n\t\t\t\t} else {\n\t\t\t\t\t// Variable from another source (props from parent component)\n\t\t\t\t\thasUnresolvableVariables = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// No provider ID - unresolvable\n\t\t\t\thasUnresolvableVariables = true\n\t\t\t}\n\t\t}\n\n\t\t// Create a function that accepts variable dependencies and returns the query object\n\t\t// This allows the object to be GC'd after querying\n\t\tconst hasVariableBindings = orderedBindings.length > 0\n\t\tconst params = hasVariableBindings ? js.listFrom(orderedBindings) : js``\n\t\tconst queryFn = js`(${params}) => (${query})`\n\t\tconst constantBinding = this.ctx.declarations.dedupe(\"query\", queryFn)\n\n\t\tthis.#routeLoaderQueries.set(key, {\n\t\t\tkey,\n\t\t\tconstantBinding,\n\t\t\tquery,\n\t\t\tnodeId: node.id,\n\t\t\tnodeIds: [node.id],\n\t\t\tdetailPageVariableIds,\n\t\t\turlVariables,\n\t\t\trepeaterVariables,\n\t\t\thasUnresolvableVariables,\n\t\t\targumentOrder,\n\t\t})\n\n\t\treturn hasVariableBindings ? SafeJS.fn(constantBinding, ...orderedBindings) : SafeJS.fn(constantBinding)\n\t}\n\n\t/**\n\t * Registers a child component that should have its loader called.\n\t * The loader will be called with forwardLoader(Component, staticProps, context).\n\t */\n\taddChildComponent(\n\t\tmoduleIdentifier: ModuleIdentifierString,\n\t\tstaticProps: SerializableRecord,\n\t\tnodeId: NodeID,\n\t\tancestorRepeaterId?: NodeID,\n\t): void {\n\t\tif (!isModuleExportIdentifier(moduleIdentifier)) return\n\t\tif (this.#childComponents.has(nodeId)) return\n\n\t\tthis.#childComponents.set(nodeId, {\n\t\t\tmoduleIdentifier,\n\t\t\tstaticProps,\n\t\t\tnodeId,\n\t\t\tancestorRepeaterId,\n\t\t})\n\t}\n\n\thasRouteLoaderQueries(): boolean {\n\t\treturn this.#routeLoaderQueries.size > 0 || !isUndefined(this.#detailPageQuery) || this.#childComponents.size > 0\n\t}\n\n\tgetDetailPageQueryConstant(): SafeJS | undefined {\n\t\treturn this.#detailPageQuery?.constantBinding\n\t}\n\n\tgetRouteLoaderCode(): LoaderCode {\n\t\tconst plan = buildRouteLoaderPlan({\n\t\t\trouteLoaderQueries: this.#routeLoaderQueries,\n\t\t\tdetailPageQuery: this.#detailPageQuery,\n\t\t\tchildComponents: this.#childComponents,\n\t\t})\n\t\tif (!plan) return\n\t\treturn new RouteLoaderSerializer(this.ctx).serialize(plan)\n\t}\n\n\t#getURLVariableDefinitions(): Map<string, URLVariableInfo> {\n\t\tconst existing = this.#urlVariableDefinitions\n\t\tif (existing) return existing\n\n\t\tconst result = new Map<string, URLVariableInfo>()\n\t\tif (!isWebPageNode(this.ctx.entryNode)) {\n\t\t\tthis.#urlVariableDefinitions = result\n\t\t\treturn result\n\t\t}\n\n\t\tfor (const variable of this.ctx.entryNode.variables) {\n\t\t\tif (!isVariableDefinition(variable)) continue\n\t\t\tif (!withQueryParam(variable)) continue\n\t\t\tif (\n\t\t\t\tvariable.type !== ControlType.String &&\n\t\t\t\tvariable.type !== ControlType.CollectionReference &&\n\t\t\t\tvariable.type !== ControlType.MultiCollectionReference\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlet initialValue: string | string[] | undefined\n\t\t\tswitch (variable.type) {\n\t\t\t\tcase ControlType.MultiCollectionReference:\n\t\t\t\t\tinitialValue = isArray(variable.initialValue) ? variable.initialValue : []\n\t\t\t\t\tbreak\n\t\t\t\tcase ControlType.CollectionReference:\n\t\t\t\t\tinitialValue = isString(variable.initialValue) ? variable.initialValue : \"\"\n\t\t\t\t\tbreak\n\t\t\t\tcase ControlType.String:\n\t\t\t\t\tinitialValue = variable.optional === true ? undefined : variable.initialValue\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(variable, \"Unexpected variable type\")\n\t\t\t}\n\n\t\t\tconst info: URLVariableInfo = {\n\t\t\t\tid: variable.id,\n\t\t\t\tparameterName: getQueryParamNameOfVariable(variable),\n\t\t\t\ttype: variable.type,\n\t\t\t\toptional: variable.type === ControlType.String ? (variable.optional === true ? true : undefined) : undefined,\n\t\t\t\tinitialValue,\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t(variable.type === ControlType.CollectionReference || variable.type === ControlType.MultiCollectionReference) &&\n\t\t\t\tvariable.dataIdentifier\n\t\t\t) {\n\t\t\t\tconst parsed = parseModuleIdentifier(variable.dataIdentifier)\n\t\t\t\tif (parsed && \"type\" in parsed && parsed.type === ModuleType.Collection) {\n\t\t\t\t\tinfo.collectionId = parsed.localIdName\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresult.set(variable.id, info)\n\t\t}\n\n\t\tthis.#urlVariableDefinitions = result\n\t\treturn result\n\t}\n}\n", "import { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport { isComputedValue } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type { FetchDataValue } from \"document/models/CanvasTree/traits/FetchDataValue.ts\"\nimport { fillVariablesInURL, patchFetchValue } from \"document/models/CanvasTree/traits/FetchDataValue.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { assert, assertNever } from \"library/utils/assert.ts\"\nimport type { AssetCollector } from \"./AssetCollector.ts\"\nimport type { LinkCollector } from \"./LinkCollector.ts\"\nimport type { VariableCollector } from \"./VariableCollector.ts\"\n\nexport function serializeFetchDataUrl(value: FetchDataValue, variables: VariableCollector) {\n\tconst usedVariables: VariableReference[] = []\n\tconst urlString = fillVariablesInURL(value, variable => {\n\t\tconst variableBinding = variables.create(variable)\n\n\t\tusedVariables.push(variable)\n\n\t\treturn \"${\" + variableBinding + \"}\"\n\t})\n\n\tconst templatedUrl = new SafeJS(\"`\" + urlString + \"`\")\n\n\treturn {\n\t\ttemplatedUrl,\n\t\tusedVariables,\n\t}\n}\n\nexport function serializeFallbackValue(\n\tcontrol: NonNullable<FetchDataValue[\"controlProp\"]>,\n\tvariables: VariableCollector,\n\tassets: AssetCollector,\n\tlinks: LinkCollector | undefined = undefined,\n) {\n\tif (isDynamicValue(control.value)) {\n\t\tassert(!isComputedValue(control.value), \"Computed values should not be possible in fetch fallback\")\n\n\t\treturn variables.create(control.value)\n\t}\n\tswitch (control.type) {\n\t\tcase ControlType.Color:\n\t\t\treturn control.value ? js`${control.value}` : js`undefined`\n\t\tcase ControlType.String:\n\t\t\treturn js`${control.value}`\n\t\tcase ControlType.Boolean:\n\t\t\treturn new SafeJS(control.value)\n\t\tcase ControlType.Number:\n\t\t\treturn new SafeJS(control.value)\n\t\tcase ControlType.Image: {\n\t\t\tif (control.value === undefined) return js`undefined`\n\n\t\t\tconst asset = assets.resolveResponsiveImage(control.value)\n\t\t\tif (!asset) return js`undefined`\n\n\t\t\treturn js`${asset.src}`\n\t\t}\n\t\tcase ControlType.Link: {\n\t\t\tif (!control.value || !links) {\n\t\t\t\t// In preloading context the LinkCollector for the fallbackValue is undefined.\n\t\t\t\t// The reason is that this fallback value is only used for rendering but we use a shared function for serializing fetches\n\t\t\t\t// We cannot resolve the fallback links in the preload context because it relies on resolving slugs asynchronously via Suspense\n\t\t\t\treturn js`undefined`\n\t\t\t}\n\n\t\t\tconst linkBinding = links.create(control.value)\n\t\t\tif (!linkBinding) return js`undefined`\n\n\t\t\treturn new SafeJS(serializeJS(linkBinding))\n\t\t}\n\t\tdefault:\n\t\t\tassertNever(control)\n\t}\n}\n\nexport function serializeFetchDataValue(\n\tfetchDataValue: FetchDataValue,\n\tvariables: VariableCollector,\n\tassets: AssetCollector,\n\tlinks: LinkCollector | undefined = undefined,\n) {\n\tconst { templatedUrl } = serializeFetchDataUrl(fetchDataValue, variables)\n\n\tconst safeValue = patchFetchValue(fetchDataValue)\n\n\treturn new SerializableObject({\n\t\turl: templatedUrl,\n\t\tresultKeyPath: fetchDataValue.resultKeyPath,\n\t\tfallbackValue: serializeFallbackValue(safeValue.controlProp, variables, assets, links),\n\t\terrorFallbackValue: safeValue.errorControlProp\n\t\t\t? serializeFallbackValue(safeValue.errorControlProp, variables, assets, links)\n\t\t\t: undefined,\n\t\tresultOutputType: safeValue.controlProp.type,\n\t\tcacheDuration: fetchDataValue.cacheDuration,\n\t\tcredentials: fetchDataValue.credentials,\n\t})\n}\n", "import type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\n\n/**\n * A node can depend on the resolved value of a promise. The data needed to\n * initiate those promises could be dependent on the resolved data from some\n * ancestor node. To build a precise dependency graph, we build a tree where\n * each node may request data that it's children may depend on. Child\n * PreloadNodes depend on the `value` of their parent. Meanwhile the fetches of\n * a node are stored as high as possible in the preload dependency tree, in\n * other words they are stored as a direct descendant of the node that provides\n * data the fetch depends on to initiate the request.\n */\nexport interface PreloadNode {\n\tid: NodeID\n\tvalue: SafeJS | undefined\n\tdependencies: Map<NodeID, VariableReference[]>\n\tusedVariables: VariableReference[]\n\tchildren: Map<NodeID, PreloadNode>\n\tfetches: SafeJS.Set\n\tvariantHasAnyFetches: boolean\n}\n\nfunction createPreloadNode(id: NodeID): PreloadNode {\n\treturn {\n\t\tid,\n\t\tvalue: undefined,\n\t\tdependencies: new Map(),\n\t\tusedVariables: [],\n\t\tchildren: new Map(),\n\t\tfetches: new SafeJS.Set(),\n\t\tvariantHasAnyFetches: false,\n\t}\n}\n\nexport function getOrCreatePreloadNode(map: Map<NodeID, PreloadNode>, id: NodeID): PreloadNode {\n\treturn map.get(id) ?? createPreloadNode(id)\n}\n\n/**\n * The path at which a PreloadNode should live in the tree is dependent on the\n * order of ancestor repeaters. We depend on this cache value being accurate at\n * the time of code-generation. In some cases we can optimize the minimum depth\n * to avoid unnecessary requests, in these cases we can trim repeater ids from\n * the path if they aren't providing any values needed to initiate the request.\n */\nexport function getPreloadPath(\n\tnode: CanvasNode,\n\tdependencies: Map<NodeID, VariableReference[]>,\n\toptimizeWaterfall: boolean,\n): NodeID[] {\n\tif (node.cache.ancestorRepeaterIds) {\n\t\tif (optimizeWaterfall) {\n\t\t\tconst path: NodeID[] = [...node.cache.ancestorRepeaterIds, node.id]\n\t\t\tfor (let index = node.cache.ancestorRepeaterIds.length - 1; index >= 0; index--) {\n\t\t\t\tconst element = node.cache.ancestorRepeaterIds[index]\n\t\t\t\tif (element && dependencies.has(element)) break\n\t\t\t\tpath.splice(index, 1)\n\t\t\t}\n\t\t\treturn path\n\t\t}\n\t\treturn [...node.cache.ancestorRepeaterIds, node.id]\n\t}\n\treturn [node.id]\n}\n\n/**\n * Create arguments for a function call, dropping undefined values.\n */\nexport function createArguments(...args: (SerializableValue | undefined)[]): SafeJS {\n\tconst out: string[] = []\n\tfor (const arg of args) {\n\t\tif (!arg) continue\n\t\tout.push(serializeJS(arg))\n\t}\n\treturn new SafeJS(out.join(\", \"))\n}\n\n/**\n * To avoid having to guarantee the order of arguments, we create a destructured\n * object to provide and read arguments from a list of variables.\n */\nexport function createDestructuredArguments(variables: SafeJS[]) {\n\tif (variables.length === 0) return\n\n\tconst result: Record<string, SafeJS> = {}\n\n\tfor (const variable of variables) {\n\t\tresult[serializeJS(variable)] = variable\n\t}\n\n\treturn result\n}\n\n/**\n * Values from repeaters are not prefixed by the id of the repeater, but\n * references to those variables are. Create a destructuring pattern that\n * aliases the variables.\n */\nexport function createDestructuredValue(\n\tcreateVariableBinding: (variable: VariableReference) => SafeJS,\n\tusedVariables: VariableReference[],\n): SerializableObject | SafeJS {\n\tif (usedVariables.length === 0) return js``\n\n\tconst result = new SerializableObject()\n\n\tfor (const variable of usedVariables) {\n\t\tresult[variable.id] = createVariableBinding(variable)\n\t}\n\n\treturn result\n}\n", "import { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport type { SerializableRecord } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { isStatusGestureVariant } from \"document/components/chrome/properties/utils/gestureStatusVariant.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isLayoutTemplateNode, isSmartComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { SafeFetchDataValue } from \"document/models/CanvasTree/traits/FetchDataValue.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { serializeFetchDataUrl, serializeFetchDataValue } from \"../utils/serializeFetchData.ts\"\nimport type { PreloadCollectorContext } from \"./PreloadCollectorContext.ts\"\nimport type { PreloadNode } from \"./PreloadNode.ts\"\nimport {\n\tcreateArguments,\n\tcreateDestructuredArguments,\n\tcreateDestructuredValue,\n\tgetOrCreatePreloadNode,\n\tgetPreloadPath,\n} from \"./PreloadNode.ts\"\n\nexport class VariantPreloadCollector {\n\tprivate preloadDependencyTree = new Map<NodeID, PreloadNode>()\n\n\tconstructor(private readonly ctx: PreloadCollectorContext) {}\n\n\t/**\n\t * Whether the entry node supports collecting preload data.\n\t * Both SmartComponents and LayoutTemplates can collect preload data.\n\t */\n\t#isComponentScope() {\n\t\treturn isSmartComponentNode(this.ctx.entryNode) || isLayoutTemplateNode(this.ctx.entryNode)\n\t}\n\n\t/**\n\t * Whether the entry node supports loading gesture variants.\n\t * Only SmartComponents support loading gestures. LayoutTemplates use\n\t * useHydratedBreakpointVariants which doesn't provide clearLoadingGesture\n\t * or setGestureState needed for the loading gesture hook.\n\t */\n\t#supportsLoadingGestures() {\n\t\treturn isSmartComponentNode(this.ctx.entryNode)\n\t}\n\n\taddQuery(node: CanvasNode, query: SerializableRecord, variables: VariableReference[]) {\n\t\tif (!this.#isComponentScope()) return\n\n\t\tconst { destructured, dependencies } = this.getVariableDependencies(variables)\n\n\t\tconst binding = js`(${createArguments(this.ctx.command(\"query\"), destructured)}) => ${SafeJS.fn(\n\t\t\tthis.ctx.command(\"query\"),\n\t\t\tquery,\n\t\t)}`\n\n\t\tthis.addStatement(\n\t\t\t\"query\",\n\t\t\tnode,\n\t\t\tdependencies,\n\t\t\tSafeJS.fn(this.ctx.declarations.dedupe(\"query\", binding), this.ctx.command(\"query\"), destructured),\n\t\t)\n\t}\n\n\taddFetch(node: CanvasNode, fetchValue: SafeFetchDataValue) {\n\t\tif (!this.#isComponentScope()) return\n\n\t\tconst { usedVariables } = serializeFetchDataUrl(fetchValue, this.ctx.variables)\n\n\t\tif (isVariableReference(fetchValue.controlProp.value)) {\n\t\t\tusedVariables.push(fetchValue.controlProp.value)\n\t\t}\n\n\t\tconst { destructured, dependencies } = this.getVariableDependencies(usedVariables)\n\t\tconst binding = js`(${createArguments(this.ctx.command(\"fetch\"), destructured)}) => ${SafeJS.fn(\n\t\t\tthis.ctx.command(\"fetch\"),\n\t\t\tserializeFetchDataValue(fetchValue, this.ctx.variables, this.ctx.assets, undefined),\n\t\t)}`\n\n\t\tthis.addStatement(\n\t\t\t\"fetch\",\n\t\t\tnode,\n\t\t\tdependencies,\n\t\t\tSafeJS.fn(this.ctx.declarations.dedupe(\"fetch\", binding), this.ctx.command(\"fetch\"), destructured),\n\t\t)\n\t}\n\n\t/**\n\t * Converts the tree of statements into a waterfall of promises.\n\t *\n\t * [\n\t *   query1(prequery, { fake_id_111 }).then(async (collection) => {\n\t *     await Promise.all(collection.flatMap(async ({ fake_id_67: fake_id_112fake_id_67 }) => [\n\t *       query3(prefetch, { fake_id_111 }),\n\t *       query5(prefetch, { fake_id_112fake_id_67 }),\n\t *     ]))}),\n\t *   query2(prequery),\n\t *   query4(prefetch),\n\t * ]\n\t */\n\tprivate createPromiseList({ fetches, children }: PreloadNode, topLevel = false) {\n\t\tconst list: SafeJS[] = []\n\n\t\t// When we create the promise list for the top level PreloadNode, we\n\t\t// need to incorporate the fetches. Otherwise we only incorporate\n\t\t// descendant fetches.\n\t\tif (topLevel) for (const fetch of fetches) list.push(fetch)\n\n\t\tfor (const [, childStatement] of children) {\n\t\t\tfor (const fetch of childStatement.fetches) list.push(fetch)\n\t\t\tif (!childStatement.value) continue\n\n\t\t\tconst base = childStatement.value\n\t\t\tif (childStatement.children.size === 0) {\n\t\t\t\tlist.push(base)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlist.push(\n\t\t\t\tjs`${base}.then(collection => Promise.all(collection.flatMap((${createDestructuredValue(\n\t\t\t\t\tvariable => this.ctx.variables.create(variable),\n\t\t\t\t\tchildStatement.usedVariables,\n\t\t\t\t)}) => (${this.createPromiseList(childStatement)}))))`,\n\t\t\t)\n\t\t}\n\n\t\treturn list\n\t}\n\n\t/**\n\t * Extract all of the recorded promises and create a call to a hook that\n\t * will allow the calling component to show a loading variant until the\n\t * promises for the base variant are resolved.\n\t *\n\t * Note: Only SmartComponents support loading gestures. LayoutTemplates use\n\t * useHydratedBreakpointVariants which doesn't provide clearLoadingGesture\n\t * or setGestureState needed for this hook.\n\t */\n\tgetHook() {\n\t\tif (!this.#supportsLoadingGestures()) {\n\t\t\treturn { variants: new Set<NodeID>(), hook: undefined }\n\t\t}\n\n\t\tconst statementsByVariant: Record<NodeID, SafeJS> = {}\n\n\t\t// Track all top-level variables used in the statements. These are\n\t\t// variables with the scope node as their provider id.\n\t\tconst variables: SafeJS[] = []\n\n\t\t// Track the variants that have statements. Variants without statements\n\t\t// won't flash a loading variant even if one is designed.\n\t\tconst variants = new Set<NodeID>()\n\n\t\t// Walk the preload dependency tree and create a Promise.all() statement\n\t\t// for each variant.\n\t\tfor (const [variantId, statement] of this.preloadDependencyTree) {\n\t\t\tif (statement.children.size === 0 && statement.fetches.size === 0) continue\n\n\t\t\t// If the variant has no fetches, we don't want to allow the\n\t\t\t// component to display a loading variant if one is designed. For\n\t\t\t// now, we simply won't record the promises. In the future we might\n\t\t\t// want to change this to support preloading other types of async\n\t\t\t// work, for instance to avoid suspense when transitioning between\n\t\t\t// pages. At that point we should not continue but instead exclude\n\t\t\t// the variantId from the variants Set.\n\t\t\tif (!statement.variantHasAnyFetches) continue\n\n\t\t\tvariants.add(variantId)\n\n\t\t\t// Gather all variables that should be provided by the component.\n\t\t\tconst usedVariables = statement.usedVariables.map(variable => this.ctx.variables.create(variable))\n\t\t\tvariables.push(...usedVariables)\n\n\t\t\t// Create a deduplicated function for each variant. If multiple\n\t\t\t// variants have the same queries, these functions can be reused.\n\t\t\tstatementsByVariant[variantId] = this.ctx.declarations.dedupe(\n\t\t\t\t\"preload\",\n\t\t\t\tjs`(${this.ctx.command(\"query\")}, ${this.ctx.command(\"fetch\")}, ${\n\t\t\t\t\tcreateDestructuredArguments(usedVariables) ?? js`props`\n\t\t\t\t}) => Promise.all(${this.createPromiseList(statement, true)})`,\n\t\t\t)\n\t\t}\n\n\t\tif (!variants.size) return { variants: new Set<NodeID>(), hook: undefined }\n\n\t\tconst statements = this.ctx.declarations.dedupe(\"preloadStatements\", statementsByVariant)\n\t\tconst React = this.ctx.imports.addImport(\"react\", { exportSpecifier: \"*\", importBinding: \"React\" })\n\t\tconst usePreloadQuery = this.ctx.imports.addImport(\"framer\", { exportSpecifier: \"usePreloadQuery\" })\n\t\tconst usePrefetch = this.ctx.imports.addImport(\"framer\", { exportSpecifier: \"usePrefetch\" })\n\t\tconst variant = js`variant`\n\t\tconst gestures = js`gestures`\n\t\tconst clearLoadingVariant = js`clearLoadingVariant`\n\t\tconst setGestureState = js`setGestureState`\n\n\t\t// Generate the hook that will import the bindings to preload queries,\n\t\t// and respond to the active variant changing to remove the loading\n\t\t// variant when the promises resolve.\n\t\tconst hook = this.ctx.declarations.dedupe(\n\t\t\t\"useLoadingVariant\",\n\t\t\tjs`(${variant}, ${gestures}, ${clearLoadingVariant}, ${setGestureState}, props?: Record<string, unknown>) => {${js.joinLines(\n\t\t\t\tjs`const prequery = ${SafeJS.fn(usePreloadQuery)}`,\n\t\t\t\tjs`const prefetch = ${SafeJS.fn(usePrefetch)}`,\n\t\t\t\tjs`${React}.useEffect(() => {${js.joinLines(\n\t\t\t\t\tjs`const promise = ${statements}[${variant}]`,\n\t\t\t\t\tjs`if (!promise || !${gestures}?.[${variant}]?.loading) return`,\n\t\t\t\t\tjs`promise(prequery, prefetch, props)`,\n\t\t\t\t\tjs`.then(() => ${SafeJS.fn(clearLoadingVariant)})`,\n\t\t\t\t\tjs`.catch(() => ${SafeJS.fn(setGestureState, { isError: true })})`,\n\t\t\t\t\t// We should only rerun the effect if the variant changes.\n\t\t\t\t\t// The props should change at the same time.\n\t\t\t\t)}}, [${variant}])`,\n\t\t\t)}}`,\n\t\t)\n\n\t\treturn {\n\t\t\tvariants,\n\t\t\t// Return the hook pre-instantiated with the arguments required.\n\t\t\thook: (gestureBinding: SafeJS) =>\n\t\t\t\tSafeJS.fn(\n\t\t\t\t\thook,\n\t\t\t\t\tVar.baseVariant,\n\t\t\t\t\tgestureBinding,\n\t\t\t\t\tVar.clearLoadingGesture,\n\t\t\t\t\tVar.setGestureState,\n\t\t\t\t\t// These variables are assumed to exist in the component since\n\t\t\t\t\t// they follow the expected naming convention (reusing the same\n\t\t\t\t\t// naming function).\n\t\t\t\t\tcreateDestructuredArguments(variables),\n\t\t\t\t),\n\t\t}\n\t}\n\n\t/**\n\t * Add a statement to the list of statements, based on it's path of ancestor\n\t * repeater ids.\n\t */\n\tprivate addStatement(\n\t\ttype: \"query\" | \"fetch\",\n\t\tnode: CanvasNode,\n\t\tdependencies: Map<NodeID, VariableReference[]>,\n\t\tvalue: SafeJS,\n\t) {\n\t\tconst variantId = this.ctx.getVariantIdFor(node)\n\t\tconst variant = this.ctx.tree.get(variantId)\n\t\t// Don't track promises if they are initiated by a loading or error variant.\n\t\tif (!variant || !isVariant(variant) || isStatusGestureVariant(variant.gesture)) return\n\n\t\tconst entry = getOrCreatePreloadNode(this.preloadDependencyTree, variant.id)\n\t\tif (type === \"fetch\") entry.variantHasAnyFetches = true\n\n\t\t// If the statement depends on variables provided by the component, add\n\t\t// them as dependencies right away.\n\t\tconst variablesProvidedByComponent = dependencies.get(this.ctx.entryNode.id)\n\t\tif (variablesProvidedByComponent) entry.usedVariables.push(...variablesProvidedByComponent)\n\n\t\t// Then walk the ancestor repeaters of the node from top to bottom,\n\t\t// creating or updating the entry at that path as we walk down, and\n\t\t// tracking dependencies along the way. Tracking dependencies makes the\n\t\t// final serialization simpler since we know which variables that an\n\t\t// ancestor provides must be declared so they are in-scope for\n\t\t// dependents.\n\t\tlet write = entry\n\t\tfor (const ancestorId of getPreloadPath(node, dependencies, type === \"fetch\")) {\n\t\t\tconst next = getOrCreatePreloadNode(write.children, ancestorId)\n\t\t\tif (ancestorId === node.id) {\n\t\t\t\tif (type === \"query\") next.value = value\n\t\t\t\tif (type === \"fetch\") next.fetches.add(value)\n\n\t\t\t\tfor (const [key, vars] of dependencies) {\n\t\t\t\t\tconst existing = next.dependencies.get(key) ?? []\n\t\t\t\t\texisting.push(...vars)\n\t\t\t\t\tnext.dependencies.set(key, existing)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst variableDependenciesFromAncestor = dependencies.get(ancestorId)\n\t\t\tif (variableDependenciesFromAncestor) next.usedVariables.push(...variableDependenciesFromAncestor)\n\t\t\twrite.children.set(ancestorId, next)\n\t\t\twrite = next\n\t\t}\n\n\t\tthis.preloadDependencyTree.set(variant.id, entry)\n\t}\n\n\tprivate getVariableDependencies(variables: VariableReference[]) {\n\t\tconst args: SafeJS[] = []\n\t\tconst dependencies = new Map<NodeID, VariableReference[]>()\n\t\tfor (const variable of variables) {\n\t\t\targs.push(this.ctx.variables.create(variable))\n\t\t\taddDependency(dependencies, variable.providerId ?? this.ctx.entryNode.id, variable)\n\t\t}\n\n\t\treturn { destructured: createDestructuredArguments(args), dependencies } as const\n\t}\n}\n\nfunction addDependency(\n\tdependencies: Map<NodeID, VariableReference[]>,\n\tproviderId: NodeID,\n\tvariable: VariableReference,\n) {\n\tconst dependenciesForVariable = dependencies.get(providerId) ?? []\n\tdependenciesForVariable.push(variable)\n\tdependencies.set(providerId, dependenciesForVariable)\n}\n", "import type { ModuleIdentifierString } from \"@framerjs/shared\"\nimport type { SerializableRecord } from \"code-generation/js/SerializableValue.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { CollectorEntryNode } from \"code-generation/types.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { SafeFetchDataValue } from \"document/models/CanvasTree/traits/FetchDataValue.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { AssetCollector } from \"../utils/AssetCollector.ts\"\nimport type { BindingCollector } from \"../utils/BindingCollector.ts\"\nimport type { FileDeclarationCollector } from \"../utils/DeclarationCollector.ts\"\nimport type { ImportCollector } from \"../utils/ImportCollector.ts\"\nimport { PreloadCollectorContext } from \"./PreloadCollectorContext.ts\"\nimport { type LoaderCode, RouteLoaderCollector } from \"./RouteLoaderCollector.ts\"\nimport { VariantPreloadCollector } from \"./VariantPreloadCollector.ts\"\nimport type { DetailPageQuery } from \"./buildRouteLoaderPlan.ts\"\n\n/**\n * The PreloadCollector manages preloading during React rendering (variantPreload) and for the React-independent loader API (routeLoader).\n *\n * The loader API enables recursive data loading that mirrors the React component tree.\n * Parent loaders call child loaders via forwardLoader(), passing props and resolved data.\n *\n * Supported by the loader API:\n *\n * | Source                              | Resolvable  | How                                        |\n * |-------------------------------------|-------------|--------------------------------------------|\n * | Detail page variables               | \u2705 Yes      | Chained: fetch detail query first          |\n * | URL variables (string)              | \u2705 Yes      | Read from context.pathVariables            |\n * | URL variables (collection)          | \u2705 Yes      | Resolve slug\u2192ID via context.collectionUtils|\n * | Nested (multi-)repeater variables   | \u2705 Yes      | Chain: parent query \u2192 map results \u2192 child  |\n * | Rich Text components                | \u274C Not yet  | Call child loaders of components           |\n * | Static props                        | \u274C Not yet  | Pass relevant props to forwardLoader()     |\n * | Fetch (feature)                     | \u274C Not yet  | Only those that can be cached              |\n */\n\nexport class PreloadCollector {\n\tprivate readonly ctx: PreloadCollectorContext\n\tprivate readonly routeLoader: RouteLoaderCollector\n\tprivate readonly variantPreload: VariantPreloadCollector\n\n\tconstructor(\n\t\tprivate readonly entryNode: CollectorEntryNode,\n\t\tprivate readonly tree: CanvasTree,\n\t\tprivate readonly variables: VariableCollector,\n\t\tprivate readonly declarations: FileDeclarationCollector,\n\t\tprivate readonly bindings: BindingCollector,\n\t\tprivate readonly imports: ImportCollector,\n\t\tprivate readonly assets: AssetCollector,\n\t) {\n\t\tthis.ctx = new PreloadCollectorContext(\n\t\t\tthis.entryNode,\n\t\t\tthis.tree,\n\t\t\tthis.variables,\n\t\t\tthis.declarations,\n\t\t\tthis.bindings,\n\t\t\tthis.imports,\n\t\t\tthis.assets,\n\t\t)\n\t\tthis.routeLoader = new RouteLoaderCollector(this.ctx)\n\t\tthis.variantPreload = new VariantPreloadCollector(this.ctx)\n\t}\n\n\taddDetailPageQuery(\n\t\tfrom: DetailPageQuery[\"from\"],\n\t\tselect: DetailPageQuery[\"select\"],\n\t\tcollectionAlias: DetailPageQuery[\"collectionAlias\"],\n\t): void {\n\t\tthis.routeLoader.addDetailPageQuery(from, select, collectionAlias)\n\t}\n\n\taddRouteLoaderQuery(\n\t\tnode: CanvasNode,\n\t\tquery: SerializableRecord,\n\t\tvariableDependencies: VariableReference[] = [],\n\t): SafeJS {\n\t\treturn this.routeLoader.addRouteLoaderQuery(node, query, variableDependencies)\n\t}\n\n\taddChildComponent(\n\t\tmoduleIdentifier: ModuleIdentifierString,\n\t\tstaticProps: SerializableRecord,\n\t\tnodeId: NodeID,\n\t\tancestorRepeaterId?: NodeID,\n\t): void {\n\t\tthis.routeLoader.addChildComponent(moduleIdentifier, staticProps, nodeId, ancestorRepeaterId)\n\t}\n\n\tgetRouteLoaderCode(): LoaderCode {\n\t\treturn this.routeLoader.getRouteLoaderCode()\n\t}\n\n\thasRouteLoaderQueries(): boolean {\n\t\treturn this.routeLoader.hasRouteLoaderQueries()\n\t}\n\n\tgetDetailPageQueryConstant(): SafeJS | undefined {\n\t\treturn this.routeLoader.getDetailPageQueryConstant()\n\t}\n\n\taddQuery(node: CanvasNode, query: SerializableRecord, variables: VariableReference[]) {\n\t\tthis.variantPreload.addQuery(node, query, variables)\n\t}\n\n\taddFetch(node: CanvasNode, fetchValue: SafeFetchDataValue) {\n\t\tthis.variantPreload.addFetch(node, fetchValue)\n\t}\n\n\tgetHook() {\n\t\treturn this.variantPreload.getHook()\n\t}\n}\n", "import type { NodeID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport type { SimulatedDOMCSSValue } from \"./cssValue.ts\"\nimport type { GridLayoutInfo } from \"./grid.ts\"\nimport type { SimulatedDOMNumberValue } from \"./numberValue.ts\"\nimport type { StackLayoutInfo } from \"./stack.ts\"\n\nexport class SimulatedDOMCache {\n\tprivate readonly cssWidthCache = new Map<NodeID, SimulatedDOMCSSValue>()\n\tprivate readonly heightCache = new Map<NodeID, SimulatedDOMNumberValue>()\n\tprivate readonly yPositionCache = new Map<NodeID, SimulatedDOMNumberValue>()\n\tprivate readonly verticalStackLayoutInfoCache = new Map<NodeID, StackLayoutInfo>()\n\tprivate readonly gridLayoutInfoCache = new Map<NodeID, GridLayoutInfo>()\n\tprivate readonly computationCache = new Map<string, unknown>()\n\n\tpublic getCSSWidth(nodeId: NodeID): SimulatedDOMCSSValue | undefined {\n\t\treturn this.cssWidthCache.get(nodeId)\n\t}\n\n\tpublic setCSSWidth(nodeId: NodeID, value: SimulatedDOMCSSValue) {\n\t\tthis.cssWidthCache.set(nodeId, value)\n\t}\n\n\tpublic getHeight(nodeId: NodeID): SimulatedDOMNumberValue | undefined {\n\t\treturn this.heightCache.get(nodeId)\n\t}\n\n\tpublic setHeight(nodeId: NodeID, value: SimulatedDOMNumberValue) {\n\t\tthis.heightCache.set(nodeId, value)\n\t}\n\n\tpublic getYPosition(nodeId: NodeID): SimulatedDOMNumberValue | undefined {\n\t\treturn this.yPositionCache.get(nodeId)\n\t}\n\n\tpublic setYPosition(nodeId: NodeID, value: SimulatedDOMNumberValue) {\n\t\tthis.yPositionCache.set(nodeId, value)\n\t}\n\n\tpublic getVerticalStackLayoutInfo(nodeId: NodeID): StackLayoutInfo | undefined {\n\t\treturn this.verticalStackLayoutInfoCache.get(nodeId)\n\t}\n\n\tpublic setVerticalStackLayoutInfo(nodeId: NodeID, value: StackLayoutInfo) {\n\t\tthis.verticalStackLayoutInfoCache.set(nodeId, value)\n\t}\n\n\tpublic getGridLayoutInfo(nodeId: NodeID): GridLayoutInfo | undefined {\n\t\treturn this.gridLayoutInfoCache.get(nodeId)\n\t}\n\n\tpublic setGridLayoutInfo(nodeId: NodeID, value: GridLayoutInfo) {\n\t\tthis.gridLayoutInfoCache.set(nodeId, value)\n\t}\n\n\t/** Memoize an arbitrary computation for the lifetime of the cache (= the duration of this codegen pass). */\n\tpublic memo<T>(key: string, callback: () => T): T {\n\t\tif (this.computationCache.has(key)) {\n\t\t\treturn this.computationCache.get(key) as T\n\t\t}\n\t\tconst value = callback()\n\t\tthis.computationCache.set(key, value)\n\t\treturn value\n\t}\n\n\tpublic testing = {\n\t\tgetCSSWidthCache: () => this.cssWidthCache,\n\t\tgetHeightCache: () => this.heightCache,\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { ComponentDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type { ValueTransformCollector } from \"code-generation/utils/valueTransformCollector/ValueTransformCollector.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isComputedValue } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport type { DynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { assertNever } from \"library/utils/assert.ts\"\nimport { SimulatedDOMCache } from \"./cache.ts\"\n\n// This will be extended to support width when we implement auto-sizing in simulateCSSWidth()\nclass WorkInProgressTracker {\n\tprivate heightNodes: Set<NodeID> = new Set()\n\n\tstartComputingHeightFor(nodeId: NodeID) {\n\t\tthis.heightNodes.add(nodeId)\n\t}\n\n\tisComputingHeightFor(nodeId: NodeID) {\n\t\treturn this.heightNodes.has(nodeId)\n\t}\n\n\tfinishComputingHeightFor(nodeId: NodeID) {\n\t\tthis.heightNodes.delete(nodeId)\n\t}\n}\n\n/**\n * Initializes a function that creates JavaScript bindings for dynamic values. Dynamic values in Framer can be either\n * variable references or computed values. Here\u2019s how they look in code-generated components:\n *\n * ```\n * function MySmartComponent({ stackDirectionVariable }) {\n *   stackDirectionVariable // \u2190 this is a variable reference\n *   convertEnumToString(stackDirectionVariable) // \u2190 this is a computed value (a variable reference wrapped by a transform)\n * }\n * ```\n *\n * This function returns a binding for the passed dynamic value. \u201CBinding\u201D simply means a SafeJS string that looks like\n * `\"stackDirectionVariable\"` or `\"convertEnumToString(stackDirectionVariable)\"`. We can use this string in the\n * code-generated `sizes` attribute to refer to the dynamic value.\n *\n * Note that we create the bindings in the collectors only if the variable is not already collected. We can't guarantee\n * that the bindings will be collected at this point (we could very well be collecting the image background before\n * we collect the flex layout). Calling .create() in both places won't result in redundant bindings with identical values\n * because the hash will be identical.\n */\nfunction initGetVariableBinding(\n\tvariables: VariableCollector,\n\tvalueTransforms: ValueTransformCollector,\n): GetVariableBinding {\n\treturn (value: DynamicValue, node: CanvasNode, outputControl: ControlDescription | undefined = undefined) => {\n\t\tif (isComputedValue(value)) {\n\t\t\treturn valueTransforms.createComputedValue(value, node, outputControl)\n\t\t}\n\n\t\tif (isVariableReference(value)) {\n\t\t\treturn variables.create(value)\n\t\t}\n\n\t\tassertNever(value, \"all dynamic values should be handled above\")\n\t}\n}\n\ntype GetVariableBinding = (value: DynamicValue, node: CanvasNode) => SafeJS\n\n/**\n * SimulationContext reduces prop drilling by grouping all dependencies used by various simulated DOM functions\n * into one object. This is basically like JSXContext, but for simulated DOM.\n */\nexport interface SimulationContext {\n\ttree: CanvasTree\n\tcomponentLoader: ComponentLoader\n\tcache: SimulatedDOMCache\n\tgetVariableBinding: GetVariableBinding\n\tworkInProgress: WorkInProgressTracker\n\timports: ImportCollector\n\tdeclarations: ComponentDeclarationCollector\n}\n\nexport function createSimulationContext(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tvariables: VariableCollector,\n\tvalueTransforms: ValueTransformCollector,\n\timports: ImportCollector,\n\tdeclarations: ComponentDeclarationCollector,\n): SimulationContext {\n\treturn {\n\t\ttree,\n\t\tcomponentLoader,\n\t\tcache: new SimulatedDOMCache(),\n\t\tworkInProgress: new WorkInProgressTracker(),\n\t\tgetVariableBinding: initGetVariableBinding(variables, valueTransforms),\n\t\timports,\n\t\tdeclarations,\n\t}\n}\n", "/** This exception helps to exit multiple levels of recursive calculation early when we encounter an unsupported case. */\nexport class CantCalculate extends Error {\n\t// biome-ignore lint/complexity/noUselessConstructor: done for easier debugging\n\tconstructor(...args: ConstructorParameters<typeof Error>) {\n\t\tsuper(...args)\n\t\t// Tip for developers: put a breakpoint here to see where the error is thrown from\n\t}\n}\n", "import { jst } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { serializesToSameValue } from \"code-generation/jsx/serializesToSameValue.ts\"\nimport type { CSSUnit } from \"document/models/CanvasTree/traits/utils/CSSDimension.ts\"\nimport { assertNever } from \"library/utils/assert.ts\"\nimport type { SimulatedDOMNumberValue } from \"./numberValue.ts\"\n\n/**\n * Intermediate representation of a value in simulated DOM calculations.\n * Only used in calculations that return a CSS expression string \u2013 that is,\n * a string that can be passed into `calc()` or `<img sizes>`. Today, the only\n * such calculation is `computeCSSWidth`.\n */\nexport type SimulatedDOMCSSValue = CSSConstValue | CSSOpValue | CSSTemplateValue\n\ntype CSSConstUnit = Extract<CSSUnit, \"%\" | \"px\" | \"vw\"> | undefined\n\n/**\n * Intermediate representation of a constant in simulated DOM calculations.\n * E.g. the value of 5px would be represented as { type: \"const\", expr: \"5px\", value: 5, unit: \"px\" }.\n */\ninterface CSSConstValue<Unit extends CSSConstUnit = CSSConstUnit> {\n\ttype: \"css-const\"\n\texpr: string\n\tvalue: number\n\tunit: Unit\n}\n\n/**\n * Intermediate representation of an operation in simulated DOM calculations.\n * E.g. \u201C10vw - 200px\u201D would be represented as { type: \"op\", expr: \"10vw - 200px\", op: \"-\", left: { type: \"const\", expr: \"10vw\", ... }, right: { type: \"const\", expr: \"200px\", ... } }.\n */\ninterface CSSOpValue {\n\ttype: \"css-op\"\n\texpr: SafeJS | string\n\top: \"+\" | \"-\" | \"*\" | \"/\" | \"min\" | \"max\"\n\tleft: SimulatedDOMCSSValue\n\tright: SimulatedDOMCSSValue\n}\n\n/**\n * Intermediate representation of an expression that references some codegenerated variables.\n * E.g. `stackDirection === \"horizontal\" ? \"10vw\" : \"200px\"` would be represented as { type: \"template\", expr: js`${stackDirectionVarName} === \"horizontal\" ? \"10vw\" : \"200px\"` }.\n */\ninterface CSSTemplateValue {\n\ttype: \"css-template\"\n\texpr: SafeJS | string\n}\n\nexport function cssConst(value: number): CSSConstValue<undefined>\nexport function cssConst<Unit extends CSSConstUnit = CSSConstUnit>(value: number, unit: Unit): CSSConstValue<Unit>\nexport function cssConst<Unit extends CSSConstUnit = CSSConstUnit>(\n\tvalue: number,\n\tunit?: Unit,\n): CSSConstValue<Unit | undefined> {\n\tconst roundedValue = Math.round(value * 10000) / 10000\n\treturn { type: \"css-const\", expr: unit ? `${roundedValue}${unit}` : `${roundedValue}`, value, unit }\n}\n\nconst invertedOps = { \"+\": \"-\", \"-\": \"+\", \"*\": \"/\", \"/\": \"*\" } as const\n\nexport function cssOp(\n\top: CSSOpValue[\"op\"],\n\tleft: SimulatedDOMCSSValue,\n\tright: SimulatedDOMCSSValue,\n): SimulatedDOMCSSValue {\n\tif (left.type === \"css-const\" && right.type === \"css-const\") {\n\t\tif (left.unit === right.unit) {\n\t\t\t// For addition/subtraction/min/max we can statically calculate the result if we\n\t\t\t// have two constant values that have the same unit.\n\t\t\tif (op === \"+\") return cssConst(left.value + right.value, left.unit)\n\t\t\tif (op === \"-\") return cssConst(left.value - right.value, left.unit)\n\t\t\tif (op === \"min\") return cssConst(Math.min(left.value, right.value), left.unit)\n\t\t\tif (op === \"max\") return cssConst(Math.max(left.value, right.value), left.unit)\n\t\t} else if (isAddOrSub(op) && (left.value === 0 || right.value === 0)) {\n\t\t\t// Additionally, for addition/subtraction, if one of the constant\n\t\t\t// values is zero, we can just use the other value, even if the two\n\t\t\t// values have different units.\n\t\t\treturn right.value !== 0 ? right : left\n\t\t}\n\n\t\tif (op === \"*\" && (!left.unit || !right.unit)) {\n\t\t\t// Multiplication can be done commutatively between one unit\n\t\t\t// value and one unitless value.\n\t\t\treturn cssConst(left.value * right.value, left.unit || right.unit)\n\t\t} else if (op === \"/\" && !right.unit) {\n\t\t\t// Division can always be done as long as the right operand does not have a unit.\n\t\t\treturn cssConst(left.value / right.value, left.unit)\n\t\t}\n\t}\n\t// Simplify no-ops into just returning the left or right operand.\n\tif (isAddOrSub(op)) {\n\t\tif (right.type === \"css-const\" && right.value === 0) {\n\t\t\treturn left\n\t\t} else if (left.type === \"css-const\" && left.value === 0) {\n\t\t\treturn right\n\t\t}\n\t} else if (isMulOrDiv(op)) {\n\t\tif (right.type === \"css-const\" && right.value === 1) {\n\t\t\treturn left\n\t\t} else if (left.type === \"css-const\" && left.value === 1) {\n\t\t\treturn right\n\t\t}\n\t} else if (op === \"min\" || op === \"max\") {\n\t\tif (left.type === \"css-op\" && left.op === op && isEitherBranchEqual(left, right)) {\n\t\t\t// Turn expressions such as `min(min(x, y), y)` or `min(min(y, x), y)` into `min(x, y)`.\n\t\t\treturn left\n\t\t} else if (right.type === \"css-op\" && right.op === op && isEitherBranchEqual(right, left)) {\n\t\t\t// Turn expressions such as `min(y, min(x, y))` or `min(y, min(y, x))` into `min(x, y)`.\n\t\t\treturn right\n\t\t} else if (serializesToSameValue(left.expr, right.expr)) {\n\t\t\t// Turn expressions such as `min(x, x)` into `x`.\n\t\t\treturn left\n\t\t}\n\t}\n\t// If we have an operation like (X + Y) + Z, and (X + Y) cannot be\n\t// turned into a constant (it becomes an expression when flattened),\n\t// attempt to change the operation to X + (Z + Y) instead.\n\t//\n\t// TODO: We should support moving the left sub-operand too.\n\tif (left.type === \"css-op\" && left.right.type === \"css-const\") {\n\t\tif (isAddOrSub(op) && isAddOrSub(left.op)) {\n\t\t\t// Example:\n\t\t\t// 1. (max(\u2026) + 5px) - 20px\n\t\t\t// 2. max(\u2026) - (20px - 5px)\n\t\t\t// 3. max(\u2026) - 15px\n\t\t\tright = cssOp(op === \"+\" ? left.op : invertedOps[left.op], right, left.right)\n\t\t\tleft = left.left\n\t\t} else if (isMulOrDiv(op) && isMulOrDiv(left.op)) {\n\t\t\t// Example:\n\t\t\t// 1. (max(\u2026) * 10) / 5\n\t\t\t// 2. max(\u2026) / (5 / 10)\n\t\t\t// 3. max(\u2026) / 0.5\n\t\t\tright = cssOp(op === \"*\" ? left.op : invertedOps[left.op], right, left.right)\n\t\t\tleft = left.left\n\t\t}\n\t}\n\t// One or both sides of the operation contain an expression or units that need to be resolved at runtime.\n\tlet expr: SafeJS | string\n\tif (isAddOrSub(op)) {\n\t\tif (right.type === \"css-const\" && right.value < 0) {\n\t\t\t// Turn `x + -10` into `x - 10` and `x - -10` into `x + 10`.\n\t\t\top = invertedOps[op]\n\t\t\tright = cssConst(-right.value, right.unit)\n\t\t}\n\t\tif (op === \"+\") {\n\t\t\texpr = jst`${wrapIfAddOrSub(left)} + ${right.expr}`\n\t\t} else if (op === \"-\") {\n\t\t\tif (right.type === \"css-op\" && !isCallOp(right.op)) {\n\t\t\t\t// Always add parentheses around right operand expressions in a subtraction.\n\t\t\t\texpr = jst`${wrapIfAddOrSub(left)} - (${right.expr})`\n\t\t\t} else {\n\t\t\t\texpr = jst`${wrapIfAddOrSub(left)} - ${wrapIfAddOrSub(right)}`\n\t\t\t}\n\t\t} else {\n\t\t\tassertNever(op)\n\t\t}\n\t} else if (isMulOrDiv(op)) {\n\t\tif (right.type === \"css-const\" && right.value < 1) {\n\t\t\t// We may be able to make the multiplication/division cleaner by\n\t\t\t// inversing it (for example, turning `* 0.25` into `/ 4`, or `/ 0.1`\n\t\t\t// into `* 10`).\n\t\t\tconst inverseRight = cssConst(1 / right.value, right.unit)\n\t\t\tif (inverseRight.expr.length < right.expr.length) {\n\t\t\t\top = invertedOps[op]\n\t\t\t\tright = inverseRight\n\t\t\t}\n\t\t}\n\t\tif (op === \"/\" && right.type === \"css-op\" && !isCallOp(right.op)) {\n\t\t\t// Always add parentheses around right operand expressions in a division.\n\t\t\texpr = jst`${wrapIfAddOrSub(left)} / (${right.expr})`\n\t\t} else {\n\t\t\texpr = jst`${wrapIfAddOrSub(left)} ${op} ${wrapIfAddOrSub(right)}`\n\t\t}\n\t} else if (isCallOp(op)) {\n\t\texpr = jst`${op}(${left.expr}, ${right.expr})`\n\t} else {\n\t\tassertNever(op, `unhandled op ${op}`)\n\t}\n\treturn { type: \"css-op\", expr, op, left, right }\n}\n\nexport function cssValueFromNumberValue(value: SimulatedDOMNumberValue): SimulatedDOMCSSValue {\n\tswitch (value.type) {\n\t\tcase \"number-const\":\n\t\t\treturn cssConst(value.value, \"px\")\n\t\tcase \"number-template\":\n\t\t\treturn cssTemplate(value.expr)\n\t\tdefault:\n\t\t\tassertNever(value)\n\t}\n}\n\nexport function cssTemplate(expr: SafeJS | string): CSSTemplateValue {\n\treturn { type: \"css-template\", expr }\n}\n\nfunction isAddOrSub(op: CSSOpValue[\"op\"]): op is \"+\" | \"-\" {\n\treturn op === \"+\" || op === \"-\"\n}\n\nfunction isMulOrDiv(op: CSSOpValue[\"op\"]): op is \"*\" | \"/\" {\n\treturn op === \"*\" || op === \"/\"\n}\n\nfunction isCallOp(op: CSSOpValue[\"op\"]): op is \"min\" | \"max\" {\n\treturn op === \"min\" || op === \"max\"\n}\n\nfunction isEitherBranchEqual(op: CSSOpValue, value: SimulatedDOMCSSValue): boolean {\n\treturn serializesToSameValue(op.left.expr, value.expr) || serializesToSameValue(op.right.expr, value.expr)\n}\n\nfunction wrapIfAddOrSub(value: SimulatedDOMCSSValue): SafeJS | string {\n\treturn value.type === \"css-op\" && isAddOrSub(value.op) ? jst`(${value.expr})` : value.expr\n}\n\nexport function wrapInCalcExpressionIfNeeded(value: SimulatedDOMCSSValue) {\n\tif (value.type === \"css-template\" || value.type === \"css-const\" || (value.type === \"css-op\" && isCallOp(value.op))) {\n\t\t// No need to wrap constant values or function calls in calc(\u2026).\n\t\treturn value.expr\n\t}\n\n\treturn jst`calc(${value.expr})`\n}\n", "import type { DataDefinition, VerifiedControlDescription } from \"@framerjs/framer-runtime\"\nimport type { SandboxDataDefinition } from \"@framerjs/framer-runtime/sandbox\"\nimport { assert } from \"@framerjs/shared\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport type { CombinedVariableProviderValueMap } from \"../VariableProvider.ts\"\nimport type { VariableReference } from \"../VariableReference.ts\"\nimport type { CollectionFilterData, CollectionFilterOperator } from \"../WithCollectionOptions.ts\"\nimport { defaultFiltersOperator } from \"../WithCollectionOptions.ts\"\nimport { applyValueTransform } from \"./applyValueTransform.ts\"\n\nexport interface CollectionFilterVariableGetters {\n\tgetVariableControlByKey: (key: string) => VerifiedControlDescription | undefined\n\tgetVariableReferenceValue: (ref: VariableReference) => unknown\n}\n\nexport function isCollectionItemIncluded(\n\tfilterData: CollectionFilterData,\n\tfiltersOperator: CollectionFilterOperator | undefined,\n\tgetItemValue: (itemKey: string) => unknown,\n\tvariableGetters: CollectionFilterVariableGetters,\n\tvariableOverrides: CombinedVariableProviderValueMap | undefined,\n\tdataDefinition: DataDefinition | SandboxDataDefinition | null,\n): boolean {\n\tconst operator = filtersOperator ?? defaultFiltersOperator\n\n\tif (!dataDefinition) return true\n\n\tconst filters = filterData.filters.filter(filter => {\n\t\t// Remove any inactive filters\n\t\tif (!filter.itemKey) return false\n\n\t\t// Remove any filters where control is missing or of an unexpected type\n\t\tconst control = dataDefinition.properties[filter.itemKey]\n\t\tif (!control) return false\n\t\tif (control.type !== ControlType.Boolean && filter.transforms.length === 0) return false\n\n\t\treturn true\n\t})\n\n\t// .some on an empty array is always false\n\tif (filters.length === 0) return true\n\n\treturn filters[operator === \"all\" ? \"every\" : \"some\"](filter => {\n\t\tconst itemKey = filter.itemKey\n\t\tassert(itemKey !== null, \"itemKey should not be null\")\n\n\t\tconst control = dataDefinition.properties[itemKey]\n\t\tassert(control, \"control should exist\")\n\n\t\tconst value = getItemValue(itemKey)\n\t\tconst inputControl = variableGetters.getVariableControlByKey(itemKey)\n\n\t\treturn filter.transforms.reduce((lastValue, valueTransform) => {\n\t\t\treturn applyValueTransform(\n\t\t\t\tlastValue,\n\t\t\t\tvalueTransform,\n\t\t\t\tvariableGetters,\n\t\t\t\tvariableOverrides,\n\t\t\t\tinputControl,\n\t\t\t\tundefined,\n\t\t\t\tundefined, // locale doesn't effect collection item filtering\n\t\t\t)\n\t\t}, value)\n\t})\n}\n\nexport function applyCollectionFilters(\n\tfilterData: CollectionFilterData | undefined,\n\tfiltersOperator: CollectionFilterOperator | undefined,\n\tlist: Record<string, unknown>[],\n\tvariableGetters: CollectionFilterVariableGetters,\n\tvariableOverrides: CombinedVariableProviderValueMap | undefined,\n\tdataDefinition: DataDefinition | SandboxDataDefinition | null,\n): Record<string, unknown>[] {\n\tif (!filterData) return list\n\treturn list.filter(record =>\n\t\tisCollectionItemIncluded(\n\t\t\tfilterData,\n\t\t\tfiltersOperator,\n\t\t\tkey => record[key],\n\t\t\tvariableGetters,\n\t\t\tvariableOverrides,\n\t\t\tdataDefinition,\n\t\t),\n\t)\n}\n", "import type { DataDefinition } from \"@framerjs/framer-runtime\"\nimport type { SandboxDataDefinition } from \"@framerjs/framer-runtime/sandbox\"\nimport type { CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport type { CombinedVariableProviderValueMap } from \"../VariableProvider.ts\"\nimport type { WithCollectionOptions } from \"../WithCollectionOptions.ts\"\nimport { applyCollectionFilters } from \"./applyCollectionFilters.ts\"\n\nfunction reverseArray<T>(list: T[], reverse: boolean | undefined): T[] {\n\treturn reverse ? Array.from(list).reverse() : list\n}\n\nfunction offsetArray<T>(list: T[], offset: number | undefined): T[] {\n\tif (offset === undefined) return list\n\tif (offset === 0) return list\n\tconst listCopy = Array.from(list)\n\tlistCopy.splice(0, offset)\n\treturn listCopy\n}\n\nfunction limitArrayLength<T>(list: T[], maxLength: number): T[] {\n\tif (list.length <= maxLength) return list\n\treturn list.slice(0, maxLength)\n}\n\nexport const enum CollectionOptionsToApply {\n\tNone = 0,\n\tFilters = 1 << 0,\n\tReverse = 1 << 1,\n\tStartOffset = 1 << 2,\n\tLimitAndPageSize = 1 << 3,\n\tAll = Filters | Reverse | StartOffset | LimitAndPageSize,\n}\n\nexport function applyCollectionOptions(\n\tdataRepeater: CanvasNode & WithCollectionOptions,\n\tlist: Record<string, unknown>[],\n\tvariableOverrides: CombinedVariableProviderValueMap | undefined,\n\tdataDefinition: DataDefinition | SandboxDataDefinition | null,\n\toptionsToApply: CollectionOptionsToApply = CollectionOptionsToApply.All,\n): Record<string, unknown>[] {\n\tif (optionsToApply & CollectionOptionsToApply.Filters) {\n\t\tlist = applyCollectionFilters(\n\t\t\tdataRepeater.collectionFilters,\n\t\t\tdataRepeater.collectionFiltersOperator,\n\t\t\tlist,\n\t\t\tdataRepeater.cache,\n\t\t\tvariableOverrides,\n\t\t\tdataDefinition,\n\t\t)\n\t}\n\n\tif (optionsToApply & CollectionOptionsToApply.Reverse) {\n\t\tlist = reverseArray(list, dataRepeater.collectionReverse)\n\t}\n\n\tif (optionsToApply & CollectionOptionsToApply.StartOffset) {\n\t\tlist = offsetArray(list, dataRepeater.collectionStartOffset)\n\t}\n\n\tif (optionsToApply & CollectionOptionsToApply.LimitAndPageSize) {\n\t\tconst collectionLimit = dataRepeater.collectionLimit ?? Infinity\n\t\tconst collectionPaginationPageSize = dataRepeater.collectionPaginationPageSize ?? Infinity\n\t\tconst maxLength = Math.min(collectionLimit, collectionPaginationPageSize)\n\t\tlist = limitArrayLength(list, maxLength)\n\t}\n\n\treturn list\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport type { DataRepeater } from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport { isDataRepeater } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isFixedOrRelativeOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { isResponsiveImage } from \"document/models/CanvasTree/traits/ResponsiveImage.ts\"\nimport { withDOMLayout } from \"document/models/CanvasTree/traits/WithDOMLayout.ts\"\nimport type { WithFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { withItemsOrder } from \"document/models/CanvasTree/traits/WithItemsOrder.ts\"\nimport type { HasGridLayout, HasStackLayout, WithLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { withPadding } from \"document/models/CanvasTree/traits/WithPadding.ts\"\nimport type { WithSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport type { WithSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { withVisibility } from \"document/models/CanvasTree/traits/WithVisibility.ts\"\nimport {\n\tCollectionOptionsToApply,\n\tapplyCollectionOptions,\n} from \"document/models/CanvasTree/traits/utils/applyCollectionOptions.ts\"\nimport { getPixelDimensionsFromImageSrc } from \"document/models/CanvasTree/traits/utils/getPixelDimensionsFromImageSrc.ts\"\nimport {\n\tcanBePositionAbsolute,\n\tcanBePositionFixed,\n\tisPositionAbsolute,\n\tisPositionFixed,\n} from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { DimensionType } from \"library/index.ts\"\nimport { isNonNull } from \"utils/typeChecks.ts\"\nimport { CantCalculate } from \"./CantCalculate.ts\"\nimport type { SimulationContext } from \"./SimulationContext.ts\"\n\n/**\n * Some of the nodes in the tree might depend on the viewport height. Since we don\u2019t know how tall the viewport\n * will be at runtime, we approximate it to be 1000px.\n *\n * Why 1000px? Because height algos in simulated DOM were created to put `loading=\"lazy\"` on images outside of\n * the viewport. And for lazy-loaded images, it\u2019s better to underoptimize than overoptimize \u2013 otherwise, we\n * might lazy-load some critical images.\n *\n * We might adjust this value in the future as we add more optimizations. Or perhaps make it an argument to\n * the layout algorithm.\n */\nexport const VIEWPORT_HEIGHT = 1000\n\nconst Indeterminate = Symbol(\"Affects Layout: Indeterminate\")\nexport function isIndeterminate(value: unknown): value is typeof Indeterminate {\n\treturn value === Indeterminate\n}\n\n/**\n * Returns `false` if the `node` doesn\u2019t move any siblings around in the stack or the grid\n * (e.g. it\u2019s absolutely positioned or just hidden).\n *\n * @param whenVisibilityIsDynamic determines how the function should treat nodes which are visible\n * or hidden based on a variable: should it return the currently resolved value (which might\n * actually be different during runtime), or should it return `Indeterminate` to let the caller make\n * the right decision?\n */\nexport function nodeAffectsSiblings(\n\tnode: CanvasNode,\n\tparentNode: CanvasNode,\n\ttree: CanvasTree,\n\tresolveDynamicVisibility: true,\n): boolean\nexport function nodeAffectsSiblings(\n\tnode: CanvasNode,\n\tparentNode: CanvasNode,\n\ttree: CanvasTree,\n\tresolveDynamicVisibility: false,\n): typeof Indeterminate | boolean\nexport function nodeAffectsSiblings(\n\tnode: CanvasNode,\n\tparentNode: CanvasNode,\n\ttree: CanvasTree,\n\tresolveDynamicVisibility: boolean,\n) {\n\t// Overlay nodes do not affect layout calculations\n\tif (isFixedOrRelativeOverlay(node)) return false\n\n\t// Absolute-positioned and fixed-positioned nodes don\u2019t affect the layout calculations\n\tif (canBePositionAbsolute(node, parentNode) && isPositionAbsolute(node)) return false\n\tif (canBePositionFixed(tree, node) && isPositionFixed(node)) return false\n\n\t// Invisible nodes don\u2019t affect the layout calculations\n\tif (withVisibility(node) && node.visible === false) return false\n\n\t// Nodes which visibility is controlled with a variable *do* affect\n\t// the layout calculation, but we don\u2019t know the variable value\n\t// ahead of time. In this case, we delegate decision making to the caller:\n\t// some callers would prefer to know that visibility is mixed (so they can\n\t// make the right decision), and some would prefer to simply use the resolved value.\n\tif (withVisibility(node) && isDynamicValue(node.visible)) {\n\t\treturn resolveDynamicVisibility ? node.isVisible() : Indeterminate\n\t}\n\n\treturn true\n}\n\nexport function getNodePaddingTop(node: CanvasNode) {\n\tif (!withPadding(node)) return 0\n\n\t// FIXME: Variable support isn\u2019t implemented at the moment\n\tif (isDynamicValue(node.padding)) throw new CantCalculate()\n\n\tif (node.paddingPerSide) return node.paddingTop ?? 0\n\n\treturn node.padding ?? 0\n}\n\nexport function getNodePaddingBottom(node: CanvasNode) {\n\tif (!withPadding(node)) return 0\n\n\t// FIXME: Variable support isn\u2019t implemented at the moment\n\tif (isDynamicValue(node.padding)) throw new CantCalculate()\n\n\tif (node.paddingPerSide) return node.paddingBottom ?? 0\n\n\treturn node.padding ?? 0\n}\n\nexport function resolveGap(gap: WithLayout[\"gap\"]) {\n\t// FIXME: Variable support isn\u2019t implemented at the moment\n\tif (isDynamicValue(gap)) return 0\n\treturn gap ?? 0\n}\n\nconst emptyChildren: CanvasNode[] = []\n/**\n * Returns the children of a node in the way they would actually be rendered on the page.\n * That is, it returns the children taking into account:\n * - data repeaters (one tree node \u2192 multiple rendered nodes)\n * - order overrides (node.children[5] being rendered as child 1 due to `order: 1`)\n *\n * Note: the algo doesn\u2019t support the latest changes around data repeaters; see https://github.com/framer/company/issues/30001\n */\nexport function getLayoutChildren(\n\tcomponentLoader: AnyComponentLoader,\n\tnode: CanvasNode & (HasStackLayout | HasGridLayout),\n): CanvasNode[] {\n\tconst orderedChildren =\n\t\t(withItemsOrder(node) ? node.getChildrenInVisualOrder() : node.children?.toArray()) ?? emptyChildren\n\n\tif (isDataRepeater(node)) {\n\t\tconst repeatedChildIndex = getRepeatedChildIndex(node, orderedChildren)\n\t\tif (repeatedChildIndex === null) return orderedChildren\n\n\t\tconst repeatedChild = orderedChildren[repeatedChildIndex]\n\t\tif (!repeatedChild) return orderedChildren\n\n\t\tconst count = getDataRepeaterItemsCount(componentLoader, node)\n\n\t\treturn orderedChildren\n\t\t\t.slice(0, repeatedChildIndex)\n\t\t\t.concat(Array<CanvasNode>(count).fill(repeatedChild))\n\t\t\t.concat(orderedChildren.slice(repeatedChildIndex + 1))\n\t}\n\n\treturn orderedChildren\n}\n\nfunction getRepeatedChildIndex(node: DataRepeater, orderedChildren: CanvasNode[]): number | null {\n\t// When `repeatedItemId` is set, we do *not* fallback to any other child.\n\tif (node.repeatedItemId !== undefined) {\n\t\tconst index = orderedChildren.findIndex(child => child.getPrimaryId() === node.repeatedItemId)\n\t\treturn index === -1 ? null : index\n\t}\n\n\t// When `collectionRepeatedItemId` is set, we fallback to the first child.\n\tif (node.collectionRepeatedItemId !== undefined) {\n\t\tconst index = orderedChildren.findIndex(child => child.getPrimaryId() === node.collectionRepeatedItemId)\n\t\treturn index === -1 ? 0 : index\n\t}\n\n\treturn 0\n}\n\nfunction getDataRepeaterItemsCount(componentLoader: AnyComponentLoader, node: DataRepeater): number {\n\t// When a collection has filters, we can\u2019t filter it at this point (outside of the sandbox)\n\t// because we don\u2019t have the actual collection data. To work around that, we assume every\n\t// collection with filters has been filtered to a single item.\n\t//\n\t// Why 1? Because as of Jan 2025, for the purposes of optimizations that simulated DOM does,\n\t// it\u2019s better than other values:\n\t// - Not applying filters at all (and simulating DOM as if the whole collection is there)\n\t//   is silly. Collections commonly exceed 100 or even 1000 items, and it\u2019s filters that get\n\t//   them down to a reasonable number. Without filters, the simulated DOM would be unnecessarily large\n\t//   and incorrect.\n\t// - Returning 0 will lead to runtime assertions, such as the one here: https://github.com/framer/FramerStudio/pull/20250\n\t// - It\u2019s better to stick to lower values than to higher ones. Sticking with lower values might\n\t//   lead to underoptimizing (in <img sizes>: this might lead to the algorithm assuming that the\n\t//   image in a stack has fewer siblings than it actually has, making the image too large; in\n\t//   loading=lazy: this might lead to the algorithm assuming that the image is located inside\n\t//   the viewport, making the image not lazy-loadable). But it\u2019s better than the alternative\n\t//   where we assume that every filtered collection has been filtered to e.g. 100 items, and\n\t//   that makes some images too small and blurry (in <img sizes>), or lazy-loads some critical\n\t//   LCP images (in loading=lazy).\n\tif ((node.collectionFilters?.filters?.length ?? 0) > 0) return 1\n\n\tconst dataDefinition = componentLoader.dataForIdentifier(node.dataIdentifier)\n\tconst itemToSlug = dataDefinition?.itemToSlug ?? {}\n\tconst dataEntriesCount = Object.keys(itemToSlug).length\n\n\tconst fakeData = Array<Record<string, unknown>>(dataEntriesCount).fill({})\n\tconst fakeDataWithLimitsPaginationEtc = applyCollectionOptions(\n\t\tnode,\n\t\tfakeData,\n\t\tundefined,\n\t\tdataDefinition,\n\t\t// Don\u2019t apply filters because they were handled above\n\t\tCollectionOptionsToApply.All & ~CollectionOptionsToApply.Filters,\n\t)\n\n\treturn fakeDataWithLimitsPaginationEtc.length\n}\n\n/**\n * Calculates the aspect ratio to be used to calculate the real size of the fit image dimension.\n */\nexport function getFitImageAspectRatio(node: CanvasNode & WithFill) {\n\tconst resolvedFillImage = node.resolveValue(\"fillImage\")\n\n\tconst src = isResponsiveImage(resolvedFillImage) ? resolvedFillImage.src : resolvedFillImage\n\n\tif (!src) {\n\t\treturn undefined\n\t}\n\n\tconst pixelSize = getPixelDimensionsFromImageSrc(src)\n\tif (\n\t\t!pixelSize ||\n\t\t!Number.isFinite(pixelSize.width) ||\n\t\t!Number.isFinite(pixelSize.height) ||\n\t\tpixelSize.width <= 0 ||\n\t\tpixelSize.height <= 0\n\t) {\n\t\treturn undefined\n\t}\n\n\treturn pixelSize.width / pixelSize.height\n}\n\n/**\n * Returns width of a node in pixels, as measured when the node is rendered on the canvas.\n * This does not account for responsiveness / etc.\n */\nexport function getCanvasMeasuredWidth(\n\tnode: CanvasNode & WithSize & WithSizeDimensionType,\n\tctx: SimulationContext,\n): number | undefined {\n\tconst isFixedWidthNode = node.widthType === DimensionType.FixedNumber\n\tconst wasMeasuredOnCanvasBefore =\n\t\twithDOMLayout(node) && node.usesDOMRectCached() && isNonNull(node.cache.getRawDOMRect(node.id))\n\n\t// The node might not have an up-to-date rect if it was never measured during the current session\n\t// (eg the canvas is huge, and the user never panned to the node). In that case, the node\u2019s\n\t// rect defaults to 200\u00D7200 px, and we can\u2019t use it\n\tif (!isFixedWidthNode && !wasMeasuredOnCanvasBefore) return undefined\n\n\treturn ctx.tree.getRect(node).width\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { isNull, isNumber, isUndefined } from \"utils/typeChecks.ts\"\nimport type { CanvasNode } from \"../../document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport { withGridItemLayout } from \"../../document/models/CanvasTree/traits/WithGridItemLayout.ts\"\nimport type { HasGridLayout } from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport { CantCalculate } from \"./CantCalculate.ts\"\nimport type { SimulationContext } from \"./SimulationContext.ts\"\nimport { getLayoutChildren, nodeAffectsSiblings } from \"./utils.ts\"\n\nconst CELL_COORDINATE_SEPARATOR = \";\" as const\n\ntype RowIndex = number\ntype ColumnIndex = number\ntype CellCoordinate = `${RowIndex}${typeof CELL_COORDINATE_SEPARATOR}${ColumnIndex}`\ntype GridLayout = Map<CellCoordinate, NodeID>\n\nfunction stringifyCellCoordinate(rowIndex: number, columnIndex: number): CellCoordinate {\n\treturn `${rowIndex}${CELL_COORDINATE_SEPARATOR}${columnIndex}`\n}\n\nfunction parseCellCoordinate(coordinate: CellCoordinate): [number, number] {\n\tconst [rowIndex, columnIndex] = coordinate.split(CELL_COORDINATE_SEPARATOR)\n\tassert(\n\t\t!isUndefined(columnIndex),\n\t\t\"parseCellCoordinate(), satisfying TypeScript: columnIndex must exist: \" + coordinate,\n\t)\n\treturn [Number(rowIndex), Number(columnIndex)]\n}\n\n/** Returns -1 if item doesn't fit on the current row. */\nfunction getInsertColumnIndexForItem(\n\tgridLayout: GridLayout,\n\tcurrentRowIndex: number,\n\tcolumnCount: number,\n\titemColumnCount: number,\n): number {\n\tlet emptyCellCount = 0\n\tfor (let columnIndex = 0; columnIndex < columnCount; columnIndex++) {\n\t\tconst coordinate = stringifyCellCoordinate(currentRowIndex, columnIndex)\n\t\tconst isCellTaken = gridLayout.has(coordinate)\n\t\tif (isCellTaken) {\n\t\t\temptyCellCount = 0\n\t\t\tcontinue\n\t\t}\n\t\temptyCellCount++\n\t\tif (emptyCellCount !== itemColumnCount) {\n\t\t\tcontinue\n\t\t}\n\t\tconst result = columnIndex - (itemColumnCount - 1)\n\t\tassert(result >= 0, \"getColumnIndexForItem(), column index should be at least 0\")\n\t\treturn result\n\t}\n\n\treturn -1\n}\n\nfunction fillCellsForItem(\n\tnodeId: NodeID,\n\tgridLayout: GridLayout,\n\tinsertRowIndex: number,\n\tinsertColumnIndex: number,\n\titemRowSpan: number,\n\titemColumnSpan: number,\n\tcolumnCount: number,\n) {\n\tconst maxColumnIndex = insertColumnIndex + (itemColumnSpan - 1)\n\tassert(columnCount > maxColumnIndex, \"fillCellsForItem(), column count has to be larger than maxColumnIndex\")\n\n\tconst maxRowIndex = insertRowIndex + (itemRowSpan - 1)\n\n\tfor (let columnIndex = insertColumnIndex; columnIndex <= maxColumnIndex; columnIndex++) {\n\t\tfor (let rowIndex = insertRowIndex; rowIndex <= maxRowIndex; rowIndex++) {\n\t\t\tconst coordinate = stringifyCellCoordinate(rowIndex, columnIndex)\n\t\t\tgridLayout.set(coordinate, nodeId)\n\t\t}\n\t}\n}\n\nfunction getGridItemColumnSpan(node: CanvasNode, columnCount: number): number {\n\tif (!withGridItemLayout(node)) return 1\n\tif (isDynamicValue(node.gridItemColumnSpan)) return 1 // We can't calculate the column span for dynamic values\n\tif (node.gridItemColumnSpan === \"all\") return columnCount\n\treturn Math.min(node.gridItemColumnSpan ?? 1, columnCount)\n}\n\nexport function getGridItemRowSpan(node: CanvasNode, parentNode: CanvasNode & HasGridLayout): number {\n\tif (!withGridItemLayout(node)) return 1\n\tif (!experiments.isOn(\"gridBentoFit\") && parentNode.gridRowHeightType === \"fit\") return 1\n\tif (isDynamicValue(node.gridItemRowSpan)) return 1 // We can't calculate the row span for dynamic values\n\treturn node.gridItemRowSpan ?? 1\n}\n\nexport class GridLayoutInfo {\n\tconstructor(\n\t\tprivate gridLayout: GridLayout,\n\t\t/** Total actual number of rows in the grid. */\n\t\tpublic readonly rowCount: number,\n\t\t/** Total actual number of columns in the grid. */\n\t\tpublic readonly columnCount: number,\n\t\t/** Total number of filled rows in the grid. If it\u2019s less than `rowCount`, that means there are empty rows. */\n\t\tpublic readonly filledRowCount: number,\n\t) {}\n\n\tgetGridItem(rowIndex: RowIndex, columnIndex: ColumnIndex): NodeID | null {\n\t\tconst coordinate = stringifyCellCoordinate(rowIndex, columnIndex)\n\t\treturn this.gridLayout.get(coordinate) ?? null\n\t}\n\n\tprivate coordinateCache?: Map<NodeID, { rowIndex: RowIndex; columnIndex: ColumnIndex }>\n\t/**\n\t * Find coordinates of a node in the grid.\n\t * Note that this can realistically return `null` for an existing grid child\n\t * if it\u2019s invisible, or the grid is an (empty) data repeater, etc.\n\t */\n\tfindCoordinates(nodeId: NodeID): { rowIndex: RowIndex; columnIndex: ColumnIndex } | null {\n\t\tif (!this.coordinateCache) {\n\t\t\tthis.coordinateCache = new Map()\n\t\t\tfor (const [coordinate, nodeId] of this.gridLayout) {\n\t\t\t\tconst [rowIndex, columnIndex] = parseCellCoordinate(coordinate)\n\t\t\t\tconst existingCoordinate = this.coordinateCache.get(nodeId)\n\t\t\t\tif (\n\t\t\t\t\t!existingCoordinate ||\n\t\t\t\t\t// A node may span multiple cells, so we need to find the topmost and leftmost cell\n\t\t\t\t\trowIndex < existingCoordinate.rowIndex ||\n\t\t\t\t\tcolumnIndex < existingCoordinate.columnIndex\n\t\t\t\t) {\n\t\t\t\t\tthis.coordinateCache.set(nodeId, { rowIndex, columnIndex })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn this.coordinateCache.get(nodeId) ?? null\n\t}\n\n\tisEmpty(): boolean {\n\t\treturn this.gridLayout.size === 0\n\t}\n}\n\nfunction innerGetGridLayoutInfo(\n\tnode: CanvasNode & HasGridLayout,\n\ttree: CanvasTree,\n\tcomponentLoader: AnyComponentLoader,\n): GridLayoutInfo | null {\n\t// If the node doesn\u2019t have a fixed column count, we can't compute the grid layout.\n\t// That\u2019s because to compute the number of columns, we need to know the width of\n\t// each child, and we don\u2019t support that yet.\n\tconst columnCount = node.gridColumnCount\n\tif (!isNumber(columnCount)) return null\n\n\tconst gridLayoutMap: GridLayout = new Map()\n\tlet currentRowIndex = 0\n\tlet maxFilledRowIndex = -1\n\n\tfor (const child of getLayoutChildren(componentLoader, node)) {\n\t\tif (\n\t\t\t!nodeAffectsSiblings(\n\t\t\t\tchild,\n\t\t\t\tnode,\n\t\t\t\ttree,\n\t\t\t\t// We don\u2019t really know how to support the case when some node is visible or hidden\n\t\t\t\t// based on a variable, so let\u2019s just use the current variable\u2019s value\n\t\t\t\ttrue,\n\t\t\t)\n\t\t) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst itemColumnSpan = getGridItemColumnSpan(child, columnCount)\n\t\tconst itemRowSpan = getGridItemRowSpan(child, node)\n\n\t\tlet insertColumnIndex = getInsertColumnIndexForItem(gridLayoutMap, currentRowIndex, columnCount, itemColumnSpan)\n\n\t\twhile (insertColumnIndex === -1) {\n\t\t\tcurrentRowIndex++\n\t\t\tinsertColumnIndex = getInsertColumnIndexForItem(gridLayoutMap, currentRowIndex, columnCount, itemColumnSpan)\n\t\t}\n\n\t\tfillCellsForItem(\n\t\t\tchild.id,\n\t\t\tgridLayoutMap,\n\t\t\tcurrentRowIndex,\n\t\t\tinsertColumnIndex,\n\t\t\titemRowSpan,\n\t\t\titemColumnSpan,\n\t\t\tcolumnCount,\n\t\t)\n\n\t\tconst maxRowIndexForItem = currentRowIndex + (itemRowSpan - 1)\n\t\tmaxFilledRowIndex = Math.max(maxFilledRowIndex, maxRowIndexForItem)\n\t}\n\n\tconst filledRowCount = maxFilledRowIndex + 1\n\n\t// `node.gridRowCount` sets the number of rows in the code-generated grid:\n\t//\n\t//    grid-template-rows: repeat(${node.gridRowCount}, ...)\n\t//\n\t// However, this doesn\u2019t equal the actual number of rows in the grid:\n\t// if there are more children than rows \u00D7 columns, the browser will create\n\t// implicit rows.\n\t//\n\t// Therefore: for the actual grid layout, we use `node.gridRowCount` or\n\t// the actual number of filled rows, whichever is higher.\n\tconst rowCount = Math.max(node.gridRowCount ?? 0, filledRowCount)\n\n\treturn new GridLayoutInfo(gridLayoutMap, rowCount, columnCount, filledRowCount)\n}\n\n/**\n * Given a Grid node, determine how the nodes are laid out in the grid, taking\n * children `gridItemColumnSpan` and `gridItemRowSpan` into account.\n *\n * Throw `CantCalculate` if the grid layout can\u2019t be computed (e.g. if it doesn\u2019t\n * have a fixed column count).\n *\n * If the grid is a repeater, we will assume all of its children span the same\n * number of columns, as it is currently impossible to override this. If that\n * were to change, we would need to improve the detection.\n */\nexport function getGridLayoutInfo(node: CanvasNode & HasGridLayout, ctx: SimulationContext): GridLayoutInfo {\n\tconst cachedResult = ctx.cache.getGridLayoutInfo(node.id)\n\tif (cachedResult) return cachedResult\n\n\tconst result = innerGetGridLayoutInfo(node, ctx.tree, ctx.componentLoader)\n\tif (isNull(result)) throw new CantCalculate()\n\tctx.cache.setGridLayoutInfo(node.id, result)\n\treturn result\n}\n\n/** Get the total number of filled rows in a given grid. */\nexport function getGridFilledRowCount(\n\tnode: CanvasNode & HasGridLayout,\n\ttree: CanvasTree,\n\tcomponentLoader: AnyComponentLoader,\n): number | undefined {\n\treturn innerGetGridLayoutInfo(node, tree, componentLoader)?.filledRowCount\n}\n", "import { isNumber } from \"@framerjs/assets/src/utils.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { assert, assertNever } from \"library/utils/assert.ts\"\nimport { join } from \"utils/join.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { VIEWPORT_HEIGHT } from \"./utils.ts\"\n\n/**\n * Intermediate representation of a value in simulated DOM calculations.\n * Only used in calculations that return a number (currently computeHeight and computeY).\n */\nexport type SimulatedDOMNumberValue = NumberConstValue | NumberTemplateValue\n\n/**\n * Intermediate representation of a constant in simulated DOM calculations.\n * E.g. the value of 5px would be represented as { type: \"const\", value: 5 }.\n */\ninterface NumberConstValue {\n\ttype: \"number-const\"\n\tvalue: number\n}\n\n/**\n * Intermediate representation of an expression that references some codegenerated variables.\n * E.g. `stackDirection === \"horizontal\" ? 300 : 500` would be represented as { type: \"template\", expr: js`${stackDirectionVarName} === \"horizontal\" ? 300 : 500` }.\n */\nexport interface NumberTemplateValue {\n\ttype: \"number-template\"\n\texpr: SafeJS\n\t/**\n\t * The most likely value of the template when executed in runtime. This is used for more\n\t * advanced algorithms (like the one simulating stack wrapping) which rely on being able\n\t * to do arbitrary number comparisons, not just the +-/* operations.\n\t */\n\timpreciseEstimate: number\n}\n\n// Hard-code some common number values to avoid allocating them over and over\nconst NUMBER_ZERO: NumberConstValue = { type: \"number-const\", value: 0 }\nconst NUMBER_INFINITY: NumberConstValue = { type: \"number-const\", value: Infinity }\nconst NUMBER_VIEWPORT_HEIGHT: NumberConstValue = { type: \"number-const\", value: VIEWPORT_HEIGHT }\nexport function numberConst(value: number): NumberConstValue {\n\tif (value === 0) return NUMBER_ZERO\n\tif (value === Infinity) return NUMBER_INFINITY\n\tif (value === VIEWPORT_HEIGHT) return NUMBER_VIEWPORT_HEIGHT\n\n\treturn { type: \"number-const\", value: round(value) }\n}\n\ntype SupportedOp = \"+\" | \"-\" | \"*\" | \"/\" | \"min\" | \"max\"\n\ntype NumberOpOperand = SimulatedDOMNumberValue | number\nexport type NumberOpArguments =\n\t| [NumberOpOperand, NumberOpOperand]\n\t| [NumberOpOperand, NumberOpOperand, NumberOpOperand]\n\t| [NumberOpOperand, NumberOpOperand, NumberOpOperand, NumberOpOperand]\n\n/**\n * Performs an operation (+, -, *, /, min, max) on two or more numbers. If all operands are constants, the operation is performed immediately.\n * If one or more operands are templates, the operation is performed at runtime.\n *\n * @param operands Any arguments of type number, numberConst, or numberTemplate.\n *\n * @example\n * // With numbers:\n * numberOp(\"+\", 1, 2) // returns numberConst(3)\n * // With templates:\n * numberOp(\"+\", 1, numberTemplate(js`${someVar} + 200`)) // returns numberTemplate(js`1 + ${someVar} + 200`)\n * // Numbers, numberConsts, and numberTemplates can be mixed:\n * numberOp(\"+\", 1, numberConst(2), 3, numberTemplate(js`4`)) // returns numberTemplate(js`1 + 2 + 3 + 4`)\n * // Passing an empty array will return null \u2013 use this to provide a fallback value:\n * numberOp(\"+\", ...someOperands) ?? numberConst(0)\n * // Operations like - and / are performed from left to right:\n * numberOp(\"-\", 1, 2, 3) // works as numberConst(1 - 2 - 3) = numberConst(-4)\n * numberOp(\"/\", 1, 2, 3) // works as numberConst(1 / 2 / 3) = numberConst(1 / 6)\n */\nexport function numberOp(op: SupportedOp, operand1: NumberOpOperand, operand2: NumberOpOperand): SimulatedDOMNumberValue\nexport function numberOp(\n\top: SupportedOp,\n\toperand1: NumberOpOperand,\n\toperand2: NumberOpOperand,\n\toperand3: NumberOpOperand,\n): SimulatedDOMNumberValue\nexport function numberOp(\n\top: SupportedOp,\n\toperand1: NumberOpOperand,\n\toperand2: NumberOpOperand,\n\toperand3: NumberOpOperand,\n\toperand4: NumberOpOperand,\n): SimulatedDOMNumberValue\n// numberOp() will return null if \u2013 and only if \u2013 called with zero operands.\n// In practice, this can happen when you\u2019re calling it as\n//\n//   numberOp(\"+\", ...array)\n//\n// and the array is empty. If you\u2019re calling it with a fixed number of operands:\n//\n//   numberOp(\"+\", a, b, c, d)\n//\n// and you don\u2019t want to do an unnecessary check for `null`, add more overloads\n// above.\nexport function numberOp(\n\top: SupportedOp,\n\t...operands: (SimulatedDOMNumberValue | number)[]\n): SimulatedDOMNumberValue | null\nexport function numberOp(op: SupportedOp, ...operands: (SimulatedDOMNumberValue | number)[]) {\n\treturn numberOpForArraySlice(op, 0, operands.length, operands)\n}\n\n/**\n * Like {@link numberOp}, but allows to run the operation on a slice of an array \u2013 without\n * allocating memory for that slice. This matters because, theoretically, some slices\n * might be 10K-100K elements long (e.g. in case of very large CMS collections).\n */\nexport function numberOpForArraySlice(\n\top: SupportedOp,\n\tstart: number,\n\tend: number,\n\toperands: (SimulatedDOMNumberValue | number)[],\n): SimulatedDOMNumberValue | null {\n\t// Note: today, if any of the arguments is a template, newNumberOp() simply returns a template.\n\t// Sometimes, this might lead to codegenerating unnecessarily long operations, like:\n\t//   (((someVar + 200) - 500) + 100)\n\t// If this becomes annoying, we can make this function more similar to newCSSOp(),\n\t// which 1) stores all operations in a CSSOpValue, 2) simplifies all CSSOpValues\n\t// it encounters, where it can.\n\n\tassert(0 <= start && start <= end && end <= operands.length, \"start and end must be within the bounds of operands\")\n\n\t// Handle size 0 and 1 cases\n\tconst operandsCount = end - start\n\tif (operandsCount === 0) return null\n\tif (operandsCount === 1) {\n\t\tconst operand = operands[start]!\n\t\treturn isNumber(operand) ? numberConst(operand) : operand\n\t}\n\n\t// Compute the precise (if all operands are constants) or imprecise (if some operands are\n\t// templates) result of the operation\n\tconst { hasTemplateOperands, operationResult } = computeOperation(start, end, operands, op)\n\n\t// If all operands are constants, just return the computed result\n\tif (!hasTemplateOperands) {\n\t\treturn numberConst(operationResult)\n\t}\n\n\t// Otherwise, create a template applying the operation to the operands\n\tconst operandExpressions: SafeJS[] = convertOperandsToExpressions(start, end, operands)\n\tconst template =\n\t\top === \"min\" || op === \"max\"\n\t\t\t? SafeJS.fn(js`Math.${new SafeJS(op)}`, ...operandExpressions)\n\t\t\t: new SafeJS(`(${join(operandExpressions, ` ${op} `)})`)\n\treturn numberTemplate(template, operationResult, true)\n}\n\nfunction computeOperation(\n\tstart: number,\n\tend: number,\n\toperands: (number | SimulatedDOMNumberValue)[],\n\top: SupportedOp,\n): { hasTemplateOperands: boolean; operationResult: number } {\n\tlet hasTemplateOperands = false\n\tlet operationResult: number | undefined\n\n\tfor (let i = start; i < end; i++) {\n\t\tconst operand = operands[i]!\n\n\t\tlet operandValue: number\n\t\tif (isNumber(operand)) {\n\t\t\toperandValue = operand\n\t\t} else if (operand.type === \"number-const\") {\n\t\t\toperandValue = operand.value\n\t\t} else if (operand.type === \"number-template\") {\n\t\t\thasTemplateOperands = true\n\t\t\toperandValue = getImpreciseEstimate(operand)\n\t\t} else {\n\t\t\tassertNever(operand)\n\t\t}\n\n\t\tif (isUndefined(operationResult)) {\n\t\t\toperationResult = operandValue\n\t\t} else {\n\t\t\toperationResult = applyOp(op, operationResult, operandValue)\n\t\t}\n\t}\n\n\tassert(!isUndefined(operationResult), \"resultEstimate must be computed after walking over all operands\")\n\n\treturn { hasTemplateOperands, operationResult }\n}\n\nfunction convertOperandsToExpressions(start: number, end: number, operands: (number | SimulatedDOMNumberValue)[]) {\n\tconst operandExpressions: SafeJS[] = []\n\n\tfor (let i = start; i < end; i++) {\n\t\tconst operand = operands[i]!\n\t\tif (isNumber(operand)) {\n\t\t\toperandExpressions.push(js`${operand}`)\n\t\t} else if (operand.type === \"number-const\") {\n\t\t\toperandExpressions.push(js`${operand.value}`)\n\t\t} else {\n\t\t\toperandExpressions.push(operand.expr)\n\t\t}\n\t}\n\n\treturn operandExpressions\n}\n\n/**\n * @see {@link NumberTemplateValue} for what this does and parameters it receives\n *\n * @param isolatedOperandGuaranteed A cosmetic parameter that allows us to avoid\n * wrapping the expression in parentheses unnecessarily. By default, `numberTemplate()`\n * will wrap everything passed into it in parentheses, to ensure that the expression\n * is treated as an isolated operand. Set it to `true` if the parameter is already\n * guaranteed to be treated as an isolated operand, and this step can be skipped.\n *\n * \u201CIsolated operand\u201D is an operand that\u2019s guaranteed to be computed properly whatever\n * code it concatenated with. A non-isolated operand is not guaranteed. For example,\n * these are all isolated operands: `5`; `Math.max(5, 2)`; `(5 + 2)`. These are not:\n * `5 + 2`; `5 * 7`. The latter operands might result in incorrect code if concatenated\n * with something unexpected, e.g.: `numberOp(\"*\", numberTemplate(SafeJS(\"5 + 2\")), 7)` will\n * result in `5 + 2 * 7`, not `(5 + 2) * 7`, which is the expected result.\n *\n * @example\n * numberOp(\"+\", numberTemplate(js`someVar ? 5 : 2`), numberTemplate(js`someVar2 + 5`))\n * // returns numberTemplate(js`(someVar ? 5 : 2) + (someVar2 + 5)`)\n */\nexport function numberTemplate(\n\texpr: SafeJS,\n\timpreciseEstimate: number,\n\tisolatedOperandGuaranteed: boolean = false,\n): NumberTemplateValue {\n\treturn { type: \"number-template\", expr: isolatedOperandGuaranteed ? expr : js`(${expr})`, impreciseEstimate }\n}\n\nfunction applyOp(op: SupportedOp, left: number, right: number): number {\n\tswitch (op) {\n\t\tcase \"+\":\n\t\t\treturn left + right\n\t\tcase \"-\":\n\t\t\treturn left - right\n\t\tcase \"*\":\n\t\t\treturn left * right\n\t\tcase \"/\":\n\t\t\treturn left / right\n\t\tcase \"min\":\n\t\t\treturn Math.min(left, right)\n\t\tcase \"max\":\n\t\t\treturn Math.max(left, right)\n\t\tdefault:\n\t\t\tassertNever(op)\n\t}\n}\n\nfunction round(value: number): number {\n\t// Round the value to avoid codegenerating unnecessarily long numbers (like 15.49999999999999994).\n\t// The 10000 value is a bit arbitrary but should be a good balance: some of the numbers\n\t// we\u2019re rounding are %s (so, 50.45% will be 0.5045), and we don\u2019t want to lose too much\n\t// precision.\n\treturn Math.round(value * 10000) / 10000\n}\n\n/**\n * Returns the impecise estimate of a simulated DOM number value. This is useful for cases when\n * you have a template like `${componentHeight} - 200`, and you want to figure out what that value\n * will likely evaluate to on runtime.\n *\n * This is, obviously, imprecise, sometimes wildly \u2013 because we don\u2019t actually know `componentHeight`\n * until runtime.\n *\n * Normally, you don\u2019t need to use this method unless you have to do something newNumberOp()\n * doesn\u2019t support, such as a comparison between two simulated values at codegen time.\n */\nexport function getImpreciseEstimate(value: SimulatedDOMNumberValue): number {\n\treturn value.type === \"number-const\" ? value.value : value.impreciseEstimate\n}\n", "import type { CanvasNode, MaybeNodeID, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { getNumericColumnGapFromShorthand } from \"document/models/CanvasTree/traits/NumberShorthand.ts\"\nimport type { WithSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { assertNever } from \"library/utils/assert.ts\"\nimport type { HasStackLayout } from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport { supportGap } from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport type { WithSize } from \"../../document/models/CanvasTree/traits/WithSize.ts\"\nimport { withSize } from \"../../document/models/CanvasTree/traits/WithSize.ts\"\nimport type { SimulationContext } from \"./SimulationContext.ts\"\nimport type { SimulatedDOMNumberValue } from \"./numberValue.ts\"\nimport { getImpreciseEstimate, numberConst, numberOp } from \"./numberValue.ts\"\nimport {\n\tgetLayoutChildren,\n\tgetNodePaddingBottom,\n\tgetNodePaddingTop,\n\tisIndeterminate,\n\tnodeAffectsSiblings,\n\tresolveGap,\n} from \"./utils.ts\"\n\ninterface RegularColumnItem {\n\ttype: \"regular\"\n\tnodeId: NodeID\n\tgetHeight: () => SimulatedDOMNumberValue\n}\n\ninterface FrColumnItem {\n\ttype: \"fr\"\n\tnodeId: NodeID\n\tfrUnits: number\n\tgetMinHeight: () => SimulatedDOMNumberValue\n\tgetMaxHeight: () => SimulatedDOMNumberValue\n\tgetMinHeightPerFr: () => SimulatedDOMNumberValue\n\tgetMaxHeightPerFr: () => SimulatedDOMNumberValue\n}\n\nexport class StackLayoutInfo {\n\tconstructor(\n\t\tprivate columns: (RegularColumnItem | FrColumnItem)[][],\n\t\tprivate nodeToAccurateCoordinateMap: Map<NodeID, { columnIndex: number; columnItemIndex: number }>,\n\t\tprivate nodeToRoughCoordinateMap: Map<NodeID, { columnIndex: number; columnItemIndex: number }>,\n\t\tprivate gap: number,\n\t\tprivate contentHeight: SimulatedDOMNumberValue,\n\t) {}\n\n\t/** Walk all column items in a column, calling a callback for each node ID. */\n\twalkColumn(columnIndex: number, callback: (nodeId: NodeID) => void): void {\n\t\tif (!this.columns[columnIndex]) return\n\n\t\tfor (const columnItem of this.columns[columnIndex]) {\n\t\t\tcallback(columnItem.nodeId)\n\t\t}\n\t}\n\n\tgetStackItem(columnIndex: number, columnItemIndex: number): MaybeNodeID {\n\t\treturn this.columns[columnIndex]?.[columnItemIndex]?.nodeId ?? null\n\t}\n\n\t/**\n\t * Find coordinates of a node in the stack.\n\t *\n\t * Returns `null` for nodes that are not a part of the stack layout (hidden, position: absolute,\n\t * simply not a child, etc).\n\t */\n\tfindCoordinates(nodeId: NodeID): { columnIndex: number; columnItemIndex: number } | null {\n\t\treturn this.findAccurateCoordinates(nodeId) ?? this.findRoughCoordinatesOfConditionallyVisibleNode(nodeId)\n\t}\n\n\t/**\n\t * Find accurate coordinates of a node in the stack.\n\t *\n\t * Returns `null` for nodes that are not a part of the stack layout (hidden, position: absolute,\n\t * simply not a child, etc), and nodes that are conditionally visible (for those, use\n\t * `.findRoughCoordinatesOfConditionallyVisibleNode`).\n\t */\n\tfindAccurateCoordinates(nodeId: NodeID): { columnIndex: number; columnItemIndex: number } | null {\n\t\treturn this.nodeToAccurateCoordinateMap.get(nodeId) ?? null\n\t}\n\n\t/**\n\t * Find rough coordinates of a node that\u2019s conditionally visible.\n\t *\n\t * They are \u201Crough\u201D in a sense that the node would likely end up in the returned spot if it were\n\t * visible, but we\u2019re otherwise ignoring it in stack layouting. As a consequence, it can end up\n\t * sharing coordinates with another node:\n\t *\n\t * ```\n\t * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t * \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502\n\t * \u2502 \u2502  NODE 1  \u2502 \u2502 \u2190 Node 1: coordinates = { columnIndex = 0, columnItemIndex = 0 }, roughCoordinates = none\n\t * \u2502 \u2502          \u2502 \u2502\n\t * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n\t * \u2502\u250C\u2500\u2500\u2500\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u2500\u2500\u2500\u2510\u2502\n\t * \u2502\u2502   \u00B7 N2 \u00B7   \u2502\u2502 \u2190 Node 2 (conditionally visible): coordinates = none, roughCoordinates = { columnIndex = 0, columnItemIndex = 1 }\n\t * \u2502\u2502   \u00B7\u00B7\u00B7\u00B7\u00B7\u00B7   \u2502\u2502\n\t * \u2502\u2502            \u2502\u2502\n\t * \u2502\u2502   NODE 3   \u2502\u2502 \u2190 Node 3: coordinates = { columnIndex = 0, columnItemIndex = 1 }, roughCoordinates = none\n\t * \u2502\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2502\n\t * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t * ```\n\t */\n\tfindRoughCoordinatesOfConditionallyVisibleNode(\n\t\tnodeId: NodeID,\n\t): { columnIndex: number; columnItemIndex: number } | null {\n\t\treturn this.nodeToRoughCoordinateMap.get(nodeId) ?? null\n\t}\n\n\tprivate frToPxCache: Map<number, SimulatedDOMNumberValue> = new Map()\n\tpublic getFrToPxForColumn(columnIndex: number): SimulatedDOMNumberValue | null {\n\t\tconst columnItems = this.columns[columnIndex]\n\t\tif (!columnItems) return null\n\n\t\tif (!this.frToPxCache.has(columnIndex)) {\n\t\t\t// Here, we need to compute the size of 1fr unit in a given column.\n\t\t\t// The naive implementation would simply do\n\t\t\t//   freeSpace := stackHeight - totalHeightOfNonFrItems - totalGaps\n\t\t\t//   frHeight := freeSpace / totalFrUnits\n\t\t\t// but this doesn\u2019t always work due to min-max constraints.\n\t\t\t//\n\t\t\t// Imagine you have a stack:\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2510 \u2502\n\t\t\t// \u2502 \u2502 A \u2502 \u2502  \u2190 1 fr, min-height: 150px\n\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2518 \u2502\n\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2510 \u2502\n\t\t\t// \u2502 \u2502 B \u2502 \u2502  \u2190 1 fr\n\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2518 \u2502\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t// And imagine that in this stack, both node A and node B are 1fr tall; however, node A\n\t\t\t// also has min-height of 150px.\n\t\t\t//\n\t\t\t// If the stack is 500px tall, then the naive implementation works: we take the free space (500px),\n\t\t\t// divide it by totalFrUnits (2), and get the height of 1 fr unit (250px).\n\t\t\t// But if the stack is 200px tall, then the naive implementation suddenly doesn\u2019t work anymore:\n\t\t\t// because A now has a \u201Cfixed\u201D height of 150px, node B ends up being only 50px tall (whereas\n\t\t\t// the naive implementation would\u2019ve computed 100px). Likewise with max-heights.\n\t\t\t//\n\t\t\t// So how can you deal with min-max constraints? If you stare at them for a while, you\u2019ll realize\n\t\t\t// the guiding principle behind them: when you have a fr node, it acts as fr while it\u2019s within\n\t\t\t// the min/max-height constraints, and as a fixed node when it\u2019s outside. So we do the following:\n\t\t\t// - we run the naive implementation to compute the naive size of 1 fr,\n\t\t\t// - and then, if any fr node ends up being outside of the constraints with that 1 fr size,\n\t\t\t//   we treat it as a fixed-height node \u2013 that is, remove it from the calculation\n\t\t\t//   (subtracting it both from freeSpace and from totalFrUnits).\n\t\t\tconst fixedItems: RegularColumnItem[] = []\n\t\t\tlet frItems: FrColumnItem[] = []\n\t\t\tfor (const item of columnItems) {\n\t\t\t\tif (item.type === \"regular\") fixedItems.push(item)\n\t\t\t\telse if (item.type === \"fr\") frItems.push(item)\n\t\t\t\telse assertNever(item)\n\t\t\t}\n\n\t\t\t// First, the naive calculation:\n\t\t\tconst totalHeightOfNonFrItems = fixedItems.reduce(\n\t\t\t\t(size, item) => numberOp(\"+\", size, item.getHeight()),\n\t\t\t\tnumberConst(0),\n\t\t\t)\n\t\t\tconst totalGaps = this.gap * (columnItems.length - 1)\n\t\t\tlet freeSpace = numberOp(\"-\", this.contentHeight, numberOp(\"+\", totalHeightOfNonFrItems, totalGaps))\n\t\t\tlet totalFrUnits = frItems.reduce((units, item) => units + item.frUnits, 0)\n\t\t\tlet frHeight = numberOp(\n\t\t\t\t\"/\",\n\t\t\t\tfreeSpace,\n\t\t\t\t// Never allow division by zero (which might otherwise happen if there are no fr items)\n\t\t\t\tMath.max(totalFrUnits, 1),\n\t\t\t)\n\n\t\t\t// Second, account for any items with minSize > frSize, starting from the biggest ones\n\t\t\tfrItems = frItems.sort(\n\t\t\t\t(a, b) => getImpreciseEstimate(b.getMinHeightPerFr()) - getImpreciseEstimate(a.getMinHeightPerFr()),\n\t\t\t)\n\t\t\twhile (frItems[0] && getImpreciseEstimate(frItems[0].getMinHeightPerFr()) > getImpreciseEstimate(frHeight)) {\n\t\t\t\tfreeSpace = numberOp(\"-\", freeSpace, frItems[0].getMinHeight())\n\t\t\t\ttotalFrUnits -= frItems[0].frUnits\n\n\t\t\t\tfrHeight = numberOp(\n\t\t\t\t\t\"/\",\n\t\t\t\t\tfreeSpace,\n\t\t\t\t\t// Never allow division by zero (which might otherwise happen if we walked over *all* existing frItems in this loop)\n\t\t\t\t\tMath.max(totalFrUnits, 1),\n\t\t\t\t)\n\t\t\t\tfrItems.shift()\n\t\t\t}\n\n\t\t\t// Third, account for any remaining items with maxSize < frSize, starting from the smallest one\n\t\t\tfrItems = frItems.sort(\n\t\t\t\t(a, b) => getImpreciseEstimate(a.getMaxHeightPerFr()) - getImpreciseEstimate(b.getMaxHeightPerFr()),\n\t\t\t)\n\t\t\twhile (frItems[0] && getImpreciseEstimate(frItems[0].getMaxHeightPerFr()) < getImpreciseEstimate(frHeight)) {\n\t\t\t\tfreeSpace = numberOp(\"-\", freeSpace, frItems[0].getMaxHeight())\n\t\t\t\ttotalFrUnits -= frItems[0].frUnits\n\n\t\t\t\tfrHeight = numberOp(\n\t\t\t\t\t\"/\",\n\t\t\t\t\tfreeSpace,\n\t\t\t\t\t// Never allow division by zero (which might otherwise happen if we walked over *all* existing frItems in this loop)\n\t\t\t\t\tMath.max(totalFrUnits, 1),\n\t\t\t\t)\n\t\t\t\tfrItems.shift()\n\t\t\t}\n\n\t\t\t// `frHeight` can sometimes be computed to be negative \u2013 e.g. when the column has fixed-height items\n\t\t\t// that are too tall for the remaining free space. In that case, we return 0.\n\t\t\tthis.frToPxCache.set(columnIndex, numberOp(\"max\", numberConst(0), frHeight))\n\t\t}\n\n\t\treturn this.frToPxCache.get(columnIndex) ?? null\n\t}\n}\n\n/**\n * Given a Stack node, determine how the nodes are laid out in the stack,\n * and what their rendered heights are.\n *\n * This properly accounts for:\n * - stack wrapping\n * - fr nodes\n * - min- and max-heights of fr nodes\n *\n * As currently implemented, this function only works for vertical stacks. However,\n * it\u2019s trivially adaptable to work for horizontal stacks as well. The layout algorithm\n * for horizontal and vertical stacks is the same; the only thing that\u2019d need to change\n * is some variable names.\n *\n * FIXME: if this function ends up being expensive, it can be made faster by:\n * - stopping computations early: introducing a `stopAfter?: CanvasNode` argument,\n *   which functions like `simulateYPosition` can use to signal that they are not interested\n *   in the layout past that node\u2019s column\n */\nexport function getVerticalStackLayoutInfo(\n\tstackNode: CanvasNode & HasStackLayout & WithSize & WithSizeDimensionType,\n\tctx: SimulationContext,\n\tgetNodeHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n\tgetNodeMinHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n\tgetNodeMaxHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n) {\n\tconst cachedValue = ctx.cache.getVerticalStackLayoutInfo(stackNode.id)\n\tif (cachedValue) return cachedValue\n\n\tconst value = uncachedGetVerticalStackLayoutInfo(stackNode, ctx, getNodeHeight, getNodeMinHeight, getNodeMaxHeight)\n\tctx.cache.setVerticalStackLayoutInfo(stackNode.id, value)\n\treturn value\n}\n\nfunction uncachedGetVerticalStackLayoutInfo(\n\tstackNode: CanvasNode & HasStackLayout & WithSize & WithSizeDimensionType,\n\tctx: SimulationContext,\n\tgetNodeHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n\tgetNodeMinHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n\tgetNodeMaxHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n) {\n\tconst resolvedStackGap = getEffectiveStackGap(stackNode)\n\tconst stackGap = getNumericColumnGapFromShorthand(resolvedStackGap)\n\n\tconst contentHeight = numberOp(\n\t\t\"-\",\n\t\tgetNodeHeight(stackNode),\n\t\tgetNodePaddingTop(stackNode) + getNodePaddingBottom(stackNode),\n\t)\n\tconst contentHeightEstimate = getImpreciseEstimate(contentHeight)\n\n\tconst nodeToCoordinateMap = new Map<NodeID, { columnIndex: number; columnItemIndex: number }>()\n\tconst nodeToCoordinateRoughMap = new Map<NodeID, { columnIndex: number; columnItemIndex: number }>()\n\tconst columns: (RegularColumnItem | FrColumnItem)[][] = []\n\tlet thisColumnHeight = 0\n\n\t// This loop splits children between columns. Here\u2019s how we do that:\n\t// 1) For non-fr items, we compute the height in pixels.\n\t// 2) For fr items, we assume they are 0px* in size, because they get as small as needed to fill\n\t//    the remaining available space.\n\t//    * \u2014 Unless they have a min-height, in which case they\u2019re that min-height.\n\t// 3) Then, we start filling the first column and continue until it overflows. If it overflows,\n\t//    we start a new column.\n\t//\n\t// Note: we use this algorithm for non-wrapping stacks as well. On the surface, it\u2019s an overkill:\n\t// if I know that the stack is non-wrapping and will only have one column, why do all this work?\n\t// But, unfortunately, we still need to know the height of every child to compute the size\n\t// of a 1fr unit (which is what StackLayoutInfo is doing).\n\tfor (const child of getLayoutChildren(ctx.componentLoader, stackNode)) {\n\t\tif (!(withSize(child) && withSizeDimensionType(child))) continue\n\n\t\tconst doesNodeAffectLayout = nodeAffectsSiblings(child, stackNode, ctx.tree, false)\n\n\t\t// Only regular nodes that affect the layout can shift subsequent siblings. Thus, when doing\n\t\t// stack layouting, we only account for these nodes.\n\t\tif (doesNodeAffectLayout === false) continue\n\n\t\t// FIXME: until we have support for visibility variables, we\u2019ll have to treat all children\n\t\t// where visibility is a variable (doesNodeAffectLayout === Indeterminate) as children that\n\t\t// are hidden (doesNodeAffectLayout === false).\n\t\t//\n\t\t// This is a reasonably simple approach, but it comes with drawbacks. For the loading=lazy\n\t\t// optimization, specifically, it might lead to some images not being marked with\n\t\t// loading=lazy even if they end up below the fold (e.g. because all dynamic elements above\n\t\t// ended up being visible). Previously, we did the opposite of this heuristic (we assumed\n\t\t// that all children where visibility is a variable are always visible), but that led to\n\t\t// some LCP images having loading=lazy, and Lighthouse complaining about that.\n\t\tif (isIndeterminate(doesNodeAffectLayout)) {\n\t\t\t// All visible stack children get a clear coordinate (columnIndex and columnItemIndex)\n\t\t\t// assigned for them. (The simulateYPosition algo might use this later to compute the\n\t\t\t// `y` position of a node.)\n\t\t\t//\n\t\t\t// All nodes that aren\u2019t a part of the stack layout (hidden, position: absolute, etc)\n\t\t\t// don\u2019t get a coordinate, because they don\u2019t need it, and because a column index /\n\t\t\t// column item index doesn\u2019t make sense for them.\n\t\t\t//\n\t\t\t// However, what about nodes that are conditionally visible? On one hand, they\u2019re\n\t\t\t// usually invisible, so we don\u2019t want them to be a part of the layout. (See above for\n\t\t\t// why.) On the other hand, if they do end up being visible, we do want to be able to\n\t\t\t// compute their `y` coordinate.\n\t\t\t//\n\t\t\t// As a compromise, until we get proper variable support, we don\u2019t include these nodes\n\t\t\t// in the layout, but we do give them rough coordinates that would reflect where they\n\t\t\t// would have been if they were visible. This way, if a conditionally visible node has\n\t\t\t// an image inside, the `y` position of that image will still be computed correctly.\n\t\t\tnodeToCoordinateRoughMap.set(child.id, {\n\t\t\t\tcolumnIndex: Math.max(columns.length - 1, 0),\n\t\t\t\tcolumnItemIndex: Math.max(columns[columns.length - 1]?.length ?? 0, 0),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tconst currentChild = getColumnItem(child, ctx, getNodeHeight, getNodeMinHeight, getNodeMaxHeight)\n\n\t\tconst mayHaveMultipleColumns = stackNode.stackWrapEnabled\n\t\tif (mayHaveMultipleColumns) {\n\t\t\tconst currentChildHeightEstimate = getImpreciseEstimate(\n\t\t\t\t// Why use .getMinHeight() and not .getHeight() for fr items here? See pt. 2 of the algo above.\n\t\t\t\tcurrentChild.type === \"fr\" ? currentChild.getMinHeight() : currentChild.getHeight(),\n\t\t\t)\n\n\t\t\tconst childWouldOverflowColumn =\n\t\t\t\tMath.ceil(thisColumnHeight + stackGap + currentChildHeightEstimate) > Math.ceil(contentHeightEstimate)\n\n\t\t\tif (\n\t\t\t\tchildWouldOverflowColumn ||\n\t\t\t\t// Edge case: if we\u2019re just starting, the first element always goes into the first column\n\t\t\t\tcolumns.length === 0\n\t\t\t) {\n\t\t\t\tcolumns.push([currentChild])\n\t\t\t\tthisColumnHeight = currentChildHeightEstimate\n\t\t\t} else {\n\t\t\t\tcolumns[columns.length - 1]!.push(currentChild)\n\t\t\t\tthisColumnHeight += stackGap + currentChildHeightEstimate\n\t\t\t}\n\t\t} else {\n\t\t\tcolumns[0] = columns[0] ?? []\n\t\t\tcolumns[0].push(currentChild)\n\t\t}\n\n\t\tnodeToCoordinateMap.set(child.id, {\n\t\t\tcolumnIndex: columns.length - 1,\n\t\t\tcolumnItemIndex: columns[columns.length - 1]!.length - 1,\n\t\t})\n\t}\n\n\treturn new StackLayoutInfo(columns, nodeToCoordinateMap, nodeToCoordinateRoughMap, stackGap, contentHeight)\n}\n\nfunction getColumnItem(\n\tchild: CanvasNode & WithSize & WithSizeDimensionType,\n\tctx: SimulationContext,\n\tgetNodeHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n\tgetNodeMinHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n\tgetNodeMaxHeight: (node: CanvasNode & WithSize & WithSizeDimensionType) => SimulatedDOMNumberValue,\n): RegularColumnItem | FrColumnItem {\n\tif (child.heightType === DimensionType.FractionOfFreeSpace) {\n\t\tconst frColumnItem: FrColumnItem = {\n\t\t\tnodeId: child.id,\n\t\t\ttype: \"fr\",\n\t\t\tfrUnits: child.height,\n\t\t\t// Note: using lazy computations to avoid doing extra work when the caller\n\t\t\t// ends up never calling `getFrToPxForColumn`, and/or when the stack isn\u2019t wrapping\n\t\t\tgetMinHeight: () => ctx.cache.memo(`stack-getMinHeight-${child.id}`, () => getNodeMinHeight(child)),\n\t\t\tgetMaxHeight: () => ctx.cache.memo(`stack-getMaxHeight-${child.id}`, () => getNodeMaxHeight(child)),\n\t\t\tgetMinHeightPerFr: () =>\n\t\t\t\tctx.cache.memo(`stack-getMinHeightPerFr-${child.id}`, () =>\n\t\t\t\t\tnumberOp(\"/\", frColumnItem.getMinHeight(), frColumnItem.frUnits),\n\t\t\t\t),\n\t\t\tgetMaxHeightPerFr: () =>\n\t\t\t\tctx.cache.memo(`stack-getMaxHeightPerFr-${child.id}`, () =>\n\t\t\t\t\tnumberOp(\"/\", frColumnItem.getMaxHeight(), frColumnItem.frUnits),\n\t\t\t\t),\n\t\t}\n\n\t\treturn frColumnItem\n\t} else {\n\t\treturn {\n\t\t\tnodeId: child.id,\n\t\t\tgetHeight: () => ctx.cache.memo(`stack-getHeight-${child.id}`, () => getNodeHeight(child)),\n\t\t\ttype: \"regular\",\n\t\t}\n\t}\n}\n\nexport function getEffectiveStackGap(stackNode: CanvasNode & HasStackLayout) {\n\t// space-* stacks don\u2019t use stack gaps\n\tif (!supportGap(stackNode)) return 0\n\treturn resolveGap(stackNode.gap)\n}\n", "import type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport type { RichTextNode } from \"document/models/CanvasTree/nodes/RichTextNode.ts\"\nimport { isTextStylePresetNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { DEFAULT_ROOT_FONT_SIZE } from \"document/models/CanvasTree/traits/WithRootFontSize.ts\"\nimport { parseCSSDimension } from \"document/models/CanvasTree/traits/utils/CSSDimension.ts\"\nimport { DimensionType, roundedNumber } from \"library/index.ts\"\nimport { assertNever } from \"library/utils/assert.ts\"\nimport type { Node } from \"prosemirror-model\"\nimport { isInlineStylesMark } from \"prosemirror/schema/inlineStyles.ts\"\nimport { isProseMirrorTextNode } from \"prosemirror/schema/text.ts\"\nimport type { TextBlockNode } from \"prosemirror/schema/textBlock.ts\"\nimport { hasTextStylePreset } from \"prosemirror/schema/utils.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { isDynamicValue } from \"../../document/models/CanvasTree/traits/DynamicValue.ts\"\nimport {\n\tconvertFontSizeValue,\n\tisFontSize,\n\tisFontSizeCSSDimension,\n\ttextStyleDefaults,\n} from \"../../document/models/CanvasTree/traits/WithTextStyle.ts\"\nimport { CantCalculate } from \"./CantCalculate.ts\"\n\n/**\n * Take a rich text node, and return an estimate of its height.\n *\n * Note that the calculations for wrapping text nodes are very approximate,\n * but it isn\u2019t too hard to get much better precision: https://framer-team.slack.com/archives/C05V49Q4NJ2/p1718236110168089\n *\n * FIXME: this algo doesn\u2019t support text variables (node.htmlContent or node.textContent)\n * at the moment. Even if a variable is present, we\u2019ll fall back to the default text value\n * (node.html), which can be wildly different from the real one.\n */\nexport function getApproximateAutosizingTextHeight(richTextNode: RichTextNode, tree: CanvasTree): number {\n\t// FIXME: Auto-fit text isn\u2019t supported at the moment\n\tif (richTextNode.textFitViewBoxSize) throw new CantCalculate()\n\n\tconst isWrapping = richTextNode.widthType !== DimensionType.Auto\n\n\tlet totalHeight = 0\n\tfor (const [index, blockNode] of richTextNode.getProsemirrorTextBlocks(false).entries()) {\n\t\tlet textBlockHeight: number\n\t\tconst [lineHeightValue, lineHeightUnit] = getTextBlockLineHeight(blockNode, tree)\n\n\t\tif (lineHeightUnit === \"px\") {\n\t\t\ttextBlockHeight = lineHeightValue\n\t\t} else {\n\t\t\tconst lineHeightMultiplier =\n\t\t\t\tlineHeightUnit === \"%\"\n\t\t\t\t\t? // %\n\t\t\t\t\t\tlineHeightValue / 100\n\t\t\t\t\t: // em\n\t\t\t\t\t\tlineHeightValue\n\n\t\t\t// For simplicity, we currently use getTextBlockMaxFontSize() for wrapping text blocks,\n\t\t\t// even though its values can\u2019t be really used for such blocks. Specifically, for\n\t\t\t// a wrapping block like\n\t\t\t//\n\t\t\t//   12px text text text text text\n\t\t\t//   12px text 20PX TEXT TEXT TEXT\n\t\t\t//   12px text text text text text\n\t\t\t//   12px text text text text\n\t\t\t//\n\t\t\t// this function will return 20px. We then will assume the whole text block\u2019s font size to be\n\t\t\t// 20 px, even though only the second line will be affected by it.\n\t\t\tconst fontSize = getTextBlockMaxFontSize(blockNode, tree)\n\n\t\t\ttextBlockHeight = fontSize * lineHeightMultiplier\n\t\t}\n\n\t\t// If there\u2019s paragraph spacing defined (for individual text blocks, or for the whole text node),\n\t\t// it will only apply past the first text block.\n\t\tlet paragraphSpacing = 0\n\t\tif (index > 0) {\n\t\t\tparagraphSpacing = getTextBlockParagraphSpacing(blockNode, richTextNode, tree) ?? 0\n\t\t}\n\n\t\tlet wrappingMultiplier = 1\n\t\tif (isWrapping) {\n\t\t\t// We can\u2019t compute the actual number of lines in a wrapping text node (yet).\n\t\t\t// For that, we need to know 1) width of the node (computed in ./simulateCSSWidth.ts,\n\t\t\t// but needs to be intergrated with this function), 2) width of font characters\n\t\t\t// (available in font-metrics/google.json).\n\t\t\t// However, we can approximate the number of lines. We assume that header nodes\n\t\t\t// will, on average, have 1 line, and paragraph nodes will have 5 lines.\n\t\t\tconst tagName = blockNode.attrs.tag\n\t\t\tif (\n\t\t\t\ttagName === \"h1\" ||\n\t\t\t\ttagName === \"h2\" ||\n\t\t\t\ttagName === \"h3\" ||\n\t\t\t\ttagName === \"h4\" ||\n\t\t\t\ttagName === \"h5\" ||\n\t\t\t\ttagName === \"h6\"\n\t\t\t) {\n\t\t\t\twrappingMultiplier = 1\n\t\t\t} else if (tagName === \"p\" || tagName === \"div\") {\n\t\t\t\twrappingMultiplier = 5\n\t\t\t} else {\n\t\t\t\tassertNever(tagName)\n\t\t\t}\n\t\t}\n\n\t\ttotalHeight += paragraphSpacing + textBlockHeight * wrappingMultiplier\n\t}\n\n\treturn totalHeight\n}\n\n/**\n * Returns the maximum font size for a (non-wrapping) text block, taking into account style presents.\n *\n * \u201CMaximum\u201D here means that if the text block has fontSize: 12, but some span inside it has fontSize: 20,\n * we\u2019ll return fontSize: 20 because that\u2019s what ultimately defines the height of the text block.\n *\n * If the found font size is in `rem`, it will convert to a `px` value.\n */\nfunction getTextBlockMaxFontSize(prosemirrorTextBlockNode: TextBlockNode, tree: CanvasTree): number {\n\tlet fontSize = getTextBlockFontSize(prosemirrorTextBlockNode, tree)\n\n\tprosemirrorTextBlockNode.descendants((node: Node) => {\n\t\tif (!isProseMirrorTextNode(node)) return\n\n\t\tconst mark = node.marks.find(isInlineStylesMark)\n\t\tconst value = mark?.attrs.inlineStyles.fontSize\n\n\t\t// FIXME: Variable support isn\u2019t implemented at the moment\n\t\tif (isDynamicValue(value)) throw new CantCalculate()\n\t\tif (isUndefined(value)) return\n\n\t\tconst [size, fromUnit = \"px\"] = isFontSize(value) ? value : [value]\n\t\t// Root font size would make it more accurate, but since these are ProseMirror nodes, it's not\n\t\t// as easy to get as a Vekter node.\n\t\tconst sizeInPx = convertFontSizeValue(size, fromUnit, \"px\")\n\n\t\tif (sizeInPx > fontSize) {\n\t\t\tfontSize = sizeInPx\n\t\t}\n\t})\n\n\treturn fontSize\n}\n\nfunction getTextBlockFontSize(prosemirrorTextBlockNode: TextBlockNode, tree: CanvasTree): number {\n\tif (hasTextStylePreset(prosemirrorTextBlockNode)) {\n\t\tconst presetId = prosemirrorTextBlockNode.attrs.textStylePreset\n\t\tconst preset = tree.getNodeWithTrait(presetId, isTextStylePresetNode)\n\t\tif (preset) {\n\t\t\tconst [size, unit] = isFontSizeCSSDimension(preset.fontSize)\n\t\t\t\t? parseCSSDimension(preset.fontSize)\n\t\t\t\t: [preset.fontSize, \"px\"]\n\t\t\t// TODO: Can we get root font size instead of 16?\n\t\t\treturn unit === \"rem\" ? roundedNumber(size * DEFAULT_ROOT_FONT_SIZE, 0) : size\n\t\t}\n\t}\n\n\tif (!isUndefined(prosemirrorTextBlockNode.attrs.inlineStyles.fontSize)) {\n\t\tconst fontSizeOrVariable = prosemirrorTextBlockNode.attrs.inlineStyles.fontSize\n\n\t\t// FIXME: Variable support isn\u2019t implemented at the moment\n\t\tif (isDynamicValue(fontSizeOrVariable)) throw new CantCalculate()\n\t\tconst [size, fromUnit = \"px\"] = isFontSize(fontSizeOrVariable) ? fontSizeOrVariable : [fontSizeOrVariable]\n\n\t\t// Root font size would make it more accurate, but since these are ProseMirror nodes, it's not\n\t\t// as easy to get as a Vekter node.\n\t\treturn convertFontSizeValue(size, fromUnit, \"px\")\n\t}\n\n\treturn parseCSSDimension(textStyleDefaults.fontSize)[0]\n}\n\n/**\n * Returns the line height for a text block, taking into account style presents.\n */\nfunction getTextBlockLineHeight(prosemirrorTextBlockNode: TextBlockNode, tree: CanvasTree) {\n\tif (hasTextStylePreset(prosemirrorTextBlockNode)) {\n\t\tconst presetId = prosemirrorTextBlockNode.attrs.textStylePreset\n\t\tconst preset = tree.getNodeWithTrait(presetId, isTextStylePresetNode)\n\t\tif (preset) return preset.lineHeight\n\t}\n\n\tif (!isUndefined(prosemirrorTextBlockNode.attrs.blockStyles.lineHeight)) {\n\t\tconst lineHeightOrVariable = prosemirrorTextBlockNode.attrs.blockStyles.lineHeight\n\t\treturn lineHeightOrVariable\n\t}\n\n\treturn textStyleDefaults.lineHeight\n}\n\n/**\n * Returns the paragraph spacing for a text block, taking into account style presents.\n */\nfunction getTextBlockParagraphSpacing(\n\tprosemirrorTextBlockNode: TextBlockNode,\n\trichTextNode: RichTextNode,\n\ttree: CanvasTree,\n) {\n\tif (hasTextStylePreset(prosemirrorTextBlockNode)) {\n\t\tconst presetId = prosemirrorTextBlockNode.attrs.textStylePreset\n\t\tconst preset = tree.getNodeWithTrait(presetId, isTextStylePresetNode)\n\t\tif (preset) return preset.paragraphSpacing\n\t}\n\n\treturn richTextNode.paragraphSpacing\n}\n", "import { assert, assertNever, getLogger } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { getNumericColumnGapFromShorthand } from \"document/models/CanvasTree/traits/NumberShorthand.ts\"\nimport { hasImageFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { withGridItemLayout } from \"document/models/CanvasTree/traits/WithGridItemLayout.ts\"\nimport type { WithSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { isSmartComponentVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isVisibleNode } from \"document/models/CanvasTree/traits/WithVisibility.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { isNonNull, isNumber, isUndefined } from \"utils/typeChecks.ts\"\nimport {\n\tisCodeComponentNode,\n\tisOverlayNode,\n\tisRichTextNode,\n} from \"../../document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"../../document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { isGridChildFillingCellHeight } from \"../../document/models/CanvasTree/traits/WithGridItemSize.ts\"\nimport type { HasGridLayout, HasStackLayout } from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport { hasGridLayout, hasStackLayout } from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport { isPinnable } from \"../../document/models/CanvasTree/traits/WithPins.ts\"\nimport type { WithSize } from \"../../document/models/CanvasTree/traits/WithSize.ts\"\nimport { withSize } from \"../../document/models/CanvasTree/traits/WithSize.ts\"\nimport type { WithSizeConstraints } from \"../../document/models/CanvasTree/traits/WithSizeConstraints.ts\"\nimport {\n\tparseConstraintValue,\n\tsupportsSizeConstraints,\n} from \"../../document/models/CanvasTree/traits/WithSizeConstraints.ts\"\nimport {\n\tisPositionAbsolute,\n\tisPositionFixed,\n\tisPositionRelative,\n} from \"../../document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { CantCalculate } from \"./CantCalculate.ts\"\nimport type { SimulationContext } from \"./SimulationContext.ts\"\nimport type { GridLayoutInfo } from \"./grid.ts\"\nimport { getGridItemRowSpan, getGridLayoutInfo } from \"./grid.ts\"\nimport type { SimulatedDOMNumberValue } from \"./numberValue.ts\"\nimport { getImpreciseEstimate, numberConst, numberOp, numberTemplate } from \"./numberValue.ts\"\nimport { getEffectiveStackGap, getVerticalStackLayoutInfo } from \"./stack.ts\"\nimport { getApproximateAutosizingTextHeight } from \"./text.ts\"\nimport {\n\tVIEWPORT_HEIGHT,\n\tgetCanvasMeasuredWidth,\n\tgetFitImageAspectRatio,\n\tgetLayoutChildren,\n\tgetNodePaddingBottom,\n\tgetNodePaddingTop,\n\tnodeAffectsSiblings,\n\tresolveGap,\n} from \"./utils.ts\"\n\nconst logger = getLogger(\"simulateHeight\")\nconst DEFAULT_SMART_COMPONENT_HEIGHT = 200 /* px */\n\n/**\n * This function calculates how tall a node is, taking all layout information into account. This is then used\n * in simulateYPosition() to get simulate Y positions as well.\n *\n * \u201CBut can\u2019t you just read node.height?\u201D You can, if the node is a fixed-height. But what if it has a % height?\n * Or a height that equals to 3 fr? Or it\u2019s a stack with an auto height (which means summing up all heights\n * of its children)? This function handles all these cases, returning the computed height in pixels.\n *\n * Important considerations:\n * - Some of the nodes in the tree might depend on the viewport height. Since we don\u2019t know how tall the viewport\n *   will be at runtime, we approximate it to be @see VIEWPORT_HEIGHT px. For why that specific value, see a comment\n *   next to that variable :)\n *\n * - Unlike simulateCSSWidth(), this function returns a number instead of an expression like `100vh - 500px`. This\n *   leads to poorer precision (we have to approximate the viewport height), but it\u2019s a requirement because the results\n *   of height and y position algos have to be comparable to regular numbers:\n *\n *     <img loading={imageYPosition > 1000 ? \"lazy\" : undefined} />\n */\nexport function simulateHeight(node: CanvasNode & WithSize & WithSizeDimensionType, ctx: SimulationContext) {\n\ttry {\n\t\tconst value = innerSimulateHeight(node, ctx)\n\t\treturn value.type === \"number-const\" ? value.value : value.expr\n\t} catch (error) {\n\t\tif (error instanceof CantCalculate) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (process.env.NODE_ENV === \"test\") {\n\t\t\t// In tests, re-throw the error \u2013 this 1) allows to test that asserts\n\t\t\t// are working, 2) makes debugging failing tests a little easier\n\t\t\tthrow error\n\t\t}\n\n\t\tlogger.reportWithoutLogging(error, { nodeId: node.id })\n\t\tlogger.warnOncePerMinute(\n\t\t\t`Can\u2019t simulate the height for node ${node.id} because the tree doesn\u2019t match expectations. Skipping.`,\n\t\t\terror,\n\t\t)\n\t\treturn undefined\n\t}\n}\n\nexport function innerSimulateHeight(node: CanvasNode, ctx: SimulationContext): SimulatedDOMNumberValue {\n\tconst cachedHeight = ctx.cache.getHeight(node.id)\n\tif (!isUndefined(cachedHeight)) return cachedHeight\n\n\tif (ctx.workInProgress.isComputingHeightFor(node.id)) {\n\t\t// What does this error mean?\n\t\t//\n\t\t// When `simulateHeight()` is given a node to compute a height for, it\n\t\t// might need to also compute the height of its parent (e.g. if the node\n\t\t// has a % height) or children (e.g. if the node has an auto height). If\n\t\t// we\u2019re not careful, in some layouts, this might result in the\n\t\t// algorithm ending up in a cyclic walk between a parent and its\n\t\t// children.\n\t\t//\n\t\t// Normally, all cases where this could happen should be prevented\n\t\t// by this algo itself (e.g. by returning a height of 0 instead of walking\n\t\t// up). But if we miss something, we have to handle it somewhere in\n\t\t// this file to ensure the algorithm doesn\u2019t get stuck.\n\t\t//\n\t\t// This error is thrown because otherwise, the algo will just keep\n\t\t// looping until the call stack is exceeded. Better to finish early and\n\t\t// keep the main thread free.\n\t\tthrow new Error(\n\t\t\t`Detected a circular walk in simulateHeight(): we\u2019re entering a node which is already being computed. ` +\n\t\t\t\t`This would result in a call stack overflow. Exiting early.`,\n\t\t)\n\t}\n\n\tlet result: SimulatedDOMNumberValue\n\ttry {\n\t\tctx.workInProgress.startComputingHeightFor(node.id)\n\t\tresult = uncachedInnerSimulateHeight(node, ctx)\n\t} finally {\n\t\tctx.workInProgress.finishComputingHeightFor(node.id)\n\t}\n\n\t// We\u2019re caching the node height to avoid calculating it several times\n\t// if the node is visited several times during the same code generation pass.\n\t// The cache is invalidated after every code generation.\n\tctx.cache.setHeight(node.id, result)\n\treturn result\n}\n\nfunction uncachedInnerSimulateHeight(node: CanvasNode, ctx: SimulationContext): SimulatedDOMNumberValue {\n\tif (!isVisibleNode(node)) {\n\t\t// We *can* calculate the height of invisible nodes, but there\u2019s no point in doing so\n\t\t// as they won\u2019t be rendered. Let\u2019s save CPU cycles.\n\t\tthrow new CantCalculate()\n\t}\n\n\tconst parentNode = ctx.tree.getNodeParent(node)\n\n\t//\n\t// This is an overlay node. They always fill the entire viewport height\n\t//\n\tif (isOverlayNode(node)) {\n\t\treturn numberConst(VIEWPORT_HEIGHT)\n\t}\n\n\t// Most nodes handled here must have a width and a width type \u2013 with some rare exceptions (above)\n\tassert(\n\t\twithSize(node) && withSizeDimensionType(node),\n\t\t`Can\u2019t calculate the height on a node when it doesn\u2019t have size information`,\n\t)\n\n\t//\n\t// This is a smart component node. We expect its height to be provided by the parent component, since\n\t// smart component instances can be resized freely.\n\t//\n\t// If the height was not provided (which can happen if the parent component hasn\u2019t been updated since we\n\t// introduced the container viewport context), we fall back to the intrinsic height (the height that\n\t// the component had on the canvas).\n\t//\n\tif (isSmartComponentVariant(node)) {\n\t\tconst intrinsicHeight = ctx.tree.getRect(node).height\n\t\treturn numberTemplate(js`${Var.componentViewport}?.height || ${intrinsicHeight}`, intrinsicHeight)\n\t}\n\n\t//\n\t// This is a node inside a grid row, and it vertically spans the full row.\n\t// Its height is equal to the height of that row.\n\t//\n\tif (isGridChildFillingCellHeight(node)) {\n\t\treturn NodeHeightBuilder.startFromRowHeightMultipliedBySpan(node, ctx).getWithConstraints()\n\t}\n\n\t//\n\t// This is a node with top & bottom pinning. Its height depends on its parent height \u2013 because it\u2019s absolutely\n\t// positioned with `top: ...` and `bottom: ...`.\n\t// Note that we can only trust node.top and node.bottom when the node is not position: relative.\n\t// https://github.com/framer/FramerStudio/pull/17140#discussion_r1547420603\n\t//\n\tconst isTopBottomPinned =\n\t\t!isPositionRelative(node, parentNode) && isPinnable(node) && isNonNull(node.top) && isNonNull(node.bottom)\n\tif (isTopBottomPinned) {\n\t\tconst builder = isPositionFixed(node)\n\t\t\t? NodeHeightBuilder.startFromFixedValue(numberConst(VIEWPORT_HEIGHT), node, ctx)\n\t\t\t: NodeHeightBuilder.startFromParentOuterHeight(node, ctx)\n\n\t\treturn (\n\t\t\tbuilder\n\t\t\t\t// To get the node\u2019s height, subtract the top & bottom margins from the parent\u2019s outer height\n\t\t\t\t.op((height, node) => {\n\t\t\t\t\t// We check `node.top !== null && node.bottom !== null` a few lines above \u2013 but TypeScript can\u2019t transfer\n\t\t\t\t\t// that check\u2019s result here\n\t\t\t\t\tconst nodeTop = node.top\n\t\t\t\t\tconst nodeBottom = node.bottom\n\t\t\t\t\tassert(isNonNull(nodeTop) && isNonNull(nodeBottom), \"Satisfying TypeScript\")\n\t\t\t\t\treturn numberOp(\"-\", height, numberConst(nodeTop + nodeBottom))\n\t\t\t\t})\n\t\t\t\t.getWithConstraints()\n\t\t)\n\t}\n\n\t//\n\t// This is a fixed-height node, which is is always `node.height` tall (unless min/max height constraints apply).\n\t//\n\t// FIXME: this doesn\u2019t account for `aspectRatio`, but it should: https://framer-team.slack.com/archives/CR3CYA1D4/p1721595602280359\n\tif (node.heightType === DimensionType.FixedNumber) {\n\t\treturn NodeHeightBuilder.startFromFixedValue(numberConst(node.height), node, ctx).getWithConstraints()\n\t}\n\n\t//\n\t// This is a percentage-height node, which is as tall as X% of its parent.\n\t//\n\tif (node.heightType === DimensionType.Percentage) {\n\t\tassert(parentNode, `A node can\u2019t have a % height without a parent`)\n\n\t\tlet builder: NodeHeightBuilder<CanvasNode & WithSize>\n\n\t\tif (isPositionFixed(node)) {\n\t\t\t// For position: fixed nodes, % height is the same as viewport height\n\t\t\tbuilder = NodeHeightBuilder.startFromFixedValue(numberConst(VIEWPORT_HEIGHT), node, ctx)\n\t\t} else if (isPositionAbsolute(node)) {\n\t\t\t// For position: absolute nodes, % height is always computed relative to parent\u2019s outer height,\n\t\t\t// regardless of whether it\u2019s a grid or not\n\t\t\tbuilder = NodeHeightBuilder.startFromParentOuterHeight(node, ctx)\n\t\t} else if (hasGridLayout(parentNode) && withGridItemLayout(node)) {\n\t\t\t// Inside grids, % height is computed relative to the grid row height\n\t\t\tbuilder = NodeHeightBuilder.startFromRowHeightMultipliedBySpan(node, ctx)\n\t\t} else {\n\t\t\tbuilder = NodeHeightBuilder.startFromParentInnerHeight(node, ctx)\n\t\t}\n\n\t\treturn (\n\t\t\tbuilder\n\t\t\t\t// To get the node\u2019s height, multiply the parent (or grid row) height by the %.\n\t\t\t\t// (If the node has a height of 80%, `node.height` will be 0.8.)\n\t\t\t\t.op((parentHeight, node) => numberOp(\"*\", parentHeight /* px */, numberConst(node.height) /* % */))\n\t\t\t\t.getWithConstraints()\n\t\t)\n\t}\n\n\t//\n\t// This is a viewport-height node, which is as tall as a fraction of the viewport\u2019s height.\n\t// Since we don\u2019t know how large the viewport will be on runtime, we approximate it to be 1000px.\n\t//\n\tif (node.heightType === DimensionType.Viewport) {\n\t\treturn NodeHeightBuilder.startFromFixedValue(\n\t\t\tnumberConst(node.height * VIEWPORT_HEIGHT),\n\t\t\tnode,\n\t\t\tctx,\n\t\t).getWithConstraints()\n\t}\n\n\t//\n\t// A fraction-height node is a node that lives inside a stack and occupies a fraction of the available space \u2013\n\t// just like `flex-grow` values in CSS flexbox. Its behavior depends on whether the stack is vertical or horizontal,\n\t// and on whether stack wrapping is enabled.\n\t//\n\tif (node.heightType === DimensionType.FractionOfFreeSpace) {\n\t\tassert(\n\t\t\t!isPositionAbsolute(node) && !isPositionFixed(node),\n\t\t\t`FractionOfFreeSpace height is not supported for fixed or absolute node`,\n\t\t)\n\t\tassert(parentNode, `A node can\u2019t have a fractional height without a parent`)\n\t\t// fr units outside of stack layouts are generally forbidden. However,\n\t\t// projects can still end up in a state when they use them outside of a\n\t\t// stack. One of the most common cases for this (fr units in a grid,\n\t\t// https://github.com/framer/company/issues/30038#issuecomment-2303205852)\n\t\t// is common enough that we decided to support it.\n\t\t//\n\t\t// As of Nov 2024, fr nodes inside a grid behave as having an auto\n\t\t// height.\n\t\tif (!hasStackLayout(parentNode) && hasGridLayout(parentNode)) {\n\t\t\tconst nodeAutoHeight = getNodeAutoHeight(node, ctx)\n\t\t\tif (!nodeAutoHeight) throw new CantCalculate()\n\t\t\treturn nodeAutoHeight\n\t\t}\n\t\tassert(hasStackLayout(parentNode), `A node can have a fractional height only if it\u2019s inside a stack`)\n\t\tassert(parentNode.stackDirection, `A stack must have a direction defined`)\n\n\t\t// FIXME: Variable support isn\u2019t implemented at the moment\n\t\tif (isDynamicValue(parentNode.stackDirection)) throw new CantCalculate()\n\n\t\tif (parentNode.stackDirection === \"horizontal\") {\n\t\t\t// When the stack is horizontal, all elements stretch vertically.\n\t\t\t// In this situation, fraction units in height lose their typical meaning and start behaving as % units.\n\t\t\t// A 1fr tall node acts as if it was 100% of the parent height; a 0.5fr tall node acts\n\t\t\t// as if it was 50% of the parent height; and so on, regardless of stack wrapping:\n\t\t\t//\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2510           \u2502\n\t\t\t// \u2502 \u2502     \u2502 \u2502     \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t// \u2502 \u2502 1fr \u2502 \u2502 1fr \u2502 \u2502 0.6fr \u2502 \u2502\n\t\t\t// \u2502 \u2502     \u2502 \u2502     \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2518           \u2502\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t//\n\t\t\t// So here, we treat fraction units as % units and multiply the resulting inner height accordingly\n\n\t\t\treturn NodeHeightBuilder.startFromParentInnerHeight(node, ctx)\n\t\t\t\t.op((height, node) => numberOp(\"*\", height /* px */, numberConst(node.height) /* % */))\n\t\t\t\t.getWithConstraints()\n\t\t}\n\n\t\tif (parentNode.stackDirection === \"vertical\") {\n\t\t\t// When the stack is vertical, fr units in height strive to fill all available space,\n\t\t\t// scaling according to their fr value:\n\t\t\t//\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t// \u2502 \u2502  1fr  \u2502 \u2502\n\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t// \u2502 \u2502 150px \u2502 \u2502\n\t\t\t// \u2502 \u2502       \u2502 \u2502\n\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t// \u2502 \u2502  20%  \u2502 \u2502\n\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t// \u2502 \u2502       \u2502 \u2502\n\t\t\t// \u2502 \u2502  2fr  \u2502 \u2502\n\t\t\t// \u2502 \u2502       \u2502 \u2502\n\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t//\n\t\t\t// In this situation, to understand the size of the fr node, we need to consider\n\t\t\t// 1) the height of the stack\n\t\t\t// 2) the heights of all siblings\n\t\t\t// 3) whether there\u2019s a single or multiple columns\n\t\t\t// 4) whether any fr nodes have min- or max-heights set\n\t\t\t//\n\t\t\t// This is done in getVerticalStackLayoutInfo().\n\n\t\t\tassert(\n\t\t\t\twithSize(parentNode) && withSizeDimensionType(parentNode),\n\t\t\t\t\"A stack must have a size and size-dimension type\",\n\t\t\t)\n\n\t\t\t// Lay out the elements in the stack\n\t\t\tconst stackLayoutInfo = getVerticalStackLayoutInfo(\n\t\t\t\tparentNode,\n\t\t\t\tctx,\n\t\t\t\tnode => innerSimulateHeight(node, ctx),\n\t\t\t\tnode => simulateMinHeight(node, ctx),\n\t\t\t\tnode => simulateMaxHeight(node, ctx),\n\t\t\t)\n\t\t\tconst coordinates = stackLayoutInfo.findCoordinates(node.id)\n\t\t\tassert(coordinates, `Node must be found in stack`)\n\n\t\t\t// Get the height of 1fr\n\t\t\tconst frHeight = stackLayoutInfo.getFrToPxForColumn(coordinates.columnIndex)\n\t\t\tassert(frHeight, `frHeight must be available for column`)\n\n\t\t\tconst nodeHeight = numberOp(\"*\", frHeight, numberConst(node.height))\n\t\t\treturn NodeHeightBuilder.startFromFixedValue(nodeHeight, node, ctx).getWithConstraints()\n\t\t}\n\n\t\tassertNever(parentNode.stackDirection)\n\t}\n\n\t//\n\t// The height of an auto node depends on the height of its content \u2013 either text, smart component, or a stack/grid with children.\n\t//\n\tif (node.heightType === DimensionType.Auto) {\n\t\tconst nodeAutoHeight = getNodeAutoHeight(node, ctx)\n\t\tif (!nodeAutoHeight) throw new CantCalculate()\n\t\treturn nodeAutoHeight\n\t}\n\n\tif (node.heightType === DimensionType.FitImage) {\n\t\tif (!hasImageFill(node)) throw new CantCalculate()\n\t\tconst aspectRatio = getFitImageAspectRatio(node)\n\t\t// FIXME: for precision, this should be `innerSimulateCSSWidth()` once we add support for calling CSS width from height\n\t\tconst width = getCanvasMeasuredWidth(node, ctx)\n\t\tconst height = isUndefined(width) || isUndefined(aspectRatio) ? node.height : Math.round(width * (1 / aspectRatio))\n\n\t\treturn NodeHeightBuilder.startFromFixedValue(numberConst(height), node, ctx).getWithConstraints()\n\t}\n\n\tassertNever(node.heightType)\n}\n\nclass NodeHeightBuilder<NodeType extends CanvasNode & WithSize> {\n\t#height: SimulatedDOMNumberValue\n\t// Instead of storing the parent height directly, we store a lazy getter function.\n\t// The parent height is needed only in some code paths, so we\u2019re avoiding calculating it unless necessary.\n\t#getParentHeight: () => SimulatedDOMNumberValue\n\t#node: NodeType\n\t#ctx: SimulationContext\n\n\tprivate constructor(\n\t\theightToStartFrom: SimulatedDOMNumberValue,\n\t\tgetParentHeight: () => SimulatedDOMNumberValue,\n\t\tnode: NodeType,\n\t\tctx: SimulationContext,\n\t) {\n\t\tthis.#height = heightToStartFrom\n\t\tthis.#getParentHeight = getParentHeight\n\t\tthis.#node = node\n\t\tthis.#ctx = ctx\n\t}\n\n\tstatic startFromFixedValue<NodeType extends CanvasNode & WithSize>(\n\t\theightToStartFrom: SimulatedDOMNumberValue,\n\t\tnode: NodeType,\n\t\tctx: SimulationContext,\n\t) {\n\t\treturn new NodeHeightBuilder(\n\t\t\theightToStartFrom,\n\t\t\t// We don\u2019t need to _.memoize this function because SimulatedDOMCache is already caching\n\t\t\t// the result of the computation after a single run.\n\t\t\t() => {\n\t\t\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\t\t\tassert(parentNode, `Can\u2019t calculate the parent height on a node without a parent`)\n\t\t\t\tassert(\n\t\t\t\t\twithSize(parentNode) && withSizeDimensionType(parentNode),\n\t\t\t\t\t`Can\u2019t calculate the parent height on a node when a parent doesn\u2019t have size information`,\n\t\t\t\t)\n\n\t\t\t\tif (hasGridLayout(parentNode)) {\n\t\t\t\t\t// Get the height of a single row...\n\t\t\t\t\tconst rowHeight = NodeHeightBuilder.#getGridRowHeight(node, parentNode, ctx)\n\n\t\t\t\t\t// ...and multiply it by the number of rows the node spans\n\t\t\t\t\tconst rowHeightMultipliedBySpan = NodeHeightBuilder.#multiplyRowHeightBySpan(rowHeight, node, parentNode)\n\n\t\t\t\t\treturn rowHeightMultipliedBySpan\n\t\t\t\t} else {\n\t\t\t\t\treturn innerSimulateHeight(parentNode, ctx)\n\t\t\t\t}\n\t\t\t},\n\t\t\tnode,\n\t\t\tctx,\n\t\t)\n\t}\n\n\t/**\n\t * Outer height is the height of the parent node, including padding. This is primarily useful for absolute positioning;\n\t * in other cases, you\u2019d normally want to use startFromParentInnerHeight() instead.\n\t */\n\tstatic startFromParentOuterHeight<NodeType extends CanvasNode & WithSize>(node: NodeType, ctx: SimulationContext) {\n\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\tassert(parentNode, `Can\u2019t call startFromParentOuterHeight() on a node without a parent`)\n\n\t\tconst parentOuterHeight = innerSimulateHeight(parentNode, ctx)\n\n\t\treturn new NodeHeightBuilder(parentOuterHeight, () => parentOuterHeight, node, ctx)\n\t}\n\n\t/**\n\t * Inner height is the height of the node\u2019s \u201Cinsides\u201D, which is node\u2019s height minus padding. This is the standard height\n\t * that most other computations (% height, etc) are based on.\n\t */\n\tstatic startFromParentInnerHeight<NodeType extends CanvasNode & WithSize>(node: NodeType, ctx: SimulationContext) {\n\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\tassert(parentNode, `Can\u2019t call startFromParentInnerHeight() on a node without a parent`)\n\n\t\tconst parentInnerHeight = numberOp(\n\t\t\t\"-\",\n\t\t\tinnerSimulateHeight(parentNode, ctx),\n\t\t\tgetNodePaddingTop(parentNode) + getNodePaddingBottom(parentNode),\n\t\t)\n\n\t\treturn new NodeHeightBuilder(parentInnerHeight, () => parentInnerHeight, node, ctx)\n\t}\n\n\tstatic startFromRowHeightMultipliedBySpan<NodeType extends CanvasNode & WithSize>(\n\t\tnode: NodeType,\n\t\tctx: SimulationContext,\n\t) {\n\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\tassert(\n\t\t\tparentNode && hasGridLayout(parentNode),\n\t\t\t`Can\u2019t call startFromColumnHeightMultipliedBySpan() if the node isn\u2019t inside a grid`,\n\t\t)\n\n\t\t// Get the height of a single row...\n\t\tconst rowHeight = NodeHeightBuilder.#getGridRowHeight(node, parentNode, ctx)\n\n\t\t// ...and multiply it by the number of rows the node spans\n\t\tconst rowHeightMultipliedBySpan = NodeHeightBuilder.#multiplyRowHeightBySpan(rowHeight, node, parentNode)\n\n\t\treturn new NodeHeightBuilder(\n\t\t\trowHeightMultipliedBySpan,\n\t\t\t// Inside a grid, any % calculations are relative to the column height, not to the grid container height.\n\t\t\t// Hence we\u2019re passing the column height as the parent height.\n\t\t\t() => rowHeightMultipliedBySpan,\n\t\t\tnode,\n\t\t\tctx,\n\t\t)\n\t}\n\n\tstatic #getGridRowHeight(gridItem: CanvasNode, gridNode: CanvasNode & HasGridLayout, ctx: SimulationContext) {\n\t\tassert(!isUndefined(gridNode.gridRowHeightType), `A grid node must have gridRowHeightType defined`)\n\n\t\tif (gridNode.gridRowHeightType === \"fixed\") {\n\t\t\tassert(!isUndefined(gridNode.gridRowHeight), `A fixed-height grid node must have gridRowHeight defined`)\n\t\t\treturn numberConst(gridNode.gridRowHeight)\n\t\t} else if (gridNode.gridRowHeightType === \"fit\") {\n\t\t\t// This is a grid where each row is as tall as its tallest child is:\n\t\t\t//\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2510\u2502\n\t\t\t// \u2502\u2502    \u2502 \u2502   \u2502\u2502\n\t\t\t// \u2502\u2502    \u2502 \u2514\u2500\u2500\u2500\u2518\u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2518      \u2502\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u250C\u2500\u2500\u2500\u2510\u2502\n\t\t\t// \u2502\u2502   \u2502  \u2502   \u2502\u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2502   \u2502\u2502\n\t\t\t// \u2502       \u2502   \u2502\u2502\n\t\t\t// \u2502       \u2514\u2500\u2500\u2500\u2518\u2502\n\t\t\t// \u2502            \u2502\n\t\t\t// \u2502            \u2502\n\t\t\t// \u2502            \u2502\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t//\n\t\t\t// In this grid, the height of a row is the height of the tallest item in that row.\n\n\t\t\tconst gridLayoutInfo = getGridLayoutInfo(gridNode, ctx)\n\t\t\tif (gridLayoutInfo.isEmpty()) {\n\t\t\t\t// We could end up here if e.g. the `gridNode` is a data repeater,\n\t\t\t\t// and the `gridItem` is the repeater template, but the data is empty.\n\t\t\t\treturn numberConst(0)\n\t\t\t}\n\n\t\t\tconst gridCoordinates = gridLayoutInfo.findCoordinates(gridItem.id)\n\t\t\tassert(gridCoordinates, `Node must be found in the grid layout`)\n\n\t\t\tconst rowIndex = gridCoordinates.rowIndex\n\t\t\treturn getFitGridRowHeight(ctx, gridLayoutInfo, gridNode, rowIndex)\n\t\t} else if (gridNode.gridRowHeightType === \"auto\") {\n\t\t\t// This is a grid where rows fill all available space evenly:\n\t\t\t//\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2510\u2502  \u2500\u2500\u2510\n\t\t\t// \u2502\u2502    \u2502 \u2502   \u2502\u2502    \u2502\n\t\t\t// \u2502\u2502    \u2502 \u2514\u2500\u2500\u2500\u2518\u2502    \u2502 row 1: 50% of the grid\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2518      \u2502    \u2502\n\t\t\t// \u2502            \u2502  \u2500\u2500\u2518\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u250C\u2500\u2500\u2500\u2510\u2502  \u2500\u2500\u2510\n\t\t\t// \u2502\u2502   \u2502  \u2502   \u2502\u2502    \u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2502   \u2502\u2502    \u2502 row 2: 50% of the grid\n\t\t\t// \u2502       \u2502   \u2502\u2502    \u2502\n\t\t\t// \u2502       \u2514\u2500\u2500\u2500\u2518\u2502  \u2500\u2500\u2518\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t//\n\t\t\t// In this grid, the height of a row is the height of the grid container,\n\t\t\t// divided by the number of rows (accounting for gaps)\n\n\t\t\tconst nodeHeight = innerSimulateHeight(gridNode, ctx)\n\t\t\tconst contentHeight = numberOp(\"-\", nodeHeight, getNodePaddingTop(gridNode) + getNodePaddingBottom(gridNode))\n\n\t\t\tconst rowCount = getGridLayoutInfo(gridNode, ctx).rowCount\n\t\t\tconst resolvedGap = resolveGap(gridNode.gap)\n\t\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\t\tconst totalGaps = (rowCount - 1) * gap\n\n\t\t\tconst singleRowHeight = numberOp(\"/\", numberOp(\"-\", contentHeight, totalGaps), rowCount)\n\t\t\treturn singleRowHeight\n\t\t} else {\n\t\t\tassertNever(gridNode.gridRowHeightType)\n\t\t}\n\t}\n\n\tstatic #multiplyRowHeightBySpan(\n\t\trowHeight: SimulatedDOMNumberValue,\n\t\tnode: CanvasNode,\n\t\tparentNode: CanvasNode & HasGridLayout,\n\t) {\n\t\tconst rowSpan = getGridItemRowSpan(node, parentNode)\n\t\tconst resolvedGap = resolveGap(parentNode.gap)\n\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\tconst nodeScrollHeight = numberOp(\"+\", numberOp(\"*\", rowHeight, rowSpan), gap * (rowSpan - 1))\n\t\treturn nodeScrollHeight\n\t}\n\n\top(callback: (height: SimulatedDOMNumberValue, node: NodeType) => SimulatedDOMNumberValue) {\n\t\tthis.#height = callback(this.#height, this.#node)\n\t\treturn this\n\t}\n\n\tgetWithConstraints() {\n\t\tthis.#height = NodeHeightBuilder.#applyMinMaxConstraints(this.#height, this.#node, this.#ctx, this.#getParentHeight)\n\t\treturn this.#height\n\t}\n\n\tstatic #applyMinMaxConstraints(\n\t\tvalue: SimulatedDOMNumberValue,\n\t\tnode: CanvasNode,\n\t\tctx: SimulationContext,\n\t\tgetParentHeight: () => SimulatedDOMNumberValue,\n\t) {\n\t\tlet result = value\n\n\t\tif (!supportsSizeConstraints(node)) {\n\t\t\treturn result\n\t\t}\n\n\t\tif (node.maxHeight) {\n\t\t\tresult = NodeHeightBuilder.#applyMinMaxHeightConstraint(\"maxHeight\", result, node, ctx, getParentHeight)\n\t\t}\n\t\tif (node.minHeight) {\n\t\t\tresult = NodeHeightBuilder.#applyMinMaxHeightConstraint(\"minHeight\", result, node, ctx, getParentHeight)\n\t\t}\n\n\t\treturn result\n\t}\n\n\tstatic #applyMinMaxHeightConstraint<NodeType extends CanvasNode & WithSizeConstraints>(\n\t\tconstraint: \"minHeight\" | \"maxHeight\",\n\t\tnodeHeight: SimulatedDOMNumberValue,\n\t\tnode: NodeType,\n\t\tctx: SimulationContext,\n\t\tgetParentHeight: () => SimulatedDOMNumberValue,\n\t) {\n\t\t// This is counterintuitive, but to get a *min* height, you need to apply\n\t\t// the *max* function, and vice versa. If a node\u2019s minHeight is 100px,\n\t\t// and the calculated height is 90px, the effective height must be 100px.\n\t\t// This is achieved with max(90px, 100px), not min().\n\t\tconst operationToApply = constraint === \"minHeight\" ? \"max\" : \"min\"\n\n\t\tconst [value, unit] = parseConstraintValue(node[constraint])\n\t\tif (unit === \"%\") {\n\t\t\t// Per the CSS spec, % min-max heights are ignored for nodes that have an\n\t\t\t// auto height. We follow the same rule, or we\u2019ll get into an infinite\n\t\t\t// up\u2192down\u2192up\u2192down tree walk.\n\t\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\t\tassert(parentNode, `parentNode must exist for a node with percentage min-max heights`)\n\t\t\tif (withSizeDimensionType(parentNode) && parentNode.heightType === DimensionType.Auto) return nodeHeight\n\n\t\t\tconst parentNodeHeight = getParentHeight()\n\n\t\t\t// If the minHeight or maxHeight is expressed in %, that \u201C%\u201D is a % of\n\t\t\t// the parent\u2019s height.\n\t\t\t//\n\t\t\t//     minHeight == 30% -> max(${nodeHeight}, ${parentHeight} * 30%)\n\t\t\t//\n\t\t\treturn numberOp(operationToApply, nodeHeight, numberOp(\"*\", parentNodeHeight, value / 100))\n\t\t} else if (unit === \"px\") {\n\t\t\t// If the minHeight or maxHeight is expressed in pixels or viewport\n\t\t\t// relative, we just apply that:\n\t\t\t//\n\t\t\t//     minHeight == 300px -> max(${nodeHeight}, 300px)\n\t\t\t//\n\t\t\treturn numberOp(operationToApply, nodeHeight, value)\n\t\t} else if (unit === \"vh\") {\n\t\t\treturn numberOp(operationToApply, nodeHeight, (VIEWPORT_HEIGHT * value) / 100)\n\t\t} else {\n\t\t\tassertNever(unit)\n\t\t}\n\t}\n}\n\nfunction getNodeAutoHeight(\n\tnode: CanvasNode & WithSize & WithSizeDimensionType,\n\tctx: SimulationContext,\n): SimulatedDOMNumberValue | null {\n\treturn ctx.cache.memo(`autoHeight-${node.id}`, () => uncachedGetNodeAutoHeight(node, ctx))\n}\n\nfunction uncachedGetNodeAutoHeight(\n\tnode: CanvasNode & WithSize & WithSizeDimensionType,\n\tctx: SimulationContext,\n): SimulatedDOMNumberValue | null {\n\t// Text nodes\n\tif (isRichTextNode(node)) {\n\t\tconst approximateTextHeight = getApproximateAutosizingTextHeight(node, ctx.tree)\n\n\t\treturn NodeHeightBuilder.startFromFixedValue(numberConst(approximateTextHeight), node, ctx).getWithConstraints()\n\t}\n\n\t// Smart and code components\n\tif (isCodeComponentNode(node)) {\n\t\t// Smart components pose an interesting challenge: we likely have the height simulated for them,\n\t\t// but we can\u2019t pass that *simulated* height up to the parent when the parent renders.\n\t\t// (Or maybe we can, using annotations, like `@framerSimulatedHeight \"500 + ${props.foo} ? 300 : 200\"`?)\n\t\t//\n\t\t// So we take a shortcut \u2013 and instead of returning the precise simulated height, use the intrinsic height,\n\t\t// or the height of 200 px if that\u2019s not available.\n\t\tconst codeComponentIntrinsicHeight =\n\t\t\tnode.getIntrinsicSize(ctx.componentLoader).height ?? DEFAULT_SMART_COMPONENT_HEIGHT\n\t\treturn NodeHeightBuilder.startFromFixedValue(\n\t\t\tnumberConst(codeComponentIntrinsicHeight),\n\t\t\tnode,\n\t\t\tctx,\n\t\t).getWithConstraints()\n\t}\n\n\t// Stack nodes\n\tif (hasStackLayout(node)) {\n\t\tassert(node.stackDirection, `A stack must have a direction defined`)\n\n\t\t// FIXME: Variable support isn\u2019t implemented at the moment\n\t\tif (isDynamicValue(node.stackDirection)) throw new CantCalculate()\n\n\t\tif (node.stackDirection === \"horizontal\") {\n\t\t\tif (node.stackWrapEnabled) {\n\t\t\t\t// FIXME: we don\u2019t support horizontal wrapping stacks at the moment because\n\t\t\t\t// - to compute their height, we need to know how many rows they have;\n\t\t\t\t// - to learn how many rows they have, we need to know the width of every child.\n\t\t\t\t//\n\t\t\t\t// We can totally learn the width of every child (via ./simulateWidth.ts),\n\t\t\t\t// but this just needs to be integrated.\n\t\t\t\tthrow new CantCalculate()\n\t\t\t} else {\n\t\t\t\t// This stack will look like this:\n\t\t\t\t//\n\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2510 \u250C\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t\t// \u2502 \u2502        \u2502 \u2502 \u2502 \u2502   \u2502 \u2502    \u2502 \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 \u2514\u2500\u2500\u2500\u2518 \u2502    \u2502 \u2502\n\t\t\t\t// \u2502            \u2502 \u2502       \u2502    \u2502 \u2502\n\t\t\t\t// \u2502            \u2514\u2500\u2518       \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t//\n\t\t\t\t// In this situation,\n\t\t\t\t//   stackHeight := max(height of its children) + top padding + bottom padding\n\n\t\t\t\tconst maxChildHeight = getMaxChildHeightInHorizontalStack(node, ctx)\n\n\t\t\t\treturn NodeHeightBuilder.startFromFixedValue(maxChildHeight, node, ctx)\n\t\t\t\t\t.op((height, node) => numberOp(\"+\", height, getNodePaddingTop(node) + getNodePaddingBottom(node)))\n\t\t\t\t\t.getWithConstraints()\n\t\t\t}\n\t\t} else if (node.stackDirection === \"vertical\") {\n\t\t\t// This stack will look like this (if it doesn\u2019t wrap):\n\t\t\t//\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u2502\n\t\t\t// \u2502\u2502   \u2502  \u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2502\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2500\u2510\u2502\n\t\t\t// \u2502\u2502     \u2502\u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2500\u2518\u2502\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u2502\n\t\t\t// \u2502\u2502   \u2502  \u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2502\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t//\n\t\t\t// or like this (if it wraps):\n\t\t\t//\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510   \u250C\u2500\u2510\u2502\n\t\t\t// \u2502\u2502   \u2502   \u2502 \u2502\u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2518\u2502\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2510\u2502\n\t\t\t// \u2502\u2502     \u2502 \u2502 \u2502\u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502\u2502\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510   \u2514\u2500\u2518\u2502\n\t\t\t// \u2502\u2502   \u2502      \u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518      \u2502\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t//\n\t\t\t// The key thing about this auto-height stack, however, is that it will only wrap\n\t\t\t// when max-height is set, and when the max-height is lower than the height\n\t\t\t// of all children together.\n\t\t\t//\n\t\t\t// In this situation, if the stack is wrapping, to compute its height,\n\t\t\t// we lay out the children into a column until we reach maxHeight, then continue\n\t\t\t// into the next column, and so on. (And then pick the tallest column.) And if\n\t\t\t// the stack is non-wrapping or its max-height isn\u2019t set, we use the same algorithm\n\t\t\t// but just default maxHeight to Infinity.\n\n\t\t\tconst maxHeightEstimate = getMaxHeightEstimateForVerticalAutoStack(node, ctx)\n\n\t\t\tconst maxColumnHeight = getMaxColumnHeightInVerticalAutoStack(node, ctx, maxHeightEstimate)\n\n\t\t\treturn NodeHeightBuilder.startFromFixedValue(maxColumnHeight, node, ctx)\n\t\t\t\t.op((height, node) => numberOp(\"+\", height, getNodePaddingTop(node) + getNodePaddingBottom(node)))\n\t\t\t\t.getWithConstraints()\n\t\t} else {\n\t\t\tassertNever(node.stackDirection)\n\t\t}\n\t}\n\n\t// Grid nodes\n\tif (hasGridLayout(node)) {\n\t\tassert(!isUndefined(node.gridColumnCount), `A grid node must have gridColumnCount`)\n\n\t\tif (node.gridColumnCount === \"auto-fill\") {\n\t\t\t// With auto-fill grid columns, the row the current node will be in depends on the widths of siblings,\n\t\t\t// and the width of the grid itself. E.g., in this grid, the node marked X is in the second row:\n\t\t\t//\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2502\n\t\t\t// \u2502\u2502   \u2502 \u2502      \u2502\u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2502\n\t\t\t// \u2502\u250C\u2500\u2510   \u250C\u2500\u2500\u2500\u2510   \u2502\n\t\t\t// \u2502\u2502X\u2502   \u2502   \u2502   \u2502\n\t\t\t// \u2502\u2514\u2500\u2518   \u2514\u2500\u2500\u2500\u2518   \u2502\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t//\n\t\t\t// But if you make the grid wider, the node will automatically reflow to the first row:\n\t\t\t//\n\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2510\u2502\n\t\t\t// \u2502\u2502   \u2502 \u2502      \u2502 \u2502X\u2502\u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2518\u2502\n\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510             \u2502\n\t\t\t// \u2502\u2502   \u2502             \u2502\n\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518             \u2502\n\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t//\n\t\t\t// To compute `y` of that \u201CX\u201D node in such grid, we need to know which row\n\t\t\t// it is in. For that, we need to know node widths. We know them already\n\t\t\t// (see computeCSSWidth), but we need to integrate that algorithm with this one.\n\t\t\t//\n\t\t\t// FIXME: support this case\n\t\t\tthrow new CantCalculate()\n\t\t}\n\n\t\t// fixed number of columns\n\t\tif (isNumber(node.gridColumnCount)) {\n\t\t\tassert(!isUndefined(node.gridRowHeightType), `A grid must have gridRowHeightType defined`)\n\n\t\t\tconst gridLayoutInfo = getGridLayoutInfo(node, ctx)\n\n\t\t\tif (node.gridRowHeightType === \"fixed\") {\n\t\t\t\t// This is a grid where each row has a fixed height:\n\t\t\t\t//\n\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2510   \u2502\n\t\t\t\t// \u2502\u2502    \u2502 \u2502   \u2502   \u2502\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2518   \u2502\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2502\n\t\t\t\t// \u2502\u2502   \u2502  \u2502      \u2502\u2502\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2502\n\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t//\n\t\t\t\t// In this case,\n\t\t\t\t//   gridHeight := row height * row count + total gaps + paddings\n\n\t\t\t\tassert(!isUndefined(node.gridRowHeight), `A node with gridRowHeightType: fixed must have gridRowHeight defined`)\n\n\t\t\t\tconst rowCount = gridLayoutInfo.rowCount\n\t\t\t\tconst resolvedGap = resolveGap(node.gap)\n\t\t\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\t\t\tconst totalGaps = (gridLayoutInfo.rowCount - 1) * gap\n\t\t\t\tconst rowHeight = node.gridRowHeight\n\n\t\t\t\tconst contentHeight = rowHeight * rowCount + totalGaps\n\n\t\t\t\treturn NodeHeightBuilder.startFromFixedValue(numberConst(contentHeight), node, ctx)\n\t\t\t\t\t.op((height, node) => numberOp(\"+\", height, getNodePaddingTop(node) + getNodePaddingBottom(node)))\n\t\t\t\t\t.getWithConstraints()\n\t\t\t} else if (node.gridRowHeightType === \"fit\") {\n\t\t\t\t// This is a grid where each row is as tall as its tallest child is:\n\t\t\t\t//\n\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2510\u2502\n\t\t\t\t// \u2502\u2502    \u2502 \u2502   \u2502\u2502\n\t\t\t\t// \u2502\u2502    \u2502 \u2514\u2500\u2500\u2500\u2518\u2502\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2518      \u2502\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u250C\u2500\u2500\u2500\u2510\u2502\n\t\t\t\t// \u2502\u2502   \u2502  \u2502   \u2502\u2502\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2502   \u2502\u2502\n\t\t\t\t// \u2502       \u2502   \u2502\u2502\n\t\t\t\t// \u2502       \u2514\u2500\u2500\u2500\u2518\u2502\n\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t//\n\t\t\t\t// In this case,\n\t\t\t\t//   gridHeight := sum(tallest child in each row) + total gaps\n\n\t\t\t\tlet totalRowHeights: SimulatedDOMNumberValue = numberConst(0)\n\t\t\t\tfor (let rowIndex = 0; rowIndex < gridLayoutInfo.rowCount; rowIndex++) {\n\t\t\t\t\tconst rowHeight = getFitGridRowHeight(ctx, gridLayoutInfo, node, rowIndex)\n\t\t\t\t\ttotalRowHeights = numberOp(\"+\", totalRowHeights, rowHeight)\n\t\t\t\t}\n\n\t\t\t\tconst resolvedGap = resolveGap(node.gap)\n\t\t\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\t\t\tconst totalGaps = (gridLayoutInfo.rowCount - 1) * gap\n\t\t\t\tconst contentHeight = numberOp(\"+\", totalRowHeights, totalGaps)\n\n\t\t\t\treturn NodeHeightBuilder.startFromFixedValue(contentHeight, node, ctx)\n\t\t\t\t\t.op((height, node) => numberOp(\"+\", height, getNodePaddingTop(node) + getNodePaddingBottom(node)))\n\t\t\t\t\t.getWithConstraints()\n\t\t\t} else if (node.gridRowHeightType === \"auto\") {\n\t\t\t\t// This is a case that\u2019s forbidden in the UI. But because some UIs may end up\n\t\t\t\t// in a forbidden state (https://github.com/framer/company/issues/30038), and\n\t\t\t\t// this state is *very* common, we still support it in simulated DOM.\n\t\t\t\t//\n\t\t\t\t// As of Jul 2024, in this forbidden state,\n\t\t\t\t//   gridHeight := sum(row heights) + sum(gaps),\n\t\t\t\t//   where\n\t\t\t\t//     row height := tallest child *in the whole grid*\n\t\t\t\t//\n\t\t\t\t// That means the grid in such state would look as follows:\n\t\t\t\t//\n\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2510\u2502\n\t\t\t\t// \u2502\u2502    \u2502 \u2502   \u2502\u2502\n\t\t\t\t// \u2502\u2502    \u2502 \u2514\u2500\u2500\u2500\u2518\u2502\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2518      \u2502\n\t\t\t\t// \u2502            \u2502\n\t\t\t\t// \u2502            \u2502\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u250C\u2500\u2500\u2500\u2510\u2502\n\t\t\t\t// \u2502\u2502   \u2502  \u2502   \u2502\u2502 \u2190 Tallest child sets the height of all rows\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2502   \u2502\u2502\n\t\t\t\t// \u2502       \u2502   \u2502\u2502\n\t\t\t\t// \u2502       \u2502   \u2502\u2502\n\t\t\t\t// \u2502       \u2514\u2500\u2500\u2500\u2518\u2502\n\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t//\n\t\t\t\t// Note that since this layout is forbidden, the way Framer is rendering/\n\t\t\t\t// codegenerating it can change at any moment, making this implementation\n\t\t\t\t// outdated.\n\n\t\t\t\tlet maxCellHeight: SimulatedDOMNumberValue = numberConst(0)\n\t\t\t\tfor (let rowIndex = 0; rowIndex < gridLayoutInfo.rowCount; rowIndex++) {\n\t\t\t\t\tfor (let columnIndex = 0; columnIndex < gridLayoutInfo.columnCount; columnIndex++) {\n\t\t\t\t\t\tconst childId = gridLayoutInfo.getGridItem(rowIndex, columnIndex)\n\t\t\t\t\t\t// Some grid cells might be empty\n\t\t\t\t\t\tif (!childId) continue\n\n\t\t\t\t\t\tconst child = ctx.tree.getNode(childId)\n\t\t\t\t\t\tassert(child, `Can\u2019t find grid item in the tree`)\n\n\t\t\t\t\t\tif (!withSize(child) || !withSizeDimensionType(child)) continue\n\n\t\t\t\t\t\tconst cellHeight = getGridItemHeightInFitOrAutoRow(child, node, ctx)\n\n\t\t\t\t\t\tmaxCellHeight = numberOp(\"max\", maxCellHeight, cellHeight)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst totalRowHeights = numberOp(\"*\", maxCellHeight, gridLayoutInfo.rowCount)\n\t\t\t\tconst resolvedGap = resolveGap(node.gap)\n\t\t\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\t\t\tconst totalGaps = (gridLayoutInfo.rowCount - 1) * gap\n\t\t\t\tconst contentHeight = numberOp(\"+\", totalRowHeights, totalGaps)\n\n\t\t\t\treturn NodeHeightBuilder.startFromFixedValue(contentHeight, node, ctx)\n\t\t\t\t\t.op((height, node) => numberOp(\"+\", height, getNodePaddingTop(node) + getNodePaddingBottom(node)))\n\t\t\t\t\t.getWithConstraints()\n\t\t\t} else {\n\t\t\t\tassertNever(node.gridRowHeightType)\n\t\t\t}\n\t\t}\n\n\t\tassertNever(node.gridColumnCount)\n\t}\n\n\t// If we arrived here, it\u2019s one of:\n\t// - Something else (not text/stack/grid) has height: auto, and we don\u2019t support that yet\n\t// - It\u2019s an impossible state that got created due to overrides, and it looks broken on the live site as well\n\treturn null\n}\n\nfunction getMaxChildHeightInHorizontalStack(\n\tnode: CanvasNode & WithSize & WithSizeDimensionType & HasStackLayout,\n\tctx: SimulationContext,\n) {\n\tlet maxChildHeight: SimulatedDOMNumberValue = numberConst(0)\n\n\tfor (const child of node.children ?? []) {\n\t\tif (!withSize(child) || !withSizeDimensionType(child)) continue\n\n\t\tif (\n\t\t\t!nodeAffectsSiblings(\n\t\t\t\tchild,\n\t\t\t\tnode,\n\t\t\t\tctx.tree,\n\t\t\t\t// We don\u2019t really know how to support the case when some node is visible or hidden\n\t\t\t\t// based on a variable, so let\u2019s just use the current variable\u2019s value\n\t\t\t\ttrue,\n\t\t\t)\n\t\t) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Percentage-height nodes (and fr-height nodes, which in a horizontal stack behave just like percentage-height)\n\t\t// don\u2019t affect auto computations and simply fill the parent once the height is computed.\n\t\tif (child.heightType === DimensionType.Percentage || child.heightType === DimensionType.FractionOfFreeSpace) {\n\t\t\tcontinue\n\t\t}\n\n\t\tmaxChildHeight = numberOp(\"max\", maxChildHeight, innerSimulateHeight(child, ctx))\n\t}\n\n\treturn maxChildHeight\n}\n\nfunction getMaxHeightEstimateForVerticalAutoStack(\n\tnode: CanvasNode & WithSize & WithSizeDimensionType & HasStackLayout,\n\tctx: SimulationContext,\n) {\n\tif (\n\t\twithSize(node) &&\n\t\tsupportsSizeConstraints(node) &&\n\t\t!isUndefined(node.maxHeight) &&\n\t\t// A vertical auto-sized stack will only have a max height if it\u2019s actually wrapping\n\t\tnode.stackWrapEnabled\n\t) {\n\t\tconst maxHeight = simulateMaxHeight(node, ctx)\n\t\tconst maxInnerHeight = numberOp(\"-\", maxHeight, getNodePaddingTop(node) + getNodePaddingBottom(node))\n\t\treturn getImpreciseEstimate(maxInnerHeight)\n\t}\n\n\treturn Infinity\n}\n\nfunction getMaxColumnHeightInVerticalAutoStack(\n\tnode: CanvasNode & WithSize & WithSizeDimensionType & HasStackLayout,\n\tctx: SimulationContext,\n\tmaxHeightEstimate: number,\n) {\n\tconst effectiveStackGap = getEffectiveStackGap(node)\n\tconst stackGap = getNumericColumnGapFromShorthand(effectiveStackGap)\n\tconst columnHeights: SimulatedDOMNumberValue[] = []\n\n\t// This is a version of the algo in `getVerticalStackLayoutInfo()`,\n\t// but simplified and adapted to auto-height stack requirements\n\tfor (const child of getLayoutChildren(ctx.componentLoader, node)) {\n\t\tif (!withSize(child) || !withSizeDimensionType(child)) continue\n\n\t\tif (\n\t\t\t!nodeAffectsSiblings(\n\t\t\t\tchild,\n\t\t\t\tnode,\n\t\t\t\tctx.tree,\n\t\t\t\t// We don\u2019t really know how to support the case when some node is visible or hidden\n\t\t\t\t// based on a variable, so let\u2019s just use the current variable\u2019s value\n\t\t\t\ttrue,\n\t\t\t)\n\t\t) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlet currentChildHeight\n\t\tswitch (child.heightType) {\n\t\t\tcase DimensionType.FractionOfFreeSpace:\n\t\t\t\tcurrentChildHeight = simulateMinHeight(child, ctx)\n\t\t\t\tbreak\n\t\t\tcase DimensionType.Percentage:\n\t\t\t\t// A percentage-height node in an auto-height stack, per the CSS spec,\n\t\t\t\t// evaluates to 0 px. We can\u2019t end up in this state through Framer UI,\n\t\t\t\t// but it\u2019s good to be extra defensive.\n\t\t\t\tcurrentChildHeight = numberConst(0)\n\t\t\t\tbreak\n\t\t\tcase DimensionType.FixedNumber:\n\t\t\tcase DimensionType.Auto:\n\t\t\tcase DimensionType.Viewport:\n\t\t\tcase DimensionType.FitImage:\n\t\t\t\tcurrentChildHeight = innerSimulateHeight(child, ctx)\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tassertNever(child.heightType)\n\t\t}\n\n\t\tconst columnHeight = columnHeights[columnHeights.length - 1] ?? numberConst(0)\n\t\tconst columnHeightPlusChild = numberOp(\"+\", columnHeight, stackGap, currentChildHeight)\n\n\t\tconst childWouldOverflowColumn =\n\t\t\tMath.ceil(getImpreciseEstimate(columnHeightPlusChild)) > Math.ceil(maxHeightEstimate)\n\n\t\tif (\n\t\t\tchildWouldOverflowColumn ||\n\t\t\t// Edge case: if we\u2019re just starting, the first element always goes into the first column\n\t\t\tcolumnHeights.length === 0\n\t\t) {\n\t\t\tcolumnHeights.push(currentChildHeight)\n\t\t} else {\n\t\t\tcolumnHeights[columnHeights.length - 1] = columnHeightPlusChild\n\t\t}\n\t}\n\n\t// Find the max column height\n\tconst maxColumnHeight = numberOp(\"max\", ...columnHeights) ?? numberConst(0)\n\n\treturn maxColumnHeight\n}\n\nfunction getFitGridRowHeight(\n\tctx: SimulationContext,\n\tgridLayoutInfo: GridLayoutInfo,\n\tgridNode: CanvasNode & HasGridLayout,\n\trowIndex: number,\n): SimulatedDOMNumberValue {\n\tlet maxCellHeight: SimulatedDOMNumberValue = numberConst(0)\n\n\tfor (let columnIndex = 0; columnIndex < gridLayoutInfo.columnCount; columnIndex++) {\n\t\tconst childId = gridLayoutInfo.getGridItem(rowIndex, columnIndex)\n\t\t// Some grid cells might be empty\n\t\tif (!childId) continue\n\n\t\tconst child = ctx.tree.getNode(childId)\n\t\tassert(child, `Can\u2019t find grid item in the tree`)\n\n\t\tif (!withSize(child) || !withSizeDimensionType(child)) continue\n\n\t\t// Note: we might end up calling `getNodeAutoHeight` or `innerSimulateHeight` on the same child multiple times\n\t\t// (if it spans multiple columns), but this is essentially free thanks to caching in them.\n\t\tconst cellHeight = experiments.isOn(\"gridBentoFit\")\n\t\t\t? getGridItemHeightInFitOrAutoRow(child, gridNode, ctx)\n\t\t\t: child.heightType === DimensionType.Percentage\n\t\t\t\t? // %-sized children make the row as tall as their auto-height is.\n\t\t\t\t\t// In the \u201Cheight: fit\u201D grid row, a 125%-sized child will:\n\t\t\t\t\t// - make the cell as tall as 100% of its auto height\n\t\t\t\t\t// - then expand (overflowing the cell) to 125% of its auto height\n\t\t\t\t\t// Likewise, a 75%-sized child will:\n\t\t\t\t\t// - make the cell as tall as 100% of its auto height\n\t\t\t\t\t// - then shrink (leaving the cell partially empty) to 75% of\n\t\t\t\t\t//   its auto height\n\t\t\t\t\t(getNodeAutoHeight(child, ctx) ??\n\t\t\t\t\t// However, if a child doesn\u2019t have an auto height to take (e.g.\n\t\t\t\t\t// it doesn\u2019t have children), it doesn\u2019t affect the row height.\n\t\t\t\t\tnumberConst(0))\n\t\t\t\t: innerSimulateHeight(child, ctx)\n\n\t\tmaxCellHeight = numberOp(\"max\", maxCellHeight, cellHeight)\n\t}\n\n\treturn maxCellHeight\n}\n\nfunction getGridItemHeightInFitOrAutoRow(\n\tchild: CanvasNode & WithSize & WithSizeDimensionType,\n\tgrid: CanvasNode & HasGridLayout,\n\tctx: SimulationContext,\n): SimulatedDOMNumberValue {\n\tlet cellHeight =\n\t\tchild.heightType === DimensionType.Percentage || isGridChildFillingCellHeight(child)\n\t\t\t? // %-sized children (and children that fill their cell) make the row\n\t\t\t\t// as tall as their *auto-height* is.\n\t\t\t\t// In the \u201Cheight: fit\u201D grid row, a 125%-sized child will:\n\t\t\t\t// - make the cell as tall as 100% of its auto height\n\t\t\t\t// - then expand (overflowing the cell) to 125% of its auto height\n\t\t\t\t// Likewise, a 75%-sized child will:\n\t\t\t\t// - make the cell as tall as 100% of its auto height\n\t\t\t\t// - then shrink (leaving the cell partially empty) to 75% of\n\t\t\t\t//   its auto height\n\t\t\t\t(getNodeAutoHeight(child, ctx) ??\n\t\t\t\t// However, if a child doesn\u2019t have an auto height to take (e.g.\n\t\t\t\t// it doesn\u2019t have children), it doesn\u2019t affect the row height.\n\t\t\t\tnumberConst(0))\n\t\t\t: innerSimulateHeight(child, ctx)\n\n\tconst rowSpan = getGridItemRowSpan(child, grid)\n\tif (rowSpan > 1) {\n\t\tconst resolvedGap = resolveGap(grid.gap)\n\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\tconst totalGaps = gap * (rowSpan - 1)\n\t\tcellHeight = numberOp(\"/\", numberOp(\"-\", cellHeight, totalGaps), rowSpan)\n\t}\n\n\treturn cellHeight\n}\n\n/**\n * Returns the effective min height of the node in pixels.\n *\n * The difference between this and node.minHeight is that the latter might be in % and vh units as well,\n * whereas this function returns the effective simulated value in pixels.\n * */\nexport function simulateMinHeight(node: CanvasNode, ctx: SimulationContext): SimulatedDOMNumberValue {\n\tconst zero = numberConst(0)\n\n\tif (!withSize(node)) return zero\n\t// This is a little convoluted, but we\u2019re calling getWithMinMaxConstraints() and not just\n\t// returning node.minHeight because maxHeight might also affect computations.\n\treturn NodeHeightBuilder.startFromFixedValue(zero, node, ctx).getWithConstraints()\n}\n\n/**\n * Returns the effective max height of the node in pixels.\n *\n * The difference between this and node.maxHeight is that\n * 1) the latter might be in % and vh units as well, whereas this function\n *    returns the effective simulated value in pixels;\n * 2) minHeight will take precedence over maxHeight if the former is larger,\n *    and this function accounts for that.\n */\nexport function simulateMaxHeight(node: CanvasNode, ctx: SimulationContext): SimulatedDOMNumberValue {\n\tconst infinity = numberConst(Infinity)\n\n\tif (!withSize(node)) return infinity\n\t// This is a little convoluted, but we\u2019re calling getWithMinMaxConstraints() and not just\n\t// returning node.maxHeight because minHeight might also affect computations.\n\treturn NodeHeightBuilder.startFromFixedValue(infinity, node, ctx).getWithConstraints()\n}\n", "import { assert, assertNever, getLogger } from \"@framerjs/shared\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { js, jst } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { serializesToSameValue } from \"code-generation/jsx/serializesToSameValue.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isLayoutTemplateNode, isOverlayNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { getNumericRowGapFromShorthand } from \"document/models/CanvasTree/traits/NumberShorthand.ts\"\nimport { withAspectRatio } from \"document/models/CanvasTree/traits/WithAspectRatio.ts\"\nimport { type WithOptionalFill, hasImageFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport type { WithSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { autoAxisForAspectRatio } from \"document/models/CanvasTree/traits/collectStyles/collectAspectRatio.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { isNonNull, isNumber, isUndefined } from \"utils/typeChecks.ts\"\nimport { type DynamicValue, isDynamicValue } from \"../../document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type { GridItemColumnSpan } from \"../../document/models/CanvasTree/traits/WithGridItemLayout.ts\"\nimport { withGridItemLayout } from \"../../document/models/CanvasTree/traits/WithGridItemLayout.ts\"\nimport { isGridChildFillingCellWidth } from \"../../document/models/CanvasTree/traits/WithGridItemSize.ts\"\nimport type { HasGridLayout } from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport { hasGridLayout, hasStackLayout } from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport { withPadding } from \"../../document/models/CanvasTree/traits/WithPadding.ts\"\nimport { isPinnable } from \"../../document/models/CanvasTree/traits/WithPins.ts\"\nimport type { WithSize } from \"../../document/models/CanvasTree/traits/WithSize.ts\"\nimport { withSize } from \"../../document/models/CanvasTree/traits/WithSize.ts\"\nimport type { WithSizeConstraints } from \"../../document/models/CanvasTree/traits/WithSizeConstraints.ts\"\nimport {\n\tparseConstraintValue,\n\tsupportsSizeConstraints,\n} from \"../../document/models/CanvasTree/traits/WithSizeConstraints.ts\"\nimport { isBreakpointVariant, isSmartComponentVariant } from \"../../document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isVisibleNode } from \"../../document/models/CanvasTree/traits/WithVisibility.ts\"\nimport {\n\tisPositionAbsolute,\n\tisPositionFixed,\n\tisPositionRelative,\n} from \"../../document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { CantCalculate } from \"./CantCalculate.ts\"\nimport type { SimulationContext } from \"./SimulationContext.ts\"\nimport type { SimulatedDOMCSSValue } from \"./cssValue.ts\"\nimport { cssConst, cssOp, cssTemplate, cssValueFromNumberValue, wrapInCalcExpressionIfNeeded } from \"./cssValue.ts\"\nimport { innerSimulateHeight } from \"./simulateHeight.ts\"\nimport {\n\tgetCanvasMeasuredWidth,\n\tgetFitImageAspectRatio,\n\tgetLayoutChildren,\n\tisIndeterminate,\n\tnodeAffectsSiblings,\n} from \"./utils.ts\"\n\nconst logger = getLogger(\"simulateCSSWidth\")\n\n/**\n * This function calculates how wide a node is relative to the Framer Site viewport and returns a CSS calc\n * expression like `calc(500px)` or `calc(100vw * 0.5)`.\n * This calc expression is then used in Framer Sites to estimate the image width and speed up image loading.\n *\n * Important considerations:\n * - The \u201Cviewport\u201D here means the viewport of a published Framer Site, not the viewport of the canvas editor.\n *   In tree terms, that means we\u2019re measuring how wide a node is relative to the ground node.\n *   (And the ground node is assumed to be 100vw.)\n *\n * - The function returns a calc expression optimized for usage in `<img sizes=\"...\">`. For example,\n *   the expression only uses px and vw units because, in `sizes`, the browser doesn\u2019t recognize `%`s or `em`s.\n *\n * - The function handles both simple cases (a node with a fixed 500px width will always be 500px wide\n *   no matter the viewport width) and more complex ones (nested nodes, % values, fr values, paddings, stack gaps\n *   are all accounted for).\n */\nexport function simulateCSSWidth(node: CanvasNode & WithSize & WithSizeDimensionType, ctx: SimulationContext) {\n\ttry {\n\t\tconst value = innerSimulateCSSWidth(node, ctx)\n\t\treturn wrapInCalcExpressionIfNeeded(value)\n\t} catch (error) {\n\t\tif (error instanceof CantCalculate) {\n\t\t\treturn undefined\n\t\t}\n\t\tlogger.reportWithoutLogging(error, { nodeId: node.id })\n\t\tlogger.warnOncePerMinute(\n\t\t\t`Can\u2019t simulate the CSS width for node ${node.id} because the tree doesn\u2019t match expectations. Skipping.`,\n\t\t\terror,\n\t\t)\n\t\treturn undefined\n\t}\n}\n\nfunction innerSimulateCSSWidth(node: CanvasNode, ctx: SimulationContext): SimulatedDOMCSSValue {\n\tconst cachedWidth = ctx.cache.getCSSWidth(node.id)\n\tif (cachedWidth) return cachedWidth\n\n\tconst result = uncachedInnerSimulateCSSWidth(node, ctx)\n\n\t// We\u2019re caching the node width to avoid calculating it several times\n\t// if the node is visited several times during the same code generation pass.\n\t// The cache is invalidated after every code generation.\n\tctx.cache.setCSSWidth(node.id, result)\n\treturn result\n}\n\nfunction uncachedInnerSimulateCSSWidth(node: CanvasNode, ctx: SimulationContext): SimulatedDOMCSSValue {\n\tif (!isVisibleNode(node)) {\n\t\t// We *can* calculate the width of invisible nodes, but there\u2019s no point in doing so\n\t\t// as they won\u2019t be rendered. Let\u2019s save CPU cycles.\n\t\tthrow new CantCalculate()\n\t}\n\n\tconst parentNode = ctx.tree.getNodeParent(node)\n\n\t//\n\t// This is an overlay node. They always fill the entire viewport width\n\t//\n\tif (isOverlayNode(node)) {\n\t\treturn cssConst(100, \"vw\")\n\t}\n\n\t// Most nodes handled here must have a width and a width type \u2013 with some rare exceptions (above)\n\tassert(\n\t\twithSize(node) && withSizeDimensionType(node),\n\t\t`Can\u2019t calculate the width on a node ${node.id} when it doesn\u2019t have size information`,\n\t)\n\n\t//\n\t// This is a ground node, which is either:\n\t// - a web page breakpoint\n\t// - a smart component ground node\n\t// - a separate, non-breakpoint canvas ground node\n\t//\n\tif (ctx.tree.isGroundNode(node)) {\n\t\tif (isBreakpointVariant(node) && isLayoutTemplateNode(ctx.tree.getScopeNodeFor(node))) {\n\t\t\t// If this is a Layout Template breakpoint node, then it\u2019s the root\n\t\t\t// of the site. It always starts at 0 px.\n\t\t\treturn cssConst(100, \"vw\")\n\t\t} else if (isSmartComponentVariant(node) || isBreakpointVariant(node)) {\n\t\t\t// If this is a Smart Component or Web Page, then we expect its viewport to be provided by the parent component, since\n\t\t\t// smart component instances can be resized freely, or web pages can be nested inside layout templates.\n\t\t\t//\n\t\t\t// If the viewport was not provided (which can happen if the parent component hasn't been updated since we introduced the container viewport context, or if it\u2019s a web page that\u2019s not nested inside a layout template), ...\n\t\t\t// introduced the container viewport context), we fall back to 100vw rather than the smart component's\n\t\t\t// intrinsic width, on the off chance that the instance is wider than that, and using the intrinsic width\n\t\t\t// could result in a blurry image.\n\t\t\tconst fallback = cssConst(100, \"vw\")\n\t\t\treturn cssTemplate(js`${Var.componentViewport}?.width || ${fallback.expr}`)\n\t\t} else {\n\t\t\t// Otherwise, this might be a ground node outside of a web page. In cases like this, we can still assume\n\t\t\t// *some* width: ground nodes outside of a web page commonly represent stuff like images linked to the\n\t\t\t// Ticker component. These *typically* keep the same size in the Ticker.\n\t\t\tconst width = getCanvasMeasuredWidth(node, ctx)\n\t\t\tif (isUndefined(width)) throw new CantCalculate()\n\n\t\t\treturn cssConst(width, \"px\")\n\t\t}\n\t}\n\n\t//\n\t// This is a node inside a grid column that horizontally spans the full column.\n\t// Its width is equal to the width of that column\n\t//\n\tif (isGridChildFillingCellWidth(node)) {\n\t\treturn NodeWidthBuilder.startFromColumnWidthMultipliedBySpan(node, ctx).getWithConstraints()\n\t}\n\n\t//\n\t// This is a node with left & right pinning. Its width depends on its parent width \u2013 because it\u2019s absolutely\n\t// positioned with `left: ...` and `right: ...`.\n\t// Note that we can only trust node.left and node.right when the node is not position: relative.\n\t// https://github.com/framer/FramerStudio/pull/17140#discussion_r1547420603\n\t//\n\tconst isLeftRightPinned =\n\t\t!isPositionRelative(node, parentNode) && isPinnable(node) && isNonNull(node.left) && isNonNull(node.right)\n\tif (isLeftRightPinned) {\n\t\treturn (\n\t\t\tNodeWidthBuilder.startFromParentOuterWidth(node, ctx)\n\t\t\t\t// To get the node\u2019s width, subtract the left & right margins from the parent\u2019s outer width\n\t\t\t\t.op((width, node) => {\n\t\t\t\t\t// We check `node.left !== null && node.right !== null` a few lines above \u2013 but TypeScript can\u2019t transfer\n\t\t\t\t\t// that check\u2019s result here\n\t\t\t\t\tconst nodeLeft = node.left\n\t\t\t\t\tconst nodeRight = node.right\n\t\t\t\t\tassert(isNonNull(nodeLeft) && isNonNull(nodeRight), \"Satisfying TypeScript\")\n\t\t\t\t\treturn cssOp(\"-\", width, cssConst(nodeLeft + nodeRight, \"px\"))\n\t\t\t\t})\n\t\t\t\t.getWithConstraints()\n\t\t)\n\t}\n\n\t//\n\t// This is a node with an aspect ratio that\u2019s based on its height. Its width is `height * node.aspectRatio`.\n\t//\n\tif (\n\t\twithAspectRatio(node) &&\n\t\tisPinnable(node) &&\n\t\tisNumber(node.aspectRatio) &&\n\t\tautoAxisForAspectRatio(node) === \"width\"\n\t) {\n\t\tconst height = innerSimulateHeight(node, ctx)\n\t\tconst widthBasedOnHeight = cssOp(\"*\", cssValueFromNumberValue(height), cssConst(node.aspectRatio))\n\n\t\treturn NodeWidthBuilder.startFromRawValue(widthBasedOnHeight, node, ctx).getWithConstraints()\n\t}\n\n\t//\n\t// This is a fixed-width node, which is is always `node.width` wide (unless min/max width constraints apply).\n\t//\n\tif (node.widthType === DimensionType.FixedNumber) {\n\t\t// When not aspect-ratio constrained, the width is always `node.width` wide\n\t\treturn NodeWidthBuilder.startFromRawValue(cssConst(node.width, \"px\"), node, ctx).getWithConstraints()\n\t}\n\n\t//\n\t// A percentage-width node is as wide as X% of its parent.\n\t// Unfortunately, because we\u2019re building an expression for HTML\u2019s `sizes` attribute, we can\u2019t use `%` units directly.\n\t// The only units that a browser will recognize there are absolute (px) and viewport-relative (vw) ones.\n\t// Therefore, for percentage-width nodes we\n\t//   1) take the parent\u2019s or the column\u2019s width, and then\n\t//   2) multiply it by the percentage value.\n\t//\n\tif (node.widthType === DimensionType.Percentage) {\n\t\tassert(parentNode, \"A node can\u2019t have a % width without a parent\")\n\n\t\tlet builder: NodeWidthBuilder<CanvasNode & WithSize>\n\n\t\tif (isPositionFixed(node)) {\n\t\t\t// For position: fixed nodes, % width is always computed relative to\n\t\t\t// the viewport\n\t\t\tbuilder = NodeWidthBuilder.startFromRawValue(cssConst(100, \"vw\"), node, ctx)\n\t\t} else if (isPositionAbsolute(node)) {\n\t\t\t// For position: absolute nodes, % width is always computed relative to\n\t\t\t// parent\u2019s outer width, regardless of whether it\u2019s a grid or not\n\t\t\tbuilder = NodeWidthBuilder.startFromParentOuterWidth(node, ctx)\n\t\t} else if (hasGridLayout(parentNode)) {\n\t\t\t// Inside grids, % width is computed relative to the grid column width\n\t\t\tbuilder = NodeWidthBuilder.startFromColumnWidthMultipliedBySpan(node, ctx)\n\t\t} else {\n\t\t\tbuilder = NodeWidthBuilder.startFromParentInnerWidth(node, ctx)\n\t\t}\n\n\t\treturn (\n\t\t\tbuilder\n\t\t\t\t// To get the node\u2019s width, multiply the column width by the %.\n\t\t\t\t// (If the node has a width of 80%, `node.width` will be 0.8.)\n\t\t\t\t.op((width, node) => cssOp(\"*\", width, cssConst(node.width)))\n\t\t\t\t.getWithConstraints()\n\t\t)\n\t}\n\n\t//\n\t// A fraction-width node is a node that lives inside a stack and occupies a fraction of the available space \u2013\n\t// just like `fr` units in CSS grid or `flex-grow` values in CSS flexbox. Its behavior depends on whether\n\t// the stack is vertical or horizontal, and on whether stack wrapping is enabled.\n\t//\n\tif (node.widthType === DimensionType.FractionOfFreeSpace) {\n\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\tassert(parentNode, \"A node can\u2019t have a fractional width without a parent\")\n\n\t\t// fr units outside of stack layouts are generally forbidden.\n\t\t// However, projects can still end up in a state when they use them\n\t\t// outside of a stack. One of the most common cases for this (fr\n\t\t// units in a grid, https://github.com/framer/company/issues/30038#issuecomment-2303205852)\n\t\t// is common enough that we decided to support it.\n\t\t//\n\t\t// As of Aug 2024, fr nodes inside a grid behave as having an auto width;\n\t\t// but because we can\u2019t calculate auto widths, we\u2019ll just return the column width.\n\t\tif (hasGridLayout(parentNode)) {\n\t\t\treturn NodeWidthBuilder.startFromColumnWidthMultipliedBySpan(node, ctx).getWithConstraints()\n\t\t}\n\t\tassert(hasStackLayout(parentNode), \"A node can have a fractional width only if it\u2019s inside a stack\")\n\n\t\tassert(parentNode.stackDirection, \"A stack must have a direction defined\")\n\n\t\tif (parentNode.stackDirection === \"horizontal\") {\n\t\t\treturn calculateWidthInHorizontalStack(node, parentNode.stackWrapEnabled ?? false, ctx)\n\t\t}\n\n\t\tif (parentNode.stackDirection === \"vertical\") {\n\t\t\treturn calculateWidthInVerticalStack(node, ctx)\n\t\t}\n\n\t\tif (isDynamicValue(parentNode.stackDirection)) {\n\t\t\tconst horizontalSize = calculateWidthInHorizontalStack(node, parentNode.stackWrapEnabled ?? false, ctx)\n\t\t\tconst verticalSize = calculateWidthInVerticalStack(node, ctx)\n\t\t\t// If the two sizes are the same, we don't need a condition.\n\t\t\tif (serializesToSameValue(horizontalSize, verticalSize)) return horizontalSize\n\n\t\t\tconst directionBinding = ctx.getVariableBinding(parentNode.stackDirection, parentNode)\n\t\t\tif (!directionBinding) throw new CantCalculate()\n\n\t\t\tconst condition = js`${directionBinding} === \"row\"`\n\t\t\tconst expr = js`${condition} ? ${wrapInCalcExpressionIfNeeded(\n\t\t\t\thorizontalSize,\n\t\t\t)} : ${wrapInCalcExpressionIfNeeded(verticalSize)}`\n\n\t\t\treturn cssTemplate(expr)\n\t\t}\n\n\t\t// If TypeScript errors out here, then a new stackDirection was introduced. Please support it here.\n\t\t// Don\u2019t forget to add unit AND end-to-end tests for this new widthType (see src/app/vekter/test/end-to-end/ImgSrcset.pw.test.ts).\n\t\tassertNever(parentNode.stackDirection)\n\t}\n\n\t// FIXME (~2022): nodes with an `auto` width are not supported by this algorithm.\n\t// There are two complexities in handling `auto` nodes:\n\t// 1) A width of an `auto` node is a sum of widths of its descendants.\n\t//    This means, to calculate its width, we\u2019ll have walk its children, it\u2019s children\u2019s children\n\t//    (if any of its direct children are stacks), it\u2019s children\u2019s children\u2019s children, and so on.\n\t//    This doesn\u2019t rhyme with this algorithm well. The algorithm takes a node and traverses its ancestors;\n\t//    it would be weird to, upon encountering an `auto` node, switch the direction\n\t//    and start traversing its descendants. (Or maybe it\u2019s fine! I\u2019m just not sure how to express it well.)\n\t//    This might also get prohibitively expensive if an `auto` node has a deep descendant tree\n\t//    full of stacks (which is likely a common occurrence for sites).\n\t//    [I haven\u2019t profiled this, though, plus I\u2019m sure there are ways to optimize it.]\n\t// 2) Even if we decide to walk all descendants to sum their widths, one of the descendants might be a text node\n\t//    which has an auto width but no children. I have no idea how to handle these.\n\t//\n\t// The only case when we can return at least some kind of a value is when a node has a max width.\n\t// This is cheating, and this won\u2019t be precise (other branches are written to be 100% precise), which means\n\t// the resulting `sizes` attribute might load an image larger than necessary. But it\u2019s still better\n\t// than returning nothing and loading a full 100vw image.\n\t//\n\t// UPDATE (Jun 2024): Two years down the line, we learned how to handle auto heights in simulateHeight.ts.\n\t// We can handle widths here similarly :)\n\tif (node.widthType === DimensionType.Auto) {\n\t\tif (supportsSizeConstraints(node) && node.maxWidth) {\n\t\t\tconst [value, unit] = parseConstraintValue(node.maxWidth)\n\t\t\treturn cssConst(value, unit)\n\t\t}\n\n\t\tthrow new CantCalculate()\n\t}\n\n\t//\n\t// Viewport-width nodes are always ${node.width * 100}vw wide (with min-max constraints applied).\n\t//\n\tif (node.widthType === DimensionType.Viewport) {\n\t\tconst widthToStartFrom = cssConst(node.width * 100, \"vw\")\n\t\treturn NodeWidthBuilder.startFromRawValue(widthToStartFrom, node, ctx).getWithConstraints()\n\t}\n\n\tif (node.widthType === DimensionType.FitImage) {\n\t\tif (!hasImageFill(node)) {\n\t\t\tthrow new CantCalculate()\n\t\t}\n\n\t\tconst aspectRatio = getFitImageAspectRatio(node)\n\t\tconst height = innerSimulateHeight(node, ctx)\n\t\tconst width =\n\t\t\tisUndefined(height) || isUndefined(aspectRatio)\n\t\t\t\t? cssConst(node.width, \"px\")\n\t\t\t\t: cssOp(\"*\", cssValueFromNumberValue(height), cssConst(aspectRatio))\n\n\t\treturn NodeWidthBuilder.startFromRawValue(width, node, ctx).getWithConstraints()\n\t}\n\n\t// If TypeScript errors out here, then a new widthType was introduced. Please support it in this function.\n\t// Don\u2019t forget to add unit AND end-to-end tests for this new widthType (see src/app/vekter/test/end-to-end/ImgSrcset.pw.test.ts).\n\tassertNever(node.widthType)\n}\n\nfunction calculateWidthInHorizontalStack(\n\tnode: CanvasNode & WithSize & WithSizeDimensionType,\n\twrapEnabled: boolean,\n\tctx: SimulationContext,\n): SimulatedDOMCSSValue {\n\tif (wrapEnabled) {\n\t\treturn (\n\t\t\tNodeWidthBuilder.startFromParentInnerWidth(node, ctx)\n\t\t\t\t// With stack wrapping enabled, figuring out the width of a `fr` item\n\t\t\t\t// (especially if it has a min width) is very hard.\n\t\t\t\t// Say you had a 1fr item with a min-width of 200px. In this 350px-wide stack, 1fr would be equal to 200px:\n\t\t\t\t// -------------------------\n\t\t\t\t// | ----------- --------- |\n\t\t\t\t// | |   1fr   | | 150px | |\n\t\t\t\t// | ----------- --------- |\n\t\t\t\t// | --------- ----------- |\n\t\t\t\t// | | 150px | |  200px  | |\n\t\t\t\t// | --------- ----------- |\n\t\t\t\t// -------------------------\n\t\t\t\t//          350px\n\t\t\t\t//\n\t\t\t\t// But make the stack 1px narrower \u2013 and all rows would reflow, making the 1fr item equal to 349px:\n\t\t\t\t// -------------------------\n\t\t\t\t// | --------------------- |\n\t\t\t\t// | |        1fr        | |\n\t\t\t\t// | --------------------- |\n\t\t\t\t// | --------- ---------   |\n\t\t\t\t// | | 150px | | 150px |   |\n\t\t\t\t// | --------- ---------   |\n\t\t\t\t// | -----------           |\n\t\t\t\t// | |  200px  |           |\n\t\t\t\t// | -----------           |\n\t\t\t\t// -------------------------\n\t\t\t\t//          349px\n\t\t\t\t//\n\t\t\t\t// Furthermore, 1ft has a different value depending on the row it\u2019s in. All in all, this makes figuring out\n\t\t\t\t// the value of `1fr` too hard. (Or maybe I\u2019m not smart enough for this!)\n\t\t\t\t//\n\t\t\t\t// So instead of figuring out the precise width of an `fr` item, we just YOLO it and say\n\t\t\t\t// \u201Cit may be wide, it may be narrow, but it\u2019s definitely not wider than the stack width\u201D.\n\t\t\t\t// This won\u2019t be precise, which means the resulting `sizes` attribute might load an image\n\t\t\t\t// larger than necessary. But it\u2019s still better than returning nothing and not having `sizes` at all.)\n\t\t\t\t//\n\t\t\t\t// FIXME: maybe we can actually do this, see the matching computeHeight.ts implementation\n\t\t\t\t// that just does this.\n\t\t\t\t.getWithConstraints()\n\t\t)\n\t} else {\n\t\treturn (\n\t\t\tNodeWidthBuilder.startFromParentInnerWidth(node, ctx)\n\t\t\t\t// When the stack is horizontal (and doesn\u2019t wrap), it\u2019s impossible to figure out what `1fr` equals to\n\t\t\t\t// based on just the parent\u2019s width. The width of `1fr` is affected by its siblings!\n\t\t\t\t//\n\t\t\t\t// For example, say you have a 500px wide stack with four children:\n\t\t\t\t// ------------------------------------------\n\t\t\t\t// | ------- --------- ------- ------------ |\n\t\t\t\t// | | 1fr | | 150px | | 20% | |   2fr    | |\n\t\t\t\t// | ------- --------- ------- ------------ |\n\t\t\t\t// ------------------------------------------\n\t\t\t\t// In this case, the width of the first child will be equal to:\n\t\t\t\t//   ([stack: 500px] - [child 2: 150 px] - [child 3: 20% of the stack width]) / [3 (total fr units)] * [1 (fr unit of this child)]\n\t\t\t\t//\n\t\t\t\t// This means that, to evaluate the width of the first child, we have to evaluate its siblings as well.\n\t\t\t\t.subtractSiblingWidths()\n\t\t\t\t.getWithConstraints()\n\t\t)\n\t}\n}\n\nfunction calculateWidthInVerticalStack(\n\tnode: CanvasNode & WithSize & WithSizeDimensionType,\n\tctx: SimulationContext,\n): SimulatedDOMCSSValue {\n\treturn (\n\t\tNodeWidthBuilder.startFromParentInnerWidth(node, ctx)\n\t\t\t// When the stack is vertical, all elements are stretched horizontally to fill the stack:\n\t\t\t// -----\n\t\t\t// |   |\n\t\t\t// -----\n\t\t\t// -----\n\t\t\t// |   |\n\t\t\t// |   |\n\t\t\t// -----\n\t\t\t// In this situation, fraction units in width lose their typical meaning and start behaving as % units.\n\t\t\t// A 1fr wide node acts as if it were 100% wide, a 0.5fr wide node acts as if it were 50% wide, and so on.\n\t\t\t// So here, we treat fraction units as % units and multiply the resulting inner width accordingly\n\t\t\t.op((width, node) => cssOp(\"*\", width, cssConst(node.width)))\n\t\t\t.getWithConstraints()\n\t)\n}\nclass NodeWidthBuilder<NodeType extends CanvasNode & WithSize> {\n\t#width: SimulatedDOMCSSValue\n\t// Instead of storing the parent width directly, we store a lazy getter function.\n\t// The parent width is needed only in some code paths, so we\u2019re avoiding calculating it unless necessary.\n\t#getParentWidth: () => SimulatedDOMCSSValue\n\t#node: NodeType\n\t#ctx: SimulationContext\n\n\t// The constructor is private. Instead of the constructor, use static `createFrom*` methods\n\tprivate constructor(\n\t\twidthToStartFrom: SimulatedDOMCSSValue,\n\t\tgetParentWidth: () => SimulatedDOMCSSValue,\n\t\tnode: NodeType,\n\t\tctx: SimulationContext,\n\t) {\n\t\tthis.#width = widthToStartFrom\n\t\tthis.#getParentWidth = getParentWidth\n\t\tthis.#node = node\n\t\tthis.#ctx = ctx\n\t}\n\n\tstatic startFromRawValue<NodeType extends CanvasNode & WithSize>(\n\t\twidthToStartFrom: SimulatedDOMCSSValue,\n\t\tnode: NodeType,\n\t\tctx: SimulationContext,\n\t) {\n\t\treturn new NodeWidthBuilder(\n\t\t\twidthToStartFrom,\n\t\t\t// We don\u2019t need to _.memoize this function because SimulatedDOMCache is already caching\n\t\t\t// the result of the computation after a single run.\n\t\t\t() => {\n\t\t\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\t\t\tassert(parentNode, \"Can\u2019t calculate the parent width if the node doesn\u2019t have a parent\")\n\n\t\t\t\treturn innerSimulateCSSWidth(parentNode, ctx)\n\t\t\t},\n\t\t\tnode,\n\t\t\tctx,\n\t\t)\n\t}\n\n\tstatic startFromParentOuterWidth<NodeType extends CanvasNode & WithSize>(node: NodeType, ctx: SimulationContext) {\n\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\tassert(parentNode, \"Can\u2019t call createFromParentWidth() if the node doesn\u2019t have a parent\")\n\n\t\tconst parentWidth = innerSimulateCSSWidth(parentNode, ctx)\n\n\t\treturn new NodeWidthBuilder(parentWidth, () => parentWidth, node, ctx)\n\t}\n\n\tstatic startFromParentInnerWidth<NodeType extends CanvasNode & WithSize>(node: NodeType, ctx: SimulationContext) {\n\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\tassert(parentNode, \"Can\u2019t call createFromParentWidthMinusPaddings() if the node doesn\u2019t have a parent\")\n\n\t\tlet parentWidth = innerSimulateCSSWidth(parentNode, ctx)\n\t\tparentWidth = NodeWidthBuilder.#subtractNodePaddings(parentWidth, parentNode, ctx)\n\n\t\treturn new NodeWidthBuilder(parentWidth, () => parentWidth, node, ctx)\n\t}\n\n\tstatic startFromColumnWidthMultipliedBySpan<NodeType extends CanvasNode & WithSize>(\n\t\tnode: NodeType,\n\t\tctx: SimulationContext,\n\t) {\n\t\tconst parentNode = ctx.tree.getNodeParent(node)\n\t\tassert(\n\t\t\tparentNode && hasGridLayout(parentNode),\n\t\t\t\"Can\u2019t call createFromColumnWidthMultipliedBySpan() if the node isn\u2019t inside a grid\",\n\t\t)\n\t\tassert(\n\t\t\twithGridItemLayout(node),\n\t\t\t\"Can\u2019t call createFromColumnWidthMultipliedBySpan() if the node doesn\u2019t have grid item layout\",\n\t\t)\n\n\t\t// Get the width of a single column...\n\t\tconst columnWidth = NodeWidthBuilder.#getGridColumnWidth(parentNode, ctx)\n\n\t\t// ...and multiply it by the number of columns this node spans\n\t\tconst columnWidthMultipliedBySpan = NodeWidthBuilder.#multiplyColumnWidthBySpan(\n\t\t\tcolumnWidth,\n\t\t\tparentNode,\n\t\t\tnode.gridItemColumnSpan ?? 1,\n\t\t\tctx,\n\t\t)\n\n\t\treturn new NodeWidthBuilder(\n\t\t\tcolumnWidthMultipliedBySpan,\n\t\t\t// Inside a grid, any % calculations are relative to the column width, not to the grid container width.\n\t\t\t// Hence we\u2019re passing the column width as the parent width.\n\t\t\t() => columnWidthMultipliedBySpan,\n\t\t\tnode,\n\t\t\tctx,\n\t\t)\n\t}\n\n\tsubtractSiblingWidths() {\n\t\tconst parentNode = this.#ctx.tree.getNodeParent(this.#node)\n\t\tassert(\n\t\t\tparentNode && hasStackLayout(parentNode),\n\t\t\t\"Can\u2019t call subtractSiblingWidths() if the node isn\u2019t inside a stack\",\n\t\t)\n\n\t\tconst fixedNumberChildren: (CanvasNode & WithSize & WithSizeDimensionType)[] = []\n\t\tconst percentageChildren: (CanvasNode & WithSize & WithSizeDimensionType)[] = []\n\t\tconst fractionalChildren: (CanvasNode & WithSize & WithSizeDimensionType)[] = []\n\t\tconst viewportChildren: (CanvasNode & WithSize & WithSizeDimensionType)[] = []\n\t\tconst fitImageChildren: (CanvasNode & WithSize & WithSizeDimensionType & WithOptionalFill)[] = []\n\t\tlet totalVisibleChildren = 0\n\t\tfor (const child of getLayoutChildren(this.#ctx.componentLoader, parentNode)) {\n\t\t\tconst affectsLayout = nodeAffectsSiblings(child, parentNode, this.#ctx.tree, false)\n\t\t\tif (affectsLayout === false) continue\n\t\t\t// Nodes which visibility is controlled with a variable *do* affect\n\t\t\t// the layout calculation, but we don\u2019t know the variable value\n\t\t\t// ahead of time. Let\u2019s assume the variable is always false (i.e.,\n\t\t\t// the node is always hidden) \u2013 it\u2019s better to load a slightly\n\t\t\t// larger image than to render one that\u2019s too small and blurry.\n\t\t\tif (isIndeterminate(affectsLayout)) continue\n\n\t\t\tassert(\n\t\t\t\twithSize(child) && withSizeDimensionType(child),\n\t\t\t\t\"It\u2019s impossible to have a regular visible node without width/height/widthType/heightType fields\",\n\t\t\t)\n\n\t\t\ttotalVisibleChildren++\n\n\t\t\tswitch (child.widthType) {\n\t\t\t\tcase DimensionType.FixedNumber: {\n\t\t\t\t\tfixedNumberChildren.push(child)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase DimensionType.Percentage: {\n\t\t\t\t\tpercentageChildren.push(child)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase DimensionType.FractionOfFreeSpace: {\n\t\t\t\t\tfractionalChildren.push(child)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase DimensionType.Viewport: {\n\t\t\t\t\tviewportChildren.push(child)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase DimensionType.Auto: {\n\t\t\t\t\t// Auto children don\u2019t have an explicit width and are too complex to calculate\n\t\t\t\t\tthrow new CantCalculate()\n\t\t\t\t}\n\t\t\t\tcase DimensionType.FitImage: {\n\t\t\t\t\tif (!hasImageFill(child) || !child.fillImagePixelWidth || !child.fillImagePixelHeight) {\n\t\t\t\t\t\tthrow new CantCalculate()\n\t\t\t\t\t}\n\t\t\t\t\tfitImageChildren.push(child)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(child.widthType)\n\t\t\t}\n\t\t}\n\n\t\t// In some scenarios (https://framer-team.slack.com/archives/C01B14R6E22/p1775031074614169), we might end up\n\t\t// with no visible children at all. (This happens when eg every node in a stack has conditional visibility.)\n\t\t// In this case, we don\u2019t subtract anything from the parent\u2019s width. The resulting images will be as wide\n\t\t// as the parent.\n\t\tif (totalVisibleChildren === 0) return this\n\n\t\t// FIXME: the below steps don\u2019t account for min-widths and max-widths of the siblings.\n\t\t// See getVerticalStackLayoutInfo() in stack.ts to a more complete implementation.\n\t\t//\n\t\t// To calculate a `fr` width based on parent\u2019s and siblings\u2019 widths:\n\t\t// First, subtract widths of percentage nodes\n\t\tconst totalPctWidths = percentageChildren.reduce((sum, child) => sum + child.width, 0)\n\t\t// Even though we\u2019re generating an expression for `calc`, we can\u2019t\n\t\t// subtract % units directly, like `calc(100vw - 40%)`. We\u2019re building\n\t\t// an expression for HTML\u2019s `sizes` attribute, and it only supports px\n\t\t// and vw values. So instead of subtracting 40% from the width, we\n\t\t// multiply the width by 100% - 40% = 0.6.\n\t\tconst remainingSpacePct = 1 - totalPctWidths\n\t\tif (remainingSpacePct !== 1) {\n\t\t\tthis.#width = cssOp(\"*\", this.#width, cssConst(remainingSpacePct))\n\t\t}\n\n\t\t// Second, subtract widths of fixed nodes, fit image nodes and vw nodes\n\t\tif (fixedNumberChildren.length) {\n\t\t\tconst totalFixedWidths = fixedNumberChildren.reduce(\n\t\t\t\t(sum, child) => {\n\t\t\t\t\treturn cssOp(\"+\", sum, cssConst(child.width, \"px\"))\n\t\t\t\t},\n\t\t\t\tcssConst(0, \"px\"),\n\t\t\t)\n\t\t\tthis.#width = cssOp(\"-\", this.#width, totalFixedWidths)\n\t\t}\n\n\t\tif (fitImageChildren.length) {\n\t\t\tconst totalFitImageWidths = fitImageChildren.reduce(\n\t\t\t\t(sum, child) => {\n\t\t\t\t\tconst aspectRatio = getFitImageAspectRatio(child)\n\t\t\t\t\tif (!aspectRatio) throw new CantCalculate()\n\t\t\t\t\tconst height = innerSimulateHeight(child, this.#ctx)\n\t\t\t\t\tif (!height) throw new CantCalculate()\n\t\t\t\t\treturn cssOp(\"+\", sum, cssOp(\"*\", cssValueFromNumberValue(height), cssConst(aspectRatio, \"px\")))\n\t\t\t\t},\n\t\t\t\tcssConst(0, \"px\"),\n\t\t\t)\n\n\t\t\tthis.#width = cssOp(\"-\", this.#width, totalFitImageWidths)\n\t\t}\n\n\t\tif (viewportChildren.length) {\n\t\t\tconst totalViewportWidths = viewportChildren.reduce(\n\t\t\t\t(sum, child) => {\n\t\t\t\t\treturn cssOp(\"+\", sum, cssConst(child.width * 100, \"vw\"))\n\t\t\t\t},\n\t\t\t\tcssConst(0, \"vw\"),\n\t\t\t)\n\t\t\tthis.#width = cssOp(\"-\", this.#width, totalViewportWidths)\n\t\t}\n\n\t\t// Third, don\u2019t forget about stack gaps! They reduce the width available to `fr` units as well\n\t\tif (isDynamicValue(parentNode.gap)) {\n\t\t\tconst gapBinding = this.#ctx.getVariableBinding(parentNode.gap, parentNode)\n\t\t\tif (gapBinding) {\n\t\t\t\tconst gapTotalAmount = cssTemplate(jst`${js`${gapBinding} * ${totalVisibleChildren - 1}`}px`)\n\n\t\t\t\tthis.#width = cssOp(\"-\", this.#width, gapTotalAmount)\n\t\t\t}\n\t\t} else {\n\t\t\tconst parentGap = getNumericRowGapFromShorthand(parentNode.gap)\n\t\t\tconst gapTotalAmount = parentGap * (totalVisibleChildren - 1)\n\t\t\tif (gapTotalAmount !== 0) {\n\t\t\t\tthis.#width = cssOp(\"-\", this.#width, cssConst(gapTotalAmount, \"px\"))\n\t\t\t}\n\t\t}\n\n\t\t// Fourth,..\n\t\tconst totalFrUnits = fractionalChildren.reduce((sum, child) => sum + child.width, 0)\n\t\t// (we don\u2019t want to divide by zero if fractionalChildren.length is 0, aka all fr units have conditional visibility)\n\t\tif (totalFrUnits !== 0) {\n\t\t\t// ...split the remaining space among fractional units...\n\t\t\tthis.#width = cssOp(\"/\", this.#width, cssConst(totalFrUnits))\n\t\t\t// ...and multiple by the fr width of the current node\n\t\t\tthis.#width = cssOp(\"*\", this.#width, cssConst(this.#node.width))\n\t\t}\n\n\t\t// Fifth, apply a max(..., 1px). It\u2019s possible for siblings to be wider\n\t\t// than the parent\u2019s width. (Eg a stack may have two children with a 80%\n\t\t// width.) This `max()` accounts for that, ensuring that the node\u2019s\n\t\t// width doesn\u2019t go into the negative territory.\n\t\t// We use 1px and not 0px because 0px behaves weirdly in Chrome: https://framer-team.slack.com/archives/C05V49Q4NJ2/p1711652371579029\n\t\tthis.#width = cssOp(\"max\", this.#width, cssConst(1, \"px\"))\n\n\t\treturn this\n\t}\n\n\top(callback: (width: SimulatedDOMCSSValue, node: NodeType) => SimulatedDOMCSSValue) {\n\t\tthis.#width = callback(this.#width, this.#node)\n\t\treturn this\n\t}\n\n\tgetWithConstraints(): SimulatedDOMCSSValue {\n\t\t// As the last step, we must always apply minWidth/maxWidth\n\t\tif (!supportsSizeConstraints(this.#node)) {\n\t\t\treturn this.#width\n\t\t}\n\n\t\t// Note: the order of the operations is important (max, then min) \u2013 because both can be present,\n\t\t// and when they do, min wins. (E.g. a node with max-width: 50px but min-width: 100px will be 100px wide.)\n\t\tif (this.#node.maxWidth) {\n\t\t\tthis.#width = NodeWidthBuilder.#applyMinMaxWidthConstraint(\n\t\t\t\t\"maxWidth\",\n\t\t\t\tthis.#width,\n\t\t\t\tthis.#getParentWidth,\n\t\t\t\tthis.#node,\n\t\t\t)\n\t\t}\n\t\tif (this.#node.minWidth) {\n\t\t\tthis.#width = NodeWidthBuilder.#applyMinMaxWidthConstraint(\n\t\t\t\t\"minWidth\",\n\t\t\t\tthis.#width,\n\t\t\t\tthis.#getParentWidth,\n\t\t\t\tthis.#node,\n\t\t\t)\n\t\t}\n\n\t\treturn this.#width\n\t}\n\n\tstatic #getGridColumnWidth(node: CanvasNode & HasGridLayout, ctx: SimulationContext): SimulatedDOMCSSValue {\n\t\tassert(!isUndefined(node.gridColumnWidthType), \"A grid node must have a gridColumnWidthType defined\")\n\n\t\tif (node.gridColumnWidthType === \"fixed\") {\n\t\t\tassert(\n\t\t\t\t!isUndefined(node.gridColumnWidth),\n\t\t\t\t\"A grid node with fixed width columns must have a gridColumnWidth defined\",\n\t\t\t)\n\t\t\treturn cssConst(node.gridColumnWidth, \"px\")\n\t\t} else if (node.gridColumnWidthType === \"minmax\") {\n\t\t\tif (node.gridColumnCount === \"auto-fill\") {\n\t\t\t\t// When the number of columns is dynamic, figuring out the width\n\t\t\t\t// of every column becomes too hard. We\u2019d have to recursively\n\t\t\t\t// walk the descendants, calculate their widths, map them onto a\n\t\t\t\t// grid, and then figure out how many columns fit in the\n\t\t\t\t// container. This doesn\u2019t fit the current algorithm well (here,\n\t\t\t\t// we recursively walk ancestors, not descendants), and this may\n\t\t\t\t// be too complex to express as a calc() operation\n\t\t\t\tthrow new CantCalculate()\n\t\t\t}\n\n\t\t\t// Let\u2019s calculate the width of a single column. First, get the\n\t\t\t// width of the grid container (minus paddings)\n\t\t\tlet columnWidth = innerSimulateCSSWidth(node, ctx)\n\t\t\tcolumnWidth = NodeWidthBuilder.#subtractNodePaddings(columnWidth, node, ctx)\n\n\t\t\t// Second, subtract the gaps between columns\n\t\t\tassert(!isUndefined(node.gridColumnCount), \"A grid node must have a gridColumnCount defined\")\n\t\t\tif (isDynamicValue(node.gap)) {\n\t\t\t\tconst gapBinding = ctx.getVariableBinding(node.gap, node)\n\t\t\t\tif (gapBinding) {\n\t\t\t\t\tconst gapTotalAmount = cssTemplate(jst`${js`${gapBinding} * ${node.gridColumnCount - 1}`}px`)\n\n\t\t\t\t\tcolumnWidth = cssOp(\"-\", columnWidth, gapTotalAmount)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst nodeGap = getNumericRowGapFromShorthand(node.gap)\n\t\t\t\tconst gapTotalAmount = nodeGap * (node.gridColumnCount - 1)\n\t\t\t\tif (gapTotalAmount !== 0) {\n\t\t\t\t\tcolumnWidth = cssOp(\"-\", columnWidth, cssConst(gapTotalAmount, \"px\"))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Third, divide the remaining space between every column\n\t\t\tif (node.gridColumnCount > 1) {\n\t\t\t\tcolumnWidth = cssOp(\"/\", columnWidth, cssConst(node.gridColumnCount))\n\t\t\t}\n\n\t\t\tif (node.gridColumnMinWidth) {\n\t\t\t\t// Fourth, account for columns\u2019 min width. (We use the max()\n\t\t\t\t// operation: this is counterintuitive, but to get a *min*\n\t\t\t\t// width, you need to apply the *max* function, and vice versa.)\n\t\t\t\tcolumnWidth = cssOp(\"max\", columnWidth, cssConst(node.gridColumnMinWidth, \"px\"))\n\t\t\t}\n\n\t\t\treturn columnWidth\n\t\t} else {\n\t\t\t// If TypeScript errors out here, then a new gridColumnWidthType was introduced. Please support it in this function.\n\t\t\tassertNever(node.gridColumnWidthType)\n\t\t}\n\t}\n\n\tstatic #multiplyColumnWidthBySpan(\n\t\tnodeWidth: SimulatedDOMCSSValue,\n\t\tgridContainerNode: CanvasNode & HasGridLayout,\n\t\tgridItemColumnSpan: GridItemColumnSpan | DynamicValue,\n\t\tctx: SimulationContext,\n\t): SimulatedDOMCSSValue {\n\t\t// Short-circuit: if the node only spans one column, return the node width.\n\t\t// This helps to avoid `auto-fill` CantCalculate exceptions below.\n\t\tif (gridItemColumnSpan === 1) {\n\t\t\treturn nodeWidth\n\t\t}\n\n\t\t// Multiply the column width by the number of columns this node spans...\n\t\tlet columnsToSpan: number\n\t\tif (isNumber(gridItemColumnSpan)) {\n\t\t\t// We don\u2019t have a number of columns to Math.min() with\n\t\t\tif (gridContainerNode.gridColumnCount === \"auto-fill\") throw new CantCalculate()\n\n\t\t\tassert(!isUndefined(gridContainerNode.gridColumnCount), \"A grid must have gridColumnCount defined\")\n\t\t\t// Ideally, the expression below would be:\n\t\t\t//\n\t\t\t//     columnsToSpan = gridItemColumnSpan\n\t\t\t//\n\t\t\t// However, sometimes, the grid item spans more columns than the\n\t\t\t// grid actually has. (This happens as a performance optimization,\n\t\t\t// see:\n\t\t\t// https://framer-team.slack.com/archives/CR3CYA1D4/p1657802681632599).\n\t\t\t// We use Math.min() to ensure gridItemColumnSpan doesn\u2019t exceed the\n\t\t\t// number of columns in the grid.\n\t\t\tcolumnsToSpan = Math.min(gridItemColumnSpan, gridContainerNode.gridColumnCount)\n\t\t} else if (gridItemColumnSpan === \"all\") {\n\t\t\t// We don\u2019t have a number of columns to assign\n\t\t\tif (gridContainerNode.gridColumnCount === \"auto-fill\") throw new CantCalculate()\n\n\t\t\tassert(!isUndefined(gridContainerNode.gridColumnCount), \"A grid must have gridColumnCount defined\")\n\t\t\tcolumnsToSpan = gridContainerNode.gridColumnCount\n\t\t} else if (isDynamicValue(gridItemColumnSpan)) {\n\t\t\tthrow new CantCalculate()\n\t\t} else {\n\t\t\tassertNever(gridItemColumnSpan)\n\t\t}\n\n\t\tif (columnsToSpan > 1) {\n\t\t\tnodeWidth = cssOp(\"*\", nodeWidth, cssConst(columnsToSpan))\n\t\t}\n\n\t\t// ...and add gaps between the columns\n\t\tif (isDynamicValue(gridContainerNode.gap)) {\n\t\t\tconst gapBinding = ctx.getVariableBinding(gridContainerNode.gap, gridContainerNode)\n\t\t\tif (gapBinding) {\n\t\t\t\tconst gapTotalAmount = cssTemplate(jst`${js`${gapBinding} * ${columnsToSpan - 1}`}px`)\n\n\t\t\t\tnodeWidth = cssOp(\"+\", nodeWidth, gapTotalAmount)\n\t\t\t}\n\t\t} else {\n\t\t\tconst gridContainerGap = getNumericRowGapFromShorthand(gridContainerNode.gap)\n\t\t\tconst gapTotalAmount = gridContainerGap * (columnsToSpan - 1)\n\t\t\tif (gapTotalAmount !== 0) {\n\t\t\t\tnodeWidth = cssOp(\"+\", nodeWidth, cssConst(gapTotalAmount, \"px\"))\n\t\t\t}\n\t\t}\n\n\t\treturn nodeWidth\n\t}\n\n\tstatic #subtractNodePaddings(\n\t\tnodeWidth: SimulatedDOMCSSValue,\n\t\tnode: CanvasNode,\n\t\tctx: SimulationContext,\n\t): SimulatedDOMCSSValue {\n\t\tif (!withPadding(node)) {\n\t\t\treturn nodeWidth\n\t\t}\n\n\t\tlet nodePadding: SimulatedDOMCSSValue | undefined = undefined\n\t\tif (isDynamicValue(node.padding)) {\n\t\t\tconst paddingBinding = ctx.getVariableBinding(node.padding, node)\n\t\t\tif (paddingBinding) {\n\t\t\t\tconst parseFn = ctx.imports.addImport(\"framer\", { exportSpecifier: \"parsePaddingString\" })\n\t\t\t\tconst parsed = ctx.declarations.dedupe(\n\t\t\t\t\t\"parsedPadding\",\n\t\t\t\t\tjs`typeof ${paddingBinding} === \"string\" ? ${SafeJS.fn(parseFn, paddingBinding)} : { top: ${paddingBinding}, right: ${paddingBinding}, bottom: ${paddingBinding}, left: ${paddingBinding} }`,\n\t\t\t\t)\n\t\t\t\tnodePadding = cssTemplate(jst`${js`(${parsed}?.left ?? 0) + (${parsed}?.right ?? 0)`}px`)\n\t\t\t}\n\t\t} else if (node.paddingPerSide) {\n\t\t\tnodePadding = cssConst((node.paddingLeft ?? 0) + (node.paddingRight ?? 0), \"px\")\n\t\t} else {\n\t\t\tnodePadding = cssConst((node.padding ?? 0) * 2, \"px\")\n\t\t}\n\n\t\tif (nodePadding) {\n\t\t\treturn cssOp(\"-\", nodeWidth, nodePadding)\n\t\t}\n\n\t\treturn nodeWidth\n\t}\n\n\tstatic #applyMinMaxWidthConstraint<NodeType extends CanvasNode>(\n\t\tconstraint: \"minWidth\" | \"maxWidth\",\n\t\tnodeWidth: SimulatedDOMCSSValue,\n\t\tgetParentWidth: () => SimulatedDOMCSSValue,\n\t\tnode: NodeType & WithSizeConstraints,\n\t): SimulatedDOMCSSValue {\n\t\t// This is counterintuitive, but to get a *min* width, you need to apply\n\t\t// the *max* function, and vice versa. If a node\u2019s minWidth is 100px,\n\t\t// and the calculated width is 90px, the effective width must be 100px.\n\t\t// This is achieved with max(90px, 100px), not min().\n\t\tconst operationToApply = constraint === \"minWidth\" ? \"max\" : \"min\"\n\n\t\tconst [value, unit] = parseConstraintValue(node[constraint])\n\t\tif (unit === \"%\") {\n\t\t\tconst parentNodeWidth = getParentWidth()\n\n\t\t\t// If the minWidth or maxWidth is expressed in %, that \u201C%\u201D is a % of\n\t\t\t// the parent\u2019s width.\n\t\t\t//\n\t\t\t//     minWidth == 30% -> max(${nodeWidth}, ${parentWidth} * 30%)\n\t\t\t//\n\t\t\treturn cssOp(operationToApply, nodeWidth, cssOp(\"*\", parentNodeWidth, cssConst(value / 100)))\n\t\t} else {\n\t\t\t// If the minWidth or maxWidth is expressed in pixels or viewport\n\t\t\t// relative, we just apply that:\n\t\t\t//\n\t\t\t//     minWidth == 300px -> max(${nodeWidth}, 300px)\n\t\t\t//\n\t\t\treturn cssOp(operationToApply, nodeWidth, cssConst(value, unit))\n\t\t}\n\t}\n}\n", "import { assert, assertNever, getLogger } from \"@framerjs/shared\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { getNumericColumnGapFromShorthand } from \"document/models/CanvasTree/traits/NumberShorthand.ts\"\nimport { withSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport {\n\tcanBePositionAbsolute,\n\tcanBePositionFixed,\n\tcanBePositionSticky,\n} from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport { DimensionType } from \"library/index.ts\"\nimport { isNonNull, isNumber, isUndefined } from \"utils/typeChecks.ts\"\nimport {\n\tisLayoutTemplateNode,\n\tisOverlayNode,\n\tisSlotNode,\n} from \"../../document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"../../document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type { HasGridLayout, HasStackLayout } from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport {\n\thasAnyLayout,\n\thasGridLayout,\n\thasStackLayout,\n\tsupportGap,\n} from \"../../document/models/CanvasTree/traits/WithLayout.ts\"\nimport type { WithPins } from \"../../document/models/CanvasTree/traits/WithPins.ts\"\nimport { isPinnable } from \"../../document/models/CanvasTree/traits/WithPins.ts\"\nimport type { PositionType, WithPositionType } from \"../../document/models/CanvasTree/traits/WithPositionType.ts\"\nimport { withPositionType } from \"../../document/models/CanvasTree/traits/WithPositionType.ts\"\nimport { withSize } from \"../../document/models/CanvasTree/traits/WithSize.ts\"\nimport { isBreakpointVariant, isSmartComponentVariant } from \"../../document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isVisibleNode } from \"../../document/models/CanvasTree/traits/WithVisibility.ts\"\nimport { CantCalculate } from \"./CantCalculate.ts\"\nimport type { SimulationContext } from \"./SimulationContext.ts\"\nimport type { GridLayoutInfo } from \"./grid.ts\"\nimport { getGridLayoutInfo } from \"./grid.ts\"\nimport type { NumberOpArguments, SimulatedDOMNumberValue } from \"./numberValue.ts\"\nimport { numberConst, numberOp, numberOpForArraySlice, numberTemplate } from \"./numberValue.ts\"\nimport { innerSimulateHeight, simulateMaxHeight, simulateMinHeight } from \"./simulateHeight.ts\"\nimport type { StackLayoutInfo } from \"./stack.ts\"\nimport { getVerticalStackLayoutInfo } from \"./stack.ts\"\nimport { VIEWPORT_HEIGHT, getNodePaddingBottom, getNodePaddingTop, resolveGap } from \"./utils.ts\"\n\nconst logger = getLogger(\"simulateYPosition\")\n\n/**\n * This function calculates the y position of a node relative to the Framer Site page.\n * It returns a value (like 500), a codegen expression (like js`${Var.componentViewport}.y + 500`),\n * or undefined if it can\u2019t compute it. This value is then used in Framer Sites for optimizations \u2013\n * e.g. to figure out which images are outside of the viewport and should be lazy-loaded.\n *\n * Because this function has to be used in code generation, it can\u2019t rely on the page being rendered\n * in actual DOM. To compute the y position of the node relative to the page, it re-implements the\n * simplified version of the browser\u2019s layout algorithm. It then uses this algorithm to calculate\n * (\u201Csimulate\u201D) the y position of a node based on all information available in the tree.\n *\n * NOTE: Because this function doesn\u2019t use the actual DOM, the returned values aren\u2019t guaranteed to be\n * precise. The function *strives* to be precise, but you should expect occasional errors close to\n * dozens of pixels. If you notice a big disperancy (hundreds of pixels), this is a bug; please ping @ivan.\n */\nexport function simulateYPosition(node: CanvasNode & WithPins & WithPositionType, ctx: SimulationContext) {\n\ttry {\n\t\tconst value = innerSimulateYPosition(node, ctx)\n\t\treturn value.type === \"number-const\" ? value.value : value.expr\n\t} catch (error) {\n\t\tif (error instanceof CantCalculate) {\n\t\t\treturn undefined\n\t\t}\n\t\tlogger.reportWithoutLogging(error, { nodeId: node.id })\n\t\tlogger.warnOncePerMinute(\n\t\t\t`Can\u2019t simulate the y position for node ${node.id} because the tree doesn\u2019t match expectations. Skipping.`,\n\t\t\terror,\n\t\t)\n\t\treturn undefined\n\t}\n}\n\nfunction innerSimulateYPosition(node: CanvasNode, ctx: SimulationContext): SimulatedDOMNumberValue {\n\tconst cachedYPosition = ctx.cache.getYPosition(node.id)\n\tif (cachedYPosition) return cachedYPosition\n\n\tconst result = uncachedInnerSimulateYPosition(node, ctx)\n\n\t// We\u2019re caching the node Y position to avoid calculating it several times\n\t// if the node is visited several times during the same code generation pass.\n\t// The cache is invalidated after every code generation.\n\tctx.cache.setYPosition(node.id, result)\n\treturn result\n}\n\nfunction uncachedInnerSimulateYPosition(node: CanvasNode, ctx: SimulationContext): SimulatedDOMNumberValue {\n\tif (!isVisibleNode(node)) {\n\t\t// We *can* calculate the y position of invisible nodes, but there\u2019s no point in doing so\n\t\t// as they won\u2019t be rendered. Let\u2019s save CPU cycles.\n\t\tthrow new CantCalculate()\n\t}\n\n\tconst parentNode = ctx.tree.getNodeParent(node)\n\n\t// Most nodes handled here must have a width and a width type \u2013 with a rare exception\n\tif (!(isPinnable(node) && withPositionType(node))) {\n\t\t//\n\t\t// This is an overlay node. They always fill the entire viewport and start from 0\n\t\t//\n\t\tif (isOverlayNode(node)) {\n\t\t\treturn numberConst(0)\n\t\t}\n\n\t\tassert(false, `Can\u2019t calculate the y position on a node when it doesn\u2019t have position information`)\n\t}\n\n\t//\n\t// This is a ground node, which is either:\n\t// - a web page breakpoint\n\t// - a smart component ground node\n\t// - a separate, non-breakpoint canvas ground node\n\t//\n\tif (ctx.tree.isGroundNode(node)) {\n\t\tif (isBreakpointVariant(node) && isLayoutTemplateNode(ctx.tree.getScopeNodeFor(node))) {\n\t\t\t// If this is a Layout Template breakpoint node, then it\u2019s the root\n\t\t\t// of the site. It always starts at 0 px.\n\t\t\treturn numberConst(0)\n\t\t} else if (isSmartComponentVariant(node) || isBreakpointVariant(node)) {\n\t\t\t// If this is a Smart Component or Web Page, then we expect its\n\t\t\t// viewport to be provided by the parent component, as Smart\n\t\t\t// Components can be resized freely, and Web Pages can be rendered\n\t\t\t// inside a Layout Template. Layout Templates will provide\n\t\t\t// ComponentViewportProvider props in the future.\n\t\t\t//\n\t\t\t// If the viewport was not provided (which can happen if the parent\n\t\t\t// component hasn't been updated since we introduced the container\n\t\t\t// viewport context), we fall back to 0. For loading=lazy purposes,\n\t\t\t// this is a bit better than throwing `CantCalculate` because it\n\t\t\t// still allows elements below 1000px in the component to be\n\t\t\t// lazy-loaded.\n\t\t\treturn numberTemplate(js`${Var.componentViewport}?.y || 0`, 0)\n\t\t} else {\n\t\t\t// Otherwise, this might be a ground node outside of a web page. This is likely slots for a ticker or smth.\n\t\t\t// We can\u2019t handle these cases today.\n\t\t\tthrow new CantCalculate()\n\t\t}\n\t}\n\n\tconst nodeEffectivePosition = getNodeEffectivePosition(node, parentNode, ctx)\n\n\t//\n\t// If a node has `position: fixed`, simply return the position as a constant value\n\t//\n\tif (nodeEffectivePosition === \"fixed\") {\n\t\tif (isNonNull(node.top)) {\n\t\t\t// It\u2019s top-pinned or top-bottom-pinned node. In either case, its `y` is always at `node.top`\n\t\t\treturn numberConst(node.top)\n\t\t} else if (isNonNull(node.bottom)) {\n\t\t\t// It\u2019s a bottom-pinned node. Assume the viewport height is 1000px\n\t\t\t// and return 1000 - bottom - nodeHeight\n\t\t\tconst nodeHeightInPx = innerSimulateHeight(node, ctx)\n\t\t\treturn numberOp(\"-\", VIEWPORT_HEIGHT - node.bottom, nodeHeightInPx)\n\t\t} else {\n\t\t\t// It\u2019s a left-right pinned node or center-pinned node. Its `y` is viewportHeight * node.centerAnchorY - nodeHeight / 2\n\t\t\tconst nodeHeightInPx = innerSimulateHeight(node, ctx)\n\t\t\treturn numberOp(\"-\", numberOp(\"*\", VIEWPORT_HEIGHT, node.centerAnchorY), numberOp(\"/\", nodeHeightInPx, 2))\n\t\t}\n\t}\n\n\t//\n\t// If a node has `position: absolute`, same rules as `position: fixed` apply, but\n\t// with parent\u2019s y position added\n\t//\n\tif (nodeEffectivePosition === \"absolute\") {\n\t\tassert(\n\t\t\tparentNode && isPinnable(parentNode) && withPositionType(parentNode),\n\t\t\t`absolute position: parentNode for the node must exist, be pinnable, and have position type`,\n\t\t)\n\n\t\tconst parentNodeY = innerSimulateYPosition(parentNode, ctx)\n\n\t\tif (isNonNull(node.top)) {\n\t\t\t// It\u2019s top-pinned or top-bottom-pinned node. In either case, its `y` is `parentNode.y + node.top`\n\t\t\treturn numberOp(\"+\", parentNodeY, numberConst(node.top))\n\t\t} else if (isNonNull(node.bottom)) {\n\t\t\t// It\u2019s a bottom-pinned node. Its `y` is `parentNode.y + parentNode.height - node.bottom - nodeHeight`\n\t\t\tconst parentNodeHeight = innerSimulateHeight(parentNode, ctx)\n\t\t\tconst nodeHeight = innerSimulateHeight(node, ctx)\n\t\t\treturn numberOp(\"-\", numberOp(\"+\", parentNodeY, parentNodeHeight), numberOp(\"+\", node.bottom, nodeHeight))\n\t\t} else {\n\t\t\t// It\u2019s a left-right pinned node or center-pinned node. Its `y` is `parentNode.y + (parentNodeHeight * node.centerAnchorY - nodeHeight / 2)`\n\t\t\tconst parentNodeHeight = innerSimulateHeight(parentNode, ctx)\n\t\t\tconst nodeHeight = innerSimulateHeight(node, ctx)\n\t\t\treturn numberOp(\n\t\t\t\t\"+\",\n\t\t\t\tparentNodeY,\n\t\t\t\tnumberOp(\"-\", numberOp(\"*\", parentNodeHeight, node.centerAnchorY), numberOp(\"/\", nodeHeight, 2)),\n\t\t\t)\n\t\t}\n\t}\n\n\t//\n\t// Relative and sticky nodes are usually nodes inside stacks or grids. (Are there even any other cases?)\n\t// For these nodes, we simulate a stack/grid layout.\n\t//\n\t// Note that there\u2019s no difference between `position: relative` and `position: sticky`.\n\t// Even though `position: sticky` nodes, well, stick, that doesn\u2019t affect their placement\n\t// in stacks/grids, even scrollable one.\n\t//\n\tif (nodeEffectivePosition === \"sticky\" || isUndefined(nodeEffectivePosition) /* relative */) {\n\t\tassert(\n\t\t\tparentNode && isPinnable(parentNode) && withPositionType(parentNode),\n\t\t\t`relative position: parentNode for the node must exist, be pinnable, and have position type`,\n\t\t)\n\n\t\tif (hasStackLayout(parentNode)) {\n\t\t\tassert(parentNode.stackDirection, `parentNode for the node must have stackDirection`)\n\n\t\t\tif (parentNode.stackDirection === \"horizontal\") {\n\t\t\t\t//\n\t\t\t\t// This is a horizontal stack with wrapping enabled\n\t\t\t\t//\n\t\t\t\tif (parentNode.stackWrapEnabled) {\n\t\t\t\t\t// This case will look like this:\n\t\t\t\t\t//\n\t\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t\t\t// \u2502 \u2502      \u2502 \u2502  \u2502 \u2502      \u2502 \u2502\n\t\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510       \u2502\n\t\t\t\t\t// \u2502 \u2502   \u2502 \u2502        \u2502       \u2502\n\t\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518       \u2502\n\t\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t\t//\n\t\t\t\t\t// To compute the exact `y` of a node in such wrapping stack, we need to know\n\t\t\t\t\t// which line that node is at. For that, we need to know node widths. We know\n\t\t\t\t\t// them already (see computeCSSWidth), but we need to integrate that algorithm\n\t\t\t\t\t// with this one.\n\t\t\t\t\t//\n\t\t\t\t\t// However, we can still return a useful minimum: the node\n\t\t\t\t\t// is guaranteed to be at least at `parentNode.y + parentNode.paddingTop`. This\n\t\t\t\t\t// allows images that are definitely below the fold (based on parent position)\n\t\t\t\t\t// to still get loading=lazy, even if we can't compute their exact row position.\n\t\t\t\t\t//\n\t\t\t\t\t// FIXME: for better precision, integrate with width calculations to determine\n\t\t\t\t\t// actual row position\n\t\t\t\t\treturn numberOp(\"+\", innerSimulateYPosition(parentNode, ctx), getNodePaddingTop(parentNode))\n\t\t\t\t}\n\n\t\t\t\t//\n\t\t\t\t// This is a horizontal stack with wrapping disabled\n\t\t\t\t//\n\t\t\t\tif (isDynamicValue(parentNode.stackAlignment)) {\n\t\t\t\t\t// We don\u2019t currently support variables in stack alignment. Instead of throwing\n\t\t\t\t\t// `CantCalculate`, we return a reasonable minimum: the node is guaranteed to be at least\n\t\t\t\t\t// at `parentNode.y + parentNode.paddingTop`. This allows images that are definitely below\n\t\t\t\t\t// the fold (based on parent position) to still get loading=lazy, even if we can\u2019t compute\n\t\t\t\t\t// whether they should be aligned to the top, center, or bottom of the stack.\n\t\t\t\t\t//\n\t\t\t\t\t// FIXME: support variables for better precision\n\t\t\t\t\treturn numberOp(\"+\", innerSimulateYPosition(parentNode, ctx), getNodePaddingTop(parentNode))\n\t\t\t\t}\n\n\t\t\t\tconst parentHeight = innerSimulateHeight(parentNode, ctx)\n\t\t\t\tconst parentContentBoxHeight = numberOp(\n\t\t\t\t\t\"-\",\n\t\t\t\t\tparentHeight,\n\t\t\t\t\tgetNodePaddingTop(parentNode) + getNodePaddingBottom(parentNode),\n\t\t\t\t)\n\n\t\t\t\tassert(parentNode.stackAlignment, `parentNode for node must have stackAlignment`)\n\n\t\t\t\tif (parentNode.stackAlignment === \"start\") {\n\t\t\t\t\t// This case will look like this:\n\t\t\t\t\t//\n\t\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2510 \u250C\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t\t\t// \u2502 \u2502        \u2502 \u2502 \u2502 \u2502   \u2502 \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 \u2514\u2500\u2500\u2500\u2518 \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502            \u2502 \u2502       \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502            \u2514\u2500\u2518       \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t\t\t// \u2502                             \u2502\n\t\t\t\t\t// \u2502                             \u2502\n\t\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t\t//\n\t\t\t\t\t// In this situation, the `y` of any node inside the stack is the parent\u2019s `y`\n\t\t\t\t\t// plus its padding top\n\t\t\t\t\treturn numberOp(\"+\", innerSimulateYPosition(parentNode, ctx), getNodePaddingTop(parentNode))\n\t\t\t\t} else if (parentNode.stackAlignment === \"center\") {\n\t\t\t\t\t// This case will look like this:\n\t\t\t\t\t//\n\t\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t\t// \u2502                             \u2502\n\t\t\t\t\t// \u2502            \u250C\u2500\u2510       \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 \u250C\u2500\u2500\u2500\u2510 \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502 \u2502        \u2502 \u2502 \u2502 \u2502   \u2502 \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 \u2514\u2500\u2500\u2500\u2518 \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502            \u2514\u2500\u2518       \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t\t\t// \u2502                             \u2502\n\t\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t\t//\n\t\t\t\t\t// In this case, the `y` of any node inside the stack is the parent\u2019s `y`\n\t\t\t\t\t// plus its padding top plus half of the remaining free space around the node\n\t\t\t\t\tconst nodeHeight = innerSimulateHeight(node, ctx)\n\t\t\t\t\tconst freeSpace = numberOp(\"-\", parentContentBoxHeight, nodeHeight)\n\n\t\t\t\t\treturn numberOp(\n\t\t\t\t\t\t\"+\",\n\t\t\t\t\t\tinnerSimulateYPosition(parentNode, ctx),\n\t\t\t\t\t\tnumberOp(\"+\", getNodePaddingTop(parentNode), numberOp(\"/\", freeSpace, 2)),\n\t\t\t\t\t)\n\t\t\t\t} else if (parentNode.stackAlignment === \"end\") {\n\t\t\t\t\t// This case will look like this:\n\t\t\t\t\t//\n\t\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t\t// \u2502                             \u2502\n\t\t\t\t\t// \u2502                             \u2502\n\t\t\t\t\t// \u2502            \u250C\u2500\u2510       \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t\t\t// \u2502            \u2502 \u2502       \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 \u250C\u2500\u2500\u2500\u2510 \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502 \u2502        \u2502 \u2502 \u2502 \u2502   \u2502 \u2502    \u2502 \u2502\n\t\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2518 \u2514\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t\t//\n\t\t\t\t\t// In this case, the `y` of any node inside the stack is the parent\u2019s `y`\n\t\t\t\t\t// plus its padding top plus all remaining free space around the node\n\t\t\t\t\tconst nodeHeight = innerSimulateHeight(node, ctx)\n\t\t\t\t\tconst freeSpace = numberOp(\"-\", parentContentBoxHeight, nodeHeight)\n\n\t\t\t\t\treturn numberOp(\"+\", innerSimulateYPosition(parentNode, ctx), getNodePaddingTop(parentNode), freeSpace)\n\t\t\t\t} else {\n\t\t\t\t\tassertNever(parentNode.stackAlignment)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (parentNode.stackDirection === \"vertical\") {\n\t\t\t\t// This case will look like this (if the stack is non-wrapping):\n\t\t\t\t//\n\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t\t// \u2502 \u2502    \u2502 \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502\n\t\t\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t//\n\t\t\t\t// or like this (if the stack is wrapping):\n\t\t\t\t//\n\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2510    \u250C\u2500\u2500\u2510   \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2518    \u2502  \u2502   \u2502\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510  \u2514\u2500\u2500\u2518   \u2502\n\t\t\t\t// \u2502 \u2502    \u2502  \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518  \u2502    \u2502 \u2502\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2510    \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t\t\t// \u2502 \u2502  \u2502    \u250C\u2500\u2500\u2510   \u2502\n\t\t\t\t// \u2502 \u2502  \u2502    \u2514\u2500\u2500\u2518   \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2518           \u2502\n\t\t\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510         \u2502\n\t\t\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518         \u2502\n\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t//\n\t\t\t\t// In either case, to compute the `y` of the current node, we:\n\t\t\t\t// - do stack layouting to figure out which column the node is in, and how large `1fr` is\n\t\t\t\t//   for that column\n\t\t\t\t// - and then sum heights of all items above the current one (plus some extra variables,\n\t\t\t\t//   depending on the stack distribution)\n\n\t\t\t\t// Do stack layouting for all stack children\n\t\t\t\tconst stackLayoutInfo = getVerticalStackLayoutInfo(\n\t\t\t\t\tparentNode,\n\t\t\t\t\tctx,\n\t\t\t\t\tnode => innerSimulateHeight(node, ctx),\n\t\t\t\t\tnode => simulateMinHeight(node, ctx),\n\t\t\t\t\tnode => simulateMaxHeight(node, ctx),\n\t\t\t\t)\n\n\t\t\t\t// Find the column the current item is in, plus its index in the column\n\t\t\t\tconst itemCoordinates = stackLayoutInfo.findCoordinates(node.id)\n\t\t\t\tassert(itemCoordinates, `Node must be found in stack layout info`)\n\n\t\t\t\t// Find the height of all items in the column\n\t\t\t\tconst itemHeights = getItemHeightsInStackColumn(itemCoordinates.columnIndex, stackLayoutInfo, ctx)\n\n\t\t\t\t// Compute the y position of the current node relative to the start of the stack\n\t\t\t\tconst yRelativeToContentStart = getRelativeYInVerticalStackColumn(\n\t\t\t\t\titemCoordinates.columnItemIndex,\n\t\t\t\t\titemHeights,\n\t\t\t\t\tparentNode,\n\t\t\t\t\tctx,\n\t\t\t\t)\n\n\t\t\t\tconst args: NumberOpArguments = [\n\t\t\t\t\tinnerSimulateYPosition(parentNode, ctx),\n\t\t\t\t\tgetNodePaddingTop(parentNode),\n\t\t\t\t\tyRelativeToContentStart,\n\t\t\t\t]\n\n\t\t\t\t// Edge case: The root of a Layout Template is a stack with\n\t\t\t\t// tight constraints (it\u2019s always vertical, it can\u2019t wrap, etc).\n\t\t\t\t// If the current node is a child of such stack, *and* it comes\n\t\t\t\t// after the Layout Template Slot, assume the node will not be\n\t\t\t\t// in the viewport. The height of the slot is unknowable since\n\t\t\t\t// it is determined by the webpage that is rendered as a child\n\t\t\t\t// of the Layout Template, and changes as the Route changes.\n\t\t\t\tif (isLayoutTemplateSlotSibling(parentNode, node, ctx)) args.unshift(VIEWPORT_HEIGHT)\n\n\t\t\t\treturn numberOp(\"+\", ...args)\n\t\t\t}\n\n\t\t\tif (isDynamicValue(parentNode.stackDirection)) {\n\t\t\t\t// We don\u2019t currently support variables in stack direction. Instead of throwing\n\t\t\t\t// `CantCalculate`, we return a reasonable minimum: the node is guaranteed to be at least\n\t\t\t\t// at `parentNode.y + parentNode.paddingTop`. This allows images that are definitely below\n\t\t\t\t// the fold (based on parent position) to still get loading=lazy, even if we can\u2019t compute\n\t\t\t\t// whether they should be flowing horizontally or vertically.\n\t\t\t\t//\n\t\t\t\t// FIXME: support variables for better precision\n\t\t\t\treturn numberOp(\"+\", innerSimulateYPosition(parentNode, ctx), getNodePaddingTop(parentNode))\n\t\t\t}\n\n\t\t\tassertNever(parentNode.stackDirection)\n\t\t}\n\n\t\tif (hasGridLayout(parentNode)) {\n\t\t\tassert(!isUndefined(parentNode.gridColumnCount), `parentNode for node must have gridColumnCount`)\n\n\t\t\tif (parentNode.gridColumnCount === \"auto-fill\") {\n\t\t\t\t// With auto-fill grid columns, the row the current node will be in depends on the widths of siblings,\n\t\t\t\t// and the width of the grid itself. E.g., in this grid, the node marked X is in the second row:\n\t\t\t\t//\n\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2502\n\t\t\t\t// \u2502\u2502   \u2502 \u2502      \u2502\u2502\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2502\n\t\t\t\t// \u2502\u250C\u2500\u2510   \u250C\u2500\u2500\u2500\u2510   \u2502\n\t\t\t\t// \u2502\u2502X\u2502   \u2502   \u2502   \u2502\n\t\t\t\t// \u2502\u2514\u2500\u2518   \u2514\u2500\u2500\u2500\u2518   \u2502\n\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t//\n\t\t\t\t// But if you make the grid wider, the node will automatically reflow to the first row:\n\t\t\t\t//\n\t\t\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2510\u2502\n\t\t\t\t// \u2502\u2502   \u2502 \u2502      \u2502 \u2502X\u2502\u2502\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2518\u2502\n\t\t\t\t// \u2502\u250C\u2500\u2500\u2500\u2510             \u2502\n\t\t\t\t// \u2502\u2502   \u2502             \u2502\n\t\t\t\t// \u2502\u2514\u2500\u2500\u2500\u2518             \u2502\n\t\t\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t\t\t//\n\t\t\t\t// To compute the exact `y` of that \"X\" node in such grid, we need to know\n\t\t\t\t// which row it is in. For that, we need to know node widths. We know them\n\t\t\t\t// already (see computeCSSWidth), but we need to integrate that algorithm\n\t\t\t\t// with this one.\n\t\t\t\t//\n\t\t\t\t// However, we can still return a useful minimum: the node is guaranteed to be\n\t\t\t\t// at least at `parentNode.y + parentNode.paddingTop`. This allows images that\n\t\t\t\t// are definitely below the fold (based on parent position) to still get\n\t\t\t\t// loading=lazy, even if we can't compute their exact row position.\n\t\t\t\t//\n\t\t\t\t// FIXME: for better precision, integrate with width calculations to determine\n\t\t\t\t// actual row position\n\t\t\t\treturn numberOp(\"+\", innerSimulateYPosition(parentNode, ctx), getNodePaddingTop(parentNode))\n\t\t\t}\n\n\t\t\tif (isNumber(parentNode.gridColumnCount)) {\n\t\t\t\tconst gridLayoutInfo = getGridLayoutInfo(parentNode, ctx)\n\t\t\t\tif (gridLayoutInfo.isEmpty()) {\n\t\t\t\t\t// We could end up here if e.g. the `parentNode` is a data repeater,\n\t\t\t\t\t// and the `node` is the repeater template, but the data is empty.\n\t\t\t\t\treturn numberOp(\"+\", innerSimulateYPosition(parentNode, ctx), getNodePaddingTop(parentNode))\n\t\t\t\t}\n\n\t\t\t\tconst nodeCoordinates = gridLayoutInfo.findCoordinates(node.id)\n\t\t\t\tassert(nodeCoordinates, `Node must be found in the grid layout info`)\n\n\t\t\t\tconst yRelativeToContentStart = getRelativeYInGrid(nodeCoordinates.rowIndex, gridLayoutInfo, parentNode, ctx)\n\n\t\t\t\treturn numberOp(\n\t\t\t\t\t\"+\",\n\t\t\t\t\tinnerSimulateYPosition(parentNode, ctx),\n\t\t\t\t\tgetNodePaddingTop(parentNode),\n\t\t\t\t\tyRelativeToContentStart,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tassertNever(parentNode.gridColumnCount)\n\t\t}\n\n\t\tassert(false, `Relative and sticky nodes can only exist in stacks or grids`)\n\t}\n\n\tassertNever(nodeEffectivePosition)\n}\n\nfunction getItemHeightsInStackColumn(columnIndex: number, stackLayoutInfo: StackLayoutInfo, ctx: SimulationContext) {\n\tconst itemHeights: SimulatedDOMNumberValue[] = []\n\n\tstackLayoutInfo.walkColumn(columnIndex, itemId => {\n\t\tconst currentItem = ctx.tree.get(itemId)\n\t\tassert(\n\t\t\tcurrentItem && withSize(currentItem) && withSizeDimensionType(currentItem),\n\t\t\t`column item must exist, have size, and have size dimension type`,\n\t\t)\n\n\t\tlet currentItemHeight: SimulatedDOMNumberValue\n\t\tif (currentItem.heightType === DimensionType.FractionOfFreeSpace) {\n\t\t\tconst returnedFrToPx = stackLayoutInfo.getFrToPxForColumn(columnIndex)\n\t\t\tassert(returnedFrToPx, `frToPx must be available for the column`)\n\t\t\tcurrentItemHeight = numberOp(\"*\", returnedFrToPx, currentItem.height /* fr units */)\n\t\t} else {\n\t\t\tcurrentItemHeight = innerSimulateHeight(currentItem, ctx)\n\t\t}\n\n\t\titemHeights.push(currentItemHeight)\n\t})\n\n\treturn itemHeights\n}\n\n/**\n * Sum all heights of stack children, memoizing the result. Memoization will greatly help in cases\n * when we have a stack with a 1000+ items (e.g. a repeater), and we end up calling\n * getRelativeYInVerticalStackColumn() for each item in the stack (e.g. because each item is an image).\n */\nfunction sumAllStackChildrenHeights(\n\tstackNode: CanvasNode & WithPins & WithPositionType & HasStackLayout,\n\titemHeights: SimulatedDOMNumberValue[],\n\tctx: SimulationContext,\n) {\n\treturn ctx.cache.memo(\n\t\t`sumAllStackChildrenHeights-${stackNode.id}`,\n\t\t() => numberOp(\"+\", ...itemHeights) ?? numberConst(0),\n\t)\n}\n\nfunction getRelativeYInVerticalStackColumn(\n\tnodeIndex: number,\n\titemHeights: SimulatedDOMNumberValue[],\n\tstackNode: CanvasNode & WithPins & WithPositionType & HasStackLayout,\n\tctx: SimulationContext,\n) {\n\tconst stackDistribution = stackNode.stackDistribution\n\tassert(stackDistribution, `parentNode for node must have stackDistribution`)\n\t// We don\u2019t currently support variables for stack distribution. Instead of throwing\n\t// `CantCalculate`, we return a reasonable minimum: the node is guaranteed to be at least\n\t// at `0`. This allows images that are definitely below the fold (based on parent position)\n\t// to still get loading=lazy, even if we can\u2019t compute whether they should be aligned\n\t// to the top, center, or bottom of the stack.\n\t//\n\t// FIXME: support variables for better precision\n\tif (isDynamicValue(stackDistribution)) return numberConst(0)\n\n\tconst parentOuterHeight = innerSimulateHeight(stackNode, ctx)\n\tconst parentInnerHeight = numberOp(\n\t\t\"-\",\n\t\tparentOuterHeight,\n\t\tgetNodePaddingTop(stackNode) + getNodePaddingBottom(stackNode),\n\t)\n\n\tif (stackDistribution === \"start\" || stackDistribution === \"center\" || stackDistribution === \"end\") {\n\t\tconst resolvedItemGap = resolveGap(stackNode.gap)\n\t\tconst itemGap = getNumericColumnGapFromShorthand(resolvedItemGap)\n\n\t\t// A start-aligned stack looks like this:\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510 stack\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518 gap\n\t\t// \u2502 \u2502    \u2502 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t// \u2502        \u2502\n\t\t// \u2502        \u2502\n\t\t// \u2502        \u2502\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t//\n\t\t// A center-aligned stack looks like this:\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 top offset\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510 stack\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518 gap\n\t\t// \u2502 \u2502    \u2502 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t// \u2502        \u2502\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t//\n\t\t// An end-aligned stack looks like this:\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502\n\t\t// \u2502        \u2502    \u2502 top offset\n\t\t// \u2502        \u2502    \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510 stack\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518 gap\n\t\t// \u2502 \u2502    \u2502 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t//\n\t\t// In all of these stacks, a node\u2019s `y` := sum(heights of items above it) + sum(gaps above it) + top offset.\n\t\t// The only difference between them is in the top offset, which equals\n\t\t// - if the stackDistribution is \"start\": 0\n\t\t// - if the stackDistribution is \"center\": half of the free space\n\t\t// - if the stackDistribution is \"end\": the full free space\n\n\t\tlet topOffset: SimulatedDOMNumberValue\n\t\tif (stackDistribution === \"start\") {\n\t\t\ttopOffset = numberConst(0)\n\t\t} else {\n\t\t\tconst sumOfAllItemHeights = sumAllStackChildrenHeights(stackNode, itemHeights, ctx)\n\t\t\tconst sumOfAllGaps = itemGap * (itemHeights.length - 1)\n\t\t\tconst freeSpace = numberOp(\"-\", parentInnerHeight, numberOp(\"+\", sumOfAllItemHeights, sumOfAllGaps))\n\t\t\ttopOffset = stackDistribution === \"center\" ? numberOp(\"/\", freeSpace, 2) : freeSpace\n\t\t}\n\n\t\tconst itemHeightsAbove = numberOpForArraySlice(\"+\", 0, nodeIndex, itemHeights) ?? numberConst(0)\n\t\tconst gapsAbove = itemGap * nodeIndex\n\n\t\treturn numberOp(\"+\", topOffset, itemHeightsAbove, gapsAbove)\n\t}\n\n\tif (\n\t\tstackDistribution === \"space-between\" ||\n\t\tstackDistribution === \"space-around\" ||\n\t\tstackDistribution === \"space-evenly\"\n\t) {\n\t\t// A space-between-aligned stack looks like this:\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502\n\t\t// \u2502        \u2502    \u2502 spaceBetween\n\t\t// \u2502        \u2502    \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2502    \u2502 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502\n\t\t// \u2502        \u2502    \u2502 spaceBetween\n\t\t// \u2502        \u2502    \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502\n\t\t// \u2502        \u2502    \u2502 spaceBetween\n\t\t// \u2502        \u2502    \u2502\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t//\n\t\t// A space-around-aligned stack looks like this:\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 topOffset = spaceAround / 2\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 space\n\t\t// \u2502        \u2502    \u2502 Around\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2502    \u2502 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 space\n\t\t// \u2502        \u2502    \u2502 Around\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 space\n\t\t// \u2502        \u2502    \u2502 Around\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 bottomOffset = spaceAround / 2\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2500\u2500\u2518\n\t\t//\n\t\t// A space-evenly-aligned stack looks like this (https://www.samanthaming.com/flexbox30/14-space-around-vs-space-evenly/):\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 topOffset = spaceEvenly\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 spaceEvenly\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2502    \u2502 \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 spaceEvenly\n\t\t// \u2502 \u250C\u2500\u2500\u2510   \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2502  \u2502   \u2502\n\t\t// \u2502 \u2514\u2500\u2500\u2518   \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 spaceEvenly\n\t\t// \u2502 \u250C\u2500\u2500\u2500\u2500\u2510 \u2502  \u2500\u2500\u2518\n\t\t// \u2502 \u2514\u2500\u2500\u2500\u2500\u2518 \u2502  \u2500\u2500\u2510\n\t\t// \u2502        \u2502    \u2502 bottomOffset = spaceEvenly\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2500\u2500\u2518\n\t\t//\n\t\t// In each of these stacks, a node\u2019s `y` := sum(heights of items above it) + sum(spaces above it) + top offset.\n\t\t// The only differences between each stack are:\n\t\t// - the size of the spaces between items\n\t\t//   - in space-between stacks, it\u2019s free space / (count(all items) - 1)\n\t\t//   - in space-around stacks, it\u2019s free space / (count(all items))\n\t\t//   - in space-evenly stacks, it\u2019s free space / (count(all items) + 1)\n\t\t// - the top offset\n\t\t//   - in space-between stacks, it\u2019s 0\n\t\t//   - in space-around stacks, it\u2019s the size of the spaces between items / 2\n\t\t//   - in space-evenly stacks, it\u2019s the size of the spaces between items\n\n\t\t// Note: stack gaps have no effect in stacks like these ones, so we don\u2019t need to include them into calculations.\n\t\tassert(!supportGap(stackNode), \"gap is not expected with stackDistribution:\", stackNode.stackDistribution)\n\n\t\tconst sumOfAllItemHeights = sumAllStackChildrenHeights(stackNode, itemHeights, ctx)\n\t\tconst freeSpace = numberOp(\"-\", parentInnerHeight, sumOfAllItemHeights)\n\n\t\tconst numberOfItems = itemHeights.length\n\t\tlet space: SimulatedDOMNumberValue\n\t\tswitch (stackDistribution) {\n\t\t\tcase \"space-between\":\n\t\t\t\t// Math.max() ensures no division by zero\n\t\t\t\tspace = numberOp(\"/\", freeSpace, Math.max(1, numberOfItems - 1))\n\t\t\t\tbreak\n\t\t\tcase \"space-around\":\n\t\t\t\tspace = numberOp(\"/\", freeSpace, numberOfItems)\n\t\t\t\tbreak\n\t\t\tcase \"space-evenly\":\n\t\t\t\tspace = numberOp(\"/\", freeSpace, numberOfItems + 1)\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tassertNever(stackDistribution)\n\t\t}\n\n\t\tlet topOffset: SimulatedDOMNumberValue\n\t\tswitch (stackDistribution) {\n\t\t\tcase \"space-between\":\n\t\t\t\ttopOffset = numberConst(0)\n\t\t\t\tbreak\n\t\t\tcase \"space-around\":\n\t\t\t\ttopOffset = numberOp(\"/\", space, 2)\n\t\t\t\tbreak\n\t\t\tcase \"space-evenly\":\n\t\t\t\ttopOffset = space\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tassertNever(stackDistribution)\n\t\t}\n\n\t\tconst itemHeightsAbove = numberOpForArraySlice(\"+\", 0, nodeIndex, itemHeights) ?? numberConst(0)\n\t\tconst spacesAbove = numberOp(\"*\", space, nodeIndex)\n\n\t\treturn numberOp(\"+\", topOffset, itemHeightsAbove, spacesAbove)\n\t}\n\n\tassertNever(stackDistribution)\n}\n\nfunction getRelativeYInGrid(\n\tnodeRowIndex: number,\n\tgridLayoutInfo: GridLayoutInfo,\n\tgridNode: CanvasNode & HasGridLayout,\n\tctx: SimulationContext,\n) {\n\tassert(!isUndefined(gridNode.gridRowHeightType), `parentNode for node must have gridRowHeightType defined`)\n\n\tif (gridNode.gridRowHeightType === \"fixed\") {\n\t\t// This is a grid where each row has a fixed height:\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2510   \u2502\n\t\t// \u2502\u2502    \u2502 \u2502   \u2502   \u2502\n\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2518   \u2502\n\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2502\n\t\t// \u2502\u2502 X \u2502  \u2502      \u2502\u2502\n\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2502\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t//\n\t\t// To compute the Y position of the node marked with X, we just need to check which row it is in.\n\t\tassert(\n\t\t\t!isUndefined(gridNode.gridRowHeight),\n\t\t\t`A grid parent node with gridRowHeightType === 'fixed' (for node) must have gridRowHeight defined`,\n\t\t)\n\n\t\tconst rowHeightsAbove = nodeRowIndex * gridNode.gridRowHeight\n\n\t\tconst resolvedGap = resolveGap(gridNode.gap)\n\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\tconst gapsAbove = nodeRowIndex * gap\n\t\treturn numberConst(rowHeightsAbove + gapsAbove)\n\t}\n\n\tif (gridNode.gridRowHeightType === \"fit\") {\n\t\t// This is a grid where each row is as tall as its tallest child is:\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2510\u2502\n\t\t// \u2502\u2502    \u2502 \u2502   \u2502\u2502\n\t\t// \u2502\u2502    \u2502 \u2514\u2500\u2500\u2500\u2518\u2502\n\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2518      \u2502\n\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u250C\u2500\u2500\u2500\u2510\u2502\n\t\t// \u2502\u2502   \u2502  \u2502   \u2502\u2502\n\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2502   \u2502\u2502\n\t\t// \u2502       \u2502   \u2502\u2502\n\t\t// \u2502       \u2514\u2500\u2500\u2500\u2518\u2502\n\t\t// \u2502            \u2502\n\t\t// \u2502            \u2502\n\t\t// \u2502            \u2502\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t//\n\t\t// In such grid:\n\t\t//   node\u2019s y := sum(heights of each row above) + sum(gaps above),\n\t\t//   where\n\t\t//     height of each row := max(height of each child in the row)\n\t\tconst rowHeights: SimulatedDOMNumberValue[] = []\n\n\t\t// Why `< currentNodeRowIndex`: we only care about the rows that are above the node we\u2019re measuring\n\t\tfor (let rowIndex = 0; rowIndex < nodeRowIndex; rowIndex++) {\n\t\t\tfor (let columnIndex = 0; columnIndex < gridLayoutInfo.columnCount; columnIndex++) {\n\t\t\t\tconst child = ctx.tree.get(gridLayoutInfo.getGridItem(rowIndex, columnIndex))\n\t\t\t\t// Some grid cells might be empty\n\t\t\t\tif (!child) continue\n\n\t\t\t\tassert(withSize(child) && withSizeDimensionType(child), `grid child must have size and size-dimension type`)\n\t\t\t\t// Note 1: we might end up calling `computeNodeHeight` on the same child multiple times\n\t\t\t\t// (if it spans multiple columns), but this is essentially free thanks to caching in `innerSimulateHeight`.\n\t\t\t\t// Note 2: we don\u2019t need to care about nodes spanning multiple *rows* because fit grids don\u2019t support that today\n\t\t\t\tconst childHeight = innerSimulateHeight(child, ctx)\n\t\t\t\trowHeights[rowIndex] = numberOp(\"max\", rowHeights[rowIndex] ?? numberConst(0), childHeight)\n\t\t\t}\n\t\t}\n\n\t\tconst rowHeightsAbove = numberOp(\"+\", ...rowHeights) ?? numberConst(0)\n\t\tconst resolvedGap = resolveGap(gridNode.gap)\n\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\tconst gapsAbove = nodeRowIndex * gap\n\t\treturn numberOp(\"+\", rowHeightsAbove, gapsAbove)\n\t}\n\n\tif (gridNode.gridRowHeightType === \"auto\") {\n\t\t// This is a grid where rows fill all available space evenly:\n\t\t//\n\t\t// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\t// \u2502\u250C\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2510\u2502  \u2500\u2500\u2510\n\t\t// \u2502\u2502    \u2502 \u2502   \u2502\u2502    \u2502\n\t\t// \u2502\u2502    \u2502 \u2514\u2500\u2500\u2500\u2518\u2502    \u2502 row 1: 50% of the grid\n\t\t// \u2502\u2514\u2500\u2500\u2500\u2500\u2518      \u2502    \u2502\n\t\t// \u2502            \u2502  \u2500\u2500\u2518\n\t\t// \u2502\u250C\u2500\u2500\u2500\u2510  \u250C\u2500\u2500\u2500\u2510\u2502  \u2500\u2500\u2510\n\t\t// \u2502\u2502   \u2502  \u2502   \u2502\u2502    \u2502\n\t\t// \u2502\u2514\u2500\u2500\u2500\u2518  \u2502   \u2502\u2502    \u2502 row 2: 50% of the grid\n\t\t// \u2502       \u2502   \u2502\u2502    \u2502\n\t\t// \u2502       \u2514\u2500\u2500\u2500\u2518\u2502  \u2500\u2500\u2518\n\t\t// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\t\t//\n\t\t// In such grid:\n\t\t//   node\u2019s y := sum(heights of each row above) + sum(gaps above),\n\t\t//   where\n\t\t//     height of each row := (grid\u2019s inner height - sum(all gaps)) / count(rows)\n\t\tconst parentOuterHeight = innerSimulateHeight(gridNode, ctx)\n\t\tconst gridInnerHeight = numberOp(\n\t\t\t\"-\",\n\t\t\tparentOuterHeight,\n\t\t\tgetNodePaddingTop(gridNode) + getNodePaddingBottom(gridNode),\n\t\t)\n\n\t\tconst gridRowInfo = getGridLayoutInfo(gridNode, ctx)\n\t\tconst rowCount = gridRowInfo.rowCount\n\t\tconst resolvedGap = resolveGap(gridNode.gap)\n\t\tconst gap = getNumericColumnGapFromShorthand(resolvedGap)\n\t\tconst totalGaps = (gridRowInfo.rowCount - 1) * gap\n\t\tconst rowHeight = numberOp(\"/\", numberOp(\"-\", gridInnerHeight, totalGaps), rowCount)\n\n\t\tconst rowHeightsAbove = numberOp(\"*\", nodeRowIndex, rowHeight)\n\t\tconst gapsAbove = nodeRowIndex * gap\n\t\treturn numberOp(\"+\", rowHeightsAbove, gapsAbove)\n\t}\n\n\tassertNever(gridNode.gridRowHeightType)\n}\n\n/** Returns the effective CSS position a node will have (`fixed`, `sticky`, `absolute`, or undefined for `relative`). */\nfunction getNodeEffectivePosition(\n\tnode: CanvasNode & WithPins & WithPositionType,\n\tparentNode: CanvasNode | null,\n\tctx: SimulationContext,\n): PositionType {\n\tif (canBePositionFixed(ctx.tree, node) && node.position === \"fixed\") return \"fixed\"\n\tif (canBePositionAbsolute(node, parentNode) && node.position === \"absolute\") return \"absolute\"\n\tif (canBePositionSticky(node, parentNode) && node.position === \"sticky\") return \"sticky\"\n\tif (parentNode && isOverlayNode(parentNode)) return \"fixed\"\n\t// \u201Cundefined\u201D means \u201Crelative\u201D\n\tif (parentNode && hasAnyLayout(parentNode)) return undefined\n\treturn \"absolute\"\n}\n\nfunction isLayoutTemplateSlotSibling(parentNode: CanvasNode, node: CanvasNode, ctx: SimulationContext): boolean {\n\tif (isBreakpointVariant(parentNode) && isLayoutTemplateNode(ctx.tree.getScopeNodeFor(parentNode))) {\n\t\tconst slotIndex = parentNode.children?.findIndex(isSlotNode)\n\t\tif (isUndefined(slotIndex)) return false\n\t\tconst nodeIndex = ctx.tree.getIndex(node)\n\t\treturn slotIndex < nodeIndex\n\t}\n\treturn false\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { ComponentDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type { ValueTransformCollector } from \"code-generation/utils/valueTransformCollector/ValueTransformCollector.ts\"\nimport type { CanvasNode, CanvasTree, CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { nodeIsInOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport type { WithPins } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport type { WithPositionType } from \"document/models/CanvasTree/traits/WithPositionType.ts\"\nimport type { WithSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport type { WithSizeDimensionType } from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport type { ComponentViewport } from \"library/modules/ComponentViewportContext.tsx\"\nimport { type SimulationContext, createSimulationContext } from \"./SimulationContext.ts\"\nimport { simulateCSSWidth } from \"./simulateCSSWidth.ts\"\nimport { simulateHeight } from \"./simulateHeight.ts\"\nimport { simulateYPosition } from \"./simulateYPosition.ts\"\n\nexport class SimulatedDOM {\n\tprivate simulationContext: SimulationContext\n\n\tconstructor(\n\t\tcomponentLoader: ComponentLoader,\n\t\ttree: CanvasTree,\n\t\tvariables: VariableCollector,\n\t\tvalueTransforms: ValueTransformCollector,\n\t\timports: ImportCollector,\n\t\tdeclarations: ComponentDeclarationCollector,\n\t) {\n\t\tthis.simulationContext = createSimulationContext(\n\t\t\ttree,\n\t\t\tcomponentLoader,\n\t\t\tvariables,\n\t\t\tvalueTransforms,\n\t\t\timports,\n\t\t\tdeclarations,\n\t\t)\n\t}\n\n\tgetCSSWidth(node: CanvasNode & WithSize & WithSizeDimensionType) {\n\t\treturn simulateCSSWidth(node, this.simulationContext)\n\t}\n\n\tgetHeight(node: CanvasNode & WithSize & WithSizeDimensionType) {\n\t\treturn simulateHeight(node, this.simulationContext)\n\t}\n\n\tgetYPosition(node: CanvasNode & WithPins & WithPositionType) {\n\t\treturn simulateYPosition(node, this.simulationContext)\n\t}\n\n\t// Record<keyof ComponentViewport, unknown> is intended to check that all\n\t// ComponentViewport properties are included (even as undefined), but not\n\t// that their types are correct. We can\u2019t check types because the\n\t// ComponentViewport object lives at runtime, but the object this function\n\t// returns is used during codegen, so the types won\u2019t necessarily match\n\t// (think `SafeJS` during codegen that turns into a `number` during runtime).\n\tgetComponentViewportContext(node: CodeComponentNode): Record<keyof ComponentViewport, unknown> {\n\t\tconst width = this.getCSSWidth(node)\n\t\tlet height: number | SafeJS | undefined, y: number | SafeJS | undefined\n\t\tif (\n\t\t\t// Do not simulate the height and y position of nodes in overlays.\n\t\t\t// As of Dec 2024, the only optimization we use heights and y\n\t\t\t// positions for is <img loading=lazy>, and it\u2019s not needed for\n\t\t\t// images in overlays because they aren\u2019t in DOM when the page is\n\t\t\t// loading.\n\t\t\t!nodeIsInOverlay(node)\n\t\t) {\n\t\t\theight = this.getHeight(node)\n\t\t\ty = this.getYPosition(node)\n\t\t}\n\t\treturn { width, height, y }\n\t}\n}\n", "import hash from \"@emotion/hash\"\nimport { jst } from \"code-generation/js/js.ts\"\nimport type { CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { assert } from \"library/utils/assert.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport type { BindingCollector } from \"./BindingCollector.ts\"\nimport { getAncestorRepeaterIds } from \"./elementIdPatternForNode.ts\"\n\nexport class AppearIdCollector {\n\tids = new Map<string, number>()\n\n\tconstructor(\n\t\tprivate readonly tree: CanvasTree,\n\t\tprivate readonly bindings: BindingCollector,\n\t) {}\n\n\tcreate(nodeId: NodeID) {\n\t\tconst baseId = this.composeBaseId(nodeId)\n\n\t\tconst node = this.tree.get(nodeId)\n\t\tassert(node, \"AppearIdCollector: Node not found\")\n\n\t\t// If the node lives inside one or more repeaters, postfix the binding index of **each**\n\t\t// ancestor repeater (outer-to-inner) to guarantee uniqueness across nested repeater scopes.\n\t\tconst ancestorRepeaterIds = getAncestorRepeaterIds(node, this.tree)\n\t\tif (ancestorRepeaterIds.length > 0) {\n\t\t\tconst repeaterId = this.composeRepeaterId(baseId, ancestorRepeaterIds)\n\t\t\treturn repeaterId\n\t\t}\n\n\t\treturn baseId\n\t}\n\n\t/**\n\t * Generates a unique base id for a node regardless of whether it is inside a repeater.\n\t * The base id is stable per `nodeId` yet unique if the same `nodeId` is encountered\n\t * multiple times.\n\t */\n\tprivate composeBaseId(nodeId: NodeID) {\n\t\tconst hashedId = hash(nodeId)\n\t\tconst count = this.ids.get(hashedId)\n\n\t\tif (isUndefined(count)) {\n\t\t\tthis.ids.set(hashedId, 0)\n\t\t\treturn hashedId\n\t\t}\n\n\t\tconst next = count + 1\n\t\tthis.ids.set(hashedId, next)\n\t\treturn `${hashedId}-${next}`\n\t}\n\n\t/**\n\t * Builds `<baseId>-<outerIndex>-<innerIndex>-\u2026` so nested repeater items stay unique.\n\t */\n\tprivate composeRepeaterId(baseId: string, ancestorRepeaterIds: NodeID[]) {\n\t\tconst parts: (string | ReturnType<typeof this.bindings.createWithNode>)[] = [baseId]\n\n\t\tfor (const id of ancestorRepeaterIds) {\n\t\t\tconst repeater = this.tree.get(id)\n\t\t\tif (!repeater) continue\n\t\t\tparts.push(this.bindings.createWithNode(\"index\", repeater))\n\t\t}\n\n\t\treturn jst.join(parts, \"-\")\n\t}\n}\n", "import type {\n\tAssetMap,\n\tAssetReferenceParseResult,\n\tAssetSize,\n\tAssetWithOwnerTypes,\n\tVariantDimensions,\n} from \"@framerjs/assets\"\nimport {\n\tcreateAbsoluteAssetURL,\n\tcreateAbsoluteImageAssetURL,\n\tcreateAbsoluteImageAssetURLFromAsset,\n\tcreateAbsoluteImageAssetURLFromAssetWithPreferredSize,\n\tgetVariantsDimensions,\n\tparseAssetReference,\n} from \"@framerjs/assets\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { SerializableRecord } from \"code-generation/js/SerializableValue.ts\"\nimport type { WithControlFocalPoint } from \"document/models/controlProps/WithControlFocalPoint.ts\"\nimport { MinVariantSizeForSourceSet } from \"library/render/style/getSrcSet.ts\"\nimport type { RelativeNumber } from \"library/render/types/RelativeNumber.ts\"\nimport { assert } from \"library/utils/assert.ts\"\nimport { isNull, isNullish, isString } from \"utils/typeChecks.ts\"\n\nexport interface ResolvedAsset extends SerializableRecord {\n\t/**\n\t * absolute URL to asset\n\t */\n\tsrc: string\n\t/* @deprecated - Image components generate `srcSet`s */\n\tsrcSet?: string\n\tpreferredSize?: AssetSize\n\n\t/**\n\t * The actual size of the image processed by the asset service:\n\t * https://github.com/framer/FramerWebAssetsService/blob/aac3b5adbe7e45003109a048ca9db64f9e519ced/lib/reprocess/images.go\n\t * Note that it might not be identical to the pixel width/height we stored on a frame node with\n\t * an image fill, as those are density-corrected. But we only use this data for calculating the\n\t * aspect ratio, in which case the device ratio doesn't matter.\n\t */\n\tpixelWidth: number | undefined\n\tpixelHeight: number | undefined\n\n\t/**\n\t * focal point X\n\t */\n\tpositionX?: RelativeNumber\n\t/**\n\t * focal point Y\n\t */\n\tpositionY?: RelativeNumber\n}\n\nexport class AssetCollector {\n\tconstructor(private readonly assetMap: AssetMap) {}\n\n\t/**\n\t * Collected asset keys (with extensions).\n\t */\n\treadonly keys = new Set<string>()\n\n\taddAsset(assetKeyWithExtension: string) {\n\t\tthis.keys.add(assetKeyWithExtension)\n\t}\n\n\t#isValidIdentifier(identifier: string | undefined | null): identifier is string {\n\t\tif (\n\t\t\tisNullish(identifier) ||\n\t\t\t// Ignore already resolved images, due to a bug resolved asset references could\n\t\t\t// end up in the document model.\n\t\t\tidentifier.startsWith(\"https:\")\n\t\t) {\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}\n\n\t/**\n\t * Resolves an identifier to its reference.\n\t * @return null only if identifier is not valid or must not be resolved (again).\n\t */\n\t#resolveAssetReference(identifier: string): AssetReferenceParseResult | undefined | null {\n\t\tconst assetReference = parseAssetReference(identifier)\n\t\tif (assetReference) identifier = assetReference.identifier\n\n\t\t// Prevent creating empty string asset references, which will fail\n\t\t// evaluation once code generated. `createAssetReference` already\n\t\t// asserts this is not the case, but it seems it is still possible to\n\t\t// encounter this case.\n\t\tif (identifier === \"\") return null\n\n\t\t// Track asset keys that we've encountered (regardless of size).\n\t\tthis.addAsset(identifier)\n\n\t\treturn assetReference\n\t}\n\n\t/**\n\t * Resolves any non-image asset to their reference and returns the absolute URL.\n\t * @see {@link resolveResponsiveImage} for resolving images.\n\t */\n\tresolve(identifier: string | null | undefined): { src: string } | undefined {\n\t\tif (!this.#isValidIdentifier(identifier)) return\n\n\t\tconst assetReference = this.#resolveAssetReference(identifier)\n\t\tif (isNull(assetReference)) return\n\t\tif (assetReference) identifier = assetReference.identifier\n\n\t\treturn {\n\t\t\tsrc: createAbsoluteAssetURL(identifier),\n\t\t}\n\t}\n\n\t/**\n\t * Resolves an image asset to their reference and returns {@link ResolvedAsset}.\n\t * If the asset is not an image, use {@link resolve} instead.\n\t */\n\tresolveResponsiveImage(\n\t\tidentifier: string | null | undefined,\n\t\t{ focalPoint }: { focalPoint?: WithControlFocalPoint } = {},\n\t): ResolvedAsset | undefined {\n\t\tif (!this.#isValidIdentifier(identifier)) return\n\n\t\tconst assetReference = this.#resolveAssetReference(identifier)\n\t\tif (isNull(assetReference)) return\n\n\t\tif (assetReference) {\n\t\t\tidentifier = assetReference.identifier\n\t\t}\n\t\tconst preferredSize: AssetSize = assetReference?.preferredSize ?? \"auto\"\n\n\t\tconst asset = this.assetMap.assetForKey(identifier)\n\t\tconst props = asset?.properties?.image\n\t\tconst pixelDimensions = assetReference?.intrinsicSize ?? props\n\n\t\tconst variantsDimensions = getVariantsDimensions(props?.width, props?.height)\n\n\t\t// Find an available variant of the asset given the preferred size and context.\n\t\tconst imageSrc = asset\n\t\t\t? createAbsoluteImageAssetURLFromAssetWithPreferredSize(asset, preferredSize, variantsDimensions)\n\t\t\t: createAbsoluteImageAssetURL(identifier, undefined, undefined, pixelDimensions)\n\n\t\tconst result: ResolvedAsset = {\n\t\t\tsrc: imageSrc,\n\t\t\tpositionX: undefined,\n\t\t\tpositionY: undefined,\n\t\t\tsrcSet: experiments.isOn(\"fixedSizeImageSrcset\")\n\t\t\t\t? undefined\n\t\t\t\t: this.generateSrcSet(asset, variantsDimensions, preferredSize),\n\t\t\tpreferredSize: experiments.isOn(\"fixedSizeImageSrcset\") ? preferredSize : undefined,\n\t\t\tpixelWidth: pixelDimensions?.width,\n\t\t\tpixelHeight: pixelDimensions?.height,\n\t\t}\n\n\t\tif (focalPoint && isString(focalPoint.positionX) && isString(focalPoint.positionY)) {\n\t\t\tresult.positionX = focalPoint.positionX\n\t\t\tresult.positionY = focalPoint.positionY\n\t\t}\n\n\t\treturn result\n\t}\n\n\tgenerateSrcSet(\n\t\tasset: AssetWithOwnerTypes | undefined,\n\t\tvariantsDimensions: VariantDimensions[] | undefined,\n\t\tpreferredSize: AssetSize | undefined,\n\t): string | undefined {\n\t\tif (!asset) return\n\t\tassert(\n\t\t\t!experiments.isOn(\"fixedSizeImageSrcset\"),\n\t\t\t\"This code path must only be executed with fixedSizeImageSrcset: off\",\n\t\t)\n\n\t\tlet srcSet: string | undefined\n\t\t// We only need a srcset for automated optimizations, so when a user hasn't picked a certain resolution.\n\t\t// Full is a special case here which uses lossless images, so we act like it's auto.\n\t\t// ref: https://github.com/framer/company/issues/28919\n\t\tconst shouldGenerateSrcset = !preferredSize || preferredSize === \"auto\" || preferredSize === \"lossless\"\n\t\tif (shouldGenerateSrcset && variantsDimensions?.length && asset.properties?.image) {\n\t\t\tsrcSet = \"\"\n\t\t\tfor (const { maxSideSize, width } of variantsDimensions) {\n\t\t\t\tif (width < MinVariantSizeForSourceSet) continue\n\n\t\t\t\tsrcSet += `${createAbsoluteImageAssetURLFromAsset(asset, maxSideSize, preferredSize === \"lossless\")} ${width}w,`\n\t\t\t}\n\n\t\t\t// Also include the original, so that browsers pick the non-scaled-down version on very large / high DPR monitors\n\t\t\tsrcSet += `${createAbsoluteImageAssetURLFromAsset(asset, undefined, preferredSize === \"lossless\")} ${\n\t\t\t\tasset.properties.image.width\n\t\t\t}w`\n\t\t}\n\n\t\treturn srcSet\n\t}\n}\n", "import hash from \"@emotion/hash\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { RenderConditions } from \"code-generation/types.ts\"\nimport type { NodeID, ScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport { withBreakpointVariants } from \"document/models/CanvasTree/traits/WithBreakpointVariants.ts\"\nimport { join } from \"utils/join.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { SafeJS, isSafeJS, serializeJS } from \"../js/serializeJS.ts\"\nimport { createUnique } from \"./BindingCollector.ts\"\nimport type { ComponentDeclarationCollector } from \"./DeclarationCollector.ts\"\n\n/**\n * - Keys: serialized values, e.g. \"true\", \"false\", \"qge3QPO_G\" (variable ID)\n * - Values: variant IDs\n */\ntype ConditionGroup = Map<string, Set<string>>\n\nexport class ConditionalRenderingCollector {\n\tconstructor(\n\t\tprivate readonly declarations: ComponentDeclarationCollector,\n\t\tprivate readonly scope?: ScopeNode,\n\t\tprivate readonly primaryVariantId?: NodeID,\n\t) {}\n\n\tcreate(\n\t\tprimaryCondition: boolean | SafeJS,\n\t\tvariantConditions: RenderConditions | undefined,\n\t): { condition: SafeJS | boolean; classNames?: Set<string>; classNameExpressions?: SafeJS.Set } {\n\t\t// If there are no render conditions the layer should render unconditionally\n\t\tif (primaryCondition === true && isUndefined(variantConditions)) {\n\t\t\treturn { condition: true }\n\t\t}\n\n\t\t// If there are is only a primary condition the layer should\n\t\t// render based on that condition (not at all or based on a variable).\n\t\tif (!isUndefined(primaryCondition) && isUndefined(variantConditions)) {\n\t\t\treturn { condition: primaryCondition }\n\t\t}\n\n\t\tif (variantConditions) {\n\t\t\t// If every variant condition is identical to the primary condition, we\n\t\t\t// can safely use the primary condition.\n\t\t\tif (Array.from(variantConditions.values()).every(({ value }) => value === primaryCondition)) {\n\t\t\t\treturn { condition: primaryCondition }\n\t\t\t}\n\n\t\t\tconst conditionalRenderingClassNames = new Set<string>()\n\t\t\tconst conditionalRenderingClassNameExpressions = new SafeJS.Set()\n\t\t\tif (withBreakpointVariants(this.scope) && this.primaryVariantId) {\n\t\t\t\tmaybeAddConditionalClassName(\n\t\t\t\t\tthis.primaryVariantId,\n\t\t\t\t\tprimaryCondition,\n\t\t\t\t\tconditionalRenderingClassNames,\n\t\t\t\t\tconditionalRenderingClassNameExpressions,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst gestureGroup: ConditionGroup = new Map()\n\t\t\tconst topLevelGroup: ConditionGroup = new Map()\n\n\t\t\tconst argumentNameByValueBinding = new Map<string, SafeJS>()\n\t\t\tconst getConditionValue = makeGetConditionalValue(argumentNameByValueBinding)\n\t\t\tconst primaryConditionValue = getConditionValue(primaryCondition)\n\n\t\t\t// To efficiently create logic to return the correct visibility for\n\t\t\t// the layer, iterate through all the conditions, and group them by\n\t\t\t// their conditional value. e.g. { true : [\"a\", \"b\"], \"variableX\":\n\t\t\t// [\"c\", \"d\"] }\n\t\t\tfor (const [variant, condition] of variantConditions) {\n\t\t\t\tif (withBreakpointVariants(this.scope)) {\n\t\t\t\t\tmaybeAddConditionalClassName(\n\t\t\t\t\t\tvariant,\n\t\t\t\t\t\tcondition.value,\n\t\t\t\t\t\tconditionalRenderingClassNames,\n\t\t\t\t\t\tconditionalRenderingClassNameExpressions,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// We don't need to group and record top-level conditions that\n\t\t\t\t// are the same as the primary, we can rely on the default\n\t\t\t\t// return value.\n\t\t\t\tif (!condition.isGesture && condition.value === primaryCondition) continue\n\n\t\t\t\t// Since we don't know if a gesture condition is different from\n\t\t\t\t// the top-level variant, we have to group and record every\n\t\t\t\t// gesture condition.\n\t\t\t\tconst group = condition.isGesture ? gestureGroup : topLevelGroup\n\t\t\t\tgroupVariantByValue(variant, getConditionValue(condition.value), group)\n\t\t\t}\n\n\t\t\tconst argumentNames: string[] = []\n\t\t\tconst argumentValues: SafeJS[] = []\n\n\t\t\tfor (const valueBinding of argumentNameByValueBinding.keys()) {\n\t\t\t\tconst name = argumentNameByValueBinding.get(valueBinding)\n\t\t\t\tif (!name) continue\n\n\t\t\t\targumentValues.push(new SafeJS(valueBinding))\n\t\t\t\targumentNames.push(serializeJS(name))\n\t\t\t}\n\n\t\t\tconst binding = this.declarations.dedupe(\n\t\t\t\t\"isDisplayed\",\n\t\t\t\tnew SafeJS(\n\t\t\t\t\tjoin.lines(\n\t\t\t\t\t\tjs`(${new SafeJS(argumentNames.join(\", \"))}) => {`,\n\t\t\t\t\t\t// During SSR, we only ever render with `baseVariant` set to the primary variant, but we don't\n\t\t\t\t\t\t// know what actual variant (breakpoint) will be shown to the user before hydration. So we must\n\t\t\t\t\t\t// not rely on variant conditions to determine visibility. Instead, we'll *always* render the\n\t\t\t\t\t\t// conditionally-visible layer into the HTML, and instead rely on the `hidden-xxx` classes\n\t\t\t\t\t\t// generated above to make sure we're showing or hiding the layer as needed before hydration.\n\t\t\t\t\t\twithBreakpointVariants(this.scope) && js`if (!${SafeJS.fn(Var.isBrowser)}) return true`,\n\t\t\t\t\t\t...this.createConditionStatementsForGroup(gestureGroup, \"gestureVariant\"),\n\t\t\t\t\t\t...this.createConditionStatementsForGroup(topLevelGroup, \"baseVariant\"),\n\t\t\t\t\t\tjs`return ${primaryConditionValue}`,\n\t\t\t\t\t\tjs`}`,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\n\t\t\treturn {\n\t\t\t\tcondition: SafeJS.fn(binding, ...argumentValues),\n\t\t\t\tclassNames: conditionalRenderingClassNames,\n\t\t\t\tclassNameExpressions: conditionalRenderingClassNameExpressions,\n\t\t\t}\n\t\t}\n\n\t\t// By default layers render unconditionally.\n\t\treturn { condition: true }\n\t}\n\n\tprivate createConditionStatementsForGroup(\n\t\tgroup: ConditionGroup,\n\t\tgroupVariable: \"gestureVariant\" | \"baseVariant\",\n\t): SafeJS[] {\n\t\tif (group.size === 0) return []\n\n\t\tconst statements: SafeJS[] = []\n\n\t\tconst variantVariable = new SafeJS(groupVariable)\n\t\tfor (const [serializedValue, variants] of group) {\n\t\t\tconst value = new SafeJS(serializedValue)\n\t\t\tif (variants.size === 1) {\n\t\t\t\t// If the layer only renders with a specific value when one variant\n\t\t\t\t// is active, it's clearer to just check if that variant is active.\n\t\t\t\tconst variant = Array.from(variants)[0]\n\t\t\t\tif (isUndefined(variant)) continue\n\t\t\t\tstatements.push(js`if (${variantVariable} === ${variant}) return ${value}`)\n\t\t\t} else {\n\t\t\t\t// Otherwise, check if any of the variants that render based on the\n\t\t\t\t// shared value are active.\n\t\t\t\tstatements.push(js`if (${Array.from(variants)}.includes(${variantVariable})) return ${value};`)\n\t\t\t}\n\t\t}\n\n\t\treturn statements\n\t}\n}\n\nfunction groupVariantByValue(variant: string, value: SafeJS | boolean, category: ConditionGroup) {\n\tconst serializedValue = serializeJS(value)\n\tconst existing = category.get(serializedValue) ?? new Set()\n\tcategory.set(serializedValue, existing.add(variant))\n}\n\n/**\n * For any SafeJS conditional values, create a named function argument for each\n * unique conditional value binding, reusing the same function argument for same\n * value bindings.\n */\nfunction makeGetConditionalValue(argumentNameByValueBinding: Map<string, SafeJS>) {\n\tconst usedArgumentNames = new Set<string>()\n\n\treturn (conditionValue: boolean | SafeJS) => {\n\t\tif (!isSafeJS(conditionValue)) return conditionValue\n\n\t\tconst key = serializeJS(conditionValue)\n\t\tconst argumentValue = argumentNameByValueBinding.get(key) ?? new SafeJS(createUnique(\"value\", usedArgumentNames))\n\n\t\targumentNameByValueBinding.set(key, argumentValue)\n\n\t\treturn argumentValue\n\t}\n}\n\nfunction generateHiddenClassName(variantId: string) {\n\t// This classname is also used in the SSG appear effect optimization script to query the animating elements on the\n\t// active breakpoint.\n\treturn `hidden-${hash(variantId)}`\n}\n\nfunction maybeAddConditionalClassName(\n\tvariantId: string,\n\tcondition: boolean | SafeJS,\n\tclassNames: Set<string>,\n\tclassNameExpressions: SafeJS.Set,\n) {\n\tif (condition === false) {\n\t\tconst className = generateHiddenClassName(variantId)\n\t\tclassNames.add(className)\n\t} else if (isSafeJS(condition)) {\n\t\tconst className = generateHiddenClassName(variantId)\n\t\tclassNameExpressions.add(js`!(${condition}) && ${className}`)\n\t}\n}\n", "import hash from \"@emotion/hash\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { isEmptyObject } from \"@framerjs/shared\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js, jst } from \"code-generation/js/js.ts\"\nimport type {\n\tAnySmartComponentNode,\n\tAnyWebPageNode,\n\tCanvasNode,\n\tCanvasTree,\n\tNodeID,\n\tScopeNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type { MaybeCanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport { isOverlayNode, isSmartComponentNode, isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isFixedOrRelativeOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { createVariableReference, isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { withControlProps } from \"document/models/CanvasTree/traits/WithControlProps.ts\"\nimport { hasLayoutTemplate } from \"document/models/CanvasTree/traits/WithLayoutTemplate.ts\"\nimport { hasScrollTarget } from \"document/models/CanvasTree/traits/WithScrollTarget.ts\"\nimport type { EffectScrollTarget } from \"document/models/CanvasTree/traits/utils/EffectScrollTarget.ts\"\nimport type { ResolvedCollectionItemSelector } from \"document/models/CanvasTree/traits/utils/ResolvedCollectionItemSelector.ts\"\nimport { isResolvedCollectionItemSelector } from \"document/models/CanvasTree/traits/utils/ResolvedCollectionItemSelector.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { isNull, isUndefined } from \"utils/typeChecks.ts\"\nimport { SafeJS } from \"../js/serializeJS.ts\"\nimport type { BindingCollector } from \"./BindingCollector.ts\"\nimport type { JSXDeclarationCollector } from \"./DeclarationCollector.ts\"\nimport type { ImportCollector } from \"./ImportCollector.ts\"\nimport type { VariableCollector } from \"./VariableCollector.ts\"\nimport {\n\ttype ScrollSectionPatternAnnotation,\n\tcreateScrollSectionPattern,\n\tgetAncestorRepeaterIds,\n\tscrollSectionPatternFromTree,\n} from \"./elementIdPatternForNode.ts\"\n\nexport class ElementIdCollector {\n\t#refs = new Map<NodeID, SafeJS>()\n\tconstructor(\n\t\tprivate readonly scope: ScopeNode,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly bindings: BindingCollector,\n\t\tprivate readonly declarations: JSXDeclarationCollector,\n\t\tprivate readonly imports: ImportCollector,\n\t\tprivate readonly variables: VariableCollector,\n\t\tprivate readonly tree: CanvasTree,\n\t) {}\n\n\t#layoutTemplateRefs: Set<NodeID> | null = null\n\n\t/**\n\t * When creating a ref for an element in a web page, first check if the\n\t * Layout Template applied to the containing Web Page is being provided with\n\t * a Scroll Section variable to this same element. If it is, we will have to\n\t * handle it differently.\n\t */\n\tprivate isLayoutTemplateRef(target: NodeID) {\n\t\t// If our cached refs set is null, we haven't yet checked if the Web\n\t\t// Page provides props to the Layout Template.\n\t\tif (isNull(this.#layoutTemplateRefs)) {\n\t\t\tthis.#layoutTemplateRefs = new Set()\n\n\t\t\tif (!hasLayoutTemplate(this.scope) || !withControlProps(this.scope)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst controls = this.componentLoader.componentForIdentifier(this.scope.layoutTemplateIdentifier)?.properties\n\t\t\tif (!controls) return false\n\t\t\tconst props = this.scope.getControlProps(controls)\n\n\t\t\tfor (const key in props) {\n\t\t\t\tconst value = props[key]\n\t\t\t\tif (isUndefined(value?.value) || isDynamicValue(value.value)) continue\n\t\t\t\tif (value.type !== ControlType.ScrollSectionRef) continue\n\t\t\t\tconst id = value.value.target\n\t\t\t\tif (isUndefined(id) || isDynamicValue(id)) continue\n\t\t\t\tthis.#layoutTemplateRefs.add(id)\n\t\t\t}\n\t\t}\n\n\t\t// Otherwise return true if this target is provided as a ref to the\n\t\t// Layout Template.\n\t\treturn this.#layoutTemplateRefs.has(target)\n\t}\n\n\tprivate getNodeInPrimary(node: CanvasNode | null) {\n\t\tif (!node) return undefined\n\t\tconst originalNode = node.originalid ? this.tree.get(node.originalid) : node\n\t\tif (!originalNode) return undefined\n\t\treturn originalNode\n\t}\n\n\tscrollTargetInfo({\n\t\ttarget,\n\t\tcollectionItem,\n\t}: Pick<EffectScrollTarget, \"target\" | \"collectionItem\">): { ref: SafeJS; offset?: number } | undefined {\n\t\tif (!target) return undefined\n\n\t\tif (isVariableReference(target)) return { ref: this.variables.create(target) }\n\n\t\tconst targetNode = this.tree.get(target)\n\t\tif (\n\t\t\t!targetNode ||\n\t\t\t!hasScrollTarget(targetNode) ||\n\t\t\t// Don't provide scroll target info for nodes that aren't in the\n\t\t\t// current webpage. This isn't possible via the editor, but was in\n\t\t\t// the past via copy/paste/duplication workflows.\n\t\t\tthis.tree.getScopeNodeFor(targetNode)?.id !== this.scope.id\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tconst nodeInPrimary = this.getNodeInPrimary(targetNode)\n\t\tif (!nodeInPrimary) return undefined\n\n\t\tconst ref = this.ref(nodeInPrimary, collectionItem)\n\t\tif (!ref) return undefined\n\n\t\treturn {\n\t\t\tref,\n\t\t\toffset: targetNode.scrollMarginTop,\n\t\t}\n\t}\n\n\tref(node: CanvasNode, collectionItem?: ResolvedCollectionItemSelector | VariableReference) {\n\t\tconst nodeInPrimary = this.getNodeInPrimary(node)\n\t\tif (!nodeInPrimary) return undefined\n\n\t\tconst existingRef = this.#refs.get(nodeInPrimary.id)\n\t\tif (existingRef) return existingRef\n\n\t\tconst ancestorRepeaterIds = getAncestorRepeaterIds(nodeInPrimary, this.tree)\n\t\tconst layoutTemplateRef = this.isLayoutTemplateRef(nodeInPrimary.id)\n\t\tif (layoutTemplateRef || collectionItem || (ancestorRepeaterIds && ancestorRepeaterIds.length > 0)) {\n\t\t\tconst id = this.id(nodeInPrimary, collectionItem)\n\t\t\tif (!id) return undefined\n\n\t\t\tconst useDynamicRefs = this.imports.addImport(\"framer\", {\n\t\t\t\texportSpecifier: layoutTemplateRef ? \"useSiteRefs\" : \"useDynamicRefs\",\n\t\t\t})\n\t\t\treturn SafeJS.fn(\n\t\t\t\tthis.declarations.component.dedupe(\"dynamicRef\", SafeJS.fn(js`${useDynamicRefs}<HTMLElement>`)),\n\t\t\t\tid,\n\t\t\t)\n\t\t}\n\n\t\tconst binding = this.bindings.create(\"ref\")\n\t\tconst React = this.imports.addImport(\"react\", {\n\t\t\texportSpecifier: \"*\",\n\t\t\timportBinding: \"React\",\n\t\t})\n\t\tconst initializer = js`const ${binding} = ${SafeJS.fn(js`${React}.useRef<HTMLElement>`, js`null`)}`\n\t\tthis.declarations.component.create(initializer)\n\t\tthis.#refs.set(nodeInPrimary.id, binding)\n\t\treturn binding\n\t}\n\n\tprivate getBaseId(node: CanvasNode, scopeNode: AnySmartComponentNode | AnyWebPageNode) {\n\t\tif (isWebPageNode(scopeNode)) {\n\t\t\tif (hasScrollTarget(node)) {\n\t\t\t\tconst useRouteElementIdArgs: SerializableValue[] = [node.id]\n\t\t\t\tif (scopeNode && scopeNode.id !== this.scope.id) useRouteElementIdArgs.push(scopeNode.id)\n\n\t\t\t\treturn this.declarations.component.dedupe(\n\t\t\t\t\t\"elementId\",\n\t\t\t\t\tSafeJS.fn(\n\t\t\t\t\t\tthis.imports.addImport(\"framer\", { exportSpecifier: \"useRouteElementId\" }),\n\t\t\t\t\t\t...useRouteElementIdArgs,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn hash(node.id)\n\t\t}\n\n\t\tif (isSmartComponentNode(scopeNode)) return jst`${Var.layoutId}-${hash(node.id)}`\n\n\t\treturn undefined\n\t}\n\n\tprivate getPortalAncestor(node: CanvasNode): MaybeCanvasNode {\n\t\tconst parent = this.tree.getParent(node.id)\n\t\tif (!parent) return undefined\n\n\t\tif (isFixedOrRelativeOverlay(node)) {\n\t\t\treturn this.tree.get(parent.getPrimaryId())\n\t\t}\n\n\t\tif (isOverlayNode(parent)) {\n\t\t\tconst grandParent = this.tree.getParent(parent.id)\n\t\t\treturn this.tree.get(grandParent?.getPrimaryId())\n\t\t}\n\t}\n\n\t/**\n\t * Overlays are rendered in portals, meaning that they don't properly\n\t * inherit custom cursors. To work around that, we provide information to\n\t * the dom to walk from the overlay to the react parent, rather than the DOM\n\t * parent.\n\t */\n\tportalId(node: CanvasNode) {\n\t\tconst portalAncestor = this.getPortalAncestor(node)\n\t\treturn portalAncestor ? this.id(portalAncestor) : undefined\n\t}\n\n\tid(node: CanvasNode, collectionItem?: ResolvedCollectionItemSelector | VariableReference) {\n\t\tconst nodeInPrimary = this.getNodeInPrimary(node)\n\t\tif (!nodeInPrimary) return undefined\n\n\t\tconst scopeNode = this.tree.getScopeNodeFor(nodeInPrimary)\n\t\tif (!isWebPageNode(scopeNode) && !isSmartComponentNode(scopeNode)) return undefined\n\n\t\t// Web Pages record a list of elements that are scroll sections. Allowing nodes to create\n\t\t// deep links without fully loading the Web Page.\n\t\tif (isWebPageNode(scopeNode) && hasScrollTarget(nodeInPrimary)) {\n\t\t\tconst pattern = createScrollSectionPattern(nodeInPrimary, this.tree, this.componentLoader)\n\t\t\tif (pattern) this.#annotations.set(nodeInPrimary.id, pattern)\n\t\t}\n\n\t\tconst baseId = this.getBaseId(nodeInPrimary, scopeNode)\n\t\tif (!baseId) return undefined\n\n\t\treturn scrollSectionPatternFromTree(nodeInPrimary, this.tree, this.componentLoader, part => {\n\t\t\tif (part.id === nodeInPrimary.id) return baseId\n\t\t\t// Either use the user-bound variable (in the case of effects\n\t\t\t// which decide which provider should provide the data), or\n\t\t\t// create a reference based on the key, and the top most data\n\t\t\t// repeater's id. This ensures that we never try to use a nested\n\t\t\t// repeater provider id.\n\t\t\tif (isVariableReference(collectionItem) && collectionItem.id === part.id) {\n\t\t\t\treturn this.variables.create(collectionItem)\n\t\t\t}\n\n\t\t\t// If a specific collection item is specified, always return that id,\n\t\t\t// even if we are not in a repeater context.\n\t\t\tif (isResolvedCollectionItemSelector(collectionItem) && collectionItem.key === part.id) {\n\t\t\t\treturn collectionItem.value\n\t\t\t}\n\n\t\t\t// If the element requires a provider variable, create a binding to\n\t\t\t// the value from the provider. The providerId is guaranteed to be\n\t\t\t// in scope by the calling function.\n\t\t\tif (part.type === \"slug\") return this.variables.create(createVariableReference(part.id, part.providerId))\n\n\t\t\t// Invalid.\n\t\t\treturn undefined\n\t\t})\n\t}\n\n\t#annotations: Map<NodeID, ScrollSectionPatternAnnotation[NodeID]> = new Map()\n\n\t/**\n\t * Generate an annotation that allows a link to be created to an element on this page without\n\t * fully loading the Web Page Node. e.g.\n\t *\n\t * @framerScrollSections {\n\t *   [id: NodeID]: {\n\t *      pattern: \":xxx-:yyy-:zzz\",\n\t *      name: \"section-about\",\n\t *      slugs: {\n\t *          xxx: { identifier: \"local-module:aaa/bbb:default\", provider: \"aaa\" }\n\t *          yyy: { identifier: \"local-module:ccc/qqq:default\", provider: \"bbb\" }\n\t *      }\n\t *   }\n\t * }\n\t */\n\tannotation(): string | undefined {\n\t\tconst value: ScrollSectionPatternAnnotation = Object.fromEntries(this.#annotations)\n\t\tif (isEmptyObject(value)) return undefined\n\t\treturn JSON.stringify(value)\n\t}\n}\n", "import type { ModuleExportIdentifierString, ModuleIdentifierString, ModuleType } from \"@framerjs/shared\"\nimport { isModuleExportIdentifier } from \"@framerjs/shared\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { ErrorNode, ErrorNodeReason, ErrorNodeType } from \"document/models/CanvasTree/nodes/ErrorNode.ts\"\nimport {\n\ttype WaitForLoadingComponentsError,\n\tisWaitForLoadingComponentsError,\n} from \"modules/waitForComponentLoaderToCatchUp.ts\"\nimport { isObject, isString } from \"utils/typeChecks.ts\"\n\ntype KnownError = WaitForLoadingComponentsError\nfunction isKnownError(error: unknown): error is KnownError {\n\tif (!(error instanceof Error)) return false\n\tif (isWaitForLoadingComponentsError(error)) return true\n\treturn false\n}\n\nexport interface CodeGenerationError {\n\treason: string\n\tnodeId: NodeID\n\tmoduleIdentifier?: ModuleExportIdentifierString\n}\n\nfunction getReason(error: unknown): string {\n\tif (isString(error)) return error\n\tif (error instanceof Error) return error.message\n\tif (isObject(error)) return JSON.stringify(error)\n\treturn \"Unknown error\"\n}\n\nexport class ErrorCollector {\n\tconstructor(\n\t\tprivate readonly scopeId: NodeID,\n\t\tprivate readonly sourceNodeId: NodeID,\n\t\tprivate readonly type: ModuleType,\n\t) {}\n\n\t#errors: CodeGenerationError[] = []\n\t/**\n\t * Record an error that occurred during code-generation to later process\n\t * into an ErrorNode in the ErrorListNode in bulk at the end of the\n\t * code-generation pass. Unlink other collectors, these errors are not added\n\t * to the module, but saved to the tree.\n\t */\n\trecord(\n\t\tnode: CanvasNode,\n\t\t/**\n\t\t * Currently this can be anything, an Error, a string, etc. as we aren't\n\t\t * showing these errors to customers at this time. In the future we may\n\t\t * want to use a specific enum to show specific messages. Currently this\n\t\t * will help framer developers debug issues.\n\t\t */\n\t\treason: unknown,\n\t\tmoduleIdentifier?: ModuleIdentifierString,\n\t): void {\n\t\tif (isKnownError(reason)) {\n\t\t\tthis.recordKnownError(node, reason)\n\t\t\treturn\n\t\t}\n\n\t\tthis.#errors.push({\n\t\t\tnodeId: node.id,\n\t\t\treason: getReason(reason),\n\t\t\tmoduleIdentifier: isModuleExportIdentifier(moduleIdentifier) ? moduleIdentifier : undefined,\n\t\t})\n\t}\n\n\tget errors(): ErrorNode[] {\n\t\treturn this.#errors.map(\n\t\t\terror =>\n\t\t\t\tnew ErrorNode({\n\t\t\t\t\t...error,\n\t\t\t\t\tsourceNodeId: this.sourceNodeId,\n\t\t\t\t\tsourceNodeModuleType: this.type,\n\t\t\t\t\tscopeId: this.scopeId,\n\t\t\t\t\ttype: ErrorNodeType.CodeGeneration,\n\t\t\t\t}),\n\t\t)\n\t}\n\n\tprivate recordKnownError(node: CanvasNode, error: KnownError) {\n\t\tif (isWaitForLoadingComponentsError(error)) {\n\t\t\t// WaitForLoadingComponentsError tracks a list of components that\n\t\t\t// are missing, and a list that have errors. Smart components that\n\t\t\t// have an error will be considered missing as well but we don't want\n\t\t\t// to track that duplicate error since it doesn't reflect the path\n\t\t\t// to recovery.\n\t\t\tconst componentLoaderErrors = new Set<ModuleExportIdentifierString>()\n\t\t\terror.error.forEach(identifier => {\n\t\t\t\tcomponentLoaderErrors.add(identifier)\n\t\t\t\tthis.record(node, ErrorNodeReason.CodeError, identifier)\n\t\t\t})\n\t\t\terror.missing.forEach(identifier => {\n\t\t\t\tif (componentLoaderErrors.has(identifier)) return\n\t\t\t\tthis.record(node, ErrorNodeReason.MissingModule, identifier)\n\t\t\t})\n\t\t}\n\t}\n}\n", "import type { AnyScopeNode, LoadedScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCanvasPageNode,\n\tisSmartComponentNode,\n\tisContentManagementNode,\n\tisLayoutTemplateNode,\n\tisAnalyticsScopeNode,\n\tisLocalizationGlossaryNode,\n\tisRoutesNode,\n\tisCustomCodeScopeNode,\n\tisWebPageNode,\n\tisVectorSetNode,\n\tisDesignPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\n\nexport function getScopeTypeForScope(scope: AnyScopeNode): ScopeType {\n\tif (isCanvasPageNode(scope)) return ScopeType.CanvasPage\n\tif (isWebPageNode(scope)) return ScopeType.WebPage\n\tif (isSmartComponentNode(scope)) return ScopeType.SmartComponent\n\tif (isContentManagementNode(scope)) return ScopeType.ContentManagement\n\tif (isLayoutTemplateNode(scope)) return ScopeType.LayoutTemplate\n\tif (isVectorSetNode(scope)) return ScopeType.VectorSet\n\tif (isAnalyticsScopeNode(scope)) return ScopeType.Analytics\n\tif (isLocalizationGlossaryNode(scope)) return ScopeType.LocalizationGlossary\n\tif (isDesignPageNode(scope)) return ScopeType.DesignPage\n\tif (isRoutesNode(scope)) return ScopeType.Routes\n\tif (isCustomCodeScopeNode(scope)) return ScopeType.CustomCode\n\tthrow Error(`Failed to return scope type, invalid scope: ${scope.__class}`)\n}\n\nexport interface BaseScopeStore {\n\tactive: LoadedScopeNode\n\tscopeType: ScopeType\n}\n", "import type { OpenURLOptions } from \"@framerjs/framer-runtime\"\nimport type { EventAction } from \"document/models/EventAction.ts\"\nimport { isEventAction } from \"document/models/EventAction.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { v4 as uuid } from \"uuid\"\nimport type { Link } from \"../traits/utils/Link.ts\"\nimport { HardCodedCodeIdentifier } from \"../traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport type { ActionControlValues } from \"./actions.ts\"\n\ntype OpenLinkURLOptions = Record<keyof OpenURLOptions, Link | undefined>\n\ntype OpenURLActionControls = ActionControlValues<OpenLinkURLOptions>\n\nexport interface OpenURLAction extends EventAction {\n\tcontrols: OpenURLActionControls\n}\n\nexport const openURLActionKeys: { [Key in keyof OpenURLOptions]: Key } = { url: \"url\" }\n\nexport function isOpenURLAction(value: unknown): value is OpenURLAction {\n\treturn isEventAction(value) && value.actionIdentifier === HardCodedCodeIdentifier.openURLAction\n}\n\nexport function createOpenURLAction(\n\tmodel?: Partial<OpenLinkURLOptions>,\n\tid?: string,\n\tmeta?: OpenURLAction[\"meta\"],\n): OpenURLAction {\n\tconst modelWithTypes: OpenURLActionControls = {\n\t\turl: {\n\t\t\ttype: ControlType.Link,\n\t\t\tvalue: model?.url,\n\t\t},\n\t}\n\n\treturn {\n\t\tidentifier: id ? id : uuid(),\n\t\tactionIdentifier: HardCodedCodeIdentifier.openURLAction,\n\t\tcontrols: modelWithTypes,\n\t\tmeta,\n\t}\n}\n\nexport function updatedOpenURLAction(\n\taction: OpenURLAction,\n\tcontrolOverrides: Partial<OpenURLActionControls>,\n): OpenURLAction {\n\tconst controls = {\n\t\t...action.controls,\n\t\t...controlOverrides,\n\t}\n\treturn { ...action, controls }\n}\n", "import type { EventAction } from \"document/models/EventAction.ts\"\nimport { HardCodedCodeIdentifier } from \"../traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport type { ActionControlValues } from \"./actions.ts\"\n\ninterface ResetVariablesAction extends EventAction {\n\tcontrols: ActionControlValues<Record<string, never>>\n}\n\nexport function isResetVariableValuesAction(value: EventAction): value is ResetVariablesAction {\n\treturn value.actionIdentifier === HardCodedCodeIdentifier.resetVariableValuesAction\n}\n", "import hash from \"@emotion/hash\"\nimport type { ComponentLoader, SetVariantType, VerifiedControlDescription } from \"@framerjs/framer-runtime\"\nimport { assert, ModuleType, assertNever } from \"@framerjs/shared\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { ValueTransformCollector } from \"code-generation/utils/valueTransformCollector/ValueTransformCollector.ts\"\nimport { getScopeTypeForScope } from \"document/base-engine/BaseScopeStore.ts\"\nimport type { ActionControlValues } from \"document/models/CanvasTree/actions/actions.ts\"\nimport { isNavigationAction } from \"document/models/CanvasTree/actions/navigationActions.ts\"\nimport { isOpenURLAction } from \"document/models/CanvasTree/actions/openURLActions.ts\"\nimport { isDismissOverlayAction, isShowOverlayAction } from \"document/models/CanvasTree/actions/overlayActions.ts\"\nimport { isLoadMoreAction } from \"document/models/CanvasTree/actions/paginationActions.ts\"\nimport { isResetVariableValuesAction } from \"document/models/CanvasTree/actions/resetVariablesActions.ts\"\nimport {\n\ttype SetVariableValueAction,\n\tisSetVariableValueAction,\n\tisValidVariableForSetVariableValueAction,\n} from \"document/models/CanvasTree/actions/setVariableValueActions.ts\"\nimport type { TriggerEventAction } from \"document/models/CanvasTree/actions/triggerEventActions.ts\"\nimport { isTriggerEventAction } from \"document/models/CanvasTree/actions/triggerEventActions.ts\"\nimport type { SetVariantAction } from \"document/models/CanvasTree/actions/variantActions.ts\"\nimport { isSetVariantAction, isSetVariantType } from \"document/models/CanvasTree/actions/variantActions.ts\"\nimport type { CanvasNode, CanvasTree, MaybeNodeID, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { getVariantForNode } from \"document/models/CanvasTree/nodes/utils/breakpointHelpers.ts\"\nimport { isCollectionRepeater, isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { nodeIsInOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { instantiateExistingVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { withCodeComponent } from \"document/models/CanvasTree/traits/WithCodeComponent.ts\"\nimport { hasPaginationEnabled } from \"document/models/CanvasTree/traits/WithCollectionOptions.ts\"\nimport { withEventActions } from \"document/models/CanvasTree/traits/WithEventActions.ts\"\nimport { appearKey, keyDownKey, withFrameEvents } from \"document/models/CanvasTree/traits/WithFrameEvents.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport {\n\tcontrolDescriptionFromVariable,\n\tisOptionalVariable,\n\twithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isFormInputEventKey } from \"document/models/CanvasTree/traits/forms/WithFormInputEvents.ts\"\nimport type { Link } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport { getLink, isLinkToURL, isLinkToWebPage } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport { HardCodedCodeIdentifier } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport type { EventAction, RecordedGamepadKey, RecordedKeyboardKey } from \"document/models/EventAction.ts\"\nimport { isRecordedGamepadKey } from \"document/models/EventAction.ts\"\nimport { getControlPropValueForCodeGeneration } from \"document/models/controlProps/getControlPropValuesForCodeGeneration.ts\"\nimport { getControlProp } from \"document/models/controlProps/getControlProps.ts\"\nimport { propsForLink } from \"library/modules/Link/propsForLink.tsx\"\nimport type { GestureHandlers } from \"library/modules/useVariantState.ts\"\nimport { join } from \"utils/join.ts\"\nimport { getNearestAncestorDataRepeater } from \"utils/repeaterUtils.ts\"\nimport { isString, isUndefined } from \"utils/typeChecks.ts\"\nimport type { SerializableRecord, SerializableValue } from \"../js/SerializableValue.ts\"\nimport { SafeJS, isSafeJS, serializeJS } from \"../js/serializeJS.ts\"\nimport type { AssetCollector } from \"./AssetCollector.ts\"\nimport type { BindingCollector } from \"./BindingCollector.ts\"\nimport type { FetchDataCollector } from \"./FetchDataCollector.ts\"\nimport type { FontCollector } from \"./FontCollector.ts\"\nimport type { ImportCollector } from \"./ImportCollector.ts\"\nimport type { LinkCollector } from \"./LinkCollector.ts\"\nimport { OverlayCollector } from \"./OverlayCollector.ts\"\nimport type { VariableCollector } from \"./VariableCollector.ts\"\n\ninterface AddHandlerArgs {\n\ttrigger: string\n\tnode: CanvasNode\n\tactionInfo: readonly EventAction[] | undefined\n}\n\nexport const PreviousTarget = Symbol(\"previous\")\n\nexport const PATH_VARIABLES_BINDING = js`pathVariables`\n\nconst NAVIGATE_BINDING = js`navigate`\nconst SET_VARIANT_BINDING = js`setVariant`\nconst REPEATER_LOAD_MORE_BINDING = js`loadMore`\n\nconst gestureStateForMotionHandler: Record<keyof GestureHandlers, { isHovered: boolean } | { isPressed: boolean }> = {\n\tonMouseEnter: { isHovered: true },\n\tonMouseLeave: { isHovered: false },\n\tonTapStart: { isPressed: true },\n\tonTap: { isPressed: false },\n\t// Since layers could be hidden in some variants, the element that fires\n\t// mousedown/mouseup might be different, as a result onTap won't fire and\n\t// the component will be stuck at the pressed state.\n\tonTapCancel: { isPressed: false },\n}\n\ninterface Options {\n\ttype: ModuleType\n}\n\nexport class EventCollector {\n\tconstructor(\n\t\tprivate readonly sourceNode: CanvasNode,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly tree: CanvasTree,\n\t\tprivate readonly variables: VariableCollector,\n\t\tprivate readonly bindings: BindingCollector,\n\t\tprivate readonly imports: ImportCollector,\n\t\tprivate readonly assets: AssetCollector,\n\t\tprivate readonly links: LinkCollector,\n\t\tprivate readonly fonts: FontCollector,\n\t\tprivate readonly fetches: FetchDataCollector,\n\t\tprivate readonly valueTransforms: ValueTransformCollector,\n\t\tprivate readonly overlays: OverlayCollector,\n\t\tprivate readonly options: Options = {\n\t\t\ttype: ModuleType.Canvas,\n\t\t},\n\t) {}\n\n\thandlers = new Map<string, SafeJS>()\n\tvariantOnAppearId = new Map<NodeID, SafeJS | undefined>()\n\tkeyBindHooks = new Set<SafeJS>()\n\tnavigationTargets = new Set<NodeID | typeof PreviousTarget>()\n\tneedsPathVariables = false\n\trouteHandlers = new Map<string, SafeJS>()\n\n\taddHandler({ trigger, node, actionInfo }: AddHandlerArgs): SafeJS | undefined {\n\t\tactionInfo?.forEach(eventAction => {\n\t\t\tif (!isTriggerEventAction(eventAction) || !eventAction.controls.id?.value) return\n\n\t\t\tthis.variables.create(instantiateExistingVariableReference(eventAction.controls.id.value, undefined))\n\t\t})\n\n\t\tconst isOnAppear = trigger === appearKey && withFrameEvents(node)\n\t\tconst isKeyBind = trigger === keyDownKey && withFrameEvents(node)\n\n\t\t// In the case where we have are creating a handler for an appear\n\t\t// interaction, but the handler is empty, if we haven't already recorded\n\t\t// an appear interaction for this variant (Smart components can only\n\t\t// have 1 appear interaction per variant), then we can immediately flag\n\t\t// that this variant should not have an appear interaction. This ensures\n\t\t// that a non-primary variant doesn't unintentionally inherit an appear\n\t\t// interaction from the primary variant. If we are collecting events for\n\t\t// a prototype, or we cannot find the replica root for a node in a Smart\n\t\t// Component Variant or a Webpage Breakpoint, fallback to the node\n\t\t// provided as the primary variant.\n\t\tconst variant = getVariantForNode(this.tree, node.id) ?? this.sourceNode\n\t\tconst isEmptyHandler = !actionInfo || actionInfo.length === 0\n\t\tif (isOnAppear && isEmptyHandler) {\n\t\t\tif (!this.variantOnAppearId.has(variant.id)) {\n\t\t\t\tthis.variantOnAppearId.set(variant.id, js`undefined`)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif (isEmptyHandler) return undefined\n\n\t\t// Each EventAction for a keyDown trigger can be triggered individually\n\t\t// by the appropriate key or gamepad action, unlike other events, which\n\t\t// use a single trigger to execute all of the events grouped in the\n\t\t// trigger, so we have to handle them differently.\n\t\tconst result = isKeyBind\n\t\t\t? this.createKeydownEvents(node, actionInfo, this.imports)\n\t\t\t: this.createCombinedEvents(node, actionInfo, trigger)\n\n\t\t// If no handler is created because the actionInfo is invalid, set the\n\t\t// onAppearId to undefined. This ensures that an onAppearId isn't set to\n\t\t// an identifier that we won't serialize to the generated code.\n\t\tif (isOnAppear) {\n\t\t\tif (result && !this.variantOnAppearId.has(variant.id)) {\n\t\t\t\tthis.variantOnAppearId.set(variant.id, result)\n\t\t\t}\n\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (isKeyBind || !result) return undefined\n\t\treturn result\n\t}\n\n\teventHandlersForNode(node: CanvasNode) {\n\t\tif (!withEventActions(node) || withCodeComponent(node)) return\n\n\t\tconst actions = node.getActions(this.componentLoader)\n\t\tconst handlers: Record<string, SafeJS | undefined> = {}\n\t\tfor (const key in actions) {\n\t\t\thandlers[key] = this.addHandler({\n\t\t\t\tnode,\n\t\t\t\ttrigger: key,\n\t\t\t\tactionInfo: actions[key],\n\t\t\t})\n\t\t}\n\n\t\tif (this.options.type !== ModuleType.Canvas || !isVariant(node)) return handlers\n\n\t\treturn handlers\n\t}\n\n\tprivate transformAction(trigger: string, action: EventAction, groups: Groups): (handler: SafeJS) => SafeJS {\n\t\treturn (handler: SafeJS) => {\n\t\t\tif (!isFormInputEventKey(trigger) || isUndefined(action.meta?.inputValue)) return handler\n\t\t\tconst valueBinding = js`inputValue`\n\n\t\t\tgroups.bindings.add(js`const ${valueBinding} = args[0]?.target?.value?.trim()`)\n\n\t\t\tswitch (action.meta.inputValue) {\n\t\t\t\tcase \"empty\":\n\t\t\t\t\treturn js`if (!${valueBinding}) { ${handler} }`\n\t\t\t\tcase \"set\":\n\t\t\t\t\treturn js`if (${valueBinding}?.length > 0 ) { ${handler} }`\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(action.meta.inputValue, \"All inputValue values should be handled\")\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getRepeaterIdForNode(node: CanvasNode): MaybeNodeID {\n\t\tconst lastRepeater = getNearestAncestorDataRepeater(node)\n\t\tif (!lastRepeater) return null\n\n\t\treturn isReplicaOrReplicaChild(node) ? lastRepeater.originalid : lastRepeater.id\n\t}\n\n\t/**\n\t * Create a callback that will execute all of the EventActions recorded for\n\t * the trigger.\n\t */\n\tprivate createCombinedEvents(node: CanvasNode, actionInfo: readonly EventAction[], trigger: string): SafeJS {\n\t\t/**\n\t\t * @FIXME when the Framer editor supports event reordering we should\n\t\t * only collect to a single list and not group actions.\n\t\t */\n\t\tconst groups = createGroups()\n\t\tconst eventArguments: Record<string, SafeJS> = {}\n\t\tlet overlayId = this.overlays.getOverlayIdForNode(node)\n\n\t\tif (trigger in gestureStateForMotionHandler && this.options.type === ModuleType.Canvas && isVariant(node)) {\n\t\t\tgroups.gestureHandlers.add(\n\t\t\t\tSafeJS.fn(\n\t\t\t\t\tVar.setGestureState,\n\t\t\t\t\tgestureStateForMotionHandler[trigger as keyof typeof gestureStateForMotionHandler],\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\n\t\tfor (const action of actionInfo) {\n\t\t\tthis.extractActionsToGroups(\n\t\t\t\tnode,\n\t\t\t\taction,\n\t\t\t\tgroups,\n\t\t\t\teventArguments,\n\t\t\t\ttrigger,\n\t\t\t\tthis.transformAction(trigger, action, groups),\n\t\t\t)\n\t\t\t// Break as soon as a navigation action is encountered, preventing\n\t\t\t// future actions from being executed when the screen has changed.\n\t\t\tif (groups.navigationActions.size > 0) break\n\n\t\t\tif (isShowOverlayAction(action) && !nodeIsInOverlay(node)) {\n\t\t\t\tif (!overlayId) overlayId = action.controls.overlay.value\n\t\t\t}\n\t\t}\n\n\t\tif (groupOrder.every(key => groups[key].size === 0)) {\n\t\t\treturn js`undefined`\n\t\t}\n\n\t\tif (groups.overlayActions.size > 0 && overlayId) {\n\t\t\tconst overlayBinding = this.overlays.bindingsByOverlayId.get(overlayId)\n\n\t\t\tif (overlayBinding) {\n\t\t\t\teventArguments[OverlayCollector.OverlayBinding.toString()] = overlayBinding\n\t\t\t}\n\t\t}\n\n\t\tconst repeaterId = this.getRepeaterIdForNode(node)\n\t\tif (groups.repeaterActions.size > 0 && repeaterId) {\n\t\t\tconst repeaterNode = this.tree.get(repeaterId)\n\t\t\tconst paginationEnabled = isCollectionRepeater(repeaterNode) && hasPaginationEnabled(repeaterNode)\n\t\t\tconst loadMoreBinding = paginationEnabled ? this.bindings.createWithNode(\"loadMore\", repeaterNode) : undefined\n\n\t\t\tif (loadMoreBinding) {\n\t\t\t\teventArguments[REPEATER_LOAD_MORE_BINDING.toString()] = loadMoreBinding\n\t\t\t}\n\t\t}\n\n\t\tconst eventParameters = Object.keys(eventArguments)\n\t\tconst binding = this.createEventFromGroups(trigger, groups, eventParameters)\n\n\t\tif (eventParameters.length > 0) {\n\t\t\treturn SafeJS.fn(binding, eventArguments)\n\t\t}\n\n\t\treturn binding\n\t}\n\n\tprivate createEventFromGroups(trigger: string, groups: Groups, eventParameters: string[]): SafeJS {\n\t\tconst fn = createHandlerFromGroups(groups, eventParameters)\n\t\tconst identifier = `${trigger}${hash(serializeJS(fn))}`\n\t\tconst binding = new SafeJS(identifier)\n\t\tconst handler = js`const ${binding} = ${fn}`\n\n\t\tthis.handlers.set(identifier, handler)\n\n\t\treturn binding\n\t}\n\n\t/**\n\t * Create a callback for each EventAction that will be triggered by the\n\t * EventActions meta.key - either a gamepad event or a keyboard key down.\n\t */\n\tprivate createKeydownEvents(node: CanvasNode, actionInfo: readonly EventAction[], imports?: ImportCollector) {\n\t\tassert(this.options.type === ModuleType.Screen, \"Smart Components do not support keydown events\")\n\n\t\tfor (const action of actionInfo) {\n\t\t\tconst trigger = action.meta?.key\n\t\t\tif (isUndefined(trigger)) continue\n\n\t\t\tconst groups = createGroups()\n\n\t\t\t// We don't support arguments in KeydownEvents\n\t\t\tconst eventArguments = {}\n\n\t\t\tthis.extractActionsToGroups(\n\t\t\t\tnode,\n\t\t\t\taction,\n\t\t\t\tgroups,\n\t\t\t\teventArguments,\n\t\t\t\t\"onKeyDown\",\n\t\t\t\tthis.transformAction(\"onKeyDown\", action, groups),\n\t\t\t)\n\n\t\t\tif (Object.keys(groups).every(key => groups[key as keyof typeof groups].size === 0)) continue\n\n\t\t\tconst binding = this.createEventFromGroups(\"onKeyDown\", groups, [])\n\n\t\t\t// Keydown events are only available inside prototype screens which\n\t\t\t// don't have variants, so an ImportCollector should always be\n\t\t\t// available.\n\t\t\tassert(imports, \"An Import collector must be provided to add gamepad or hotkey bindings.\")\n\n\t\t\tif (isRecordedGamepadKey(trigger)) {\n\t\t\t\tthis.keyBindHooks.add(\n\t\t\t\t\tSafeJS.fn(imports.addImport(\"framer\", { exportSpecifier: \"useGamepad\" }), trigger.key, binding, {\n\t\t\t\t\t\tmapping: trigger.mapping,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tconst key = trigger.key\n\t\t\t\tconst modifiers = createUseShortcutModifiers(trigger)\n\t\t\t\tconst shortcut = modifiers.length ? modifiers.concat(key).join(\"+\") : key\n\t\t\t\tthis.keyBindHooks.add(\n\t\t\t\t\tSafeJS.fn(imports.addImport(\"framer\", { exportSpecifier: \"useHotkey\" }), shortcut, binding),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate extractActionsToGroups(\n\t\tnode: CanvasNode,\n\t\taction: EventAction,\n\t\tgroups: Groups,\n\t\teventArguments: Record<string, SafeJS>,\n\t\ttrigger: string,\n\t\ttransform: (value: SafeJS) => SafeJS,\n\t) {\n\t\tif (isSetVariantAction(action)) {\n\t\t\tif (this.options.type !== ModuleType.Canvas) return\n\t\t\t// Unlike most events, a single input event, e.g. onBlur, can trigger multiple\n\t\t\t// setVariantActions to different variants.\n\t\t\tif (!isFormInputEventKey(trigger) && groups.setVariantActions.size > 0) return\n\t\t\tconst newAction = extractSetVariantAction(this.imports, action, trigger)\n\t\t\tif (newAction) groups.setVariantActions.add(transform(newAction))\n\t\t} else if (isTriggerEventAction(action)) {\n\t\t\tif (this.options.type !== ModuleType.Canvas) return\n\t\t\tconst newAction = extractTriggerEventAction(action)\n\t\t\tif (newAction) groups.eventActions.add(transform(newAction))\n\t\t} else if (isNavigationAction(action)) {\n\t\t\tif (this.options.type !== ModuleType.Screen) return\n\t\t\tif (groups.navigationActions.size > 0) return\n\t\t\tconst newAction = this.createNavigateAction(\n\t\t\t\taction.controls.type.value,\n\t\t\t\taction.controls.target.value,\n\t\t\t\taction.meta?.delay,\n\t\t\t\taction.controls,\n\t\t\t)\n\t\t\tif (newAction) groups.navigationActions.add(transform(newAction))\n\t\t} else if (action.actionIdentifier === HardCodedCodeIdentifier.consoleLogAction) {\n\t\t\tif (this.options.type !== ModuleType.Screen) return\n\t\t\tconst newAction = extractConsoleLogAction(action)\n\t\t\tif (newAction) groups.otherActions.add(transform(newAction))\n\t\t} else if (action.actionIdentifier === HardCodedCodeIdentifier.setLocaleAction) {\n\t\t\tconst localeId = action.controls.localeId?.value\n\t\t\tif (!isString(localeId)) return\n\t\t\tgroups.otherActions.add(transform(SafeJS.fn(Var.setLocale, localeId)))\n\t\t} else if (isSetVariableValueAction(action)) {\n\t\t\tconst newAction = this.createSetVariableValueAction(node, action, eventArguments)\n\t\t\tif (newAction) groups.otherActions.add(transform(newAction))\n\t\t} else if (isResetVariableValuesAction(action)) {\n\t\t\tconst newAction = this.createResetVariablesAction(node)\n\t\t\tif (newAction) groups.otherActions.add(transform(newAction))\n\t\t} else if (isOpenURLAction(action)) {\n\t\t\t// Old openURLActions can have a string value. Coerce those to a\n\t\t\t// Link shape.\n\t\t\tconst link = getLink(action.controls.url.value)\n\t\t\tif (isUndefined(link) || isDynamicValue(link)) return\n\t\t\tif (isLinkToWebPage(link)) {\n\t\t\t\tconst newAction = this.createOpenPageAction(link.webPageId, link.hash, action.meta?.delay)\n\t\t\t\tif (newAction) groups.navigationActions.add(transform(newAction))\n\t\t\t} else {\n\t\t\t\tconst newAction = extractOpenURLAction(action, link)\n\t\t\t\tif (newAction) groups.otherActions.add(transform(newAction))\n\t\t\t}\n\t\t} else if (!nodeIsInOverlay(node) && isShowOverlayAction(action)) {\n\t\t\t// Fixed position overlays are not valid in Smart Components.\n\t\t\tif (\n\t\t\t\taction.actionIdentifier === HardCodedCodeIdentifier.showOverlayAction &&\n\t\t\t\tthis.options.type === ModuleType.Canvas\n\t\t\t) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst overlayId = action.controls.overlay.value\n\t\t\tconst newAction = this.overlays.addOverlayTrigger(overlayId, node.id)\n\t\t\tif (newAction) groups.overlayActions.add(transform(newAction))\n\t\t} else if (isDismissOverlayAction(action)) {\n\t\t\tif (!this.overlays.hasAncestorOverlayBinding(node)) return\n\t\t\t// If the overlay ancestor exists, we can always create a dismiss\n\t\t\t// action.\n\t\t\tgroups.overlayActions.add(transform(this.createDismissOverlayAction(action.meta?.delay)))\n\t\t} else if (isLoadMoreAction(action)) {\n\t\t\tconst repeaterId = this.getRepeaterIdForNode(node)\n\t\t\tconst repeaterNode = this.tree.get(repeaterId)\n\t\t\tif (!isCollectionRepeater(repeaterNode)) return\n\t\t\tgroups.repeaterActions.add(SafeJS.fn(REPEATER_LOAD_MORE_BINDING))\n\t\t}\n\t}\n\n\tprivate createDismissOverlayAction(delay?: number): SafeJS {\n\t\treturn optionallyDelay(SafeJS.fn(OverlayCollector.overlayMethod(OverlayCollector.OverlayBinding, \"hide\")), delay)\n\t}\n\n\tprivate createOpenPageAction(\n\t\ttargetId: NodeID,\n\t\telementId: NodeID | undefined | null,\n\t\tdelay?: number,\n\t): SafeJS | undefined {\n\t\tconst targetNode = this.getNavigationTarget(targetId)\n\t\tif (!targetNode) return\n\n\t\t// FIXME: This action doesn't support path variables.\n\t\tconst uuid = `${hash(targetId)}${elementId ? hash(elementId) : \"\"}`\n\t\tconst binding = new SafeJS(`openRoute${uuid}`)\n\t\tconst args: SerializableValue[] = [targetId, js`true`]\n\t\tif (elementId) {\n\t\t\targs.push(elementId)\n\t\t}\n\n\t\tthis.routeHandlers.set(\n\t\t\tuuid,\n\t\t\tjs`const ${binding} = ${SafeJS.fn(\n\t\t\t\tthis.imports.addImport(\"framer\", { exportSpecifier: \"useRouteHandler\" }),\n\t\t\t\t...args,\n\t\t\t)}`,\n\t\t)\n\n\t\tconst navigateExpression = SafeJS.fn(binding)\n\n\t\treturn js`return ${optionallyDelay(navigateExpression, delay)}`\n\t}\n\n\tprivate createNavigateAction(\n\t\ttype: \"previous\" | \"next\" | unknown,\n\t\ttargetId: NodeID,\n\t\tdelay?: number,\n\t\tcontrols?: ActionControlValues<any>,\n\t): SafeJS | undefined {\n\t\tif (type === \"previous\") {\n\t\t\tthis.navigationTargets.add(PreviousTarget)\n\t\t\treturn js`return ${optionallyDelay(SafeJS.fn(NAVIGATE_BINDING, \"previous\"), delay)}`\n\t\t}\n\n\t\tif (!targetId || !this.isValidNavigationTarget(targetId)) return\n\n\t\tconst options: SerializableRecord = {}\n\t\tfor (const controlKey in controls) {\n\t\t\tif (controlKey === \"target\") continue\n\t\t\tconst controlValue = controls[controlKey]\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: we know it exists.\n\t\t\toptions[controlKey] = controlValue!.value\n\t\t}\n\n\t\tthis.navigationTargets.add(targetId)\n\n\t\treturn js`return ${optionallyDelay(SafeJS.fn(NAVIGATE_BINDING, targetId, options), delay)}`\n\t}\n\n\tprivate createSetVariableValueAction(\n\t\tnode: CanvasNode,\n\t\taction: SetVariableValueAction,\n\t\teventArguments: Record<string, SafeJS>,\n\t): SafeJS | undefined {\n\t\tconst scopeNode = this.tree.getScopeNodeFor(node)\n\t\tif (!withVariables(scopeNode)) return\n\n\t\tconst variableId = action.controls.variableId.value\n\t\tconst variable = scopeNode.getVariable(variableId)\n\t\tif (!variable) return\n\n\t\tconst scopeType = getScopeTypeForScope(scopeNode)\n\n\t\tconst controlDescription = controlDescriptionFromVariable(this.tree, this.componentLoader, variable, scopeType)\n\t\tif (!controlDescription) return\n\n\t\tconst value = this.getControlValueForCodeGeneration(node, controlDescription, action.controls.value)\n\n\t\tconst setterBinding = this.variables.createSetter(variableId)\n\n\t\tif (isSafeJS(value)) {\n\t\t\t// Prefix with alphabetic characters because the hash could begin with a number\n\t\t\tconst parameterName = `arg${hash(serializeJS(value))}`\n\n\t\t\teventArguments[parameterName] = value\n\t\t\treturn SafeJS.optionalFn(setterBinding, new SafeJS(parameterName))\n\t\t}\n\n\t\treturn SafeJS.optionalFn(setterBinding, value === undefined ? js`undefined` : value)\n\t}\n\n\tprivate createResetVariablesAction(node: CanvasNode): SafeJS | undefined {\n\t\tconst scopeNode = this.tree.getScopeNodeFor(node)\n\t\tif (!withVariables(scopeNode)) return\n\n\t\tconst setterCalls: SafeJS[] = []\n\t\tconst scopeType = getScopeTypeForScope(scopeNode)\n\n\t\tfor (const variable of scopeNode.variables) {\n\t\t\tif (!isValidVariableForSetVariableValueAction(variable)) continue\n\n\t\t\tconst setterBinding = this.variables.createSetter(variable.id)\n\n\t\t\tlet value: SerializableValue | undefined\n\n\t\t\tif (isOptionalVariable(variable, scopeType)) {\n\t\t\t\tvalue = js`undefined`\n\t\t\t} else {\n\t\t\t\tconst controlDescription = controlDescriptionFromVariable(this.tree, this.componentLoader, variable, scopeType)\n\n\t\t\t\tif (!controlDescription) return\n\n\t\t\t\tconst rawControlProp = { type: controlDescription.type, value: variable.initialValue }\n\t\t\t\tvalue = this.getControlValueForCodeGeneration(node, controlDescription, rawControlProp)\n\t\t\t}\n\n\t\t\tsetterCalls.push(SafeJS.optionalFn(setterBinding, value === undefined ? js`undefined` : value))\n\t\t}\n\n\t\tif (setterCalls.length === 0) return\n\n\t\treturn js.joinLines(...setterCalls)\n\t}\n\n\tprivate getControlValueForCodeGeneration(\n\t\tnode: CanvasNode,\n\t\tcontrolDescription: VerifiedControlDescription,\n\t\trawControlProp: unknown,\n\t): SerializableValue | undefined {\n\t\tconst controlProp = getControlProp(controlDescription, rawControlProp)\n\t\tif (!controlProp) return\n\n\t\treturn getControlPropValueForCodeGeneration(node, controlDescription, controlProp, {\n\t\t\tcontext: {\n\t\t\t\timports: this.imports,\n\t\t\t\tassets: this.assets,\n\t\t\t\tlinks: this.links,\n\t\t\t\tfonts: this.fonts,\n\t\t\t\tfetches: this.fetches,\n\t\t\t\tvariables: this.variables,\n\t\t\t\tvalueTransforms: this.valueTransforms,\n\t\t\t},\n\t\t}) as SerializableValue | undefined\n\t}\n\n\tprivate getNavigationTarget(targetId: NodeID | null): CanvasNode | null {\n\t\tif (!targetId) return null\n\t\tconst targetNode = this.tree.getNode(targetId)\n\t\tif (!targetNode || !(this.tree.isGroundNode(targetNode) || isWebPageNode(targetNode))) {\n\t\t\treturn null\n\t\t}\n\t\treturn targetNode\n\t}\n\n\tprivate isValidNavigationTarget(targetId: NodeID): boolean {\n\t\treturn !!this.getNavigationTarget(targetId)\n\t}\n}\n\nfunction createGroups() {\n\treturn {\n\t\tbindings: new SafeJS.Set(),\n\t\tgestureHandlers: new SafeJS.Set(),\n\t\teventActions: new SafeJS.Set(),\n\t\tsetVariantActions: new SafeJS.Set(),\n\t\tnavigationActions: new SafeJS.Set(),\n\t\totherActions: new SafeJS.Set(),\n\t\toverlayActions: new SafeJS.Set(),\n\t\trepeaterActions: new SafeJS.Set(),\n\t} as const\n}\n\ntype Groups = ReturnType<typeof createGroups>\n\nconst groupOrder: (keyof Groups)[] = [\n\t\"bindings\",\n\t\"gestureHandlers\",\n\t\"eventActions\",\n\t\"setVariantActions\",\n\t\"otherActions\",\n\t\"overlayActions\",\n\t\"repeaterActions\",\n\t\"navigationActions\",\n]\n\nfunction createHandlerFromGroups(groups: Groups, eventParameters: string[]) {\n\tconst handlers: SafeJS[] = []\n\tfor (const key of groupOrder) {\n\t\tfor (const handler of groups[key]) handlers.push(handler)\n\t}\n\n\tconst definition = js.joinLines(js`activeVariantCallback(async (...args) => {`, ...handlers, js`})`)\n\tif (eventParameters.length > 0) {\n\t\tconst serializedParameters = new SafeJS(join.listFrom(eventParameters))\n\t\treturn js`({${serializedParameters}}) => ${definition}`\n\t}\n\n\treturn definition\n}\n\nfunction createUseShortcutModifiers(meta: RecordedKeyboardKey | RecordedGamepadKey | undefined): string[] {\n\tconst modifiers: string[] = []\n\tfor (const modifier in meta) {\n\t\tif (!meta[modifier as keyof typeof meta]) continue\n\n\t\tswitch (modifier) {\n\t\t\tcase \"altKey\":\n\t\t\t\tmodifiers.push(\"alt\")\n\t\t\t\tbreak\n\t\t\tcase \"ctrlKey\":\n\t\t\t\tmodifiers.push(\"ctrl\")\n\t\t\t\tbreak\n\t\t\tcase \"metaKey\":\n\t\t\t\tmodifiers.push(\"meta\")\n\t\t\t\tbreak\n\t\t\tcase \"shiftKey\":\n\t\t\t\tmodifiers.push(\"shift\")\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t}\n\t}\n\treturn modifiers\n}\n\nfunction createSetVariantAction(\n\timports: ImportCollector,\n\ttype: SetVariantType,\n\tvariantId?: string,\n\tpauseOffscreen?: boolean,\n): SafeJS | undefined {\n\tif (type === \"cycle\") {\n\t\treturn SafeJS.fn(\n\t\t\tSET_VARIANT_BINDING,\n\t\t\timports.addImport(\"framer\", { exportSpecifier: \"CycleVariantState\" }),\n\t\t\tpauseOffscreen,\n\t\t)\n\t}\n\tif (variantId) return SafeJS.fn(SET_VARIANT_BINDING, variantId, pauseOffscreen)\n}\n\nfunction extractSetVariantAction(\n\timports: ImportCollector,\n\taction: SetVariantAction,\n\ttrigger: string,\n): SafeJS | undefined {\n\tconst type = action.controls.type?.value\n\tconst variantId = action.controls.variantId?.value\n\tconst pauseOffscreen = action.controls.pauseOffscreen?.value\n\tif (!isSetVariantType(type)) return\n\n\tconst serializedHandler = createSetVariantAction(\n\t\timports,\n\t\ttype,\n\t\tvariantId,\n\t\ttrigger === \"onAppear\" ? pauseOffscreen : undefined,\n\t)\n\tif (!serializedHandler) return\n\n\treturn optionallyDelay(serializedHandler, action.meta?.delay)\n}\n\nfunction extractTriggerEventAction(action: TriggerEventAction): SafeJS | undefined {\n\tconst variableId = action.controls.id?.value\n\tif (!isString(variableId)) return\n\tconst eventName = new SafeJS(variableId)\n\n\treturn js.joinLines(\n\t\tjs`if (${eventName}) {${js.joinLines(\n\t\t\taction.meta?.delay && js`await delay(() => {}, ${action.meta?.delay * 1000});`,\n\t\t\tjs`const res = await ${eventName}(...args);`,\n\t\t\tjs`if (res === false) return false;`,\n\t\t)}}`,\n\t)\n}\n\n/**\n * Performs similar work to sandbox/actions/useOpenURL.  In future one of these\n * two files will no longer be required, depending on our approach. E.g. if we\n * decide to support Custom Actions in compiled code, we can remove this code\n * altogether.\n */\nfunction extractOpenURLAction(action: EventAction, link: Link): SafeJS | undefined {\n\tif (!isLinkToURL(link)) return\n\tconst { href, target = js`undefined`, rel } = propsForLink(link.url)\n\tif (!href) return\n\n\tconst args = [href, target ?? js`undefined`, rel ?? `noopener`]\n\n\t// When it is a link to an element, we want to open it with _self, so it\n\t// jumps the page\n\treturn optionallyDelay(SafeJS.fn(js`window.open`, ...args), action.meta?.delay)\n}\n\nfunction extractConsoleLogAction(action: EventAction): SafeJS | undefined {\n\tconst type = action.controls?.type?.value\n\tconst message = action.controls?.message?.value\n\tif (!isString(type)) return\n\n\tswitch (type) {\n\t\tcase \"event\":\n\t\t\t// Because our custom console is async, we need to persist the\n\t\t\t// event. Otherwise React will re-use the event object between\n\t\t\t// events. See https://reactjs.org/docs/events.html#event-pooling\n\t\t\t// for details.\n\t\t\treturn new SafeJS(\n\t\t\t\tjoin.lines(\n\t\t\t\t\t`if (args[0] && \"persist\" in args[0]) args[0].persist()`,\n\t\t\t\t\toptionallyDelay(js`console.log(...args)`, action.meta?.delay),\n\t\t\t\t),\n\t\t\t)\n\n\t\tcase \"message\":\n\t\t\tif (!isString(message)) return\n\t\t\treturn optionallyDelay(js`console.log(${message})`, action.meta?.delay)\n\t\tcase \"count\":\n\t\t\tif (!isString(message)) return\n\t\t\treturn optionallyDelay(js`console.count(${message})`, action.meta?.delay)\n\t}\n}\n\nfunction optionallyDelay(serializedHandler: SafeJS, delay: number | undefined) {\n\tif (!isUndefined(delay) && delay > 0) {\n\t\treturn js`await delay(() => ${serializedHandler}, ${delay * 1000})`\n\t}\n\n\treturn serializedHandler\n}\n", "import { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS, SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { FetchDataValue } from \"document/models/CanvasTree/traits/FetchDataValue.ts\"\nimport { isConfiguredFetchDataValue, patchFetchValue } from \"document/models/CanvasTree/traits/FetchDataValue.ts\"\nimport type { PreloadCollector } from \"../loader/PreloadCollector.ts\"\nimport type { AssetCollector } from \"./AssetCollector.ts\"\nimport type { BindingCollector } from \"./BindingCollector.ts\"\nimport type { LinkCollector } from \"./LinkCollector.ts\"\nimport type { VariableCollector } from \"./VariableCollector.ts\"\nimport { serializeFallbackValue, serializeFetchDataValue } from \"./serializeFetchData.ts\"\n\nexport class FetchDataCollector {\n\tprivate fetchesByNode: Map<NodeID, SerializableObject[]> = new Map()\n\tprivate resultBindingsByNode: Map<NodeID, SafeJS> = new Map()\n\n\tconstructor(\n\t\tprivate readonly bindings: BindingCollector,\n\t\tprivate readonly variables: VariableCollector,\n\t\tprivate readonly preload: PreloadCollector,\n\t\tprivate readonly assets: AssetCollector,\n\t\tprivate readonly links: LinkCollector,\n\t) {}\n\n\tcreateFetchBinding(node: CanvasNode, fetchValue: FetchDataValue) {\n\t\tconst safeFetchValue = patchFetchValue(fetchValue)\n\n\t\tif (!isConfiguredFetchDataValue(safeFetchValue)) {\n\t\t\treturn serializeFallbackValue(safeFetchValue.controlProp, this.variables, this.assets, this.links)\n\t\t}\n\n\t\tconst originalNodeId = node.getPrimaryId()\n\t\tconst binding = this.resultBindingsByNode.get(originalNodeId) ?? this.bindings.create(\"fetchResult\")\n\t\tthis.resultBindingsByNode.set(originalNodeId, binding)\n\n\t\tthis.preload.addFetch(node, safeFetchValue)\n\n\t\tconst fetches = this.fetchesByNode.get(node.id) ?? []\n\t\tfetches.push(serializeFetchDataValue(safeFetchValue, this.variables, this.assets, this.links))\n\n\t\tthis.fetchesByNode.set(node.id, fetches)\n\n\t\tconst fetchBinding = js`${binding}[${fetches.length - 1}]`\n\n\t\treturn fetchBinding\n\t}\n\n\tgetResultBinding(node: CanvasNode) {\n\t\treturn this.resultBindingsByNode.get(node.getPrimaryId())\n\t}\n\n\tgetFetchesForNode(node: CanvasNode) {\n\t\treturn this.fetchesByNode.get(node.id)\n\t}\n}\n", "import type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport { shouldSerializeOpenType } from \"document/models/CanvasTree/utils/openType.ts\"\nimport type { ReadonlyFont } from \"library/index.ts\"\nimport { fontStore } from \"library/render/fonts/fontStore.ts\"\nimport type { ComponentFont } from \"library/utils/addFonts.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport type { FontDeclarationCollector } from \"./DeclarationCollector.ts\"\n\nexport interface SerializableComponentFont extends Omit<ComponentFont, \"variationAxes\"> {\n\tvariationAxes?: ComponentFont[\"variationAxes\"] | SafeJS | undefined\n}\n\nexport class FontCollector {\n\tconstructor(private declarationCollector: FontDeclarationCollector) {}\n\n\tfontObjects = new Set<SerializableComponentFont>()\n\tfontReferences = new Map<string, SafeJS>()\n\treferencedComponentIdentifiers = new Set<string>()\n\n\tprivate fontObjectsBySelector = new Map<string, SerializableComponentFont[]>()\n\n\tprivate createDedupedVariationAxesBinding(font: ReadonlyFont) {\n\t\treturn font.variationAxes ? this.declarationCollector.dedupe(\"variationAxes\", [...font.variationAxes]) : undefined\n\t}\n\n\t/**\n\t * Collect a font with the given selector.\n\t */\n\taddFontObjectBySelector(selector: string, openType?: ComponentFont[\"openType\"]) {\n\t\tconst existingFonts = this.fontObjectsBySelector.get(selector)\n\t\tif (existingFonts) {\n\t\t\tif (!openType) return\n\n\t\t\tconst firstFont = existingFonts[0]\n\t\t\tif (!firstFont) return\n\n\t\t\t// When a Google font with OpenType features is used, we need the complete font file\n\t\t\t// rather than a subset. If we previously collected this font without OpenType features,\n\t\t\t// we should upgrade it to use the complete file by setting openType=true\n\t\t\tif (shouldSerializeOpenType(firstFont.source, openType) && !firstFont.openType) {\n\t\t\t\tfor (const font of existingFonts) {\n\t\t\t\t\tfont.openType = true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tconst font = fontStore.getFontBySelector(selector)\n\t\tif (!font || !font.file) return\n\n\t\tif (font.subsets) {\n\t\t\tconst fontObjectsForThisSubset: SerializableComponentFont[] = []\n\t\t\tthis.fontObjectsBySelector.set(selector, fontObjectsForThisSubset)\n\n\t\t\tfor (const subset of font.subsets) {\n\t\t\t\tconst fontObject: SerializableComponentFont = {\n\t\t\t\t\turl: subset.file,\n\t\t\t\t\tuiFamilyName: font.family.name,\n\t\t\t\t\tcssFamilyName: font.cssFamilyName,\n\t\t\t\t\tstyle: font.style,\n\t\t\t\t\tweight: !isUndefined(font.weight) ? String(font.weight) : undefined,\n\t\t\t\t\tsource: font.family.source,\n\t\t\t\t\tunicodeRange: subset.unicodeRange,\n\t\t\t\t\tvariationAxes: this.createDedupedVariationAxesBinding(font),\n\t\t\t\t\topenType: shouldSerializeOpenType(font.family.source, openType),\n\t\t\t\t}\n\n\t\t\t\tthis.fontObjects.add(fontObject)\n\t\t\t\tfontObjectsForThisSubset.push(fontObject)\n\t\t\t}\n\t\t} else {\n\t\t\tconst fontObject: SerializableComponentFont = {\n\t\t\t\turl: font.file,\n\t\t\t\tuiFamilyName: font.family.name,\n\t\t\t\tcssFamilyName: font.cssFamilyName,\n\t\t\t\tstyle: font.style,\n\t\t\t\tweight: !isUndefined(font.weight) ? String(font.weight) : undefined,\n\t\t\t\tsource: font.family.source,\n\t\t\t\tvariationAxes: this.createDedupedVariationAxesBinding(font),\n\t\t\t\topenType: shouldSerializeOpenType(font.family.source, openType),\n\t\t\t}\n\n\t\t\tthis.fontObjects.add(fontObject)\n\t\t\tthis.fontObjectsBySelector.set(selector, [fontObject])\n\t\t}\n\t}\n\n\t/**\n\t * Collect a reference to fonts used by the given component.\n\t *\n\t * @param fontReference When evaluated, should yield an array of ComponentFonts used by the component.\n\t */\n\taddFontReference({ componentIdentifier, fontReference }: { componentIdentifier: string; fontReference: SafeJS }) {\n\t\tthis.fontReferences.set(serializeJS(fontReference), fontReference)\n\t\tthis.referencedComponentIdentifiers.add(componentIdentifier)\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assertNever, isModuleExportIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { getKitSectionIdFromGeneratedSection } from \"app/ai/utils/kitSection.ts\"\nimport type { Section } from \"app/ai/workers/generateWebPage/schema.ts\"\nimport type { CanvasNode, CanvasTree, CodeComponentNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode, isRichTextNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasCustomizations, isCustomizable } from \"document/models/CanvasTree/traits/WithCustomizations.ts\"\nimport { withKitSectionSource } from \"document/models/CanvasTree/traits/WithKitSectionSource.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { vectorInfoForIdentifier } from \"utils/vectorSets.ts\"\n\nexport type KitSection = Omit<Section, \"action\" | \"collectionBindings\">\n\nfunction isCustomizableControlType(type: ControlType) {\n\treturn type === ControlType.String || type === ControlType.VectorSetItem\n}\n\n/**\n * When we walk the tree to serialize JSX, we collect an abbreviated version of the structure if the\n * tree has nodes that were created by wireframer. This allows subsequent wireframer sessions to\n * make informed/consistent choices without walking the tree again.\n *\n * This information is stored in memory, then written to the tree when the module is persisted, much\n * like Errors.\n */\nexport class KitSectionsStructureCollector {\n\t#structure: Map<NodeID, KitSection> = new Map()\n\n\tget structure() {\n\t\treturn Array.from(this.#structure.values())\n\t}\n\n\tconstructor(\n\t\tprivate readonly modulesStore: ModulesStore,\n\t\tprivate readonly tree: CanvasTree,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t) {}\n\n\taddSection(node: CanvasNode) {\n\t\tif (!isCustomizable(node) && !withKitSectionSource(node)) return\n\n\t\tconst sectionId = getKitSectionIdFromGeneratedSection(node)\n\t\tif (!sectionId) return\n\n\t\t// KITS @TODO: If we want to mix and match kit generations we might need more details here like category\n\t\t// and rules for instance to give the LLM more context.\n\t\tconst section: KitSection = {\n\t\t\t_id: sectionId,\n\t\t\t_layerId: node.id,\n\t\t\tcontent: [],\n\t\t}\n\n\t\t// We need to use the node id as the key because the section id is not unique across nodes. You can have\n\t\t// the same kit section generated multiple times in the same page.\n\t\tthis.#structure.set(node.id, section)\n\n\t\treturn node.id\n\t}\n\n\taddCustomizations(node: CanvasNode, sectionNodeId?: NodeID) {\n\t\tif (!isCustomizable(node) || !sectionNodeId) return\n\n\t\tconst section = this.#structure.get(sectionNodeId)\n\t\tif (!section) return\n\n\t\tif (isCodeComponentNode(node)) {\n\t\t\trecordPropertyControlFields(node, section, this.tree, this.componentLoader, this.modulesStore)\n\t\t}\n\n\t\tif (!hasCustomizations(node)) return\n\n\t\tfor (const customization of node.customizations) {\n\t\t\tif (isRichTextNode(node)) {\n\t\t\t\tsection.content.push({ field: customization.fieldPath, text: node.getTextContent() })\n\t\t\t} else if (isCodeComponentNode(node) && node.isVectorInstance) {\n\t\t\t\tif (!isModuleExportIdentifier(node.codeComponentIdentifier)) return\n\t\t\t\tconst vectorName = vectorInfoForIdentifier(\n\t\t\t\t\tparseModuleIdentifier(node.codeComponentIdentifier),\n\t\t\t\t\tthis.tree,\n\t\t\t\t\tthis.modulesStore,\n\t\t\t\t)?.name\n\n\t\t\t\tif (!isString(vectorName)) return\n\t\t\t\tsection.content.push({ field: customization.fieldPath, text: vectorName })\n\t\t\t}\n\t\t}\n\n\t\tthis.#structure.set(sectionNodeId, section)\n\t}\n}\n\nfunction recordPropertyControlFields(\n\tnode: CodeComponentNode,\n\tsection: KitSection,\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tmodulesStore: ModulesStore,\n) {\n\tconst properties = componentLoader.componentForIdentifier(node.codeComponentIdentifier)?.properties\n\tif (!properties) return\n\tconst controls = node.getControlProps(properties)\n\n\tfor (const key in controls) {\n\t\tconst control = controls[key]\n\t\tif (!control) continue\n\t\tconst { type, value } = control\n\t\tif (!isString(type) || !isCustomizableControlType(type)) continue\n\t\tconst title = properties[key]?.title ?? key\n\t\tif (!isString(value)) continue\n\n\t\tswitch (type) {\n\t\t\tcase ControlType.String:\n\t\t\t\tsection.content.push({ field: title, text: value })\n\t\t\t\tbreak\n\t\t\tcase ControlType.VectorSetItem: {\n\t\t\t\tif (!isModuleExportIdentifier(value)) continue\n\t\t\t\tconst vectorName = vectorInfoForIdentifier(parseModuleIdentifier(value), tree, modulesStore)?.name\n\t\t\t\tif (!isString(vectorName)) continue\n\t\t\t\tsection.content.push({ field: title, text: value })\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tassertNever(type, \"Unknown control type\")\n\t\t}\n\t}\n}\n", "import type { CollectorEntryNode } from \"code-generation/types.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isLayoutTemplateNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withLock } from \"document/models/CanvasTree/traits/WithLock.ts\"\n\ntype VariantId = NodeID\ntype ClassName = string\n\n/**\n * Record the className of elements that are position fixed in a breakpoint\n * variant to generate an annotation of selectors that can be consumed later.\n */\nexport class LayoutTemplateHitTargetAnnotationCollector {\n\t#map = new Map<VariantId, Set<ClassName>>()\n\n\tconstructor(private readonly scopeNode: CollectorEntryNode) {}\n\n\trecordClassName(node: CanvasNode, variantId: VariantId, className: ClassName) {\n\t\tif (!isLayoutTemplateNode(this.scopeNode) || node.parentid !== variantId) return\n\t\t// Nodes with that are unconditionally hidden in a variant, or locked shouldn't be\n\t\t// included in the annotation.\n\t\tif (node.visible === false || (withLock(node) && node.locked)) return\n\n\t\tconst key = variantId\n\t\tconst set = this.#map.get(key) ?? new Set()\n\t\tset.add(\".\" + className)\n\t\tthis.#map.set(key, set)\n\t}\n\n\tannotation() {\n\t\tif (!isLayoutTemplateNode(this.scopeNode) || this.#map.size === 0) return \"{}\"\n\n\t\tconst result: Record<VariantId, ClassName[]> = {}\n\t\tfor (const [key, set] of this.#map) {\n\t\t\tresult[key] = Array.from(set)\n\t\t}\n\n\t\treturn JSON.stringify(result)\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ModuleType } from \"@framerjs/shared\"\nimport { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { NodeID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport type { SubmoduleFilename, SubmoduleImport, SubmoduleName } from \"modules/submodules.ts\"\nimport { getSubmoduleFilename, getSubmoduleImport, getSubmoduleName } from \"modules/submodules.ts\"\nimport type { Submodules } from \"modules/types.ts\"\nimport { join } from \"utils/join.ts\"\n\nexport class GeneratedSubmodule {\n\treadonly submoduleFilename: SubmoduleFilename\n\treadonly submoduleImport: SubmoduleImport\n\n\treadonly bindings = new BindingCollector()\n\treadonly imports: ImportCollector\n\treadonly declarations = new FileDeclarationCollector(this.bindings)\n\n\tget estimatedSize() {\n\t\treturn this.declarations.declarationsByteSize\n\t}\n\n\tconstructor(\n\t\treadonly moduleType: ModuleType,\n\t\treadonly componentLoader: ComponentLoader,\n\t\treadonly modulesStore: ModulesStore,\n\t\treadonly submoduleName: SubmoduleName,\n\t\treadonly sourceCode?: string,\n\t) {\n\t\tthis.submoduleFilename = getSubmoduleFilename(this.submoduleName)\n\t\tthis.submoduleImport = getSubmoduleImport(this.submoduleFilename)\n\t\tthis.imports = new ImportCollector(this.moduleType, this.componentLoader, this.modulesStore, this.bindings)\n\t}\n\n\tserialize() {\n\t\tconst imports = join.linesFrom(this.imports.statements)\n\t\tconst declarations = this.declarations.list()\n\t\treturn join.sections(imports, this.sourceCode, ...declarations)\n\t}\n}\n\nexport class SubmoduleCollector {\n\tprivate readonly submodules = new Set<GeneratedSubmodule>()\n\n\tconstructor(\n\t\treadonly moduleType: ModuleType,\n\t\treadonly componentLoader: ComponentLoader,\n\t\treadonly modulesStore: ModulesStore,\n\t\treadonly componentSourceNodeId: NodeID,\n\t) {}\n\n\tcreate(sourceCode?: string) {\n\t\tconst name = getSubmoduleName(this.componentSourceNodeId, this.submodules.size)\n\t\tconst submodule = new GeneratedSubmodule(this.moduleType, this.componentLoader, this.modulesStore, name, sourceCode)\n\t\tthis.submodules.add(submodule)\n\t\treturn submodule\n\t}\n\n\tdelete(submodule: GeneratedSubmodule) {\n\t\tthis.submodules.delete(submodule)\n\t}\n\n\tserialize() {\n\t\tconst submodules: Submodules = new Map()\n\n\t\tfor (const submodule of this.submodules) {\n\t\t\tconst code = submodule.serialize()\n\t\t\tsubmodules.set(submodule.submoduleName, code)\n\t\t}\n\n\t\treturn submodules\n\t}\n}\n", "import type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport type { ValueTransformWithoutIdAndType } from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport { isBoolean, isNumber } from \"utils/typeChecks.ts\"\n\nexport function getNumberToStringOptionsArgument(\n\ttransform: Extract<ValueTransformWithoutIdAndType, { name: \"numberToString\" }>,\n): SerializableValue {\n\tconst {\n\t\tlocale,\n\t\tgrouping,\n\t\tnotation,\n\t\tcompactDisplay,\n\t\tstyle,\n\t\tcurrency,\n\t\tcurrencyDisplay,\n\t\tunit,\n\t\tunitDisplay,\n\t\tminimumFractionDigits,\n\t\tmaximumFractionDigits,\n\t\tminimumIntegerDigits,\n\t} = transform\n\n\tconst options: Record<string, SerializableValue | undefined> = { locale, notation, style }\n\tif (isBoolean(grouping)) options.useGrouping = grouping\n\tif (isNumber(minimumFractionDigits)) options.minimumFractionDigits = minimumFractionDigits\n\tif (isNumber(maximumFractionDigits)) options.maximumFractionDigits = maximumFractionDigits\n\tif (isNumber(minimumIntegerDigits)) options.minimumIntegerDigits = minimumIntegerDigits\n\tif (notation === \"compact\") options.compactDisplay = compactDisplay\n\n\tswitch (style) {\n\t\tcase \"currency\":\n\t\t\toptions.currency = currency\n\t\t\toptions.currencyDisplay = currencyDisplay\n\t\t\tbreak\n\t\tcase \"unit\":\n\t\t\toptions.unit = unit\n\t\t\toptions.unitDisplay = unitDisplay\n\t\t\tbreak\n\t}\n\n\treturn new SerializableObject(options)\n}\n\nexport const numberToString = js`(value, options = {}, activeLocale) => {\n    const fallbackLocale = \"en-US\";\n    const locale = options.locale || activeLocale || fallbackLocale;\n    const {\n        useGrouping,\n        notation,\n        compactDisplay,\n        style,\n        currency,\n        currencyDisplay,\n        unit,\n        unitDisplay,\n        minimumFractionDigits,\n        maximumFractionDigits,\n        minimumIntegerDigits,\n    } = options;\n    const formatOptions = {useGrouping, notation, compactDisplay, style, currency, currencyDisplay, unit, unitDisplay, minimumFractionDigits, maximumFractionDigits, minimumIntegerDigits};\n    const number = Number(value);\n    try {\n        return number.toLocaleString(locale, formatOptions);\n    } catch {\n        try {\n            return number.toLocaleString(fallbackLocale, formatOptions);\n        } catch {\n            return number.toLocaleString();\n        }\n    }\n};\n`\n", "import { assert, assertNever } from \"@framerjs/shared\"\nimport type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { ValueTransformWithoutIdAndType } from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { forEachVariableOfLink, isLink } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport { isNumber, isUndefined } from \"utils/typeChecks.ts\"\nimport type { LocalizedValueCollector } from \"../LocalizedValueCollector.ts\"\nimport type { VariableCollector } from \"../VariableCollector.ts\"\nimport type { ValueTransformCollector } from \"./ValueTransformCollector.ts\"\nimport { getNumberToStringOptionsArgument } from \"./functions/numberToString.ts\"\n\n/** Optional object containing all used variables. */\nfunction getVariableObjectArgument(\n\tvariableCollector: VariableCollector | undefined,\n\tvariableReferences: VariableReference[],\n): SafeJS | null {\n\tif (variableReferences.length === 0) return null\n\n\tassert(variableCollector)\n\tconst usedVariables: Set<string> = new Set()\n\n\tfor (const variableReference of variableReferences) {\n\t\tconst variable = variableCollector.create(variableReference)\n\t\tusedVariables.add(serializeJS(variable))\n\t}\n\n\tconst variableObject = `{${Array.from(usedVariables).join(\", \")}}`\n\treturn new SafeJS(variableObject)\n}\n\nexport function getValueTransformArguments(\n\ttransform: ValueTransformWithoutIdAndType,\n\tvalueTransformCollector: ValueTransformCollector,\n\tvariableCollector: VariableCollector | undefined,\n\tlocalizedValueCollector: LocalizedValueCollector | undefined,\n): SerializableValue[] {\n\tconst transformName = transform.name\n\n\tswitch (transformName) {\n\t\tcase \"contains\":\n\t\tcase \"containsAny\":\n\t\tcase \"containsAll\":\n\t\tcase \"endsWith\":\n\t\tcase \"equals\":\n\t\tcase \"startsWith\":\n\t\tcase \"greaterThan\":\n\t\tcase \"lessThan\":\n\t\tcase \"isBefore\":\n\t\tcase \"isAfter\":\n\t\tcase \"isIncludedIn\":\n\t\tcase \"toggleInList\":\n\t\t\tif (isVariableReference(transform.value)) {\n\t\t\t\tassert(variableCollector)\n\t\t\t\treturn [variableCollector.create(transform.value)]\n\t\t\t}\n\n\t\t\treturn [isUndefined(transform.value) ? js`undefined` : transform.value]\n\t\tcase \"prefix\":\n\t\tcase \"suffix\": {\n\t\t\tif (isVariableReference(transform.value)) {\n\t\t\t\tassert(variableCollector)\n\t\t\t\treturn [variableCollector.create(transform.value)]\n\t\t\t}\n\n\t\t\tconst defaultValue = isUndefined(transform.value) ? js`undefined` : transform.value\n\n\t\t\tif (transform.valueLocalized) {\n\t\t\t\tassert(localizedValueCollector, \"LocalizedValueCollector is required\")\n\t\t\t\treturn [\n\t\t\t\t\tlocalizedValueCollector.add(\n\t\t\t\t\t\tdefaultValue,\n\t\t\t\t\t\ttransform.valueLocalized,\n\t\t\t\t\t\tlocaleId => transform.valueLocalized?.[localeId]?.value,\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t}\n\n\t\t\treturn [defaultValue]\n\t\t}\n\t\tcase \"toDateString\":\n\t\t\treturn [valueTransformCollector.getActiveLocaleCode()]\n\t\tcase \"extractDateSegment\":\n\t\t\treturn [transform.segment]\n\t\tcase \"numberToString\":\n\t\t\treturn [getNumberToStringOptionsArgument(transform), valueTransformCollector.getActiveLocaleCode()]\n\t\tcase \"offsetAndLimitArray\":\n\t\t\treturn [transform.startOffset, isNumber(transform.limit) ? transform.limit : js`undefined`]\n\t\tcase \"isBetweenDates\": {\n\t\t\tconst args: SerializableValue[] = []\n\n\t\t\tif (isVariableReference(transform.start)) {\n\t\t\t\tassert(variableCollector)\n\t\t\t\targs.push(variableCollector.create(transform.start))\n\t\t\t} else {\n\t\t\t\targs.push(isUndefined(transform.start) ? js`undefined` : transform.start)\n\t\t\t}\n\n\t\t\tif (isVariableReference(transform.end)) {\n\t\t\t\tassert(variableCollector)\n\t\t\t\targs.push(variableCollector.create(transform.end))\n\t\t\t} else {\n\t\t\t\targs.push(isUndefined(transform.end) ? js`undefined` : transform.end)\n\t\t\t}\n\n\t\t\treturn args\n\t\t}\n\t\tcase \"convertFromEnum\":\n\t\tcase \"convertFromString\": {\n\t\t\tconst usedVariableReferences: VariableReference[] = []\n\n\t\t\tfunction checkForVariables(value: unknown) {\n\t\t\t\tif (isLink(value)) {\n\t\t\t\t\tforEachVariableOfLink(value, variable => checkForVariables(variable))\n\t\t\t\t}\n\n\t\t\t\tif (isVariableReference(value)) {\n\t\t\t\t\tusedVariableReferences.push(value)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcheckForVariables(transform.default)\n\n\t\t\tfor (const caseOption of transform.cases) {\n\t\t\t\tcheckForVariables(caseOption.to)\n\t\t\t}\n\n\t\t\tconst variableObject = getVariableObjectArgument(variableCollector, usedVariableReferences)\n\t\t\tconst activeLocale = variableCollector?.getLocale() ?? js`undefined`\n\n\t\t\treturn variableObject ? [activeLocale, variableObject] : [activeLocale]\n\t\t}\n\t\tcase \"convertFromBoolean\": {\n\t\t\tconst usedVariableReferences: VariableReference[] = []\n\n\t\t\tfunction checkForVariables(value: unknown) {\n\t\t\t\tif (isLink(value)) {\n\t\t\t\t\tforEachVariableOfLink(value, variable => checkForVariables(variable))\n\t\t\t\t}\n\n\t\t\t\tif (isVariableReference(value)) {\n\t\t\t\t\tusedVariableReferences.push(value)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcheckForVariables(transform.truthy)\n\t\t\tcheckForVariables(transform.falsy)\n\t\t\tcheckForVariables(transform.fallback?.value)\n\n\t\t\tconst activeLocale = variableCollector?.getLocale() ?? js`undefined`\n\t\t\tconst variableObject = getVariableObjectArgument(variableCollector, usedVariableReferences)\n\t\t\treturn variableObject ? [activeLocale, variableObject] : [activeLocale]\n\t\t}\n\t\tcase \"enumToDisplayName\":\n\t\t\tif (!valueTransformCollector.variables) return []\n\t\t\treturn [valueTransformCollector.variables.getLocale()]\n\t\tcase \"toString\":\n\t\tcase \"toBoolean\":\n\t\tcase \"toNumber\":\n\t\tcase \"isSet\":\n\t\tcase \"negate\":\n\t\tcase \"reverseArray\":\n\t\tcase \"toResponsiveImage\":\n\t\tcase \"toImageSrc\":\n\t\tcase \"jsonStringify\":\n\t\tcase \"htmlEscape\":\n\t\tcase \"htmlUnescape\":\n\t\tcase \"addImageAlt\":\n\t\tcase \"toZIndex\":\n\t\tcase \"toAxisOverflow\":\n\t\tcase \"toOverflowWithClipFallback\":\n\t\tcase \"numberToPixelString\":\n\t\tcase \"radiusForCorner\":\n\t\tcase \"percentageToCornerShape\":\n\t\tcase \"arrayToArray\":\n\t\tcase \"arrayLength\":\n\t\tcase \"isEven\":\n\t\tcase \"isOdd\":\n\t\tcase \"getGridColumnCSSValue\":\n\t\tcase \"getGridRowCSSValue\":\n\t\tcase \"getNumericColumnGap\":\n\t\t\treturn []\n\t\tdefault:\n\t\t\tassertNever(transformName, \"All value transforms should define their arguments\")\n\t}\n}\n", "import { js } from \"code-generation/js/js.ts\"\n\n/** Add alt tag to responsive image if image is defined. */\nexport const addImageAlt = js`(image, alt) => {\n\tif (!image || typeof image !== \"object\") {\n\t\treturn;\n\t};\n\treturn { ...image, alt };\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const arrayLength = js`(value) => {\n\treturn Array.isArray(value) ? value.length : 0\n}\n`\n", "import { assert } from \"@framerjs/shared\"\nimport { arrayIdKey } from \"code-generation/components/cms/dataIdKeys.ts\"\nimport type { SerializableRecord } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type {\n\tValueTransformArrayToArray,\n\tValueTransformWithoutIdAndType,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport { isInlineTransformVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isDefined } from \"utils/typeChecks.ts\"\n\nexport function createArrayToArray(transform: ValueTransformWithoutIdAndType<ValueTransformArrayToArray>): SafeJS {\n\tconst itemBinding = js`item`\n\n\tconst staticallyMappedItem: SerializableRecord = {\n\t\t[arrayIdKey]: js`${itemBinding}?.[${arrayIdKey}]`,\n\t}\n\n\tfor (const key in transform.mapping) {\n\t\tconst controlProp = transform.mapping[key]\n\t\tassert(isDefined(controlProp))\n\n\t\tif (isInlineTransformVariableReference(controlProp.value)) {\n\t\t\tstaticallyMappedItem[key] = js`${itemBinding}?.[${controlProp.value.id}]`\n\t\t\tcontinue\n\t\t}\n\n\t\t// We currently only support values of type InlineTransformVariableReference\n\t\tcontrolProp.value satisfies never\n\t}\n\n\treturn js`(value) => {\n      if (!Array.isArray(value)) return\n      return value.map((${itemBinding}) => (${staticallyMappedItem}))\n    }`\n}\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const containsAll = js`(a, b) => {\n\tif (!Array.isArray(a)) return false;\n\tif (b === undefined) return true;\n\tif (!Array.isArray(b)) return false;\n\tif (b.length === 0) return true;\n\n\tconst aSet = new Set(a);\n\tfor (const item of b) {\n\t\tif (!aSet.has(item)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const containsAny = js`(a, b) => {\n\tif (!Array.isArray(a)) return false;\n\tif (b === undefined) return true;\n\tif (!Array.isArray(b)) return false;\n\tif (b.length === 0) return true;\n\n\tconst aSet = new Set(a);\n\tfor (const item of b) {\n\t\tif (aSet.has(item)) return true;\n\t}\n\treturn false;\n};\n`\n", "import { assert } from \"@framerjs/shared\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport type { LocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type {\n\tConvertFromBooleanOutputType,\n\tConvertFromBooleanOutputValueType,\n\tValueTransformConvertFromBoolean,\n\tValueTransformWithoutIdAndType,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { forEachVariableOfLink, isLink } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport { getFallbackValue } from \"document/models/CanvasTree/traits/utils/codeComponentProps.ts\"\nimport {\n\tconvertFromBooleanFallbackOutputValue,\n\tisValidConvertFromBooleanOutputType,\n\tisValidConvertFromBooleanOutputValue,\n} from \"document/models/CanvasTree/traits/utils/valueTransformUtils.ts\"\nimport type { LocalizedValues } from \"document/models/LocalizedValue.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { join } from \"utils/join.ts\"\n\nfunction getFallbackFunctionBody(transform: ValueTransformWithoutIdAndType<ValueTransformConvertFromBoolean>) {\n\tconst fallbackValue = getFallbackValue(transform.outputType)\n\treturn serializeJS(js`return ${isSerializableValue(fallbackValue) ? fallbackValue : js`undefined`};`)\n}\n\nfunction getBooleanOutputValue(\n\tvalue: ConvertFromBooleanOutputValueType | VariableReference,\n\tlocalizedValues: LocalizedValues | undefined,\n\toutputType: ConvertFromBooleanOutputType,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector,\n\tlocalizedValueCollector: LocalizedValueCollector | undefined,\n\tlinkCollector: LinkCollector | undefined,\n) {\n\tif (outputType === ControlType.Link) {\n\t\tif (!linkCollector) return undefined\n\t\tif (!isLink(value) && !isVariableReference(value)) return undefined\n\t\treturn linkCollector.create(value)\n\t}\n\n\tif (isLink(value)) return undefined\n\n\tif (isVariableReference(value)) return variableCollector.create(value)\n\n\tif (isValidConvertFromBooleanOutputValue(outputType, value, outputControl)) {\n\t\tif (localizedValueCollector && localizedValues && outputType === ControlType.String) {\n\t\t\treturn localizedValueCollector.add(value, localizedValues, localeId => localizedValues?.[localeId]?.value)\n\t\t}\n\n\t\treturn value\n\t}\n\treturn convertFromBooleanFallbackOutputValue(outputType, outputControl)\n}\n\nfunction createConvertFromBooleanFunctionBody(\n\ttransform: ValueTransformWithoutIdAndType<ValueTransformConvertFromBoolean>,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector,\n\tlocalizedValueCollector: LocalizedValueCollector,\n\tlinkCollector: LinkCollector,\n): string | SafeJS {\n\tif (!isValidConvertFromBooleanOutputType(transform.outputType)) return getFallbackFunctionBody(transform)\n\n\tconst truthyOutput = getBooleanOutputValue(\n\t\ttransform.truthy,\n\t\ttransform.truthyLocalized,\n\t\ttransform.outputType,\n\t\toutputControl,\n\t\tvariableCollector,\n\t\tlocalizedValueCollector,\n\t\tlinkCollector,\n\t)\n\tconst falsyOutput = getBooleanOutputValue(\n\t\ttransform.falsy,\n\t\ttransform.falsyLocalized,\n\t\ttransform.outputType,\n\t\toutputControl,\n\t\tvariableCollector,\n\t\tlocalizedValueCollector,\n\t\tlinkCollector,\n\t)\n\n\tconst serializableTruthyOutput = truthyOutput === undefined ? js`undefined` : truthyOutput\n\tconst serializableFalsyOutput = falsyOutput === undefined ? js`undefined` : falsyOutput\n\n\tif (transform.fallback) {\n\t\tconst fallbackOutput = getBooleanOutputValue(\n\t\t\ttransform.fallback.value,\n\t\t\ttransform.fallback.valueLocalized,\n\t\t\ttransform.outputType,\n\t\t\toutputControl,\n\t\t\tvariableCollector,\n\t\t\tlocalizedValueCollector,\n\t\t\tlinkCollector,\n\t\t)\n\t\tconst serializableFallbackOutput = fallbackOutput === undefined ? js`undefined` : fallbackOutput\n\n\t\treturn join.lines(\n\t\t\tjs`switch (value) {`,\n\t\t\tjs`case true: return ${serializableTruthyOutput};`,\n\t\t\tjs`case false: return ${serializableFalsyOutput};`,\n\t\t\tjs`default: return ${serializableFallbackOutput};`,\n\t\t\tjs`}`,\n\t\t)\n\t}\n\n\treturn js`return value ? ${serializableTruthyOutput} : ${serializableFalsyOutput};`\n}\n\nexport function createConvertFromBoolean(\n\ttransform: ValueTransformWithoutIdAndType<ValueTransformConvertFromBoolean>,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector | undefined,\n\tlocalizedValueCollector: LocalizedValueCollector | undefined,\n\tlinkCollector: LinkCollector | undefined,\n): SafeJS {\n\tassert(variableCollector)\n\tassert(localizedValueCollector)\n\tassert(linkCollector)\n\n\tconst usedVariables: Set<string> = new Set()\n\n\tfunction checkForVariables(value: unknown) {\n\t\tif (isLink(value)) {\n\t\t\tforEachVariableOfLink(value, variable => checkForVariables(variable))\n\t\t}\n\n\t\tif (isVariableReference(value)) {\n\t\t\tassert(variableCollector)\n\t\t\tconst variable = variableCollector.create(value)\n\t\t\tusedVariables.add(serializeJS(variable))\n\t\t}\n\t}\n\n\tcheckForVariables(transform.truthy)\n\tcheckForVariables(transform.falsy)\n\tcheckForVariables(transform.fallback?.value)\n\n\tconst args = [js`value`, Var.activeLocale]\n\n\tif (usedVariables.size > 0) {\n\t\t// Optional second argument, an object containing all used variables\n\t\tconst variableObject = `{${Array.from(usedVariables).join(\", \")}}`\n\t\targs.push(new SafeJS(variableObject))\n\t}\n\n\treturn new SafeJS(\n\t\tjoin.lines(\n\t\t\tjs`(${new SafeJS(args.map(serializeJS).join(\", \"))}) => {`,\n\t\t\tnew SafeJS(\n\t\t\t\tcreateConvertFromBooleanFunctionBody(\n\t\t\t\t\ttransform,\n\t\t\t\t\toutputControl,\n\t\t\t\t\tvariableCollector,\n\t\t\t\t\tlocalizedValueCollector,\n\t\t\t\t\tlinkCollector,\n\t\t\t\t),\n\t\t\t),\n\t\t\tjs`}`,\n\t\t),\n\t)\n}\n", "import type { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport type { LocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type {\n\tConvertFromEnumOrStringOutputValueType,\n\tConvertFromEnumOutputType,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isLink } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport {\n\tconvertFromEnumOrStringFallbackOutputValue,\n\tisValidConvertFromEnumOrStringOutputValue,\n} from \"document/models/CanvasTree/traits/utils/valueTransformUtils.ts\"\nimport type { LocalizedValues } from \"document/models/LocalizedValue.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\n\nexport function getConvertFromEnumOrStringOutputValue(\n\tvalue: ConvertFromEnumOrStringOutputValueType | VariableReference,\n\tvalueLocalized: LocalizedValues | undefined,\n\toutputType: ConvertFromEnumOutputType,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector,\n\tlocalizedValueCollector: LocalizedValueCollector | undefined,\n\tlinkCollector: LinkCollector | undefined,\n) {\n\tif (outputType === ControlType.Link) {\n\t\tif (!linkCollector) return undefined\n\t\tif (!isLink(value) && !isVariableReference(value)) return undefined\n\t\treturn linkCollector.create(value)\n\t}\n\n\tif (isLink(value)) return undefined\n\n\tif (isVariableReference(value)) return variableCollector.create(value)\n\n\tif (isValidConvertFromEnumOrStringOutputValue(outputType, value, outputControl)) {\n\t\tif (localizedValueCollector && outputType === ControlType.String && isString(value) && valueLocalized) {\n\t\t\treturn localizedValueCollector.add(value, valueLocalized, localeId => valueLocalized?.[localeId]?.value)\n\t\t}\n\n\t\treturn value\n\t}\n\treturn convertFromEnumOrStringFallbackOutputValue(outputType, outputControl)\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport type { LocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type {\n\tValueTransformConvertFromEnum,\n\tValueTransformWithoutIdAndType,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { forEachVariableOfLink, isLink } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport { getFallbackValue } from \"document/models/CanvasTree/traits/utils/codeComponentProps.ts\"\nimport { isValidConvertFromEnumOutputType } from \"document/models/CanvasTree/traits/utils/valueTransformUtils.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { join } from \"utils/join.ts\"\nimport { getConvertFromEnumOrStringOutputValue } from \"./utils/getConvertFromEnumOrStringOutputValue.ts\"\n\nfunction getFallbackFunctionBody(transform: ValueTransformWithoutIdAndType<ValueTransformConvertFromEnum>) {\n\tconst fallbackValue = getFallbackValue(transform.outputType)\n\treturn serializeJS(js`return ${isSerializableValue(fallbackValue) ? fallbackValue : js`undefined`};`)\n}\n\nfunction createConvertFromEnumFunctionBody(\n\ttransform: ValueTransformWithoutIdAndType<ValueTransformConvertFromEnum>,\n\tinputControl: ControlDescription | undefined,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector,\n\tlocalizedValueCollector: LocalizedValueCollector,\n\tlinkCollector: LinkCollector,\n): string {\n\tif (inputControl?.type !== ControlType.Enum) return getFallbackFunctionBody(transform)\n\tif (!isValidConvertFromEnumOutputType(transform.outputType)) return getFallbackFunctionBody(transform)\n\n\tconst seenCases = new Set<string>()\n\tconst defaultValue = getConvertFromEnumOrStringOutputValue(\n\t\ttransform.default,\n\t\ttransform.defaultLocalized,\n\t\ttransform.outputType,\n\t\toutputControl,\n\t\tvariableCollector,\n\t\tlocalizedValueCollector,\n\t\tlinkCollector,\n\t)\n\n\treturn join.lines(\n\t\tjs`switch (value) {`,\n\t\t...transform.cases\n\t\t\t.filter(caseOption => {\n\t\t\t\tif (seenCases.has(caseOption.from)) return false\n\t\t\t\tif (!inputControl.options.includes(caseOption.from)) return false\n\t\t\t\tseenCases.add(caseOption.from)\n\t\t\t\treturn true\n\t\t\t})\n\t\t\t.map(caseOption => {\n\t\t\t\tconst output = getConvertFromEnumOrStringOutputValue(\n\t\t\t\t\tcaseOption.to,\n\t\t\t\t\tcaseOption.toLocalized,\n\t\t\t\t\ttransform.outputType,\n\t\t\t\t\toutputControl,\n\t\t\t\t\tvariableCollector,\n\t\t\t\t\tlocalizedValueCollector,\n\t\t\t\t\tlinkCollector,\n\t\t\t\t)\n\t\t\t\treturn js`case ${caseOption.from}: return ${output === undefined ? js`undefined` : output};`\n\t\t\t}),\n\t\tjs`default: return ${defaultValue === undefined ? js`undefined` : defaultValue};`,\n\t\tjs`}`,\n\t)\n}\n\nexport function createConvertFromEnum(\n\ttransform: ValueTransformWithoutIdAndType<ValueTransformConvertFromEnum>,\n\tinputControl: ControlDescription | undefined,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector | undefined,\n\tlocalizedValueCollector: LocalizedValueCollector | undefined,\n\tlinkCollector: LinkCollector | undefined,\n): SafeJS {\n\tassert(variableCollector)\n\tassert(localizedValueCollector)\n\tassert(linkCollector)\n\n\tconst usedVariables: Set<string> = new Set()\n\n\tfunction checkForVariables(value: unknown) {\n\t\tif (isLink(value)) {\n\t\t\tforEachVariableOfLink(value, variable => checkForVariables(variable))\n\t\t}\n\n\t\tif (isVariableReference(value)) {\n\t\t\tassert(variableCollector)\n\t\t\tconst variable = variableCollector.create(value)\n\t\t\tusedVariables.add(serializeJS(variable))\n\t\t}\n\t}\n\n\ttransform.cases.forEach(caseOption => {\n\t\tcheckForVariables(caseOption.to)\n\t})\n\tcheckForVariables(transform.default)\n\n\tconst args = [js`value`, Var.activeLocale]\n\n\tif (usedVariables.size > 0) {\n\t\t// Optional second argument, an object containing all used variables\n\t\tconst variableObject = `{${Array.from(usedVariables).join(\", \")}}`\n\t\targs.push(new SafeJS(variableObject))\n\t}\n\n\treturn new SafeJS(\n\t\tjoin.lines(\n\t\t\tjs`(${new SafeJS(args.map(serializeJS).join(\", \"))}) => {`,\n\t\t\tnew SafeJS(\n\t\t\t\tcreateConvertFromEnumFunctionBody(\n\t\t\t\t\ttransform,\n\t\t\t\t\tinputControl,\n\t\t\t\t\toutputControl,\n\t\t\t\t\tvariableCollector,\n\t\t\t\t\tlocalizedValueCollector,\n\t\t\t\t\tlinkCollector,\n\t\t\t\t),\n\t\t\t),\n\t\t\tjs`}`,\n\t\t),\n\t)\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport type { LocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type {\n\tValueTransformConvertFromString,\n\tValueTransformWithoutIdAndType,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { forEachVariableOfLink, isLink } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport { getFallbackValue } from \"document/models/CanvasTree/traits/utils/codeComponentProps.ts\"\nimport { isValidConvertFromStringOutputType } from \"document/models/CanvasTree/traits/utils/valueTransformUtils.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { join } from \"utils/join.ts\"\nimport { getConvertFromEnumOrStringOutputValue } from \"./utils/getConvertFromEnumOrStringOutputValue.ts\"\n\nfunction getFallbackFunctionBody(transform: ValueTransformWithoutIdAndType<ValueTransformConvertFromString>) {\n\tconst fallbackValue = getFallbackValue(transform.outputType)\n\treturn serializeJS(js`return ${isSerializableValue(fallbackValue) ? fallbackValue : js`undefined`};`)\n}\n\nfunction createConvertFromStringFunctionBody(\n\ttransform: ValueTransformWithoutIdAndType<ValueTransformConvertFromString>,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector,\n\tlocalizedValueCollector: LocalizedValueCollector,\n\tlinkCollector: LinkCollector,\n): string {\n\tif (!isValidConvertFromStringOutputType(transform.outputType)) return getFallbackFunctionBody(transform)\n\n\tconst seenCases = new Set<string>()\n\tconst defaultValue = getConvertFromEnumOrStringOutputValue(\n\t\ttransform.default,\n\t\ttransform.defaultLocalized,\n\t\ttransform.outputType,\n\t\toutputControl,\n\t\tvariableCollector,\n\t\tlocalizedValueCollector,\n\t\tlinkCollector,\n\t)\n\n\treturn join.lines(\n\t\tjs`switch (typeof value === \"string\" ? value.toLowerCase() : value) {`,\n\t\t...transform.cases\n\t\t\t.filter(caseOption => {\n\t\t\t\tconst from = caseOption.from.toLowerCase()\n\t\t\t\tif (seenCases.has(from)) return false\n\t\t\t\tseenCases.add(from)\n\t\t\t\treturn true\n\t\t\t})\n\t\t\t.map(caseOption => {\n\t\t\t\tconst output = getConvertFromEnumOrStringOutputValue(\n\t\t\t\t\tcaseOption.to,\n\t\t\t\t\tcaseOption.toLocalized,\n\t\t\t\t\ttransform.outputType,\n\t\t\t\t\toutputControl,\n\t\t\t\t\tvariableCollector,\n\t\t\t\t\tlocalizedValueCollector,\n\t\t\t\t\tlinkCollector,\n\t\t\t\t)\n\t\t\t\treturn js`case ${caseOption.from.toLowerCase()}: return ${output === undefined ? js`undefined` : output};`\n\t\t\t}),\n\t\tjs`default: return ${defaultValue === undefined ? js`undefined` : defaultValue};`,\n\t\tjs`}`,\n\t)\n}\n\nexport function createConvertFromString(\n\ttransform: ValueTransformWithoutIdAndType<ValueTransformConvertFromString>,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector | undefined,\n\tlocalizedValueCollector: LocalizedValueCollector | undefined,\n\tlinkCollector: LinkCollector | undefined,\n): SafeJS {\n\tassert(variableCollector)\n\tassert(localizedValueCollector)\n\tassert(linkCollector)\n\n\tconst usedVariables: Set<string> = new Set()\n\n\tfunction checkForVariables(value: unknown) {\n\t\tif (isLink(value)) {\n\t\t\tforEachVariableOfLink(value, variable => checkForVariables(variable))\n\t\t}\n\n\t\tif (isVariableReference(value)) {\n\t\t\tassert(variableCollector)\n\t\t\tconst variable = variableCollector.create(value)\n\t\t\tusedVariables.add(serializeJS(variable))\n\t\t}\n\t}\n\n\ttransform.cases.forEach(caseOption => {\n\t\tcheckForVariables(caseOption.to)\n\t})\n\tcheckForVariables(transform.default)\n\n\tconst args = [js`value`, Var.activeLocale]\n\n\tif (usedVariables.size > 0) {\n\t\t// Optional second argument, an object containing all used variables\n\t\tconst variableObject = `{${Array.from(usedVariables).join(\", \")}}`\n\t\targs.push(new SafeJS(variableObject))\n\t}\n\n\treturn new SafeJS(\n\t\tjoin.lines(\n\t\t\tjs`(${new SafeJS(args.map(serializeJS).join(\", \"))}) => {`,\n\t\t\tnew SafeJS(\n\t\t\t\tcreateConvertFromStringFunctionBody(\n\t\t\t\t\ttransform,\n\t\t\t\t\toutputControl,\n\t\t\t\t\tvariableCollector,\n\t\t\t\t\tlocalizedValueCollector,\n\t\t\t\t\tlinkCollector,\n\t\t\t\t),\n\t\t\t),\n\t\t\tjs`}`,\n\t\t),\n\t)\n}\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const endsWith = js`(a, b) => {\n\treturn typeof a === \"string\" && typeof b === \"string\" && a.toLowerCase().endsWith(b.toLowerCase());\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const equals = js`(a, b) => {\n\treturn (typeof a === \"string\" && typeof b === \"string\") ? a.toLowerCase() === b.toLowerCase() : a === b;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const extractDateSegment = js`(value, segment = \"year\") => {\n\tif (typeof value !== \"string\") return;\n\tconst date = new Date(value);\n\tif (isNaN(date.getTime())) return;\n\tif (segment === \"year\") return date.getUTCFullYear();\n\tif (segment === \"month\") return date.getUTCMonth() + 1;\n\tif (segment === \"day\") return date.getUTCDate();\n\tif (segment === \"hour24\") return date.getUTCHours();\n\tif (segment === \"hour12\") {\n\t\tconst hour = date.getUTCHours();\n\t\treturn hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;\n\t}\n\tif (segment === \"minute\") return date.getUTCMinutes();\n};\n`\n", "import { js, jst } from \"code-generation/js/js.ts\"\n\nconst spanCount = js`spanCount`\nconst optionalColumnCount = js`optionalColumnCount`\n\nexport const getGridColumnCSSValue = js`(columnSpan, ${optionalColumnCount}) => {\n\tif (columnSpan === \"all\") return \"-1 / 1\";\n\tconst ${spanCount} = Number.isFinite(columnSpan) && columnSpan > 0 ? columnSpan : 1;\n\tif (Number.isFinite(${optionalColumnCount}) && ${spanCount} > ${optionalColumnCount}) {\n\t\treturn ${jst`span ${optionalColumnCount}`};\n\t}\n\treturn ${jst`span ${spanCount}`};\n};\n`\n", "import { js, jst } from \"code-generation/js/js.ts\"\n\nconst spanCount = js`spanCount`\n\nexport const getGridRowCSSValue = js`(rowSpan) => {\n\tconst ${spanCount} = Number.isFinite(rowSpan) && rowSpan > 0 ? rowSpan : 1;\n\treturn ${jst`span ${spanCount}`}\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const getNumericColumnGap = js`(gap) => {\n\tif (Number.isFinite(gap) && gap >= 0) return gap;\n\tif (typeof gap !== \"string\") return 0;\n\tconst firstSegment = gap.split(\" \")[0];\n\tconst parsedGap = parseFloat(firstSegment);\n\treturn Number.isFinite(parsedGap) && parsedGap >= 0 ? parsedGap : 0;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const greaterThan = js`(a, b) => {\n\treturn (typeof a === \"number\" && typeof b === \"number\") ? a > b : false;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const htmlEscape = js`(value) => {\n\tif (typeof value !== \"string\") return \"\";\n\treturn value.replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\").replaceAll('\"', \"&quot;\").replaceAll(\"'\", \"&#39;\");\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\n// inspired by https://github.com/SukkaW/fast-escape-html/blob/master/src/unescape.ts\nexport const htmlUnescape = js`(value) => {\n\tif (typeof value !== \"string\") return \"\";\n\tconst entities = /&(?:[gl]t|quot|#39|amp|#6[02]|#34|apos|#38);/gu;\n\tconst replacers = { \"&lt;\": \"<\", \"&gt;\": \">\", \"&quot;\": '\"', \"&#39;\": \"'\", \"&amp;\": \"&\", \"&#60;\": \"<\", \"&#62;\": \">\", \"&#34;\": '\"', \"&apos;\": \"'\", \"&#38;\": \"&\" };\n\treturn value.replace(entities, match => replacers[match]);\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const isAfter = js`(dateString, minDateString) => {\n\tif (typeof dateString !== \"string\" || typeof minDateString !== \"string\") return false;\n\n\tconst date = new Date(dateString);\n\tif (isNaN(date.getTime())) return false;\n\n\tconst minDate = new Date(minDateString);\n\tif (isNaN(minDate.getTime())) return false;\n\n\treturn date >= minDate;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const isBefore = js`(dateString, maxDateString) => {\n\tif (typeof dateString !== \"string\" || typeof maxDateString !== \"string\") return false;\n\n\tconst date = new Date(dateString);\n\tif (isNaN(date.getTime())) return false;\n\n\tconst maxDate = new Date(maxDateString);\n\tif (isNaN(maxDate.getTime())) return false;\n\n\treturn date <= maxDate;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const isBetweenDates = js`(value, start, end) => {\n\tif (typeof value !== \"string\" || typeof start !== \"string\" || typeof end !== \"string\") return false;\n\n\tconst date = new Date(value);\n\tif (isNaN(date.getTime())) return false;\n\n\tconst startDate = new Date(start);\n\tif (isNaN(startDate.getTime())) return false;\n\n\tconst endDate = new Date(end);\n\tif (isNaN(endDate.getTime())) return false;\n\n\treturn date >= startDate && date <= endDate;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const isEven = js`(value) => {\n\treturn typeof value === \"number\" && value % 2 === 0;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const isIncludedIn = js`(a, b) => {\n\treturn b.includes(a);\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const isOdd = js`(value) => {\n\treturn typeof value === \"number\" && value % 2 === 1;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const isSet = js`(value) => {\n\tif (Array.isArray(value)) return value.length > 0;\n\treturn value !== undefined && value !== null && value !== \"\";\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\n/**\n * Also encodes ETAGO-delimiters.\n * @see https://mathiasbynens.be/notes/etago\n */\nexport const jsonStringify = js`(value) => {\n\tconst result = JSON.stringify(value)\n\tif (typeof result === 'string') return result.replace(/<\\\\/(script|style)/gi, '<\\\\\\\\/$1')\n\treturn result\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const lessThan = js`(a, b) => {\n\treturn (typeof a === \"number\" && typeof b === \"number\") ? a < b : false;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const negate = js`(value) => {\n\treturn !value;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const numberToPixelString = js`(value) => {\n\tif (typeof value !== \"number\") return value;\n\tif (!Number.isFinite(value)) return undefined;\n\treturn Math.max(0, value) + \"px\";\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const offsetAndLimitArray = js`(value, offset, limit) => {\n\tif (!Array.isArray(value)) return []\n\tconst end = typeof limit === \"number\" ? offset + limit : undefined\n\treturn value.slice(offset, end);\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const percentageToCornerShape = js`(value) => {\n\tif (!Number.isFinite(value) || value <= 0) return 1;\n\tif (value >= 100) return 2;\n\treturn Math.round(value) / 100 + 1;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const prefix = js`(value, prefix) => {\n\tif (typeof value === \"string\" && typeof prefix === \"string\") {\n\t\treturn prefix + value;\n\t} else if (typeof value === \"string\") {\n\t\treturn value;\n\t} else if (typeof prefix === \"string\") {\n\t\treturn prefix;\n\t}\n\treturn \"\";\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const radiusForCorner = js`(value, cornerIndex) => {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return Math.max(0, value) + \"px\";\n\tif (typeof value !== \"string\" || typeof cornerIndex !== \"number\") return undefined;\n\tconst segments = value.split(\" \");\n\treturn segments[cornerIndex] || segments[cornerIndex - 2] || segments[0];\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const reverseArray = js`(value) => {\n\treturn Array.isArray(value) ? Array.from(value).reverse() : [];\n}\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const startsWith = js`(a, b) => {\n\treturn typeof a === \"string\" && typeof b === \"string\" && a.toLowerCase().startsWith(b.toLowerCase());\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const suffix = js`(value, suffix) => {\n\tif (typeof value === \"string\" && typeof suffix === \"string\") {\n\t\treturn value + suffix;\n\t} else if (typeof value === \"string\") {\n\t\treturn value;\n\t} else if (typeof suffix === \"string\") {\n\t\treturn suffix;\n\t}\n\treturn \"\";\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\n/**\n * toAxisOverflow is applied to both overflow-x and overflow-y to prevent situations where these\n * respective properties are set to the value that is incompatible with the primary overflow\n * property. We already try to prevent this in the UI, but that doesn't address dynamic values, and\n * this does.\n *\n * If both overflows are scrollable, or both values are not scrollable, they are compatible. Otherwise,\n * we strip the axis overflow.\n *\n * NOTE: It needs to be kept in sync with @link{compatibleOverflowCombinations},\n * @link{isOverflowVisuallyHidden} and @link{OverflowPanel}.\n *\n * NOTE: When the main overflow is undefined, it is considered to compute to visible. In case the\n * axis is undefined, returning value or undefined is the same.\n */\nexport const toAxisOverflow = js`(value, overflow) => {\n\tconst isNonScrollable = (o) => o === \"visible\" || o === \"clip\" || o === undefined\n\treturn isNonScrollable(value) === isNonScrollable(overflow) ? value : undefined\n}`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const toBoolean = js`(value) => {\n\treturn Boolean(value);\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport type {\n\tValueTransformToDateString,\n\tValueTransformWithoutIdAndType,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport {\n\tdateStyleConfig,\n\ttransformOptionsToDateStyleKey,\n} from \"document/models/CanvasTree/traits/utils/toDateStringTransformOptions.ts\"\nimport { join } from \"utils/join.ts\"\n\nconst valueArgument = js`value`\nconst activeLocaleArgument = js`activeLocale`\n\n// We add a try block because an invalid language code results in a crash\nexport function createToDateString(\n\ttransform: ValueTransformWithoutIdAndType<ValueTransformToDateString>,\n\tfileDeclarationCollector: FileDeclarationCollector,\n): SafeJS {\n\tconst sharedDateFormatter = fileDeclarationCollector.dedupe(\n\t\t\"sharedDateFormatter\",\n\t\tnew SafeJS(\n\t\t\tjoin.lines(\n\t\t\t\tjs`(value, formatOptions, locale) => {`,\n\t\t\t\tjs`  if (typeof value !== \"string\") return \"\";`,\n\t\t\t\tjs`  const date = new Date(value);`,\n\t\t\t\tjs`  if (isNaN(date.getTime())) return \"\";`,\n\t\t\t\tjs`  const fallbackLocale = \"en-US\";`,\n\t\t\t\tjs`  try {`,\n\t\t\t\tjs`      return date.toLocaleString(locale || fallbackLocale, formatOptions);`,\n\t\t\t\tjs`  } catch {`,\n\t\t\t\tjs`      return date.toLocaleString(fallbackLocale, formatOptions);`,\n\t\t\t\tjs`  }`,\n\t\t\t\tjs`};`,\n\t\t\t),\n\t\t),\n\t)\n\n\tconst dateStyleKey = transformOptionsToDateStyleKey(transform.display, transform.format, transform.dateStyle, false)\n\tconst applicableIntlOptions: Intl.DateTimeFormatOptions = {\n\t\t...dateStyleConfig[dateStyleKey].options,\n\t\ttimeZone: \"UTC\",\n\t}\n\n\tconst dateOptions = fileDeclarationCollector.dedupe(\"dateOptions\", new SafeJS(serializeJS(applicableIntlOptions)))\n\n\treturn new SafeJS(\n\t\tjoin.lines(\n\t\t\tjs`(${valueArgument}, ${activeLocaleArgument}) => {`,\n\t\t\tjs`return ${SafeJS.fn(sharedDateFormatter, valueArgument, dateOptions, transform.locale || activeLocaleArgument)};`,\n\t\t\tjs`};`,\n\t\t),\n\t)\n}\n", "import { js } from \"code-generation/js/js.ts\"\n\n/** Convert responsive images into src. */\nexport const toImageSrc = js`(value) => {\n\tif (typeof value === \"object\" && value !== null && typeof value.src === \"string\") {\n\t\treturn value.src;\n\t};\n\treturn typeof value === \"string\" ? value : undefined;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const toNumber = js`(value) => {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value !== \"string\") return 0;\n\tconst parsedNumber = parseFloat(value);\n\treturn (typeof parsedNumber === \"number\" && Number.isFinite(parsedNumber)) ? parsedNumber : 0;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\nimport { overflowClipFallbackCSSVariable } from \"library/render/utils/injectComponentCSSRules.ts\"\n\n/**\n * toOverflowWithClipFallback replaces \"clip\" values with \"var(--overflow-clip-fallback, clip)\"\n * to provide a fallback for browsers that don't support overflow: clip (like Safari 15).\n *\n * The CSS variable --overflow-clip-fallback is set to \"hidden\" via @supports when\n * overflow: clip is not supported.\n */\n\n// Build the var() string outside the template to avoid escaping\nconst clipFallbackValue = `var(${overflowClipFallbackCSSVariable}, clip)`\n\nexport const toOverflowWithClipFallback = js`(value) => {${js.joinLines(\n\tjs`if (value === \"clip\") return ${clipFallbackValue}`,\n\tjs`return value`,\n)}};`\n", "import { js } from \"code-generation/js/js.ts\"\n\n/** Convert image `src` into responsive image. */\nexport const toResponsiveImage = js`(value) => {\n\tif (typeof value === \"object\" && value !== null && typeof value.src === \"string\") {\n\t\treturn value\n\t}\n\treturn typeof value === \"string\" ? {src: value} : undefined;\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\nexport const toString = js`(value) => {\n\treturn typeof value === \"string\" ? value : String(value);\n};\n`\n", "import { js } from \"code-generation/js/js.ts\"\n\n/**\n * @TODO - In the future, this could become a more generic \"clamp\" function that receives `min` and `max` args.\n */\nexport const toZIndex = js`(value) => {${js.joinLines(\n\tjs`if (!Number.isFinite(value)) return 0`,\n\tjs`if (value < -1) return -1`,\n\tjs`if (value > 11) return 11`,\n\tjs`return value`,\n)}};`\n", "import { assertNever } from \"@framerjs/shared\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type {\n\tValueTransform,\n\tValueTransformConstantName,\n\tValueTransformDynamicName,\n\tValueTransformWithoutIdAndType,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport type { FileDeclarationCollector } from \"../DeclarationCollector.ts\"\nimport type { LinkCollector } from \"../LinkCollector.ts\"\nimport type { LocalizedValueCollector } from \"../LocalizedValueCollector.ts\"\nimport type { VariableCollector } from \"../VariableCollector.ts\"\nimport { addImageAlt } from \"./functions/addImageAlt.ts\"\nimport { arrayLength } from \"./functions/arrayLength.ts\"\nimport { createArrayToArray } from \"./functions/arrayToArray.ts\"\nimport { contains } from \"./functions/contains.ts\"\nimport { containsAll } from \"./functions/containsAll.ts\"\nimport { containsAny } from \"./functions/containsAny.ts\"\nimport { createConvertFromBoolean } from \"./functions/convertFromBoolean.ts\"\nimport { createConvertFromEnum } from \"./functions/convertFromEnum.ts\"\nimport { createConvertFromString } from \"./functions/convertFromString.ts\"\nimport { endsWith } from \"./functions/endsWith.ts\"\nimport { createEnumToDisplayName } from \"./functions/enumToDisplayName.ts\"\nimport { equals } from \"./functions/equals.ts\"\nimport { extractDateSegment } from \"./functions/extractDateSegment.ts\"\nimport { getGridColumnCSSValue } from \"./functions/getGridColumnCSSValue.ts\"\nimport { getGridRowCSSValue } from \"./functions/getGridRowCSSValue.ts\"\nimport { getNumericColumnGap } from \"./functions/getNumericColumnGap.ts\"\nimport { greaterThan } from \"./functions/greaterThan.ts\"\nimport { htmlEscape } from \"./functions/htmlEscape.ts\"\nimport { htmlUnescape } from \"./functions/htmlUnescape.ts\"\nimport { isAfter } from \"./functions/isAfter.ts\"\nimport { isBefore } from \"./functions/isBefore.ts\"\nimport { isBetweenDates } from \"./functions/isBetweenDates.ts\"\nimport { isEven } from \"./functions/isEven.ts\"\nimport { isIncludedIn } from \"./functions/isIncludedIn.ts\"\nimport { isOdd } from \"./functions/isOdd.ts\"\nimport { isSet } from \"./functions/isSet.ts\"\nimport { jsonStringify } from \"./functions/jsonStringify.ts\"\nimport { lessThan } from \"./functions/lessThan.ts\"\nimport { negate } from \"./functions/negate.ts\"\nimport { numberToPixelString } from \"./functions/numberToPixelString.ts\"\nimport { numberToString } from \"./functions/numberToString.ts\"\nimport { offsetAndLimitArray } from \"./functions/offsetAndLimitArray.ts\"\nimport { percentageToCornerShape } from \"./functions/percentageToCornerShape.ts\"\nimport { prefix } from \"./functions/prefix.ts\"\nimport { radiusForCorner } from \"./functions/radiusForCorner.ts\"\nimport { reverseArray } from \"./functions/reverseArray.ts\"\nimport { startsWith } from \"./functions/startsWith.ts\"\nimport { suffix } from \"./functions/suffix.ts\"\nimport { toAxisOverflow } from \"./functions/toAxisOverflow.ts\"\nimport { toBoolean } from \"./functions/toBoolean.ts\"\nimport { createToDateString } from \"./functions/toDateString.ts\"\nimport { toImageSrc } from \"./functions/toImageSrc.ts\"\nimport { toNumber } from \"./functions/toNumber.ts\"\nimport { toOverflowWithClipFallback } from \"./functions/toOverflowWithClipFallback.ts\"\nimport { toResponsiveImage } from \"./functions/toResponsiveImage.ts\"\nimport { toString } from \"./functions/toString.ts\"\nimport { toZIndex } from \"./functions/toZIndex.ts\"\nimport { toggleInList } from \"./functions/toggleInList.ts\"\n\n/**\n * The value transform function implementations should never throw during runtime. These are picked\n * using a visual editor so throwing in runtime doesn't add any value and only adds frustration. If\n * a transform chain is invalid this should be made clear from the UI within Framer. So the user can\n * fix any problems themselves.\n */\nexport function getValueTransformConstantFunction(valueTransformName: ValueTransformConstantName): SafeJS {\n\tswitch (valueTransformName) {\n\t\tcase \"isAfter\":\n\t\t\treturn isAfter\n\t\tcase \"isBefore\":\n\t\t\treturn isBefore\n\t\tcase \"isBetweenDates\":\n\t\t\treturn isBetweenDates\n\t\tcase \"contains\":\n\t\t\treturn contains\n\t\tcase \"containsAny\":\n\t\t\treturn containsAny\n\t\tcase \"containsAll\":\n\t\t\treturn containsAll\n\t\tcase \"endsWith\":\n\t\t\treturn endsWith\n\t\tcase \"equals\":\n\t\t\treturn equals\n\t\tcase \"isSet\":\n\t\t\treturn isSet\n\t\tcase \"greaterThan\":\n\t\t\treturn greaterThan\n\t\tcase \"lessThan\":\n\t\t\treturn lessThan\n\t\tcase \"negate\":\n\t\t\treturn negate\n\t\tcase \"numberToString\":\n\t\t\treturn numberToString\n\t\tcase \"startsWith\":\n\t\t\treturn startsWith\n\t\tcase \"toString\":\n\t\t\treturn toString\n\t\tcase \"toNumber\":\n\t\t\treturn toNumber\n\t\tcase \"toBoolean\":\n\t\t\treturn toBoolean\n\t\tcase \"extractDateSegment\":\n\t\t\treturn extractDateSegment\n\t\tcase \"reverseArray\":\n\t\t\treturn reverseArray\n\t\tcase \"offsetAndLimitArray\":\n\t\t\treturn offsetAndLimitArray\n\t\tcase \"arrayLength\":\n\t\t\treturn arrayLength\n\t\tcase \"prefix\":\n\t\t\treturn prefix\n\t\tcase \"suffix\":\n\t\t\treturn suffix\n\t\tcase \"toResponsiveImage\":\n\t\t\treturn toResponsiveImage\n\t\tcase \"toImageSrc\":\n\t\t\treturn toImageSrc\n\t\tcase \"jsonStringify\":\n\t\t\treturn jsonStringify\n\t\tcase \"htmlEscape\":\n\t\t\treturn htmlEscape\n\t\tcase \"htmlUnescape\":\n\t\t\treturn htmlUnescape\n\t\tcase \"addImageAlt\":\n\t\t\treturn addImageAlt\n\t\tcase \"toZIndex\":\n\t\t\treturn toZIndex\n\t\tcase \"toAxisOverflow\":\n\t\t\treturn toAxisOverflow\n\t\tcase \"toOverflowWithClipFallback\":\n\t\t\treturn toOverflowWithClipFallback\n\t\tcase \"numberToPixelString\":\n\t\t\treturn numberToPixelString\n\t\tcase \"radiusForCorner\":\n\t\t\treturn radiusForCorner\n\t\tcase \"percentageToCornerShape\":\n\t\t\treturn percentageToCornerShape\n\t\tcase \"isIncludedIn\":\n\t\t\treturn isIncludedIn\n\t\tcase \"toggleInList\":\n\t\t\treturn toggleInList\n\t\tcase \"isEven\":\n\t\t\treturn isEven\n\t\tcase \"isOdd\":\n\t\t\treturn isOdd\n\t\tcase \"getGridColumnCSSValue\":\n\t\t\treturn getGridColumnCSSValue\n\t\tcase \"getGridRowCSSValue\":\n\t\t\treturn getGridRowCSSValue\n\t\tcase \"getNumericColumnGap\":\n\t\t\treturn getNumericColumnGap\n\t\tdefault:\n\t\t\tassertNever(valueTransformName, \"All constant transform names should be implemented\")\n\t}\n}\n\n/**\n * The value transform function implementations should never throw during runtime. These are picked\n * using a visual editor so throwing in runtime doesn't add any value and only adds frustration. If\n * a transform chain is invalid this should be made clear from the UI within Framer. So the user can\n * fix any problems themselves.\n */\nexport function getValueTransformDynamicFunction(\n\tvalueTransform: ValueTransformWithoutIdAndType<Extract<ValueTransform, { name: ValueTransformDynamicName }>>,\n\tinputControl: ControlDescription | undefined,\n\toutputControl: ControlDescription | undefined,\n\tvariableCollector: VariableCollector | undefined,\n\tlocalizedValueCollector: LocalizedValueCollector | undefined,\n\tlinkCollector: LinkCollector | undefined,\n\tfileDeclarationCollector: FileDeclarationCollector,\n): SafeJS {\n\tswitch (valueTransform.name) {\n\t\tcase \"enumToDisplayName\":\n\t\t\treturn createEnumToDisplayName(inputControl)\n\t\tcase \"convertFromEnum\":\n\t\t\treturn createConvertFromEnum(\n\t\t\t\tvalueTransform,\n\t\t\t\tinputControl,\n\t\t\t\toutputControl,\n\t\t\t\tvariableCollector,\n\t\t\t\tlocalizedValueCollector,\n\t\t\t\tlinkCollector,\n\t\t\t)\n\t\tcase \"convertFromString\":\n\t\t\treturn createConvertFromString(\n\t\t\t\tvalueTransform,\n\t\t\t\toutputControl,\n\t\t\t\tvariableCollector,\n\t\t\t\tlocalizedValueCollector,\n\t\t\t\tlinkCollector,\n\t\t\t)\n\t\tcase \"convertFromBoolean\":\n\t\t\treturn createConvertFromBoolean(\n\t\t\t\tvalueTransform,\n\t\t\t\toutputControl,\n\t\t\t\tvariableCollector,\n\t\t\t\tlocalizedValueCollector,\n\t\t\t\tlinkCollector,\n\t\t\t)\n\t\tcase \"arrayToArray\":\n\t\t\treturn createArrayToArray(valueTransform)\n\t\tcase \"toDateString\":\n\t\t\treturn createToDateString(valueTransform, fileDeclarationCollector)\n\t\tdefault:\n\t\t\tassertNever(valueTransform, \"All dynamic transform names should be implemented\")\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ModuleType } from \"@framerjs/shared\"\nimport {\n\tassert,\n\tassertNever,\n\temptyArray,\n\tisModuleExportIdentifier,\n\tparseModuleIdentifier,\n\tshouldBeNever,\n} from \"@framerjs/shared\"\nimport type { TemplateFilter } from \"@framerjs/shared/src/custom-code/templateFilters.ts\"\nimport type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport type { ComputedValue, ComputedValueOutputType } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport { isComputedValueFromVariableReference } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport type {\n\tValueTransform,\n\tValueTransformDynamicName,\n\tValueTransformWithoutIdAndType,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport {\n\tgetOutputTypesForValueTransformName,\n\tisKnownValueTransformName,\n\tisValueTransformConstantName,\n\tisValueTransformDynamicName,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport { layoutDirectionVariableId, localeSourceIdentifier } from \"document/utils/LocaleVariable.ts\"\nimport type { ControlDescription, EnumControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { getDataIdentifierAndEnumFieldKeyForControl } from \"utils/getDataIdentifierAndEnumFieldKeyForControl.ts\"\nimport { isNumber, isString } from \"utils/typeChecks.ts\"\nimport type { ComponentDeclarationCollector, FileDeclarationCollector } from \"../DeclarationCollector.ts\"\nimport type { FetchDataCollector } from \"../FetchDataCollector.ts\"\nimport type { ImportCollector } from \"../ImportCollector.ts\"\nimport { moduleImportSpecifiers } from \"../ImportCollector.ts\"\nimport type { LinkCollector } from \"../LinkCollector.ts\"\nimport type { LocalizedValueCollector } from \"../LocalizedValueCollector.ts\"\nimport type { VariableCollector } from \"../VariableCollector.ts\"\nimport { enumToDisplayNameFunctionsName, getEnumToDisplayNameFunctionName } from \"./functions/enumToDisplayName.ts\"\nimport { getValueTransformArguments } from \"./getValueTransformArguments.ts\"\nimport { getValueTransformConstantFunction, getValueTransformDynamicFunction } from \"./getValueTransformFunction.ts\"\nimport { wrapValueInTemplateFilters } from \"./wrapValueInTemplateFilters.ts\"\n\nconst noArguments = emptyArray<SerializableValue>()\n\nconst toString: ValueTransformWithoutIdAndType = { name: \"toString\" }\nconst toNumber: ValueTransformWithoutIdAndType = { name: \"toNumber\" }\nconst toBoolean: ValueTransformWithoutIdAndType = { name: \"toBoolean\" }\nconst toResponsiveImage: ValueTransformWithoutIdAndType = {\n\tname: \"toResponsiveImage\",\n}\nconst toImageSrc: ValueTransformWithoutIdAndType = { name: \"toImageSrc\" }\nconst toZIndex: ValueTransformWithoutIdAndType = { name: \"toZIndex\" }\nconst numberToPixelString: ValueTransformWithoutIdAndType = { name: \"numberToPixelString\" }\nconst radiusForCorner: ValueTransformWithoutIdAndType = { name: \"radiusForCorner\" }\nconst percentageToCornerShape: ValueTransformWithoutIdAndType = { name: \"percentageToCornerShape\" }\nconst toAxisOverflow: ValueTransformWithoutIdAndType = { name: \"toAxisOverflow\" }\nconst toOverflowWithClipFallback: ValueTransformWithoutIdAndType = { name: \"toOverflowWithClipFallback\" }\nconst jsonStringify: ValueTransformWithoutIdAndType = { name: \"jsonStringify\" }\nconst htmlEscape: ValueTransformWithoutIdAndType = { name: \"htmlEscape\" }\nconst htmlUnescape: ValueTransformWithoutIdAndType = { name: \"htmlUnescape\" }\nconst addImageAlt: ValueTransformWithoutIdAndType = { name: \"addImageAlt\" }\nconst getGridColumnCSSValue: ValueTransformWithoutIdAndType = { name: \"getGridColumnCSSValue\" }\nconst getGridRowCSSValue: ValueTransformWithoutIdAndType = { name: \"getGridRowCSSValue\" }\nconst getNumericColumnGap: ValueTransformWithoutIdAndType = { name: \"getNumericColumnGap\" }\n\nfunction isValueTransformDynamic(\n\tvalueTransform: ValueTransformWithoutIdAndType,\n): valueTransform is ValueTransformWithoutIdAndType<Extract<ValueTransform, { name: ValueTransformDynamicName }>> {\n\treturn isValueTransformDynamicName(valueTransform.name)\n}\n\nexport class ValueTransformCollector {\n\tconstructor(\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly fileDeclarations: FileDeclarationCollector,\n\t\tprivate readonly componentDeclarations: ComponentDeclarationCollector | undefined,\n\t\tprivate readonly imports: ImportCollector | undefined,\n\t\t/**\n\t\t * @param variables - Should always be passed in unless variables\n\t\t * are not supported. For example in the metadata module.\n\t\t */\n\t\treadonly variables: VariableCollector | undefined,\n\t\treadonly localizedValues: LocalizedValueCollector | undefined,\n\t\treadonly links: LinkCollector | undefined,\n\t\treadonly fetches: FetchDataCollector,\n\t\tprivate readonly modulesStore: ModulesStore | undefined,\n\t\tprivate readonly type: ModuleType,\n\t) {}\n\n\tprivate wrapInTransformFunction(\n\t\tcurrentValue: SafeJS,\n\t\ttransform: ValueTransformWithoutIdAndType,\n\t\targs: readonly SerializableValue[],\n\t\tinputControl?: ControlDescription,\n\t\toutputControl?: ControlDescription,\n\t) {\n\t\tif (isValueTransformConstantName(transform.name)) {\n\t\t\tconst functionBody = this.fileDeclarations.dedupe(\n\t\t\t\ttransform.name,\n\t\t\t\tgetValueTransformConstantFunction(transform.name),\n\t\t\t)\n\t\t\treturn SafeJS.fn(functionBody, currentValue, ...args)\n\t\t}\n\t\tif (isValueTransformDynamic(transform)) {\n\t\t\tif (transform.name === \"enumToDisplayName\" && inputControl && inputControl.type === ControlType.Enum) {\n\t\t\t\tconst importedFunction = this.getImportedEnumToDisplayNameIfPossible(currentValue, inputControl)\n\t\t\t\tif (importedFunction) return importedFunction\n\t\t\t}\n\n\t\t\tconst generatedFunction = getValueTransformDynamicFunction(\n\t\t\t\ttransform,\n\t\t\t\tinputControl,\n\t\t\t\toutputControl,\n\t\t\t\tthis.variables,\n\t\t\t\tthis.localizedValues,\n\t\t\t\tthis.links,\n\t\t\t\tthis.fileDeclarations,\n\t\t\t)\n\n\t\t\treturn SafeJS.fn(\n\t\t\t\tnew SafeJS(this.fileDeclarations.dedupe(transform.name, generatedFunction)),\n\t\t\t\tcurrentValue,\n\t\t\t\t...args,\n\t\t\t)\n\t\t}\n\n\t\tassertNever(transform.name, \"All value transforms should be handled in wrapInTransformFunction\")\n\t}\n\n\t/**\n\t * If the enum comes from a collection, the collection might export an enum to display name\n\t * utility. If so, we should use that one, a locally generated function can get out of date.\n\t */\n\tprivate getImportedEnumToDisplayNameIfPossible(currentValue: SafeJS, inputControl: EnumControlDescription) {\n\t\tconst imports = this.imports\n\t\tconst modulesStore = this.modulesStore\n\t\tif (!imports || !modulesStore) return\n\n\t\tconst controlMetadata = getDataIdentifierAndEnumFieldKeyForControl(inputControl)\n\t\tif (!controlMetadata) return\n\n\t\tconst { dataIdentifier, enumFieldKey } = controlMetadata\n\n\t\tif (dataIdentifier === localeSourceIdentifier) {\n\t\t\tif (enumFieldKey === layoutDirectionVariableId) {\n\t\t\t\treturn this.variables?.getLayoutDirectionName() ?? js`undefined`\n\t\t\t}\n\t\t\treturn this.variables?.getLocaleName() ?? js`undefined`\n\t\t}\n\n\t\tconst data = this.componentLoader.dataForIdentifier(dataIdentifier)\n\t\tif (!data || !data.annotations) return\n\n\t\tconst annotationKey = AnnotationKey.FramerEnumToDisplayNameUtils\n\t\tconst annotationValue = data.annotations?.[annotationKey]\n\n\t\t// Lacking the annotation means the module did not export enum to name utils\n\t\tif (!isString(annotationValue)) return\n\n\t\tconst version = Number.parseInt(annotationValue, 10)\n\t\tif (!isNumber(version)) return\n\n\t\tconst identifier = parseModuleIdentifier(dataIdentifier)\n\t\tif (!isModuleExportIdentifier(identifier)) return\n\n\t\tconst { importSpecifier } = moduleImportSpecifiers(identifier, this.type, this.componentLoader, modulesStore)\n\t\tif (!importSpecifier) return\n\n\t\tconst localeBinding = this.variables?.getLocale() ?? js`undefined`\n\n\t\tswitch (version) {\n\t\t\tcase 1: {\n\t\t\t\tconst exportSpecifier = getEnumToDisplayNameFunctionName(enumFieldKey)\n\t\t\t\tconst binding = imports.addImport(importSpecifier, { exportSpecifier })\n\t\t\t\treturn SafeJS.optionalFn(binding, currentValue, localeBinding)\n\t\t\t}\n\t\t\tcase 2: {\n\t\t\t\tconst exportSpecifier = enumToDisplayNameFunctionsName\n\t\t\t\tconst binding = imports.addImport(importSpecifier, { exportSpecifier })\n\t\t\t\treturn SafeJS.optionalFn(js`${binding}[${enumFieldKey}]`, currentValue, localeBinding)\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Enum to display name utils, unsupported version: ${version}`)\n\t\t}\n\t}\n\n\twrapInValueTransform(\n\t\tcurrentValue: SafeJS,\n\t\ttransform: ValueTransformWithoutIdAndType,\n\t\tinputControl?: ControlDescription,\n\t\toutputControl?: ControlDescription,\n\t): SafeJS {\n\t\treturn this.wrapInTransformFunction(\n\t\t\tcurrentValue,\n\t\t\ttransform,\n\t\t\tgetValueTransformArguments(transform, this, this.variables, this.localizedValues),\n\t\t\tinputControl,\n\t\t\toutputControl,\n\t\t)\n\t}\n\n\tprivate makeTypeSafe(currentValue: SafeJS, outputType: ComputedValueOutputType): SafeJS {\n\t\tswitch (outputType) {\n\t\t\tcase ControlType.String:\n\t\t\tcase ControlType.Color:\n\t\t\t\treturn this.wrapInTransformFunction(currentValue, toString, noArguments)\n\t\t\tcase ControlType.Number:\n\t\t\t\treturn this.wrapInTransformFunction(currentValue, toNumber, noArguments)\n\t\t\tcase ControlType.Boolean:\n\t\t\t\treturn this.wrapInTransformFunction(currentValue, toBoolean, noArguments)\n\t\t\tcase ControlType.Array:\n\t\t\tcase ControlType.Enum:\n\t\t\tcase ControlType.Link:\n\t\t\tcase ControlType.Gap:\n\t\t\tcase ControlType.Padding:\n\t\t\tcase ControlType.BorderRadius:\n\t\t\tcase ControlType.Image:\n\t\t\tcase ControlType.MultiCollectionReference:\n\t\t\t\treturn currentValue\n\t\t\tdefault:\n\t\t\t\t// Not asserting because we don't want to crash after a rollback\n\t\t\t\tshouldBeNever(outputType)\n\t\t\t\treturn currentValue\n\t\t}\n\t}\n\n\tgetActiveLocaleCode(): SafeJS {\n\t\tif (!this.componentDeclarations || !this.imports) return js`undefined`\n\t\tconst useLocaleCode = this.imports.addImport(\"framer\", {\n\t\t\texportSpecifier: \"useLocaleCode\",\n\t\t})\n\t\treturn this.componentDeclarations.dedupe(\"activeLocaleCode\", SafeJS.fn(useLocaleCode))\n\t}\n\n\tcreateComputedValue(\n\t\tcomputedValue: ComputedValue,\n\t\tnode: CanvasNode,\n\t\toutputControl: ControlDescription | undefined,\n\t): SafeJS {\n\t\tassert(this.variables)\n\n\t\tconst inputControl = isComputedValueFromVariableReference(computedValue)\n\t\t\t? node.cache.getVariableControlByReference(computedValue.startValue)\n\t\t\t: undefined\n\n\t\tlet result = isComputedValueFromVariableReference(computedValue)\n\t\t\t? this.variables.create(computedValue.startValue)\n\t\t\t: this.fetches.createFetchBinding(node, computedValue.startValue)\n\n\t\tlet lastTransform: ValueTransform | undefined\n\n\t\tcomputedValue.transforms.forEach(transform => {\n\t\t\t// Value transforms might be unknown after a rollback\n\t\t\tif (!isKnownValueTransformName(transform.name)) return\n\n\t\t\tresult = this.wrapInValueTransform(result, transform, inputControl, outputControl)\n\t\t\tlastTransform = transform\n\t\t})\n\n\t\tconst outputTypes = lastTransform ? getOutputTypesForValueTransformName(lastTransform.name) : null\n\n\t\t// Make sure result has the right type even when the chain is invalid\n\t\tif (!outputTypes || outputTypes.length > 1 || outputTypes[0] !== computedValue.outputType) {\n\t\t\treturn this.makeTypeSafe(result, computedValue.outputType)\n\t\t}\n\n\t\treturn result\n\t}\n\n\twrapInToResponsiveImage(currentValue: SafeJS): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, toResponsiveImage, noArguments)\n\t}\n\n\twrapInToImageSrc(currentValue: SafeJS): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, toImageSrc, noArguments)\n\t}\n\n\twrapInToZIndex(currentValue: SafeJS): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, toZIndex, noArguments)\n\t}\n\n\twrapInNumberToPixelString(currentValue: SafeJS): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, numberToPixelString, noArguments)\n\t}\n\n\twrapInRadiusForCorner(currentValue: SafeJS, cornerIndex: SerializableValue): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, radiusForCorner, [cornerIndex])\n\t}\n\n\twrapInPercentageToCornerShape(currentValue: SafeJS): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, percentageToCornerShape, noArguments)\n\t}\n\n\twrapInToAxisOverflow(currentValue: SafeJS, overflow: SerializableValue): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, toAxisOverflow, [overflow])\n\t}\n\n\twrapInToOverflowWithClipFallback(currentValue: SafeJS): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, toOverflowWithClipFallback, noArguments)\n\t}\n\n\twrapInAddImageAlt(currentValue: SafeJS, alt: SafeJS) {\n\t\treturn this.wrapInTransformFunction(currentValue, addImageAlt, [alt])\n\t}\n\twrapInClampRGB(currentValue: SafeJS): SafeJS | string {\n\t\tassert(this.imports, \"ValueTransformCollector: Must have imports to wrap in clampColor.\")\n\t\treturn SafeJS.fn(this.imports.addImport(\"framer\", { exportSpecifier: \"clampRGB\" }), currentValue)\n\t}\n\n\twrapInGetGridColumnCSSValue(currentValue: SafeJS, columnCount: SerializableValue | undefined): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, getGridColumnCSSValue, columnCount ? [columnCount] : noArguments)\n\t}\n\n\twrapInGetGridRowCSSValue(currentValue: SafeJS): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, getGridRowCSSValue, noArguments)\n\t}\n\n\twrapInGetNumericColumnGap(currentValue: SafeJS): SafeJS {\n\t\treturn this.wrapInTransformFunction(currentValue, getNumericColumnGap, noArguments)\n\t}\n\n\twrapInTemplateFilters(currentValue: SafeJS, filters: Set<TemplateFilter>): SafeJS {\n\t\treturn this.makeTypeSafe(\n\t\t\twrapValueInTemplateFilters(currentValue, filters, {\n\t\t\t\tjson: value => this.wrapInTransformFunction(value, jsonStringify, noArguments),\n\t\t\t\tescape: value => this.wrapInTransformFunction(value, htmlEscape, noArguments),\n\t\t\t\traw: value => this.wrapInTransformFunction(value, htmlUnescape, noArguments),\n\t\t\t}),\n\t\t\tControlType.String,\n\t\t)\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, ModuleType, isEmptyObject, localModuleIdForStableName } from \"@framerjs/shared\"\nimport type { SourceCodeWithArtifacts } from \"code-generation/components/GeneratedComponent.ts\"\nimport type { GeneratedSubmodule } from \"code-generation/components/GeneratedSubmodule.ts\"\nimport { SubmoduleCollector } from \"code-generation/components/GeneratedSubmodule.ts\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport type { SerializableRecord, SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { CollectorEntryNode } from \"code-generation/types.ts\"\nimport type { CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCollectionNode,\n\tisLayoutTemplateNode,\n\tisRootNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { LocaleId } from \"document/models/CanvasTree/traits/WithLocales.ts\"\nimport type { LocalizedSize, LocalizedTextValue, LocalizedValues } from \"document/models/LocalizedValue.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport { isNullish, isUndefined } from \"utils/typeChecks.ts\"\nimport { BindingCollector } from \"./BindingCollector.ts\"\nimport type { JSXDeclarationCollector } from \"./DeclarationCollector.ts\"\nimport { FileDeclarationCollector } from \"./DeclarationCollector.ts\"\nimport type { FetchDataCollector } from \"./FetchDataCollector.ts\"\nimport { ImportCollector } from \"./ImportCollector.ts\"\nimport { LinkCollector } from \"./LinkCollector.ts\"\nimport { VariableCollector } from \"./VariableCollector.ts\"\nimport { ValueTransformCollector } from \"./valueTransformCollector/ValueTransformCollector.ts\"\n\ninterface LocaleCollectors {\n\timports: ImportCollector\n\tdeclarations: FileDeclarationCollector\n\tvariables: VariableCollector | undefined\n\tlinks: LinkCollector\n\tvalueTransforms: ValueTransformCollector\n}\n\ntype GetLocalizedValue<Value> = (localeId: LocaleId, collectors: LocaleCollectors) => Value | SafeJS | null | undefined\n\nfunction isLocalizableEntryNode(node: CollectorEntryNode): boolean {\n\treturn (\n\t\tisWebPageNode(node) ||\n\t\tisCollectionNode(node) ||\n\t\tisSmartComponentNode(node) ||\n\t\tisRootNode(node) ||\n\t\tisLayoutTemplateNode(node)\n\t)\n}\n\nfunction getValuesInitializer(values: SafeJS, useDynamicImports: boolean) {\n\treturn js`(key, locale){${js.joinLines(\n\t\tjs`while (locale) {${js.joinLines(\n\t\t\tjs`const values = ${values}[locale.id]`,\n\t\t\tjs`if (values) {${js.joinLines(\n\t\t\t\tjs`const value = ${useDynamicImports ? js`values.read()[key]` : js`values[key]`}`,\n\t\t\t\tjs`if (value) return value`,\n\t\t\t)}}`,\n\t\t\tjs`locale = locale.fallback`,\n\t\t)}}`,\n\t)}}`\n}\n\nexport interface LocalizedValueCollector {\n\tadd<V extends SerializableValue | undefined>(\n\t\tdefaultValue: V,\n\t\tvalueLocalized: LocalizedValues<LocalizedTextValue> | LocalizedSize | undefined,\n\t\tgetLocalizedValue: GetLocalizedValue<V>,\n\t): V | SafeJS\n}\n\n/**\n * All LocalizedValueCollectors implement an `add` method which allows multiple\n * localizations of a source value to be serialized into the calling code.\n *\n * How these values are collected and combined is up to the implementors of this\n * abstract class.\n */\nabstract class ValueCollector implements LocalizedValueCollector {\n\tprotected constructor(\n\t\tprotected readonly entryNode: CollectorEntryNode,\n\t\tprotected readonly variables: VariableCollector | undefined,\n\t\tprotected readonly tree: CanvasTree,\n\t) {}\n\n\t/**\n\t * Return the binding that should be used to access a localized value for a\n\t * key and locale.\n\t */\n\tprotected abstract get getLocalizedValueBinding(): SafeJS\n\n\t/**\n\t * Record a localized value at a localeId and key so that it can be\n\t * serialized into a module as a single object.\n\t */\n\tprotected abstract recordLocalizedValue(localeId: NodeID, key: string, value: SerializableValue): void\n\n\t/**\n\t * Generate a localized value for a key and locale, maybe adding\n\t * declarations or imports to serialization collectors.\n\t */\n\tprotected abstract createLocalizedValue<V>(\n\t\tlocaleId: NodeID,\n\t\tvariables: VariableCollector | undefined,\n\t\tgetLocalizedValue: GetLocalizedValue<V>,\n\t): V | SafeJS | null | undefined\n\n\tprivate cache: Record<string, SafeJS> = {}\n\tprivate valueCounter = 0\n\n\t#frozen = false\n\n\t/**\n\t * Freeze the collector so that new entries can't be added after all entries\n\t * have been extracted.\n\t */\n\tprotected freeze() {\n\t\tthis.#frozen = true\n\t}\n\n\t/**\n\t * Add localized values for a localizable value in a module. Missing values\n\t * will try to fallback through locale fallbacks.\n\t */\n\tadd<V extends SerializableValue | undefined>(\n\t\tdefaultValue: V,\n\t\tvalueLocalized: LocalizedValues<LocalizedTextValue> | LocalizedSize | undefined,\n\t\tgetLocalizedValue: GetLocalizedValue<V>,\n\t): V | SafeJS {\n\t\tassert(!this.#frozen, \"Cannot add values to a frozen LocalizedValuesCollector.\")\n\n\t\tconst localizedValues: Record<LocaleId, V | SafeJS> = {}\n\t\tif (!valueLocalized || !isLocalizableEntryNode(this.entryNode)) return defaultValue\n\n\t\tlet variables: VariableCollector | undefined\n\t\tif (this.variables) {\n\t\t\tconst bindings = new BindingCollector()\n\t\t\tvariables = new VariableCollector(this.entryNode, bindings)\n\t\t}\n\n\t\tconst locales = this.tree.root.locales ?? []\n\t\tfor (const locale of locales) {\n\t\t\t// If the value doesn't have a localized value for a locale, we can\n\t\t\t// continue.\n\t\t\tif (!(locale.id in valueLocalized)) continue\n\n\t\t\tconst value = this.createLocalizedValue<V>(locale.id, variables, getLocalizedValue)\n\t\t\tif (isNullish(value)) continue\n\t\t\tlocalizedValues[locale.id] = value\n\t\t}\n\n\t\tif (isEmptyObject(localizedValues)) return defaultValue\n\n\t\tconst cacheKey = serializeJS({ defaultValue, localizedValues })\n\t\tconst existing = this.cache[cacheKey]\n\t\tif (existing) return existing\n\n\t\tconst exportBinding = `v${this.valueCounter++}`\n\n\t\tlet localizedValue = SafeJS.fn(this.getLocalizedValueBinding, exportBinding, Var.activeLocale)\n\n\t\tif (this.variables && variables && variables.size > 0) {\n\t\t\t// If there are any variables we need to pass them to the localized value.\n\t\t\tconst variableParameters: SafeJS[] = []\n\t\t\tconst variableArguments: SafeJS[] = []\n\n\t\t\tfor (const [variable, parameter] of variables) {\n\t\t\t\tvariableParameters.push(parameter)\n\t\t\t\tconst argument = this.variables.create(variable)\n\t\t\t\tvariableArguments.push(argument)\n\t\t\t}\n\n\t\t\tfor (const localeId in localizedValues) {\n\t\t\t\tconst value = localizedValues[localeId]\n\t\t\t\tassert(!isNullish(value), \"Localized should not be null or undefined\")\n\n\t\t\t\tconst serializedParameters = js.listFrom(variableParameters)\n\t\t\t\tlocalizedValues[localeId] = js`(${serializedParameters}) => ${value}`\n\t\t\t}\n\n\t\t\tconst serializedArguments = js.listFrom(variableArguments)\n\t\t\tlocalizedValue = js`${localizedValue}?.(${serializedArguments})`\n\t\t}\n\n\t\tfor (const localeId in localizedValues) {\n\t\t\tconst value = localizedValues[localeId]\n\t\t\tassert(!isNullish(value), \"Localized should not be null or undefined\")\n\t\t\tthis.recordLocalizedValue(localeId, exportBinding, value)\n\t\t}\n\n\t\tif (!isUndefined(defaultValue)) {\n\t\t\tlocalizedValue = js`${localizedValue} ?? ${defaultValue}`\n\t\t}\n\n\t\treturn (this.cache[cacheKey] = localizedValue)\n\t}\n}\n\n/**\n * A LocalizedValueCollector that generates an entire module for all localized\n * values. The main file will export functions which allow another module to\n * get values for an identifier. The localizations will be stored in submodules.\n */\nexport class ModuleLocalizedValueCollector extends ValueCollector {\n\tconstructor(\n\t\tentryNode: CollectorEntryNode,\n\t\tvariables: VariableCollector | undefined,\n\t\ttree: CanvasTree,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly imports: ImportCollector,\n\t\tprivate readonly declarations: JSXDeclarationCollector,\n\t\tprivate readonly fetches: FetchDataCollector,\n\t\tprivate readonly modulesStore: ModulesStore,\n\t\tprivate readonly moduleType: ModuleType,\n\t) {\n\t\tsuper(entryNode, variables, tree)\n\t\tthis.submodules = new SubmoduleCollector(\n\t\t\tthis.moduleType,\n\t\t\tthis.componentLoader,\n\t\t\tthis.modulesStore,\n\t\t\tthis.entryNode.id,\n\t\t)\n\t}\n\n\tprivate readonly submoduleByLocaleId = new Map<LocaleId, GeneratedSubmodule>()\n\tprivate readonly identifier = `../${localModuleIdForStableName(ModuleType.Localization, this.entryNode.id)}`\n\tprivate readonly submodules: SubmoduleCollector\n\tprivate readonly bindings = new BindingCollector()\n\n\tprotected get getLocalizedValueBinding(): SafeJS {\n\t\treturn this.imports.addImport(this.identifier, {\n\t\t\texportSpecifier: \"default\",\n\t\t\timportBinding: \"getLocalizedValue\",\n\t\t})\n\t}\n\n\tprivate canPreloadWithSuspense() {\n\t\treturn !isSmartComponentNode(this.entryNode)\n\t}\n\n\t#usePreloadBinding: SafeJS | undefined\n\tprivate preloadWithSuspense(): void {\n\t\tif (this.#usePreloadBinding) return\n\n\t\tthis.#usePreloadBinding = this.bindings.create(\"usePreloadLocalizedValues\")\n\n\t\t// Import and invoke the hook in the calling component.\n\t\tthis.declarations.component.create(\n\t\t\tSafeJS.fn(\n\t\t\t\tthis.imports.addImport(this.identifier, { exportSpecifier: serializeJS(this.#usePreloadBinding) }),\n\t\t\t\tVar.activeLocale,\n\t\t\t),\n\t\t)\n\t}\n\n\tprotected createLocalizedValue<V>(\n\t\tlocaleId: NodeID,\n\t\tvariables: VariableCollector | undefined,\n\t\tgetLocalizedValue: GetLocalizedValue<V>,\n\t): V | SafeJS | null | undefined {\n\t\t// When serializing localizations into submodules, we use the submodules\n\t\t// collectors to generate a localized value.\n\t\tconst submodule = this.submoduleByLocaleId.get(localeId) ?? this.submodules.create()\n\t\tconst links = new LinkCollector(\n\t\t\tthis.entryNode,\n\t\t\tthis.componentLoader,\n\t\t\tsubmodule.imports,\n\t\t\tsubmodule.bindings,\n\t\t\tvariables,\n\t\t\tthis.tree,\n\t\t\tthis.modulesStore,\n\t\t)\n\n\t\tconst value = getLocalizedValue(localeId, {\n\t\t\tlinks,\n\t\t\tvariables,\n\t\t\timports: submodule.imports,\n\t\t\tdeclarations: submodule.declarations,\n\t\t\tvalueTransforms: new ValueTransformCollector(\n\t\t\t\tthis.componentLoader,\n\t\t\t\tsubmodule.declarations,\n\t\t\t\tundefined,\n\t\t\t\tsubmodule.imports,\n\t\t\t\tvariables,\n\t\t\t\tthis,\n\t\t\t\tlinks,\n\t\t\t\tthis.fetches,\n\t\t\t\tthis.modulesStore,\n\t\t\t\tthis.moduleType,\n\t\t\t),\n\t\t})\n\n\t\tif (isNullish(value)) {\n\t\t\t// If the localized value resolves to null, delete the submodule if\n\t\t\t// it has just been created. This ensures we don't create empty\n\t\t\t// submodules.\n\t\t\tif (submodule && !this.submoduleByLocaleId.has(localeId)) {\n\t\t\t\tthis.submodules.delete(submodule)\n\t\t\t}\n\t\t\treturn undefined\n\t\t}\n\n\t\tthis.submoduleByLocaleId.set(localeId, submodule)\n\t\tif (this.canPreloadWithSuspense()) this.preloadWithSuspense()\n\n\t\treturn value\n\t}\n\n\tprotected recordLocalizedValue(localeId: NodeID, key: string, value: SerializableValue): void {\n\t\tconst submodule = this.submoduleByLocaleId.get(localeId)\n\t\tassert(submodule, \"Localization submodule must exist\")\n\t\tsubmodule.declarations.create(js`export const ${new SafeJS(key)} = ${value}`)\n\t}\n\n\tprivate maybeGetUsePreloadDeclarations(values: SafeJS): SafeJS[] {\n\t\tif (!this.canPreloadWithSuspense() || !this.#usePreloadBinding) return []\n\n\t\tconst preload = this.bindings.create(\"preload\")\n\t\tconst binding = this.#usePreloadBinding\n\n\t\treturn [\n\t\t\tjs`function ${preload}(locale) {${js.joinLines(\n\t\t\t\tjs`const promises = []`,\n\t\t\t\tjs`while (locale) {${js.joinLines(\n\t\t\t\t\tjs`const values = ${values}[locale.id]`,\n\t\t\t\t\tjs`if (values) {${js.joinLines(\n\t\t\t\t\t\tjs`const promise = values.preload()`,\n\t\t\t\t\t\tjs`if (promise) promises.push(promise)`,\n\t\t\t\t\t)}}`,\n\t\t\t\t\tjs`locale = locale.fallback`,\n\t\t\t\t)}}`,\n\t\t\t\tjs`if (promises.length > 0) return Promise.all(promises)`,\n\t\t\t)}}`,\n\t\t\tjs`export function ${binding}(locale) {${js.joinLines(\n\t\t\t\tjs`const preloadPromise = ${preload}(locale)`,\n\t\t\t\tjs`if (preloadPromise) throw preloadPromise`,\n\t\t\t)}}`,\n\t\t]\n\t}\n\n\tprivate values(imports: ImportCollector): SerializableRecord {\n\t\tconst valuesByLocaleId: Record<LocaleId, SafeJS> = {}\n\t\tfor (const [localeId, submodule] of this.submoduleByLocaleId) {\n\t\t\tif (this.canPreloadWithSuspense()) {\n\t\t\t\t// For web pages and collections we can use dynamic imports to\n\t\t\t\t// asynchronously load the active locale and their fallbacks.\n\t\t\t\tconst lazyValueBinding = imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"LazyValue\",\n\t\t\t\t})\n\n\t\t\t\tvaluesByLocaleId[localeId] = SafeJS.fn(\n\t\t\t\t\tjs`new ${lazyValueBinding}`,\n\t\t\t\t\tjs`() => import(${submodule.submoduleImport})`,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\t// For smart components we can't do that because we need to\n\t\t\t\t// render them synchronously as they are not wrapped in a\n\t\t\t\t// Suspense boundary.\n\t\t\t\tvaluesByLocaleId[localeId] = imports.addImport(submodule.submoduleImport, {\n\t\t\t\t\texportSpecifier: \"*\",\n\t\t\t\t\timportBinding: \"localizedValues\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\treturn valuesByLocaleId\n\t}\n\n\t/**\n\t * Create the source code and artifacts necessary to compile a localization\n\t * module.\n\t */\n\tmodule(revision: number | undefined): SourceCodeWithArtifacts | undefined {\n\t\tthis.freeze()\n\n\t\tconst locales = this.tree.root.locales ?? []\n\t\tif (locales.length === 0 || this.submoduleByLocaleId.size === 0) return undefined\n\n\t\tconst imports = new ImportCollector(this.moduleType, this.componentLoader, this.modulesStore, this.bindings)\n\t\tconst declarations = new FileDeclarationCollector(this.bindings)\n\n\t\tconst values = declarations.dedupe(\"valuesByLocaleId\", this.values(imports))\n\n\t\treturn {\n\t\t\ttype: ModuleType.Localization,\n\t\t\trevision,\n\t\t\tsource: js.joinSections(\n\t\t\t\tjs.joinLines(...imports.statements),\n\t\t\t\t...declarations.list(),\n\t\t\t\tjs`export default function getLocalizedValue${getValuesInitializer(values, this.canPreloadWithSuspense())}`,\n\t\t\t\t...this.maybeGetUsePreloadDeclarations(values),\n\t\t\t),\n\t\t\tartifacts: { submodules: this.submodules.serialize() },\n\t\t}\n\t}\n}\n\n/**\n * A LocalizedValueCollector that will inline localized values into the module\n * source instead of creating submodules. This is useful for metadata modules\n * which only have 2 plain text fields that can be localized.\n */\nexport class InlineLocalizedValueCollector extends ValueCollector {\n\tconstructor(\n\t\tentryNode: CollectorEntryNode,\n\t\tvariables: VariableCollector | undefined,\n\t\ttree: CanvasTree,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly imports: ImportCollector,\n\t\tprivate readonly bindings: BindingCollector,\n\t\tprivate readonly declarations: FileDeclarationCollector,\n\t\tprivate readonly fetches: FetchDataCollector,\n\t\tprivate readonly modulesStore: ModulesStore,\n\t\tprivate readonly moduleType: ModuleType,\n\t) {\n\t\tsuper(entryNode, variables, tree)\n\t}\n\n\tprivate readonly valuesByLocaleId: Record<LocaleId, SerializableRecord> = {}\n\n\t#localizedValueBinding: SafeJS | undefined\n\tprotected get getLocalizedValueBinding(): SafeJS {\n\t\tthis.#localizedValueBinding ||= this.bindings.create(\"getLocalizedValue\")\n\t\treturn this.#localizedValueBinding\n\t}\n\n\tprotected recordLocalizedValue(localeId: NodeID, key: string, value: SerializableValue): void {\n\t\tconst existing = this.valuesByLocaleId[localeId] ?? {}\n\t\texisting[key] = value\n\t\tthis.valuesByLocaleId[localeId] = existing\n\t}\n\n\tprotected createLocalizedValue<V>(\n\t\tlocalId: NodeID,\n\t\tvariables: VariableCollector | undefined,\n\t\tgetLocalizedValue: GetLocalizedValue<V>,\n\t): V | SafeJS | null | undefined {\n\t\t// When serializing localizations inline to a module, we reuse the\n\t\t// modules collectors.\n\t\tconst links = new LinkCollector(\n\t\t\tthis.entryNode,\n\t\t\tthis.componentLoader,\n\t\t\tthis.imports,\n\t\t\tthis.bindings,\n\t\t\tvariables,\n\t\t\tthis.tree,\n\t\t\tthis.modulesStore,\n\t\t)\n\n\t\treturn getLocalizedValue(localId, {\n\t\t\tlinks,\n\t\t\tvariables,\n\t\t\timports: this.imports,\n\t\t\tdeclarations: this.declarations,\n\t\t\tvalueTransforms: new ValueTransformCollector(\n\t\t\t\tthis.componentLoader,\n\t\t\t\tthis.declarations,\n\t\t\t\tundefined,\n\t\t\t\tthis.imports,\n\t\t\t\tvariables,\n\t\t\t\tthis,\n\t\t\t\tlinks,\n\t\t\t\tthis.fetches,\n\t\t\t\tthis.modulesStore,\n\t\t\t\tthis.moduleType,\n\t\t\t),\n\t\t})\n\t}\n\n\t/**\n\t * List localization declarations into a module.\n\t */\n\tlist(): SafeJS[] {\n\t\tthis.freeze()\n\n\t\tconst locales = this.tree.root.locales ?? []\n\t\tif (locales.length === 0) return []\n\n\t\tconst binding = this.bindings.create(\"valuesByLocaleId\")\n\t\treturn [\n\t\t\tjs`const ${binding} = ${this.valuesByLocaleId}`,\n\t\t\tjs`function ${this.getLocalizedValueBinding} ${getValuesInitializer(binding, false)}`,\n\t\t]\n\t}\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { pruneRanges } from \"utils/ranges.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\n\ninterface MetricsTimer<Metric extends string> {\n\tmetric: Metric\n\tcancel(): void\n\tdone(): void\n}\n\nexport class MetricsCollector<MetricNames extends string> {\n\treadonly #metrics: Record<MetricNames, number>\n\treadonly #pendingTimers = new Set<MetricsTimer<MetricNames>>()\n\treadonly #timerRanges = new Map<MetricNames, [number, number][]>()\n\n\tconstructor(metrics: Record<MetricNames, number>) {\n\t\tthis.#metrics = { ...metrics }\n\t}\n\n\tcount(metric: MetricNames, amount = 1) {\n\t\tthis.#metrics[metric] += amount\n\t}\n\n\t/** This will only include values that are of type `string` or `SafeJS`. */\n\tmeasureLength<T>(metric: MetricNames, value: T): T {\n\t\tif (isString(value) || value instanceof SafeJS) {\n\t\t\tthis.#metrics[metric] += value.length\n\t\t}\n\t\treturn value\n\t}\n\n\tget(): { [Metric in MetricNames]: number } {\n\t\tif (this.#pendingTimers.size > 0) {\n\t\t\tconst timerNames = Array.from(this.#pendingTimers, t => t.metric).join(\", \")\n\t\t\tthrow Error(`Attempted to get metrics before completing timer(s): ${timerNames}`)\n\t\t}\n\t\t// Update metrics with latest timer values.\n\t\tconst metrics = { ...this.#metrics }\n\t\tfor (const [metric, ranges] of this.#timerRanges) {\n\t\t\t// Collect non-overlapping time ranges (in case we were doing\n\t\t\t// measurements in parallel) and sum the ranges into an integer.\n\t\t\tconst prunedRanges = pruneRanges(ranges)\n\t\t\tmetrics[metric] += Math.round(prunedRanges.reduce((sum, [a, b]) => sum + (b - a), 0))\n\t\t}\n\t\treturn metrics\n\t}\n\n\ttime<Metric extends MetricNames>(metric: Metric): MetricsTimer<Metric> {\n\t\tconst start = performance.now()\n\t\tlet cancelled = false\n\t\tconst timer = {\n\t\t\tget metric() {\n\t\t\t\treturn metric\n\t\t\t},\n\t\t\tcancel: () => {\n\t\t\t\tif (cancelled) return\n\t\t\t\tthis.#pendingTimers.delete(timer)\n\t\t\t\tcancelled = true\n\t\t\t},\n\t\t\tdone: () => {\n\t\t\t\tassert(!cancelled, \"Attempted to complete a cancelled timer\")\n\t\t\t\tlet ranges = this.#timerRanges.get(metric)\n\t\t\t\tif (!ranges) {\n\t\t\t\t\tranges = []\n\t\t\t\t\tthis.#timerRanges.set(metric, ranges)\n\t\t\t\t}\n\t\t\t\tranges.push([start, performance.now()])\n\t\t\t\ttimer.cancel()\n\t\t\t},\n\t\t}\n\t\tthis.#pendingTimers.add(timer)\n\t\treturn timer\n\t}\n\n\tasync timed<Metric extends MetricNames, T>(metric: Metric, fn: () => Promise<T>): Promise<T> {\n\t\tconst timer = this.time(metric)\n\t\ttry {\n\t\t\treturn await fn()\n\t\t} finally {\n\t\t\ttimer.done()\n\t\t}\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { murmurHash } from \"@framerjs/shared\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { TrackingEventType } from \"document/models/CanvasTree/nodes/FunnelStepActionNode.ts\"\nimport { isCodeComponentNode, isRichTextNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withLink } from \"document/models/CanvasTree/traits/WithLink.ts\"\nimport { hasTriggerActions } from \"document/models/CanvasTree/traits/WithTriggerActions.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport type {\n\tRichTextBlock,\n\tRichTextDocument,\n\tRichTextInline,\n\tRichTextTableRow,\n} from \"document/models/richText/RichTextDocument.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { CLICK_TRACKING_ID_ATTR } from \"prosemirror/schema/link.ts\"\nimport { parseHTML } from \"utils/parseHTML.ts\"\nimport { isArray, isObject, isString, isUndefined } from \"utils/typeChecks.ts\"\n\n/** Tracking id content without computed id - used during collection */\ninterface TrackingIdContent {\n\ttrackingId: string\n\t/**\n\t * Currently, the event type can either be a \"click\",\n\t * or is unknown, if the tracking id is set to a property of a component\n\t */\n\ttype: TrackingEventType | undefined\n\t/**\n\t * The node id that is included in the tracking event,\n\t * or is unknown, if the tracking id is set to a property of a component\n\t */\n\tnodeId: NodeID | undefined\n}\n\n/**\n * Tracking id for a node\n */\nexport interface TrackingIdForNode extends TrackingIdContent {\n\t/** Unique ID; a hash computed from the tracking content */\n\tid: string\n}\n\nfunction hashTrackingIdContent(\n\ttrackingId: string,\n\ttype: TrackingEventType | undefined,\n\tnodeId: NodeID | undefined,\n): string {\n\t// Lets add a prefix in case we ever need to use as a JS identifier\n\treturn \"_\" + murmurHash(JSON.stringify({ trackingId, type, nodeId })).toString(36)\n}\n\nexport class TrackingIdCollector {\n\t#annotations: TrackingIdContent[] = []\n\n\tconstructor(private readonly componentLoader: ComponentLoader) {}\n\n\tadd(node: CanvasNode) {\n\t\tconst trackingIds = collectTrackingIdsForNode(this.componentLoader, node)\n\t\tif (trackingIds.length === 0) return\n\t\tthis.#annotations.push(...trackingIds)\n\t}\n\n\t/**\n\t * Generate an annotation that is used to collect all the tracking ids\n\t * from a page or a smart component without fully loading the scope.\n\t *\n\t * @framerTrackingIds [{ id: \"_abc123\", trackingId: \"clicked-subscribe\", type: \"click\", nodeId: \"woSKE1A99\" }]\n\t */\n\tannotation(): string | undefined {\n\t\tif (this.#annotations.length === 0) return\n\t\tconst uniques = new Map<string, string>()\n\t\tfor (const annotation of this.#annotations) {\n\t\t\tconst id = hashTrackingIdContent(annotation.trackingId, annotation.type, annotation.nodeId)\n\t\t\tif (uniques.has(id)) continue\n\t\t\tuniques.set(\n\t\t\t\tid,\n\t\t\t\tJSON.stringify({ id, trackingId: annotation.trackingId, type: annotation.type, nodeId: annotation.nodeId }),\n\t\t\t)\n\t\t}\n\t\treturn `[${Array.from(uniques.values()).join(\",\")}]`\n\t}\n}\n\nfunction isValidTrackingId(id: unknown): id is string {\n\treturn isString(id) && id.length > 0\n}\n\nfunction isSupportedEventTypeForTrackingId(type: unknown) {\n\tif (!isString(type)) return false\n\treturn type === \"click\" || type === \"form_submit\" || type === \"trigger_invoke\"\n}\n\nexport function parseTrackingIdsAnnotation(annotation: unknown): TrackingIdForNode[] | undefined {\n\tif (!isArray(annotation)) return undefined\n\n\tconst result: TrackingIdForNode[] = []\n\tfor (const item of annotation) {\n\t\tif (!isObject(item)) return undefined\n\t\tif (!isUndefined(item.type) && !isSupportedEventTypeForTrackingId(item.type)) return undefined\n\n\t\tconst type = (item.type as TrackingEventType) ?? undefined\n\t\tconst nodeId = (\"nodeId\" in item ? (item.nodeId as NodeID) : undefined) ?? undefined\n\n\t\tconst trackingId = item?.trackingId\n\t\tconst id = item?.id\n\t\tif (isValidTrackingId(trackingId) && typeof id === \"string\") {\n\t\t\t// New format (trackingId) introduced in migration 117->118\n\t\t\tresult.push({ id, trackingId, type, nodeId })\n\t\t} else if (!trackingId && isValidTrackingId(id)) {\n\t\t\t// Legacy format, 'id' is the trackingId\n\t\t\tresult.push({ id: hashTrackingIdContent(id, type, nodeId), trackingId: id, type, nodeId })\n\t\t} else {\n\t\t\treturn undefined\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Collects tracking IDs from HTML content by parsing anchor elements\n * with data-framer-click-tracking-id attributes and adding them directly to the collection\n */\nfunction collectTrackingIdsFromHTML(html: string, nodeId: NodeID | undefined, trackingIds: TrackingIdContent[]): void {\n\tif (!html.includes(CLICK_TRACKING_ID_ATTR)) return\n\n\ttry {\n\t\tconst doc = parseHTML(html)\n\t\tconst anchors = doc.querySelectorAll(`[${CLICK_TRACKING_ID_ATTR}]`)\n\t\tfor (const anchor of anchors) {\n\t\t\tconst trackingId = anchor.getAttribute(CLICK_TRACKING_ID_ATTR)\n\t\t\tif (!isValidTrackingId(trackingId)) continue\n\t\t\ttrackingIds.push({ trackingId, nodeId, type: \"click\" })\n\t\t}\n\t} catch {\n\t\t// If HTML parsing fails, silently continue\n\t\t// This ensures we don't break the build process\n\t}\n}\n\nfunction collectTrackingIdsFromRichTextInline(\n\tinline: RichTextInline,\n\tnodeId: NodeID | undefined,\n\ttrackingIds: TrackingIdContent[],\n) {\n\tif (inline.type !== \"text\") return\n\tif (!isValidTrackingId(inline.link?.clickTrackingId)) return\n\n\ttrackingIds.push({ trackingId: inline.link.clickTrackingId, nodeId, type: \"click\" })\n}\n\nfunction collectTrackingIdsFromRichTextBlock(\n\tblock: RichTextBlock,\n\tnodeId: NodeID | undefined,\n\ttrackingIds: TrackingIdContent[],\n) {\n\tswitch (block.type) {\n\t\tcase \"textBlock\":\n\t\t\tfor (const inline of block.children) {\n\t\t\t\tcollectTrackingIdsFromRichTextInline(inline, nodeId, trackingIds)\n\t\t\t}\n\t\t\treturn\n\t\tcase \"bulletedList\":\n\t\tcase \"numberedList\":\n\t\t\tfor (const item of block.children) {\n\t\t\t\tcollectTrackingIdsFromRichTextBlocks(item.children, nodeId, trackingIds)\n\t\t\t}\n\t\t\treturn\n\t\tcase \"blockquote\":\n\t\t\tcollectTrackingIdsFromRichTextBlocks(block.children, nodeId, trackingIds)\n\t\t\treturn\n\t\tcase \"table\":\n\t\t\tfor (const row of block.children) {\n\t\t\t\tcollectTrackingIdsFromRichTextTableRow(row, nodeId, trackingIds)\n\t\t\t}\n\t\t\treturn\n\t\tcase \"media\":\n\t\t\tif (!isValidTrackingId(block.link?.clickTrackingId)) return\n\t\t\ttrackingIds.push({ trackingId: block.link.clickTrackingId, nodeId, type: \"click\" })\n\t\t\treturn\n\t\tcase \"module\":\n\t\t\treturn\n\t}\n}\n\nfunction collectTrackingIdsFromRichTextBlocks(\n\tblocks: RichTextBlock[],\n\tnodeId: NodeID | undefined,\n\ttrackingIds: TrackingIdContent[],\n) {\n\tfor (const block of blocks) {\n\t\tcollectTrackingIdsFromRichTextBlock(block, nodeId, trackingIds)\n\t}\n}\n\nfunction collectTrackingIdsFromRichTextTableRow(\n\trow: RichTextTableRow,\n\tnodeId: NodeID | undefined,\n\ttrackingIds: TrackingIdContent[],\n) {\n\tfor (const cell of row.children) {\n\t\tcollectTrackingIdsFromRichTextBlocks(cell.children, nodeId, trackingIds)\n\t}\n}\n\nfunction collectTrackingIdsFromRichTextDocument(\n\tdocument: RichTextDocument,\n\tnodeId: NodeID | undefined,\n\ttrackingIds: TrackingIdContent[],\n) {\n\tcollectTrackingIdsFromRichTextBlocks(document.children, nodeId, trackingIds)\n}\n\nfunction collectTrackingIdsForNode(componentLoader: ComponentLoader, node: CanvasNode): TrackingIdContent[] {\n\tconst trackingIds: TrackingIdContent[] = []\n\tconst nodeId = node.getPrimaryId()\n\n\tif (withLink(node) && isValidTrackingId(node.linkClickTrackingId)) {\n\t\ttrackingIds.push({ trackingId: node.linkClickTrackingId, nodeId, type: \"click\" })\n\t}\n\n\tif (isRichTextNode(node)) {\n\t\tfor (const trackingId of node.getLinkClickTrackingId(false)) {\n\t\t\tif (!isValidTrackingId(trackingId)) continue\n\t\t\ttrackingIds.push({ trackingId, nodeId, type: \"click\" })\n\t\t}\n\n\t\tif (node.htmlLocalized) {\n\t\t\tfor (const localeId in node.htmlLocalized) {\n\t\t\t\tconst localizedValue = node.htmlLocalized[localeId]?.value\n\t\t\t\tif (!localizedValue) continue\n\t\t\t\tif (typeof localizedValue === \"string\") {\n\t\t\t\t\tcollectTrackingIdsFromHTML(localizedValue, nodeId, trackingIds)\n\t\t\t\t} else {\n\t\t\t\t\tcollectTrackingIdsFromRichTextDocument(localizedValue, nodeId, trackingIds)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (isCodeComponentNode(node)) {\n\t\tconst component = componentLoader.reactComponentForIdentifier(node.codeComponentIdentifier)\n\t\tif (component?.properties) {\n\t\t\tconst controlProps = node.getControlProps(component.properties)\n\t\t\tfor (const key in controlProps) {\n\t\t\t\tif (!controlProps[key]) continue\n\t\t\t\tconst control = controlProps[key]\n\t\t\t\tif (control.type === ControlType.TrackingId && isValidTrackingId(control.value)) {\n\t\t\t\t\ttrackingIds.push({\n\t\t\t\t\t\ttrackingId: control.value,\n\t\t\t\t\t\tnodeId: undefined, // the node that triggers events is not the same as component instance\n\t\t\t\t\t\ttype: undefined, // We don't know the type in the case of a component prop\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (isFormContainer(node) && isValidTrackingId(node.formSubmitTrackingId)) {\n\t\ttrackingIds.push({ trackingId: node.formSubmitTrackingId, nodeId, type: \"form_submit\" })\n\t}\n\n\tif (hasTriggerActions(node)) {\n\t\ttrackingIds.push(\n\t\t\t...node.triggerActions\n\t\t\t\t.filter(triggerAction => isValidTrackingId(triggerAction.trigger.trackingId))\n\t\t\t\t.map(triggerAction => ({\n\t\t\t\t\ttrackingId: triggerAction.trigger.trackingId,\n\t\t\t\t\tnodeId,\n\t\t\t\t\ttype: \"trigger_invoke\" as const,\n\t\t\t\t})),\n\t\t)\n\t}\n\n\treturn trackingIds\n}\n", "import { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { type TriggerAction, hasTriggerActions } from \"document/models/CanvasTree/traits/WithTriggerActions.ts\"\nimport { assert } from \"library/utils/assert.ts\"\nimport { type Trigger, getTriggerTargetId } from \"library/utils/triggerActions.ts\"\nimport type { JSXDeclarationCollector } from \"./DeclarationCollector.ts\"\nimport type { ImportCollector } from \"./ImportCollector.ts\"\nimport type { OverlayCollector } from \"./OverlayCollector.ts\"\n\nexport interface CollectedTriggerAction {\n\t/** Static ID that can be used to identify the trigger at runtime */\n\ttriggerId: string\n\t/** ID that can be used to identify the target of the trigger action, this allows us to dedupe invocations when multiple triggers are attached to the same target */\n\ttargetId: string\n\tbinding: SafeJS\n\toverlayBinding?: SafeJS\n\tsetVariantBinding?: SafeJS\n}\n\nexport interface TriggerActionCollectorOptions {\n\tdeclarations: JSXDeclarationCollector\n\timports: ImportCollector\n\toverlays: OverlayCollector\n}\nexport class TriggerActionCollector {\n\tprivate readonly declarations: JSXDeclarationCollector\n\tprivate readonly imports: ImportCollector\n\tprivate readonly overlays: OverlayCollector\n\n\ttriggerActionByNode = new Map<NodeID, CollectedTriggerAction[]>()\n\tconstructor(input: TriggerActionCollectorOptions) {\n\t\tthis.declarations = input.declarations\n\t\tthis.imports = input.imports\n\t\tthis.overlays = input.overlays\n\t}\n\n\tcollectTriggerActionsForNode(node: CanvasNode): void {\n\t\tif (!hasTriggerActions(node)) return\n\n\t\tfor (const triggerAction of node.triggerActions) {\n\t\t\tconst triggerBinding = this.declarations.file.dedupe(\n\t\t\t\t\"trigger\",\n\t\t\t\tSafeJS.fn(\n\t\t\t\t\tthis.imports.addImport(\"framer\", { exportSpecifier: \"createTrigger\" }),\n\t\t\t\t\tcleanTrigger(triggerAction.trigger),\n\t\t\t\t),\n\t\t\t)\n\t\t\tconst currentTriggerActions = this.triggerActionByNode.get(node.id) ?? []\n\t\t\tthis.triggerActionByNode.set(node.id, [\n\t\t\t\t...currentTriggerActions,\n\t\t\t\tthis.getTriggerActionProps(node, triggerAction, triggerBinding),\n\t\t\t])\n\n\t\t\tif (triggerAction.action.type === \"setComponentVariant\") {\n\t\t\t\t// we need a top level hook to set the variant based on the trigger state\n\t\t\t\tthis.declarations.component.dedupe(\n\t\t\t\t\t\"triggers\",\n\t\t\t\t\tSafeJS.fn(this.imports.addImport(\"framer\", { exportSpecifier: \"useTriggers\" })),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getTriggerActionProps(\n\t\tnode: CanvasNode,\n\t\ttriggerAction: TriggerAction,\n\t\ttriggerBinding: SafeJS,\n\t): CollectedTriggerAction {\n\t\tconst targetId = getTriggerTargetId(node.id, triggerAction.action.type)\n\t\tconst baseProps: CollectedTriggerAction = {\n\t\t\ttriggerId: `${node.id}-${triggerAction.id}`,\n\t\t\ttargetId,\n\t\t\tbinding: triggerBinding,\n\t\t}\n\t\tswitch (triggerAction.action.type) {\n\t\t\tcase \"showOverlay\": {\n\t\t\t\tassert(node.parentid, \"Parent ID is required for showOverlay trigger action\")\n\t\t\t\tthis.overlays.addOverlayTrigger(node.id, node.parentid)\n\t\t\t\tconst overlayBinding = this.overlays.bindingsByOverlayId.get(node.id)\n\t\t\t\tassert(overlayBinding, \"Overlay binding is required for showOverlay trigger action\")\n\t\t\t\treturn { ...baseProps, overlayBinding }\n\t\t\t}\n\t\t\tcase \"setComponentVariant\":\n\t\t\t\treturn {\n\t\t\t\t\t...baseProps,\n\t\t\t\t\tsetVariantBinding: js`triggers.hasTriggered(${baseProps.triggerId}) && ${SafeJS.fromValue(triggerAction.action.variant)}`,\n\t\t\t\t}\n\t\t}\n\t}\n}\n\n/** Removes any empty rules from the trigger to reduce obsolete generated code.  */\nfunction cleanTrigger(trigger: Trigger): Trigger {\n\tconst cookies = cleanArray(trigger.cookies?.rules, rule => rule.key)\n\tconst urlParams = cleanArray(trigger.urlParams?.rules, rule => rule.key)\n\n\treturn {\n\t\t...trigger,\n\t\teventHistory: cleanArray(trigger.eventHistory, rule => rule.eventId),\n\t\tcookies: trigger.cookies && cookies ? { ...trigger.cookies, rules: cookies } : undefined,\n\t\turlParams: trigger.urlParams && urlParams ? { ...trigger.urlParams, rules: urlParams } : undefined,\n\t\tincludeRoutes: cleanArray(trigger.includeRoutes, rule => rule.route),\n\t\texcludeRoutes: cleanArray(trigger.excludeRoutes, rule => rule.route),\n\t\tpageCount: trigger.pageCount && trigger.pageCount > 1 ? trigger.pageCount : undefined,\n\t}\n}\n\nfunction cleanArray<T>(array: T[] | undefined, predicate: (item: T) => unknown): T[] | undefined {\n\tconst filtered = array?.filter(predicate)\n\treturn filtered?.length ? filtered : undefined\n}\n", "import {\n\tassert,\n\ttype GlobalModuleId,\n\ttype ModuleExportIdentifierString,\n\tasGlobalId,\n\tisModuleExportIdentifier,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { CreateDeduplicatedDynamicValueBinding } from \"code-generation/jsx/createDeduplicatedDynamicValueBinding.ts\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { type VariableReference, isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { WithCodeComponent } from \"document/models/CanvasTree/traits/WithCodeComponent.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport type { VectorSetItemControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { projectVectorSetIdentifier, vectorInfoForIdentifier } from \"utils/vectorSets.ts\"\nimport type { ImportCollector } from \"./ImportCollector.ts\"\n\n/**\n * Collects the Global Module Ids of Vector Sets that are exposed as controls to a dependent\n * component. This makes it easy to import the required Vector Sets into an external project on\n * paste.\n *\n * These annotations are always accurate, as the global id of a Vector Set variable can never\n * change. The variable can only be deleted.\n *\n * In that case, it is possible that dependents that haven't been serialized since a dependent\n * removed a Vector Set variable, can cause those no longer used sets to be imported. This should be\n * rare and unlikely to be problematic.\n */\nexport class VectorSetCollector {\n\tprivate readonly sets = new Set<GlobalModuleId>()\n\n\tconstructor(\n\t\tprivate readonly imports: ImportCollector,\n\t\tprivate readonly tree: CanvasTree,\n\t\tprivate readonly modulesStore: ModulesStore,\n\t\tprivate readonly createBinding: CreateDeduplicatedDynamicValueBinding,\n\t) {}\n\n\tresolveVariableInstance(node: CanvasNode & WithCodeComponent) {\n\t\tassert(isVariableReference(node.dynamicVectorSetIdentifier), \"Vector set identifier must be a variable reference\")\n\t\tassert(isModuleExportIdentifier(node.codeComponentIdentifier), \"Code component identifier must be a module\")\n\n\t\tconst parsed = parseModuleIdentifier(node.codeComponentIdentifier)\n\t\tconst moduleId = vectorInfoForIdentifier(parsed, this.tree, this.modulesStore)?.set.moduleId\n\t\tif (moduleId) this.sets.add(moduleId)\n\n\t\t// Bind with a capitalized name since it's a ComponentType<>.\n\t\treturn this.createBinding(node.dynamicVectorSetIdentifier, node, \"Icon\")\n\t}\n\n\tresolveControl(\n\t\tvalue: VariableReference | ModuleExportIdentifierString | undefined,\n\t\tcontrol: VectorSetItemControlDescription,\n\t\tnode: CanvasNode,\n\t): SafeJS | undefined {\n\t\tif (isVariableReference(value)) {\n\t\t\tthis.sets.add(asGlobalId(control.setModuleId))\n\t\t\t// Bind with a capitalized name since it's a ComponentType<>.\n\t\t\treturn this.createBinding(value, node, \"Icon\")\n\t\t}\n\n\t\tassert(isModuleExportIdentifier(value), \"Vector set item must be a module export identifier\")\n\n\t\tconst identifier = projectVectorSetIdentifier(this.tree, control, value)\n\t\tif (!identifier) return undefined\n\n\t\treturn this.imports.addModuleImport(identifier)\n\t}\n\n\tannotation() {\n\t\tif (this.sets.size === 0) return\n\n\t\treturn JSON.stringify(Array.from(this.sets))\n\t}\n}\n", "import type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\n\n/**\n * Historically, all nodes were always serialized into motion elements\n * (motion.div, motion.a, etc). Nowadays, we have heuristics that serialize\n * nodes into plain HTML elements (div, a, etc) where possible, to reduce\n * sites\u2019 TBT. This class stores and returns whether a node should be serialized\n * into a Motion element.\n */\nexport class NodeRendersWithMotion {\n\t#map = new Map<NodeID, boolean>()\n\t#getMapKey(nodeInPrimaryOrReplica: CanvasNode): string {\n\t\t// We key by `getPrimaryId()`, for all variants of a given node. That\u2019s because all variants\n\t\t// of a given node are guaranteed to serialize in the same way (motion or plain HTML), so\n\t\t// there\u2019s no need to key by replica variant IDs.\n\t\treturn nodeInPrimaryOrReplica.getPrimaryId()\n\t}\n\tset(node: CanvasNode, rendersWithMotion: boolean): void {\n\t\tthis.#map.set(this.#getMapKey(node), rendersWithMotion)\n\t}\n\tget(node: CanvasNode): boolean | undefined {\n\t\treturn this.#map.get(this.#getMapKey(node))\n\t}\n}\n", "import type { CanvasNode, LoadedWebPageNode } from \"document/models/CanvasTree/index.ts\"\nimport { withLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport type { IsBreakpoint, IsVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\n\nfunction hasValidLayout(node: CanvasNode & IsVariant & IsBreakpoint): boolean {\n\treturn withLayout(node) && node.layout === \"stack\" && node.stackDirection === \"vertical\"\n}\n\nexport function webPageAcceptsLayoutTemplate(webPage: LoadedWebPageNode): boolean {\n\treturn hasValidLayout(webPage.getPrimaryVariant()) && webPage.getReplicaVariants().every(hasValidLayout)\n}\n", "import { assertNever, getLogger } from \"@framerjs/shared\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type {\n\tComponentDeclarationCollector,\n\tJSXDeclarationCollector,\n\tNodeDeclarationCollector,\n} from \"code-generation/utils/DeclarationCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type { ValueTransformCollector } from \"code-generation/utils/valueTransformCollector/ValueTransformCollector.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isDataRepeater } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { ComputedValue } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport { isComputedValue, isComputedValueFromFetchData } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport type { DynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { hasRepeatArray } from \"document/models/CanvasTree/traits/WithRepeatArray.ts\"\nimport type { VariableID } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isRepeaterVariableIdAvailableToNonRepeatedChildren } from \"document/utils/RepeaterVariables.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { getOriginalRepeatedItemOfDataRepeater } from \"utils/repeaterUtils.ts\"\nimport { forEachVariableReferenceOfDynamicValue } from \"utils/updateDynamicValues.ts\"\n\nconst logger = getLogger(\"createDeduplicatedDynamicValueBinding\")\n\nexport type CreateDeduplicatedDynamicValueBinding = <T extends CanvasNode>(\n\tvalue: DynamicValue,\n\tnode: T,\n\tname: string,\n\t/**\n\t * Optionally provide a function that further transforms the value before creating a binding.\n\t */\n\ttransform?: (value: SafeJS) => SafeJS,\n\toutputControl?: ControlDescription,\n) => SafeJS\n\nfunction findLowestDeclarationCollectorWithConsumedVariablesInScope(\n\tconsumer: CanvasNode,\n\ttree: CanvasTree,\n\tproviderIdsToConsumedVariableIds: Map<NodeID, VariableID[]>,\n\tdeclarations: JSXDeclarationCollector,\n): NodeDeclarationCollector | ComponentDeclarationCollector {\n\tconst anyRepeaterProviders = Array.from(providerIdsToConsumedVariableIds.keys()).some(id => {\n\t\tconst provider = tree.get(id)\n\t\treturn isDataRepeater(provider) || hasRepeatArray(provider)\n\t})\n\n\tif (!anyRepeaterProviders) return declarations.component\n\n\t// Node-level repeaters can provide variables that are consumed by the same node.\n\t// We must check the consumer itself before walking ancestors, because the walk\n\t// starts at consumer.parentid and would otherwise miss this scope.\n\tconst consumerVariableIds = providerIdsToConsumedVariableIds.get(consumer.getPrimaryId())\n\tif (consumerVariableIds) {\n\t\tconst provider = tree.get(consumer.getPrimaryId())\n\t\tif (hasRepeatArray(provider)) {\n\t\t\treturn declarations.forScope(provider.id, \"repeater-item\")\n\t\t}\n\t}\n\n\tlet node = tree.get(consumer.parentid)\n\t// Track the last node we visited so we can see which branch of the repeater\n\t// we have walked up when we find one.\n\tlet lastNode = consumer\n\twhile (node) {\n\t\t// Only return repeater nodes that are ancestors of the consumer node.\n\t\t// If the repeater is not an ancestor of the consuming node, we can't\n\t\t// create a binding in the right scope to access the values.\n\t\t//\n\t\t// We may be in a replica tree, and the provider may be in the primary\n\t\t// tree. In that case, we must check the primary id.\n\t\tconst variableIds = providerIdsToConsumedVariableIds.get(node.getPrimaryId())\n\t\tif (variableIds) {\n\t\t\tconst provider = tree.get(node.getPrimaryId())\n\t\t\tif (hasRepeatArray(provider)) {\n\t\t\t\treturn declarations.forScope(provider.id, \"repeater-item\")\n\t\t\t}\n\t\t\tif (isDataRepeater(provider)) {\n\t\t\t\tconst repeatedChild = getOriginalRepeatedItemOfDataRepeater(tree, provider)\n\t\t\t\tconst needsRepeatedChildOnlyVariable = variableIds.some(\n\t\t\t\t\tvariableId => !isRepeaterVariableIdAvailableToNonRepeatedChildren(variableId),\n\t\t\t\t)\n\t\t\t\t// If the node we walked up from before encountering the provider is not the repeated child of the repeater,\n\t\t\t\t// but we need a variable available only to repeated children, we can't create a binding in the right scope.\n\t\t\t\tif (needsRepeatedChildOnlyVariable && repeatedChild?.getPrimaryId() !== lastNode.getPrimaryId()) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\"Trying to consume a repeater variable available only to repeated children from another child. Falling back to component scope. This will result in undefined values.\",\n\t\t\t\t\t)\n\t\t\t\t\treturn declarations.component\n\t\t\t\t}\n\t\t\t\treturn declarations.forScope(provider.id, needsRepeatedChildOnlyVariable ? \"repeater-item\" : \"repeater\")\n\t\t\t}\n\t\t}\n\t\tlastNode = node\n\t\tnode = tree.get(node.parentid)\n\t}\n\n\tlogger.warn(\n\t\t\"Dynamic value consumes variables from a repeater but cannot find a suitable scope. Falling back to component scope. This will result in undefined values.\",\n\t)\n\treturn declarations.component\n}\n\nfunction identity<T>(value: T): T {\n\treturn value\n}\n\nfunction getProviderIdsToConsumedVariableIds(computedValue: ComputedValue) {\n\tconst providerIds = new Map<NodeID, VariableID[]>()\n\tforEachVariableReferenceOfDynamicValue(computedValue, variableReference => {\n\t\tif (!variableReference.providerId) return\n\t\tconst variableIds = providerIds.get(variableReference.providerId) ?? []\n\t\tproviderIds.set(variableReference.providerId, [...variableIds, variableReference.id])\n\t})\n\treturn providerIds\n}\n\nexport const makeCreateDeduplicatedDynamicValueBinding =\n\t(\n\t\ttree: CanvasTree,\n\t\tdeclarations: JSXDeclarationCollector,\n\t\tvariables: VariableCollector,\n\t\tvalueTransforms: ValueTransformCollector,\n\t): CreateDeduplicatedDynamicValueBinding =>\n\t(value, node, name, transform = identity, outputControl = undefined): SafeJS => {\n\t\tif (isVariableReference(value)) {\n\t\t\t// @TODO - This transform will not be deduplicated, consider doing\n\t\t\t// that in future so that transforms are not recalculated unnecessarily.\n\t\t\treturn transform(variables.create(value))\n\t\t}\n\n\t\tif (isComputedValue(value)) {\n\t\t\tconst transformed = transform(valueTransforms.createComputedValue(value, node, outputControl))\n\n\t\t\tif (isComputedValueFromFetchData(value)) {\n\t\t\t\t// Data fetches rely on bindings which are provided by wrapping a\n\t\t\t\t// <Fetcher> component around layers that use fetched data.\n\t\t\t\t// Because this binding is provided via a children render\n\t\t\t\t// function the fetched data cannot be deduped and must be\n\t\t\t\t// declared inline.\n\t\t\t\treturn transformed\n\t\t\t}\n\n\t\t\tconst declarationCollector = findLowestDeclarationCollectorWithConsumedVariablesInScope(\n\t\t\t\tnode,\n\t\t\t\ttree,\n\t\t\t\tgetProviderIdsToConsumedVariableIds(value),\n\t\t\t\tdeclarations,\n\t\t\t)\n\t\t\treturn declarationCollector.dedupe(name, transformed)\n\t\t}\n\n\t\t// All dynamic value types should be handled.\n\t\tassertNever(value)\n\t}\n", "import { ModuleType, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { Var } from \"code-generation/components/GeneratedVariantComponentVars.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { PreloadCollector } from \"code-generation/loader/PreloadCollector.ts\"\nimport { SimulatedDOM } from \"code-generation/simulatedDOM/SimulatedDOM.ts\"\nimport { AppearIdCollector } from \"code-generation/utils/AppearIdCollector.ts\"\nimport { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport { CSSCollector } from \"code-generation/utils/CSSCollector.ts\"\nimport { CSSVariableDefinitionCollector } from \"code-generation/utils/CSSVariableDefinitionCollector.ts\"\nimport { ConditionalRenderingCollector } from \"code-generation/utils/ConditionalRenderingCollector.ts\"\nimport { CustomCursorCollector } from \"code-generation/utils/CustomCursorCollector.ts\"\nimport { JSXDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport { ElementIdCollector } from \"code-generation/utils/ElementIdCollector.ts\"\nimport { ErrorCollector } from \"code-generation/utils/ErrorCollector.ts\"\nimport { EventCollector } from \"code-generation/utils/EventCollector.ts\"\nimport { FetchDataCollector } from \"code-generation/utils/FetchDataCollector.ts\"\nimport { FontCollector } from \"code-generation/utils/FontCollector.ts\"\nimport { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport { KitSectionsStructureCollector } from \"code-generation/utils/KitSectionStructureCollector.ts\"\nimport { LayoutTemplateHitTargetAnnotationCollector } from \"code-generation/utils/LayoutTemplateHitTargetAnnotationCollector.ts\"\nimport { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport { ModuleLocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport { MetricsCollector } from \"code-generation/utils/MetricsCollector.ts\"\nimport { OverlayCollector } from \"code-generation/utils/OverlayCollector.ts\"\nimport { TrackingIdCollector } from \"code-generation/utils/TrackingIdCollector.ts\"\nimport { TriggerActionCollector } from \"code-generation/utils/TriggerActionCollector.ts\"\nimport { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport { VectorSetCollector } from \"code-generation/utils/VectorSetCollector.ts\"\nimport { ValueTransformCollector } from \"code-generation/utils/valueTransformCollector/ValueTransformCollector.ts\"\nimport { getScopeTypeForScope } from \"document/base-engine/BaseScopeStore.ts\"\nimport { isStatusGestureVariant } from \"document/components/chrome/properties/utils/gestureStatusVariant.ts\"\nimport type {\n\tAnyCanvasPageNode,\n\tAnyDesignPageNode,\n\tAnySmartComponentNode,\n\tAnyWebPageNode,\n\tCanvasNode,\n\tCanvasPageNode,\n\tDesignPageNode,\n\tNodeID,\n\tSmartComponentNode,\n\tWebPageNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type { AnyLayoutTemplateNode, LayoutTemplateNode } from \"document/models/CanvasTree/nodes/LayoutTemplateNode.ts\"\nimport type { AnyVectorSetNode, VectorSetNode } from \"document/models/CanvasTree/nodes/VectorSetNode.ts\"\nimport {\n\tisCanvasPageNode,\n\tisDesignPageNode,\n\tisLayoutTemplateNode,\n\tisSmartComponentNode,\n\tisVectorSetNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport { isGestureVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { NodeRendersWithMotion } from \"document/models/CanvasTree/traits/collectStyles/nodeRendersWithMotion.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { assert } from \"library/utils/assert.ts\"\nimport { randomBase62 } from \"utils/base62.ts\"\nimport { webPageAcceptsLayoutTemplate } from \"utils/layoutTemplates.ts\"\nimport { makeCreateDeduplicatedDynamicValueBinding } from \"./createDeduplicatedDynamicValueBinding.ts\"\nimport type { JSXElementProps } from \"./jsxAttributesForNode.ts\"\nimport type { JSXContext, JSXEngineDependencies, PackageDependencies } from \"./types.ts\"\nimport { defaultJSXMetrics } from \"./types.ts\"\n\nexport function getModuleTypeForScope(\n\tscopeNode:\n\t\t| AnyCanvasPageNode\n\t\t| AnyWebPageNode\n\t\t| AnySmartComponentNode\n\t\t| AnyLayoutTemplateNode\n\t\t| AnyVectorSetNode\n\t\t| AnyDesignPageNode,\n): ModuleType {\n\tif (isCanvasPageNode(scopeNode)) return ModuleType.Screen\n\tif (isVectorSetNode(scopeNode)) return ModuleType.Vector\n\tif (isDesignPageNode(scopeNode)) return ModuleType.Design\n\n\tconst { type } = parseModuleIdentifier(scopeNode.instanceIdentifier)\n\treturn type\n}\n\n/**\n * Create a context object to both provide dependencies required for generating\n * SafeJS jsx from a tree of CanvasNodes, as well as store metadata collected\n * while doing so.\n */\nexport function createJSXContext(\n\tsourceNode: CanvasNode,\n\tscopeNode: CanvasPageNode | WebPageNode | SmartComponentNode | LayoutTemplateNode | VectorSetNode | DesignPageNode,\n\t{ componentLoader, tree, modulesStore, engineChanges, assetMap }: JSXEngineDependencies,\n\treservedWords: Set<string> = new Set(),\n\tserializationId: string = `framer-${randomBase62(5)}`,\n\tllmSnapshot: boolean = false,\n): JSXContext {\n\tconst moduleType = getModuleTypeForScope(scopeNode)\n\n\tconst bindings = new BindingCollector(...reservedWords)\n\tconst imports = new ImportCollector(moduleType, componentLoader, modulesStore, bindings)\n\t// As we are creating JSX, we must ensure React is in scope.\n\timports.addImport(\"react\", { exportSpecifier: \"*\", importBinding: \"React\" })\n\n\tconst errors = new ErrorCollector(\n\t\tscopeNode.id,\n\t\tisCanvasPageNode(scopeNode) ? sourceNode.id : scopeNode.id,\n\t\tmoduleType,\n\t)\n\tconst scopeType = getScopeTypeForScope(scopeNode)\n\tassert(\n\t\tscopeType !== ScopeType.ContentManagement &&\n\t\t\tscopeType !== ScopeType.Analytics &&\n\t\t\tscopeType !== ScopeType.LocalizationGlossary &&\n\t\t\tscopeType !== ScopeType.Routes &&\n\t\t\tscopeType !== ScopeType.CustomCode,\n\t\t\"Content management, Analytics, Localization glossary, Routes & Custom Code nodes cannot be code-generated\",\n\t)\n\tconst declarations = new JSXDeclarationCollector(bindings)\n\tconst variables = new VariableCollector(scopeNode, bindings)\n\n\tconst assets = new AssetCollector(assetMap)\n\tconst links = new LinkCollector(scopeNode, componentLoader, imports, bindings, variables, tree, modulesStore, () => {\n\t\tconst useRouter = imports.addImport(\"framer\", { exportSpecifier: \"useRouter\" })\n\t\treturn declarations.component.dedupe(\"router\", SafeJS.fn(useRouter))\n\t})\n\tconst preload = new PreloadCollector(scopeNode, tree, variables, declarations.file, bindings, imports, assets)\n\tconst fetches = new FetchDataCollector(bindings, variables, preload, assets, links)\n\tconst localizedValues = new ModuleLocalizedValueCollector(\n\t\tscopeNode,\n\t\tvariables,\n\t\ttree,\n\t\tcomponentLoader,\n\t\timports,\n\t\tdeclarations,\n\t\tfetches,\n\t\tmodulesStore,\n\t\tmoduleType,\n\t)\n\n\tconst valueTransforms = new ValueTransformCollector(\n\t\tcomponentLoader,\n\t\tdeclarations.file,\n\t\tdeclarations.component,\n\t\timports,\n\t\tvariables,\n\t\tlocalizedValues,\n\t\tlinks,\n\t\tfetches,\n\t\tmodulesStore,\n\t\tmoduleType,\n\t)\n\tconst elementIds = new ElementIdCollector(\n\t\tscopeNode,\n\t\tcomponentLoader,\n\t\tbindings,\n\t\tdeclarations,\n\t\timports,\n\t\tvariables,\n\t\ttree,\n\t)\n\tconst trackingIds = new TrackingIdCollector(componentLoader)\n\tconst renderFunctions = new ConditionalRenderingCollector(declarations.component, scopeNode, sourceNode.id)\n\tconst createDeduplicatedDynamicValueBinding = makeCreateDeduplicatedDynamicValueBinding(\n\t\ttree,\n\t\tdeclarations,\n\t\tvariables,\n\t\tvalueTransforms,\n\t)\n\tconst cssVariableDefinitions = new CSSVariableDefinitionCollector(\n\t\tscopeNode,\n\t\tvariables,\n\t\ttree,\n\t\tvalueTransforms,\n\t\tcreateDeduplicatedDynamicValueBinding,\n\t)\n\tconst css = new CSSCollector(scopeNode, sourceNode, serializationId, cssVariableDefinitions)\n\tconst overlays = new OverlayCollector({ tree, bindings })\n\n\tconst fonts = new FontCollector(declarations.font)\n\tconst events = new EventCollector(\n\t\tsourceNode,\n\t\tcomponentLoader,\n\t\ttree,\n\t\tvariables,\n\t\tbindings,\n\t\timports,\n\t\tassets,\n\t\tlinks,\n\t\tfonts,\n\t\tfetches,\n\t\tvalueTransforms,\n\t\toverlays,\n\t\t{ type: moduleType },\n\t)\n\tconst triggerActions = new TriggerActionCollector({\n\t\tdeclarations,\n\t\timports,\n\t\toverlays,\n\t})\n\n\tconst componentPresetIds = new Set<NodeID>()\n\n\tconst metrics = new MetricsCollector(defaultJSXMetrics())\n\tconst packageDependencies = new Set<string>()\n\tconst packages: PackageDependencies = {\n\t\tdependencies: packageDependencies,\n\t\taddDependency: (name: string) => packageDependencies.add(name),\n\t}\n\n\tconst variants = withReplicaVariants(scopeNode) && !llmSnapshot ? scopeNode.getReplicaVariants() : []\n\tconst topLevelVariantsWithGestures: Record<NodeID, boolean> = {}\n\tif (isSmartComponentNode(scopeNode)) {\n\t\tfor (const variant of variants) {\n\t\t\tif (!isGestureVariant(variant) || isStatusGestureVariant(variant.gesture)) continue\n\t\t\ttopLevelVariantsWithGestures[variant.replicaInfo.inheritsFrom ?? variant.replicaInfo.master] = true\n\t\t}\n\t}\n\n\tconst appearIds = new AppearIdCollector(tree, bindings)\n\tconst customCursors = new CustomCursorCollector(\n\t\tscopeNode,\n\t\tcomponentLoader,\n\t\tfonts,\n\t\timports,\n\t\tdeclarations.file,\n\t\tvariables,\n\t\tmodulesStore,\n\t\ttree,\n\t)\n\n\tconst kitSectionsStructure = new KitSectionsStructureCollector(modulesStore, tree, componentLoader)\n\tconst hitTargets = new LayoutTemplateHitTargetAnnotationCollector(scopeNode)\n\tconst vectorSets = new VectorSetCollector(imports, tree, modulesStore, createDeduplicatedDynamicValueBinding)\n\tconst simulatedDOM = new SimulatedDOM(\n\t\tcomponentLoader,\n\t\ttree,\n\t\tvariables,\n\t\tvalueTransforms,\n\t\timports,\n\t\tdeclarations.component,\n\t)\n\n\t// Create a \"hidden\" variable as the children prop for the slot node.\n\tconst layoutTemplateSlotBinding = isLayoutTemplateNode(scopeNode) ? Var.children : undefined\n\n\treturn {\n\t\ttype: \"jsxContext\",\n\n\t\tcomponentLoader,\n\t\tmodulesStore,\n\t\tengineChanges,\n\t\tassetMap,\n\t\tsimulatedDOM,\n\t\ttree,\n\n\t\t// Variants\n\t\tvariants,\n\t\ttopLevelVariantsWithGestures,\n\n\t\t// Collectors\n\t\timports,\n\t\terrors,\n\t\tvariables,\n\t\tfetches,\n\t\tassets,\n\t\tvalueTransforms,\n\t\telementIds,\n\t\tcss,\n\t\trenderFunctions,\n\t\toverlays,\n\t\tevents,\n\t\tlinks,\n\t\tfonts,\n\t\tmetrics,\n\t\tpackages,\n\t\tappearIds,\n\t\tbindings,\n\t\tdeclarations,\n\t\tpreload,\n\t\tlocalizedValues,\n\t\tcomponentPresetIds,\n\t\trenderAsListNodes: new Map(),\n\t\tnodesRenderedAsImageInAnyVariant: new Set(),\n\t\trepeaterInfo: new Map(),\n\t\trenderConditions: new Map(),\n\t\tnodesWithAnyGradientFill: new Map(),\n\t\tcustomCursors,\n\t\tcssVariableDefinitions,\n\t\tformIds: new Set(),\n\t\thitTargets,\n\t\tcreateDeduplicatedDynamicValueBinding,\n\t\ttrackingIds,\n\t\tvectorSets,\n\t\tkitSectionsStructure,\n\t\toverlayProps: new Map<NodeID, JSXElementProps | undefined>(),\n\t\ttriggerActions,\n\n\t\t// Flags\n\t\tllmSnapshot,\n\t\tscopeId: scopeNode.id,\n\t\tscopeType,\n\t\tmoduleType: moduleType,\n\t\trootId: sourceNode.id,\n\t\tlinkClassName: css.addRule({ display: \"block\" }, scopeNode),\n\t\tlayoutTemplateSlotBinding,\n\t\tnodeRendersWithMotion: new NodeRendersWithMotion(),\n\t\tserializationId,\n\t\tacceptsLayoutTemplate:\n\t\t\t// @TODO - Hundreds of tests create a JSX Context with a Web Page node that\n\t\t\t// doesn't have a primary variant. As such this fails unintentionally.\n\t\t\t// Ideally we should not have to check baseVariantId as it must always be\n\t\t\t// defined, but we do to avoid rewriting tests.\n\t\t\tisWebPageNode(scopeNode) && scopeNode.isLoaded() && scopeNode.baseVariantId\n\t\t\t\t? webPageAcceptsLayoutTemplate(scopeNode)\n\t\t\t\t: undefined,\n\t}\n}\n\n/**\n * For testing simple functions that require a JSXContext, but do not need the\n * entire context to be properly setup.\n */\nexport function createStubbedJSXContext(stub?: Partial<JSXContext>): JSXContext {\n\treturn {\n\t\ttype: \"jsxContext\",\n\t\t...stub,\n\t} as unknown as JSXContext\n}\n", "import { assert, isEmptyObject } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport type { MakeSerializable } from \"code-generation/types.ts\"\nimport type {\n\tComponentDeclarationCollector,\n\tJSXDeclarationCollector,\n\tNodeDeclarationCollector,\n} from \"code-generation/utils/DeclarationCollector.ts\"\nimport {\n\tgetQueryDefaultCollectionAlias,\n\tgetQueryForDataRepeater,\n\tgetQueryVariableNames,\n} from \"code-generation/utils/valueTransformCollector/getQueryForDataRepeater.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { CollectionRepeater, DataRepeater } from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport { isDataRepeater } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { CombinedVariableProviderControlMap } from \"document/models/CanvasTree/traits/VariableProvider.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { HasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport type { WithCollectionOptions } from \"document/models/CanvasTree/traits/WithCollectionOptions.ts\"\nimport { hasPaginationEnabled } from \"document/models/CanvasTree/traits/WithCollectionOptions.ts\"\nimport { hasRepeatArray } from \"document/models/CanvasTree/traits/WithRepeatArray.ts\"\nimport { type Expression, FunctionName, type Query } from \"library/modules/cms/types.ts\"\nimport { isEqual } from \"library/render/utils/isEqual.ts\"\nimport { isRepeatedItem } from \"utils/repeaterUtils.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport type { JSXElementProps, ProcessedVariantProps } from \"./jsxAttributesForNode.ts\"\nimport type { AncestorInfo, JSXContext, ProcessedVariantsFlags } from \"./types.ts\"\nimport { getReplicaNode } from \"./utils.ts\"\n\ninterface GetQueryDataPropsOptions {\n\tctx: JSXContext\n\tancestorInfo: AncestorInfo\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps\n\t/** Variable IDs contained in all variants, including the primary.\n\t *\n\t * TODO: Ideally we'd only use variable IDs specific to each variant,\n\t * resulting in less duplication. But we'd have to change how the\n\t * `VariableCollector` works.\n\t */\n\tusedVariableIds: Set<string>\n\t/** Data repeater to reference in the specific variant. */\n\tdataRepeater: CanvasNode & HasCollectionDataSource & WithCollectionOptions\n\tprimaryCombinedControlMap: CombinedVariableProviderControlMap\n\tshouldInlineQuery: boolean\n\tvariantId: NodeID\n}\n\n/** Creates query props for the `QueryData` component. */\nfunction getQueryDataProps({\n\tctx,\n\tancestorInfo,\n\tjsxAttributes,\n\tusedVariableIds,\n\tdataRepeater,\n\tprimaryCombinedControlMap,\n\tshouldInlineQuery,\n\tvariantId,\n}: GetQueryDataPropsOptions): SerializableObject {\n\tconst variableDependencies: VariableReference[] = []\n\n\tconst subqueries = jsxAttributes.subqueries\n\tconst parentSubqueries = ancestorInfo.subqueries\n\n\tconst query = getQueryForDataRepeater(\n\t\tdataRepeater,\n\t\tprimaryCombinedControlMap,\n\t\tusedVariableIds,\n\t\t(variable): Expression => {\n\t\t\t// If we inline this query into an ancestor, we need to replace the\n\t\t\t// variable with query identifiers.\n\t\t\tif (shouldInlineQuery) {\n\t\t\t\tlet currentSubqueries = parentSubqueries\n\t\t\t\twhile (currentSubqueries) {\n\t\t\t\t\tif (variable.providerId === currentSubqueries.repeaterNode.id) {\n\t\t\t\t\t\tconst defaultCollectionAlias = getQueryDefaultCollectionAlias(currentSubqueries.repeaterNode)\n\n\t\t\t\t\t\tconst [collectionAlias, variableName] = getQueryVariableNames(variable.id, defaultCollectionAlias)\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"Identifier\",\n\t\t\t\t\t\t\tname: variableName,\n\t\t\t\t\t\t\tcollection: collectionAlias,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentSubqueries = currentSubqueries.parent\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert(ctx.variables, \"VariableCollector is required\")\n\t\t\tvariableDependencies.push(variable)\n\n\t\t\treturn {\n\t\t\t\ttype: \"LiteralValue\",\n\t\t\t\tvalue: ctx.variables.create(variable),\n\t\t\t}\n\t\t},\n\t\tdataIdentifier => {\n\t\t\tconst binding = ctx.imports.addModuleImport(dataIdentifier)\n\t\t\tassert(binding, \"Can't import collection\")\n\t\t\treturn binding\n\t\t},\n\t)\n\n\tassert(subqueries, \"Subqueries must exist\")\n\n\tconst variantSubqueries = subqueries.getSubqueries(variantId)\n\tfor (const [childRepeaterId, subquery] of variantSubqueries) {\n\t\tquery.select.push({\n\t\t\ttype: \"FunctionCall\",\n\t\t\tfunctionName: FunctionName.Array,\n\t\t\talias: childRepeaterId,\n\t\t\targuments: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"Select\",\n\t\t\t\t\t...subquery,\n\t\t\t\t},\n\t\t\t],\n\t\t})\n\t}\n\n\tconst subqueryVariableDependencies = subqueries.getVariableDependencies(variantId)\n\tvariableDependencies.push(...subqueryVariableDependencies)\n\n\tconst serializableQuery = query as MakeSerializable<Query>\n\n\tif (shouldInlineQuery) {\n\t\tassert(parentSubqueries, \"Parent subqueries must exist\")\n\t\tparentSubqueries.addSubquery(variantId, dataRepeater.getPrimaryId(), query)\n\t\tparentSubqueries.addVariableDependencies(variantId, variableDependencies)\n\t\t// Inlined queries can't use constants - return inline\n\t\treturn new SerializableObject({ query: serializableQuery, pageSize: dataRepeater.collectionPaginationPageSize })\n\t}\n\n\t// Add to loading variant preload (for gesture transitions)\n\tctx.preload.addQuery(dataRepeater, serializableQuery, variableDependencies)\n\n\t// Add to route loader collection and get constant binding\n\t// Pass variable dependencies so the query function accepts them as parameters\n\tconst queryConstant = ctx.preload.addRouteLoaderQuery(dataRepeater, serializableQuery, variableDependencies)\n\n\treturn new SerializableObject({ query: queryConstant, pageSize: dataRepeater.collectionPaginationPageSize })\n}\n\n/**\n * Get whether we should inline the query into the parent repeater.\n */\nfunction getShouldInlineQuery(\n\tancestorInfo: AncestorInfo,\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps,\n): boolean {\n\tif (isUndefined(ancestorInfo.subqueries)) return false\n\n\t// We can't inline queries if the data repeater is paginated, because the\n\t// parent query will not have the pagination variables in scope. Check the\n\t// comment in `jsxAttributesForNode` for more details.\n\tif (jsxAttributes.isAnyVariantPaginated) return false\n\n\treturn ancestorInfo.inRepeatedItem ?? false\n}\n\n/**\n * Collection repeaters generate a query data element that provides a JS scope for declarations,\n * unless the query is inlined ({@link getShouldInlineQuery}). For any repeater item count\n * declaration we need an ancestor JS scope, so for cases without an own scope we hoist to the\n * nearest ancestor repeater scope (data repeater or node-level repeat).\n */\nexport function hoistedDeclarationScope(\n\tnodeInPrimary: CanvasNode,\n\ttree: CanvasTree,\n\tdeclarations: JSXDeclarationCollector,\n): NodeDeclarationCollector | ComponentDeclarationCollector {\n\tlet child = nodeInPrimary\n\tfor (const parent of nodeInPrimary.ancestors()) {\n\t\tif (isDataRepeater(parent)) {\n\t\t\treturn declarations.forScope(parent.id, isRepeatedItem(tree, child, parent) ? \"repeater-item\" : \"repeater\")\n\t\t}\n\n\t\tif (hasRepeatArray(parent)) {\n\t\t\treturn declarations.forScope(parent.id, \"repeater-item\")\n\t\t}\n\n\t\tchild = parent\n\t}\n\n\treturn declarations.component\n}\n\nexport function getQueryDataElementProps(\n\tnodeInPrimary: CollectionRepeater,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps,\n\tusedVariableIds: Set<string>,\n): JSXElementProps | null {\n\tconst primaryCombinedControlMap = jsxAttributes.inheritedControlMap\n\tassert(primaryCombinedControlMap, \"Primary variant combined control map must be defined.\")\n\n\tconst shouldInlineQuery = getShouldInlineQuery(ancestorInfo, jsxAttributes)\n\n\t// Create query for primary.\n\tconst queryProps = getQueryDataProps({\n\t\tctx,\n\t\tancestorInfo,\n\t\tjsxAttributes,\n\t\tusedVariableIds,\n\t\tdataRepeater: nodeInPrimary,\n\t\tprimaryCombinedControlMap,\n\t\tshouldInlineQuery,\n\t\tvariantId: \"primary\",\n\t})\n\n\t// Create query for all other variants.\n\tconst overrideProps: Record<NodeID, SerializableObject> = {}\n\n\tfor (const variant of ctx.variants) {\n\t\t// Nodes inside slots are not inside the variant, but we still need to\n\t\t// create queries for them. As slots can't be overridden in variants, we\n\t\t// can use the primary node instead.\n\t\tconst nodeInVariant = getReplicaNode(variant, nodeInPrimary.id, ctx.tree) ?? nodeInPrimary\n\t\tassert(isDataRepeater(nodeInVariant), \"Node must be a data repeater\")\n\n\t\tconst variantQueryProps = getQueryDataProps({\n\t\t\tctx,\n\t\t\tancestorInfo,\n\t\t\tjsxAttributes,\n\t\t\tusedVariableIds,\n\t\t\tdataRepeater: nodeInVariant,\n\t\t\tprimaryCombinedControlMap,\n\t\t\tshouldInlineQuery,\n\t\t\tvariantId: variant.id,\n\t\t})\n\n\t\tif (isEqual(queryProps, variantQueryProps)) continue\n\n\t\toverrideProps[variant.id] = variantQueryProps\n\t}\n\n\t// If this query is inlined into an ancestor repeater we don't need to\n\t// create a `QueryData` component.\n\tif (shouldInlineQuery) {\n\t\treturn null\n\t}\n\n\treturn { props: queryProps, overrides: isEmptyObject(overrideProps) ? undefined : overrideProps }\n}\n\nfunction createQueryDataBody(repeater: DataRepeater, ctx: JSXContext): SafeJS {\n\tconst useQueryDataBinding = ctx.imports.addImport(\"framer\", {\n\t\texportSpecifier: \"useQueryData\",\n\t})\n\n\tif (hasPaginationEnabled(repeater)) {\n\t\tconst useLoadMorePaginatedQueryBinding = ctx.imports.addImport(\"framer\", {\n\t\t\texportSpecifier: \"useLoadMorePaginatedQuery\",\n\t\t})\n\n\t\tconst paginatedQueryBinding = js`paginatedQuery`\n\n\t\treturn js.joinLines(\n\t\t\tjs`const { ${paginatedQueryBinding}, paginationInfo, loadMore } = ${useLoadMorePaginatedQueryBinding}(query, pageSize, ${repeater.id})`,\n\t\t\tjs`const data = ${SafeJS.fn(useQueryDataBinding, paginatedQueryBinding)}`,\n\t\t\tjs`return children(data, paginationInfo, loadMore)`,\n\t\t)\n\t}\n\n\treturn js.joinLines(js`const data = ${SafeJS.fn(useQueryDataBinding, js`query`)}`, js`return children(data)`)\n}\n\nexport function createQueryDataComponent(repeater: DataRepeater, ctx: JSXContext) {\n\treturn js`({ query, pageSize, children }) => {\n        ${createQueryDataBody(repeater, ctx)}\n    }`\n}\n", "import type { JSXContext } from \"code-generation/jsx/types.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\n\n/**\n * Determines from the context whether a node should be rendered as a list item (li) which is a special case that overrides the default htmlTag in some cases\n */\nexport function shouldNodeUseListItem({ renderAsListNodes }: JSXContext, node: CanvasNode): boolean {\n\tif (!node.parentid) return false\n\treturn renderAsListNodes.has(node.parentid)\n}\n", "import { shouldNodeUseListItem } from \"code-generation/utils/shouldNodeUseListItem.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { defaultHTMLTag, withHTMLTag } from \"document/models/CanvasTree/traits/WithHTMLTag.ts\"\nimport { hasLink, withLink } from \"document/models/CanvasTree/traits/WithLink.ts\"\nimport { scopeTypeSupportsA11yFeatures } from \"document/models/CanvasTree/traits/utils/scopeTypeSupportsA11yFeatures.ts\"\nimport type { JSXContext, ProcessedVariantsFlags } from \"./types.ts\"\n\nexport function componentForNode(\n\tctx: JSXContext,\n\tnode: CanvasNode,\n\t{ isAnyVariantALink }: Partial<Pick<ProcessedVariantsFlags, \"isAnyVariantALink\">>,\n\trendersWithMotion: boolean,\n) {\n\tconst motionPrefixOrNoop = rendersWithMotion ? \"motion.\" : \"\"\n\n\tif (withLink(node) && (hasLink(node) || isAnyVariantALink)) return `${motionPrefixOrNoop}a`\n\tif (shouldNodeUseListItem(ctx, node)) return `${motionPrefixOrNoop}li`\n\n\tif (withHTMLTag(node) && node.htmlTag && scopeTypeSupportsA11yFeatures(ctx.scopeType)) {\n\t\treturn `${motionPrefixOrNoop}${node.htmlTag}`\n\t}\n\treturn `${motionPrefixOrNoop}${defaultHTMLTag}`\n}\n", "import { getPackageModuleInfo } from \"@framerjs/framer-runtime\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ModuleExportIdentifier } from \"@framerjs/shared\"\nimport {\n\tassert,\n\tModuleType,\n\tassertNever,\n\tisModuleExportIdentifier,\n\tlocalModuleIdForStableName,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { MakeSerializablePrimitives } from \"code-generation/types.ts\"\nimport type { ComposedImport } from \"code-generation/utils/ImportCollector.ts\"\nimport { moduleImportSpecifiers } from \"code-generation/utils/ImportCollector.ts\"\nimport {\n\tbuiltInComponentName,\n\tisBuiltInComponent,\n\tnodeNeedsContainer,\n} from \"code-generation/utils/builtInCodeComponents.ts\"\nimport type { CanvasNode, CodeComponentNode, ShaderNode } from \"document/models/CanvasTree/index.ts\"\nimport { getPageNodeIdForPrototype } from \"document/models/CanvasTree/nodes/utils/getPageNodeIdForPrototype.ts\"\nimport {\n\tisCodeComponentNode,\n\tisCollectionRepeater,\n\tisDynamicVectorInstance,\n\tisFrameNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isSmartComponentInstance } from \"document/models/CanvasTree/nodes/utils/smartComponentInstanceHelpers.ts\"\nimport { withCodeComponent } from \"document/models/CanvasTree/traits/WithCodeComponent.ts\"\nimport { hasPaginationEnabled } from \"document/models/CanvasTree/traits/WithCollectionOptions.ts\"\nimport { isRepeaterLoaderInstance } from \"document/models/CanvasTree/traits/WithDataLoaderVariants.ts\"\nimport { hasImageFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { hasFlowEffect, isFlowEffectSupportedScopeType } from \"document/models/CanvasTree/traits/WithFlowEffect.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport type { WithCodeBoundaryForOverridesParams } from \"library/modules/code-boundary/withCodeBoundaryForOverrides.tsx\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport { isArray, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { ClassDiscriminator } from \"utils/withClassDiscriminator.ts\"\nimport { componentForNode } from \"./componentForNode.ts\"\nimport { createCodeOverrides, getValidOverrideImportSpecifiers } from \"./getValidOverrideImportSpecifiers.ts\"\nimport type { AncestorInfo, JSXContext, ProcessedVariantsFlags } from \"./types.ts\"\n\ntype Flags = Pick<\n\tPartial<ProcessedVariantsFlags>,\n\t| \"isAnyVariantAnImage\"\n\t| \"isAnyVariantAnEffect\"\n\t| \"isAnyVariantOptimizedAppearEffect\"\n\t| \"isAnyVariantAVariantAppearEffect\"\n\t| \"isAnyVariantATickerEffect\"\n\t| \"isAnyVariantALink\"\n\t| \"identifiers\"\n\t| \"isAnyVariantColumnMasonryLayout\"\n>\n\n/**\n * Code components that need to have their positioning handled by a container\n * use different components depending on the context. Additionally, these\n * components also host *some* of the nodes effects.\n */\nexport function jsxTagNameForComponentContainer(\n\tnode: CodeComponentNode | ShaderNode,\n\tctx: JSXContext,\n\t{ isAnyVariantAnEffect, isAnyVariantOptimizedAppearEffect }: ProcessedVariantsFlags,\n\tancestorInfo: AncestorInfo,\n): SafeJS {\n\tconst composeWithImports: SafeJS[] = []\n\n\tif (isAnyVariantAnEffect) {\n\t\tcomposeWithImports.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withFX\" }))\n\t}\n\n\tif (isAnyVariantOptimizedAppearEffect) {\n\t\tcomposeWithImports.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withOptimizedAppearEffect\" }))\n\t}\n\n\tconst repeaterNode = ctx.tree.get(ancestorInfo.lastRepeaterId)\n\tif (\n\t\tisCollectionRepeater(repeaterNode) &&\n\t\thasPaginationEnabled(repeaterNode) &&\n\t\tisRepeaterLoaderInstance(node, repeaterNode)\n\t) {\n\t\tcomposeWithImports.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withInfiniteScroll\" }))\n\t}\n\n\tif (ctx.scopeType === ScopeType.SmartComponent) {\n\t\treturn ctx.imports.addImport(\"framer\", {\n\t\t\texportSpecifier: \"SmartComponentScopedContainer\",\n\t\t\tcomposeWithImports,\n\t\t})\n\t} else {\n\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"Container\", composeWithImports })\n\t}\n}\n\n/**\n * When a Smart Component instance has code overrides, we want to provide a good\n * API experience by remapping the React properties that have been\n * code-generated with immutable variable id keys, to the human readable ones.\n * This ensures that users can access `props.opacity`, but Framer can code\n * generate `as7fd7h={0.7}`.\n */\nfunction maybeCreateOverridePropMap(node: CanvasNode, ctx: JSXContext): ComposedImport | undefined {\n\tif (!isSmartComponentInstance(ctx.tree, node)) return\n\n\t// Smart Components that do not have immutable variable names do not need\n\t// mapping.\n\tconst supportsMappedVariables = !!ctx.componentLoader.reactComponentForIdentifier(node.codeComponentIdentifier)\n\t\t?.annotations?.[AnnotationKey.FramerImmutableVariables]\n\tif (!supportsMappedVariables) return\n\n\tconst moduleIdentifier = parseModuleIdentifier(node.codeComponentIdentifier)\n\tif (!isModuleExportIdentifier(moduleIdentifier)) return\n\n\tconst { importSpecifier, importBinding } = moduleImportSpecifiers(\n\t\tmoduleIdentifier,\n\t\tctx.moduleType,\n\t\tctx.componentLoader,\n\t\tctx.modulesStore,\n\t)\n\n\tif (!importSpecifier) return\n\n\tconst infoBinding = ctx.imports.addImport(importSpecifier, {\n\t\texportSpecifier: \"*\",\n\t\timportBinding: `${importBinding}Info`,\n\t})\n\n\treturn [ctx.imports.addImport(\"framer\", { exportSpecifier: \"withMappedReactProps\" }), infoBinding]\n}\n\nfunction higherOrderComponentImportsForNode(\n\tnode: CanvasNode,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n\tflags: Pick<\n\t\tFlags,\n\t\t| \"isAnyVariantAnEffect\"\n\t\t| \"isAnyVariantOptimizedAppearEffect\"\n\t\t| \"isAnyVariantAVariantAppearEffect\"\n\t\t| \"isAnyVariantATickerEffect\"\n\t\t| \"isAnyVariantColumnMasonryLayout\"\n\t>,\n) {\n\tconst bindings: ComposedImport[] = []\n\n\t// Prototype screens need to generate dynamic layout ids. Rather than\n\t// importing FrameWithMotion, we wrap a motion.div in a higher order\n\t// component that provides just the layoutId generation behavior of\n\t// FrameWithMotion.\n\tif (isFrameNode(node) && ctx.scopeType === ScopeType.CanvasPage) {\n\t\tbindings.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withGeneratedLayoutId\" }))\n\t}\n\n\tif (flags.isAnyVariantColumnMasonryLayout) {\n\t\tbindings.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withColumnMasonryLayout\" }))\n\t}\n\n\tconst overrideImport = createOverrideImportForNode(node, ctx, ancestorInfo)\n\tif (overrideImport) bindings.push(overrideImport)\n\n\tconst stackedCodeOverrides = createCodeOverrides(node, ctx)\n\tbindings.push(...stackedCodeOverrides)\n\n\t// If we have any overrides, and if the node is a smart component instance\n\t// that has a FramerImmutableVariables on its Annotations, we can add a\n\t// final Higher Order Component wrapper that ensures that the prop object\n\t// provided to the user overrides is keyed by the human readable React\n\t// property name, rather than the immutable id.\n\tif (overrideImport || stackedCodeOverrides.length > 0) {\n\t\tconst mapImport = maybeCreateOverridePropMap(node, ctx)\n\t\tif (mapImport) bindings.push(mapImport)\n\t}\n\n\tif (flags.isAnyVariantAVariantAppearEffect) {\n\t\tbindings.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withVariantAppearEffect\" }))\n\t}\n\n\t// If we are collecting for a code component/shader, and we are not collecting for its container,\n\t// return early. Parallax and style appear effects are not supported on code component elements\n\t// since we don't know if the element will support the hoc.\n\t//\n\t// Vector instances don't use a container, so should not early return.\n\tif (nodeNeedsContainer(node)) return bindings\n\n\tif (hasFlowEffect(node) && isFlowEffectSupportedScopeType(ctx.scopeType)) {\n\t\tbindings.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withFlowFX\" }))\n\t}\n\n\tif (flags.isAnyVariantAnEffect) {\n\t\tbindings.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withFX\" }))\n\t}\n\n\tif (flags.isAnyVariantOptimizedAppearEffect) {\n\t\tbindings.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withOptimizedAppearEffect\" }))\n\t}\n\n\tif (flags.isAnyVariantATickerEffect) {\n\t\tbindings.push(ctx.imports.addImport(\"framer\", { exportSpecifier: \"withTickerFX\" }))\n\t}\n\n\treturn bindings\n}\n\nexport type SerializableCodeBoundaryOverridesParams = MakeSerializablePrimitives<\n\tWithCodeBoundaryForOverridesParams<unknown>\n>\n\nfunction createOverrideImportForNode(\n\tnode: CanvasNode,\n\tctx: Pick<JSXContext, \"componentLoader\" | \"moduleType\" | \"modulesStore\" | \"imports\" | \"scopeId\">,\n\tancestorInfo: AncestorInfo,\n): SafeJS | [SafeJS, SerializableCodeBoundaryOverridesParams] | undefined {\n\tconst specifiers = getValidOverrideImportSpecifiers(node, ctx)\n\tif (!specifiers) return\n\n\tconst { importSpecifier, exportSpecifier } = specifiers\n\n\tconst overrideControls: SerializableCodeBoundaryOverridesParams = {\n\t\tscopeId: ctx.scopeId,\n\t\tnodeId: node.getPrimaryId(),\n\t\toverride: ctx.imports.addImport(importSpecifier, { exportSpecifier }),\n\t\tinComponentSlot: ancestorInfo.inComponentSlot ? true : undefined,\n\t}\n\n\treturn [ctx.imports.addImport(\"framer\", { exportSpecifier: \"withCodeBoundaryForOverrides\" }), overrideControls]\n}\n\nfunction recordPackageDependencies(identifier: ModuleExportIdentifier, ctx: JSXContext) {\n\tif (identifier.kind !== \"localModuleExport\") return\n\n\tconst { localId } = identifier\n\tconst persistedModule = ctx.modulesStore.getPersistedModuleByLocalId(localId)\n\tconst dependencies = persistedModule?.metadata[ModuleMetadata.PackageDependencies]\n\tif (isArray(dependencies)) {\n\t\tdependencies.forEach(name => {\n\t\t\tif (isString(name)) ctx.packages.addDependency(name)\n\t\t})\n\t}\n}\n\n/**\n * A Framer prototype component renders the generated prototype that it contains\n * as its children. Since this node is not itself represented by a Code\n * Component node, we need to look it up and import it.\n */\nexport function jsxTagNameForFramerPrototype(node: CodeComponentNode, ctx: JSXContext) {\n\tconst pageNodeId = getPageNodeIdForPrototype(node, ctx.componentLoader)\n\tif (!pageNodeId) return undefined\n\n\tconst prototypeModuleId = localModuleIdForStableName(ModuleType.Prototype, pageNodeId)\n\treturn ctx.imports.addImport(`../${prototypeModuleId}`, {\n\t\texportSpecifier: \"default\",\n\t\timportBinding: \"Prototype\",\n\t})\n}\n\ntype SerializableClassDiscriminator =\n\t| ClassDiscriminator.BooleanShapeNode\n\t| ClassDiscriminator.CodeComponentNode\n\t| ClassDiscriminator.FormBooleanInputNode\n\t| ClassDiscriminator.FormPlainTextInputNode\n\t| ClassDiscriminator.FormSelectNode\n\t| ClassDiscriminator.FrameNode\n\t| ClassDiscriminator.OvalShapeNode\n\t| ClassDiscriminator.OverlayNode\n\t| ClassDiscriminator.PathNode\n\t| ClassDiscriminator.PolygonShapeNode\n\t| ClassDiscriminator.RectangleShapeNode\n\t| ClassDiscriminator.RichTextNode\n\t| ClassDiscriminator.ShaderNode\n\t| ClassDiscriminator.ShapeContainerNode\n\t| ClassDiscriminator.ShapeGroupNode\n\t| ClassDiscriminator.StarShapeNode\n\t| ClassDiscriminator.SVGNode\n\t| ClassDiscriminator.TextNode\n\nfunction isSerializableClassDiscriminator(\n\tclassDiscriminator: ClassDiscriminator,\n): classDiscriminator is SerializableClassDiscriminator {\n\tswitch (classDiscriminator) {\n\t\tcase ClassDiscriminator.BooleanShapeNode:\n\t\tcase ClassDiscriminator.CodeComponentNode:\n\t\tcase ClassDiscriminator.FormBooleanInputNode:\n\t\tcase ClassDiscriminator.FormPlainTextInputNode:\n\t\tcase ClassDiscriminator.FormSelectNode:\n\t\tcase ClassDiscriminator.FrameNode:\n\t\tcase ClassDiscriminator.OvalShapeNode:\n\t\tcase ClassDiscriminator.OverlayNode:\n\t\tcase ClassDiscriminator.PathNode:\n\t\tcase ClassDiscriminator.PolygonShapeNode:\n\t\tcase ClassDiscriminator.RectangleShapeNode:\n\t\tcase ClassDiscriminator.RichTextNode:\n\t\tcase ClassDiscriminator.ShaderNode:\n\t\tcase ClassDiscriminator.ShapeContainerNode:\n\t\tcase ClassDiscriminator.ShapeGroupNode:\n\t\tcase ClassDiscriminator.StarShapeNode:\n\t\tcase ClassDiscriminator.SVGNode:\n\t\tcase ClassDiscriminator.TextNode: {\n\t\t\t// This check is there to make sure that all the cases in\n\t\t\t// SerializableClassDiscriminator are present in the above switch\n\t\t\tconst _: SerializableClassDiscriminator = classDiscriminator\n\t\t\treturn true\n\t\t}\n\t\tcase ClassDiscriminator.AbTestsEntityTypeRootNode:\n\t\tcase ClassDiscriminator.AgentPanelTool:\n\t\tcase ClassDiscriminator.AgentDragSelectTool:\n\t\tcase ClassDiscriminator.AgentSelectTool:\n\t\tcase ClassDiscriminator.AnalyticsScopeNode:\n\t\tcase ClassDiscriminator.BlockquoteEntityTypeRootNode:\n\t\tcase ClassDiscriminator.BlockquoteStylePresetNode:\n\t\tcase ClassDiscriminator.BoxShadow:\n\t\tcase ClassDiscriminator.BranchNode:\n\t\tcase ClassDiscriminator.BranchesNode:\n\t\tcase ClassDiscriminator.CanvasNode:\n\t\tcase ClassDiscriminator.CanvasPageNode:\n\t\tcase ClassDiscriminator.CanvasScopeNode:\n\t\tcase ClassDiscriminator.ChatTool:\n\t\tcase ClassDiscriminator.CMSEntityTypeRootNode:\n\t\tcase ClassDiscriminator.CodeFileEntityTypeRootNode:\n\t\tcase ClassDiscriminator.CollectionReferenceVariableEditTool:\n\t\tcase ClassDiscriminator.CollectionItemNode:\n\t\tcase ClassDiscriminator.CollectionNode:\n\t\tcase ClassDiscriminator.Color:\n\t\tcase ClassDiscriminator.ColorEntityTypeRootNode:\n\t\tcase ClassDiscriminator.ColorStyleTokenListNode:\n\t\tcase ClassDiscriminator.ColorStyleTokenNode:\n\t\tcase ClassDiscriminator.ComponentEntityTypeRootNode:\n\t\tcase ClassDiscriminator.ComponentPresetNode:\n\t\tcase ClassDiscriminator.ConicGradient:\n\t\tcase ClassDiscriminator.ContentManagementNode:\n\t\tcase ClassDiscriminator.CreateCodeComponentBaseTool:\n\t\tcase ClassDiscriminator.CreateFrameBaseTool:\n\t\tcase ClassDiscriminator.CreateShapeBaseTool:\n\t\tcase ClassDiscriminator.CreateTextTool:\n\t\tcase ClassDiscriminator.CustomCodeScopeNode:\n\t\tcase ClassDiscriminator.CustomCodeNode:\n\t\tcase ClassDiscriminator.DateVariableEditTool:\n\t\tcase ClassDiscriminator.DesignPageNode:\n\t\tcase ClassDiscriminator.EntityFolderNode:\n\t\tcase ClassDiscriminator.EntityReferenceNode:\n\t\tcase ClassDiscriminator.EntityRootNode:\n\t\tcase ClassDiscriminator.ErrorListNode:\n\t\tcase ClassDiscriminator.ErrorNode:\n\t\tcase ClassDiscriminator.ExportOptions:\n\t\tcase ClassDiscriminator.EnumVariableEditTool:\n\t\tcase ClassDiscriminator.ExternalModuleNode:\n\t\tcase ClassDiscriminator.ExternalModulesListNode:\n\t\tcase ClassDiscriminator.FeedbackTool:\n\t\tcase ClassDiscriminator.FunnelNode:\n\t\tcase ClassDiscriminator.FunnelsEntityTypeRootNode:\n\t\tcase ClassDiscriminator.FunnelStepActionNode:\n\t\tcase ClassDiscriminator.FunnelStepNode:\n\t\tcase ClassDiscriminator.GapTool:\n\t\tcase ClassDiscriminator.GradientColorStop:\n\t\tcase ClassDiscriminator.GradientToolManagerTool:\n\t\tcase ClassDiscriminator.GuideMoveTool:\n\t\tcase ClassDiscriminator.HeaderRouteNode:\n\t\tcase ClassDiscriminator.HighlightStackItemTool:\n\t\tcase ClassDiscriminator.HighlightTool:\n\t\tcase ClassDiscriminator.ImageStylePresetNode:\n\t\tcase ClassDiscriminator.InitialTool:\n\t\tcase ClassDiscriminator.InlineCodeEntityTypeRootNode:\n\t\tcase ClassDiscriminator.InlineCodeStylePresetNode:\n\t\tcase ClassDiscriminator.LayoutTemplateEntityTypeRootNode:\n\t\tcase ClassDiscriminator.LayoutTemplateNode:\n\t\tcase ClassDiscriminator.LineAnchorMoveTool:\n\t\tcase ClassDiscriminator.LinearGradient:\n\t\tcase ClassDiscriminator.LinkEntityTypeRootNode:\n\t\tcase ClassDiscriminator.LinkStylePresetNode:\n\t\tcase ClassDiscriminator.LinkTool:\n\t\tcase ClassDiscriminator.LoadingShieldTool:\n\t\tcase ClassDiscriminator.LocalizationGlossaryItemNode:\n\t\tcase ClassDiscriminator.LocalizationGlossaryNode:\n\t\tcase ClassDiscriminator.LocalModuleNode:\n\t\tcase ClassDiscriminator.LocalModulesListNode:\n\t\tcase ClassDiscriminator.MoveTool:\n\t\tcase ClassDiscriminator.MutableNode:\n\t\tcase ClassDiscriminator.PaddingTool:\n\t\tcase ClassDiscriminator.PageLinkTool:\n\t\tcase ClassDiscriminator.PanTool:\n\t\tcase ClassDiscriminator.PathCurveBendTool:\n\t\tcase ClassDiscriminator.PathDefaultTool:\n\t\tcase ClassDiscriminator.PathSegment:\n\t\tcase ClassDiscriminator.PathSegmentAdditionTool:\n\t\tcase ClassDiscriminator.PathSegmentHandleMoveTool:\n\t\tcase ClassDiscriminator.PathSegmentMoveTool:\n\t\tcase ClassDiscriminator.PathSegmentSelectTool:\n\t\tcase ClassDiscriminator.PresetsListNode:\n\t\tcase ClassDiscriminator.PreviewSettings:\n\t\tcase ClassDiscriminator.ProxyRouteNode:\n\t\tcase ClassDiscriminator.RadialGradient:\n\t\tcase ClassDiscriminator.RadiusTool:\n\t\tcase ClassDiscriminator.RecoveryTool:\n\t\tcase ClassDiscriminator.RedirectRouteNode:\n\t\tcase ClassDiscriminator.ResizeTool:\n\t\tcase ClassDiscriminator.RewriteRouteNode:\n\t\tcase ClassDiscriminator.RichTextEditTool:\n\t\tcase ClassDiscriminator.RichTextVariableEditTool:\n\t\tcase ClassDiscriminator.RootNode:\n\t\tcase ClassDiscriminator.RotateTool:\n\t\tcase ClassDiscriminator.RouteNode:\n\t\tcase ClassDiscriminator.RouteLocaleNode:\n\t\tcase ClassDiscriminator.RouteSegmentNode:\n\t\tcase ClassDiscriminator.RouteSegmentRootNode:\n\t\tcase ClassDiscriminator.RoutesNode:\n\t\tcase ClassDiscriminator.SampleColorTool:\n\t\tcase ClassDiscriminator.ScaleTool:\n\t\tcase ClassDiscriminator.ScopeNode:\n\t\tcase ClassDiscriminator.SelectTool:\n\t\tcase ClassDiscriminator.Shadow:\n\t\tcase ClassDiscriminator.SlotConnectTool:\n\t\tcase ClassDiscriminator.SlotNode:\n\t\tcase ClassDiscriminator.SlotPropertyNode:\n\t\tcase ClassDiscriminator.ContentManagementEntityTypeRootNode:\n\t\tcase ClassDiscriminator.SmartComponentNode:\n\t\tcase ClassDiscriminator.StringVariableEditTool:\n\t\tcase ClassDiscriminator.StyledTextDraft:\n\t\tcase ClassDiscriminator.TableStylePresetNode:\n\t\tcase ClassDiscriminator.TestTool:\n\t\tcase ClassDiscriminator.TextEditTool:\n\t\tcase ClassDiscriminator.TextEntityTypeRootNode:\n\t\tcase ClassDiscriminator.TextStylePresetNode:\n\t\tcase ClassDiscriminator.VectorSetEntityTypeRootNode:\n\t\tcase ClassDiscriminator.VectorSetNode:\n\t\tcase ClassDiscriminator.VekterGradientTool:\n\t\tcase ClassDiscriminator.VekterPathEngine:\n\t\tcase ClassDiscriminator.VekterTool:\n\t\tcase ClassDiscriminator.ViewportResizeTool:\n\t\tcase ClassDiscriminator.WebPageNode:\n\t\tcase ClassDiscriminator.ZoomSelectTool:\n\t\tcase ClassDiscriminator.ZoomTool: {\n\t\t\t// This check is there to make sure that all the cases in not\n\t\t\t// included in SerializableClassDiscriminator are present in the\n\t\t\t// above switch\n\t\t\tconst _: Exclude<ClassDiscriminator, SerializableClassDiscriminator> = classDiscriminator\n\t\t\treturn false\n\t\t}\n\t\tdefault:\n\t\t\tassertNever(classDiscriminator)\n\t}\n}\n\n/**\n * Determine the name of the jsx tag that a node should be rendered with when\n * code generated. This may not be all of the jsx elements that a node must be\n * transformed into, but is always the innermost, including any higher order\n * components like some page fx. If it is required that a node be wrapped in\n * several layers of JSX tags, that is handled elsewhere.\n *\n * Unsupported nodes will cause this function to throw.\n */\nexport function jsxTagNameForNode(node: CanvasNode, ctx: JSXContext, ancestorInfo: AncestorInfo, flags: Flags): SafeJS {\n\tif (!isSerializableClassDiscriminator(node.__class)) {\n\t\tthrow Error(`jsxTagNameForNode: ${node.__class} does not support serialization to JSX.`)\n\t}\n\n\t// Determine any higher order components that the node needs to be wrapped\n\t// in.\n\tconst composeWithImports = higherOrderComponentImportsForNode(node, ctx, ancestorInfo, flags)\n\n\tswitch (node.__class) {\n\t\tcase ClassDiscriminator.SVGNode:\n\t\tcase ClassDiscriminator.ShapeContainerNode:\n\t\t// VECTOR @TODO: consider reusing the SVG serializer for inline shapes.\n\t\tcase ClassDiscriminator.BooleanShapeNode:\n\t\tcase ClassDiscriminator.OvalShapeNode:\n\t\tcase ClassDiscriminator.PathNode:\n\t\tcase ClassDiscriminator.PolygonShapeNode:\n\t\tcase ClassDiscriminator.RectangleShapeNode:\n\t\tcase ClassDiscriminator.ShapeGroupNode:\n\t\tcase ClassDiscriminator.StarShapeNode:\n\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"SVG\", composeWithImports })\n\t\tcase ClassDiscriminator.TextNode:\n\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"Text\", composeWithImports })\n\t\tcase ClassDiscriminator.RichTextNode:\n\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"RichText\", composeWithImports })\n\t\tcase ClassDiscriminator.FrameNode: {\n\t\t\tif (isFormContainer(node)) {\n\t\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"FormContainer\", composeWithImports })\n\t\t\t}\n\t\t\tif (hasImageFill(node) || flags.isAnyVariantAnImage) {\n\t\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"Image\", composeWithImports })\n\t\t\t}\n\n\t\t\tconst rendersWithMotion = ctx.nodeRendersWithMotion.get(node)\n\t\t\tassert(!isUndefined(rendersWithMotion), \"Node must have had `rendersWithMotion` computed for it.\")\n\n\t\t\tconst component = componentForNode(ctx, node, flags, rendersWithMotion)\n\t\t\tif (rendersWithMotion) {\n\t\t\t\treturn ctx.imports.addImport(\"framer-motion\", {\n\t\t\t\t\texportSpecifier: component,\n\t\t\t\t\tcomposeWithImports,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\treturn new SafeJS(component)\n\t\t\t}\n\t\t}\n\n\t\tcase ClassDiscriminator.CodeComponentNode: {\n\t\t\tassert(withCodeComponent(node), \"Nodes with a ClassDiscriminator of CodeComponentNode must be a Code Component\")\n\n\t\t\tif (isBuiltInComponent(node)) {\n\t\t\t\treturn ctx.imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: builtInComponentName(node),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// If the code component is a dynamic vector instance, we use an Instance component to\n\t\t\t// be able to wrap it in effects. If there are multiple identifiers, we need to use an\n\t\t\t// Instance as well to be able to change the ComponentType via props.\n\t\t\tif (isDynamicVectorInstance(node) || (flags.identifiers && flags.identifiers.size > 1)) {\n\t\t\t\treturn ctx.imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"Instance\",\n\t\t\t\t\tcomposeWithImports,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst moduleIdentifier = parseModuleIdentifier(node.codeComponentIdentifier)\n\t\t\tif (!isModuleExportIdentifier(moduleIdentifier)) {\n\t\t\t\tconst packageModuleInfo = getPackageModuleInfo(node.codeComponentIdentifier)\n\t\t\t\tassert(packageModuleInfo, \"A package must have module information to be included in code-generation.\")\n\n\t\t\t\tctx.packages.addDependency(packageModuleInfo.packageName)\n\n\t\t\t\treturn ctx.imports.addImport(packageModuleInfo.moduleURL, {\n\t\t\t\t\texportSpecifier: packageModuleInfo.exportIdentifier,\n\t\t\t\t\t// Packages do not support fx, but they require a legacy HOC\n\t\t\t\t\t// to support legacy width and height props.\n\t\t\t\t\tcomposeWithImports: [ctx.imports.addImport(\"framer\", { exportSpecifier: \"withMeasuredSize\" })],\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tassert(isModuleExportIdentifier(moduleIdentifier), \"A code component that is not a package must be a module.\")\n\n\t\t\t// For LLM snapshots, we set the import binding to \"Icon\" for vector instances.\n\t\t\t// This helps the LLM understand that the component is an icon.\n\t\t\tconst importBindingOverride =\n\t\t\t\tctx.llmSnapshot && isCodeComponentNode(node) && node.isVectorInstance ? \"Icon\" : undefined\n\n\t\t\tconst { importSpecifier, exportSpecifier, importBinding } = moduleImportSpecifiers(\n\t\t\t\tmoduleIdentifier,\n\t\t\t\tctx.moduleType,\n\t\t\t\tctx.componentLoader,\n\t\t\t\tctx.modulesStore,\n\t\t\t\tundefined,\n\t\t\t\timportBindingOverride,\n\t\t\t)\n\n\t\t\tassert(importSpecifier, \"A module must have an import specifier.\")\n\n\t\t\trecordPackageDependencies(moduleIdentifier, ctx)\n\n\t\t\tctx.fonts.addFontReference({\n\t\t\t\tcomponentIdentifier: node.codeComponentIdentifier,\n\t\t\t\tfontReference: ctx.imports.addImport(importSpecifier, {\n\t\t\t\t\texportSpecifier,\n\t\t\t\t\timportBinding,\n\t\t\t\t\tcomposeWithImports: [ctx.imports.addImport(\"framer\", { exportSpecifier: \"getFonts\" })],\n\t\t\t\t}),\n\t\t\t})\n\n\t\t\treturn ctx.imports.addImport(importSpecifier, {\n\t\t\t\texportSpecifier,\n\t\t\t\timportBinding,\n\t\t\t\tcomposeWithImports,\n\t\t\t})\n\t\t}\n\t\tcase ClassDiscriminator.OverlayNode:\n\t\t\t// Reset the outer link context (and don\u2019t do nested link replacement) since the overlay is in a portal,\n\t\t\t// and there would be no ancestor link causing the \u201Cinvalid DOM nesting\u201D issue.\n\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"ResetOuterLinkContext\" })\n\t\tcase ClassDiscriminator.FormBooleanInputNode:\n\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"FormBooleanInput\", composeWithImports })\n\t\tcase ClassDiscriminator.FormPlainTextInputNode:\n\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"FormPlainTextInput\", composeWithImports })\n\t\tcase ClassDiscriminator.FormSelectNode:\n\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"FormSelect\", composeWithImports })\n\t\tcase ClassDiscriminator.ShaderNode:\n\t\t\treturn ctx.imports.addImport(\"framer\", { exportSpecifier: \"Shader\", composeWithImports })\n\t\tdefault:\n\t\t\tassertNever(node.__class)\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport { assert, assertNever } from \"@framerjs/shared\"\nimport { arrayIdKey } from \"code-generation/components/cms/dataIdKeys.ts\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { SubqueryCollector } from \"code-generation/utils/SubqueryCollector.ts\"\nimport type { ReadonlyVariableBindings } from \"code-generation/utils/VariableCollector.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { DataRepeater } from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport { isArrayRepeater } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { VariableProviderControlMap } from \"document/models/CanvasTree/traits/VariableProvider.ts\"\nimport { createVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport type { HasAnyDataSource } from \"document/models/CanvasTree/traits/WithRepeaterDataSource.ts\"\nimport { hasDataRepeaterArray } from \"document/models/CanvasTree/traits/WithRepeaterDataSource.ts\"\nimport { getFallbackValue } from \"document/models/CanvasTree/traits/utils/codeComponentProps.ts\"\nimport {\n\tisRepeaterVariableId,\n\trepeaterItemCountVariableId,\n\trepeaterItemIndexVariableId,\n} from \"document/utils/RepeaterVariables.ts\"\nimport type { ProcessedVariantProps } from \"./jsxAttributesForNode.ts\"\nimport type { JSXContext, ProcessedVariantsFlags, RepeaterInfo } from \"./types.ts\"\n\nexport function dataRepeaterInfo(\n\tcomponentLoader: ComponentLoader,\n\tnodeInPrimary: CanvasNode & DataRepeater,\n): RepeaterInfo {\n\tif (hasCollectionDataSource(nodeInPrimary)) {\n\t\tconst entity = componentLoader.dataForIdentifier(nodeInPrimary.dataIdentifier)\n\t\tassert(entity, \"A Data Repeater must have an evaluated data entity in the sandbox.\")\n\n\t\treturn {\n\t\t\tid: nodeInPrimary.id,\n\t\t\tannotations: entity.annotations,\n\t\t}\n\t}\n\tif (hasDataRepeaterArray(nodeInPrimary)) {\n\t\treturn {\n\t\t\tid: nodeInPrimary.id,\n\t\t\tannotations: undefined,\n\t\t}\n\t}\n\tassertNever(nodeInPrimary, \"A data repeater must have either an identifier or array variable\")\n}\n\nexport function variableFallbackList(\n\tusedVariableBindings: ReadonlyVariableBindings,\n\tcontrols: VariableProviderControlMap | undefined,\n): SafeJS[] {\n\tconst list: SafeJS[] = []\n\n\tfor (const [variableId, variableBinding] of usedVariableBindings) {\n\t\tif (isRepeaterVariableId(variableId)) continue\n\n\t\tconst control = controls?.get(variableId)\n\t\tif (!control) continue\n\n\t\tconst fallbackValue = getFallbackValue(control.type)\n\t\tif (!isSerializableValue(fallbackValue)) continue\n\n\t\tlist.push(js`${variableBinding} ??= ${fallbackValue}`)\n\t}\n\n\treturn list\n}\n\nfunction keyBindingForRepeater(\n\trepeater: DataRepeater,\n\tctx: JSXContext,\n\tannotations: RepeaterInfo[\"annotations\"],\n\tindexBinding: SafeJS,\n): SafeJS {\n\tif (hasCollectionDataSource(repeater)) {\n\t\tconst recordIdProperty = annotations?.[AnnotationKey.FramerRecordIdKey]\n\t\tif (recordIdProperty) {\n\t\t\treturn ctx.variables.create(createVariableReference(recordIdProperty, repeater.id))\n\t\t}\n\t\treturn indexBinding\n\t}\n\n\treturn ctx.bindings.create(\"id\")\n}\n\nexport function dataBindingForRepeater(repeater: DataRepeater, ctx: JSXContext) {\n\tif (hasCollectionDataSource(repeater)) {\n\t\treturn ctx.bindings.createWithNode(\"collection\", repeater)\n\t}\n\tif (hasDataRepeaterArray(repeater)) {\n\t\treturn ctx.variables.create(repeater.dataRepeaterArray)\n\t}\n\tassertNever(repeater, \"parent should be a collection or array repeater\")\n}\n\nfunction mapArgsForRepeater(\n\tparent: CanvasNode & HasAnyDataSource,\n\trecordKeyBinding: SafeJS,\n\tusedVariableBindings: ReadonlyVariableBindings,\n\tsubqueries: SubqueryCollector | undefined,\n\tctx: JSXContext,\n) {\n\tconst args: Record<string, SafeJS> = {}\n\n\taddNonRepeaterVariableBindingsToArgs(args, usedVariableBindings)\n\n\tif (hasCollectionDataSource(parent)) {\n\t\tassert(subqueries, \"Subqueries must exist\")\n\n\t\tfor (const subqueryRepeaterId of subqueries.childRepeaterIds) {\n\t\t\tconst subqueryRepeater = ctx.tree.get(subqueryRepeaterId)\n\t\t\tassert(subqueryRepeater, \"Repeater node must exist\")\n\t\t\tconst subqueryBinding = ctx.bindings.createWithNode(\"collection\", subqueryRepeater)\n\t\t\targs[subqueryRepeaterId] = subqueryBinding\n\t\t}\n\t} else {\n\t\targs[arrayIdKey] = recordKeyBinding\n\t}\n\n\treturn args\n}\n\nexport function addNonRepeaterVariableBindingsToArgs(\n\targs: Record<string, SafeJS>,\n\tusedVariableBindings: ReadonlyVariableBindings,\n): void {\n\tfor (const [variableId, variableBinding] of usedVariableBindings) {\n\t\tif (isRepeaterVariableId(variableId)) continue\n\t\targs[variableId] = variableBinding\n\t}\n}\n\nexport function repeaterItemCountDeclaration(nodeId: NodeID, dataBinding: SafeJS, ctx: JSXContext): SafeJS | undefined {\n\tconst repeaterItemCountBinding = ctx.variables.getBinding(nodeId, repeaterItemCountVariableId)\n\treturn repeaterItemCountBinding && js`const ${repeaterItemCountBinding} = ${dataBinding}?.length ?? 0`\n}\n\nexport function repeaterItemIndexDeclaration(\n\tnodeId: NodeID,\n\tindexBinding: SafeJS,\n\tctx: JSXContext,\n): SafeJS | undefined {\n\tconst repeaterItemIndexBinding = ctx.variables.getBinding(nodeId, repeaterItemIndexVariableId)\n\treturn repeaterItemIndexBinding && js`const ${repeaterItemIndexBinding} = ${indexBinding} + 1`\n}\n\nexport function repeaterMapBindings(\n\trepeater: DataRepeater,\n\tannotations: RepeaterInfo[\"annotations\"],\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps,\n\tctx: JSXContext,\n\tindexBinding: SafeJS,\n) {\n\tconst recordKeyBinding = keyBindingForRepeater(repeater, ctx, annotations, indexBinding)\n\tconst repeaterDataBinding = dataBindingForRepeater(repeater, ctx)\n\n\t// WARNING: Getting the used variables needs to happen after all the variables are created\n\t// inside this function.\n\tconst usedVariableBindings = ctx.variables.getBindings(repeater.id)\n\n\tconst args = mapArgsForRepeater(repeater, recordKeyBinding, usedVariableBindings, jsxAttributes.subqueries, ctx)\n\n\tconst controls = jsxAttributes.inheritedControlMap?.get(repeater.id)\n\n\tconst itemIdCanBeUndefined = isArrayRepeater(repeater)\n\n\treturn {\n\t\t/** Arguments to destructure in the map body */\n\t\targs: js`${args}, ${indexBinding}`,\n\t\t/** Each variable used in the repeater is initialized with its fallback value */\n\t\tvariableFallbackList: variableFallbackList(usedVariableBindings, controls),\n\t\t/** The existing in-scope Javascript variable that contains the repeater data */\n\t\tdata: repeaterDataBinding,\n\t\t/** Binding to item id/key for each item of the repeater */\n\t\tkey: itemIdCanBeUndefined ? js`${recordKeyBinding} ?? ${indexBinding}` : recordKeyBinding,\n\t}\n}\n", "import type {\n\tExternalModuleExportIdentifier,\n\tModuleExportIdentifier,\n\tModuleExportIdentifierString,\n} from \"@framerjs/shared\"\nimport {\n\tassert,\n\tModuleType,\n\temptyArray,\n\tgetLogger,\n\tisEmptyObject,\n\tisExternalModuleIdentifier,\n\tisLocalModuleIdentifier,\n\tisModuleExportIdentifier,\n\tlocalModuleIdentifierForStableName,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { arrayIdKey } from \"code-generation/components/cms/dataIdKeys.ts\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { type TagTransform, js, jst, jsx } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject, isSafeJS, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport { OverlayCollector } from \"code-generation/utils/OverlayCollector.ts\"\nimport { nodeNeedsContainer } from \"code-generation/utils/builtInCodeComponents.ts\"\nimport { waitForLoadingComponentsWithTimeout } from \"code-generation/utils/waitForLoadingComponentsWithTimeout.ts\"\nimport type {\n\tCanvasNode,\n\tCanvasPageNode,\n\tCodeComponentNode,\n\tDesignPageNode,\n\tSmartComponentNode,\n\tWebPageNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { ErrorNodeReason } from \"document/models/CanvasTree/nodes/ErrorNode.ts\"\nimport type { DataRepeater } from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport type { LayoutTemplateNode } from \"document/models/CanvasTree/nodes/LayoutTemplateNode.ts\"\nimport { PresetsListNode } from \"document/models/CanvasTree/nodes/PresetsListNode.ts\"\nimport { allVariantsAreHidden } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport { getPageNodeIdForPrototype } from \"document/models/CanvasTree/nodes/utils/getPageNodeIdForPrototype.ts\"\nimport {\n\tisCodeComponentNode,\n\tisDataRepeater,\n\tisOverlayNode,\n\tisRichTextNode,\n\tisShaderNode,\n\tisShapeContainerNode,\n\tisSlotNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport {\n\tisFixedOrRelativeOverlay,\n\tisObsoleteOverlay,\n\tnodeCanTriggerOverlay,\n} from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { getChildrenSlotItems, getSlotItemsBySlotKey } from \"document/models/CanvasTree/nodes/utils/slotUtils.ts\"\nimport { isSmartComponentInstance } from \"document/models/CanvasTree/nodes/utils/smartComponentInstanceHelpers.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { hasCodeOverride } from \"document/models/CanvasTree/traits/WithCodeOverride.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { hasFloatingPosition } from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { hasColumnMasonryLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { type HasRepeatArray, hasRepeatArray } from \"document/models/CanvasTree/traits/WithRepeatArray.ts\"\nimport type { Loaded } from \"document/models/CanvasTree/traits/WithScopeLoader.ts\"\nimport { hasTickerEffect } from \"document/models/CanvasTree/traits/WithTickerEffect.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport { HardCodedCodeIdentifier } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { overlayContainerId, templateOverlayContainerId } from \"library/modules/Floating.tsx\"\nimport { randomBase62 } from \"utils/base62.ts\"\nimport { COMPONENT_PRESETS_MODULE_ID } from \"utils/componentPresetUtils.ts\"\nimport { join } from \"utils/join.ts\"\nimport { isRepeatedItem } from \"utils/repeaterUtils.ts\"\nimport { isUndefined } from \"../../../../runtime/src/utils/typeChecks.ts\"\nimport type { JSXElementProps, PrimaryJSXElementProps, ProcessedVariantProps } from \"./jsxAttributesForNode.ts\"\nimport { classNameForSlotSpacer, jsxAttributesForNode } from \"./jsxAttributesForNode.ts\"\nimport { createJSXContext } from \"./jsxContext.ts\"\nimport { createQueryDataComponent, getQueryDataElementProps, hoistedDeclarationScope } from \"./jsxForRepeater.ts\"\nimport {\n\tjsxTagNameForComponentContainer,\n\tjsxTagNameForFramerPrototype,\n\tjsxTagNameForNode,\n} from \"./jsxTagNameForNode.ts\"\nimport { FORM_STATE_BINDING } from \"./propsForNode.ts\"\nimport {\n\taddNonRepeaterVariableBindingsToArgs,\n\tdataBindingForRepeater,\n\tdataRepeaterInfo,\n\trepeaterItemCountDeclaration,\n\trepeaterItemIndexDeclaration,\n\trepeaterMapBindings,\n\tvariableFallbackList,\n} from \"./repeaterUtils.ts\"\nimport type { AncestorInfo, JSXContext, JSXEngineDependencies, ProcessedVariantsFlags } from \"./types.ts\"\nimport { getReplicaNode } from \"./utils.ts\"\n\nconst logger = getLogger(\"jsxForNode\")\n\nasync function addSlotContentToProps(\n\tnode: CodeComponentNode,\n\tctx: JSXContext,\n\tpropsForElement: PrimaryJSXElementProps,\n\tancestorInfo: AncestorInfo,\n): Promise<void> {\n\tconst slotItemsBySlotKey = getSlotItemsBySlotKey(ctx.tree, node, ctx.componentLoader)\n\tfor (const slotKey in slotItemsBySlotKey) {\n\t\tif (slotKey === \"children\") continue\n\n\t\tconst list: SafeJS[] = []\n\n\t\tconst slotItems = slotItemsBySlotKey[slotKey]\n\t\tif (!slotItems) continue\n\n\t\tfor (let i = 0; i < slotItems.length; i++) {\n\t\t\tconst slotItem = slotItems[i]\n\t\t\tif (!slotItem) continue\n\n\t\t\t// FIXME: we should set the key here (slotItem.key)\n\t\t\tconst slotJSX = await serializeNodeToJSX(slotItem.node, node, ctx, {\n\t\t\t\t...ancestorInfo,\n\t\t\t\tinComponentSlot: true,\n\t\t\t})\n\t\t\tif (slotJSX && slotJSX.length > 0) {\n\t\t\t\tlist.push(slotJSX)\n\t\t\t}\n\t\t}\n\n\t\tpropsForElement.props[slotKey] = list\n\t}\n}\n\n/**\n * Overlays and Prototype components have jsx children that are not represented\n * by CanvasNodes, so must be included specially.\n */\nfunction defaultChildrenJSX(node: CanvasNode, ctx: JSXContext, propsForElement: PrimaryJSXElementProps): string {\n\tif (isOverlayNode(node)) {\n\t\t// Overlay nodes store all information about the backdrop themselves,\n\t\t// that means we must create a backdrop div from this node's information\n\t\t// without a backing node.\n\t\treturn serializeJS(\n\t\t\tjsxTagWithOverrides(\n\t\t\t\tctx.imports.addImport(\"framer-motion\", { exportSpecifier: \"motion.div\" }),\n\t\t\t\tctx,\n\t\t\t\tpropsForElement,\n\t\t\t),\n\t\t)\n\t}\n\n\tif (isCodeComponentNode(node) && node.codeComponentIdentifier === HardCodedCodeIdentifier.prototype) {\n\t\t// Prototype components render the actual generated prototype component\n\t\t// as their child, which is not represented by a node.\n\t\tconst prototype = jsxTagNameForFramerPrototype(node, ctx)\n\t\tif (prototype) return serializeJS(jsx.tag(prototype, undefined))\n\t}\n\n\treturn \"\"\n}\n\nfunction nextRepeaterId(ancestorInfo: AncestorInfo, currentNode: CanvasNode, ctx: JSXContext) {\n\tif (isDataRepeater(currentNode)) {\n\t\tconst info = dataRepeaterInfo(ctx.componentLoader, currentNode)\n\t\tctx.repeaterInfo.set(currentNode.id, info)\n\t\treturn currentNode.id\n\t}\n\n\treturn ancestorInfo.lastRepeaterId\n}\n\nfunction getInRepeatedItem(ancestorInfo: AncestorInfo, currentNode: CanvasNode, ctx: JSXContext) {\n\tif (isDataRepeater(currentNode)) return false\n\tif (isRepeatedItem(ctx.tree, currentNode)) return true\n\tif (ancestorInfo.inRepeatedItem) return true\n\n\treturn false\n}\n\nfunction updateAncestorInfoForDescendants(\n\tancestorInfo: AncestorInfo,\n\tcurrentNode: CanvasNode,\n\tctx: JSXContext,\n\t{\n\t\titemsOrderOverrides,\n\t\thiddenInVariants,\n\t\tinheritedControlMap,\n\t\tinCodeOverride,\n\t\tsubqueries,\n\t\tkitSectionNodeId,\n\t\tisAnyVariantColumnMasonryLayout,\n\t}: ProcessedVariantsFlags,\n): AncestorInfo {\n\treturn {\n\t\t...ancestorInfo,\n\t\t// @FIXME - We always make sure we are using the \"latest\" possible\n\t\t// data-repeater binding, otherwise using the latest ancestor. This\n\t\t// could be an issue with multiple repeater bindings:\n\t\t// https://github.com/framer/company/issues/25937. We now provide a map\n\t\t// of providers to data info. We should update dependents to consume\n\t\t// that correctly.\n\t\tlastRepeaterId: nextRepeaterId(ancestorInfo, currentNode, ctx),\n\t\tinRepeatedItem: getInRepeatedItem(ancestorInfo, currentNode, ctx),\n\t\tsubqueries,\n\t\titemsOrderOverrides,\n\t\thiddenInVariants,\n\t\tinheritedControlMap,\n\t\tinCodeOverride,\n\t\tisColumnMasonryLayout: isAnyVariantColumnMasonryLayout,\n\t\tkitSectionNodeId: ancestorInfo.kitSectionNodeId ?? kitSectionNodeId,\n\t\t// If the current node is a code component, *and* it has a slot called `children`, we know that descendants\n\t\t// we\u2019ll process next are a part of that slot.\n\t\tinComponentSlot:\n\t\t\tancestorInfo.inComponentSlot ||\n\t\t\t// If a code component has children, those are slots by definition\n\t\t\t(isCodeComponentNode(currentNode) && currentNode.codeComponentIdentifier !== HardCodedCodeIdentifier.prototype),\n\t}\n}\n\n/**\n * Every CanvasNode may need more than a single jsx element to properly\n * represent all of the behaviors that it requires. In these cases we transform\n * the inner jsx by wrapping it in outer jsx.\n *\n * Theoretically any node could receive any of this wrapping JSX, so the order\n * the transforms are added is important to preserve functionality.\n */\nfunction jsxTagTransformsForNode(\n\tnode: CanvasNode,\n\tparent: CanvasNode | null,\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n): TagTransform[] {\n\tconst transforms: TagTransform[] = []\n\n\t// Wrap RichTextNode with HTML variable in ComponentPresetsProvider.\n\tconst listNode = PresetsListNode.get(ctx.tree)\n\tconst componentPresetNodes = listNode?.getComponentPresets()\n\tif (\n\t\tisRichTextNode(node) &&\n\t\tisVariableReference(node.htmlContent) &&\n\t\tcomponentPresetNodes &&\n\t\tcomponentPresetNodes.length > 0\n\t) {\n\t\tconst componentPresetsImport = ctx.imports.addImport(`../${COMPONENT_PRESETS_MODULE_ID}`, {\n\t\t\texportSpecifier: \"*\",\n\t\t\timportBinding: \"componentPresets\",\n\t\t})\n\n\t\t// Collect primary node's presets.\n\t\ttype ComponentPresetRefs = Record<string, SafeJS>\n\t\tconst primaryPresets: ComponentPresetRefs = {}\n\t\tconst primaryComponentPresets = node.getComponentPresets()\n\n\t\tfor (const [componentIdentifier, presetId] of primaryComponentPresets) {\n\t\t\tctx.componentPresetIds.add(presetId)\n\t\t\tprimaryPresets[componentIdentifier] = js`${componentPresetsImport}.props[${presetId}]`\n\t\t}\n\n\t\ttransforms.push(children =>\n\t\t\tjsx.tag(\n\t\t\t\tctx.imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"ComponentPresetsProvider\",\n\t\t\t\t}),\n\t\t\t\tnew SerializableObject({ presets: primaryPresets }),\n\t\t\t\tchildren,\n\t\t\t),\n\t\t)\n\n\t\t// Collect variant-specific presets and wrap with PropertyOverrides\n\t\t// when any variant has different component presets than the primary node.\n\t\tconst variantPresetOverrides: Record<string, { presets: ComponentPresetRefs }> = {}\n\n\t\tfor (const variant of ctx.variants) {\n\t\t\tconst replicaNode = getReplicaNode(variant, node.id, ctx.tree)\n\t\t\tif (!replicaNode || !isRichTextNode(replicaNode)) continue\n\n\t\t\tconst replicaComponentPresets = replicaNode.getComponentPresets()\n\t\t\tif (replicaComponentPresets.size === 0) continue\n\n\t\t\tconst variantPresets: ComponentPresetRefs = { ...primaryPresets }\n\t\t\tlet hasDifference = false\n\n\t\t\tfor (const [componentIdentifier, presetId] of replicaComponentPresets) {\n\t\t\t\tctx.componentPresetIds.add(presetId)\n\t\t\t\tconst presetRef = js`${componentPresetsImport}.props[${presetId}]`\n\t\t\t\tvariantPresets[componentIdentifier] = presetRef\n\n\t\t\t\tif (serializeJS(presetRef) !== serializeJS(primaryPresets[componentIdentifier])) {\n\t\t\t\t\thasDifference = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (hasDifference) {\n\t\t\t\tvariantPresetOverrides[variant.id] = { presets: variantPresets }\n\t\t\t}\n\t\t}\n\n\t\tif (!isEmptyObject(variantPresetOverrides)) {\n\t\t\ttransforms.push(children =>\n\t\t\t\tjsx.tag(\n\t\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"PropertyOverrides\" }),\n\t\t\t\t\tnew SerializableObject({\n\t\t\t\t\t\tbreakpoint: js`baseVariant`,\n\t\t\t\t\t\toverrides: variantPresetOverrides,\n\t\t\t\t\t}),\n\t\t\t\t\tchildren,\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\n\t// Wrap code components in a container to render position.\n\tif (isCodeComponentNode(node) && nodeNeedsContainer(node)) {\n\t\tinjectTriggerSubscriptionsBeforeChildren(node, ctx, transforms)\n\n\t\ttransforms.push(inner =>\n\t\t\tjsxTagWithOverrides(\n\t\t\t\tjsxTagNameForComponentContainer(node, ctx, jsxAttributes, ancestorInfo),\n\t\t\t\tctx,\n\t\t\t\tjsxAttributes.propsForContainer,\n\t\t\t\tinner,\n\t\t\t),\n\t\t)\n\t}\n\n\t// Wrap shader nodes in a container to render position.\n\tif (isShaderNode(node)) {\n\t\tinjectTriggerSubscriptionsBeforeChildren(node, ctx, transforms)\n\n\t\ttransforms.push(inner =>\n\t\t\tjsxTagWithOverrides(\n\t\t\t\tjsxTagNameForComponentContainer(node, ctx, jsxAttributes, ancestorInfo),\n\t\t\t\tctx,\n\t\t\t\tjsxAttributes.propsForContainer,\n\t\t\t\tinner,\n\t\t\t),\n\t\t)\n\t}\n\n\t// Vector Instances do not have a images so don't need to be wrapped in a\n\t// ComponentViewportProvider.\n\tif (isCodeComponentNode(node) && !node.isVectorInstance) {\n\t\ttransforms.push(inner =>\n\t\t\tjsxTagWithOverrides(\n\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"ComponentViewportProvider\" }),\n\t\t\t\tctx,\n\t\t\t\tjsxAttributes.propsForComponentViewport,\n\t\t\t\tinner,\n\t\t\t),\n\t\t)\n\t}\n\n\t// Wrap into ResolveLinks component that handles parallelized async resolving of slugs\n\tconst unresolvedNodeLinks = ctx.links.getUnresolvedLinksForNode(node)\n\tif (unresolvedNodeLinks) {\n\t\tconst { unresolvedLinks, binding } = unresolvedNodeLinks\n\t\tif (isSerializableValue(unresolvedLinks) || isUndefined(unresolvedLinks)) {\n\t\t\tconst ResolveLinks = ctx.imports.addImport(\"framer\", { exportSpecifier: \"ResolveLinks\" })\n\t\t\tconst props = new SerializableObject({ links: unresolvedLinks })\n\t\t\ttransforms.push(inner => jsxTagWithOverrides(ResolveLinks, ctx, { props }, js`(${binding}) => (${inner})`))\n\t\t}\n\t}\n\n\t// Wrap layers that need to be a link in a <Link> component.\n\tif (jsxAttributes.isAnyVariantALink) {\n\t\ttransforms.push(inner =>\n\t\t\tjsxTagWithOverrides(\n\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"Link\" }),\n\t\t\t\tctx,\n\t\t\t\tjsxAttributes.propsForLink,\n\t\t\t\tinner,\n\t\t\t),\n\t\t)\n\t}\n\n\t// For tickers we need the items to be the children of the ticker, so we make sure the CMS repeater wrapper is outside the ticker.\n\t// If we always do this it can break code components slotting cms items.\n\tif (isDataRepeater(node) && (hasTickerEffect(node) || hasColumnMasonryLayout(node))) {\n\t\tcollectRepeaterTransforms(node, ctx, ancestorInfo, jsxAttributes, transforms)\n\t}\n\n\tif (jsxAttributes.isAnyVariantATransitionOverride) {\n\t\tconst MotionConfigContext = ctx.imports.addImport(\"framer-motion\", { exportSpecifier: \"MotionConfigContext\" })\n\t\tconst React = ctx.imports.addImport(\"react\", { exportSpecifier: \"*\", importBinding: \"React\" })\n\t\t// A simplified version of MotionConfig with slightly different\n\t\t// transition cascade behavior. Setting the transition prop to undefined\n\t\t// will inherit the ancestors transition rather than erase it.\n\t\tconst context = ctx.declarations.file.dedupe(\n\t\t\tDictionary.Transition,\n\t\t\tnew SafeJS(\n\t\t\t\tjoin.lines(\n\t\t\t\t\tjs`({value, children}) => {`,\n\t\t\t\t\tjs`const config = ${React}.useContext(${MotionConfigContext})`,\n\t\t\t\t\tjs`const transition = value ?? config.transition`,\n\t\t\t\t\tjs`const contextValue = ${React}.useMemo(() => ({ ...config, transition }), [JSON.stringify(transition)])`,\n\t\t\t\t\tjs`return <${MotionConfigContext}.Provider value={contextValue}>{children}</${MotionConfigContext}.Provider>`,\n\t\t\t\t\tjs`}`,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t\ttransforms.push(children => jsxTagWithOverrides(context, ctx, jsxAttributes.propsForTransition, children))\n\t}\n\n\t// Wrap overlay triggers in the component that handles the overlay state.\n\tconst overlaysTriggeredByNode = ctx.overlays.bindingsByOverlayTriggerId.get(node.id)\n\tif (overlaysTriggeredByNode && overlaysTriggeredByNode.size > 0) {\n\t\ttransforms.push(children => jsx`<>${children}</>`)\n\n\t\tconst visible = js`visible`\n\t\tconst setVisible = js`setVisible`\n\n\t\tconst api: Record<keyof typeof OverlayCollector.Api, SafeJS> = {\n\t\t\tvisible: js`enabled && ${visible}`,\n\t\t\t[OverlayCollector.Api.show]: js`() => ${SafeJS.fn(setVisible, js`true`)}`,\n\t\t\t[OverlayCollector.Api.hide]: js`() => ${SafeJS.fn(setVisible, js`false`)}`,\n\t\t\t[OverlayCollector.Api.toggle]: js`() => ${SafeJS.fn(setVisible, js`!${visible}`)}`,\n\t\t}\n\n\t\tconst useOverlayState = ctx.imports.addImport(\"framer\", { exportSpecifier: \"useOverlayState\" })\n\t\tconst OverlayState = ctx.declarations.file.dedupe(\n\t\t\tDictionary.Overlay,\n\t\t\tnew SafeJS(\n\t\t\t\tjoin.lines(\n\t\t\t\t\tjs`({ children, blockDocumentScrolling, dismissWithEsc, enabled = true }) => {`,\n\t\t\t\t\tjs`const ${[visible, setVisible]} = ${SafeJS.fn(\n\t\t\t\t\t\tuseOverlayState,\n\t\t\t\t\t\tjs`{ blockDocumentScrolling, dismissWithEsc: enabled && dismissWithEsc }`,\n\t\t\t\t\t)}`,\n\t\t\t\t\tjs`return children(${api})`,\n\t\t\t\t\tjs`}`,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\n\t\tfor (const [overlayId, overlayBinding] of overlaysTriggeredByNode) {\n\t\t\tconst overlay = ctx.tree.get(overlayId)\n\t\t\tif (!overlay) continue\n\n\t\t\tconst overlayElementProps = ctx.overlayProps.get(overlayId)\n\t\t\tconst enabled = ctx.renderConditions.get(overlayId)\n\t\t\tconst isOverlay = isOverlayNode(overlay)\n\n\t\t\t// NOTE: Because we're handling fixed and relative overlays in this loop, and the latter\n\t\t\t// does not return true for `isOverlayNode`, we need to handle the default props here.\n\t\t\t// Fixed overlays will receive variant overrides.\n\t\t\tconst propsToUse = new SerializableObject({\n\t\t\t\tenabled: isSafeJS(enabled) ? enabled : undefined,\n\t\t\t\tblockDocumentScrolling: isOverlay ? overlayElementProps?.props?.blockDocumentScrolling : false,\n\t\t\t\tdismissWithEsc: isOverlay ? overlayElementProps?.props?.dismissWithEsc : false,\n\t\t\t})\n\n\t\t\tinjectTriggerSubscriptionsBeforeChildren(overlay, ctx, transforms)\n\n\t\t\ttransforms.push(children =>\n\t\t\t\tjsxTagWithOverrides(\n\t\t\t\t\tOverlayState,\n\t\t\t\t\tctx,\n\t\t\t\t\t{ props: propsToUse, overrides: isOverlay ? overlayElementProps?.overrides : undefined },\n\t\t\t\t\tjs`${overlayBinding} => (${children})`,\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\n\t// Wrap Fixed Position Overlays in a portal.\n\tconst overlayBinding = ctx.overlays.bindingsByOverlayId.get(node.id)\n\tif (overlayBinding && isOverlayNode(node)) {\n\t\t// For fixed overlays, inject the text selection styles of the trigger\n\t\tconst triggerId = parent ? ctx.elementIds.id(parent) : js`undefined`\n\n\t\t// Inject any text selection styles based on the trigger\n\t\ttransforms.push(children =>\n\t\t\tjsx.tag(\n\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"InjectSelectionStyle\" }),\n\t\t\t\tnew SerializableObject({ triggerId }),\n\t\t\t\tchildren,\n\t\t\t),\n\t\t)\n\n\t\tconst reactDOM = ctx.imports.addImport(\"react-dom\", { exportSpecifier: \"*\", importBinding: \"ReactDOM\" })\n\n\t\tconst templateContainerSelector = `#${templateOverlayContainerId}`\n\t\tconst webPageContainerSelector = `#${overlayContainerId}`\n\n\t\tconst getContainer = ctx.declarations.file.dedupe(\n\t\t\t\"getContainer\",\n\t\t\tjs`() => {${js.joinLines(\n\t\t\t\tjs`return document.querySelector(${templateContainerSelector}) ?? document.querySelector(${webPageContainerSelector}) ?? document.body`,\n\t\t\t)}}`,\n\t\t)\n\n\t\ttransforms.push(children => jsx`<>{${reactDOM}.createPortal(${children}, ${SafeJS.fn(getContainer)})}</>`)\n\t}\n\n\t// Wrap Relative Position Overlays in <Floating> which handles positioning\n\t// the overlay to the trigger.\n\tif (parent && overlayBinding && hasFloatingPosition(node) && jsxAttributes.isAnyVariantFloating) {\n\t\ttransforms.push(children =>\n\t\t\tjsxTagWithOverrides(\n\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"Floating\" }),\n\t\t\t\tctx,\n\t\t\t\tjsxAttributes.propsForFloating,\n\t\t\t\tchildren,\n\t\t\t),\n\t\t)\n\t}\n\n\t// Wrap any overlay in a React state condition and AnimatePresence.\n\tif (overlayBinding && isFixedOrRelativeOverlay(node)) {\n\t\ttransforms.push(children =>\n\t\t\tjsx.tag(\n\t\t\t\tctx.imports.addImport(\"framer-motion\", { exportSpecifier: \"AnimatePresence\" }),\n\t\t\t\tundefined,\n\t\t\t\tjs`${overlayBinding}.visible && (${children})`,\n\t\t\t),\n\t\t)\n\t}\n\n\tif (jsxAttributes.isAnyVariantATickerItem) {\n\t\ttransforms.push(children =>\n\t\t\tjsxTagWithOverrides(\n\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"TickerItem\" }),\n\t\t\t\tctx,\n\t\t\t\tjsxAttributes.propsForTickerItem ?? {},\n\t\t\t\tchildren,\n\t\t\t),\n\t\t)\n\t}\n\n\t// Wrap in conditional rendering if required.\n\tif (jsxAttributes.renderCondition !== true) {\n\t\ttransforms.push(children => js`${jsxAttributes.renderCondition} && (${children})`)\n\t}\n\n\tconst resultBinding = ctx.fetches.getResultBinding(node)\n\tif (jsxAttributes.propsForFetcher && resultBinding) {\n\t\ttransforms.push(inner =>\n\t\t\tjsxTagWithOverrides(\n\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"Fetcher\" }),\n\t\t\t\tctx,\n\t\t\t\tjsxAttributes.propsForFetcher,\n\t\t\t\tjs`${resultBinding} => (${inner})`,\n\t\t\t),\n\t\t)\n\t}\n\n\t// Wrap the repeated item of a collection list in a {data.map()} loop to\n\t// render as many items as there are currently being shown.\n\tif (isDataRepeater(parent) && isRepeatedItem(ctx.tree, node)) {\n\t\tconst repeaterInfo = ctx.repeaterInfo.get(parent.id)\n\t\tassert(repeaterInfo, \"jsxForNode: `repeaterInfo` must exist when transforming a repeated child.\")\n\t\tif (hasCollectionDataSource(parent)) {\n\t\t\t// Get the path variables before collecting all used variables.\n\t\t\tconst pathVariables = ctx.links.getPathVariablesForRepeaterInfo(repeaterInfo)\n\t\t\tif (pathVariables) {\n\t\t\t\ttransforms.push(children =>\n\t\t\t\t\tjsx.tag(\n\t\t\t\t\t\tctx.imports.addImport(\"framer\", {\n\t\t\t\t\t\t\texportSpecifier: \"PathVariablesContext.Provider\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tnew SerializableObject({ value: pathVariables }),\n\t\t\t\t\t\tchildren,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst indexBinding = ctx.bindings.createWithNode(\"index\", parent)\n\t\tconst { data, args, variableFallbackList, key } = repeaterMapBindings(\n\t\t\tparent,\n\t\t\trepeaterInfo.annotations,\n\t\t\tjsxAttributes,\n\t\t\tctx,\n\t\t\tindexBinding,\n\t\t)\n\n\t\tconst itemIndexDeclaration = repeaterItemIndexDeclaration(parent.id, indexBinding, ctx)\n\n\t\ttransforms.push(\n\t\t\tchildren =>\n\t\t\t\tjs`${data}?.map((${args}) => {${js.joinLines(\n\t\t\t\t\t...variableFallbackList,\n\t\t\t\t\titemIndexDeclaration,\n\t\t\t\t\t...ctx.declarations.forScope(parent.id, \"repeater-item\").list(),\n\t\t\t\t\tjs`return (${jsx.tag(\n\t\t\t\t\t\tctx.imports.addImport(\"framer-motion\", { exportSpecifier: \"LayoutGroup\" }),\n\t\t\t\t\t\tnew SerializableObject({\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tid: jst`${parent.id}-${key}`,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tchildren,\n\t\t\t\t\t)})`,\n\t\t\t\t)}})`,\n\t\t)\n\t}\n\n\tif (hasRepeatArray(node)) {\n\t\tconst indexBinding = ctx.bindings.createWithNode(\"index\", node)\n\t\tconst { args, data, key, variableFallbackList, repeaterItemCountDeclaration, repeaterItemIndexDeclaration } =\n\t\t\tgetNodeLevelRepeatMapBindings(node, jsxAttributes, ctx, indexBinding)\n\t\tif (repeaterItemCountDeclaration) {\n\t\t\tconst hoistedScope = hoistedDeclarationScope(node, ctx.tree, ctx.declarations)\n\t\t\thoistedScope.create(repeaterItemCountDeclaration)\n\t\t}\n\n\t\ttransforms.push(\n\t\t\tchildren =>\n\t\t\t\tjs`${data}?.map((${args}) => {${js.joinLines(\n\t\t\t\t\t...variableFallbackList,\n\t\t\t\t\trepeaterItemIndexDeclaration,\n\t\t\t\t\t...ctx.declarations.forScope(node.id, \"repeater-item\").list(),\n\t\t\t\t\tjs`return (${jsx.tag(\n\t\t\t\t\t\tctx.imports.addImport(\"framer-motion\", { exportSpecifier: \"LayoutGroup\" }),\n\t\t\t\t\t\tnew SerializableObject({\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tid: jst`${node.id}-${key}`,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tchildren,\n\t\t\t\t\t)})`,\n\t\t\t\t)}})`,\n\t\t)\n\t}\n\n\treturn transforms\n}\n/**\n * After serializing the children of a node, add any additional props that can\n * only be determined once the children have been serialized.\n */\nfunction updatePropsAfterSerializingDescendants(\n\tnodeInPrimary: CanvasNode,\n\tjsxAttributes: ProcessedVariantProps,\n\tctx: JSXContext,\n) {\n\tconst needsContainer = nodeNeedsContainer(nodeInPrimary)\n\tconst targetPropsAndOverrides = needsContainer ? jsxAttributes.propsForContainer : jsxAttributes.propsForElement\n\n\t// If the node triggers overlays, ensure that we can walk the dom from the\n\t// overlay to the trigger via attributes.\n\tconst overlaysTriggeredByNode = ctx.overlays.bindingsByOverlayTriggerId.get(nodeInPrimary.id)\n\tconst triggersOverlays = overlaysTriggeredByNode && overlaysTriggeredByNode.size > 0\n\n\tif (triggersOverlays) {\n\t\tlet targetProps = targetPropsAndOverrides.props\n\t\tif (!targetProps) targetProps = new SerializableObject()\n\t\ttargetProps.id = targetProps.id ?? ctx.elementIds.id(nodeInPrimary)\n\t}\n\n\t// Normally, each node collects the CSS variable definitions for the\n\t// variables it consumes, and such definitions will be inlined on the node\n\t// itself. But stack children can create variables for their conditional\n\t// layout (e.g. due to a dynamic stack direction) that need to be inlined on\n\t// the stack. Hence we need to inline the definitions here after we iterate\n\t// through the children. If the node has css variable definitions, we need\n\t// to inline them onto style.\n\tconst inlineStyleCSSVariableDefinitions = ctx.cssVariableDefinitions.getDefinitionsForNode(nodeInPrimary) ?? {}\n\tif (!isEmptyObject(inlineStyleCSSVariableDefinitions)) {\n\t\tlet targetProps = targetPropsAndOverrides.props\n\t\tif (!targetProps) targetProps = new SerializableObject()\n\n\t\tif (targetProps.style) {\n\t\t\tObject.assign(targetProps.style, inlineStyleCSSVariableDefinitions)\n\t\t} else {\n\t\t\ttargetProps.style = inlineStyleCSSVariableDefinitions\n\t\t}\n\t}\n}\n\n/**\n * Turn a CanvasNode into a SafeJS jsx string, including recursively serializing\n * all descendants. CanvasNodes that throw while serializing will be dropped\n * from the jsx output, and these nodes can be tracked in future to flag to\n * users.\n */\nasync function serializeNodeToJSX(\n\tnodeInPrimary: CanvasNode,\n\tparent: CanvasNode | null,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n): Promise<SafeJS | undefined> {\n\ttry {\n\t\t// SlotNodes currently do not have attributes and simply represent the\n\t\t// template position for children.\n\t\tif (isSlotNode(nodeInPrimary)) {\n\t\t\tassert(parent && ctx.layoutTemplateSlotBinding, \"A SlotNode must be in a Layout Template and have a parent.\")\n\t\t\tconst className = classNameForSlotSpacer(nodeInPrimary, parent, ctx)\n\t\t\treturn jsx`${js.joinLines(\n\t\t\t\tjsx.children(ctx.layoutTemplateSlotBinding),\n\t\t\t\tjsx.tag(\"div\", new SerializableObject({ className })),\n\t\t\t)}`\n\t\t}\n\n\t\tawait readyToSerializeNode(nodeInPrimary, ctx)\n\t\tctx.metrics.count(\"nodes\")\n\n\t\t// Register smart component instances for loader forwarding\n\t\tregisterChildComponentForLoader(nodeInPrimary, ctx, ancestorInfo)\n\n\t\tconst jsxAttributes = jsxAttributesForNode(nodeInPrimary, parent, ctx, ancestorInfo)\n\n\t\tif (isOverlayNode(nodeInPrimary)) {\n\t\t\tctx.overlayProps.set(nodeInPrimary.id, jsxAttributes?.propsForOverlay)\n\t\t}\n\n\t\t// If the result of processing all variants is undefined we don't need to\n\t\t// render this element, or any of its descendants.\n\t\tif (!jsxAttributes) return jsx``\n\n\t\tif (isCodeComponentNode(nodeInPrimary)) {\n\t\t\tawait addSlotContentToProps(nodeInPrimary, ctx, jsxAttributes.propsForElement, ancestorInfo)\n\t\t}\n\n\t\t// Recursively call this function on the children for the node, creating\n\t\t// a single JSX string.\n\t\tlet children = defaultChildrenJSX(nodeInPrimary, ctx, jsxAttributes.propsForElement)\n\t\tconst infoForDescendants = updateAncestorInfoForDescendants(ancestorInfo, nodeInPrimary, ctx, jsxAttributes)\n\t\tfor (const child of childrenForNode(nodeInPrimary, ctx)) {\n\t\t\tif (isFixedOrRelativeOverlay(child) && isObsoleteOverlay(ctx, child)) continue\n\n\t\t\tconst childJSX = await serializeNodeToJSX(child, nodeInPrimary, ctx, infoForDescendants)\n\t\t\tif (childJSX) children += serializeJS(jsx.children(childJSX))\n\t\t}\n\n\t\t// Sometimes, processing the children of a node will tell us whether\n\t\t// we need to add additional props:\n\t\t// - Stacks may need to add CSS variable definitions for their children\n\t\t// - Layers that trigger Overlays may need to add a data-attribute for\n\t\t//   traversal.\n\t\tupdatePropsAfterSerializingDescendants(nodeInPrimary, jsxAttributes, ctx)\n\n\t\t// At this point we have everything we need to construct a SafeJS string of\n\t\t// a complete jsx tag for the node we are serializing, and its subtree.\n\t\tconst jsxTag = await jsxTagForNodeAndAttributes(\n\t\t\tnodeInPrimary,\n\t\t\tctx,\n\t\t\tancestorInfo,\n\t\t\tinfoForDescendants,\n\t\t\tjsxAttributes,\n\t\t\tjsx.fromTrustedString(children),\n\t\t)\n\n\t\t// Finally we must often wrap the jsx for a node in additional jsx or\n\t\t// javascript. This supports repeaters, overlays, links, code component\n\t\t// containers, and conditions of when to render. A single CanvasNode can have\n\t\t// all of these wrapping tags.\n\t\treturn jsx.applyTransforms(jsxTag, jsxTagTransformsForNode(nodeInPrimary, parent, jsxAttributes, ctx, ancestorInfo))\n\t} catch (error) {\n\t\tlogger.reportError(error, {\n\t\t\tnode: nodeInPrimary.id,\n\t\t\tprimaryVariant: ctx.rootId,\n\t\t})\n\n\t\tctx.errors.record(nodeInPrimary, error)\n\n\t\t// If serializing jsx from a CanvasNode fails, drop the result from the\n\t\t// jsx tree. This ensures that we don't fail code-generation for the\n\t\t// whole tree simply if some component is missing. In the future we\n\t\t// could track those issues here to feedback to users.\n\t\treturn jsx``\n\t}\n}\n\n/**\n * Serialize a node and its subtree to a SafeJS jsx string, tracking all\n * dependencies and metadata required.\n */\nexport async function jsxForNode(\n\tsourceNode: CanvasNode,\n\tscopeNode: Loaded<CanvasPageNode | WebPageNode | SmartComponentNode | LayoutTemplateNode | DesignPageNode>,\n\tdependencies: JSXEngineDependencies,\n\treserved?: Set<string>,\n\tserializationId: string = `framer-${randomBase62(5)}`,\n\tllmSnapshot: boolean = false,\n) {\n\tconst { combinedVariableControlMap } = scopeNode.combineVariableControlMap(\n\t\tdependencies.tree,\n\t\tundefined,\n\t\tundefined,\n\t\tdependencies.componentLoader,\n\t\tdependencies.componentLoader.activeBundleHash,\n\t)\n\n\tconst ancestorInfo: AncestorInfo = {\n\t\tinheritedControlMap: combinedVariableControlMap,\n\t}\n\n\tconst ctx = createJSXContext(sourceNode, scopeNode, dependencies, reserved, serializationId, llmSnapshot)\n\n\treturn {\n\t\t// Return all of our collectors for use in the body of the function we\n\t\t// construct to host this JSX.\n\t\tctx,\n\t\tjsx: await serializeNodeToJSX(sourceNode, null, ctx, ancestorInfo),\n\t} as const\n}\n\nasync function waitForModuleToLoad(\n\tnode: CanvasNode,\n\tidentifiers: ModuleExportIdentifier[],\n\t{ componentLoader, modulesStore, errors, tree, rootId }: JSXContext,\n) {\n\tconst root = tree.get(rootId)\n\tconst scope = tree.getScopeNodeFor(root)\n\tif (allVariantsAreHidden(tree, scope, node)) return\n\n\tfor (const identifier of identifiers) {\n\t\t// Make sure to evaluate modules if necessary. Skip local code modules, as they could have been deleted.\n\t\tconst isLocalCodeModule = isLocalModuleIdentifier(identifier) && identifier.type === ModuleType.Code\n\t\tif (isLocalCodeModule) {\n\t\t\tconst definition = componentLoader.componentForIdentifier(identifier.value)\n\t\t\tconst error = componentLoader.errorForIdentifier(identifier.value)\n\t\t\tif (!definition) {\n\t\t\t\terrors.record(node, ErrorNodeReason.MissingModule, identifier.value)\n\t\t\t} else if (error) {\n\t\t\t\terrors.record(node, ErrorNodeReason.CodeError, identifier.value)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\n\tconst externalIdentifiers = externalModuleExportIdentifiers(identifiers)\n\tif (externalIdentifiers.length > 0) await modulesStore.preloadExternalModules(externalIdentifiers)\n\n\tawait waitForLoadingComponentsWithTimeout(\n\t\tcomponentLoader,\n\t\tidentifiers.map(i => i.value),\n\t\tmodulesStore,\n\t)\n}\n\nfunction externalModuleExportIdentifiers(identifiers: ModuleExportIdentifier[]): ExternalModuleExportIdentifier[] {\n\tconst list: ExternalModuleExportIdentifier[] = []\n\tfor (const identifier of identifiers) {\n\t\tif (!isExternalModuleIdentifier(identifier)) continue\n\t\tlist.push(identifier)\n\t}\n\treturn list\n}\n\nfunction codeComponentIdentifiersForNode(\n\tnode: CodeComponentNode,\n\tctx: JSXContext,\n): Set<ModuleExportIdentifierString> | undefined {\n\tif (!isModuleExportIdentifier(node.codeComponentIdentifier)) return\n\n\tconst identifiers = new Set<ModuleExportIdentifierString>([node.codeComponentIdentifier])\n\n\tfor (const variant of ctx.variants) {\n\t\tconst nodeInVariant = getReplicaNode(variant, node.id, ctx.tree)\n\t\t// Code component slots do not have a replica node in the tree. And there's currently no way\n\t\t// to override component slots, so we trust that collecting the identifier on the primary\n\t\t// slot alone is enough.\n\t\tif (!nodeInVariant) continue\n\n\t\tassert(isCodeComponentNode(nodeInVariant), \"Expected a CodeComponentNode in the variant\", nodeInVariant?.id)\n\t\tif (!isModuleExportIdentifier(nodeInVariant.codeComponentIdentifier)) continue\n\t\tidentifiers.add(nodeInVariant.codeComponentIdentifier)\n\t}\n\n\treturn identifiers\n}\n\n/**\n * Ensure that any code we are about to import and process into the jsx we are\n * generating has been evaluated by the component loader before proceeding,\n * waiting for a few frames for it to exist. This ensure that we don't drop\n * react props specified by Property Controls.\n */\nasync function readyToSerializeNode(node: CanvasNode, context: JSXContext): Promise<void> {\n\tif (isCodeComponentNode(node)) {\n\t\t// Assume prototypes don't have overrides in replicas. Clean this up if they do, or we\n\t\t// remove prototype support.\n\t\tif (node.codeComponentIdentifier === HardCodedCodeIdentifier.prototype) {\n\t\t\tconst pageId = getPageNodeIdForPrototype(node, context.componentLoader)\n\t\t\tif (!pageId) return\n\n\t\t\tawait waitForModuleToLoad(\n\t\t\t\tnode,\n\t\t\t\t[localModuleIdentifierForStableName(ModuleType.Prototype, pageId, \"default\")],\n\t\t\t\tcontext,\n\t\t\t)\n\t\t}\n\n\t\tconst identifiers = codeComponentIdentifiersForNode(node, context)\n\t\tif (!identifiers) return\n\n\t\tconst parsedIdentifiers: ModuleExportIdentifier[] = []\n\t\tfor (const identifier of identifiers) parsedIdentifiers.push(parseModuleIdentifier(identifier))\n\n\t\tawait waitForModuleToLoad(node, parsedIdentifiers, context)\n\t}\n\n\tif (hasCodeOverride(node)) {\n\t\tif (!isModuleExportIdentifier(node.codeOverrideIdentifier)) return\n\t\tawait waitForModuleToLoad(node, [parseModuleIdentifier(node.codeOverrideIdentifier)], context)\n\t}\n\tif (hasCollectionDataSource(node)) {\n\t\tawait waitForModuleToLoad(node, [parseModuleIdentifier(node.dataIdentifier)], context)\n\t}\n}\n\n/**\n * Registers a child smart component instance for loader forwarding.\n * This enables the parent route loader to call forwardLoader() on child components.\n */\nfunction registerChildComponentForLoader(node: CanvasNode, ctx: JSXContext, ancestorInfo: AncestorInfo): void {\n\t// Only process smart component instances (local or external)\n\tif (!isSmartComponentInstance(ctx.tree, node)) return\n\n\t// This should never really happen, as we don't want to process the root node.\n\tassert(node.id !== ctx.scopeId, \"Expected the node not to be the scope node\")\n\n\t// TODO: Add static props for loader forwarding\n\tctx.preload.addChildComponent(node.codeComponentIdentifier, {}, node.id, ancestorInfo.lastRepeaterId)\n}\n\nfunction childrenForNode(nodeInPrimary: CanvasNode, ctx: JSXContext): readonly CanvasNode[] {\n\tif (!withChildren(nodeInPrimary) || isShapeContainerNode(nodeInPrimary) || isRichTextNode(nodeInPrimary)) {\n\t\treturn emptyArray()\n\t}\n\n\tif (\n\t\tisCodeComponentNode(nodeInPrimary) &&\n\t\t// Prototype components children are special cased since in code\n\t\t// generation, they refer to a module generated from the CanvasPage\n\t\t// scope, but CodeComponentNode.getComponentChildren() is special cased\n\t\t// for canvas rendering to provide the screen node that is the home node\n\t\t// of the Canvas Page.\n\t\tnodeInPrimary.codeComponentIdentifier !== HardCodedCodeIdentifier.prototype\n\t) {\n\t\treturn getChildrenSlotItems(ctx.tree, nodeInPrimary, ctx.componentLoader).map(slot => slot.node)\n\t}\n\n\treturn nodeInPrimary.children.toArray()\n}\n\nfunction getNodeLevelRepeatMapBindings(\n\tnode: CanvasNode & HasRepeatArray,\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps,\n\tctx: JSXContext,\n\tindexBinding: SafeJS,\n) {\n\tconst itemIdBinding = ctx.bindings.create(\"id\")\n\tconst data = ctx.variables.create(node.repeatArray)\n\n\t// WARNING: Getting the used variables needs to happen after all variables are created.\n\tconst usedVariableBindings = ctx.variables.getBindings(node.id)\n\tconst args: Record<string, SafeJS> = {\n\t\t[arrayIdKey]: itemIdBinding,\n\t}\n\taddNonRepeaterVariableBindingsToArgs(args, usedVariableBindings)\n\n\tconst controls = jsxAttributes.inheritedControlMap?.get(node.id)\n\n\tconst itemCountDeclaration = repeaterItemCountDeclaration(node.id, data, ctx)\n\tconst itemIndexDeclaration = repeaterItemIndexDeclaration(node.id, indexBinding, ctx)\n\n\treturn {\n\t\targs: js`${args}, ${indexBinding}`,\n\t\tdata,\n\t\tkey: js`${itemIdBinding} ?? ${indexBinding}`,\n\t\tvariableFallbackList: variableFallbackList(usedVariableBindings, controls),\n\t\trepeaterItemCountDeclaration: itemCountDeclaration,\n\t\trepeaterItemIndexDeclaration: itemIndexDeclaration,\n\t}\n}\n\nfunction collectRepeaterTransforms(\n\tnode: DataRepeater,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps,\n\ttransforms: TagTransform[],\n) {\n\tconst collectionOrArrayBinding = dataBindingForRepeater(node, ctx)\n\n\tconst itemCountDeclaration = repeaterItemCountDeclaration(node.id, collectionOrArrayBinding, ctx)\n\n\t// Insert a query data element along with any declarations on an own repeater scope\n\tif (hasCollectionDataSource(node)) {\n\t\tconst usedVariableBindings = ctx.variables.getBindings(node.id)\n\t\tconst usedVariableIds = new Set(usedVariableBindings.keys())\n\n\t\tconst queryElementProps = getQueryDataElementProps(node, ctx, ancestorInfo, jsxAttributes, usedVariableIds)\n\n\t\tif (queryElementProps) {\n\t\t\tconst QueryDataBinding = ctx.declarations.file.dedupe(\"QueryData\", createQueryDataComponent(node, ctx))\n\t\t\tconst collectionBinding = collectionOrArrayBinding\n\t\t\tconst paginationInfoBinding = ctx.bindings.createWithNode(\"paginationInfo\", node)\n\t\t\tconst loadMoreBinding = ctx.bindings.createWithNode(\"loadMore\", node)\n\n\t\t\ttransforms.push(children =>\n\t\t\t\tjsx.tag(\n\t\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"ChildrenCanSuspend\" }),\n\t\t\t\t\tundefined,\n\t\t\t\t\tjsxTagWithOverrides(\n\t\t\t\t\t\tQueryDataBinding,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tqueryElementProps,\n\t\t\t\t\t\tjs`(${collectionBinding}, ${paginationInfoBinding}, ${loadMoreBinding}) => {${js.joinLines(\n\t\t\t\t\t\t\titemCountDeclaration,\n\t\t\t\t\t\t\t...ctx.declarations.forScope(node.id, \"repeater\").list(),\n\t\t\t\t\t\t\tjsx`return <>${children}</>`,\n\t\t\t\t\t\t)}}`,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// If we didn't generate a query data element, we still need to emit the declarations\n\tif (itemCountDeclaration) {\n\t\tconst hoistedScope = hoistedDeclarationScope(node, ctx.tree, ctx.declarations)\n\t\thoistedScope.create(itemCountDeclaration)\n\t\tctx.declarations.forScope(node.id, \"repeater\").hoistTo(hoistedScope)\n\t}\n}\n\nfunction transformChildren(\n\tnode: CanvasNode,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps,\n): TagTransform[] {\n\tconst transforms: TagTransform[] = []\n\n\tif (isFormContainer(node)) {\n\t\ttransforms.push(children => js`(${FORM_STATE_BINDING}) => (<>${children}</>)`)\n\t}\n\n\tif (isDataRepeater(node) && !hasTickerEffect(node) && !hasColumnMasonryLayout(node)) {\n\t\tcollectRepeaterTransforms(node, ctx, ancestorInfo, jsxAttributes, transforms)\n\t}\n\n\treturn transforms\n}\n\nasync function jsxTagForNodeAndAttributes(\n\tnodeInPrimary: CanvasNode,\n\tctx: JSXContext,\n\tancestorInfo: AncestorInfo,\n\tinfoForDescendants: AncestorInfo,\n\tjsxAttributes: ProcessedVariantsFlags & ProcessedVariantProps,\n\tchildren: SafeJS,\n): Promise<SafeJS> {\n\tconst tag = jsxTagWithOverrides(\n\t\tjsxTagNameForNode(nodeInPrimary, ctx, ancestorInfo, jsxAttributes),\n\t\tctx,\n\t\tisOverlayNode(nodeInPrimary) ? undefined : jsxAttributes.propsForElement,\n\t\tjsx.applyTransforms(children, transformChildren(nodeInPrimary, ctx, ancestorInfo, jsxAttributes)),\n\t)\n\n\t// OverlayNode's are stored in the CanvasTree as children of the triggering\n\t// node, however CodeComponentNodes, and RichText cannot render these nodes\n\t// as React `children` by nesting them inside the elements jsx tag.\n\t// CodeComponent authors may be using props.children for a specific\n\t// ComponentInstance slot, and RichText converts its prose mirror html into\n\t// jsx that is rendered as it's children. To ensure we don't impact these\n\t// behaviors, for these nodes we move overlays to be siblings of the node\n\t// that triggers them to ensure they render as expected.\n\tif (\n\t\t(isCodeComponentNode(nodeInPrimary) || isRichTextNode(nodeInPrimary)) &&\n\t\tnodeCanTriggerOverlay(nodeInPrimary, HardCodedCodeIdentifier.showRelativeOverlayAction)\n\t) {\n\t\tlet tagWithSiblings = serializeJS(tag)\n\t\tfor (const child of nodeInPrimary.children) {\n\t\t\tif (!isFixedOrRelativeOverlay(child) || isObsoleteOverlay(ctx, child)) continue\n\t\t\tconst childJSX = await serializeNodeToJSX(child, nodeInPrimary, ctx, infoForDescendants)\n\t\t\tif (childJSX) tagWithSiblings += serializeJS(jsx.children(childJSX))\n\t\t}\n\n\t\t// Since `createJSXFromNode` always returns a single SafeJS jsx string,\n\t\t// we need to add those siblings to the tag.\n\t\treturn jsx.fromTrustedString(tagWithSiblings)\n\t}\n\n\treturn tag\n}\n\nfunction jsxTagWithOverrides(\n\ttag: SafeJS,\n\tctx: JSXContext,\n\telementProps?: JSXElementProps,\n\tjsxChildren?: SafeJS,\n): SafeJS {\n\tif (!elementProps) return jsx.tag(tag, undefined, jsxChildren)\n\n\tconst { props = new SerializableObject(), overrides } = elementProps\n\n\tconst transforms: TagTransform[] = []\n\n\tif (overrides) {\n\t\tswitch (ctx.scopeType) {\n\t\t\tcase ScopeType.SmartComponent:\n\t\t\t\tSerializableObject.addSpreadAtEnd(\n\t\t\t\t\tprops,\n\t\t\t\t\tSafeJS.fn(js`addPropertyOverrides`, overrides, js`baseVariant`, js`gestureVariant`),\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase ScopeType.WebPage:\n\t\t\tcase ScopeType.LayoutTemplate:\n\t\t\t\ttransforms.push(children =>\n\t\t\t\t\tjsx.tag(\n\t\t\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"PropertyOverrides\" }),\n\t\t\t\t\t\tnew SerializableObject({ breakpoint: js`baseVariant`, overrides }),\n\t\t\t\t\t\tchildren,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t// Other scopes cannot have overrides.\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\treturn jsx.applyTransforms(jsx.tag(tag, props, jsxChildren), transforms)\n}\n\nfunction injectTriggerSubscriptionsBeforeChildren(node: CanvasNode, ctx: JSXContext, transforms: TagTransform[]) {\n\tconst triggers: SafeJS[] = []\n\tfor (const {\n\t\ttriggerId,\n\t\ttargetId,\n\t\tbinding,\n\t\toverlayBinding: overlayBindingForTrigger,\n\t} of ctx.triggerActions.triggerActionByNode.get(node.id) ?? []) {\n\t\ttriggers.push(\n\t\t\tjsx.tag(\n\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"TriggerSubscription\" }),\n\t\t\t\tnew SerializableObject({\n\t\t\t\t\ttriggerId: triggerId,\n\t\t\t\t\ttargetId: targetId,\n\t\t\t\t\ttrigger: binding,\n\t\t\t\t\tcallback: overlayBindingForTrigger ? js`() => {${overlayBindingForTrigger}.show()}` : undefined,\n\t\t\t\t\ttriggeredExternally: overlayBindingForTrigger ? js`${overlayBindingForTrigger}.visible` : undefined,\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\t}\n\n\tif (triggers.length > 0) {\n\t\ttransforms.push(children => js`<>${js.joinLines(...triggers)}${children}</>`)\n\t}\n}\n", "import { assert, getLogger } from \"@framerjs/shared\"\nimport { streamText } from \"ai\"\nimport { StreamingDSLParser } from \"app/ai/StreamingDSLParser.ts\"\nimport { createVekterOpenRouterExtraBody, openRouter } from \"app/ai/config/openRouter.ts\"\nimport { LanguageModel } from \"app/ai/languageModels.ts\"\nimport { jsxForNode } from \"code-generation/jsx/jsxForNode.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { type CanvasNode, isVectorNode } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCanvasPageNode,\n\tisDesignPageNode,\n\tisLayoutTemplateNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { createGeneratedValue } from \"document/models/CanvasTree/traits/Generated.ts\"\nimport { withName } from \"document/models/CanvasTree/traits/WithName.ts\"\nimport { isBreakpointVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport { z } from \"zod\"\n\nconst log = getLogger(\"renameLayers\")\n\nconst systemPrompt = `Propose names for the elements in provided React JSX fragment of a web site.\n\n**Naming Rules:**\n1. Never use an ancestor's name in a descendant's name. A descendant's name must never repeat any part of its ancestors name.\n    - INCORRECT: \"Pricing Plans\", \"Pricing Plans Icon\", \"Pricing Plans Title\"\n    - CORRECT: \"Pricing Plans\", \"Icon\", \"Title\"\n2. Evaluate the entire fragment, paying special attention to the text in the children of RichText components, to determine the theme of the content, e.g. \"Savings Goals\" or \"Pricing Plans\", and use this to inform the individual names.\n3. When an element is a layout wrapper (e.g., flex, grid), describe its function or structure. Use this to replace generic wrappers like 'Body,' 'Content,' or 'Group.' (Example: '2x2 Grid,' 'Info Stack,' 'Action Bar'). (Never: 'Icon Flex,' 'Details Group').\n4. Titles should be short. Aim for 1 word (80%). Use 2-3 words only when necessary (20%).\n5. All names must use Title Case, including spaces.\n6. Ignore \"*-container\" suffixes.\n7. Ignore the attribute value of data-framer-name=\"*\".\n\n**Response Format:**\n- Respond with a single line of text.\n- Do not include any other text, explanation, or preamble.\n- The line must be a list of \"class-name Proposed Name\" pairs separated by semicolons.\n- The class name must be the class name of the JSX element.\n\n**Example Output:**\nframer-asifd Title; framer-adfda Content; framer-fdsafd Footer; framer-aht4dq Submit Button;\n`\n\nconst SEPARATOR = \";\"\n\nconst LayerName = z.object({\n\tclassName: z.string(),\n\tname: z.string(),\n})\n\nfunction parseLayerName(result: string): z.infer<typeof LayerName> {\n\tconst trimmed = result.trim()\n\tassert(trimmed.length > 0, \"Trimmed result is empty\")\n\tconst [className, ...nameParts] = trimmed.split(\" \")\n\treturn LayerName.parse({ className, name: nameParts.join(\" \") })\n}\n\nexport function scopeAllowsRenameLayers(scope: CanvasNode) {\n\treturn (\n\t\tisDesignPageNode(scope) ||\n\t\tisWebPageNode(scope) ||\n\t\tisCanvasPageNode(scope) ||\n\t\tisSmartComponentNode(scope) ||\n\t\tisLayoutTemplateNode(scope)\n\t)\n}\n\nexport async function renameLayers(engine: VekterEngine, nodes: CanvasNode[]) {\n\tconst startTime = performance.now()\n\tlet renameCount = 0\n\n\tconst scope = engine.stores.scopeStore.active\n\tif (!scopeAllowsRenameLayers(scope)) return\n\n\ttry {\n\t\tengine.scheduler.process(() => engine.beginUndoGroup())\n\n\t\tfor (const node of engine.tree.withoutDescendants(nodes)) {\n\t\t\tconst { jsx, ctx } = await jsxForNode(\n\t\t\t\tnode,\n\t\t\t\tscope,\n\t\t\t\t{\n\t\t\t\t\tcomponentLoader: engine.componentLoader,\n\t\t\t\t\tmodulesStore: engine.stores.modulesStore,\n\t\t\t\t\ttree: engine.stores.treeStore.tree,\n\t\t\t\t\tengineChanges: engine.scheduler.changes,\n\t\t\t\t\tassetMap: engine.stores.assetStore.assetMap,\n\t\t\t\t},\n\t\t\t\tundefined,\n\t\t\t\t\"\",\n\t\t\t\ttrue,\n\t\t\t)\n\n\t\t\tif (!jsx) continue\n\n\t\t\tconst parser = new StreamingDSLParser<{ className: string; name: string }>(SEPARATOR, parseLayerName, result => {\n\t\t\t\tvoid engine.scheduler.processWhenReadyAsync(() => {\n\t\t\t\t\tconst { className, name } = result\n\t\t\t\t\tconst n = engine.tree.get(ctx.css.getNodeIdForClassName(className))\n\t\t\t\t\tif (!n || !withName(n)) return\n\t\t\t\t\t// Skip nodes that don't benefit from a name.\n\t\t\t\t\tif (isVectorNode(n) || isBreakpointVariant(n)) return\n\t\t\t\t\t// Skip node that are already named by a human.\n\t\t\t\t\tif (isString(n.name)) return\n\t\t\t\t\tn.set({ name: createGeneratedValue(name) })\n\t\t\t\t\trenameCount++\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tconst abortController = new AbortController()\n\n\t\t\ttry {\n\t\t\t\tconst { textStream } = streamText({\n\t\t\t\t\tmodel: openRouter(LanguageModel.GeminiFlash25Lite, {\n\t\t\t\t\t\textraBody: createVekterOpenRouterExtraBody({\n\t\t\t\t\t\t\tfeatureCategory: \"canvas\",\n\t\t\t\t\t\t\tfeatureName: \"rename-layers\",\n\t\t\t\t\t\t\tstep: \"rename\",\n\t\t\t\t\t\t\tsessionId: crypto.randomUUID(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t}),\n\t\t\t\t\tsystem: systemPrompt,\n\t\t\t\t\tmessages: [{ role: \"user\", content: `\\`\\`\\`\\n${jsx.toString()}\\`\\`\\`` }],\n\t\t\t\t\tabortSignal: abortController.signal,\n\t\t\t\t})\n\n\t\t\t\tfor await (const textPart of textStream) {\n\t\t\t\t\tparser.addToken(textPart)\n\t\t\t\t}\n\n\t\t\t\tparser.finalize()\n\t\t\t} catch (error) {\n\t\t\t\tabortController.abort()\n\t\t\t\tthrow error\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tlog.error(\"Failed to generate layer names:\", error)\n\t\t// Rethrow the error to trigger the toast.\n\t\tthrow error\n\t} finally {\n\t\tawait engine.scheduler.processWhenReadyAsync(() => engine.endUndoGroup())\n\t\trecord(\"rename_layers\", { duration: performance.now() - startTime, count: renameCount })\n\t}\n}\n", "import type { CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport type { IsMaster, IsReplica, IsReplicaChild, IsReplicaOrReplicaChild } from \"../WithTemplate.ts\"\nimport { isMaster, isReplica, isReplicaChild, isReplicaOrReplicaChild } from \"../WithTemplate.ts\"\nimport { isReplicaVariantOrReplicaVariantChild, isVariant } from \"../WithVariant.ts\"\n\n/** node is master or replica but not a variant */\nexport function isSymbol<N extends CanvasNode>(node: N): node is N & (IsMaster | IsReplica) {\n\treturn (isMaster(node) || isReplica(node)) && !isVariant(node)\n}\n\nexport function isSymbolReplica<N extends CanvasNode>(node: N): node is N & IsReplica {\n\treturn isReplica(node) && !isVariant(node)\n}\n\nexport function isSymbolReplicaOrSymbolReplicaChild<N extends CanvasNode>(\n\tnode: N,\n): node is N & IsReplicaOrReplicaChild {\n\treturn isReplicaOrReplicaChild(node) && !isReplicaVariantOrReplicaVariantChild(node)\n}\n\nexport function isSymbolReplicaChild<N extends CanvasNode>(node: N): node is N & IsReplicaChild {\n\treturn isReplicaChild(node) && !isReplicaVariantOrReplicaVariantChild(node)\n}\n", "import { assert, getLogger } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { CanvasNode, CanvasTree } from \"../index.ts\"\nimport { withTemplate } from \"../traits/WithTemplate.ts\"\n\n// TODO: check if the function can be deleted completely\nexport function insertTemplateNode(\n\tengine: VekterEngine,\n\ttemplate: CanvasNode,\n\tparentId?: string,\n\tposition?: number,\n\ttree: CanvasTree = engine.tree,\n): CanvasNode {\n\t// If this is a symbol (a.k.a. design component) we strip it for compatibility reasons. But\n\t// realistically this should never happen.\n\tif (withTemplate(template)) {\n\t\tgetLogger(\"app\").warn(\"Inserting a symbol is no longer supported.\")\n\t\ttemplate.isMaster = false\n\t\ttemplate.replicaInfo = null\n\t\ttemplate.originalid = null\n\t}\n\n\tassert(!tree.has(template.id), \"Tree should not contain node with same id as inserted template\")\n\tengine.stores.scopeStore.insertNode(template, parentId, position, undefined, undefined, tree)\n\treturn template\n}\n", "import type {\n\tComponentLoader,\n\tEntityDefinition,\n\tEntityIdentifier,\n\tReactComponentDefinition,\n} from \"@framerjs/framer-runtime\"\nimport { isErrorDefinition } from \"@framerjs/framer-runtime\"\nimport { assert, ModuleType, isLocalModuleIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { experiments } from \"app/experiments.ts\"\nimport { parseIntrinsicSizeFromAnnotations } from \"code-generation/utils/annotations.ts\"\nimport { getDefaultName } from \"document/components/utils/nodes.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { HardCodedCodeIdentifier } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport { isFiniteNumber } from \"library/render/utils/isFiniteNumber.ts\"\nimport { isDefined } from \"utils/typeChecks.ts\"\n\n/**\n * This is usually a partial `EntityDefinition`\n */\nexport interface CategorizableComponent {\n\tfile?: string\n\tname: string | null\n\tpackageIdentifier?: string | null\n\tidentifier?: EntityIdentifier\n}\n\nexport function codeComponentFromDefinition(componentDefinition: ReactComponentDefinition): CodeComponentNode {\n\tconst props: Partial<CodeComponentNode> = {\n\t\twidth: 200,\n\t\theight: 200,\n\t\tcodeComponentIdentifier: componentDefinition.identifier,\n\t\tintrinsicWidth: null,\n\t\tintrinsicHeight: null,\n\t\tslotsAreChildNodes: experiments.isOn(\"componentSlotsAreChildNodes\"),\n\t}\n\n\tconst { defaultProps, annotations } = componentDefinition\n\n\tif (defaultProps !== undefined) {\n\t\tif (isFiniteNumber(defaultProps.width)) {\n\t\t\tprops.width = defaultProps.width\n\t\t\tprops.intrinsicWidth = defaultProps.width\n\t\t}\n\t\tif (isFiniteNumber(defaultProps.height)) {\n\t\t\tprops.height = defaultProps.height\n\t\t\tprops.intrinsicHeight = defaultProps.height\n\t\t}\n\t}\n\n\tif (annotations) {\n\t\tconst intrinsicSize = parseIntrinsicSizeFromAnnotations(annotations)\n\n\t\tif (intrinsicSize.width) props.width = intrinsicSize.width\n\t\tif (intrinsicSize.height) props.height = intrinsicSize.height\n\t}\n\n\treturn new CodeComponentNode(props)\n}\n\ninterface WithName {\n\tname: string | null\n}\n\nexport function sortComponents<T extends WithName>(components: T[]): T[] {\n\treturn components.sort(sortByName)\n}\n\nconst sanitizedNameCache = new Map<string, string>()\n\nfunction sanitizeName(name: string) {\n\tconst cached = sanitizedNameCache.get(name)\n\tif (cached) return cached\n\n\tconst sanitizedName = name\n\t\t.split(\"/\")\n\t\t.map(part => part.trim())\n\t\t.join(\"\")\n\n\tsanitizedNameCache.set(name, sanitizedName)\n\treturn sanitizedName\n}\n\nfunction sortByName<T extends WithName>(a: T, b: T) {\n\tif (a.name === null) return -1\n\tif (b.name === null) return 1\n\n\tconst nameA = sanitizeName(a.name)\n\tconst nameB = sanitizeName(b.name)\n\n\treturn nameA.localeCompare(nameB, undefined, { numeric: true })\n}\n\nexport function isUserCreatedComponent(component: EntityDefinition) {\n\tif (isErrorDefinition(component) && component.file === \"./canvas.tsx\") {\n\t\treturn false\n\t}\n\t// Stack is no longer a code component but it can still be found\n\tif (component.identifier === HardCodedCodeIdentifier.stack) return false\n\n\tconst parsedIdentifier = parseModuleIdentifier(component.identifier)\n\tif (isLocalModuleIdentifier(parsedIdentifier)) {\n\t\tif (parsedIdentifier.type === ModuleType.Screen) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn component.type === \"component\" || component.type === \"master\"\n}\n\nexport function removeCategoriesFromName(name: string): string {\n\tconst nameSections = name.split(\"/\")\n\tconst lastSection = nameSections[nameSections.length - 1]\n\tassert(isDefined(lastSection), \"Last section is required\")\n\treturn lastSection.trim()\n}\n\nexport function getComponentName(\n\tcomponentLoader: ComponentLoader,\n\tcomponentDefinition: EntityDefinition,\n\tcomponent: CanvasNode | null,\n) {\n\tif (componentDefinition.name) return componentDefinition.name\n\tif (component) return getDefaultName(componentLoader, component)\n\treturn Dictionary.Unknown\n}\n", "import type { ComponentLoader, EntityDefinition } from \"@framerjs/framer-runtime\"\nimport { isReactComponentDefinition } from \"@framerjs/framer-runtime\"\nimport { supportsAutoSizing } from \"@framerjs/framer-runtime/crossorigin\"\nimport { assert, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { getOriginalVariantNodeIfExists } from \"code-generation/utils/variantEditingHelpers.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport {\n\ttype CanvasNode,\n\ttype CanvasTree,\n\ttype CodeComponentNode,\n\ttype NodeID,\n\tSmartComponentNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { TemplateHelper, generateReplicaChildId } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport {\n\tisCodeComponentNode,\n\tisDynamicVectorInstance,\n\tisFrameNode,\n\tisShapeContainerNode,\n\tisSmartComponentNode,\n\tisTextNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isFixedOrRelativeOverlay, nodeIsInOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport {\n\tgetSmartComponentOrWebPageForCodeComponent,\n\tisLocalSmartComponentInstance,\n} from \"document/models/CanvasTree/nodes/utils/smartComponentInstanceHelpers.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { isRepeaterLoaderInstance } from \"document/models/CanvasTree/traits/WithDataLoaderVariants.ts\"\nimport {\n\tgetFloatingPositionProps,\n\thasFloatingPosition,\n\twithFloatingPosition,\n} from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport {\n\tcanLoadedComponentBeFormButtonSource,\n\trequiresModificationsToBeFormButtonSource,\n} from \"document/models/CanvasTree/traits/WithFormVariants.ts\"\nimport { withFrameEvents } from \"document/models/CanvasTree/traits/WithFrameEvents.ts\"\nimport type { WithGridItemSize } from \"document/models/CanvasTree/traits/WithGridItemSize.ts\"\nimport {\n\tisGridChildFillingCellHeight,\n\tisGridChildFillingCellWidth,\n\twithGridItemSize,\n} from \"document/models/CanvasTree/traits/WithGridItemSize.ts\"\nimport { HTMLTag } from \"document/models/CanvasTree/traits/WithHTMLTag.ts\"\nimport { isLockedOrLockedByParent } from \"document/models/CanvasTree/traits/WithLock.ts\"\nimport type { WithConstraints, WithPins } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { isPinnable } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { withTarget } from \"document/models/CanvasTree/traits/WithTarget.ts\"\nimport type { IsReplica, ReplicaNodeOverrides } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport {\n\tgetMasterAncestor,\n\tisMaster,\n\tisReplica,\n\tisReplicaChild,\n} from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { IsVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport {\n\tisPrimaryVariant,\n\tisReplicaVariantChild,\n\tisReplicaVariantOrReplicaVariantChild,\n\tisVariant,\n} from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport type { WithFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport type { VekterConstraintValues } from \"document/models/CanvasTree/traits/utils/VekterConstraintValues.ts\"\nimport { isAutoSizedOnAnyDimension } from \"document/models/CanvasTree/traits/utils/autoSizeHelpers.ts\"\nimport { isSymbolReplicaChild } from \"document/models/CanvasTree/traits/utils/isSymbol.ts\"\nimport { insertTemplateNode } from \"document/models/CanvasTree/utils/insertTemplateNode.ts\"\nimport type { EventActions } from \"document/models/EventAction.ts\"\nimport type { ControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { prefixControlProps } from \"document/models/controlProps/controlPropKey.ts\"\nimport { getCompatibleNodeProperties } from \"document/utils/getCompatibleNodeProperties.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport {\n\tgetParentDataRepeater,\n\trestoreRepeatedItemsFromSnapshots,\n\tsnapshotRepeatedItemsForNodes,\n} from \"utils/repeaterUtils.ts\"\nimport { isArray, isString } from \"utils/typeChecks.ts\"\nimport { getActionsForNode } from \"../chrome/properties/utils/eventActions.ts\"\nimport { RenamedIds, updateNodeConnections } from \"../tools/utils/updateNodeConnections.ts\"\nimport { codeComponentFromDefinition } from \"./componentHelpers.ts\"\n\ninterface CanReplaceNodeOptions {\n\tallowVariants?: boolean\n\tallowLockedNodes?: boolean\n}\n\nexport function canReplaceNode(\n\tnode: CanvasNode,\n\t{ allowVariants, allowLockedNodes }: CanReplaceNodeOptions = {},\n): node is CanvasNode & WithPins & WithConstraints {\n\tif (!allowLockedNodes && isLockedOrLockedByParent(node)) return false\n\tif (isMaster(node)) return false\n\tif (!allowVariants && (isVariant(node) || isReplicaVariantOrReplicaVariantChild(node))) return false\n\tif (isSymbolReplicaChild(node)) return false\n\tif (isTextNode(node)) return false\n\tif (isShapeContainerNode(node)) return false\n\tif (isDynamicVectorInstance(node)) return false\n\treturn isPinnable(node)\n}\n\n/**\n * This function is async because we cannot guarantee that the `template` CanvasNode\n * component definition is available in the componentLoader (module loaded or bundle evaluated).\n */\nexport async function replaceNodeWithTemplate(\n\tengine: VekterEngine,\n\tnode: CanvasNode & WithPins & WithConstraints,\n\ttemplate: CanvasNode,\n\tasRelativeOverlay?: boolean,\n): Promise<void> {\n\tfunction performReplace() {\n\t\treplaceNodesWithTemplateAssumingComponentLoaded(engine, [node], template, asRelativeOverlay)\n\t}\n\n\tif (!isCodeComponentNode(template)) {\n\t\t// This is not a component and does not need any extra work.\n\t\tperformReplace()\n\t\treturn\n\t}\n\n\tconst identifier = parseModuleIdentifier(template.codeComponentIdentifier)\n\tif (!identifier || identifier.kind !== \"externalModuleExport\") {\n\t\t// This component does not need any external module loading.\n\t\tperformReplace()\n\t\treturn\n\t}\n\n\t// We need to add the external module to the project and make sure it's\n\t// evaluated before performing the replacement.\n\tawait engine.stores.modulesStore.addExternalModulesToProject([identifier], {\n\t\tonTreeUpdate: performReplace,\n\t})\n}\n\nexport function modifyLocalSmartComponentToBeFormButtonInstance(\n\ttree: CanvasTree,\n\tnode: CodeComponentNode,\n\tform: CanvasNode & WithFormContainer,\n): void {\n\tif (!isLocalSmartComponentInstance(node)) return\n\n\tconst scope = getSmartComponentOrWebPageForCodeComponent(tree, node)\n\tif (!isSmartComponentNode(scope)) return\n\n\tassert(scope.isLoaded(), \"smart component must be loaded\")\n\n\tform.set({ formSubmitButtonId: node.id })\n\n\tconst primaryVariant = scope.getPrimaryVariant()\n\n\t// Remove any overrides on the htmlTag and link properties of any replica\n\t// variants.\n\tscope.getReplicaVariants().forEach(replica => {\n\t\tTemplateHelper.resetOverridesByProperty(tree, replica, replica, [\"htmlTag\", \"link\"])\n\t})\n\n\t// And ensure that the primary variant is a button without a link (it cannot\n\t// be an <a>).\n\tif (requiresModificationsToBeFormButtonSource(primaryVariant)) {\n\t\t// If the primary variant of the new submit button didn't have a button\n\t\t// tag, or was a link, update it.\n\t\tprimaryVariant.set({ htmlTag: HTMLTag.button, link: undefined })\n\t}\n}\n\nfunction ensureLocalSmartComponentCanBeFormButtonInstance(tree: CanvasTree, node: CanvasNode, replacement: CanvasNode) {\n\tif (!isCodeComponentNode(node) || !isCodeComponentNode(replacement)) return\n\tif (!node.cache.formContainerAncestorId) return\n\tconst form = tree.get(node.cache.formContainerAncestorId)\n\tif (!isFormContainer(form)) return\n\tmodifyLocalSmartComponentToBeFormButtonInstance(tree, replacement, form)\n}\n\nfunction ensureLocalSmartComponentCanBeRepeaterLoaderInstance(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\treplacement: CanvasNode,\n) {\n\tconst repeaterNode = getParentDataRepeater(tree, node)\n\tif (!repeaterNode) return\n\n\t// If the node being replaced was a repeater loader, update the repeater to\n\t// point to the new instance.\n\tif (!isRepeaterLoaderInstance(node, repeaterNode)) return\n\trepeaterNode.set({ dataSourceLoaderId: replacement.id })\n}\n\n/**\n * Unlike `replaceWith` This function is synchronous and expects the `template` CanvasNode\n * component definitions to already be available to the componentLoader.\n */\nexport function replaceNodesWithTemplateAssumingComponentLoaded(\n\tengine: VekterEngine,\n\tnodes: (CanvasNode & WithPins & WithConstraints)[],\n\ttemplate: CanvasNode,\n\tasRelativeOverlay?: boolean,\n) {\n\tconst selectionIdChanges: Record<string, string> = {}\n\tconst selection = new Set<NodeID>()\n\tconst repeatedItemSnapshots = new Map<NodeID, ReturnType<typeof snapshotRepeatedItemsForNodes>[number]>()\n\tconst repeatedItemRenamedIds = new RenamedIds()\n\n\tconst { treeStore, selectionStore, scopeStore } = engine.stores\n\tconst componentLoader = engine.componentLoader\n\tconst tree = treeStore.getDataTreeOrPartialTree()\n\n\tnodes.forEach(node => {\n\t\tlet addingToVariant: (CanvasNode & IsVariant) | null = null\n\n\t\tif (isReplicaChild(node)) {\n\t\t\tif (!isReplicaVariantChild(node)) {\n\t\t\t\t// We can't replace symbol children\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst originalNode = getOriginalVariantNodeIfExists(tree, node) as\n\t\t\t\t| (CanvasNode & WithPins & WithConstraints)\n\t\t\t\t| null\n\t\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, node)\n\n\t\t\tif (!originalNode || !replica || !isVariant(replica)) return\n\n\t\t\tnode = originalNode\n\t\t\taddingToVariant = replica\n\t\t}\n\n\t\tfor (const snapshot of snapshotRepeatedItemsForNodes(tree, [node])) {\n\t\t\trepeatedItemSnapshots.set(snapshot.repeaterId, snapshot)\n\t\t}\n\n\t\tconst nonScopeNodeParent = tree.getNodeParent(node)\n\t\tconst parentOfOriginal = nonScopeNodeParent || tree.getScopeNodeFor(node) || scopeStore.active\n\n\t\tconst indexOfOriginal = parentOfOriginal.children.indexOf(node)\n\n\t\tconst replacement = insertTemplateNode(engine, template, parentOfOriginal.id, indexOfOriginal, tree)\n\t\trepeatedItemRenamedIds.set(node.id, replacement.id)\n\t\tensureLocalSmartComponentCanBeFormButtonInstance(tree, node, replacement)\n\t\tensureLocalSmartComponentCanBeRepeaterLoaderInstance(tree, node, replacement)\n\n\t\t// Move all style and code component properties along that have the same key and type\n\t\tconst compatibleStyles = getCompatibleNodeProperties(tree, componentLoader, node, replacement, parentOfOriginal)\n\t\treplacement.set(compatibleStyles)\n\t\t// @TODO: for now we're updating the node connects only for floating overlays to reduce the impact. But maybe we\n\t\t// should consider updating it regardless?\n\t\tif (nonScopeNodeParent && hasFloatingPosition(node) && withFloatingPosition(replacement)) {\n\t\t\treplacement.set(getFloatingPositionProps(node))\n\t\t\tconst renamedIds = new RenamedIds([[node.id, replacement.id]])\n\t\t\tupdateNodeConnections(\n\t\t\t\ttree,\n\t\t\t\tcomponentLoader,\n\t\t\t\tnonScopeNodeParent,\n\t\t\t\trenamedIds,\n\t\t\t\tisFixedOrRelativeOverlay(nonScopeNodeParent) || nodeIsInOverlay(nonScopeNodeParent),\n\t\t\t)\n\t\t\tselection.add(replacement.id)\n\t\t}\n\t\tif (isCodeComponentNode(replacement)) {\n\t\t\treapplyActions(componentLoader, node, replacement, new Set(Object.keys(compatibleStyles)))\n\t\t}\n\n\t\t// Convert symbol properties to smart component variables\n\t\tif (isReplica(node) && !isVariant(node) && isCodeComponentNode(replacement)) {\n\t\t\tconvertSymbolPropertiesToSmartComponentInstanceControlValues(tree, node, replacement)\n\t\t}\n\n\t\t// Use existing variant node overrides to replacement\n\t\tupdateVariantOverridesWithCompatibleProperties(tree, parentOfOriginal, node, replacement)\n\n\t\tif (withChildren(node)) {\n\t\t\tfor (const child of node.children) {\n\t\t\t\tif (!isFixedOrRelativeOverlay(child)) continue\n\t\t\t\tengine.moveNode(child.id, replacement.id, undefined, undefined, tree)\n\t\t\t}\n\t\t}\n\t\tengine.deleteNode(node.id)\n\t\tconst layoutUpdate = layoutPropsForNodeReplacement(tree, componentLoader, node, replacement)\n\t\tif (isPinnable(replacement) && layoutUpdate) {\n\t\t\tif (asRelativeOverlay) {\n\t\t\t\t// When replacing layers with floating position enabled,\n\t\t\t\t// preserve the size of the template.\n\t\t\t\ttree.current(replacement)?.set({\n\t\t\t\t\tleft: layoutUpdate.left,\n\t\t\t\t\tright: layoutUpdate.right,\n\t\t\t\t\ttop: layoutUpdate.top,\n\t\t\t\t\tbottom: layoutUpdate.bottom,\n\t\t\t\t\tcenterAnchorX: layoutUpdate.centerAnchorX,\n\t\t\t\t\tcenterAnchorY: layoutUpdate.centerAnchorY,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\ttree.current(replacement)?.set(layoutUpdate)\n\t\t\t}\n\t\t}\n\n\t\t// Make sure that the selection is updated for this id.\n\t\tif (addingToVariant) {\n\t\t\tselectionIdChanges[node.id] = generateReplicaChildId(addingToVariant.id, replacement.id)\n\t\t} else {\n\t\t\tselectionIdChanges[node.id] = replacement.id\n\t\t}\n\t})\n\n\trestoreRepeatedItemsFromSnapshots(tree, repeatedItemSnapshots.values(), repeatedItemRenamedIds)\n\n\tfor (const id of selectionStore.ids) selection.add(selectionIdChanges[id] ?? id)\n\n\t// Update the selection to use the new node ids.\n\tselectionStore.set(Array.from(selection))\n}\n\nfunction convertSymbolPropertiesToSmartComponentInstanceControlValues(\n\ttree: CanvasTree,\n\tsymbol: CanvasNode & IsReplica,\n\tcodeComponent: CodeComponentNode,\n) {\n\tif (isVariant(symbol)) return\n\tconst smartComponentId = codeComponent.getLocalSmartComponentNodeId()\n\tif (!smartComponentId) return\n\n\tconst localSmartComponent = tree.getNode(smartComponentId)\n\tif (!localSmartComponent || !isSmartComponentNode(localSmartComponent)) return\n\n\t// Check if symbol is related to smart component\n\tif (localSmartComponent.originalSymbolId !== symbol.replicaInfo.master) return\n\n\tfor (const symbolDescendant of symbol.walk()) {\n\t\tif (!withTarget(symbolDescendant) || !symbolDescendant.isTarget) continue\n\t\tif (!symbolDescendant.originalid) continue\n\n\t\tif (\n\t\t\tisFrameNode(symbolDescendant) &&\n\t\t\tsymbolDescendant.fillType === \"image\" &&\n\t\t\tisString(symbolDescendant.fillImage)\n\t\t) {\n\t\t\t// Update image control value with symbol override\n\t\t\tconst controlProp = codeComponent.getRawControlProp(`symbol_${symbolDescendant.originalid}`)\n\t\t\tif (controlProp && controlProp.type === ControlType.Image) {\n\t\t\t\tcontrolProp.value = symbolDescendant.fillImage\n\t\t\t}\n\t\t} else if (isTextNode(symbolDescendant)) {\n\t\t\t// Update text control value with symbol override\n\t\t\tconst controlProp = codeComponent.getRawControlProp(`symbol_${symbolDescendant.originalid}`)\n\t\t\tif (controlProp && controlProp.type === ControlType.String) {\n\t\t\t\tcontrolProp.value = symbolDescendant.styledText.text\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * If we find a single set of actions we try to re-apply it to the first code component event handler.\n * Provide the `propsToSkip` argument to avoid replacing any properties that were already handled.\n */\nfunction reapplyActions(\n\tcomponentLoader: ComponentLoader,\n\tnode: CanvasNode,\n\treplacement: CodeComponentNode,\n\tpropsToSkip?: Set<string>,\n) {\n\t// We only try to re-apply the actions if we find a single list of actions, null means we found multiple.\n\t// We ignore multiple lists because it is impossible to apply them correctly.\n\tlet actionsToReapply: EventActions | null | undefined = undefined\n\n\twalk: for (const descendant of node.walk()) {\n\t\tif (!withFrameEvents(descendant) && !isCodeComponentNode(descendant)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst actionMap = getActionsForNode(componentLoader, descendant)\n\t\tfor (const [, actions] of Object.entries(actionMap)) {\n\t\t\tif (actionsToReapply === undefined) {\n\t\t\t\tactionsToReapply = actions\n\t\t\t} else if (actionsToReapply) {\n\t\t\t\tactionsToReapply = null\n\t\t\t\tbreak walk\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!actionsToReapply) return\n\tconst componentDefinition = componentLoader.componentForIdentifier(replacement.codeComponentIdentifier)\n\tif (!componentDefinition?.properties) return\n\n\tfor (const prop in componentDefinition.properties) {\n\t\t// Don't reapply actions on props that already had a direct 1:1 match.\n\t\tif (propsToSkip?.has(prop)) continue\n\n\t\tconst controlDef = componentDefinition.properties[prop]\n\t\tif (controlDef?.type !== ControlType.EventHandler) continue\n\n\t\tconst controlProp: ControlProp = {\n\t\t\ttype: ControlType.EventHandler,\n\t\t\tvalue: actionsToReapply,\n\t\t}\n\n\t\treplacement.set(prefixControlProps({ [prop]: controlProp }))\n\n\t\treturn\n\t}\n}\n\n/**\n * Deletes the overrides for the node and applies all compatible overrides to the replacement\n */\nfunction updateVariantOverridesWithCompatibleProperties(\n\ttree: CanvasTree,\n\tparentOfOriginal: CanvasNode,\n\tnode: CanvasNode,\n\treplacement: CanvasNode,\n) {\n\tconst masterAncestor = parentOfOriginal ? getMasterAncestor(parentOfOriginal) : null\n\tif (!masterAncestor) return\n\tif (!isPrimaryVariant(masterAncestor)) return\n\n\tconst smartComponent = SmartComponentNode.getFor(tree, masterAncestor)\n\tif (!smartComponent) return\n\n\tfor (const replicaVariant of smartComponent.getReplicaVariants()) {\n\t\tconst replicaInfo = replicaVariant.replicaInfo\n\t\tif (!(node.id in replicaInfo.overrides)) continue\n\t\tconst newReplicaInfo = { ...replicaInfo }\n\t\tnewReplicaInfo.overrides = { ...newReplicaInfo.overrides }\n\n\t\t// Collect the compatible overrides\n\t\tconst compatibleOverrides: ReplicaNodeOverrides = {}\n\t\tconst currentOverrides = newReplicaInfo.overrides[node.id]\n\t\tfor (const key in currentOverrides) {\n\t\t\tconst value = currentOverrides[key]\n\t\t\tif (key === \"_deleted\") {\n\t\t\t\tif (!isArray(value)) continue\n\t\t\t\tconst newDeleted = value.filter((deletedKey: string): deletedKey is string => deletedKey in replacement)\n\t\t\t\tif (newDeleted.length) {\n\t\t\t\t\tcompatibleOverrides._deleted = newDeleted\n\t\t\t\t}\n\t\t\t} else if (key in replacement) {\n\t\t\t\tcompatibleOverrides[key] = value\n\t\t\t}\n\t\t}\n\n\t\tdelete newReplicaInfo.overrides[node.id]\n\t\tnewReplicaInfo.overrides[replacement.id] = compatibleOverrides\n\t\ttree.current(replicaVariant)?.set({ replicaInfo: newReplicaInfo })\n\t}\n}\n\n/**\n * Returns layout props from the source node and ensures they are compatible\n * with the replacement node, converting auto dimensions to fixed if necessary.\n * Also propagates grid-related props in case item is going into a grid, as otherwise\n * the height & width values can distort the layout.\n */\nfunction layoutPropsForNodeReplacement(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tsource: CanvasNode,\n\ttarget: CanvasNode,\n): Partial<VekterConstraintValues & WithGridItemSize> | undefined {\n\tif (!isPinnable(source) || !isPinnable(target)) return\n\n\tconst props = source.constraintValues() as Partial<VekterConstraintValues & WithGridItemSize>\n\n\tif (withGridItemSize(source) && withGridItemSize(target)) {\n\t\tif (isGridChildFillingCellWidth(source)) props.gridItemFillCellWidth = true\n\t\tif (isGridChildFillingCellHeight(source)) props.gridItemFillCellHeight = true\n\t}\n\n\tif (!isCodeComponentNode(target)) return props\n\n\tif (isAutoSizedOnAnyDimension(source)) {\n\t\tconst supportedLayout = target.getSupportedLayout(componentLoader)\n\t\tconst rect = tree.getRect(source)\n\n\t\tif (source.widthType === DimensionType.Auto && !supportsAutoSizing(supportedLayout.width)) {\n\t\t\tprops.widthType = DimensionType.FixedNumber\n\t\t\tprops.width = rect.width\n\t\t}\n\n\t\tif (source.widthType === DimensionType.FitImage) {\n\t\t\tprops.widthType = supportsAutoSizing(supportedLayout.width) ? DimensionType.Auto : DimensionType.FixedNumber\n\t\t}\n\n\t\tif (source.heightType === DimensionType.Auto && !supportsAutoSizing(supportedLayout.height)) {\n\t\t\tprops.heightType = DimensionType.FixedNumber\n\t\t\tprops.height = rect.height\n\t\t}\n\n\t\tif (source.heightType === DimensionType.FitImage) {\n\t\t\tprops.heightType = supportsAutoSizing(supportedLayout.height) ? DimensionType.Auto : DimensionType.FixedNumber\n\t\t}\n\t}\n\n\treturn props\n}\n\nexport function getComponentToUseAsReplacement(componentDefinition: EntityDefinition): CodeComponentNode | null {\n\treturn isReactComponentDefinition(componentDefinition) ? codeComponentFromDefinition(componentDefinition) : null\n}\n\n/**\n * We will modify local smart components to be suitable for use as form submit\n * button on replace. We prompt users if this is going to happen to avoid\n * unexpected changes.\n */\nexport async function replacingSubmitButtonWithTemplateWillModifyTemplate(\n\ttree: CanvasTree,\n\tnode: CodeComponentNode,\n): Promise<boolean> {\n\tif (!isLocalSmartComponentInstance(node)) return false\n\tconst scopeId = node.getLocalSmartComponentNodeId()\n\tconst scopeNode = tree.getNode(scopeId)\n\tif (!isSmartComponentNode(scopeNode)) return false\n\n\tconst loaded = scopeNode.isLoaded() ? scopeNode : await scopeNode.load()\n\tif (!isSmartComponentNode(loaded)) return false\n\n\treturn !canLoadedComponentBeFormButtonSource(loaded)\n}\n", "import type { CanvasTree, NodeID, ShapeContainerNode, VectorNode } from \"document/models/CanvasTree/index.ts\"\nimport type { WithBoxShadow } from \"document/models/CanvasTree/traits/WithBoxShadow.ts\"\nimport { supportsBoxShadow, withBoxShadow } from \"document/models/CanvasTree/traits/WithBoxShadow.ts\"\nimport type { WithRadius } from \"document/models/CanvasTree/traits/WithRadius.ts\"\nimport { withRadius } from \"document/models/CanvasTree/traits/WithRadius.ts\"\nimport type { WithRadiusPerCorner } from \"document/models/CanvasTree/traits/WithRadiusPerCorner.ts\"\nimport { withRadiusPerCorner } from \"document/models/CanvasTree/traits/WithRadiusPerCorner.ts\"\nimport type { StrokeDash, StrokeWidth } from \"document/models/CanvasTree/traits/WithStroke.ts\"\nimport { withStroke } from \"document/models/CanvasTree/traits/WithStroke.ts\"\nimport type { BoxShadow } from \"document/models/Shadow.ts\"\nimport { getUpdatedShadow, isBoxShadowList } from \"document/models/Shadow.ts\"\nimport { Map } from \"immutable\"\nimport type { WithPath } from \"library/render/traits/Path.ts\"\nimport { withPath } from \"library/render/traits/Path.ts\"\nimport type { PathSegment } from \"library/render/types/PathSegment.ts\"\nimport { roundedNumber } from \"library/render/utils/roundedNumber.ts\"\nimport { isNumber, isString } from \"utils/typeChecks.ts\"\nimport type { DynamicValue, NonDynamicValueRecord } from \"./DynamicValue.ts\"\nimport { isDynamicValue } from \"./DynamicValue.ts\"\nimport type { WithFill } from \"./WithFill.ts\"\nimport { withFill } from \"./WithFill.ts\"\n\nexport type ScalableVectorStyles = Partial<\n\tNonDynamicValueRecord<StrokeWidth> &\n\t\tStrokeDash &\n\t\tWithBoxShadow &\n\t\tWithRadius &\n\t\tWithRadiusPerCorner &\n\t\tWithPath &\n\t\tWithFill\n>\n\nexport function collectScalableVectorStyles(node: ShapeContainerNode | VectorNode) {\n\tconst result: { [id: string]: ScalableVectorStyles } = {}\n\n\tfor (const n of node.walk()) {\n\t\tconst styles: ScalableVectorStyles = {}\n\t\tif (withStroke(n)) {\n\t\t\tstyles.strokeDashArray = n.strokeDashArray\n\t\t\tstyles.strokeDashOffset = n.strokeDashOffset\n\t\t\tif (!isDynamicValue(n.strokeWidth)) {\n\t\t\t\tstyles.strokeWidth = n.strokeWidth\n\t\t\t}\n\t\t}\n\n\t\tif (supportsBoxShadow(n)) {\n\t\t\tstyles.boxShadows = n.boxShadows\n\t\t}\n\n\t\tif (withRadius(n)) {\n\t\t\tstyles.radius = n.radius\n\t\t}\n\t\tif (withRadiusPerCorner(n)) {\n\t\t\tstyles.radiusTopLeft = n.radiusTopLeft\n\t\t\tstyles.radiusTopRight = n.radiusTopRight\n\t\t\tstyles.radiusBottomRight = n.radiusBottomRight\n\t\t\tstyles.radiusBottomLeft = n.radiusBottomLeft\n\t\t}\n\t\tif (withPath(n)) {\n\t\t\tstyles.pathSegments = n.pathSegments\n\t\t}\n\t\tif (withFill(n) && n.fillType === \"image\" && n.fillImageResize === \"tile\") {\n\t\t\tstyles.fillImageTileSize = n.fillImageTileSize ?? 1\n\t\t}\n\n\t\tresult[n.id] = styles\n\t}\n\n\treturn Map(result)\n}\n\nexport function scaleVectorStyles(\n\ttree: CanvasTree,\n\tbeginState: Map<NodeID, ScalableVectorStyles>,\n\tscaleFactor: number,\n) {\n\tbeginState.forEach((scalableStyles: ScalableVectorStyles, id: NodeID) => {\n\t\tconst node = tree.getNode(id)\n\t\tif (!node) return\n\n\t\tconst scaleUpdate: ScalableVectorStyles = {}\n\n\t\tif (withStroke(node)) {\n\t\t\tif (isNumber(scalableStyles.strokeWidth)) {\n\t\t\t\tscaleUpdate.strokeWidth = roundedNumber(scalableStyles.strokeWidth * scaleFactor, 2)\n\t\t\t}\n\n\t\t\tif (isString(scalableStyles.strokeDashArray)) {\n\t\t\t\tscaleUpdate.strokeDashArray = scaleDashArray(scalableStyles.strokeDashArray, scaleFactor)\n\t\t\t}\n\n\t\t\tif (isNumber(scalableStyles.strokeDashOffset)) {\n\t\t\t\tscaleUpdate.strokeDashOffset = roundedNumber(scalableStyles.strokeDashOffset * scaleFactor, 2)\n\t\t\t}\n\t\t}\n\n\t\tif (withBoxShadow(node) && isBoxShadowList(scalableStyles.boxShadows)) {\n\t\t\tscaleUpdate.boxShadows = scaleShadow(scalableStyles.boxShadows, scaleFactor)\n\t\t}\n\n\t\tif (withRadius(node)) {\n\t\t\tif (isNumber(scalableStyles.radius)) {\n\t\t\t\tscaleUpdate.radius = roundedNumber(scalableStyles.radius * scaleFactor, 2)\n\t\t\t}\n\n\t\t\tif (isNumber(scalableStyles.radiusTopLeft)) {\n\t\t\t\tscaleUpdate.radiusTopLeft = roundedNumber(scalableStyles.radiusTopLeft * scaleFactor, 2)\n\t\t\t}\n\n\t\t\tif (isNumber(scalableStyles.radiusTopRight)) {\n\t\t\t\tscaleUpdate.radiusTopRight = roundedNumber(scalableStyles.radiusTopRight * scaleFactor, 2)\n\t\t\t}\n\n\t\t\tif (isNumber(scalableStyles.radiusBottomRight)) {\n\t\t\t\tscaleUpdate.radiusBottomRight = roundedNumber(scalableStyles.radiusBottomRight * scaleFactor, 2)\n\t\t\t}\n\n\t\t\tif (isNumber(scalableStyles.radiusBottomLeft)) {\n\t\t\t\tscaleUpdate.radiusBottomLeft = roundedNumber(scalableStyles.radiusBottomLeft * scaleFactor, 2)\n\t\t\t}\n\t\t}\n\n\t\tif (withPath(node) && scalableStyles.pathSegments) {\n\t\t\tscaleUpdate.pathSegments = node.pathSegments.map((pathSegment: PathSegment, index: number) => {\n\t\t\t\tconst segment = scalableStyles.pathSegments![index]!\n\t\t\t\tconst radius = segment.radius * scaleFactor\n\t\t\t\treturn pathSegment.merge({ radius })\n\t\t\t})\n\t\t}\n\n\t\tif (withFill(node) && isNumber(scalableStyles.fillImageTileSize)) {\n\t\t\tscaleUpdate.fillImageTileSize = scalableStyles.fillImageTileSize * scaleFactor\n\t\t}\n\n\t\tnode.set(scaleUpdate)\n\t})\n}\n\nfunction scaleShadow(\n\tshadows: readonly BoxShadow[] | DynamicValue | undefined,\n\tscale: number,\n): readonly BoxShadow[] | undefined {\n\tif (!shadows || isDynamicValue(shadows)) return undefined\n\treturn shadows.map((shadow: BoxShadow) => {\n\t\treturn getUpdatedShadow(shadow, {\n\t\t\tx: roundedNumber(shadow.x * scale, 2),\n\t\t\ty: roundedNumber(shadow.y * scale, 2),\n\t\t\tblur: roundedNumber(shadow.blur * scale, 2),\n\t\t\tspread: roundedNumber(shadow.spread * scale, 2),\n\t\t})\n\t})\n}\n\nfunction scaleDashArray(dashArray: string, scale: number) {\n\tconst numberValues: number[] = []\n\tconst stringValues = dashArray.split(\",\")\n\tfor (const stringValue of stringValues) {\n\t\tconst value = parseFloat(stringValue)\n\t\tif (!isNumber(value)) continue\n\t\tconst scaledValue = roundedNumber(value * scale, 2)\n\t\tnumberValues.push(scaledValue)\n\t}\n\treturn numberValues.join(\", \")\n}\n", "import { paddingFromNode } from \"document/utils/StackComponent/paddingFromNode.ts\"\nimport type { Size } from \"library/render/types/Size.ts\"\nimport type { CanvasNode, CanvasTree } from \"../../index.ts\"\nimport { isFrameNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { hasAnyLayout } from \"../WithLayout.ts\"\n\nexport function getSizeMinusPadding(tree: CanvasTree, node: CanvasNode): Size {\n\tconst rect = tree.getRect(node)\n\tconst size: Size = { width: rect.width, height: rect.height }\n\n\tif (!isFrameNode(node) || !hasAnyLayout(node)) return size\n\n\tconst padding = paddingFromNode(node)\n\n\tif (padding.perSide) {\n\t\tif (padding.top) size.height -= padding.top\n\t\tif (padding.bottom) size.height -= padding.bottom\n\t\tif (padding.right) size.width -= padding.right\n\t\tif (padding.left) size.width -= padding.left\n\t} else if (padding.top) {\n\t\tconst doublePadding = padding.top * 2\n\t\tsize.width -= doublePadding\n\t\tsize.height -= doublePadding\n\t}\n\n\tsize.width = Math.max(1, size.width)\n\tsize.height = Math.max(1, size.height)\n\n\treturn size\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport {\n\tcollectDescendantShapesAndFlattenRotations,\n\tconvertPath,\n\tconvertPathFromNodeToDescendant,\n\tconvertPathToCanvas,\n\tconvertPathToNode,\n\tconvertPointToParent,\n} from \"document/components/tools/pathEdit/utils/index.ts\"\nimport type {\n\tCanvasNode,\n\tCanvasTree,\n\tNodeID,\n\tPathNode,\n\tShapeContainerNode,\n\tVectorNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { isVectorNode } from \"document/models/CanvasTree/index.ts\"\nimport { isShapeContainerNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withAspectRatio } from \"document/models/CanvasTree/traits/WithAspectRatio.ts\"\nimport { getLayoutType } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { withShape } from \"document/models/CanvasTree/traits/WithShape.ts\"\nimport type { BasicShapeNode } from \"document/models/CanvasTree/traits/utils/basicShape/index.ts\"\nimport { getSizeMinusPadding } from \"document/models/CanvasTree/traits/utils/sizeMinusPadding.ts\"\nimport { convertPointFromNodeToDescendant } from \"document/models/CanvasTree/utils/geometry.ts\"\nimport { Matrix } from \"document/models/Matrix.ts\"\nimport { Path } from \"document/models/Path.ts\"\nimport type { Map } from \"immutable\"\nimport { modulate } from \"library/index.ts\"\nimport type { WithPath } from \"library/render/traits/Path.ts\"\nimport type { WithShape } from \"library/render/traits/Shape.ts\"\nimport type { PathSegment } from \"library/render/types/PathSegment.ts\"\nimport type { Point } from \"library/render/types/Point.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport { Size } from \"library/render/types/Size.ts\"\nimport { roundToHalfPixel } from \"library/render/utils/roundedNumber.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\n\nexport type FlipAxis = \"horizontal\" | \"vertical\"\n\nexport function flipShapes(tree: CanvasTree, engine: VekterEngine, ids: NodeID[], axis: FlipAxis) {\n\tconst nodes = tree.getNodesWithTrait(ids, isVectorNode)\n\tnodes.forEach(node => {\n\t\tconst { descendantPaths } = collectDescendantShapesAndFlattenRotations(engine, node, true, ids)\n\n\t\tconst withPaths = descendantPaths.valueSeq().toArray()\n\t\tconst startRect = Path.boundingBox(withPaths)\n\n\t\tconst resizeRect = {\n\t\t\t...startRect,\n\t\t}\n\n\t\tif (axis === \"horizontal\") {\n\t\t\tresizeRect.x = startRect.x + startRect.width\n\t\t\tresizeRect.width = -startRect.width\n\t\t} else {\n\t\t\tresizeRect.y = startRect.y + startRect.height\n\t\t\tresizeRect.height = -startRect.height\n\t\t}\n\n\t\tconst toWidth = resizeRect.width > -1 && resizeRect.width < 1 ? 1 : resizeRect.width\n\t\tconst toHeight = resizeRect.height > -1 && resizeRect.height < 1 ? 1 : resizeRect.height\n\t\tconst xFromRange: [number, number] = [startRect.x, startRect.x + startRect.width]\n\t\tconst xToRange: [number, number] = [resizeRect.x, resizeRect.x + toWidth]\n\t\tconst yFromRange: [number, number] = [startRect.y, startRect.y + startRect.height]\n\t\tconst yToRange: [number, number] = [resizeRect.y, resizeRect.y + toHeight]\n\t\tconst widthRatio = toWidth / startRect.width\n\t\tconst heightRatio = toHeight / startRect.height\n\n\t\tdescendantPaths.forEach((path: WithPath, id: NodeID) => {\n\t\t\tconst pathSegments = path.pathSegments.map((segment: PathSegment) => {\n\t\t\t\treturn segment.merge({\n\t\t\t\t\tx: modulate(segment.x, xFromRange, xToRange, false),\n\t\t\t\t\ty: modulate(segment.y, yFromRange, yToRange, false),\n\t\t\t\t\thandleOutX: segment.handleOutX * widthRatio,\n\t\t\t\t\thandleOutY: segment.handleOutY * heightRatio,\n\t\t\t\t\thandleInX: segment.handleInX * widthRatio,\n\t\t\t\t\thandleInY: segment.handleInY * heightRatio,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tassert(engine.tree === tree)\n\t\t\tconst pathNode = tree.get<PathNode>(id)\n\t\t\tif (!pathNode) return\n\n\t\t\tconst withPath = { pathSegments, pathClosed: pathNode.pathClosed }\n\t\t\tconst projectedBack = convertPathToNode(tree, pathNode, [withPath])\n\t\t\tconst newPath = { pathSegments: projectedBack[0], pathClosed: pathNode.pathClosed }\n\t\t\tconst pathUpdate = pathNode.updateForPath(newPath)\n\n\t\t\tpathNode.set(pathUpdate)\n\t\t})\n\t})\n}\n\nexport function updateNodeSizeForEach(\n\tengine: VekterEngine,\n\tnodes: CanvasNode[],\n\tupdate: (currentSize: Size) => Partial<Size>,\n) {\n\tconst { tree } = engine\n\tnodes.forEach(node => {\n\t\tconst frame = tree.getRect(node)\n\t\tconst newSize = update(frame)\n\t\tif (newSize.width && newSize.width < 1) {\n\t\t\tnewSize.width = 1\n\t\t}\n\t\tif (newSize.height && newSize.height < 1) {\n\t\t\tnewSize.height = 1\n\t\t}\n\n\t\tif (isShapeContainerNode(node)) {\n\t\t\tupdateShapeContainerSize(engine, node, newSize)\n\t\t} else if (withShape(node)) {\n\t\t\tupdateShapeSize(engine, node, newSize)\n\t\t} else {\n\t\t\tconst parentNode = tree.getParent(node.id)\n\t\t\tconst parentSize = parentNode ? getSizeMinusPadding(tree, parentNode) : null\n\t\t\tconst nodeUpdate = node.updateForSize(\n\t\t\t\tnewSize,\n\t\t\t\t// The update is always performed on an exisiting node, so we trust the viewport in the node cache has\n\t\t\t\t// been initialized.\n\t\t\t\tparentSize\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tsizing: parentSize,\n\t\t\t\t\t\t\tpositioning: parentSize,\n\t\t\t\t\t\t\tviewport: node.cache.viewportRect,\n\t\t\t\t\t\t\tlayout: getLayoutType(parentNode),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t)\n\t\t\ttree.current(node)?.set(nodeUpdate as any)\n\t\t}\n\t})\n}\n\nfunction updateShapeContainerSize(engine: VekterEngine, shapeContainer: ShapeContainerNode, size: Partial<Size>) {\n\tconst { tree } = engine\n\n\tconst parentNode = tree.getParent(shapeContainer.id)\n\tconst parentRect = parentNode ? tree.getRect(parentNode) : null\n\t// Shape containers can't use viewHeight, so the sizing and positioning rects are the same, and they don't need\n\t// the viewport part of parentSizeInfo.\n\tconst nodeUpdate: Partial<ShapeContainerNode> = shapeContainer.updateForSize(\n\t\tsize,\n\t\tparentRect\n\t\t\t? {\n\t\t\t\t\tsizing: parentRect,\n\t\t\t\t\tpositioning: parentRect,\n\t\t\t\t\tviewport: null,\n\t\t\t\t\tlayout: getLayoutType(parentNode),\n\t\t\t\t}\n\t\t\t: null,\n\t)\n\tnodeUpdate.sizeToFit = false\n\ttree.current(shapeContainer)?.set(nodeUpdate)\n}\n\nfunction updateShapeSize(engine: VekterEngine, node: CanvasNode & WithShape, size: Partial<Size>) {\n\tconst { tree } = engine\n\tconst startRect = tree.getRect(node)\n\tconst sizeUpdate = Size.update(startRect, size, withAspectRatio(node) ? isNumber(node.aspectRatio) : false)\n\tconst resizeRect = { ...startRect, ...sizeUpdate }\n\n\tconst toWidth = resizeRect.width > -1 && resizeRect.width < 1 ? 1 : resizeRect.width\n\tconst toHeight = resizeRect.height > -1 && resizeRect.height < 1 ? 1 : resizeRect.height\n\tconst xFromRange: [number, number] = [startRect.x, startRect.x + startRect.width]\n\tconst xToRange: [number, number] = [resizeRect.x, resizeRect.x + toWidth]\n\tconst yFromRange: [number, number] = [startRect.y, startRect.y + startRect.height]\n\tconst yToRange: [number, number] = [resizeRect.y, resizeRect.y + toHeight]\n\tconst widthRatio = toWidth / startRect.width\n\tconst heightRatio = toHeight / startRect.height\n\n\tconst { descendantPaths, descendantBasicShapes } = collectDescendantShapesAndFlattenRotations(engine, node)\n\n\tdescendantPaths.forEach((path: WithPath, id: NodeID) => {\n\t\tconst localPath = convertPathToNode(tree, node, [path])[0]\n\n\t\tconst modulatedPathSegments = localPath.map((segment: PathSegment) => {\n\t\t\treturn segment.merge({\n\t\t\t\tx: modulate(segment.x + startRect.x, xFromRange, xToRange, false) - startRect.x,\n\t\t\t\ty: modulate(segment.y + startRect.y, yFromRange, yToRange, false) - startRect.y,\n\t\t\t\thandleOutX: segment.handleOutX * widthRatio,\n\t\t\t\thandleOutY: segment.handleOutY * heightRatio,\n\t\t\t\thandleInX: segment.handleInX * widthRatio,\n\t\t\t\thandleInY: segment.handleInY * heightRatio,\n\t\t\t})\n\t\t})\n\n\t\tconst globalPath = convertPathToCanvas(tree, node, {\n\t\t\tpathSegments: modulatedPathSegments,\n\t\t\tpathClosed: true,\n\t\t})\n\t\tassert(engine.tree === tree)\n\t\tconst pathNode = tree.get<PathNode>(id)\n\t\tif (!pathNode) return\n\n\t\tconst projectedBack = convertPathToNode(tree, pathNode, globalPath)\n\t\tconst newPath = { pathSegments: projectedBack[0], pathClosed: pathNode.pathClosed }\n\t\tconst pathUpdate = pathNode.updateForPath(newPath)\n\n\t\tpathNode.set(pathUpdate)\n\t})\n\n\tdescendantBasicShapes.forEach((points: Point[], id: NodeID) => {\n\t\tif (points === null) {\n\t\t\treturn\n\t\t}\n\n\t\tconst localPoints = points.map(point => {\n\t\t\treturn tree.convertPointToNode(node, point)\n\t\t})\n\n\t\tconst modulatedPoints = localPoints.map(point => {\n\t\t\treturn {\n\t\t\t\tx: modulate(point.x + startRect.x, xFromRange, xToRange, false) - startRect.x,\n\t\t\t\ty: modulate(point.y + startRect.y, yFromRange, yToRange, false) - startRect.y,\n\t\t\t}\n\t\t})\n\t\tconst globalPoints = modulatedPoints.map(point => {\n\t\t\treturn tree.convertPointToCanvas(node, point)\n\t\t})\n\n\t\tconst basicShape = tree.get<VectorNode>(id)\n\t\tif (!basicShape) return\n\n\t\tconst projectedBack = globalPoints.map(point => {\n\t\t\treturn tree.convertPointToNode(basicShape, point)\n\t\t})\n\n\t\tconst localRect = Rect.boundingRectFromPoints(projectedBack)\n\t\tconst center = Rect.center(localRect)\n\n\t\tconst centerInParent = convertPointToParent(basicShape, center)\n\n\t\tconst newRect = {\n\t\t\tx: centerInParent.x - localRect.width / 2,\n\t\t\ty: centerInParent.y - localRect.height / 2,\n\t\t\twidth: localRect.width,\n\t\t\theight: localRect.height,\n\t\t}\n\n\t\tbasicShape.set(newRect)\n\t})\n}\n\nexport function scaleShapeContainerDescendantShapes(\n\tengine: VekterEngine,\n\tshapeContainer: ShapeContainerNode,\n\tdescendantPaths: Map<NodeID, WithPath>,\n\tdescendantBasicShapes: Map<NodeID, null | Point[]>,\n\tstartSize: Size,\n\tnewSize: Size,\n) {\n\tconst { tree } = engine\n\n\tconst currentShapeContainer = tree.getNode(shapeContainer.id) as ShapeContainerNode\n\n\tconst toWidth = newSize.width > -1 && newSize.width < 1 ? 1 : newSize.width\n\tconst toHeight = newSize.height > -1 && newSize.height < 1 ? 1 : newSize.height\n\tconst widthRatio = toWidth / startSize.width\n\tconst heightRatio = toHeight / startSize.height\n\n\tdescendantPaths.forEach((pathBeginState: WithPath, id: NodeID) => {\n\t\tconst pathNode = tree.getNode(id) as PathNode\n\t\tif (!pathNode) return\n\n\t\tconst modulatedPathSegments = pathBeginState.pathSegments.map((segment: PathSegment) => {\n\t\t\treturn segment.merge({\n\t\t\t\tx: segment.x * widthRatio,\n\t\t\t\ty: segment.y * heightRatio,\n\t\t\t\thandleOutX: segment.handleOutX * widthRatio,\n\t\t\t\thandleOutY: segment.handleOutY * heightRatio,\n\t\t\t\thandleInX: segment.handleInX * widthRatio,\n\t\t\t\thandleInY: segment.handleInY * heightRatio,\n\t\t\t})\n\t\t})\n\n\t\tconst shapeContainerPath = {\n\t\t\tpathSegments: modulatedPathSegments,\n\t\t\tpathClosed: pathBeginState.pathClosed,\n\t\t}\n\n\t\tconst projectedBack = convertPathFromNodeToDescendant(tree, currentShapeContainer, pathNode, [shapeContainerPath])\n\n\t\tconst newPath = { pathSegments: projectedBack[0], pathClosed: pathNode.pathClosed }\n\t\tconst update = pathNode.updateForPath(newPath)\n\t\tpathNode.set(update)\n\t})\n\n\tdescendantBasicShapes.forEach((cornerPointsAtStart: Point[] | null, id: NodeID) => {\n\t\tif (cornerPointsAtStart === null) {\n\t\t\treturn\n\t\t}\n\n\t\tconst modulatedPoints = cornerPointsAtStart.map(point => {\n\t\t\treturn {\n\t\t\t\tx: point.x * widthRatio,\n\t\t\t\ty: point.y * heightRatio,\n\t\t\t}\n\t\t})\n\n\t\tconst basicShape = tree.getNode(id) as VectorNode\n\n\t\tconst projectedBack = modulatedPoints.map(point => {\n\t\t\treturn convertPointFromNodeToDescendant(tree, currentShapeContainer, basicShape, point, false)\n\t\t})\n\n\t\tconst localRect = Rect.boundingRectFromPoints(projectedBack)\n\t\tengine.tree.get<BasicShapeNode>(id)?.set(localRect)\n\t})\n}\n\ninterface ScaleShapeNodeBeginState {\n\tdescendantPaths?: Immutable.Map<NodeID, WithPath> // paths are normalized for the canvas\n\tdescendantBasicShapes?: Immutable.Map<NodeID, null | Point[]> // corner points are normalized for the canvas\n\tcanvasMatrix: DOMMatrixReadOnly\n\trect: Rect\n}\nexport function scaleShapeNode(\n\ttree: CanvasTree,\n\tbeginState: ScaleShapeNodeBeginState,\n\tstartRect: Rect,\n\tresizeRect: Rect,\n\tinCanvas: boolean,\n\t/**\n\t * Function called to retrieve a matrix for the node target node. Allows scaling to function when the\n\t * node's cached matrix is missing or out of date. The argument can be omitted if the node cache is valid.\n\t */\n\tgetCachedMatrixForNode: (node: CanvasNode) => DOMMatrixReadOnly = node => node.canvasMatrix(),\n) {\n\tconst toWidth = resizeRect.width > -1 && resizeRect.width < 1 ? 1 : resizeRect.width\n\tconst toHeight = resizeRect.height > -1 && resizeRect.height < 1 ? 1 : resizeRect.height\n\tconst xFromRange: [number, number] = [startRect.x, startRect.x + startRect.width]\n\tconst xToRange: [number, number] = [resizeRect.x, resizeRect.x + toWidth]\n\tconst yFromRange: [number, number] = [startRect.y, startRect.y + startRect.height]\n\tconst yToRange: [number, number] = [resizeRect.y, resizeRect.y + toHeight]\n\tconst widthRatio = toWidth / startRect.width\n\tconst heightRatio = toHeight / startRect.height\n\n\tconst offset: Point = inCanvas ? { x: 0, y: 0 } : beginState.rect\n\n\tif (beginState.descendantPaths) {\n\t\tbeginState.descendantPaths.forEach((pathBeginState: WithPath, id: NodeID) => {\n\t\t\tconst localPath = inCanvas\n\t\t\t\t? pathBeginState.pathSegments\n\t\t\t\t: (convertPath(beginState.canvasMatrix.inverse(), [pathBeginState])[0] ?? [])\n\n\t\t\tconst modulatedPathSegments = localPath.map((segment: PathSegment) => {\n\t\t\t\treturn segment.merge({\n\t\t\t\t\tx: modulate(segment.x + offset.x, xFromRange, xToRange, false) - offset.x,\n\t\t\t\t\ty: modulate(segment.y + offset.y, yFromRange, yToRange, false) - offset.y,\n\t\t\t\t\thandleOutX: segment.handleOutX * widthRatio,\n\t\t\t\t\thandleOutY: segment.handleOutY * heightRatio,\n\t\t\t\t\thandleInX: segment.handleInX * widthRatio,\n\t\t\t\t\thandleInY: segment.handleInY * heightRatio,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tconst globalPath = inCanvas\n\t\t\t\t? { pathSegments: modulatedPathSegments, pathClosed: pathBeginState.pathClosed }\n\t\t\t\t: {\n\t\t\t\t\t\tpathSegments:\n\t\t\t\t\t\t\tconvertPath(beginState.canvasMatrix, [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tpathSegments: modulatedPathSegments,\n\t\t\t\t\t\t\t\t\tpathClosed: pathBeginState.pathClosed,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t])[0] ?? [],\n\t\t\t\t\t\tpathClosed: pathBeginState.pathClosed,\n\t\t\t\t\t}\n\t\t\tconst pathNode = tree.get<PathNode>(id)\n\t\t\tif (!pathNode) return\n\t\t\tconst projectedBack = convertPathToNode(tree, pathNode, [globalPath])\n\t\t\tconst newPath = { pathSegments: projectedBack[0], pathClosed: pathNode.pathClosed }\n\n\t\t\tconst update = pathNode.updateForPath(newPath)\n\t\t\tpathNode.set(update)\n\t\t})\n\t}\n\tif (beginState.descendantBasicShapes) {\n\t\tbeginState.descendantBasicShapes.forEach((pathBeginState: Point[] | null, id: NodeID) => {\n\t\t\tif (pathBeginState === null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst localPoints = inCanvas\n\t\t\t\t? pathBeginState\n\t\t\t\t: pathBeginState.map(point => {\n\t\t\t\t\t\treturn Matrix.convertPoint(beginState.canvasMatrix.inverse(), point)\n\t\t\t\t\t})\n\n\t\t\tconst modulatedPoints = localPoints.map(point => {\n\t\t\t\treturn {\n\t\t\t\t\tx: modulate(point.x + offset.x, xFromRange, xToRange, false) - offset.x,\n\t\t\t\t\ty: modulate(point.y + offset.y, yFromRange, yToRange, false) - offset.y,\n\t\t\t\t}\n\t\t\t})\n\t\t\tconst globalPoints = inCanvas\n\t\t\t\t? modulatedPoints\n\t\t\t\t: modulatedPoints.map(point => {\n\t\t\t\t\t\treturn Matrix.convertPoint(beginState.canvasMatrix, point)\n\t\t\t\t\t})\n\n\t\t\tconst basicShape = tree.get<VectorNode>(id)\n\t\t\tif (!basicShape) return\n\n\t\t\tconst projectedBack = globalPoints.map(point => {\n\t\t\t\treturn Matrix.convertPoint(getCachedMatrixForNode(basicShape).inverse(), point)\n\t\t\t})\n\n\t\t\tconst localRect = Rect.boundingRectFromPoints(projectedBack)\n\t\t\tconst center = Rect.center(localRect)\n\n\t\t\tconst centerInParent = convertPointToParent(basicShape, center)\n\n\t\t\tconst frame = {\n\t\t\t\t// Shape positions and sizes are rounded to half-pixels when rendering. Round to the\n\t\t\t\t// nearest half-pixel to avoid visible jumps when resizing with small deltas. For\n\t\t\t\t// example, 10.5 and 10.75 would round to different pixels and appear jumpy. The\n\t\t\t\t// localRect is modulated by the start/resize rects (which are already rounded), so\n\t\t\t\t// we don't need to round it again here.\n\t\t\t\tx: roundToHalfPixel(centerInParent.x - localRect.width / 2),\n\t\t\t\ty: roundToHalfPixel(centerInParent.y - localRect.height / 2),\n\t\t\t\twidth: localRect.width,\n\t\t\t\theight: localRect.height,\n\t\t\t}\n\n\t\t\tbasicShape.set(frame)\n\t\t})\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { SupportedLayoutOption } from \"@framerjs/framer-runtime/crossorigin\"\nimport { assert, assertNever } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport {\n\ttype CanvasNode,\n\ttype CanvasTree,\n\ttype CodeComponentNode,\n\ttype NodeID,\n\ttype RichTextNode,\n\ttype ShapeContainerNode,\n\tisVectorNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type { ReadonlyChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport { isInlineVectorNode } from \"document/models/CanvasTree/nodes/TreeNode.ts\"\nimport {\n\tisCodeComponentNode,\n\tisRichTextNode,\n\tisShapeContainerNode,\n\tisTextStylePresetNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isFixedOrRelativeOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { type DynamicValue, isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type { RelativeOrFourPixelNumberShorthand } from \"document/models/CanvasTree/traits/NumberShorthand.ts\"\nimport {\n\tcollectScalableVectorStyles,\n\tscaleVectorStyles,\n} from \"document/models/CanvasTree/traits/ScalableVectorStyles.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { type WithBorder, withBorder } from \"document/models/CanvasTree/traits/WithBorder.ts\"\nimport { type WithBoxShadow, supportsBoxShadow } from \"document/models/CanvasTree/traits/WithBoxShadow.ts\"\nimport { type WithFill, withFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { type WithFilters, withFilters } from \"document/models/CanvasTree/traits/WithFilters.ts\"\nimport { type WithGridItemSize, withGridItemSize } from \"document/models/CanvasTree/traits/WithGridItemSize.ts\"\nimport {\n\ttype WithLayout,\n\thasAnyLayout,\n\thasGridLayout,\n\twithLayout,\n} from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { type WithPadding, withPadding } from \"document/models/CanvasTree/traits/WithPadding.ts\"\nimport { type WithPins, isPinnable } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { type WithPosition, withPosition } from \"document/models/CanvasTree/traits/WithPosition.ts\"\nimport { type WithRadius, withRadius } from \"document/models/CanvasTree/traits/WithRadius.ts\"\nimport { type WithRadiusPerCorner, withRadiusPerCorner } from \"document/models/CanvasTree/traits/WithRadiusPerCorner.ts\"\nimport { type WithSize, withSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport {\n\ttype HeightConstraintUnit,\n\ttype WidthConstraintUnit,\n\ttype WithSizeConstraints,\n\tparseConstraintValue,\n\tsupportsSizeConstraints,\n} from \"document/models/CanvasTree/traits/WithSizeConstraints.ts\"\nimport {\n\ttype WithSizeDimensionType,\n\twithSizeDimensionType,\n} from \"document/models/CanvasTree/traits/WithSizeDimensionType.ts\"\nimport { type WithStroke, withStroke } from \"document/models/CanvasTree/traits/WithStroke.ts\"\nimport type { FontSize, FontSizeCSSDimension, FontSizeUnit } from \"document/models/CanvasTree/traits/WithTextStyle.ts\"\nimport { isBreakpointVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport {\n\ttype WithFormInputFontStyles,\n\twithFormInputFontStyles,\n} from \"document/models/CanvasTree/traits/forms/WithFormInputTextStyles.ts\"\nimport {\n\ttype CSSDimension,\n\tcreateCSSDimension,\n\tparseCSSDimension,\n\tupdatePxValueString,\n} from \"document/models/CanvasTree/traits/utils/CSSDimension.ts\"\nimport { getBoundingFrameForNodes } from \"document/models/CanvasTree/utils/geometry.ts\"\nimport { constrainedFrame } from \"document/models/ConstraintSolver.ts\"\nimport { Matrix } from \"document/models/Matrix.ts\"\nimport { type BoxShadow, getUpdatedShadow } from \"document/models/Shadow.ts\"\nimport type {\n\tBorderControlPropValue,\n\tBorderRadiusControlPropValue,\n\tControlProps,\n\tPaddingControlPropValue,\n} from \"document/models/controlProps/ControlProp.ts\"\nimport type { FontControlPropValue } from \"document/models/controlProps/FontControlPropValue.ts\"\nimport type { RawControlProp } from \"document/models/controlProps/RawControlProp.ts\"\nimport { type PrefixedControlPropKey, prefixControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport { ControlType, DimensionType, Point, Rect, modulate, roundedNumber } from \"library/index.ts\"\nimport { isNumber, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport {\n\tcollectDescendantShapesAndFlattenRotations,\n\tcollectShapeContainerDescendantShapesAndFlattenRotations,\n} from \"../tools/pathEdit/utils/index.ts\"\nimport { scaleShapeContainerDescendantShapes, scaleShapeNode } from \"./dimensions.ts\"\n\n/**\n * Scales all the target nodes and relevant descendants by the given scaleFactor. Dimensions and properties with measurements\n * will be scaled if required.\n * @param nodes Pass all nodes to be scaled\n * @param scaleFactor The factor to scale the target nodes by, so to double the size pass 2, to half the size pass 0.5, 1 is a no-op\n * @param anchorPoint The point to scale around, will be treated as relative to the selection frame\n * e.g. { x: 0.5, y: 0.5 } is the center of the selection\n */\nexport function scaleNodes(\n\tengine: VekterEngine,\n\tnodes: CanvasNode[],\n\tscaleFactor: number,\n\tinitialState: ScaleNodesInitialState,\n\tanchorPoint?: Point,\n) {\n\tif (scaleFactor === 1) return\n\n\t// The scale anchor should not apply across different parents, rather the anchoring should apply as if the selection only contains\n\t// those each selected sibling. This allows users to select a number of similar nodes around the page and scale them all at once without\n\t// them repositioning wildly. Each array of nodes will apply the anchor based on the frame of all nodes in the array.\n\tfor (const [parentId] of initialState.parentsInitialState) {\n\t\tconst parentInitialState = initialState.parentsInitialState.get(parentId)\n\t\tif (!parentInitialState) continue\n\n\t\tconst selectedNodes: CanvasNode[] = []\n\t\tfor (const node of nodes) {\n\t\t\tif (!parentInitialState.selectedNodeIds.has(node.id)) continue\n\t\t\tselectedNodes.push(node)\n\t\t}\n\n\t\trecursivelyScaleNodes(\n\t\t\tselectedNodes,\n\t\t\tscaleFactor,\n\t\t\tgetScaleNodesContext(engine, parentId, scaleFactor, initialState, anchorPoint),\n\t\t\ttrue,\n\t\t)\n\t}\n}\n\ninterface ParentInitialState {\n\tmatrix: DOMMatrixReadOnly\n\tselectedNodeIds: Set<NodeID>\n\tselectionBoundingFrame: Rect\n}\ninterface NodeInitialState\n\textends\n\t\tPartial<ReturnType<typeof collectDescendantShapesAndFlattenRotations>>,\n\t\tPartial<ReturnType<typeof collectShapeContainerDescendantShapesAndFlattenRotations>> {\n\trect: Rect\n\tmatrix: DOMMatrixReadOnly\n\tscalableShapeStylesMap?: ReturnType<typeof collectScalableVectorStyles>\n\tcodeComponentControlProps?: ControlProps\n}\nexport interface ScaleNodesInitialState {\n\tparentsInitialState: Map<NodeID, ParentInitialState>\n\tnodesInitialState: Map<NodeID, NodeInitialState>\n\tnonScalableNodes: Set<NodeID>\n}\n\nexport function getScaleNodesInitialState(engine: VekterEngine, nodes: CanvasNode[]): ScaleNodesInitialState {\n\tconst parentsInitialState = new Map<NodeID, ParentInitialState>()\n\tconst nodesInitialState = new Map<NodeID, NodeInitialState>()\n\tconst nodesPerParent: Record<NodeID, CanvasNode[]> = {}\n\tconst nonScalableNodes = new Set<NodeID>()\n\n\tfor (const node of engine.tree.withoutDescendants(nodes)) {\n\t\tconst parentId = node.parentid\n\n\t\tif (!parentId) continue\n\t\tconst parent = engine.tree.getNode(parentId)\n\t\tassert(parent, \"Parent must exist\")\n\n\t\tsetNodeInitialState(engine, node, nodesInitialState, nonScalableNodes)\n\t\tsetParentInitialState(engine, node, parent, parentsInitialState)\n\n\t\tnodesPerParent[parentId] ??= []\n\t\tnodesPerParent[parentId].push(node)\n\t}\n\n\tfor (const [parentId, parentInitialState] of parentsInitialState) {\n\t\tconst selectedNodes = nodesPerParent[parentId]\n\t\tassert(selectedNodes, \"Nodes must exist\")\n\t\tparentInitialState.selectionBoundingFrame = getBoundingFrameForNodes(engine.tree, selectedNodes)\n\t}\n\n\treturn {\n\t\tparentsInitialState,\n\t\tnodesInitialState,\n\t\tnonScalableNodes,\n\t}\n}\n\nfunction setNodeInitialState(\n\tengine: VekterEngine,\n\tnode: CanvasNode,\n\tnodesInitialState: Map<NodeID, NodeInitialState>,\n\tnonScalableNodes: Set<NodeID>,\n): void {\n\tfor (const { node: walkedNode, skipChildren } of node.walkWithSkipChildren()) {\n\t\tif (nodesInitialState.has(walkedNode.id)) continue\n\n\t\tconst isTopLevel = walkedNode.id === node.id\n\t\tconst shouldCollectDescendantShapes =\n\t\t\tisVectorNode(walkedNode) && (isInlineVectorNode(engine.tree, walkedNode) || isTopLevel)\n\n\t\tif (!isScalable(engine.componentLoader, walkedNode, isTopLevel)) {\n\t\t\tnonScalableNodes.add(walkedNode.id)\n\t\t\tskipChildren()\n\t\t\tcontinue\n\t\t}\n\n\t\tconst descendantShapes = shouldCollectDescendantShapes\n\t\t\t? collectDescendantShapesAndFlattenRotations(engine, walkedNode)\n\t\t\t: undefined\n\t\tconst shapeContainerDescendantShapes = isShapeContainerNode(walkedNode)\n\t\t\t? collectShapeContainerDescendantShapesAndFlattenRotations(engine, walkedNode)\n\t\t\t: undefined\n\t\t// Collecting scalable styles must come after flattening rotations, because when rotations are flattened it\n\t\t// creates new path nodes. We need those new path nodes to be included so we can scale their styles.\n\t\tconst scalableShapeStylesMap =\n\t\t\tisShapeContainerNode(walkedNode) || shouldCollectDescendantShapes\n\t\t\t\t? collectScalableVectorStyles(walkedNode.draftOrCurrent())\n\t\t\t\t: undefined\n\n\t\tconst codeComponentControlProps = isCodeComponentNode(walkedNode)\n\t\t\t? getCodeComponentControlProps(engine.componentLoader, walkedNode)\n\t\t\t: undefined\n\n\t\tnodesInitialState.set(walkedNode.id, {\n\t\t\t// Rects here are still likely to be pixel aligned, however, there are some cases where they are not, and\n\t\t\t// issues can arise. Nodes with absolute positioning with top & left pins and are not influenced by their\n\t\t\t// parent will return a unrounded rect. This is because in the `repositionNodeAfterScale`, the scaled width\n\t\t\t// & height would be rounded & overwritten. See `withDOMLayoutTraits.usesDOMRect()`.\n\t\t\trect: Rect.round(engine.tree.getRect(walkedNode, false), 2),\n\t\t\tmatrix: engine.tree.transformMatrixToNode(walkedNode),\n\t\t\tcodeComponentControlProps,\n\t\t\tscalableShapeStylesMap,\n\t\t\t...descendantShapes,\n\t\t\t...shapeContainerDescendantShapes,\n\t\t})\n\n\t\tif (isShapeContainerNode(walkedNode)) {\n\t\t\tskipChildren()\n\t\t}\n\t}\n}\n\nfunction getCodeComponentControlProps(componentLoader: ComponentLoader, node: CodeComponentNode) {\n\tconst component = componentLoader.reactComponentForIdentifier(node.codeComponentIdentifier)\n\n\tif (!component || !component.properties) return undefined\n\n\treturn node.getControlProps(component.properties)\n}\n\nfunction setParentInitialState(\n\tengine: VekterEngine,\n\tnode: CanvasNode,\n\tparent: CanvasNode,\n\tparentsInitialState: ScaleNodesInitialState[\"parentsInitialState\"],\n): void {\n\tconst parentInitialState = parentsInitialState.get(parent.id) ?? {\n\t\tmatrix: engine.tree.transformMatrixToNode(parent).invertSelf(),\n\t\tselectedNodeIds: new Set<NodeID>(),\n\t\tselectionBoundingFrame: { x: 0, y: 0, width: 0, height: 0 },\n\t}\n\tparentInitialState.selectedNodeIds.add(node.id)\n\tparentsInitialState.set(parent.id, parentInitialState)\n}\n\nfunction getScaleNodesContext(\n\tengine: VekterEngine,\n\tparentId: NodeID,\n\tscaleFactor: number,\n\tinitialState: ScaleNodesInitialState,\n\tanchorPoint?: Point,\n): ScaleNodesContext {\n\tconst parentInitialState = initialState.parentsInitialState.get(parentId)\n\tassert(parentInitialState, \"Parent must be present in initial state\")\n\tconst selectionFrame = parentInitialState.selectionBoundingFrame\n\tconst resizedFrame: Rect = {\n\t\t...selectionFrame,\n\t\twidth: selectionFrame.width * scaleFactor,\n\t\theight: selectionFrame.height * scaleFactor,\n\t}\n\n\treturn {\n\t\tinitialRect: selectionFrame,\n\t\tresizedRect: resizedFrame,\n\t\tengine,\n\t\ttree: engine.tree,\n\t\tinitialState,\n\t\tanchorPoint: anchorPoint ?? { x: 0.5, y: 0.5 },\n\t}\n}\n\ninterface ScaleNodesContext {\n\tinitialRect: Rect\n\tresizedRect: Rect\n\tengine: VekterEngine\n\ttree: CanvasTree\n\tinitialState: ScaleNodesInitialState\n\tanchorPoint: Point\n}\n\nfunction recursivelyScaleNodes(\n\tnodes: CanvasNode[] | ReadonlyChildList<CanvasNode>,\n\tscaleFactor: number,\n\tcontext: ScaleNodesContext,\n\ttopLevel: boolean,\n): boolean {\n\tif (nodes.length === 0) return false\n\tlet didScaleSize = false\n\tfor (const node of nodes) {\n\t\tif (context.initialState.nonScalableNodes.has(node.id)) continue\n\n\t\tconst didScaleChildSize =\n\t\t\tshouldScaleDescendants(node) && recursivelyScaleNodes(node.children, scaleFactor, context, false)\n\t\tconst didScaleNodeSize = scaleNode(node, context, scaleFactor, didScaleChildSize, topLevel)\n\n\t\tdidScaleSize ||= didScaleNodeSize || didScaleChildSize\n\t}\n\n\treturn didScaleSize\n}\n\nfunction scaleNode(\n\tnode: CanvasNode,\n\tcontext: ScaleNodesContext,\n\tscaleFactor: number,\n\tdidScaleChildSize: boolean,\n\ttopLevel: boolean,\n): boolean {\n\tconst scaledProperties = updateForScale(node, scaleFactor, topLevel)\n\tconst didScaleSize = scaleForNodeType(node, context, scaleFactor, didScaleChildSize, topLevel, scaledProperties)\n\n\tnode.set(scaledProperties)\n\n\tif (didScaleSize || didScaleChildSize) {\n\t\trepositionNodeAfterScale(node, context, scaleFactor, topLevel)\n\t}\n\n\treturn didScaleSize\n}\n\nfunction scaleForNodeType(\n\tnode: CanvasNode,\n\tcontext: ScaleNodesContext,\n\tscaleFactor: number,\n\tdidScaleChildSize: boolean,\n\ttopLevel: boolean,\n\tscaledProperties: ScaledProperties,\n): boolean {\n\tif (isRichTextNode(node)) {\n\t\treturn scaleRichTextNode(node, scaleFactor, context, topLevel, scaledProperties)\n\t}\n\tif (isShapeContainerNode(node)) {\n\t\treturn scaleShapeContainer(node, scaleFactor, context, topLevel, scaledProperties)\n\t}\n\tif (isVectorNode(node)) {\n\t\treturn scaleShapeNodeAndDescendants(node, scaleFactor, context)\n\t}\n\tif (isCodeComponentNode(node)) {\n\t\treturn scaleCodeComponentNode(node, scaleFactor, context, topLevel, scaledProperties)\n\t}\n\tif (withSize(node)) {\n\t\treturn scaleNodeSize(node, scaleFactor, context, didScaleChildSize, topLevel, scaledProperties)\n\t}\n\n\treturn false\n}\n\nfunction scaleRichTextNode(\n\tnode: RichTextNode,\n\tscaleFactor: number,\n\tcontext: ScaleNodesContext,\n\ttopLevel: boolean,\n\tscaledProperties: ScaledProperties,\n) {\n\tlet didScaleSize = false\n\tif (!node.textFitViewBoxSize) {\n\t\tdetachAllTextStyles(node, context.tree)\n\n\t\t// there may be a draft if text styles were detached\n\t\tconst update = node.draftOrCurrent().updateForScale(scaleFactor)\n\t\tObject.assign(scaledProperties, update satisfies ScaledProperties)\n\t\tdidScaleSize = true\n\t}\n\n\tif (node.widthType !== DimensionType.Auto) {\n\t\tdidScaleSize =\n\t\t\tscaleDimension(\"width\", node, scaleFactor, context, false, topLevel, scaledProperties) || didScaleSize\n\t}\n\n\tif (node.heightType !== DimensionType.Auto) {\n\t\tdidScaleSize =\n\t\t\tscaleDimension(\"height\", node, scaleFactor, context, false, topLevel, scaledProperties) || didScaleSize\n\t}\n\n\treturn didScaleSize\n}\n\nfunction scaleShapeContainer(\n\tnode: ShapeContainerNode,\n\tscaleFactor: number,\n\tcontext: ScaleNodesContext,\n\ttopLevel: boolean,\n\tscaledProperties: ScaledProperties,\n) {\n\tconst nodeInitialState = context.initialState.nodesInitialState.get(node.id)\n\tconst shapeContainerDescendantPaths = nodeInitialState?.shapeContainerDescendantPaths\n\tconst shapeContainerDescendantBasicShapes = nodeInitialState?.shapeContainerDescendantBasicShapes\n\tconst scalableShapeStylesMap = nodeInitialState?.scalableShapeStylesMap\n\n\tassert(scalableShapeStylesMap, \"Shape container styles should be available in initial state\")\n\tassert(shapeContainerDescendantPaths, \"Shape container paths should be available in initial state\")\n\tassert(shapeContainerDescendantBasicShapes, \"Shape container shapes should be available in initial state\")\n\n\tscaleShapeContainerDescendantShapes(\n\t\tcontext.engine,\n\t\tnode,\n\t\tshapeContainerDescendantPaths,\n\t\tshapeContainerDescendantBasicShapes,\n\t\tnode,\n\t\t{ width: node.width * scaleFactor, height: node.height * scaleFactor },\n\t)\n\n\tscaleVectorStyles(context.tree, scalableShapeStylesMap, scaleFactor)\n\n\tscaleDimension(\"width\", node, scaleFactor, context, true, topLevel, scaledProperties)\n\tscaleDimension(\"height\", node, scaleFactor, context, true, topLevel, scaledProperties)\n\n\treturn true\n}\n\nfunction repositionNodeAfterScale(\n\tnode: CanvasNode,\n\tcontext: ScaleNodesContext,\n\tscaleFactor: number,\n\ttopLevel: boolean,\n) {\n\tif (topLevel) {\n\t\trepositionWithAnchor(node, scaleFactor, context)\n\t} else if (isPinnable(node)) {\n\t\t// When a child has pixel positioning within its parent it needs to scale the position to prevent movement within the scale parent\n\t\t// for example a parent 1000x1000 with a child positioned at 100,100, after scaling the parent and child by 2 the child needs to be\n\t\t// repositioned to 200,200 to avoid it moving closer to the top left corner of the parent. The center anchor does not have to be\n\t\t// updated because it is not a pixel value, as long as the parent and child scale with the same factor it will not change.\n\t\tconst newPins: Partial<WithPins> = {}\n\t\tif (node.left) {\n\t\t\tnewPins.left = scaled(node.left, scaleFactor)\n\t\t}\n\t\tif (node.right) {\n\t\t\tnewPins.right = scaled(node.right, scaleFactor)\n\t\t}\n\t\tif (node.top) {\n\t\t\tnewPins.top = scaled(node.top, scaleFactor)\n\t\t}\n\t\tif (node.bottom) {\n\t\t\tnewPins.bottom = scaled(node.bottom, scaleFactor)\n\t\t}\n\t\tnode.set(newPins)\n\t}\n}\n\nfunction repositionWithAnchor(node: CanvasNode, scaleFactor: number, context: ScaleNodesContext) {\n\tif (!isPinnable(node) && !withPosition(node)) return\n\n\tconst nodeInitialState = context.initialState.nodesInitialState.get(node.id)\n\tassert(nodeInitialState, \"Node must be present in initial state\")\n\tconst parentInitialState = node.parentid ? context.initialState.parentsInitialState.get(node.parentid) : undefined\n\tassert(parentInitialState, \"Node parent must be present in the initial state\")\n\tconst singleSelection = parentInitialState.selectedNodeIds.size === 1\n\n\tif (singleSelection) {\n\t\trepositionWithAnchorForSingleSelectionNode(node, scaleFactor, context, nodeInitialState)\n\t} else {\n\t\trepositionWithAnchorForMulitSelectionNode(node, context, nodeInitialState, parentInitialState)\n\t}\n}\n\n/**\n * Repositions the node based on the scale factor, this takes into account any transformations applied to any ancestors\n */\nfunction repositionWithAnchorForSingleSelectionNode(\n\tnode: CanvasNode & (WithPins | WithPosition),\n\tscaleFactor: number,\n\tcontext: ScaleNodesContext,\n\tnodeInitialState: NodeInitialState,\n) {\n\tconst startFrame = nodeInitialState.rect\n\tconst resizedFrame: Rect = {\n\t\t...startFrame,\n\t\twidth: startFrame.width * scaleFactor,\n\t\theight: startFrame.height * scaleFactor,\n\t}\n\tconst ignoreRotation = isVectorNode(node) || isShapeContainerNode(node)\n\tconst matrixTargetNode = ignoreRotation ? node.clone({ rotation: 0 }) : node\n\n\tconst anchorStart = getAbsoluteAnchorPoint(startFrame, context.anchorPoint)\n\tconst anchorEnd = getAbsoluteAnchorPoint(resizedFrame, context.anchorPoint)\n\tconst startPoint = Matrix.convertPoint(matrixTargetNode.originAdjustedMatrix(null, startFrame), anchorStart)\n\tconst endPoint = Matrix.convertPoint(matrixTargetNode.originAdjustedMatrix(null, resizedFrame), anchorEnd)\n\n\tconst delta = Point.subtract(startPoint, endPoint)\n\tconst rect = Rect.round(Rect.offset(resizedFrame, delta), 2)\n\n\tif (isPinnable(node)) {\n\t\t// constrainedFrame returns dimension types and size constraints which may be outdated, we\n\t\t// don't care about changing the size here so we ignore them\n\t\tconst {\n\t\t\twidthType: _widthType,\n\t\t\theightType: _heightType,\n\t\t\tmaxHeight: _maxHeight,\n\t\t\tminHeight: _minHeight,\n\t\t\tmaxWidth: _maxWidth,\n\t\t\tminWidth: _minWidth,\n\t\t\t...pinUpdate\n\t\t} = constrainedFrame(\n\t\t\tnode.constraints(),\n\t\t\trect,\n\t\t\tcontext.tree.getParentSizeInfo(node, context.tree.getParent(node.id)),\n\t\t\tnull,\n\t\t\tfalse,\n\t\t)\n\t\tnode.set(pinUpdate)\n\t} else {\n\t\tnode.set({ x: rect.x, y: rect.y })\n\t}\n}\n\n/**\n * Repositions the node based on the resized frame of all nodes selected inside the parent, this does not take into\n * account any transformations applied to ancestors\n */\nfunction repositionWithAnchorForMulitSelectionNode(\n\tnode: CanvasNode & (WithPins | WithPosition),\n\tcontext: ScaleNodesContext,\n\tnodeInitialState: NodeInitialState,\n\tparentInitialState: ParentInitialState,\n) {\n\tconst anchorStart = Point.add(getAbsoluteAnchorPoint(context.initialRect, context.anchorPoint), context.initialRect)\n\tconst anchorEnd = Point.add(getAbsoluteAnchorPoint(context.resizedRect, context.anchorPoint), context.resizedRect)\n\tconst delta = Point.subtract(anchorStart, anchorEnd)\n\n\tconst canvasToParentMatrix = parentInitialState.matrix ?? null\n\tconst convertedStartRect = projectFrame(canvasToParentMatrix, context.initialRect)\n\tconst convertedResizeRect = projectFrame(canvasToParentMatrix, Rect.offset(context.resizedRect, delta))\n\n\tconst xFromRange: [number, number] = [convertedStartRect.x, convertedStartRect.x + convertedStartRect.width]\n\tconst xToRange: [number, number] = [convertedResizeRect.x, convertedResizeRect.x + convertedResizeRect.width]\n\tconst yFromRange: [number, number] = [convertedStartRect.y, convertedStartRect.y + convertedStartRect.height]\n\tconst yToRange: [number, number] = [convertedResizeRect.y, convertedResizeRect.y + convertedResizeRect.height]\n\n\tconst nodeRect = nodeInitialState.rect\n\n\tconst pointA = {\n\t\tx: modulate(nodeRect.x, xFromRange, xToRange, false),\n\t\ty: modulate(nodeRect.y, yFromRange, yToRange, false),\n\t}\n\tconst pointB = {\n\t\tx: modulate(nodeRect.x + nodeRect.width, xFromRange, xToRange, false),\n\t\ty: modulate(nodeRect.y + nodeRect.height, yFromRange, yToRange, false),\n\t}\n\n\tconst rect = Rect.round(Rect.fromTwoPoints(pointA, pointB))\n\n\tif (isPinnable(node)) {\n\t\tconst update = constrainedFrame(\n\t\t\tnode.constraints(),\n\t\t\trect,\n\t\t\tcontext.tree.getParentSizeInfo(node, context.tree.getParent(node.id)),\n\t\t\tnull,\n\t\t\tfalse,\n\t\t)\n\t\t// constrainedFrame returns a widthType and heightType which may be outdated, we don't care about changing the size here so we ignore them\n\t\tdelete update.widthType\n\t\tdelete update.heightType\n\t\tnode.set(update)\n\t} else {\n\t\tnode.set({ x: rect.x, y: rect.y })\n\t}\n}\n\nfunction projectFrame(matrix: DOMMatrixReadOnly | null, frame: Rect) {\n\tif (!matrix) return frame\n\tconst convertedCorners = Matrix.convertPointsWithClipping(matrix, Rect.cornerPoints(frame))\n\treturn Rect.boundingRectFromPoints(convertedCorners)\n}\n\ntype ScaledProperties = Partial<\n\tCanvasNode &\n\t\tPick<RichTextNode, \"html\" | \"linkFontSize\" | \"linkHoverFontSize\" | \"linkCurrentFontSize\"> & {\n\t\t\t[key: PrefixedControlPropKey]: RawControlProp\n\t\t} & WithBorder &\n\t\tWithBoxShadow &\n\t\tWithStroke &\n\t\tWithPadding &\n\t\tWithRadius &\n\t\tWithRadiusPerCorner &\n\t\tWithSizeConstraints &\n\t\tWithLayout &\n\t\tWithFormInputFontStyles &\n\t\tWithFill &\n\t\tWithFilters &\n\t\tWithSize &\n\t\tWithSizeDimensionType &\n\t\tWithGridItemSize\n>\nfunction updateForScale(node: CanvasNode, scaleFactor: number, topLevel: boolean): ScaledProperties {\n\tconst scaledProperties: ScaledProperties = {}\n\tif (withBorder(node)) {\n\t\tscaledProperties.borderWidth = scaled(node.borderWidth, scaleFactor)\n\t\tscaledProperties.borderBottom = scaled(node.borderBottom, scaleFactor)\n\t\tscaledProperties.borderLeft = scaled(node.borderLeft, scaleFactor)\n\t\tscaledProperties.borderTop = scaled(node.borderTop, scaleFactor)\n\t\tscaledProperties.borderRight = scaled(node.borderRight, scaleFactor)\n\t}\n\n\tif (supportsBoxShadow(node)) {\n\t\tscaledProperties.boxShadows = scaleShadows(node.boxShadows, scaleFactor)\n\t}\n\n\tif (withStroke(node)) {\n\t\tscaledProperties.strokeWidth = scaled(node.strokeWidth, scaleFactor)\n\t}\n\n\tif (withPadding(node)) {\n\t\tscaledProperties.padding = scaled(node.padding, scaleFactor)\n\t\tscaledProperties.paddingBottom = scaled(node.paddingBottom, scaleFactor)\n\t\tscaledProperties.paddingLeft = scaled(node.paddingLeft, scaleFactor)\n\t\tscaledProperties.paddingTop = scaled(node.paddingTop, scaleFactor)\n\t\tscaledProperties.paddingRight = scaled(node.paddingRight, scaleFactor)\n\t}\n\n\tif (withRadiusPerCorner(node)) {\n\t\tscaledProperties.radiusBottomLeft = scaled(node.radiusBottomLeft, scaleFactor)\n\t\tscaledProperties.radiusBottomRight = scaled(node.radiusBottomRight, scaleFactor)\n\t\tscaledProperties.radiusTopLeft = scaled(node.radiusTopLeft, scaleFactor)\n\t\tscaledProperties.radiusTopRight = scaled(node.radiusTopRight, scaleFactor)\n\t}\n\n\tif (withRadius(node)) {\n\t\tscaledProperties.radius = scaled(node.radius, scaleFactor)\n\t}\n\n\tif (hasGridLayout(node)) {\n\t\tscaledProperties.gridColumnMinWidth = scaled(node.gridColumnMinWidth, scaleFactor)\n\t\tscaledProperties.gridColumnWidth = scaled(node.gridColumnWidth, scaleFactor)\n\t\tif (node.gridRowHeightType === \"fixed\") {\n\t\t\tscaledProperties.gridRowHeight = scaled(node.gridRowHeight, scaleFactor)\n\t\t}\n\t}\n\n\tif (hasAnyLayout(node)) {\n\t\tscaledProperties.gap = scaledGap(node.gap, scaleFactor)\n\t}\n\n\tif (withFormInputFontStyles(node)) {\n\t\tscaledProperties.formInputFontSize = scaleFontSizeCSSDimension(node.formInputFontSize, scaleFactor)\n\n\t\tif (node.formInputFontLetterSpacingUnit === \"px\") {\n\t\t\tscaledProperties.formInputFontLetterSpacing = scaled(node.formInputFontLetterSpacing, scaleFactor)\n\t\t}\n\n\t\tif (node.formInputFontLineHeightUnit === \"px\") {\n\t\t\tscaledProperties.formInputFontLineHeight = scaled(node.formInputFontLineHeight, scaleFactor)\n\t\t}\n\t}\n\n\tif (withFilters(node)) {\n\t\tscaledProperties.blur = scaled(node.blur, scaleFactor, 0)\n\t\tscaledProperties.backgroundBlur = scaled(node.backgroundBlur, scaleFactor, 0)\n\t}\n\n\tif (withFill(node)) {\n\t\tif (node.fillType === \"image\" && node.fillImageResize === \"tile\") {\n\t\t\t// fillImageTileSize is a percentage but it must be scaled to maintain the same ratio.\n\t\t\t// It defaults to 1 if it is not set, so we have to scale as if it is 1.\n\t\t\tscaledProperties.fillImageTileSize = scaled(node.fillImageTileSize ?? 1, scaleFactor)\n\t\t}\n\t}\n\n\tif (supportsSizeConstraints(node)) {\n\t\tscaledProperties.minWidth = scaledConstraint(node.minWidth, scaleFactor, topLevel)\n\t\tscaledProperties.maxWidth = scaledConstraint(node.maxWidth, scaleFactor, topLevel)\n\t\tscaledProperties.minHeight = scaledConstraint(node.minHeight, scaleFactor, topLevel)\n\t\tscaledProperties.maxHeight = scaledConstraint(node.maxHeight, scaleFactor, topLevel)\n\t}\n\n\treturn scaledProperties\n}\n\nfunction scaleNodeSize(\n\tnode: CanvasNode & WithSize,\n\tscaleFactor: number,\n\tcontext: ScaleNodesContext,\n\tdescendantsUpdated: boolean,\n\ttopLevel: boolean,\n\tscaledProperties: Partial<WithSize & WithSizeDimensionType>,\n): boolean {\n\tif (!withSizeDimensionType(node)) {\n\t\t// some more basic nodes don't have dimension units, like shape nodes\n\t\tscaledProperties.width = scaled(node.width, scaleFactor)\n\t\tscaledProperties.height = scaled(node.height, scaleFactor)\n\n\t\treturn true\n\t}\n\n\tlet didScaleSize = false\n\tdidScaleSize =\n\t\tscaleDimension(\"width\", node, scaleFactor, context, descendantsUpdated, topLevel, scaledProperties) || didScaleSize\n\tdidScaleSize =\n\t\tscaleDimension(\"height\", node, scaleFactor, context, descendantsUpdated, topLevel, scaledProperties) || didScaleSize\n\n\treturn didScaleSize\n}\n\n/**\n * Replaces all text style presets on the text node with resolved properties so they can be scaled\n */\nfunction detachAllTextStyles(node: RichTextNode, tree: CanvasTree) {\n\tconst textStylePresets = node.getTextStylePresets(false)\n\tfor (const presetId of textStylePresets) {\n\t\tconst preset = tree.getNode(presetId)\n\t\tif (isTextStylePresetNode(preset)) {\n\t\t\tnode.draftOrCurrent().detachTextStylePreset(preset, false)\n\t\t}\n\t}\n}\n\nfunction scaleDimension(\n\tdimensionKey: keyof WithSize,\n\tnode: CanvasNode & WithSize & WithSizeDimensionType,\n\tscaleFactor: number,\n\tcontext: ScaleNodesContext,\n\tdescendantsUpdated: boolean,\n\ttopLevel: boolean,\n\tscaledProperties: ScaledProperties,\n) {\n\tconst dimensionTypeKey: keyof WithSizeDimensionType = dimensionKey === \"width\" ? \"widthType\" : \"heightType\"\n\tconst dimensionType = node[dimensionTypeKey]\n\n\tconst initialRect = context.initialState.nodesInitialState.get(node.id)?.rect\n\tassert(initialRect, \"node should have cached rect\")\n\n\tconst gridCellFillKey: keyof WithGridItemSize =\n\t\tdimensionKey === \"width\" ? \"gridItemFillCellWidth\" : \"gridItemFillCellHeight\"\n\tconst isFillGridCell = withGridItemSize(node) && node[gridCellFillKey]\n\n\tif (isFillGridCell && topLevel) {\n\t\t// if it is grid cell with fill then the size does not necessarilly represent the actual node size, so we scale\n\t\t// using the true size and disconnect the fill\n\t\tscaledProperties[gridCellFillKey] = false\n\t\tscaledProperties[dimensionKey] = scaled(initialRect[dimensionKey], scaleFactor)\n\t\tscaledProperties[dimensionTypeKey] = DimensionType.FixedNumber\n\t\treturn true\n\t}\n\n\tswitch (dimensionType) {\n\t\tcase DimensionType.FixedNumber:\n\t\t\tscaledProperties[dimensionKey] = scaled(node[dimensionKey], scaleFactor)\n\t\t\treturn true\n\t\tcase DimensionType.Viewport:\n\t\t\tscaledProperties[dimensionKey] = scaled(node[dimensionKey], scaleFactor, 4)\n\t\t\treturn true\n\t\tcase DimensionType.Percentage:\n\t\t\t// only update relative if top level, otherwise we rely on the parent scale causing it to scale\n\t\t\tif (topLevel) {\n\t\t\t\tscaledProperties[dimensionKey] = scaled(node[dimensionKey], scaleFactor, 4)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\tcase DimensionType.FractionOfFreeSpace: {\n\t\t\t// only update fill if top level, otherwise we rely on the parent scale causing it to scale\n\t\t\tif (!topLevel) return false\n\n\t\t\tscaledProperties[dimensionKey] = scaled(initialRect[dimensionKey], scaleFactor)\n\t\t\tscaledProperties[dimensionTypeKey] = DimensionType.FixedNumber\n\t\t\treturn true\n\t\t}\n\t\tcase DimensionType.Auto:\n\t\t\t// only update auto if no children were scaled, otherwise we rely on the children scale causing the parent to scale\n\t\t\tif (!descendantsUpdated) {\n\t\t\t\t// grid cells with auto can have incorrect dimensions, so we need to take the real rendered dimension\n\t\t\t\tconst parent = context.tree.getNodeParent(node)\n\t\t\t\tconst parentLayout = parent && withLayout(parent) ? parent.layout : undefined\n\t\t\t\tconst dimensionValue = parentLayout === \"grid\" ? initialRect[dimensionKey] : node[dimensionKey]\n\n\t\t\t\tscaledProperties[dimensionKey] = scaled(dimensionValue, scaleFactor)\n\t\t\t\tscaledProperties[dimensionTypeKey] = DimensionType.FixedNumber\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\tcase DimensionType.FitImage:\n\t\t\t// fit image maintains the aspect ratio, so we don't need to do anything, just consider it scaled\n\t\t\treturn true\n\t\tdefault:\n\t\t\tassertNever(dimensionType)\n\t}\n}\n\nfunction isScalable(componentLoader: ComponentLoader, node: CanvasNode, topLevel: boolean) {\n\t// don't scale code component nodes that can't change from Auto to Fixed\n\tconst supportedLayoutOptions = isCodeComponentNode(node) ? node.getSupportedLayout(componentLoader) : undefined\n\tif (\n\t\tsupportedLayoutOptions?.width === SupportedLayoutOption.Auto &&\n\t\tsupportedLayoutOptions?.height === SupportedLayoutOption.Auto\n\t) {\n\t\treturn false\n\t}\n\tif (isBreakpointVariant(node)) return false\n\t// don't scale overlays if they are encountered as a descendant of a selected node\n\tif (isFixedOrRelativeOverlay(node) && !topLevel) return false\n\n\treturn true\n}\n\nfunction shouldScaleDescendants(node: CanvasNode): node is CanvasNode & Pick<Required<CanvasNode>, \"children\"> {\n\tif (!node.children) return false\n\tif (isShapeContainerNode(node)) return false\n\tif (isVectorNode(node)) return false\n\n\treturn true\n}\n\nfunction scaled<T extends number | DynamicValue | undefined>(value: T, scaleFactor: number, decimals = 2): T {\n\tif (isNumber(value)) return roundedNumber(value * scaleFactor, decimals) as T\n\n\treturn value\n}\n\nfunction scaledGap<T extends WithLayout[\"gap\"]>(value: T, scaleFactor: number): T {\n\tif (isNumber(value)) return scaled(value, scaleFactor)\n\tif (!isString(value)) return value\n\treturn updatePxValueString(value, pxVal => scaled(pxVal, scaleFactor)) as T\n}\n\nfunction scaledConstraint<T extends HeightConstraintUnit | WidthConstraintUnit>(\n\tconstraint: CSSDimension<T> | number | undefined,\n\tscaleFactor: number,\n\ttopLevel: boolean,\n): CSSDimension<T | \"px\"> | number | undefined {\n\tif (isUndefined(constraint)) return constraint\n\n\tconst [value, unit] = parseConstraintValue<T>(constraint)\n\tif (Number.isNaN(value)) return constraint\n\tif (unit === \"%\" && !topLevel) return constraint\n\treturn createCSSDimension(scaled(value, scaleFactor, 0), unit)\n}\n\nfunction scaleShadows(\n\tshadows: readonly BoxShadow[] | DynamicValue | undefined,\n\tscaleFactor: number,\n): readonly BoxShadow[] | undefined {\n\tif (!shadows || isDynamicValue(shadows)) return undefined\n\treturn shadows.map((shadow: BoxShadow) => {\n\t\tif (shadow.type === \"realistic\") return shadow\n\n\t\treturn getUpdatedShadow(shadow, {\n\t\t\tx: scaled(shadow.x, scaleFactor),\n\t\t\ty: scaled(shadow.y, scaleFactor),\n\t\t\tspread: scaled(shadow.spread, scaleFactor),\n\t\t})\n\t})\n}\n\nfunction scaleShapeNodeAndDescendants(shape: CanvasNode, scaleFactor: number, context: ScaleNodesContext): boolean {\n\tconst initialState = context.initialState.nodesInitialState.get(shape.id)\n\tif (!initialState) return false\n\n\tscaleShapeNode(\n\t\tcontext.tree,\n\t\t{\n\t\t\tcanvasMatrix: initialState.matrix,\n\t\t\trect: initialState.rect,\n\t\t\tdescendantPaths: initialState.descendantPaths,\n\t\t\tdescendantBasicShapes: initialState.descendantBasicShapes,\n\t\t},\n\t\tcontext.initialRect,\n\t\tcontext.resizedRect,\n\t\ttrue,\n\t\tnode => {\n\t\t\tconst basicShapeInitialState = context.initialState.nodesInitialState.get(node.id)\n\t\t\tassert(basicShapeInitialState, \"Basic shape initial state must exist\")\n\t\t\treturn basicShapeInitialState.matrix\n\t\t},\n\t)\n\n\tif (initialState.scalableShapeStylesMap) {\n\t\tscaleVectorStyles(context.tree, initialState.scalableShapeStylesMap, scaleFactor)\n\t}\n\n\treturn true\n}\n\nfunction getAbsoluteAnchorPoint(rect: Rect, anchorPoint: Point): Point {\n\treturn {\n\t\tx: rect.width * anchorPoint.x,\n\t\ty: rect.height * anchorPoint.y,\n\t}\n}\n\nfunction scaleCodeComponentNode(\n\tnode: CodeComponentNode,\n\tscaleFactor: number,\n\tcontext: ScaleNodesContext,\n\ttopLevel: boolean,\n\tscaledProperties: ScaledProperties,\n) {\n\tconst didScaleSize = withSize(node)\n\t\t? scaleNodeSize(node, scaleFactor, context, false, topLevel, scaledProperties)\n\t\t: false\n\n\tconst codeComponentControlProps = context.initialState.nodesInitialState.get(node.id)?.codeComponentControlProps\n\n\tif (!codeComponentControlProps) return didScaleSize\n\n\tfor (const key in codeComponentControlProps) {\n\t\tconst controlProp = codeComponentControlProps[key]\n\t\tif (!controlProp || isDynamicValue(controlProp.value)) continue\n\n\t\tswitch (controlProp.type) {\n\t\t\tcase ControlType.BorderRadius:\n\t\t\t\tscaledProperties[prefixControlPropKey(key)] = {\n\t\t\t\t\t...controlProp,\n\t\t\t\t\tvalue: scaledBorderRadiusControlPropValue(controlProp.value, scaleFactor),\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase ControlType.Padding:\n\t\t\t\tscaledProperties[prefixControlPropKey(key)] = {\n\t\t\t\t\t...controlProp,\n\t\t\t\t\tvalue: scaledPaddingControlPropValue(controlProp.value, scaleFactor),\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase ControlType.Gap:\n\t\t\t\tscaledProperties[prefixControlPropKey(key)] = {\n\t\t\t\t\t...controlProp,\n\t\t\t\t\tvalue: scaledGap(controlProp.value, scaleFactor),\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase ControlType.BoxShadow:\n\t\t\t\tscaledProperties[prefixControlPropKey(key)] = {\n\t\t\t\t\t...controlProp,\n\t\t\t\t\tvalue: scaleShadows(controlProp.value, scaleFactor),\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase ControlType.Font:\n\t\t\t\tscaledProperties[prefixControlPropKey(key)] = {\n\t\t\t\t\t...controlProp,\n\t\t\t\t\tvalue: scaledFontControlPropValue(controlProp.value, scaleFactor),\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase ControlType.Border:\n\t\t\t\tscaledProperties[prefixControlPropKey(key)] = {\n\t\t\t\t\t...controlProp,\n\t\t\t\t\tvalue: scaledBorderPropValue(controlProp.value, scaleFactor),\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase ControlType.Array:\n\t\t\tcase ControlType.Boolean:\n\t\t\tcase ControlType.CollectionReference:\n\t\t\tcase ControlType.Color:\n\t\t\tcase ControlType.Slot:\n\t\t\tcase ControlType.Cursor:\n\t\t\tcase ControlType.CustomCursor:\n\t\t\tcase ControlType.Date:\n\t\t\tcase ControlType.Enum:\n\t\t\tcase ControlType.EventHandler:\n\t\t\tcase ControlType.File:\n\t\t\tcase ControlType.Link:\n\t\t\tcase ControlType.LinkRelValues:\n\t\t\tcase ControlType.MultiCollectionReference:\n\t\t\tcase ControlType.Number:\n\t\t\tcase ControlType.Object:\n\t\t\tcase ControlType.PageScope:\n\t\t\tcase ControlType.RichText:\n\t\t\tcase ControlType.ScrollSectionRef:\n\t\t\tcase ControlType.String:\n\t\t\tcase ControlType.Transition:\n\t\t\tcase ControlType.FusedNumber:\n\t\t\tcase ControlType.Image:\n\t\t\tcase ControlType.TrackingId:\n\t\t\tcase ControlType.VectorSetItem:\n\t\t\tcase ControlType.Location:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tassertNever(controlProp)\n\t\t}\n\t}\n\n\treturn didScaleSize\n}\n\nfunction isRelativeValue(value: RelativeOrFourPixelNumberShorthand): value is `${number}%` {\n\treturn value.includes(\"%\")\n}\n\nfunction scaledBorderRadiusControlPropValue(\n\tvalue: BorderRadiusControlPropValue,\n\tscaleFactor: number,\n): BorderRadiusControlPropValue {\n\tif (isDynamicValue(value)) return value\n\tif (isRelativeValue(value)) return value\n\n\treturn updatePxValueString(value, pxVal => scaled(pxVal, scaleFactor))\n}\n\nfunction scaledPaddingControlPropValue(value: PaddingControlPropValue, scaleFactor: number): PaddingControlPropValue {\n\tif (isDynamicValue(value)) return value\n\n\treturn updatePxValueString(value, pxVal => scaled(pxVal, scaleFactor))\n}\n\nconst roundingForFontSizeUnit: Record<FontSizeUnit, number> = {\n\tpx: 2,\n\trem: 3,\n}\nfunction scaleFontSizeCSSDimension(\n\tvalue: FontSizeCSSDimension | number | undefined,\n\tscaleFactor: number,\n): FontSizeCSSDimension | undefined {\n\tif (isUndefined(value)) return value\n\tconst [size, unit] = isNumber(value) ? ([value, \"px\"] satisfies FontSize) : parseCSSDimension(value)\n\treturn createCSSDimension(scaled(size, scaleFactor, roundingForFontSizeUnit[unit]), unit)\n}\n\nfunction scaledFontControlPropValue(value: FontControlPropValue, scaleFactor: number): FontControlPropValue {\n\tif (isUndefined(value)) return value\n\n\tconst scaledFontSize = scaleFontSizeCSSDimension(value.fontSize, scaleFactor)\n\n\treturn {\n\t\t...value,\n\t\tfontSize: scaledFontSize,\n\t\tlineHeight: value.lineHeight?.[1] === \"px\" ? [scaled(value.lineHeight[0], scaleFactor), \"px\"] : value.lineHeight,\n\t\tletterSpacing:\n\t\t\tvalue.letterSpacing?.[1] === \"px\" ? [scaled(value.letterSpacing[0], scaleFactor), \"px\"] : value.letterSpacing,\n\t}\n}\n\nfunction scaledBorderPropValue(value: BorderControlPropValue, scaleFactor: number): BorderControlPropValue {\n\tif (!value || isVariableReference(value)) return value\n\n\treturn {\n\t\t...value,\n\t\tborderWidth: scaled(value.borderWidth, scaleFactor),\n\t\tborderTop: scaled(value.borderTop, scaleFactor),\n\t\tborderRight: scaled(value.borderRight, scaleFactor),\n\t\tborderBottom: scaled(value.borderBottom, scaleFactor),\n\t\tborderLeft: scaled(value.borderLeft, scaleFactor),\n\t}\n}\n", "import type { ComponentDesignCreateSource } from \"@framerjs/framer-events\"\nimport {\n\ttriggerCanvasPageAddEvent,\n\ttriggerComponentCanvasVariantCreateEvent,\n\ttriggerComponentDesignInstanceEvent,\n} from \"@framerjs/framer-events\"\nimport type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport {\n\tassert,\n\tModuleType,\n\tassertNever,\n\tisEmptyObject,\n\tisMixed,\n\tlocalModuleIdentifierForStableName,\n\tunhandledError,\n} from \"@framerjs/shared\"\nimport { showModalIfAiDisabled } from \"app/ai/config/disableAi.ts\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { experiments } from \"app/experiments.ts\"\nimport { MetricsInteractionViews } from \"app/metrics.ts\"\nimport { isVisibleInOtherVariants } from \"code-generation/utils/isOnlyVisibleInCurrentVariant.ts\"\nimport {\n\tapplyOverridesToReplicasOfDuplicatedPrimaryChild,\n\tgetOriginalVariantNodeIfExists,\n\tupdateInsertedVariantNode,\n\tupdateNodeWhenMovedIntoVariant,\n} from \"code-generation/utils/variantEditingHelpers.ts\"\nimport type { EngineStores } from \"document/EngineStores.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { bothSidesOf, rightSideOf } from \"document/components/tools/utils/FramesHelper.ts\"\nimport { hasEmptyEvents } from \"document/models/CanvasTree/actions/actions.ts\"\nimport { getNavigationTarget, isNavigationAction } from \"document/models/CanvasTree/actions/navigationActions.ts\"\nimport { isShowRelativeOverlayAction } from \"document/models/CanvasTree/actions/overlayActions.ts\"\nimport { getSetVariantTarget, isSetVariantAction } from \"document/models/CanvasTree/actions/variantActions.ts\"\nimport {\n\tCanvasPageNode,\n\ttype CanvasNode,\n\tCanvasTree,\n\tCodeComponentNode,\n\tFrameNode,\n\tInvalidID,\n\ttype LoadedScopeNode,\n\ttype MaybeNodeID,\n\tNullID,\n\ttype NodeID,\n\tOvalShapeNode,\n\tPolygonShapeNode,\n\ttype SVGNode,\n\ttype ScopeNode,\n\tShapeContainerNode,\n\tSmartComponentNode,\n\ttype VectorNode,\n\ttype WebPageNode,\n\tisVectorNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { AnalyticsScopeNode } from \"document/models/CanvasTree/nodes/AnalyticsScopeNode.ts\"\nimport type { MaybeCanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport { CanvasChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport { CONTENT_MANAGEMENT_ID } from \"document/models/CanvasTree/nodes/ContentManagementNode.ts\"\nimport { getContentManagementNode } from \"document/models/CanvasTree/nodes/ContentManagementNode.utils.ts\"\nimport { DesignPageNode } from \"document/models/CanvasTree/nodes/DesignPageNode.ts\"\nimport { EntityRootNode } from \"document/models/CanvasTree/nodes/EntityRootNode.ts\"\nimport {\n\tCOMPONENTS_ENTITY_TYPE_ROOT_ID,\n\tLAYOUT_TEMPLATE_ENTITY_ROOT_ID,\n\tVECTOR_SET_ENTITY_TYPE_ROOT_ID,\n} from \"document/models/CanvasTree/nodes/EntityTypeRootNode.ts\"\nimport {\n\tLAYOUT_TEMPLATE_HEIGHT,\n\tLayoutTemplateNode,\n\ttype LoadedLayoutTemplateNode,\n} from \"document/models/CanvasTree/nodes/LayoutTemplateNode.ts\"\nimport { randomID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport { getShapeContainerNodeFor } from \"document/models/CanvasTree/nodes/ShapeContainerNode.ts\"\nimport { SlotNode } from \"document/models/CanvasTree/nodes/SlotNode.ts\"\nimport { isInlineVectorNode, isRootVectorNode } from \"document/models/CanvasTree/nodes/TreeNode.ts\"\nimport { type LoadedVectorSetNode, VectorSetNode } from \"document/models/CanvasTree/nodes/VectorSetNode.ts\"\nimport { getBreakpointForNode } from \"document/models/CanvasTree/nodes/utils/breakpointHelpers.ts\"\nimport { convertCSSColorVariableToValue } from \"document/models/CanvasTree/nodes/utils/convertCSSColorVariableToValue.ts\"\nimport { createEntityFolderNodesFromPath } from \"document/models/CanvasTree/nodes/utils/entityFolderNode.ts\"\nimport { createReferenceForNodeIfNeeded } from \"document/models/CanvasTree/nodes/utils/entityReferenceNode.ts\"\nimport type { AnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport { isAnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport {\n\tisCanvasPageNode,\n\tisCodeComponentNode,\n\tisDesignPageNode,\n\tisFormBooleanInputNode,\n\tisFormPlainTextInputNode,\n\tisFormSelectNode,\n\tisFrameNode,\n\tisLayoutTemplateNode,\n\tisOverlayNode,\n\tisRichTextNode,\n\tisSVGNode,\n\tisShapeContainerNode,\n\tisSlotNode,\n\tisSlotPropertyNode,\n\tisSmartComponentNode,\n\tisStackComponent,\n\tisStackOrGridComponent,\n\tisVectorSetNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isFixedOrRelativeOverlay, nodeIsInOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { updateReplicaNodeOverrides } from \"document/models/CanvasTree/nodes/utils/updateReplicaOverrides.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type { CombinedVariableProviderValueMap } from \"document/models/CanvasTree/traits/VariableProvider.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { WithAspectRatio } from \"document/models/CanvasTree/traits/WithAspectRatio.ts\"\nimport {\n\ttype WithBreakpointVariants,\n\twithBreakpointVariants,\n} from \"document/models/CanvasTree/traits/WithBreakpointVariants.ts\"\nimport type { WithChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { getChildren, withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { withEventActions } from \"document/models/CanvasTree/traits/WithEventActions.ts\"\nimport type { FillImageAlt, WithFill, WithOptionalFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { withFillImageAlts, withOptionalFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport {\n\tgetFloatingPositionProps,\n\thasFloatingPosition,\n} from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { withFrameEvents } from \"document/models/CanvasTree/traits/WithFrameEvents.ts\"\nimport { hasItemsOrderOverride } from \"document/models/CanvasTree/traits/WithItemsOrder.ts\"\nimport {\n\ttype HasStackLayout,\n\tgetLayoutType,\n\thasAnyLayout,\n\thasStackLayout,\n\twithLayout,\n} from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { isLockedOrLockedByParent, withLock } from \"document/models/CanvasTree/traits/WithLock.ts\"\nimport { type WithOverflow, withOverflow } from \"document/models/CanvasTree/traits/WithOverflow.ts\"\nimport { type WithPadding, withPadding } from \"document/models/CanvasTree/traits/WithPadding.ts\"\nimport { withPath } from \"document/models/CanvasTree/traits/WithPath.ts\"\nimport type { WithConstraints, WithPins } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { isPinnable } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { withPosition } from \"document/models/CanvasTree/traits/WithPosition.ts\"\nimport type { WithPositionType } from \"document/models/CanvasTree/traits/WithPositionType.ts\"\nimport type { WithRepeatArray } from \"document/models/CanvasTree/traits/WithRepeatArray.ts\"\nimport type { WithReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport { withReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport type { WithRotation } from \"document/models/CanvasTree/traits/WithRotation.ts\"\nimport { withRotation } from \"document/models/CanvasTree/traits/WithRotation.ts\"\nimport type { Loaded } from \"document/models/CanvasTree/traits/WithScopeLoader.ts\"\nimport { withSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport type {\n\tIsMaster,\n\tIsReplica,\n\tIsReplicaOrReplicaChild,\n\tReplicaOverrides,\n\tWithTemplate,\n} from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport {\n\tisExternalMaster,\n\tisHiddenMaster,\n\tisInternalHiddenMaster,\n\tisMaster,\n\tisMasterChild,\n\tisMasterOrMasterChild,\n\tisReplica,\n\tisReplicaChild,\n\tisReplicaOrReplicaChild,\n\twithTemplate,\n} from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isFontSize } from \"document/models/CanvasTree/traits/WithTextStyle.ts\"\nimport { creates3dContext, getOriginPoint } from \"document/models/CanvasTree/traits/WithTransforms.ts\"\nimport type {\n\tGestureType,\n\tIsBreakpoint,\n\tIsPrimaryVariant,\n\tIsVariant,\n} from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport {\n\tisBreakpointVariant,\n\tisGestureVariant,\n\tisPrimaryVariant,\n\tisReplicaVariant,\n\tisReplicaVariantChild,\n\tisReplicaVariantOrReplicaVariantChild,\n\tisTopLevelVariant,\n\tisVariant,\n\twithVariant,\n} from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { type IsVectorSetItem, isVectorSetItem } from \"document/models/CanvasTree/traits/WithVectorSetItem.ts\"\nimport type { WithVectorSetItems } from \"document/models/CanvasTree/traits/WithVectorSetItems.ts\"\nimport { withVisibility } from \"document/models/CanvasTree/traits/WithVisibility.ts\"\nimport { createCSSDimension } from \"document/models/CanvasTree/traits/utils/CSSDimension.ts\"\nimport { EagerVariableProviderMap } from \"document/models/CanvasTree/traits/utils/EagerVariableProviderMap.ts\"\nimport { isNotFound } from \"document/models/CanvasTree/traits/utils/Reduced.ts\"\nimport { acceptsChild } from \"document/models/CanvasTree/traits/utils/acceptsChild.ts\"\nimport { getFramePreset } from \"document/models/CanvasTree/traits/utils/framePresets.ts\"\nimport { isDeviceNode } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifierChecks.ts\"\nimport { isWebPageInstance } from \"document/models/CanvasTree/traits/utils/isWebPageInstance.ts\"\nimport {\n\tisPositionAbsolute,\n\tisPositionFixed,\n\tisPositionRelative,\n\tpositionTypeUpdateForNewParent,\n} from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport {\n\tconvertCornerPointsToCanvas,\n\tconvertFrameToCanvas,\n\tgetBoundingFrameForNodes,\n\tgetViewportRect,\n} from \"document/models/CanvasTree/utils/geometry.ts\"\nimport {\n\tgetNodeUpdateResolvingDynamicValues,\n\tgetVariableToDefaultValueMap,\n} from \"document/models/CanvasTree/utils/getNodeUpdateResolvingDynamicValues.ts\"\nimport type { NodeIDsOrNodes } from \"document/models/CanvasTree/utils/nodeIdsOrNodes.ts\"\nimport { getNodesForNodeIDsOrNodes } from \"document/models/CanvasTree/utils/nodeIdsOrNodes.ts\"\nimport { updateConstrainedFrame } from \"document/models/ConstraintSolver.ts\"\nimport type { EventAction } from \"document/models/EventAction.ts\"\nimport { isEventAction } from \"document/models/EventAction.ts\"\nimport { Matrix } from \"document/models/Matrix.ts\"\nimport { Path } from \"document/models/Path.ts\"\nimport type { EventHandlerControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { type PrefixedControlProps, isPrefixedControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport { getCodeComponentControlPropValues } from \"document/models/controlProps/getCodeComponentControlPropValues.ts\"\nimport { shouldGuessPinToBottom } from \"document/models/shouldGuessPinToBottom.ts\"\nimport { shouldGuessPinToRight } from \"document/models/shouldGuessPinToRight.ts\"\nimport type { CanvasStore } from \"document/stores/CanvasStore.ts\"\nimport { CodeFileCreationType } from \"document/stores/ModalStore.ts\"\nimport { PopoverType } from \"document/stores/PopoverStore.ts\"\nimport { isSelectionEqual } from \"document/stores/SelectionStore.ts\"\nimport type { SelectionStore } from \"document/stores/SelectionStore.ts\"\nimport { Tools } from \"document/stores/ToolStore.ts\"\nimport { ActiveContentPanelTab, ActiveMainView, CanvasPanelTab } from \"document/utils/ActiveEditorType.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { paddingFromNode } from \"document/utils/StackComponent/paddingFromNode.ts\"\nimport { overridesToMakeVariantsMatchNewBreakpoint } from \"document/utils/breakPointAndVariantMatching.ts\"\nimport { getCompatibleNodeProperties } from \"document/utils/getCompatibleNodeProperties.ts\"\nimport { isSortableNode, updateIdIndexInItemsOrder } from \"document/utils/itemsOrderOverrideHelpers.ts\"\nimport { collectResponsiveOverrides } from \"document/utils/layoutHelpers.ts\"\nimport { isLayoutSection } from \"document/utils/layoutSectionHelpers.ts\"\nimport { uniqueName } from \"document/utils/uniqueName.ts\"\nimport type { Size } from \"library/index.ts\"\nimport type { WithPath } from \"library/render/traits/Path.ts\"\nimport { ConvertColor } from \"library/render/types/Color/index.ts\"\nimport type { ConstraintMask } from \"library/render/types/Constraints.ts\"\nimport { DimensionType, isAutoDimensionType } from \"library/render/types/Constraints.ts\"\nimport { Point } from \"library/render/types/Point.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport { commonValue } from \"utils/commonValue.ts\"\nimport { getCollectionForIdentifier } from \"utils/getCollectionForIdentifier.ts\"\nimport { importSVG } from \"utils/paperjs/importSVG.ts\"\nimport { restoreRepeatedItemsFromSnapshots, snapshotRepeatedItemsForNodes } from \"utils/repeaterUtils.ts\"\nimport { isNull, isNumber, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { generateVariableReferenceUpdateForNode } from \"utils/updateDynamicValues.ts\"\nimport { toastProgress } from \"web/lib/toaster.ts\"\nimport { UIInteraction, record } from \"web/lib/tracker.ts\"\nimport {\n\tTemplateHelper,\n\tcreateDuplicatedFromIfAllowed,\n\tgenerateReplicaChildId,\n\tmergeOverrides,\n} from \"../../models/CanvasTree/nodes/TemplateHelper.ts\"\nimport type { WithSize } from \"../../models/CanvasTree/traits/WithSize.ts\"\nimport { editPageTitle } from \"../chrome/Pages/utils/editPageRow.ts\"\nimport { getRouteSegmentNodeByWebPageId } from \"../chrome/Pages/utils/getRouteSegmentNodeByWebPageId.ts\"\nimport { QuickActionsCategoryType } from \"../chrome/QuickActions/types.ts\"\nimport { promptAddAbVariant } from \"../chrome/analytics/utils/promptAddAbVariant.ts\"\nimport { createContentManagementNodeIfNeeded } from \"../chrome/contentManagement/utils/createContentManagementNodeIfNeeded.ts\"\nimport { trackDimensionTypeChange } from \"../chrome/properties/panels/utils/trackDimensionTypeChange.ts\"\nimport { getActionsForNode } from \"../chrome/properties/utils/eventActions.ts\"\nimport { isStatusGestureVariant } from \"../chrome/properties/utils/gestureStatusVariant.ts\"\nimport { remapOverrides } from \"../tools/utils/remapOverrides.ts\"\nimport {\n\tinferStackLayout,\n\treparentStackChildren,\n\tupdateChildrenSizingWhenWrappedInStack,\n} from \"../tools/utils/stackCreateHelper.ts\"\nimport { RenamedIds, updateNodeConnections } from \"../tools/utils/updateNodeConnections.ts\"\nimport { cloneWithRenamedIdMap } from \"../unlinking/utils.ts\"\nimport { countChildNodes } from \"./countChildNodes.ts\"\nimport type { PrimaryVariantSourceNeedsWrappingFrame } from \"./createSmartComponent.ts\"\nimport {\n\tblendNestedOpacityAndRotation,\n\tgetDetachedControlPropValues,\n\tgetDetachedInstanceVariableReferenceUpdate,\n\tgetDetachedNodeComputedValueUpdate,\n\tgetDetachedRepeatVariableControlPropUpdate,\n\tgetRawEventActions,\n\treplicaOverridesForInstanceVariables,\n\twithoutPositionOrSizeOrNameProperties,\n} from \"./detachComponentHelpers.ts\"\nimport { type EventSource, enableAutoSizeForNodes } from \"./enableAutoSizeForNodes.ts\"\nimport { getDefaultName } from \"./nodes.ts\"\nimport { nameToPath } from \"./pathToName.ts\"\nimport { renameLayers as renameLayersInternal } from \"./renameLayers.ts\"\nimport { canReplaceNode } from \"./replaceNodes.ts\"\nimport { getScaleNodesInitialState, scaleNodes } from \"./scaleToolUtils.ts\"\n\ninterface ParentNodeGroup {\n\t[key: string]: CanvasNode[]\n}\n\nenum Wrappers {\n\tFrame,\n\tStack,\n\tViewBox,\n}\n\nexport namespace ContextAction {\n\texport function canCopyNodes(nodes: CanvasNode[]): boolean {\n\t\treturn nodes.some(node => canCopyNode(node))\n\t}\n\n\t// Duplication is allowed if some of the nodes can be duplicated\n\texport function canDuplicateNodes(nodes: CanvasNode[]): boolean {\n\t\treturn nodes.some(node => canDuplicateNode(node))\n\t}\n\n\texport function canCutNodes(engine: VekterEngine, nodes: CanvasNode[]): boolean {\n\t\treturn canCopyNodes(nodes) && canDeleteOrHideNodes(engine, nodes)\n\t}\n\n\texport function duplicateNodes(\n\t\tengine: VekterEngine,\n\t\tselection: NodeID[],\n\t\tnewParentOverride?: { node: (CanvasNode & WithChildren) | null; insertionIndex: number } | undefined,\n\t\tshouldSetSelection = true,\n\t): Set<string> | undefined {\n\t\tconst {\n\t\t\tdocumentSettingsStore,\n\t\t\tcodeGenerationStore,\n\t\t\tmodalStore,\n\t\t\tcanvasStore,\n\t\t\tscopeStore,\n\t\t\tselectionStore,\n\t\t\ttreeStore,\n\t\t} = engine.stores\n\t\tconst tree = treeStore.tree\n\t\tconst nodes = tree.withoutDescendants(tree.getNodes(selection))\n\t\tconst scope = scopeStore.active\n\t\tconst singleSelectedNode = nodes.length === 1 ? nodes[0] : undefined\n\n\t\tif (\n\t\t\t!isUndefined(singleSelectedNode) &&\n\t\t\tisTopLevelVariant(singleSelectedNode) &&\n\t\t\t!isBreakpointVariant(singleSelectedNode) &&\n\t\t\tisFrameNode(singleSelectedNode) &&\n\t\t\tisSmartComponentNode(scope)\n\t\t) {\n\t\t\tconst baseNodeRect = tree.getRect(singleSelectedNode)\n\t\t\tconst targetRect = rightSideOf(tree, scope, singleSelectedNode, baseNodeRect)\n\t\t\tconst node = ContextAction.createVariant(\n\t\t\t\tengine.componentLoader,\n\t\t\t\ttreeStore.tree,\n\t\t\t\tselectionStore,\n\t\t\t\tcanvasStore,\n\t\t\t\tscope,\n\t\t\t\tsingleSelectedNode,\n\t\t\t\ttargetRect,\n\t\t\t)\n\t\t\tif (!node) return\n\t\t\treturn new Set([node.id])\n\t\t}\n\n\t\t// Check if duplicating an A/B testing variant or breakpoint variant\n\t\tconst anyBreakpointVariant = nodes.find(node => isBreakpointVariant(node) && isFrameNode(node)) as\n\t\t\t| (FrameNode & IsVariant & IsBreakpoint)\n\t\t\t| undefined\n\t\tif (anyBreakpointVariant && isFrameNode(anyBreakpointVariant)) {\n\t\t\tconst scopeNode = treeStore.tree.getScopeNodeFor(anyBreakpointVariant)\n\t\t\tif (scopeNode && isWebPageNode(scopeNode)) {\n\t\t\t\tif (scopeNode.abTestingParentId) {\n\t\t\t\t\t// Use the existing A/B variant duplication logic which handles confirmation modals\n\t\t\t\t\tengine.loadScopesThenProcess(\n\t\t\t\t\t\t[scopeNode, AnalyticsScopeNode.get(treeStore.tree)],\n\t\t\t\t\t\tasync ([webPage, analyticsScope]) => {\n\t\t\t\t\t\t\tif (webPage) {\n\t\t\t\t\t\t\t\tpromptAddAbVariant(engine, webPage, analyticsScope, \"context_menu\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tmodalStore.set({\n\t\t\t\t\t\ttype: ModalType.DuplicateWebPage,\n\t\t\t\t\t\tsource: \"context_menu\",\n\t\t\t\t\t\tduplicateFromId: scopeNode.id,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tconst originalRects = nodes.map(node => tree.getRect(node))\n\n\t\tconst renamedIds = new RenamedIds()\n\t\tconst newSelection: Set<NodeID> = new Set()\n\t\tconst filledFrames: Rect[] = []\n\t\tconst cloneMap = new Map<CanvasNode, CanvasNode>()\n\t\tconst duplicationMap: Map<NodeID, NodeID> = new Map()\n\n\t\tlet duplicationFrameCount = 0\n\t\tnodes.forEach((node: CanvasNode & WithTemplate, idx: number) => {\n\t\t\tif (!canDuplicateNode(node)) return\n\t\t\tconst parent = tree.getParent(node.id)\n\n\t\t\t// Only allow duplicating an overlay node if the parent component\n\t\t\t// has a free event handler to trigger it.\n\t\t\tif (isOverlayNode(node)) {\n\t\t\t\tif (parent && isCodeComponentNode(parent)) {\n\t\t\t\t\tif (!hasEmptyEvents(parent, engine.componentLoader)) return\n\t\t\t\t} else if (!parent || !isBreakpointVariant(parent)) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Track layer duplication of Frames\n\t\t\tfor (const n of node.walk()) {\n\t\t\t\tif (isFrameNode(n)) {\n\t\t\t\t\tduplicationFrameCount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst clone = engine.cloneNode(node, false, true, renamedIds)\n\t\t\trenamedIds.set(node.id, clone.id)\n\t\t\tduplicationMap.set(node.id, clone.id)\n\t\t\tnewSelection.add(clone.id)\n\t\t\tcloneMap.set(node, clone)\n\t\t\tif (node.isMaster) {\n\t\t\t\t// create new instance\n\t\t\t\ttriggerComponentDesignInstanceEvent({})\n\t\t\t} else if (node.replicaInfo) {\n\t\t\t\tconst { master } = node.replicaInfo\n\t\t\t\tconst masterNode = master && tree.getNode(master)\n\t\t\t\tconst isExternal = masterNode && isExternalMaster(masterNode)\n\t\t\t\tif (!isExternal) {\n\t\t\t\t\t// create new instance from another local design instance\n\t\t\t\t\ttriggerComponentDesignInstanceEvent({})\n\t\t\t\t}\n\t\t\t} else if (isMasterChild(node)) {\n\t\t\t\t// Only keep existing related replica overrides if the node stays within the same master\n\t\t\t\tconst staysWithinMaster =\n\t\t\t\t\t!newParentOverride || Boolean(newParentOverride.node && isMasterOrMasterChild(newParentOverride.node))\n\t\t\t\tif (staysWithinMaster) {\n\t\t\t\t\tapplyOverridesToReplicasOfDuplicatedPrimaryChild(engine, node, renamedIds)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newParentOverride) {\n\t\t\t\tconst currentParent = tree.getParent(node.id)\n\t\t\t\tif (newParentOverride.node) {\n\t\t\t\t\tlet originalNewParent: (CanvasNode & WithChildren) | null = newParentOverride.node\n\t\t\t\t\tif (isReplicaOrReplicaChild(newParentOverride.node)) {\n\t\t\t\t\t\toriginalNewParent = getOriginalVariantNodeIfExists(tree, newParentOverride.node) as\n\t\t\t\t\t\t\t| (CanvasNode & WithChildren)\n\t\t\t\t\t\t\t| null\n\n\t\t\t\t\t\tif (!originalNewParent) return\n\t\t\t\t\t}\n\n\t\t\t\t\tif (acceptsChild(engine.tree, originalNewParent, clone, scopeStore.active.id, engine.componentLoader)) {\n\t\t\t\t\t\tconst stackToStackMove =\n\t\t\t\t\t\t\tcurrentParent && isStackComponent(currentParent) && isStackComponent(originalNewParent)\n\t\t\t\t\t\tconst frameToFrameMove = currentParent && isFrameNode(currentParent) && isFrameNode(originalNewParent)\n\n\t\t\t\t\t\tif (stackToStackMove || frameToFrameMove) {\n\t\t\t\t\t\t\t// Layout rules will be valid after move\n\t\t\t\t\t\t\tengine.moveNode(clone.id, originalNewParent.id, newParentOverride.insertionIndex)\n\t\t\t\t\t\t} else if (isPinnable(clone)) {\n\t\t\t\t\t\t\tengine.moveNode(clone.id, originalNewParent.id, newParentOverride.insertionIndex)\n\t\t\t\t\t\t\t// clones might not have their cache initialized yet\n\t\t\t\t\t\t\tconst allowCache = false\n\t\t\t\t\t\t\tconst parentSizeInfo = tree.getParentSizeInfo(clone, originalNewParent, true, allowCache)\n\t\t\t\t\t\t\t// make sure node gets a valid layout\n\t\t\t\t\t\t\tconst layoutUpdate = clone.updateForSize(originalRects[idx] ?? {}, parentSizeInfo)\n\t\t\t\t\t\t\t// move ground nodes to the top left of their new parent\n\t\t\t\t\t\t\tif (!currentParent) {\n\t\t\t\t\t\t\t\tlayoutUpdate.left = 0\n\t\t\t\t\t\t\t\tlayoutUpdate.top = 0\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tengine.tree.current(clone)?.set(layoutUpdate)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// shape editing\n\t\t\t\t\t\t\tContextAction.convertNodeToNewParent(\n\t\t\t\t\t\t\t\tengine,\n\t\t\t\t\t\t\t\tclone,\n\t\t\t\t\t\t\t\tcurrentParent,\n\t\t\t\t\t\t\t\tnewParentOverride.node,\n\t\t\t\t\t\t\t\tnewParentOverride.insertionIndex,\n\t\t\t\t\t\t\t\tnode,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (isReplicaVariantOrReplicaVariantChild(newParentOverride.node)) {\n\t\t\t\t\t\t\tupdateNodeWhenMovedIntoVariant(\n\t\t\t\t\t\t\t\tengine,\n\t\t\t\t\t\t\t\tclone,\n\t\t\t\t\t\t\t\tnewParentOverride.node,\n\t\t\t\t\t\t\t\toriginalNewParent,\n\t\t\t\t\t\t\t\tnewSelection,\n\t\t\t\t\t\t\t\trenamedIds,\n\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, newParentOverride.node)\n\t\t\t\t\t\t\tif (replica) {\n\t\t\t\t\t\t\t\tconst cloneIdInVariant = generateReplicaChildId(replica.id, clone.id)\n\t\t\t\t\t\t\t\tduplicationMap.set(node.id, cloneIdInVariant)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tContextAction.convertNodeToNewParent(\n\t\t\t\t\t\tengine,\n\t\t\t\t\t\tclone,\n\t\t\t\t\t\tcurrentParent,\n\t\t\t\t\t\tnewParentOverride.node,\n\t\t\t\t\t\tnewParentOverride.insertionIndex,\n\t\t\t\t\t\tnode,\n\t\t\t\t\t)\n\t\t\t\t\tif (isStackComponent(currentParent) && originalRects[idx]) {\n\t\t\t\t\t\t// Make sure stack items keep their original size\n\t\t\t\t\t\tengine.tree.current(clone)?.set(clone.updateForSize(originalRects[idx], null) as any)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tif (!newParentOverride) {\n\t\t\t// Offset calculation and canvas centering are slightly different for nested and ground nodes.\n\t\t\t// Keep track of whether all selected nodes are nested to handle these cases correctly.\n\t\t\tconst hasGroundNodes = nodes.some(node => tree.isGroundNode(node))\n\t\t\tconst hasRotatedNodes = nodes.some(node => withRotation(node) && node.resolveValue(\"rotation\") !== 0)\n\t\t\tif (nodes.length) {\n\t\t\t\tconst nodesRects = nodes.map(node => convertFrameToCanvas(tree, node))\n\t\t\t\tconst nodeSelectionRect = Rect.merge(...nodesRects)\n\t\t\t\tlet offsetDistance: Point | undefined\n\n\t\t\t\tconst hasDuplicatedSelectedNodes = hasSameSelectionSinceLastDuplication(engine, selection)\n\t\t\t\tconst nodesAreChildrenOfStack = areNodesInAStack(tree, nodes)\n\t\t\t\t// Never use duplication offset for vector type nodes.\n\t\t\t\tconst anyVectorNode = nodes.some(node => isVectorNode(node))\n\n\t\t\t\t// If the following conditions are met, keep track of the distance between the last two duplicated nodes\n\t\t\t\t// and apply it when inserting the new node\n\t\t\t\tconst lastDuplicationMap = documentSettingsStore.lastDuplicationMap\n\t\t\t\tlet usingDuplicationOffset = false\n\t\t\t\tif (\n\t\t\t\t\t!anyVectorNode &&\n\t\t\t\t\thasDuplicatedSelectedNodes &&\n\t\t\t\t\t!nodesAreChildrenOfStack &&\n\t\t\t\t\t!hasRotatedNodes &&\n\t\t\t\t\tlastDuplicationMap\n\t\t\t\t) {\n\t\t\t\t\tconst sourceNodesIds = lastDuplicationMap.keys()\n\t\t\t\t\tconst sourceBoundingRect = getBoundingFrameForNodes(engine.tree, tree.getNodes(sourceNodesIds))\n\t\t\t\t\tusingDuplicationOffset = true\n\t\t\t\t\toffsetDistance = Point.subtract(nodeSelectionRect, sourceBoundingRect)\n\t\t\t\t}\n\n\t\t\t\tlet offset: Point = offsetDistance || { y: 0, x: 0 }\n\n\t\t\t\t// `bothSidesOf` triggers a flow that we use to make sure a duplicate node never\n\t\t\t\t// overlaps with an existing ground node. We only want to trigger this for the cases\n\t\t\t\t// in which we're not keeping track of the distance between the original and\n\t\t\t\t// duplicated nodes.\n\t\t\t\tconst singleNode = nodes[0]\n\t\t\t\tif (!anyVectorNode && hasGroundNodes && !usingDuplicationOffset && singleNode) {\n\t\t\t\t\tconst newRect = bothSidesOf(\n\t\t\t\t\t\ttree,\n\t\t\t\t\t\tscopeStore.active,\n\t\t\t\t\t\tsingleNode,\n\t\t\t\t\t\tnodeSelectionRect,\n\t\t\t\t\t\t// Vector Set Items should be offset by half their width to align with the\n\t\t\t\t\t\t// suggestion rect.\n\t\t\t\t\t\tnodes.every(isVectorSetItem) ? { x: engine.tree.getRect(singleNode).width } : offsetDistance,\n\t\t\t\t\t)\n\t\t\t\t\toffset = Point.subtract(newRect, nodeSelectionRect)\n\t\t\t\t}\n\t\t\t\tfor (const node of nodes) {\n\t\t\t\t\tconst { x, y, width, height } = tree.getRect(node)\n\t\t\t\t\tconst clone = cloneMap.get(node)\n\t\t\t\t\tif (!clone) continue\n\n\t\t\t\t\tconst nodeParent = engine.tree.getParent(node.id)\n\t\t\t\t\tconst parent = engine.tree.getParent(clone.id)\n\n\t\t\t\t\tif (parent && nodeParent && isReplicaVariantOrReplicaVariantChild(nodeParent)) {\n\t\t\t\t\t\tupdateNodeWhenMovedIntoVariant(engine, clone, nodeParent, parent, newSelection, renamedIds)\n\n\t\t\t\t\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, nodeParent)\n\t\t\t\t\t\tif (replica) {\n\t\t\t\t\t\t\tconst cloneIdInVariant = generateReplicaChildId(replica.id, clone.id)\n\t\t\t\t\t\t\tduplicationMap.set(node.id, cloneIdInVariant)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Don't update layout of stack children\n\t\t\t\t\tif (parent && isStackComponent(parent)) continue\n\n\t\t\t\t\tconst newX = x + offset.x\n\t\t\t\t\tconst newY = y + offset.y\n\t\t\t\t\tconst parentSizeInfo = engine.tree.getParentSizeInfo(node, nodeParent)\n\t\t\t\t\tconst update = clone.updateForRect({\n\t\t\t\t\t\trect: {\n\t\t\t\t\t\t\t// Don't pixel align vector nodes. The offsets are intentional.\n\t\t\t\t\t\t\tx: isVectorNode(node) ? newX : Math.round(newX),\n\t\t\t\t\t\t\ty: isVectorNode(node) ? newY : Math.round(newY),\n\t\t\t\t\t\t\twidth,\n\t\t\t\t\t\t\theight,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t// supportsViewportSizing is going to check if the node is in a breakpoint by checking its\n\t\t\t\t\t\t// cache, but the clone might not have its cache updated yet. Therefore here we use the copied\n\t\t\t\t\t\t// node, as it should share the same parent size info as the clone.\n\t\t\t\t\t\tparentSizeInfo,\n\t\t\t\t\t\tconstraintsLocked: false,\n\t\t\t\t\t\tshouldGuessPinToBottom: true,\n\t\t\t\t\t\tshouldGuessPinToRight: shouldGuessPinToRight(engine.tree, clone, parent),\n\t\t\t\t\t})\n\n\t\t\t\t\tengine.tree.current(clone)?.set(update)\n\t\t\t\t\tif (hasGroundNodes && tree.isGroundNode(clone)) {\n\t\t\t\t\t\tfilledFrames.push(clone.rect())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdocumentSettingsStore.lastDuplicationMap = duplicationMap\n\n\t\tconst vectorSetItems: (CanvasNode & IsVectorSetItem)[] = []\n\t\tlet onlyOverlays = true\n\t\tfor (const node of cloneMap.values()) {\n\t\t\tupdateNodeConnections(tree, engine.componentLoader, node, renamedIds, false)\n\t\t\tif (isVectorSetItem(node)) vectorSetItems.push(node)\n\t\t\tif (!isFixedOrRelativeOverlay(node)) onlyOverlays = false\n\t\t}\n\n\t\tif (vectorSetItems.length) {\n\t\t\tvoid codeGenerationStore.createVectorSet(vectorSetItems)\n\t\t}\n\n\t\tif (onlyOverlays && cloneMap.size > 0) {\n\t\t\t// If we only duplicated overlays then hide any visible overlays (the source nodes), so only the new ones\n\t\t\t// will be visible after the selection is set. If any duplicated nodes are not overlays then for safety we don't do this\n\t\t\t// because they might be duplicating a node in an overlay or a node that they want to drag into a visible overlay.\n\t\t\tengine.stores.overlayStore.hideAll()\n\t\t}\n\n\t\tif (filledFrames.length) {\n\t\t\tconst addedFrames = Rect.merge(...filledFrames)\n\t\t\tcanvasStore.scrollToCenter(Rect.center(addedFrames))\n\t\t}\n\n\t\tif (shouldSetSelection && newSelection.size > 0) {\n\t\t\tengine.stores.selectionStore.set(newSelection, { sticky: true, switchToProperties: true })\n\t\t}\n\n\t\tif (duplicationFrameCount > 0) {\n\t\t\trecord(\"layout_frame\", { source: \"duplication\", count: duplicationFrameCount })\n\t\t}\n\n\t\treturn newSelection\n\t}\n\n\tfunction shouldShowDeleteNodesWarning(nodes: CanvasNode[]) {\n\t\tconst SHOW_DELETION_WARNING_NODE_COUNT = 50\n\n\t\tif (nodes.length >= SHOW_DELETION_WARNING_NODE_COUNT) return true\n\n\t\tlet count = nodes.length\n\t\tnodes.forEach(node => {\n\t\t\tcount += countChildNodes(node)\n\t\t})\n\n\t\treturn count >= SHOW_DELETION_WARNING_NODE_COUNT\n\t}\n\n\texport function deleteOrHideNodes(engine: VekterEngine, nodes: CanvasNode[], showWarning?: boolean) {\n\t\tconst withoutDescendants = engine.tree.withoutDescendants(nodes)\n\t\tfunction deleteOrHide() {\n\t\t\tconst nodesToDelete: NodeID[] = []\n\t\t\tconst nodesToHide: CanvasNode[] = []\n\n\t\t\twithoutDescendants.forEach(node => {\n\t\t\t\tif (isReplicaVariantChild(node)) {\n\t\t\t\t\tif (!isVisibleInOtherVariants(engine.tree, node)) {\n\t\t\t\t\t\tconst originalNode = engine.tree.get(node.originalid)\n\t\t\t\t\t\tif (originalNode && canDeleteNode(originalNode)) {\n\t\t\t\t\t\t\tnodesToDelete.push(originalNode.id)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnodesToHide.push(node)\n\t\t\t\t\t}\n\t\t\t\t} else if (canDeleteNode(node)) {\n\t\t\t\t\tnodesToDelete.push(node.id)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tnodesToHide.forEach(node => node.set({ visible: false }))\n\t\t\tengine.deleteNodes(nodesToDelete)\n\t\t\tengine.stores.selectionStore.clear()\n\t\t\tengine.stores.treeStore.setHighlight(null)\n\t\t}\n\n\t\tif (showWarning && shouldShowDeleteNodesWarning(withoutDescendants)) {\n\t\t\tengine.stores.modalStore.set({\n\t\t\t\ttype: ModalType.Confirmation,\n\t\t\t\tvariant: \"destructive\",\n\t\t\t\ttitle: \"Delete Selection\",\n\t\t\t\tdescription: \"You are about to delete the selected layers for all project collaborators.\",\n\t\t\t\tconfirmLabel: Dictionary.Delete,\n\t\t\t\tonConfirm: deleteOrHide,\n\t\t\t\tsource: \"delete_node\",\n\t\t\t})\n\t\t} else {\n\t\t\tdeleteOrHide()\n\t\t}\n\t}\n\n\texport function deleteAction(engine: VekterEngine, nodes?: CanvasNode[]) {\n\t\tif (engine.tool.deleteAction) {\n\t\t\tengine.tool.deleteAction()\n\t\t} else if (nodes) {\n\t\t\tdeleteOrHideNodes(engine, nodes, true)\n\t\t}\n\t}\n\n\t// Check if the \"delete\" option is available for the given nodes. It does not neccessarily mean deleting the nodes,\n\t// in variant editing delete might just hide the replica node under the hood.\n\texport function canDeleteOrHideNodes(engine: VekterEngine, nodes?: CanvasNode[]) {\n\t\tif (engine.tool.deleteAction) {\n\t\t\treturn !!engine.tool.canDelete && engine.tool.canDelete()\n\t\t} else {\n\t\t\treturn !!nodes && nodes.some(n => canDeleteOrHideNode(n))\n\t\t}\n\t}\n\n\t// biome-ignore lint/correctness/noUnusedVariables:\n\t// biome-ignore lint/correctness/noUnusedFunctionParameters: cleanup references and remove tree arg\n\texport function canRenameNode(tree: CanvasTree, node: CanvasNode) {\n\t\t// Slot property nodes take the name of the slot control, so they can't be renamed by users.\n\t\tif (isSlotPropertyNode(node)) return false\n\n\t\tif (isReplicaChild(node)) {\n\t\t\treturn isReplicaVariantChild(node)\n\t\t}\n\n\t\tif (isGestureVariant(node)) return false\n\n\t\treturn true\n\t}\n\n\texport function canRename(tree: CanvasTree, nodes: CanvasNode[]) {\n\t\treturn nodes.filter(node => canRenameNode(tree, node)).length === 1\n\t}\n\n\texport function canRenameActivePage(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tif (engine.stores.chromeStore.contentPanelTab !== ActiveContentPanelTab.Pages) return false\n\t\tif (engine.stores.scopeStore.active.id === engine.tree.root.homePageNodeId) return false\n\t\tif (nodes.length !== 0) return false\n\n\t\treturn isWebPageNode(engine.stores.scopeStore.active) || isCanvasPageNode(engine.stores.scopeStore.active)\n\t}\n\n\texport function rename(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tif (canRenameActivePage(engine, nodes)) {\n\t\t\tconst activePageId = engine.stores.scopeStore.active.id\n\t\t\tconst renamePageId = getRouteSegmentNodeByWebPageId(engine.tree, activePageId)?.id || activePageId\n\t\t\teditPageTitle(renamePageId)\n\t\t} else if (nodes.length === 1) {\n\t\t\tengine.stores.chromeStore.layersExpanded = true\n\t\t\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Layers\n\t\t\tengine.scheduler.runBeforeNextFrame(() => {\n\t\t\t\tconst selectedLayers = document.querySelectorAll(\".layerPanelPlaceholder.active\")\n\t\t\t\tif (selectedLayers.length === 1 && selectedLayers[0]) {\n\t\t\t\t\tconst event = new MouseEvent(\"dblclick\", {\n\t\t\t\t\t\tview: window,\n\t\t\t\t\t\tbubbles: true,\n\t\t\t\t\t\tcancelable: true,\n\t\t\t\t\t})\n\t\t\t\t\tconst doubleClickToEdit = selectedLayers[0].parentElement\n\t\t\t\t\tif (doubleClickToEdit) {\n\t\t\t\t\t\tdoubleClickToEdit.dispatchEvent(event)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\texport async function renameLayers(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tif (nodes.length === 0) return\n\n\t\tif (showModalIfAiDisabled(engine, \"context_menu\")) return\n\n\t\tawait toastProgress(\n\t\t\t{\n\t\t\t\tkey: \"generate-layer-names\",\n\t\t\t\tprogress: {\n\t\t\t\t\tvariant: \"progress\",\n\t\t\t\t\tprimaryText: \"Renaming layers.\",\n\t\t\t\t\tsecondaryText: \"Just a moment\u2026\",\n\t\t\t\t\tshowCloseButton: \"always\",\n\t\t\t\t},\n\t\t\t\terror: {\n\t\t\t\t\tvariant: \"error\",\n\t\t\t\t\tprimaryText: \"Rename failed.\",\n\t\t\t\t\tsecondaryText: \"Couldn\u2019t rename layers.\",\n\t\t\t\t},\n\t\t\t\tsuccess: {\n\t\t\t\t\tvariant: \"success\",\n\t\t\t\t\tprimaryText: \"Rename complete.\",\n\t\t\t\t\tsecondaryText: \"Layers updated.\",\n\t\t\t\t},\n\t\t\t\twaitTime: 1000,\n\t\t\t},\n\t\t\t() => renameLayersInternal(engine, nodes),\n\t\t)\n\t}\n\n\texport function sendToFront(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tconst tree = engine.tree\n\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\t\tconst grouped = groupByParent(withoutDescendants)\n\t\tif (sendForwardEnabled(tree, nodes, grouped)) {\n\t\t\tsendNodesTo(engine, grouped, \"front\")\n\t\t}\n\t}\n\n\texport function sendToBack(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tconst tree = engine.tree\n\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\t\tconst grouped = groupByParent(withoutDescendants)\n\t\tif (sendBackwardEnabled(tree, nodes, grouped)) {\n\t\t\tsendNodesTo(engine, grouped, \"back\")\n\t\t}\n\t}\n\n\texport function sendForward(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tconst tree = engine.tree\n\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\t\tconst grouped = groupByParent(withoutDescendants)\n\t\tif (sendForwardEnabled(tree, nodes, grouped)) {\n\t\t\tsendNodes(engine, grouped, 1)\n\t\t}\n\t}\n\n\texport function sendBackward(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tconst tree = engine.tree\n\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\t\tconst grouped = groupByParent(withoutDescendants)\n\t\tif (sendBackwardEnabled(tree, nodes, grouped)) {\n\t\t\tsendNodes(engine, grouped, -1)\n\t\t}\n\t}\n\n\texport function sendBackwardEnabled(tree: CanvasTree, nodes: CanvasNode[], grouped?: ParentNodeGroup) {\n\t\tif (anyUnmovableNode(nodes)) {\n\t\t\treturn false\n\t\t}\n\t\tif (!grouped) {\n\t\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\t\t\tgrouped = groupByParent(withoutDescendants)\n\t\t}\n\t\treturn canSendNode(tree, grouped, -1)\n\t}\n\n\texport function sendForwardEnabled(tree: CanvasTree, nodes: CanvasNode[], grouped?: ParentNodeGroup) {\n\t\tif (anyUnmovableNode(nodes)) {\n\t\t\treturn false\n\t\t}\n\t\tif (!grouped) {\n\t\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\t\t\tgrouped = groupByParent(withoutDescendants)\n\t\t}\n\t\treturn canSendNode(tree, grouped, 1)\n\t}\n\n\tinterface WrappingOptions {\n\t\tbypassToolGuard?: boolean\n\t\tpreserveSelection?: boolean\n\t}\n\n\texport function addFrame(engine: VekterEngine, nodes: CanvasNode[], options?: WrappingOptions) {\n\t\treturn wrapSelectionWith(engine, nodes, Wrappers.Frame, options)\n\t}\n\n\texport function addStack(engine: VekterEngine, nodes: CanvasNode[], options?: WrappingOptions) {\n\t\treturn wrapSelectionWith(engine, nodes, Wrappers.Stack, options)\n\t}\n\n\texport function canWrapInAutoSizedFrame(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tconst scopeNode = engine.stores.scopeStore.active\n\t\tconst withoutDescendants = engine.tree.withoutDescendants(nodes)\n\n\t\treturn (\n\t\t\twithoutDescendants.length > 1 &&\n\t\t\twrappingEnabled(engine, withoutDescendants) &&\n\t\t\t(!isWebPageNode(scopeNode) || withoutDescendants.every(n => engine.tree.isGroundNode(n)))\n\t\t)\n\t}\n\n\texport function wrapInAutoSizedFrame(engine: VekterEngine, nodes: CanvasNode[], reason?: EventSource) {\n\t\tconst newFrameId = addFrame(engine, nodes)\n\t\tassert(newFrameId !== undefined, \"new frame ID must be defined\")\n\n\t\tconst newFrame = engine.tree.getNode(newFrameId)\n\t\tassert(newFrame !== null, \"new frame must exist\")\n\n\t\tconst withoutDescendants = engine.tree.withoutDescendants([newFrame])\n\t\tenableAutoSizeForNodes(engine, withoutDescendants, reason)\n\t\treturn newFrame\n\t}\n\n\tfunction hasSameSelectionSinceLastDuplication(engine: VekterEngine, nodeIds: NodeID[]): boolean {\n\t\tconst { documentSettingsStore, selectionStore } = engine.stores\n\t\tif (!documentSettingsStore.lastDuplicationMap) return false\n\n\t\tif (!isSelectionEqual(nodeIds, selectionStore.ids)) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst latestDuplicates = [...documentSettingsStore.lastDuplicationMap.values()]\n\t\tif (!isSelectionEqual(selectionStore.ids, latestDuplicates)) {\n\t\t\treturn false\n\t\t}\n\t\tconst lastDuplicationOriginal = [...documentSettingsStore.lastDuplicationMap.keys()]\n\t\treturn isSelectionEqual(selectionStore.previousIds, lastDuplicationOriginal)\n\t}\n\n\tfunction areNodesInAStack(tree: CanvasTree, nodes: CanvasNode[]): boolean {\n\t\tconst commonGroundNode = tree.getCommonGroundNode(nodes)\n\t\treturn !!commonGroundNode && isStackComponent(commonGroundNode)\n\t}\n\n\texport function getUntransformedBoundingRect(\n\t\ttree: CanvasTree,\n\t\tnodes: CanvasNode[],\n\t\tparentNode: CanvasNode | null,\n\t): Rect {\n\t\tif (parentNode !== null) {\n\t\t\t// When we have a parent, our nodes may be distorted by transforms.\n\t\t\t// To ensure we create a bounding rect around the untransformed\n\t\t\t// shapes we need to first get all of the transformed points.\n\t\t\tconst transformedPoints = nodes.flatMap(node => convertCornerPointsToCanvas(tree, node))\n\n\t\t\t// Then we must construct the matrix that we need to project these\n\t\t\t// points through.\n\t\t\tconst matrix = tree.transformMatrixToNode(parentNode)\n\t\t\tconst invertParentMatrix = (\n\t\t\t\tcreates3dContext(parentNode) ? matrix : Matrix.flatProjectionMatrix(matrix)\n\t\t\t).invertSelf()\n\n\t\t\t// Convert all of these points through the matrix to find their untransformed position.\n\t\t\tconst untransformedCorners = transformedPoints.map(corner => {\n\t\t\t\treturn Matrix.convertPoint(invertParentMatrix, corner)\n\t\t\t})\n\n\t\t\t// Finally create a bounding rect around these untransformed points.\n\t\t\t// This will result in a new frame with a bounding box that\n\t\t\t// perfectly matches the selection. Round to the outside for shapes.\n\t\t\treturn Rect.roundToOutside(Rect.boundingRectFromPoints(untransformedCorners))\n\t\t}\n\n\t\t// Nodes without a parent can't have transforms (ground nodes don't\n\t\t// support transforms), so we can just create a merged frame by\n\t\t// converting each frame to the canvas, and merging them. Round to the\n\t\t// outside for shapes.\n\t\treturn Rect.roundToOutside(Rect.merge(...nodes.map(node => convertFrameToCanvas(tree, node))))\n\t}\n\n\tfunction getPropertiesForWrappingNode(\n\t\tengine: VekterEngine,\n\t\ttree: CanvasTree,\n\t\twrappingFrame: Rect,\n\t\tparentNode: CanvasNode | null,\n\t\twrappedNodes: CanvasNode[],\n\t\tallowAutoSize: boolean,\n\t) {\n\t\tconst properties: Partial<\n\t\t\tPick<\n\t\t\t\tWithPins & WithOptionalFill & WithOverflow,\n\t\t\t\t\"top\" | \"left\" | \"width\" | \"height\" | \"fillEnabled\" | \"overflow\"\n\t\t\t> &\n\t\t\t\tReturnType<typeof getLayoutPropsForWrappingNode>\n\t\t> = {\n\t\t\ttop: wrappingFrame.y,\n\t\t\tleft: wrappingFrame.x,\n\t\t\twidth: wrappingFrame.width,\n\t\t\theight: wrappingFrame.height,\n\t\t\tfillEnabled: false,\n\t\t}\n\n\t\tconst singleWrappedNode = wrappedNodes.length === 1 ? wrappedNodes[0] : null\n\t\tassert(singleWrappedNode !== undefined, \"node must be defined\", wrappedNodes)\n\n\t\tif (parentNode) {\n\t\t\tObject.assign(\n\t\t\t\tproperties,\n\t\t\t\tgetLayoutPropsForWrappingNode(tree, wrappingFrame, parentNode, singleWrappedNode, allowAutoSize),\n\t\t\t)\n\t\t}\n\n\t\tconst isGroundFrame = parentNode === null\n\t\tconst isWebPage = isWebPageNode(engine.stores.scopeStore.active)\n\t\tproperties.overflow = isGroundFrame || isWebPage ? \"clip\" : \"visible\"\n\t\treturn properties\n\t}\n\n\tfunction getLayoutPropsForWrappingNode(\n\t\ttree: CanvasTree,\n\t\twrappingFrame: Rect,\n\t\tparentNode: CanvasNode,\n\t\tsingleWrappedNode: CanvasNode | null,\n\t\tallowAutoSize: boolean,\n\t) {\n\t\tconst viewportSize = getViewportRect(tree, parentNode)\n\t\tconst parentSize = tree.getRect(parentNode)\n\n\t\tconst parentSizeInfo = singleWrappedNode\n\t\t\t? tree.getParentSizeInfo(singleWrappedNode, parentNode)\n\t\t\t: { sizing: parentSize, positioning: parentSize, viewport: viewportSize, layout: getLayoutType(parentNode) }\n\t\t// If there's only one wrapped node, try to reuse its constraints\n\t\t// for the wrapping node. Otherwise, guess the constraints.\n\t\tconst isSingleWrappedNodePinnable = !!singleWrappedNode && isPinnable(singleWrappedNode)\n\n\t\tconst currentConstraints = getNewConstraintsForWrappingFrame(singleWrappedNode, allowAutoSize)\n\t\tconst constraintProps = updateConstrainedFrame({\n\t\t\trect: wrappingFrame,\n\t\t\tparentSizeInfo,\n\t\t\tcurrentConstraints,\n\t\t\tconstraintsLocked: isSingleWrappedNodePinnable,\n\t\t\tshouldGuessPinToBottom: shouldGuessPinToBottom(tree, null, parentNode),\n\t\t\tshouldGuessPinToRight: shouldGuessPinToRight(tree, null, parentNode),\n\t\t\tfloatingPosition: null,\n\t\t})\n\n\t\tif (allowAutoSize && parentNode) {\n\t\t\t// Try to create a responsive stack with 1fr width and auto height.\n\t\t\treturn {\n\t\t\t\t...positionTypeUpdateForNewParent(singleWrappedNode, parentNode),\n\t\t\t\t...getNewSizeForWrappingFrame(singleWrappedNode),\n\t\t\t\t...constraintProps,\n\t\t\t\twidthType: hasAnyLayout(parentNode) ? DimensionType.FractionOfFreeSpace : DimensionType.Percentage,\n\t\t\t\theightType: DimensionType.Auto,\n\t\t\t\twidth: 1,\n\t\t\t\tleft: 0,\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\t...positionTypeUpdateForNewParent(singleWrappedNode, parentNode),\n\t\t\t...getNewSizeForWrappingFrame(singleWrappedNode),\n\t\t\t...constraintProps,\n\t\t}\n\t}\n\n\tfunction getNewConstraintsForWrappingFrame(\n\t\tsingleWrappedNode: CanvasNode | null,\n\t\tallowAutoSize: boolean,\n\t): ConstraintMask | undefined {\n\t\t// If there's only one wrapped node, try to reuse its constraints\n\t\t// for the wrapping node. Otherwise, guess the constraints.\n\t\tconst isSingleWrappedNodePinnable = !!singleWrappedNode && isPinnable(singleWrappedNode)\n\t\tconst currentConstraints = isSingleWrappedNodePinnable ? singleWrappedNode.constraints() : undefined\n\n\t\tif (!currentConstraints) return\n\n\t\tconst newConstraints = { ...currentConstraints }\n\t\tif (allowAutoSize) {\n\t\t\t// If the wrapped node has a fit image dimension, convert it to auto for the wrapper node\n\t\t\tif (newConstraints.widthType === DimensionType.FitImage) {\n\t\t\t\tnewConstraints.widthType = DimensionType.Auto\n\t\t\t}\n\t\t\tif (newConstraints.heightType === DimensionType.FitImage) {\n\t\t\t\tnewConstraints.heightType = DimensionType.Auto\n\t\t\t}\n\t\t} else {\n\t\t\t// If the wrapped node has an auto dimension, convert it to fixed for the wrapper node\n\t\t\tif (isAutoDimensionType(newConstraints.widthType)) {\n\t\t\t\tnewConstraints.widthType = DimensionType.FixedNumber\n\t\t\t}\n\t\t\tif (isAutoDimensionType(newConstraints.heightType)) {\n\t\t\t\tnewConstraints.heightType = DimensionType.FixedNumber\n\t\t\t}\n\t\t}\n\n\t\treturn newConstraints\n\t}\n\n\tfunction getNewSizeForWrappingFrame(singleWrappedNode: CanvasNode | null): WithSize | undefined {\n\t\tif (!singleWrappedNode || !withSize(singleWrappedNode)) return\n\n\t\t// If there's only one wrapped node, use its sizing property instead of the calculated\n\t\t// wrapping frame. This prevent us from producing huge fr value when wrapping a filled stack\n\t\t// child, for example.\n\t\treturn { width: singleWrappedNode.width, height: singleWrappedNode.height }\n\t}\n\n\tfunction createWrappingNode(\n\t\tengine: VekterEngine,\n\t\twrapperType: Wrappers,\n\t\tnewId: NodeID,\n\t\tfirstWrappedNodeId: NodeID,\n\t\tframe: Rect,\n\t\tparentNode: (CanvasNode & WithChildren) | null,\n\t\tinsertIndex: number,\n\t\tchildren: CanvasNode[],\n\t\tproperties: ReturnType<typeof getPropertiesForWrappingNode>,\n\t): CanvasNode {\n\t\tconst parentId = parentNode?.id ?? NullID\n\n\t\tswitch (wrapperType) {\n\t\t\tcase Wrappers.Frame: {\n\t\t\t\tconst createdNode = engine.createFrame(parentId, { id: newId, ...properties }, firstWrappedNodeId)\n\t\t\t\tengine.moveNode(createdNode.id, parentId, insertIndex)\n\n\t\t\t\tassert(\n\t\t\t\t\tcreatedNode && withChildren(createdNode),\n\t\t\t\t\t\"Fail to create a wrapping frame: the created frame should have the `children` field\",\n\t\t\t\t)\n\n\t\t\t\t// Move original nodes into the created frame and update their rects\n\t\t\t\tchildren.forEach(node => {\n\t\t\t\t\tconst update = convertNodeToNewParentUpdate(engine.tree, node, parentNode, createdNode)\n\t\t\t\t\tengine.moveNode(node.id, createdNode.id)\n\t\t\t\t\tengine.tree.current(node)?.set(update)\n\t\t\t\t})\n\n\t\t\t\treturn createdNode\n\t\t\t}\n\t\t\tcase Wrappers.Stack: {\n\t\t\t\tconst createdNode = createWrappingStack(engine, newId, parentId, properties, children, frame)\n\t\t\t\tengine.moveNode(createdNode.id, parentId, insertIndex)\n\n\t\t\t\t// Children rects are updated in createWrappingStack already.\n\t\t\t\treturn createdNode\n\t\t\t}\n\t\t\tcase Wrappers.ViewBox: {\n\t\t\t\tconst createdNode = engine.createShapeContainer(parentId, { id: newId, ...properties })\n\t\t\t\tengine.moveNode(createdNode.id, parentId, insertIndex)\n\n\t\t\t\tassert(\n\t\t\t\t\tcreatedNode && withChildren(createdNode),\n\t\t\t\t\t\"Fail to create a wrapping frame: the created frame should have the `children` field\",\n\t\t\t\t)\n\n\t\t\t\t// Move original nodes into the created frame and update their rects\n\t\t\t\tchildren.forEach(node => {\n\t\t\t\t\tconst update = convertNodeToNewParentUpdate(engine.tree, node, parentNode, createdNode)\n\t\t\t\t\tengine.moveNode(node.id, createdNode.id)\n\t\t\t\t\tengine.tree.current(node)?.set(update)\n\t\t\t\t})\n\n\t\t\t\treturn createdNode\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tassertNever(wrapperType)\n\t\t}\n\t}\n\n\tfunction createWrappingStack(\n\t\tengine: VekterEngine,\n\t\tid: NodeID,\n\t\tparent: MaybeNodeID,\n\t\tattributes: Partial<FrameNode>,\n\t\titems: CanvasNode[],\n\t\trect: Rect,\n\t\tsourceNodeId?: NodeID,\n\t) {\n\t\tconst preferredStackLayout = inferStackLayout(engine, items, rect)\n\t\tconst createdNode = engine.createNode(\n\t\t\tFrameNode,\n\t\t\t{ id, ...attributes, ...preferredStackLayout },\n\t\t\tparent,\n\t\t\tsourceNodeId,\n\t\t)\n\t\tassert(hasStackLayout(createdNode), \"Fail to create stack: the created node should have stack layout\")\n\t\tconst { stackDirection } = preferredStackLayout\n\t\treparentStackChildren(engine, id, rect, items, stackDirection)\n\n\t\treturn createdNode\n\t}\n\n\tfunction wrapSelectionWith(engine: VekterEngine, nodes: CanvasNode[], wrapper: Wrappers, options?: WrappingOptions) {\n\t\tconst tree = engine.tree\n\t\tif (!wrappingEnabled(engine, nodes, options)) return\n\n\t\tconst withoutDescendants = tree.sortVisually(tree.withoutDescendants(nodes))\n\t\tconst parentNode = withoutDescendants[0] ? tree.getParent(withoutDescendants[0].id) : null\n\n\t\tconst isWrappingInVariants = parentNode && isReplicaVariantOrReplicaVariantChild(parentNode)\n\n\t\tconst originalParentNode: (CanvasNode & WithChildren) | null = isWrappingInVariants\n\t\t\t? (engine.tree.getNode((parentNode as CanvasNode & IsReplicaOrReplicaChild).originalid) as CanvasNode &\n\t\t\t\t\tWithChildren)\n\t\t\t: parentNode\n\n\t\tlet areAllOriginalsHidden: boolean = true\n\t\tconst originalWithoutDescendants = isWrappingInVariants\n\t\t\t? withoutDescendants.map(node => {\n\t\t\t\t\tif (!isReplicaChild(node)) return node\n\t\t\t\t\tconst originalNode = engine.tree.getNode(node.originalid)\n\t\t\t\t\tassert(originalNode, \"Fail to create a wrapping frame: the original node must exist\")\n\t\t\t\t\tif (areAllOriginalsHidden) {\n\t\t\t\t\t\tareAllOriginalsHidden = !originalNode.cache.visible\n\t\t\t\t\t}\n\t\t\t\t\treturn originalNode\n\t\t\t\t})\n\t\t\t: withoutDescendants\n\t\tconst repeatedItemSnapshots = snapshotRepeatedItemsForNodes(tree, originalWithoutDescendants)\n\n\t\tconst insertIndex = parentNode?.children.findIndex(child => withoutDescendants.includes(child)) ?? -1\n\n\t\tconst newId = randomID()\n\n\t\tconst originalWrappingRect = getUntransformedBoundingRect(tree, originalWithoutDescendants, originalParentNode)\n\t\tconst originalProperties = getPropertiesForWrappingNode(\n\t\t\tengine,\n\t\t\ttree,\n\t\t\toriginalWrappingRect,\n\t\t\toriginalParentNode,\n\t\t\toriginalWithoutDescendants,\n\t\t\twrapper === Wrappers.Stack,\n\t\t)\n\n\t\tconst originalWrappingNode: CanvasNode = createWrappingNode(\n\t\t\tengine,\n\t\t\twrapper,\n\t\t\tnewId,\n\t\t\toriginalWithoutDescendants[0]?.id as string,\n\t\t\toriginalWrappingRect,\n\t\t\toriginalParentNode,\n\t\t\tinsertIndex,\n\t\t\toriginalWithoutDescendants,\n\t\t\toriginalProperties,\n\t\t)\n\t\trestoreRepeatedItemsFromSnapshots(tree, repeatedItemSnapshots)\n\n\t\tlet idToSelect = newId\n\t\tif (isWrappingInVariants) {\n\t\t\t// isWrappingInVariants already makes sure parentNode is not null,\n\t\t\t// the assert here is just for the type.\n\t\t\tassert(parentNode, \"Fail to create a wrapping frame: parentNode should not be null\")\n\t\t\tassert(\n\t\t\t\tisReplicaOrReplicaChild(parentNode),\n\t\t\t\t\"Fail to create a wrapping frame: parentNode should be a replica node\",\n\t\t\t)\n\n\t\t\t// If all the original nodes are hidden, the original wrapping frame\n\t\t\t// should be hidden as well\n\t\t\tif (areAllOriginalsHidden) {\n\t\t\t\tupdateInsertedVariantNode(engine, originalWrappingNode, parentNode, originalParentNode)\n\t\t\t}\n\n\t\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(engine.tree, parentNode)\n\t\t\tassert(replica, \"Fail to create a wrapping frame: replica must exist\")\n\n\t\t\tconst replicaWrappingRect = getUntransformedBoundingRect(tree, withoutDescendants, parentNode)\n\t\t\tconst properties = getPropertiesForWrappingNode(\n\t\t\t\tengine,\n\t\t\t\ttree,\n\t\t\t\treplicaWrappingRect,\n\t\t\t\tparentNode,\n\t\t\t\twithoutDescendants,\n\t\t\t\twrapper === Wrappers.Stack,\n\t\t\t)\n\n\t\t\t// Override replica wrapping node's layout: since the tree cache is\n\t\t\t// not updated at this point, originalWrappingNode.cache.visible is\n\t\t\t// still false, using engine.updateNode will push the changes into\n\t\t\t// the original node. So we update the replica overrides directly.\n\t\t\tupdateReplicaNodeOverrides(tree, replica, originalWrappingNode.id, properties)\n\t\t\t// Rebuild the replica so subsequent children update will take the\n\t\t\t// overrides into account\n\t\t\tTemplateHelper.replicaWithChanges(engine.tree, replica.draftOrCurrent())\n\n\t\t\tconst replicaWrappingNodeId = generateReplicaChildId(replica.id, newId)\n\t\t\tidToSelect = replicaWrappingNodeId\n\n\t\t\tconst replicaWrappingNode = engine.tree.get(replicaWrappingNodeId)\n\t\t\tassert(\n\t\t\t\treplicaWrappingNode && withChildren(replicaWrappingNode),\n\t\t\t\t\"Fail to create a wrapping frame: replica wrapping node should exist and should have the `children` field\",\n\t\t\t)\n\n\t\t\t// Override the replica wrapping node's children according to its\n\t\t\t// layout\n\t\t\tif (wrapper === Wrappers.Frame || wrapper === Wrappers.ViewBox) {\n\t\t\t\twithoutDescendants.forEach(node => {\n\t\t\t\t\tconst update = convertNodeToNewParentUpdate(tree, node, parentNode, replicaWrappingNode)\n\t\t\t\t\tengine.tree.current(node)?.set(update)\n\t\t\t\t})\n\t\t\t} else if (wrapper === Wrappers.Stack) {\n\t\t\t\tassert(\n\t\t\t\t\tisFrameNode(originalWrappingNode),\n\t\t\t\t\t\"Fail to create a wrapping frame: the wrapping node should be a FrameNode\",\n\t\t\t\t)\n\t\t\t\tassert(\n\t\t\t\t\thasStackLayout(originalWrappingNode),\n\t\t\t\t\t\"Fail to create a wrapping frame: the wrapping node should have stack layout\",\n\t\t\t\t)\n\n\t\t\t\t// Update the preferred stack layout\n\t\t\t\tconst preferredStackLayout = inferStackLayout(engine, withoutDescendants, replicaWrappingRect)\n\t\t\t\tupdateReplicaNodeOverrides(tree, replica, originalWrappingNode.id, preferredStackLayout)\n\t\t\t\t// The children can have their sizing overridden, so we need to\n\t\t\t\t// update them again.\n\t\t\t\tupdateChildrenSizingWhenWrappedInStack(\n\t\t\t\t\tengine,\n\t\t\t\t\toriginalWrappingNode,\n\t\t\t\t\tpreferredStackLayout.stackDirection,\n\t\t\t\t\twithoutDescendants,\n\t\t\t\t\treplicaWrappingRect,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tif (!options?.preserveSelection) {\n\t\t\tengine.stores.selectionStore.set(idToSelect)\n\t\t}\n\n\t\treturn newId\n\t}\n\n\tfunction canNodeBeWrappedByFrame(node: CanvasNode) {\n\t\tif (isDeviceNode(node)) return false\n\t\tif (isVariant(node)) return false\n\t\tif (hasFloatingPosition(node)) return false\n\t\tif (isSlotNode(node)) return false\n\t\tif (isSlotPropertyNode(node)) return false\n\t\tif (isOverlayNode(node)) return false\n\t\tif (isReplicaChild(node)) {\n\t\t\treturn isReplicaVariantChild(node)\n\t\t}\n\n\t\treturn true\n\t}\n\n\texport function wrappingEnabled(engine: VekterEngine, nodes: CanvasNode[], options?: WrappingOptions) {\n\t\tif (nodes.length === 0) return false\n\t\tif (!options?.bypassToolGuard) {\n\t\t\tswitch (engine.tool.enum) {\n\t\t\t\tcase Tools.Highlight:\n\t\t\t\tcase Tools.DirectSelect:\n\t\t\t\tcase Tools.Move:\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\t// For most tools we don't want to accidently wrap the current selection\n\t\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tif (!nodes.every(node => canNodeBeWrappedByFrame(node))) return false\n\n\t\tconst tree = engine.tree\n\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\t\tconst [sameParents, isParentable] = withoutDescendants.reduce(\n\t\t\t([sameParentsResult, isParentableResult], node) => {\n\t\t\t\tconst parentable = isInlineVectorNode(tree, node) || (!isVectorNode(node) && !hasFloatingPosition(node))\n\t\t\t\tconst firstParent = withoutDescendants[0] ? tree.getParentId(withoutDescendants[0]) : undefined\n\t\t\t\tconst parent = tree.getParentId(node)\n\t\t\t\treturn [sameParentsResult && firstParent === parent, isParentableResult && parentable]\n\t\t\t},\n\t\t\t[true, true],\n\t\t)\n\n\t\treturn sameParents && isParentable\n\t}\n\n\texport function overflowEnabled(nodes: CanvasNode[]) {\n\t\treturn nodes.some(withOverflow)\n\t}\n\n\texport function createDesignPage(engine: VekterEngine): NodeID {\n\t\tengine.stores.chromeStore.removePanelOverrides()\n\t\tengine.stores.chromeStore.chromeIsVisible = true\n\t\tengine.stores.chromeStore.pagesExpanded = true\n\t\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Pages\n\t\tconst existingPageNames = new Set(\n\t\t\tengine.stores.scopeStore.getDesignPageNodes().map(pageNode => pageNode.resolveValue(\"name\") ?? \"\"),\n\t\t)\n\t\tconst page = engine.createNode(\n\t\t\tDesignPageNode,\n\t\t\t{\n\t\t\t\tname: uniqueName(Dictionary.Design, existingPageNames, {\n\t\t\t\t\tstartIndex: existingPageNames.size + 1,\n\t\t\t\t\tomitCountIfFirst: true,\n\t\t\t\t}),\n\t\t\t},\n\t\t\tengine.tree.root.id,\n\t\t)\n\t\tengine.stores.scopeStore.select(page.id, { keepHistory: false })\n\n\t\tengine.scheduler.runAtEndOfFrame(() => editPageTitle(page.id))\n\n\t\treturn page.id\n\t}\n\n\texport function createCanvasPage(engine: VekterEngine) {\n\t\tengine.stores.chromeStore.removePanelOverrides()\n\t\tengine.stores.chromeStore.chromeIsVisible = true\n\t\tengine.stores.chromeStore.pagesExpanded = true\n\t\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Pages\n\t\tconst existingPageNames = new Set(\n\t\t\tengine.stores.scopeStore.getCanvasPageNodes().map(pageNode => pageNode.resolveValue(\"name\") ?? \"\"),\n\t\t)\n\t\tconst page = engine.createNode(\n\t\t\tCanvasPageNode,\n\t\t\t{\n\t\t\t\tname: uniqueName(Dictionary.Canvas, existingPageNames, {\n\t\t\t\t\tstartIndex: existingPageNames.size + 1,\n\t\t\t\t\tomitCountIfFirst: false,\n\t\t\t\t}),\n\t\t\t},\n\t\t\tengine.tree.root.id,\n\t\t)\n\t\tconst preset = getFramePreset(\"iPhone_390_844\")\n\t\tconst frame = engine.createFrame(page.id, {\n\t\t\twidth: preset.screenWidth,\n\t\t\theight: preset.screenHeight,\n\t\t\tname: preset.title,\n\t\t\tframePreset: preset.id,\n\t\t\tisScreen: true,\n\t\t})\n\n\t\t// Immediately generate the home screen. This ensures that when the\n\t\t// prototype is generated in the debounce, the dependency is already\n\t\t// generated.\n\t\tengine.stores.codeGenerationStore.updateComponent(frame.id).catch(unhandledError)\n\t\tengine.stores.scopeStore.select(page.id, { keepHistory: false })\n\t\ttriggerCanvasPageAddEvent({ pageId: page.id })\n\t\tengine.scheduler.runAtEndOfFrame(() => editPageTitle(page.id))\n\t}\n\n\texport const toggleContentManagementScope = (engine: VekterEngine) => {\n\t\tconst { chromeStore, selectionStore, scopeStore, analyticsStore, siteSettingsStore, codeEditorStore } =\n\t\t\tengine.stores\n\t\tconst mainView = chromeStore.mainView\n\n\t\tif (mainView === ActiveMainView.ContentManagement) {\n\t\t\t// go back to non content management node\n\t\t\tscopeStore.selectPreviousActiveScope()\n\t\t\treturn\n\t\t}\n\n\t\tswitch (mainView) {\n\t\t\tcase ActiveMainView.Canvas:\n\t\t\t\tengine.cancelTool()\n\t\t\t\tbreak\n\t\t\tcase ActiveMainView.Localizations:\n\t\t\t\tchromeStore.setLocalizationsVisible(false)\n\t\t\t\tbreak\n\t\t\tcase ActiveMainView.Analytics:\n\t\t\t\tanalyticsStore.close()\n\t\t\t\tbreak\n\t\t\tcase ActiveMainView.SiteSettings:\n\t\t\t\tsiteSettingsStore.close()\n\t\t\t\tbreak\n\t\t\tcase ActiveMainView.CodeEditor:\n\t\t\t\tcodeEditorStore.closeEditor()\n\t\t\t\tbreak\n\t\t\tcase ActiveMainView.Preview:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tassertNever(mainView)\n\t\t}\n\n\t\t// FIXME If CMS Node will ever become shallow this code needs to be checked/updated\n\t\tconst existingContentManagementNode = getContentManagementNode(engine.tree)?.loaded\n\t\tif (existingContentManagementNode && existingContentManagementNode.children.length > 0) {\n\t\t\tconst activeScope = scopeStore.active\n\t\t\tconst selectedNode = selectionStore.nodes.at(0)\n\n\t\t\tscopeStore.select(existingContentManagementNode.id, { keepHistory: false })\n\n\t\t\tconst nearestCollectionId = getNearestCollectionId(engine, activeScope, selectedNode)\n\t\t\tif (nearestCollectionId) {\n\t\t\t\tselectionStore.set(nearestCollectionId)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tcreateContentManagementNodeIfNeeded(engine.tree)\n\t\t\tscopeStore.select(CONTENT_MANAGEMENT_ID, { keepHistory: false })\n\t\t}\n\t}\n\n\texport function openContentCollection(engine: VekterEngine, collectionNodeId: NodeID) {\n\t\tengine.stores.chromeStore.chromeIsVisible = true\n\t\tengine.stores.scopeStore.select(CONTENT_MANAGEMENT_ID, { keepHistory: false })\n\t\tengine.stores.selectionStore.set(collectionNodeId)\n\t}\n\n\texport function makeComponent(\n\t\tengine: VekterEngine,\n\t\tsource: ComponentDesignCreateSource,\n\t\tparentId?: NodeID,\n\t\tonSuccess?: (node: SmartComponentNode) => void,\n\t) {\n\t\tengine.stores.modalStore.set({\n\t\t\ttype: ModalType.CreateComponent,\n\t\t\tsource,\n\t\t\tonSuccess: (node: SmartComponentNode) => {\n\t\t\t\tconst name = node.resolveValue(\"name\")\n\t\t\t\t// If the name contains a path, we need to create a reference node\n\t\t\t\t// for the smart component and the folders extracted from the path\n\t\t\t\tif (isNull(name)) return\n\n\t\t\t\t// TODO: Remove once migration runs and new asset panel experiment is removed\n\t\t\t\tif (isNull(EntityRootNode.get(engine.tree))) return\n\n\t\t\t\tconst newParentId = createEntityFolderNodesFromPath(\n\t\t\t\t\tengine.tree,\n\t\t\t\t\tname,\n\t\t\t\t\tparentId ?? COMPONENTS_ENTITY_TYPE_ROOT_ID,\n\t\t\t\t)\n\n\t\t\t\tcreateReferenceForNodeIfNeeded(engine.tree, newParentId, node.id)\n\n\t\t\t\tonSuccess?.(node)\n\t\t\t},\n\t\t})\n\t}\n\n\texport function canMakeComponent(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\treturn canMakeSmartComponent(engine, nodes)\n\t}\n\n\t/** @deprecated Legacy design components, should only used by tests */\n\texport function makeMaster(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tif (nodes.length !== 1) return\n\t\tif (withReplicaVariants(engine.stores.scopeStore.active)) return\n\n\t\tconst node = nodes[0]\n\t\tif (!node) return\n\t\tif (!withTemplate(node)) return\n\t\tif (!TemplateHelper.canMakeMaster(node)) return\n\n\t\tengine.tree.current(node)?.set({\n\t\t\tisMaster: true,\n\t\t\treplicaInfo: null,\n\t\t\toriginalid: null,\n\t\t})\n\t}\n\n\texport function canResetToMasterValues(tree: CanvasTree, nodes: CanvasNode[]) {\n\t\tfor (const node of nodes) {\n\t\t\tif (!node.originalid) continue\n\t\t\tif (!isReplicaOrReplicaChild(node)) continue\n\t\t\tif (TemplateHelper.overrideKeys(tree, [node]).size > 0) return true\n\t\t}\n\t\treturn false\n\t}\n\n\texport function resetToMasterValues(tree: CanvasTree, nodes: CanvasNode[]) {\n\t\tfor (const node of nodes) {\n\t\t\tconst originalid = node.originalid\n\t\t\tif (!originalid) continue\n\n\t\t\tconst replica: any = TemplateHelper.getReplicaForTemplateNode(tree, node)\n\t\t\tif (!replica) continue\n\n\t\t\tTemplateHelper.resetOverrides(tree, replica, node)\n\t\t}\n\t}\n\n\texport function resetPropertiesToMasterValues(tree: CanvasTree, nodes: CanvasNode[], properties: readonly string[]) {\n\t\tfor (const node of nodes) {\n\t\t\tif (!isReplicaOrReplicaChild(node)) continue\n\n\t\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, node)\n\t\t\tif (!replica) continue\n\n\t\t\tTemplateHelper.resetOverridesByProperty(tree, replica, node, properties)\n\t\t}\n\t}\n\n\texport function canDetachFromMaster(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tif (nodes.length === 0) return false\n\t\tfor (const node of nodes) {\n\t\t\tif (isPrimaryVariant(node)) return false\n\t\t\tif (isTopLevelVariant(node)) {\n\t\t\t\tconst scopeNode = engine.tree.getScopeNodeFor(node)\n\t\t\t\tif (!scopeNode) return false\n\t\t\t\t// Should not be possible for a node to be a top level variant,\n\t\t\t\t// but for it's scope node to not be a smart component or web page.\n\t\t\t\tif (isSmartComponentNode(scopeNode)) {\n\t\t\t\t\tconst { hover, pressed } = scopeNode.getGesturesForTopLevelVariant(node)\n\t\t\t\t\tif (hover || pressed) return false\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\treturn isWebPageNode(scopeNode) && !isBreakpointVariant(node)\n\t\t\t}\n\t\t\tif (isReplica(node)) return true\n\t\t}\n\t\treturn false\n\t}\n\n\texport function detachFromMaster(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tconst renamedIds = new RenamedIds()\n\n\t\t// We don't want to leak the computed ids into the main document, so we\n\t\t// clone and replace the replicas.\n\t\tnodes.filter(isReplica).forEach(replica => {\n\t\t\tif (!canReplaceNode(replica, { allowVariants: true })) return\n\n\t\t\tconst clone = replica.clone({ parentid: null }) as CanvasNode & WithPins & WithConstraints\n\t\t\tclone.replicaInfo = null\n\t\t\tif (withVariant(clone)) clone.isVariant = undefined\n\t\t\tfor (const n of clone.walk()) {\n\t\t\t\tn.originalid = null\n\t\t\t}\n\t\t\tassert(replica.id !== clone.id)\n\n\t\t\t// similar to replaceNodeWithTemplate ...\n\t\t\tengine.tree.insertNode(clone)\n\t\t\tconst parentOfOriginal = engine.tree.getParent(replica.id) || engine.stores.scopeStore.active\n\t\t\tconst indexOfOriginal = parentOfOriginal.children.indexOf(replica)\n\n\t\t\tengine.tree.removeNode(replica)\n\t\t\tengine.moveNode(clone.id, parentOfOriginal.id, indexOfOriginal)\n\t\t\tengine.tree.current(clone)?.set(clone.constraintValues())\n\n\t\t\trenamedIds.set(replica.id, clone.id)\n\t\t})\n\n\t\t// Update any links in this document to the replica and update the selection\n\t\tupdateNodeConnections(engine.tree, engine.componentLoader, engine.tree.root, renamedIds, false)\n\t\tconst newSelection = engine.stores.selectionStore.ids.map(id => renamedIds.get(id) ?? id)\n\t\tengine.stores.selectionStore.set(newSelection)\n\t\treturn renamedIds\n\t}\n\n\texport function visibility(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tif (!visibilityEnabled(nodes)) {\n\t\t\treturn\n\t\t}\n\t\tconst currentValue = nodesAreVisible(nodes)\n\t\tconst filtered = nodes.filter(withVisibility)\n\t\tfiltered.forEach(node => node.set({ visible: !currentValue }))\n\t\tengine.stores.treeStore.setHighlight(NullID)\n\t}\n\n\texport function visibilityEnabled(nodes: CanvasNode[]) {\n\t\treturn nodes.some(withVisibility)\n\t}\n\n\tconst nodesAreVisible = (nodes: CanvasNode[]) => {\n\t\treturn nodes.every(node => node.isVisible())\n\t}\n\n\texport function visibilityTitle(nodes: CanvasNode[]) {\n\t\treturn nodesAreVisible(nodes) ? Dictionary.Hide : Dictionary.Show\n\t}\n\n\texport function toggleLock(tree: CanvasTree, nodes: CanvasNode[]) {\n\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\t\tif (!toggleLockEnabled(withoutDescendants)) return\n\n\t\tconst shouldLock = !nodesAreLocked(withoutDescendants)\n\t\tconst allDescendants = new Set<CanvasNode>()\n\n\t\tfor (const node of withoutDescendants) {\n\t\t\tif (!withLock(node)) continue\n\t\t\tconst lockedByParent = node.cache.lockedByParent\n\t\t\tconst locked = shouldLock === lockedByParent ? undefined : shouldLock\n\t\t\tnode.set({ locked })\n\t\t\tfor (const descendant of node.descendants()) {\n\t\t\t\tallDescendants.add(descendant)\n\t\t\t}\n\t\t}\n\n\t\t// Enable inheritance for all descendants\n\t\tfor (const descendant of allDescendants) {\n\t\t\tif (!withLock(descendant)) continue\n\t\t\tif (descendant.locked !== undefined) {\n\t\t\t\tdescendant.set({ locked: undefined })\n\t\t\t}\n\t\t}\n\t}\n\n\texport function toggleLockEnabled(withoutDescendants: CanvasNode[]) {\n\t\treturn withoutDescendants.some(withLock)\n\t}\n\n\tfunction nodesAreLocked(withoutDescendants: CanvasNode[]): boolean {\n\t\treturn withoutDescendants.some(node => withLock(node) && isLockedOrLockedByParent(node))\n\t}\n\n\texport function toggleLockTitle(withoutDescendants: CanvasNode[]) {\n\t\treturn nodesAreLocked(withoutDescendants) ? \"Unlock\" : \"Lock\"\n\t}\n\n\texport function copyURLEnabled(nodes: CanvasNode[]) {\n\t\treturn nodes.every(isVectorSetItem)\n\t}\n\n\texport function removeFrameTitle(withoutDescendants: CanvasNode[]) {\n\t\tconst onlyViewBoxes = withoutDescendants.length > 0 && withoutDescendants.every(node => isRemovableViewBox(node))\n\t\tif (onlyViewBoxes) {\n\t\t\treturn `Remove ${withoutDescendants.length > 1 ? Dictionary.ViewBoxes : Dictionary.ViewBox}`\n\t\t}\n\n\t\tconst onlyStackComponents =\n\t\t\twithoutDescendants.length > 0 && withoutDescendants.find(node => !isStackComponent(node)) === undefined\n\n\t\tconst type = onlyStackComponents ? Dictionary.Stack : Dictionary.Frame\n\t\treturn `Remove ${type}${withoutDescendants.length > 1 ? \"s\" : \"\"}`\n\t}\n\n\texport function removeFrame(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tif (!removeFrameEnabled(engine, nodes)) return\n\t\tungroup(engine, nodes)\n\t}\n\n\texport function removeFrameEnabled(engine: VekterEngine, nodes: CanvasNode[]): boolean {\n\t\tif (nodes.length === 0) return false\n\t\tconst activeScopeId = engine.stores.scopeStore.active.id\n\t\treturn nodes.every(node => {\n\t\t\tif (\n\t\t\t\t(!isFrameNode(node) && !isStackComponent(node) && !isRemovableViewBox(node)) ||\n\t\t\t\t!node.children ||\n\t\t\t\tnode.children.length === 0\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif (isMaster(node) || isReplica(node)) return false\n\t\t\tif (isReplicaChild(node)) {\n\t\t\t\tif (!isReplicaVariantChild(node)) return false\n\t\t\t}\n\n\t\t\tconst newParent = engine.tree.getParent(node.id)\n\t\t\tif (!newParent) return true\n\n\t\t\tfor (const child of node.children) {\n\t\t\t\tconst parentAcceptsChild = acceptsChild(engine.tree, newParent, child, activeScopeId, engine.componentLoader)\n\t\t\t\tif (!parentAcceptsChild) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\t}\n\n\tfunction isRemovableViewBox(node: CanvasNode) {\n\t\treturn isShapeContainerNode(node) && !isVectorSetItem(node)\n\t}\n\n\texport function convertNodeToNewParentUpdate<T extends CanvasNode>(\n\t\ttree: CanvasTree,\n\t\tnode: T,\n\t\tcurrentParent: (CanvasNode & WithChildren) | null,\n\t\tnewParent: (CanvasNode & WithChildren) | null,\n\t): Partial<T> {\n\t\tconst currentRect = tree.getRect(node)\n\n\t\tconst originPoint = getOriginPoint(node)\n\t\tlet newCenterPoint = tree.convertPointToCanvas(node, {\n\t\t\tx: currentRect.width * originPoint.x,\n\t\t\ty: currentRect.height * originPoint.y,\n\t\t})\n\n\t\tif (newParent) {\n\t\t\t// We don't know if the new parent is the node's current parent,\n\t\t\t// this means we can't use tree.convertPointToNode(node) since it\n\t\t\t// walks the current tree to create an aggregate matrix. We also\n\t\t\t// can't use `tree.convertPointToNode(newParent)` because the matrix\n\t\t\t// used there will always be 3d, even when the new parent doesn't\n\t\t\t// preserve 3d. Instead we must use the correct matrix provided by\n\t\t\t// the new parent to the child, optionally converting it to a flat\n\t\t\t// projection matrix if the paren't doesn't create a 3d context.\n\t\t\tconst newParentMatrix = tree.transformMatrixToNode(newParent)\n\t\t\tconst matrix = creates3dContext(newParent) ? newParentMatrix : Matrix.flatProjectionMatrix(newParentMatrix)\n\t\t\tnewCenterPoint = Matrix.convertPoint(matrix.inverse(), newCenterPoint)\n\t\t}\n\n\t\tconst newFrame = {\n\t\t\t...currentRect,\n\t\t\tx: newCenterPoint.x - currentRect.width * originPoint.x,\n\t\t\ty: newCenterPoint.y - currentRect.height * originPoint.y,\n\t\t}\n\n\t\tconst update: Partial<WithPins & Rect & WithRotation & WithPositionType> = node.updateForRect({\n\t\t\trect: newFrame,\n\t\t\tparentSizeInfo: tree.getParentSizeInfo(node, newParent),\n\t\t\tconstraintsLocked: false,\n\t\t\tshouldGuessPinToBottom: newParent ? shouldGuessPinToBottom(tree, node, newParent) : true,\n\t\t\tshouldGuessPinToRight: shouldGuessPinToRight(tree, node, newParent),\n\t\t})\n\n\t\tconst newParentSupportsFractions = isStackComponent(newParent)\n\n\t\tif (!newParentSupportsFractions) {\n\t\t\tif (update.widthType === DimensionType.FractionOfFreeSpace) {\n\t\t\t\tupdate.widthType = DimensionType.FixedNumber\n\t\t\t\tupdate.width = currentRect.width\n\t\t\t}\n\t\t\tif (update.heightType === DimensionType.FractionOfFreeSpace) {\n\t\t\t\tupdate.heightType = DimensionType.FixedNumber\n\t\t\t\tupdate.height = currentRect.height\n\t\t\t}\n\t\t}\n\n\t\tif (withRotation(node)) {\n\t\t\tconst newRotation = node.resolveValue(\"rotation\") - rotationDelta(tree, currentParent, newParent)\n\t\t\tif (newRotation !== 0) {\n\t\t\t\tupdate.rotation = newRotation\n\t\t\t}\n\t\t}\n\n\t\tif (newParent && hasAnyLayout(newParent) && !isPositionFixed(node) && !isPositionAbsolute(node)) {\n\t\t\tupdate.top = null\n\t\t\tupdate.left = null\n\t\t\tupdate.bottom = null\n\t\t\tupdate.right = null\n\t\t}\n\n\t\tObject.assign(update, positionTypeUpdateForNewParent(node, newParent))\n\n\t\treturn update as Partial<T>\n\t}\n\n\texport function convertNodeToNewParent(\n\t\tvekterEngine: VekterEngine,\n\t\tnode: CanvasNode,\n\t\tcurrentParent: (CanvasNode & WithChildren) | null,\n\t\tnewParent: (CanvasNode & WithChildren) | null,\n\t\tinsertionIndex = -1,\n\t\tcloneSource?: CanvasNode,\n\t): {\n\t\toriginalNode: CanvasNode | null\n\t\toriginalCurrentParent: CanvasNode | null\n\t\toriginalNewParent: CanvasNode | null\n\t} | null {\n\t\tconst { tree } = vekterEngine\n\n\t\tlet originalNode: CanvasNode | null = node\n\t\tif (isReplicaChild(node)) {\n\t\t\toriginalNode = getOriginalVariantNodeIfExists(tree, node)\n\t\t\tif (!originalNode) return null\n\t\t}\n\n\t\tlet originalNewParent: (CanvasNode & WithChildren) | null = newParent\n\t\tif (newParent && isReplicaOrReplicaChild(newParent)) {\n\t\t\toriginalNewParent = getOriginalVariantNodeIfExists(tree, newParent) as (CanvasNode & WithChildren) | null\n\t\t\tif (!originalNewParent) return null\n\t\t}\n\n\t\tlet originalCurrentParent: (CanvasNode & WithChildren) | null = currentParent\n\t\tif (currentParent && isReplicaOrReplicaChild(currentParent)) {\n\t\t\toriginalCurrentParent = getOriginalVariantNodeIfExists(tree, currentParent) as (CanvasNode & WithChildren) | null\n\t\t\tif (!originalCurrentParent) return null\n\t\t}\n\n\t\t// When cloning a node, the clone doesn't have an originalid, so it's\n\t\t// taken as the original node. But the new/current parent could be\n\t\t// replica nodes and we should use the them to calculate the update,\n\t\t// otherwise the clone would be placed at a wrong position.\n\t\tconst originalUpdate = convertNodeToNewParentUpdate(\n\t\t\ttree,\n\t\t\tcloneSource ?? originalNode,\n\t\t\tisReplicaChild(node) ? originalCurrentParent : currentParent,\n\t\t\tisReplicaChild(node) ? originalNewParent : newParent,\n\t\t)\n\t\tvekterEngine.tree.current(originalNode)?.set(originalUpdate)\n\n\t\tvekterEngine.moveNode(\n\t\t\toriginalNode.id,\n\t\t\toriginalNewParent ? originalNewParent.id : vekterEngine.stores.scopeStore.active.id,\n\t\t\tinsertionIndex,\n\t\t)\n\n\t\tconst isEditingVariant = originalNode.id !== node.id\n\t\tif (isEditingVariant) {\n\t\t\t// The node/currentParent/newParent could have their position\n\t\t\t// overridden in the replica variant. In order to make sure the node\n\t\t\t// stays at the same position after being re-parented to a different\n\t\t\t// node in the same variant, we need to update the replica node\n\t\t\t// using the update calculated with the replica node & parents,\n\t\t\t// rather than the original nodes.\n\t\t\t// @TODO: If we want all the related nodes in other variants stay at\n\t\t\t// their current position after the move, we should also update them\n\t\t\t// Considering this is an edge case, we only update the moving node\n\t\t\t// for now.\n\t\t\tassert(currentParent, \"Current parent must exist when editing variants\")\n\t\t\tconst currentVariant = TemplateHelper.getReplicaForTemplateNode(tree, currentParent)\n\t\t\tassert(currentVariant, \"The current parent should located in a variant node\")\n\t\t\tconst newVariant = newParent ? TemplateHelper.getReplicaForTemplateNode(tree, newParent) : null\n\t\t\tif (currentVariant.id === newVariant?.id) {\n\t\t\t\tconst update = convertNodeToNewParentUpdate(tree, node, currentParent, newParent)\n\t\t\t\ttree.current(node)?.set(update)\n\t\t\t}\n\t\t}\n\n\t\treturn { originalNode, originalCurrentParent, originalNewParent }\n\t}\n\n\t// Selection\n\n\tfunction allSelectableNodes(node: CanvasNode, ids: NodeID[]) {\n\t\tif (isHiddenMaster(node)) return\n\t\tif (isLockedOrLockedByParent(node)) return\n\t\tids.push(node.id)\n\n\t\tif (!node.children) return\n\t\tfor (const child of node.children) {\n\t\t\tallSelectableNodes(child, ids)\n\t\t}\n\t}\n\n\tfunction getParentNodeIds(tree: CanvasTree, withoutDescendants: CanvasNode[]): Set<NodeID> {\n\t\tconst parents: Set<NodeID> = new Set()\n\t\twithoutDescendants.forEach(node => {\n\t\t\tconst parent = tree.getParent(node.id)\n\t\t\tif (parent) parents.add(parent.id)\n\t\t})\n\t\treturn parents\n\t}\n\n\texport function canSelectAncestor(tree: CanvasTree, selection: NodeID[]) {\n\t\tconst withoutDescendants = tree.withoutDescendants(tree.getNodes(selection))\n\t\tconst parents = getParentNodeIds(tree, withoutDescendants)\n\t\treturn parents.size > 0\n\t}\n\n\texport function selectParent(engine: VekterEngine, selection: NodeID[]) {\n\t\tselectAncestor(engine, selection, \"parent\")\n\t}\n\n\texport function selectGroundNode(engine: VekterEngine, selection: NodeID[]) {\n\t\tselectAncestor(engine, selection, \"groundNode\")\n\t}\n\n\texport function selectAncestor(engine: VekterEngine, selection: NodeID[], type: \"parent\" | \"groundNode\"): boolean {\n\t\tconst { tree } = engine\n\t\tconst withoutDescendants = tree.withoutDescendants(tree.getNodes(selection))\n\t\tlet newSelection: NodeID[] | null = null\n\t\tif (type === \"groundNode\") {\n\t\t\tconst topLevelLayers = new Set(withoutDescendants.map(node => tree.getGroundNodeFor(node).id))\n\t\t\tif (topLevelLayers.size > 0) newSelection = Array.from(topLevelLayers)\n\t\t} else {\n\t\t\tconst parentIds = getParentNodeIds(tree, withoutDescendants)\n\t\t\tif (parentIds.size > 0) {\n\t\t\t\tnewSelection = Array.from(parentIds)\n\t\t\t}\n\t\t}\n\n\t\tif (!newSelection) return false\n\n\t\tconst { selectionStore, overlayStore, treeStore } = engine.stores\n\n\t\tselectionStore.set(newSelection, { sticky: true, switchToLayers: true, switchToProperties: true })\n\n\t\t// If the currently selected node is an overlay, and we are\n\t\t// setting its parent as the current selection, exit the overlay\n\t\t// edit mode.\n\t\tconst singleSelectedNode = withoutDescendants.length === 1 ? withoutDescendants[0] : null\n\t\tif (singleSelectedNode && overlayStore.activeOverlays.has(singleSelectedNode.id)) {\n\t\t\t// we pass false to exitEditMode to prevent triggering another selection change\n\t\t\toverlayStore.exitEditMode(selectionStore, false)\n\t\t}\n\t\ttreeStore.setHighlight(null)\n\t\treturn true\n\t}\n\n\texport function selectAll(engine: VekterEngine, selection: NodeID[]) {\n\t\tconst tree = engine.tree\n\t\tlet nodesToSelect: NodeID[] = []\n\n\t\tif (engine.tool.selectAll) {\n\t\t\tengine.tool.selectAll()\n\t\t\treturn\n\t\t} else {\n\t\t\tconst groundAncestors = selection.map(id => {\n\t\t\t\tconst selectedNode = tree.get(id)\n\t\t\t\tif (isVectorNode(selectedNode)) {\n\t\t\t\t\tconst shapeContainerAncestor = getShapeContainerNodeFor(tree, selectedNode)\n\t\t\t\t\treturn shapeContainerAncestor && tree.isGroundNode(shapeContainerAncestor)\n\t\t\t\t\t\t? shapeContainerAncestor.id\n\t\t\t\t\t\t: NullID\n\t\t\t\t}\n\n\t\t\t\tconst frameNode = tree.getGroundFrameAncestor(id, true)\n\t\t\t\treturn frameNode !== null ? frameNode.id : NullID\n\t\t\t})\n\n\t\t\tif (new Set(groundAncestors).size === 1 && groundAncestors[0] !== null) {\n\t\t\t\tconst frameAncestor = groundAncestors[0]\n\t\t\t\tnodesToSelect = tree\n\t\t\t\t\t.getSubtreeNodes(frameAncestor)\n\t\t\t\t\t.filter(node => {\n\t\t\t\t\t\tif (isLockedOrLockedByParent(node)) {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn node.id !== frameAncestor\n\t\t\t\t\t})\n\t\t\t\t\t.map(node => node.id)\n\t\t\t}\n\n\t\t\tif (nodesToSelect.length === 0) {\n\t\t\t\tfor (const child of engine.stores.scopeStore.active.children) {\n\t\t\t\t\tallSelectableNodes(child, nodesToSelect)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tengine.stores.selectionStore.set(nodesToSelect)\n\t}\n\n\texport function selectAllSiblings(engine: VekterEngine, selection: NodeID[]) {\n\t\tconst nodesToSelect: Set<NodeID> = new Set()\n\n\t\tfor (const selectedId of selection) {\n\t\t\tconst selectedNode = engine.tree.get(selectedId)\n\t\t\tif (!selectedNode) continue\n\n\t\t\tconst siblingsIncludingSelf = engine.tree.getSiblingsIncludingSelf(selectedNode)\n\t\t\tfor (const sibling of siblingsIncludingSelf) {\n\t\t\t\tnodesToSelect.add(sibling.id)\n\t\t\t}\n\t\t}\n\n\t\tengine.stores.selectionStore.set(nodesToSelect)\n\t}\n\n\texport function canSelectChildren(engine: VekterEngine, selection: NodeID[]) {\n\t\treturn engine.tree.getNodes(selection).some(node => withChildren(node) && node.children.length > 0)\n\t}\n\n\texport function selectAllChildren(engine: VekterEngine, selection: NodeID[]) {\n\t\tconst nodesToSelect: Set<NodeID> = new Set()\n\n\t\tfor (const selectedId of selection) {\n\t\t\tconst node = engine.tree.get(selectedId)\n\t\t\tif (!node) continue\n\n\t\t\tconst children = getChildren(node)\n\t\t\tfor (const child of children) {\n\t\t\t\tnodesToSelect.add(child.id)\n\t\t\t}\n\t\t}\n\n\t\t// only set the selection if there are new child nodes to select\n\t\t// if there are no nodes to select, then the existing selection\n\t\t// is retained, and the 'Enter' key has no effect, allowing you to\n\t\t// drill down through the hierarchy without losing the last valid selection\n\t\t// when you reach a node with no children.\n\t\tif (nodesToSelect.size > 0) {\n\t\t\tengine.stores.selectionStore.set(nodesToSelect)\n\t\t}\n\t}\n\n\texport function selectAllTextNodes(engine: VekterEngine, selection: NodeID[]) {\n\t\tconst baseNodes =\n\t\t\tselection.length > 0 ? engine.tree.getNodes(selection) : engine.stores.scopeStore.active.getGroundNodes()\n\n\t\t// Check if node is a text node. If it is, select its siblings.\n\t\tconst nodes: CanvasNode[] = []\n\t\tbaseNodes.map(node => {\n\t\t\tif (isAnyTextNode(node)) {\n\t\t\t\tnodes.push(...engine.tree.getSiblingsIncludingSelf(node))\n\t\t\t} else {\n\t\t\t\tnodes.push(node)\n\t\t\t}\n\t\t})\n\n\t\t// Stores Node IDs to not go over the same nodes multiple times.\n\t\tconst checkedNodes: Set<NodeID> = new Set()\n\n\t\t// Recursively go over a node and its children, checking if it's a text node.\n\t\t// Todo: Add styling branching.\n\t\tconst textNodeIds: Set<NodeID> = new Set()\n\t\tconst _findTextNodes = (node: CanvasNode) => {\n\t\t\t// Skip if it has already been checked.\n\t\t\tif (checkedNodes.has(node.id)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Add to the array if it's a text node\n\t\t\tif (isAnyTextNode(node)) {\n\t\t\t\ttextNodeIds.add(node.id)\n\t\t\t}\n\n\t\t\t// Loop over the children.\n\t\t\tif (node.children) {\n\t\t\t\tfor (const childNode of node.children) {\n\t\t\t\t\t_findTextNodes(childNode)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Push node to the checked nodes.\n\t\t\tcheckedNodes.add(node.id)\n\t\t}\n\t\tfor (const node of nodes) {\n\t\t\t_findTextNodes(node)\n\t\t}\n\n\t\tengine.stores.selectionStore.set(textNodeIds)\n\t}\n\n\t/**\n\t * This method is used to select nodes with partially matching font styles.\n\t * Currently we will select all nodes that have exclusively matching font,\n\t * font weight, font size and text color.\n\t */\n\texport function selectAllTextNodesWithSameFontStyles(engine: VekterEngine, selection: NodeID[]) {\n\t\tconst [node] = engine.tree.getNodes(selection)\n\t\tif (!node || !isAnyTextNode(node)) return\n\n\t\tconst textNodes: AnyTextNode[] = []\n\t\tconst textStylePreset = isRichTextNode(node) ? commonValue(node.getTextStylePresets(false)) : undefined\n\t\tconst font = commonValue(node.getFonts(false))\n\n\t\tconst fontSize = commonValue(\n\t\t\tnode.getFontSizes(false).map(value => {\n\t\t\t\tif (isFontSize(value)) return createCSSDimension(...value)\n\t\t\t\tif (isNumber(value)) return createCSSDimension(value, \"px\")\n\t\t\t\treturn value\n\t\t\t}),\n\t\t)\n\n\t\tconst fontTextColor = commonValue(node.getTextColors(false))\n\n\t\tif (isNotFound(textStylePreset) || isMixed(textStylePreset)) return\n\t\tif (isNotFound(font) || isMixed(font)) return\n\t\tif (isNotFound(fontSize) || isMixed(fontSize)) return\n\t\tif (isNotFound(fontTextColor) || isMixed(fontTextColor)) return\n\n\t\tfor (const child of engine.stores.scopeStore.active.walk()) {\n\t\t\tif (isReplicaVariantOrReplicaVariantChild(child)) continue\n\n\t\t\tif (!isAnyTextNode(child)) continue\n\n\t\t\tconst childTextStylePreset = isRichTextNode(child) ? commonValue(child.getTextStylePresets(false)) : undefined\n\t\t\tif (childTextStylePreset !== textStylePreset) continue\n\n\t\t\tconst childFont = commonValue(child.getFonts(false))\n\t\t\tif (childFont !== font) continue\n\n\t\t\tconst childFontSize = commonValue(\n\t\t\t\tchild.getFontSizes(false).map(value => {\n\t\t\t\t\tif (isFontSize(value)) return createCSSDimension(...value)\n\t\t\t\t\tif (isNumber(value)) return createCSSDimension(value, \"px\")\n\t\t\t\t\treturn value\n\t\t\t\t}),\n\t\t\t)\n\n\t\t\tif (childFontSize !== fontSize) continue\n\n\t\t\tconst childTextColor = commonValue(child.getTextColors(false))\n\t\t\tif (childTextColor !== fontTextColor) continue\n\n\t\t\ttextNodes.push(child)\n\t\t}\n\n\t\tengine.stores.selectionStore.set(textNodes)\n\t}\n\n\texport function selectAllLayersWithSameFill(engine: VekterEngine, selection: NodeID[]) {\n\t\tconst selectedNodes = engine.tree.getNodes(selection)\n\t\tassert(selection.length === 1, \"Cannot have multiple layers selected\")\n\t\tconst [node] = selectedNodes\n\n\t\tif (!node || !isFrameNode(node)) return\n\n\t\tconst nodes: CanvasNode[] = []\n\n\t\tconst breakpoint = getBreakpointForNode(engine.tree, node.id)\n\t\tconst nodeForWalk = breakpoint ?? engine.stores.scopeStore.active\n\t\tfor (const child of nodeForWalk.walk()) {\n\t\t\tif (!isFrameNode(child)) continue\n\t\t\tif (isFillEqual(node, child, engine.tree)) {\n\t\t\t\tnodes.push(child)\n\t\t\t}\n\t\t}\n\t\tengine.stores.selectionStore.set(nodes)\n\t}\n\n\t// Helpers\n\tfunction isFillEqual(a: CanvasNode & WithFill, b: CanvasNode & WithFill, tree: CanvasTree) {\n\t\tif ((withOptionalFill(a) && !a.fillEnabled) || (withOptionalFill(b) && !b.fillEnabled)) return false\n\n\t\tconst { fillType } = a\n\t\tif (fillType !== b.fillType) return false\n\t\tif (fillType === undefined) return false\n\n\t\tswitch (fillType) {\n\t\t\tcase \"color\": {\n\t\t\t\tif (!isString(a.fillColor) || !isString(b.fillColor)) return false\n\t\t\t\treturn ConvertColor.equals(\n\t\t\t\t\tconvertCSSColorVariableToValue(a.fillColor, tree, undefined),\n\t\t\t\t\tconvertCSSColorVariableToValue(b.fillColor, tree, undefined),\n\t\t\t\t)\n\t\t\t}\n\t\t\tcase \"linear-gradient\":\n\t\t\t\treturn a.fillLinearGradient && b.fillLinearGradient ? a.fillLinearGradient.equals(b.fillLinearGradient) : false\n\n\t\t\tcase \"radial-gradient\":\n\t\t\t\treturn a.fillRadialGradient && b.fillRadialGradient ? a.fillRadialGradient.equals(b.fillRadialGradient) : false\n\t\t\tcase \"conic-gradient\":\n\t\t\t\treturn a.fillConicGradient && b.fillConicGradient ? a.fillConicGradient.equals(b.fillConicGradient) : false\n\t\t\tcase \"image\":\n\t\t\t\treturn a.fillImage === b.fillImage\n\t\t\tdefault:\n\t\t\t\tassertNever(fillType)\n\t\t}\n\t}\n\n\tfunction anyUnmovableNode(nodes: CanvasNode[]): boolean {\n\t\treturn nodes.some(node => {\n\t\t\tif (!isSortableNode(node)) return true\n\t\t\tif (!isReplicaChild(node)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn !isReplicaVariantChild(node)\n\t\t})\n\t}\n\n\tfunction groupByParent(nodes: CanvasNode[]) {\n\t\tconst grouped: ParentNodeGroup = {}\n\t\tnodes.forEach(node => {\n\t\t\tconst parentid = node.parentid ? node.parentid : InvalidID\n\t\t\tlet group = grouped[parentid]\n\t\t\tif (!group) {\n\t\t\t\tgroup = []\n\t\t\t\tgrouped[parentid] = group\n\t\t\t}\n\t\t\tgroup.push(node)\n\t\t})\n\t\treturn grouped\n\t}\n\n\tfunction sendNodesTo(engine: VekterEngine, grouped: ParentNodeGroup, to: \"front\" | \"back\") {\n\t\tconst tree = engine.tree\n\t\tfor (const parentid in grouped) {\n\t\t\tconst parent = parentid === InvalidID ? tree.root : tree.get(parentid)\n\t\t\tif (!parent || !grouped[parentid]) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Note: children are in render order which is bottom-up\n\t\t\tconst selectedChildren: CanvasNode[] = tree.sortVisually(grouped[parentid])\n\n\t\t\tif (to === \"back\") {\n\t\t\t\tselectedChildren.reverse()\n\t\t\t}\n\n\t\t\tconst position = to === \"front\" ? -1 : 0\n\t\t\tconst isReplicaVariantStackOrGridParent =\n\t\t\t\tisReplicaVariantOrReplicaVariantChild(parent) && isStackOrGridComponent(parent)\n\n\t\t\tselectedChildren.forEach(child => {\n\t\t\t\tconst originalChild = child.originalid ? tree.get(child.originalid) : child\n\t\t\t\tassert(originalChild, \"Cannot send\", child.id, \"backward/forward: original node must exist.\")\n\t\t\t\tif (isReplicaVariantStackOrGridParent && isSortableNode(originalChild)) {\n\t\t\t\t\tupdateIdIndexInItemsOrder(originalChild.id, parent, position)\n\t\t\t\t} else {\n\t\t\t\t\tengine.tree.moveNodeIndex(originalChild, position)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction getRelativePositionedRectForMoving(\n\t\tengine: VekterEngine,\n\t\ttype: \"backward\" | \"forward\",\n\t\tnode: CanvasNode,\n\t): Rect | null {\n\t\tconst parent = engine.tree.getParent(node.id)\n\t\tif (!parent) return null\n\t\tconst index = parent.children.indexOf(node)\n\t\tconst siblingIndex = type === \"backward\" ? index - 1 : index + 1\n\t\tif (siblingIndex < 0 || siblingIndex >= parent.children.length) return null\n\t\tconst siblingNode = parent.children.at(siblingIndex)\n\t\tif (!siblingNode || !isPositionRelative(siblingNode)) return null\n\n\t\tconst currentRect = convertFrameToCanvas(engine.tree, node)\n\t\tconst siblingRect = convertFrameToCanvas(engine.tree, siblingNode)\n\n\t\tif (type === \"backward\") {\n\t\t\treturn { ...currentRect, y: siblingRect.y }\n\t\t}\n\n\t\tconst heightDelta = siblingRect.height - currentRect.height\n\t\treturn { ...currentRect, y: siblingRect.y + heightDelta }\n\t}\n\n\tfunction zoomToMoveLocationIfNeeded(engine: VekterEngine, type: \"backward\" | \"forward\", node: CanvasNode) {\n\t\tconst nextCanvasRect = getRelativePositionedRectForMoving(engine, type, node)\n\t\tconst { canvasStore } = engine.stores\n\t\tif (\n\t\t\t!nextCanvasRect ||\n\t\t\tRect.containsRect(canvasStore.getCanvasVisibleRectTakingOverlaysIntoAccount(), nextCanvasRect)\n\t\t) {\n\t\t\treturn\n\t\t}\n\n\t\tcanvasStore.zoomToCenter(nextCanvasRect, {\n\t\t\tzoom: canvasStore.zoom,\n\t\t\tmaxZoom: 0.5,\n\t\t\tanimated: true,\n\t\t})\n\t}\n\n\tfunction sendNodes(engine: VekterEngine, grouped: ParentNodeGroup, direction: 1 | -1) {\n\t\tconst tree = engine.tree\n\t\tconst isSingleGroup = Object.keys(grouped).length === 1\n\n\t\tfor (const parentid in grouped) {\n\t\t\tconst parent = parentid === InvalidID ? tree.root : tree.get(parentid)\n\t\t\tif (!parent || !withChildren(parent)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst isReplicaVariantStackOrGridParent =\n\t\t\t\tisReplicaVariantOrReplicaVariantChild(parent) && isStackOrGridComponent(parent)\n\n\t\t\tconst selectedChildren = grouped[parentid]\n\n\t\t\tconst isSingleNodeSelected = isSingleGroup && selectedChildren?.length === 1\n\n\t\t\tconst children = hasItemsOrderOverride(parent) ? parent.getChildrenInVisualOrder() : parent.children\n\n\t\t\tlet free = false\n\t\t\tfor (let i = 0, il = children.length; i < il; i++) {\n\t\t\t\tconst currentIndex = direction === 1 ? il - i - 1 : i\n\t\t\t\tconst child = children.at(currentIndex) as CanvasNode\n\t\t\t\tconst selected = selectedChildren?.includes(child)\n\t\t\t\tif (!selected) {\n\t\t\t\t\tfree = true\n\t\t\t\t} else if (free) {\n\t\t\t\t\tif (isReplicaVariantStackOrGridParent && isSortableNode(child)) {\n\t\t\t\t\t\tassert(child.originalid, \"Cannot send nodes: nodes in a replica variant parent must have originalid.\")\n\t\t\t\t\t\tupdateIdIndexInItemsOrder(child.originalid, parent, currentIndex + direction)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (isSingleNodeSelected && isLayoutSection(tree, child)) {\n\t\t\t\t\t\t\tzoomToMoveLocationIfNeeded(engine, direction === -1 ? \"backward\" : \"forward\", child)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst originalChild = child.originalid ? tree.get(child.originalid) : child\n\t\t\t\t\t\tconst originalParent = parent.originalid ? tree.get(parent.originalid) : parent\n\t\t\t\t\t\tassert(originalChild, \"Cannot send node\", child.id, \": original child node does not exist.\")\n\t\t\t\t\t\tassert(originalParent, \"Cannot send node\", parent.id, \": original parent node does not exist.\")\n\t\t\t\t\t\tengine.moveNode(originalChild.id, originalParent.id, currentIndex + direction)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction canSendNode(tree: CanvasTree, grouped: ParentNodeGroup, direction: 1 | -1): boolean {\n\t\tfor (const parentid in grouped) {\n\t\t\tconst parent = parentid === InvalidID ? tree.root : tree.get(parentid)\n\t\t\tif (!parent || !withChildren(parent)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst selectedChildren = grouped[parentid]\n\n\t\t\tconst children = hasItemsOrderOverride(parent) ? parent.getChildrenInVisualOrder() : parent.children\n\t\t\tlet free = false\n\t\t\tfor (let i = 0, il = children.length; i < il; i++) {\n\t\t\t\tconst currentIndex = direction === 1 ? il - i - 1 : i\n\t\t\t\tconst child = children.at(currentIndex) as CanvasNode\n\t\t\t\tconst selected = selectedChildren?.includes(child)\n\t\t\t\tif (!selected) {\n\t\t\t\t\tfree = true\n\t\t\t\t} else if (free) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tfunction rotationDelta(\n\t\ttree: CanvasTree,\n\t\tcurrentParent: (CanvasNode & WithChildren) | null,\n\t\tnewParent: (CanvasNode & WithChildren) | null,\n\t) {\n\t\tlet startRotation = 0\n\t\tlet endRotation = 0\n\n\t\tif (currentParent) {\n\t\t\tstartRotation = tree.totalAncestorRotation(currentParent)\n\t\t}\n\t\tif (newParent) {\n\t\t\tendRotation = tree.totalAncestorRotation(newParent)\n\t\t}\n\n\t\treturn Math.round(endRotation - startRotation)\n\t}\n\n\t// Shapes\n\n\texport function reversePathDirectionEnabled(nodes: CanvasNode[]) {\n\t\tif (nodes.length !== 1) return false\n\t\tconst node = nodes[0]\n\t\treturn node && withPath(node) && !node.originalid\n\t}\n\n\texport function reversePathDirection(tree: CanvasTree, node: CanvasNode & WithPath) {\n\t\tconst latestNode = tree.current(node)\n\t\tif (!latestNode) return\n\t\tlatestNode.set({ pathSegments: Path.reverse(latestNode.pathSegments) })\n\t}\n\n\texport function canUngroup(tree: CanvasTree, nodeIDsOrNodes: NodeIDsOrNodes): boolean {\n\t\tconst nodes = getNodesForNodeIDsOrNodes(nodeIDsOrNodes, tree)\n\t\tif (nodes.length === 0) return false\n\t\t// We can ungroup if all given nodes are vector nodes that have children:\n\t\treturn nodes.every(node => isVectorNode(node) && !node.originalid && getChildren(node).length > 0)\n\t}\n\n\texport function ungroup(engine: VekterEngine, nodeIDsOrNodes: NodeIDsOrNodes): NodeID[] | undefined {\n\t\tif (nodeIDsOrNodes.length === 0) return\n\n\t\tconst tree = engine.tree\n\t\tconst nodes: CanvasNode[] = tree.sortVisually(getNodesForNodeIDsOrNodes(nodeIDsOrNodes, tree))\n\t\tconst withoutDescendants = tree.withoutDescendants(nodes)\n\n\t\tconst nodesToSelectWhenDone: NodeID[] = []\n\t\tconst repeatedItemSnapshots = new Map<NodeID, ReturnType<typeof snapshotRepeatedItemsForNodes>[number]>()\n\n\t\twithoutDescendants.forEach(node => {\n\t\t\tif (!withChildren(node)) return\n\n\t\t\tlet originalNode: (CanvasNode & WithChildren) | null = node\n\t\t\tlet replica: (CanvasNode & IsReplica) | null = null\n\t\t\tif (isReplicaChild(node)) {\n\t\t\t\toriginalNode = getOriginalVariantNodeIfExists(tree, node) as (CanvasNode & WithChildren) | null\n\t\t\t\tif (!originalNode) return\n\n\t\t\t\treplica = TemplateHelper.getReplicaForTemplateNode(tree, node)\n\t\t\t}\n\t\t\tfor (const snapshot of snapshotRepeatedItemsForNodes(tree, originalNode ? [originalNode] : [])) {\n\t\t\t\trepeatedItemSnapshots.set(snapshot.repeaterId, snapshot)\n\t\t\t}\n\n\t\t\tconst parentNode = tree.getParent(node.id)\n\t\t\tif (node.children.length > 0) {\n\t\t\t\t// This item is a group. Move it's children onto the group's parent:\n\t\t\t\tconst nodeIndex = tree.getIndex(node)\n\t\t\t\tlet lastSourceNodeId = originalNode?.id ?? node.id\n\t\t\t\t// We will be mutating node.children in the loop. Create a copy so that the\n\t\t\t\t// iteration is stable.\n\t\t\t\tconst children = [...getChildren(node)]\n\t\t\t\tchildren.forEach((child, index) => {\n\t\t\t\t\tlet originalChild: CanvasNode | null = child\n\t\t\t\t\tif (isReplicaChild(child)) {\n\t\t\t\t\t\toriginalChild = getOriginalVariantNodeIfExists(tree, child)\n\t\t\t\t\t\tif (!originalChild) return\n\t\t\t\t\t}\n\n\t\t\t\t\t// When removing a frame, ensure any overlays triggered by\n\t\t\t\t\t// the frame are also cleaned up.\n\t\t\t\t\tif (isFixedOrRelativeOverlay(originalChild)) {\n\t\t\t\t\t\ttree.removeNode(originalChild)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tconst newParent = parentNode\n\t\t\t\t\tlet originalNewParent: (CanvasNode & WithChildren) | null = newParent\n\t\t\t\t\tif (newParent && isReplicaOrReplicaChild(newParent)) {\n\t\t\t\t\t\toriginalNewParent = getOriginalVariantNodeIfExists(tree, newParent) as (CanvasNode & WithChildren) | null\n\t\t\t\t\t\tif (!originalNewParent) return\n\t\t\t\t\t}\n\n\t\t\t\t\tconst originalUpdate = ContextAction.convertNodeToNewParentUpdate(\n\t\t\t\t\t\ttree,\n\t\t\t\t\t\toriginalChild,\n\t\t\t\t\t\toriginalNode,\n\t\t\t\t\t\toriginalNewParent,\n\t\t\t\t\t)\n\t\t\t\t\tengine.moveNode(originalChild.id, originalNewParent?.id ?? null, nodeIndex + index, lastSourceNodeId)\n\t\t\t\t\tengine.tree.current(originalChild)?.set(originalUpdate)\n\t\t\t\t\tlastSourceNodeId = originalChild.id\n\n\t\t\t\t\tif (replica) {\n\t\t\t\t\t\tconst update = ContextAction.convertNodeToNewParentUpdate(tree, child, node, newParent)\n\t\t\t\t\t\tengine.tree.current(child)?.set(update)\n\t\t\t\t\t}\n\t\t\t\t\tnodesToSelectWhenDone.push(child.id)\n\t\t\t\t})\n\t\t\t\tengine.deleteNode(originalNode.id)\n\t\t\t}\n\t\t})\n\t\trestoreRepeatedItemsFromSnapshots(tree, repeatedItemSnapshots.values())\n\n\t\tengine.stores.selectionStore.set(nodesToSelectWhenDone)\n\t\treturn nodesToSelectWhenDone\n\t}\n\n\texport function canSetDefaultSize(engine: VekterEngine, node: CodeComponentNode) {\n\t\treturn !node.hasPreferredSize(engine.componentLoader)\n\t}\n\n\texport function setDefaultSize(engine: VekterEngine, node: CodeComponentNode) {\n\t\tif (node.hasPreferredSize(engine.componentLoader)) return\n\n\t\tconst preferredSize = node.getPreferredSize(engine.componentLoader)\n\n\t\tconst update: Partial<WithPins & WithAspectRatio> = {\n\t\t\taspectRatio: null,\n\t\t}\n\t\tif (preferredSize.width === \"auto\") {\n\t\t\tupdate.width = 1\n\t\t\tupdate.widthType = DimensionType.Auto\n\t\t} else if (isNumber(preferredSize.width)) {\n\t\t\tupdate.width = preferredSize.width\n\t\t\tupdate.widthType = DimensionType.FixedNumber\n\t\t}\n\t\tif (preferredSize.height === \"auto\") {\n\t\t\tupdate.height = 1\n\t\t\tupdate.heightType = DimensionType.Auto\n\t\t} else if (isNumber(preferredSize.height)) {\n\t\t\tupdate.height = preferredSize.height\n\t\t\tupdate.heightType = DimensionType.FixedNumber\n\t\t}\n\n\t\tif (isPinnable(node) && isNumber(node.top) && isNumber(node.bottom)) update.bottom = null\n\t\tif (isPinnable(node) && isNumber(node.left) && isNumber(node.right)) update.right = null\n\t\ttrackDimensionTypeChange(node, update, \"context_menu_default_size_item\")\n\t\tnode.set(update, engine.tree)\n\t}\n\n\texport function canJoinInGroup(engine: VekterEngine, nodeIDsOrNodes: NodeIDsOrNodes): boolean {\n\t\tif (!engine.stores.toolStore.isDefaultToolActive) return false\n\t\tconst nodes = getNodesForNodeIDsOrNodes(nodeIDsOrNodes, engine.tree)\n\t\tif (nodes.length === 0) return false\n\t\t// All nodes are vector nodes\n\t\treturn nodes.every(node => isVectorNode(node) && !node.originalid)\n\t}\n\n\texport function joinInGroup(engine: VekterEngine, nodeIDsOrNodes: NodeIDsOrNodes) {\n\t\tconst tree = engine.tree\n\t\tassert(nodeIDsOrNodes.length > 0, \"No nodes\")\n\t\tif (!canJoinInGroup(engine, nodeIDsOrNodes)) return\n\n\t\tconst nodes: CanvasNode[] = getNodesForNodeIDsOrNodes(nodeIDsOrNodes, tree)\n\t\tconst withoutDescendants = tree.sortVisually(tree.withoutDescendants(nodes))\n\n\t\tconst firstDescendant = withoutDescendants[0]\n\t\tconst parentNode = firstDescendant ? tree.getParent(firstDescendant.id) : undefined\n\t\tconst parentId = parentNode ? parentNode.id : NullID\n\t\tconst firstDescendantIndex = firstDescendant ? tree.getIndex(firstDescendant) : undefined\n\n\t\tconst newGroupId = randomID()\n\t\tengine.createShapeGroup(parentId, { id: newGroupId }, firstDescendantIndex)\n\n\t\twithoutDescendants.forEach(node => {\n\t\t\tconst update = ContextAction.convertNodeToNewParentUpdate(\n\t\t\t\ttree,\n\t\t\t\tnode,\n\t\t\t\ttree.getParent(node.id),\n\t\t\t\tparentNode as CanvasNode & WithChildren,\n\t\t\t)\n\n\t\t\tengine.moveNode(node.id, newGroupId)\n\t\t\tengine.tree.current(node)?.set(update)\n\t\t})\n\n\t\tengine.stores.selectionStore.set(newGroupId)\n\t}\n\n\texport function convertSVGToShape(engine: VekterEngine, node: SVGNode): MaybeNodeID {\n\t\tif (node.originalid) return null\n\n\t\tconst size: Size = { width: node.width, height: node.height }\n\t\tconst vectorFrame = importSVG(node.svg, CanvasTree.createEmpty, size, node)\n\n\t\tif (vectorFrame) {\n\t\t\tvectorFrame.name = node.name || node.originalFilename\n\t\t\tvectorFrame.parentid = node.parentid\n\t\t\tconst insertedNode = engine.cloneNode(vectorFrame)\n\n\t\t\t// When directly on the canvas, give the containing frame a white background:\n\t\t\tconst fillEnabled = node.parentid === null\n\t\t\tconst fillColor = fillEnabled ? \"rgb(255,255,255)\" : \"transparent\"\n\n\t\t\t// VECTOR @TODO: for vector item, lock the aspect ratio\n\t\t\t// Graphic container doens't have aspect ratio lock\n\t\t\tconst { aspectRatio: _, ...constraints } = node.constraintValues()\n\n\t\t\tengine.tree.current(insertedNode)?.set({\n\t\t\t\t...constraints,\n\t\t\t\twidth: vectorFrame.width,\n\t\t\t\theight: vectorFrame.height,\n\t\t\t\tfillEnabled,\n\t\t\t\tfillColor,\n\t\t\t})\n\n\t\t\t// Make sure the position in the list does not change\n\t\t\t// NOTE: This should work with TreeAction.replace, but doesn't\n\t\t\tconst parent = engine.tree.getParent(node.id)\n\t\t\tif (parent !== null && withChildren(parent)) {\n\t\t\t\tconst index = parent.children.indexOf(node)\n\t\t\t\tengine.moveNode(insertedNode.id, parent.id, index)\n\t\t\t}\n\n\t\t\tscaleVector(engine, insertedNode.id, size)\n\n\t\t\tengine.deleteNode(node.id)\n\n\t\t\treturn insertedNode.id\n\t\t}\n\n\t\treturn null\n\t}\n\n\texport function scaleVector(engine: VekterEngine, id: NodeID, targetDimension: Size): void {\n\t\tconst importedNode: ShapeContainerNode | null = engine.tree.get<ShapeContainerNode>(id)\n\t\tif (!isShapeContainerNode(importedNode)) return\n\n\t\t// Calculate a scale that would make the longest side fits into the target box again.\n\t\tconst dimension = importedNode.width >= importedNode.height ? \"width\" : \"height\"\n\t\tconst oppositeDimension = dimension === \"width\" ? \"height\" : \"width\"\n\t\tconst scale = targetDimension[dimension] / importedNode[dimension]\n\t\tif (scale === 1) return\n\n\t\tscaleNodes(\n\t\t\tengine,\n\t\t\t[importedNode],\n\t\t\tscale,\n\t\t\tgetScaleNodesInitialState(engine, [importedNode]),\n\t\t\tgetScaleOrigin(importedNode),\n\t\t)\n\n\t\tconst scaledNode = engine.tree.current(importedNode)\n\t\tassert(scaledNode, \"Node must exist after scaling\")\n\n\t\t// After scaling, check if we need to resize the other dimension to match the original size.\n\t\tconst delta = targetDimension[oppositeDimension] - scaledNode[oppositeDimension]\n\t\tif (delta === 0) return\n\n\t\tscaledNode.set({ [oppositeDimension]: targetDimension[oppositeDimension] })\n\n\t\tconst axis = oppositeDimension === \"width\" ? \"x\" : \"y\"\n\t\t// Upon updating the size, offset all the elements inside to center them on that dimension.\n\t\tfor (const child of scaledNode.children) {\n\t\t\tconst latest = engine.tree.current(child)\n\t\t\tif (!latest || !withPosition(latest)) continue\n\t\t\tlatest.set({\n\t\t\t\t[axis]: latest[axis] + delta / 2,\n\t\t\t})\n\t\t}\n\t\treturn\n\t}\n\n\tfunction getScaleOrigin(node: ShapeContainerNode) {\n\t\tconst constraints = node.constraints()\n\t\tlet x = 0,\n\t\t\ty = 0\n\t\tif (constraints.top === false && constraints.bottom === false) {\n\t\t\t// centered\n\t\t\ty = 0.5\n\t\t} else if (constraints.top === false) {\n\t\t\t// pinned to bottom\n\t\t\ty = 1\n\t\t}\n\n\t\tif (constraints.left === false && constraints.right === false) {\n\t\t\t// centered\n\t\t\tx = 0.5\n\t\t} else if (constraints.left === false) {\n\t\t\t// pinned to right\n\t\t\tx = 1\n\t\t}\n\t\treturn { x, y }\n\t}\n\n\texport function canUpdateMasterFromInstance(tree: CanvasTree, nodes: CanvasNode[]): boolean {\n\t\tif (nodes.length > 1) return false\n\n\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, nodes[0])\n\t\tif (!replica) return false\n\n\t\tconst master = TemplateHelper.getMaster(tree, replica)\n\t\tif (isHiddenMaster(master)) return false\n\n\t\tfor (let i = 0, il = nodes.length; i < il; i++) {\n\t\t\tconst node = nodes[i] as CanvasNode & WithTemplate\n\t\t\tif (TemplateHelper.overrideKeys(tree, [node]).size > 0) return true\n\t\t}\n\t\treturn false\n\t}\n\n\texport function updateMasterFromInstance({ tree }: VekterEngine, nodes: CanvasNode[]) {\n\t\tfunction updatedMasterProperties(properties: { [key: string]: any }, main: boolean): { [key: string]: any } {\n\t\t\tfor (const prop of [\n\t\t\t\t\"id\",\n\t\t\t\t\"update\",\n\t\t\t\t\"cache\",\n\t\t\t\t\"children\",\n\t\t\t\t\"mutable\",\n\t\t\t\t\"parentid\",\n\t\t\t\t\"originalid\",\n\t\t\t\t\"isMaster\",\n\t\t\t\t\"isVariant\",\n\t\t\t\t\"isBreakpoint\",\n\t\t\t\t\"replicaInfo\",\n\t\t\t\t\"duplicatedFrom\",\n\t\t\t\t\"gesture\",\n\t\t\t]) {\n\t\t\t\tdelete properties[prop]\n\t\t\t}\n\t\t\tif (main) {\n\t\t\t\tfor (const prop of TemplateHelper.positionKeysToIgnore) {\n\t\t\t\t\tdelete properties[prop]\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn properties\n\t\t}\n\n\t\tfunction preservedReplicaProperties(\n\t\t\tproperties: { [key: string]: any },\n\t\t\tmain: boolean,\n\t\t): { [key: string]: any } | undefined {\n\t\t\tlet propertyOverrides: { [key: string]: any } | undefined\n\t\t\tif (main) {\n\t\t\t\tfor (const prop of TemplateHelper.positionKeysToIgnore) {\n\t\t\t\t\tif (properties[prop] === undefined) continue\n\t\t\t\t\tpropertyOverrides = propertyOverrides || {}\n\t\t\t\t\tpropertyOverrides[prop] = properties[prop]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (properties.gesture) {\n\t\t\t\tif (!propertyOverrides) propertyOverrides = {}\n\t\t\t\tpropertyOverrides.gesture = properties.gesture\n\t\t\t}\n\t\t\treturn propertyOverrides\n\t\t}\n\n\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, nodes[0])\n\t\tif (!replica) return\n\n\t\tconst master = TemplateHelper.getMaster(tree, replica)\n\t\tif (isHiddenMaster(master)) return\n\n\t\tconst overrides = { ...replica.replicaInfo.overrides }\n\t\tconst replicaInfo = { ...replica.replicaInfo, overrides }\n\t\tfor (let i = 0, il = nodes.length; i < il; i++) {\n\t\t\tconst node = nodes[i]\n\t\t\tif (!node?.originalid) continue\n\n\t\t\tconst original = tree.get(node.originalid)\n\t\t\tconst props = updatedMasterProperties(node.raw(), isReplica(node))\n\t\t\toriginal?.set(props)\n\n\t\t\tconst preserved = preservedReplicaProperties(overrides[node.originalid] ?? {}, isReplica(node))\n\t\t\tif (preserved) {\n\t\t\t\toverrides[node.originalid] = preserved\n\t\t\t} else {\n\t\t\t\tdelete overrides[node.originalid]\n\t\t\t}\n\t\t}\n\n\t\treplica.asDraft().replicaInfo = replicaInfo\n\t}\n\n\t// returns 1 if can go to master, 2 if that master is internally hidden\n\texport function canGoToMaster(tree: CanvasTree, nodes: CanvasNode[]): 0 | 1 | 2 {\n\t\tconst master = getSharedMaster(tree, nodes)\n\t\tif (!master) return 0\n\t\tif (isExternalMaster(master)) return 0\n\t\tif (isInternalHiddenMaster(master)) return 2\n\t\treturn 1\n\t}\n\n\tconst getSharedMaster = (tree: CanvasTree, originalNodes: CanvasNode[]): (CanvasNode & IsMaster) | null => {\n\t\tlet masterId: NodeID | null = null\n\n\t\tfor (let i = 0, il = originalNodes.length; i < il; i++) {\n\t\t\tconst node = originalNodes[i] as CanvasNode & WithTemplate\n\n\t\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, node)\n\t\t\tif (!replica) continue\n\n\t\t\tif (!masterId) {\n\t\t\t\tmasterId = replica.originalid\n\t\t\t} else if (masterId !== replica.originalid) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\n\t\tif (!masterId) return null\n\t\tconst masterNode = tree.get(masterId)\n\t\tif (!masterNode) return null\n\t\tif (!isMaster(masterNode)) return null\n\t\treturn masterNode\n\t}\n\n\texport function goToMaster(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\t// For single node selection, get original node from the selection\n\t\tif (nodes.length === 1) {\n\t\t\tconst originalNode = engine.tree.getNode(nodes[0]?.originalid)\n\t\t\tif (!originalNode) return\n\n\t\t\tshowNodeOnCanvas(engine, originalNode)\n\t\t\treturn\n\t\t}\n\n\t\t// For multiple nodes, find shared master\n\t\tconst masterNode = getSharedMaster(engine.tree, nodes)\n\t\tif (!masterNode) return\n\n\t\tTemplateHelper.showMaster(engine.tree, masterNode)\n\t\tshowNodeOnCanvas(engine, masterNode)\n\t}\n\n\texport function showNodeOnCanvas(engine: VekterEngine, node: CanvasNode) {\n\t\tlet pageNode = engine.tree.getScopeNodeFor(node)\n\t\tconst activePage = engine.stores.scopeStore.active\n\n\t\tif (isMaster(node)) {\n\t\t\tTemplateHelper.showMaster(engine.tree, node)\n\t\t}\n\n\t\tif (pageNode === null) {\n\t\t\tengine.moveNode(node.id, activePage.id)\n\t\t\tpageNode = activePage\n\t\t}\n\n\t\tengine.stores.scopeStore.select(pageNode.id, { keepHistory: false })\n\t\tengine.stores.selectionStore.set(node)\n\n\t\tconst canvasFrame = convertFrameToCanvas(engine.tree, node)\n\t\tengine.stores.canvasStore.scrollToCenter(Rect.center(canvasFrame))\n\t}\n\n\texport function createCodeComponent(engine: VekterEngine, parentId?: NodeID) {\n\t\tengine.exitMode()\n\n\t\tengine.stores.modalStore.set({\n\t\t\ttype: ModalType.CodeFileCreation,\n\t\t\tsource: \"main_menu\",\n\t\t\tcreationType: CodeFileCreationType.Component,\n\t\t\tparentId,\n\t\t})\n\t}\n\n\texport function createCodeOverride(engine: VekterEngine) {\n\t\tengine.exitMode()\n\t\tengine.stores.modalStore.set({\n\t\t\ttype: ModalType.CodeFileCreation,\n\t\t\tsource: \"main_menu\",\n\t\t\tcreationType: CodeFileCreationType.Override,\n\t\t})\n\t}\n\n\texport function createVariant(\n\t\tcomponentLoader: AnyComponentLoader,\n\t\ttree: CanvasTree,\n\t\tselectionStore: SelectionStore | undefined,\n\t\tcanvasStore: CanvasStore | undefined,\n\t\tscopeNode: CanvasNode & WithReplicaVariants,\n\t\tbase: FrameNode & IsVariant,\n\t\tsuggestedRect: Rect,\n\t\t{\n\t\t\tid,\n\t\t\tgesture,\n\t\t\toverrides,\n\t\t\toverrideSize,\n\t\t\tvariantName,\n\t\t\tviewportHeight,\n\t\t\tselectAndCenter = true,\n\t\t}: {\n\t\t\tid?: NodeID\n\t\t\tgesture?: GestureType\n\t\t\toverrides?: ReplicaOverrides\n\t\t\toverrideSize?: boolean\n\t\t\tvariantName?: string\n\t\t\tviewportHeight?: number\n\t\t\tselectAndCenter?: boolean\n\t\t} = {},\n\t) {\n\t\tif (gesture) {\n\t\t\tassert(isTopLevelVariant(base), \"gesture variant should inherit from top level variant\")\n\t\t}\n\n\t\tconst primaryVariant = scopeNode.getPrimaryVariant()\n\n\t\tlet name: string | null = null\n\n\t\tif (!gesture) {\n\t\t\tconst existingVariantNames = new Set(scopeNode.getTopLevelVariants().map(n => n.resolveValue(\"name\") ?? \"\"))\n\n\t\t\tif (variantName) {\n\t\t\t\tname = uniqueName(variantName, existingVariantNames)\n\t\t\t} else {\n\t\t\t\tname = uniqueName(\n\t\t\t\t\tisBreakpointVariant(base) ? Dictionary.Breakpoint : Dictionary.Variant,\n\t\t\t\t\texistingVariantNames,\n\t\t\t\t\t{ startIndex: existingVariantNames.size + 1, omitCountIfFirst: false },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// New variants should be created out of the selected variant,\n\t\t// but gestures should not override its inheritsFrom\n\t\tif (!overrides) overrides = gesture ? undefined : base.replicaInfo?.overrides\n\n\t\tif (name && isBreakpointVariant(base)) {\n\t\t\t// We have to merge the overrides before we create the new variant, applying them after creation results missing data, either inside or outside the sandbox\n\t\t\tconst variantOverrides = overridesToMakeVariantsMatchNewBreakpoint(componentLoader, tree, name, base)\n\t\t\tif (variantOverrides) {\n\t\t\t\tif (overrides) {\n\t\t\t\t\t// We first put the variantOverrides because those will win from the second argument, reverse from Object.assign\n\t\t\t\t\toverrides = mergeOverrides(variantOverrides, overrides)\n\t\t\t\t} else {\n\t\t\t\t\toverrides = variantOverrides\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// When creating a breakpoint, go over the direct descendant stacks/grids and make them responsive if needed.\n\t\t\tconst responsiveOverrides = {}\n\t\t\tbase.children.forEach(child => {\n\t\t\t\tif (!isStackOrGridComponent(child)) return\n\t\t\t\tif (isPinnable(child) && child.widthType === DimensionType.Auto) return\n\n\t\t\t\tconst originalChild = child.originalid ? tree.getNode(child.originalid) : child\n\t\t\t\tif (!originalChild) return\n\n\t\t\t\tconst rect = tree.getRect(child)\n\t\t\t\tcollectResponsiveOverrides(tree, child, rect, base, suggestedRect.width, responsiveOverrides)\n\t\t\t})\n\t\t\tif (!overrides) overrides = {}\n\t\t\toverrides = mergeOverrides(overrides, responsiveOverrides)\n\t\t}\n\n\t\tconst newNode = TemplateHelper.create(tree, primaryVariant, {\n\t\t\towner: id,\n\t\t\toverrides,\n\t\t\tinheritsFrom: gesture ? base.id : undefined,\n\t\t\tduplicatedFrom: createDuplicatedFromIfAllowed(base),\n\t\t})\n\n\t\t// Move node to front so it becomes that last variant\n\t\ttree.insertNode(newNode, scopeNode.id, -1)\n\n\t\tif (!newNode) return\n\n\t\tconst update: Partial<FrameNode & IsReplica & IsVariant> = {\n\t\t\ttop: suggestedRect.y,\n\t\t\tleft: suggestedRect.x,\n\t\t\tgesture,\n\t\t\tisBreakpoint: withBreakpointVariants(scopeNode) ? true : undefined,\n\t\t\tname,\n\t\t}\n\n\t\tif (viewportHeight) update.viewportHeight = viewportHeight\n\n\t\tif (overrideSize) {\n\t\t\tupdate.width = suggestedRect.width\n\t\t\tupdate.widthType = DimensionType.FixedNumber\n\n\t\t\t// When creating a new breakpoint we want to keep the (auto) height intact\n\t\t\tif (!isBreakpointVariant(newNode)) {\n\t\t\t\tupdate.height = suggestedRect.height\n\t\t\t\tupdate.heightType = DimensionType.FixedNumber\n\t\t\t}\n\t\t}\n\n\t\tnewNode.set(update)\n\n\t\tif (isSmartComponentNode(scopeNode)) {\n\t\t\t// Temporarily alias a loading variant to a normal variant for\n\t\t\t// tracking. If we decide to ship this feature we can iterate on the\n\t\t\t// tracking types to allow for \"loading\".\n\t\t\tconst variantType = isStatusGestureVariant(gesture) ? \"variant\" : (gesture ?? \"variant\")\n\t\t\ttriggerComponentCanvasVariantCreateEvent({\n\t\t\t\tvariantId: newNode.id,\n\t\t\t\tvariantType,\n\t\t\t\tcomponentId: scopeNode.id,\n\t\t\t})\n\t\t} else if (isBreakpointVariant(newNode)) {\n\t\t\trecord(\"breakpoint_create\", { scopeId: scopeNode.id, breakpointId: newNode.id, width: newNode.width })\n\t\t}\n\n\t\tif (selectAndCenter) {\n\t\t\tselectionStore?.set(newNode.id)\n\t\t\tcanvasStore?.scrollToCenter(Rect.center(suggestedRect))\n\t\t}\n\t\treturn newNode\n\t}\n\n\tfunction filterActionTargetingNode(actions: EventAction[], nodeID: NodeID) {\n\t\treturn actions.filter(action => {\n\t\t\tif (isNavigationAction(action)) {\n\t\t\t\tconst target = getNavigationTarget(action)\n\t\t\t\treturn target !== nodeID\n\t\t\t}\n\t\t\tif (isSetVariantAction(action)) {\n\t\t\t\tconst target = getSetVariantTarget(action)\n\t\t\t\treturn target !== nodeID\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n\n\texport function removeActionsWithTarget(engine: VekterEngine, scope: ScopeNode, target: NodeID) {\n\t\tfor (const descendant of scope.walk()) {\n\t\t\tconst actionMap = getActionsForNode(engine.componentLoader, descendant)\n\t\t\tfor (const [eventKey, actions] of Object.entries(actionMap)) {\n\t\t\t\tconst newActions = filterActionTargetingNode(actions, target)\n\t\t\t\tif (newActions.length === actions.length) continue\n\t\t\t\tif (withFrameEvents(descendant)) {\n\t\t\t\t\tengine.tree.current(descendant)?.set({ [eventKey]: newActions })\n\t\t\t\t} else if (isCodeComponentNode(descendant)) {\n\t\t\t\t\tif (!isPrefixedControlPropKey(eventKey)) continue\n\t\t\t\t\tconst newControlProp: EventHandlerControlProp = {\n\t\t\t\t\t\ttype: ControlType.EventHandler,\n\t\t\t\t\t\tvalue: newActions,\n\t\t\t\t\t}\n\t\t\t\t\tconst update: PrefixedControlProps<EventHandlerControlProp> = { [eventKey]: newControlProp }\n\t\t\t\t\tengine.tree.current(descendant)?.set(update)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\texport function canDetachVariantInstance(engine: VekterEngine, instance: CodeComponentNode): boolean {\n\t\tconst parentOfInstance = engine.tree.getParent(instance.id) || engine.stores.scopeStore.active\n\n\t\t// We can't replace instances that are the child of a non-primary variant.\n\t\tif (isReplicaOrReplicaChild(parentOfInstance)) return false\n\n\t\t// Makes sure there is a smart component with this codeComponentIdentifier in the tree.\n\t\treturn (\n\t\t\tengine.stores.treeStore\n\t\t\t\t.query()\n\t\t\t\t.partial(true)\n\t\t\t\t.whereClass(SmartComponentNode)\n\t\t\t\t// Notice: `instanceIdentifier` is a getter, not a stored property.\n\t\t\t\t// TODO: But this can still be optimized by not materializing real nodes, as the\n\t\t\t\t// getter only uses node.id. can be optimized, because we only need the node id, not\n\t\t\t\t// a full node.\n\t\t\t\t.some(node => node.instanceIdentifier === instance.codeComponentIdentifier)\n\t\t)\n\t}\n\n\texport function detachSmartComponentOrWebPageInstance(\n\t\tengine: VekterEngine,\n\t\tinstance: CodeComponentNode,\n\t\tsmartComponentOrWebPage: SmartComponentNode | WebPageNode | null,\n\t\tvariantRenamedIds?: RenamedIds,\n\t): FrameNode | null {\n\t\tif (!smartComponentOrWebPage) return null\n\n\t\tconst rawEventActions = getRawEventActions(engine.componentLoader, instance)\n\t\t// Read the instance's current variant before repeated-item control props are remapped to the detached node scope.\n\t\tconst rawVariant = getCodeComponentControlPropValues(instance, engine.componentLoader).variant\n\n\t\t// Create a map of variant ids to nodes. This prevents needing to look\n\t\t// in the tree for them. The variants may not be in the tree if we are\n\t\t// auto detaching, since we never inserted the source SmartComponentNode\n\t\t// into the document.\n\t\tconst variants: Map<NodeID, CanvasNode> = new Map()\n\t\tsmartComponentOrWebPage.getTopLevelVariants().forEach(node => variants.set(node.id, node))\n\n\t\t// Get the variant and create the replacement node before handling\n\t\t// replica's incase we need the Map of `renamedIds`\n\t\tconst variant = (isString(rawVariant) && variants.get(rawVariant)) || smartComponentOrWebPage.getPrimaryVariant()\n\n\t\tassert(isFrameNode(variant), \"Variant must be a frame node\")\n\n\t\tconst parentOfOriginal =\n\t\t\tengine.tree.getParent(instance.id) || engine.tree.getScopeNodeFor(instance) || engine.stores.scopeStore.active\n\n\t\t// We can't replace instances that are the child of a non-primary variant.\n\t\tif (isReplicaOrReplicaChild(parentOfOriginal)) return null\n\n\t\tconst renamedIds = new RenamedIds()\n\t\t// Casting to FrameNode because else it doesn't allow use to unset `isVariant`\n\t\tconst replacement = cloneWithRenamedIdMap(variant, new Map(), new Map(), renamedIds) as FrameNode\n\t\t// The instance is not cloned, but renamed to the variant. We use this information later to update the node\n\t\t// connections.\n\t\trenamedIds.set(instance.id, replacement.id)\n\n\t\tconst scopeNode = engine.tree.getScopeNodeFor(parentOfOriginal)\n\t\tconst repeatVariableControlPropUpdate = getDetachedRepeatVariableControlPropUpdate(\n\t\t\tengine.tree,\n\t\t\tinstance,\n\t\t\treplacement.id,\n\t\t)\n\t\tconst props = {\n\t\t\t...getDetachedControlPropValues(instance, engine.componentLoader, repeatVariableControlPropUpdate),\n\t\t\t...rawEventActions,\n\t\t}\n\n\t\t// This handles detaching inside a `WebPageNode` or `SmartComponentNode`\n\t\t// which has variants/replica. We gather all relevant,\n\t\t// overrides/constrains/styles and flatten all variable references. Then\n\t\t// all of these values are flattened into a new set of overrides that\n\t\t// are applied to the each variant/replica.\n\t\tif (isWebPageNode(scopeNode) || isSmartComponentNode(scopeNode)) {\n\t\t\tconst replicaVariants = scopeNode.getTopLevelReplicaVariants()\n\t\t\tfor (const replicaVariant of replicaVariants) {\n\t\t\t\tconst mixId = generateReplicaChildId(replicaVariant.id, instance.id)\n\t\t\t\tconst instanceReplica = engine.tree.getNode(mixId)\n\n\t\t\t\tif (!instanceReplica) continue\n\t\t\t\tif (!isCodeComponentNode(instanceReplica)) continue\n\n\t\t\t\tlet variantId = instanceReplica.getResolvedControlPropValues(engine.componentLoader).variant\n\n\t\t\t\tif (!isString(variantId)) continue\n\n\t\t\t\t// In the case where we are auto-detaching, we may not have\n\t\t\t\t// updated the on-canvas instances to point to the new variants\n\t\t\t\t// in the unlinked tree. In that case we need to check the\n\t\t\t\t// renamed ids.\n\t\t\t\tif (variantRenamedIds) {\n\t\t\t\t\tconst renamedVariantId = variantRenamedIds.get(variantId)\n\t\t\t\t\tif (renamedVariantId) variantId = renamedVariantId\n\t\t\t\t}\n\n\t\t\t\tconst instanceSource = isString(variantId) ? variants.get(variantId) : undefined\n\t\t\t\tif (!instanceSource || !isFrameNode(instanceSource) || !isVariant(instanceSource)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Extract variable values and then use them to create an object\n\t\t\t\t// that maps original ids to a node update object. These can\n\t\t\t\t// then be merged with the overrides for the current replica to\n\t\t\t\t// flatten the variables.\n\t\t\t\tconst variableUpdates = remapOverrides(\n\t\t\t\t\treplicaOverridesForInstanceVariables(\n\t\t\t\t\t\tinstanceSource,\n\t\t\t\t\t\tengine.tree,\n\t\t\t\t\t\tengine.componentLoader,\n\t\t\t\t\t\tinstanceReplica,\n\t\t\t\t\t\tsmartComponentOrWebPage.id,\n\t\t\t\t\t\treplacement.id,\n\t\t\t\t\t),\n\t\t\t\t\trenamedIds,\n\t\t\t\t)\n\n\t\t\t\tconst additionalUpdates: ReplicaOverrides = {}\n\t\t\t\tconst renamedVariantId = renamedIds.get(variant.id) ?? variant.id\n\t\t\t\tif (isReplicaVariant(instanceSource)) {\n\t\t\t\t\tconst remappedOverrides = remapOverrides(instanceSource.replicaInfo.overrides, renamedIds, true)\n\t\t\t\t\tObject.assign(additionalUpdates, {\n\t\t\t\t\t\t...remappedOverrides,\n\t\t\t\t\t\t// Filter out these positional properties as we want to\n\t\t\t\t\t\t// use the overrides set on the instance.\n\t\t\t\t\t\t[renamedVariantId]: withoutPositionOrSizeOrNameProperties(remappedOverrides[renamedVariantId] ?? {}),\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tconst nextOverrides = mergeOverrides(variableUpdates, additionalUpdates)\n\n\t\t\t\t// Both the instance of the smart component, and the root frame\n\t\t\t\t// of the smart components source can have opacity and rotation.\n\t\t\t\t// If they both do, those values are visually multiplied before\n\t\t\t\t// we detach. To ensure that there is no change on detach, we\n\t\t\t\t// must manually merge/multiply values.\n\t\t\t\tif (isReplicaVariant(instanceSource)) {\n\t\t\t\t\tconst { opacity, rotation } = replicaVariant.replicaInfo.overrides?.[instance.id] || {}\n\t\t\t\t\tblendNestedOpacityAndRotation(nextOverrides[renamedVariantId] ?? {}, {\n\t\t\t\t\t\topacity,\n\t\t\t\t\t\trotation,\n\t\t\t\t\t})\n\t\t\t\t} else if (replicaVariant.replicaInfo.overrides?.[instance.id]) {\n\t\t\t\t\t// If the source is the primary variant, it doesn't have\n\t\t\t\t\t// opacity and rotation defined on its overides, that means\n\t\t\t\t\t// we only need to blend the values if the instance has\n\t\t\t\t\t// overrides. We can blend the values onto the instance\n\t\t\t\t\t// overrides because we will merge them below.\n\t\t\t\t\tconst { opacity, rotation } = instanceSource\n\t\t\t\t\tblendNestedOpacityAndRotation(replicaVariant.replicaInfo.overrides[instance.id] ?? {}, {\n\t\t\t\t\t\topacity,\n\t\t\t\t\t\trotation,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// In the case where the instance is auto sized, fallback to the\n\t\t\t\t// source size (which may also be auto sized).\n\t\t\t\tconst sizeUpdate: Partial<WithPins> = {}\n\t\t\t\tif (instanceReplica.heightType === DimensionType.Auto) {\n\t\t\t\t\tsizeUpdate.heightType = instanceSource.heightType\n\t\t\t\t\tsizeUpdate.height = instanceSource.height\n\t\t\t\t}\n\t\t\t\tif (instanceReplica.widthType === DimensionType.Auto) {\n\t\t\t\t\tsizeUpdate.widthType = instanceSource.widthType\n\t\t\t\t\tsizeUpdate.width = instanceSource.width\n\t\t\t\t}\n\n\t\t\t\tengine.tree.current(replicaVariant)?.set({\n\t\t\t\t\treplicaInfo: {\n\t\t\t\t\t\t...replicaVariant.replicaInfo,\n\t\t\t\t\t\toverrides: mergeOverrides(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t...replicaVariant.replicaInfo.overrides,\n\t\t\t\t\t\t\t\t// Remove overrides for the old instance that will\n\t\t\t\t\t\t\t\t// no longer exist after detach.\n\t\t\t\t\t\t\t\t[instance.id]: {},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t...nextOverrides,\n\t\t\t\t\t\t\t\t[renamedVariantId]: {\n\t\t\t\t\t\t\t\t\t// Merge the overrides for the old instance\n\t\t\t\t\t\t\t\t\t// with the new root frame of the detached\n\t\t\t\t\t\t\t\t\t// variant to preserve the layout of the\n\t\t\t\t\t\t\t\t\t// instance. The nextOverrides don't include\n\t\t\t\t\t\t\t\t\t// layout properties so this is safe.\n\t\t\t\t\t\t\t\t\t...replicaVariant.replicaInfo.overrides[instance.id],\n\t\t\t\t\t\t\t\t\t...nextOverrides[renamedVariantId],\n\t\t\t\t\t\t\t\t\t...sizeUpdate,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tconst compatibleProperties = getCompatibleNodeProperties(\n\t\t\tengine.tree,\n\t\t\tengine.componentLoader,\n\t\t\tinstance,\n\t\t\treplacement,\n\t\t\tparentOfOriginal,\n\t\t)\n\n\t\t// The root of the smart component source can have opacity and rotation.\n\t\t// This is implicitly combined with the opacity and rotation of any\n\t\t// instance of said smart component. So when we detach the instance of\n\t\t// the smart component we need to blend the inner and outer property\n\t\t// values if they exist.\n\t\tblendNestedOpacityAndRotation(compatibleProperties, {\n\t\t\topacity: isVariableReference(variant.opacity) ? props[variant.opacity.id] : variant.opacity,\n\t\t\trotation: isVariableReference(variant.rotation) ? props[variant.rotation.id] : variant.rotation,\n\t\t})\n\n\t\t// Clone the variant from the local SmartComponentNode. Ensure the\n\t\t// clone is not a primary, replica, or gesture variant. Finally ensure\n\t\t// it's rendered at the same size as the instance we are replacing. If\n\t\t// the instance is auto-sized and the variant is not, make sure we use\n\t\t// the constraints of the variant, otherwise the instance will shrink\n\t\t// when it's detached.\n\t\tconst constraints = instance.constraintValues()\n\t\tconst variantConstraints = variant.constraintValues()\n\t\tif (constraints.widthType === DimensionType.Auto && variantConstraints.widthType !== DimensionType.Auto) {\n\t\t\tconstraints.widthType = variantConstraints.widthType\n\t\t}\n\t\tif (constraints.heightType === DimensionType.Auto && variantConstraints.heightType !== DimensionType.Auto) {\n\t\t\tconstraints.heightType = variantConstraints.heightType\n\t\t}\n\n\t\treplacement.set({\n\t\t\t...constraints,\n\t\t\t...compatibleProperties,\n\t\t\t// getCompatibleNodeProperties only shares floating position values\n\t\t\t// if both the source and target nodes *have* floating position.\n\t\t\t// This ensures that copy/paste styles doesn't incorrectly add\n\t\t\t// floating positioning to a layer that doesn't have a trigger.\n\t\t\t...(parentOfOriginal ? getFloatingPositionProps(instance) : undefined),\n\t\t\tisVariant: false,\n\t\t\tisMaster: false,\n\t\t\tgesture: undefined,\n\t\t\treplicaInfo: null,\n\t\t\toriginalid: null,\n\t\t\tname: instance.name ?? getDefaultName(engine.componentLoader, instance),\n\t\t})\n\n\t\tif (instance.repeatArray) {\n\t\t\treplacement.set({ repeatArray: instance.repeatArray })\n\t\t}\n\n\t\t// Walk the node we have cloned out of the SmartComponentNode, and\n\t\t// ensure that none of the layers have originalid, strip invalid\n\t\t// actions, and finally, reset any variable values to the default\n\t\t// variable value.\n\t\t//\n\t\t// @FIXME - Consider optimizing, we do 3 individual iterations through\n\t\t// all actions that could be collapsed into one.\n\n\t\t// We're detaching away from the source scope, so any variables it provides should no longer be accessible.\n\t\tconst detachedVariableToValue = getVariableToDefaultValueMap(smartComponentOrWebPage)\n\t\tconst variableValues = new EagerVariableProviderMap([...(detachedVariableToValue ?? []), ...Object.entries(props)])\n\t\tconst variableValuesByProvider: CombinedVariableProviderValueMap = new Map()\n\t\tvariableValuesByProvider.set(smartComponentOrWebPage.id, variableValues)\n\t\tconst detachedVariableReferenceUpdate = getDetachedInstanceVariableReferenceUpdate(\n\t\t\tsmartComponentOrWebPage.id,\n\t\t\trepeatVariableControlPropUpdate,\n\t\t)\n\n\t\t// We must record overlay IDs to move them to the replacement after detaching. Otherwise, we might try moving an overlay to a non-existent node.\n\t\tconst overlayMap: Record<NodeID, NodeID> = {}\n\t\tfor (const originalNode of replacement.walk()) {\n\t\t\tlet node = originalNode\n\t\t\tnode.originalid = null\n\n\t\t\tif (detachedVariableReferenceUpdate) {\n\t\t\t\tconst update = generateVariableReferenceUpdateForNode(engine.tree, node, detachedVariableReferenceUpdate)\n\t\t\t\tif (update) {\n\t\t\t\t\tconst updatedNode = node.set(update)\n\t\t\t\t\tnode = engine.tree.current(updatedNode) ?? updatedNode\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (withEventActions(node)) {\n\t\t\t\tfor (const [key, actions] of Object.entries(node.getActions(engine.componentLoader))) {\n\t\t\t\t\tif (!actions) continue\n\t\t\t\t\tconst updatedNode = node.set({\n\t\t\t\t\t\t[key]: actions.filter(action => {\n\t\t\t\t\t\t\treturn isShowRelativeOverlayAction(action) || isEventAction(action)\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t\tnode = engine.tree.current(updatedNode) ?? updatedNode\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet dynamicValueUpdate: Partial<typeof node> | undefined\n\t\t\tif (variableValues.size > 0) {\n\t\t\t\tdynamicValueUpdate = getNodeUpdateResolvingDynamicValues(\n\t\t\t\t\tengine.tree,\n\t\t\t\t\tsmartComponentOrWebPage.id,\n\t\t\t\t\tnode,\n\t\t\t\t\tvariableValuesByProvider,\n\t\t\t\t\toverlayMap,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst detachedNodeComputedValueUpdate = getDetachedNodeComputedValueUpdate(\n\t\t\t\tengine.tree,\n\t\t\t\tnode,\n\t\t\t\tsmartComponentOrWebPage.id,\n\t\t\t\trepeatVariableControlPropUpdate,\n\t\t\t)\n\n\t\t\tconst update = {\n\t\t\t\t...dynamicValueUpdate,\n\t\t\t\t...detachedNodeComputedValueUpdate,\n\t\t\t}\n\n\t\t\tif (!isEmptyObject(update)) {\n\t\t\t\tlet updateToApply = update\n\n\t\t\t\tconst repeatArrayKey: keyof WithRepeatArray = \"repeatArray\"\n\t\t\t\tif (node.id === replacement.id && instance.repeatArray && repeatArrayKey in update) {\n\t\t\t\t\t// Keep the repeat binding copied from the instance instead of letting source-scope cleanup reset it.\n\t\t\t\t\tconst { [repeatArrayKey]: _repeatArray, ...updateWithoutRepeatArray } = update\n\t\t\t\t\tupdateToApply = updateWithoutRepeatArray\n\t\t\t\t}\n\n\t\t\t\tif (!isEmptyObject(updateToApply)) {\n\t\t\t\t\tconst updatedNode = node.set(updateToApply)\n\t\t\t\t\tnode = engine.tree.current(updatedNode) ?? updatedNode\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tassert(replacement.id !== variant.id)\n\n\t\tconst indexOfOriginal = parentOfOriginal.children.indexOf(instance)\n\n\t\tengine.tree.insertNode(replacement, parentOfOriginal.id, indexOfOriginal)\n\n\t\t// Move overlays into the replacement.\n\t\tfor (const child of instance.children) {\n\t\t\tif (!isFixedOrRelativeOverlay(child)) continue\n\t\t\tengine.tree.moveNode(child, overlayMap[child.id] ?? replacement.id)\n\t\t}\n\n\t\t// update connections between the old parent with the replacement\n\t\tupdateNodeConnections(\n\t\t\tengine.tree,\n\t\t\tengine.componentLoader,\n\t\t\tparentOfOriginal,\n\t\t\trenamedIds,\n\t\t\tisFixedOrRelativeOverlay(parentOfOriginal) || nodeIsInOverlay(parentOfOriginal),\n\t\t)\n\n\t\tengine.deleteNode(instance.id)\n\n\t\tif (hasFloatingPosition(replacement)) {\n\t\t\tengine.scheduler.runBeforeNextFrame(() => {\n\t\t\t\tengine.stores.overlayStore.showOverlay(engine.stores.selectionStore, replacement, replacement.parentid)\n\t\t\t})\n\t\t}\n\n\t\treturn engine.tree.current(replacement) ?? replacement\n\t}\n\n\texport function toggleTeamLibrary(engine: VekterEngine) {\n\t\ttoggleQuickActions(engine, { openLibrary: true })\n\t}\n\n\texport function toggleQuickActions(engine: VekterEngine, { openLibrary }: { openLibrary?: boolean } = {}) {\n\t\tconst { modalStore, popoverStore } = engine.stores\n\t\tif (modalStore.active.type === ModalType.QuickActions) {\n\t\t\tmodalStore.dismiss()\n\t\t} else {\n\t\t\tengine.cancelTool()\n\t\t\tpopoverStore.active = PopoverType.None\n\t\t\tmodalStore.set({\n\t\t\t\ttype: ModalType.QuickActions,\n\t\t\t\tsource: \"main_menu\",\n\t\t\t\tinitialCategory: openLibrary ? { type: QuickActionsCategoryType.TeamLibrary } : undefined,\n\t\t\t})\n\n\t\t\tif (openLibrary) {\n\t\t\t\trecord(\"ui_interaction\", { page: MetricsInteractionViews.MAIN_MENU, id: UIInteraction.teamLibrary })\n\t\t\t} else {\n\t\t\t\trecord(\"ui_interaction\", { page: MetricsInteractionViews.MAIN_MENU, id: UIInteraction.quickActions })\n\t\t\t}\n\t\t}\n\t}\n\n\texport function canCreateBreakpoint(\n\t\tbaseNode: CanvasNode,\n\t): baseNode is typeof baseNode & FrameNode & IsVariant & IsBreakpoint {\n\t\tif (!isBreakpointVariant(baseNode)) return false\n\t\treturn true\n\t}\n\n\texport function showCustomBreakpointModal(\n\t\tengine: VekterEngine,\n\t\ttype: \"update\" | \"add\",\n\t\tnodeId: NodeID,\n\t\tname?: string,\n\t\twidth?: number,\n\t) {\n\t\tconst { modalStore } = engine.stores\n\t\tif (modalStore.active.type === ModalType.CustomBreakpoint) return\n\n\t\tengine.cancelTool()\n\t\tmodalStore.set({\n\t\t\ttype: ModalType.CustomBreakpoint,\n\t\t\tactionType: type,\n\t\t\tbaseNodeId: nodeId,\n\t\t\tname,\n\t\t\twidth,\n\t\t\tsource: \"undefined\",\n\t\t})\n\t}\n\n\texport function createBreakpoint(\n\t\tengine: VekterEngine,\n\t\tbaseNode: FrameNode & IsVariant & IsBreakpoint,\n\t\tscope: LoadedScopeNode & WithBreakpointVariants,\n\t\tnewBreakpointRect: Rect,\n\t\twidth: number,\n\t\tname: string,\n\t\tviewportHeight?: number,\n\t\tselectAndCenter?: boolean,\n\t) {\n\t\tconst targetRect = { ...newBreakpointRect, width }\n\n\t\tconst node = ContextAction.createVariant(\n\t\t\tengine.componentLoader,\n\t\t\tengine.stores.treeStore.tree,\n\t\t\tengine.stores.selectionStore,\n\t\t\tengine.stores.canvasStore,\n\t\t\tscope,\n\t\t\tbaseNode,\n\t\t\ttargetRect,\n\t\t\t{\n\t\t\t\toverrideSize: true,\n\t\t\t\tvariantName: name,\n\t\t\t\tviewportHeight,\n\t\t\t\tselectAndCenter,\n\t\t\t},\n\t\t)\n\n\t\tassert(isBreakpointVariant(node), \"Created node is not a breakpoint variant\")\n\n\t\treturn node\n\t}\n\n\texport function containsMaster(node: CanvasNode) {\n\t\treturn node.some(n => n !== node && isMaster(n))\n\t}\n\n\texport function nodeTypeCanBePrimaryVariantSource(\n\t\tnode: CanvasNode,\n\t): node is FrameNode | PrimaryVariantSourceNeedsWrappingFrame {\n\t\treturn (\n\t\t\tisFrameNode(node) ||\n\t\t\tisSVGNode(node) ||\n\t\t\tisShapeContainerNode(node) ||\n\t\t\tisAnyTextNode(node) ||\n\t\t\tisFormPlainTextInputNode(node) ||\n\t\t\tisFormBooleanInputNode(node) ||\n\t\t\tisFormSelectNode(node)\n\t\t)\n\t}\n\n\texport function canConvertNodeToSmartComponentPrimaryVariant(\n\t\ttree: CanvasTree,\n\t\tnode: CanvasNode,\n\t): node is FrameNode | PrimaryVariantSourceNeedsWrappingFrame {\n\t\tif (!nodeTypeCanBePrimaryVariantSource(node)) return false\n\t\tif (isWebPageInstance(tree, node)) return false\n\t\tif (isVariant(node)) return false\n\t\tif (isReplica(node)) return false\n\t\tif (isMaster(node)) return false\n\t\tif (containsMaster(node)) return false\n\t\treturn true\n\t}\n\n\texport function canMakeSmartComponent(engine: VekterEngine, nodes: CanvasNode[]): boolean {\n\t\tconst nodeCount = nodes.length\n\t\tif (nodeCount === 0) return true\n\n\t\tconst node1 = nodes[0]\n\t\tassert(node1, \"node must be defined\", nodes)\n\n\t\treturn nodeCount === 1 && canConvertNodeToSmartComponentPrimaryVariant(engine.tree, node1)\n\t}\n\n\texport function canMakeWebPagePrimaryBreakpoint(engine: VekterEngine, nodes: CanvasNode[]): boolean {\n\t\tconst nodeCount = nodes.length\n\t\tif (nodeCount !== 1) return false\n\n\t\tconst node = nodes[0]\n\t\tassert(node, \"node must be defined\", nodes)\n\n\t\tif (!isFrameNode(node)) return false\n\t\tif (isReplicaOrReplicaChild(node)) return false\n\n\t\tconst scope = engine.tree.get(node.parentid)\n\t\treturn isDesignPageNode(scope)\n\t}\n\n\texport async function convertNodeToWebPagePrimaryBreakpoint(engine: VekterEngine, nodes: CanvasNode[]) {\n\t\tif (!canMakeWebPagePrimaryBreakpoint(engine, nodes)) return\n\n\t\tconst node = nodes[0]\n\t\tassert(node, \"node must be defined\", nodes)\n\n\t\tconst name = node.resolveValue(\"name\")\n\n\t\treturn engine.createWebPage({\n\t\t\tprimaryBreakpointTemplateId: node.id,\n\t\t\tshouldRemovePanelOverrides: false,\n\t\t\tstartEditingPageTitle: false,\n\t\t\tpreferredPath: name ? nameToPath(name) : undefined,\n\t\t})\n\t}\n\n\texport function createLayoutTemplate(\n\t\ttree: CanvasTree,\n\t\tsource: \"assets_panel\" | \"context_menu\" | \"properties\",\n\t\tname: string = Dictionary.Template,\n\t\tfromBreakpoint?: FrameNode & IsPrimaryVariant & IsBreakpoint,\n\t\tentityParentId?: MaybeNodeID,\n\t): LoadedLayoutTemplateNode {\n\t\tconst primary = new FrameNode({\n\t\t\t...layoutTemplatePrimaryLayoutDefaults,\n\t\t\t...getLayoutPropertiesFromExistingNode(fromBreakpoint),\n\t\t\tisMaster: true,\n\t\t\tisVariant: true,\n\t\t\tisBreakpoint: true,\n\t\t\twidthType: DimensionType.FixedNumber,\n\t\t\theightType: DimensionType.FixedNumber,\n\t\t\twidth: fromBreakpoint?.width ?? 1200,\n\t\t\tname: fromBreakpoint?.name ?? Dictionary.Desktop,\n\t\t})\n\n\t\tconst slot = new SlotNode()\n\t\tprimary.addChild(slot)\n\n\t\tconst templateName = uniqueName(name, getAllLocalLayoutTemplateNames(tree))\n\t\tconst template = new LayoutTemplateNode({\n\t\t\tbaseVariantId: primary.id,\n\t\t\tname: templateName,\n\t\t})\n\n\t\tassert(template.isLoaded(), \"A newly created LayoutTemplateNode must be loaded.\")\n\n\t\ttemplate.addChild(primary)\n\n\t\ttree.latestTree().insertNode(template)\n\n\t\tconst newParentId = createEntityFolderNodesFromPath(\n\t\t\ttree,\n\t\t\ttemplateName,\n\t\t\tentityParentId ?? LAYOUT_TEMPLATE_ENTITY_ROOT_ID,\n\t\t)\n\n\t\tcreateReferenceForNodeIfNeeded(tree, newParentId, template.id)\n\n\t\trecord(\"layout_template_create\", { source })\n\t\treturn template\n\t}\n\n\t// VECTOR @TODO - createDefaultShape and itemsCount are mutually exclusive. Try an overload.\n\texport function createVectorSet(\n\t\tengine: VekterEngine,\n\t\tname: string,\n\t\tcreateDefaultShape: boolean = true,\n\t\tentityParentId: NodeID | null = null,\n\t\tid: NodeID = randomID(),\n\t\tsource: \"assets\" | \"context_menu\" | \"import\" = \"context_menu\",\n\t\titemsCount: number = 0,\n\t): LoadedVectorSetNode {\n\t\tconst vectorSetNode = new VectorSetNode({ name, id })\n\t\tassert(vectorSetNode.isLoaded(), \"A newly created VectorSetNode must be loaded\")\n\n\t\tengine.tree.latestTree().insertNode(vectorSetNode)\n\n\t\tcreateReferenceForNodeIfNeeded(engine.tree, entityParentId ?? VECTOR_SET_ENTITY_TYPE_ROOT_ID, vectorSetNode.id)\n\t\tif (createDefaultShape) {\n\t\t\tfor (const container of getDefaultVectorSetShapes()) {\n\t\t\t\tengine.tree.latestTree().insertNode(container, vectorSetNode.id)\n\t\t\t}\n\t\t}\n\n\t\tconst latestVectorSet = engine.tree.current(vectorSetNode)\n\t\tassert(latestVectorSet, \"A newly created VectorSetNode must exist\")\n\t\tvoid engine.stores.codeGenerationStore.createVectorSet(latestVectorSet.getVectorSetItems())\n\n\t\trecord(\"vector_set_create\", { source, items: createDefaultShape ? 3 : itemsCount })\n\t\treturn vectorSetNode\n\t}\n\n\texport async function addToVectorSet(engine: VekterEngine, nodes: MaybeCanvasNode[], vectorSetId: NodeID) {\n\t\tconst vectorSet = engine.tree.get(vectorSetId)\n\t\tif (!isVectorSetNode(vectorSet)) return\n\n\t\tconst loaded = !vectorSet.isLoaded() ? await vectorSet.load() : vectorSet\n\t\tif (!loaded) return\n\n\t\tconst firstItem = loaded.children.find(isVectorSetItem)\n\t\tif (!isVectorSetItem(firstItem)) return\n\n\t\tconst rect = engine.tree.getRect(firstItem)\n\n\t\tengine.scheduler.process(() => {\n\t\t\t// The selection might contain multiple Vectors in the same Shape Container. Ensure we\n\t\t\t// only add the Shape Container once.\n\t\t\tconst topLevelNodes = getTopLevelVectorNodes(engine, nodes)\n\n\t\t\tconst newNodes: (CanvasNode & IsVectorSetItem)[] = []\n\t\t\tconst fill = withOptionalFill(firstItem)\n\t\t\t\t? { fillEnabled: firstItem.fillEnabled, fillType: firstItem.fillType, fillColor: firstItem.fillColor }\n\t\t\t\t: undefined\n\n\t\t\tfor (const id of topLevelNodes) {\n\t\t\t\tconst node = engine.tree.get<ShapeContainerNode | VectorNode>(id)\n\t\t\t\tif (!node) continue\n\n\t\t\t\tconst indexInParent = engine.tree.getIndex(node)\n\t\t\t\tconst point = rightSideOf(engine.tree, loaded, node, rect, rect.width)\n\t\t\t\tconst clone = cloneNodeAsVectorSetItem(node, point, fill)\n\t\t\t\tif (!isVectorSetItem(clone)) continue\n\n\t\t\t\tengine.tree.insertNode(clone, loaded.id)\n\n\t\t\t\tnewNodes.push(clone)\n\n\t\t\t\tscaleVector(engine, clone.id, rect)\n\t\t\t\trecord(\"vector_set_item_create\", { source: \"context_menu\" })\n\n\t\t\t\tif (vectorSetId !== engine.stores.scopeStore.active.id) {\n\t\t\t\t\tconst instance = new CodeComponentNode({\n\t\t\t\t\t\t...positionUpdateForVectorInstance(node),\n\t\t\t\t\t\tcodeComponentIdentifier: localModuleIdentifierForStableName(ModuleType.Vector, clone.id, \"default\").value,\n\t\t\t\t\t\twidth: node.width,\n\t\t\t\t\t\theight: node.height,\n\t\t\t\t\t\twidthType: DimensionType.FixedNumber,\n\t\t\t\t\t\theightType: DimensionType.FixedNumber,\n\t\t\t\t\t\tslotsAreChildNodes: experiments.isOn(\"componentSlotsAreChildNodes\"),\n\t\t\t\t\t\tname: node.name,\n\t\t\t\t\t})\n\t\t\t\t\tengine.tree.insertNode(instance, node.parentid, indexInParent)\n\t\t\t\t}\n\t\t\t\tengine.tree.removeNode(node)\n\t\t\t}\n\n\t\t\tif (newNodes.length === 0) return\n\n\t\t\tengine.stores.scopeStore.select(vectorSet.id, { keepHistory: false })\n\t\t\tengine.stores.selectionStore.set(newNodes)\n\t\t\tengine.stores.chromeStore.layersExpanded = true\n\t\t\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Layers\n\n\t\t\tvoid engine.stores.codeGenerationStore.createVectorSet(newNodes)\n\t\t})\n\t}\n\n\texport function createVectorSetFromNodes(\n\t\tengine: VekterEngine,\n\t\tnodes: MaybeCanvasNode[],\n\t\tname: string = Dictionary.IconSet,\n\t\tsource: \"assets\" | \"context_menu\" = \"context_menu\",\n\t) {\n\t\tconst vectorSetNode = new VectorSetNode({ name })\n\t\tassert(vectorSetNode.isLoaded(), \"A newly created VectorSetNode must be loaded\")\n\t\t// The selection might contain multiple Vectors in the same Shape Container. Ensure we\n\t\t// only add the Shape Container once.\n\t\tconst topLevelNodes = getTopLevelVectorNodes(engine, nodes)\n\n\t\tlet offset = 0\n\t\tconst newNodes: (CanvasNode & IsVectorSetItem)[] = []\n\t\tfor (const id of topLevelNodes) {\n\t\t\tconst node = engine.tree.get<ShapeContainerNode | VectorNode>(id)\n\t\t\tif (!node) continue\n\n\t\t\tconst rect = engine.tree.getRect(node)\n\t\t\tconst clone = cloneNodeAsVectorSetItem(node, { x: offset, y: 0 })\n\t\t\tif (!isVectorSetItem(clone)) continue\n\n\t\t\tconst indexInParent = engine.tree.getIndex(node)\n\t\t\tnewNodes.push(clone)\n\t\t\tvectorSetNode.addChild(clone)\n\t\t\toffset += rect.width * 2\n\n\t\t\tconst instance = new CodeComponentNode({\n\t\t\t\t...positionUpdateForVectorInstance(node),\n\t\t\t\tcodeComponentIdentifier: localModuleIdentifierForStableName(ModuleType.Vector, clone.id, \"default\").value,\n\t\t\t\twidth: node.width,\n\t\t\t\theight: node.height,\n\t\t\t\twidthType: DimensionType.FixedNumber,\n\t\t\t\theightType: DimensionType.FixedNumber,\n\t\t\t\tslotsAreChildNodes: experiments.isOn(\"componentSlotsAreChildNodes\"),\n\t\t\t\tname: node.name,\n\t\t\t})\n\t\t\tengine.tree.insertNode(instance, node.parentid, indexInParent)\n\t\t\tengine.tree.removeNode(node)\n\t\t}\n\n\t\tengine.tree.latestTree().insertNode(vectorSetNode)\n\n\t\tcreateReferenceForNodeIfNeeded(engine.tree, VECTOR_SET_ENTITY_TYPE_ROOT_ID, vectorSetNode.id)\n\n\t\tvoid engine.stores.codeGenerationStore.createVectorSet(newNodes)\n\n\t\tengine.stores.scopeStore.select(vectorSetNode.id, { keepHistory: false })\n\t\tengine.stores.selectionStore.set(newNodes)\n\t\tengine.stores.chromeStore.layersExpanded = true\n\t\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Layers\n\n\t\trecord(\"vector_set_create\", { source, items: topLevelNodes.size })\n\t}\n\n\texport function createVectorSetItem(\n\t\tstores: EngineStores,\n\t\tscopeNode: Loaded<ScopeNode> & WithVectorSetItems,\n\t\titem: CanvasNode & IsVectorSetItem,\n\t\trect: Rect,\n\t\tsource: \"canvas\" | \"context_menu\",\n\t) {\n\t\tconst newItem = item.clone({ children: new CanvasChildList(), name: Dictionary.Vector })\n\t\tconst { scopeStore, codeGenerationStore, selectionStore, canvasStore } = stores\n\n\t\tscopeStore.insertNode(newItem, scopeNode.id)\n\n\t\tassert(isPinnable(newItem), \"Vector must be pinnable.\")\n\n\t\tnewItem.set({ top: rect.y, left: rect.x })\n\n\t\tvoid codeGenerationStore.createVectorSet([newItem])\n\n\t\tselectionStore.set(newItem.id)\n\t\tcanvasStore.scrollToCenter(Rect.center(rect))\n\n\t\trecord(\"vector_set_item_create\", { source })\n\t}\n\n\texport function addSelectionToAgent(stores: EngineStores, selection: NodeID[]) {\n\t\tconst { chromeStore, agentStore } = stores\n\t\tchromeStore.activeRightPanelTab = CanvasPanelTab.Chat\n\t\tagentStore.enqueueSelection({ type: \"layerSelection\", nodeIds: selection, focusInput: true })\n\t}\n\n\texport function startAgentContextTool(engine: VekterEngine) {\n\t\tengine.stores.chromeStore.activeRightPanelTab = CanvasPanelTab.Chat\n\t\tengine.stores.chromeStore.removePanelOverrides()\n\t\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Layers\n\t\tengine.stores.selectionStore.clear()\n\t\tengine.setTool(Tools.AgentPanel)\n\t}\n}\n\nexport const layoutTemplatePrimaryLayoutDefaults: Partial<WithSize> &\n\tPartial<WithPins> &\n\tHasStackLayout &\n\tWithPadding &\n\tPartial<WithOverflow> = {\n\theight: LAYOUT_TEMPLATE_HEIGHT,\n\tleft: 0,\n\ttop: 0,\n\tlayout: \"stack\",\n\tstackDirection: \"vertical\",\n\tstackAlignment: \"center\",\n\tstackDistribution: \"start\",\n\tstackWrapEnabled: false,\n\tgap: 0,\n\tpadding: 0,\n\tpaddingPerSide: false,\n\tpaddingLeft: 0,\n\tpaddingBottom: 0,\n\tpaddingTop: 0,\n\tpaddingRight: 0,\n\toverflow: \"clip\",\n}\n\ntype LayoutTemplateFillProperties = Pick<HasStackLayout, \"gap\"> &\n\tWithPadding &\n\tWithOptionalFill & {\n\t\tfillImageAlts?: FillImageAlt[] | undefined\n\t}\n\nfunction getLayoutPropertiesFromExistingNode(node: CanvasNode | undefined): LayoutTemplateFillProperties | undefined {\n\tif (!node) return\n\tif (!withLayout(node) || !withPadding(node) || !withOptionalFill(node)) return\n\n\tconst padding = paddingFromNode(node)\n\n\tconst layoutProperties: LayoutTemplateFillProperties = {\n\t\tgap: node.resolveValue(\"gap\") ?? layoutTemplatePrimaryLayoutDefaults.gap,\n\t\tpadding: padding.perSide ? layoutTemplatePrimaryLayoutDefaults.padding : padding.top,\n\t\tpaddingPerSide: padding.perSide ?? layoutTemplatePrimaryLayoutDefaults.paddingPerSide,\n\t\tpaddingLeft: padding.left ?? layoutTemplatePrimaryLayoutDefaults.paddingLeft,\n\t\tpaddingBottom: padding.bottom ?? layoutTemplatePrimaryLayoutDefaults.paddingBottom,\n\t\tpaddingTop: padding.top ?? layoutTemplatePrimaryLayoutDefaults.paddingTop,\n\t\tpaddingRight: padding.right ?? layoutTemplatePrimaryLayoutDefaults.paddingRight,\n\t\tfillEnabled: node.resolveValue(\"fillEnabled\"),\n\t\tfillType: node.resolveValue(\"fillType\"),\n\t\tfillColor: node.resolveValue(\"fillColor\"),\n\t\tfillLinearGradient: node.resolveValue(\"fillLinearGradient\"),\n\t\tfillRadialGradient: node.resolveValue(\"fillRadialGradient\"),\n\t\tfillConicGradient: node.resolveValue(\"fillConicGradient\"),\n\t\tfillImage: !isDynamicValue(node.fillImage) ? node.fillImage : undefined,\n\t\tfillImageOriginalName: node.resolveValue(\"fillImageOriginalName\"),\n\t\tfillImageResize: node.resolveValue(\"fillImageResize\"),\n\t\tfillImagePixelWidth: node.resolveValue(\"fillImagePixelWidth\"),\n\t\tfillImagePixelHeight: node.resolveValue(\"fillImagePixelHeight\"),\n\t\tfillImagePositionX: node.resolveValue(\"fillImagePositionX\"),\n\t\tfillImagePositionY: node.resolveValue(\"fillImagePositionY\"),\n\t\tfillImageTileSize: node.resolveValue(\"fillImageTileSize\"),\n\t}\n\n\tif (withFillImageAlts(node)) {\n\t\tlayoutProperties.fillImageAlts = node.fillImageAlts ? [...node.fillImageAlts] : undefined\n\t}\n\n\treturn layoutProperties\n}\n\nfunction getAllLocalLayoutTemplateNames(tree: CanvasTree) {\n\tconst names = new Set<string>()\n\n\ttree.root.children.forEach(node => {\n\t\tif (!isLayoutTemplateNode(node)) return\n\t\tconst name = node.resolveValue(\"name\")\n\t\tif (name) names.add(name)\n\t})\n\n\treturn names\n}\n\nexport function canCopyNode(node: CanvasNode) {\n\tif (isGestureVariant(node)) return false\n\tif (isSlotNode(node)) return false\n\tif (isSlotPropertyNode(node)) return false\n\treturn true\n}\n\nfunction canDeleteNode(node: CanvasNode) {\n\tif (isPrimaryVariant(node)) return false\n\tif (isSlotNode(node)) return false\n\tif (isSlotPropertyNode(node)) return false\n\tif (isReplicaChild(node)) return false\n\treturn true\n}\n\nexport function canDeleteOrHideNode(node: CanvasNode) {\n\t// Variant editing will hide the node instead of deleting.\n\tif (isReplicaVariantChild(node) && node.isVisible()) return true\n\treturn canDeleteNode(node)\n}\n\nfunction canDuplicateNode(node: CanvasNode) {\n\tif (!canCopyNode(node)) return false\n\tif (isReplicaChild(node)) {\n\t\treturn isReplicaVariantChild(node)\n\t}\n\n\treturn true\n}\n\nfunction getCollectionIdFromNode(engine: VekterEngine, node: CanvasNode): NodeID | null {\n\tif (hasCollectionDataSource(node)) {\n\t\tconst collection = getCollectionForIdentifier(engine.tree, node.dataIdentifier)\n\t\tif (collection) return collection.id\n\t}\n\n\treturn null\n}\n\n/**\n * Getting the most logical collection ID for the currently selected node\n *\n * Search for a node with a collection attached in the following priority order:\n *   1. The currently selected node\n *   2. The currently selected node's ancestors\n *   3. The active scope node (e.g. blog details page)\n *   4. The currently selected node's descendents\n *   5. The active scope node's descendants\n */\nfunction getNearestCollectionId(\n\tengine: VekterEngine,\n\tactiveScope: LoadedScopeNode,\n\tselectedNode: CanvasNode | undefined,\n) {\n\tif (selectedNode) {\n\t\tconst collectionIdFromSelectedNode = getCollectionIdFromNode(engine, selectedNode)\n\t\tif (collectionIdFromSelectedNode) return collectionIdFromSelectedNode\n\n\t\tfor (const ancestorNode of selectedNode.ancestors()) {\n\t\t\tconst collectionIdFromAncestors = getCollectionIdFromNode(engine, ancestorNode)\n\t\t\tif (collectionIdFromAncestors) return collectionIdFromAncestors\n\t\t}\n\t}\n\n\tconst collectionIdFromActiveScope = getCollectionIdFromNode(engine, activeScope)\n\tif (collectionIdFromActiveScope) return collectionIdFromActiveScope\n\n\tif (selectedNode) {\n\t\tfor (const descendantNode of selectedNode.walk()) {\n\t\t\tconst collectionIdFromChildren = getCollectionIdFromNode(engine, descendantNode)\n\t\t\tif (collectionIdFromChildren) return collectionIdFromChildren\n\t\t}\n\t}\n\n\tfor (const { node, skipChildren } of activeScope.walkWithSkipChildren()) {\n\t\t// We already checked the selected node and its descendants\n\t\tif (selectedNode && node.id === selectedNode.id) {\n\t\t\tskipChildren()\n\t\t} else {\n\t\t\tconst collectionIdFromTree = getCollectionIdFromNode(engine, node)\n\t\t\tif (collectionIdFromTree) return collectionIdFromTree\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction cloneNodeAsVectorSetItem(\n\tnode: ShapeContainerNode | VectorNode,\n\t{ x, y }: Point,\n\tfill?: Partial<WithOptionalFill>,\n) {\n\tif (isVectorNode(node)) {\n\t\tconst shapeContainer = new ShapeContainerNode({\n\t\t\t...fill,\n\t\t\tisVectorSetItem: true,\n\t\t\twidth: node.width,\n\t\t\theight: node.height,\n\t\t\tleft: x,\n\t\t\ttop: y,\n\t\t\t// hoist layer name from the original node to vector set item root\n\t\t\tname: node.name,\n\t\t})\n\n\t\tconst vector = node.clone({ x: 0, y: 0 })\n\t\tshapeContainer.addChild(vector)\n\t\treturn shapeContainer\n\t}\n\n\treturn node.clone({\n\t\t...fill,\n\t\tisVectorSetItem: true,\n\t\tleft: x,\n\t\ttop: y,\n\t})\n}\n\nfunction getTopLevelVectorNodes(engine: VekterEngine, nodes: MaybeCanvasNode[]) {\n\treturn new Set(\n\t\tnodes.map<MaybeNodeID>(node => {\n\t\t\tif (!node) return null\n\t\t\tif (isShapeContainerNode(node)) return node.getPrimaryId()\n\t\t\tconst topLevelNode = engine.tree.getAncestorThatMatches(node, n => isTopLevelVectorNode(engine, n), true, true)\n\n\t\t\tif (!topLevelNode) return null\n\t\t\tconst parent = engine.tree.getNodeParent(topLevelNode)\n\t\t\tif (!parent) return topLevelNode.getPrimaryId()\n\t\t\treturn isShapeContainerNode(parent) ? parent.getPrimaryId() : topLevelNode.getPrimaryId()\n\t\t}),\n\t)\n}\n\nfunction isTopLevelVectorNode(engine: VekterEngine, node: CanvasNode): node is VectorNode {\n\treturn isVectorNode(node) && isRootVectorNode(engine.tree, node)\n}\n\nfunction positionUpdateForVectorInstance(node: ShapeContainerNode | VectorNode) {\n\tif (isPinnable(node)) {\n\t\treturn {\n\t\t\ttop: node.top,\n\t\t\tbottom: node.bottom,\n\t\t\tleft: node.left,\n\t\t\tright: node.right,\n\t\t\tcenterAnchorX: node.centerAnchorX,\n\t\t\tcenterAnchorY: node.centerAnchorY,\n\t\t\tconstraintsLocked: node.constraintsLocked,\n\t\t}\n\t}\n\n\treturn {\n\t\ttop: node.y,\n\t\tleft: node.x,\n\t}\n}\n\nconst tint = \"rgb(0, 153, 255)\"\n\nconst defaultVectorShapeFill: Partial<WithOptionalFill> = {\n\tfillType: \"color\",\n\tfillColor: tint,\n\tfillEnabled: true,\n}\n\nconst vectorSetShapeContainerDefaults: Partial<ShapeContainerNode> = {\n\tisVectorSetItem: true,\n\ttop: 0,\n\twidth: 40,\n\theight: 40,\n\tautoSize: false,\n}\n\nconst getDefaultVectorSetShapes = () => {\n\tconst triangle = new PolygonShapeNode({\n\t\t...defaultVectorShapeFill,\n\t\tx: -3,\n\t\ty: -3,\n\t\twidth: 46,\n\t\theight: 46,\n\t\tpolygonSides: 3,\n\t\tcentered: true,\n\t\tradius: 1,\n\t})\n\n\tconst diamond = new PolygonShapeNode({\n\t\t...defaultVectorShapeFill,\n\t\tx: 0,\n\t\ty: 0,\n\t\twidth: 40,\n\t\theight: 40,\n\t\tpolygonSides: 4,\n\t\tcentered: true,\n\t\tradius: 1,\n\t})\n\n\tconst oval = new OvalShapeNode({\n\t\t...defaultVectorShapeFill,\n\t\tx: 2,\n\t\ty: 2,\n\t\twidth: 36,\n\t\theight: 36,\n\t})\n\n\tconst triangleContainer = new ShapeContainerNode({\n\t\t...vectorSetShapeContainerDefaults,\n\t\tname: \"Triangle\",\n\t})\n\n\ttriangleContainer.addChild(triangle)\n\n\tconst diamondContainer = new ShapeContainerNode({\n\t\t...vectorSetShapeContainerDefaults,\n\t\tleft: 80,\n\t\tname: \"Diamond\",\n\t})\n\n\tdiamondContainer.addChild(diamond)\n\n\tconst ovalContainer = new ShapeContainerNode({\n\t\t...vectorSetShapeContainerDefaults,\n\t\tleft: 160,\n\t\tname: Dictionary.Oval,\n\t})\n\n\tovalContainer.addChild(oval)\n\n\treturn [triangleContainer, diamondContainer, ovalContainer]\n}\n", "import { deepCloneUnsafe } from \"utils/deepClone.ts\"\n\ntype RawObject = Record<string | number | symbol, unknown>\n\nfunction isObject(item: unknown): item is RawObject {\n\treturn typeof item === \"object\" && !Array.isArray(item) && item !== null\n}\n\nfunction deepMerge(target: unknown, source: unknown) {\n\tif (!isObject(target) && isObject(source)) {\n\t\treturn Object.assign({}, source)\n\t}\n\tif (!isObject(target) || !isObject(source)) return source\n\tfor (const key of Object.keys(source)) {\n\t\ttarget[key] = deepMerge(target[key], source[key])\n\t}\n\treturn target\n}\n\n/**\n * Merge sources with target deeply, copying arrays and primitives, preserving class instances by reference.\n */\nexport function assignDeepUnsafe<TObj extends RawObject, Sources extends RawObject[]>(\n\ttarget: TObj,\n\t...sources: Sources\n) {\n\tlet result: unknown = target\n\tfor (const source of sources) {\n\t\tresult = deepMerge(result, deepCloneUnsafe(source))\n\t}\n\treturn result as RawObject\n}\n", "import {\n\ttype BranchedSerializableRow,\n\ttype CrdtTreePatch,\n\ttype CrdtTreePatchMap,\n\tDELETED_VALUE,\n\tKEEP_KEY,\n\tStore,\n\tgroupRowsByBranch,\n\ttype StoreId,\n\tMAIN_BRANCH_ID,\n} from \"@framerjs/crdtree2\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert } from \"@framerjs/shared\"\nimport { treeLibrary } from \"document/models/CanvasTree/FastTreeLibrary.ts\"\nimport { reviveProps } from \"document/models/CanvasTree/TreeDiff.ts\"\nimport { changeOverrides } from \"document/models/CanvasTree/TreeDiffOverrides.ts\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport { CanvasChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport type { ReadonlyChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport { isEntityReferenceNodeId } from \"document/models/CanvasTree/nodes/EntityReferenceNode.ts\"\nimport { TemplateHelper } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport { type ValueNode, reviveReplicaInfo } from \"document/models/CanvasTree/nodes/canvasNodeFromValue.ts\"\nimport { getNodeSubclassByClassName, isEntityReferenceNodeClass } from \"document/models/CanvasTree/nodes/classList.ts\"\nimport type { WithChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { type ReplicaInfo, isMaster, isReplica } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { assignDeepUnsafe } from \"document/utils/assignDeep.ts\"\nimport type { CrdtBranchStoreRegistry } from \"./CrdtBranchStoreRegistry.ts\"\n\nfunction shouldRemoveNode(patch: CrdtTreePatch): patch is undefined {\n\treturn patch === undefined\n}\n\nfunction dependsOnFuturePatch(tree: CanvasTree, id: string, patch: NonNullable<CrdtTreePatch>): boolean {\n\tconst replicaInfo = patch.replicaInfo\n\tif (replicaInfo?.master) {\n\t\tconst master = tree.get(replicaInfo.master)\n\t\tif (!master || !isMaster(master)) return true\n\t}\n\tif (replicaInfo?.inheritsFrom) {\n\t\tconst inherits = tree.get(replicaInfo.inheritsFrom)\n\t\tif (!inherits || !(isReplica(inherits) || isMaster(inherits))) return true\n\t}\n\n\tconst parentid = patch.parentid\n\tif (!parentid) return false\n\n\tconst parentNode = tree.get(parentid)\n\tif (parentNode) return tree.isAncestorOfNode(parentNode, id)\n\n\treturn true\n}\n\nfunction addNode(\n\ttree: CanvasTree,\n\tid: string,\n\t{ children: _, ...patch }: NonNullable<CrdtTreePatch>,\n): CanvasNode | null {\n\tassert(!tree.has(id), \"Tree must not have node\", id)\n\n\tif (!patch.parentid) {\n\t\treturn null\n\t}\n\n\tconst parent = tree.get(patch.parentid)\n\tif (!parent || (isScopeNode(parent) && !parent.isLoaded())) {\n\t\treturn null\n\t}\n\n\tconst className = patch.__class\n\tif (!className) throw new Error(\"Unknown node class for: \" + id)\n\n\tconst cls = getNodeSubclassByClassName(className)\n\tif (!cls) throw new Error(\"Unknown node class for: \" + id)\n\n\tconst replicaInfo = patch.replicaInfo as ReplicaInfo | undefined\n\tif (replicaInfo) {\n\t\tconst master = tree.get(replicaInfo.master)\n\t\tif (!master || !isMaster(master)) {\n\t\t\tthrow Error(\"broken diff, replica without master: \" + id + \" \" + replicaInfo.master)\n\t\t}\n\t\tconst revived = reviveReplicaInfo(replicaInfo)\n\t\tconst replica = TemplateHelper.create(tree, master, {\n\t\t\toverrides: revived?.overrides,\n\t\t\towner: id,\n\t\t\tinheritsFrom: revived?.inheritsFrom,\n\t\t\tduplicatedFrom: patch.duplicatedFrom as string[] | null,\n\t\t\tfromDiff: true,\n\t\t})\n\t\treplica.parentid = patch.parentid\n\t\ttree.insertNode(replica, replica.parentid)\n\t\treturn replica\n\t}\n\n\tif (isEntityReferenceNodeClass(cls)) {\n\t\tassert(isEntityReferenceNodeId(id), \"Invalid EntityReferenceNode ID: \" + id)\n\t\tconst node = new cls({ ...reviveProps(patch), id })\n\t\ttree.insertNode(node, node.parentid)\n\t\treturn node\n\t}\n\n\tconst node = new cls({ ...reviveProps(patch), id })\n\ttree.insertNode(node, node.parentid)\n\treturn node\n}\n\nfunction removeNode(tree: CanvasTree, id: string) {\n\tif (!tree.has(id)) return\n\ttree.remove(id)\n}\n\nfunction changeNode(\n\ttree: CanvasTree,\n\tid: string,\n\t{ children: _, ...patch }: NonNullable<CrdtTreePatch>,\n): CanvasNode | null {\n\tconst node = tree.get(id) as CanvasNode\n\tif (!node) return null\n\n\t// handle parentid change\n\tif (patch.parentid && node.parentid !== patch.parentid) {\n\t\tif (!tree.has(patch.parentid)) {\n\t\t\ttree.remove(id)\n\t\t\treturn null\n\t\t}\n\t\ttree.move(id, patch.parentid)\n\t}\n\n\tconst draft = node.asDraft(tree)\n\tfor (const key in patch) {\n\t\tconst prevValue = draft[key as keyof CanvasNode]\n\t\tif (key === \"replicaInfo\" || typeof prevValue !== \"object\" || Array.isArray(prevValue) || prevValue === null) {\n\t\t\tcontinue\n\t\t}\n\n\t\tpatch[key] = assignDeepUnsafe({}, prevValue, patch[key])\n\t}\n\n\tif (patch.replicaInfo && isReplica(node)) {\n\t\tconst { overrides, _deleted, ...rest } = patch.replicaInfo\n\n\t\tfor (const originalId in overrides) {\n\t\t\tlet override = overrides[originalId]\n\t\t\tconst prevOverride = draft.replicaInfo?.overrides[originalId]\n\t\t\tif (prevOverride !== null && typeof prevOverride === \"object\" && !Array.isArray(prevOverride)) {\n\t\t\t\toverride = assignDeepUnsafe({}, prevOverride, override)\n\t\t\t}\n\n\t\t\tif (!override) continue\n\t\t\tchangeOverrides(tree, draft, originalId, override)\n\t\t}\n\n\t\tconst replicaInfo = Object.assign(draft.replicaInfo!, rest)\n\n\t\ttreeLibrary.updateNode(tree, draft, patch)\n\t\tdraft.replicaInfo = replicaInfo\n\t\tdraft.cache.rebuildReplica = true\n\t\treturn draft\n\t} else {\n\t\ttreeLibrary.updateNode(tree, node, patch)\n\t\treturn draft\n\t}\n}\n\nfunction isEqualChildrenOrder(children: ReadonlyChildList<CanvasNode>, to: string[]) {\n\tif (children.length !== to.length) return false\n\tfor (let i = 0; i < children.length; i++) {\n\t\tif (children.at(i)!.id !== to[i]!) return false\n\t}\n\n\treturn true\n}\n\nfunction resyncChildOrder(tree: CanvasTree, node: CanvasNode & WithChildren, to: string[]) {\n\t// if the order is already the same, do nothing\n\tif (isEqualChildrenOrder(node.children, to)) return\n\n\t// create new child list in correct order, dropping any child that doesn't exist locally\n\tconst newChildren: CanvasNode[] = []\n\tfor (let i = 0, il = to.length; i < il; i++) {\n\t\tconst child = tree.get(to[i])\n\t\tif (!child) continue\n\t\t// only take in children that have the correct parentid set\n\t\tif (child.parentid !== node.id) continue\n\t\tnewChildren.push(child)\n\t}\n\n\t// make sure we don't drop any children that exist locally\n\tconst seen = new Set<string>(to)\n\tconst children = node.children\n\tfor (const child of children) {\n\t\tif (seen.has(child.id)) continue\n\t\tnewChildren.push(child)\n\t}\n\n\t// if indeed a change, set to the mutable node\n\tif (!isChildrenShallowEqual(children, newChildren)) {\n\t\tnode.asDraft(tree).children = new CanvasChildList(newChildren)\n\t}\n}\n\nfunction isChildrenShallowEqual(children: ReadonlyChildList<CanvasNode>, newChildren: CanvasNode[]) {\n\tif (children.length !== newChildren.length) return false\n\treturn children.every((child, index) => newChildren[index] === child)\n}\n\nexport function applyPatchesToTheTree(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tpatches: CrdtTreePatchMap,\n\t/**\n\t * Usually, we bypass certain operations (like bumping the module revision hint) when applying diffs, but if we want\n\t * to treat them as a regular local edit, we can set this to true.\n\t */\n\tasLocalEdit = false,\n) {\n\tif (!asLocalEdit) {\n\t\ttree.applyingDiffs = true\n\t}\n\n\t// Convert patches map to array format for processing\n\tconst allNodeIds = Array.from(patches.keys())\n\tlet pendingPatches = [...allNodeIds]\n\n\t// We keep a list of patches that are postponed and applied later, because\n\t// some patches depend on others. Additions depend on a parent existing and\n\t// might need to be postponed until the parent is created. Removes might\n\t// need to be postponed if any child nodes move out.\n\twhile (pendingPatches.length > 0) {\n\t\tconst postponedPatches: string[] = []\n\n\t\tfor (const id of pendingPatches) {\n\t\t\tconst patch = patches.get(id)\n\n\t\t\tif (shouldRemoveNode(patch)) continue\n\n\t\t\tif (dependsOnFuturePatch(tree, id, patch)) {\n\t\t\t\tpostponedPatches.push(id)\n\t\t\t} else if (tree.has(id)) {\n\t\t\t\tchangeNode(tree, id, patch)\n\t\t\t} else if (patch.__class) {\n\t\t\t\taddNode(tree, id, patch)\n\t\t\t}\n\t\t}\n\n\t\tif (postponedPatches.length === 0 || postponedPatches.length === pendingPatches.length) {\n\t\t\tbreak\n\t\t}\n\n\t\tpendingPatches = postponedPatches\n\t}\n\n\tfor (const id of allNodeIds) {\n\t\tconst patch = patches.get(id)\n\t\tconst children = patch?.children as string[] | undefined\n\t\tif (!children || children.length === 0) continue\n\t\tconst node = tree.get(id)\n\t\tif (!node) continue\n\t\tif (!node.children) throw Error(\"assertion failure: node has no children\")\n\t\tresyncChildOrder(tree, node as CanvasNode & WithChildren, children)\n\t}\n\n\t// Then, process all deletions.\n\tfor (const id of allNodeIds) {\n\t\tconst patch = patches.get(id)\n\t\tif (!shouldRemoveNode(patch)) continue\n\t\tremoveNode(tree, id)\n\t}\n\n\tif (!asLocalEdit) {\n\t\ttree.applyingDiffs = false\n\t}\n\n\tif (asLocalEdit) {\n\t\treturn tree.commit(componentLoader)\n\t} else {\n\t\treturn tree.commitDiffs(componentLoader)\n\t}\n}\n\nfunction hasDeletedAncestor(store: Store, id: StoreId) {\n\tlet ancestorId = store.getParentId(id)\n\twhile (ancestorId && ancestorId !== DELETED_VALUE) {\n\t\tancestorId = store.getParentId(ancestorId)\n\t}\n\n\treturn ancestorId === DELETED_VALUE\n}\n\n/** True when any touched path starts with hierarchy fields for this node. */\nfunction isHierarchyChanged(fieldsList: (string | number)[][]): boolean {\n\treturn fieldsList.some(fields => fields.length > 0 && (fields[0] === \"parentid\" || fields[0] === \"children\"))\n}\n\n/**\n * Builds a sparse patch map from the field paths produced by\n * `getFieldsForPatches`. For each node:\n *\n * - Deleted ancestor \u2192 patch is `undefined` (tombstone).\n * - Otherwise, walks each field path into the node and mirrors only the\n *   touched leaves into a patch object seeded with\n *   `{ id, __class, parentid, children }` (`__class` is always set so\n *   `applyPatchesToTheTree` can insert nodes that are new to the canvas tree).\n *   Arrays are replaced wholesale; missing fields become `undefined` (or are\n *   pushed to `_deleted` for `replicaInfo` fields).\n * - Resurrected nodes get all their keys patched, not just the changed ones.\n * - Any update that touches `parentid` or `children` on a node expands to all\n *   keys (with a fully resolved store object), so moves keep untouched props\n *   even when the row batch also carries other field paths for that node.\n * - Parents of patched nodes get a stub entry with their children list.\n *\n * @example\n * // fieldMap: Map { \"node1\" => [[\"style\", \"color\", \"red\"]] }\n * // node1 in store: { style: { color: \"red\" }, ... }\n * // Result: Map { \"node1\" => { id: \"node1\", parentid: \"root\", children: [], style: { color: \"red\" } } }\n */\nfunction createPatches(store: Store, fieldMap: Map<StoreId, (string | number)[][]>, resurrectedNodes: Set<string>) {\n\tconst patches: CrdtTreePatchMap = new Map()\n\n\tfor (const [nodeId, fieldsList] of fieldMap) {\n\t\tif (hasDeletedAncestor(store, nodeId)) {\n\t\t\tpatches.set(nodeId, undefined)\n\t\t\tcontinue\n\t\t}\n\n\t\tconst expandAllKeysAndDescendants = resurrectedNodes.has(nodeId) || isHierarchyChanged(fieldsList)\n\t\tconst node = expandAllKeysAndDescendants\n\t\t\t? store.getObject<ValueNode>(nodeId)\n\t\t\t: store.getObjectWithShallowChildren<ValueNode>(nodeId, 0)\n\t\tif (!node) continue\n\n\t\tif (!node.__class) continue\n\t\tif (!getNodeSubclassByClassName(node.__class)) continue\n\n\t\tconst isRoot = store.isRoot(nodeId)\n\t\tconst patch: CrdtTreePatch = {\n\t\t\tid: nodeId,\n\t\t\t__class: node.__class,\n\t\t\t// RootNode needs parentid = null, not undefined\n\t\t\tparentid: isRoot ? null : store.getParentId(nodeId),\n\t\t\tchildren: store.getChildrenIds(nodeId) ?? [],\n\t\t}\n\t\tconst list = expandAllKeysAndDescendants ? Object.keys(node).map(k => [k]) : fieldsList\n\n\t\tfor (const fields of list) {\n\t\t\tlet currentInPatch = patch\n\t\t\tlet currentInNode = node\n\n\t\t\tfor (const [idx, field] of fields.entries()) {\n\t\t\t\tif (field === \"parentid\" || field === \"children\" || field === KEEP_KEY) break\n\n\t\t\t\tif (Array.isArray(currentInPatch)) {\n\t\t\t\t\tif (!currentInPatch.length && Array.isArray(currentInNode)) currentInPatch.push(...currentInNode)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif (currentInPatch === undefined) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif (!(field in currentInPatch)) {\n\t\t\t\t\tif (currentInNode?.[field] === undefined) {\n\t\t\t\t\t\tif (!fields.includes(\"replicaInfo\")) {\n\t\t\t\t\t\t\tcurrentInPatch[field] = undefined\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!currentInPatch?._deleted) currentInPatch._deleted = []\n\t\t\t\t\t\tcurrentInPatch._deleted.push(field)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst isLeaf = idx === fields.length - 1\n\t\t\t\t\t\tif (isLeaf) {\n\t\t\t\t\t\t\tcurrentInPatch[field] = currentInNode[field]\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst isArray = Array.isArray(currentInNode[field])\n\t\t\t\t\t\t\tcurrentInPatch[field] = isArray ? [] : {}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcurrentInPatch = currentInPatch[field]\n\t\t\t\tcurrentInNode = currentInNode[field]\n\t\t\t}\n\t\t}\n\n\t\tpatches.set(nodeId, patch)\n\n\t\tif (!patch.parentid) continue\n\t\tif (!patches.has(patch.parentid)) {\n\t\t\tpatches.set(patch.parentid, {\n\t\t\t\tchildren: store.getChildrenIds(patch.parentid),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn patches\n}\n\n/**\n * Scans store rows from the given sequence onward and groups touched field\n * paths by node ID. Each row's `id` is split on `\".\"` to extract the node ID\n * and nested property path; the row's `key` is appended to form the full path.\n *\n * @example\n * // Row: id = \"node1.style.color\", key = \"red\"\n * // Output: Map { \"node1\" => [[\"style\", \"color\", \"red\"], ...] }\n */\nfunction getFieldsForPatches(store: Store, from = 0) {\n\tconst output = new Map<StoreId, (string | number)[][]>()\n\tconst cols = store.branchData.columns\n\tconst startingIdx = store.getFirstRowForSeq(from)\n\n\tfor (let i = startingIdx; i < cols.client.length; ++i) {\n\t\tconst cseq = cols.seq.get(i)\n\t\tif (cseq < from) continue\n\n\t\tconst id = cols.id.get(i)\n\t\tconst key = cols.key.get(i)\n\n\t\tconst parts = id.split(\".\")\n\t\tconst [nodeId, ...rest] = parts as [string, ...(string | number)[]]\n\n\t\tlet nested = output.get(nodeId)\n\t\tif (!nested) {\n\t\t\tnested = []\n\t\t\toutput.set(nodeId, nested)\n\t\t}\n\n\t\trest.push(key)\n\t\tnested.push(rest)\n\t}\n\n\treturn output\n}\n\n/**\n * Get nodes that should be resurrected, meaning the remote client has\n * moved a node so that it should no longer be deleted on this one.\n *\n * @param target Store receiving the rows; used for same-branch LWW checks\n * @param active Active visible branch; used to decide whether the live tree needs resurrection patches\n * @param source Stores that contains new updates\n *\n * @note This method needs to be called before merge\n *       because we need to know previously node was deleted in\n *       the active view.\n */\nfunction getNodesToResurrect(target: Store, active: Store, source: Store) {\n\tconst fields = getFieldsForPatches(source)\n\tconst resurrectedNodes = new Set<string>()\n\tfor (const [id, _] of fields) {\n\t\t// we don't have a move - continue\n\t\tconst sourceSeq = source.getParentIdSeq(id)\n\t\tif (sourceSeq === undefined) continue\n\n\t\t// the move is actually a delete - continue\n\t\tconst branchVal = source.getParentId(id)\n\t\tif (branchVal === DELETED_VALUE) continue\n\n\t\t// Skip when target's own row is a newer LWW write than source's: source loses,\n\t\t// node stays deleted. Only valid when target owns the parentid row \u2014 otherwise\n\t\t// targetSeq comes from a base store's counter, not source's seq space.\n\t\tconst targetSeq = target.getParentIdSeq(id)\n\t\tif (targetSeq === undefined) continue\n\t\tif (target.hasOwnRow(id, \"parentid\") && targetSeq > sourceSeq) continue\n\n\t\t// node not deleted in current store/tree - continue\n\t\tif (!hasDeletedAncestor(active, id)) continue\n\n\t\tresurrectedNodes.add(id)\n\t}\n\n\treturn resurrectedNodes\n}\n\nfunction includeChildrenToResurrect(main: Store, resurrectedNodes: Set<string>) {\n\tconst resurrectedNodeList = [...resurrectedNodes]\n\n\tfor (const nodeId of resurrectedNodeList) {\n\t\tfor (const child of main.getChildrenIds(nodeId) ?? []) {\n\t\t\tresurrectedNodeList.push(child)\n\t\t}\n\t}\n\n\treturn new Set(resurrectedNodeList)\n}\n\nexport function mergeBranchedRowsAndGetPatches(\n\tbranches: CrdtBranchStoreRegistry,\n\trows: BranchedSerializableRow[],\n): CrdtTreePatchMap {\n\tconst grouped = groupRowsByBranch(rows)\n\n\t// Fast-path: rows only target main and active branch is main \u2192 frozen single-branch behaviour.\n\t// TODO: Remove this path when we are comfortable with the branching model.\n\tconst rowsOnlyMain = grouped.size === 0 || (grouped.size === 1 && grouped.has(MAIN_BRANCH_ID))\n\tif (rowsOnlyMain && branches.activeBranchId === MAIN_BRANCH_ID) {\n\t\tconst mainStore = branches.getStore(MAIN_BRANCH_ID)\n\t\tconst mainRows = grouped.get(MAIN_BRANCH_ID) ?? []\n\t\tconst mainUpdatesStore = new Store({ client: 0, user: \"temp-user\" })\n\t\tmainUpdatesStore.addSerializableRows(mainRows)\n\t\treturn mergeAndGetPatches(mainStore, mainUpdatesStore)\n\t}\n\n\tconst activeBranchStore = branches.activeStore\n\tconst activeChain = collectActiveChainIds(activeBranchStore)\n\n\t/**\n\t * Nodes across all touched stores to mark as resurrected in the active view:\n\t * direct revivals from `getNodesToResurrect`, cycle-resolution overrides, and\n\t * parentid rows on non-active branches that revive shallow-loaded nodes.\n\t * Pruned by `hasDeletedAncestor(activeStore)` then expanded via\n\t * `includeChildrenToResurrect` before being passed to `createPatches`.\n\t */\n\tconst globalResurrection = new Set<StoreId>()\n\n\t/**\n\t * Nodes the pre-pass cycle resolution moved to DELETED_VALUE. These tombstones\n\t * live in `Hierarchy.parentOverrides`, not as rows, so `getFieldsForPatches`\n\t * won't surface them. Seeded as empty field entries so `createPatches` still\n\t * emits the tombstone patch.\n\t */\n\tconst prePassTombstoned = new Set<StoreId>()\n\n\t/**\n\t * Active-view descendants of nodes that became deleted \u2014 either via cycle\n\t * resolution producing a DELETED_VALUE override, or via a parentid row whose\n\t * target already has a deleted ancestor in the active view. Seeded as empty\n\t * field entries so `createPatches` emits tombstones for the whole subtree.\n\t */\n\tconst inheritedDeletions = new Set<StoreId>()\n\n\tconst fieldsByStore: { branchStore: Store; minSeq: number; branchUpdatesStore: Store }[] = []\n\n\tconst touched = new Set<string>()\n\n\tfor (const branchId of activeChainBaseToLeaf(activeBranchStore)) {\n\t\tconst branchStore = branches.getStore(branchId)\n\t\tconst baseTouched = branchStore.base !== undefined && touched.has(branchStore.base.branchId)\n\t\tconst branchRows = grouped.get(branchId) ?? []\n\n\t\t// Resolve overlay cycles if the base mutated earlier this walk.\n\t\t// Any hierarchy changes in the overlay need to be applied on top.\n\t\tif (baseTouched) {\n\t\t\tconst resolutions = branchStore.getHierarchy().resolveCycles(0)\n\n\t\t\tfor (const override of resolutions.nextOverrides) {\n\t\t\t\t// Override may have moved node out of a deleted subtree.\n\t\t\t\tglobalResurrection.add(override.nodeId)\n\t\t\t\tif (override.parentTo === DELETED_VALUE) {\n\t\t\t\t\tprePassTombstoned.add(override.nodeId)\n\t\t\t\t\tcollectDescendants(activeBranchStore, override.nodeId, inheritedDeletions)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const override of resolutions.prevOverrides) {\n\t\t\t\t// Override may have placed node in a deleted subtree.\n\t\t\t\tglobalResurrection.add(override.nodeId)\n\t\t\t\tif (override.parentFrom === DELETED_VALUE) {\n\t\t\t\t\tprePassTombstoned.add(override.nodeId)\n\t\t\t\t\tcollectDescendants(activeBranchStore, override.nodeId, inheritedDeletions)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If base touched, we resolved cycles. Iff we have rows, we're adding them.\n\t\t// We updated branch state in both cases.\n\t\tif (baseTouched || branchRows.length) {\n\t\t\ttouched.add(branchId)\n\t\t}\n\n\t\tif (!branchRows.length) continue\n\n\t\tconst branchUpdatesStore = new Store({ client: 0, user: \"temp-user\" })\n\t\tbranchUpdatesStore.addSerializableRows(branchRows)\n\n\t\tconst resurrectionCandidates = getNodesToResurrect(branchStore, activeBranchStore, branchUpdatesStore)\n\t\tconst { minSeq, cycleResolutions } = branchStore.append(branchUpdatesStore)\n\n\t\tif (cycleResolutions) {\n\t\t\tfor (const override of cycleResolutions.nextOverrides) {\n\t\t\t\t// Override may have moved node out of a deleted subtree.\n\t\t\t\tresurrectionCandidates.add(override.nodeId)\n\t\t\t\tif (override.parentTo === DELETED_VALUE) {\n\t\t\t\t\tcollectDescendants(activeBranchStore, override.nodeId, inheritedDeletions)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const override of cycleResolutions.prevOverrides) {\n\t\t\t\t// Override may have placed node in a deleted subtree.\n\t\t\t\tresurrectionCandidates.add(override.nodeId)\n\t\t\t\tif (override.parentFrom === DELETED_VALUE) {\n\t\t\t\t\tcollectDescendants(activeBranchStore, override.nodeId, inheritedDeletions)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const id of resurrectionCandidates) {\n\t\t\tglobalResurrection.add(id)\n\t\t}\n\t\tfieldsByStore.push({ branchStore, minSeq, branchUpdatesStore })\n\t}\n\n\t// Non-active branches: pre-pass cycles, then silently merge. Order helper runs\n\t// here so branch-config rows in main (e.g. BRANCH_BASE_ID_KEY) have already\n\t// landed and `getStore` can resolve each non-active branch.\n\tfor (const branchId of nonActiveBranchesBaseToLeaf(branches, grouped, activeChain)) {\n\t\tconst branchStore = branches.getStore(branchId)\n\t\tconst baseTouched = branchStore.base !== undefined && touched.has(branchStore.base.branchId)\n\t\tconst branchRows = grouped.get(branchId) ?? []\n\n\t\tif (baseTouched) {\n\t\t\tbranchStore.getHierarchy().resolveCycles(0)\n\t\t}\n\n\t\t// If base touched, we resolved cycles. Iff we have rows, we're adding them.\n\t\t// We updated branch state in both cases.\n\t\tif (baseTouched || branchRows.length) {\n\t\t\ttouched.add(branchId)\n\t\t}\n\n\t\tif (!branchRows.length) continue\n\n\t\tconst branchUpdatesStore = new Store({ client: 0, user: \"temp-user\" })\n\t\tbranchUpdatesStore.addSerializableRows(branchRows)\n\t\tbranchStore.append(branchUpdatesStore)\n\t}\n\n\t// Deferred until after the walk so all pre-passes have resolved cycles \u2014\n\t// `hasDeletedAncestor` walks parent pointers and would loop otherwise.\n\tfor (const { branchUpdatesStore } of fieldsByStore) {\n\t\tfor (const id of getInheritedDeletions(branchUpdatesStore, activeBranchStore)) {\n\t\t\tinheritedDeletions.add(id)\n\t\t}\n\t}\n\n\tfor (const id of Array.from(globalResurrection)) {\n\t\tif (!hasDeletedAncestor(activeBranchStore, id)) continue\n\t\tglobalResurrection.delete(id)\n\t}\n\n\tconst expandedResurrection = includeChildrenToResurrect(activeBranchStore, globalResurrection)\n\n\tconst fields = new Map<StoreId, (string | number)[][]>()\n\tfor (const { branchStore: store, minSeq } of fieldsByStore) {\n\t\tmergeFieldMaps(fields, getFieldsForPatches(store, minSeq))\n\t}\n\tfor (const id of expandedResurrection) {\n\t\tif (!fields.has(id)) fields.set(id, [])\n\t}\n\tfor (const id of prePassTombstoned) {\n\t\tif (!fields.has(id)) fields.set(id, [])\n\t}\n\tfor (const id of inheritedDeletions) {\n\t\tif (!fields.has(id)) fields.set(id, [])\n\t}\n\n\treturn createPatches(activeBranchStore, fields, expandedResurrection)\n}\n\nfunction mergeFieldMaps(target: Map<StoreId, (string | number)[][]>, source: Map<StoreId, (string | number)[][]>) {\n\tfor (const [nodeId, paths] of source) {\n\t\tlet bucket = target.get(nodeId)\n\t\tif (!bucket) {\n\t\t\tbucket = []\n\t\t\ttarget.set(nodeId, bucket)\n\t\t}\n\t\tfor (const path of paths) bucket.push(path)\n\t}\n}\n\n/** Active chain ordered base\u2192leaf. */\nfunction activeChainBaseToLeaf(activeStore: Store): string[] {\n\tconst ids: string[] = []\n\tfor (let s: Store | undefined = activeStore; s !== undefined; s = s.base) {\n\t\tids.push(s.branchId)\n\t}\n\treturn ids.reverse()\n}\n\n/**\n * Non-active branches with rows, topological base\u2192leaf. Resolves each branch's\n * store via `branches.getStore`, so must run *after* the active chain has been\n * processed \u2014 branch-config rows (e.g. `BRANCH_BASE_ID_KEY`) sit in main's row\n * stream and need to land before non-active stores can be resolved.\n */\nfunction nonActiveBranchesBaseToLeaf(\n\tbranches: CrdtBranchStoreRegistry,\n\tgrouped: Map<string, BranchedSerializableRow[]>,\n\tactiveChain: Set<string>,\n): string[] {\n\tconst candidates = new Set<string>()\n\tfor (const branchId of grouped.keys()) {\n\t\tif (activeChain.has(branchId)) continue\n\t\tcandidates.add(branchId)\n\t}\n\n\tconst visited = new Set<string>()\n\tconst ordered: string[] = []\n\n\tfunction visit(branchId: string) {\n\t\tif (visited.has(branchId)) return\n\t\tvisited.add(branchId)\n\n\t\tconst store = branches.getStore(branchId)\n\t\tconst base = store.base\n\t\tif (base !== undefined && candidates.has(base.branchId)) {\n\t\t\tvisit(base.branchId)\n\t\t}\n\n\t\tordered.push(branchId)\n\t}\n\n\tfor (const branchId of candidates) {\n\t\tvisit(branchId)\n\t}\n\n\treturn ordered\n}\n\nfunction collectActiveChainIds(activeStore: Store): Set<string> {\n\tconst ids = new Set<string>()\n\tfor (let s: Store | undefined = activeStore; s !== undefined; s = s.base) {\n\t\tids.add(s.branchId)\n\t}\n\treturn ids\n}\n\n/**\n * A parentid row whose target already has a deleted ancestor in the active view\n * means the move lands inside a deleted subtree. Return the active-view\n * descendants of that target so they can be seeded as tombstones.\n */\nfunction getInheritedDeletions(branchUpdatesStore: Store, activeStore: Store): Set<StoreId> {\n\tconst nodeIds = new Set<StoreId>()\n\tfor (const row of branchUpdatesStore.getRows()) {\n\t\tif (row.key !== \"parentid\") continue\n\t\tconst changedNodeId = row.id\n\t\tif (!hasDeletedAncestor(activeStore, changedNodeId)) continue\n\t\tcollectDescendants(activeStore, changedNodeId, nodeIds)\n\t}\n\treturn nodeIds\n}\n\nfunction collectDescendants(store: Store, parentId: StoreId, output: Set<StoreId>) {\n\tfor (const childId of store.getChildrenIds(parentId)) {\n\t\tif (output.has(childId)) continue\n\t\toutput.add(childId)\n\t\tcollectDescendants(store, childId, output)\n\t}\n}\n\nexport function mergeAndGetPatches(targetStore: Store, updatesStore: Store): CrdtTreePatchMap {\n\tif (updatesStore.length === 0) return new Map()\n\n\tconst nodesToResurrect = getNodesToResurrect(targetStore, targetStore, updatesStore)\n\n\tconst { minSeq, cycleResolutions } = targetStore.append(updatesStore)\n\n\tif (cycleResolutions) {\n\t\t// Override changes from cycle resolution can result previously\n\t\t// deleted nodes being resurrected - they may have been set\n\t\t// an override to move them out of a deleted subtree, or they may\n\t\t// no longer need an override that existed in a deleted subtree.\n\t\tfor (const override of cycleResolutions.nextOverrides) {\n\t\t\tnodesToResurrect.add(override.nodeId)\n\t\t}\n\t\tfor (const override of cycleResolutions.prevOverrides) {\n\t\t\tnodesToResurrect.add(override.nodeId)\n\t\t}\n\t}\n\n\tfor (const nodeId of Array.from(nodesToResurrect)) {\n\t\t// Ancestors may get deleted as part of cycle resolution\n\t\tif (hasDeletedAncestor(targetStore, nodeId)) nodesToResurrect.delete(nodeId)\n\t}\n\n\tconst expanded = includeChildrenToResurrect(targetStore, nodesToResurrect)\n\tconst fields = getFieldsForPatches(targetStore, minSeq)\n\tfor (const nodeId of expanded) {\n\t\tif (!fields.has(nodeId)) fields.set(nodeId, [])\n\t}\n\n\treturn createPatches(targetStore, fields, expanded)\n}\n", "export const tsExtension = \".ts\"\nexport const tsxExtension = \".tsx\"\n", "// https://mathiasbynens.be/notes/javascript-identifiers-es6\nconst reservedWords = [\n\t\"arguments\",\n\t\"await\",\n\t\"break\",\n\t\"case\",\n\t\"catch\",\n\t\"class\",\n\t\"const\",\n\t\"continue\",\n\t\"debugger\",\n\t\"default\",\n\t\"delete\",\n\t\"do\",\n\t\"else\",\n\t\"enum\",\n\t\"eval\",\n\t\"export\",\n\t\"extends\",\n\t\"false\",\n\t\"finally\",\n\t\"for\",\n\t\"function\",\n\t\"if\",\n\t\"implements\",\n\t\"import\",\n\t\"in\",\n\t\"instanceof\",\n\t\"interface\",\n\t\"let\",\n\t\"new\",\n\t\"null\",\n\t\"package\",\n\t\"private\",\n\t\"protected\",\n\t\"public\",\n\t\"return\",\n\t\"static\",\n\t\"super\",\n\t\"switch\",\n\t\"this\",\n\t\"throw\",\n\t\"true\",\n\t\"try\",\n\t\"typeof\",\n\t\"var\",\n\t\"void\",\n\t\"while\",\n\t\"with\",\n\t\"yield\",\n\t// JavaScript globals\n\t\"Infinity\",\n\t\"NaN\",\n\t\"document\",\n\t\"undefined\",\n\t\"window\",\n]\n\nconst overwritableProperties = [\"toolbar\"]\n\n// TODO: Convert these to the original regexes when supported by all browsers.\n// Generated with https://mothereff.in/regexpu\n//\n// Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1361876\n\n/* eslint-disable */\n\n// /^[$_\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}]+/u\nconst firstCharacterRegex =\n\t/^[$A-Z_a-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1878\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1CE9-\\u1CEC\\u1CEE-\\u1CF3\\u1CF5\\u1CF6\\u1CFA\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEF\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7BF\\uA7C2-\\uA7C6\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA8FE\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB67\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC\\u{10000}-\\u{1000B}\\u{1000D}-\\u{10026}\\u{10028}-\\u{1003A}\\u{1003C}\\u{1003D}\\u{1003F}-\\u{1004D}\\u{10050}-\\u{1005D}\\u{10080}-\\u{100FA}\\u{10140}-\\u{10174}\\u{10280}-\\u{1029C}\\u{102A0}-\\u{102D0}\\u{10300}-\\u{1031F}\\u{1032D}-\\u{1034A}\\u{10350}-\\u{10375}\\u{10380}-\\u{1039D}\\u{103A0}-\\u{103C3}\\u{103C8}-\\u{103CF}\\u{103D1}-\\u{103D5}\\u{10400}-\\u{1049D}\\u{104B0}-\\u{104D3}\\u{104D8}-\\u{104FB}\\u{10500}-\\u{10527}\\u{10530}-\\u{10563}\\u{10600}-\\u{10736}\\u{10740}-\\u{10755}\\u{10760}-\\u{10767}\\u{10800}-\\u{10805}\\u{10808}\\u{1080A}-\\u{10835}\\u{10837}\\u{10838}\\u{1083C}\\u{1083F}-\\u{10855}\\u{10860}-\\u{10876}\\u{10880}-\\u{1089E}\\u{108E0}-\\u{108F2}\\u{108F4}\\u{108F5}\\u{10900}-\\u{10915}\\u{10920}-\\u{10939}\\u{10980}-\\u{109B7}\\u{109BE}\\u{109BF}\\u{10A00}\\u{10A10}-\\u{10A13}\\u{10A15}-\\u{10A17}\\u{10A19}-\\u{10A35}\\u{10A60}-\\u{10A7C}\\u{10A80}-\\u{10A9C}\\u{10AC0}-\\u{10AC7}\\u{10AC9}-\\u{10AE4}\\u{10B00}-\\u{10B35}\\u{10B40}-\\u{10B55}\\u{10B60}-\\u{10B72}\\u{10B80}-\\u{10B91}\\u{10C00}-\\u{10C48}\\u{10C80}-\\u{10CB2}\\u{10CC0}-\\u{10CF2}\\u{10D00}-\\u{10D23}\\u{10F00}-\\u{10F1C}\\u{10F27}\\u{10F30}-\\u{10F45}\\u{10FE0}-\\u{10FF6}\\u{11003}-\\u{11037}\\u{11083}-\\u{110AF}\\u{110D0}-\\u{110E8}\\u{11103}-\\u{11126}\\u{11144}\\u{11150}-\\u{11172}\\u{11176}\\u{11183}-\\u{111B2}\\u{111C1}-\\u{111C4}\\u{111DA}\\u{111DC}\\u{11200}-\\u{11211}\\u{11213}-\\u{1122B}\\u{11280}-\\u{11286}\\u{11288}\\u{1128A}-\\u{1128D}\\u{1128F}-\\u{1129D}\\u{1129F}-\\u{112A8}\\u{112B0}-\\u{112DE}\\u{11305}-\\u{1130C}\\u{1130F}\\u{11310}\\u{11313}-\\u{11328}\\u{1132A}-\\u{11330}\\u{11332}\\u{11333}\\u{11335}-\\u{11339}\\u{1133D}\\u{11350}\\u{1135D}-\\u{11361}\\u{11400}-\\u{11434}\\u{11447}-\\u{1144A}\\u{1145F}\\u{11480}-\\u{114AF}\\u{114C4}\\u{114C5}\\u{114C7}\\u{11580}-\\u{115AE}\\u{115D8}-\\u{115DB}\\u{11600}-\\u{1162F}\\u{11644}\\u{11680}-\\u{116AA}\\u{116B8}\\u{11700}-\\u{1171A}\\u{11800}-\\u{1182B}\\u{118A0}-\\u{118DF}\\u{118FF}\\u{119A0}-\\u{119A7}\\u{119AA}-\\u{119D0}\\u{119E1}\\u{119E3}\\u{11A00}\\u{11A0B}-\\u{11A32}\\u{11A3A}\\u{11A50}\\u{11A5C}-\\u{11A89}\\u{11A9D}\\u{11AC0}-\\u{11AF8}\\u{11C00}-\\u{11C08}\\u{11C0A}-\\u{11C2E}\\u{11C40}\\u{11C72}-\\u{11C8F}\\u{11D00}-\\u{11D06}\\u{11D08}\\u{11D09}\\u{11D0B}-\\u{11D30}\\u{11D46}\\u{11D60}-\\u{11D65}\\u{11D67}\\u{11D68}\\u{11D6A}-\\u{11D89}\\u{11D98}\\u{11EE0}-\\u{11EF2}\\u{12000}-\\u{12399}\\u{12400}-\\u{1246E}\\u{12480}-\\u{12543}\\u{13000}-\\u{1342E}\\u{14400}-\\u{14646}\\u{16800}-\\u{16A38}\\u{16A40}-\\u{16A5E}\\u{16AD0}-\\u{16AED}\\u{16B00}-\\u{16B2F}\\u{16B40}-\\u{16B43}\\u{16B63}-\\u{16B77}\\u{16B7D}-\\u{16B8F}\\u{16E40}-\\u{16E7F}\\u{16F00}-\\u{16F4A}\\u{16F50}\\u{16F93}-\\u{16F9F}\\u{16FE0}\\u{16FE1}\\u{16FE3}\\u{17000}-\\u{187F7}\\u{18800}-\\u{18AF2}\\u{1B000}-\\u{1B11E}\\u{1B150}-\\u{1B152}\\u{1B164}-\\u{1B167}\\u{1B170}-\\u{1B2FB}\\u{1BC00}-\\u{1BC6A}\\u{1BC70}-\\u{1BC7C}\\u{1BC80}-\\u{1BC88}\\u{1BC90}-\\u{1BC99}\\u{1D400}-\\u{1D454}\\u{1D456}-\\u{1D49C}\\u{1D49E}\\u{1D49F}\\u{1D4A2}\\u{1D4A5}\\u{1D4A6}\\u{1D4A9}-\\u{1D4AC}\\u{1D4AE}-\\u{1D4B9}\\u{1D4BB}\\u{1D4BD}-\\u{1D4C3}\\u{1D4C5}-\\u{1D505}\\u{1D507}-\\u{1D50A}\\u{1D50D}-\\u{1D514}\\u{1D516}-\\u{1D51C}\\u{1D51E}-\\u{1D539}\\u{1D53B}-\\u{1D53E}\\u{1D540}-\\u{1D544}\\u{1D546}\\u{1D54A}-\\u{1D550}\\u{1D552}-\\u{1D6A5}\\u{1D6A8}-\\u{1D6C0}\\u{1D6C2}-\\u{1D6DA}\\u{1D6DC}-\\u{1D6FA}\\u{1D6FC}-\\u{1D714}\\u{1D716}-\\u{1D734}\\u{1D736}-\\u{1D74E}\\u{1D750}-\\u{1D76E}\\u{1D770}-\\u{1D788}\\u{1D78A}-\\u{1D7A8}\\u{1D7AA}-\\u{1D7C2}\\u{1D7C4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A2\\u03F6\\u0482\\u0488\\u0489\\u0530\\u0557\\u0558\\u055A-\\u055F\\u0589-\\u0590\\u05BE\\u05C0\\u05C3\\u05C6\\u05C8-\\u05CF\\u05EB-\\u05EE\\u05F3-\\u060F\\u061B-\\u061F\\u066A-\\u066D\\u06D4\\u06DD\\u06DE\\u06E9\\u06FD\\u06FE\\u0700-\\u070F\\u074B\\u074C\\u07B2-\\u07BF\\u07F6-\\u07F9\\u07FB\\u07FC\\u07FE\\u07FF\\u082E-\\u083F\\u085C-\\u085F\\u086B-\\u089F\\u08B5\\u08BE-\\u08D2\\u08E2\\u0964\\u0965\\u0970\\u0984\\u098D\\u098E\\u0991\\u0992\\u09A9\\u09B1\\u09B3-\\u09B5\\u09BA\\u09BB\\u09C5\\u09C6\\u09C9\\u09CA\\u09CF-\\u09D6\\u09D8-\\u09DB\\u09DE\\u09E4\\u09E5\\u09F2-\\u09FB\\u09FD\\u09FF\\u0A00\\u0A04\\u0A0B-\\u0A0E\\u0A11\\u0A12\\u0A29\\u0A31\\u0A34\\u0A37\\u0A3A\\u0A3B\\u0A3D\\u0A43-\\u0A46\\u0A49\\u0A4A\\u0A4E-\\u0A50\\u0A52-\\u0A58\\u0A5D\\u0A5F-\\u0A65\\u0A76-\\u0A80\\u0A84\\u0A8E\\u0A92\\u0AA9\\u0AB1\\u0AB4\\u0ABA\\u0ABB\\u0AC6\\u0ACA\\u0ACE\\u0ACF\\u0AD1-\\u0ADF\\u0AE4\\u0AE5\\u0AF0-\\u0AF8\\u0B00\\u0B04\\u0B0D\\u0B0E\\u0B11\\u0B12\\u0B29\\u0B31\\u0B34\\u0B3A\\u0B3B\\u0B45\\u0B46\\u0B49\\u0B4A\\u0B4E-\\u0B55\\u0B58-\\u0B5B\\u0B5E\\u0B64\\u0B65\\u0B70\\u0B72-\\u0B81\\u0B84\\u0B8B-\\u0B8D\\u0B91\\u0B96-\\u0B98\\u0B9B\\u0B9D\\u0BA0-\\u0BA2\\u0BA5-\\u0BA7\\u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135B\\u135C\\u1360-\\u137F\\u1390-\\u139F\\u13F6\\u13F7\\u13FE-\\u1400\\u166D\\u166E\\u1680\\u169B-\\u169F\\u16EB-\\u16ED\\u16F9-\\u16FF\\u170D\\u1715-\\u171F\\u1735-\\u173F\\u1754-\\u175F\\u176D\\u1771\\u1774-\\u177F\\u17D4-\\u17D6\\u17D8-\\u17DB\\u17DE\\u17DF\\u17EA-\\u180A\\u180E\\u180F\\u181A-\\u181F\\u1879-\\u187F\\u18AB-\\u18AF\\u18F6-\\u18FF\\u191F\\u192C-\\u192F\\u193C-\\u1945\\u196E\\u196F\\u1975-\\u197F\\u19AC-\\u19AF\\u19CA-\\u19CF\\u19DA-\\u19FF\\u1A1C-\\u1A1F\\u1A5F\\u1A7D\\u1A7E\\u1A8A-\\u1A8F\\u1A9A-\\u1AA6\\u1AA8-\\u1AAF\\u1ABE-\\u1AFF\\u1B4C-\\u1B4F\\u1B5A-\\u1B6A\\u1B74-\\u1B7F\\u1BF4-\\u1BFF\\u1C38-\\u1C3F\\u1C4A-\\u1C4C\\u1C7E\\u1C7F\\u1C89-\\u1C8F\\u1CBB\\u1CBC\\u1CC0-\\u1CCF\\u1CD3\\u1CFB-\\u1CFF\\u1DFA\\u1F16\\u1F17\\u1F1E\\u1F1F\\u1F46\\u1F47\\u1F4E\\u1F4F\\u1F58\\u1F5A\\u1F5C\\u1F5E\\u1F7E\\u1F7F\\u1FB5\\u1FBD\\u1FBF-\\u1FC1\\u1FC5\\u1FCD-\\u1FCF\\u1FD4\\u1FD5\\u1FDC-\\u1FDF\\u1FED-\\u1FF1\\u1FF5\\u1FFD-\\u200C\\u200E-\\u203E\\u2041-\\u2053\\u2055-\\u2070\\u2072-\\u207E\\u2080-\\u208F\\u209D-\\u20CF\\u20DD-\\u20E0\\u20E2-\\u20E4\\u20F1-\\u2101\\u2103-\\u2106\\u2108\\u2109\\u2114\\u2116-\\u2118\\u211E-\\u2123\\u2125\\u2127\\u2129\\u212E\\u213A\\u213B\\u2140-\\u2144\\u214A-\\u214D\\u214F-\\u215F\\u2189-\\u220B\\u220D-\\u2BFF\\u2C2F\\u2C5F\\u2CE5-\\u2CEA\\u2CF4-\\u2CFF\\u2D26\\u2D28-\\u2D2C\\u2D2E\\u2D2F\\u2D68-\\u2D6E\\u2D70-\\u2D7E\\u2D97-\\u2D9F\\u2DA7\\u2DAF\\u2DB7\\u2DBF\\u2DC7\\u2DCF\\u2DD7\\u2DDF\\u2E00-\\u2E2E\\u2E30-\\u3004\\u3008-\\u3020\\u3030\\u3036\\u3037\\u303D-\\u3040\\u3097\\u3098\\u309B\\u309C\\u30A0\\u30FB\\u3100-\\u3104\\u3130\\u318F-\\u319F\\u31BB-\\u31EF\\u3200-\\u33FF\\u4DB6-\\u4DFF\\u9FF0-\\u9FFF\\uA48D-\\uA4CF\\uA4FE\\uA4FF\\uA60D-\\uA60F\\uA62C-\\uA63F\\uA670-\\uA673\\uA67E\\uA6F2-\\uA716\\uA720\\uA721\\uA789\\uA78A\\uA7C0\\uA7C1\\uA7C7-\\uA7F6\\uA828-\\uA83F\\uA874-\\uA87F\\uA8C6-\\uA8CF\\uA8DA-\\uA8DF\\uA8F8-\\uA8FA\\uA8FC\\uA92E\\uA92F\\uA954-\\uA95F\\uA97D-\\uA97F\\uA9C1-\\uA9CE\\uA9DA-\\uA9DF\\uA9FF\\uAA37-\\uAA3F\\uAA4E\\uAA4F\\uAA5A-\\uAA5F\\uAA77-\\uAA79\\uAAC3-\\uAADA\\uAADE\\uAADF\\uAAF0\\uAAF1\\uAAF7-\\uAB00\\uAB07\\uAB08\\uAB0F\\uAB10\\uAB17-\\uAB1F\\uAB27\\uAB2F\\uAB5B\\uAB68-\\uAB6F\\uABEB\\uABEE\\uABEF\\uABFA-\\uABFF\\uD7A4-\\uD7AF\\uD7C7-\\uD7CA\\uD7FC-\\uF8FF\\uFA6E\\uFA6F\\uFADA-\\uFAFF\\uFB07-\\uFB12\\uFB18-\\uFB1C\\uFB29\\uFB37\\uFB3D\\uFB3F\\uFB42\\uFB45\\uFBB2-\\uFBD2\\uFD3E-\\uFD4F\\uFD90\\uFD91\\uFDC8-\\uFDEF\\uFDFC-\\uFDFF\\uFE10-\\uFE1F\\uFE30-\\uFE32\\uFE35-\\uFE4C\\uFE50-\\uFE6F\\uFE75\\uFEFD-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF3E\\uFF40\\uFF5B-\\uFF65\\uFFBF-\\uFFC1\\uFFC8\\uFFC9\\uFFD0\\uFFD1\\uFFD8\\uFFD9\\uFFDD-\\uFFFF\\u{1000C}\\u{10027}\\u{1003B}\\u{1003E}\\u{1004E}\\u{1004F}\\u{1005E}-\\u{1007F}\\u{100FB}-\\u{1013F}\\u{10175}-\\u{101FC}\\u{101FE}-\\u{1027F}\\u{1029D}-\\u{1029F}\\u{102D1}-\\u{102DF}\\u{102E1}-\\u{102FF}\\u{10320}-\\u{1032C}\\u{1034B}-\\u{1034F}\\u{1037B}-\\u{1037F}\\u{1039E}\\u{1039F}\\u{103C4}-\\u{103C7}\\u{103D0}\\u{103D6}-\\u{103FF}\\u{1049E}\\u{1049F}\\u{104AA}-\\u{104AF}\\u{104D4}-\\u{104D7}\\u{104FC}-\\u{104FF}\\u{10528}-\\u{1052F}\\u{10564}-\\u{105FF}\\u{10737}-\\u{1073F}\\u{10756}-\\u{1075F}\\u{10768}-\\u{107FF}\\u{10806}\\u{10807}\\u{10809}\\u{10836}\\u{10839}-\\u{1083B}\\u{1083D}\\u{1083E}\\u{10856}-\\u{1085F}\\u{10877}-\\u{1087F}\\u{1089F}-\\u{108DF}\\u{108F3}\\u{108F6}-\\u{108FF}\\u{10916}-\\u{1091F}\\u{1093A}-\\u{1097F}\\u{109B8}-\\u{109BD}\\u{109C0}-\\u{109FF}\\u{10A04}\\u{10A07}-\\u{10A0B}\\u{10A14}\\u{10A18}\\u{10A36}\\u{10A37}\\u{10A3B}-\\u{10A3E}\\u{10A40}-\\u{10A5F}\\u{10A7D}-\\u{10A7F}\\u{10A9D}-\\u{10ABF}\\u{10AC8}\\u{10AE7}-\\u{10AFF}\\u{10B36}-\\u{10B3F}\\u{10B56}-\\u{10B5F}\\u{10B73}-\\u{10B7F}\\u{10B92}-\\u{10BFF}\\u{10C49}-\\u{10C7F}\\u{10CB3}-\\u{10CBF}\\u{10CF3}-\\u{10CFF}\\u{10D28}-\\u{10D2F}\\u{10D3A}-\\u{10EFF}\\u{10F1D}-\\u{10F26}\\u{10F28}-\\u{10F2F}\\u{10F51}-\\u{10FDF}\\u{10FF7}-\\u{10FFF}\\u{11047}-\\u{11065}\\u{11070}-\\u{1107E}\\u{110BB}-\\u{110CF}\\u{110E9}-\\u{110EF}\\u{110FA}-\\u{110FF}\\u{11135}\\u{11140}-\\u{11143}\\u{11147}-\\u{1114F}\\u{11174}\\u{11175}\\u{11177}-\\u{1117F}\\u{111C5}-\\u{111C8}\\u{111CD}-\\u{111CF}\\u{111DB}\\u{111DD}-\\u{111FF}\\u{11212}\\u{11238}-\\u{1123D}\\u{1123F}-\\u{1127F}\\u{11287}\\u{11289}\\u{1128E}\\u{1129E}\\u{112A9}-\\u{112AF}\\u{112EB}-\\u{112EF}\\u{112FA}-\\u{112FF}\\u{11304}\\u{1130D}\\u{1130E}\\u{11311}\\u{11312}\\u{11329}\\u{11331}\\u{11334}\\u{1133A}\\u{11345}\\u{11346}\\u{11349}\\u{1134A}\\u{1134E}\\u{1134F}\\u{11351}-\\u{11356}\\u{11358}-\\u{1135C}\\u{11364}\\u{11365}\\u{1136D}-\\u{1136F}\\u{11375}-\\u{113FF}\\u{1144B}-\\u{1144F}\\u{1145A}-\\u{1145D}\\u{11460}-\\u{1147F}\\u{114C6}\\u{114C8}-\\u{114CF}\\u{114DA}-\\u{1157F}\\u{115B6}\\u{115B7}\\u{115C1}-\\u{115D7}\\u{115DE}-\\u{115FF}\\u{11641}-\\u{11643}\\u{11645}-\\u{1164F}\\u{1165A}-\\u{1167F}\\u{116B9}-\\u{116BF}\\u{116CA}-\\u{116FF}\\u{1171B}\\u{1171C}\\u{1172C}-\\u{1172F}\\u{1173A}-\\u{117FF}\\u{1183B}-\\u{1189F}\\u{118EA}-\\u{118FE}\\u{11900}-\\u{1199F}\\u{119A8}\\u{119A9}\\u{119D8}\\u{119D9}\\u{119E2}\\u{119E5}-\\u{119FF}\\u{11A3F}-\\u{11A46}\\u{11A48}-\\u{11A4F}\\u{11A9A}-\\u{11A9C}\\u{11A9E}-\\u{11ABF}\\u{11AF9}-\\u{11BFF}\\u{11C09}\\u{11C37}\\u{11C41}-\\u{11C4F}\\u{11C5A}-\\u{11C71}\\u{11C90}\\u{11C91}\\u{11CA8}\\u{11CB7}-\\u{11CFF}\\u{11D07}\\u{11D0A}\\u{11D37}-\\u{11D39}\\u{11D3B}\\u{11D3E}\\u{11D48}-\\u{11D4F}\\u{11D5A}-\\u{11D5F}\\u{11D66}\\u{11D69}\\u{11D8F}\\u{11D92}\\u{11D99}-\\u{11D9F}\\u{11DAA}-\\u{11EDF}\\u{11EF7}-\\u{11FFF}\\u{1239A}-\\u{123FF}\\u{1246F}-\\u{1247F}\\u{12544}-\\u{12FFF}\\u{1342F}-\\u{143FF}\\u{14647}-\\u{167FF}\\u{16A39}-\\u{16A3F}\\u{16A5F}\\u{16A6A}-\\u{16ACF}\\u{16AEE}\\u{16AEF}\\u{16AF5}-\\u{16AFF}\\u{16B37}-\\u{16B3F}\\u{16B44}-\\u{16B4F}\\u{16B5A}-\\u{16B62}\\u{16B78}-\\u{16B7C}\\u{16B90}-\\u{16E3F}\\u{16E80}-\\u{16EFF}\\u{16F4B}-\\u{16F4E}\\u{16F88}-\\u{16F8E}\\u{16FA0}-\\u{16FDF}\\u{16FE2}\\u{16FE4}-\\u{16FFF}\\u{187F8}-\\u{187FF}\\u{18AF3}-\\u{1AFFF}\\u{1B11F}-\\u{1B14F}\\u{1B153}-\\u{1B163}\\u{1B168}-\\u{1B16F}\\u{1B2FC}-\\u{1BBFF}\\u{1BC6B}-\\u{1BC6F}\\u{1BC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48}\\u{1EE4A}\\u{1EE4C}\\u{1EE50}\\u{1EE53}\\u{1EE55}\\u{1EE56}\\u{1EE58}\\u{1EE5A}\\u{1EE5C}\\u{1EE5E}\\u{1EE60}\\u{1EE63}\\u{1EE65}\\u{1EE66}\\u{1EE6B}\\u{1EE73}\\u{1EE78}\\u{1EE7D}\\u{1EE7F}\\u{1EE8A}\\u{1EE9C}-\\u{1EEA0}\\u{1EEA4}\\u{1EEAA}\\u{1EEBC}-\\u{1FFFF}\\u{2A6D7}-\\u{2A6FF}\\u{2B735}-\\u{2B73F}\\u{2B81E}\\u{2B81F}\\u{2CEA2}-\\u{2CEAF}\\u{2EBE1}-\\u{2F7FF}\\u{2FA1E}-\\u{E00FF}\\u{E01F0}-\\u{10FFFF}]+/gu\n\n/* eslint-enable */\n\nconst onlyDotsRegex = /^\\.+$/u\n\nexport const uniqueVariableName = (name: string | null, existingNames: string[]): string | null => {\n\tif (name === null || name.trim().length === 0) {\n\t\treturn null\n\t}\n\tlet index = 1\n\tconst strippedName = name.replace(/_\\d+$/u, \"\")\n\tlet result = name\n\twhile (existingNames.includes(result) || reserved(result)) {\n\t\tresult = `${strippedName}_${index}`\n\t\tindex++\n\t}\n\treturn result\n}\n\nconst reserved = (name: string) => {\n\treturn (\n\t\treservedWords.includes(name) ||\n\t\t// biome-ignore lint/suspicious/noPrototypeBuiltins: <explanation>\n\t\t(window.hasOwnProperty(name) && !overwritableProperties.includes(name))\n\t)\n}\n\nenum NameType {\n\tDirectory = \"directory\",\n\tVariable = \"variable\",\n\tSelector = \"selector\",\n}\n\nfunction sanitizedName(type: NameType, name: string | null) {\n\tif (!name) return null\n\n\tlet validName = name.trim()\n\tif (validName.length === 0) return null\n\tconst validFirstChar = type === NameType.Selector ? \"_\" : \"$\"\n\tif (type === NameType.Directory) {\n\t\tif (onlyDotsRegex.test(validName)) return null\n\t} else if (!firstCharacterRegex.test(validName)) {\n\t\tvalidName = validFirstChar + validName\n\t}\n\n\tvalidName = validName.replace(remainingCharactersRegex, \"_\")\n\tvalidName = validName.replace(/_+/gu, \"_\")\n\tvalidName = validName.replace(/^\\$_/u, validFirstChar)\n\treturn validName\n}\n\nexport function sanitizedVariableName(name: string | null): string | null {\n\treturn sanitizedName(NameType.Variable, name)\n}\n\nexport function sanitizedSelectorName(name: string | null): string | null {\n\tlet result = sanitizedName(NameType.Selector, name)\n\tif (result) result = result.replace(/^\\$/gu, \"_\")\n\treturn result\n}\n\nexport function sanitizedDirectoryName(name: string | null): string | null {\n\treturn sanitizedName(NameType.Directory, name)\n}\n", "import { tsxExtension } from \"utils/fileExtensionNames.ts\"\nimport { sanitizedVariableName } from \"utils/sanitizedVariableName.ts\"\n\nexport function createCodeComponentFile(rawName: string) {\n\tconst safeName = sanitizedVariableName(rawName)\n\tconst componentName = safeName || \"MyComponent\"\n\tconst name = componentName + tsxExtension\n\tconst content = simplifiedModulesComponentTemplate(componentName)\n\n\treturn { name, content }\n}\n\nfunction simplifiedModulesComponentTemplate(name: string) {\n\treturn `// Get Started: https://www.framer.com/developers\n\nimport { addPropertyControls, ControlType } from \"framer\"\nimport { motion } from \"framer-motion\"\n\n/**\n * @framerSupportedLayoutWidth auto\n * @framerSupportedLayoutHeight auto\n */\nexport default function ${name}(props) {\n    const { tint } = props\n\n    return (\n        <motion.div\n            style={{\n                margin: 50,\n                width: 100,\n                height: 100,\n                borderRadius: 25,\n                backgroundColor: tint,\n            }}\n            animate={{ scale: 1.5 }}\n            whileHover={{ rotate: 90 }}\n        />\n    )\n}\n\naddPropertyControls(${name}, {\n    tint: {\n        title: \"Tint\",\n        type: ControlType.Color,\n        defaultValue: \"#09F\",\n    },\n})\n`\n}\n", "import { tsxExtension } from \"utils/fileExtensionNames.ts\"\nimport { sanitizedVariableName } from \"utils/sanitizedVariableName.ts\"\n\nfunction overrideTemplate(_name: string) {\n\treturn `import { forwardRef, type ComponentType } from \"react\"\nimport { createStore } from \"https://framer.com/m/framer/store.js@^1.0.0\"\nimport { randomColor } from \"https://framer.com/m/framer/utils.js@^0.9.0\"\n\n// Learn more: https://www.framer.com/developers/overrides/\n\nconst useStore = createStore({\n    background: \"#0099FF\",\n})\n\nexport function withRotate(Component): ComponentType {\n    return forwardRef((props, ref) => {\n        return (\n            <Component\n                ref={ref}\n                {...props}\n                animate={{ rotate: 90 }}\n                transition={{ duration: 2 }}\n            />\n        )\n    })\n}\n\nexport function withHover(Component): ComponentType {\n    return forwardRef((props, ref) => {\n        return <Component ref={ref} {...props} whileHover={{ scale: 1.05 }} />\n    })\n}\n\nexport function withRandomColor(Component): ComponentType {\n    return forwardRef((props, ref) => {\n        const [store, setStore] = useStore()\n\n        return (\n            <Component\n                ref={ref}\n                {...props}\n                animate={{\n                    background: store.background,\n                }}\n                onClick={() => {\n                    setStore({ background: randomColor() })\n                }}\n            />\n        )\n    })\n}\n`\n}\n\nexport function createCodeOverrideFile(rawComponentName: string) {\n\tconst safeName = sanitizedVariableName(rawComponentName)\n\tconst componentName = safeName || \"MyOverrides\"\n\tconst name = componentName + tsxExtension\n\tconst content = overrideTemplate(componentName)\n\treturn { name, content }\n}\n", "import { splitExtension } from \"@framerjs/assets\"\nimport { capitalizeFirstLetterWithLocale } from \"utils/capitalizeFirstLetter.ts\"\nimport { createCodeComponentFile } from \"utils/createCodeComponent.ts\"\nimport { createCodeOverrideFile } from \"utils/createCodeOverride.ts\"\nimport { tsxExtension } from \"utils/fileExtensionNames.ts\"\nimport { sanitizedDirectoryName, sanitizedVariableName } from \"utils/sanitizedVariableName.ts\"\n\nexport function hasValidExtension(fileName: string) {\n\tif (fileName.endsWith(\".json\")) return true\n\treturn /\\.[tj]sx?$/u.test(fileName)\n}\n\n// https://github.com/framer/FramerModulesService/blob/master/models/validators.go#L15\nconst moduleNameRegex = /^(?:[\\w-]+\\/)*[\\w-]+(?:\\.[\\w-]+)*$/u\nexport function isValidModuleName(moduleName: string) {\n\t// When creating a file we'll do some smart sanitization to allow more inputs\n\t// We use that same logic here to validate against.\n\t// https://github.com/framer/FramerStudio/blob/master/src/app/vekter/src/code-editor/utils.ts#L88\n\tconst { path } = sanitizeFilePath(moduleName)\n\treturn moduleNameRegex.test(path)\n}\n\nexport function restoreExtension(fileName: string, previousName: string) {\n\tif (hasValidExtension(fileName)) return fileName\n\n\tlet [_, extension] = splitExtension(previousName)\n\tif (extension) extension = `.${extension}`\n\tif (!extension || !hasValidExtension(extension)) {\n\t\textension = tsxExtension\n\t}\n\n\treturn fileName + extension\n}\n\n/**\n * If the `path` doesn't have a valid code file extension, appends \".tsx\" to it.\n */\nexport function ensureCodeFileExtension(path: string): string {\n\tif (!hasValidExtension(path)) path += \".tsx\"\n\n\treturn path\n}\n\nexport function dirname(path: string) {\n\tconst at = path.lastIndexOf(\"/\")\n\tif (at < 0) return \"\"\n\treturn path.slice(0, at)\n}\n\nexport function filename(path: string) {\n\tconst at = path.lastIndexOf(\"/\") + 1\n\treturn path.slice(at)\n}\n\nexport function pathJoin(...parts: string[]): string {\n\tlet res = \"\"\n\tparts.forEach(part => {\n\t\twhile (part.startsWith(\"/\")) part = part.slice(1)\n\t\twhile (part.endsWith(\"/\")) part = part.slice(0, -1)\n\t\tif (part === \"\") return\n\t\tif (res !== \"\") res += \"/\"\n\t\tres += part\n\t})\n\treturn res\n}\n\nexport function sanitizeFilePath(input: string, capitalizeFirstLetter = true) {\n\tinput = input.trim()\n\tlet [inputName, extension] = splitExtension(filename(input))\n\tif (extension) extension = `.${extension}`\n\tconst dirName = dirname(input)\n\t\t.split(\"/\")\n\t\t.map(part => sanitizedDirectoryName(part))\n\t\t.filter(part => !!part)\n\t\t.join(\"/\")\n\n\tlet name = sanitizedVariableName(inputName) || \"MyComponent\"\n\tif ((!hasValidExtension(extension) || extension === tsxExtension) && capitalizeFirstLetter) {\n\t\tname = capitalizeFirstLetterWithLocale(name)\n\t}\n\tconst path = pathJoin(dirName, name + extension)\n\treturn { path, dirName, name, extension }\n}\n\nexport function createCodeFileData(\n\tinput: string,\n\ttype: \"component\" | \"override\" = \"component\",\n\tcapitalizeFirstLetter = true,\n): { path: string; content: string } | undefined {\n\tinput = input.trim()\n\tconst { dirName, name, extension } = sanitizeFilePath(input, capitalizeFirstLetter)\n\n\t// create non .tsx file without template\n\tif (hasValidExtension(extension) && extension !== tsxExtension) {\n\t\tconst tsFileName = name + extension\n\t\treturn { path: pathJoin(dirName, tsFileName), content: \"\" }\n\t}\n\n\t// create code template\n\tconst code = type === \"component\" ? createCodeComponentFile(name) : createCodeOverrideFile(name)\n\tconst fileName = restoreExtension(name + extension, code.name)\n\n\treturn { path: pathJoin(dirName, fileName), content: code.content }\n}\n\nexport function getUniqueName(usedNames: Set<string>, desiredName: string): string {\n\tif (!usedNames.has(desiredName)) return desiredName\n\tlet counter = 1\n\tlet result: string\n\tlet [name, extension] = splitExtension(desiredName)\n\tif (extension) extension = `.${extension}`\n\tdo {\n\t\tresult = name + \"_\" + String(counter++) + extension\n\t} while (usedNames.has(result))\n\treturn result\n}\n\n/** We only enable type analysis and linting for TypeScript and JavaScript, ignoring JSON files. */\nexport function supportsTypeAnalysisAndLinting(languageId: string) {\n\treturn languageId === \"typescript\" || languageId === \"javascript\"\n}\n", "import { experiments } from \"app/experiments.ts\"\n\nexport function isModulesInTreeOn() {\n\t// The \"branching\" experiment implicitly enables the modules-in-tree behavior.\n\treturn experiments.isOn(\"modulesInTree\") || !experiments.is(\"branching\", \"off\")\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type {\n\tAnyCanvasPageNode,\n\tAnyDesignPageNode,\n\tAnyScopeNode,\n\tAnyWebPageNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCanvasPageNode,\n\tisDesignPageNode,\n\tisFrameNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"./models/CanvasTree/nodes/utils/nodeCheck.ts\"\n\ntype FoundFirstPages = {\n\t// The first page might not be the first page that we want to\n\t// load / show due to other heuristics\n\tmaybeFirstPage: AnyWebPageNode | AnyCanvasPageNode | AnyDesignPageNode\n\thomePage: AnyWebPageNode | undefined\n\tfirstWebPageWithoutCollection: AnyWebPageNode | undefined\n\tfirstWebPageWithCollection: AnyWebPageNode | undefined\n\tfirstCanvasPage: AnyCanvasPageNode | undefined\n\tfirstDesignPage: AnyDesignPageNode | undefined\n}\n\n/**\n * This function is exported because document loader\n * needs fine grained control to determine\n * which pages to load first.\n *\n * To get the first page according to UI,\n * refer to {@link getFirstPageNodeAccordingToUI}\n */\nexport function findFirstScopes(nodes: Iterable<unknown>, homePageNodeId: string | undefined): FoundFirstPages {\n\tlet homePage: AnyWebPageNode | undefined\n\tlet firstWebPageWithoutCollection: AnyWebPageNode | undefined\n\tlet firstWebPageWithCollection: AnyWebPageNode | undefined\n\tlet firstCanvasPage: AnyCanvasPageNode | undefined\n\tlet firstDesignPage: AnyDesignPageNode | undefined\n\tfor (const node of nodes) {\n\t\tif (isWebPageNode(node, true)) {\n\t\t\tif (homePageNodeId === node.id) {\n\t\t\t\thomePage = homePage ?? node\n\t\t\t}\n\t\t\tif (node.dataIdentifier) {\n\t\t\t\tfirstWebPageWithCollection = firstWebPageWithCollection ?? node\n\t\t\t} else {\n\t\t\t\tfirstWebPageWithoutCollection = firstWebPageWithoutCollection ?? node\n\t\t\t}\n\t\t} else if (isDesignPageNode(node, true)) {\n\t\t\tfirstDesignPage = firstDesignPage ?? node\n\t\t} else if (isCanvasPageNode(node, true)) {\n\t\t\tfirstCanvasPage = firstCanvasPage ?? node\n\t\t}\n\t}\n\tconst maybeFirstPage =\n\t\thomePage ?? firstWebPageWithoutCollection ?? firstWebPageWithCollection ?? firstDesignPage ?? firstCanvasPage\n\tassert(maybeFirstPage, `findFirstScopes: Tree must contain at least one Web Page, Design Page or Canvas Page`)\n\n\treturn {\n\t\tmaybeFirstPage,\n\t\thomePage,\n\t\tfirstWebPageWithCollection,\n\t\tfirstWebPageWithoutCollection,\n\t\tfirstCanvasPage,\n\t\tfirstDesignPage,\n\t}\n}\n\n/**\n * This function is exported because loader\n * needs fine grained control to determine\n * which pages to load first.\n *\n * To get the first page according to UI,\n * refer to {@link getFirstPageNodeAccordingToUI}\n */\nexport function determineFirstPage(\n\tfirstPage: AnyWebPageNode | AnyDesignPageNode | AnyCanvasPageNode,\n\tfirstDesignPage: AnyDesignPageNode | undefined,\n) {\n\tif (isEmptyWebPage(firstPage) && firstDesignPage) {\n\t\treturn firstDesignPage\n\t}\n\n\treturn firstPage\n}\n\nexport function getFirstPageNodeAccordingToUI(nodes: Iterable<unknown>, homePageNodeId: string | undefined) {\n\tconst foundPages = findFirstScopes(nodes, homePageNodeId)\n\treturn determineFirstPage(foundPages.maybeFirstPage, foundPages.firstDesignPage)\n}\n\n/**\n * Naive check if a web page is empty by checking the scope contains only ground node frames with no\n * children.\n *\n * @todo: Look into unifying all `isEmptyWebPage` functions (from `replaceWebPage.ts`, `promptAndDeletePage.ts`, `commons.ts`)\n * /\n */\nexport function isEmptyWebPage(node: AnyWebPageNode | AnyCanvasPageNode | AnyDesignPageNode): boolean {\n\tif (!isWebPageNode(node) || !node.isLoaded()) return false\n\n\tfor (const child of node.children) {\n\t\tif (!isFrameNode(child)) return false\n\t\tif (child.children.length > 0) return false\n\t}\n\n\treturn true\n}\n\nexport function canRenderPageTypeBeforeDocumentHasFullyLoaded(node: unknown): node is AnyScopeNode {\n\tif (!node) return false\n\treturn (\n\t\tisWebPageNode(node, true) ||\n\t\tisCanvasPageNode(node, true) ||\n\t\tisSmartComponentNode(node, true) ||\n\t\tisDesignPageNode(node, true)\n\t)\n}\n", "import { assert, delay, schedulerYield } from \"@framerjs/shared\"\n\n/** The specific error the task will end in if cancel was called while the task was running. */\nclass CancelledError extends Error {\n\tconstructor() {\n\t\tsuper(\"cancelled\")\n\t\tthis.name = \"CancelledError\"\n\t}\n}\n\n/** Runs a task inside of scheduler.run() which should separate events with yield calls and yield\n * before every cpu heavy code.\n *\n * If the code inside of run throws an error the task ends in an error state. If cancel is called,\n * the task ends in a cancelled state. If the code inside or run ends normally the task ends in a\n * success state.\n *\n * The task can also be paused and resumed. Internally a paused task will block in yield until\n * resume is called.\n * */\nexport class TaskScheduler {\n\tprivate resumePromiseResolve: (() => void) | undefined\n\tprivate resumePromise: Promise<void> | undefined\n\n\tprivate backgroundMode = false\n\tprivate done: boolean = false\n\tprivate firstError: Error | undefined = undefined\n\n\tconstructor(private readonly requestIdleCallback?: (callback: Function) => void) {}\n\n\t/** A function some debugging tool can install to listen for progress. */\n\tdebugStepListener: (() => void) | undefined\n\n\t/** A function some debugging tool can call to resume for only one step. */\n\tdebugResumeOneStep() {\n\t\tthis.resume()\n\t\tthis.pause()\n\t}\n\n\t/** Returns the current mode the task is running in. */\n\tcurrentMode(): \"slow\" | \"fast\" {\n\t\treturn this.backgroundMode ? \"slow\" : \"fast\"\n\t}\n\n\t/** Returns true if the task ended successfully, or was cancelled, or encountered an error. */\n\tisDone(): boolean {\n\t\treturn Boolean(this.firstError) || this.done\n\t}\n\n\t/** Returns true if the task is done and ended successfully. */\n\tisSuccess(): boolean {\n\t\treturn !this.firstError && this.done\n\t}\n\n\t/** Returns true if the task is done because it was cancelled. */\n\tisCancelled(): boolean {\n\t\treturn Boolean(this.firstError) && this.firstError instanceof CancelledError\n\t}\n\n\t/** Returns true if the task is done because it encountered an error. */\n\tisError(): boolean {\n\t\treturn Boolean(this.firstError) && !(this.firstError instanceof CancelledError)\n\t}\n\n\t/** Returns the error that ended the task. */\n\tgetError(): Error | undefined {\n\t\treturn this.firstError\n\t}\n\n\t/** Cancels the task. Can be called by the task implementation itself, or from the outside. */\n\tcancel() {\n\t\tif (this.isDone()) return\n\t\tthis.firstError = new CancelledError()\n\t\tthis.resume()\n\t}\n\n\tprivate error(error: Error): Error {\n\t\tif (this.isDone()) return error\n\t\tthis.firstError = error\n\t\treturn error\n\t}\n\n\t/** Pause the task. Typically called from outside of the task itself, but is fine to call from\n\t * the inside, or via an event handler. */\n\tpause() {\n\t\tif (this.firstError) return\n\t\tif (this.resumePromise) return\n\t\tthis.resumePromise = new Promise(resolve => {\n\t\t\tthis.resumePromiseResolve = resolve\n\t\t})\n\t}\n\n\t/** Resume the task. */\n\tresume() {\n\t\tconst resolve = this.resumePromiseResolve\n\t\tif (!resolve) return\n\n\t\tthis.resumePromise = undefined\n\t\tthis.resumePromiseResolve = undefined\n\t\tresolve()\n\t}\n\n\t/** Returns true if the task is currently paused. */\n\tisPaused() {\n\t\treturn Boolean(this.resumePromise)\n\t}\n\n\t/** Will still yield the CPU but won't use the idle callback to run as fast as possible. */\n\tfast() {\n\t\tthis.backgroundMode = false\n\t\treturn this\n\t}\n\n\t/** Will yield the CPU and use the idle callback to only run when the user is idle. */\n\tslow() {\n\t\tthis.backgroundMode = true\n\t\treturn this\n\t}\n\n\t/** This defines the task implementation. This implementation should call .yield() after every\n\t * await on some external promise (eg a fetch, a callback, etc). And call .yield() after every\n\t * CPU heavy operation. If the implementation throws any errors the task will end in an error\n\t * state. Otherwise it will end in success. If the task got cancelled, any .yield() or .sleep()\n\t * calls will throw a cancelled error. */\n\tasync run(taskImplementation: () => Promise<void>) {\n\t\tassert(!this.isDone(), \"task is already done\")\n\t\ttry {\n\t\t\tawait taskImplementation()\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tthrow this.error(error)\n\t\t\t} else {\n\t\t\t\tthrow this.error(new Error(String(error ?? \"Unknown Error\"), { cause: error }))\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.done = true\n\t\t}\n\t}\n\n\t/** To be called by the task implementation. Let the task for a certain amount of milliseconds.\n\t * If the task is paused, this will block until it is resumed. If the task gets cancelled, this\n\t * will throw instead of return. */\n\tasync sleep(ms: number) {\n\t\tthis.debugStepListener?.()\n\t\tawait delay(ms)\n\t\tif (this.resumePromise) await this.resumePromise\n\t\tthis.debugStepListener?.()\n\t\tif (this.resumePromise) await this.resumePromise\n\t\tif (this.firstError) throw this.firstError\n\t}\n\n\t/** To be called by the task implementation. Yield the CPU to other tasks. If the task is\n\t * paused, this will block until it is resumed. If the task gets cancelled, this will throw\n\t * instead of return. */\n\tasync yield(): Promise<void> {\n\t\tthis.debugStepListener?.()\n\t\tif (this.resumePromise) {\n\t\t\tawait this.resumePromise\n\t\t} else if (this.backgroundMode) {\n\t\t\tawait new Promise(resolve => {\n\t\t\t\tif (this.requestIdleCallback) {\n\t\t\t\t\tthis.requestIdleCallback(resolve)\n\t\t\t\t} else if (typeof requestIdleCallback === \"function\") {\n\t\t\t\t\trequestIdleCallback(resolve)\n\t\t\t\t} else {\n\t\t\t\t\tsetTimeout(resolve, 0)\n\t\t\t\t}\n\t\t\t})\n\t\t} else {\n\t\t\tawait schedulerYield()\n\t\t}\n\t\tif (this.resumePromise) await this.resumePromise\n\t\tthis.debugStepListener?.()\n\t\tif (this.resumePromise) await this.resumePromise\n\t\tif (this.firstError) throw this.firstError\n\t}\n}\n", "import type { ModulesAPI } from \"@framerjs/framer-services\"\nimport type { ModuleType } from \"@framerjs/shared\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { defaultJSXMetrics } from \"code-generation/jsx/types.ts\"\nimport type { KitSection } from \"code-generation/utils/KitSectionStructureCollector.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport type { ErrorNode } from \"document/models/CanvasTree/nodes/ErrorNode.ts\"\nimport type { Size } from \"library/render/types/Size.ts\"\nimport type { BinaryAssets } from \"modules/binaryAssets.ts\"\nimport type { Submodules } from \"modules/types.ts\"\nimport { isDefined } from \"utils/typeChecks.ts\"\nimport type { ProcessDependencies } from \"./processNodes/types.ts\"\n\nexport interface SerializeOptions {\n\treadonly serializationId: string\n\treadonly initialIntrinsicSize?: Size\n\treadonly includeVectorSetSaveIds?: boolean\n}\n\ninterface Artifacts {\n\treadonly assets?: Set<string>\n\treadonly packageDependencies?: Set<string> | undefined\n\treadonly errors?: ErrorNode[]\n\treadonly kitSectionsStructure?: KitSection[]\n\treadonly binaryAssets?: BinaryAssets\n\treadonly submodules?: Submodules\n\treadonly metrics?: Partial<Record<keyof ReturnType<typeof defaultJSXMetrics>, number>>\n\treadonly files?: ModulesAPI.FileUpload[]\n}\n\nexport interface SourceCodeWithArtifacts {\n\ttype: ModuleType\n\tsource: SafeJS\n\trevision: number | undefined\n\tartifacts?: Artifacts\n}\n\nexport type SourceCodeSerializer<T extends CanvasNode = CanvasNode> = (\n\tsourceNode: T,\n\tdependencies: ProcessDependencies,\n\toptions: SerializeOptions,\n) => Promise<SourceCodeWithArtifacts[]>\n\nexport const sourceCodeSerializer = <T extends CanvasNode>(fn: SourceCodeSerializer<T>) => fn\n\nexport function sourceCodeList(list: (SourceCodeWithArtifacts | undefined)[]): SourceCodeWithArtifacts[] {\n\treturn list.filter(isDefined)\n}\n", "import hash from \"@emotion/hash\"\nimport type { AnyComponentLoader, ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { LocalModuleId, ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, ModuleType, assertNever, localModuleIdForStableName, shouldBeNever } from \"@framerjs/shared\"\nimport { type TemplateFilter, parseTemplateVariableContents } from \"@framerjs/shared/src/custom-code/templateFilters.ts\"\nimport { getTemplateVariableNameRegex } from \"@framerjs/shared/src/custom-code/templateVariableRegexes.ts\"\nimport type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js, jst } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport { PreloadCollector } from \"code-generation/loader/PreloadCollector.ts\"\nimport type { MakeSerializable } from \"code-generation/types.ts\"\nimport { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport { FetchDataCollector } from \"code-generation/utils/FetchDataCollector.ts\"\nimport { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport type { LocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport { InlineLocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport { ValueTransformCollector } from \"code-generation/utils/valueTransformCollector/ValueTransformCollector.ts\"\nimport {\n\tgetQueryDefaultCollectionAlias,\n\tgetQueryFrom,\n\tgetQuerySelect,\n} from \"code-generation/utils/valueTransformCollector/getQueryForDataRepeater.ts\"\nimport { getWebPagePath } from \"document/components/utils/getWebPagePath.ts\"\nimport { pathToName } from \"document/components/utils/pathToName.ts\"\nimport type { AnyWebPageNode, CanvasTree, NodeID, ShallowWebPageNode } from \"document/models/CanvasTree/index.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport type { RootNode } from \"document/models/CanvasTree/nodes/RootNode.ts\"\nimport type { LoadedWebPageNode, WebPageNode } from \"document/models/CanvasTree/nodes/WebPageNode.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport {\n\tisComputedValue,\n\tisComputedValueFromVariableReference,\n} from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport type { DynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type { VariableProviderControlMap } from \"document/models/CanvasTree/traits/VariableProvider.ts\"\nimport { createVariableReference, isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { getWebPageScrollTargets } from \"document/models/CanvasTree/traits/WithScrollTarget.ts\"\nimport type { VariableID } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport type { WebMetadata, WithWebMetadata } from \"document/models/CanvasTree/traits/WithWebMetadata.ts\"\nimport type { Query } from \"library/modules/cms/types.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isNullish, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { sourceCodeSerializer } from \"./GeneratedComponent.ts\"\nimport { Var } from \"./GeneratedVariantComponentVars.ts\"\nimport { createMediaQueryFromBreakpoint } from \"./helpers/breakpoints.ts\"\n\nconst PARAMS_VAR = js`params`\n\n// Not using the LocalModuleIdentifier from @framerjs/shared, because its\n// type property is a string, whereas most module APIs require a ModuleType.\n// See: https://github.com/framer/FramerStudio/pull/12059#discussion_r916913314\ninterface MetadataModuleIdentifier {\n\treadonly type: ModuleType\n\treadonly localIdName: string\n\treadonly localId: LocalModuleId\n}\n\nexport const siteMetadataModuleIdentifier: MetadataModuleIdentifier = {\n\ttype: ModuleType.SiteMetadata,\n\tlocalIdName: \"siteMetadata\",\n\tlocalId: localModuleIdForStableName(ModuleType.SiteMetadata, \"siteMetadata\"),\n}\n\nexport function pageMetadataModuleIdentifier(webPageNodeId: string): MetadataModuleIdentifier {\n\treturn {\n\t\ttype: ModuleType.WebPageMetadata,\n\t\tlocalIdName: webPageNodeId,\n\t\tlocalId: localModuleIdForStableName(ModuleType.WebPageMetadata, webPageNodeId),\n\t}\n}\n\nexport const generateSiteMetadataModule = sourceCodeSerializer<RootNode>(async (node, dependencies) => {\n\tconst { assetMap, componentLoader, tree, modulesStore } = dependencies\n\n\tconst assets = new AssetCollector(assetMap)\n\tconst bindings = new BindingCollector()\n\tconst imports = new ImportCollector(ModuleType.SiteMetadata, componentLoader, modulesStore, bindings)\n\tconst variables = new VariableCollector(node, bindings)\n\tconst declarations = new FileDeclarationCollector(bindings)\n\tconst links = new LinkCollector(node, componentLoader, imports, bindings, undefined, tree, modulesStore)\n\tconst preload = new PreloadCollector(node, tree, variables, declarations, bindings, imports, assets)\n\tconst fetches = new FetchDataCollector(bindings, variables, preload, assets, links)\n\tconst localizedValues = new InlineLocalizedValueCollector(\n\t\tnode,\n\t\tvariables,\n\t\ttree,\n\t\tcomponentLoader,\n\t\timports,\n\t\tbindings,\n\t\tdeclarations,\n\t\tfetches,\n\t\tmodulesStore,\n\t\tModuleType.SiteMetadata,\n\t)\n\tconst valueTransforms = new ValueTransformCollector(\n\t\tcomponentLoader,\n\t\tdeclarations,\n\t\tundefined,\n\t\timports,\n\t\tvariables,\n\t\tlocalizedValues,\n\t\tundefined,\n\t\tfetches,\n\t\tmodulesStore,\n\t\tModuleType.SiteMetadata,\n\t)\n\n\tconst metadata = generateMetadataObject(\n\t\tnode,\n\t\tassets,\n\t\tvalueTransforms,\n\t\tvariables,\n\t\tlocalizedValues,\n\t\tundefined,\n\t\tundefined,\n\t\tundefined,\n\t)\n\n\treturn [\n\t\t{\n\t\t\ttype: ModuleType.SiteMetadata,\n\t\t\trevision: undefined,\n\t\t\tsource: serializeMetadataModule(\n\t\t\t\tnode,\n\t\t\t\tmetadata,\n\t\t\t\timports,\n\t\t\t\tdeclarations,\n\t\t\t\tlocalizedValues,\n\t\t\t\tvalueTransforms,\n\t\t\t\tvariables,\n\t\t\t\tundefined,\n\t\t\t),\n\t\t\tartifacts: { assets: assets.keys },\n\t\t},\n\t]\n})\n\nexport const generatePageMetadataModule = sourceCodeSerializer<LoadedWebPageNode>(\n\tasync (node, dependencies, options) => {\n\t\tconst { componentLoader, tree, modulesStore, assetMap } = dependencies\n\t\tconst { serializationId } = options\n\t\tconst assets = new AssetCollector(assetMap)\n\t\tconst bindings = new BindingCollector()\n\t\tconst imports = new ImportCollector(ModuleType.WebPageMetadata, componentLoader, modulesStore, bindings)\n\t\tconst variables = new VariableCollector(node, bindings)\n\t\tconst declarations = new FileDeclarationCollector(bindings)\n\t\tconst links = new LinkCollector(node, componentLoader, imports, bindings, undefined, tree, modulesStore)\n\t\tconst preload = new PreloadCollector(node, tree, variables, declarations, bindings, imports, assets)\n\t\tconst fetches = new FetchDataCollector(bindings, variables, preload, assets, links)\n\t\tconst localizedValues = new InlineLocalizedValueCollector(\n\t\t\tnode,\n\t\t\tvariables,\n\t\t\ttree,\n\t\t\tcomponentLoader,\n\t\t\timports,\n\t\t\tbindings,\n\t\t\tdeclarations,\n\t\t\tfetches,\n\t\t\tmodulesStore,\n\t\t\tModuleType.WebPageMetadata,\n\t\t)\n\t\tconst valueTransforms = new ValueTransformCollector(\n\t\t\tcomponentLoader,\n\t\t\tdeclarations,\n\t\t\tundefined,\n\t\t\timports,\n\t\t\tvariables,\n\t\t\tlocalizedValues,\n\t\t\tundefined,\n\t\t\tfetches,\n\t\t\tmodulesStore,\n\t\t\tModuleType.WebPageMetadata,\n\t\t)\n\n\t\tconst controlMap = node.getProvidedControlMap(tree, undefined, componentLoader, componentLoader.activeBundleHash)\n\n\t\tconst metadata = generateMetadataObject(\n\t\t\tnode,\n\t\t\tassets,\n\t\t\tvalueTransforms,\n\t\t\tvariables,\n\t\t\tlocalizedValues,\n\t\t\tgetFallbackWebPageTitleForCodeGen(tree, componentLoader, node, imports),\n\t\t\tgetFallbackWebPageDescriptionForCodeGen(imports),\n\t\t\tcontrolMap,\n\t\t)\n\n\t\tmetadata[\"viewport\"] = await viewportForNode(node)\n\n\t\tconst breakpoints = Object.entries(node.getBreakpointValues()).map(([variantId, breakpoint]) => ({\n\t\t\thash: hash(variantId),\n\t\t\tmediaQuery: createMediaQueryFromBreakpoint(breakpoint),\n\t\t}))\n\t\tmetadata[\"breakpoints\"] = breakpoints\n\n\t\tconst elements = getWebPageScrollTargets(node)\n\t\tmetadata[\"elements\"] = elements\n\n\t\tmetadata[\"serializationId\"] = serializationId\n\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: ModuleType.WebPageMetadata,\n\t\t\t\tsource: serializeMetadataModule(\n\t\t\t\t\tnode,\n\t\t\t\t\tmetadata,\n\t\t\t\t\timports,\n\t\t\t\t\tdeclarations,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tvalueTransforms,\n\t\t\t\t\tvariables,\n\t\t\t\t\tcontrolMap,\n\t\t\t\t),\n\t\t\t\tartifacts: { assets: assets.keys },\n\t\t\t\trevision: node.moduleSourceRevision,\n\t\t\t},\n\t\t]\n\t},\n)\n\n/**\n * Return all the variable IDs found in the metadata and custom HTML fields.\n */\nexport function extractVariableIdsFromMetadata(\n\tnode: CanvasNode & WithWebMetadata,\n\tcontrolMap: VariableProviderControlMap | undefined,\n) {\n\tconst variables = new Set<VariableID>()\n\n\tfunction addVariablesFromTemplate(value: string) {\n\t\tconst templateVariableNameRegex = getTemplateVariableNameRegex()\n\t\tconst matches = value.matchAll(templateVariableNameRegex)\n\n\t\tfor (const [, variableName] of matches) {\n\t\t\tif (!variableName) continue\n\t\t\tif (!controlMap?.has(variableName)) {\n\t\t\t\t// TODO: Provide feedback to the user.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvariables.add(variableName)\n\t\t}\n\t}\n\n\tfor (const untypedKey in node.webMetadata) {\n\t\tconst key = untypedKey as keyof WebMetadata\n\t\tconst value = node.webMetadata[key]\n\n\t\tswitch (key) {\n\t\t\tcase \"title\":\n\t\t\tcase \"description\":\n\t\t\tcase \"socialImage\":\n\t\t\t\tif (isString(value)) {\n\t\t\t\t\taddVariablesFromTemplate(value)\n\t\t\t\t}\n\n\t\t\t\tif (isVariableReference(value)) {\n\t\t\t\t\tvariables.add(value.id)\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\tcase \"noIndex\":\n\t\t\tcase \"noIndexSite\":\n\t\t\t\tif (!isDynamicValue(value)) continue\n\t\t\t\tif (isVariableReference(value)) {\n\t\t\t\t\tvariables.add(value.id)\n\t\t\t\t} else if (isComputedValue(value)) {\n\t\t\t\t\tif (isComputedValueFromVariableReference(value)) {\n\t\t\t\t\t\tvariables.add(value.startValue.id)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tassertNever(value)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase \"favicon\":\n\t\t\tcase \"faviconDark\":\n\t\t\tcase \"appleTouchIcon\":\n\t\t\tcase \"googleAnalyticsTrackingId\":\n\t\t\tcase \"reducedMotion\":\n\t\t\tcase \"language\":\n\t\t\tcase \"languageTitle\":\n\t\t\tcase \"adaptLayoutToTextDirection\":\n\t\t\tcase \"canonicalURL\":\n\t\t\tcase \"customCanonicalURL\":\n\t\t\tcase \"rewriteCanonicalHostname\":\n\t\t\tcase \"rewriteCanonicalPath\":\n\t\t\tcase \"optOutOfHTMLPlugin\":\n\t\t\tcase \"automaticLocale\":\n\t\t\tcase \"preserveQueryParams\":\n\t\t\tcase \"enableFormsUTMTracking\":\n\t\t\tcase \"translatePagePaths\":\n\t\t\tcase \"translatePagePathsWithAI\":\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tshouldBeNever(key)\n\t\t}\n\t}\n\n\tif (node.titleLocalized) {\n\t\tfor (const localizedValue of Object.values(node.titleLocalized)) {\n\t\t\tif (isString(localizedValue.value)) {\n\t\t\t\taddVariablesFromTemplate(localizedValue.value)\n\t\t\t}\n\t\t}\n\t}\n\n\tif (node.descriptionLocalized) {\n\t\tfor (const localizedValue of Object.values(node.descriptionLocalized)) {\n\t\t\tif (isString(localizedValue.value)) {\n\t\t\t\taddVariablesFromTemplate(localizedValue.value)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn variables\n}\n\n// Values shared between the site and page metadata modules.\nfunction generateMetadataObject(\n\tnode: RootNode | WebPageNode,\n\tassets: AssetCollector,\n\tvalueTransforms: ValueTransformCollector,\n\tvariables: VariableCollector,\n\tlocalizedValues: LocalizedValueCollector,\n\ttitleFallback: SafeJS | undefined,\n\tdescriptionFallback: SafeJS | undefined,\n\tcontrolMap: VariableProviderControlMap | undefined,\n) {\n\tconst metadata: Record<string, SerializableValue> = {}\n\n\tconst title = localizedValues.add(\n\t\treplaceTemplateVariables(node, node.webMetadata?.title, valueTransforms, variables, controlMap) ?? titleFallback,\n\t\tnode.titleLocalized,\n\t\t(localeId, collectors) => {\n\t\t\tassert(collectors.variables)\n\n\t\t\treturn replaceTemplateVariables(\n\t\t\t\tnode,\n\t\t\t\tnode.titleLocalized?.[localeId]?.value,\n\t\t\t\tcollectors.valueTransforms,\n\t\t\t\tcollectors.variables,\n\t\t\t\tcontrolMap,\n\t\t\t)\n\t\t},\n\t)\n\n\tif (!isUndefined(title)) {\n\t\tmetadata[\"title\"] = title\n\t}\n\n\tconst description = localizedValues.add(\n\t\treplaceTemplateVariables(node, node.webMetadata?.description, valueTransforms, variables, controlMap) ??\n\t\t\tdescriptionFallback,\n\t\tnode.descriptionLocalized,\n\t\t(localeId, collectors) => {\n\t\t\tassert(collectors.variables)\n\n\t\t\treturn replaceTemplateVariables(\n\t\t\t\tnode,\n\t\t\t\tnode.descriptionLocalized?.[localeId]?.value,\n\t\t\t\tcollectors.valueTransforms,\n\t\t\t\tcollectors.variables,\n\t\t\t\tcontrolMap,\n\t\t\t)\n\t\t},\n\t)\n\n\tif (!isUndefined(description)) {\n\t\tmetadata[\"description\"] = description\n\t}\n\n\tif (node.webMetadata?.favicon) {\n\t\tconst resolvedAsset = assets.resolve(node.webMetadata.favicon)\n\t\tassert(resolvedAsset, \"Favicon is not a valid asset reference\")\n\n\t\tmetadata[\"favicon\"] = resolvedAsset.src\n\t}\n\n\tconst socialImage = node.webMetadata?.socialImage\n\n\tif (isVariableReference(socialImage)) {\n\t\tconst socialImageVariable = createVariableReference(socialImage.id, node.id)\n\t\tconst socialImageVariableValue = variables.create(socialImageVariable)\n\n\t\tmetadata[\"socialImage\"] = valueTransforms.wrapInToImageSrc(socialImageVariableValue)\n\t} else if (socialImage) {\n\t\t/**\n\t\t * For social images, we don't want to run it through the compression proxy,\n\t\t * so that we avoid conversion to webp which could introduce artifacts in high-fidelity images.\n\t\t */\n\t\tconst resolvedAsset = assets.resolve(socialImage)\n\t\tassert(resolvedAsset, \"Social image is not a valid asset reference\")\n\n\t\tmetadata[\"socialImage\"] = resolvedAsset.src\n\t}\n\n\tconst searchEngineIndexingDisabled = \"noindex\"\n\t// SEO optimization: https://developers.google.com/search/case-studies/large-images-case-study\n\tconst searchEngineIndexingEnabled = \"max-image-preview:large\"\n\n\tif (isDynamicValue(node.webMetadata?.noIndex)) {\n\t\t// Search engine indexing is enabled if the variable is found (not undefined), and the\n\t\t// computed value equals false.\n\t\tconst indexingEnabled = variableIsFoundAndComputationEqualsFalse(\n\t\t\tnode.webMetadata.noIndex,\n\t\t\tnode.id,\n\t\t\tvariables,\n\t\t\tvalueTransforms,\n\t\t)\n\t\tmetadata[\"robots\"] = js`${indexingEnabled} ? ${searchEngineIndexingEnabled} : ${searchEngineIndexingDisabled}`\n\t} else if (node.webMetadata?.noIndex === true) {\n\t\tmetadata[\"robots\"] = searchEngineIndexingDisabled\n\t} else {\n\t\tmetadata[\"robots\"] = searchEngineIndexingEnabled\n\t}\n\n\tif (!isUndefined(node.webMetadata?.noIndexSite)) {\n\t\tif (isDynamicValue(node.webMetadata?.noIndexSite)) {\n\t\t\tconst framerSearchIndexingEnabled = variableIsFoundAndComputationEqualsFalse(\n\t\t\t\tnode.webMetadata.noIndexSite,\n\t\t\t\tnode.id,\n\t\t\t\tvariables,\n\t\t\t\tvalueTransforms,\n\t\t\t)\n\t\t\tmetadata[\"framerSearch\"] = { index: framerSearchIndexingEnabled }\n\t\t} else {\n\t\t\tmetadata[\"framerSearch\"] = { index: !node.webMetadata?.noIndexSite }\n\t\t}\n\t}\n\n\treturn metadata\n}\n\nfunction variableIsFoundAndComputationEqualsFalse(\n\tvalue: DynamicValue,\n\twebPageId: NodeID,\n\tvariables: VariableCollector,\n\tvalueTransforms: ValueTransformCollector,\n): SafeJS {\n\tlet variableValue: SafeJS\n\tlet transformedValue: SafeJS\n\n\tif (isVariableReference(value)) {\n\t\tconst noIndexVariable = createVariableReference(value.id, webPageId)\n\t\tvariableValue = variables.create(noIndexVariable)\n\t\ttransformedValue = variableValue\n\t} else if (isComputedValue(value)) {\n\t\tassert(isComputedValueFromVariableReference(value), \"Fetch is not supported for no index\")\n\t\tconst noIndexStartValue = createVariableReference(value.startValue.id, webPageId)\n\t\tvariableValue = variables.create(noIndexStartValue)\n\t\ttransformedValue = variableValue\n\n\t\t// Apply the transforms to the variable value.\n\t\tfor (const transform of value.transforms) {\n\t\t\ttransformedValue = valueTransforms.wrapInValueTransform(transformedValue, transform, undefined, undefined)\n\t\t}\n\t} else {\n\t\tassertNever(value)\n\t}\n\n\treturn js`${variableValue} !== undefined && ${transformedValue} === false`\n}\n\n/**\n * Generates a `fetchMetadata` function that returns the correct metadata given the `pathVariables`\n * and the `activeLocale`, and a `fetchAllMetadata` function that returns all metadata for all items.\n * This is only used by SSG to resolve the metadata and isn't imported by the site otherwise.\n *\n * The difference with the default `metadata` export is that `metadata` requires the caller to\n * fetch the necessary data from the CMS themselves, but `fetchMetadata` queries the CMS under the\n * hood and abstracts the CMS away from the caller.\n */\nfunction generateFetchMetadataFunction(\n\tnode: ShallowWebPageNode,\n\timports: ImportCollector,\n\tcontrolMap: VariableProviderControlMap | undefined,\n\tvariables: VariableCollector,\n): SafeJS | undefined {\n\tif (!controlMap || !hasCollectionDataSource(node)) return\n\n\tconst variableBindings = variables.getBindings(node.id)\n\tif (variableBindings.size === 0) return\n\n\tconst variableIds = new Set(variableBindings.keys())\n\n\tconst QueryEngine = imports.addImport(\"framer\", {\n\t\texportSpecifier: \"QueryEngine\",\n\t})\n\n\tconst getWhereExpressionFromPathVariables = imports.addImport(\"framer\", {\n\t\texportSpecifier: \"getWhereExpressionFromPathVariables\",\n\t})\n\n\tfunction resolveCollection(dataIdentifier: ModuleExportIdentifierString) {\n\t\tconst binding = imports.addModuleImport(dataIdentifier)\n\t\tassert(binding, \"Can't import collection\")\n\t\treturn binding\n\t}\n\n\tconst defaultCollectionAlias = getQueryDefaultCollectionAlias(node)\n\tconst queriedVariableIds = new Set<VariableID>()\n\n\t// NOTE: We have to call `getQuerySelect` before `getQueryFrom` because it\n\t// might add variables to `queriedVariableIds`.\n\tconst querySelect = getQuerySelect(\n\t\tcontrolMap,\n\t\tvariableIds,\n\t\tqueriedVariableIds,\n\t\tdefaultCollectionAlias,\n\t\tresolveCollection,\n\t)\n\n\tconst queryFrom = getQueryFrom(\n\t\tnode.dataIdentifier,\n\t\tcontrolMap,\n\t\tqueriedVariableIds,\n\t\tdefaultCollectionAlias,\n\t\tresolveCollection,\n\t)\n\n\tconst singleItemQuery = new SerializableObject({\n\t\tfrom: queryFrom,\n\t\tselect: querySelect,\n\t\twhere: SafeJS.fn(getWhereExpressionFromPathVariables, js`pathVariables`, defaultCollectionAlias),\n\t} as MakeSerializable<Query>)\n\n\tconst allItemsQuery = new SerializableObject({\n\t\tfrom: queryFrom,\n\t\tselect: querySelect,\n\t} as MakeSerializable<Query>)\n\n\treturn js.joinLines(\n\t\tjs`export async function fetchMetadata(pathVariables, activeLocale) {`,\n\t\tjs`  const queryEngine = new ${QueryEngine}();`,\n\t\tjs``,\n\t\tjs`  const query = ${singleItemQuery};`,\n\t\tjs``,\n\t\tjs`  const result = await queryEngine.query(query, activeLocale);`,\n\t\tjs`  if (result.length === 0) {`,\n\t\tjs`    throw new Error(\"No data matches pathVariables\");`,\n\t\tjs`  }`,\n\t\tjs``,\n\t\tjs`  const params = result[0];`,\n\t\tjs`  return metadata(params, activeLocale);`,\n\t\tjs`}`,\n\t\tjs``,\n\t\tjs`export async function fetchAllMetadata(pathVariableKeys, activeLocale) {`,\n\t\tjs`  const queryEngine = new ${QueryEngine}();`,\n\t\tjs``,\n\t\tjs`  const query = ${allItemsQuery};`,\n\t\tjs``,\n\t\tjs`  for (const pathVariableKey of pathVariableKeys) {`,\n\t\tjs`    query.select.push({`,\n\t\tjs`      collection: ${defaultCollectionAlias},`,\n\t\tjs`      name: pathVariableKey,`,\n\t\tjs`      type: \"Identifier\",`,\n\t\tjs`    });`,\n\t\tjs`  }`,\n\t\tjs``,\n\t\tjs`  const results = await queryEngine.query(query, activeLocale);`,\n\t\tjs``,\n\t\tjs`  return results.map(result => ({`,\n\t\tjs`    metadata: metadata(result, activeLocale),`,\n\t\tjs`    pathVariables: Object.fromEntries(`,\n\t\tjs`      pathVariableKeys.map(pathVariableKey => [pathVariableKey, result[pathVariableKey]])`,\n\t\tjs`    )`,\n\t\tjs`  }));`,\n\t\tjs`}`,\n\t)\n}\n\nfunction serializeMetadataModule(\n\tnode: RootNode | WebPageNode,\n\tmetadata: Record<string, SerializableValue>,\n\timports: ImportCollector,\n\tdeclarations: FileDeclarationCollector,\n\tlocalizedValues: InlineLocalizedValueCollector,\n\tvalueTransforms: ValueTransformCollector,\n\tvariables: VariableCollector,\n\tcontrolMap: VariableProviderControlMap | undefined,\n): SafeJS {\n\tconst variableBindings = variables.getBindings(node.id)\n\n\tconst variableDeclarations: SafeJS[] = []\n\tfor (const [variableId, variableBinding] of variableBindings) {\n\t\tlet variableValue = js`${PARAMS_VAR}?.[${variableId}]`\n\n\t\tconst control = controlMap?.get(variableId)\n\t\tif (control && control.type === ControlType.Enum) {\n\t\t\tconst transformedValue = valueTransforms.wrapInValueTransform(\n\t\t\t\tvariableValue,\n\t\t\t\t{ name: \"enumToDisplayName\" },\n\t\t\t\tcontrol,\n\t\t\t)\n\t\t\tvariableValue = js`${variableValue} !== undefined ? ${transformedValue} : undefined`\n\t\t}\n\n\t\tconst declaration = js`const ${variableBinding} = ${variableValue}`\n\t\tvariableDeclarations.push(declaration)\n\t}\n\n\tconst metadataFunction = js.joinLines(\n\t\tjs`export default function metadata(${PARAMS_VAR}, ${Var.activeLocale}) {`,\n\t\t...variableDeclarations,\n\t\tjs`return ${metadata}`,\n\t\tjs`}`,\n\t)\n\n\tconst fetchMetadataFunction = isWebPageNode(node)\n\t\t? generateFetchMetadataFunction(node, imports, controlMap, variables)\n\t\t: undefined\n\n\treturn js.joinSections(\n\t\tjs.linesFrom(imports.statements),\n\t\t...localizedValues.list(),\n\t\t...declarations.list(),\n\t\tmetadataFunction,\n\t\tfetchMetadataFunction,\n\t\tjs`export const metadataVersion = 1`,\n\t)\n}\n\n/**\n * Replace all instances of template variables with the equivalent SafeJS code.\n */\nfunction replaceTemplateVariables(\n\tnode: RootNode | WebPageNode,\n\tvalue: string | null | undefined,\n\tvalueTransforms: ValueTransformCollector,\n\tvariables: VariableCollector,\n\tcontrolMap: VariableProviderControlMap | undefined,\n\tdefaultFilter?: TemplateFilter,\n) {\n\tif (isNullish(value)) return\n\n\tconst templateVariableNameRegex = getTemplateVariableNameRegex()\n\n\treturn jst.replaceAll(value, templateVariableNameRegex, (original, templateVariable) => {\n\t\tconst [variableName, filters] = parseTemplateVariableContents(templateVariable, defaultFilter)\n\t\tif (!controlMap?.has(variableName)) {\n\t\t\t// TODO: Provide feedback to the user.\n\t\t\treturn original\n\t\t}\n\n\t\tconst variable = createVariableReference(variableName, node.id)\n\t\tconst variableValue = variables.create(variable)\n\n\t\tlet transformedValue = variableValue\n\n\t\tif (controlMap?.get(variableName)?.type === ControlType.ResponsiveImage) {\n\t\t\ttransformedValue = valueTransforms.wrapInToImageSrc(transformedValue)\n\t\t}\n\n\t\ttransformedValue = valueTransforms.wrapInTemplateFilters(transformedValue, filters)\n\n\t\treturn js`${variableValue} !== undefined ? ${transformedValue} : ${original}`\n\t})\n}\n\n// getFallbackWebPageTitle and getFallbackWebPageTitleForCodeGen must be kept in sync:\n//\n// - Used for displaying the fallback in the Framer UI.\nexport function getFallbackWebPageTitle(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tpage: AnyWebPageNode,\n\trootMetadata: WebMetadata | undefined,\n): string {\n\tconst globalTitle = rootMetadata?.title\n\tconst defaultTitle = getDefaultWebPageTitle(tree, componentLoader, page)\n\treturn globalTitle || defaultTitle\n}\n\n// - Used when generating the metadata module.\nfunction getFallbackWebPageTitleForCodeGen(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tpage: WebPageNode,\n\timports: ImportCollector,\n): SafeJS {\n\tconst siteMetadata = imports.addImport(`../${siteMetadataModuleIdentifier.localId}`, {\n\t\texportSpecifier: \"default\",\n\t\timportBinding: \"siteMetadata\",\n\t})\n\n\tconst globalTitle = js`${siteMetadata}(${PARAMS_VAR}, ${Var.activeLocale}).title`\n\tconst defaultTitle = getDefaultWebPageTitle(tree, componentLoader, page)\n\treturn js`${globalTitle} || ${defaultTitle}`\n}\n\nfunction getFallbackWebPageDescriptionForCodeGen(imports: ImportCollector): SafeJS {\n\tconst siteMetadata = imports.addImport(`../${siteMetadataModuleIdentifier.localId}`, {\n\t\texportSpecifier: \"default\",\n\t\timportBinding: \"siteMetadata\",\n\t})\n\n\treturn js`${siteMetadata}(${PARAMS_VAR}, ${Var.activeLocale}).description`\n}\n\n// Used as fallback if there's neither page title, nor global site title.\nexport function getDefaultWebPageTitle(\n\ttree: CanvasTree,\n\tcomponentLoader: AnyComponentLoader,\n\tpage: AnyWebPageNode,\n): string {\n\tif (hasCollectionDataSource(page)) {\n\t\tconst data = componentLoader.dataForIdentifier(page.dataIdentifier)\n\t\tif (data?.name) return data.name + \" Detail\"\n\t}\n\tconst pagePath = getWebPagePath(tree, page)\n\tconst nameFromPath = pathToName(pagePath ?? \"/\")\n\treturn nameFromPath\n}\n\nexport async function viewportForNode(node: AnyWebPageNode): Promise<string> {\n\tconst loadedNode = node.isLoaded() ? node : await node.load()\n\tif (!loadedNode) return \"width=device-width\"\n\tconst hasBreakpoints = loadedNode.getReplicaVariants().length > 0\n\treturn hasBreakpoints ? \"width=device-width\" : `width=${loadedNode.getPrimaryVariant().width}`\n}\n", "import type { VerifiedArrayControlDescription } from \"@framerjs/framer-runtime\"\nimport { isArrayOfObjectControlDescription } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport type {\n\tArrayValue,\n\tImageControlProp,\n\tObjectControlProp,\n\tStaticArrayControlPropValue,\n} from \"document/models/controlProps/ControlProp.ts\"\nimport { isImageControlProp, isObjectControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { ControlType, type ResponsiveImageControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { assert } from \"library/utils/assert.ts\"\nimport { isString, isUndefined } from \"utils/typeChecks.ts\"\n\nexport function getImageControlKeyAndDescription(\n\tcontrol: VerifiedArrayControlDescription,\n): [string, ResponsiveImageControlDescription] {\n\tassert(isArrayOfObjectControlDescription(control), \"Array gallery control must be Array of Object controls\")\n\tconst itemControl = control.control\n\n\tlet result: [string, ResponsiveImageControlDescription] | undefined\n\n\tfor (const controlKey in itemControl.controls) {\n\t\tassert(!result, \"Multiple item properties found in gallery control\")\n\n\t\tconst imageControl = itemControl.controls[controlKey]\n\t\tassert(imageControl?.type === ControlType.ResponsiveImage)\n\n\t\tresult = [controlKey, imageControl]\n\t}\n\n\tassert(result, \"Gallery control must have at least one item property\")\n\treturn result\n}\n\nexport function getImageControlPropFromArrayItem(imageKey: string, item: ArrayValue): ImageControlProp | undefined {\n\tif (!isObjectControlProp(item) || !item.value) return\n\n\tconst imageControlProp = item.value[imageKey]\n\tif (imageControlProp?.type !== ControlType.Image) return\n\n\treturn imageControlProp\n}\n\nexport function createGalleryItem({\n\titemId,\n\timageKey,\n\timageControlProp,\n}: {\n\titemId: string\n\timageKey: string\n\timageControlProp: ImageControlProp\n}): ObjectControlProp & ArrayValue {\n\treturn {\n\t\tid: itemId,\n\t\ttype: ControlType.Object,\n\t\tvalue: {\n\t\t\t[imageKey]: imageControlProp,\n\t\t},\n\t}\n}\n\nexport function getNonPlaceholderItems(items: StaticArrayControlPropValue | undefined): StaticArrayControlPropValue {\n\tif (!items) return []\n\treturn items.filter(item => !isPlaceholderControlProp(item))\n}\n\nexport function isPlaceholderControlProp(item: ArrayValue): boolean {\n\tif (!isObjectControlProp(item)) return false\n\tif (!item.value) return false\n\tconst values = Object.values(item.value)\n\n\tif (values.length !== 1) return false\n\tconst value = values[0]\n\tif (!isImageControlProp(value)) return false\n\n\treturn isUndefined(value.value)\n}\n\nexport function isGalleryControl(control: VerifiedArrayControlDescription): boolean {\n\tif (!isArrayOfObjectControlDescription(control)) return false\n\tconst arrayItemControls = Object.values(control.control.controls)\n\tif (arrayItemControls.length !== 1) return false\n\tconst itemPropertyControl = arrayItemControls[0]\n\treturn itemPropertyControl?.type === ControlType.ResponsiveImage\n}\n\nexport function getGalleryImages(value: ArrayValue[], imageKey: string): (string | undefined)[] {\n\treturn value.map(item => {\n\t\tconst imageControlProp = getImageControlPropFromArrayItem(imageKey, item)\n\t\tif (!imageControlProp) return undefined\n\t\tif (!isString(imageControlProp.value)) return undefined\n\t\treturn imageControlProp.value\n\t})\n}\n", "import type { ComponentLoader, EntityDefinition } from \"@framerjs/framer-runtime\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { keyDownKey } from \"document/models/CanvasTree/traits/WithFrameEvents.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { titleCase } from \"utils/titleCase.ts\"\n\nexport type EventKeyToDisplayNameMap = Record<string, string>\n\nexport function eventKeyToDisplayName(\n\teventKey: string,\n\teventMap: EventKeyToDisplayNameMap | null,\n\tisNodeWithFrameEvents = false,\n\tshortName = false,\n): string {\n\tconst displayName = eventMap?.[eventKey]\n\tif (displayName) return displayName\n\tif (eventKey === keyDownKey && isNodeWithFrameEvents) return shortName ? \"Key\" : \"Key & Gamepad\"\n\tif (shortName && eventKey === \"onMouseEnter\") return \"Enter\"\n\tif (shortName && eventKey === \"onMouseLeave\") return \"Leave\"\n\n\tconst titleWithoutOn = eventKey.startsWith(\"on\") && eventKey.length > 2 ? eventKey.substring(2) : eventKey\n\t// We currently mix \"Click\" and \"Tap\" throughout the product. \"Tap\" is mostly a legacy leftover name from prototyping.\n\t// But we still use it in some places, so it's safer to just replace it with \"Click\" in the UI.\n\tconst title = titleWithoutOn.replace(\"Tap\", Dictionary.Click)\n\treturn titleCase(title)\n}\n\nfunction eventKeyToDisplayNameMapGenerator() {\n\t// Caches last used values\n\tlet lastComponent: EntityDefinition | null = null\n\tlet lastResult: EventKeyToDisplayNameMap | null = null\n\n\treturn (componentLoader: ComponentLoader, node: CodeComponentNode): EventKeyToDisplayNameMap | null => {\n\t\tconst component = componentLoader.componentForIdentifier(node.codeComponentIdentifier)\n\t\tif (component === lastComponent) {\n\t\t\treturn lastResult\n\t\t}\n\n\t\tif (!component || !component.properties) return null\n\n\t\tconst result: EventKeyToDisplayNameMap = {}\n\n\t\tconst propertyKeys = Object.keys(component.properties)\n\t\tfor (let i = 0, il = propertyKeys.length; i < il; i++) {\n\t\t\tconst prop = propertyKeys[i]\n\t\t\tconst property = component.properties[prop]\n\t\t\tif (property?.type === ControlType.EventHandler && property.title) {\n\t\t\t\tresult[prop] = property.title\n\t\t\t}\n\t\t}\n\n\t\tlastComponent = component\n\t\tlastResult = result\n\t\treturn result\n\t}\n}\n\nexport const getMemoEventKeyToDisplayNameMap = eventKeyToDisplayNameMapGenerator()\n", "import type { PopoutId } from \"../../shared/PopoutNavigation.tsx\"\n\nexport function generateVariablePanelPopoutId(variableId: string, parentVariableId?: string): PopoutId {\n\tif (parentVariableId) return `variable-panel-popout-${parentVariableId}-${variableId}`\n\treturn `variable-panel-popout-${variableId}`\n}\n", "import type { VariableCreateScopeType } from \"@framerjs/events\"\nimport { triggerVariableReferenceCreateEvent } from \"@framerjs/framer-events\"\nimport { assert, List } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCollectionNode,\n\tisLayoutTemplateNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { createVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type {\n\tVariableID,\n\tVariablesAndDividers,\n\tWithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport {\n\tgetDefaultNameForVariable,\n\tisArrayItemVariableDefinition,\n\twithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isVekterEngine } from \"document/useVekterEngine.ts\"\nimport { CollectionPanelTab } from \"document/utils/ActiveEditorType.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { uniqueName } from \"document/utils/uniqueName.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { titleCase } from \"utils/titleCase.ts\"\nimport { generateVariablePanelPopoutId } from \"../../contentManagement/utils/collectionFieldPopoutId.ts\"\nimport {\n\ttype SelectedVariableInfo,\n\tgetVariableListFromVariableParent,\n\tupdateVariableListInVariableParent,\n} from \"../../shared/VariablesModal/getSelectedVariableInfo.ts\"\nimport type { CreateVariableOptions } from \"./createVariable.ts\"\nimport { createVariable } from \"./createVariable.ts\"\n\nexport type CreateVariableWithTreeOptions = CreateVariableOptions & {\n\tscopeId: NodeID\n\t/** Defaults to true, when assigned we fire a VARIABLE REFERENCE CREATE event */\n\tisAssigned?: boolean\n\tuseUniqueName?: boolean\n\tinsertAfterVariable?: SelectedVariableInfo | null\n}\n\nexport type CreateVariableInScopeOptions = CreateVariableWithTreeOptions & {\n\tengine: BaseEngine\n\tshowEditor?: boolean\n}\n\n/** Make sure variable name is unique in current scope. */\nfunction uniqueVariableName(variables: VariablesAndDividers, name: string) {\n\tconst existingNames = new Set(variables.map(variable => variable.name))\n\treturn uniqueName(titleCase(name), existingNames)\n}\n\nexport function getFallbackNameForCreateVariableOptions(options: {\n\ttype: CreateVariableOptions[\"type\"]\n\texpectedType?: ControlType\n}): string {\n\tswitch (options.type) {\n\t\tcase \"controlReference\":\n\t\tcase \"nodePropertyControlReference\":\n\t\t\tswitch (options.expectedType) {\n\t\t\t\tcase ControlType.Enum:\n\t\t\t\t\treturn Dictionary.Type\n\t\t\t\tcase ControlType.File:\n\t\t\t\t\treturn \"File\"\n\t\t\t\tdefault:\n\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t`getFallbackNameForCreateVariableOptions(), unsupported file reference type: ${options.expectedType}`,\n\t\t\t\t\t)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn getDefaultNameForVariable(options.type)\n\t}\n}\n\nexport function getVariableInsertionIndex(\n\texistingVariables: VariablesAndDividers,\n\tselectedVariableId?: VariableID | null,\n): number {\n\tconst defaultIndex = existingVariables.length\n\tif (!selectedVariableId) return defaultIndex\n\n\tconst selectedVariableIndex = existingVariables.findIndex(({ id }) => id === selectedVariableId)\n\treturn selectedVariableIndex === -1 ? defaultIndex : selectedVariableIndex + 1\n}\n\nfunction getVariableCreationScopeType(scope: CanvasNode & WithVariables): VariableCreateScopeType {\n\tif (isCollectionNode(scope)) return \"collection\"\n\tif (isLayoutTemplateNode(scope)) return \"layout_template\"\n\tif (isSmartComponentNode(scope)) return \"canvas_component\"\n\tif (isWebPageNode(scope)) return \"web_page\"\n\tassert(true, \"Should not be able to create variables on invalid scope\", scope.__class)\n\treturn \"canvas_component\"\n}\n\n/**\n * Returns null if scope doesn't support variables (without an engine dependency).\n */\nexport function createVariableWithTree(\n\ttree: CanvasTree,\n\toptions: CreateVariableWithTreeOptions,\n): VariableReference | null {\n\tconst { scopeId, isAssigned = true, useUniqueName = true, insertAfterVariable, ...variableOptions } = options\n\n\t// Create variable\n\tconst scope = tree.get(scopeId)\n\tif (!withVariables(scope)) return null\n\tconst selectedVariableParent = insertAfterVariable?.selectedVariableParent\n\tconst arrayVariables = selectedVariableParent\n\t\t? getVariableListFromVariableParent(scope, selectedVariableParent.id)\n\t\t: null\n\tif (selectedVariableParent && !arrayVariables) return null\n\n\tconst trimmedName = options.name.trim()\n\tconst nameWithFallback = trimmedName ? trimmedName : getFallbackNameForCreateVariableOptions(variableOptions)\n\tconst variablesInScope = arrayVariables ?? scope.variables\n\tconst name = useUniqueName ? uniqueVariableName(variablesInScope, nameWithFallback) : nameWithFallback\n\tconst variable = createVariable({ ...variableOptions, name }, getVariableCreationScopeType(scope))\n\n\tif (variable.type === ControlType.EventHandler && !isSmartComponentNode(scope)) {\n\t\treturn null\n\t}\n\n\tif (selectedVariableParent && arrayVariables) {\n\t\tconst selectedVariable = insertAfterVariable?.selectedVariable\n\t\tconst insertionIndexWithinArray = getVariableInsertionIndex(arrayVariables, selectedVariable?.id)\n\t\tassert(isArrayItemVariableDefinition(variable), \"Variable must be an array item variable\")\n\t\tconst newItemVariables = List.insert(arrayVariables, insertionIndexWithinArray, variable)\n\n\t\tupdateVariableListInVariableParent(scope, selectedVariableParent.id, newItemVariables)\n\t} else {\n\t\tconst insertionIndex = getVariableInsertionIndex(scope.variables, insertAfterVariable?.selectedVariable?.id)\n\t\tconst newVariables = List.insert(scope.variables, insertionIndex, variable)\n\t\tscope.set({ variables: newVariables })\n\t}\n\n\tif (isAssigned) {\n\t\ttriggerVariableReferenceCreateEvent({ variableType: variable.type, variableId: variable.id })\n\t}\n\n\treturn createVariableReference(variable.id, scope.id)\n}\n\n/** Returns null if scope doesn't support variables. */\nexport function createVariableInScope(options: CreateVariableInScopeOptions): VariableReference | null {\n\tconst { engine, showEditor = true, ...opts } = options\n\tconst variable = createVariableWithTree(engine.tree, opts)\n\tconst showFieldsPopout = isCollectionNode(engine.tree.get(options.scopeId))\n\tif (!variable) return null\n\n\tconst scope = engine.tree.get(options.scopeId)\n\tif (!scope || !withVariables(scope)) return null\n\n\tif (isVekterEngine(engine) && showEditor) {\n\t\tconst parentId = opts.insertAfterVariable?.selectedVariableParent?.id\n\t\tengine.stores.variablesStore.selectedVariablePath = parentId ? [parentId, variable.id] : [variable.id]\n\n\t\tif (showFieldsPopout) {\n\t\t\t// Reveal the Fields sidebar so the popout can register and open, even when the field is\n\t\t\t// created from a surface where the sidebar isn't already visible (e.g. quick actions)\n\t\t\tengine.stores.chromeStore.activeCollectionPanelTab = CollectionPanelTab.Fields\n\t\t\tengine.floatingWindowPopoutNavigation?.presentPopout(generateVariablePanelPopoutId(variable.id, parentId))\n\t\t} else {\n\t\t\tengine.stores.modalStore.set({ type: ModalType.Variables, source: \"properties\" })\n\t\t}\n\t}\n\n\treturn createVariableReference(variable.id, scope.id)\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { getLogger } from \"@framerjs/shared\"\nimport { eventKeyToDisplayName } from \"document/components/chrome/properties/panels/utils/eventKeyToDisplayName.ts\"\nimport { createVariableWithTree } from \"document/components/chrome/properties/utils/createVariableInScope.ts\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode, isSmartComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withFrameEvents } from \"document/models/CanvasTree/traits/WithFrameEvents.ts\"\nimport type { VariableID } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isPrimaryVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { HardCodedCodeIdentifier } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport type { CodeGenerationStore } from \"document/stores/CodeGenerationStore.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { addActionToEventKey, addActionToReplicaOverrides } from \"../../chrome/properties/utils/eventActions.ts\"\n\nconst log = getLogger(\"createAndAssignActionVariableToNode\")\n\nexport function createAndAssignActionVariableToNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CanvasNode,\n\teventKey: string,\n\t/**\n\t * An optional name for the event trigger variable we create. If it's not given, we will just use the event key.\n\t */\n\tvariableName?: string,\n\t/**\n\t * To trigger code generation of the component after the variable is added. If not provided code generation will not occur immediately.\n\t */\n\tcodeGenerationStore?: CodeGenerationStore,\n): VariableID | null {\n\tif (!(withFrameEvents(node) || isCodeComponentNode(node))) return null\n\n\tconst scopeNode = tree.getScopeNodeFor(node)\n\tif (!scopeNode || !isSmartComponentNode(scopeNode)) return null\n\n\t// Make sure we add the event on the primary node\n\tconst primaryVariant = tree.getGroundNodeFor(node)\n\tif (!primaryVariant || !isPrimaryVariant(primaryVariant)) return null\n\n\tconst triggerEventAction = componentLoader.componentForIdentifier(HardCodedCodeIdentifier.triggerEventAction)\n\tif (!triggerEventAction) return null\n\n\t// Create action variable and assign it to the selected layer\n\tconst variableRef = createVariableWithTree(tree, {\n\t\tscopeId: scopeNode.id,\n\t\ttype: ControlType.EventHandler,\n\t\tname: variableName ?? eventKeyToDisplayName(eventKey, null),\n\t\tinitialValue: undefined,\n\t})\n\n\tif (!variableRef) return null\n\n\t// Add the event to the node in the primary variant\n\taddActionToEventKey(tree, componentLoader, node, eventKey, triggerEventAction, {\n\t\tid: { type: ControlType.String, value: variableRef.id },\n\t})\n\n\t// Go through all top-level variants and check if the same event key is already overridden.\n\t// If yes, we need to add the new action to the overrides.\n\tconst topLevelVariants = scopeNode.getTopLevelReplicaVariants()\n\tfor (const topLevelVariant of topLevelVariants) {\n\t\tconst { overrides } = topLevelVariant.replicaInfo\n\t\tconst nodeOverrides = overrides[node.id]\n\t\tif (!nodeOverrides) continue\n\t\taddActionToReplicaOverrides(tree, componentLoader, topLevelVariant, node.id, eventKey, triggerEventAction, {\n\t\t\tid: { type: ControlType.String, value: variableRef.id },\n\t\t})\n\t}\n\n\tif (codeGenerationStore) {\n\t\tcodeGenerationStore.updateComponent(scopeNode.id).catch(err => log.error(err))\n\t}\n\n\treturn variableRef.id\n}\n", "import { createBoxShadow } from \"document/models/Shadow.ts\"\nimport {\n\tDEFAULT_FLOATING_ALIGNMENT,\n\tDEFAULT_FLOATING_COLLISION_PADDING,\n\tDEFAULT_FLOATING_OFFSET_X,\n\tDEFAULT_FLOATING_OFFSET_Y,\n\tDEFAULT_FLOATING_PLACEMENT,\n} from \"../../traits/WithFloatingPosition.ts\"\nimport { effectPresets } from \"../../traits/WithStyleAppearEffect.ts\"\nimport { floatingZIndex } from \"../../traits/WithZIndex.ts\"\nimport { EffectTrigger } from \"../../traits/utils/EffectTrigger.ts\"\nimport type FrameNode from \"../FrameNode.ts\"\n\nexport const relativeOverlayFrameCreateDefaults = {\n\twidth: 200,\n\theight: 150,\n\tradius: 10,\n\tboxShadows: [\n\t\tcreateBoxShadow({\n\t\t\tx: 0,\n\t\t\ty: 10,\n\t\t\tblur: 20,\n\t\t\tcolor: \"rgba(0,0,0,0.05)\",\n\t\t\tspread: 0,\n\t\t}),\n\t],\n\tfloatingPositionEnabled: true,\n\tfloatingPlacement: DEFAULT_FLOATING_PLACEMENT,\n\tfloatingAlignment: DEFAULT_FLOATING_ALIGNMENT,\n\tfloatingOffsetX: DEFAULT_FLOATING_OFFSET_X,\n\tfloatingOffsetY: DEFAULT_FLOATING_OFFSET_Y,\n\tfloatingCollisionDetection: true,\n\tfloatingCollisionPadding: DEFAULT_FLOATING_COLLISION_PADDING,\n} satisfies Partial<FrameNode>\n\nexport const relativeOverlayPresentationDefaults = {\n\tzIndex: floatingZIndex,\n\tstyleAppearEffectEnabled: true,\n\tstyleAppearEffectTrigger: EffectTrigger.OnMount,\n\toverflow: \"clip\",\n\tposition: \"absolute\",\n\t...effectPresets.fadeIn(),\n} satisfies Partial<FrameNode>\n\nexport const relativeOverlayDefaults = {\n\t...relativeOverlayFrameCreateDefaults,\n\t...relativeOverlayPresentationDefaults,\n} satisfies Partial<FrameNode>\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, assertNever } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { EngineStores } from \"document/EngineStores.ts\"\nimport { addActionToEventKey, eventsForNode } from \"document/components/chrome/properties/utils/eventActions.ts\"\nimport { createAndAssignActionVariableToNode } from \"document/components/tools/utils/createAndAssignActionVariableToNode.ts\"\nimport type { CodeGenerationStore } from \"document/stores/CodeGenerationStore.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport type { CanvasTree } from \"../../CanvasTree.ts\"\nimport type { WithFloatingPosition } from \"../../traits/WithFloatingPosition.ts\"\nimport { hasFloatingPosition } from \"../../traits/WithFloatingPosition.ts\"\nimport { type WithFrameEvents, withFrameEvents } from \"../../traits/WithFrameEvents.ts\"\nimport { isReplicaOrReplicaChild } from \"../../traits/WithTemplate.ts\"\nimport { createTriggerActionWithDefaultTrigger, hasTriggerActions } from \"../../traits/WithTriggerActions.ts\"\nimport { isBreakpointVariant } from \"../../traits/WithVariant.ts\"\nimport { HardCodedCodeIdentifier } from \"../../traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport type { CanvasNode } from \"../CanvasNode.ts\"\nimport type CodeComponentNode from \"../CodeComponentNode.ts\"\nimport FrameNode from \"../FrameNode.ts\"\nimport type { NodeID } from \"../NodeID.ts\"\nimport { OverlayNode } from \"../OverlayNode.ts\"\nimport { isCodeComponentNode, isFrameNode, isOverlayNode } from \"./nodeCheck.ts\"\nimport { relativeOverlayFrameCreateDefaults, relativeOverlayPresentationDefaults } from \"./relativeOverlayDefaults.ts\"\nimport { getSmartComponentForCodeComponent, isLocalSmartComponentInstance } from \"./smartComponentInstanceHelpers.ts\"\n\nfunction getAvailableTriggerKey(componentLoader: ComponentLoader, node: CodeComponentNode) {\n\t// Don't allow pasting/duplicating overlays into code components without free triggers\n\tconst nodeEvents = eventsForNode(componentLoader, node)\n\tconst nodeEventKeys = Object.keys(nodeEvents)\n\tif (nodeEventKeys.length === 0) return undefined\n\n\tfor (const key in nodeEvents) {\n\t\tconst actions = nodeEvents[key]\n\t\tif (actions && actions.length === 0) {\n\t\t\treturn key\n\t\t}\n\t}\n\treturn undefined\n}\n\nfunction createOverlayNode(\n\ttree: CanvasTree,\n\tactionIdentifier: HardCodedCodeIdentifier.showOverlayAction | HardCodedCodeIdentifier.showRelativeOverlayAction,\n\tparentId: NodeID,\n) {\n\tswitch (actionIdentifier) {\n\t\tcase HardCodedCodeIdentifier.showOverlayAction:\n\t\t\treturn tree.create(OverlayNode, parentId)\n\t\tcase HardCodedCodeIdentifier.showRelativeOverlayAction:\n\t\t\treturn tree.create(FrameNode, parentId, { ...relativeOverlayFrameCreateDefaults })\n\t\tdefault:\n\t\t\tassertNever(actionIdentifier)\n\t}\n}\n\nfunction prepareOverlayNode(\n\ttree: CanvasTree,\n\tactionIdentifier: HardCodedCodeIdentifier.showOverlayAction | HardCodedCodeIdentifier.showRelativeOverlayAction,\n\toverlayNode: OverlayNode | (CanvasNode & WithFloatingPosition) | undefined,\n\toriginalParent: CanvasNode,\n) {\n\tif (overlayNode) {\n\t\tassert(\n\t\t\t(actionIdentifier === HardCodedCodeIdentifier.showOverlayAction && isOverlayNode(overlayNode)) ||\n\t\t\t\t(actionIdentifier === HardCodedCodeIdentifier.showRelativeOverlayAction &&\n\t\t\t\t\t(isFrameNode(overlayNode) || isCodeComponentNode(overlayNode))),\n\t\t\t\"Invalid overlay type: \",\n\t\t\toverlayNode.__class,\n\t\t\t\"for overlay action: \",\n\t\t\tactionIdentifier,\n\t\t)\n\t}\n\n\tconst overlay = overlayNode ?? createOverlayNode(tree, actionIdentifier, originalParent.id)\n\n\t// Apply presets to a relative overlay node\n\tif (hasFloatingPosition(overlay)) {\n\t\toverlay.set({ ...relativeOverlayPresentationDefaults })\n\t}\n\n\treturn overlay\n}\n\nfunction createSmartComponentEventAndConnectAction(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tcodeGenerationStore: CodeGenerationStore | undefined,\n\toriginalParent: CanvasNode,\n\teventKey: string,\n\tsetupOverlayActionForVariable: (variableId: string) => void,\n) {\n\tassert(\n\t\tisLocalSmartComponentInstance(originalParent),\n\t\t\"Parent is not a local smart component instance, events can't be created\",\n\t)\n\tconst smartComponentNode = getSmartComponentForCodeComponent(tree, originalParent)\n\ttree.loadScopes([smartComponentNode], ([loadedSmartComponentNode]) => {\n\t\tif (!loadedSmartComponentNode) return\n\n\t\tconst primaryVariant = loadedSmartComponentNode.getPrimaryVariant()\n\t\tassert(primaryVariant, \"SmartComponentNode should have a primary variant\")\n\n\t\tconst variableId = createAndAssignActionVariableToNode(\n\t\t\ttree,\n\t\t\tcomponentLoader,\n\t\t\tprimaryVariant,\n\t\t\teventKey,\n\t\t\teventKey === \"onMouseEnter\" ? Dictionary.Hover : undefined,\n\t\t\tcodeGenerationStore,\n\t\t)\n\t\tassert(variableId, \"Should be able to create event key for local smart component node\")\n\t\tsetupOverlayActionForVariable(variableId)\n\t})\n}\n\nexport function setupOverlayAction(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tactionIdentifier: HardCodedCodeIdentifier.showOverlayAction | HardCodedCodeIdentifier.showRelativeOverlayAction,\n\toverlay: OverlayNode | (CanvasNode & WithFloatingPosition),\n\teventKey: string,\n\toriginalParent: CodeComponentNode | (CanvasNode & WithFrameEvents),\n) {\n\tconst overlayActionDefinition = componentLoader.componentForIdentifier(actionIdentifier)\n\tassert(overlayActionDefinition, \"Cannot find overlay action definition\")\n\taddActionToEventKey(\n\t\ttree,\n\t\tcomponentLoader,\n\t\toriginalParent,\n\t\teventKey,\n\t\toverlayActionDefinition,\n\t\t{\n\t\t\toverlay: { type: ControlType.String, value: overlay.id },\n\t\t},\n\t\ttrue,\n\t)\n}\n\nfunction overlayTypeForAction(\n\taction: HardCodedCodeIdentifier.showOverlayAction | HardCodedCodeIdentifier.showRelativeOverlayAction,\n) {\n\tswitch (action) {\n\t\tcase HardCodedCodeIdentifier.showOverlayAction:\n\t\t\treturn \"fixed\"\n\t\tcase HardCodedCodeIdentifier.showRelativeOverlayAction:\n\t\t\treturn \"relative\"\n\t\tdefault:\n\t\t\tassertNever(action)\n\t}\n}\n\n/**\n * Creates an overlay with a default trigger action if the parent is a breakpoint variant, otherwise creates an overlay with a default event action.\n * If an overlayNode is provided, it will be used instead of creating a new one. If required a default trigger action will be added to it.\n */\nexport function createOverlayWithEventOrTriggerAction(\n\tcomponentLoader: ComponentLoader,\n\tstores: Pick<EngineStores, \"treeStore\" | \"codeGenerationStore\">,\n\tactionIdentifier: HardCodedCodeIdentifier.showOverlayAction | HardCodedCodeIdentifier.showRelativeOverlayAction,\n\toverlayTriggerId: NodeID,\n\toverlayNode?: OverlayNode | (CanvasNode & WithFloatingPosition),\n) {\n\tconst parent = stores.treeStore.tree.get(overlayTriggerId)\n\tif (!parent) return\n\tconst originalParent = isReplicaOrReplicaChild(parent) ? stores.treeStore.tree.get(parent.originalid) : parent\n\tif (!originalParent) return\n\n\tif (isBreakpointVariant(originalParent)) {\n\t\treturn createOverlayWithTriggerAction(stores, actionIdentifier, overlayTriggerId, overlayNode)\n\t}\n\treturn createOverlayWithEvent(componentLoader, stores, actionIdentifier, overlayTriggerId, overlayNode)\n}\n\nexport function createOverlayWithEvent(\n\tcomponentLoader: ComponentLoader,\n\t{ treeStore, codeGenerationStore }: Pick<EngineStores, \"treeStore\" | \"codeGenerationStore\">,\n\tactionIdentifier: HardCodedCodeIdentifier.showOverlayAction | HardCodedCodeIdentifier.showRelativeOverlayAction,\n\toverlayTriggerId: NodeID,\n\toverlayNode?: OverlayNode | (CanvasNode & WithFloatingPosition),\n) {\n\tconst parent = treeStore.tree.get(overlayTriggerId)\n\tif (!parent) return\n\tconst originalParent = isReplicaOrReplicaChild(parent) ? treeStore.tree.get(parent.originalid) : parent\n\tif (!originalParent) return\n\tif (!withFrameEvents(originalParent) && !isCodeComponentNode(originalParent)) return\n\n\tconst defaultEventKey =\n\t\tactionIdentifier === HardCodedCodeIdentifier.showRelativeOverlayAction ? \"onMouseEnter\" : \"onTap\"\n\tconst availableTriggerKey = isCodeComponentNode(originalParent)\n\t\t? getAvailableTriggerKey(componentLoader, originalParent)\n\t\t: defaultEventKey\n\tconst canCreateAvailableTriggerKey = isLocalSmartComponentInstance(originalParent)\n\n\tif (!availableTriggerKey && !canCreateAvailableTriggerKey) return\n\n\tconst overlay = prepareOverlayNode(treeStore.tree, actionIdentifier, overlayNode, originalParent)\n\n\tif (!availableTriggerKey) {\n\t\t// we don't have a trigger key but we do need one, so create it and connect the action\n\t\t// this is possibly async because the smart component scope may not be loaded yet\n\t\tcreateSmartComponentEventAndConnectAction(\n\t\t\ttreeStore.tree,\n\t\t\tcomponentLoader,\n\t\t\tcodeGenerationStore,\n\t\t\toriginalParent,\n\t\t\tdefaultEventKey,\n\t\t\tvariableId =>\n\t\t\t\tsetupOverlayAction(treeStore.tree, componentLoader, actionIdentifier, overlay, variableId, originalParent),\n\t\t)\n\t} else {\n\t\tsetupOverlayAction(\n\t\t\ttreeStore.tree,\n\t\t\tcomponentLoader,\n\t\t\tactionIdentifier,\n\t\t\toverlay,\n\t\t\tavailableTriggerKey ?? defaultEventKey,\n\t\t\toriginalParent,\n\t\t)\n\t}\n\n\trecord(\"overlay_create\", {\n\t\tsource: overlayNode ? \"duplicate\" : \"events_panel\",\n\t\toverlayType: overlayTypeForAction(actionIdentifier),\n\t\ttriggerType: isBreakpointVariant(originalParent)\n\t\t\t? \"breakpoint\"\n\t\t\t: isCodeComponentNode(originalParent)\n\t\t\t\t? \"component\"\n\t\t\t\t: \"frame\",\n\t})\n\n\treturn overlay\n}\n\n/**\n * Creates a new overlay without an event action on the parent and adds a default trigger action to the overlay.\n * If an overlayNode is provided, it will be used instead of creating a new one, a trigger action will only be added if none are present.\n */\nexport function createOverlayWithTriggerAction(\n\t{ treeStore }: Pick<EngineStores, \"treeStore\">,\n\tactionIdentifier: HardCodedCodeIdentifier.showOverlayAction | HardCodedCodeIdentifier.showRelativeOverlayAction,\n\toverlayTriggerId: NodeID,\n\toverlayNode?: OverlayNode | (CanvasNode & WithFloatingPosition),\n) {\n\tconst parent = treeStore.tree.get(overlayTriggerId)\n\tif (!parent) return\n\tconst originalParent = isReplicaOrReplicaChild(parent) ? treeStore.tree.get(parent.originalid) : parent\n\tif (!originalParent) return\n\tif (!withFrameEvents(originalParent) && !isCodeComponentNode(originalParent)) return\n\n\tconst overlay = prepareOverlayNode(treeStore.tree, actionIdentifier, overlayNode, originalParent)\n\n\tif (!hasTriggerActions(overlay)) {\n\t\toverlay.set({\n\t\t\ttriggerActions: [createTriggerActionWithDefaultTrigger({ type: \"showOverlay\" })],\n\t\t})\n\n\t\trecord(\"trigger_actions_create\", {\n\t\t\tactionType: \"showOverlay\",\n\t\t\ttriggerCount: 1,\n\t\t})\n\t}\n\n\trecord(\"overlay_create\", {\n\t\tsource: overlayNode ? \"duplicate\" : \"events_panel\",\n\t\toverlayType: overlayTypeForAction(actionIdentifier),\n\t\ttriggerType: isBreakpointVariant(originalParent)\n\t\t\t? \"breakpoint\"\n\t\t\t: isCodeComponentNode(originalParent)\n\t\t\t\t? \"component\"\n\t\t\t\t: \"frame\",\n\t})\n\n\treturn overlay\n}\n", "import type { Draft } from \"@framerjs/app-shared/src/lib/immer.ts\"\nimport { produce } from \"@framerjs/app-shared/src/lib/immer.ts\"\nimport { ModuleType } from \"@framerjs/shared\"\nimport type { RelativeFilePath, TypeSlashName } from \"./types.ts\"\nimport { normalizePath } from \"./utils.ts\"\n\n/**\n * The main function of this data structure is to maintain the state of relationship between the modules,\n * it can be able to efficiently find the modules that should be updated when a specific module is updated,\n * which is the list of the module's dependents including transitive ones.\n */\nexport type DependencyGraph = Readonly<Record<TypeSlashName, DependencyGraphNode | undefined>>\n\ninterface DependencyGraphNode {\n\treadonly dependents: Set<TypeSlashName>\n\treadonly dependencies: Set<TypeSlashName>\n}\n\nexport function createDependencyGraph(nodes: readonly [TypeSlashName, readonly RelativeFilePath[]][]): DependencyGraph {\n\tconst depsGraph: DependencyGraph = {}\n\tfor (const [modulePath, dependencies] of nodes) {\n\t\tupsertNodeInternal(depsGraph, modulePath, dependencies)\n\t}\n\treturn depsGraph\n}\n\nexport function upsertNode(\n\tdepsGraph: DependencyGraph,\n\tmoduleTypeSlashName: TypeSlashName,\n\tdependencies: readonly RelativeFilePath[],\n): DependencyGraph {\n\treturn produce(depsGraph, draftState => {\n\t\tupsertNodeInternal(draftState, moduleTypeSlashName, dependencies)\n\t})\n}\n\nexport function deleteNode(depsGraph: DependencyGraph, moduleTypeSlashName: TypeSlashName): DependencyGraph {\n\tif (!depsGraph[moduleTypeSlashName]) return depsGraph\n\n\treturn produce(depsGraph, draftState => {\n\t\tconst node = draftState[moduleTypeSlashName]\n\t\tif (!node) return\n\n\t\tfor (const dependentPath of node.dependents) {\n\t\t\tconst dependent = draftState[dependentPath]\n\t\t\tif (!dependent) continue\n\n\t\t\tdependent.dependencies.delete(moduleTypeSlashName)\n\n\t\t\t// Remove the dependent node incase we just deleted its last dependency.\n\t\t\tif (isEmpty(dependent)) {\n\t\t\t\tdelete draftState[dependentPath]\n\t\t\t}\n\t\t}\n\n\t\tfor (const dependencyPath of node.dependencies) {\n\t\t\tconst dependency = draftState[dependencyPath]\n\t\t\tif (!dependency) continue\n\n\t\t\tdependency.dependents.delete(moduleTypeSlashName)\n\n\t\t\t// Remove the dependency node incase we just deleted its last dependency.\n\t\t\tif (isEmpty(dependency)) {\n\t\t\t\tdelete draftState[dependencyPath]\n\t\t\t}\n\t\t}\n\n\t\tdelete draftState[moduleTypeSlashName]\n\t})\n}\n\nexport function collectModuleAndItsDependentsRecursively(\n\tdependencyGraph: DependencyGraph,\n\tmoduleName: TypeSlashName,\n\tdependentModules: Set<TypeSlashName>,\n\tpriorityModules: Set<TypeSlashName>,\n\tpriorityDependentModules: Set<TypeSlashName>,\n): void\nexport function collectModuleAndItsDependentsRecursively(\n\tdependencyGraph: DependencyGraph,\n\tdependentModules: TypeSlashName,\n\tcollectedModules: Set<TypeSlashName>,\n): void\nexport function collectModuleAndItsDependentsRecursively(\n\tdependencyGraph: DependencyGraph,\n\tmoduleName: TypeSlashName,\n\tdependentModules: Set<TypeSlashName>,\n\tpriorityModules?: Set<TypeSlashName>,\n\tpriorityDependentModules?: Set<TypeSlashName>,\n): void {\n\tconst visited = new Set<TypeSlashName>()\n\tconst stack = [moduleName]\n\tpriorityModules = priorityModules || new Set()\n\tpriorityDependentModules = priorityDependentModules || new Set()\n\twhile (stack.length > 0) {\n\t\tconst currentModule = stack.pop()\n\t\tif (!currentModule) continue\n\t\tif (visited.has(currentModule)) continue\n\t\tvisited.add(currentModule)\n\n\t\tconst currentNode = dependencyGraph[currentModule]\n\t\tif (!currentNode) continue\n\n\t\tif (priorityModules.has(currentModule)) {\n\t\t\tpriorityDependentModules.add(currentModule)\n\t\t} else if (!priorityModules.size) {\n\t\t\tdependentModules.add(currentModule)\n\t\t} else {\n\t\t\tlet isPriority = false\n\t\t\tfor (const dependent of currentNode.dependents) {\n\t\t\t\tif (priorityModules.has(dependent) || priorityDependentModules.has(dependent)) {\n\t\t\t\t\tisPriority = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isPriority) {\n\t\t\t\tpriorityDependentModules.add(currentModule)\n\t\t\t} else {\n\t\t\t\tdependentModules.add(currentModule)\n\t\t\t}\n\t\t}\n\n\t\tfor (const dependent of currentNode.dependents) {\n\t\t\tif (visited.has(dependent)) continue\n\n\t\t\tstack.push(dependent)\n\t\t}\n\t}\n}\n\nexport function hasCircularImports(depsGraph: DependencyGraph, moduleTypeSlashName: TypeSlashName): boolean {\n\t// Perform a breadth-first scan of the dependency graph to discover circular imports.\n\tconst imports = new Set<TypeSlashName>()\n\tconst queue = [moduleTypeSlashName]\n\twhile (isNotEmpty(queue)) {\n\t\tconst nodeKey = queue.shift()\n\t\tconst node = depsGraph[nodeKey]\n\t\tif (!node) continue\n\t\tfor (const dependentKey of node.dependents) {\n\t\t\tif (imports.has(dependentKey)) continue\n\t\t\timports.add(dependentKey)\n\t\t\tqueue.push(dependentKey)\n\t\t}\n\t\tif (imports.has(moduleTypeSlashName)) {\n\t\t\t// We discovered a circular import.\n\t\t\t// TODO: It would be nice to calculate the shortest cycle path and return it.\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunction getDependencyCanonicalPath(\n\tdependency: RelativeFilePath,\n\tmoduleTypeSlashName: TypeSlashName,\n): TypeSlashName | undefined {\n\tconst normalizedPath = normalizePath(dependency, moduleTypeSlashName)\n\tif (!normalizedPath) return\n\n\t// If the dependency is a collection module, use its draft collection version as the dependency\n\t// unless the importing module is already a draft collection or collection itself\n\tif (normalizedPath.startsWith(ModuleType.Collection)) {\n\t\tif (\n\t\t\t!moduleTypeSlashName.startsWith(ModuleType.Collection) &&\n\t\t\t!moduleTypeSlashName.startsWith(ModuleType.DraftCollection)\n\t\t) {\n\t\t\treturn normalizedPath.replace(ModuleType.Collection, ModuleType.DraftCollection)\n\t\t}\n\t}\n\n\treturn normalizedPath\n}\n\nfunction upsertNodeInternal(\n\tdraftState: Draft<DependencyGraph>,\n\tmoduleTypeSlashName: TypeSlashName,\n\tdependencies: readonly RelativeFilePath[],\n): void {\n\tlet node = draftState[moduleTypeSlashName]\n\tif (!node) {\n\t\tif (dependencies.length === 0) return\n\t\tnode = createAndSetNode(draftState, moduleTypeSlashName)\n\t}\n\n\tconst outdatedDependencies = new Set(node.dependencies)\n\n\t// Add the dependencies as nodes to the graph and add the module as a dependent to all of them.\n\tfor (const dependency of dependencies) {\n\t\tconst dependencyCanonicalPath = getDependencyCanonicalPath(dependency, moduleTypeSlashName)\n\t\tif (!dependencyCanonicalPath) continue\n\n\t\tnode.dependencies.add(dependencyCanonicalPath)\n\n\t\tlet dependencyNode = draftState[dependencyCanonicalPath]\n\t\tif (!dependencyNode) {\n\t\t\tdependencyNode = createAndSetNode(draftState, dependencyCanonicalPath)\n\t\t}\n\n\t\tdependencyNode.dependents.add(moduleTypeSlashName)\n\t\tnode.dependencies.add(dependencyCanonicalPath)\n\t\toutdatedDependencies.delete(dependencyCanonicalPath)\n\t}\n\n\t// Clean up the outdated dependencies' state.\n\tfor (const outdatedDependencyPath of outdatedDependencies) {\n\t\tconst outdatedDependency = draftState[outdatedDependencyPath]\n\t\tif (!outdatedDependency) continue\n\n\t\toutdatedDependency.dependents.delete(moduleTypeSlashName)\n\n\t\t// Remove the dependent node incase we just deleted its last dependency.\n\t\tif (isEmpty(outdatedDependency)) {\n\t\t\tdelete draftState[outdatedDependencyPath]\n\t\t}\n\t}\n\n\t// Remove node itself if it became empty.\n\tif (isEmpty(node)) {\n\t\tdelete draftState[moduleTypeSlashName]\n\t}\n}\n\nfunction isEmpty(node: DependencyGraphNode): boolean {\n\treturn node.dependents.size === 0 && node.dependencies.size === 0\n}\n\nfunction createAndSetNode(draftState: Draft<DependencyGraph>, typeSlashName: string): DependencyGraphNode {\n\tconst node: DependencyGraphNode = {\n\t\tdependents: new Set(),\n\t\tdependencies: new Set(),\n\t}\n\tdraftState[typeSlashName] = node\n\treturn node\n}\n\nfunction isNotEmpty<T>(arr: T[]): arr is { shift(): T } & T[] {\n\treturn arr.length > 0\n}\n", "// This version tracks compatibility of web pages and smart components with the\n\nimport { ModuleType } from \"@framerjs/shared\"\nimport type { PersistedModule } from \"modules/ModulesStorage.ts\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport { getTypeSlashName, normalizePath } from \"modules/utils.ts\"\nimport { isNumber, isString } from \"utils/typeChecks.ts\"\n\n/**\n * This version tracks compatibility of web pages and smart components with the\n * CMS. Version 1 means that the module is using the `useQueryData` hook.\n * IMPORTANT: This mechanism should be used sparingly. In general the CMS should\n * be backwards compatible with all previous versions of web pages but this\n * wasn't possible before the `useQueryData` hook was introduced.\n */\nexport const currentCmsVersion = 1\n\nexport function supportsCmsImports(type: ModuleType | string) {\n\treturn type === ModuleType.Screen || type === ModuleType.Canvas\n}\n\nexport function getCompatibleCmsVersion(module: PersistedModule) {\n\tconst version = module.metadata[ModuleMetadata.CompatibleCmsVersion]\n\treturn isNumber(version) ? version : 0\n}\n\nfunction hasCmsImport(module: PersistedModule) {\n\tconst typeSlashName = getTypeSlashName(module)\n\n\treturn module.imports.relative.some(importSpecifier => {\n\t\tconst path = normalizePath(importSpecifier, typeSlashName)\n\t\treturn isString(path) && path.startsWith(ModuleType.Collection)\n\t})\n}\n\nexport function hasCmsDependency(module: PersistedModule) {\n\treturn supportsCmsImports(module.type) && hasCmsImport(module)\n}\n\nexport function needsUpdateToBeCompatibleWithCms(module: PersistedModule) {\n\treturn hasCmsDependency(module) && getCompatibleCmsVersion(module) < currentCmsVersion\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { LocalModuleId, ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, ModuleType, localModuleIdForStableName, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { type TemplateFilter, parseTemplateVariableContents } from \"@framerjs/shared/src/custom-code/templateFilters.ts\"\nimport { getTemplateVariableNameRegex } from \"@framerjs/shared/src/custom-code/templateVariableRegexes.ts\"\nimport type { CustomCodePlacement, Snippet } from \"@framerjs/shared/src/custom-code/types.ts\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js, jst } from \"code-generation/js/js.ts\"\nimport { SafeJS, SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport { PreloadCollector } from \"code-generation/loader/PreloadCollector.ts\"\nimport type { MakeSerializable } from \"code-generation/types.ts\"\nimport { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport { FetchDataCollector } from \"code-generation/utils/FetchDataCollector.ts\"\nimport { ImportCollector, moduleImportSpecifiers } from \"code-generation/utils/ImportCollector.ts\"\nimport { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport { InlineLocalizedValueCollector } from \"code-generation/utils/LocalizedValueCollector.ts\"\nimport { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport { ValueTransformCollector } from \"code-generation/utils/valueTransformCollector/ValueTransformCollector.ts\"\nimport {\n\tgetQueryDefaultCollectionAlias,\n\tgetQueryFrom,\n\tgetQuerySelect,\n} from \"code-generation/utils/valueTransformCollector/getQueryForDataRepeater.ts\"\nimport type {\n\tCanvasTree,\n\tCustomCodeNode,\n\tCustomCodeScopeNode,\n\tShallowWebPageNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { VariableProviderControlMap } from \"document/models/CanvasTree/traits/VariableProvider.ts\"\nimport { createVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { VariableID } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { getFallbackValue } from \"document/models/CanvasTree/traits/utils/codeComponentProps.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport type { Query } from \"library/modules/cms/types.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isNullish } from \"utils/typeChecks.ts\"\nimport { sourceCodeSerializer } from \"./GeneratedComponent.ts\"\n\nconst PARAMS_VAR = js`params`\nconst SNIPPETS_VAR = js`snippets`\nconst QUERY_LOADERS_VAR = js`queryLoaders`\nconst SNIPPETS_SORTING_VAR = js`snippetsSorting`\nconst PATH_VARIABLES_ARG = js`pathVariables`\nconst ACTIVE_LOCALE_ARG = js`activeLocale`\n\n// Not using the LocalModuleIdentifier from @framerjs/shared, because its\n// type property is a string, whereas most module APIs require a ModuleType.\n// See: https://github.com/framer/FramerStudio/pull/12059#discussion_r916913314\ninterface SnippetsModuleIdentifier {\n\treadonly type: ModuleType\n\treadonly localIdName: string\n\treadonly localId: LocalModuleId\n}\n\nexport const snippetsModuleIdentifier: SnippetsModuleIdentifier = {\n\ttype: ModuleType.Snippets,\n\tlocalIdName: \"snippets\",\n\tlocalId: localModuleIdForStableName(ModuleType.Snippets, \"snippets\"),\n}\n\nexport const generateSnippetsModule = sourceCodeSerializer<CustomCodeScopeNode>(async (node, dependencies) => {\n\tconst { componentLoader, tree, modulesStore, assetMap } = dependencies\n\tconst assets = new AssetCollector(assetMap)\n\tconst bindings = new BindingCollector()\n\tconst imports = new ImportCollector(ModuleType.Snippets, componentLoader, modulesStore, bindings)\n\tconst variables = new VariableCollector(node, bindings)\n\tconst declarations = new FileDeclarationCollector(bindings)\n\tconst links = new LinkCollector(node, componentLoader, imports, bindings, undefined, tree, modulesStore)\n\tconst preload = new PreloadCollector(node, tree, variables, declarations, bindings, imports, assets)\n\tconst fetches = new FetchDataCollector(bindings, variables, preload, assets, links)\n\tconst localizedValues = new InlineLocalizedValueCollector(\n\t\tnode,\n\t\tvariables,\n\t\ttree,\n\t\tcomponentLoader,\n\t\timports,\n\t\tbindings,\n\t\tdeclarations,\n\t\tfetches,\n\t\tmodulesStore,\n\t\tModuleType.Snippets,\n\t)\n\tconst valueTransforms = new ValueTransformCollector(\n\t\tcomponentLoader,\n\t\tdeclarations,\n\t\tundefined,\n\t\timports,\n\t\tvariables,\n\t\tlocalizedValues,\n\t\tundefined,\n\t\tfetches,\n\t\tmodulesStore,\n\t\tModuleType.Snippets,\n\t)\n\n\tconst customCodeNodes: CustomCodeNode[] = []\n\tconst snippetsSorting: Record<CustomCodePlacement, string[]> = {\n\t\theadStart: [],\n\t\theadEnd: [],\n\t\tbodyStart: [],\n\t\tbodyEnd: [],\n\t}\n\n\tfor (const customCodeNode of node.children) {\n\t\tif (customCodeNode.disabled) continue\n\n\t\tsnippetsSorting[customCodeNode.placement].push(customCodeNode.id)\n\n\t\tif ((customCodeNode.pageIds && customCodeNode.pageIds.length > 0) || customCodeNode.loadMode === \"always\") {\n\t\t\tcustomCodeNodes.push(customCodeNode)\n\t\t}\n\t}\n\n\treturn [\n\t\t{\n\t\t\ttype: ModuleType.Snippets,\n\t\t\trevision: node.moduleSourceRevision,\n\t\t\tsource: serializeSnippetsModule(\n\t\t\t\tcustomCodeNodes,\n\t\t\t\tsnippetsSorting,\n\t\t\t\tmodulesStore,\n\t\t\t\ttree,\n\t\t\t\tcomponentLoader,\n\t\t\t\timports,\n\t\t\t\tdeclarations,\n\t\t\t\tvalueTransforms,\n\t\t\t\tvariables,\n\t\t\t),\n\t\t\tartifacts: { assets: assets.keys },\n\t\t},\n\t]\n})\n\nfunction serializeSnippetsModule(\n\tcustomCodeNodes: CustomCodeNode[],\n\tsnippetsSorting: Record<CustomCodePlacement, string[]>,\n\tmodulesStore: ModulesStore,\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\timports: ImportCollector,\n\tdeclarations: FileDeclarationCollector,\n\tvalueTransforms: ValueTransformCollector,\n\tvariables: VariableCollector,\n) {\n\tconst { pageIds, snippets } = serializeCustomCodeNodes(\n\t\tcustomCodeNodes,\n\t\ttree,\n\t\tcomponentLoader,\n\t\tvalueTransforms,\n\t\tvariables,\n\t)\n\n\tconst queryCode = serializeQueryLoaders(pageIds, modulesStore, tree, componentLoader, imports, variables)\n\n\tconst getSnippetsFunction = serializeGetSnippetsFunction()\n\n\tconst module = js.joinLines(\n\t\tsnippets,\n\t\tqueryCode,\n\t\tjs`export const ${SNIPPETS_SORTING_VAR} = ${snippetsSorting}`,\n\t\tgetSnippetsFunction,\n\t)\n\n\treturn js.joinSections(js.linesFrom(imports.statements), ...declarations.list(), module)\n}\n\nfunction serializeGetSnippetsFunction() {\n\treturn js`export async function getSnippets(pageId, ${PATH_VARIABLES_ARG}, ${ACTIVE_LOCALE_ARG}) {${js.joinLines(\n\t\tjs`const queryLoader = ${QUERY_LOADERS_VAR}[pageId]`,\n\t\tjs`const ${PARAMS_VAR} = queryLoader ? await queryLoader(${PATH_VARIABLES_ARG}, ${ACTIVE_LOCALE_ARG}) : undefined`,\n\n\t\tjs`const result = ${{ headStart: [], headEnd: [], bodyStart: [], bodyEnd: [] }}`,\n\t\tjs`for (const snippet of ${SNIPPETS_VAR}) {${js.joinLines(\n\t\t\t// Check for existence of pageIds, because it's possible to have snippets without pageIds (e.g. always load mode)\n\t\t\tjs`if (snippet.pageIds && !snippet.pageIds.has(pageId)) continue`,\n\n\t\t\tjs`const code = snippet.code(${PARAMS_VAR})`,\n\t\t\tjs`if (code) {${js.joinLines(js`result[snippet.placement].push({ ...snippet, code })`)}}`,\n\t\t)}}`,\n\t\tjs`return result`,\n\t)}}`\n}\n\n/**\n * This is the internal representation of the snippet.\n * During serialization `pageIds` becomes a real Set<string>.\n * Then while building the `loadSnippets` function result, the `code` is replaced by its result.\n */\ninterface SnippetItem extends Omit<Snippet, \"pageIds\" | \"code\"> {\n\tpageIds?: SafeJS\n\tcode: SafeJS\n}\n\nfunction serializeCustomCodeNodes(\n\tcustomCodeNodes: CustomCodeNode[],\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tvalueTransforms: ValueTransformCollector,\n\tvariables: VariableCollector,\n) {\n\tconst allPageIds = new Set<string>()\n\n\tconst items: MakeSerializable<SnippetItem>[] = []\n\tfor (const node of customCodeNodes) {\n\t\t// Strips any pages that aren't in the tree anymore and weren't removed before\n\t\tconst validPageIds = node.pageIds?.filter(pageId => tree.get(pageId))\n\t\tconst pageIds = validPageIds && validPageIds.length > 0 ? validPageIds : undefined\n\n\t\t// This is the case where the node had pageIDs attached to it, but none of them are in the tree anymore\n\t\t// So we need to skip this node\n\t\tif (node.pageIds && node.pageIds.length > 0 && !pageIds) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst name = node.resolveValue(\"name\")\n\t\tconst replacedCode = replaceCodeVariables(node, tree, componentLoader, valueTransforms, variables, \"escape\")\n\n\t\t// If we have replaced code, means that it's a CMS page snippet.\n\t\t// Which also means that it has only one pageId.\n\t\t// Then it will be added to the pageIds set, to later be used in the CMS query loaders.\n\t\tif (replacedCode && node.pageIds && node.pageIds[0]) {\n\t\t\tallPageIds.add(node.pageIds[0])\n\t\t}\n\n\t\tconst code = replacedCode ?? js`return ${node.code}`\n\n\t\titems.push({\n\t\t\tid: node.id,\n\t\t\tname,\n\t\t\tloadMode: node.loadMode,\n\t\t\tplacement: node.placement,\n\t\t\tpageIds: pageIds ? js`new Set(${pageIds})` : undefined,\n\t\t\tcode: js`(${PARAMS_VAR}) => { ${code} }`,\n\t\t})\n\t}\n\n\tconst result = js`const ${SNIPPETS_VAR} = ${items}`\n\n\treturn {\n\t\tpageIds: allPageIds,\n\t\tsnippets: result,\n\t}\n}\n\n/**\n * Creates the code snippet function.\n * It replaces CMS variable templates with the according JS replacement code.\n * The output function will expect the `data` from CMS query result as the argument.\n *\n * The template variables are collected based on the `pageId` so that we can collect all variables that are present in all snippets related to the page.\n * This way we can build only one query for the given page and provide that data to all snippets.\n */\nfunction replaceCodeVariables(\n\tnode: CustomCodeNode,\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tvalueTransforms: ValueTransformCollector,\n\tvariables: VariableCollector,\n\tdefaultFilter?: TemplateFilter,\n) {\n\t// Variable control map will only be used for CMS template variables\n\t// which we only support custom code nodes with one page in that case.\n\tif (!node.pageIds || node.pageIds.length !== 1) return\n\n\t// We need to retrieve the CMS page, so that we know which collection we need to query.\n\tconst pageId = node.pageIds[0]\n\tif (!pageId) return\n\n\tconst { pageNode, controlMap, collectionData } = getPageData(pageId, tree, componentLoader)\n\tif (!pageNode?.dataIdentifier || !controlMap || !collectionData) return\n\n\t// Convert {{ <field_id> }} to escaped JS code\n\tconst result = replaceTemplateVariables(pageNode, node.code, valueTransforms, variables, controlMap, defaultFilter)\n\tif (!result) return\n\n\tconst variableIds = variables.getBindings(pageId)\n\t// The variables are collected in `replaceTemplateVariables` function, if there are no variables, there's no need to do anything here.\n\tif (!variableIds) return\n\n\tconst variableDeclarations: SafeJS[] = []\n\tfor (const [variableId, variableBinding] of variableIds ?? []) {\n\t\tlet variableValue = js`${PARAMS_VAR}?.[${variableId}]`\n\n\t\tconst control = controlMap?.get(variableId)\n\t\tif (control?.type === ControlType.Enum) {\n\t\t\tconst transformedValue = valueTransforms.wrapInValueTransform(\n\t\t\t\tvariableValue,\n\t\t\t\t{ name: \"enumToDisplayName\" },\n\t\t\t\tcontrol,\n\t\t\t)\n\t\t\tvariableValue = js`${variableValue} !== undefined ? ${transformedValue} : undefined`\n\t\t} else if (control) {\n\t\t\tconst fallbackValue = getFallbackValue(control.type)\n\t\t\tif (isSerializableValue(fallbackValue)) {\n\t\t\t\tvariableValue = js`${variableValue} ?? ${fallbackValue}`\n\t\t\t}\n\t\t}\n\n\t\tvariableDeclarations.push(js`const ${variableBinding} = ${variableValue}`)\n\t}\n\n\treturn js.joinLines(...variableDeclarations, js`return ${result}`)\n}\n\nfunction serializeQueryLoaders(\n\tpageIds: Set<string>,\n\tmodulesStore: ModulesStore,\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\timports: ImportCollector,\n\tvariables: VariableCollector,\n) {\n\tconst queryLoaderItems: Record<string, SafeJS> = {}\n\tfor (const pageId of pageIds) {\n\t\tconst bindings = variables.getBindings(pageId)\n\t\t// If there are no variables collected for that page, we don't need to write a query loader for it.\n\t\tif (!bindings) continue\n\n\t\tconst variableIds = new Set(bindings.keys())\n\n\t\tconst { pageNode, collectionData, controlMap } = getPageData(pageId, tree, componentLoader)\n\t\tif (!pageNode?.dataIdentifier || !controlMap || !collectionData) continue\n\n\t\tconst queryFn = getCMSQuery(\n\t\t\tpageNode,\n\t\t\tpageNode?.dataIdentifier,\n\t\t\tvariableIds,\n\t\t\timports,\n\t\t\tcomponentLoader,\n\t\t\tmodulesStore,\n\t\t\tcontrolMap,\n\t\t)\n\t\tqueryLoaderItems[pageId] = queryFn\n\t}\n\n\tif (Object.keys(queryLoaderItems).length > 0) {\n\t\tconst QueryEngine = imports.addImport(\"framer\", {\n\t\t\texportSpecifier: \"QueryEngine\",\n\t\t})\n\n\t\treturn js.joinLines(\n\t\t\tjs`const queryEngine = new ${QueryEngine}()`,\n\t\t\tjs`const ${QUERY_LOADERS_VAR} = ${queryLoaderItems}`,\n\t\t)\n\t}\n\n\treturn js`const ${QUERY_LOADERS_VAR} = {}`\n}\n\nfunction getPageData(pageId: string, tree: CanvasTree, componentLoader: ComponentLoader) {\n\tconst pageNode = tree.getNodeWithTrait(pageId, isWebPageNode)\n\tconst controlMap = pageNode?.getProvidedControlMap(tree, undefined, componentLoader, componentLoader.activeBundleHash)\n\tconst collectionData = componentLoader.dataForIdentifier(pageNode?.dataIdentifier)\n\n\treturn {\n\t\tpageNode,\n\t\tcontrolMap,\n\t\tcollectionData,\n\t}\n}\n\nfunction getCMSQuery(\n\tpageNode: ShallowWebPageNode,\n\tpageDataIdentifier: ModuleExportIdentifierString,\n\tvariableIds: Set<VariableID>,\n\tmoduleImports: ImportCollector,\n\tcomponentLoader: ComponentLoader,\n\tmodulesStore: ModulesStore,\n\tcontrolMap: VariableProviderControlMap,\n) {\n\tconst getWhereExpressionFromPathVariables = moduleImports.addImport(\"framer\", {\n\t\texportSpecifier: \"getWhereExpressionFromPathVariables\",\n\t})\n\n\tconst defaultCollectionAlias = getQueryDefaultCollectionAlias(pageNode)\n\tconst queriedVariableIds = new Set<VariableID>()\n\n\tconst asyncImports: SafeJS[] = []\n\tconst resolveCollection = getCollectionResolver(componentLoader, modulesStore, asyncImports)\n\n\tconst querySelect = getQuerySelect(\n\t\tcontrolMap,\n\t\tvariableIds,\n\t\tqueriedVariableIds,\n\t\tdefaultCollectionAlias,\n\t\tresolveCollection,\n\t)\n\n\tconst queryFrom = getQueryFrom(\n\t\tpageDataIdentifier,\n\t\tcontrolMap,\n\t\tqueriedVariableIds,\n\t\tdefaultCollectionAlias,\n\t\tresolveCollection,\n\t)\n\n\tconst query = new SerializableObject({\n\t\tfrom: queryFrom,\n\t\tselect: querySelect,\n\t\twhere: SafeJS.fn(getWhereExpressionFromPathVariables, js`pathVariables`, defaultCollectionAlias),\n\t} as MakeSerializable<Query>)\n\n\tconst queryFn = js.joinLines(\n\t\tjs`async (${PATH_VARIABLES_ARG}, ${ACTIVE_LOCALE_ARG}) => {${js.joinLines(\n\t\t\t...asyncImports,\n\t\t\tjs`const query = ${query}`,\n\t\t\tjs`const result = await queryEngine.query(query, ${ACTIVE_LOCALE_ARG})`,\n\t\t\tjs`if (result.length === 0) throw new Error(\"No data matches pathVariables\")`,\n\t\t\tjs`return result[0]`,\n\t\t)}}`,\n\t)\n\n\treturn queryFn\n}\n\nfunction getCollectionResolver(componentLoader: ComponentLoader, modulesStore: ModulesStore, asyncImports: SafeJS[]) {\n\tconst importedCollections = new Map<ModuleExportIdentifierString, SafeJS>()\n\n\treturn function resolveCollection(dataIdentifier: ModuleExportIdentifierString) {\n\t\tconst existing = importedCollections.get(dataIdentifier)\n\t\tif (existing) return existing\n\n\t\tconst identifier = parseModuleIdentifier(dataIdentifier)\n\t\tconst { exportSpecifier, importBinding, importSpecifier } = moduleImportSpecifiers(\n\t\t\tidentifier,\n\t\t\tModuleType.Snippets,\n\t\t\tcomponentLoader,\n\t\t\tmodulesStore,\n\t\t)\n\t\tassert(importBinding, \"Can't import collection\")\n\n\t\tconst binding = new SafeJS(importBinding)\n\t\tconst exportBinding = new SafeJS(exportSpecifier)\n\n\t\tasyncImports.push(js`const ${binding} = await import(${importSpecifier})`)\n\n\t\t// Will become `Collection.default`\n\t\tconst result = js`${binding}.${exportBinding}`\n\t\timportedCollections.set(dataIdentifier, result)\n\t\treturn result\n\t}\n}\n\n/**\n * Replace all instances of template variables with the equivalent SafeJS code.\n */\nfunction replaceTemplateVariables(\n\tnode: ShallowWebPageNode,\n\tvalue: string | null | undefined,\n\tvalueTransforms: ValueTransformCollector,\n\tvariables: VariableCollector,\n\tcontrolMap: VariableProviderControlMap | undefined,\n\tdefaultFilter?: TemplateFilter,\n) {\n\tif (isNullish(value)) return\n\n\tconst templateVariableNameRegex = getTemplateVariableNameRegex()\n\n\treturn jst.replaceAll(value, templateVariableNameRegex, (original, templateVariable) => {\n\t\tconst [variableName, filters] = parseTemplateVariableContents(templateVariable, defaultFilter)\n\t\tif (!controlMap?.has(variableName)) {\n\t\t\t// TODO: Provide feedback to the user.\n\t\t\treturn original\n\t\t}\n\n\t\tconst variable = createVariableReference(variableName, node.id)\n\t\tconst variableValue = variables.create(variable)\n\n\t\tlet transformedValue = variableValue\n\n\t\tif (controlMap?.get(variableName)?.type === ControlType.ResponsiveImage) {\n\t\t\ttransformedValue = valueTransforms.wrapInToImageSrc(transformedValue)\n\t\t}\n\n\t\ttransformedValue = valueTransforms.wrapInTemplateFilters(transformedValue, filters)\n\n\t\treturn js`${variableValue} !== undefined ? ${transformedValue} : ${original}`\n\t})\n}\n", "import { ModuleType } from \"@framerjs/shared\"\nimport type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport type { AnyScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport { isScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport { isStylePresetNode } from \"document/models/CanvasTree/nodes/utils/isStylePresetNode.ts\"\nimport {\n\tisCanvasPageNode,\n\tisCollectionNode,\n\tisCustomCodeScopeNode,\n\tisDesignPageNode,\n\tisLayoutTemplateNode,\n\tisPresetsListNode,\n\tisRootNode,\n\tisShapeContainerNode,\n\tisSmartComponentNode,\n\tisVectorSetNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isVectorSetItem } from \"document/models/CanvasTree/traits/WithVectorSetItem.ts\"\n\nexport function moduleTypesForSourceNode(node: CanvasNode | AnyScopeNode, tree: CanvasTree): ModuleType[] {\n\tif (isSmartComponentNode(node, true)) {\n\t\treturn [ModuleType.Canvas]\n\t} else if (isWebPageNode(node, true)) {\n\t\treturn [ModuleType.Screen, ModuleType.WebPageMetadata]\n\t} else if (isLayoutTemplateNode(node, true)) {\n\t\treturn [ModuleType.LayoutTemplate]\n\t} else if (isCanvasPageNode(tree.get(node.parentid))) {\n\t\treturn [ModuleType.Screen]\n\t} else if (isVectorSetNode(node, true)) {\n\t\treturn [ModuleType.VectorSet]\n\t} else if (isCanvasPageNode(node, true)) {\n\t\treturn [ModuleType.Prototype]\n\t} else if (isCustomCodeScopeNode(node, true)) {\n\t\treturn [ModuleType.Snippets]\n\t} else if (isScopeNode(node, true)) {\n\t\tthrow new Error(\"Unhandled scope node type\")\n\t} else if (isCollectionNode(node)) {\n\t\t// Keep in sync with the sources emitted from `GeneratedCollection.ts`\n\t\treturn [ModuleType.Collection, ModuleType.DraftCollection]\n\t} else if (isStylePresetNode(node)) {\n\t\treturn [ModuleType.CSS]\n\t} else if (isPresetsListNode(node)) {\n\t\t// Style and code presets are siblings in presets list node but are code\n\t\t// generated in different ways. See comments in `PresetListNode` for\n\t\t// more info on why.\n\t\treturn [ModuleType.ComponentPresets]\n\t} else if (isShapeContainerNode(node) && isVectorSetNode(tree.getScopeNodeFor(node))) {\n\t\t// VECTOR @TODO: Consider a special node for the vector set item.\n\t\treturn [ModuleType.Vector]\n\t} else if (isRootNode(node)) {\n\t\treturn [ModuleType.SiteMetadata]\n\t} else if (isVectorSetItem(node)) {\n\t\treturn [ModuleType.Vector]\n\t} else if (isDesignPageNode(tree.get(node.parentid))) {\n\t\treturn [ModuleType.Design]\n\t} else {\n\t\tthrow new Error(`Unsupported component node: ${node.__class} ${node.id}`)\n\t}\n}\n", "import type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isDrawableNode } from \"document/models/CanvasTree/index.ts\"\nimport { isCanvasPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\n\nexport function isDrawablePageGroundNode(componentSourceNode: CanvasNode, tree: CanvasTree): boolean {\n\tif (!isDrawableNode(componentSourceNode) || !tree.isGroundNode(componentSourceNode)) return false\n\n\tconst screenParent = tree.get(componentSourceNode.parentid)\n\tif (screenParent && isCanvasPageNode(screenParent)) return true\n\n\treturn false\n}\n", "import type { LocalModuleId } from \"@framerjs/shared\"\nimport { ModuleType, localModuleIdForStableName } from \"@framerjs/shared\"\nimport { isModuleType } from \"@framerjs/shared/src/moduleIdentifiers.ts\"\nimport { siteMetadataModuleIdentifier } from \"code-generation/components/generateMetadataModule.ts\"\nimport { snippetsModuleIdentifier } from \"code-generation/components/generateSnippetsModule.ts\"\nimport { moduleTypesForSourceNode } from \"code-generation/moduleTypeForSourceNode.ts\"\nimport { type AnyScopeNode, type CanvasNode, type CanvasTree, isScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport type { MaybeCanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport { PRESETS_LIST_NODE_ID } from \"document/models/CanvasTree/nodes/PresetsListNode.ts\"\nimport { CUSTOM_CODE_SCOPE_ID } from \"document/models/CanvasTree/nodes/custom-code/CustomCodeScopeNode.ts\"\nimport { isStylePresetNode } from \"document/models/CanvasTree/nodes/utils/isStylePresetNode.ts\"\nimport {\n\tisCanvasPageNode,\n\tisCollectionNode,\n\tisCustomCodeScopeNode,\n\tisDesignPageNode,\n\tisFrameNode,\n\tisPresetsListNode,\n\tisRootNode,\n\tisVectorSetNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isVectorSetItem } from \"document/models/CanvasTree/traits/WithVectorSetItem.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { isDrawablePageGroundNode } from \"./isDrawablePageGroundNode.ts\"\n\nexport function sourceNodeIdForModule(module: { type: string; name: string }) {\n\tif (!isModuleType(module.type)) return module.name\n\tif (module.type === ModuleType.Snippets) return CUSTOM_CODE_SCOPE_ID\n\treturn module.name\n}\n\n/**\n * Most source nodes module's use the source node id as the module name, but\n * there are exceptions.\n */\nexport function moduleNameForSourceNode(node: CanvasNode | AnyScopeNode) {\n\t// The root node generates a site metadata module which should have a static\n\t// name.\n\tif (isRootNode(node)) return siteMetadataModuleIdentifier.localIdName\n\tif (isCustomCodeScopeNode(node, true)) return snippetsModuleIdentifier.localIdName\n\n\tswitch (node.id) {\n\t\t// Component presets doesn't use `sourceNodeId` because it used to be\n\t\t// it's own node. Now it's combined with the presets list node.\n\t\tcase PRESETS_LIST_NODE_ID:\n\t\t\treturn \"componentPresets\"\n\t\tdefault:\n\t\t\treturn node.id\n\t}\n}\n\n/**\n * A single node can generate multiple modules. For example, a WebPageNode\n * has both a ModuleType.Screen and a ModuleType.WebPageMetadata. In the\n * future this may grow as we support draft collections.\n */\nexport function localModuleIdsForSourceNode(node: CanvasNode | AnyScopeNode, tree: CanvasTree): LocalModuleId[] {\n\tconst moduleTypes = moduleTypesForSourceNode(node, tree)\n\treturn moduleTypes.map(type => localModuleIdForStableName(type, moduleNameForSourceNode(node)))\n}\n\n/**\n * Check that all modules that a source node will generate exist.\n */\nexport function allModulesExistForSourceNode(\n\tnode: MaybeCanvasNode,\n\ttree: CanvasTree,\n\tmodulesStore: ModulesStore,\n): boolean {\n\tif (!node) return false\n\treturn localModuleIdsForSourceNode(node, tree).every(id => !isUndefined(modulesStore.getModuleEntryByLocalId(id)))\n}\n\nexport function isPersistedModuleSourceNode(sourceNode: CanvasNode, tree: CanvasTree) {\n\tif (!isValidModuleSourceNode(sourceNode, tree)) return false\n\tif (isDesignPageNode(sourceNode)) return false\n\tif (!isScopeNode(sourceNode)) {\n\t\tconst scope = tree.getScopeNodeFor(sourceNode)\n\t\tif (isDesignPageNode(scope)) return false\n\t}\n\treturn true\n}\n\nexport function isValidModuleSourceNode(node: CanvasNode, tree: CanvasTree): boolean {\n\t// Generates a site metadata module.\n\tif (isRootNode(node)) return true\n\tif (!tree.has(node.id)) return false\n\n\tif (withReplicaVariants(node)) return true\n\tif (isReplicaOrReplicaChild(node)) return false\n\tif (isCollectionNode(node)) return true\n\t// TODO: Use isStylePresetPrimaryNode here.\n\tif (isStylePresetNode(node)) return true\n\tif (isPresetsListNode(node)) return true\n\tif (isVectorSetNode(node)) return true\n\tif (isVectorSetItem(node)) {\n\t\tconst parent = tree.get(node.parentid)\n\t\treturn isVectorSetNode(parent)\n\t}\n\tif (isDesignPageNode(node)) return false\n\t// DESIGN_PAGE @todo - What about other ground nodes, like text nodes? Can we hide the preview\n\t// badge?\n\tif (tree.isGroundNode(node) && isFrameNode(node)) {\n\t\tconst scopeNode = tree.getScopeNodeFor(node)\n\t\tif (isDesignPageNode(scopeNode)) return true\n\t}\n\tif (isCanvasPageNode(node) || isDrawablePageGroundNode(node, tree)) return true\n\tif (isCustomCodeScopeNode(node)) return true\n\n\treturn false\n}\n", "export type Result<T, E = unknown> = Ok<T> | Err<E>\n\nexport type Ok<T> = T extends void ? { ok: true } : { ok: true; value: T }\n\nexport interface Err<E> {\n\tok: false\n\terror: E\n}\n\nexport function ok(): Ok<void>\nexport function ok<T>(value: T): Ok<T>\nexport function ok<T>(value?: T) {\n\treturn value !== undefined ? { ok: true, value } : { ok: true }\n}\n\nexport function err<E = unknown>(error: E): Err<E> {\n\treturn { ok: false, error }\n}\n\n/**\n * Turns `promise` into a non-fallible `Promise` of a `Result`.\n */\nexport function resultify<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> {\n\treturn promise.then(\n\t\tvalue => ok(value),\n\t\t(error: E) => err(error),\n\t)\n}\n", "import type { LinkToWebPage } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport type { ResolvedCollectionItemSelector } from \"document/models/CanvasTree/traits/utils/ResolvedCollectionItemSelector.ts\"\nimport { isResolvedCollectionItemSelector } from \"document/models/CanvasTree/traits/utils/ResolvedCollectionItemSelector.ts\"\n\nexport function getCollectionItemSelectorFromLink(link: LinkToWebPage): ResolvedCollectionItemSelector | undefined {\n\tfor (const key in link.pathVariables) {\n\t\tconst value = link.pathVariables[key]\n\t\tif (isResolvedCollectionItemSelector(value)) return value\n\t}\n}\n", "import type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport type { ShallowWebPageNode } from \"document/models/CanvasTree/nodes/WebPageNode.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport type { LinkToWebPage } from \"document/models/CanvasTree/traits/utils/Link.ts\"\n\nexport function webPageNodeForLink(tree: CanvasTree, link: LinkToWebPage): ShallowWebPageNode | null {\n\tconst node = tree.getNode(link.webPageId)\n\tif (!isWebPageNode(node)) return null\n\treturn node\n}\n\nexport function getLinkDataIdentifiers(\n\ttree: CanvasTree,\n\tlinks: LinkToWebPage[],\n): ReadonlySet<ModuleExportIdentifierString> {\n\tconst dataIdentifiers = new Set<ModuleExportIdentifierString>()\n\n\tfor (const link of links) {\n\t\tconst webPage = webPageNodeForLink(tree, link)\n\t\tif (!webPage) continue\n\t\tif (!hasCollectionDataSource(webPage)) continue\n\t\tdataIdentifiers.add(webPage.dataIdentifier)\n\t}\n\n\treturn dataIdentifiers\n}\n", "import { ResolvablePromise } from \"@framerjs/shared\"\n\nexport interface LockQueueItem {\n\tid?: string\n\tpromise: ResolvablePromise<void>\n\ttask: () => ResolvablePromise<void>\n}\n\n/**\n * A queue that ensures that async tasks are executed in order, after the\n * preceding task resolves, and allows awaiting the current snapshot of the\n * queue to resolve without blocking adding new tasks. For example, assuming\n * functions are long lived promises that can resolve in any order:\n *\n * ```typescript\n *  queue.request(fn1);\n *  queue.request(fn2);\n *  queue.synchronize();\n *  queue.request(fn3);\n * ```\n *\n * In this sequence of events, fn2 will only be invoked after fn1 resolves, and\n * synchronize will always resolve before fn3 is invoked.\n *\n * The queue works similarly to Web Locks\n * https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API, but allows\n * synchronously querying the number of active tasks.\n */\nexport class LockQueue {\n\tqueue: LockQueueItem[] = []\n\n\tsnapshot(filter?: (item: LockQueueItem) => boolean) {\n\t\tthis.queue = this.queue.filter(filter ?? (item => !item.promise.isResolved()))\n\t\treturn Array.from(this.queue)\n\t}\n\n\tisScheduled(id: string): boolean {\n\t\tfor (const item of this.queue) {\n\t\t\tif (item.promise.isResolved()) continue\n\t\t\tif (item.id === id) return item.promise.state === \"initial\"\n\t\t}\n\t\treturn false\n\t}\n\n\tawait(id: string): Promise<void> {\n\t\tfor (const item of this.queue) {\n\t\t\tif (item.promise.isResolved()) continue\n\t\t\tif (item.id === id) return item.promise\n\t\t}\n\t\treturn Promise.resolve()\n\t}\n\n\tget size() {\n\t\treturn this.snapshot().length\n\t}\n\n\t/**\n\t * If we popped each task off of the queue when we processed it, we would\n\t * lose the ability for another process to await the queue to be clear\n\t * without tracking a secondary promise for each request or synchronize. Instead, we\n\t * keep the tasks on the queue until they resolve, and prune complete tasks\n\t * from the queue whenever we process it. This makes it easy to keep track\n\t * of how many tasks are still processing and keeps the queue conceptually\n\t * simple. There are only tasks that we are waiting to resolve.\n\t */\n\tasync request(\n\t\ttask: () => Promise<void> | undefined,\n\t\toptions?: { id?: string; synchronize?: boolean },\n\t): Promise<void> {\n\t\tconst promise = new ResolvablePromise<void>()\n\n\t\tthis.queue.push({\n\t\t\tid: options?.id,\n\t\t\tpromise,\n\t\t\ttask: () => {\n\t\t\t\tif (promise.state !== \"initial\") return promise\n\t\t\t\tvoid promise.pending()\n\t\t\t\tconst result = task() ?? Promise.resolve()\n\t\t\t\tvoid result.finally(() => promise.resolve())\n\t\t\t\treturn promise\n\t\t\t},\n\t\t})\n\n\t\tif (options?.synchronize === false) return\n\n\t\tawait this.synchronize()\n\t}\n\n\t/**\n\t * Process all tasks on the queue in series. Don't begin executing a task\n\t * until the preceding task resolves.\n\t *\n\t * @TODO - Consider an optimization mechanism so that calling synchronize\n\t * doesn't repeat the same iterations unnecessarily.\n\t */\n\tsynchronize = async () => {\n\t\tfor (const item of this.snapshot()) await item.task()\n\t}\n\n\t/**\n\t * Process all tasks on the queue in series with progress reporting.\n\t * Calls the onProgress callback after each task completes.\n\t */\n\tsynchronizeWithProgress = async (onProgress: (completed: number, total: number) => void) => {\n\t\tconst items = this.snapshot()\n\t\tconst total = items.length\n\t\tlet completed = 0\n\t\tfor (const item of items) {\n\t\t\tawait item.task()\n\t\t\tcompleted++\n\t\t\tonProgress(completed, total)\n\t\t}\n\t}\n}\n", "import { ContextAction } from \"document/components/utils/contextActions.ts\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { type TraitType, getPropKeysByTraitTypes } from \"document/models/CanvasTree/traits/TraitType.ts\"\n\n// If traitTypeKeys is given, traitTypes would be ignored.\nexport function resetNodeOverrides(\n\ttree: CanvasTree,\n\tnodes: CanvasNode[],\n\ttraitTypes: readonly TraitType[] | undefined,\n\tkeys: readonly string[] | undefined = undefined,\n) {\n\tif (!traitTypes && !keys) return\n\n\tconst keysToReset: readonly string[] = keys ?? getPropK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AA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA;AAAA;AAAA,IAIR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA,IAER;AAIC,kBAAYA,KAAI;AAAA,EAClB;AACD;AAEA,SAAS,YAAYA,OAAiC;AACrD,UAAQA,OAAM;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA,IAER;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA,IAER;AACC,kBAAYA,KAAI;AAAA,EAClB;AACD;AAEA,SAAS,eAAeA,OAAa;AACpC,UAAQA,OAAM;AAAA;AAAA;AAAA,IAGb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA;AAAA;AAAA,IAIR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA,IAER;AAIC,kBAAYA,KAAI;AAAA,EAClB;AACD;AAEO,SAAS,WAAWA,OAAa;AACvC,UAAQA,OAAM;AAAA,IACb;AAAA,IACA;AACC,aAAO;AAAA,IAER;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA,IAER;AAIC,kBAAYA,KAAI;AAAA,EAClB;AACD;AAEO,SAAS,wBAAwBA,OAAa;AAGpD,UAAQA,OAAM;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA,IAER;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA,IAER;AAKC,kBAAYA,KAAI;AAAA,EAClB;AACD;AAEO,SAAS,yCAAyCA,OAAa;AACrE,UAAQA,OAAM;AAAA,IACb;AAAA,IACA;AAAA,IACA;AACC,aAAO;AAAA,IAER;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,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AAC9B,UAAI,KAAK,QAAQ,WAAW,EAAG;AAC/B,UAAI,KAAK,OAAO,GAAI,QAAO,KAAK;AAAA,IACjC;AACA,WAAO,QAAQ,QAAQ;AAAA,EACxB;AAAA,EAEA,IAAI,OAAO;AACV,WAAO,KAAK,SAAS,EAAE;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,QACL,MACA,SACgB;AAChB,UAAM,UAAU,IAAI,kBAAwB;AAE5C,SAAK,MAAM,KAAK;AAAA,MACf,IAAI,SAAS;AAAA,MACb;AAAA,MACA,MAAM,MAAM;AACX,YAAI,QAAQ,UAAU,UAAW,QAAO;AACxC,aAAK,QAAQ,QAAQ;AACrB,cAAM,SAAS,KAAK,KAAK,QAAQ,QAAQ;AACzC,aAAK,OAAO,QAAQ,MAAM,QAAQ,QAAQ,CAAC;AAC3C,eAAO;AAAA,MACR;AAAA,IACD,CAAC;AAED,QAAI,SAAS,gBAAgB,MAAO;AAEpC,UAAM,KAAK,YAAY;AAAA,EACxB;AA2BD;;;AC5GO,SAAS,mBACf,MACA,OACA,YACA,OAAsC,QACrC;AACD,MAAI,CAAC,cAAc,CAAC,KAAM;AAE1B,QAAM,cAAiC,QAAQ,wBAAwB,cAAc,CAAC,CAAC;AACvF,MAAI,CAAC,YAAY,OAAQ;AAEzB,gBAAc,8BAA8B,MAAM,OAAO,WAAW;AACrE;",
  "names": ["__defProp", "__hasOwnProp", "__export", "name", "getContext", "__defProp", "__hasOwnProp", "__export", "name", "AccessTokenMissingError", "RefreshAccessTokenFailedError", "__defProp", "__hasOwnProp", "__export", "name", "getVercelOidcToken", "array", "object", "meta", "meta", "meta", "meta", "meta", "constrainedFrame", "isReplica", "isString", "meta", "withPath", "equals", "array", "closestCurve", "withPath", "withShape", "isNumber", "ImmutableMap", "log", "tool", "text", "isNumber", "base", "log", "withShape", "isString", "message", "name", "isNull", "name", "name", "name", "isString", "isEqual", "isString", "withPath", "log", "isString", "Paper", "withPath", "isString", "log", "message", "resolve", "log", "fn", "log", "isNull", "externalModuleExportIdentifiers", "isNull", "document", "name", "isString", "document", "stylePresetKeys", "object", "isString", "isString", "isNumber", "isNull", "assertNever", "assert", "name", "name", "isNumber", "isViewOnly", "name", "message", "marker", "symbol", "_a", "_b", "text", "context", "util", "assertNever", "object", "array", "objectUtil", "_ctx", "message", "isValid", "errorUtil", "message", "isValid", "errorMap", "message", "err", "ctx", "result", "issues", "elements", "fn", "lazySchema", "processed", "base", "result", "isValid", "ZodFirstPartyTypeKind", "message", "trailing", "value", "line", "delay", "resolve", "_a", "atob", "array", "name", "marker", "symbol", "_a", "_b", "message", "prefix", "getErrorMessage", "fetch", "APICallError", "mediaType", "text", "jsonSchema", "_a", "_b", "emojiRegex", "message", "ZodFirstPartyTypeKind", "object", "types", "x", "base", "name", "schema", "standardSchema", "zodSchema", "context", "TypeValidationError", "InvalidArgumentError", "getOriginalFetch", "fetch", "APICallError", "tool", "outputSchema", "APICallError", "import_oidc", "marker", "symbol", "_a", "_b", "message", "name", "lazySchema", "zodSchema", "z", "safeValidateTypes", "getFromApi", "resolve", "createJsonResponseHandler", "createJsonErrorResponseHandler", "postJsonToApi", "combineHeaders", "APICallError", "convertUint8ArrayToBase64", "providerMetadataEntrySchema", "createProviderToolFactoryWithOutputSchema", "VERSION", "environment", "now", "VERSION", "isCompatible", "VERSION", "VERSION", "_a", "err", "_b", "DiagComponentLogger", "logger", "DiagLogLevel", "logger", "DiagAPI", "logger", "__spreadArray", "__read", "self", "err", "_a", "_b", "BaseContext", "self", "context", "NoopContextManager", "fn", "__spreadArray", "__read", "API_NAME", "ContextAPI", "context", "fn", "_a", "__spreadArray", "__read", "TraceFlags", "NonRecordingSpan", "context", "_a", "NoopTracer", "name", "context", "fn", "ProxyTracer", "name", "context", "NoopTracerProvider", "ProxyTracerProvider", "name", "_a", "SpanStatusCode", "API_NAME", "TraceAPI", "name", "name", "marker", "symbol", "_a", "InvalidArgumentError", "message", "AISDKError", "text", "getErrorMessage", "prefix", "logger", "_b", "VERSION", "DownloadError", "download", "convertBase64ToUint8Array", "tool", "object", "z", "InvalidPromptError", "fn", "base", "APICallError", "delay", "durationMs", "content", "convertUint8ArrayToBase64", "__export", "asSchema", "jsonSchema", "context", "safeParseJSON", "safeValidateTypes", "TypeValidationError", "generateId", "withUserAgentSuffix", "output", "callSettings", "span", "_c", "_d", "_e", "_f", "_g", "_h", "totalUsage", "toolCall", "resolve", "part", "isAborted", "err", "originalGenerateId", "createIdGenerator", "now", "self", "isAbortError", "result", "includeRawChunks", "stream", "doStreamSpan", "UnsupportedFunctionalityError", "validateTypes", "toolMetadataSchema", "lazySchema", "zodSchema", "embedding", "usage", "array", "embeddings", "warnings", "providerMetadata", "uint8Data", "JSONParseError", "reasoning", "DelayedPromise", "error", "normalizePrompt", "suffix", "doWrap", "NoSuchModelError", "document", "ranking", "defaultDownload", "getOriginalFetch", "fetch", "getRuntimeEnvironmentUserAgent", "parseJsonEventStream", "generateIdFunc", "id", "state", "text", "isNull", "marker", "symbol", "_a", "_b", "AISDKError", "_AISDKError", "name", "message", "APICallError", "EmptyResponseBodyError", "getErrorMessage", "InvalidArgumentError", "InvalidPromptError", "InvalidResponseDataError", "JSONParseError", "text", "LoadAPIKeyError", "LoadSettingError", "NoContentGeneratedError", "NoSuchModelError", "TooManyEmbeddingValuesForCallError", "TypeValidationError", "_TypeValidationError", "context", "UnsupportedFunctionalityError", "combineHeaders", "_a", "tool", "extractResponseHeaders", "btoa", "atob", "convertBase64ToUint8Array", "convertUint8ArrayToBase64", "array", "convertToBase64", "convertToFormData", "name", "marker", "symbol", "_a", "_b", "DownloadError", "AISDKError", "message", "DEFAULT_MAX_DOWNLOAD_SIZE", "readResponseWithSizeLimit", "validateDownloadUrl", "isPrivateIPv6", "isIPv4", "isPrivateIPv4", "downloadBlob", "createIdGenerator", "prefix", "InvalidArgumentError", "generateId", "isAbortError", "FETCH_FAILED_ERROR_MESSAGES", "BUN_ERROR_CODES", "isBunNetworkError", "handleFetchError", "APICallError", "getRuntimeEnvironmentUserAgent", "_a", "_b", "normalizeHeaders", "withUserAgentSuffix", "VERSION", "isNonNullable", "LoadAPIKeyError", "loadOptionalSetting", "_a", "suspectProtoRx", "suspectConstructorRx", "_parse", "text", "filter", "secureJsonParse", "addAdditionalPropertiesToJsonSchema", "jsonSchema", "visit", "ignoreOverride", "defaultOptions", "getDefaultOptions", "parseAnyDef", "parseArrayDef", "_b", "parseDef", "parseBigintDef", "parseBooleanDef", "parseBrandedDef", "parseCatchDef", "parseDateDef", "integerDateParser", "parseDefaultDef", "parseEffectsDef", "parseEnumDef", "isJsonSchema7AllOfType", "parseIntersectionDef", "parseLiteralDef", "emojiRegex", "zodPatterns", "parseStringDef", "addFormat", "addPattern", "escapeLiteralCheckValue", "escapeNonAlphaNumeric", "ALPHA_NUMERIC", "message", "stringifyRegExpWithFlags", "parseRecordDef", "ZodFirstPartyTypeKind", "parseMapDef", "parseNativeEnumDef", "object", "parseNeverDef", "parseNullDef", "primitiveMappings", "parseUnionDef", "types", "x", "asAnyOf", "parseNullableDef", "base", "parseNumberDef", "parseObjectDef", "safeIsOptional", "decideAdditionalProperties", "parseOptionalDef", "parsePipelineDef", "parsePromiseDef", "parseSetDef", "parseTupleDef", "parseUndefinedDef", "parseUnknownDef", "parseReadonlyDef", "selectParser", "getRelativePath", "get$ref", "addMeta", "getRefs", "name", "zod3ToJsonSchema", "schema", "schemaSymbol", "lazySchema", "isSchema", "asSchema", "zodSchema", "standardSchema", "TypeValidationError", "zod3Schema", "zod4Schema", "isZod4Schema", "validateTypes", "context", "safeValidateTypes", "parseJSON", "JSONParseError", "safeParseJSON", "isParsableJson", "parseJsonEventStream", "parseProviderOptions", "InvalidArgumentError", "getOriginalFetch", "postJsonToApi", "fetch", "postToApi", "postFormDataToApi", "withUserAgentSuffix", "VERSION", "getRuntimeEnvironmentUserAgent", "extractResponseHeaders", "isAbortError", "APICallError", "handleFetchError", "tool", "outputSchema", "tool", "createProviderToolFactoryWithOutputSchema", "createJsonErrorResponseHandler", "extractResponseHeaders", "APICallError", "parseJSON", "createEventSourceResponseHandler", "EmptyResponseBodyError", "parseJsonEventStream", "createJsonResponseHandler", "safeParseJSON", "withoutTrailingSlash", "createJsonErrorResponseHandler", "_a", "_b", "convertToBase64", "UnsupportedFunctionalityError", "text", "lazySchema", "zodSchema", "z", "openaiTools", "tool", "parseProviderOptions", "postJsonToApi", "combineHeaders", "createJsonResponseHandler", "choice", "generateId", "createEventSourceResponseHandler", "InvalidResponseDataError", "toolCall", "isParsableJson", "InvalidPromptError", "getResponseMetadata", "mapOpenAIFinishReason", "TooManyEmbeddingValuesForCallError", "prefix", "response", "responseHeaders", "postFormDataToApi", "convertToFormData", "convertBase64ToUint8Array", "downloadBlob", "_c", "_d", "_e", "_f", "base", "createProviderToolFactoryWithOutputSchema", "jsonValueSchema", "parseJSON", "validateTypes", "isNonNullable", "filter", "environment", "env", "message", "APICallError", "providerMetadata", "self", "VERSION", "withoutTrailingSlash", "loadOptionalSetting", "withUserAgentSuffix", "_a", "_b", "message", "text", "getResponseMetadata", "z", "tool", "UnsupportedFunctionalityError", "openaiTools", "choice", "usage", "toolCall", "mapOpenAICompatibleFinishReason", "createJsonErrorResponseHandler", "parseProviderOptions", "postJsonToApi", "combineHeaders", "createJsonResponseHandler", "createEventSourceResponseHandler", "openaiTextEmbeddingResponseSchema", "response", "responseHeaders", "fileToBlob", "convertBase64ToUint8Array", "VERSION", "marker", "symbol", "_a", "_b", "AISDKError", "_AISDKError", "name", "message", "APICallError", "EmptyResponseBodyError", "getErrorMessage", "InvalidArgumentError", "InvalidPromptError", "InvalidResponseDataError", "JSONParseError", "text", "LoadAPIKeyError", "LoadSettingError", "NoContentGeneratedError", "NoSuchModelError", "TooManyEmbeddingValuesForCallError", "TypeValidationError", "_TypeValidationError", "context", "UnsupportedFunctionalityError", "ParseError", "noop", "createParser", "EventSourceParserStream", "combineHeaders", "delay", "resolve", "createAbortError", "extractResponseHeaders", "btoa", "atob", "convertUint8ArrayToBase64", "array", "DownloadError", "DEFAULT_MAX_DOWNLOAD_SIZE", "createIdGenerator", "prefix", "generateId", "isAbortError", "FETCH_FAILED_ERROR_MESSAGES", "BUN_ERROR_CODES", "isBunNetworkError", "handleFetchError", "getRuntimeEnvironmentUserAgent", "normalizeHeaders", "withUserAgentSuffix", "VERSION", "getOriginalFetch", "getFromApi", "fetch", "loadApiKey", "suspectProtoRx", "suspectConstructorRx", "_parse", "filter", "secureJsonParse", "addAdditionalPropertiesToJsonSchema", "jsonSchema", "visit", "ignoreOverride", "defaultOptions", "getDefaultOptions", "parseAnyDef", "parseArrayDef", "parseDef", "parseBigintDef", "parseBooleanDef", "parseBrandedDef", "parseCatchDef", "parseDateDef", "integerDateParser", "parseDefaultDef", "parseEffectsDef", "parseEnumDef", "isJsonSchema7AllOfType", "parseIntersectionDef", "parseLiteralDef", "emojiRegex", "zodPatterns", "parseStringDef", "addFormat", "addPattern", "escapeLiteralCheckValue", "escapeNonAlphaNumeric", "ALPHA_NUMERIC", "stringifyRegExpWithFlags", "parseRecordDef", "ZodFirstPartyTypeKind", "parseMapDef", "parseNativeEnumDef", "object", "parseNeverDef", "parseNullDef", "primitiveMappings", "parseUnionDef", "types", "x", "asAnyOf", "parseNullableDef", "base", "parseNumberDef", "parseObjectDef", "safeIsOptional", "decideAdditionalProperties", "parseOptionalDef", "parsePipelineDef", "parsePromiseDef", "parseSetDef", "parseTupleDef", "parseUndefinedDef", "parseUnknownDef", "parseReadonlyDef", "selectParser", "getRelativePath", "get$ref", "addMeta", "getRefs", "zod3ToJsonSchema", "schema", "schemaSymbol", "isSchema", "asSchema", "zodSchema", "standardSchema", "zod3Schema", "zod4Schema", "isZod4Schema", "validateTypes", "safeValidateTypes", "parseJSON", "safeParseJSON", "isParsableJson", "parseJsonEventStream", "postJsonToApi", "postToApi", "tool", "createProviderToolFactory", "outputSchema", "createJsonErrorResponseHandler", "createEventSourceResponseHandler", "createJsonResponseHandler", "withoutTrailingSlash", "ReasoningFormat", "d", "z", "err", "__privateAdd", "__privateGet", "openrouter", "_c", "_d", "_e", "_f", "_g", "logger", "content", "choice", "toolCall", "z", "_a", "UnsupportedFunctionalityError", "postJsonToApi", "combineHeaders", "createJsonResponseHandler", "choice", "NoContentGeneratedError", "webSearchInputSchema", "webSearch", "createProviderToolFactory", "record", "normalizeHeaders", "withUserAgentSuffix", "VERSION", "_b", "delay", "getFromApi", "APICallError", "withoutTrailingSlash", "loadApiKey", "isNumber", "isString", "environment", "isString", "message", "isString", "assert", "isString", "log", "name", "component", "name", "context", "logger", "isNumber", "assertNever", "isNull", "isString", "isNumber", "isString", "name", "isNull", "newVariableDefinition", "isString", "isString", "context", "isString", "isNumber", "isNull", "context", "isString", "context", "isString", "context", "context", "withShape", "context", "context", "isString", "entry", "context", "context", "context", "context", "context", "context", "context", "context", "isString", "_node", "context", "context", "name", "context", "context", "context", "isString", "context", "context", "isString", "context", "hasLayoutTemplate", "context", "name", "isNumber", "isRootNode", "context", "context", "isNumber", "context", "collectTextSelection", "context", "context", "context", "collectTextSelection", "isNull", "context", "text", "context", "styleDefaults", "isNumber", "logger", "omitOrder", "repeaterChains", "isString", "visit", "seenBindings", "orderedBindings", "isString", "assert", "assertNever", "fetch", "base", "assertNever", "assertNever", "filter", "record", "nodeId", "isNumber", "isNull", "assert", "assertNever", "assertNever", "assertNever", "logger", "node", "_a", "_b", "isNumber", "logger", "node", "isNumber", "parentNode", "_node", "_ctx", "_a", "_b", "logger", "node", "isNumber", "assert", "isNull", "isString", "assert", "name", "isNull", "isString", "fn", "isString", "delay", "meta", "createSetVariantAction", "message", "font", "isString", "name", "isNumber", "isNumber", "checkForVariables", "isString", "getFallbackFunctionBody", "getFallbackFunctionBody", "spanCount", "isSet", "reverseArray", "isSet", "reverseArray", "toString", "toNumber", "toBoolean", "toResponsiveImage", "toImageSrc", "toZIndex", "numberToPixelString", "radiusForCorner", "percentageToCornerShape", "toAxisOverflow", "toOverflowWithClipFallback", "jsonStringify", "htmlEscape", "htmlUnescape", "addImageAlt", "getGridColumnCSSValue", "getGridRowCSSValue", "getNumericColumnGap", "isString", "isNumber", "isString", "fn", "_annotations", "isString", "document", "assert", "array", "_map", "logger", "name", "reservedWords", "assert", "name", "name", "isString", "logger", "isUndefined", "context", "overlayBinding", "variableFallbackList", "repeaterItemCountDeclaration", "repeaterItemIndexDeclaration", "reserved", "log", "jsx", "name", "isString", "name", "sanitizedName", "symbol", "isString", "import_immutable", "isNumber", "isString", "withPath", "withShape", "isNumber", "context", "isNumber", "isString", "ContextAction", "renameLayers", "name", "isNull", "isNumber", "isString", "withPath", "base", "suggestedRect", "renamedVariantId", "update", "isObject", "node", "isArray", "visit", "base", "name", "name", "name", "name", "name", "isEmptyWebPage", "requestIdleCallback", "resolve", "fn", "isString", "assert", "isString", "uniqueVariableName", "name", "log", "err", "isNumber", "isString", "PARAMS_VAR", "name", "replaceTemplateVariables", "filter"]
}
