{
  "version": 3,
  "sources": ["../../../../../node_modules/@framerjs/framer-events/lib/esm/generated/ExternalComponentInsert.js", "../../src/document/components/chrome/Pages/utils/duplicatePage.ts", "../../src/document/components/chrome/shared/InstantNPMToast.tsx", "../../src/modules/compiler.ts", "../../src/document/components/utils/setDimensionTypeAutoIfSupported.ts", "../../src/document/components/utils/getParentForInsertNode.ts", "../../src/document/models/resetAncestorCacheForNodes.ts", "../../src/document/utils/VariableProviderInfo.ts", "../../src/document/utils/VerificationIndex.ts", "../../src/document/stores/TreeIndex.ts", "../../src/document/stores/TreeStore.ts", "../../src/utils/arrayToText.ts", "../../src/utils/externalModules.ts", "../../src/document/stores/ModulesStore.ts", "../../src/utils/tracking/trackComponentAddedToCanvas.ts", "../../src/document/components/utils/repeater.ts", "../../src/document/utils/setupInsertedCollectionRepeater.ts", "../../src/document/models/CanvasTree/traits/utils/getChildrenRects.ts", "../../src/document/utils/StackComponent/childInsertion.ts", "../../src/document/components/tools/utils/stackInsertionHelpers.ts", "../../src/document/components/utils/insertComponent.ts", "../../src/document/components/chrome/shared/utils/insertModuleComponent.ts", "../../src/document/components/unlinking/common.ts", "../../src/document/components/utils/showCanvasNode.ts", "../../src/document/components/utils/editCodeComponentInPlugin.ts", "../../src/document/components/utils/getEntityDefinitionFromCodeComponentIdentifier.ts", "../../src/document/components/unlinking/enterCodeComponentIsolation.ts", "../../src/document/components/unlinking/importExternalCodeComponent.ts", "../../src/document/components/unlinking/index.ts", "../../src/utils/clipboard/helpers/modules.ts", "../../src/document/components/chrome/richTextEditor/moduleUtils.ts", "../../src/document/models/CanvasTree/nodes/utils/insertNodeAccountingForReplicas.ts", "../../../../../node_modules/stringify-entities/lib/core.js", "../../../../../node_modules/stringify-entities/lib/util/to-hexadecimal.js", "../../../../../node_modules/stringify-entities/lib/util/to-decimal.js", "../../../../../node_modules/character-entities-legacy/index.js", "../../../../../node_modules/character-entities-html4/index.js", "../../../../../node_modules/stringify-entities/lib/constant/dangerous.js", "../../../../../node_modules/stringify-entities/lib/util/to-named.js", "../../../../../node_modules/stringify-entities/lib/util/format-smart.js", "../../../../../node_modules/stringify-entities/lib/index.js", "../../../../../node_modules/hast-util-to-html/lib/handle/comment.js", "../../../../../node_modules/hast-util-to-html/lib/handle/doctype.js", "../../../../../node_modules/hast-util-to-html/lib/omission/util/siblings.js", "../../../../../node_modules/hast-util-to-html/lib/omission/omission.js", "../../../../../node_modules/hast-util-to-html/lib/omission/closing.js", "../../../../../node_modules/hast-util-to-html/lib/omission/opening.js", "../../../../../node_modules/hast-util-to-html/lib/handle/element.js", "../../../../../node_modules/hast-util-to-html/lib/handle/text.js", "../../../../../node_modules/hast-util-to-html/lib/handle/raw.js", "../../../../../node_modules/hast-util-to-html/lib/handle/root.js", "../../../../../node_modules/hast-util-to-html/lib/handle/index.js", "../../../../../node_modules/hast-util-to-html/lib/index.js", "../../../../../node_modules/rehype-stringify/lib/index.js", "../../../../../node_modules/mdast-util-newline-to-break/lib/index.js", "../../../../../node_modules/remark-breaks/lib/index.js", "../../../../../node_modules/remark-stringify/lib/index.js", "../../src/prosemirror/serialization/markdown.ts", "../../src/document/utils/contentManagementOverlayStack.ts", "../../src/utils/shouldEnableDraftStatusForNewEntity.ts", "../../src/document/components/chrome/localization/updateLocalizedValue.ts", "../../src/document/components/utils/editActionForCodeComponent.ts", "../../src/document/components/chrome/contentManagement/useTakenSlugs.ts", "../../src/document/components/chrome/contentManagement/utils/maybeAutoGenerateSlugForCollectionItem.ts"],
  "sourcesContent": ["import { triggerEvent } from \"../listeners\";\nfunction createExternalComponentInsertEvent(payload) {\n  console.warn(\"[DEPRECATED] Use triggerExternalComponentInsertEvent instead of createExternalComponentInsertEvent.\");\n  return {\n    ...payload,\n    event: \"external_component_insert\"\n  };\n}\nconst meta = {\n  track: true\n};\nfunction triggerExternalComponentInsertEvent(payload) {\n  const event = {\n    ...payload,\n    event: \"external_component_insert\"\n  };\n  triggerEvent(event, meta);\n}\nexport {\n  createExternalComponentInsertEvent,\n  triggerExternalComponentInsertEvent\n};\n", "import { Dictionary } from \"app/dictionary.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { RenamedIds, updateNodeConnections } from \"document/components/tools/utils/updateNodeConnections.ts\"\nimport { cloneScopeNodeWithVariants } from \"document/components/unlinking/importExternalSmartComponentOrWebpage.ts\"\nimport { cloneWithRenamedIdMap } from \"document/components/unlinking/utils.ts\"\nimport type { AnyDesignPageNode, CanvasNode, FrameNode, LoadedWebPageNode } from \"document/models/CanvasTree/index.ts\"\nimport { CanvasChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport type { LoadedDesignPageNode } from \"document/models/CanvasTree/nodes/DesignPageNode.ts\"\nimport { duplicatedFromForNode } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport type { IsMaster } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { IsVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { uniqueName } from \"document/utils/uniqueName.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { record } from \"web/lib/tracker.ts\"\n\nexport function duplicateWebPage(\n\tengine: VekterEngine,\n\tnode: LoadedWebPageNode,\n\tprimaryVariant: FrameNode & IsMaster & IsVariant,\n\tpreferredName?: string,\n\t{ shouldOpenPage = true, renamedIds = new RenamedIds() }: { shouldOpenPage?: boolean; renamedIds?: RenamedIds } = {},\n) {\n\t// TODO: update tracking value\n\tconst webPage = cloneScopeNodeWithVariants(engine, node, primaryVariant, \"duplicate\", {\n\t\tenterIsolation: false,\n\t\tpreferredName,\n\t\tinsertionIndex: engine.tree.root.children.findIndex(child => child.id === node.id) + 1,\n\t\trenamedIds,\n\t})\n\n\tif (engine.stores.persistedUserDefaults.newContentAsDraft) {\n\t\twebPage.set({\n\t\t\tisDraft: true,\n\t\t\tduplicatedFrom: duplicatedFromForNode(webPage.duplicatedFrom, node.id),\n\t\t})\n\t}\n\n\tif (shouldOpenPage) {\n\t\t// This will switch to the new scope and zoom/scroll it with our default behavior.\n\t\tengine.stores.scopeStore.select(webPage.id, { keepHistory: false })\n\t}\n\n\treturn webPage\n}\n\nexport function duplicateLoadedDesignPage(\n\tengine: VekterEngine,\n\tloadedNode: LoadedDesignPageNode,\n\tname?: string,\n): LoadedDesignPageNode {\n\tconst renamedIds = new RenamedIds()\n\n\tconst allScopeNames = new Set(\n\t\tengine.stores.scopeStore\n\t\t\t.getDesignPageNodes()\n\t\t\t.map(node => node.resolveValue(\"name\"))\n\t\t\t.filter(isString),\n\t)\n\tconst newName = uniqueName(name ?? loadedNode.resolveValue(\"name\") ?? Dictionary.Design, allScopeNames)\n\n\t// Don't clone the children yet, we will do that in the next step with the renamed ids tracked.\n\tconst clonedScope = loadedNode.clone({ name: newName, children: new CanvasChildList() })\n\trenamedIds.set(loadedNode.id, clonedScope.id)\n\n\tconst clonedChildren: CanvasNode[] = []\n\tfor (const groundNode of loadedNode.children) {\n\t\tconst clone = cloneWithRenamedIdMap(groundNode, new Map(), new Map(), renamedIds, false)\n\t\tclonedChildren.push(clone)\n\t\trenamedIds.set(groundNode.id, clone.id)\n\t\tclonedScope.addChild(clone)\n\t}\n\n\t// Insert the new node after the original node\n\tengine.tree.insertNode(\n\t\tclonedScope,\n\t\tundefined,\n\t\tengine.tree.root.children.findIndex(child => child.id === loadedNode.id) + 1,\n\t)\n\n\tfor (const clone of clonedChildren) {\n\t\tupdateNodeConnections(engine.tree, engine.componentLoader, clone, renamedIds, false)\n\t}\n\n\trecord(\"design_page_create\", { pageId: clonedScope.id, source: \"duplicate\" })\n\n\treturn clonedScope\n}\n\nexport async function duplicateDesignPage(\n\tengine: VekterEngine,\n\tnode: AnyDesignPageNode,\n\tname?: string,\n): Promise<LoadedDesignPageNode | undefined> {\n\tconst loadedNode = node.isLoaded() ? node : await node.load()\n\tif (!loadedNode) return undefined\n\treturn duplicateLoadedDesignPage(engine, loadedNode, name)\n}\n", "import { Translatable as T } from \"@framerjs/fresco\"\nimport { toast } from \"web/lib/toaster.ts\"\n\n// Instant NPM toast\n// @TODO: Delete this file and it's usages when Instant NPM moves out of beta.\n\nconst DISMISSED_INSTANT_NPM_TOAST_STORAGE_KEY = \"dismissedInstantNPMToast\"\nconst SHOWED_INSTANT_NPM_TOAST_STORAGE_KEY = \"showedInstantNPMToast\"\nconst INSTANT_NPM_TOAST_KEY = \"instant-npm-toast\"\n\n// Helpers\nexport const hasShownInstantNPMToast = () =>\n\twindow.localStorage.getItem(SHOWED_INSTANT_NPM_TOAST_STORAGE_KEY) === \"true\"\n\nexport const hasDismissedInstantNPMToast = () =>\n\twindow.localStorage.getItem(DISMISSED_INSTANT_NPM_TOAST_STORAGE_KEY) === \"true\"\n\n// Toast\n\nfunction InstantNPMToastContent() {\n\treturn (\n\t\t<>\n\t\t\t<T>Installed NPM library.</T>\n\t\t\t<a href=\"https://www.framer.com/developers/#faq\" target=\"_blank\">\n\t\t\t\t{\" \"}\n\t\t\t\t<T>Learn more.</T>\n\t\t\t</a>\n\t\t</>\n\t)\n}\n\nexport function showInstantNPMToast() {\n\twindow.localStorage.setItem(SHOWED_INSTANT_NPM_TOAST_STORAGE_KEY, \"true\")\n\ttoast({\n\t\ttype: \"add\",\n\t\tvariant: \"info\",\n\t\ttext: <InstantNPMToastContent />,\n\t\tkey: INSTANT_NPM_TOAST_KEY,\n\t\tduration: Infinity,\n\t\tshowCloseButton: \"never\",\n\t\taction: {\n\t\t\ttitle: \"Dismiss\",\n\t\t\tonClick: () => window.localStorage.setItem(DISMISSED_INSTANT_NPM_TOAST_STORAGE_KEY, \"true\"),\n\t\t},\n\t})\n}\n\nexport function hideInstantNPMToast() {\n\ttoast({\n\t\ttype: \"remove\",\n\t\tkey: INSTANT_NPM_TOAST_KEY,\n\t})\n}\n", "import type initCompiler from \"@framerjs/framer-compiler\"\nimport type { analyzeImports } from \"@framerjs/framer-compiler\"\nimport compilerWASMPath from \"@framerjs/framer-compiler/framer_compiler_bg.wasm\"\nimport type { Annotations, ExportSpecifier, ExportedIdentifierType } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ModulesAPI } from \"@framerjs/framer-services\"\nimport type { LocalModuleId } from \"@framerjs/shared\"\nimport { ModuleType, getLogger, hostInfo } from \"@framerjs/shared\"\nimport type { CodeGenerationTelemetrySession } from \"code-generation/TelemetrySession.ts\"\nimport type { Remote } from \"comlink\"\nimport { wrap } from \"comlink\"\nimport { getTunnelId } from \"environment/getTunnelId.ts\"\nimport type { DeepMutable } from \"utils/Mutable.ts\"\nimport { randomBase62 } from \"utils/base62.ts\"\nimport { absoluteEditorPath } from \"utils/platformPaths.ts\"\nimport type { Result } from \"utils/result.ts\"\nimport {\n\tperformanceClearMarks,\n\tperformanceClearMeasures,\n\tperformanceMark,\n\tperformanceMeasure,\n} from \"utils/userTiming.ts\"\nimport { ErrorArea, record } from \"web/lib/tracker.ts\"\nimport { COMPILER_CONTRACT_VERSION } from \"./compilerContractVersion.ts\"\nimport { filenamesFromModuleName } from \"./filenamesFromModuleName.ts\"\nimport type { AnalyzedImports, ModuleSpecifier } from \"./types.ts\"\n\nconst log = getLogger(\"compiler\")\n\ninterface CompilerConfig {\n\tfileName: string\n\tframerContractVersion: number\n\tmediaType: \"tsx\" | \"typescript\" | \"jsx\" | \"js\"\n\tminify: boolean\n\tcompress: boolean\n\tmangle: boolean\n\tuseClassicJsxTransform?: boolean\n\tuseReactRefresh?: boolean\n\tsourceMap?: boolean\n}\n\ninterface TransformResult {\n\tcode: CodeWithRelativeImports\n\tmap: string | null\n\tmetadata: Metadata\n}\n\ninterface FramerCompilerModule {\n\tdefault: typeof initCompiler\n\ttransformSync(source: string, opts: CompilerConfig): Promise<TransformResult>\n\tanalyzeImports: typeof analyzeImports\n}\n\ninterface FramerCompilerModuleWorker extends FramerCompilerModule {\n\tinitWithPathToWasm: typeof initCompiler\n}\n\ntype Compiler = Pick<FramerCompilerModule, \"analyzeImports\" | \"transformSync\">\n\ninterface Metadata {\n\trequestedModules: {\n\t\tabsolute: ModuleSpecifier[]\n\t\trelative: ModuleSpecifier[]\n\t\tbare: ModuleSpecifier[]\n\t}\n\texports: TypeExportMap\n\treExportedModules: string[]\n}\n\ninterface TypeExport {\n\ttype: ExportedIdentifierType\n\tannotations?: Annotations | null\n}\n\ntype TypeExportMap = Record<ExportSpecifier, TypeExport>\n\ninterface CompiledModule {\n\tcode: CodeWithRelativeImports\n\tsourceMap: string | undefined\n\tannotations: Record<ExportSpecifier, Annotations | undefined>\n\texportedNames: string[]\n\treExportedModules: string[]\n\timports: DeepMutable<ModulesAPI.Imports>\n}\n\n/** Opaque string type, representing module code that has all the relative import module specifiers preserved. */\nexport type CodeWithRelativeImports = string & { readonly __OPAQUE__: \"CodeWithRelativeImports\" }\n\nexport async function preloadCompiler(): Promise<void> {\n\tawait getCompiler()\n}\n\nfunction createErrorResponse(error: unknown) {\n\treturn {\n\t\tcode: `const err = new Error(${JSON.stringify(\n\t\t\tString(error),\n\t\t)}); err.name = \"CompilationError\"; throw err;` as CodeWithRelativeImports,\n\t\tsourceMap: undefined,\n\t\tannotations: {},\n\t\texportedNames: [],\n\t\treExportedModules: [],\n\t\timports: {\n\t\t\tabsolute: [],\n\t\t\trelative: [],\n\t\t\tbare: [],\n\t\t},\n\t}\n}\n\nfunction processCompilationResult(code: CodeWithRelativeImports, metadata: Metadata, addFramerMetadata: boolean) {\n\t// Store the exported types and annotations metadata in the compiled\n\t// module. We may want to figure out a nicer format for this in the\n\t// future. Note that the compiler and JSON refers to these type exports\n\t// as just \"exports\" while the \"exportedNames\" return value only refers\n\t// to exported JavaScript identifiers (excluding types).\n\tconst exportedTypes: TypeExportMap = { ...metadata.exports }\n\tif (addFramerMetadata) {\n\t\texportedTypes.__FramerMetadata__ = { type: \"variable\" }\n\n\t\tcode = code.concat(\n\t\t\t\"\\nexport const __FramerMetadata__ = \",\n\t\t\tJSON.stringify({ exports: exportedTypes }),\n\t\t) as CodeWithRelativeImports\n\t}\n\n\t// Filter out TypeScript types.\n\tconst exportedNames = Object.entries(exportedTypes)\n\t\t.filter(([, info]) => info.type !== \"tsType\")\n\t\t.map(([exportedName]) => exportedName)\n\n\tconst annotations = {}\n\tfor (const [exportSpecifier, exportMetadata] of Object.entries(metadata.exports)) {\n\t\tif (!exportMetadata.annotations) continue\n\t\tannotations[exportSpecifier] = exportMetadata.annotations\n\t}\n\n\treturn { moduleCode: code, annotations, exportedNames }\n}\n\nexport async function compileModuleForFastRefresh({\n\tlocalId,\n\tname,\n\tsource,\n\tincludeSourceMap = true,\n}: {\n\tlocalId: LocalModuleId\n\tname: string\n\tsource: string\n\tincludeSourceMap?: boolean\n}): Promise<CompiledModule> {\n\tconst compiler = await getCompiler()\n\n\ttry {\n\t\tconst { code, metadata, map } = await compiler.transformSync(source, {\n\t\t\tfileName: filenamesFromModuleName(name).source,\n\t\t\tframerContractVersion: COMPILER_CONTRACT_VERSION,\n\t\t\tmediaType: \"tsx\",\n\t\t\tminify: false,\n\t\t\tcompress: false,\n\t\t\tmangle: false,\n\t\t\tsourceMap: includeSourceMap,\n\t\t\tuseReactRefresh: true,\n\t\t})\n\n\t\t// The reactRefreshRuntime object is set on window in preview-module/bootstrap.tsx\n\t\tconst codeWithReactFastRefresh = `\nif (!window.$RefreshReg$) throw new Error(\"React refresh preamble was not loaded. Something is wrong.\");\nconst prevRefreshReg = window.$RefreshReg$;\nconst prevRefreshSig = window.$RefreshSig$;\nwindow.$RefreshReg$ = window.reactRefreshRuntime.getRefreshReg(\"${localId}\");\nwindow.$RefreshSig$ = window.reactRefreshRuntime.createSignatureFunctionForTransform;\n\n${code}\n\nwindow.$RefreshReg$ = prevRefreshReg;\nwindow.$RefreshSig$ = prevRefreshSig;` as CodeWithRelativeImports\n\n\t\tconst { moduleCode, annotations, exportedNames } = processCompilationResult(\n\t\t\tcodeWithReactFastRefresh,\n\t\t\tmetadata,\n\t\t\ttrue,\n\t\t)\n\n\t\treturn {\n\t\t\tcode: moduleCode,\n\t\t\tsourceMap: map ?? undefined,\n\t\t\timports: metadata.requestedModules,\n\t\t\tannotations,\n\t\t\texportedNames,\n\t\t\treExportedModules: metadata.reExportedModules,\n\t\t}\n\t} catch (error) {\n\t\tconst message = `Failed to compile development module ${name}: ${error}`\n\t\tlog.debug(message, \"(enable trace logging to see full source)\")\n\t\tlog.trace(source)\n\t\tif (!localId.startsWith(\"codeFile/\")) {\n\t\t\tlog.reportCriticalError(new Error(message, { cause: error }), { moduleName: name, moduleSource: source })\n\t\t\trecord(\"application_error\", { message, area: ErrorArea.compiler })\n\t\t}\n\t\t// The error we are dealing with here is a string, not an Error object.\n\t\treturn createErrorResponse(error)\n\t}\n}\n\nexport async function compileModuleForPlugin(moduleName: string, source: string) {\n\tconst compiler = await getCompiler()\n\n\tawait compiler.transformSync(source, {\n\t\tfileName: filenamesFromModuleName(moduleName).source,\n\t\tframerContractVersion: COMPILER_CONTRACT_VERSION,\n\t\tmediaType: \"tsx\",\n\t\tminify: true,\n\t\tcompress: false,\n\t\tmangle: false,\n\t\tsourceMap: false,\n\t\tuseReactRefresh: false,\n\t})\n}\n\nexport async function compileModule({\n\tname,\n\tsource,\n\ttype,\n\tincludeSourceMap = true,\n\taddFramerMetadata = true,\n\ttelemetrySession,\n}: {\n\tlocalId?: LocalModuleId\n\tname: string\n\tsource: string\n\t// Is this always ModuleType?\n\ttype: string\n\tincludeSourceMap?: boolean\n\taddFramerMetadata?: boolean\n\ttelemetrySession?: CodeGenerationTelemetrySession\n}): Promise<CompiledModule> {\n\tconst uid: string = randomBase62(10)\n\tconst markName = `compile-${name}-${uid}`\n\tconst measureName = `\uD83D\uDCDD Compile ${name}`\n\n\tlog.debug(\"Compiling module\", name, \"; with source map:\", includeSourceMap)\n\tperformanceMark(markName)\n\n\tconst compiler = await getCompiler()\n\tconst telemetryTask = telemetrySession?.start(\"transform\")\n\tconst compressAndMangle = type === ModuleType.Collection\n\n\ttry {\n\t\tconst { code, map, metadata } = await compiler.transformSync(source, {\n\t\t\tfileName: filenamesFromModuleName(name).source,\n\t\t\tframerContractVersion: COMPILER_CONTRACT_VERSION,\n\t\t\tmediaType: \"tsx\",\n\t\t\tminify: true,\n\t\t\tcompress: compressAndMangle,\n\t\t\tmangle: compressAndMangle,\n\t\t\tsourceMap: includeSourceMap,\n\t\t\tuseReactRefresh: false,\n\t\t})\n\n\t\tconst { moduleCode, annotations, exportedNames } = processCompilationResult(code, metadata, addFramerMetadata)\n\n\t\treturn {\n\t\t\tcode: moduleCode,\n\t\t\tsourceMap: map ?? undefined,\n\t\t\timports: metadata.requestedModules,\n\t\t\tannotations,\n\t\t\texportedNames,\n\t\t\treExportedModules: metadata.reExportedModules,\n\t\t}\n\t} catch (error) {\n\t\tconst message = `Failed to compile module ${name}: ${error}`\n\t\tlog.debug(message, \"(enable trace logging to see full source)\")\n\t\tlog.trace(source)\n\t\tif (!name.startsWith(\"codeFile/\")) {\n\t\t\tlog.reportCriticalError(new Error(message, { cause: error }), { moduleName: name, moduleSource: source })\n\t\t\trecord(\"application_error\", { message, area: ErrorArea.compiler })\n\t\t}\n\t\t// The error we are dealing with here is a string, not an Error object.\n\t\treturn createErrorResponse(error)\n\t} finally {\n\t\ttelemetryTask?.end()\n\t\treportCompilationMeasurements(measureName, markName)\n\t}\n}\n\n/**\n * Returns the module's imports.\n * If the compiler fails to analyze the module due to a syntax error, return an empty imports object.\n */\nexport async function analyzeModuleImports(code: string): Promise<Result<AnalyzedImports, Error>> {\n\tconst uid: string = randomBase62(10)\n\tconst markName = `analyze-imports-${uid}`\n\tconst measureName = `\uD83D\uDD75\uD83C\uDFFB Analyze Imports`\n\tperformanceMark(markName)\n\n\ttry {\n\t\tconst compiler = await getCompiler()\n\n\t\tconst analyzedImports = await compiler.analyzeImports(code)\n\n\t\treturn { ok: true, value: analyzedImports }\n\t} catch (err: unknown) {\n\t\tlog.warn(\"Failed to analyze imports:\", err)\n\t\tif (err instanceof Error) {\n\t\t\treturn { ok: false, error: err }\n\t\t} else {\n\t\t\treturn { ok: false, error: new Error(`${err}`, { cause: err }) }\n\t\t}\n\t} finally {\n\t\treportCompilationMeasurements(measureName, markName)\n\t}\n}\n\nlet compilerPromise: Promise<Compiler> | undefined = undefined\n\nasync function getCompiler(): Promise<Compiler> {\n\tif (!compilerPromise) {\n\t\tconst worker = new Worker(absoluteEditorPath(\"./modulesCompilerWorker.js\"))\n\t\tconst workerMod: Remote<FramerCompilerModuleWorker> = wrap(worker)\n\t\tcompilerPromise = workerMod\n\t\t\t.initWithPathToWasm(compilerWASMPath)\n\t\t\t.then(() => ({ transformSync: workerMod.transformSync, analyzeImports: workerMod.analyzeImports }))\n\n\t\tcompilerPromise.catch(() => {\n\t\t\t// FIXME: In some cases the compiler seems to not instantiate correctly in\n\t\t\t// development, and the error message is arcane. So until we figure out\n\t\t\t// why this Error should help developers recover quickly :).\n\t\t\t// Note: testing has led me to believe that the issue is not with the\n\t\t\t// generated compiler files but somewhere else in the build artifacts. I\n\t\t\t// dont have a reliable reproduction so I cant carry on testing.\n\t\t\tif (getTunnelId() || !hostInfo.isProduction) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`\u274C Your dev setup is struggling to run the compiler\u2019s WASM binary.\\nTo fix it, run \"make clean\" followed by \"make dev\".`,\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\n\treturn compilerPromise\n}\n\nfunction reportCompilationMeasurements(measureName: string, markName: string) {\n\tif (process.env.NODE_ENV === \"test\") return\n\n\tperformanceMeasure(measureName, markName)\n\t// eslint-disable-next-line compat/compat -- performance.getEntriesByName *is* supported in Opera 114+, so compat is wrong here.\n\tperformance.getEntriesByName(measureName, \"measure\").forEach(({ name, duration }) => {\n\t\tlog.debug(name, \"took\", duration.toFixed(2), \"ms\")\n\t\tperformanceClearMeasures(name)\n\t})\n\tperformanceClearMarks(markName)\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { prefersAutoSizing } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { WithPins } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\n\n// Insert code components that support auto-sizing as width/height set to auto,\n// unless they default to fixed or their primary variant is using a fixed size.\n// That way they can be rendered without any styles passed in and we'll measure\n// whatever they rendered with their default props.\nexport function setDimensionTypeAutoIfSupported(\n\tcomponentLoader: ComponentLoader,\n\tnode: CanvasNode,\n\tupdate: Partial<WithPins>,\n) {\n\tif (!isCodeComponentNode(node)) {\n\t\treturn\n\t}\n\tconst supportedLayout = node.getSupportedLayout(componentLoader)\n\tconst variantSize = node.getCurrentVariantSize(componentLoader)\n\tif (prefersAutoSizing(supportedLayout.width) && variantSize?.widthType !== DimensionType.FixedNumber) {\n\t\tupdate.widthType = DimensionType.Auto\n\t\t// When width is set to Auto, both pins can't be enabled\n\t\tif (update.left !== null && update.right !== null) {\n\t\t\tupdate.right = null\n\t\t}\n\t}\n\tif (prefersAutoSizing(supportedLayout.height) && variantSize?.heightType !== DimensionType.FixedNumber) {\n\t\tupdate.heightType = DimensionType.Auto\n\t\t// When width is set to Auto, both pins can't be enabled\n\t\tif (update.top !== null && update.bottom !== null) {\n\t\t\tupdate.bottom = null\n\t\t}\n\t}\n}\n", "import type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { acceptsChild } from \"document/models/CanvasTree/traits/utils/acceptsChild.ts\"\n\nexport function getParentForInsertNode(component: CanvasNode, engine: VekterEngine): CanvasNode | null {\n\tconst [selection, ...multiSelection] = engine.stores.selectionStore.ids\n\n\tif (!selection || multiSelection.length) return null\n\tconst tree = engine.tree\n\n\tlet parent = tree.getNode(selection)\n\tlet parentAcceptsChildren = false\n\n\t// Walk the tree looking for the first parent that accepts a child, until there is no parent.\n\twhile (!parentAcceptsChildren && parent) {\n\t\tparentAcceptsChildren = acceptsChild(\n\t\t\ttree,\n\t\t\tparent,\n\t\t\tcomponent,\n\t\t\tengine.stores.scopeStore.active.id,\n\t\t\tengine.componentLoader,\n\t\t)\n\t\tif (parentAcceptsChildren) break\n\t\tparent = tree.getParent(parent.id)\n\t}\n\n\treturn parent\n}\n", "import { type CanvasTree, type NodeID, isScopeNode } from \"./CanvasTree/index.ts\"\n\nexport function resetAncestorCacheForNodes(tree: CanvasTree, nodeIds: Set<NodeID>) {\n\tconst scopeNodeIds = new Set<NodeID>()\n\tconst seenNodeIds = new Set<NodeID>()\n\n\tfor (const nodeId of nodeIds) {\n\t\tif (seenNodeIds.has(nodeId)) continue\n\n\t\tconst node = tree.get(nodeId)\n\t\tif (!node) continue\n\n\t\tif (isScopeNode(node)) {\n\t\t\tscopeNodeIds.add(nodeId)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const ancestor of node.ancestors()) {\n\t\t\tif (seenNodeIds.has(ancestor.id)) continue\n\t\t\tseenNodeIds.add(ancestor.id)\n\n\t\t\tancestor.cache.reset()\n\n\t\t\tif (!isScopeNode(ancestor)) continue\n\t\t\tscopeNodeIds.add(ancestor.id)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn scopeNodeIds\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert } from \"@framerjs/shared\"\nimport type { CanvasNode, CanvasTree, MaybeNodeID, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isSmartComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type {\n\tVariableProviderControlMap,\n\tVariableProviderVariableMap,\n} from \"document/models/CanvasTree/traits/VariableProvider.ts\"\nimport { hasRepeatArray } from \"document/models/CanvasTree/traits/WithRepeatArray.ts\"\nimport { withVariableProvider } from \"document/models/CanvasTree/traits/WithVariableProvider.ts\"\nimport {\n\ttype EnumVariableDefinition,\n\ttype VariableID,\n\ttype VariableType,\n\twithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { isShallowArrayEqual } from \"utils/isShallowEqual.ts\"\nimport type { NodeProvidingLocaleEnumVariable } from \"./LocaleVariable.ts\"\nimport {\n\tgetLocaleVariableMap,\n\tgetLocaleVariableProviderControlMap,\n\tisProvidingLocaleVariable,\n\tlocaleProviderId,\n\tlocaleSourceIdentifier,\n} from \"./LocaleVariable.ts\"\n\nexport type ProviderID = NodeID\ntype CombinedVariableMaps = Map<ProviderID, VariableProviderVariableMap>\ntype CombinedControlMaps = Map<ProviderID, VariableProviderControlMap>\n\ninterface EnumInfo {\n\tvariable: EnumVariableDefinition\n\tproviderId: NodeID\n\tsourceIdentifier: ModuleExportIdentifierString\n}\n\nexport interface VariableProviderInfo {\n\treadonly combined: CombinedVariableMaps\n\treadonly combinedControls: CombinedControlMaps\n\treadonly ids: Set<VariableID>\n\treadonly types: Set<VariableType>\n\t/** A list of provider ids in ancestors order from the first selected node. */\n\treadonly providerIds: readonly NodeID[]\n\t/** The node that defines the variables, on which we could mutate the variables. For example, a SmartComponentNode or a LayoutTemplateNode. */\n\treadonly idOfMutableVariableProvider: MaybeNodeID\n\t/** Originally the provider id wasn't set on variable references. This can only be a smart component root. Here we set that id as fallback. */\n\treadonly fallbackProvider: MaybeNodeID\n\t/** Required for comparing enums. */\n\treadonly variableSourceIdentifiers: Record<NodeID, ModuleExportIdentifierString>\n\treadonly enums: EnumInfo[]\n}\n\nfunction getVariableListsAndProviderIds(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CanvasNode,\n): { variableMaps: VariableProviderVariableMap[]; providerIds: readonly NodeID[] } {\n\tconst variableMaps: VariableProviderVariableMap[] = []\n\tconst providerIds: NodeID[] = []\n\n\tconst addProviderVariableMap = (provider: CanvasNode, providerChild: CanvasNode | undefined): void => {\n\t\tif (!withVariableProvider(provider)) return\n\n\t\tconst variableMap = provider.getProvidedVariableMap(\n\t\t\ttree,\n\t\t\tproviderChild,\n\t\t\tcomponentLoader,\n\t\t\tcomponentLoader.activeBundleHash,\n\t\t)\n\n\t\tif (!variableMap) return\n\n\t\tconst providerId = provider.getPrimaryId()\n\t\tproviderIds.push(providerId)\n\t\tvariableMaps.push(variableMap)\n\t}\n\n\tif (hasRepeatArray(node)) {\n\t\taddProviderVariableMap(node, undefined)\n\t}\n\n\tlet nextAncestorChild = node\n\tfor (const ancestor of node.ancestors()) {\n\t\tconst ancestorChild = nextAncestorChild\n\t\tnextAncestorChild = ancestor\n\n\t\taddProviderVariableMap(ancestor, ancestorChild)\n\n\t\tif (isProvidingLocaleVariable(ancestor)) {\n\t\t\tconst localeVariableMap = getLocaleVariableMap(tree)\n\t\t\tif (localeVariableMap) variableMaps.push(localeVariableMap)\n\t\t}\n\t}\n\treturn { variableMaps, providerIds }\n}\n\nexport const getMemoizedVariableProviderInfo = (() => {\n\tlet lastVariableMaps: VariableProviderVariableMap[] = []\n\tlet lastProviderIds: readonly NodeID[] = []\n\tlet lastResult: VariableProviderInfo | undefined\n\treturn (\n\t\ttree: CanvasTree,\n\t\tcomponentLoader: ComponentLoader,\n\t\tallNodesShareVariableContext: boolean,\n\t\tallNodesSupportVariableReferences: boolean,\n\t\tfirstNode: CanvasNode | undefined,\n\t): VariableProviderInfo | null => {\n\t\tif (!allNodesShareVariableContext || !firstNode) {\n\t\t\treturn null\n\t\t}\n\t\tif (!allNodesSupportVariableReferences) {\n\t\t\treturn null\n\t\t}\n\t\tconst { variableMaps, providerIds } = getVariableListsAndProviderIds(tree, componentLoader, firstNode)\n\t\tif (variableMaps.length === 0) {\n\t\t\treturn null\n\t\t}\n\n\t\t// The available variable can only have changed when variable lists are no longer shallow equal\n\t\t// or when the providers have changed since variable info is built around the\n\t\t// providers id (that hold the variables definition)\n\t\tif (\n\t\t\t!lastResult ||\n\t\t\t!isShallowArrayEqual(lastVariableMaps, variableMaps) ||\n\t\t\t!isShallowArrayEqual(lastProviderIds, providerIds)\n\t\t) {\n\t\t\tlastVariableMaps = variableMaps\n\t\t\tlastProviderIds = providerIds\n\n\t\t\tconst combinedVariables: CombinedVariableMaps = new Map()\n\t\t\tconst combinedControls: CombinedControlMaps = new Map()\n\t\t\tconst variableIds = new Set<VariableID>()\n\t\t\tconst allVariableTypes: Set<VariableType> = new Set()\n\t\t\tlet idOfMutableVariableProvider: MaybeNodeID = null\n\t\t\tlet fallbackProvider: MaybeNodeID = null\n\n\t\t\tconst variableSourceIdentifiers: Record<NodeID, ModuleExportIdentifierString> = {}\n\t\t\tconst enums: EnumInfo[] = []\n\n\t\t\tlet localeVariableProvider: NodeProvidingLocaleEnumVariable | null = null\n\n\t\t\tfunction addProviderInfo(provider: CanvasNode, providerChild: CanvasNode | undefined): void {\n\t\t\t\tif (!withVariableProvider(provider)) return\n\n\t\t\t\tconst variableMap = provider.getProvidedVariableMap(\n\t\t\t\t\ttree,\n\t\t\t\t\tproviderChild,\n\t\t\t\t\tcomponentLoader,\n\t\t\t\t\tcomponentLoader.activeBundleHash,\n\t\t\t\t)\n\t\t\t\tif (!variableMap) return\n\n\t\t\t\tconst providerId = provider.getPrimaryId()\n\t\t\t\tconst variableSourceIdentifier = provider.getVariableSourceIdentifier()\n\n\t\t\t\tif (variableSourceIdentifier) {\n\t\t\t\t\tvariableSourceIdentifiers[providerId] = variableSourceIdentifier\n\t\t\t\t}\n\n\t\t\t\tfor (const [variableId, variable] of variableMap) {\n\t\t\t\t\tvariableIds.add(variableId)\n\t\t\t\t\tallVariableTypes.add(variable.type)\n\n\t\t\t\t\tif (variable.type === ControlType.Enum) {\n\t\t\t\t\t\tassert(variableSourceIdentifier, \"Variable source identifier should exist for enum variables\")\n\t\t\t\t\t\tenums.push({ variable, providerId, sourceIdentifier: variableSourceIdentifier })\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (withVariables(provider)) {\n\t\t\t\t\tidOfMutableVariableProvider = providerId\n\t\t\t\t}\n\n\t\t\t\tif (isSmartComponentNode(provider)) {\n\t\t\t\t\tfallbackProvider = providerId\n\t\t\t\t}\n\n\t\t\t\tcombinedVariables.set(providerId, variableMap)\n\n\t\t\t\tconst controlMap = provider.getProvidedControlMap(\n\t\t\t\t\ttree,\n\t\t\t\t\tproviderChild,\n\t\t\t\t\tcomponentLoader,\n\t\t\t\t\tcomponentLoader.activeBundleHash,\n\t\t\t\t)\n\t\t\t\tif (controlMap) combinedControls.set(providerId, controlMap)\n\t\t\t}\n\n\t\t\tif (hasRepeatArray(firstNode)) {\n\t\t\t\taddProviderInfo(firstNode, undefined)\n\t\t\t}\n\n\t\t\tlet nextAncestorChild = firstNode\n\t\t\tfor (const ancestor of firstNode.ancestors()) {\n\t\t\t\tconst ancestorChild = nextAncestorChild\n\t\t\t\tnextAncestorChild = ancestor\n\n\t\t\t\tif (isProvidingLocaleVariable(ancestor)) {\n\t\t\t\t\tlocaleVariableProvider = ancestor\n\t\t\t\t}\n\n\t\t\t\taddProviderInfo(ancestor, ancestorChild)\n\t\t\t}\n\n\t\t\tif (localeVariableProvider) {\n\t\t\t\tconst localeVariables = getLocaleVariableMap(tree)\n\t\t\t\tif (localeVariables) {\n\t\t\t\t\tvariableSourceIdentifiers[localeProviderId] = localeSourceIdentifier\n\n\t\t\t\t\tfor (const [variableId, variable] of localeVariables) {\n\t\t\t\t\t\tvariableIds.add(variableId)\n\t\t\t\t\t\tallVariableTypes.add(variable.type)\n\n\t\t\t\t\t\tassert(variable.type === ControlType.Enum)\n\n\t\t\t\t\t\tif (variable.type === ControlType.Enum) {\n\t\t\t\t\t\t\tenums.push({ variable, providerId: localeProviderId, sourceIdentifier: localeSourceIdentifier })\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcombinedVariables.set(localeProviderId, localeVariables)\n\n\t\t\t\t\tconst controlMap = getLocaleVariableProviderControlMap(tree)\n\t\t\t\t\tassert(controlMap, \"Control map should be defined because we received locale variables\")\n\t\t\t\t\tcombinedControls.set(localeProviderId, controlMap)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlastResult = {\n\t\t\t\tcombined: combinedVariables,\n\t\t\t\tcombinedControls,\n\t\t\t\tids: variableIds,\n\t\t\t\ttypes: allVariableTypes,\n\t\t\t\tproviderIds,\n\t\t\t\tidOfMutableVariableProvider,\n\t\t\t\tfallbackProvider,\n\t\t\t\tvariableSourceIdentifiers,\n\t\t\t\tenums,\n\t\t\t}\n\t\t}\n\t\treturn lastResult\n\t}\n})()\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert } from \"@framerjs/shared\"\nimport { hasNavigationLinks } from \"document/models/CanvasTree/actions/navigationActions.ts\"\nimport { hasVariantLinks } from \"document/models/CanvasTree/actions/variantActions.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { TemplateHelper } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport {\n\tisCodeComponentNode,\n\tisLayoutTemplateNode,\n\tisRichTextNode,\n\tisShaderNode,\n\tisShapeContainerNode,\n\tisSmartComponentNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { isTopLevelVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\n\ninterface IndexNodes {\n\treadonly smartComponentNodeIds: Set<NodeID>\n\treadonly layoutTemplateNodeIds: Set<NodeID>\n\treadonly richTextNodeIds: Set<NodeID>\n\treadonly codeComponentNodeIds: Set<NodeID>\n\treadonly shaderNodeIds: Set<NodeID>\n\treadonly navigationActionNodeIds: Set<NodeID>\n\treadonly setVariantActionNodeIds: Set<NodeID>\n\treadonly shapeContainerNodeIds: Set<NodeID>\n\treadonly formContainerNodeIds: Set<NodeID>\n\treadonly withDataIdentifierNodeIds: Set<NodeID>\n}\nexport class VerificationIndex {\n\treadonly smartComponentNodes = new Set<NodeID>()\n\treadonly layoutTemplateNodes = new Set<NodeID>()\n\treadonly codeComponentNodes = new Set<NodeID>()\n\treadonly shaderNodes = new Set<NodeID>()\n\treadonly richTextNodes = new Set<NodeID>()\n\treadonly masterNodes = new Set<NodeID>()\n\treadonly navigationActionNodes = new Set<NodeID>()\n\treadonly setVariantActionNodes = new Set<NodeID>()\n\treadonly shapeContainerNodes = new Set<NodeID>()\n\treadonly formContainerNodes = new Set<NodeID>()\n\treadonly withDataIdentifierNodes = new Set<NodeID>()\n\n\tconstructor(\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly nodeIgnoredInNodeIdIndex: (node: CanvasNode | null | undefined) => boolean,\n\t) {}\n\n\tprivate reset() {\n\t\tthis.smartComponentNodes.clear()\n\t\tthis.layoutTemplateNodes.clear()\n\t\tthis.codeComponentNodes.clear()\n\t\tthis.shaderNodes.clear()\n\t\tthis.richTextNodes.clear()\n\t\tthis.masterNodes.clear()\n\t\tthis.navigationActionNodes.clear()\n\t\tthis.setVariantActionNodes.clear()\n\t\tthis.shapeContainerNodes.clear()\n\t\tthis.formContainerNodes.clear()\n\t\tthis.withDataIdentifierNodes.clear()\n\t}\n\n\tprivate verifyNode(referenceSet: Set<NodeID>, indexSet: Set<NodeID>, name: string) {\n\t\tassert(\n\t\t\treferenceSet.size === indexSet.size,\n\t\t\t\"VerificationIndex node \" + name + \" is out of sync:\",\n\t\t\treferenceSet.size,\n\t\t\t\"!==\",\n\t\t\tindexSet.size,\n\t\t)\n\n\t\tfor (const id of referenceSet) {\n\t\t\tassert(indexSet.has(id), \"Tree index for \" + name + \" does not exists\")\n\t\t}\n\t}\n\n\tupdate(tree: CanvasTree) {\n\t\tthis.reset()\n\n\t\ttree.forEachNode(node => {\n\t\t\tif (this.nodeIgnoredInNodeIdIndex(node)) return\n\n\t\t\tif (isShapeContainerNode(node)) {\n\t\t\t\tthis.shapeContainerNodes.add(node.id)\n\t\t\t}\n\n\t\t\tif (isCodeComponentNode(node)) {\n\t\t\t\tthis.codeComponentNodes.add(node.id)\n\t\t\t}\n\n\t\t\tif (isShaderNode(node)) {\n\t\t\t\tthis.shaderNodes.add(node.id)\n\t\t\t}\n\n\t\t\tif (isRichTextNode(node)) {\n\t\t\t\tthis.richTextNodes.add(node.id)\n\t\t\t}\n\n\t\t\tif (isSmartComponentNode(node)) {\n\t\t\t\tthis.smartComponentNodes.add(node.id)\n\t\t\t}\n\n\t\t\tif (isLayoutTemplateNode(node)) {\n\t\t\t\tthis.layoutTemplateNodes.add(node.id)\n\t\t\t}\n\n\t\t\tif (hasNavigationLinks(node, this.componentLoader)) {\n\t\t\t\tthis.navigationActionNodes.add(node.id)\n\t\t\t}\n\n\t\t\tif (hasVariantLinks(node, this.componentLoader)) {\n\t\t\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, node)\n\n\t\t\t\tif (!replica || (replica && isTopLevelVariant(replica))) {\n\t\t\t\t\tthis.setVariantActionNodes.add(node.id)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isFormContainer(node)) {\n\t\t\t\tthis.formContainerNodes.add(node.id)\n\t\t\t}\n\n\t\t\tif (hasCollectionDataSource(node)) {\n\t\t\t\tthis.withDataIdentifierNodes.add(node.id)\n\t\t\t}\n\t\t})\n\t}\n\n\tverify({\n\t\tsmartComponentNodeIds,\n\t\tlayoutTemplateNodeIds,\n\t\tcodeComponentNodeIds,\n\t\tshaderNodeIds,\n\t\trichTextNodeIds,\n\t\tnavigationActionNodeIds,\n\t\tsetVariantActionNodeIds,\n\t\tshapeContainerNodeIds,\n\t\tformContainerNodeIds,\n\t\twithDataIdentifierNodeIds,\n\t}: IndexNodes) {\n\t\tthis.verifyNode(this.smartComponentNodes, smartComponentNodeIds, \"SmartComponents\")\n\t\tthis.verifyNode(this.layoutTemplateNodes, layoutTemplateNodeIds, \"LayoutTemplates\")\n\t\tthis.verifyNode(this.codeComponentNodes, codeComponentNodeIds, \"CodeComponents\")\n\t\tthis.verifyNode(this.shaderNodes, shaderNodeIds, \"ShaderNodes\")\n\t\tthis.verifyNode(this.richTextNodes, richTextNodeIds, \"RichTextNodes\")\n\t\tthis.verifyNode(this.shapeContainerNodes, shapeContainerNodeIds, \"shapeContainerNodes\")\n\t\tthis.verifyNode(this.navigationActionNodes, navigationActionNodeIds, \"NavigationActionNodes\")\n\t\tthis.verifyNode(this.setVariantActionNodes, setVariantActionNodeIds, \"setVariantActionNodes\")\n\t\tthis.verifyNode(this.formContainerNodes, formContainerNodeIds, \"formContainerNodes\")\n\t\tthis.verifyNode(this.withDataIdentifierNodes, withDataIdentifierNodeIds, \"withDataIdentifierNodes\")\n\t}\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ExternalModuleExportIdentifierString, ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, isExternalModuleIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { EngineChange } from \"document/EngineChanges.ts\"\nimport { searchComponentModuleId } from \"document/components/chrome/insertSidebar/dataSources/items/interactiveItems.ts\"\nimport { MAX_VERIFY_TREE_SIZE } from \"document/models/CanvasTree/NodeTree.ts\"\nimport type { NodeChangesReader, TreeUpdater } from \"document/models/CanvasTree/TreeUpdater.ts\"\nimport { getNavigationActions, hasNavigationLinks } from \"document/models/CanvasTree/actions/navigationActions.ts\"\nimport { getSetVariantActionTargets, hasVariantLinks } from \"document/models/CanvasTree/actions/variantActions.ts\"\nimport type {\n\tCanvasNode,\n\tCanvasTree,\n\tCodeComponentNode,\n\tNodeID,\n\tScopeNode,\n\tShapeContainerNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { isScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport { isLocalModuleNode, isLocalModulesListNode } from \"document/models/CanvasTree/nodes/LocalModuleNode.ts\"\nimport { TemplateHelper } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport {\n\tisCodeComponentNode,\n\tisComponentPresetNode,\n\tisErrorListNode,\n\tisErrorNode,\n\tisExternalModuleNode,\n\tisExternalModulesListNode,\n\tisLayoutTemplateNode,\n\tisRichTextNode,\n\tisRootNode,\n\tisShaderNode,\n\tisShapeContainerNode,\n\tisSmartComponentNode,\n\tisStackComponent,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { getSlotKeys, isValidSlotItemNode } from \"document/models/CanvasTree/nodes/utils/slotUtils.ts\"\nimport {\n\thasCollectionDataSource,\n\twithCollectionDataSource,\n} from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { isHiddenMaster } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { IsVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isGestureVariant, isTopLevelVariant, isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport { isStylableCodeComponent } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifierChecks.ts\"\nimport { VerificationIndex } from \"document/utils/VerificationIndex.ts\"\nimport { environment } from \"environment/index.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isShallowArrayEqual, isShallowSetEqual } from \"utils/isShallowEqual.ts\"\n\nexport interface NodeLink<FromNode, ToNode> {\n\treadonly fromNode: FromNode\n\treadonly toNode: ToNode\n}\n\ntype VariantNode = CanvasNode & IsVariant\n\n/** we don't always show arrows for selected screens, if that becomes too much */\nconst maxSelectedScreensToRenderArrowsFor = 25\n\nconst TrueSet = new (class extends Set {\n\t// biome-ignore lint/suspicious/noExplicitAny: @TODO add explanation\n\toverride has(_: any) {\n\t\treturn true\n\t}\n})()\n\n// Nodes types the treeIndex will ignore.\nfunction nodeIgnoredInNodeIdIndex(node: CanvasNode | null | undefined): boolean {\n\tif (!node) return false\n\treturn (\n\t\tisLocalModuleNode(node) ||\n\t\tisLocalModulesListNode(node) ||\n\t\tisExternalModuleNode(node) ||\n\t\tisExternalModulesListNode(node) ||\n\t\tisErrorListNode(node) ||\n\t\tisErrorNode(node)\n\t)\n}\n\ninterface NodeIdIndexEntry {\n\tscope: NodeID\n\tground: NodeID\n}\n\nexport class TreeIndex {\n\t// Safely using a non-null assertion operator (`!`) here because this field\n\t// is assigned in this.reset() which is called in the constructor\n\tprivate tree!: CanvasTree\n\tprivate readonly reader: NodeChangesReader\n\tprivate readonly verificationIndex: VerificationIndex\n\tprivate onEngineChange?: (change: EngineChange) => void\n\n\t// Document wide indexes to quickly get to all nodes of a certain type.\n\treadonly layoutTemplateNodeIds = new Set<NodeID>()\n\treadonly smartComponentNodeIds = new Set<NodeID>()\n\treadonly codeComponentNodeIds = new Set<NodeID>()\n\treadonly shaderNodeIds = new Set<NodeID>()\n\treadonly richTextNodeIds = new Set<NodeID>()\n\treadonly navigationActionNodeIds = new Set<NodeID>()\n\treadonly setVariantActionNodeIds = new Set<NodeID>()\n\treadonly shapeContainerNodeIds = new Set<NodeID>()\n\treadonly searchComponentNodeIds = new Set<NodeID>()\n\treadonly formContainerNodeIds = new Set<NodeID>()\n\treadonly withDataIdentifierNodeIds = new Set<NodeID>()\n\n\t/** Only used to track deprecated code component usage */\n\treadonly deprecatedCodeComponentNodeIds = new Set<NodeID>()\n\n\treadonly foundExternalModuleIdentifiers = new Set<ExternalModuleExportIdentifierString>()\n\treadonly externalModuleIdentifiersToLoad = new Set<ExternalModuleExportIdentifierString>()\n\n\t/** A map from node id to scope id and ground node id. */\n\treadonly nodeIdIndex = new Map<NodeID, NodeIdIndexEntry>()\n\n\t// Some lists we maintain, creating a new list if their content changes.\n\tactiveScopeLinkedNavigationNodes: readonly NodeLink<CanvasNode, CanvasNode>[] = []\n\tactiveScopeLinkedVariantNodes: readonly NodeLink<CanvasNode, VariantNode>[] = []\n\tactiveScopeLinkedGestureNodes: readonly NodeLink<VariantNode, VariantNode>[] = []\n\tactiveScopeCodeComponentArrows: ReadonlySet<CodeComponentNode> = new Set()\n\n\t/** Something we index only for the current scope. */\n\tprivate activeScopeId: NodeID = \"\"\n\n\t/** Ground nodes in the current scope. */\n\treadonly activeScopeGroundNodeIds = new Set<NodeID>()\n\n\t/** Flags to reduce the amount of times we process node changes */\n\tprivate _shouldChangeSmartComponents = false\n\tprivate _shouldChangeLayoutTemplates = false\n\tshouldChangeCodeComponents = false\n\tshouldChangeShaderNodes = false\n\tshouldChangeRichTextNodes = false\n\tshouldChangeNavigationActions = false\n\tshouldChangeShapeContainerNodes = false\n\tshouldChangeVariantActions = false\n\tshouldChangeActiveScopeGroundNodes = false\n\tshouldChangeWithDataIdentifierNodes = false\n\n\tget shouldChangeSmartComponents(): boolean {\n\t\treturn this._shouldChangeSmartComponents\n\t}\n\n\tset shouldChangeSmartComponents(value: boolean) {\n\t\tthis._shouldChangeSmartComponents = value\n\t\tif (value && this.onEngineChange) {\n\t\t\tthis.onEngineChange(EngineChange.LocalSmartComponents)\n\t\t}\n\t}\n\n\tget shouldChangeLayoutTemplates(): boolean {\n\t\treturn this._shouldChangeLayoutTemplates\n\t}\n\n\tset shouldChangeLayoutTemplates(value: boolean) {\n\t\tthis._shouldChangeLayoutTemplates = value\n\t\tif (value && this.onEngineChange) {\n\t\t\tthis.onEngineChange(EngineChange.LocalLayoutTemplates)\n\t\t}\n\t}\n\n\tconstructor(\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\ttreeUpdater: TreeUpdater,\n\t) {\n\t\tthis.verificationIndex = new VerificationIndex(componentLoader, nodeIgnoredInNodeIdIndex)\n\t\tthis.reader = treeUpdater.openNodeChangesReader()\n\t\tthis.reset(treeUpdater.tree)\n\t}\n\n\tsetOnEngineChange(callback: (change: EngineChange) => void): void {\n\t\tthis.onEngineChange = callback\n\t}\n\n\t/** Get the scope node id for a node id. Returns undefined if the node does not exist in a scope node. */\n\tgetScopeIdFor(id: NodeID | null | undefined): NodeID | undefined {\n\t\tif (!id) return\n\t\treturn this.nodeIdIndex.get(id)?.scope\n\t}\n\n\t/** Get the ground node id for a node id. Returns undefined if the node does not exist in a ground node. */\n\tgetGroundNodeIdFor(id: NodeID | null | undefined): NodeID | undefined {\n\t\tif (!id) return\n\t\treturn this.nodeIdIndex.get(id)?.ground\n\t}\n\n\t/** Get the ground node for a node id if any. */\n\tprivate getNodeIdToCurrentGroundNode(tree: CanvasTree, id: NodeID | null | undefined): CanvasNode | undefined {\n\t\tif (!id) return\n\t\tconst entry = this.nodeIdIndex.get(id)\n\t\tif (!entry) return\n\t\tif (entry.scope !== this.activeScopeId) return\n\t\treturn tree.get(entry.ground) || undefined\n\t}\n\n\tprivate addNode(tree: CanvasTree, node: CanvasNode) {\n\t\tif (isShapeContainerNode(node)) {\n\t\t\tthis.shouldChangeShapeContainerNodes = true\n\t\t\tthis.shapeContainerNodeIds.add(node.id)\n\t\t}\n\n\t\tif (isCodeComponentNode(node)) {\n\t\t\tthis.shouldChangeCodeComponents = true\n\t\t\tthis.codeComponentNodeIds.add(node.id)\n\t\t\tthis.handleSearchComponents(node)\n\t\t\tthis.handleDeprecatedCodeComponent(node)\n\t\t}\n\n\t\tif (isShaderNode(node)) {\n\t\t\tthis.shouldChangeShaderNodes = true\n\t\t\tthis.shaderNodeIds.add(node.id)\n\t\t}\n\n\t\tif (isFormContainer(node)) {\n\t\t\tthis.formContainerNodeIds.add(node.id)\n\t\t}\n\n\t\tif (isRichTextNode(node)) {\n\t\t\tthis.shouldChangeRichTextNodes = true\n\t\t\tthis.richTextNodeIds.add(node.id)\n\t\t}\n\n\t\tif (isSmartComponentNode(node)) {\n\t\t\tthis.shouldChangeSmartComponents = true\n\t\t\tthis.smartComponentNodeIds.add(node.id)\n\t\t}\n\n\t\tif (isLayoutTemplateNode(node)) {\n\t\t\tthis.shouldChangeLayoutTemplates = true\n\t\t\tthis.layoutTemplateNodeIds.add(node.id)\n\t\t}\n\n\t\tif (hasNavigationLinks(node, this.componentLoader)) {\n\t\t\tthis.shouldChangeNavigationActions = true\n\t\t\tthis.navigationActionNodeIds.add(node.id)\n\t\t}\n\n\t\tif (hasVariantLinks(node, this.componentLoader)) {\n\t\t\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, node)\n\n\t\t\tif (!replica || (replica && isTopLevelVariant(replica))) {\n\t\t\t\tthis.shouldChangeVariantActions = true\n\t\t\t\tthis.setVariantActionNodeIds.add(node.id)\n\t\t\t}\n\t\t}\n\n\t\tif (hasCollectionDataSource(node)) {\n\t\t\tthis.shouldChangeWithDataIdentifierNodes = true\n\t\t\tthis.withDataIdentifierNodeIds.add(node.id)\n\t\t}\n\n\t\tthis.handleExternalDataSource(node)\n\t}\n\n\tprivate handleSearchComponents(node: CodeComponentNode) {\n\t\t// Track existence of searchComponentNodes in the tree, used to\n\t\t// determine if we should show an infoCard in the publishing popover\n\t\t// if the searchablePages limit has been exceeded.\n\t\tconst parsedId = parseModuleIdentifier(node.codeComponentIdentifier)\n\t\tif (!parsedId) return\n\t\tif (!isExternalModuleIdentifier(parsedId)) return\n\t\tif (parsedId.moduleId === searchComponentModuleId) {\n\t\t\tthis.searchComponentNodeIds.add(node.id)\n\t\t}\n\t}\n\n\tprivate handleDeprecatedCodeComponent(node: CodeComponentNode) {\n\t\tif (!isStylableCodeComponent(node)) {\n\t\t\treturn\n\t\t}\n\n\t\t// Only track primary occurrence\n\t\tif (node.originalid) return\n\n\t\tthis.deprecatedCodeComponentNodeIds.add(node.id)\n\t}\n\n\tprivate handleExternalDataSource(node: CanvasNode) {\n\t\tlet identifier: ModuleExportIdentifierString | undefined = undefined\n\n\t\tif (withCollectionDataSource(node)) {\n\t\t\tidentifier = node.dataIdentifier\n\t\t}\n\t\tif (isComponentPresetNode(node)) {\n\t\t\tidentifier = node.componentIdentifier\n\t\t}\n\n\t\tif (!identifier) return\n\t\tif (!isExternalModuleIdentifier(identifier)) return\n\t\tif (this.foundExternalModuleIdentifiers.has(identifier)) return\n\n\t\tthis.foundExternalModuleIdentifiers.add(identifier)\n\t\tthis.externalModuleIdentifiersToLoad.add(identifier)\n\t}\n\n\tgetAndClearExternalDataSourcesToLoad(): ExternalModuleExportIdentifierString[] | null {\n\t\tif (this.externalModuleIdentifiersToLoad.size === 0) return null\n\n\t\tconst result = Array.from(this.externalModuleIdentifiersToLoad)\n\t\tthis.externalModuleIdentifiersToLoad.clear()\n\t\treturn result\n\t}\n\n\tprivate deleteNode(id: NodeID) {\n\t\tif (this.smartComponentNodeIds.delete(id)) this.shouldChangeSmartComponents = true\n\t\tif (this.layoutTemplateNodeIds.delete(id)) this.shouldChangeLayoutTemplates = true\n\t\tif (this.codeComponentNodeIds.delete(id)) this.shouldChangeCodeComponents = true\n\t\tif (this.shaderNodeIds.delete(id)) this.shouldChangeShaderNodes = true\n\t\tif (this.richTextNodeIds.delete(id)) this.shouldChangeRichTextNodes = true\n\t\tif (this.navigationActionNodeIds.delete(id)) this.shouldChangeNavigationActions = true\n\t\tif (this.setVariantActionNodeIds.delete(id)) this.shouldChangeVariantActions = true\n\t\tif (this.shapeContainerNodeIds.delete(id)) this.shouldChangeShapeContainerNodes = true\n\t\tif (this.withDataIdentifierNodeIds.delete(id)) this.shouldChangeWithDataIdentifierNodes = true\n\n\t\tif (this.activeScopeGroundNodeIds.delete(id)) this.shouldChangeActiveScopeGroundNodes = true\n\n\t\tthis.formContainerNodeIds.delete(id)\n\t\tthis.nodeIdIndex.delete(id)\n\t\tthis.searchComponentNodeIds.delete(id)\n\t\tthis.deprecatedCodeComponentNodeIds.delete(id)\n\t}\n\n\tprivate reset(tree: CanvasTree) {\n\t\t// Clear all indexes.\n\t\tthis.smartComponentNodeIds.clear()\n\t\tthis.layoutTemplateNodeIds.clear()\n\t\tthis.codeComponentNodeIds.clear()\n\t\tthis.shaderNodeIds.clear()\n\t\tthis.richTextNodeIds.clear()\n\t\tthis.navigationActionNodeIds.clear()\n\t\tthis.setVariantActionNodeIds.clear()\n\t\tthis.shapeContainerNodeIds.clear()\n\t\tthis.activeScopeGroundNodeIds.clear()\n\t\tthis.nodeIdIndex.clear()\n\t\tthis.searchComponentNodeIds.clear()\n\t\tthis.deprecatedCodeComponentNodeIds.clear()\n\t\tthis.formContainerNodeIds.clear()\n\t\tthis.withDataIdentifierNodeIds.clear()\n\n\t\tthis.tree = tree\n\n\t\ttree.beginAllowPartialScopeAccess()\n\t\ttree.forEachNode(node => {\n\t\t\tif (nodeIgnoredInNodeIdIndex(node)) return\n\t\t\tthis.addNode(tree, node)\n\t\t\tthis.updateNodeIdIndex(tree, node)\n\t\t})\n\t\ttree.endAllowPartialScopeAccess()\n\n\t\t// We call read() on reset in order to clear the reader set\n\t\tthis.reader.read()\n\n\t\t// Let the TreeStore calculate all reset changes\n\t\tthis.setAllChangeFlags()\n\t}\n\n\tprivate setAllChangeFlags() {\n\t\tthis.shouldChangeSmartComponents = true\n\t\tthis.shouldChangeLayoutTemplates = true\n\t\tthis.shouldChangeRichTextNodes = true\n\t\tthis.shouldChangeCodeComponents = true\n\t\tthis.shouldChangeShaderNodes = true\n\t\tthis.shouldChangeNavigationActions = true\n\t\tthis.shouldChangeShapeContainerNodes = true\n\t\tthis.shouldChangeVariantActions = true\n\t\tthis.shouldChangeActiveScopeGroundNodes = true\n\t\tthis.shouldChangeWithDataIdentifierNodes = true\n\t}\n\n\tgetNodes<T extends CanvasNode>(nodeIds: Set<NodeID>): T[] {\n\t\tconst nodes: T[] = []\n\n\t\tfor (const id of nodeIds) {\n\t\t\tconst node = this.tree.get<T>(id)\n\t\t\tif (!node) continue\n\t\t\tnodes.push(node)\n\t\t}\n\n\t\treturn nodes\n\t}\n\n\tgetNodesForActiveScope<T extends CanvasNode>(nodeIds: Set<NodeID>): T[] {\n\t\tconst nodes: T[] = []\n\n\t\tfor (const id of nodeIds) {\n\t\t\tif (this.getScopeIdFor(id) !== this.activeScopeId) continue\n\t\t\tconst node = this.tree.get<T>(id)\n\t\t\tif (!node) continue\n\t\t\tnodes.push(node)\n\t\t}\n\n\t\treturn nodes\n\t}\n\n\tprocessActiveScope(tree: CanvasTree, activeScopeId: NodeID) {\n\t\tif (this.activeScopeId === activeScopeId) return\n\t\tif (activeScopeId.length === 0) return\n\n\t\tthis.activeScopeId = activeScopeId\n\t\tthis.activeScopeGroundNodeIds.clear()\n\t\tthis.shouldChangeActiveScopeGroundNodes = true\n\t\tthis.shouldChangeShapeContainerNodes = true\n\n\t\tconst scope = tree.get(this.activeScopeId)\n\t\tif (!isScopeNode(scope) || !scope.isLoaded()) return\n\n\t\tfor (const groundNode of scope.loaded.children) {\n\t\t\tthis.activeScopeGroundNodeIds.add(groundNode.id)\n\t\t}\n\t}\n\n\tprocessReset(tree: CanvasTree) {\n\t\tthis.processActiveScope(tree, \"\")\n\t\tthis.reset(tree)\n\t\tthis.verify()\n\t}\n\n\tprocess(tree: CanvasTree, activeScopeId: NodeID) {\n\t\tthis.processActiveScope(tree, activeScopeId)\n\n\t\t// We keep track of tree changes via a change tracking cursor.\n\t\tif (this.tree.lineage !== tree.lineage) {\n\t\t\tthis.reset(tree)\n\t\t\tthis.verify()\n\t\t\treturn\n\t\t}\n\n\t\tthis.tree = tree\n\n\t\tconst nodesToIndex: CanvasNode[] = []\n\t\tconst movedNodes: CanvasNode[] = []\n\n\t\tfor (const [id, changes] of this.reader.read()) {\n\t\t\tconst node = tree.get(id)\n\t\t\tif (nodeIgnoredInNodeIdIndex(node)) continue\n\n\t\t\tthis.deleteNode(id)\n\t\t\tif (node) {\n\t\t\t\tthis.addNode(tree, node)\n\t\t\t\tnodesToIndex.push(node)\n\t\t\t\tif (!isScopeNode(node)) {\n\t\t\t\t\tfor (const change of changes) {\n\t\t\t\t\t\tif (!change.added && change.to.parentid) {\n\t\t\t\t\t\t\tmovedNodes.push(node)\n\t\t\t\t\t\t\tbreak\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// After all deletions have happened, we update the node indexes with all added or changed nodes.\n\t\tfor (const node of nodesToIndex) {\n\t\t\tthis.updateNodeIdIndex(tree, node)\n\t\t}\n\t\t// Some nodes might have moved ground node or scope node. For those we might need to update\n\t\t// their children subtrees.\n\t\tfor (const node of movedNodes) {\n\t\t\tthis.updateNodeIdIndexForMovedNode(node)\n\t\t}\n\t\tthis.verify()\n\t}\n\n\tprivate updateNodeIdIndexForMovedNode(node: CanvasNode) {\n\t\t// When nodes move parents, their children subtrees might not have had any changes, and\n\t\t// won't have an updated entry in the node id index.\n\t\tif (!node.children) return\n\n\t\tconst entry = this.nodeIdIndex.get(node.id)!\n\t\tfor (const child of node.children) {\n\t\t\t// TODO: This is slightly brute force. We might avoid walking if the children point to\n\t\t\t// the correct entry. But that requires us to know if the children had any changes.\n\t\t\tfor (const sub of child.walk()) {\n\t\t\t\tthis.nodeIdIndex.set(sub.id, entry)\n\t\t\t}\n\t\t}\n\t}\n\n\tupdateNodeIdIndex(tree: CanvasTree, node: CanvasNode): NodeIdIndexEntry | undefined {\n\t\t// This method will recurse from node to parent, to parent, etc. If an entry exists, it is\n\t\t// assumed up to date, and stops the recursion. This makes updating this index for all\n\t\t// changed nodes a linear operation.\n\n\t\t// The node is already known by the index.\n\t\tconst existing = this.nodeIdIndex.get(node.id)\n\t\tif (existing) return existing\n\n\t\t// Scope node point to themselves.\n\t\tif (isScopeNode(node)) {\n\t\t\tconst entry: NodeIdIndexEntry = { scope: node.id, ground: node.id }\n\t\t\tthis.nodeIdIndex.set(node.id, entry)\n\t\t\t// Recalculate the ground nodes if the scope changes.\n\t\t\tif (node.id === this.activeScopeId) this.shouldChangeActiveScopeGroundNodes = true\n\t\t\treturn\n\t\t}\n\n\t\t// Otherwise, get the node parent.\n\t\tconst parent = tree.get(node.parentid)\n\t\tif (!parent) return\n\n\t\t// If the parent turns out to be a scope node, this is a ground node. Update indexes.\n\t\tif (isScopeNode(parent) || isRootNode(parent)) {\n\t\t\tconst entry: NodeIdIndexEntry = { scope: parent.id, ground: node.id }\n\t\t\tthis.nodeIdIndex.set(node.id, entry)\n\t\t\tif (!isHiddenMaster(node)) {\n\t\t\t\tif (parent.id === this.activeScopeId) {\n\t\t\t\t\tthis.shouldChangeActiveScopeGroundNodes = true\n\t\t\t\t\tthis.activeScopeGroundNodeIds.add(node.id)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn entry\n\t\t}\n\n\t\t// Recurse to update our parent. We will receive our scope id and ground node id.\n\t\tconst entry = this.updateNodeIdIndex(tree, parent)\n\t\tif (!entry) return\n\n\t\tthis.nodeIdIndex.set(node.id, entry)\n\t\treturn entry\n\t}\n\n\tupdateCodeComponents() {\n\t\tthis.tree.beginAllowPartialScopeAccess()\n\t\t// When updating code components, we are only interested in updating things that depend on\n\t\t// the component loader. If the tree has also changed, it will commit and process later,\n\t\t// handling deletions and such at that point in time.\n\t\t// We must remove code component nodes from component-loader-dependent sets before\n\t\t// re-evaluating, because the component definitions may have changed and stale entries\n\t\t// would cause a verification mismatch.\n\t\tfor (const id of this.codeComponentNodeIds) {\n\t\t\tif (this.navigationActionNodeIds.delete(id)) {\n\t\t\t\tthis.shouldChangeNavigationActions = true\n\t\t\t}\n\t\t\tif (this.setVariantActionNodeIds.delete(id)) {\n\t\t\t\tthis.shouldChangeVariantActions = true\n\t\t\t}\n\t\t\tconst node = this.tree.get(id)\n\t\t\tif (node) {\n\t\t\t\tthis.addNode(this.tree, node)\n\t\t\t}\n\t\t}\n\t\tthis.tree.endAllowPartialScopeAccess()\n\t}\n\n\tprivate verify() {\n\t\tif (process.env.NODE_ENV === \"production\") return\n\t\tif (environment.benchmarkSkipTreeVerify) return\n\t\tif (this.tree.size() > MAX_VERIFY_TREE_SIZE) return\n\n\t\tthis.tree.beginAllowPartialScopeAccess()\n\t\tthis.verificationIndex.update(this.tree)\n\t\tthis.verificationIndex.verify({\n\t\t\tsmartComponentNodeIds: this.smartComponentNodeIds,\n\t\t\tlayoutTemplateNodeIds: this.layoutTemplateNodeIds,\n\t\t\tcodeComponentNodeIds: this.codeComponentNodeIds,\n\t\t\tshaderNodeIds: this.shaderNodeIds,\n\t\t\trichTextNodeIds: this.richTextNodeIds,\n\t\t\tnavigationActionNodeIds: this.navigationActionNodeIds,\n\t\t\tsetVariantActionNodeIds: this.setVariantActionNodeIds,\n\t\t\tshapeContainerNodeIds: this.shapeContainerNodeIds,\n\t\t\tformContainerNodeIds: this.formContainerNodeIds,\n\t\t\twithDataIdentifierNodeIds: this.withDataIdentifierNodeIds,\n\t\t})\n\n\t\t// verify the two live index maps\n\t\tlet count = 0\n\t\tconst root = this.tree.root\n\t\tfor (const scope of this.tree.root.children) {\n\t\t\tif (isScopeNode(scope, true)) {\n\t\t\t\tcount += 1\n\t\t\t\tassert(this.nodeIdIndex.get(scope.id)!.scope === scope.id, \"scope must point to itself\")\n\n\t\t\t\t// Verify is the place where we should try to iterate over all types of nodes\n\t\t\t\t// (shallow and fully loaded).\n\t\t\t\tif (\"children\" in scope && scope.children !== undefined) {\n\t\t\t\t\tfor (const groundNode of scope.children) {\n\t\t\t\t\t\tcount += this.verifyScope(scope as CanvasNode, groundNode)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcount += this.verifyScope(root, scope)\n\t\t\t}\n\t\t}\n\t\tassert(this.nodeIdIndex.size === count, \"nodeIdToScopeAndGroundID bad size\", this.nodeIdIndex.size, count)\n\n\t\tconst scope = this.tree.get(this.activeScopeId)\n\t\tconst groundNodeCount = scope?.children?.length ?? 0\n\t\tassert(this.activeScopeGroundNodeIds.size === groundNodeCount, \"currentGroundNodeIds bad size\")\n\n\t\tthis.tree.endAllowPartialScopeAccess()\n\t}\n\n\tprivate verifyScope(scope: CanvasNode, groundNode: CanvasNode): number {\n\t\tlet count = 0\n\t\tfor (const node of groundNode.walk()) {\n\t\t\tif (nodeIgnoredInNodeIdIndex(node)) continue\n\n\t\t\tcount += 1\n\t\t\tconst entry = this.nodeIdIndex.get(node.id)\n\t\t\tassert(entry, \"id\", node.id, \"does not exist in index\")\n\t\t\tassert(entry.scope === scope.id, node.id, \"scope is:\", entry.scope, \"should be:\", scope.id)\n\t\t\tassert(entry.ground === groundNode.id, node.id, \"ground is:\", entry.ground, \"should be:\", groundNode.id)\n\t\t}\n\t\treturn count\n\t}\n\n\tupdateConnectedScreens(tree: CanvasTree, selection: NodeID[], showAllArrows: boolean) {\n\t\t// if not showing all arrows, calculate precisely which ones we want\n\t\tlet candidateGroundNodes = new Set<CanvasNode | undefined>()\n\t\tif (showAllArrows) {\n\t\t\tcandidateGroundNodes = TrueSet\n\t\t} else {\n\t\t\tfor (const id of selection) {\n\t\t\t\tconst groundNode = this.getNodeIdToCurrentGroundNode(tree, id)\n\t\t\t\tif (groundNode) {\n\t\t\t\t\tcandidateGroundNodes.add(groundNode)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (candidateGroundNodes.size > maxSelectedScreensToRenderArrowsFor) {\n\t\t\t\tcandidateGroundNodes.clear()\n\t\t\t}\n\t\t}\n\n\t\t// navigation action links\n\t\tconst linkedNavigationNodes = this.getLinkedNavigationNodes(tree, candidateGroundNodes)\n\t\tif (!isShallowArrayEqual(this.activeScopeLinkedNavigationNodes, linkedNavigationNodes)) {\n\t\t\tthis.activeScopeLinkedNavigationNodes = linkedNavigationNodes\n\t\t}\n\n\t\t// variant action links\n\t\tconst linkedVariantNodes = this.getLinkedVariantNodes(tree, selection, candidateGroundNodes, showAllArrows)\n\t\tif (!isShallowArrayEqual(this.activeScopeLinkedVariantNodes, linkedVariantNodes)) {\n\t\t\tthis.activeScopeLinkedVariantNodes = linkedVariantNodes\n\t\t}\n\n\t\t// Build connections to each variant node from their hover/pressed nodes\n\t\tconst linkedGestureNodes = this.getLinkedGestureNodes(tree, candidateGroundNodes)\n\t\tif (!isShallowArrayEqual(this.activeScopeLinkedGestureNodes, linkedGestureNodes)) {\n\t\t\tthis.activeScopeLinkedGestureNodes = linkedGestureNodes\n\t\t}\n\n\t\t// component connectors\n\t\tconst codeComponentArrows = this.getCodeComponentArrows(tree, candidateGroundNodes)\n\t\tif (!isShallowSetEqual(this.activeScopeCodeComponentArrows, codeComponentArrows)) {\n\t\t\tthis.activeScopeCodeComponentArrows = codeComponentArrows\n\t\t}\n\t}\n\n\tprivate getLinkedVariantNodes(\n\t\ttree: CanvasTree,\n\t\tselection: NodeID[],\n\t\tcandidateGroundNodes: Set<CanvasNode | undefined>,\n\t\tshowAllArrows: boolean,\n\t): NodeLink<CanvasNode, VariantNode>[] {\n\t\tconst linkedVariantNodes: NodeLink<CanvasNode, VariantNode>[] = []\n\t\tconst seenVariantTargets: Set<NodeID> = new Set()\n\n\t\tconst singleSelection = selection[0]\n\t\tif (!showAllArrows && (selection.length !== 1 || !singleSelection)) return linkedVariantNodes\n\n\t\tfor (const fromId of this.setVariantActionNodeIds) {\n\t\t\tif (this.nodeIdIndex.get(fromId)?.scope !== this.activeScopeId) continue\n\t\t\tconst fromGroundNode = this.getNodeIdToCurrentGroundNode(tree, fromId)\n\t\t\tif (!fromGroundNode) continue\n\t\t\t// only show the arrows departing from the selected ground node.\n\t\t\tif (!showAllArrows && singleSelection !== fromGroundNode.id && singleSelection !== fromId) continue\n\n\t\t\tconst fromNode = tree.get(fromId)\n\t\t\tif (!fromNode) continue\n\n\t\t\t// We are reusing seenVariantTargets for each from node\n\t\t\tseenVariantTargets.clear()\n\t\t\tconst targets = getSetVariantActionTargets(tree, fromNode, this.componentLoader)\n\t\t\ttargets.forEach(target => {\n\t\t\t\t// Make sure we draw only a single arrow to each target\n\t\t\t\tif (seenVariantTargets.has(target)) return\n\n\t\t\t\tconst toNode = tree.getNode(target)\n\t\t\t\tif (!toNode) return\n\t\t\t\tif (!isVariant(toNode)) return\n\n\t\t\t\tconst toGroundNode = this.getNodeIdToCurrentGroundNode(tree, toNode.id)\n\t\t\t\tif (toGroundNode !== toNode) return // Only link to ground nodes\n\t\t\t\tif (toGroundNode === fromGroundNode) return // Don't link to our own ground node\n\t\t\t\tif (toGroundNode.parentid !== fromGroundNode.parentid) return // Don't link to ground nodes not on the same page\n\n\t\t\t\tif (candidateGroundNodes.has(fromGroundNode) || candidateGroundNodes.has(toGroundNode)) {\n\t\t\t\t\tseenVariantTargets.add(toNode.id)\n\t\t\t\t\tlinkedVariantNodes.push({ fromNode, toNode })\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\treturn linkedVariantNodes\n\t}\n\n\tprivate getLinkedNavigationNodes(\n\t\ttree: CanvasTree,\n\t\tcandidateGroundNodes: Set<CanvasNode | undefined>,\n\t): NodeLink<CanvasNode, CanvasNode>[] {\n\t\tconst linkedNavigationNodes: NodeLink<CanvasNode, CanvasNode>[] = []\n\t\tconst seenNavigationTargets: Set<NodeID> = new Set()\n\t\tfor (const fromId of this.navigationActionNodeIds) {\n\t\t\tif (this.nodeIdIndex.get(fromId)?.scope !== this.activeScopeId) continue\n\t\t\tconst fromGroundNode = this.getNodeIdToCurrentGroundNode(tree, fromId)\n\t\t\tif (!fromGroundNode) continue\n\n\t\t\t// We are reusing seenNavigationTargets for each fromNode.\n\t\t\tseenNavigationTargets.clear()\n\t\t\tconst fromNode = tree.get(fromId)!\n\n\t\t\tconst actions = getNavigationActions(fromNode, this.componentLoader)\n\n\t\t\tactions.forEach(action => {\n\t\t\t\tif (!action.controls) return\n\t\t\t\tif (!action.controls.target) return\n\t\t\t\tif (!action.controls.target.value) return\n\t\t\t\tif (!action.controls.type) return\n\t\t\t\tif (action.controls.type.value !== \"next\") return\n\n\t\t\t\tconst toNode = tree.getNode(action.controls.target.value)\n\t\t\t\tif (!toNode) return\n\n\t\t\t\t// Make sure we draw only a single arrow to each target even when there are many actions.\n\t\t\t\tif (seenNavigationTargets.has(toNode.id)) return\n\n\t\t\t\tconst toGroundNode = this.getNodeIdToCurrentGroundNode(tree, toNode.id)\n\t\t\t\tif (!toGroundNode) return\n\t\t\t\tif (toGroundNode !== toNode) return // Only link to ground nodes\n\t\t\t\tif (toGroundNode === fromGroundNode) return // Don't link to our own ground node\n\t\t\t\tif (toGroundNode.parentid !== fromGroundNode.parentid) return // Don't link to ground nodes not on the same page\n\n\t\t\t\tif (candidateGroundNodes.has(fromGroundNode) || candidateGroundNodes.has(toGroundNode)) {\n\t\t\t\t\tlinkedNavigationNodes.push({ fromNode: fromNode, toNode })\n\t\t\t\t}\n\t\t\t\tseenNavigationTargets.add(toNode.id)\n\t\t\t})\n\t\t}\n\n\t\treturn linkedNavigationNodes\n\t}\n\n\tprivate getLinkedGestureNodes(tree: CanvasTree, candidateGroundNodes: Set<CanvasNode | undefined>) {\n\t\t// @FIXME Evaluate performance of checking for Gesture links\n\t\t// The scope can be used and prevent this filter when in isolation\n\t\t// Using the activeScope in this method may be buggy https://github.com/framer/FramerStudio/pull/6756/files#r540861786\n\n\t\tconst linkedGestureNodes: NodeLink<VariantNode, VariantNode>[] = []\n\t\tconst scopeNode = tree.get(this.activeScopeId)\n\t\tfor (const toNode of scopeNode?.children ?? []) {\n\t\t\tif (!isGestureVariant(toNode)) continue\n\n\t\t\tconst inheritsFrom = toNode.replicaInfo.inheritsFrom\n\t\t\tif (!inheritsFrom) continue\n\n\t\t\tconst fromNode = tree.getNode(toNode.replicaInfo.inheritsFrom)\n\t\t\tif (!fromNode || !isVariant(fromNode)) continue\n\n\t\t\tconst toGroundNode = this.getNodeIdToCurrentGroundNode(tree, toNode.id)\n\t\t\tconst fromGroundNode = this.getNodeIdToCurrentGroundNode(tree, fromNode.id)\n\t\t\tif (candidateGroundNodes.has(fromGroundNode) || candidateGroundNodes.has(toGroundNode)) {\n\t\t\t\tlinkedGestureNodes.push({ fromNode: toNode, toNode: fromNode })\n\t\t\t}\n\t\t}\n\t\treturn linkedGestureNodes\n\t}\n\n\tprivate getCodeComponentArrows(\n\t\ttree: CanvasTree,\n\t\tcandidateGroundNodes: Set<CanvasNode | undefined>,\n\t): ReadonlySet<CodeComponentNode> {\n\t\tconst codeComponentArrows: Set<CodeComponentNode> = new Set()\n\n\t\tconst scopeNode = tree.get(this.activeScopeId)\n\t\tif (!isScopeNode(scopeNode)) return codeComponentArrows\n\n\t\tfor (const fromId of this.codeComponentNodeIds) {\n\t\t\tif (this.nodeIdIndex.get(fromId)?.scope !== this.activeScopeId) continue\n\t\t\tconst fromGroundNode = this.getNodeIdToCurrentGroundNode(tree, fromId)\n\t\t\tif (!fromGroundNode) continue\n\n\t\t\tconst fromNode = tree.get(fromId)\n\t\t\tif (!fromNode) continue\n\t\t\tassert(isCodeComponentNode(fromNode), \"bug\")\n\n\t\t\t// Slots as child nodes use the tree hierarchy instead of arrows.\n\t\t\tif (fromNode.slotsAreChildNodes) continue\n\n\t\t\tconst isCandidate = candidateGroundNodes.has(fromGroundNode)\n\t\t\tif (isCandidate) {\n\t\t\t\tcodeComponentArrows.add(fromNode)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst componentDefinition = this.componentLoader.reactComponentForIdentifier(fromNode.codeComponentIdentifier)\n\t\t\tif (!componentDefinition) continue\n\n\t\t\tconst controlProps = fromNode.getControlProps(componentDefinition.properties)\n\n\t\t\tconst hasCandidateSlotContent = Object.values(controlProps).some(controlProp => {\n\t\t\t\tif (controlProp.type !== ControlType.Slot) return false\n\n\t\t\t\tfor (const slotItem of controlProp.value) {\n\t\t\t\t\tconst toNode = tree.get(slotItem.reference)\n\t\t\t\t\tif (!isValidSlotItemNode(scopeNode.id, toNode)) continue\n\t\t\t\t\tconst toGroundNode = this.getNodeIdToCurrentGroundNode(tree, toNode.id)\n\t\t\t\t\tif (!toGroundNode) continue\n\t\t\t\t\tif (toGroundNode === fromGroundNode) continue\n\t\t\t\t\tif (toGroundNode.parentid !== fromGroundNode.parentid) continue\n\t\t\t\t\tif (!candidateGroundNodes.has(toGroundNode)) continue\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\treturn false\n\t\t\t})\n\n\t\t\tif (hasCandidateSlotContent) {\n\t\t\t\tcodeComponentArrows.add(fromNode)\n\t\t\t}\n\t\t}\n\t\treturn codeComponentArrows\n\t}\n\n\tprivate prototypeScreenLinksTree: CanvasTree | null = null\n\tprivate prototypeScreenLinks: Record<NodeID, readonly NodeLink<NodeID, NodeID>[]> = {}\n\n\t/**\n\t * Support for generating prototype components while only importing the\n\t * screens that are navigable from the home node. This list will include all\n\t * prototype navigation links in the project, and will be from ground node\n\t * id to ground node id. It will also include slot connectors. This allows\n\t * determining the chain by understanding that a chain continues through\n\t * slots.\n\t */\n\tgetPrototypeScreenLinks(tree: CanvasTree, startingNodeId: NodeID): readonly NodeLink<NodeID, NodeID>[] {\n\t\tconst scopeId = this.getScopeIdFor(startingNodeId)\n\t\tif (!scopeId) return []\n\n\t\t// Clear any cached results if a new tree was passed in.\n\t\tif (this.prototypeScreenLinksTree !== tree) {\n\t\t\tthis.prototypeScreenLinksTree = tree\n\t\t\tthis.prototypeScreenLinks = {}\n\t\t}\n\n\t\tconst existingLinks = this.prototypeScreenLinks[scopeId]\n\t\tif (existingLinks) return existingLinks\n\n\t\tconst links: NodeLink<NodeID, NodeID>[] = []\n\n\t\tconst seenNavigationTargets: Set<NodeID> = new Set()\n\t\tfor (const fromId of this.navigationActionNodeIds) {\n\t\t\tconst entry = this.nodeIdIndex.get(fromId)\n\t\t\tif (!entry) continue\n\t\t\tif (entry.scope !== scopeId) continue\n\n\t\t\tconst fromGroundNode = tree.get(entry.ground)\n\t\t\tif (!fromGroundNode) continue\n\n\t\t\tconst fromNode = tree.get(fromId)!\n\t\t\tconst actions = getNavigationActions(fromNode, this.componentLoader)\n\n\t\t\tseenNavigationTargets.clear()\n\t\t\tactions.forEach(action => {\n\t\t\t\tif (!action.controls) return\n\t\t\t\tif (!action.controls.target) return\n\t\t\t\tif (!action.controls.target.value) return\n\t\t\t\tif (!action.controls.type) return\n\t\t\t\tif (action.controls.type.value !== \"next\") return\n\n\t\t\t\tconst toNode = tree.getNode(action.controls.target.value)\n\t\t\t\tif (!toNode) return\n\n\t\t\t\t// Evaluate each toNode only once.\n\t\t\t\tif (seenNavigationTargets.has(toNode.id)) return\n\n\t\t\t\tconst toGroundNode = tree.get(this.getGroundNodeIdFor(toNode.id))\n\t\t\t\tif (!toGroundNode) return\n\t\t\t\tif (toGroundNode !== toNode) return // Only link to ground nodes\n\t\t\t\tif (toGroundNode === fromGroundNode) return // Don't link to our own ground node\n\t\t\t\tif (toGroundNode.parentid !== fromGroundNode.parentid) return // Don't link to ground nodes not on the same page\n\n\t\t\t\tseenNavigationTargets.add(toNode.id)\n\t\t\t\tlinks.push({ fromNode: fromGroundNode.id, toNode: toNode.id })\n\t\t\t})\n\t\t}\n\n\t\t// component connectors\n\t\tfor (const fromId of this.codeComponentNodeIds) {\n\t\t\tconst entry = this.nodeIdIndex.get(fromId)\n\t\t\tif (!entry) continue\n\t\t\tif (entry.scope !== scopeId) continue\n\n\t\t\tconst fromGroundNode = tree.get(entry.ground)\n\t\t\tif (!fromGroundNode) continue\n\n\t\t\tconst fromNode = tree.get(fromId)\n\t\t\tif (!fromNode) continue\n\t\t\tassert(isCodeComponentNode(fromNode), \"bug\")\n\n\t\t\tif (isStackComponent(fromNode)) continue\n\n\t\t\tconst allSlotKeys = getSlotKeys(fromNode, this.componentLoader)\n\t\t\tif (allSlotKeys.length === 0) continue\n\n\t\t\tfor (const slotKey of allSlotKeys) {\n\t\t\t\tconst slotControlProp = fromNode.getRawControlProp(slotKey)\n\t\t\t\tconst slotValues = slotControlProp?.value\n\t\t\t\tif (!slotValues || !Array.isArray(slotValues)) continue\n\n\t\t\t\tslotValues.forEach(slotItem => {\n\t\t\t\t\tif (typeof slotItem.value !== \"string\") return\n\t\t\t\t\tconst toNode = tree.get(slotItem.value)\n\t\t\t\t\tif (!toNode) return\n\t\t\t\t\tif (isVariant(toNode)) return\n\t\t\t\t\t// Add slot connections to the prototype screen links. This\n\t\t\t\t\t// allows following navigation chains through slots.\n\t\t\t\t\tlinks.push({ fromNode: fromGroundNode.id, toNode: toNode.id })\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tthis.prototypeScreenLinks[scopeId] = links\n\t\treturn links\n\t}\n\n\tgetShapeContainerNodes(scope: ScopeNode): ShapeContainerNode[] {\n\t\tconst nodes: ShapeContainerNode[] = []\n\t\tfor (const id of this.shapeContainerNodeIds) {\n\t\t\tif (this.getScopeIdFor(id) !== scope.id) continue\n\n\t\t\tconst node = this.tree.get<ShapeContainerNode>(id)\n\t\t\tif (!node) continue\n\n\t\t\tnodes.push(node)\n\t\t}\n\t\treturn nodes\n\t}\n}\n", "import type { BootstrappedWindow } from \"@framerjs/bootstrap\"\nimport { MAIN_BRANCH_ID } from \"@framerjs/crdtree2\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { LocalModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, getLogger } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { EngineChangeSignal } from \"document/EngineChanges.ts\"\nimport { EngineChange } from \"document/EngineChanges.ts\"\nimport type { LayoutCache } from \"document/LayoutCache.ts\"\nimport { SandboxRepeaterData } from \"document/SandboxRepeaterData.ts\"\nimport { SandboxVisibility } from \"document/SandboxVisibility.ts\"\nimport {\n\tgetBaseTreeStoreMode,\n\tswitchBaseTreeStoreMode,\n\ttype BaseTreeStore,\n} from \"document/base-engine/BaseTreeStore.ts\"\nimport { without } from \"document/components/utils/list.ts\"\nimport { getCrdtSession } from \"document/crdt/CrdtSession.ts\"\nimport type { DataTree } from \"document/crdt/data-tree/DataTree.ts\"\nimport { TreeQueryBuilder, type TreeQueryContext } from \"document/crdt/data-tree/TreeQueryBuilder.ts\"\nimport { treeModeWithFallback } from \"document/crdt/isCrdt.ts\"\nimport { CrdtTreeCommitter, isCrdtTreeCommitter } from \"document/crdt/sync/CrdtTreeCommitter.ts\"\nimport type { RowsWithNext } from \"document/crdt/sync/LocalCache.ts\"\nimport { MAX_VERIFY_TREE_SIZE } from \"document/models/CanvasTree/NodeTree.ts\"\nimport type { ReversibleNodeChange } from \"document/models/CanvasTree/TreeDiff.ts\"\nimport type { TreeServices } from \"document/models/CanvasTree/TreeServices.ts\"\nimport { TreeTimeline } from \"document/models/CanvasTree/TreeTimeline.ts\"\nimport type { CommitLocalTreeResult, TreeUpdater } from \"document/models/CanvasTree/TreeUpdater.ts\"\nimport type {\n\tCanvasNode,\n\tCodeComponentNode,\n\tMaybeNodeID,\n\tNodeID,\n\tRichTextNode,\n\tShaderNode,\n\tShapeContainerNode,\n\tSmartComponentNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { CanvasTree, NullID, isScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport type { LayoutTemplateNode } from \"document/models/CanvasTree/nodes/LayoutTemplateNode.ts\"\nimport {\n\tisColorStyleTokenListNode,\n\tisColorStyleTokenNode,\n\tisPresetsListNode,\n\tisTextStylePresetNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isFixedOrRelativeOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { withDOMLayout } from \"document/models/CanvasTree/traits/WithDOMLayout.ts\"\nimport type { LocaleId } from \"document/models/CanvasTree/traits/WithLocales.ts\"\nimport { hasRepeatArray } from \"document/models/CanvasTree/traits/WithRepeatArray.ts\"\nimport { isHiddenMaster } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { IsVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isVisibleNode } from \"document/models/CanvasTree/traits/WithVisibility.ts\"\nimport { getGroundNodeOverflowRect } from \"document/models/CanvasTree/utils/getGroundNodeRect.ts\"\nimport { resetAncestorCacheForNodes } from \"document/models/resetAncestorCacheForNodes.ts\"\nimport {\n\tupdateTreeCacheForVekter,\n\tupdateTreeCacheWithLatestDOMLayout,\n} from \"document/models/updateTreeCacheForVekter.ts\"\nimport type { GuidesStore } from \"document/stores/GuidesStore.ts\"\nimport type { EffectPreviewState } from \"document/utils/EffectPreviewType.ts\"\nimport type { VariableProviderInfo } from \"document/utils/VariableProviderInfo.ts\"\nimport { getMemoizedVariableProviderInfo } from \"document/utils/VariableProviderInfo.ts\"\nimport { environment } from \"environment/index.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport { isShallowArrayEqual, isShallowObjectEqual } from \"utils/isShallowEqual.ts\"\nimport { isNumber, isObject, isString } from \"utils/typeChecks.ts\"\nimport { ClassDiscriminator } from \"utils/withClassDiscriminator.ts\"\nimport { getMultiplayerServiceURL } from \"web/lib/multiplayerService.ts\"\nimport type { ChromeStore } from \"./ChromeStore.ts\"\nimport type { PersistedUserDefaults } from \"./PersistedUserDefaults.ts\"\nimport type { Selection } from \"./SelectionStore.ts\"\nimport { TreeIndex } from \"./TreeIndex.ts\"\nimport { isTreeMode, setTreeMode, type TreeMode } from \"./TreeMode.ts\"\nimport type { UndoRedoManager } from \"./UndoRedoManager.ts\"\n\nconst log = getLogger(\"treeStore\")\n\nfunction verifySelectionCache(tree: CanvasTree, selection: Selection) {\n\tfor (const node of tree.root.walk()) {\n\t\tconst cacheSelected = node.cache.selected\n\t\tconst inSelection = selection.includes(node.id)\n\n\t\tif (inSelection && !cacheSelected) {\n\t\t\tthrow Error(\"Node is in the selection but node.cache.selected = false: \" + node.id)\n\t\t}\n\n\t\tif (cacheSelected && !inSelection) {\n\t\t\tthrow Error(\"Node is not in the selection but node.cache.selected = true: \" + node.id)\n\t\t}\n\n\t\tif (cacheSelected && isHiddenMaster(node)) {\n\t\t\tthrow Error(\"Selection contains a hidden master: \" + node.id)\n\t\t}\n\t}\n}\n\nexport type PrefetchSyncPromise = Promise<{\n\tstatus: number\n\theaders: Headers\n\tduration: Promise<number>\n\t/** Indicates the server is sending us updates. */\n\tupdates?: Promise<RowsWithNext[]>\n\t/** Indicates the server is sending us a snapshot. */\n\tsnapshot?: Promise<ArrayBuffer>\n}>\n\nfunction isPrefetchSyncPromise(value: unknown): value is PrefetchSyncPromise {\n\treturn isObject(value) && typeof value[\"then\"] === \"function\"\n}\n\ntype PrefetchPromise = Promise<{\n\tstatus: number\n\ttext?: Promise<string>\n\tbuffer?: Promise<ArrayBufferLike>\n\tduration: Promise<number>\n}>\n\nfunction isPrefetchPromise(value: unknown): value is PrefetchPromise {\n\treturn isObject(value) && typeof value[\"then\"] === \"function\"\n}\nexport interface InitData {\n\tmode?: TreeMode\n\tsocketURL?: string\n\tversion?: number | undefined\n\tfile?: string | undefined\n\tprefetchPromise?: PrefetchPromise\n\tprefetchSyncPromise?: PrefetchSyncPromise\n\tsyncURL?: string\n\tisMPSSocket?: boolean\n}\n\nfunction getTreeInitData(): InitData | undefined {\n\tif (!(\"treeInitData\" in window) || !isObject(window[\"treeInitData\"])) return undefined\n\tconst windowTreeInitData = window[\"treeInitData\"]\n\tconst { mode, version, file, prefetchPromise, prefetchSyncPromise, syncURL, socketURL, isMPSSocket } =\n\t\twindowTreeInitData\n\tdelete window[\"treeInitData\"]\n\n\tconst mpsFlag = isMPSSocket === true ? { isMPSSocket: true as const } : {}\n\tconst syncURLField = isString(syncURL) ? { syncURL } : {}\n\tconst modeField = isTreeMode(mode) ? { mode } : {}\n\n\tif (prefetchPromise && isPrefetchPromise(prefetchPromise)) {\n\t\tif (!isString(socketURL) || !isNumber(version) || !isString(file)) {\n\t\t\tconst existingKeys = Object.keys(windowTreeInitData)\n\t\t\tlog.error(\"Expected socketURL, version, and file in window.treeInitData but got:\", existingKeys)\n\t\t\treturn undefined\n\t\t}\n\t\treturn { version, file, prefetchPromise, socketURL, ...modeField, ...syncURLField, ...mpsFlag }\n\t} else if (prefetchSyncPromise && isPrefetchSyncPromise(prefetchSyncPromise)) {\n\t\tif (!isString(socketURL)) {\n\t\t\tconst existingKeys = Object.keys(windowTreeInitData)\n\t\t\tlog.error(\"Expected socketURL in window.treeInitData but got:\", existingKeys)\n\t\t\treturn undefined\n\t\t}\n\t\treturn { prefetchSyncPromise, socketURL, ...modeField, ...syncURLField, ...mpsFlag }\n\t}\n\n\t// Projects should always be served so that we can start a prefetch. While an optional\n\t// optimization, we log a warning when this is not happening.\n\tlog.warn(\"Not using prefetch.\")\n\tif (isString(socketURL)) {\n\t\treturn { socketURL, ...modeField, ...syncURLField, ...mpsFlag }\n\t}\n}\n\n/** This index is accessible via the loaded/shallow tree store getters */\ninterface TreeStoreIndexes {\n\tcodeComponents: TreeStore[\"codeComponents\"]\n\trichTextNodes: TreeStore[\"richTextNodes\"]\n\tshaderNodes: TreeStore[\"shaderNodes\"]\n\tformContainerNodeIds: TreeStore[\"formContainerNodeIds\"]\n\twithDataIdentifierNodeIds: TreeStore[\"withDataIdentifierNodeIds\"]\n\t// TODO: upgrade to a active scope index\n\tlocalSmartComponentNameByIdentifier: TreeStore[\"localSmartComponentNameByIdentifier\"]\n\tlocalLayoutTemplatesNameByIdentifier: TreeStore[\"localLayoutTemplatesNameByIdentifier\"]\n\tactiveScopeShapeContainerNodes: TreeStore[\"activeScopeShapeContainerNodes\"]\n\tactiveScopeCodeComponentArrows: TreeStore[\"activeScopeCodeComponentArrows\"]\n\tactiveScopeLinkedNavigationNodes: TreeStore[\"activeScopeLinkedNavigationNodes\"]\n\tactiveScopeLinkedVariantNodes: TreeStore[\"activeScopeLinkedVariantNodes\"]\n\tactiveScopeLinkedGestureNodes: TreeStore[\"activeScopeLinkedGestureNodes\"]\n}\n\nexport class TreeStore implements BaseTreeStore, TreeQueryContext {\n\t// private state\n\tprivate oldSelection: Selection = []\n\tprivate oldSelectedGradientStopId: NodeID | undefined = undefined\n\tprivate oldScopeId: NodeID | null = null\n\tprivate readonly projectId: string | undefined\n\t// Cache updates sometimes arrive while the tree still has draft changes (for example, the sandbox keeps rendering\n\t// while a color picker drag is in progress). Calling `updateTreeCacheForVekter` in that state asserts because the\n\t// cache expects an immutable tree. We buffer the requested node ids and replay them as soon as the commit clears\n\t// the draft state.\n\tprivate pendingCacheUpdateNodeIds: Set<NodeID> = new Set()\n\n\tinitData: InitData | undefined = getTreeInitData()\n\n\t// state\n\ttree: CanvasTree\n\ttimeline: TreeUpdater\n\thighlight: MaybeNodeID\n\tcollapseOverrides: ReadonlyMap<NodeID, boolean> = new Map()\n\n\tprivate showAllArrows = false\n\n\t// calculated state, computed just before rendering\n\n\tisDocumentEmpty = true\n\n\t/** All the visible ground nodes of the active scope. */\n\tvisibleGroundNodesInActiveScope: CanvasNode[] = []\n\n\t/** All the ground nodes visible in the viewport. */\n\tgroundNodesInViewport = new Set<NodeID>()\n\n\tprivate _codeComponents: CodeComponentNode[] | null = null\n\tprivate _richTextNodes: RichTextNode[] | null = null\n\tprivate _shaderNodes: ShaderNode[] | null = null\n\tprivate _localSmartComponentNameByIdentifier: Record<LocalModuleExportIdentifierString, string | null> | null = null\n\tprivate _localLayoutTemplatesNameByIdentifier: Record<LocalModuleExportIdentifierString, string | null> | null = null\n\n\tprivate get codeComponents(): CodeComponentNode[] {\n\t\tif (this.treeIndex.shouldChangeCodeComponents) {\n\t\t\tthis.treeIndex.shouldChangeCodeComponents = false\n\t\t\tthis._codeComponents = this.treeIndex.getNodes<CodeComponentNode>(this.treeIndex.codeComponentNodeIds)\n\t\t}\n\t\treturn this._codeComponents ?? []\n\t}\n\n\tprivate get shaderNodes(): ShaderNode[] {\n\t\tif (this.treeIndex.shouldChangeShaderNodes) {\n\t\t\tthis.treeIndex.shouldChangeShaderNodes = false\n\t\t\tthis._shaderNodes = this.treeIndex.getNodes<ShaderNode>(this.treeIndex.shaderNodeIds)\n\t\t}\n\t\treturn this._shaderNodes ?? []\n\t}\n\n\tprivate get richTextNodes(): RichTextNode[] {\n\t\tif (this.treeIndex.shouldChangeRichTextNodes) {\n\t\t\tthis.treeIndex.shouldChangeRichTextNodes = false\n\t\t\tthis._richTextNodes = this.treeIndex.getNodes(this.treeIndex.richTextNodeIds)\n\t\t}\n\t\treturn this._richTextNodes ?? []\n\t}\n\n\tprivate get formContainerNodeIds(): ReadonlySet<string> {\n\t\treturn this.treeIndex.formContainerNodeIds\n\t}\n\n\tprivate get withDataIdentifierNodeIds(): ReadonlySet<string> {\n\t\treturn this.treeIndex.withDataIdentifierNodeIds\n\t}\n\n\tprivate get localSmartComponentNameByIdentifier(): Record<LocalModuleExportIdentifierString, string | null> {\n\t\tif (this.treeIndex.shouldChangeSmartComponents) {\n\t\t\tthis.treeIndex.shouldChangeSmartComponents = false\n\t\t\tconst index: Record<LocalModuleExportIdentifierString, string | null> = {}\n\t\t\tfor (const id of this.treeIndex.smartComponentNodeIds) {\n\t\t\t\tconst node = this.tree.get<SmartComponentNode>(id)\n\t\t\t\tif (!node) continue\n\t\t\t\tindex[node.instanceIdentifier] = node.resolveValue(\"name\")\n\t\t\t}\n\n\t\t\tconst prevIndex = this._localSmartComponentNameByIdentifier ?? {}\n\t\t\tif (!isShallowObjectEqual(prevIndex, index)) {\n\t\t\t\tthis._localSmartComponentNameByIdentifier = index\n\t\t\t}\n\t\t}\n\t\treturn this._localSmartComponentNameByIdentifier ?? {}\n\t}\n\n\tprivate get localLayoutTemplatesNameByIdentifier(): Record<LocalModuleExportIdentifierString, string | null> {\n\t\tif (this.treeIndex.shouldChangeLayoutTemplates) {\n\t\t\tthis.treeIndex.shouldChangeLayoutTemplates = false\n\t\t\tconst index: Record<LocalModuleExportIdentifierString, string | null> = {}\n\t\t\tfor (const id of this.treeIndex.layoutTemplateNodeIds) {\n\t\t\t\tconst node = this.tree.get<LayoutTemplateNode>(id)\n\t\t\t\tif (!node) continue\n\t\t\t\tindex[node.instanceIdentifier] = node.resolveValue(\"name\")\n\t\t\t}\n\n\t\t\tconst prevIndex = this._localLayoutTemplatesNameByIdentifier ?? {}\n\t\t\tif (!isShallowObjectEqual(prevIndex, index)) {\n\t\t\t\tthis._localLayoutTemplatesNameByIdentifier = index\n\t\t\t}\n\t\t}\n\t\treturn this._localLayoutTemplatesNameByIdentifier ?? {}\n\t}\n\n\tprivate activeScopeShapeContainerNodes: ShapeContainerNode[] = []\n\tprivate activeScopeCodeComponentArrows: ReadonlySet<CodeComponentNode> = new Set()\n\tprivate activeScopeLinkedNavigationNodes: readonly { fromNode: CanvasNode; toNode: CanvasNode }[] = []\n\tprivate activeScopeLinkedVariantNodes: readonly { fromNode: CanvasNode; toNode: CanvasNode & IsVariant }[] = []\n\tprivate activeScopeLinkedGestureNodes: readonly {\n\t\tfromNode: CanvasNode & IsVariant\n\t\ttoNode: CanvasNode & IsVariant\n\t}[] = []\n\n\tallNodesShareVariableContext: boolean = false\n\tvariableProviderInfo: VariableProviderInfo | null = null\n\n\t// for testing cmd+ctrl+alt+n\n\tcrashSoon = false\n\n\treadonly sandboxRepeaterData = new SandboxRepeaterData(\"editor\")\n\treadonly sandboxVisibility = new SandboxVisibility(\"editor\")\n\tdomLayoutUpdate: number = 0\n\ttreeIndex: TreeIndex\n\tprivate readonly initialTree: CanvasTree\n\n\tconstructor(\n\t\tprivate readonly addChanges: EngineChangeSignal,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly persistedUserDefaults: PersistedUserDefaults,\n\t\tprivate readonly chromeStore: ChromeStore,\n\t\tprivate readonly guidesStore: GuidesStore,\n\t\tprivate readonly undoRedoManager: UndoRedoManager,\n\t\tprivate readonly layoutCache: LayoutCache,\n\t\tprivate readonly getEffectCacheUpdate: () => EffectPreviewState,\n\t\ttreeServices?: TreeServices,\n\t) {\n\t\tconst projectId = (window as BootstrappedWindow).bootstrap?.project?.id\n\t\tif (projectId) {\n\t\t\tthis.projectId = projectId\n\t\t} else if (!(environment.isAutomation || environment.isTest)) {\n\t\t\tthrow Error(\"Can't find project id\")\n\t\t}\n\n\t\tconst mode = treeModeWithFallback(treeServices?.mode ?? this.initData?.mode)\n\t\tthis.tree = CanvasTree.createWithDefaultWebPage({ ...treeServices, mode })\n\t\tthis.initialTree = this.tree\n\t\tthis.tree.setService(\"treeQueryContext\", this)\n\t\tthis.timeline = this.createTimeline(mode)\n\t\tthis.treeIndex = new TreeIndex(componentLoader, this.timeline)\n\t\tthis.treeIndex.setOnEngineChange(change => this.addChanges(change))\n\t\tthis.assertTimelineMatchesMode()\n\t\tthis.setTree(this.tree)\n\t\tthis.setShowAllArrows(persistedUserDefaults.displayAllLinks, [])\n\t}\n\n\tget mode(): TreeMode {\n\t\treturn getBaseTreeStoreMode(this)\n\t}\n\n\tset mode(mode: TreeMode) {\n\t\tif (\n\t\t\t!switchBaseTreeStoreMode(this, mode, {\n\t\t\t\tinitialTree: this.initialTree,\n\t\t\t\tcreateTimeline: nextMode => this.createTimeline(nextMode),\n\t\t\t\tresetTimeline: true,\n\t\t\t})\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tthis.treeIndex = new TreeIndex(this.componentLoader, this.timeline)\n\t\tthis.treeIndex.setOnEngineChange(change => this.addChanges(change))\n\t\tthis.assertTimelineMatchesMode()\n\t\tthis.addChanges(EngineChange.TreeStore)\n\t}\n\n\tprivate createTimeline(mode: TreeMode): TreeUpdater {\n\t\tconst { projectId } = this\n\t\tconst afterLocalWrite = projectId\n\t\t\t? (branchId: string, seq: number) => getCrdtSession().setSeqWatermark(projectId, branchId, seq)\n\t\t\t: undefined\n\n\t\treturn mode === \"crdt\"\n\t\t\t? new CrdtTreeCommitter(this.tree, this.componentLoader, { afterLocalWrite })\n\t\t\t: new TreeTimeline(this.tree, this.componentLoader)\n\t}\n\n\tassertCrdtTimeline(): asserts this is this & { timeline: CrdtTreeCommitter } {\n\t\tassert(this.mode === \"crdt\", \"CRDT timeline requested for non-CRDT tree mode\")\n\t\tassert(isCrdtTreeCommitter(this.timeline), \"CRDT tree mode requires a CRDT timeline\")\n\t}\n\n\tget crdtTimeline(): CrdtTreeCommitter {\n\t\tthis.assertCrdtTimeline()\n\t\treturn this.timeline\n\t}\n\n\tprivate assertTimelineMatchesMode(): void {\n\t\tconst hasCrdtTimeline = isCrdtTreeCommitter(this.timeline)\n\t\tassert(this.mode === \"crdt\" ? hasCrdtTimeline : !hasCrdtTimeline, \"Tree mode and timeline type are out of sync\")\n\t}\n\n\tprepareDetachedRootReplacement(tree: CanvasTree) {\n\t\tthis.timeline.reset(tree)\n\n\t\tif (this.mode === \"crdt\") {\n\t\t\tthis.resetCrdtStoreToTree(tree)\n\t\t}\n\n\t\tthis.treeIndex = new TreeIndex(this.componentLoader, this.timeline)\n\t\tthis.treeIndex.setOnEngineChange(change => this.addChanges(change))\n\t}\n\n\tprivate resetCrdtStoreToTree(tree: CanvasTree): void {\n\t\tconst { store } = this.crdtTimeline\n\t\tstore.reset()\n\t\tstore.setObject(tree.root.id, tree.root.toJS())\n\t\tstore.setRoot(tree.root.id)\n\t\tstore.setVersion(tree.serializationVersion)\n\t}\n\n\t/**\n\t * For a brand-new CRDT project (or a JSON\u2192CRDT mode switch) nothing populates the main store\n\t * until the first commit, so initialize it from the current tree on demand. Skipped for\n\t * branches, whose stores are expected to be empty and inherit from main via rebase.\n\t */\n\tprivate ensureMainCrdtStoreInitialized(): void {\n\t\tif (this.mode !== \"crdt\") return\n\t\tif (!this.isOnMainBranch()) return\n\t\tif (this.crdtTimeline.store.length > 0) return\n\t\tthis.resetCrdtStoreToTree(this.tree)\n\t}\n\n\t/**\n\t * Asserts that the tree is fully loaded before getting the indexes.\n\t */\n\tgetLoadedIndexes(): TreeStoreIndexes {\n\t\tconst loader = this.tree.getService(\"loader\")\n\t\tassert(!loader, \"Some scopes are still loading:\", loader?.numberOfScopesToLoad(), \"scopes left to load\")\n\t\treturn this.getPartialIndexes()\n\t}\n\n\t/**\n\t * Retrieves the current instance of `TreeStore` with indexes.\n\t * It might be incomplete, as we're still loading scopes\n\t */\n\tgetPartialIndexes(): TreeStoreIndexes {\n\t\t// Fixes false positive reports of linters/editors inspections and gets stripped during build.\n\t\t// As we mark indexes as private and expose them via getter,\n\t\t//  but we need to have them as property because this class is a Store\n\t\t//  and needs to signal changes to the Store Engine.\n\t\tif (process.env.NODE_ENV === \"never\") {\n\t\t\tconst _lintCheck: Record<keyof TreeStoreIndexes, unknown> = {\n\t\t\t\tcodeComponents: this.codeComponents,\n\t\t\t\trichTextNodes: this.richTextNodes,\n\t\t\t\tshaderNodes: this.shaderNodes,\n\t\t\t\tformContainerNodeIds: this.formContainerNodeIds,\n\t\t\t\twithDataIdentifierNodeIds: this.withDataIdentifierNodeIds,\n\t\t\t\tlocalSmartComponentNameByIdentifier: this.localSmartComponentNameByIdentifier,\n\t\t\t\tlocalLayoutTemplatesNameByIdentifier: this.localLayoutTemplatesNameByIdentifier,\n\t\t\t\tactiveScopeShapeContainerNodes: this.activeScopeShapeContainerNodes,\n\t\t\t\tactiveScopeCodeComponentArrows: this.activeScopeCodeComponentArrows,\n\t\t\t\tactiveScopeLinkedNavigationNodes: this.activeScopeLinkedNavigationNodes,\n\t\t\t\tactiveScopeLinkedVariantNodes: this.activeScopeLinkedVariantNodes,\n\t\t\t\tactiveScopeLinkedGestureNodes: this.activeScopeLinkedGestureNodes,\n\t\t\t}\n\t\t}\n\n\t\treturn this as unknown as TreeStoreIndexes\n\t}\n\n\t/** Returns a canvas tree like data structure that works directly on the crdt data. */\n\tgetDataTree(): DataTree | undefined {\n\t\treturn this.timeline.getOrCreateDataTree(this)\n\t}\n\n\t/** Resets the data tree. Called after every frame in postProcess. */\n\tprivate resetDataTree(): void {\n\t\tthis.timeline.resetDataTree()\n\t}\n\n\tgetDataTreeOrLoadedTree(): CanvasTree {\n\t\tconst dataTree = this.getDataTree()\n\t\tif (dataTree) {\n\t\t\treturn dataTree.getCanvasTreeProxy()\n\t\t}\n\n\t\tassert(!this.tree.getService(\"loader\"), \"Tree must be fully loaded\")\n\t\treturn this.tree\n\t}\n\n\tgetDataTreeOrPartialTree(): CanvasTree {\n\t\tconst dataTree = this.getDataTree()\n\t\tif (dataTree) {\n\t\t\treturn dataTree.getCanvasTreeProxy()\n\t\t}\n\n\t\treturn this.tree\n\t}\n\n\t/** Returns a query builder that can be used to query the tree. Which might use the data tree if\n\t * available. Or the real tree and real indexes otherwise. */\n\tquery() {\n\t\treturn new TreeQueryBuilder(this)\n\t}\n\n\tprivate updateActiveScopeShapeContainerNodes() {\n\t\tif (!this.treeIndex.shouldChangeShapeContainerNodes) return\n\t\tthis.treeIndex.shouldChangeShapeContainerNodes = false\n\n\t\tconst shapeContainerNodes = this.treeIndex.getNodesForActiveScope<ShapeContainerNode>(\n\t\t\tthis.treeIndex.shapeContainerNodeIds,\n\t\t)\n\t\tif (!isShallowArrayEqual(this.activeScopeShapeContainerNodes, shapeContainerNodes)) {\n\t\t\tthis.activeScopeShapeContainerNodes = shapeContainerNodes\n\t\t\tthis.addChanges(EngineChange.ShapeContainerNodes)\n\t\t}\n\t}\n\n\tprivate updateGroundNodesList() {\n\t\tif (!this.treeIndex.shouldChangeActiveScopeGroundNodes) return\n\t\tthis.treeIndex.shouldChangeActiveScopeGroundNodes = false\n\n\t\tconst visibleGroundNodes = this.treeIndex.getNodes(this.treeIndex.activeScopeGroundNodeIds).filter(isVisibleNode)\n\t\tif (!isShallowArrayEqual(this.visibleGroundNodesInActiveScope, visibleGroundNodes)) {\n\t\t\tthis.visibleGroundNodesInActiveScope = visibleGroundNodes\n\t\t}\n\n\t\tif (visibleGroundNodes.length > 0) {\n\t\t\tthis.isDocumentEmpty = false\n\t\t\treturn\n\t\t} else {\n\t\t\t// Slower version for when there is no visible ground nodes ground node. The current\n\t\t\t// scope might be empty, but not the document itself.\n\t\t\tfor (const scope of this.tree.root.children) {\n\t\t\t\tif (isScopeNode(scope) && !scope.isValid()) continue\n\t\t\t\tif (!scope.children) continue\n\t\t\t\tfor (const node of scope.children) {\n\t\t\t\t\tif (isVisibleNode(node)) {\n\t\t\t\t\t\tthis.isDocumentEmpty = false\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.isDocumentEmpty = true\n\t}\n\n\tget initialSnapshotVersion() {\n\t\treturn this.initData?.version\n\t}\n\n\tget isNewDocument() {\n\t\tconst treeVersionOnInitialLoad = this.initialSnapshotVersion\n\t\treturn isNumber(treeVersionOnInitialLoad) && treeVersionOnInitialLoad <= 2\n\t}\n\n\tprivate get initialFileURL() {\n\t\treturn this.initData?.file\n\t}\n\n\tprivate get initialSocketURL() {\n\t\treturn this.initData?.socketURL\n\t}\n\n\tget isMPSSocket(): boolean {\n\t\treturn this.initData?.isMPSSocket === true\n\t}\n\n\tget serverHistoryURL() {\n\t\tconst path = `/projects/${this.projectId}/history`\n\t\t// The new Multiplayer Service is mounted at `/multiplayer` on the API\n\t\t// host, while the legacy host serves the same endpoint at `/internal`\n\t\t// on the editor origin.\n\t\treturn this.isMPSSocket ? getMultiplayerServiceURL(path) : `/internal${path}`\n\t}\n\n\tgetSocketURL(defaultSocketURL: string): string {\n\t\treturn this.initialSocketURL ? this.initialSocketURL : defaultSocketURL\n\t}\n\n\tgetDocumentURL(newDocumentURL: string) {\n\t\treturn newDocumentURL || this.initialFileURL\n\t}\n\n\t// tree actions\n\tsetTree(tree: CanvasTree, options?: { isBranchSwitch?: boolean }) {\n\t\tthis.tree = tree\n\t\tthis.tree.setService(\"treeQueryContext\", this)\n\t\tsetTreeMode(this.tree, this.mode)\n\t\ttree.inEditor = true\n\t\tthis.assertTimelineMatchesMode()\n\t\tif (options?.isBranchSwitch) {\n\t\t\tthis.crdtTimeline.replaceTree(tree)\n\t\t} else {\n\t\t\tthis.timeline.reset(tree)\n\t\t}\n\t\tthis.highlight = NullID\n\t\tthis.collapseOverrides = new Map()\n\n\t\tthis.tree.resetDraftNodesAndCache()\n\t\tthis.undoRedoManager.clearUndoStack()\n\t\tthis.addChanges(EngineChange.Tree)\n\t\tthis.addChanges(EngineChange.ColorStyleTokens)\n\t\tthis.addChanges(EngineChange.TextStylePresets)\n\n\t\tassert(tree.root.children.at(0), \"Tree must not be empty\")\n\t\tthis.treeIndex.processReset(tree)\n\t\tthis.updateGroundNodesList()\n\t}\n\n\thasUncommittedChanges(): boolean {\n\t\treturn this.tree.hasUncommittedChanges() || Boolean(this.getDataTree()?.hasUncommittedChanges())\n\t}\n\n\tcommit(): CommitLocalTreeResult {\n\t\tthis.ensureMainCrdtStoreInitialized()\n\t\tconst result = this.timeline.commitLocalTree()\n\n\t\tif (this.pendingCacheUpdateNodeIds.size > 0) {\n\t\t\t// Commit cleared the draft state, so we can safely replay any cache updates the sandbox queued while the\n\t\t\t// tree was mutable.\n\t\t\tthis.updateTreeCacheForNodes(this.pendingCacheUpdateNodeIds, this.componentLoader.activeBundleHash, result.tree)\n\t\t\tthis.pendingCacheUpdateNodeIds.clear()\n\t\t}\n\n\t\treturn result\n\t}\n\n\tsyncNodeCacheWithDOMLayout(changedNodeIds: Set<NodeID>) {\n\t\tconst affectedNodeIds = updateTreeCacheWithLatestDOMLayout(this.tree, this.layoutCache, changedNodeIds)\n\n\t\tif (affectedNodeIds.size > 0) {\n\t\t\tthis.domLayoutUpdate++\n\t\t\tthis.addChanges(EngineChange.TreeDOMLayoutSync)\n\t\t}\n\t}\n\n\t/**\n\t * `node.cache.domRects` / `layoutTemplateRects` are snapshots that\n\t * `updateNodeLayoutCache` only overwrites when `LayoutCache` has fresh\n\t * entries for the node. For nodes mutated outside the active scope no\n\t * sandbox render fires, the rebuild pass doesn't visit them, and\n\t * `LayoutCache.pruneAfterTreeChanges` has already dropped the underlying\n\t * rects, so the snapshot would keep returning pre-edit geometry until the\n\t * user navigates into the affected scope. Drop the snapshot eagerly here\n\t * to match the LayoutCache invalidation.\n\t */\n\tprivate clearStaleDOMLayoutCacheForOutOfScopeNodes(nodeIds: Set<NodeID>) {\n\t\tif (nodeIds.size === 0) return\n\t\tfor (const nodeId of nodeIds) {\n\t\t\tconst node = this.tree.get(nodeId)\n\t\t\tif (!node || !withDOMLayout(node)) continue\n\t\t\tnode.invalidateDOMRect()\n\t\t}\n\t}\n\n\t/**\n\t * Resets and updates the tree cache for the given node ids. If the tree has uncommitted changes, it will update\n\t * the cache after commit()\n\t */\n\tupdateTreeCacheForNodes(nodeIds: Set<NodeID>, componentLoaderHash: string | undefined, tree: CanvasTree = this.tree) {\n\t\tif (nodeIds.size === 0) return\n\n\t\tif (tree.hasUncommittedChanges()) {\n\t\t\t// Buffer the nodes to update. It will run the update again in this.commit().\n\t\t\tfor (const id of nodeIds) {\n\t\t\t\tthis.pendingCacheUpdateNodeIds.add(id)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tconst scopesToUpdate = resetAncestorCacheForNodes(tree, nodeIds)\n\n\t\tthis.addChanges(EngineChange.TreeStore)\n\n\t\tupdateTreeCacheForVekter(\n\t\t\ttree,\n\t\t\tthis.layoutCache,\n\t\t\tthis.sandboxRepeaterData,\n\t\t\tthis.sandboxVisibility,\n\t\t\tthis.componentLoader,\n\t\t\tcomponentLoaderHash,\n\t\t\tthis.chromeStore.canvasLocaleId,\n\t\t\tthis.getEffectCacheUpdate(),\n\t\t\tscopesToUpdate,\n\t\t)\n\t}\n\n\t// computes the data behind rendering arrows between screens and between code components\n\tupdateConnectedScreens(selection: Selection) {\n\t\tthis.treeIndex.updateConnectedScreens(this.tree, selection, this.showAllArrows)\n\t\tif (\n\t\t\tthis.activeScopeLinkedNavigationNodes !== this.treeIndex.activeScopeLinkedNavigationNodes ||\n\t\t\tthis.activeScopeLinkedVariantNodes !== this.treeIndex.activeScopeLinkedVariantNodes ||\n\t\t\tthis.activeScopeLinkedGestureNodes !== this.treeIndex.activeScopeLinkedGestureNodes ||\n\t\t\tthis.activeScopeCodeComponentArrows !== this.treeIndex.activeScopeCodeComponentArrows\n\t\t) {\n\t\t\tthis.activeScopeLinkedNavigationNodes = this.treeIndex.activeScopeLinkedNavigationNodes\n\t\t\tthis.activeScopeLinkedVariantNodes = this.treeIndex.activeScopeLinkedVariantNodes\n\t\t\tthis.activeScopeLinkedGestureNodes = this.treeIndex.activeScopeLinkedGestureNodes\n\t\t\tthis.activeScopeCodeComponentArrows = this.treeIndex.activeScopeCodeComponentArrows\n\t\t\tthis.addChanges(EngineChange.Arrows)\n\t\t}\n\t}\n\n\tupdateVariableProviderInfo(selection: Selection) {\n\t\tconst nodes = this.tree.getNodes(selection)\n\t\t// Node-level repeat providers should share variable context with their direct children.\n\t\t// For these nodes we compare against the combined map (including self-provided variables),\n\t\t// while keeping inherited-only behavior for other nodes.\n\t\tconst variableValueMaps = nodes.map(node =>\n\t\t\thasRepeatArray(node)\n\t\t\t\t? node.cache.getUnsafeCombinedVariableValueMap()\n\t\t\t\t: node.cache.getUnsafeInheritedCombinedVariableValueMap(),\n\t\t)\n\t\tconst allNodesSupportVariableReferences = nodes.every(node => node.supportsDynamicValues())\n\t\tconst allNodesShareVariableContext = new Set(variableValueMaps).size === 1\n\t\tconst firstNode = nodes[0]\n\n\t\tthis.allNodesShareVariableContext = allNodesShareVariableContext\n\n\t\tconst previousVariableProviderInfo = this.variableProviderInfo\n\t\tthis.variableProviderInfo = getMemoizedVariableProviderInfo(\n\t\t\tthis.tree,\n\t\t\tthis.componentLoader,\n\t\t\tallNodesShareVariableContext,\n\t\t\tallNodesSupportVariableReferences,\n\t\t\tfirstNode,\n\t\t)\n\n\t\tif (previousVariableProviderInfo !== this.variableProviderInfo) {\n\t\t\tthis.addChanges(EngineChange.VariableProviderInfo)\n\t\t}\n\t}\n\n\tupdateCodeComponents() {\n\t\tthis.treeIndex.updateCodeComponents()\n\t}\n\n\tupdateGroundNodesInViewport(viewport: Rect) {\n\t\tconst inViewport = new Set<NodeID>()\n\t\tconst previousInViewport = this.groundNodesInViewport\n\t\tconst groundNodes = this.visibleGroundNodesInActiveScope\n\n\t\tlet same = true\n\t\tfor (const groundNode of groundNodes) {\n\t\t\tconst id = groundNode.id\n\t\t\tif (Rect.intersects(getGroundNodeOverflowRect(groundNode), viewport)) {\n\t\t\t\tinViewport.add(id)\n\t\t\t\tif (same && !previousInViewport.has(id)) {\n\t\t\t\t\tsame = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!same || inViewport.size !== previousInViewport.size) {\n\t\t\tthis.groundNodesInViewport = inViewport\n\t\t}\n\t}\n\n\tprivate selectionDidChange(selection: Selection) {\n\t\tconst tree = this.tree\n\n\t\t// Filter away nodeid references that no longer exist\n\t\tfor (const id in this.collapseOverrides) {\n\t\t\tif (!tree.has(id)) {\n\t\t\t\tthis.deleteCollapseOverride(id)\n\t\t\t}\n\t\t}\n\n\t\tif (!tree.has(this.highlight)) {\n\t\t\tthis.highlight = NullID\n\t\t}\n\n\t\t// Update collapsed overrides\n\t\tif (selection.length > 0) {\n\t\t\t// Check if manually collapsed nodes need to be reopened\n\t\t\tif (this.collapseOverrides.size > 0) {\n\t\t\t\tconst addedToSelection = without(selection, this.oldSelection)\n\t\t\t\tconst selectionAncestors: NodeID[] = []\n\t\t\t\taddedToSelection.forEach(addedId => {\n\t\t\t\t\tselectionAncestors.push(...tree.getAncestors(addedId))\n\t\t\t\t})\n\t\t\t\tselectionAncestors.forEach(expandId => {\n\t\t\t\t\tthis.deleteCollapseOverride(expandId)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Update tree cache\n\n\t\tlet selectionIsDifferent = this.oldSelection.length !== selection.length\n\n\t\tfor (const id of selection) {\n\t\t\tconst node = this.tree.getNode(id)\n\t\t\tif (!node) continue\n\t\t\tif (node.cache.selected) continue\n\n\t\t\tselectionIsDifferent = true\n\t\t\tnode.cache.selected = true\n\t\t}\n\n\t\tif (selectionIsDifferent) {\n\t\t\tfor (const id of this.oldSelection) {\n\t\t\t\tif (selection.includes(id)) continue\n\t\t\t\tconst node = tree.getNode(id)\n\t\t\t\tif (!node) continue\n\n\t\t\t\tnode.cache.selected = false\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\t\t!environment.benchmarkSkipTreeVerify &&\n\t\t\ttree.size() < MAX_VERIFY_TREE_SIZE\n\t\t) {\n\t\t\tverifySelectionCache(tree, selection)\n\t\t}\n\t}\n\n\tprivate processLatestChangesForUndo() {\n\t\tconst changes = this.timeline.getLatestChangesForUndo()\n\t\tif (!changes) return []\n\n\t\tconst changesForUndo: ReversibleNodeChange[] = []\n\t\tfor (const change of changes) {\n\t\t\tif (!change.ignoreInUndo) {\n\t\t\t\tchangesForUndo.push(change)\n\t\t\t}\n\n\t\t\tconst node = this.tree.get(change.id)\n\t\t\tif (isColorStyleTokenNode(node) || isColorStyleTokenListNode(node)) {\n\t\t\t\tthis.addChanges(EngineChange.ColorStyleTokens)\n\t\t\t}\n\n\t\t\tif (isTextStylePresetNode(node) || isPresetsListNode(node)) {\n\t\t\t\tthis.addChanges(EngineChange.TextStylePresets)\n\t\t\t}\n\n\t\t\t// clean up default fill it is set to the deleted color token\n\t\t\tconst defaultFill = this.persistedUserDefaults.frameBackground\n\t\t\tif (change.removed === ClassDiscriminator.ColorStyleTokenNode && defaultFill) {\n\t\t\t\tif (defaultFill.includes(change.id)) {\n\t\t\t\t\tthis.persistedUserDefaults.frameBackground = null\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn changesForUndo\n\t}\n\n\tdiscardUndoRedoEntriesForNode(nodeId: NodeID) {\n\t\tthis.undoRedoManager.removeEntriesForNode(nodeId)\n\t}\n\n\tpostProcess(\n\t\ttree: CanvasTree,\n\t\tselection: Selection,\n\t\tuserEdit: boolean,\n\t\tactiveScopeId: NodeID,\n\t\tlocaleId: LocaleId | undefined,\n\t\tselectedGradientStopId?: NodeID | undefined,\n\t) {\n\t\tassert(!tree.hasUncommittedChanges(), \"tree must be clean\")\n\t\tassert(tree.isLatest(), \"tree must be latest\")\n\t\ttree.lineage.setActiveChangeset(undefined)\n\n\t\tthis.resetDataTree()\n\n\t\tconst changedTree = this.tree !== tree\n\t\tlet changedActiveScope = false\n\n\t\tif (changedTree) {\n\t\t\tchangedActiveScope = tree.get(activeScopeId) !== this.tree.get(activeScopeId)\n\t\t\tthis.tree = tree\n\t\t\tthis.addChanges(EngineChange.Tree)\n\n\t\t\t// for testing red bar recovery\n\t\t\tif (this.crashSoon) {\n\t\t\t\tthis.crashSoon = false\n\t\t\t\tthrow Error(\"TreeStore CrashTest\")\n\t\t\t}\n\t\t}\n\n\t\tthis.tree.beginAllowPartialScopeAccess()\n\n\t\tconst changedSelection = this.oldSelection !== selection\n\t\tif (changedSelection) {\n\t\t\tthis.selectionDidChange(selection)\n\t\t}\n\n\t\tif (changedTree) {\n\t\t\tconst changes = this.processLatestChangesForUndo()\n\t\t\t// Record an undo entry, captures the previous selection\n\t\t\tif (userEdit) {\n\t\t\t\t// Not all changes actually produce a diff, like closing the text editor\n\t\t\t\tif (changes.length > 0) {\n\t\t\t\t\tthis.undoRedoManager.addUndoEntry({\n\t\t\t\t\t\tchanges,\n\t\t\t\t\t\tselection: this.oldSelection,\n\t\t\t\t\t\tscopeId: this.oldScopeId ?? activeScopeId,\n\t\t\t\t\t\tlocaleId: localeId,\n\t\t\t\t\t\tselectedGradientStopId: this.oldSelectedGradientStopId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.addChanges(EngineChange.TreeStore)\n\t\t\tif (changes.length > 0) {\n\t\t\t\tconst outOfScopeMutatedNodeIds = this.layoutCache.pruneAfterTreeChanges(changes, this.tree, activeScopeId)\n\t\t\t\tthis.clearStaleDOMLayoutCacheForOutOfScopeNodes(outOfScopeMutatedNodeIds)\n\t\t\t}\n\n\t\t\t// TreeIndex Updates\n\t\t\tthis.treeIndex.process(tree, activeScopeId)\n\t\t} else {\n\t\t\tthis.treeIndex.processActiveScope(tree, activeScopeId)\n\t\t}\n\n\t\tthis.updateActiveScopeShapeContainerNodes()\n\t\tthis.updateGroundNodesList()\n\n\t\tif (changedActiveScope || changedSelection) {\n\t\t\tthis.updateConnectedScreens(selection)\n\t\t}\n\n\t\tif (changedTree || changedSelection) {\n\t\t\tthis.updateVariableProviderInfo(selection)\n\t\t}\n\n\t\tthis.oldSelection = selection\n\t\tthis.oldScopeId = activeScopeId\n\t\tthis.oldSelectedGradientStopId = selectedGradientStopId\n\n\t\tthis.undoRedoManager.processScheduledEndUndoGroup({\n\t\t\tselection,\n\t\t\tscopeId: activeScopeId,\n\t\t\tlocaleId,\n\t\t\tselectedGradientStopId,\n\t\t})\n\n\t\tthis.tree.endAllowPartialScopeAccess()\n\t}\n\n\t// selection actions\n\tsetHighlight(highlight: MaybeNodeID) {\n\t\tif (this.highlight === highlight) return\n\t\tthis.highlight = highlight\n\t\t// reset guide highlight when a node is highlighted\n\t\tif (highlight) this.guidesStore.highlighted = undefined\n\t\tthis.addChanges(EngineChange.TreeStore, EngineChange.Highlight)\n\t}\n\n\tprivate setCollapseOverride(nodeId: NodeID, collapsed: boolean) {\n\t\tconst collapseOverrides = new Map(this.collapseOverrides)\n\t\tcollapseOverrides.set(nodeId, collapsed)\n\t\tthis.collapseOverrides = collapseOverrides\n\t}\n\n\tprivate deleteCollapseOverride(nodeId: NodeID) {\n\t\tif (!this.collapseOverrides.has(nodeId)) return\n\t\tconst collapseOverrides = new Map(this.collapseOverrides)\n\t\tcollapseOverrides.delete(nodeId)\n\t\tthis.collapseOverrides = collapseOverrides\n\t}\n\n\tsetCollapseMode(nodeid: NodeID, collapsed: boolean, override: boolean) {\n\t\tif (override) {\n\t\t\tthis.setCollapseOverride(nodeid, collapsed)\n\t\t} else if (this.collapseOverrides.has(nodeid)) {\n\t\t\tthis.deleteCollapseOverride(nodeid)\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t\tthis.addChanges(EngineChange.TreeStore)\n\t}\n\n\tcollapseLayers(ids: NodeID[]) {\n\t\tconst collapseOverrides: Map<NodeID, boolean> = new Map()\n\n\t\tfor (const id of ids) {\n\t\t\tconst node = this.tree.get(id)\n\t\t\tif (!node) continue\n\t\t\tif (!node.children) continue\n\n\t\t\t// We only need to collapse the direct descendants of the\n\t\t\t// selected node in order to collapse all descendants within.\n\t\t\tfor (const descendant of node.children) {\n\t\t\t\tcollapseOverrides.set(descendant.id, true)\n\t\t\t}\n\t\t\tcollapseOverrides.set(id, true)\n\t\t}\n\t\tthis.collapseOverrides = collapseOverrides\n\t\tthis.addChanges(EngineChange.TreeStore)\n\t}\n\n\tresetCollapseOverrides() {\n\t\tthis.collapseOverrides = new Map()\n\t\tthis.addChanges(EngineChange.TreeStore)\n\t}\n\n\tsetShowAllArrows(showAllArrows: boolean, selection: Selection) {\n\t\tif (this.showAllArrows === showAllArrows) return\n\t\tthis.showAllArrows = showAllArrows\n\n\t\tthis.updateConnectedScreens(selection)\n\t\tthis.addChanges(EngineChange.TreeStore)\n\t}\n\n\tresetTreeWithToken(token: number) {\n\t\tconst result = this.undoRedoManager.resetTreeWithToken(this.timeline, token)\n\t\tif (!result) return\n\n\t\tconst { selection, changedGroundNodes } = result\n\n\t\t// Normally the visibility cache will be updated when engine process the\n\t\t// frame, but the move tool checks isOnlyVisibleInCurrentVariant after\n\t\t// the reset, and this requires the cache to be correctly updated.\n\t\tfor (const groundNode of changedGroundNodes) {\n\t\t\tthis.unsafeUpdateNodeCache(groundNode, true, false)\n\t\t}\n\n\t\treturn selection\n\t}\n\n\t// FIXME: it would be nice to use the normal cache reset so all cache properties would be correct\n\tprivate unsafeUpdateNodeCache(node: CanvasNode, parentVisible: boolean, insideVariant: boolean) {\n\t\t// The node could be a replica, and its visibility and children might\n\t\t// change after the rebuilt, so we need to check the draft node\n\t\tnode = node.draftOrCurrent()\n\n\t\tconst isHiddenOverlay = isFixedOrRelativeOverlay(node) && !node.cache.overlayVisible\n\t\tparentVisible &&= experiments.isOn(\"visibilityFromSandbox\")\n\t\t\t? this.sandboxVisibility.getVisible(node.id)\n\t\t\t: node.isVisible()\n\t\tconst visible = parentVisible && !isHiddenOverlay\n\t\tnode.cache.visible = visible\n\n\t\tinsideVariant ||= isVariant(node)\n\t\tnode.cache.insideVariant = insideVariant\n\n\t\tnode.children?.forEach(child => this.unsafeUpdateNodeCache(child, visible, insideVariant))\n\t}\n\n\tget remoteTreeVersion(): number {\n\t\treturn this.timeline.remoteTreeVersion\n\t}\n\n\t/**\n\t * Test-only method that triggers all lazy index computations.\n\t * Ensures all lazy getters are initialized and their shouldChange flags are reset.\n\t */\n\tdebugComputeLazyIndexes(): void {\n\t\t// Type-safe check to ensure all TreeStoreIndexes properties are accessed\n\t\tconst _allIndexes: Record<keyof TreeStoreIndexes, unknown> = {\n\t\t\tcodeComponents: this.codeComponents,\n\t\t\trichTextNodes: this.richTextNodes,\n\t\t\tshaderNodes: this.shaderNodes,\n\t\t\tformContainerNodeIds: this.formContainerNodeIds,\n\t\t\twithDataIdentifierNodeIds: this.withDataIdentifierNodeIds,\n\t\t\tlocalSmartComponentNameByIdentifier: this.localSmartComponentNameByIdentifier,\n\t\t\tlocalLayoutTemplatesNameByIdentifier: this.localLayoutTemplatesNameByIdentifier,\n\t\t\tactiveScopeShapeContainerNodes: this.activeScopeShapeContainerNodes,\n\t\t\tactiveScopeCodeComponentArrows: this.activeScopeCodeComponentArrows,\n\t\t\tactiveScopeLinkedNavigationNodes: this.activeScopeLinkedNavigationNodes,\n\t\t\tactiveScopeLinkedVariantNodes: this.activeScopeLinkedVariantNodes,\n\t\t\tactiveScopeLinkedGestureNodes: this.activeScopeLinkedGestureNodes,\n\t\t}\n\t\tvoid _allIndexes\n\t}\n\n\tget branchId(): string {\n\t\treturn this.mode === \"crdt\" ? this.crdtTimeline.branches.activeBranchId : MAIN_BRANCH_ID\n\t}\n\n\tisOnMainBranch(): boolean {\n\t\treturn this.branchId === MAIN_BRANCH_ID\n\t}\n}\n", "interface Options {\n\t/** Max printable items (E.g. max: 3 -> one, two, three and X others) */\n\tmax?: number\n\t/** Placeholder for empty/undefined inputs */\n\tplaceholder?: string\n}\n\n/**\n * Outputs array of strings in \"pizza, banana and burrito\" format\n */\n\nexport function arrayToText(array?: string[], options?: Options): string {\n\tif (!array || array.length === 0) {\n\t\treturn options?.placeholder ?? \"\"\n\t}\n\n\tif (array.length === 1) {\n\t\tif (array[0] && array[0] !== \"\") {\n\t\t\treturn array[0]\n\t\t}\n\t\treturn options?.placeholder ?? \"\"\n\t}\n\n\tlet printableItems: string[] = [...array]\n\tlet lastItem: string = \"\"\n\tif (options?.max && options.max < array.length) {\n\t\tconst otherCount = array.length - options.max\n\t\tprintableItems = printableItems.slice(0, options.max)\n\t\tlastItem = `${otherCount} ${otherCount > 1 ? \"others\" : \"other\"}`\n\t} else {\n\t\tlastItem = printableItems.pop() ?? \"\"\n\t}\n\n\treturn printableItems.length > 1\n\t\t? `${printableItems.join(\", \")}, and ${lastItem}` // Add oxford comma for more than 2 items\n\t\t: `${printableItems.join(\", \")} and ${lastItem}`\n}\n", "import {\n\tassert,\n\ttype GlobalModuleId,\n\ttype ModuleExportIdentifierString,\n\tisExternalModuleIdentifier,\n\tisModuleExportIdentifier,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport type { CanvasNode, CanvasTree, CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { getContentManagementNode } from \"document/models/CanvasTree/nodes/ContentManagementNode.utils.ts\"\nimport {\n\tisCollectionItemNode,\n\tisCollectionNode,\n\tisLayoutTemplateNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { WithControlProps } from \"document/models/CanvasTree/traits/WithControlProps.ts\"\nimport type { WithVariables } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { isString } from \"./typeChecks.ts\"\n\ntype ExportKey = `${GlobalModuleId}:${string}`\n\n// An external module export identifier determines the global id and save id. When updating, we look\n// for all identifiers with the same global id and export identifier.\nfunction exportKeyForIdentifier(identifier: string): ExportKey | undefined {\n\tconst parsed = parseModuleIdentifier(identifier)\n\tif (!parsed || !isModuleExportIdentifier(parsed) || !isExternalModuleIdentifier(parsed)) return\n\treturn `${parsed.moduleId}:${parsed.exportSpecifier}`\n}\n\nexport function getExportReplacementMap(identifiers: Iterable<ModuleExportIdentifierString>) {\n\tconst lookup = new Map<ExportKey, ModuleExportIdentifierString>()\n\tfor (const identifier of identifiers) {\n\t\tconst key = exportKeyForIdentifier(identifier)\n\t\tif (!key) continue\n\t\tlookup.set(key, identifier)\n\t}\n\treturn lookup\n}\n\nfunction updateExternalModuleControlPropValues(\n\tnode: CanvasNode & WithControlProps,\n\tmap: Map<ExportKey, ModuleExportIdentifierString>,\n) {\n\tconst props = node.getRawControlProps()\n\tfor (const key in props) {\n\t\tconst type = props[key]?.type\n\t\tconst value = props[key]?.value\n\t\tif (type !== ControlType.VectorSetItem || !isString(value) || !isModuleExportIdentifier(value)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst lookupKey = exportKeyForIdentifier(value)\n\t\tif (!lookupKey || !map.has(lookupKey)) continue\n\n\t\tconst replacement = map.get(lookupKey)\n\t\tif (!replacement) continue\n\n\t\tnode.setControlProp(key, {\n\t\t\ttype: ControlType.VectorSetItem,\n\t\t\tvalue: replacement,\n\t\t})\n\t}\n}\n\nexport function updateExternalModuleInstances(\n\tmap: Map<ExportKey, ModuleExportIdentifierString>,\n\tnodes: Iterable<CodeComponentNode>,\n) {\n\tfor (const node of nodes) {\n\t\t// Any code component can have external vector control props, even if its identifier isn't\n\t\t// in the map.\n\t\tupdateExternalModuleControlPropValues(node, map)\n\n\t\tconst key = exportKeyForIdentifier(node.codeComponentIdentifier)\n\t\tif (!key || !map.has(key)) continue\n\t\tconst replacement = map.get(key)\n\t\tif (!replacement) continue\n\n\t\tnode.set({ codeComponentIdentifier: replacement })\n\t}\n}\n\nexport function updateExternalModuleCollectionValues(\n\tmap: Map<ExportKey, ModuleExportIdentifierString>,\n\ttree: CanvasTree,\n) {\n\tconst cms = getContentManagementNode(tree)\n\tif (!cms) return\n\tassert(cms.isLoaded(), \"CMS Should always be loaded.\")\n\tfor (const { node, skipChildren } of cms.walkWithSkipChildren()) {\n\t\tif (isCollectionNode(node)) {\n\t\t\tconst hasVectorVariables = node.variables.some(v => v.type === ControlType.VectorSetItem)\n\t\t\t// Avoid walking a collection if it doesn't have vector variables.\n\t\t\tif (!hasVectorVariables) {\n\t\t\t\tskipChildren()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tupdateExternalModuleVariableInitialValue(node, map)\n\t\t}\n\n\t\tif (!isCollectionItemNode(node)) continue\n\n\t\tconst props = node.getControlProps()\n\t\tfor (const key in props) {\n\t\t\tconst value = props[key]?.value\n\t\t\tconst type = props[key]?.type\n\t\t\tif (type !== ControlType.VectorSetItem || !isString(value) || !isModuleExportIdentifier(value)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst lookupKey = exportKeyForIdentifier(value)\n\t\t\tif (!lookupKey || !map.has(lookupKey)) continue\n\n\t\t\tconst replacement = map.get(lookupKey)\n\t\t\tif (!replacement) continue\n\n\t\t\tnode.setControlProp(key, {\n\t\t\t\t...props[key],\n\t\t\t\tvalue: replacement,\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunction updateExternalModuleVariableInitialValue(\n\tnode: CanvasNode & WithVariables,\n\tmap: Map<ExportKey, ModuleExportIdentifierString>,\n) {\n\tlet update = false\n\tconst variables = node.variables.map(variable => {\n\t\tif (variable.type !== ControlType.VectorSetItem) return variable\n\n\t\tconst { initialValue } = variable\n\t\tconst identifier = initialValue.identifier\n\t\tif (!identifier) return variable\n\n\t\tconst lookupKey = exportKeyForIdentifier(identifier)\n\t\tif (!lookupKey || !map.has(lookupKey)) return variable\n\t\tconst replacement = map.get(lookupKey)\n\t\tif (!replacement) return variable\n\t\tupdate = true\n\t\treturn { ...variable, initialValue: { ...initialValue, identifier: replacement } }\n\t})\n\n\tif (!update) return\n\n\tnode.set({ variables })\n}\n\nexport function updateScopeNodeExternalModules(map: Map<ExportKey, ModuleExportIdentifierString>, tree: CanvasTree) {\n\tfor (const node of tree.root.children) {\n\t\tif (isWebPageNode(node)) {\n\t\t\tupdateExternalModuleControlPropValues(node, map)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isSmartComponentNode(node) || isLayoutTemplateNode(node)) {\n\t\t\tupdateExternalModuleVariableInitialValue(node, map)\n\t\t}\n\t}\n}\n", "import type { Immutable, Patch } from \"@framerjs/app-shared/src/lib/immer.ts\"\nimport { produceWithPatches } from \"@framerjs/app-shared/src/lib/immer.ts\"\nimport { triggerExternalComponentInsertEvent } from \"@framerjs/framer-events\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { Annotations, ExportSpecifier } from \"@framerjs/framer-runtime/crossorigin\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ModulesAPI, ModulesUpdates, ServiceStreamOptions } from \"@framerjs/framer-services\"\nimport { ServiceEventEmitter } from \"@framerjs/framer-services\"\nimport type {\n\tDEPENDENCIES_FILE_ID,\n\tExternalModuleBareIdentifierString,\n\tExternalModuleExportIdentifier,\n\tExternalModuleExportIdentifierString,\n\tGlobalModuleId,\n\tIMPORT_MAP_FILE_ID,\n\tLocalModuleExportIdentifierString,\n\tLocalModuleId,\n} from \"@framerjs/shared\"\nimport {\n\tDEPENDENCIES_MODULE_TYPE_SLASH_NAME,\n\tModuleType,\n\tResolvablePromise,\n\tasGlobalId,\n\tassert,\n\texternalModuleIdentifier,\n\tgetLogger,\n\tisExternalModuleIdentifier,\n\tisLocalModuleIdentifier,\n\tisModuleExportIdentifier,\n\tlocalModuleIdentifier,\n\tlocalModuleIdentifierForStableName,\n\tlocalModuleImportMapSpecifier,\n\tparseModuleIdentifier,\n\tstableTypeAndNameFromLocalId,\n\tunhandledError,\n} from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport {\n\tisFramerVectorInfo,\n\tisFramerVectorSetInfo,\n\tisPublishedVectorSetInfo,\n} from \"code-generation/utils/annotations.ts\"\nimport type { NonPromiseLike } from \"document/VekterEngine.ts\"\nimport type { BaseLoadedExternalModulesStore } from \"document/base-engine/BaseLoadedExternalModulesStore.ts\"\nimport type { BaseTreeStore } from \"document/base-engine/BaseTreeStore.ts\"\nimport { hasDismissedInstantNPMToast, showInstantNPMToast } from \"document/components/chrome/shared/InstantNPMToast.tsx\"\nimport {\n\tCodeComponentNode,\n\ttype LoadedScopeNode,\n\ttype NodeID,\n\ttype ScopeNode,\n\tShaderNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCodeComponentNode,\n\tisExternalModuleNode,\n\tisExternalModulesListNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { TreeStore } from \"document/stores/TreeStore.ts\"\nimport { ActiveMainView } from \"document/utils/ActiveEditorType.ts\"\nimport { addBeforeUnloadHandler } from \"document/utils/beforeUnloadHandler.ts\"\nimport { environment } from \"environment/index.ts\"\nimport type { WritableDraft } from \"immer/dist/types/types-external.d.ts\"\nimport type { DependencyGraph } from \"modules/DependencyGraph.ts\"\nimport { collectModuleAndItsDependentsRecursively } from \"modules/DependencyGraph.ts\"\nimport type {\n\tDependenciesModule,\n\tDependenciesModuleEntry,\n\tFastRefreshModuleEntry,\n\tModuleEntry,\n\tModuleUpdateSource,\n\tModulesStorageListener,\n\tModulesStorageSnapshot,\n\tPersistParams,\n\tPersistedModule,\n} from \"modules/ModulesStorage.ts\"\nimport { ModulesStorage, TypedModulesStorage } from \"modules/ModulesStorage.ts\"\nimport type { CodeWithRelativeImports } from \"modules/compiler.ts\"\nimport { compileModule, compileModuleForFastRefresh } from \"modules/compiler.ts\"\nimport { filenamesFromModuleName } from \"modules/filenamesFromModuleName.ts\"\nimport type { ReplacementMap } from \"modules/rewriteRelativeImports.ts\"\nimport { rewriteRelativeImports } from \"modules/rewriteRelativeImports.ts\"\nimport type {\n\tDependenciesMap,\n\tImportMap,\n\tModuleOwnerId,\n\tModuleOwnerType,\n\tModuleSpecifier,\n\tTypeSlashName,\n} from \"modules/types.ts\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport { getTypeSlashName, normalizePath, parseModuleAnnotations, scopeNodeIdFromModule } from \"modules/utils.ts\"\nimport { arrayToText } from \"utils/arrayToText.ts\"\nimport { replaceModuleIdentifierInCollections } from \"utils/collectionUtils.ts\"\nimport { updateModuleIdentifiersInComponentPresets } from \"utils/componentPresetUtils.ts\"\nimport {\n\tgetExportReplacementMap,\n\tupdateExternalModuleCollectionValues,\n\tupdateExternalModuleInstances,\n\tupdateScopeNodeExternalModules,\n} from \"utils/externalModules.ts\"\nimport { resultify } from \"utils/result.ts\"\nimport { throttle } from \"utils/throttle.ts\"\nimport { tryParseNumber } from \"utils/tryParseNumber.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport { v4 as uuid } from \"uuid\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport { getCodeComponentModuleTypeSlashNamesInScope } from \"../../modules/getCodeComponentModuleTypeSlashNamesInScope.ts\"\nimport type { InstallDescriptor } from \"../../modules/importMapManager.ts\"\nimport {\n\tdidExistingImportMapResolutionChange,\n\textendDependencies,\n\textendImportMap,\n\tgenerateDependenciesFromImportMap,\n\tgetImportMapKey,\n\tisBlockedDependency,\n\tisImportMapEmpty,\n\tparseImportMapContent,\n} from \"../../modules/importMapManager.ts\"\nimport { EngineStore } from \"../EngineStore.ts\"\nimport {\n\tExternalModuleNode,\n\tExternalModulesListNode,\n\tisParsedAnnotationExternalModuleType,\n} from \"../models/CanvasTree/nodes/ExternalModuleNode.ts\"\nimport type { ChromeStore } from \"./ChromeStore.ts\"\n\nconst log = getLogger(\"modules-store\")\nconst fastRefreshableModuleTypes = new Set([\n\tModuleType.Code,\n\tModuleType.Canvas,\n\tModuleType.Screen,\n\tModuleType.LayoutTemplate,\n\tModuleType.Vector,\n])\n\nexport type ModuleEntries = Map<TypeSlashName, ModuleEntry>\n\nconst updateLookupQueryBatchSize = 500\n\nexport enum ExternalComponentInsertType {\n\tpaste = \"paste\",\n\tpasteURL = \"paste-url\",\n\tinsertDefaultComponent = \"insert-default\",\n\tdragInsertDefaultComponent = \"insert-default-drag\",\n\tinsertLibraryComponent = \"insert-library\",\n\tdragInsertLibraryComponent = \"insert-library-drag\",\n\tinsertComponent = \"insert\", // for any externalModuleComponent which has been added to this project\n\tdragInsertComponent = \"insert-drag\", // for any externalModuleComponent which has been added to this project\n\tupdate = \"update\",\n}\n\ninterface UpdateExternalModuleNodesOptions<T> {\n\t/** Function that will execute immediately after ExternalModuleNodes have been updated. */\n\tonTreeUpdate: () => NonPromiseLike<T, T>\n\t/** Whether to bump the save id if the ExternalModuleNode already exists. */\n\tupdateSave?: boolean\n\t/** Allows callers such as the agent to record this tree update in a caller-owned changeset. */\n\tscheduleTreeUpdate?: <R>(task: () => NonPromiseLike<R, R>) => Promise<R>\n}\n\nexport type ModuleLookupQuery =\n\t| { url: string }\n\t| ModuleSaveReference\n\t| { namespace: string; name: string }\n\t| { slug: string }\n\nexport interface ModuleSaveReference {\n\tmoduleId: GlobalModuleId\n\tsaveId: string\n}\n\ninterface ModuleLookupOptions {\n\tincludeDependencies?: boolean\n\tincludeStatus?: boolean\n}\n\ninterface DependenciesInfo {\n\tdependencies?: DependenciesMap\n\timportMap?: ImportMap\n\tmoduleId?: string\n\tsaveId?: string\n}\n\ninterface ModuleLookupInfo {\n\tmodule: ModulesAPI.ModuleWithSave\n\tdependencies?: DependenciesInfo\n}\n\ninterface ModulesLookupInfo {\n\tmodules: ModulesAPI.ModuleWithSave[]\n\tdependencies?: {\n\t\t[ownerType: ModuleOwnerType]: {\n\t\t\t[ownerId: ModuleOwnerId]: DependenciesInfo\n\t\t}\n\t}\n}\n\nfunction hasSourceContent(\n\tmodule: ModulesAPI.ModuleWithSave,\n): module is ModulesAPI.ModuleWithSave & { sourceContent: string } {\n\treturn \"sourceContent\" in module && isString(module.sourceContent)\n}\n\nexport interface ComponentInfo extends ModuleLookupInfo {\n\texportSpecifier: string\n}\n\nfunction moduleIdentifierForComponent(component: ComponentInfo) {\n\tconst { module, exportSpecifier } = component\n\tconst { id, saveId, files } = module\n\tassert(files.module, \"module file must exist for a saved module\")\n\treturn externalModuleIdentifier(asGlobalId(id), saveId, files.module, exportSpecifier)\n}\n\n/** Data about a module that may change over time, independent of saves. */\nexport type DynamicModuleInfo = Pick<\n\tModulesAPI.ModuleWithSave,\n\t\"title\" | \"description\" | \"lastPublish\" | \"status\" | \"localId\"\n>\n\ntype NpmDependencyInstallStatus = \"success\" | \"failure\" | \"unknown\"\n\ntype NpmDependenciesCache = Map<string, \"success\" | \"failure\">\n\n/**\n * Minimal interface for accessing persisted modules.\n *\n * Works with both {@link ModulesStore} and {@link ModulesStoreSnapshot}.\n */\nexport interface PersistedModuleProvider {\n\tgetPersistedModuleByLocalId(id: LocalModuleId): PersistedModule | undefined\n}\n\nexport class ModulesStore extends EngineStore implements PersistedModuleProvider {\n\tpublic dependenciesModule: DependenciesModuleEntry | undefined = undefined\n\tpublic localModules: Immutable<ModuleEntries> = new Map()\n\t// This contains a subset of the localModules, but with a different type\n\tpublic fastRefreshModules: Immutable<Map<TypeSlashName, FastRefreshModuleEntry>> = new Map()\n\tpublic externalModulesDynamicInfo: Immutable<Map<GlobalModuleId, DynamicModuleInfo>> = new Map()\n\tpublic revision = 0\n\t/**\n\t * Keeps track of the install status of project's npm dependencies.\n\t */\n\t#npmDependenciesStatusCache: NpmDependenciesCache = new Map()\n\tprivate moduleDepsGraph: DependencyGraph = {}\n\tprivate readonly modulesStorage: ModulesStorage\n\tprivate readonly moduleUpdatesEmitter = new ServiceEventEmitter<ModulesUpdates.ModulesUpdateEvent>()\n\tprivate readonly fastRefreshModulesEmitter = new ServiceEventEmitter<ModulesUpdates.ModulesUpdateEvent>()\n\n\t#activeScopeId: NodeID | undefined = undefined\n\n\tprivate getActiveScope(): LoadedScopeNode | undefined {\n\t\t// Whilst in the localization view, we should act like we have no scope\n\t\t// in order to avoid unnecessarily making server modules local when\n\t\t// batch updating localizations.\n\t\tif (this.chromeStore.mainView === ActiveMainView.Localizations) {\n\t\t\treturn\n\t\t}\n\n\t\tconst scope = this.treeStore.tree.getNode(this.#activeScopeId) as ScopeNode\n\t\tif (!scope) return undefined\n\t\tassert(scope?.loaded, \"Active scope node should be loaded\")\n\t\treturn scope.loaded\n\t}\n\n\tsetActiveScope(id: NodeID): void {\n\t\tthis.#activeScopeId = id\n\t}\n\n\tgetLatestDependencyGraph(): DependencyGraph {\n\t\treturn this.moduleDepsGraph\n\t}\n\n\tconstructor(\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly treeStore: BaseTreeStore,\n\t\tprivate readonly loadedExternalModulesStore: BaseLoadedExternalModulesStore,\n\t\tprivate readonly chromeStore: Pick<ChromeStore, \"mainView\" | \"codeEditorPreviewVisible\">,\n\t\tprivate readonly modulesAPIServicePromise: Promise<ModulesAPI.Interface | undefined>,\n\t\tprivate readonly makeDocumentReadOnly: () => void,\n\t\tprivate readonly insertTemporaryImportMap: (importMap: ImportMap) => Promise<void>,\n\t\treadonly loadAllLocalModules: () => Promise<void>,\n\t\tprivate abortSignal?: AbortSignal,\n\t) {\n\t\tsuper()\n\n\t\tthis.modulesStorage = new ModulesStorage(\n\t\t\t() =>\n\t\t\t\tthis.modulesAPIServicePromise.catch(err => {\n\t\t\t\t\tlog.error(err, { context: \"Failed to discover ModulesAPI service:\" })\n\t\t\t\t\tthrow err\n\t\t\t\t}),\n\t\t\tthis.compile,\n\t\t\ttask => this.scheduler.process(task),\n\t\t\ttask => this.scheduler.processWhenReady(task),\n\t\t\ttask => this.scheduler.runWhenIdle(task),\n\t\t\ttreeStore,\n\t\t\t() => this.getActiveScope(),\n\t\t\t() => this.makeDocumentReadOnly(),\n\t\t\tthis.abortSignal,\n\t\t)\n\n\t\tthis.fastRefreshModulesEmitter.onNewStream = (options?: ServiceStreamOptions) => {\n\t\t\tlog.debug(\"onNewStream - fast refresh\", options)\n\t\t\treturn { latest: this.getAllModulesAsUpdateEvent(true) }\n\t\t}\n\n\t\tthis.moduleUpdatesEmitter.onNewStream = (options?: ServiceStreamOptions) => {\n\t\t\tlog.debug(\"onNewStream - module updates\", options)\n\t\t\treturn { latest: this.getAllModulesAsUpdateEvent(false) }\n\t\t}\n\n\t\taddBeforeUnloadHandler(\n\t\t\t{\n\t\t\t\tcheck: () => {\n\t\t\t\t\tif (environment.isTest) return false\n\t\t\t\t\t// If user is a viewer, there cannot be local changes that require\n\t\t\t\t\t// persistence, so return early and don't block closing the tab.\n\t\t\t\t\tif (this.treeStore.tree.isViewOnly) return false\n\t\t\t\t\tif (!experiments.isOn(\"importMapPruning\")) return false\n\t\t\t\t\treturn this.#isProcessingImportMapUpdateQueue || this.#pendingImportMapUpdateOperations.length > 0\n\t\t\t\t},\n\t\t\t\teffect: () => {\n\t\t\t\t\tlog.debug(\"Showing Unsaved Changes dialog (import map queue processing)\")\n\t\t\t\t},\n\t\t\t},\n\t\t\tthis.abortSignal,\n\t\t)\n\n\t\tthis.modulesStorage.subscribe(snapshot => {\n\t\t\t// Handle changes in the importMap.\n\t\t\tconst newImportMapContent = snapshot.dependenciesModule?.importMapContent\n\t\t\tconst currentImportMapContent = this.dependenciesModule?.importMapContent\n\n\t\t\tconst didExistingResolutionChange = didExistingImportMapResolutionChange(\n\t\t\t\tcurrentImportMapContent,\n\t\t\t\tnewImportMapContent,\n\t\t\t)\n\n\t\t\tlet shouldReevaluateAllModulesForImportMap = true\n\t\t\tif (experiments.isOn(\"importMapPruning\")) {\n\t\t\t\tshouldReevaluateAllModulesForImportMap = didExistingResolutionChange\n\t\t\t}\n\n\t\t\tlet shouldShowDependenciesChangedToast = false\n\t\t\tif (newImportMapContent && newImportMapContent !== currentImportMapContent) {\n\t\t\t\tconst newImportMap = parseImportMapContent(newImportMapContent)\n\n\t\t\t\tfor (const packageName in newImportMap.imports ?? {}) {\n\t\t\t\t\t// Mark the install status of packages that are already in importMap as \"success\".\n\t\t\t\t\tthis.#npmDependenciesStatusCache.set(packageName, \"success\")\n\t\t\t\t}\n\n\t\t\t\t// When another collaborator pastes an external component it\n\t\t\t\t// will send a tree update over the multiplayer. If the\n\t\t\t\t// component is using Instant NPM this might also cause the\n\t\t\t\t// import map to update. If the tree update (component pasted on\n\t\t\t\t// the canvas) arrives before the import map update, the module\n\t\t\t\t// will fail to evaluate, and the browser will cache the failed\n\t\t\t\t// result of the evaluation until a page reload. That's why we\n\t\t\t\t// need to prompt the user to reload the page.\n\t\t\t\t//\n\t\t\t\t// If either the import map update is coming from the\n\t\t\t\t// multiplayer, the version of the dependency changed or scopes\n\t\t\t\t// changed, we need to reload the page to ensure the correct\n\t\t\t\t// resolution is used for all components on the canvas. The only\n\t\t\t\t// situation when an update of the import map doesn't trigger\n\t\t\t\t// the toast is when we locally add a dependency, e.g. by adding\n\t\t\t\t// an import statement into a code file.\n\t\t\t\tshouldShowDependenciesChangedToast = snapshot.metadata.multiplayerChange || didExistingResolutionChange\n\t\t\t}\n\t\t\tif (newImportMapContent !== currentImportMapContent) {\n\t\t\t\tif (didExistingResolutionChange) {\n\t\t\t\t\tlog.info(\"Import map resolutions changed, re-evaluating all modules\")\n\t\t\t\t} else if (shouldReevaluateAllModulesForImportMap) {\n\t\t\t\t\tlog.info(\"Import map updated, re-evaluating all modules\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.info(\"Import map updated without existing resolution changes, skipping blanket re-eval\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (shouldShowDependenciesChangedToast) {\n\t\t\t\tif (snapshot.metadata.multiplayerChange) {\n\t\t\t\t\t// TODO: we are experimenting with not showing the toast but\n\t\t\t\t\t//       rather displaying a better error in the \"gray box\".\n\t\t\t\t\t//       If we are happy with that experience, we should\n\t\t\t\t\t//       delete this commented out code completely.\n\t\t\t\t\t//       Multiplayer updates of the import map don't\n\t\t\t\t\t//       _always_ cause issues, so we are showing a \"softer\"\n\t\t\t\t\t//       version of the toast in this case.\n\t\t\t\t\t//\n\t\t\t\t\t// toast({\n\t\t\t\t\t//     type: \"add\",\n\t\t\t\t\t//     variant: \"info\",\n\t\t\t\t\t//     text: \"A collaborator has updated npm dependencies. Please reload the page.\",\n\t\t\t\t\t//     key: \"import-map-changed\",\n\t\t\t\t\t//     duration: Infinity,\n\t\t\t\t\t//     icon: \"notifications\",\n\t\t\t\t\t// })\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: this needs to be investigated. currently this toast\n\t\t\t\t\t// triggers way to often. This is partly due to fact that\n\t\t\t\t\t// importMaps aren't pruned and related to that that any\n\t\t\t\t\t// external module from a project with an import map will\n\t\t\t\t\t// add that import map even if its not necessary for said\n\t\t\t\t\t// external module.\n\t\t\t\t\t//\n\t\t\t\t\t// toast({\n\t\t\t\t\t//     type: \"add\",\n\t\t\t\t\t//     variant: \"warning\",\n\t\t\t\t\t//     text: \"npm dependencies changed. Please reload the page.\",\n\t\t\t\t\t//     key: \"import-map-changed\",\n\t\t\t\t\t//     duration: Infinity,\n\t\t\t\t\t//     icon: \"warning\",\n\t\t\t\t\t//     showCloseButton: \"never\",\n\t\t\t\t\t//     action: {\n\t\t\t\t\t//         title: \"Reload\",\n\t\t\t\t\t//         onClick: () => window.top!.location.reload(),\n\t\t\t\t\t//     },\n\t\t\t\t\t// })\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.dependenciesModule = snapshot.dependenciesModule\n\t\t\tthis.localModules = snapshot.modules\n\t\t\tconst prevDepsGraph = this.moduleDepsGraph\n\t\t\tthis.moduleDepsGraph = snapshot.depsGraph\n\n\t\t\tconst patches = snapshot.metadata.patches as unknown as ModulesUpdates.Patch[]\n\t\t\tconst dependentModules = new Set<TypeSlashName>()\n\t\t\tconst updatedModuleTypeSlashNames: string[] = []\n\t\t\tconst deletedModuleTypeSlashNames: string[] = []\n\t\t\tlet dependencyModulePatch: ModulesUpdates.Patch | undefined = undefined\n\n\t\t\tfor (const patch of patches) {\n\t\t\t\tconst typeSlashName = patch.path[0]\n\t\t\t\tassert(typeof typeSlashName === \"string\")\n\n\t\t\t\tif (typeSlashName === DEPENDENCIES_MODULE_TYPE_SLASH_NAME) {\n\t\t\t\t\tdependencyModulePatch = patch\n\t\t\t\t\t// If any mapping in the import map is updated all modules need to be re-evaluated.\n\t\t\t\t\tif (shouldReevaluateAllModulesForImportMap) {\n\t\t\t\t\t\tfor (const t of snapshot.modules.keys()) {\n\t\t\t\t\t\t\tdependentModules.add(t)\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\tif (patch.op === \"remove\" && patch.path.length === 1) {\n\t\t\t\t\tdeletedModuleTypeSlashNames.push(typeSlashName)\n\t\t\t\t} else {\n\t\t\t\t\tupdatedModuleTypeSlashNames.push(typeSlashName)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst visibleDependentModules = new Set<TypeSlashName>()\n\n\t\t\tif (!dependencyModulePatch) {\n\t\t\t\tconst scope = this.getActiveScope()\n\t\t\t\tconst visibleModules = getCodeComponentModuleTypeSlashNamesInScope(scope)\n\t\t\t\tlog.debug(\"Calculated visible code component module typeSlashNames\", visibleModules)\n\n\t\t\t\tfor (const updatedModuleTypeSlashName of updatedModuleTypeSlashNames) {\n\t\t\t\t\tcollectModuleAndItsDependentsRecursively(\n\t\t\t\t\t\tsnapshot.depsGraph,\n\t\t\t\t\t\tupdatedModuleTypeSlashName,\n\t\t\t\t\t\tdependentModules,\n\t\t\t\t\t\tvisibleModules,\n\t\t\t\t\t\tvisibleDependentModules,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tfor (const deletedModuleTypeSlashName of deletedModuleTypeSlashNames) {\n\t\t\t\t\tcollectModuleAndItsDependentsRecursively(\n\t\t\t\t\t\t// For the deleted modules we use the previous depsGraph to collect the dependent modules,\n\t\t\t\t\t\t// because the new graph doesn't have the deleted node in it.\n\t\t\t\t\t\tprevDepsGraph,\n\t\t\t\t\t\tdeletedModuleTypeSlashName,\n\t\t\t\t\t\tdependentModules,\n\t\t\t\t\t\tvisibleModules,\n\t\t\t\t\t\tvisibleDependentModules,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// Remove updated modules from the list of dependent modules.\n\t\t\t\t// They will be represented in patches. Don't remove updated\n\t\t\t\t// modules from the high priority set. If the set is empty we\n\t\t\t\t// will run an optimization to avoid rerendering the canvas.\n\t\t\t\tupdatedModuleTypeSlashNames.forEach(m => {\n\t\t\t\t\tdependentModules.delete(m)\n\t\t\t\t})\n\n\t\t\t\t// Remove deleted modules from both lists. This ensures that if\n\t\t\t\t// a deleted module had no dependencies, we don't perform\n\t\t\t\t// unnecessary updates.\n\t\t\t\tdeletedModuleTypeSlashNames.forEach(m => {\n\t\t\t\t\tdependentModules.delete(m)\n\t\t\t\t\tvisibleDependentModules.delete(m)\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tlog.debug(\n\t\t\t\t\"prioritized evaluation sending to sandbox\",\n\t\t\t\t{ dependentModules, visibleDependentModules },\n\t\t\t\t\"highprio size\",\n\t\t\t\tvisibleDependentModules.size,\n\t\t\t\t\"dep size\",\n\t\t\t\tdependentModules.size,\n\t\t\t)\n\n\t\t\tconst updateEvent = {\n\t\t\t\tpatches,\n\t\t\t\tdependentModules: Array.from(dependentModules),\n\t\t\t\tprioritizedModules: Array.from(visibleDependentModules),\n\t\t\t\trevision: ++this.revision,\n\t\t\t\tinitialized: snapshot.initialized,\n\t\t\t}\n\n\t\t\tthis.moduleUpdatesEmitter.emit(updateEvent)\n\n\t\t\tif (this.fastRefreshEnabled && dependencyModulePatch) {\n\t\t\t\t// Also emit dependency patches to fast refresh channel\n\t\t\t\tthis.fastRefreshModulesEmitter.emit({\n\t\t\t\t\tpatches: [dependencyModulePatch],\n\t\t\t\t\tdependentModules: [],\n\t\t\t\t\tprioritizedModules: [],\n\t\t\t\t\trevision: updateEvent.revision,\n\t\t\t\t\tinitialized: snapshot.initialized,\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Eagerly kicks off the modules list request so it's already in-flight\n\t * when {@link initialize} runs. Idempotent \u2014 safe to call from outside\n\t * (e.g. when the remote document learns the project id) or from\n\t * {@link initialize} itself.\n\t */\n\tpublic preInit = () => {\n\t\tthis.modulesStorage.preInit()\n\t}\n\n\tpublic initialize(): Promise<void> {\n\t\tif (this.initialized) {\n\t\t\treturn this.modulesStorage.refresh()\n\t\t}\n\t\tthis.preInit()\n\t\tthis.setupPollingExternalModulesUpdates()\n\t\treturn this.modulesStorage.initialize()\n\t}\n\n\tpublic get initialized() {\n\t\treturn this.modulesStorage.initialized\n\t}\n\n\tpublic whenInitialized(): Promise<void> {\n\t\treturn this.modulesStorage.whenInitialized()\n\t}\n\n\tpublic whenIdle(): Promise<void> {\n\t\treturn this.modulesStorage.whenIdle()\n\t}\n\n\tpublic startDivergenceReporter(): void {\n\t\tthis.modulesStorage.startDivergenceReporter()\n\t}\n\n\tpublic sampleDivergencesNow(): void {\n\t\tthis.modulesStorage.sampleDivergencesNow()\n\t}\n\n\tpublic refresh(): Promise<void> {\n\t\treturn this.modulesStorage.refresh()\n\t}\n\n\tpublic deleteModules(localIds: LocalModuleId[]): Promise<void> {\n\t\treturn this.modulesStorage.delete(localIds)\n\t}\n\n\tpublic restoreModule(moduleId: GlobalModuleId, name?: string): Promise<PersistedModule> {\n\t\treturn this.modulesStorage.restore(moduleId, name)\n\t}\n\n\tpublic upsertBatch(sources: Record<LocalModuleId, PersistParams>): Promise<void> {\n\t\treturn this.modulesStorage.upsertBatch(sources)\n\t}\n\n\tpublic forType<T extends ModuleType>(type: T): TypedModulesStorage<T> {\n\t\treturn new TypedModulesStorage(this.modulesStorage, type, this.debugModuleStoreAndComponentLoaderRevisionsMatch)\n\t}\n\n\tpublic getNpmDependencyInstallStatus(descriptor: InstallDescriptor): NpmDependencyInstallStatus {\n\t\treturn this.#npmDependenciesStatusCache.get(getImportMapKey(descriptor)) ?? \"unknown\"\n\t}\n\n\tpublic async addNpmDependencies(\n\t\tdescriptor: InstallDescriptor | InstallDescriptor[],\n\t): Promise<{ dependenciesMap: DependenciesMap }> {\n\t\tconst isFirstInstantNPMImport = typeof this.dependenciesModule === \"undefined\"\n\t\tconst shouldShowInstantNPMToast = isFirstInstantNPMImport && !hasDismissedInstantNPMToast()\n\n\t\tconst response = await resultify(this.modulesStorage.addNpmDependencies(descriptor))\n\t\tconst descriptors = Array.isArray(descriptor) ? descriptor : [descriptor]\n\t\tconst filteredDescriptors = descriptors.filter(({ target }) => !isBlockedDependency(target))\n\n\t\tfor (const d of filteredDescriptors) {\n\t\t\tthis.#npmDependenciesStatusCache.set(getImportMapKey(d), response.ok ? \"success\" : \"failure\")\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tconst reason = response.error instanceof Error ? response.error.message : String(response.error)\n\n\t\t\tfor (const d of filteredDescriptors) {\n\t\t\t\tconst name = getImportMapKey(d)\n\t\t\t\trecord(\"npm_dependency_add_fail\", { name, reason })\n\t\t\t}\n\n\t\t\tif (filteredDescriptors.length > 0) {\n\t\t\t\tlog.reportError(response.error, {\n\t\t\t\t\tcontext: \"Failed to add npm dependencies\",\n\t\t\t\t\tdescriptors: filteredDescriptors.map(({ target }) => target),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tthrow response.error\n\t\t}\n\t\tif (shouldShowInstantNPMToast) {\n\t\t\tshowInstantNPMToast()\n\t\t}\n\n\t\tconst installedDependencyKeys = Object.keys(response.value.dependenciesMap.dependencies)\n\t\tconst blockedDependencies = descriptors\n\t\t\t.map(({ target }) => target)\n\t\t\t.filter(target => {\n\t\t\t\treturn !installedDependencyKeys.includes(target) && isBlockedDependency(target)\n\t\t\t})\n\n\t\tif (blockedDependencies.length > 0) {\n\t\t\tconst packages = arrayToText(blockedDependencies, { max: 5, placeholder: \"package\" })\n\n\t\t\ttoast({\n\t\t\t\ttype: \"add\",\n\t\t\t\tvariant: \"warning\",\n\t\t\t\tprimaryText: packages,\n\t\t\t\tsecondaryText: `${blockedDependencies.length === 1 ? \"is\" : \"are\"} incompatible.`,\n\t\t\t\tduration: 5000,\n\t\t\t})\n\t\t}\n\n\t\treturn response.value\n\t}\n\n\tpublic changeScope(scope: LoadedScopeNode): void {\n\t\tthis.setActiveScope(scope.id)\n\t\tvoid this.modulesStorage.changeScope(scope)\n\t}\n\n\tpublic async reinstallNpmDependencies(): Promise<{ importMap: ImportMap }> {\n\t\tconst importMap = await this.modulesStorage.reinstallNpmDependencies()\n\n\t\treturn { importMap }\n\t}\n\n\tpublic async uninstallBlockedNpmDependencies(): Promise<{ importMap: ImportMap }> {\n\t\tconst importMap = await this.modulesStorage.uninstallBlockedNpmDependencies()\n\n\t\treturn { importMap }\n\t}\n\n\tpublic async unsafeUpgradeDependency(\n\t\tdependency: string,\n\t\texpectedSubDependencies: string[],\n\t\tversion?: string,\n\t): Promise<{ importMap: ImportMap }> {\n\t\tconst importMap = await this.modulesStorage.unsafeUpgradeDependency(dependency, expectedSubDependencies, version)\n\n\t\treturn { importMap }\n\t}\n\n\tpublic async clearNpmDependencies(): Promise<void> {\n\t\treturn this.modulesStorage.clearNpmDependencies()\n\t}\n\n\tpublic async removeBlockedNpmDependencies(): Promise<{ dependenciesMap: DependenciesMap }> {\n\t\tconst dependenciesMap = await this.modulesStorage.removeBlockedNpmDependencies()\n\n\t\treturn { dependenciesMap }\n\t}\n\n\tpublic async rebuildImportMapFromDependencies(): Promise<{ importMap: ImportMap }> {\n\t\tconst importMap = await this.modulesStorage.rebuildImportMapFromDependencies()\n\n\t\treturn { importMap }\n\t}\n\n\t/**\n\t * Prunes the project\u2019s import map to the dependencies reachable from its entry points.\n\t * JSPM Generator walks the import graph starting from entry points,\n\t * to determine which dependencies are being used across the project.\n\t *\n\t * TODO: JSPM re-resolves missing deps to latest, not the pinned version. To preserve\n\t * session-pinned versions across destructive prunes, we'd need an in-memory record of\n\t * pruned versions plus a JSPM \"resolve missing to this version\" mode.\n\t */\n\tpublic async pruneProjectImportMapFromEntryPoints(dryRun: boolean = false): Promise<{ importMap: ImportMap }> {\n\t\tconst entryPoints = this.getEntryPointModuleNames()\n\t\tconst importMap = await this.modulesStorage.pruneProjectImportMapFromEntryPoints(entryPoints, { dryRun })\n\n\t\treturn { importMap }\n\t}\n\n\t/**\n\t * Gets module URLs of all entry points for this project.\n\t * Used to perform a trace through all modules to see which dependencies are being used.\n\t */\n\tprivate getEntryPointModuleNames(): string[] {\n\t\tconst entryPoints: string[] = []\n\n\t\tfor (const moduleEntry of this.localModules.values()) {\n\t\t\tif (moduleEntry.kind === \"fast-refresh\") continue\n\n\t\t\tif (\n\t\t\t\tmoduleEntry.type !== ModuleType.Code &&\n\t\t\t\tmoduleEntry.type !== ModuleType.Canvas &&\n\t\t\t\tmoduleEntry.type !== ModuleType.Screen\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst moduleFilename = moduleEntry.files?.module\n\t\t\tif (!moduleFilename) continue\n\n\t\t\tconst importSpecifier = localModuleImportMapSpecifier(moduleEntry.localId, moduleFilename)\n\t\t\tentryPoints.push(importSpecifier)\n\t\t}\n\n\t\t// Also include external modules to avoid installation on re-insert.\n\t\tfor (const externalModuleNode of ExternalModulesListNode.getModuleNodes(this.treeStore.tree)) {\n\t\t\tif (externalModuleNode.type !== ModuleType.Code && externalModuleNode.type !== ModuleType.Canvas) continue\n\n\t\t\tconst identifier = parseModuleIdentifier(externalModuleNode.codeComponentIdentifier)\n\t\t\tif (!isExternalModuleIdentifier(identifier)) continue\n\n\t\t\tentryPoints.push(identifier.importSpecifier)\n\t\t}\n\n\t\treturn [...new Set(entryPoints)]\n\t}\n\n\tpublic async updateSources(updates: ModuleUpdateSource[]) {\n\t\treturn this.modulesStorage.updateSources(updates)\n\t}\n\n\tpublic async updateKit(...args: Parameters<ModulesStorage[\"upsertKit\"]>) {\n\t\tawait this.modulesStorage.whenInitialized()\n\n\t\treturn this.modulesStorage.upsertKit(...args)\n\t}\n\n\tpublic async listKits() {\n\t\tconst service = await this.modulesAPIServicePromise\n\t\tassert(service, \"Modules API service not initialized correctly\")\n\t\tconst response = await service.kits()\n\t\treturn response\n\t}\n\n\t/**\n\t * Requests screenshots for a single kit page, asynchronously.\n\t * Pass the rendered HTML for a kit page containing sections to screenshot.\n\t * Only screenshots for kit sections present in the given page will be replaced,\n\t * and any screenshots for sections in other pages will remain unchanged, allowing partial updates.\n\t */\n\tpublic async enqueueKitScreenshots(...args: Parameters<ModulesStorage[\"enqueueKitScreenshots\"]>): Promise<void> {\n\t\treturn this.modulesStorage.enqueueKitScreenshots(...args)\n\t}\n\n\tpublic async updateDependenciesSource(\n\t\tfileId: typeof IMPORT_MAP_FILE_ID | typeof DEPENDENCIES_FILE_ID,\n\t\tsource: string,\n\t) {\n\t\tawait this.modulesStorage.updateDependenciesSource(fileId, source)\n\t}\n\n\tpublic getDependentsOfModule(typeSlashName: TypeSlashName): Set<TypeSlashName> | undefined {\n\t\treturn this.modulesStorage.getDependentsOfModule(typeSlashName)\n\t}\n\n\tpublic subscribeToModulesStorage(listener: ModulesStorageListener): () => void {\n\t\treturn this.modulesStorage.subscribe(listener)\n\t}\n\n\t/**\n\t * Gets the dependencies (assets and imports) for a specific module save.\n\t * @param request Tip: you can use an `ExternalModulesIdentifier` object directly here.\n\t */\n\tpublic async getModuleDependencies(request: ModulesAPI.DependenciesRequest) {\n\t\tconst service = await this.modulesAPIServicePromise\n\t\tassert(service, \"Modules API service not initialized correctly\")\n\t\tconst response = await service.getModuleDependencies(request)\n\t\treturn response\n\t}\n\n\tpublic getModuleEntryByLocalId(id: LocalModuleId): Immutable<ModuleEntry> | undefined {\n\t\tfor (const entry of this.localModules.values()) {\n\t\t\tif (entry.localId === id) return entry\n\t\t}\n\t}\n\n\tpublic getModuleEntryByUniqueName(name: string): Immutable<ModuleEntry> | undefined {\n\t\tfor (const entry of this.localModules.values()) {\n\t\t\tif (entry.name === name) return entry\n\t\t}\n\t}\n\n\tpublic getPersistedDependenciesModule(): DependenciesModule | undefined {\n\t\treturn this.modulesStorage.getPersistedDependenciesModule()\n\t}\n\n\t/**\n\t * Iterates over all the module entries and finds one with `id` equals to the provided one.\n\t */\n\tpublic getPersistedModuleByGlobalId(moduleId: GlobalModuleId): PersistedModule | undefined {\n\t\treturn this.modulesStorage.getPersistedModuleByGlobalId(moduleId)\n\t}\n\n\t/**\n\t * Gets an object with information about the module as it was persisted on the server.\n\t * Prefer using `getModuleEntryByLocalId` since it will have more real-time data.\n\t */\n\tpublic getPersistedModuleByLocalId(id: LocalModuleId): PersistedModule | undefined {\n\t\treturn this.modulesStorage.getPersistedModuleByLocalId(id)\n\t}\n\n\t/**\n\t * Gets an object with information about the module as it was persisted on the server.\n\t * Prefer using `getModuleEntryByLocalId` since it will have more real-time data.\n\t */\n\tpublic getPersistedModuleByLocalIdentifier(identifier: string | undefined): PersistedModule | undefined {\n\t\tconst parsedIdentifier = parseModuleIdentifier(identifier)\n\t\tif (!isLocalModuleIdentifier(parsedIdentifier)) return\n\t\treturn this.getPersistedModuleByLocalId(parsedIdentifier.localId)\n\t}\n\n\tpublic tryConvertExternalCodeComponentIdentifierToLocal(\n\t\tcodeComponentIdentifier: ExternalModuleExportIdentifierString,\n\t): LocalModuleExportIdentifierString | undefined {\n\t\tconst parsedIdentifier = parseModuleIdentifier(codeComponentIdentifier)\n\n\t\tif (parsedIdentifier?.kind !== \"externalModuleExport\") return\n\n\t\tconst persistedModule = this.getPersistedModuleByGlobalId(parsedIdentifier.moduleId)\n\n\t\tif (!persistedModule) return\n\n\t\treturn localModuleIdentifier(persistedModule.localId, parsedIdentifier.exportSpecifier).value\n\t}\n\n\tpublic async listNamespaces() {\n\t\tconst service = await this.modulesAPIServicePromise\n\t\tassert(service, \"Modules API service not initialized correctly\")\n\t\tconst response = await service.listNamespaces()\n\t\treturn response\n\t}\n\n\tpublic async createNamespace(ownerId: string, ownerType: string) {\n\t\tconst service = await this.modulesAPIServicePromise\n\t\tassert(service, \"Modules API service not initialized correctly\")\n\n\t\tconst response = await service.createNamespace({ ownerId, ownerType })\n\t\treturn response\n\t}\n\n\tpublic async lookUpModule(query: ModuleLookupQuery, options?: ModuleLookupOptions): Promise<ModuleLookupInfo> {\n\t\tconst { modules, dependencies } = await this.lookUpModules([query], options)\n\n\t\tconst module = modules[0]\n\t\tassert(module, \"Module does not exist, looking up:\", query)\n\n\t\tconst result: ModuleLookupInfo = { module }\n\n\t\tif (dependencies) {\n\t\t\tresult.dependencies = dependencies[module.ownerType]?.[module.ownerId]\n\t\t}\n\n\t\treturn result\n\t}\n\n\tpublic async getSourceContentForModuleSave(query: ModuleSaveReference) {\n\t\tconst { module } = await this.lookUpModule(query)\n\t\tif (hasSourceContent(module)) return module.sourceContent\n\t\tconst sourceURL = module.baseURL + module.files.source\n\t\tconst response = await resultify(fetch(sourceURL))\n\t\tif (!response.ok) {\n\t\t\tlog.reportError(response.error, {\n\t\t\t\tcontext: \"Failed to fetch source content for module save\",\n\t\t\t\tmoduleId: query.moduleId,\n\t\t\t\tsaveId: query.saveId,\n\t\t\t\tsourceURL,\n\t\t\t})\n\t\t\tthrow response.error\n\t\t}\n\t\tif (!response.value.ok) {\n\t\t\tconst error = new Error(\n\t\t\t\t`Failed to fetch source content for module save ${query.moduleId}@${query.saveId}: ` +\n\t\t\t\t\t`${response.value.status} ${response.value.statusText}`,\n\t\t\t)\n\t\t\tlog.reportError(error, {\n\t\t\t\tcontext: \"Failed to fetch source content for module save\",\n\t\t\t\tmoduleId: query.moduleId,\n\t\t\t\tsaveId: query.saveId,\n\t\t\t\tsourceURL,\n\t\t\t\thttpStatus: response.value.status,\n\t\t\t})\n\t\t\tthrow error\n\t\t}\n\n\t\tconst source = await resultify(response.value.text())\n\t\tif (!source.ok) {\n\t\t\tlog.reportError(source.error, {\n\t\t\t\tcontext: \"Failed to read source content for module save\",\n\t\t\t\tmoduleId: query.moduleId,\n\t\t\t\tsaveId: query.saveId,\n\t\t\t\tsourceURL,\n\t\t\t})\n\t\t\tthrow source.error\n\t\t}\n\n\t\treturn source.value\n\t}\n\n\tpublic async lookUpModules(queries: ModuleLookupQuery[], options?: ModuleLookupOptions): Promise<ModulesLookupInfo> {\n\t\tconst service = await this.modulesAPIServicePromise\n\t\tif (!service) {\n\t\t\tlog.error(\"Modules API service not initialized correctly\")\n\t\t\treturn { modules: [], dependencies: {} }\n\t\t}\n\t\tconst { data, dependencies } = await service.lookUpModules({ queries, ...options })\n\t\t// Keep a cache of the latest known module information.\n\t\tconst dynamicInfo = new Map(this.externalModulesDynamicInfo)\n\t\tfor (const module of data) {\n\t\t\tconst key = asGlobalId(module.id)\n\t\t\tconst { localId, title, description, lastPublish, status } = module\n\t\t\t// Retain the status key of the previous value if the new one doesn't have status.\n\t\t\tdynamicInfo.set(key, {\n\t\t\t\tlocalId,\n\t\t\t\ttitle,\n\t\t\t\tdescription,\n\t\t\t\tlastPublish,\n\t\t\t\tstatus: status ?? dynamicInfo.get(key)?.status,\n\t\t\t})\n\t\t}\n\t\tthis.externalModulesDynamicInfo = dynamicInfo\n\t\t// Return the result with the correct types (services mess them up a bit).\n\t\tconst result: ModulesLookupInfo = {\n\t\t\tmodules: data as ModulesAPI.ModuleWithSave[],\n\t\t}\n\t\tif (dependencies) {\n\t\t\tresult.dependencies = dependencies as unknown as ModulesLookupInfo[\"dependencies\"]\n\t\t}\n\t\treturn result\n\t}\n\n\tpublic trackExternalComponentInsert(\n\t\texternalModuleExportIdentifierString: (ExternalModuleExportIdentifierString | string)[],\n\t\tinsertType: ExternalComponentInsertType,\n\t) {\n\t\tconst insertId = uuid()\n\t\tfor (const codeComponentId of externalModuleExportIdentifierString) {\n\t\t\t// triggered every time an external module is inserted onto the canvas, as described by the insertType\n\t\t\ttriggerExternalComponentInsertEvent({\n\t\t\t\tinsertId,\n\t\t\t\tinsertType,\n\t\t\t\tcodeComponentId,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Caches external modules' installation work, to avoid performing it multiple times.\n\t */\n\t#externalModuleInstallPromises = new Map<ModuleSpecifier, Promise<unknown>>()\n\n\t/**\n\t * Makes sure the modules' import maps are merged into the project import map.\n\t */\n\tpublic async installExternalModulesDependencies(moduleSpecifiers: ModuleSpecifier[]): Promise<void> {\n\t\tconst moduleSpecifiersToInstall: string[] = []\n\t\tconst installPromises: Promise<unknown>[] = []\n\t\tfor (const moduleSpecifier of moduleSpecifiers) {\n\t\t\tconst cachedPromise = this.#externalModuleInstallPromises.get(moduleSpecifier)\n\t\t\tif (cachedPromise) {\n\t\t\t\tinstallPromises.push(cachedPromise)\n\t\t\t} else {\n\t\t\t\tmoduleSpecifiersToInstall.push(moduleSpecifier)\n\t\t\t}\n\t\t}\n\n\t\tif (moduleSpecifiersToInstall.length > 0) {\n\t\t\tconst installPromise = this.installDependenciesForModuleURLs(moduleSpecifiersToInstall)\n\n\t\t\tfor (const moduleSpecifier of moduleSpecifiersToInstall) {\n\t\t\t\tthis.#externalModuleInstallPromises.set(moduleSpecifier, installPromise)\n\t\t\t}\n\n\t\t\tinstallPromises.push(installPromise)\n\t\t}\n\n\t\treturn Promise.allSettled(installPromises).then(results => {\n\t\t\tfor (const result of results) {\n\t\t\t\tif (result.status === \"fulfilled\") continue\n\n\t\t\t\tlog.error(\"Failed to install external module\", result.reason)\n\t\t\t}\n\t\t})\n\t}\n\n\tpublic isProcessingModules() {\n\t\treturn this.modulesStorage.isProcessing()\n\t}\n\n\tpublic hasLocalCodeFileChanges(): boolean {\n\t\treturn this.modulesStorage.hasLocalCodeFileChanges()\n\t}\n\n\tpublic isReadOnly(): boolean {\n\t\treturn this.modulesStorage.isReadOnly()\n\t}\n\n\tpublic resetModuleStateAndPermissions(state: \"readonly\" | \"readwrite\" | \"readwrite-detached\") {\n\t\tthis.modulesStorage.resetModuleStateAndPermissions(state)\n\t}\n\n\tpublic getTransientSave(localId: LocalModuleId) {\n\t\treturn this.modulesStorage.getTransientSave(localId)\n\t}\n\n\tpublic createFastRefreshModuleFromModule(module: Immutable<ModuleEntry> | PersistedModule) {\n\t\tif (!fastRefreshableModuleTypes.has(module.type as ModuleType)) return\n\t\tif (module.kind === \"server\") {\n\t\t\tconst persistedModule = this.getPersistedModuleByLocalId(module.localId)\n\t\t\tassert(persistedModule?.kind === \"server\", \"Only server modules should have no sourceContent\")\n\t\t\t// When we create a local module from a server module, we also compile it for fast refresh\n\t\t\tthis.modulesStorage.createLocalModuleFromModule(persistedModule).catch(unhandledError)\n\t\t\treturn\n\t\t}\n\t\tthis.compileFastRefreshModule({\n\t\t\tname: getTypeSlashName(module),\n\t\t\tlocalId: module.localId,\n\t\t\tsource: module.sourceContent,\n\t\t}).catch(unhandledError)\n\t}\n\n\tpublic getModuleWithTypeSlashName(typeSlashName: string) {\n\t\treturn this.modulesStorage.getModuleWithTypeSlashName(typeSlashName)\n\t}\n\n\tpublic waitForModulesToSave() {\n\t\treturn this.modulesStorage.waitForModulesToSave()\n\t}\n\n\tprivate async insertTemporaryImportMapForExternalModules(modules: ModuleLookupInfo[]): Promise<void> {\n\t\t// Move top-level imports into module scopes so multiple import maps do not clash.\n\t\t// TODO: Investigate with JSPM team to do this in a safer way.\n\t\tconst temporaryImportMap: ImportMap = { imports: {} }\n\n\t\tfor (const { dependencies, module } of modules) {\n\t\t\tconst importMap = dependencies?.importMap\n\t\t\tif (!importMap || isImportMapEmpty(importMap)) continue\n\n\t\t\tassert(module.files.module, \"Module must have a module file\")\n\t\t\tif (importMap.scopes) {\n\t\t\t\ttemporaryImportMap.scopes ??= {}\n\t\t\t\tfor (const [scopeURL, scopeImports] of Object.entries(importMap.scopes)) {\n\t\t\t\t\ttemporaryImportMap.scopes[scopeURL] = Object.assign({}, scopeImports, temporaryImportMap.scopes[scopeURL])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Object.keys(importMap.imports).length > 0) {\n\t\t\t\ttemporaryImportMap.scopes ??= {}\n\t\t\t\ttemporaryImportMap.scopes[module.baseURL] = Object.assign(\n\t\t\t\t\t{},\n\t\t\t\t\timportMap.imports,\n\t\t\t\t\ttemporaryImportMap.scopes[module.baseURL],\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tif (isImportMapEmpty(temporaryImportMap)) return\n\n\t\tawait this.insertTemporaryImportMap(temporaryImportMap)\n\t}\n\n\tprivate async installDependenciesForExternalModules(modules: ModuleLookupInfo[]): Promise<void> {\n\t\tlet externalImportMap: ImportMap | undefined = undefined\n\t\tlet externalDependencies: DependenciesMap | undefined = undefined\n\n\t\tconst entryPoints: string[] = []\n\t\tconst installedModuleOwnerIds: Set<string> = new Set()\n\n\t\tfor (const { dependencies, module } of modules) {\n\t\t\tif (!dependencies?.importMap) continue\n\n\t\t\tif (experiments.isOn(\"importMapPruning\")) {\n\t\t\t\t// If modules start having multiple entry points, we must handle it here.\n\t\t\t\tassert(module.files.module, \"Module must have a module file\")\n\t\t\t\tconst fullModuleURL = `${module.baseURL}${module.files.module}`\n\n\t\t\t\tentryPoints.push(fullModuleURL)\n\n\t\t\t\t// There is only one set of dependencies per module owner (project/team).\n\t\t\t\tif (installedModuleOwnerIds.has(module.ownerId)) continue\n\t\t\t\tinstalledModuleOwnerIds.add(module.ownerId)\n\t\t\t}\n\n\t\t\t// Skip traditional dependencies merging if pruning experiment is enabled.\n\t\t\tif (!experiments.isOn(\"importMapPruning\")) {\n\t\t\t\tconst moduleDependencies =\n\t\t\t\t\tdependencies.dependencies ?? generateDependenciesFromImportMap(dependencies?.importMap)\n\n\t\t\t\t// Merge all external dependencies.\n\t\t\t\texternalDependencies = extendDependencies(externalDependencies ?? { dependencies: {} }, moduleDependencies)\n\t\t\t}\n\t\t\texternalImportMap = extendImportMap(externalImportMap ?? { imports: {} }, dependencies.importMap)\n\t\t}\n\n\t\tif (!externalImportMap || isImportMapEmpty(externalImportMap)) return\n\n\t\tif (experiments.isOn(\"importMapPruning\") && entryPoints.length > 0) {\n\t\t\tthis.queueImportMapUpdate({ importMap: externalImportMap, entryPoints }).catch(unhandledError)\n\t\t\treturn\n\t\t}\n\n\t\t// \u201Cdumb\u201D merge of external import map and dependencies if pruning is disabled.\n\t\tif (!experiments.isOn(\"importMapPruning\") && externalDependencies) {\n\t\t\tawait this.modulesStorage.extendCurrentImportMap(externalImportMap, externalDependencies)\n\t\t}\n\t}\n\n\tprivate installDependenciesForModuleURLs(moduleSpecifiers: ModuleSpecifier[]) {\n\t\tlog.info(\"\uD83E\uDD86 Installing external modules:\\n\\t\", moduleSpecifiers.join(\"\\n\\t\"))\n\n\t\treturn this.lookUpModules(\n\t\t\tmoduleSpecifiers.map(url => ({ url })),\n\t\t\t{ includeDependencies: true },\n\t\t).then(async ({ modules, dependencies: dependenciesByOwnerType = {} }) => {\n\t\t\tconst modulesByLookupInfo: ModuleLookupInfo[] = modules.map(module => ({\n\t\t\t\tmodule,\n\t\t\t\tdependencies: dependenciesByOwnerType[module.ownerType]?.[module.ownerId],\n\t\t\t}))\n\n\t\t\tawait this.insertTemporaryImportMapForExternalModules(modulesByLookupInfo)\n\t\t\tawait this.installDependenciesForExternalModules(modulesByLookupInfo)\n\t\t})\n\t}\n\n\t/**\n\t * When updating an external vector set, we need to add Vector modules that didn't exist in the\n\t * set when the set was originally added to the project. Since we don't know the current save\n\t * id, we query the latest.\n\t */\n\tpublic async addOrUpdateExternalVectors(queries: { moduleId: GlobalModuleId; saveId: string }[]) {\n\t\tawait this.modulesStorage.whenInitialized()\n\n\t\tconst { modules } = await this.lookUpModules(\n\t\t\tqueries.filter(query => {\n\t\t\t\t// If the vector in the project is already at the specified saveId, we can omit it from\n\t\t\t\t// the batch of queries to improve performance.\n\t\t\t\tconst node = this.treeStore.tree.getNodeWithTrait(query.moduleId, isExternalModuleNode)\n\t\t\t\tif (!node) return true\n\t\t\t\treturn parseModuleIdentifier(node.codeComponentIdentifier).saveId !== query.saveId\n\t\t\t}),\n\t\t\t{\n\t\t\t\tincludeDependencies: false,\n\t\t\t\tincludeStatus: true,\n\t\t\t},\n\t\t)\n\n\t\t// Metadata from the lookup, needed to build import map.\n\t\tconst data = new Map<ExternalModuleExportIdentifierString, ComponentInfo>()\n\n\t\tconst vectorExportSpecifier: ExportSpecifier = \"default\"\n\t\tfor (const module of modules) {\n\t\t\tconst identifier = moduleIdentifierForComponent({ module, exportSpecifier: vectorExportSpecifier })\n\n\t\t\t// Skip modules that are already in the tree with the same saveId.\n\t\t\tconst existingNode = this.treeStore.tree.getNodeWithTrait(module.id, isExternalModuleNode)\n\t\t\tif (\n\t\t\t\tisModuleExportIdentifier(existingNode?.codeComponentIdentifier) &&\n\t\t\t\tparseModuleIdentifier(existingNode.codeComponentIdentifier).saveId === module.saveId\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata.set(identifier.value, {\n\t\t\t\tmodule,\n\t\t\t\texportSpecifier: vectorExportSpecifier,\n\t\t\t})\n\t\t}\n\n\t\t// Evaluate all the modules.\n\t\tawait Promise.all(\n\t\t\tArray.from(data.keys(), identifier => {\n\t\t\t\tconst parsed = parseModuleIdentifier(identifier)\n\t\t\t\tassert(parsed, \"Identifier must be a valid module identifier\")\n\t\t\t\treturn this.loadedExternalModulesStore.ensureModuleEvaluatedInSandbox(parsed).catch(error => {\n\t\t\t\t\tlog.error(`Failed to evaluate external module \"${identifier}\"`, error)\n\t\t\t\t})\n\t\t\t}),\n\t\t)\n\n\t\t// Update instances.\n\t\tif (!this.treeStore.getDataTree()) {\n\t\t\tawait this.scheduler.runWithFullyLoadedTreeAsync({\n\t\t\t\tname: \"update_external_module_version\",\n\t\t\t\trunInBackground: true,\n\t\t\t})\n\t\t}\n\n\t\tawait this.updateExternalModuleNodes(Array.from(data.values()), {\n\t\t\t// Use the onTreeUpdate callback to ensure ExternalModuleNode and node\n\t\t\t// updates happen in a single batch.\n\t\t\tonTreeUpdate: () => {\n\t\t\t\tconst map = getExportReplacementMap(data.keys())\n\t\t\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\t\t\tconst codeComponents = tree.query().whereClass(CodeComponentNode).iterate()\n\t\t\t\tupdateExternalModuleInstances(map, codeComponents)\n\t\t\t\tupdateExternalModuleCollectionValues(map, tree)\n\t\t\t\tupdateScopeNodeExternalModules(map, tree)\n\t\t\t},\n\t\t\t// Updating the save information in the nodes will ensure the \"Update\" action disappears.\n\t\t\tupdateSave: true,\n\t\t})\n\t}\n\n\t/**\n\t * Add or update a vector set module, and then go through its annotation and add/update the\n\t * vector modules within.\n\t */\n\tpublic async addOrUpdateVectorSetAndVectors(query: { moduleId: GlobalModuleId; saveId: string }) {\n\t\tawait this.addOrUpdateExternalVectors([query])\n\n\t\tconst latest = this.treeStore.tree.getNodeWithTrait(query.moduleId, isExternalModuleNode)\n\t\tconst set = latest?.annotation(AnnotationKey.FramerVectorSet)\n\t\tif (!isFramerVectorSetInfo(set)) return\n\n\t\tawait this.addOrUpdateExternalVectors(\n\t\t\tset.items.map(info => ({ moduleId: asGlobalId(info.moduleId), saveId: info.saveId ?? \"\" })),\n\t\t)\n\t}\n\n\t/**\n\t * Makes sure there is a corresponding ExternalModuleNode in the\n\t * ExternalModulesListNode in the tree for each module provided. If there\n\t * isn't one yet, it makes a backend lookup call to get the module data\n\t * necessary for creation of such nodes. Safe to call even if the modules\n\t * have already been added.\n\t */\n\tpublic async addExternalModulesToProject<T>(\n\t\tidentifiers: readonly (ExternalModuleExportIdentifier | ExternalModuleExportIdentifierString)[],\n\t\toptions: UpdateExternalModuleNodesOptions<T>,\n\t): Promise<T> {\n\t\tconst parsedIdentifiers = identifiers.map(id => (typeof id === \"string\" ? parseModuleIdentifier(id) : id))\n\t\tconst components = await this.preloadExternalModules(parsedIdentifiers)\n\t\treturn this.updateExternalModuleNodes(components, options)\n\t}\n\n\t/** Cache to avoid evaluating the same external module twice. */\n\t#preloadPromises = new Map<ExternalModuleBareIdentifierString, ResolvablePromise<ComponentInfo>>()\n\n\tpublic usesNoopExternalModuleEvaluation(): boolean {\n\t\treturn this.loadedExternalModulesStore.usesNoopExternalModuleEvaluation?.() === true\n\t}\n\n\t/**\n\t * Makes sure provided external modules are evaluated in the sandbox. This\n\t * involves looking up modules data from ModulesAPI and temporarily\n\t * inserting import maps required for their evaluation. This method is safe\n\t * to call multiple times for the same modules: if a module was previously\n\t * handled, expensive operations will be skipped.\n\t *\n\t * @returns An array of modules that also need to be added to the tree as\n\t *          `ExternalModuleNode`s, and their dependencies merged with the\n\t *          project's ones.\n\t */\n\tpublic async preloadExternalModules(identifiers: ExternalModuleExportIdentifier[]): Promise<ComponentInfo[]> {\n\t\tif (identifiers.length === 0) return []\n\n\t\t// No external modules should be evaluated before the local modules and\n\t\t// import map are loaded.\n\t\tawait this.modulesStorage.whenInitialized()\n\n\t\t// Collect the unique set of modules among the identifiers.\n\t\t// FIXME: If a module has multiple exports, this will ignore all but one.\n\t\tconst uniqueIdentifiers = new Map<ExternalModuleBareIdentifierString, ExternalModuleExportIdentifier>()\n\t\tfor (const identifier of identifiers) {\n\t\t\tuniqueIdentifiers.set(identifier.bareValue, identifier)\n\t\t}\n\n\t\tif (this.loadedExternalModulesStore.usesNoopExternalModuleEvaluation?.() === true) {\n\t\t\t// CLI export replay uses captured tree data without a browser module runtime or backend module rows.\n\t\t\t// Mark the references as evaluated so read-only agent context building can skip sandbox-only work.\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(uniqueIdentifiers.values(), identifier =>\n\t\t\t\t\tthis.loadedExternalModulesStore.ensureModuleEvaluatedInSandbox(identifier),\n\t\t\t\t),\n\t\t\t)\n\t\t\treturn []\n\t\t}\n\n\t\t// Collect modules that need to be looked up.\n\t\tconst modulesToLookUp: ExternalModuleExportIdentifier[] = []\n\t\t// Collect modules that need to be evaluated (but not looked up).\n\t\tconst modulesToEvaluate: ExternalModuleExportIdentifier[] = []\n\t\t// Collect modules that have already been preloaded.\n\t\tinterface PreloadedModule {\n\t\t\tidentifier: ExternalModuleExportIdentifier\n\t\t\tpreloadPromise: PromiseLike<ComponentInfo>\n\t\t}\n\t\tconst modulesAlreadyPreloaded: PreloadedModule[] = []\n\t\tfor (const [key, identifier] of uniqueIdentifiers) {\n\t\t\tconst { moduleId, saveId } = identifier\n\t\t\t// Sanity check that we never get local modules.\n\t\t\tconst isLocalModule = Boolean(this.modulesStorage.getPersistedModuleByGlobalId(moduleId))\n\t\t\tif (isLocalModule) {\n\t\t\t\tlog.reportError(\"Attempted to treat local module as external module\", { identifier })\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// If there's already an `ExternalModuleNode` in the tree with the\n\t\t\t// same saveId, we only need to evaluate. We don't need to return\n\t\t\t// any dependencies because those must be a part of the project\n\t\t\t// dependencies at this point. We don't dedupe this particular code\n\t\t\t// path as it's already deduped by the module evaluation logic.\n\t\t\tconst existingNode = this.treeStore.tree.getNode<ExternalModuleNode>(moduleId)\n\t\t\tif (existingNode) {\n\t\t\t\tif (\n\t\t\t\t\tparseModuleIdentifier(existingNode.codeComponentIdentifier).saveId === saveId &&\n\t\t\t\t\t!this.loadedExternalModulesStore.hasModuleForIdentifier(identifier)\n\t\t\t\t) {\n\t\t\t\t\tmodulesToEvaluate.push(identifier)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Check if the module has already been preloaded.\n\t\t\tconst preloadPromise = this.#preloadPromises.get(key)\n\t\t\tif (preloadPromise) {\n\t\t\t\t// Handle the promise after this loop (or we would risk another\n\t\t\t\t// call to this function creating a duplicate lookup for the\n\t\t\t\t// same module).\n\t\t\t\tmodulesAlreadyPreloaded.push({ identifier, preloadPromise })\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Create a promise that will be resolved once the module is preloaded.\n\t\t\tthis.#preloadPromises.set(key, new ResolvablePromise())\n\t\t\tmodulesToLookUp.push(identifier)\n\t\t}\n\n\t\t// Metadata from the lookup, needed to build import map.\n\t\tconst data = new Map<ExternalModuleExportIdentifierString, ComponentInfo>()\n\n\t\t// Wait for the previous preloads to finish. This will generally be\n\t\t// instant as the promises have most likely already been resolved.\n\t\tfor (const { identifier, preloadPromise } of modulesAlreadyPreloaded) {\n\t\t\ttry {\n\t\t\t\tconst info = await preloadPromise\n\t\t\t\t// It can be in the cache due to preloading, but that doesn't\n\t\t\t\t// necessarily mean that its dependencies have already been\n\t\t\t\t// processed or that it was added to the tree, so we still store\n\t\t\t\t// its metadata for the import map.\n\t\t\t\tdata.set(identifier.value, info)\n\t\t\t} catch {\n\t\t\t\t// We can assume the lookup failed in an earlier preload.\n\t\t\t\t// FIXME: Concurrent preloads could perform this logic more than once.\n\t\t\t\tthis.#preloadPromises.set(identifier.bareValue, new ResolvablePromise())\n\t\t\t\tmodulesToLookUp.push(identifier)\n\t\t\t}\n\t\t}\n\n\t\t// Look up the modules that were not already evaluated.\n\t\tif (modulesToLookUp.length) {\n\t\t\ttry {\n\t\t\t\t// Note: Maps in JavaScript always iterate in insertion order.\n\t\t\t\tconst queries = Array.from(modulesToLookUp.values(), ({ moduleId, saveId }) => ({ moduleId, saveId }))\n\t\t\t\tconst { modules, dependencies } = await this.lookUpModules(queries, {\n\t\t\t\t\tincludeDependencies: true,\n\t\t\t\t\tincludeStatus: true,\n\t\t\t\t})\n\t\t\t\tlet i = 0\n\t\t\t\tfor (const identifier of modulesToLookUp) {\n\t\t\t\t\tconst module = modules[i++]\n\t\t\t\t\tassert(module, \"Module must be defined\")\n\t\t\t\t\tdata.set(identifier.value, {\n\t\t\t\t\t\tmodule,\n\t\t\t\t\t\tdependencies: dependencies?.[module.ownerType]?.[module.ownerId],\n\t\t\t\t\t\texportSpecifier: identifier.exportSpecifier,\n\t\t\t\t\t})\n\t\t\t\t\tmodulesToEvaluate.push(identifier)\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlog.reportError(error)\n\t\t\t\t// We have to reject the preload of all modules so the app does not get stuck.\n\t\t\t\tfor (const identifier of modulesToLookUp) {\n\t\t\t\t\tthis.#preloadPromises.get(identifier.bareValue)?.reject(error)\n\t\t\t\t}\n\t\t\t\tthrow Error(`Failed to preload modules: ${error}`)\n\t\t\t}\n\t\t}\n\n\t\t// Create a temporary import map required for evaluation.\n\t\tconst modulesToInsertTemporaryImportMapFor: ComponentInfo[] = []\n\t\tfor (const identifier of modulesToEvaluate) {\n\t\t\tconst info = data.get(identifier.value)\n\t\t\tif (!info) {\n\t\t\t\t// Some modules only need evaluation, but not a lookup because\n\t\t\t\t// they already exist in the project. This means we can assume\n\t\t\t\t// that if they're already in the project, there's no need to\n\t\t\t\t// add a temporary import map for them either (since their\n\t\t\t\t// dependencies will already be in the project's import map).\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmodulesToInsertTemporaryImportMapFor.push(info)\n\t\t}\n\n\t\t// Insert a temporary import map, so we can evaluate new external modules.\n\t\tawait this.insertTemporaryImportMapForExternalModules(modulesToInsertTemporaryImportMapFor)\n\n\t\t// Evaluate all the modules.\n\t\tawait Promise.all(\n\t\t\tArray.from(modulesToEvaluate.values(), identifier =>\n\t\t\t\tthis.loadedExternalModulesStore.ensureModuleEvaluatedInSandbox(identifier).catch(error => {\n\t\t\t\t\tlog.error(`Failed to evaluate external module \"${identifier.value}\"`, error)\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\n\t\t// Resolve preload promises for the modules that needed to be looked up.\n\t\tfor (const identifier of modulesToLookUp) {\n\t\t\tconst info = data.get(identifier.value)\n\t\t\tassert(info, \"Expected to have module information for:\", identifier.value)\n\t\t\tconst preloadPromise = this.#preloadPromises.get(identifier.bareValue)\n\t\t\tassert(preloadPromise, \"Expected to find a preload promise for:\", identifier.bareValue)\n\t\t\tpreloadPromise.resolve(info)\n\t\t}\n\n\t\treturn [...data.values()]\n\t}\n\n\t#isProcessingImportMapUpdateQueue = false\n\t#pendingImportMapUpdateOperations: {\n\t\texternalDeps: { importMap: ImportMap; entryPoints: string[] }\n\t\tresolve: (value: ImportMap) => void\n\t\treject: (reason: unknown) => void\n\t}[] = []\n\n\t/**\n\t * Queues a project import map prune after pre-scoping external deps before merging.\n\t * Serializes concurrent prunes so rapid external module inserts don't race.\n\t */\n\tprivate queueImportMapUpdate(externalDeps: { importMap: ImportMap; entryPoints: string[] }): Promise<ImportMap> {\n\t\treturn new Promise<ImportMap>((resolve, reject) => {\n\t\t\tthis.#pendingImportMapUpdateOperations.push({ externalDeps, resolve, reject })\n\t\t\tvoid this.processImportMapUpdateQueue()\n\t\t})\n\t}\n\n\t/**\n\t * Queue processing.\n\t * This assumes a single client and that the tab stays open until completion.\n\t * We should switch to persisted logic that any client can pickup if needed.\n\t */\n\tprivate async processImportMapUpdateQueue(): Promise<void> {\n\t\tif (this.#isProcessingImportMapUpdateQueue) return\n\t\tthis.#isProcessingImportMapUpdateQueue = true\n\n\t\tconst toastKey = \"import-map-prune\"\n\t\tlet hasError = false\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tkey: toastKey,\n\t\t\ttext: \"Optimizing dependencies\u2026\",\n\t\t\tvariant: \"progress\",\n\t\t\tduration: Infinity,\n\t\t\tshowCloseButton: \"never\",\n\t\t})\n\n\t\ttry {\n\t\t\twhile (this.#pendingImportMapUpdateOperations.length > 0) {\n\t\t\t\tconst batch = this.#pendingImportMapUpdateOperations.splice(0, this.#pendingImportMapUpdateOperations.length)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst externalEntryPoints: string[] = []\n\t\t\t\t\tlet scopedExternalImportMap: ImportMap = { imports: {} }\n\t\t\t\t\tfor (const { externalDeps } of batch) {\n\t\t\t\t\t\t// Convert each external import map to scoped dependencies before merging.\n\t\t\t\t\t\t// eg. \"imports\":\"three\" -> \"scopes\":\"framer.com/m/moduleId\":\"three\"\n\t\t\t\t\t\tconst scopedImportMap = await this.modulesStorage.scopeExternalImportMap(\n\t\t\t\t\t\t\texternalDeps.entryPoints,\n\t\t\t\t\t\t\texternalDeps.importMap,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tscopedExternalImportMap = extendImportMap(scopedExternalImportMap, scopedImportMap)\n\t\t\t\t\t\texternalEntryPoints.push(...externalDeps.entryPoints)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst pruneEntryPoints = [...new Set([...this.getEntryPointModuleNames(), ...externalEntryPoints])]\n\t\t\t\t\tconst result = await this.modulesStorage.pruneProjectImportMapFromEntryPoints(pruneEntryPoints, {\n\t\t\t\t\t\tadditionalImportMap: scopedExternalImportMap,\n\t\t\t\t\t})\n\t\t\t\t\tfor (const { resolve } of batch) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\thasError = true\n\t\t\t\t\tfor (const { reject } of batch) {\n\t\t\t\t\t\treject(error)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tif (hasError) {\n\t\t\t\ttoast({\n\t\t\t\t\ttype: \"add\",\n\t\t\t\t\tkey: toastKey,\n\t\t\t\t\ttext: \"Failed to optimize dependencies.\",\n\t\t\t\t\tvariant: \"error\",\n\t\t\t\t\tduration: 3000,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\ttoast({ type: \"remove\", key: toastKey })\n\t\t\t}\n\t\t\tthis.#isProcessingImportMapUpdateQueue = false\n\t\t}\n\t}\n\n\t/**\n\t * Updates the `ExternalModuleNode`s of the project using the provided data.\n\t * This method should be idempotent. Do not call if the user is a viewer.\n\t */\n\tpublic async updateExternalModuleNodes<T>(\n\t\tcomponents: ComponentInfo[],\n\t\t{ onTreeUpdate, updateSave = false, scheduleTreeUpdate }: UpdateExternalModuleNodesOptions<T>,\n\t): Promise<T> {\n\t\tawait this.insertTemporaryImportMapForExternalModules(components)\n\n\t\t// Ensure that we're gonna be able to find these components in the\n\t\t// component loader later inside the processWhenReadyAsync block, to\n\t\t// store their annotations.\n\t\tawait Promise.all(\n\t\t\tcomponents.map(component =>\n\t\t\t\tthis.loadedExternalModulesStore.ensureModuleEvaluatedInSandbox(moduleIdentifierForComponent(component)),\n\t\t\t),\n\t\t)\n\n\t\tconst runTreeUpdate = scheduleTreeUpdate ?? (task => this.scheduler.processWhenReadyAsync(task))\n\n\t\tconst result = await runTreeUpdate(() => {\n\t\t\t// The user might become unable to edit during this process. We\n\t\t\t// throw early because the tree would error anyway.\n\t\t\tif (this.treeStore.tree.isViewOnly) {\n\t\t\t\tthrow Error(\"unable to edit\")\n\t\t\t}\n\n\t\t\tfor (const component of components) {\n\t\t\t\tconst { id } = component.module\n\n\t\t\t\t// Update module node if it already exists; otherwise, create it.\n\t\t\t\tconst moduleNode = this.treeStore.tree.getNode<ExternalModuleNode>(id)\n\t\t\t\tif (moduleNode && !updateSave) {\n\t\t\t\t\t// Only update status metadata.\n\t\t\t\t\tconst identifier = moduleIdentifierForComponent(component)\n\t\t\t\t\tconst status = this.externalModulesDynamicInfo.get(identifier.moduleId)?.status ?? component.module.status\n\t\t\t\t\tmoduleNode.set({ group: status?.group, updateSaveId: status?.updateSaveId })\n\t\t\t\t} else {\n\t\t\t\t\tconst { type, metadata, ownerId, ownerType } = component.module\n\t\t\t\t\tconst identifier = moduleIdentifierForComponent(component)\n\t\t\t\t\t// Prefer dynamic info from global cache since it's either the same or more up-to-date.\n\t\t\t\t\tconst { title, status } = this.externalModulesDynamicInfo.get(identifier.moduleId) ?? component.module\n\n\t\t\t\t\t// Make sure that we have the global external modules list node in the document tree.\n\t\t\t\t\tlet listNode = ExternalModulesListNode.get(this.treeStore.tree)\n\t\t\t\t\tif (!listNode) {\n\t\t\t\t\t\tlistNode = new ExternalModulesListNode()\n\t\t\t\t\t\tthis.treeStore.tree.insertNode(listNode, this.treeStore.tree.root.id)\n\t\t\t\t\t}\n\t\t\t\t\tassert(isExternalModulesListNode(listNode))\n\n\t\t\t\t\tconst pluginId = metadata[ModuleMetadata.PluginId]\n\t\t\t\t\tconst externalNodeProperties: Partial<ExternalModuleNode> = {\n\t\t\t\t\t\tcodeComponentIdentifier: identifier.value,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tscopeNodeId: scopeNodeIdFromModule(component.module),\n\t\t\t\t\t\tintrinsicWidth: tryParseNumber(metadata[ModuleMetadata.IntrinsicWidth], true) ?? 200,\n\t\t\t\t\t\tintrinsicHeight: tryParseNumber(metadata[ModuleMetadata.IntrinsicHeight], true) ?? 200,\n\t\t\t\t\t\townerId,\n\t\t\t\t\t\townerType,\n\t\t\t\t\t\tgroup: status?.group,\n\t\t\t\t\t\tupdateSaveId: status?.updateSaveId,\n\t\t\t\t\t\tnamespaceId: component.module.lastPublish?.namespaceId,\n\t\t\t\t\t\tpluginId: isString(pluginId) ? pluginId : undefined,\n\t\t\t\t\t}\n\n\t\t\t\t\tconst entity = this.componentLoader.componentForIdentifier(identifier.value)\n\t\t\t\t\tassert(entity, \"Component not found in the component loader\", identifier.value)\n\t\t\t\t\t// For performance reasons, we pre-parse the annotations of vectors so we don't have\n\t\t\t\t\t// to parse them on renders, just like we do for *all* LocalModulesNodes. We don't\n\t\t\t\t\t// do this for other external modules as it would create inconsistent data. We can\n\t\t\t\t\t// do a migration to remove this fork.\n\t\t\t\t\tconst annotations: Annotations | undefined = entity.annotations ?? undefined\n\t\t\t\t\texternalNodeProperties.annotations = isParsedAnnotationExternalModuleType(type)\n\t\t\t\t\t\t? parseModuleAnnotations({ default: annotations }).default\n\t\t\t\t\t\t: annotations\n\t\t\t\t\t// We capture the displayName if its set from the code,\n\t\t\t\t\t// otherwise we fallback to the title. This is to allow Code\n\t\t\t\t\t// Components to have names with spaces.\n\t\t\t\t\tconst displayName = entity.name ?? title\n\t\t\t\t\texternalNodeProperties.title = displayName\n\n\t\t\t\t\tif (moduleNode) {\n\t\t\t\t\t\t// Update the existing module node with the new properties.\n\t\t\t\t\t\tmoduleNode.set(externalNodeProperties)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Create a new module node since one did not already exist.\n\t\t\t\t\t\tconst newModuleNode = new ExternalModuleNode({ id, ...externalNodeProperties })\n\t\t\t\t\t\tthis.treeStore.tree.insertNode(newModuleNode, listNode.id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn onTreeUpdate()\n\t\t})\n\n\t\tawait this.installDependenciesForExternalModules(components)\n\n\t\treturn result\n\t}\n\n\tprivate debugModuleStoreAndComponentLoaderRevisionsMatch = () => {\n\t\treturn this.revision === this.componentLoader.modulesRevision\n\t}\n\n\t/**\n\t * Get the latest data for the external modules in the project so that the\n\t * \"Update\" action shows up when a module has a later version available.\n\t */\n\tprivate checkForExternalModuleUpdates = async () => {\n\t\tif (this.treeStore.tree.isViewOnly) return\n\n\t\tconst externalModulesListNode = ExternalModulesListNode.get(this.treeStore.tree)\n\t\tif (!externalModulesListNode?.children?.length) return\n\n\t\tconst identifiers: ExternalModuleExportIdentifier[] = []\n\t\tconst vectorIdentifiersBySet = new Map<string, ExternalModuleExportIdentifier[]>()\n\n\t\texternalModulesListNode.children.forEach(externalModuleNode => {\n\t\t\tconst parsedId = parseModuleIdentifier(externalModuleNode.codeComponentIdentifier)\n\t\t\tassert(\n\t\t\t\tparsedId?.kind === \"externalModuleExport\",\n\t\t\t\t\"expected ExternalModuleNode identifier to be of kind externalModuleExport\",\n\t\t\t)\n\n\t\t\tif (externalModuleNode.type === ModuleType.Vector) {\n\t\t\t\t// We don't query vectors if the set is published and doesn't have updates. This\n\t\t\t\t// reduces the size of the lookup significantly, insert sidebar vectors all are\n\t\t\t\t// published, so this can remove ~1500 queries from the batch in the case of\n\t\t\t\t// Phosphor.\n\t\t\t\tconst info = externalModuleNode.annotation(AnnotationKey.FramerVector)\n\t\t\t\tif (!isFramerVectorInfo(info)) return\n\t\t\t\tconst setId = info.set.moduleId\n\t\t\t\tconst list = vectorIdentifiersBySet.get(setId) ?? []\n\t\t\t\tlist.push(parsedId)\n\t\t\t\tvectorIdentifiersBySet.set(setId, list)\n\t\t\t} else {\n\t\t\t\tidentifiers.push(parsedId)\n\t\t\t}\n\t\t})\n\n\t\t// If the set for a group of vectors doesn't specify save ids (isn't published), we include\n\t\t// queries for each of its items in the batch. Note: it's possible they won't be used in the\n\t\t// case where the query also returns an update set that specifies specific saveIds, but this\n\t\t// should be rare, and is simpler than doing a second pass.\n\t\tfor (const [id, list] of vectorIdentifiersBySet) {\n\t\t\tconst node = this.treeStore.tree.get(id)\n\t\t\tif (!isExternalModuleNode(node)) continue\n\t\t\tconst info = node.annotation(AnnotationKey.FramerVectorSet)\n\t\t\tif (!isFramerVectorSetInfo(info)) continue\n\t\t\tif (isPublishedVectorSetInfo(info)) continue\n\n\t\t\tidentifiers.push(...list)\n\t\t}\n\n\t\tconst modulesQueries = identifiers.map(({ moduleId, saveId }) => ({\n\t\t\tmoduleId,\n\t\t\tsaveId,\n\t\t}))\n\n\t\tif (!modulesQueries.length) return\n\n\t\t// The service will 503 if there are more than 2500 queries in a request. Since checking for\n\t\t// updates is not time-sensitive, we batch these in series.\n\t\tlet batch: ModuleLookupQuery[] = []\n\t\tconst modules: ModulesAPI.ModuleWithSave[] = []\n\t\tfor (let index = 0; index < modulesQueries.length; index++) {\n\t\t\tconst query = modulesQueries[index]\n\t\t\tassert(query, \"query is expected to be defined.\")\n\t\t\tbatch.push(query)\n\n\t\t\t// Persist the final batch no matter the size.\n\t\t\tif (batch.length < updateLookupQueryBatchSize && index < modulesQueries.length - 1) continue\n\n\t\t\tconst { modules: modulesBatch } = await this.lookUpModules(batch, { includeStatus: true })\n\t\t\tmodules.push(...modulesBatch)\n\t\t\tbatch = []\n\t\t}\n\n\t\tif (this.treeStore.tree.isViewOnly) return\n\n\t\t// Get the latest information about the external modules and update the document cache.\n\t\tthis.updateExternalModuleNodes(\n\t\t\tmodules.map((m, i) => {\n\t\t\t\tconst identifier = identifiers[i]\n\t\t\t\tassert(identifier, \"External module missing a matching identifier\")\n\t\t\t\treturn { module: m, exportSpecifier: identifier.exportSpecifier }\n\t\t\t}),\n\t\t\t{\n\t\t\t\tonTreeUpdate() {},\n\t\t\t},\n\t\t).catch(unhandledError)\n\t}\n\n\tprivate updatesPollId: number | undefined\n\n\tprivate setupPollingExternalModulesUpdates(): void {\n\t\t// Throttling ensures we are not calling this function too often when tab visibility changes back and forth.\n\t\tconst throttledLoad = throttle(() => {\n\t\t\tthis.checkForExternalModuleUpdates().catch(log.reportError)\n\t\t}, 10_000)\n\n\t\tlet aborted = false\n\n\t\tconst startPolling = () => {\n\t\t\tif (aborted) return\n\t\t\tthrottledLoad()\n\n\t\t\tif (this.updatesPollId !== undefined) return\n\t\t\tthis.updatesPollId = window.setInterval(this.checkForExternalModuleUpdates, 60_000)\n\t\t}\n\t\tconst pausePolling = () => {\n\t\t\twindow.clearInterval(this.updatesPollId)\n\t\t\tthis.updatesPollId = undefined\n\t\t}\n\n\t\tfunction shouldPoll() {\n\t\t\treturn !document.hidden && navigator.onLine\n\t\t}\n\n\t\tif (shouldPoll()) {\n\t\t\tstartPolling()\n\t\t}\n\n\t\tfunction handleTabStateChange() {\n\t\t\t// Check if we should start/pause polling.\n\t\t\t// We delay the poll check by a little bit so that there's a\n\t\t\t// higher chance an update from another tab has propagated.\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (shouldPoll()) {\n\t\t\t\t\tstartPolling()\n\t\t\t\t} else {\n\t\t\t\t\tpausePolling()\n\t\t\t\t}\n\t\t\t}, 500)\n\t\t}\n\n\t\tdocument.addEventListener(\"visibilitychange\", handleTabStateChange, { signal: this.abortSignal })\n\t\t// TODO: Listen to ChromeStore's isViewOnly instead.\n\t\twindow.addEventListener(\"offline\", handleTabStateChange, { signal: this.abortSignal })\n\t\twindow.addEventListener(\"online\", handleTabStateChange, { signal: this.abortSignal })\n\n\t\tthis.abortSignal?.addEventListener(\"abort\", () => {\n\t\t\taborted = true\n\t\t\tpausePolling()\n\t\t})\n\t\tthis.abortSignal = undefined\n\t}\n\n\tprivate getCodeComponentNodesForExternalModuleExport(identifier: ExternalModuleExportIdentifier) {\n\t\tif (!this.treeStore.getDataTree()) {\n\t\t\tassert(!this.treeStore.tree.getService(\"loader\"), \"tree must be complete to query code components\")\n\t\t}\n\t\tconst codeComponents =\n\t\t\tthis.treeStore instanceof TreeStore && this.treeStore.getDataTree()\n\t\t\t\t? this.treeStore.query().whereClass(CodeComponentNode).asArray()\n\t\t\t\t: this.treeStore.getLoadedIndexes().codeComponents\n\t\treturn codeComponents.filter(node => {\n\t\t\tif (!isCodeComponentNode(node)) return false\n\t\t\t// Replica nodes that aren't vector instances are automatically updated because they follow the primary.\n\t\t\tif (isReplicaOrReplicaChild(node) && !node.isVectorInstance) return false\n\n\t\t\tconst parsedId = parseModuleIdentifier(node.codeComponentIdentifier)\n\t\t\tif (parsedId?.kind !== \"externalModuleExport\") return false\n\n\t\t\treturn parsedId.moduleId === identifier.moduleId && parsedId.exportSpecifier === identifier.exportSpecifier\n\t\t})\n\t}\n\n\tprivate getShaderNodesForExternalModuleExport(identifier: ExternalModuleExportIdentifier) {\n\t\tif (!this.treeStore.getDataTree()) {\n\t\t\tassert(!this.treeStore.tree.getService(\"loader\"), \"tree must be complete to query shaders\")\n\t\t}\n\t\tconst shaderNodes =\n\t\t\tthis.treeStore instanceof TreeStore && this.treeStore.getDataTree()\n\t\t\t\t? this.treeStore.query().whereClass(ShaderNode).asArray()\n\t\t\t\t: this.treeStore.getLoadedIndexes().shaderNodes\n\t\treturn shaderNodes.filter(node => {\n\t\t\t// Replica nodes are automatically updated because they follow the primary.\n\t\t\tif (isReplicaOrReplicaChild(node)) return false\n\n\t\t\tconst parsedId = parseModuleIdentifier(node.shaderModuleIdentifier)\n\t\t\tif (parsedId?.kind !== \"externalModuleExport\") return false\n\n\t\t\treturn parsedId.moduleId === identifier.moduleId && parsedId.exportSpecifier === identifier.exportSpecifier\n\t\t})\n\t}\n\n\tprivate get fastRefreshEnabled() {\n\t\treturn this.chromeStore.codeEditorPreviewVisible\n\t}\n\n\tprivate compileFastRefreshModule = async ({\n\t\tlocalId,\n\t\tname: moduleName,\n\t\tsource,\n\t\tincludeSourceMap = true,\n\t}: {\n\t\tlocalId: LocalModuleId\n\t\tname: string\n\t\tsource: string\n\t\tincludeSourceMap?: boolean\n\t}): Promise<WritableDraft<FastRefreshModuleEntry> | undefined> => {\n\t\tconst { type, name } = stableTypeAndNameFromLocalId(localId)\n\t\tif (!fastRefreshableModuleTypes.has(type)) {\n\t\t\treturn\n\t\t}\n\t\tconst filename = type === ModuleType.Code ? filenamesFromModuleName(moduleName).source : name\n\n\t\tconst { code, imports, sourceMap } = await compileModuleForFastRefresh({\n\t\t\tlocalId,\n\t\t\tsource,\n\t\t\tname: filename,\n\t\t\tincludeSourceMap,\n\t\t})\n\n\t\tconst fastRefreshModule: WritableDraft<FastRefreshModuleEntry> = {\n\t\t\tkind: \"fast-refresh\",\n\t\t\tlocalId,\n\t\t\ttype,\n\t\t\tname: filename,\n\t\t\tsourceContent: source,\n\t\t\tmoduleContent: code,\n\t\t\trelativeImports: imports.relative,\n\t\t\tsourceMapContent: sourceMap,\n\t\t\tbinaryAssetContents: undefined,\n\t\t\tsubmoduleContents: {},\n\t\t\tupdate: 0,\n\t\t}\n\t\tconst [nextFastRefreshModules, patches] = produceWithPatches(this.fastRefreshModules, draft => {\n\t\t\t// This will get huge, maybe put this in some sort of LRU cache\n\t\t\tdraft.set(moduleName, fastRefreshModule)\n\t\t})\n\t\tthis.fastRefreshModules = nextFastRefreshModules\n\n\t\tthis.fastRefreshModulesEmitter.emit({\n\t\t\tpatches: patches as unknown as ModulesUpdates.Patch[],\n\t\t\t// TODO: figure out what these values should be\n\t\t\tdependentModules: [],\n\t\t\tprioritizedModules: [],\n\t\t\trevision: ++this.revision,\n\t\t\tinitialized: true,\n\t\t})\n\t}\n\n\tprivate compile: typeof compileModule = ({\n\t\tlocalId,\n\t\tname,\n\t\tsource,\n\t\tincludeSourceMap = true,\n\t\ttype,\n\t\ttelemetrySession,\n\t}) => {\n\t\tconst compiledModule = compileModule({\n\t\t\tname,\n\t\t\tsource,\n\t\t\tincludeSourceMap,\n\t\t\ttype,\n\t\t\ttelemetrySession,\n\t\t})\n\t\tif (this.fastRefreshEnabled && localId) {\n\t\t\tthis.compileFastRefreshModule({ localId, name, source, includeSourceMap }).catch(unhandledError)\n\t\t}\n\t\treturn compiledModule\n\t}\n\n\t/**\n\t * For a given `moduleId` / `exportIdentifier` pair, updates all\n\t * code component or shader nodes to use the latest versions of the module. Specifically\n\t * `status.updateSaveId` from the external module lookup. Also updates the\n\t * corresponding ExternalModuleNode.\n\t */\n\tpublic async updateExternalModuleComponentInstances(currentCodeComponentIdentifier: string) {\n\t\tconst parsedId = parseModuleIdentifier(currentCodeComponentIdentifier)\n\t\tassert(\n\t\t\tparsedId?.kind === \"externalModuleExport\",\n\t\t\t\"parsed 'ExternalModuleNodes.id' should be of kind externalModuleExport\",\n\t\t)\n\n\t\tconst { moduleId, exportSpecifier } = parsedId\n\t\tconst externalModuleNode = this.treeStore.tree.getNodeWithTrait(moduleId, isExternalModuleNode)\n\t\tconst newSaveId =\n\t\t\tthis.externalModulesDynamicInfo.get(moduleId)?.status?.updateSaveId ?? externalModuleNode?.updateSaveId\n\t\tif (!newSaveId) {\n\t\t\tlog.warn(\"Could not update module\", moduleId, \"latest status missing\")\n\t\t\treturn\n\t\t}\n\n\t\tif (newSaveId === parsedId.saveId) {\n\t\t\treturn\n\t\t}\n\n\t\tconst { module, dependencies } = await this.lookUpModule(\n\t\t\t{ moduleId, saveId: newSaveId },\n\t\t\t{ includeDependencies: true, includeStatus: true },\n\t\t)\n\n\t\tassert(module.files.module, \"Module file must be defined\")\n\t\tconst updatedModuleIdentifier = externalModuleIdentifier(moduleId, newSaveId, module.files.module, exportSpecifier)\n\n\t\ttry {\n\t\t\tawait this.loadedExternalModulesStore\n\t\t\t\t.ensureModuleEvaluatedInSandbox(updatedModuleIdentifier)\n\t\t\t\t.catch(log.reportError)\n\t\t\tif (!this.treeStore.getDataTree()) {\n\t\t\t\tawait this.scheduler.runWithFullyLoadedTreeAsync({\n\t\t\t\t\tname: \"update_external_module_version\",\n\t\t\t\t\tmodalTitle: \"Updating the module version\",\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait this.updateExternalModuleNodes([{ module, dependencies, exportSpecifier }], {\n\t\t\t\t// Use the onTreeUpdate callback to ensure ExternalModuleNode and\n\t\t\t\t// CodeComponentNode/ShaderNode updates happen in a single batch update.\n\t\t\t\tonTreeUpdate: () => {\n\t\t\t\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\t\t\t\tif (module.type === ModuleType.Shader) {\n\t\t\t\t\t\tconst nodes = this.getShaderNodesForExternalModuleExport(parsedId)\n\t\t\t\t\t\tnodes.forEach(node => node.set({ shaderModuleIdentifier: updatedModuleIdentifier.value }))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst nodes = this.getCodeComponentNodesForExternalModuleExport(parsedId)\n\t\t\t\t\t\tnodes.forEach(node => node.set({ codeComponentIdentifier: updatedModuleIdentifier.value }))\n\t\t\t\t\t}\n\n\t\t\t\t\treplaceModuleIdentifierInCollections(tree, parsedId.value, updatedModuleIdentifier.value)\n\n\t\t\t\t\tupdateModuleIdentifiersInComponentPresets(tree, parsedId.value, updatedModuleIdentifier.value)\n\t\t\t\t},\n\t\t\t\t// Updating the save information in the nodes will ensure the \"Update\" action disappears.\n\t\t\t\tupdateSave: true,\n\t\t\t})\n\n\t\t\t// TODO: Might be nice to track how many components on the canvas changed.\n\t\t\tthis.trackExternalComponentInsert([updatedModuleIdentifier.value], ExternalComponentInsertType.update)\n\t\t} catch (e) {\n\t\t\tlog.reportError(e)\n\t\t}\n\t}\n\n\t/**\n\t * This mostly copied from ModuleStorage but repurposed for fast-refresh modules to always use import map specifiers\n\t * TODO: figure out if we can generalize the ModuleStorage one to work for fast-refresh modules as well\n\t */\n\tasync replaceRelativeImportsWithImportMapSpecifiers(\n\t\ttypeSlashName: TypeSlashName,\n\t\tmoduleContent: CodeWithRelativeImports,\n\t\trelativeImports: Iterable<string>,\n\t) {\n\t\tconst replacementMap: ReplacementMap = {}\n\n\t\tfor (const relativeImportSpecifier of relativeImports) {\n\t\t\tconst dependencyTypeSlashName = normalizePath(relativeImportSpecifier, typeSlashName)\n\t\t\tif (!dependencyTypeSlashName) continue\n\n\t\t\tlet dependencyModule: FastRefreshModuleEntry | PersistedModule | undefined\n\n\t\t\tdependencyModule = this.fastRefreshModules.get(dependencyTypeSlashName)\n\t\t\tif (!dependencyModule) {\n\t\t\t\tdependencyModule = this.modulesStorage.getModuleWithTypeSlashName(dependencyTypeSlashName)\n\t\t\t}\n\n\t\t\t// There can be a situation when an imported module doesn't actually exist,\n\t\t\t// it will end up in an error during evaluation.\n\t\t\tif (!dependencyModule) {\n\t\t\t\tlog.error(\"Cannot resolve\", relativeImportSpecifier, \"from\", typeSlashName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlet moduleName: string | undefined\n\t\t\tconst { name, localId } = dependencyModule\n\t\t\tif (dependencyModule.kind === \"fast-refresh\") {\n\t\t\t\t// TODO: can this be consolidated into using the regular dependencyModule.files?\n\t\t\t\tmoduleName = filenamesFromModuleName(name).module\n\t\t\t} else {\n\t\t\t\tconst { files } = dependencyModule\n\t\t\t\tassert(isString(files.module), \"Must have a module file name to build a local module import map specifier.\")\n\t\t\t\tmoduleName = files.module\n\t\t\t}\n\t\t\t// For fast-refresh modules, we always want to use the import map to lookup the module,\n\t\t\t// so that we don't have to recompile them when their dependencies change. This will\n\t\t\t// work because they are never persisted or shared outside of the current project,\n\t\t\treplacementMap[relativeImportSpecifier] = localModuleImportMapSpecifier(localId, moduleName)\n\t\t}\n\t\tconst rewriteResult = await rewriteRelativeImports(moduleContent, replacementMap)\n\t\tassert(rewriteResult.ok)\n\n\t\treturn rewriteResult.value\n\t}\n\n\t// ModulesUpdatesService.Interface implementation\n\n\tprivate getModules(includingFastRefresh: boolean = false) {\n\t\tconst modules: { [_: string]: ModulesUpdates.CompiledModule } = {}\n\t\tfor (const [typeSlashName, module] of this.localModules) {\n\t\t\tmodules[typeSlashName] = module\n\t\t}\n\t\tif (includingFastRefresh) {\n\t\t\tfor (const [typeSlashName, module] of this.fastRefreshModules) {\n\t\t\t\tmodules[typeSlashName] = module\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tmodules,\n\t\t\trevision: this.revision,\n\t\t\tinitialized: this.modulesStorage.initialized,\n\t\t}\n\t}\n\n\tprivate getAllModulesAsUpdateEvent(includingFastRefresh: boolean = false): ModulesUpdates.ModulesUpdateEvent {\n\t\tconst { dependenciesModule, modules, initialized, revision } = this.getModules(includingFastRefresh)\n\n\t\tconst initialPatches: Patch[] = []\n\n\t\tif (dependenciesModule) {\n\t\t\tinitialPatches.push({\n\t\t\t\top: \"add\" as const,\n\t\t\t\tpath: [`${dependenciesModule.type}/${dependenciesModule.name}`],\n\t\t\t\tvalue: dependenciesModule,\n\t\t\t})\n\t\t}\n\n\t\tfor (const module of Object.values(modules)) {\n\t\t\t// During initial loading consider all the modules newly added.\n\t\t\tinitialPatches.push({\n\t\t\t\top: \"add\" as const,\n\t\t\t\tpath: [`${module.type}/${module.name}`],\n\t\t\t\tvalue: module,\n\t\t\t})\n\t\t}\n\n\t\treturn {\n\t\t\tpatches: initialPatches as unknown as ModulesUpdates.Patch[],\n\t\t\tdependentModules: [],\n\t\t\tprioritizedModules: [],\n\t\t\tinitialized,\n\t\t\trevision,\n\t\t}\n\t}\n\n\tpublic getModulesUpdatesService(fastRefreshing: boolean = false): ModulesUpdates.Interface {\n\t\treturn {\n\t\t\tmoduleUpdatesStream: () =>\n\t\t\t\tfastRefreshing\n\t\t\t\t\t? this.fastRefreshModulesEmitter.newStream({ replay: \"latest\" })\n\t\t\t\t\t: this.moduleUpdatesEmitter.newStream({ replay: \"latest\" }),\n\t\t}\n\t}\n\n\t// Used by end-to-end tests. Checks if the module for a screen has loaded in the sandbox and the\n\t// host component loader was notified of it.\n\tpublic hasScreenModuleLoaded(screenNodeId: string): boolean {\n\t\tconst identifier = localModuleIdentifierForStableName(ModuleType.Screen, screenNodeId, \"default\").value\n\t\treturn this.componentLoader.componentForIdentifier(identifier) !== null\n\t}\n\n\tpublic hasPendingTreeData(): boolean {\n\t\treturn this.modulesStorage.hasPendingTreeData()\n\t}\n\n\tpublic writeTreeData() {\n\t\tthis.modulesStorage.writeTreeData()\n\t}\n\n\tpostProcess(options: { writeTreeData: boolean }) {\n\t\tthis.modulesStorage.processTreeUpdates(options)\n\t}\n\n\ttakeSnapshot(): ModulesStoreSnapshot {\n\t\tconst modulesStorageSnapshot = this.modulesStorage.takeSnapshot()\n\t\treturn new ModulesStoreSnapshot(this, modulesStorageSnapshot)\n\t}\n}\n\nexport class ModulesStoreSnapshot implements PersistedModuleProvider {\n\tconstructor(\n\t\tmodulesStore: ModulesStore,\n\t\tprivate readonly modulesStorageSnapshot: ModulesStorageSnapshot,\n\t) {\n\t\tthis.dependenciesModule = modulesStore.dependenciesModule\n\t\tthis.localModuleKeys = Array.from(modulesStore.localModules.keys())\n\t}\n\n\treadonly dependenciesModule: DependenciesModuleEntry | undefined\n\n\treadonly localModuleKeys: TypeSlashName[]\n\n\tgetPersistedModuleByLocalId(id: LocalModuleId): PersistedModule | undefined {\n\t\treturn this.modulesStorageSnapshot.getPersistedModuleByLocalId(id)\n\t}\n\n\tgetPersistedModuleByLocalIdentifier(identifier: string | undefined): PersistedModule | undefined {\n\t\tconst parsedIdentifier = parseModuleIdentifier(identifier)\n\t\tif (!isLocalModuleIdentifier(parsedIdentifier)) return\n\t\treturn this.getPersistedModuleByLocalId(parsedIdentifier.localId)\n\t}\n\n\tgetModuleWithTypeSlashName(typeSlashName: string): PersistedModule | undefined {\n\t\treturn this.modulesStorageSnapshot.getModuleWithTypeSlashName(typeSlashName)\n\t}\n}\n", "import type { Event, FramerEvents, FramerEventsPayload } from \"@framerjs/events\"\nimport { isExternalModuleIdentifier, isLocalModuleIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { isFramerModule } from \"document/components/utils/defaultComponents.ts\"\nimport type { CanvasNode, CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport type { ExternalModuleNode } from \"document/models/CanvasTree/nodes/ExternalModuleNode.ts\"\nimport {\n\tisCodeComponentNode,\n\tisDataRepeater,\n\tisFrameNode,\n\tisStackComponent,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isExternalMaster, isMaster } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isFormContainer } from \"document/models/CanvasTree/traits/forms/WithFormContainer.ts\"\nimport { ExternalComponentInsertType } from \"document/stores/ModulesStore.ts\"\nimport { record } from \"web/lib/tracker.ts\"\n\nconst insertTypeMap = {\n\tdefaultComponent: {\n\t\tinsert: ExternalComponentInsertType.insertDefaultComponent,\n\t\tdrag: ExternalComponentInsertType.dragInsertDefaultComponent,\n\t},\n\tlibraryModule: {\n\t\tinsert: ExternalComponentInsertType.insertLibraryComponent,\n\t\tdrag: ExternalComponentInsertType.dragInsertLibraryComponent,\n\t},\n\texternalModuleComponent: {\n\t\tinsert: ExternalComponentInsertType.insertComponent,\n\t\tdrag: ExternalComponentInsertType.dragInsertComponent,\n\t},\n}\n\nconst defaultComponentPrefix = \"default_component_\"\nconst externalPrefix = \"external_\"\nconst localPrefix = \"local_\"\nconst legacySymbol = \"legacy_design_component\"\nconst legacyCodeComponent = \"legacy_code_component\"\nconst localLegacyCodeComponent = `${localPrefix}${legacyCodeComponent}` as const\nconst externalLegacyCodeComponent = `${externalPrefix}${legacyCodeComponent}` as const\nconst localLegacySymbol = `${localPrefix}${legacySymbol}` as const\nconst externalLegacySymbol = `${externalPrefix}${legacySymbol}` as const\n\nenum PrimitiveComponents {\n\tForm = \"form\",\n\tFrame = \"frame\",\n\tFrameWithFill = \"image-frame\",\n\tStack = \"stack\",\n\tRepeater = \"repeater\",\n}\n\nconst primitiveComponents = new Set<string>([\n\tPrimitiveComponents.Form,\n\tPrimitiveComponents.Frame,\n\tPrimitiveComponents.FrameWithFill,\n\tPrimitiveComponents.Stack,\n\tPrimitiveComponents.Repeater,\n])\n\nconst isDefaultComponent = (type: ComponentType[\"type\"]): type is DefaultComponentType =>\n\ttype.startsWith(defaultComponentPrefix)\nconst isLegacySymbol = (type: ComponentType[\"type\"]): type is LegacySymbolType =>\n\ttype === localLegacySymbol || type === externalLegacySymbol\nconst isPrimitiveComponent = (type: ComponentType[\"type\"]): type is PrimitiveComponents => primitiveComponents.has(type)\n\ntype StoreUseInstalledPayload = Extract<FramerEvents, Event<\"store_use_installed\", FramerEventsPayload>>\n\nexport type ComponentAddedToCanvasSource = StoreUseInstalledPayload[\"source\"] | \"insert_panel\" | \"quick_menu\"\n\n// This function is a catch all function for when a component is added, right now we need lots of logic to make sure we fire specific events when a component is inserted\n//  we hope to remove that in favor of our more general component_instance event.\nexport function trackComponentAddedToCanvas({\n\tcanvasNode,\n\tsource,\n\tisDrag,\n\tengine,\n}: {\n\tcanvasNode: CanvasNode\n\tsource: ComponentAddedToCanvasSource\n\tpackageIdentifier?: string | null\n\tisDrag?: boolean\n\tengine: VekterEngine\n}) {\n\tconst meta = getComponentType(canvasNode, engine)\n\t// Always track component instances so we don't miss any cases.\n\trecord(\"component_instance\", { componentType: meta.type, source })\n\n\tswitch (source) {\n\t\tcase \"insert_menu\": {\n\t\t\tconst insertType = getInsertTypeFromComponentType(meta)\n\t\t\trecord(\"insert_menu_add\", { type_added: insertType })\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif (meta.type === \"local_module_canvasComponent_component\") {\n\t\trecord(\"component_canvas_instance\", { componentId: canvasNode.id })\n\t}\n\n\tif (isLegacySymbol(meta.type)) {\n\t\trecord(\"component_design_instance\", {})\n\t}\n\n\t// this tracking call sends a string that tracks how a certain external component is inserted - either through dragging it or by clicking the insert button\n\t// the nested ternary gets the key that maps to the strings the tracking function expects.\n\t// This is an example of a tracking call that hope to remove in favor of our more general component_instance event.\n\n\tif (isCodeComponentNode(canvasNode) && isExternalModuleIdentifier(canvasNode.codeComponentIdentifier)) {\n\t\tconst key = meta.type.startsWith(defaultComponentPrefix)\n\t\t\t? \"defaultComponent\"\n\t\t\t: source === \"team_library\"\n\t\t\t\t? \"libraryModule\"\n\t\t\t\t: \"externalModuleComponent\"\n\t\tconst insertType = insertTypeMap[key][isDrag ? \"drag\" : \"insert\"]\n\t\tengine.stores.modulesStore.trackExternalComponentInsert([canvasNode.codeComponentIdentifier], insertType)\n\t}\n}\n\n// Note: this also includes module-based components (such as Smart Components).\ninterface CodeComponent {\n\ttype: CodeComponentType\n\tcodeComponentIdentifier: CodeComponentNode[\"codeComponentIdentifier\"]\n}\n\n// Symbol (from before Smart Components were introduced).\ninterface LegacySymbol {\n\ttype: LegacySymbolType\n}\n\ntype ComponentType = CodeComponent | LegacySymbol | { type: PrimitiveComponents | \"unknown\" }\n\nexport function getComponentType(node: CanvasNode, engine: VekterEngine): ComponentType {\n\tif (isCodeComponentNode(node)) {\n\t\tconst codeComponentIdentifier = node.codeComponentIdentifier\n\t\tconst moduleIdentifier = parseModuleIdentifier(codeComponentIdentifier)\n\n\t\tif (!moduleIdentifier) {\n\t\t\tconst isLocal = node.codeComponentIdentifier.startsWith(\".\")\n\t\t\treturn {\n\t\t\t\ttype: isLocal ? localLegacyCodeComponent : externalLegacyCodeComponent,\n\t\t\t\tcodeComponentIdentifier,\n\t\t\t}\n\t\t}\n\n\t\tif (isLocalModuleIdentifier(moduleIdentifier)) {\n\t\t\treturn { type: `${localPrefix}module_${moduleIdentifier.type}_component`, codeComponentIdentifier }\n\t\t}\n\n\t\tif (isExternalModuleIdentifier(moduleIdentifier)) {\n\t\t\t// modulesStore.externalModules is always empty\n\t\t\tconst externalModuleNode = engine.stores.treeStore.tree.getNode<ExternalModuleNode>(moduleIdentifier.moduleId)\n\t\t\tif (isFramerModule(engine.stores.treeStore.tree, codeComponentIdentifier)) {\n\t\t\t\treturn { type: `${defaultComponentPrefix}${externalModuleNode?.title}`, codeComponentIdentifier }\n\t\t\t} else {\n\t\t\t\treturn {\n\t\t\t\t\ttype: `${externalPrefix}module_${externalModuleNode?.type ?? \"unknown\"}_component`,\n\t\t\t\t\tcodeComponentIdentifier,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// new instance from another local symbol instance\n\tconst replicatedMasterNode = node.replicaInfo?.master && engine.tree.getNode(node.replicaInfo.master)\n\tconst masterNode = replicatedMasterNode || node\n\tif (isMaster(masterNode)) {\n\t\tif (isExternalMaster(masterNode)) {\n\t\t\treturn { type: externalLegacySymbol }\n\t\t}\n\n\t\treturn { type: localLegacySymbol }\n\t}\n\n\tif (isDataRepeater(node)) {\n\t\treturn { type: PrimitiveComponents.Repeater }\n\t} else if (isFormContainer(node)) {\n\t\treturn { type: PrimitiveComponents.Form }\n\t} else if (isStackComponent(node)) {\n\t\treturn { type: PrimitiveComponents.Stack }\n\t} else if (isFrameNode(node)) {\n\t\tif (node.fillType === \"image\") {\n\t\t\treturn { type: PrimitiveComponents.FrameWithFill }\n\t\t}\n\t\treturn { type: PrimitiveComponents.Frame }\n\t}\n\n\treturn { type: \"unknown\" }\n}\n\nexport function getInsertTypeFromComponentType({ type }: ComponentType) {\n\tif (type.startsWith(\"local_module_\") || type === localLegacyCodeComponent) {\n\t\treturn \"code_component\"\n\t} else if (isLegacySymbol(type)) {\n\t\treturn \"design_component\"\n\t} else if (type.startsWith(externalPrefix)) {\n\t\treturn \"package\"\n\t} else if (isDefaultComponent(type) || isPrimitiveComponent(type)) {\n\t\treturn type\n\t}\n\treturn \"unknown\"\n}\n\ntype ExternalOrLocalPrefix = typeof externalPrefix | typeof localPrefix\n\ntype LegacySymbolType = `${ExternalOrLocalPrefix}${typeof legacySymbol}`\n\ntype DefaultComponentType = `${typeof defaultComponentPrefix}${string}`\n\ntype CodeComponentType =\n\t| DefaultComponentType\n\t| `${ExternalOrLocalPrefix}module_${string}`\n\t| `${ExternalOrLocalPrefix}${typeof legacyCodeComponent}`\n", "import { Dictionary } from \"app/dictionary.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { type CanvasNode, FrameNode, RichTextNode } from \"document/models/CanvasTree/index.ts\"\nimport { CanvasChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport { createComputedValue } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport { createValueTransformWithName } from \"document/models/CanvasTree/traits/utils/valueTransformUtils.ts\"\nimport { repeaterItemCountVariableId } from \"document/utils/RepeaterVariables.ts\"\nimport { ControlType, DimensionType } from \"library/index.ts\"\nimport { getOriginalRepeatedItemOfDataRepeater } from \"utils/repeaterUtils.ts\"\nimport { record } from \"web/lib/tracker.ts\"\n\nexport function createRepeaterEmptyState(repeater: CanvasNode) {\n\tconst emptyStateTextNode = new RichTextNode({\n\t\twidthType: DimensionType.Auto,\n\t\theightType: DimensionType.Auto,\n\t\thtml: \"<p>No items</p>\",\n\t})\n\temptyStateTextNode.setTextColor(\"rgb(153, 153, 153)\", false)\n\n\tconst emptyStateNode = new FrameNode({\n\t\tname: Dictionary.EmptyState,\n\n\t\twidthType: DimensionType.Auto,\n\t\tminWidth: \"100%\",\n\t\theightType: DimensionType.FixedNumber,\n\t\theight: 100,\n\t\tminHeight: \"100%\",\n\n\t\tlayout: \"stack\",\n\t\tstackDirection: \"vertical\",\n\t\tstackDistribution: \"center\",\n\t\tstackAlignment: \"center\",\n\t\tgap: 10,\n\t\tpadding: 10,\n\n\t\tfillColor: \"rgba(204, 204, 204, 0.2)\",\n\t\tborderEnabled: true,\n\t\tborderWidth: 1,\n\t\tborderPerSide: false,\n\t\tborderTop: 1,\n\t\tborderRight: 1,\n\t\tborderBottom: 1,\n\t\tborderLeft: 1,\n\t\tborderColor: \"rgba(136, 136, 136, 0.2)\",\n\t\tborderStyle: \"dashed\",\n\t\tradius: 20,\n\n\t\tchildren: new CanvasChildList([emptyStateTextNode]),\n\n\t\tvisible: createComputedValue(\n\t\t\tControlType.Boolean,\n\t\t\t{ type: \"variableReference\", id: repeaterItemCountVariableId, providerId: repeater.getPrimaryId() },\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\t...createValueTransformWithName({\n\t\t\t\t\t\tname: \"equals\",\n\t\t\t\t\t\tinput: ControlType.Number,\n\t\t\t\t\t\toutput: ControlType.Boolean,\n\t\t\t\t\t}),\n\t\t\t\t\tvalue: 0,\n\t\t\t\t},\n\t\t\t],\n\t\t),\n\t})\n\n\treturn emptyStateNode\n}\n\nexport function createEmptyStateChild(engine: VekterEngine, repeater: CanvasNode): void {\n\tconst emptyStateNode = createRepeaterEmptyState(repeater)\n\trecord(\"repeater_empty_state_create\", {})\n\n\tengine.scheduler.process(() => {\n\t\tconst repeatedItem = getOriginalRepeatedItemOfDataRepeater(engine.tree, repeater)\n\t\tconst repeatedItemIndex = repeatedItem ? engine.tree.getIndex(repeatedItem) : -1\n\t\tconst insertPosition = repeatedItemIndex >= 0 ? repeatedItemIndex + 1 : undefined\n\t\tengine.tree.insertNode(emptyStateNode, repeater.getPrimaryId(), insertPosition)\n\t\tengine.stores.selectionStore.set(emptyStateNode.id)\n\t})\n}\n", "import type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { collectionIdKey } from \"code-generation/components/cms/dataIdKeys.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { createRepeaterEmptyState } from \"document/components/utils/repeater.ts\"\nimport type { CanvasNode, CollectionNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { CollectionRepeater } from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport { isCollectionRepeater } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { createVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport type { CollectionFilter } from \"document/models/CanvasTree/traits/WithCollectionOptions.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { randomID } from \"library/render/types/randomID.ts\"\nimport { getCollectionForIdentifier } from \"utils/getCollectionForIdentifier.ts\"\nimport { getNearestAncestorDataRepeater } from \"utils/repeaterUtils.ts\"\n\nfunction findReferenceToProvider(collection: CollectionNode, dataIdentifier: string) {\n\tfor (const variable of Object.values(collection.variables)) {\n\t\tif (variable?.type === ControlType.CollectionReference && variable.dataIdentifier === dataIdentifier) {\n\t\t\treturn variable\n\t\t}\n\t}\n}\n\nfunction findMultiReferenceToProvider(collection: CollectionNode, dataIdentifier: string) {\n\treturn Object.values(collection.variables).find(\n\t\tvariable => variable?.type === ControlType.MultiCollectionReference && variable.dataIdentifier === dataIdentifier,\n\t)\n}\n\nfunction getSurroundingProviderIdAndDataIdentifier(\n\tengine: VekterEngine,\n\tparent: CanvasNode,\n): { dataIdentifier: ModuleExportIdentifierString; providerId: NodeID } | undefined {\n\tconst ancestorRepeater = getNearestAncestorDataRepeater(parent)\n\n\tif (isCollectionRepeater(ancestorRepeater)) {\n\t\treturn {\n\t\t\tdataIdentifier: ancestorRepeater.dataIdentifier,\n\t\t\tproviderId: ancestorRepeater.id,\n\t\t}\n\t}\n\n\tconst scopeNode = engine.tree.getScopeNodeFor(parent)\n\n\tif (hasCollectionDataSource(scopeNode)) {\n\t\treturn {\n\t\t\tdataIdentifier: scopeNode.dataIdentifier,\n\t\t\tproviderId: scopeNode.id,\n\t\t}\n\t}\n}\n\nfunction getReferenceFieldFilters(\n\tengine: VekterEngine,\n\tparent: CanvasNode,\n\trepeater: CollectionRepeater,\n): CollectionFilter | undefined {\n\tconst surroundingProviderIdAndDataIdentifier = getSurroundingProviderIdAndDataIdentifier(engine, parent)\n\tif (!surroundingProviderIdAndDataIdentifier) return\n\tconst { dataIdentifier, providerId } = surroundingProviderIdAndDataIdentifier\n\n\tconst insertedCollection = getCollectionForIdentifier(engine.tree, repeater.dataIdentifier)\n\tconst surroundingCollection = getCollectionForIdentifier(engine.tree, dataIdentifier)\n\tif (!insertedCollection || !surroundingCollection) return\n\n\tconst insertedCollectionReference = findReferenceToProvider(insertedCollection, dataIdentifier)\n\tconst insertedMultiCollectionReference = findMultiReferenceToProvider(insertedCollection, dataIdentifier)\n\tconst surroundingCollectionReference = findReferenceToProvider(surroundingCollection, repeater.dataIdentifier)\n\tconst surroundingMultiCollectionReference = findMultiReferenceToProvider(\n\t\tsurroundingCollection,\n\t\trepeater.dataIdentifier,\n\t)\n\n\tif (surroundingMultiCollectionReference) {\n\t\t// Parent has a multi-collection reference to the repeater\n\t\treturn {\n\t\t\tid: randomID(),\n\t\t\titemKey: \"id\",\n\t\t\ttransforms: [\n\t\t\t\t{\n\t\t\t\t\tid: randomID(),\n\t\t\t\t\ttype: \"valueTransform\",\n\t\t\t\t\tname: \"isIncludedIn\",\n\t\t\t\t\tvalue: createVariableReference(surroundingMultiCollectionReference.id, providerId),\n\t\t\t\t},\n\t\t\t],\n\t\t}\n\t} else if (surroundingCollectionReference) {\n\t\t// Parent has a collection reference to the repeater\n\t\treturn {\n\t\t\tid: randomID(),\n\t\t\titemKey: \"id\",\n\t\t\ttransforms: [\n\t\t\t\t{\n\t\t\t\t\tid: randomID(),\n\t\t\t\t\ttype: \"valueTransform\",\n\t\t\t\t\tname: \"equals\",\n\t\t\t\t\tvalue: createVariableReference(surroundingCollectionReference.id, providerId),\n\t\t\t\t},\n\t\t\t],\n\t\t}\n\t} else if (insertedMultiCollectionReference) {\n\t\t// Repeater has a multi-collection reference to the parent\n\t\treturn {\n\t\t\tid: randomID(),\n\t\t\titemKey: insertedMultiCollectionReference.id,\n\t\t\ttransforms: [\n\t\t\t\t{\n\t\t\t\t\tid: randomID(),\n\t\t\t\t\ttype: \"valueTransform\",\n\t\t\t\t\tname: \"contains\",\n\t\t\t\t\tvalue: createVariableReference(collectionIdKey, providerId),\n\t\t\t\t},\n\t\t\t],\n\t\t}\n\t} else if (insertedCollectionReference) {\n\t\t// Repeater has a collection reference to the parent\n\t\treturn {\n\t\t\tid: randomID(),\n\t\t\titemKey: insertedCollectionReference.id,\n\t\t\ttransforms: [\n\t\t\t\t{\n\t\t\t\t\tid: randomID(),\n\t\t\t\t\ttype: \"valueTransform\",\n\t\t\t\t\tname: \"equals\",\n\t\t\t\t\tvalue: createVariableReference(collectionIdKey, providerId),\n\t\t\t\t},\n\t\t\t],\n\t\t}\n\t}\n}\n\n/**\n * If a collection list is being inserted, automatically set up filters for any\n * references or multi-references that match existing variables that are in\n * scope from parent collection lists or web pages.\n * For non-filtered collection lists (\"index listings\"), insert an Empty State child.\n */\nexport function setupInsertedCollectionRepeater(engine: VekterEngine, parent: CanvasNode, repeater: CanvasNode): void {\n\tif (!isCollectionRepeater(repeater)) return\n\n\tconst referenceFieldFilter = getReferenceFieldFilters(engine, parent, repeater)\n\tif (referenceFieldFilter) {\n\t\trepeater.set({ collectionFilters: { filters: [referenceFieldFilter] } })\n\t\treturn\n\t}\n\n\tengine.tree.insertNode(createRepeaterEmptyState(repeater), repeater.id)\n}\n", "import type { LayoutCache } from \"document/LayoutCache.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport type { Rect } from \"library/render/types/Rect.ts\"\nimport { hasAnyLayout } from \"../WithLayout.ts\"\n\nexport function getChildrenRects(node: CanvasNode, layoutCache: LayoutCache): Rect[] | null {\n\tconst children = node.children\n\tif (!hasAnyLayout(node)) return null\n\tif (!children || children.length === 0) return []\n\treturn layoutCache.getChildrenRects(node.id) ?? []\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport type { GridComponentNode, StackComponentNode } from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport { isGridComponent } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { hasColumnMasonryLayout, hasGridLayout } from \"document/models/CanvasTree/traits/WithLayout.ts\"\nimport { isPositionRelative } from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport type { Line } from \"library/render/types/Line.ts\"\nimport type { 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 { isNumber } from \"utils/typeChecks.ts\"\nimport { paddingFromNode } from \"./paddingFromNode.ts\"\n\nfunction distanceToRange(value: number, rangeStart: number, rangeEnd: number): number {\n\tif (value >= rangeStart && value <= rangeEnd) return 0\n\tif (value <= rangeStart && value >= rangeEnd) return 0\n\tconst distanceToStart = Math.abs(rangeStart - value)\n\tconst distanceToEnd = Math.abs(rangeEnd - value)\n\treturn Math.min(distanceToStart, distanceToEnd)\n}\n\nfunction getClosestRectIndexInCrossDirection(\n\tisMainAxisHorizontal: boolean,\n\tinsertion: Point,\n\tchildRects: Rect[],\n): number {\n\tconst crossAxisCoordinate = isMainAxisHorizontal ? \"y\" : \"x\"\n\tconst crossAxisDimension = isMainAxisHorizontal ? \"height\" : \"width\"\n\tconst mouseOffset = insertion[crossAxisCoordinate]\n\tlet closestIndex = 0\n\tlet closestDistance = Infinity\n\tchildRects.forEach((childRect, index) => {\n\t\tif (closestDistance === 0) return\n\n\t\tconst rectStart = childRect[crossAxisCoordinate]\n\t\tconst rectEnd = rectStart + childRect[crossAxisDimension]\n\t\tconst distance = distanceToRange(mouseOffset, rectStart, rectEnd)\n\t\tif (distance < closestDistance) {\n\t\t\tclosestIndex = index\n\t\t\tclosestDistance = distance\n\t\t}\n\t})\n\n\treturn closestIndex\n}\n\nfunction rangesOverlap(aRangeStart: number, aRangeEnd: number, bRangeStart: number, bRangeEnd: number): boolean {\n\tconst maxStart = Math.max(aRangeStart, bRangeStart)\n\tconst minEnd = Math.min(aRangeEnd, bRangeEnd)\n\treturn maxStart < minEnd\n}\n\ninterface ListRange {\n\tstartIndex: number\n\tendIndex: number\n}\n\nfunction getRowRange(isMainAxisHorizontal: boolean, childIndex: number, childRects: Rect[]): ListRange {\n\tconst crossAxisCoordinate = isMainAxisHorizontal ? \"y\" : \"x\"\n\tconst crossAxisDimension = isMainAxisHorizontal ? \"height\" : \"width\"\n\tconst rect = childRects[childIndex]\n\tassert(rect, \"Out of bound access to childRects:\", childIndex, childRects)\n\tconst rectStart = rect[crossAxisCoordinate]\n\tconst rectEnd = rectStart + rect[crossAxisDimension]\n\tconst rowIndices: Set<number> = new Set([childIndex])\n\tchildRects.forEach((childRect, childRectIndex) => {\n\t\tif (childRectIndex === childIndex) return\n\t\tconst childRectStart = childRect[crossAxisCoordinate]\n\t\tconst childRectEnd = childRectStart + childRect[crossAxisDimension]\n\t\tconst onSameRow = rangesOverlap(rectStart, rectEnd, childRectStart, childRectEnd)\n\t\tif (!onSameRow) return\n\t\trowIndices.add(childRectIndex)\n\t})\n\treturn {\n\t\tstartIndex: Math.min(...rowIndices),\n\t\tendIndex: Math.max(...rowIndices),\n\t}\n}\n\nfunction getClosestRectIndex(\n\tinsertion: Point,\n\tisMainAxisHorizontal: boolean,\n\tchildRects: Rect[],\n\trowRange: ListRange,\n\tinsertBeforeAll: boolean,\n\tinsertAfterAll: boolean,\n): number {\n\tif (insertBeforeAll) {\n\t\treturn rowRange.startIndex\n\t}\n\tif (insertAfterAll) {\n\t\treturn rowRange.endIndex\n\t}\n\n\tconst axisCoordinate = isMainAxisHorizontal ? \"x\" : \"y\"\n\tconst axisDimension = isMainAxisHorizontal ? \"width\" : \"height\"\n\n\tconst insertionOffset = insertion[axisCoordinate]\n\n\tlet closestDistance = Infinity\n\tlet closestIndex = rowRange.startIndex\n\tfor (let index = rowRange.startIndex; index <= rowRange.endIndex; index++) {\n\t\tconst childRect = childRects[index]\n\t\tassert(childRect, \"Ouf of bound access to childRects:\", index, rowRange, childRects)\n\t\tconst childRectStart = childRect[axisCoordinate]\n\t\tconst childRectEnd = childRectStart + childRect[axisDimension]\n\t\tconst childRectDistance = distanceToRange(insertionOffset, childRectStart, childRectEnd)\n\t\tif (childRectDistance < closestDistance) {\n\t\t\tclosestDistance = childRectDistance\n\t\t\tclosestIndex = index\n\t\t}\n\t}\n\treturn closestIndex\n}\n\nfunction getRowRect(childRects: Rect[], rowRange: ListRange): Rect {\n\tconst rowRects: Rect[] = []\n\tfor (let index = rowRange.startIndex; index <= rowRange.endIndex; index++) {\n\t\tconst childRect = childRects[index]\n\t\tassert(childRect, \"Ouf of bound access to childRects:\", index, rowRange, childRects)\n\t\trowRects.push(childRect)\n\t}\n\treturn Rect.merge(...rowRects)\n}\n\nfunction childInsertionForGridOrStackWithWrapEnabled(\n\tparentDirectedNode: StackComponentNode | GridComponentNode,\n\tchildRects: Rect[],\n\tinsertion: Point,\n\tinsertionMaxSize: Size,\n): ChildInsertion {\n\tconst isMainAxisHorizontal =\n\t\tisGridComponent(parentDirectedNode) || parentDirectedNode.resolveValue(\"stackDirection\") === \"horizontal\"\n\n\tconst childRectBounds = Rect.merge(...childRects)\n\n\tconst axisCoordinate = isMainAxisHorizontal ? \"x\" : \"y\"\n\tconst crossAxisCoordinate = isMainAxisHorizontal ? \"y\" : \"x\"\n\tconst axisDimension = isMainAxisHorizontal ? \"width\" : \"height\"\n\tconst crossAxisDimension = isMainAxisHorizontal ? \"height\" : \"width\"\n\n\tconst insertCoordinate = insertion[axisCoordinate]\n\tconst crossInsertCoordinate = insertion[crossAxisCoordinate]\n\n\tconst childRectBoundsStart = childRectBounds[crossAxisCoordinate]\n\tconst childRectBoundsEnd = childRectBoundsStart + childRectBounds[crossAxisDimension]\n\n\t// Insert index should be first or last if the mouse is before or after all rows\n\tconst insertBeforeAll = crossInsertCoordinate < childRectBoundsStart\n\tconst insertAfterAll = !insertBeforeAll && crossInsertCoordinate > childRectBoundsEnd\n\n\tconst closestRectIndexInCrossDirection = getClosestRectIndexInCrossDirection(\n\t\tisMainAxisHorizontal,\n\t\tinsertion,\n\t\tchildRects,\n\t)\n\tconst rowRange = getRowRange(isMainAxisHorizontal, closestRectIndexInCrossDirection, childRects)\n\tconst closestRectIndex = getClosestRectIndex(\n\t\tinsertion,\n\t\tisMainAxisHorizontal,\n\t\tchildRects,\n\t\trowRange,\n\t\tinsertBeforeAll,\n\t\tinsertAfterAll,\n\t)\n\tconst closestRect = childRects[closestRectIndex]\n\tassert(closestRect, \"Closest rect is not defined:\", closestRectIndex)\n\tconst rectCenterCoordinate = closestRect[axisCoordinate] + closestRect[axisDimension] / 2\n\tconst insertBefore = insertBeforeAll || insertAfterAll ? insertBeforeAll : insertCoordinate < rectCenterCoordinate\n\n\tlet insertionIndex = insertBefore ? closestRectIndex : closestRectIndex + 1\n\tif (insertBeforeAll) {\n\t\tinsertionIndex = 0\n\t}\n\tif (insertAfterAll) {\n\t\tinsertionIndex = childRects.length\n\t}\n\n\tconst closestRectStart = closestRect[axisCoordinate]\n\tconst closestRectEnd = closestRectStart + closestRect[axisDimension]\n\n\tconst closestRectCoordinate = insertBefore ? closestRectStart : closestRectEnd\n\n\tlet siblingRectCoordinate: number | null = null\n\tconst siblingRectIndex = insertBefore ? closestRectIndex - 1 : closestRectIndex + 1\n\n\tif (siblingRectIndex >= rowRange.startIndex && siblingRectIndex <= rowRange.endIndex) {\n\t\tconst siblingRect = childRects[siblingRectIndex]\n\t\tif (siblingRect) {\n\t\t\tconst siblingRectStart = siblingRect[axisCoordinate]\n\t\t\tconst siblingRectEnd = siblingRectStart + siblingRect[axisDimension]\n\t\t\tsiblingRectCoordinate = insertBefore ? siblingRectEnd : siblingRectStart\n\t\t}\n\t}\n\n\tlet mainAxisCoordinate = closestRectCoordinate\n\tif (isNumber(siblingRectCoordinate)) {\n\t\tmainAxisCoordinate = Math.round((mainAxisCoordinate + siblingRectCoordinate) / 2)\n\t}\n\n\tconst rowRect = getRowRect(childRects, rowRange)\n\tconst rowCenter = Math.round(rowRect[crossAxisCoordinate] + rowRect[crossAxisDimension] / 2)\n\n\tconst indicatorCenter = { [axisCoordinate]: mainAxisCoordinate, [crossAxisCoordinate]: rowCenter } as Point\n\tconst a = { ...indicatorCenter }\n\tconst b = { ...indicatorCenter }\n\n\tconst maxSize = insertionMaxSize[crossAxisDimension]\n\tconst halfSize = Math.round(maxSize / 2)\n\n\tif (isMainAxisHorizontal) {\n\t\ta.y -= halfSize\n\t\tb.y += halfSize\n\t} else {\n\t\ta.x -= halfSize\n\t\tb.x += halfSize\n\t}\n\n\tconst localInsertionLine: Line = { a, b }\n\treturn { insertionIndex, localInsertionLine }\n}\n\n/**\n * Calculates the correct insertion index relative to the intended insertion point within a masonry layout.\n * @param childRects - The rects of the children.\n * @param insertion - The intended insertion point.\n * @returns The insertion index and line.\n */\nfunction childInsertionForColumnMasonry(childRects: Rect[], insertion: Point): ChildInsertion {\n\tconst fallback = { insertionIndex: 0, localInsertionLine: { a: { ...insertion }, b: { ...insertion } } }\n\tif (childRects.length === 0) return fallback\n\n\tconst columns = new Map<number, { x: number; width: number; indices: number[] }>()\n\tconst keyFactor = 1000\n\n\tchildRects.forEach((rect, index) => {\n\t\tconst key = Math.round(rect.x * keyFactor)\n\t\tconst entry = columns.get(key)\n\t\tif (entry) {\n\t\t\tentry.indices.push(index)\n\t\t\tif (rect.width > entry.width) entry.width = rect.width\n\t\t} else {\n\t\t\tcolumns.set(key, { x: rect.x, width: rect.width, indices: [index] })\n\t\t}\n\t})\n\n\tconst sortedColumns = Array.from(columns.values()).sort((a, b) => a.x - b.x)\n\n\tlet targetColumn = sortedColumns.find(column => insertion.x >= column.x && insertion.x <= column.x + column.width)\n\tif (!targetColumn) {\n\t\ttargetColumn = sortedColumns.reduce((closest, column) => {\n\t\t\tif (!closest) return column\n\n\t\t\tconst columnCenter = column.x + column.width / 2\n\t\t\tconst closestCenter = closest.x + closest.width / 2\n\t\t\treturn Math.abs(insertion.x - columnCenter) < Math.abs(insertion.x - closestCenter) ? column : closest\n\t\t}, sortedColumns[0])\n\t}\n\n\tif (!targetColumn) return fallback\n\n\tconst columnIndices = [...targetColumn.indices].sort((a, b) => {\n\t\tconst rectA = childRects[a]\n\t\tconst rectB = childRects[b]\n\t\tif (!rectA || !rectB) return 0\n\t\treturn rectA.y - rectB.y\n\t})\n\n\tlet insertPosition = columnIndices.findIndex(index => {\n\t\tconst rect = childRects[index]\n\t\tif (!rect) return false\n\t\treturn insertion.y < rect.y + rect.height / 2\n\t})\n\tif (insertPosition === -1) insertPosition = columnIndices.length\n\n\tlet insertionIndex: number\n\tif (insertPosition < columnIndices.length) {\n\t\tinsertionIndex = columnIndices[insertPosition] ?? 0\n\t} else {\n\t\tinsertionIndex = (columnIndices[columnIndices.length - 1] ?? 0) + 1\n\t}\n\n\tlet lineY: number\n\tif (insertPosition <= 0) {\n\t\tif (!columnIndices[0]) return fallback\n\n\t\tconst firstRect = childRects[columnIndices[0]]\n\t\tlineY = firstRect?.y ?? 0\n\t} else if (insertPosition >= columnIndices.length) {\n\t\tconst lastColumnIdx = columnIndices[columnIndices.length - 1]\n\t\tif (!lastColumnIdx) return fallback\n\n\t\tconst lastRect = childRects[lastColumnIdx]\n\t\tif (!lastRect) return fallback\n\n\t\tlineY = lastRect.y + lastRect.height\n\t} else {\n\t\tconst targetColumnIdx = columnIndices[insertPosition]\n\t\tif (!targetColumnIdx) return fallback\n\n\t\tconst targetRect = childRects[targetColumnIdx]\n\t\tif (!targetRect) return fallback\n\n\t\tlineY = targetRect.y\n\t}\n\n\tconst localInsertionLine: Line = {\n\t\ta: { x: targetColumn.x, y: lineY },\n\t\tb: { x: targetColumn.x + targetColumn.width, y: lineY },\n\t}\n\n\treturn { insertionIndex, localInsertionLine }\n}\n\nconst containerEdgeOffset = 4\nconst minLineLength = 20\n\nexport function childInsertion(\n\t// passing the StackComponentNode instead of just props to enforce type-safety\n\tparentDirectedNode: StackComponentNode | GridComponentNode,\n\tchildRects: Rect[],\n\tcontainerSize: Size,\n\tlocalMouse: Point,\n\tinsertionMaxSize: Size,\n): ChildInsertion {\n\tassert(childRects.length, \"childInsertion only works correctly if there are more than 0 child rects\")\n\n\tif (experiments.isOn(\"betterStackGridItemMoving\")) {\n\t\tconst { rect: closestRect, index: closestIndex } = Rect.closestRect(childRects, localMouse)\n\n\t\tconst isMasonry = hasColumnMasonryLayout(parentDirectedNode)\n\n\t\tconst isHorizontal = hasGridLayout(parentDirectedNode)\n\t\t\t? !isMasonry\n\t\t\t: parentDirectedNode.resolveValue(\"stackDirection\") === \"horizontal\"\n\n\t\tconst main = isHorizontal ? \"x\" : \"y\"\n\t\tconst cross = isHorizontal ? \"y\" : \"x\"\n\t\tconst mainDimension = isHorizontal ? \"width\" : \"height\"\n\t\tconst crossDimension = isHorizontal ? \"height\" : \"width\"\n\n\t\tconst isInsertionBeforeClosest = localMouse[main] < closestRect[main] + closestRect[mainDimension] / 2\n\n\t\tconst neighborDelta =\n\t\t\tisMasonry && isNumber(parentDirectedNode.gridColumnCount)\n\t\t\t\t? Math.max(Math.floor(parentDirectedNode.gridColumnCount), 1)\n\t\t\t\t: 1\n\n\t\tconst neighborIndex = isInsertionBeforeClosest ? closestIndex - neighborDelta : closestIndex + neighborDelta\n\t\tconst neighborRect = childRects[neighborIndex]\n\n\t\tconst isInsertionAtContainerEdge =\n\t\t\t!neighborRect ||\n\t\t\t(isInsertionBeforeClosest ? neighborRect[main] >= closestRect[main] : closestRect[main] >= neighborRect[main])\n\n\t\t// Math.max because in masonry the index might go past childRects.length\n\t\tconst insertionIndex = isInsertionBeforeClosest\n\t\t\t? closestIndex\n\t\t\t: Math.min(closestIndex + neighborDelta, childRects.length)\n\n\t\tif (isInsertionAtContainerEdge) {\n\t\t\tconst mainValue = isInsertionBeforeClosest\n\t\t\t\t? closestRect[main] + containerEdgeOffset\n\t\t\t\t: closestRect[main] + closestRect[mainDimension] - containerEdgeOffset\n\n\t\t\treturn {\n\t\t\t\tinsertionIndex,\n\t\t\t\tlocalInsertionLine: {\n\t\t\t\t\ta: pointFromAxes(main, mainValue, closestRect[cross]),\n\t\t\t\t\tb: pointFromAxes(main, mainValue, closestRect[cross] + Math.max(closestRect[crossDimension], minLineLength)),\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\tconst mainValue = isInsertionBeforeClosest\n\t\t\t\t? (neighborRect[main] + neighborRect[mainDimension] + closestRect[main]) / 2\n\t\t\t\t: (closestRect[main] + closestRect[mainDimension] + neighborRect[main]) / 2\n\n\t\t\treturn {\n\t\t\t\tinsertionIndex,\n\t\t\t\tlocalInsertionLine: {\n\t\t\t\t\ta: pointFromAxes(main, mainValue, Math.min(neighborRect[cross], closestRect[cross])),\n\t\t\t\t\tb: pointFromAxes(\n\t\t\t\t\t\tmain,\n\t\t\t\t\t\tmainValue,\n\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\tneighborRect[cross] + neighborRect[crossDimension],\n\t\t\t\t\t\t\tclosestRect[cross] + Math.max(closestRect[crossDimension], minLineLength),\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\t}\n\n\tif (isGridComponent(parentDirectedNode) || parentDirectedNode.stackWrapEnabled) {\n\t\tif (hasColumnMasonryLayout(parentDirectedNode)) return childInsertionForColumnMasonry(childRects, localMouse)\n\t\treturn childInsertionForGridOrStackWithWrapEnabled(parentDirectedNode, childRects, localMouse, insertionMaxSize)\n\t}\n\n\tlet closestDistance = Infinity\n\tlet closestChildIndex: number | null = null\n\n\tconst isVertical = parentDirectedNode.stackDirection === \"vertical\"\n\n\tchildRects.forEach((childRect, index) => {\n\t\tconst distance = isVertical ? Math.abs(localMouse.y - childRect.y) : Math.abs(localMouse.x - childRect.x)\n\t\tif (distance > closestDistance) return\n\t\tclosestDistance = distance\n\t\tclosestChildIndex = index\n\t})\n\n\tlet visualIndex = 0\n\tif (closestChildIndex !== null) {\n\t\tconst closestChildRect = childRects[closestChildIndex]\n\t\tassert(closestChildRect, \"Closest child rect is not defined:\", closestChildIndex)\n\t\tconst closestCenter = Rect.center(closestChildRect)\n\t\tconst after = isVertical ? localMouse.y > closestCenter.y : localMouse.x > closestCenter.x\n\t\tif (after) closestChildIndex++\n\n\t\tvisualIndex = Math.min(Math.max(0, closestChildIndex), childRects.length)\n\t}\n\n\tconst crossPaddingOffset = crossPadding(parentDirectedNode)\n\tconst localInsertionLine = insertionIndicatorLine(\n\t\tparentDirectedNode.resolveValue(\"stackDirection\"),\n\t\tparentDirectedNode.resolveValue(\"stackAlignment\"),\n\t\tcrossPaddingOffset,\n\t\tcontainerSize,\n\t\tchildRects,\n\t\tvisualIndex,\n\t\tinsertionMaxSize,\n\t)\n\n\treturn { insertionIndex: getInsertionIndexFromVisualIndex(parentDirectedNode, visualIndex), localInsertionLine }\n}\n\ninterface ChildInsertion {\n\tinsertionIndex: number\n\tlocalInsertionLine: Line\n}\n\nfunction pointFromAxes(main: \"x\" | \"y\", mainValue: number, crossValue: number): Point {\n\tif (main === \"x\") return { x: mainValue, y: crossValue }\n\treturn { x: crossValue, y: mainValue }\n}\n\n// The visual index is deduced from the childrenRects, which excludes fixed/absolute elements. When defining the\n// insertion index, we need to consider those that we excluded from the rect.\nfunction getInsertionIndexFromVisualIndex(node: CanvasNode, visualIndex: number) {\n\tassert(withChildren(node), \"A node must support children to consider an insertion index.\")\n\n\tlet index = visualIndex\n\n\tfor (let i = 0; i < node.children.length; i++) {\n\t\tif (i === visualIndex) break\n\n\t\tconst child = node.children.at(i)\n\t\tif (!child) continue\n\n\t\tif (!isPositionRelative(child)) {\n\t\t\tindex++\n\t\t}\n\t}\n\n\treturn index\n}\n\nfunction crossPadding(node: StackComponentNode) {\n\tconst stackDirection = node.resolveValue(\"stackDirection\")\n\tconst stackAlignment = node.resolveValue(\"stackAlignment\")\n\tif (stackAlignment === \"center\") return 0\n\tconst padding = paddingFromNode(node)\n\tif (!padding.perSide) return padding.top\n\n\tconst alignStart = stackAlignment === \"start\"\n\tif (stackDirection === \"vertical\") {\n\t\treturn alignStart ? padding.left : padding.right\n\t} else {\n\t\treturn alignStart ? padding.top : padding.bottom\n\t}\n}\n\nfunction insertionIndicatorLine(\n\tdirection: \"horizontal\" | \"vertical\" | undefined,\n\tcrossAlignment: \"start\" | \"center\" | \"end\" | undefined,\n\tcrossPaddingOffset: number | undefined,\n\tcontainerSize: Size,\n\tchildrenRects: Rect[],\n\tindex: number,\n\tinsertedLayerSize: Size,\n): Line {\n\tconst beforeRect: Rect | undefined = childrenRects[index - 1]\n\tconst afterRect: Rect | undefined = childrenRects[index]\n\tconst isVertical = direction === \"vertical\"\n\n\tconst c = { x: containerSize.width / 2, y: containerSize.height / 2 }\n\n\t/* eslint-disable-next-line no-empty */\n\tif (!beforeRect && !afterRect) {\n\t} else if (childrenRects.length === 1) {\n\t\tconst onlyRect = beforeRect || afterRect\n\t\t// TS noUncheckedIndexedAccess rule doesn't understand that one of beforeRect and afterRect must exist even with the if statements above.\n\t\tassert(onlyRect, \"Child rect must be defined\")\n\t\tif (index === 0) {\n\t\t\tisVertical ? (c.y = onlyRect.y - 10) : (c.x = onlyRect.x - 10)\n\t\t} else {\n\t\t\tisVertical ? (c.y = onlyRect.y + onlyRect.height + 10) : (c.x = onlyRect.x + onlyRect.width + 10)\n\t\t}\n\t} else if (beforeRect && afterRect) {\n\t\tconst delta = Math.abs(\n\t\t\tisVertical ? beforeRect.y + beforeRect.height - afterRect.y : beforeRect.x + beforeRect.width - afterRect.x,\n\t\t)\n\t\tisVertical ? (c.y = afterRect.y - delta / 2) : (c.x = afterRect.x - delta / 2)\n\t} else if (beforeRect) {\n\t\tconst beforeBefore = childrenRects[index - 2]\n\t\t// If childrenRects.length > 1 and there's only beforeRect, means that our index >= 2\n\t\tassert(beforeBefore, \"Child rect must be defined\")\n\t\tconst delta = Math.abs(\n\t\t\tisVertical\n\t\t\t\t? beforeBefore.y + beforeBefore.height - beforeRect.y\n\t\t\t\t: beforeBefore.x + beforeBefore.width - beforeRect.x,\n\t\t)\n\t\tisVertical\n\t\t\t? (c.y = beforeRect.y + beforeRect.height + delta / 2)\n\t\t\t: (c.x = beforeRect.x + beforeRect.width + delta / 2)\n\t} else if (afterRect) {\n\t\tconst afterAfter = childrenRects[index + 1]\n\t\t// If there's only afterRect, means that our index === 0, plus childrenRects.length > 1, so index + 1 shouldn't be out of bound.\n\t\tassert(afterAfter, \"Child rect must be defined\")\n\t\tconst delta = Math.abs(\n\t\t\tisVertical ? afterRect.y + afterRect.height - afterAfter.y : afterRect.x + afterRect.width - afterAfter.x,\n\t\t)\n\t\tisVertical ? (c.y = afterRect.y - delta / 2) : (c.x = afterRect.x - delta / 2)\n\t}\n\tc.x = Math.min(Math.max(4, c.x), containerSize.width - 4)\n\tc.y = Math.min(Math.max(4, c.y), containerSize.height - 4)\n\treturn createLine(direction, crossAlignment, crossPaddingOffset, c, containerSize, insertedLayerSize)\n}\n\nfunction createLine(\n\tdirection: \"horizontal\" | \"vertical\" | undefined,\n\tcrossAlignment: \"start\" | \"center\" | \"end\" | undefined,\n\tcrossPaddingOffset: number | undefined,\n\tcenterPoint: Point,\n\tcontainerSize: Size,\n\tinsertedLayerSize: Size,\n): Line {\n\tconst isVertical = direction === \"vertical\"\n\tlet a: Point\n\tlet b: Point\n\tconst crossOffset = crossPaddingOffset ?? 0\n\n\tswitch (crossAlignment) {\n\t\tcase \"center\":\n\t\t\ta = {\n\t\t\t\tx: isVertical ? centerPoint.x - insertedLayerSize.width / 2 : centerPoint.x,\n\t\t\t\ty: isVertical ? centerPoint.y : centerPoint.y - insertedLayerSize.height / 2,\n\t\t\t}\n\t\t\tb = {\n\t\t\t\tx: isVertical ? centerPoint.x + insertedLayerSize.width / 2 : centerPoint.x,\n\t\t\t\ty: isVertical ? centerPoint.y : centerPoint.y + insertedLayerSize.height / 2,\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"start\":\n\t\t\ta = {\n\t\t\t\tx: isVertical ? crossOffset : centerPoint.x,\n\t\t\t\ty: isVertical ? centerPoint.y : crossOffset,\n\t\t\t}\n\t\t\tb = {\n\t\t\t\tx: isVertical ? insertedLayerSize.width + crossOffset : centerPoint.x,\n\t\t\t\ty: isVertical ? centerPoint.y : insertedLayerSize.height + crossOffset,\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"end\":\n\t\tdefault:\n\t\t\ta = {\n\t\t\t\tx: isVertical ? containerSize.width - insertedLayerSize.width - crossOffset : centerPoint.x,\n\t\t\t\ty: isVertical ? centerPoint.y : containerSize.height - insertedLayerSize.height - crossOffset,\n\t\t\t}\n\t\t\tb = {\n\t\t\t\tx: isVertical ? containerSize.width - crossOffset : centerPoint.x,\n\t\t\t\ty: isVertical ? centerPoint.y : containerSize.height - crossOffset,\n\t\t\t}\n\t\t\tbreak\n\t}\n\treturn { a, b }\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { ContextAction } from \"document/components/utils/contextActions.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isTreeNode } from \"document/models/CanvasTree/index.ts\"\nimport type { GridComponentNode, StackComponentNode } from \"document/models/CanvasTree/nodes/FrameNode.ts\"\nimport { isStackComponent, isStackOrGridComponent } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { shouldBlockNodeInOverlayEditMode } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { hasFloatingPosition } from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { withLock } from \"document/models/CanvasTree/traits/WithLock.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { isBreakpointVariant, isVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { acceptsChild } from \"document/models/CanvasTree/traits/utils/acceptsChild.ts\"\nimport { getChildrenRects } from \"document/models/CanvasTree/traits/utils/getChildrenRects.ts\"\nimport { isSymbolReplicaOrSymbolReplicaChild } from \"document/models/CanvasTree/traits/utils/isSymbol.ts\"\nimport { childInsertion } from \"document/utils/StackComponent/childInsertion.ts\"\nimport type { StackAlignment } from \"library/components/Stack/types.ts\"\nimport type { Line } from \"library/render/types/Line.ts\"\nimport type { Point } from \"library/render/types/Point.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport type { Size } from \"library/render/types/Size.ts\"\n\nexport interface WrapInsertionInfo {\n\twrapAlignment: StackAlignment\n}\n\nexport interface InsertionInfo {\n\tinsertionIndex: number | null\n\tinsertionLine: Line | null\n\twrap?: WrapInsertionInfo\n}\n\nconst stackInsertAtIndicatorThreshold = 10\n\nexport function nodeListsIntersect(a: NodeID[], b: NodeID[]) {\n\tfor (const i of a) {\n\t\tif (b.includes(i)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunction getWrapInfo(\n\tstack: StackComponentNode,\n\tengine: VekterEngine,\n\tmouse: Point,\n\tmaxSize: Size,\n\tchildrenRects: Rect[],\n): InsertionInfo | null {\n\t// Stack without children should not be wrapped\n\tif (childrenRects.length === 0) {\n\t\treturn null\n\t}\n\n\t// Stack with wrap enabled should not be wrapped\n\tif (stack.stackWrapEnabled) {\n\t\treturn null\n\t}\n\n\t// Variant ground node can't be wrapped\n\tif (isVariant(stack)) {\n\t\treturn null\n\t}\n\n\t// Replicas are not (yet) supported\n\tif (isReplicaOrReplicaChild(stack)) {\n\t\treturn null\n\t}\n\n\tconst { tree } = engine\n\tconst { zoom } = engine.stores.canvasStore\n\n\tconst parent = tree.getParent(stack.id)\n\tif (parent && isStackComponent(parent)) {\n\t\t// If parent is a stack in the cross direction, don't support auto wrap\n\t\tif (parent.stackDirection !== stack.stackDirection) {\n\t\t\treturn null\n\t\t}\n\t\t// If parent has stack wrap enabled, don't support auto wrap\n\t\tif (parent.stackWrapEnabled) {\n\t\t\treturn null\n\t\t}\n\t}\n\n\tconst localMouse = tree.convertPointToNode(stack, mouse)\n\tconst containerSize = tree.getRect(stack)\n\n\tconst isVertical = stack.stackDirection === \"vertical\"\n\t// The main axis for cross insertion is perpendicular to the stack direction\n\tconst mainAxis = isVertical ? \"x\" : \"y\"\n\tconst crossAxis = isVertical ? \"y\" : \"x\"\n\n\tconst mainDimension = isVertical ? \"width\" : \"height\"\n\tconst crossDimension = isVertical ? \"height\" : \"width\"\n\tconst mainDimensionSize = containerSize[mainDimension]\n\tconst crossDimensionSize = containerSize[crossDimension]\n\tconst mainDimensionScreenSize = mainDimensionSize * zoom\n\tconst crossDimensionScreenSize = crossDimensionSize * zoom\n\n\t// Only allow for cross insertion if the stack is large enough\n\tif (mainDimensionScreenSize < 40 || crossDimensionScreenSize < 40) {\n\t\treturn null\n\t}\n\n\t// For now we only care about the mouse offset in the cross direction of the stack\n\tconst mouseOffset = localMouse[mainAxis]\n\t// We are within the beginnning or end of the stack when we are 10 screen pixels away from the edge. Or\n\t// when we are closer than half the children offset.\n\tconst range = 10 / zoom\n\tconst childrenBounds = Rect.merge(...childrenRects)\n\tconst childrenBoundsStart = childrenBounds[mainAxis]\n\tconst childrenBoundsEnd = childrenBoundsStart + childrenBounds[mainDimension]\n\t// Check if we are inserting to the start or the end\n\tconst startRange = Math.max(range, childrenBoundsStart / 2)\n\tconst endRange = Math.max(range, (mainDimensionSize - childrenBoundsEnd) / 2)\n\tconst isStart = mouseOffset <= startRange\n\tconst isEnd = mouseOffset >= mainDimensionSize - endRange\n\n\tif (!isStart && !isEnd) return null\n\n\tconst insertionIndex = isStart ? 0 : 1\n\n\tconst crossDimensionMaxSize = maxSize[crossDimension]\n\n\tconst mainAxisInset = 4 / zoom\n\tconst mainAxisOffset = isStart ? mainAxisInset : mainDimensionSize - mainAxisInset\n\tconst crossAxisCenter = crossDimensionSize / 2\n\tconst crossOffset = crossDimensionMaxSize / 2\n\n\t// // Check the preferred stack alignment\n\tconst alignmentStepSize = crossDimensionSize / 3\n\tconst alignmentPosition = localMouse[crossAxis]\n\n\tlet wrapAlignment: StackAlignment = \"end\"\n\t// If the inserted item is larger then the hovered stack\n\tif (crossDimensionMaxSize > crossDimensionSize) {\n\t\twrapAlignment = \"center\"\n\t} else if (alignmentPosition < alignmentStepSize) {\n\t\twrapAlignment = \"start\"\n\t} else if (alignmentPosition < 2 * alignmentStepSize) {\n\t\twrapAlignment = \"center\"\n\t}\n\n\t// Calculate the insert indicator start and end points\n\tlet crossStart: number\n\tlet crossEnd: number\n\tswitch (wrapAlignment) {\n\t\tcase \"start\": {\n\t\t\tcrossStart = 0\n\t\t\tcrossEnd = crossDimensionMaxSize\n\t\t\tbreak\n\t\t}\n\t\tcase \"end\": {\n\t\t\tcrossEnd = crossDimensionSize\n\t\t\tcrossStart = crossEnd - crossDimensionMaxSize\n\t\t\tbreak\n\t\t}\n\t\tcase \"center\":\n\t\tdefault: {\n\t\t\tcrossStart = crossAxisCenter - crossOffset\n\t\t\tcrossEnd = crossAxisCenter + crossOffset\n\t\t\tbreak\n\t\t}\n\t}\n\n\tconst start = { [mainAxis]: mainAxisOffset, [crossAxis]: crossStart } as Point\n\tconst end = { [mainAxis]: mainAxisOffset, [crossAxis]: crossEnd } as Point\n\n\t// Convert line to canvas coordinates\n\tconst canvasStart = tree.convertPointToCanvas(stack, start)\n\tconst canvasEnd = tree.convertPointToCanvas(stack, end)\n\tconst insertionLine: Line = { a: canvasStart, b: canvasEnd }\n\n\treturn { insertionIndex, insertionLine, wrap: { wrapAlignment } }\n}\n\n/** Make sure `stackOrGrid.cache.placeholders` is up-to-date when calling. */\nexport function getStackOrGridInsertionIndexAndLine(\n\tstackOrGrid: StackComponentNode | GridComponentNode,\n\tengine: VekterEngine,\n\tmouse: Point,\n\tmaxSize: Size,\n\t{ allowWrapping = true }: { allowWrapping?: boolean } = {},\n): InsertionInfo {\n\tif (!withChildren(stackOrGrid)) return { insertionIndex: null, insertionLine: null }\n\n\tconst childrenRects = getChildrenRects(stackOrGrid, engine.stores.layoutCache)\n\tif (!childrenRects) return { insertionIndex: null, insertionLine: null }\n\n\tif (isStackComponent(stackOrGrid) && allowWrapping) {\n\t\tconst wrapInfo = getWrapInfo(stackOrGrid, engine, mouse, maxSize, childrenRects)\n\t\tif (wrapInfo) return wrapInfo\n\t}\n\n\tconst tree = engine.tree\n\tconst containerSize = tree.getRect(stackOrGrid)\n\tconst localMouse = tree.convertPointToNode(stackOrGrid, mouse)\n\n\tif (childrenRects.length === 0) {\n\t\treturn { insertionIndex: 0, insertionLine: null }\n\t}\n\n\tconst { insertionIndex, localInsertionLine } = childInsertion(\n\t\tstackOrGrid,\n\t\tchildrenRects,\n\t\tcontainerSize,\n\t\tlocalMouse,\n\t\tmaxSize,\n\t)\n\n\tconst insertionLine = {\n\t\ta: tree.convertPointToCanvas(stackOrGrid, localInsertionLine.a),\n\t\tb: tree.convertPointToCanvas(stackOrGrid, localInsertionLine.b),\n\t}\n\n\treturn { insertionIndex, insertionLine }\n}\n\nconst constantSize = { width: 10, height: 10 }\n\nexport function getStackOrGridInRange(\n\tengine: VekterEngine,\n\tmouse: Point,\n\tselectedNodes: CanvasNode[],\n\tcommonStackOrGridAtStart: StackComponentNode | GridComponentNode | null,\n\tisLayoutSection: boolean = false,\n): StackComponentNode | GridComponentNode | null {\n\tassert(selectedNodes.length, \"getStackOrGridInRange(): expects at least a single selected node\")\n\n\tconst activeScope = engine.stores.scopeStore.active\n\tconst anyFloatingPositionNodes = selectedNodes.some(hasFloatingPosition)\n\tif (anyFloatingPositionNodes) return null\n\n\tconst potentialParents = engine.tree\n\t\t.getNodesAtPoint(activeScope, mouse)\n\t\t.filter(parent => {\n\t\t\tif (withLock(parent) && parent.locked) return false\n\t\t\tif (!withChildren(parent)) return false\n\t\t\tif (isSymbolReplicaOrSymbolReplicaChild(parent)) return false\n\t\t\tif (shouldBlockNodeInOverlayEditMode(engine.tree, engine.stores.overlayStore.activeOverlays, parent)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\t.reverse()\n\n\tif (commonStackOrGridAtStart) {\n\t\tconst stackOrGridAtStartId = commonStackOrGridAtStart.id\n\t\tconst mouseOverStackAtStack = potentialParents.find(\n\t\t\t(parent): parent is StackComponentNode | GridComponentNode => parent.id === stackOrGridAtStartId,\n\t\t)\n\t\tif (mouseOverStackAtStack) {\n\t\t\treturn mouseOverStackAtStack\n\t\t}\n\t}\n\n\tlet topMostPotentialParent: CanvasNode | null = null\n\tconst selectedNodeIds = selectedNodes.map(node => node.id)\n\n\tfor (const potentialParent of potentialParents) {\n\t\tif (!isTreeNode(potentialParent)) continue\n\n\t\tif (isLayoutSection && !isBreakpointVariant(potentialParent)) continue\n\n\t\tconst ancestors = engine.tree.getAncestors(potentialParent.id)\n\t\tancestors.push(potentialParent.id)\n\t\tconst partOfSelection = nodeListsIntersect(ancestors, selectedNodeIds)\n\t\tif (partOfSelection) continue\n\t\tif (!topMostPotentialParent) topMostPotentialParent = potentialParent\n\t\tif (!isStackOrGridComponent(potentialParent)) continue\n\n\t\t// Check if we are close to one of the insertion indicators\n\t\tconst { insertionLine } = getStackOrGridInsertionIndexAndLine(\n\t\t\tpotentialParent,\n\t\t\tengine,\n\t\t\tmouse,\n\t\t\t// We can use a constant size because we are not interested in the length of the line\n\t\t\tconstantSize,\n\t\t)\n\n\t\tif (!insertionLine) continue\n\n\t\tif (insertionLine.a.x === insertionLine.b.x) {\n\t\t\t// Check horizontal distance\n\t\t\tconst horizontalDistance = Math.abs(mouse.x - insertionLine.a.x)\n\t\t\tconst screenPixelDistance = horizontalDistance * engine.stores.canvasStore.zoom\n\t\t\tif (screenPixelDistance > stackInsertAtIndicatorThreshold) continue\n\t\t} else if (insertionLine.a.y === insertionLine.b.y) {\n\t\t\t// Check vertical distance\n\t\t\tconst verticalDistance = Math.abs(mouse.y - insertionLine.a.y)\n\t\t\tconst screenPixelDistance = verticalDistance * engine.stores.canvasStore.zoom\n\t\t\tif (screenPixelDistance > stackInsertAtIndicatorThreshold) continue\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst acceptsAllChildren = selectedNodes.every(selectedNode =>\n\t\t\tacceptsChild(engine.tree, potentialParent, selectedNode, activeScope.id, engine.componentLoader),\n\t\t)\n\n\t\tif (acceptsAllChildren) return potentialParent\n\t}\n\n\tif (isStackOrGridComponent(topMostPotentialParent)) {\n\t\tconst parent = topMostPotentialParent\n\t\tconst acceptsAllChildren = selectedNodes.every(selectedNode =>\n\t\t\tacceptsChild(engine.tree, parent, selectedNode, activeScope.id, engine.componentLoader),\n\t\t)\n\t\tif (acceptsAllChildren) return topMostPotentialParent\n\t}\n\n\treturn null\n}\n\nexport function wrapStackBeforeInsertion(\n\tengine: VekterEngine,\n\tstack: StackComponentNode,\n\t{ wrapAlignment }: WrapInsertionInfo,\n) {\n\tconst newParentId = ContextAction.addStack(engine, [stack])\n\tif (!newParentId) return null\n\tconst newParent = engine.tree.getNode(newParentId)\n\tif (!newParent || !isStackComponent(newParent)) return null\n\tnewParent.set({\n\t\tstackDirection: stack.stackDirection === \"horizontal\" ? \"vertical\" : \"horizontal\",\n\t\tstackAlignment: wrapAlignment,\n\t})\n\treturn newParent\n}\n", "import { assert, unhandledError } from \"@framerjs/shared\"\nimport { updateInsertedVariantNode } from \"code-generation/utils/variantEditingHelpers.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCodeComponentNode,\n\tisFrameNode,\n\tisGridComponent,\n\tisSmartComponentNode,\n\tisStackComponent,\n\tisStackOrGridComponent,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { createOverlayWithEvent } from \"document/models/CanvasTree/nodes/utils/overlayCreationHelpers.ts\"\nimport { withBreakpointVariants } from \"document/models/CanvasTree/traits/WithBreakpointVariants.ts\"\nimport {\n\tDEFAULT_FLOATING_ALIGNMENT,\n\tDEFAULT_FLOATING_PLACEMENT,\n\tfloatingPositionDefaults,\n\twithFloatingPosition,\n} from \"document/models/CanvasTree/traits/WithFloatingPosition.ts\"\nimport { hasColumnMasonryLayout } 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 { withShader } from \"document/models/CanvasTree/traits/WithShader.ts\"\nimport type { WithSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport { withSize } from \"document/models/CanvasTree/traits/WithSize.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport {\n\tisBreakpointVariant,\n\tisPrimaryVariant,\n\tisReplicaVariantOrReplicaVariantChild,\n} from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { HardCodedCodeIdentifier } from \"document/models/CanvasTree/traits/utils/hardCodedCodeComponentIdentifiers.ts\"\nimport {\n\tconvertCanvasFrameToNode,\n\tconvertFrameToCanvas,\n\tgetBoundingFrameForNodes,\n} from \"document/models/CanvasTree/utils/geometry.ts\"\nimport { getNodesInRect } from \"document/models/CanvasTree/utils/hitTesting.ts\"\nimport { insertTemplateNode } from \"document/models/CanvasTree/utils/insertTemplateNode.ts\"\nimport { prefixControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport { shouldGuessPinToBottom } from \"document/models/shouldGuessPinToBottom.ts\"\nimport { shouldGuessPinToRight } from \"document/models/shouldGuessPinToRight.ts\"\nimport { findMatchingVariant, findVariantControlInfo } from \"document/utils/breakPointAndVariantMatching.ts\"\nimport {\n\tautoConvertParentToStackIfNeeded,\n\tmakePrimaryBreakpointAutoSizingIfNeeded,\n} from \"document/utils/layoutSectionHelpers.ts\"\nimport { DimensionType } from \"library/render/types/Constraints.ts\"\nimport type { Point } from \"library/render/types/Point.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport type { Size } from \"library/render/types/Size.ts\"\nimport type { ComponentAddedToCanvasSource } from \"utils/tracking/trackComponentAddedToCanvas.ts\"\nimport { trackComponentAddedToCanvas } from \"utils/tracking/trackComponentAddedToCanvas.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\nimport { withGridItemSize } from \"../../models/CanvasTree/traits/WithGridItemSize.ts\"\nimport { setupInsertedCollectionRepeater } from \"../../utils/setupInsertedCollectionRepeater.ts\"\nimport type { InsertableComponentType } from \"../chrome/assets/types.ts\"\nimport { uploadImage } from \"../chrome/insertSidebar/dataSources/utils.tsx\"\nimport type { ImageToUpload, LayoutVariants, VariantName } from \"../chrome/insertSidebar/types.ts\"\nimport { OverlayType } from \"../chrome/insertSidebar/types.ts\"\nimport type { WrapInsertionInfo } from \"../tools/utils/stackInsertionHelpers.ts\"\nimport {\n\tgetStackOrGridInRange,\n\tgetStackOrGridInsertionIndexAndLine,\n\twrapStackBeforeInsertion,\n} from \"../tools/utils/stackInsertionHelpers.ts\"\nimport { setDimensionTypeAutoIfSupported } from \"../utils/setDimensionTypeAutoIfSupported.ts\"\n\n// Helpers\n\nexport function getSizeForTemplate(engine: VekterEngine, template: CanvasNode): Size {\n\tlet { width, height } = engine.tree.getRect(template)\n\n\t// The auto size isn't known in time, let's try to use the width and height when non zero\n\tif (isPinnable(template) && withSize(template)) {\n\t\tif (template.widthType === DimensionType.Auto && template.width > 0) width = template.width\n\t\tif (template.heightType === DimensionType.Auto && template.height > 0) height = template.height\n\t}\n\n\treturn { width, height }\n}\n\nfunction getInsertionRectForDrop(engine: VekterEngine, template: CanvasNode, mouse: Point): Rect {\n\tconst size = getSizeForTemplate(engine, template)\n\n\treturn {\n\t\t...size,\n\t\tx: mouse.x - size.width / 2,\n\t\ty: mouse.y - size.height / 2,\n\t}\n}\n\nfunction getInsertionRectForGroundNode(engine: VekterEngine, template: CanvasNode): Rect {\n\tconst size = getSizeForTemplate(engine, template)\n\tconst activeScope = engine.stores.scopeStore.active\n\tconst commonGroundNode = engine.tree.getCommonGroundNode(engine.stores.selectionStore.nodes)\n\n\tlet x: number | undefined\n\tlet y: number | undefined\n\n\tif (commonGroundNode) {\n\t\tconst commonGroundNodeRect = convertFrameToCanvas(engine.tree, commonGroundNode)\n\t\tx = Rect.center(commonGroundNodeRect).x - size.width / 2\n\t\ty = commonGroundNodeRect.y\n\t} else if (isWebPageNode(activeScope) || isSmartComponentNode(activeScope)) {\n\t\tconst primaryVariant = activeScope.getPrimaryVariant()\n\t\tconst primaryVariantRect = convertFrameToCanvas(engine.tree, primaryVariant)\n\t\tx = Rect.center(primaryVariantRect).x - size.width / 2\n\t\ty = primaryVariantRect.y\n\t} else {\n\t\tconst centerPoint = engine.stores.canvasStore.getCanvasCenter()\n\t\tx = centerPoint.x - size.width / 2\n\t\ty = centerPoint.y - size.height / 2\n\t}\n\n\tconst point = { x, y }\n\n\t// eslint-disable-next-line no-constant-condition\n\twhile (true) {\n\t\tconst frame = { ...size, ...point }\n\n\t\tconst intersectingNodes = getNodesInRect(engine.tree, activeScope, frame, true)\n\t\t// If there is no intersecting node we can insert at this place.\n\t\tif (intersectingNodes.length === 0) return frame\n\n\t\t// Otherwise, move to the left and find an empty space.\n\t\tconst intersectingFrame = getBoundingFrameForNodes(engine.tree, intersectingNodes)\n\t\tpoint.x = intersectingFrame.x - size.width - 100\n\t}\n}\n\nexport function getInsertionParent(\n\tengine: VekterEngine,\n\ttemplate: CanvasNode,\n\tmouse: Point,\n\tisLayoutSection = false,\n): CanvasNode | null {\n\tconst { tree } = engine\n\tlet potentialParents = tree.getPotentialParents(\n\t\tengine.stores.scopeStore.active,\n\t\tengine.stores.overlayStore.activeOverlays,\n\t\tRect.cornerPoints({ ...mouse, width: 1, height: 1 }),\n\t\tmouse,\n\t\tengine.componentLoader,\n\t\ttemplate,\n\t)\n\tif (isLayoutSection) {\n\t\tpotentialParents = potentialParents.filter(isBreakpointVariant)\n\t}\n\n\tpotentialParents = tree.sortVisually(potentialParents).reverse()\n\treturn potentialParents.length > 0 && potentialParents[0] ? potentialParents[0] : null\n}\n\nconst fullWidthProps: Partial<WithPins> = {\n\twidth: 1,\n\twidthType: DimensionType.Percentage,\n\theightType: DimensionType.Auto,\n\tleft: 0,\n\tright: null,\n}\n\ninterface InsertComponentOptions {\n\tengine: VekterEngine\n\tcomponent: CanvasNode\n\tcanvasPoint: Point\n\tsource: ComponentAddedToCanvasSource\n\tshouldBecomeFullWidthForVariants?: LayoutVariants\n\ttype?: InsertableComponentType\n\tisLayoutSection?: boolean\n\tnotDraggedOntoCanvas?: boolean\n\tinsertAsGroundNode?: boolean\n\tinsertAsOverlayType?: OverlayType\n\timageToUpload?: ImageToUpload\n\tparentId?: string\n}\n\nexport function insertComponent({\n\tengine,\n\tcomponent,\n\tcanvasPoint,\n\tsource,\n\ttype,\n\tshouldBecomeFullWidthForVariants = new Set(),\n\tisLayoutSection = false,\n\tnotDraggedOntoCanvas = false,\n\tinsertAsGroundNode = false,\n\tinsertAsOverlayType,\n\timageToUpload,\n\tparentId,\n}: InsertComponentOptions) {\n\t// Shaders have their own dedicated \"shader_insert\" event.\n\tif (!withShader(component)) {\n\t\ttrackComponentAddedToCanvas({\n\t\t\tcanvasNode: component,\n\t\t\tsource: type === \"libraryModule\" ? \"team_library\" : source,\n\t\t\tisDrag: true,\n\t\t\tengine: engine,\n\t\t})\n\t}\n\n\tconst { selectionStore, canvasStore, scopeStore } = engine.stores\n\n\tconst insertionRect = insertAsGroundNode\n\t\t? getInsertionRectForGroundNode(engine, component)\n\t\t: getInsertionRectForDrop(engine, component, canvasPoint)\n\n\t// Eagerly convert the dropped component to a relative overlay to ensure\n\t// that accurately find valid parents. For example, a CodeComponentNode is a\n\t// valid parent if the proposed child is any type of overlay.\n\tif (insertAsOverlayType === OverlayType.Relative && withFloatingPosition(component)) {\n\t\tcomponent.set({\n\t\t\tfloatingPositionEnabled: true,\n\t\t\tfloatingPlacement: DEFAULT_FLOATING_PLACEMENT,\n\t\t\tfloatingAlignment: DEFAULT_FLOATING_ALIGNMENT,\n\t\t\tfloatingOffsetX: 0,\n\t\t\tfloatingOffsetY: 10,\n\t\t})\n\t}\n\n\tconst insertedNode = insertTemplateNode(engine, component)\n\n\tlet stackOrGridInRange = getStackOrGridInRange(engine, canvasPoint, [insertedNode], null, isLayoutSection)\n\n\tif (notDraggedOntoCanvas && isLayoutSection && !stackOrGridInRange) {\n\t\tconst visibleRect = canvasStore.getCanvasVisibleRectTakingOverlaysIntoAccount()\n\n\t\tconst singleSelectedNode =\n\t\t\tselectionStore.ids.length === 1 && selectionStore.ids[0] ? engine.tree.getNode(selectionStore.ids[0]) : null\n\t\tconst groundNodeOfSelectedNode = singleSelectedNode ? engine.tree.getGroundNodeFor(singleSelectedNode) : null\n\n\t\tif (\n\t\t\tisStackOrGridComponent(groundNodeOfSelectedNode) &&\n\t\t\tRect.intersects(convertFrameToCanvas(engine.tree, groundNodeOfSelectedNode), visibleRect)\n\t\t) {\n\t\t\tstackOrGridInRange = groundNodeOfSelectedNode\n\t\t}\n\t}\n\n\tlet parent = parentId\n\t\t? engine.tree.getNode(parentId)\n\t\t: (stackOrGridInRange ?? getInsertionParent(engine, component, canvasPoint, isLayoutSection))\n\n\tconst noSelectedNodes = selectionStore.ids.length === 0\n\tconst activeScope = scopeStore.active\n\tconst primaryBreakpoint = withBreakpointVariants(activeScope) ? activeScope.getPrimaryVariant() : null\n\tif (notDraggedOntoCanvas && isLayoutSection && primaryBreakpoint && noSelectedNodes) {\n\t\tparent = primaryBreakpoint\n\t}\n\n\tif (\n\t\tinsertAsOverlayType === OverlayType.Relative &&\n\t\tparent &&\n\t\twithFloatingPosition(insertedNode) &&\n\t\t!isBreakpointVariant(parent)\n\t) {\n\t\tassert(parent, \"Parent should exist\")\n\t\tconst parentId = parent.getPrimaryId()\n\t\tconst overlay = createOverlayWithEvent(\n\t\t\tengine.componentLoader,\n\t\t\tengine.stores,\n\t\t\tHardCodedCodeIdentifier.showRelativeOverlayAction,\n\t\t\tparentId,\n\t\t\tinsertedNode.draftOrCurrent(),\n\t\t)\n\n\t\tif (!overlay) return\n\n\t\tengine.tree.move(overlay.id, parentId)\n\n\t\treturn\n\t} else if (withFloatingPosition(insertedNode)) {\n\t\t// In the case where we couldn't insert the component, perhaps due to\n\t\t// not finding a parent, or the parent being a breakpoint, remove the\n\t\t// values we set to ensure we found the proper candidate so that we can\n\t\t// safely position the layer on the canvas as a regular frame.\n\t\tinsertedNode.set(floatingPositionDefaults)\n\t}\n\n\t// Non layout elements should be inserted as ground nodes so they are easier\n\t// to move to the correct place.\n\tif (insertAsGroundNode) {\n\t\tparent = null\n\t\tstackOrGridInRange = null\n\n\t\tif (!Rect.containsRect(canvasStore.getCanvasVisibleRectTakingOverlaysIntoAccount(), insertionRect)) {\n\t\t\tconst center = Rect.center(insertionRect)\n\t\t\tconst currentZoom = canvasStore.zoom\n\t\t\tconst zoom = Math.min(currentZoom, 1)\n\t\t\tcanvasStore.scrollToCenter(center, { animate: true, zoom })\n\t\t}\n\t}\n\n\tlet insertionIndex = -1\n\tlet wrap: WrapInsertionInfo | null = null\n\n\tif (parent) {\n\t\tautoConvertParentToStackIfNeeded(engine, parent, component, insertionRect)\n\t\tsetupInsertedCollectionRepeater(engine, parent, component)\n\t\tconst draftParent = parent.draftOrCurrent()\n\t\tif (isStackComponent(draftParent)) {\n\t\t\tstackOrGridInRange = draftParent\n\t\t}\n\t}\n\n\tif (stackOrGridInRange) {\n\t\tconst componentSize = getSizeForTemplate(engine, component)\n\n\t\t// When parentId is provided, always insert at the end of the stack/grid\n\t\tif (parentId) {\n\t\t\tinsertionIndex = stackOrGridInRange.children.length\n\t\t} else {\n\t\t\tconst { insertionIndex: stackInsertionIndex, wrap: wrapInfo } = getStackOrGridInsertionIndexAndLine(\n\t\t\t\tstackOrGridInRange,\n\t\t\t\tengine,\n\t\t\t\tcanvasPoint,\n\t\t\t\tcomponentSize,\n\t\t\t)\n\t\t\tif (wrapInfo) {\n\t\t\t\twrap = wrapInfo\n\t\t\t}\n\t\t\tif (isNumber(stackInsertionIndex)) {\n\t\t\t\tinsertionIndex = stackInsertionIndex\n\t\t\t}\n\t\t}\n\n\t\tif (notDraggedOntoCanvas && isLayoutSection) {\n\t\t\tinsertionIndex = stackOrGridInRange.children.length\n\n\t\t\tif (selectionStore.ids.length === 1) {\n\t\t\t\tconst selectedNodeId = selectionStore.ids[0]\n\t\t\t\tconst selectedNode = selectedNodeId && engine.tree.getNode(selectedNodeId)\n\t\t\t\tif (selectedNode) {\n\t\t\t\t\tconst possibleSelectedSectionIds = new Set<NodeID>([selectedNode.id])\n\t\t\t\t\tfor (const ancestor of selectedNode.ancestors()) {\n\t\t\t\t\t\tpossibleSelectedSectionIds.add(ancestor.id)\n\t\t\t\t\t}\n\t\t\t\t\tconst selectedSectionIndex = stackOrGridInRange.children.findIndex(child =>\n\t\t\t\t\t\tpossibleSelectedSectionIds.has(child.id),\n\t\t\t\t\t)\n\t\t\t\t\tif (selectedSectionIndex >= 0) {\n\t\t\t\t\t\tinsertionIndex = selectedSectionIndex + 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Zoom to inserted section\n\t\t\tlet insertedItemRect: Rect | undefined\n\t\t\tconst previousItem = insertionIndex > 0 ? stackOrGridInRange.children.at(insertionIndex - 1) : undefined\n\t\t\tif (previousItem) {\n\t\t\t\tinsertedItemRect = convertFrameToCanvas(engine.tree, previousItem)\n\t\t\t\tinsertedItemRect.y += insertedItemRect.height\n\t\t\t} else {\n\t\t\t\tinsertedItemRect = convertFrameToCanvas(engine.tree, stackOrGridInRange)\n\t\t\t}\n\n\t\t\t// Add the width of the ground node to the insertion rect\n\t\t\tinsertedItemRect.height = componentSize.height\n\t\t\tconst groundNodeSize = convertFrameToCanvas(engine.tree, stackOrGridInRange)\n\t\t\tconst minX = Math.min(insertedItemRect.x, groundNodeSize.x)\n\t\t\tconst maxX = Math.max(Rect.maxX(insertedItemRect), Rect.maxX(groundNodeSize))\n\t\t\tinsertedItemRect.x = minX\n\t\t\tinsertedItemRect.width = maxX - minX\n\n\t\t\tconst { zoom: currentZoom } = canvasStore\n\t\t\tconst visibleCanvasRect = canvasStore.getCanvasVisibleRectTakingOverlaysIntoAccount()\n\t\t\tconst visibleCanvasWidth = visibleCanvasRect.width * currentZoom\n\t\t\tconst visibleCanvasHeight = visibleCanvasRect.height * currentZoom\n\n\t\t\tconst margin = 40\n\t\t\tconst visualRectWidth = Math.max(visibleCanvasWidth - margin * 2, 100)\n\t\t\tconst visualRectHeight = Math.max(visibleCanvasHeight - margin * 2, 100)\n\t\t\tconst zoomForWidth = visualRectWidth / (insertedItemRect.width || 1)\n\t\t\tconst zoomForHeight = visualRectHeight / (insertedItemRect.height || 1)\n\t\t\tconst zoom = Math.min(zoomForWidth, zoomForHeight, 0.5)\n\t\t\tconst center = Rect.center(insertedItemRect)\n\t\t\tcanvasStore.scrollToCenter(center, { animate: true, zoom })\n\t\t}\n\n\t\tmakePrimaryBreakpointAutoSizingIfNeeded(engine, stackOrGridInRange, component, insertionRect)\n\t}\n\n\tlet rect: Rect | undefined\n\tif (parent) {\n\t\tconst { width, height } = insertionRect\n\t\trect = { ...convertCanvasFrameToNode(engine.tree, parent, insertionRect), width, height }\n\t} else {\n\t\trect = insertionRect\n\t}\n\n\tlet updateForRect = insertedNode.updateForRect({\n\t\trect,\n\t\tparentSizeInfo: null,\n\t\tconstraintsLocked: false,\n\t\tshouldGuessPinToBottom: parent ? shouldGuessPinToBottom(engine.tree, insertedNode, parent) : true,\n\t\tshouldGuessPinToRight: parent ? shouldGuessPinToRight(engine.tree, insertedNode, parent) : true,\n\t})\n\n\tif (parent && isStackComponent(parent) && withSize(insertedNode) && isPinnable(insertedNode)) {\n\t\tupdateForRect = preserveOriginalFractionOrRelativeSize(insertedNode, updateForRect)\n\t}\n\n\tsetDimensionTypeAutoIfSupported(engine.componentLoader, insertedNode, updateForRect)\n\n\tinsertedNode.set(updateForRect, engine.tree)\n\n\tlet idToSelect = insertedNode.id\n\tlet insertIntoReplicaVariant: boolean = false\n\tlet originalParent: CanvasNode | null = null\n\n\tif (parent) {\n\t\toriginalParent = parent\n\t\tif (isReplicaVariantOrReplicaVariantChild(parent)) {\n\t\t\toriginalParent = engine.tree.getNode(parent.originalid)\n\t\t\tinsertIntoReplicaVariant = true\n\t\t\tassert(originalParent, \"Fail to insert node into variants: the original parent should exist\")\n\t\t}\n\n\t\tif (wrap && !isReplicaOrReplicaChild(originalParent) && isStackComponent(originalParent)) {\n\t\t\tconst newParent = wrapStackBeforeInsertion(engine, originalParent, wrap)\n\t\t\tif (!newParent) return\n\t\t\toriginalParent = newParent\n\t\t}\n\n\t\tengine.moveNode(insertedNode.id, originalParent.id, insertionIndex)\n\n\t\tif (insertIntoReplicaVariant) {\n\t\t\tassert(\n\t\t\t\tisReplicaOrReplicaChild<CanvasNode>(parent),\n\t\t\t\t\"Fail to insert node into variants: the new parent should be a replica node\",\n\t\t\t)\n\t\t\tidToSelect = updateInsertedVariantNode(engine, insertedNode, parent, originalParent)\n\t\t}\n\n\t\tconst originalGroundNode = engine.tree.getGroundNodeFor(originalParent)\n\t\tconst name = originalGroundNode.resolveValue(\"name\")\n\t\tconst shouldBecomeFullWidthWithinPrimary = Boolean(\n\t\t\tname && shouldBecomeFullWidthForVariants.has(name.toLowerCase() as VariantName),\n\t\t)\n\n\t\tif (isFrameNode(insertedNode) && shouldBecomeFullWidthWithinPrimary) {\n\t\t\tinsertedNode.set({ left: 0, width: 1, widthType: DimensionType.Percentage }, engine.tree)\n\t\t}\n\n\t\t// Set code component variant to corresponding breakpoint when names match\n\t\tif (isCodeComponentNode(insertedNode)) {\n\t\t\tconst breakpointIsPrimary = isPrimaryVariant(originalGroundNode) && isBreakpointVariant(originalGroundNode)\n\t\t\tif (breakpointIsPrimary) {\n\t\t\t\t// If we're inserting a component that should have responsive behavior (100% width)...\n\t\t\t\t// Store the original values in case it shouldn't act this way in every breakpoint\n\t\t\t\tconst originalValues: LayoutOverrideValues = {\n\t\t\t\t\twidth: insertedNode.width,\n\t\t\t\t\twidthType: insertedNode.widthType,\n\t\t\t\t\tleft: insertedNode.left,\n\t\t\t\t\tright: insertedNode.right,\n\t\t\t\t}\n\t\t\t\t// ... and update the node if necessary\n\t\t\t\tif (shouldBecomeFullWidthWithinPrimary) {\n\t\t\t\t\tinsertedNode.set(fullWidthProps)\n\t\t\t\t}\n\n\t\t\t\tconst variantControlInfo = findVariantControlInfo(engine.componentLoader, insertedNode)\n\t\t\t\tif (variantControlInfo) {\n\t\t\t\t\tconst scope = engine.tree.getScopeNodeFor(originalGroundNode)\n\t\t\t\t\tif (isWebPageNode(scope)) {\n\t\t\t\t\t\tconst breakpointReplicaVariants = scope.getTopLevelReplicaVariants()\n\t\t\t\t\t\tbreakpointReplicaVariants.forEach(replicaVariant => {\n\t\t\t\t\t\t\tconst name = replicaVariant.resolveValue(\"name\")\n\t\t\t\t\t\t\tif (!name) return\n\n\t\t\t\t\t\t\tconst matchingVariant = findMatchingVariant(name, variantControlInfo)\n\t\t\t\t\t\t\tif (!matchingVariant) return\n\t\t\t\t\t\t\tif (matchingVariant === variantControlInfo.defaultVariant) return\n\n\t\t\t\t\t\t\tconst newOverrides = { ...replicaVariant.replicaInfo.overrides }\n\t\t\t\t\t\t\tconst newReplicaInfo = { ...replicaVariant.replicaInfo, overrides: newOverrides }\n\n\t\t\t\t\t\t\tconst nodeOverrides = { ...newOverrides[insertedNode.id] }\n\n\t\t\t\t\t\t\tconst layoutOverrides = getLayoutOverridesForVariant(\n\t\t\t\t\t\t\t\tshouldBecomeFullWidthWithinPrimary,\n\t\t\t\t\t\t\t\tshouldBecomeFullWidthForVariants,\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\toriginalValues,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif (layoutOverrides) {\n\t\t\t\t\t\t\t\tObject.assign(nodeOverrides, layoutOverrides)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tnodeOverrides[prefixControlPropKey(variantControlInfo.key)] = {\n\t\t\t\t\t\t\t\ttype: ControlType.Enum,\n\t\t\t\t\t\t\t\tvalue: matchingVariant,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnewOverrides[insertedNode.id] = nodeOverrides\n\t\t\t\t\t\t\treplicaVariant.set({ replicaInfo: newReplicaInfo })\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// TODO: Avoid setting grid item properties when moving into a masonry grid\n\t\tif (isGridComponent(parent) && withGridItemSize(insertedNode)) {\n\t\t\t// If it isn't a layout component that should become full width, let's make it fill the cell\n\t\t\tif (!shouldBecomeFullWidthWithinPrimary) {\n\t\t\t\tinsertedNode.set({ gridItemFillCellWidth: true })\n\t\t\t}\n\t\t\t// Always fill cell height for regular grids, but not for masonry grids\n\t\t\tif (!hasColumnMasonryLayout(parent)) {\n\t\t\t\tinsertedNode.set({ gridItemFillCellHeight: true })\n\t\t\t}\n\t\t}\n\t}\n\n\t// For pattern presets inserted via the 'Creative' insert menu:\n\t// If the draggable event data has a fill image that needs to be uploaded\n\t// then we need to offload that work to the \"floating\" promise below so that\n\t// we process the updates to the tree after the promise has resolved, otherwise\n\t// we run into issues with editing of the tree being closed.\n\tif (imageToUpload && isFrameNode(component)) {\n\t\tuploadImage(imageToUpload, component, engine).catch(unhandledError)\n\t}\n\n\t// If a parentId is provided, don't select the new node\n\tif (parentId) {\n\t\treturn\n\t}\n\n\tselectionStore.set(idToSelect, { switchToLayers: !!parentId, switchToProperties: true })\n}\n\ninterface LayoutOverrideValues {\n\twidth: number\n\twidthType: DimensionType\n\tleft: number | null\n\tright: number | null\n}\n\nfunction getLayoutOverridesForVariant(\n\tshouldBecomeFullWidthWithinPrimary: boolean,\n\tshouldBecomeFullWidthForVariants: LayoutVariants,\n\tvariantName: string,\n\toriginalValues: LayoutOverrideValues,\n): Partial<WithPins> | undefined {\n\tconst shouldBecomeFullWidthWithinVariant = shouldBecomeFullWidthForVariants.has(\n\t\tvariantName.toLowerCase() as VariantName,\n\t)\n\n\tif (shouldBecomeFullWidthWithinPrimary === shouldBecomeFullWidthWithinVariant) {\n\t\treturn\n\t}\n\n\tif (shouldBecomeFullWidthWithinVariant) {\n\t\treturn fullWidthProps\n\t}\n\n\treturn originalValues\n}\n\n/**\n * If `updateForRect` uses fixed sizes, but `node` uses fraction or relative\n * removes the `width/height/widthType/heightType` properties from `updateForRect`,\n * to prevent them from updating the original `node` properties\n */\nexport function preserveOriginalFractionOrRelativeSize(\n\tnode: CanvasNode & WithSize & WithPins,\n\tupdateForRect: { height?: number; width?: number; heightType?: DimensionType; widthType?: DimensionType },\n) {\n\tconst update = { ...updateForRect }\n\n\tif (\n\t\t(node.widthType === DimensionType.FractionOfFreeSpace || node.widthType === DimensionType.Percentage) &&\n\t\tisNumber(updateForRect.width) &&\n\t\tupdateForRect.widthType !== node.widthType\n\t) {\n\t\tdelete update.width\n\t\tdelete update.widthType\n\t}\n\tif (\n\t\t(node.heightType === DimensionType.FractionOfFreeSpace || node.heightType === DimensionType.Percentage) &&\n\t\tisNumber(updateForRect.height) &&\n\t\tupdateForRect.heightType !== node.heightType\n\t) {\n\t\tdelete update.height\n\t\tdelete update.heightType\n\t}\n\treturn update\n}\n", "import type { ModulesAPI } from \"@framerjs/framer-services\"\nimport { assert, type ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { getParentForInsertNode } from \"document/components/utils/getParentForInsertNode.ts\"\nimport { insertComponent } from \"document/components/utils/insertComponent.ts\"\nimport { CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { acceptsChild } from \"document/models/CanvasTree/traits/utils/acceptsChild.ts\"\nimport { convertFrameToCanvas } from \"document/models/CanvasTree/utils/geometry.ts\"\nimport type { Point } from \"library/render/types/Point.ts\"\nimport { Rect } from \"library/render/types/Rect.ts\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport { tryParseNumber } from \"utils/tryParseNumber.ts\"\n\nexport function insertModuleComponent({\n\tengine,\n\tmodule,\n\tidentifier,\n\tposition,\n\tcenterInParent,\n\tinsertAsGroundNode,\n\tupdate,\n\tparentId,\n}: {\n\tengine: VekterEngine\n\tmodule: ModulesAPI.ModuleWithSave\n\tidentifier: ModuleExportIdentifierString\n\tposition: Point\n\tcenterInParent: boolean\n\tinsertAsGroundNode?: boolean\n\tupdate?: (node: CodeComponentNode) => void\n\tparentId?: string\n}) {\n\tconst size = {\n\t\twidth: tryParseNumber(module.metadata[ModuleMetadata.IntrinsicWidth], true) ?? 200,\n\t\theight: tryParseNumber(module.metadata[ModuleMetadata.IntrinsicHeight], true) ?? 200,\n\t}\n\tconst component = new CodeComponentNode({\n\t\tcodeComponentIdentifier: identifier,\n\t\tslotsAreChildNodes: experiments.isOn(\"componentSlotsAreChildNodes\"),\n\t\t...size,\n\t})\n\t// When a parentId is provided, validate that the parent accepts this child node.\n\t// This prevents inserting component instances into nodes that can't have children\n\t// (e.g. text nodes, component instance nodes).\n\tif (parentId !== undefined) {\n\t\tconst parent = engine.tree.getNode(parentId)\n\t\tassert(parent, \"Parent node not found\", parentId)\n\t\tassert(\n\t\t\tacceptsChild(engine.tree, parent, component, engine.stores.scopeStore.active.id, engine.componentLoader),\n\t\t\t\"Parent does not accept children\",\n\t\t\tparentId,\n\t\t)\n\t}\n\n\tif (update) update(component)\n\n\tlet center = position\n\n\t// TODO: Find a better heuristic than \"the center of the parent to position the component\"\n\tif (centerInParent && !insertAsGroundNode && !parentId) {\n\t\tconst parent = getParentForInsertNode(component, engine)\n\t\tconst parentRectCenter = parent ? Rect.center(convertFrameToCanvas(engine.tree, parent)) : null\n\t\tconst visibleCanvasRect = engine.stores.canvasStore.getCanvasVisibleRectTakingOverlaysIntoAccount()\n\t\tif (parentRectCenter && Rect.containsPoint(visibleCanvasRect, parentRectCenter)) {\n\t\t\tcenter = parentRectCenter\n\t\t}\n\t}\n\n\tinsertComponent({\n\t\tengine: engine,\n\t\tcomponent: component,\n\t\tcanvasPoint: center,\n\t\tsource: \"context_menu\",\n\t\tinsertAsGroundNode: parentId ? false : insertAsGroundNode,\n\t\tparentId,\n\t})\n\n\treturn component\n}\n", "import type { ExternalModuleExportIdentifier } from \"@framerjs/shared\"\nimport { getLogger } from \"@framerjs/shared\"\nimport type { NonPromiseLike } from \"document/VekterEngine.ts\"\nimport type { CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport type { ComponentInfo } from \"document/stores/ModulesStore.ts\"\nimport type { RenamedIds } from \"../tools/utils/updateNodeConnections.ts\"\nimport type { CodeComponentIsolationMode } from \"./enterCodeComponentIsolation.ts\"\n\nexport const log = getLogger(\"unlinking\")\n\nexport type ScheduleUnlinkTreeUpdate = <T>(task: () => NonPromiseLike<T, T>) => Promise<T>\n\nexport interface InternalImportExternalComponentFunctionOptions {\n\tidentifier: ExternalModuleExportIdentifier\n\tinfo: ComponentInfo\n\tenterIsolation: boolean\n\tcodeComponentIsolationMode?: CodeComponentIsolationMode\n\tinstance?: CodeComponentNode | null\n\trenamedIds?: RenamedIds\n\tisAutoDetach?: boolean\n\tscheduleTreeUpdate?: ScheduleUnlinkTreeUpdate\n}\n", "import type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isFixedOrRelativeOverlay } from \"document/models/CanvasTree/nodes/utils/overlayHelpers.ts\"\nimport { getBoundingFrameForNodes } from \"document/models/CanvasTree/utils/geometry.ts\"\n\n/**\n * Selects a node on the canvas and switches the UI, accounting for all UI specifics:\n * active scope, overlay visibility, scrolling to the node, etc.\n */\nexport function showCanvasNode(engine: VekterEngine, node: CanvasNode, zoomToNode = true) {\n\tengine.scheduler.processWhenReady(() => {\n\t\tconst { overlayStore, selectionStore, scopeStore, canvasStore, persistedUserDefaults } = engine.stores\n\t\tscopeStore.selectByNode(node.id)\n\n\t\tconst overlayNode = isFixedOrRelativeOverlay(node)\n\t\t\t? node\n\t\t\t: engine.tree.getNodeWithTrait(node.cache.overlayAncestorId, isFixedOrRelativeOverlay)\n\t\tif (overlayNode) {\n\t\t\toverlayStore.showOverlay(selectionStore, overlayNode, overlayNode.parentid)\n\t\t} else {\n\t\t\toverlayStore.hideAll()\n\t\t}\n\n\t\tselectionStore.set(node.id)\n\n\t\tif (zoomToNode) {\n\t\t\tconst rect = getBoundingFrameForNodes(engine.tree, [node])\n\t\t\tcanvasStore.zoomToCenter(rect, {\n\t\t\t\tanimated: persistedUserDefaults.animateOnZoom,\n\t\t\t\tmaxZoom: 1,\n\t\t\t})\n\t\t}\n\t})\n}\n", "import type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { VekterPluginManifest } from \"plugins/plugins.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { showCanvasNode } from \"./showCanvasNode.ts\"\n\nasync function showCodeComponentInstanceIfNeeded(\n\tengine: VekterEngine,\n\tcodeComponentIdentifier: string,\n\tpluginManifest: VekterPluginManifest,\n): Promise<boolean> {\n\tconst { codeEditorStore, selectionStore, treeStore } = engine.stores\n\tcodeEditorStore.closeEditor()\n\n\tconst [selectedNode] = selectionStore.nodes\n\tif (\n\t\tselectionStore.nodes.length === 1 &&\n\t\tisCodeComponentNode(selectedNode) &&\n\t\tselectedNode.codeComponentIdentifier === codeComponentIdentifier\n\t) {\n\t\treturn true\n\t}\n\n\tlet node: CodeComponentNode | undefined\n\tif (treeStore.getDataTree()) {\n\t\tfor (const candidateNode of treeStore.query().whereClass(CodeComponentNode).iterate()) {\n\t\t\tif (candidateNode.codeComponentIdentifier === codeComponentIdentifier) {\n\t\t\t\tnode = candidateNode\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\tnode = await engine.runWithFullyLoadedTreeAsync(\n\t\t\t() => {\n\t\t\t\tfor (const id of treeStore.treeIndex.codeComponentNodeIds) {\n\t\t\t\t\tconst candidateNode = engine.tree.getNodeWithTrait(id, isCodeComponentNode)\n\t\t\t\t\tif (candidateNode?.codeComponentIdentifier === codeComponentIdentifier) return candidateNode\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ runInBackground: true, name: `findCodeComponentInstance: ${codeComponentIdentifier}` },\n\t\t)\n\t}\n\n\tif (!node) {\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tvariant: \"info\",\n\t\t\tkey: \"add-component-instance-to-edit-in-plugin\",\n\t\t\tprimaryText: \"Add component to Canvas\",\n\t\t\tsecondaryText: `to edit in ${pluginManifest.name}.`,\n\t\t})\n\n\t\treturn false\n\t}\n\n\tshowCanvasNode(engine, node)\n\treturn true\n}\n\nexport async function editCodeComponentInPlugin(\n\tengine: VekterEngine,\n\tcodeComponentIdentifier: string,\n\tpluginManifest: VekterPluginManifest,\n): Promise<boolean> {\n\tconst isInstanceShown = await showCodeComponentInstanceIfNeeded(engine, codeComponentIdentifier, pluginManifest)\n\tif (!isInstanceShown) return false\n\tvoid engine.stores.pluginStore.openPlugin(pluginManifest, engine, { mode: \"canvas\" })\n\treturn true\n}\n", "import type { ComponentLoader, EntityDefinition } from \"@framerjs/framer-runtime\"\nimport {\n\terrorIdentifierFromModuleIdentifier,\n\tisLocalModuleIdentifier,\n\tisModuleExportIdentifier,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\n\nexport function getEntityDefinitionFromCodeComponentIdentifier(\n\tcomponentLoader: ComponentLoader,\n\tcodeComponentIdentifier: string,\n): EntityDefinition | null {\n\tconst entityDefinition = componentLoader.componentForIdentifier(codeComponentIdentifier)\n\tif (entityDefinition) return entityDefinition\n\t// Retry with error identifier for local module-based code components.\n\tconst identifier = parseModuleIdentifier(codeComponentIdentifier)\n\tif (!isLocalModuleIdentifier(identifier) || !isModuleExportIdentifier(identifier)) return null\n\treturn componentLoader.componentForIdentifier(errorIdentifierFromModuleIdentifier(identifier))\n}\n", "import { parseModuleIdentifier } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { editCodeComponentInPlugin } from \"../utils/editCodeComponentInPlugin.ts\"\nimport { getEntityDefinitionFromCodeComponentIdentifier } from \"../utils/getEntityDefinitionFromCodeComponentIdentifier.ts\"\nimport { getPluginManifestFromModuleIdentifier } from \"../utils/plugins.ts\"\n\nexport enum CodeComponentIsolationMode {\n\tTryPluginFirst,\n\tEditor,\n}\n\nconst defaultCodeComponentIsolationMode = CodeComponentIsolationMode.TryPluginFirst\n\nexport async function enterCodeComponentIsolation(\n\tengine: VekterEngine,\n\tcodeComponentIdentifier: string,\n\tmode: CodeComponentIsolationMode | undefined = defaultCodeComponentIsolationMode,\n): Promise<void> {\n\tif (mode === CodeComponentIsolationMode.TryPluginFirst) {\n\t\tconst identifier = parseModuleIdentifier(codeComponentIdentifier)\n\t\tconst pluginManifest = getPluginManifestFromModuleIdentifier(\n\t\t\tengine.stores.treeStore,\n\t\t\tengine.stores.modulesStore,\n\t\t\tengine.stores.pluginStore,\n\t\t\tidentifier,\n\t\t)\n\t\tif (pluginManifest) {\n\t\t\tconst isEditingInPlugin = await editCodeComponentInPlugin(engine, codeComponentIdentifier, pluginManifest)\n\t\t\tif (isEditingInPlugin) return\n\t\t\t// Fall through to opening in an editor\n\t\t}\n\t}\n\n\tconst entityDefinition = getEntityDefinitionFromCodeComponentIdentifier(\n\t\tengine.componentLoader,\n\t\tcodeComponentIdentifier,\n\t)\n\tif (!entityDefinition) return\n\tengine.stores.codeEditorStore.editFile(entityDefinition.file)\n}\n", "import type { LocalModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { ModuleType, toLocalIdentifier } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { ActiveContentPanelTab } from \"document/utils/ActiveEditorType.ts\"\nimport { analyzeModuleImports } from \"modules/compiler.ts\"\nimport { type AnalyzedImport, ModuleMetadata } from \"modules/types.ts\"\nimport { normalizePath } from \"modules/utils.ts\"\nimport type { InternalImportExternalComponentFunctionOptions } from \"./common.ts\"\nimport { log } from \"./common.ts\"\nimport { enterCodeComponentIsolation } from \"./enterCodeComponentIsolation.ts\"\n\nexport async function importExternalCodeComponent(\n\tengine: VekterEngine,\n\t{\n\t\tidentifier,\n\t\tinfo,\n\t\tinstance,\n\t\tenterIsolation,\n\t\tcodeComponentIsolationMode,\n\t\tscheduleTreeUpdate = task => engine.scheduler.processWhenReadyAsync(task),\n\t}: InternalImportExternalComponentFunctionOptions,\n): Promise<LocalModuleExportIdentifierString> {\n\t// Download the source code of the external code component.\n\tconst sourceURL = info.module.baseURL + info.module.files.source\n\tconst response = await fetch(sourceURL)\n\tlet source = await response.text()\n\t// Replace relative imports in source with absolute ones.\n\t// TODO: This should be optimized further.\n\tconst [imports, dependencies] = await Promise.all([\n\t\tanalyzeModuleImports(source),\n\t\tengine.stores.modulesStore.getModuleDependencies(identifier),\n\t])\n\tif (imports.ok) {\n\t\t// Create a lookup map of normalized code file paths.\n\t\tconst localImports = new Map<string, AnalyzedImport[]>()\n\t\tfor (const relativeImport of imports.value.relative) {\n\t\t\t// Turn the relative import into an absolute one.\n\t\t\tconst key = normalizePath(relativeImport.specifier, `${info.module.type}/`)\n\t\t\tif (!key) {\n\t\t\t\tlog.warn(\"Failed to normalize relative import\", relativeImport.specifier)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Store each import of this type/name pair (usually there's only 1).\n\t\t\tconst list = localImports.get(key) ?? []\n\t\t\tlist.push(relativeImport)\n\t\t\tlocalImports.set(key, list)\n\t\t}\n\t\t// Replace individual imports.\n\t\tlet sourceLines: string[] | undefined\n\t\tfor (const dep of dependencies.imports) {\n\t\t\tif (dep.type !== \"local\") continue\n\t\t\tconst typeSlashName = `${dep.moduleType}/${dep.moduleName}`\n\t\t\tconst locations = localImports.get(typeSlashName)\n\t\t\tif (!locations) {\n\t\t\t\tlog.warn(\"Unable to get source location of import\", typeSlashName, \"when unlinking\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Usually there's only one import location per module but there could be multiple.\n\t\t\tfor (const location of locations) {\n\t\t\t\t// Update the line with the import.\n\t\t\t\tif (!sourceLines) {\n\t\t\t\t\tsourceLines = source.split(\"\\n\")\n\t\t\t\t}\n\t\t\t\tconst i = location.specifierLine\n\t\t\t\tsourceLines[i] = sourceLines[i].replace(JSON.stringify(location.specifier), JSON.stringify(dep.importURL))\n\t\t\t}\n\t\t}\n\t\t// Reassemble the source if we ended up changing it.\n\t\tif (sourceLines) {\n\t\t\tsource = sourceLines.join(\"\\n\")\n\t\t}\n\t}\n\t// Create the new code file, making sure it has a unique name.\n\tconst codeFiles = engine.stores.modulesStore.forType(ModuleType.Code)\n\tconst name = codeFiles.getUniqueName(info.module.name)\n\tconst localId = await codeFiles.create({\n\t\tname,\n\t\tsource,\n\t\tmetadata: { [ModuleMetadata.PluginId]: info.module.metadata[ModuleMetadata.PluginId] },\n\t})\n\tconst codeComponentIdentifier = toLocalIdentifier(identifier, localId).value\n\tif (instance) {\n\t\t// Replace the selected instance with the new local code component.\n\t\tawait scheduleTreeUpdate(() => {\n\t\t\tconst node = engine.tree.get<CodeComponentNode>(instance.getPrimaryId())\n\t\t\tif (!node) return\n\t\t\tnode.set({ codeComponentIdentifier })\n\n\t\t\t// @TODO - It would be nice to remove the external module from the asset panel here,\n\t\t\t// without losing the external module information incase the unlink is undone.\n\t\t})\n\t}\n\tif (enterIsolation) {\n\t\tengine.stores.chromeStore.contentPanelTab = ActiveContentPanelTab.Assets\n\t\tvoid enterCodeComponentIsolation(engine, codeComponentIdentifier, codeComponentIsolationMode)\n\t}\n\n\treturn codeComponentIdentifier\n}\n", "import { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ExternalModuleExportIdentifier, GlobalModuleId, ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, ModuleType } from \"@framerjs/shared\"\nimport { employeesOnlySettings } from \"app/employeesOnlySettings.ts\"\nimport { isFramerVectorInfo, isFramerVectorSetInfo } from \"code-generation/utils/annotations.ts\"\nimport { waitForLoadingComponentsWithTimeout } from \"code-generation/utils/waitForLoadingComponentsWithTimeout.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { CodeComponentNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { moduleIdentifierToLocalComponentId } from \"document/models/CanvasTree/nodes/utils/moduleIdentifierToLocalComponentId.ts\"\nimport {\n\tisCodeComponentNode,\n\tisExternalModuleNode,\n\tisSmartComponentNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { getIsViewOnly } from \"web/pages/project/permissions/isViewOnly.ts\"\nimport { EditBehavior } from \"../chrome/insertSidebar/types.ts\"\nimport { RenamedIds } from \"../tools/utils/updateNodeConnections.ts\"\nimport { isFramerModule } from \"../utils/defaultComponents.ts\"\nimport {\n\tcanReplaceNode,\n\tgetComponentToUseAsReplacement,\n\treplaceNodesWithTemplateAssumingComponentLoaded,\n} from \"../utils/replaceNodes.ts\"\nimport type { InternalImportExternalComponentFunctionOptions, ScheduleUnlinkTreeUpdate } from \"./common.ts\"\nimport { log } from \"./common.ts\"\nimport { type CodeComponentIsolationMode, enterCodeComponentIsolation } from \"./enterCodeComponentIsolation.ts\"\nimport { importExternalCodeComponent } from \"./importExternalCodeComponent.ts\"\nimport { importExternalSmartComponent } from \"./importExternalSmartComponentOrWebpage.ts\"\n\n/** A map of module types to their respective import function. */\nconst componentSourceModuleTypeToImportFunction = {\n\t[ModuleType.Canvas]: importExternalSmartComponent,\n\t[ModuleType.Code]: importExternalCodeComponent,\n} as const\n\ntype ImportableComponentModuleType = keyof typeof componentSourceModuleTypeToImportFunction\n\nexport function isImportableComponentModuleType(type: unknown): type is ImportableComponentModuleType {\n\tif (!isString(type)) return false\n\treturn type in componentSourceModuleTypeToImportFunction\n}\n\nexport interface ImportExternalComponentOptions {\n\tidentifier: ExternalModuleExportIdentifier\n\tmoduleType: ModuleType | string\n\tinstance?: CodeComponentNode\n\tenterIsolation?: boolean\n\tcodeComponentIsolationMode?: CodeComponentIsolationMode\n\trenamedIds?: RenamedIds\n\tisAutoDetach?: boolean\n\tscheduleTreeUpdate?: ScheduleUnlinkTreeUpdate\n\tskipUndoGroup?: boolean\n}\n\nexport async function importExternalComponent(\n\tengine: VekterEngine,\n\t{\n\t\tidentifier,\n\t\tmoduleType,\n\t\tinstance,\n\t\tenterIsolation = true,\n\t\tcodeComponentIsolationMode,\n\t\trenamedIds = new RenamedIds(),\n\t\tisAutoDetach = false,\n\t\tscheduleTreeUpdate,\n\t}: ImportExternalComponentOptions,\n) {\n\tif (!isImportableComponentModuleType(moduleType)) {\n\t\tthrow Error(`Cannot import external module of type ${moduleType}`)\n\t}\n\tconst [info] = await engine.stores.modulesStore.preloadExternalModules([identifier])\n\tassert(info, \"external module must exist on preload\")\n\tconst options: InternalImportExternalComponentFunctionOptions = {\n\t\tidentifier,\n\t\tinfo,\n\t\tinstance,\n\t\tenterIsolation,\n\t\tcodeComponentIsolationMode,\n\t\trenamedIds,\n\t\tisAutoDetach,\n\t\tscheduleTreeUpdate,\n\t}\n\tconst importFunction = componentSourceModuleTypeToImportFunction[moduleType]\n\tconst result = await importFunction(engine, options)\n\n\t// If we can't unlink the component we return undefined.\n\tif (isUndefined(result)) return\n\n\tif (!isString(result) && isSmartComponentNode(result)) {\n\t\treturn { ...info, codeComponentIdentifier: result.instanceIdentifier, node: result }\n\t}\n\n\treturn { ...info, codeComponentIdentifier: result, node: undefined }\n}\n\ntype UnlinkComponentOptions = ImportExternalComponentOptions & { withUnlinkModal?: boolean }\n\nconst beingUnlinked: Set<ExternalModuleExportIdentifier> = new Set()\n\n/**\n * Unlinks a component. If `withUnlinkModal` is `true`, a modal will be\n * displayed, allowing the user to confirm or cancel the action.\n */\nexport async function unlinkComponent(\n\tengine: VekterEngine,\n\toptions: UnlinkComponentOptions,\n): Promise<ModuleExportIdentifierString | undefined> {\n\tconst { instance, withUnlinkModal, ...commonOptions } = options\n\tconst framerModule = isFramerModule(engine.stores.treeStore.tree, options.identifier)\n\tconst editBehavior = engine.stores.insertSidebarStore.getEditBehavior(options.identifier.moduleId)\n\tif (\n\t\twithUnlinkModal &&\n\t\teditBehavior !== EditBehavior.AutoUnlink &&\n\t\t(!framerModule || employeesOnlySettings.isOn(\"openPrimaryForBuiltInModules\"))\n\t) {\n\t\tengine.stores.modalStore.set({\n\t\t\ttype: ModalType.UnlinkComponent,\n\t\t\tsource: \"edit_action\",\n\t\t\t...commonOptions,\n\t\t\tnodeId: instance?.id,\n\t\t})\n\t\treturn\n\t}\n\n\tif (beingUnlinked.has(options.identifier)) return\n\tbeingUnlinked.add(options.identifier)\n\tconst shouldManageUndoGroup = options.skipUndoGroup !== true\n\tif (shouldManageUndoGroup) {\n\t\tengine.scheduler.process(() => {\n\t\t\tengine.beginUndoGroup()\n\t\t})\n\t}\n\n\ttry {\n\t\tconst info = await importExternalComponent(engine, {\n\t\t\tinstance,\n\t\t\tenterIsolation: editBehavior !== EditBehavior.AutoDetach,\n\t\t\t...commonOptions,\n\t\t})\n\t\treturn info?.codeComponentIdentifier\n\t} catch (error) {\n\t\tlog.reportError(error)\n\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tvariant: \"error\",\n\t\t\tprimaryText: \"Failed to unlink\",\n\t\t\tsecondaryText: \"component.\",\n\t\t\tkey: \"external-component-unlink-error\",\n\t\t\ticon: \"error\",\n\t\t})\n\t} finally {\n\t\tif (shouldManageUndoGroup) {\n\t\t\tengine.scheduler.processWhenReady(() => {\n\t\t\t\tengine.endUndoGroup()\n\t\t\t})\n\t\t}\n\t\tbeingUnlinked.delete(options.identifier)\n\t}\n}\n\nexport async function unlinkAndReplaceAll(engine: VekterEngine, options: ImportExternalComponentOptions) {\n\tconst { instance, moduleType, enterIsolation, codeComponentIsolationMode } = options\n\tconst scheduleTreeUpdate = options.scheduleTreeUpdate ?? (task => engine.scheduler.processWhenReadyAsync(task))\n\n\tif (!isCodeComponentNode(instance)) {\n\t\treturn\n\t}\n\n\t// prevent entering isolation before all nodes have been replaced otherwise\n\t// replaceNodeTemplate may throw errors due to the scope change.\n\t// EnterIsolation + onSucess are triggered at the end of this function instead.\n\tconst componentIdentifier = await unlinkComponent(engine, { ...options, enterIsolation: false })\n\tif (!componentIdentifier) return\n\n\tawait waitForLoadingComponentsWithTimeout(engine.componentLoader, [componentIdentifier], engine.stores.modulesStore)\n\n\tconst componentDefinition = engine.componentLoader.componentForIdentifier(componentIdentifier)\n\tif (!componentDefinition) return\n\n\tconst replacementNode = getComponentToUseAsReplacement(componentDefinition)\n\tif (!replacementNode) return\n\n\tawait scheduleTreeUpdate(() => {\n\t\tconst codeComponents = engine.tree.getNodes(Array.from(engine.stores.treeStore.treeIndex.codeComponentNodeIds))\n\n\t\tcodeComponents.forEach(codeComponent => {\n\t\t\tif (!replacementNode) return\n\t\t\t// codeComponents includes the already unlinked component\n\t\t\tif (replacementNode.id === codeComponent.id) return\n\t\t\tif (!isCodeComponentNode(codeComponent)) return\n\t\t\tif (codeComponent.codeComponentIdentifier !== instance.codeComponentIdentifier) return\n\t\t\t// Don\u2019t replace inside replicas & variants, this is not\n\t\t\t// desirable (an instance using a different code component)\n\t\t\t// and not necessary (updating the primary will propagate\n\t\t\t// the update)\n\t\t\tif (isReplicaOrReplicaChild(codeComponent)) return\n\n\t\t\tif (!canReplaceNode(codeComponent, { allowLockedNodes: true })) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst clonedReplacement = engine.cloneNode(replacementNode, false, false)\n\n\t\t\treplaceNodesWithTemplateAssumingComponentLoaded(engine, [codeComponent], clonedReplacement)\n\t\t})\n\n\t\t// @TODO - It would be nice to remove the external module from the asset panel here, without\n\t\t// losing the external module information incase the unlink is undone.\n\n\t\tif (!enterIsolation) return\n\n\t\tif (moduleType === ModuleType.Canvas) {\n\t\t\tconst smartComponentId = moduleIdentifierToLocalComponentId(componentIdentifier)\n\t\t\tif (smartComponentId) {\n\t\t\t\tengine.stores.scopeStore.select(smartComponentId, { keepHistory: false })\n\t\t\t}\n\t\t} else if (moduleType === ModuleType.Code) {\n\t\t\tvoid enterCodeComponentIsolation(engine, componentIdentifier, codeComponentIsolationMode)\n\t\t}\n\t})\n}\n\nexport function showUnlinkVectorSetModal(\n\tengine: VekterEngine,\n\tvectorModuleId: GlobalModuleId,\n\tinstanceNodeId?: NodeID,\n) {\n\tif (getIsViewOnly(engine, \"canDesign\")) return\n\n\tconst vectorNode = engine.tree.getNodeWithTrait(vectorModuleId, isExternalModuleNode)\n\tconst vectorInfo = vectorNode?.annotation(AnnotationKey.FramerVector)\n\n\tif (!isFramerVectorInfo(vectorInfo)) return\n\n\tconst vectorSetModuleId = vectorInfo.set.moduleId\n\tconst setNode = engine.tree.getNodeWithTrait(vectorSetModuleId, isExternalModuleNode)\n\tconst setInfo = setNode?.annotation(AnnotationKey.FramerVectorSet)\n\n\tif (!isFramerVectorSetInfo(setInfo)) return\n\n\tengine.stores.modalStore.set({\n\t\ttype: ModalType.EditVector,\n\t\tsource: \"edit_action\",\n\t\tvectorSetNodeId: vectorSetModuleId,\n\t\tmoduleId: vectorModuleId,\n\t\titemCount: setInfo.items.length,\n\t\tinstanceNodeId,\n\t})\n}\n", "import { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ModulesAPI } from \"@framerjs/framer-services\"\nimport type { ExternalModuleExportIdentifier, LocalModuleExportIdentifier } from \"@framerjs/shared\"\nimport {\n\tassert,\n\tModuleType,\n\tasGlobalId,\n\texternalModuleIdentifier,\n\tgetLogger,\n\tisExternalModuleIdentifier,\n\tisLocalModuleIdentifier,\n\tlocalModuleIdentifier,\n\tunhandledError,\n} from \"@framerjs/shared\"\nimport { isFramerVectorInfo } from \"code-generation/utils/annotations.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport { duplicateWebPage } from \"document/components/chrome/Pages/utils/duplicatePage.ts\"\nimport { insertModuleComponent } from \"document/components/chrome/shared/utils/insertModuleComponent.ts\"\nimport { importExternalWebPageNode } from \"document/components/unlinking/importExternalSmartComponentOrWebpage.ts\"\nimport { importExternalComponent } from \"document/components/unlinking/index.ts\"\nimport type { CodeComponentNode } from \"document/models/CanvasTree/index.ts\"\nimport { moduleIdentifierToLocalComponentId } from \"document/models/CanvasTree/nodes/utils/moduleIdentifierToLocalComponentId.ts\"\nimport { isExternalModuleNode, isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { ExternalComponentInsertType } from \"document/stores/ModulesStore.ts\"\nimport type { Point } from \"library/index.ts\"\nimport { isModuleURL } from \"modules/utils.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\n\nconst log = getLogger(\"clipboard:modules\")\n\nexport async function moduleClipboardHandler(\n\tengine: VekterEngine,\n\ttextClipboardData: string | undefined,\n\tposition: Point,\n): Promise<boolean> {\n\tif (!textClipboardData || !isModuleURL(textClipboardData)) return false\n\n\tconst key = \"insert-external-component\"\n\ttry {\n\t\tawait insertModuleEntity({\n\t\t\tengine,\n\t\t\tmoduleURL: textClipboardData,\n\t\t\tposition,\n\t\t\tcenterInParent: true,\n\t\t\ttoastKey: key,\n\t\t})\n\t\ttoast({ type: \"remove\", key })\n\t} catch (error) {\n\t\t// biome-ignore lint/suspicious/noConsole: <explanation>\n\t\tconsole.error(\"Failed to insert external component\", error)\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tvariant: \"error\",\n\t\t\tkey,\n\t\t\tprimaryText: \"Failed to insert\",\n\t\t\tsecondaryText: \"external component.\",\n\t\t\ticon: \"error\",\n\t\t})\n\t}\n\treturn true\n}\n\ninterface ParsedModule {\n\tmodule: ModulesAPI.ModuleWithSave\n\tmoduleIdentifier: LocalModuleExportIdentifier | ExternalModuleExportIdentifier\n\texternalIdentifier: ExternalModuleExportIdentifier\n\tinsertUnlinked: boolean\n}\n\nfunction getExternalModuleToastSecondaryText(type: string): string {\n\tswitch (type) {\n\t\tcase ModuleType.Screen:\n\t\t\treturn \"web page.\"\n\t\tcase ModuleType.Vector:\n\t\t\treturn \"vector set.\"\n\t\tdefault:\n\t\t\treturn \"external component.\"\n\t}\n}\n\nexport async function lookUpModuleURL(engine: BaseEngine, moduleURL: string): Promise<ParsedModule> {\n\t// FIXME: Improve this logic and move it into ModulesStore.\n\tconst url = new URL(moduleURL)\n\n\t// A module URL can have a hash at the end representing the export specifier.\n\t// For example: https://framer.com/m/framer/Avatar#ShinyAvatar\n\t// URLs can have additional options after the export specifier, separated by commas.\n\t// For example: https://framer.com/m/framer/Avatar#ShinyAvatar,unlink\n\tconst hashValues = url.hash.substring(1).split(\",\")\n\tconst exportSpecifier = hashValues[0] || \"default\"\n\t// If the \"unlink\" option is provided, the component will be inserted unlinked (local).\n\tconst insertUnlinked = hashValues.some((value, i) => i > 0 && value === \"unlink\")\n\n\tconst { module } = await engine.stores.modulesStore.lookUpModule({ url: url.href })\n\tconst moduleId = asGlobalId(module.id)\n\tconst persistedModule = engine.stores.modulesStore.getPersistedModuleByGlobalId(moduleId)\n\tassert(module.files.module, \"Module file must be defined\")\n\tconst externalIdentifier = externalModuleIdentifier(moduleId, module.saveId, module.files.module, exportSpecifier)\n\n\tconst moduleIdentifier = persistedModule\n\t\t? localModuleIdentifier(persistedModule.localId, exportSpecifier)\n\t\t: externalIdentifier\n\n\treturn { module, moduleIdentifier, externalIdentifier, insertUnlinked }\n}\n\nexport async function insertModuleEntity({\n\tengine,\n\tmoduleURL,\n\tposition,\n\tcenterInParent,\n\tinsertAsGroundNode,\n\ttoastKey,\n\tupdate,\n\tparentId,\n}: {\n\tengine: VekterEngine\n\tmoduleURL: string\n\tposition: Point\n\tcenterInParent: boolean\n\tinsertAsGroundNode?: boolean\n\ttoastKey?: string\n\tupdate?: (node: CodeComponentNode) => void\n\tparentId?: string\n}) {\n\tconst { module, moduleIdentifier, externalIdentifier, insertUnlinked } = await lookUpModuleURL(engine, moduleURL)\n\n\tif (module.type === ModuleType.Screen) {\n\t\tif (isLocalModuleIdentifier(moduleIdentifier)) {\n\t\t\t// If the original screen exists in the current project, let's use that tree node.\n\t\t\tconst nodeId = moduleIdentifierToLocalComponentId(moduleIdentifier.value)\n\t\t\tif (!nodeId) return\n\n\t\t\tconst node = engine.tree.getNode(nodeId)\n\t\t\tif (!isWebPageNode(node)) return\n\n\t\t\tawait engine.loadScopesThenProcess([node], ([webPage]) => {\n\t\t\t\tif (!webPage) return\n\n\t\t\t\tduplicateWebPage(engine, webPage, webPage.getPrimaryVariant())\n\t\t\t})\n\t\t} else {\n\t\t\tif (toastKey) {\n\t\t\t\ttoast({\n\t\t\t\t\ttype: \"add\",\n\t\t\t\t\tvariant: \"progress\",\n\t\t\t\t\tkey: toastKey,\n\t\t\t\t\tprimaryText: \"Inserting\",\n\t\t\t\t\tsecondaryText: getExternalModuleToastSecondaryText(module.type),\n\t\t\t\t\ticon: \"reconnecting\",\n\t\t\t\t\tduration: Infinity,\n\t\t\t\t\tshowCloseButton: \"never\",\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait importExternalWebPageNode(engine, externalIdentifier)\n\t\t}\n\t} else if (insertUnlinked) {\n\t\tif (toastKey) {\n\t\t\ttoast({\n\t\t\t\ttype: \"add\",\n\t\t\t\tvariant: \"progress\",\n\t\t\t\tkey: toastKey,\n\t\t\t\tprimaryText: \"Inserting\",\n\t\t\t\tsecondaryText: getExternalModuleToastSecondaryText(module.type),\n\t\t\t\ticon: \"reconnecting\",\n\t\t\t\tduration: Infinity,\n\t\t\t\tshowCloseButton: \"never\",\n\t\t\t})\n\t\t}\n\t\tconst info = await importExternalComponent(engine, {\n\t\t\tidentifier: externalIdentifier,\n\t\t\tmoduleType: module.type,\n\t\t\tenterIsolation: false,\n\t\t})\n\t\tawait engine.scheduler.processWhenReadyAsync(() => {\n\t\t\tif (!info) return\n\n\t\t\tinsertModuleComponent({\n\t\t\t\tengine,\n\t\t\t\tmodule,\n\t\t\t\tidentifier: info.codeComponentIdentifier,\n\t\t\t\tposition,\n\t\t\t\tcenterInParent,\n\t\t\t\tinsertAsGroundNode,\n\t\t\t\tupdate,\n\t\t\t\tparentId,\n\t\t\t})\n\t\t})\n\t} else {\n\t\tif (toastKey) {\n\t\t\ttoast({\n\t\t\t\ttype: \"add\",\n\t\t\t\tvariant: \"progress\",\n\t\t\t\tkey: toastKey,\n\t\t\t\tprimaryText: \"Inserting\",\n\t\t\t\tsecondaryText: getExternalModuleToastSecondaryText(module.type),\n\t\t\t\ticon: \"reconnecting\",\n\t\t\t\tduration: Infinity,\n\t\t\t\tshowCloseButton: \"never\",\n\t\t\t})\n\t\t}\n\t\t// TODO: This should insert using same rules as regular paste.\n\t\tif (!isExternalModuleIdentifier(moduleIdentifier)) {\n\t\t\tawait engine.scheduler.processWhenReadyAsync(() => {\n\t\t\t\tinsertModuleComponent({\n\t\t\t\t\tengine,\n\t\t\t\t\tmodule,\n\t\t\t\t\tidentifier: moduleIdentifier.value,\n\t\t\t\t\tposition,\n\t\t\t\t\tcenterInParent,\n\t\t\t\t\tinsertAsGroundNode,\n\t\t\t\t\tupdate,\n\t\t\t\t\tparentId,\n\t\t\t\t})\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Make sure the component is added to the components panel.\n\t\tawait engine.stores.modulesStore\n\t\t\t.addExternalModulesToProject([moduleIdentifier], {\n\t\t\t\tonTreeUpdate: () => {\n\t\t\t\t\tinsertModuleComponent({\n\t\t\t\t\t\tengine,\n\t\t\t\t\t\tmodule,\n\t\t\t\t\t\tidentifier: moduleIdentifier.value,\n\t\t\t\t\t\tposition,\n\t\t\t\t\t\tcenterInParent,\n\t\t\t\t\t\tinsertAsGroundNode,\n\t\t\t\t\t\tupdate,\n\t\t\t\t\t\tparentId,\n\t\t\t\t\t})\n\n\t\t\t\t\tif (module.type !== ModuleType.Vector) return\n\n\t\t\t\t\t// When an external Vector URL is pasted, we need to add the entire set to the\n\t\t\t\t\t// project. We add the latest version of the set even if the pasted Vector is\n\t\t\t\t\t// not the latest version. This is a trade off for simplicity.\n\t\t\t\t\tconst annotation = engine.tree\n\t\t\t\t\t\t.getNodeWithTrait(module.id, isExternalModuleNode)\n\t\t\t\t\t\t?.annotation(AnnotationKey.FramerVector)\n\n\t\t\t\t\tif (!isFramerVectorInfo(annotation)) return\n\n\t\t\t\t\tengine.stores.modulesStore\n\t\t\t\t\t\t.addOrUpdateVectorSetAndVectors({ moduleId: annotation.set.moduleId, saveId: \"\" })\n\t\t\t\t\t\t.catch(unhandledError)\n\t\t\t\t},\n\t\t\t})\n\t\t\t.catch(log.reportError)\n\n\t\tengine.stores.modulesStore.trackExternalComponentInsert(\n\t\t\t[moduleIdentifier.value],\n\t\t\tExternalComponentInsertType.pasteURL,\n\t\t)\n\t}\n\n\treturn module\n}\n", "import type { ModulesAPI } from \"@framerjs/framer-services\"\nimport {\n\tModuleType,\n\tassert,\n\ttype ExternalModuleExportIdentifier,\n\ttype ModuleExportIdentifierString,\n\tasGlobalId,\n\texternalModuleIdentifier,\n\tisExternalModuleIdentifier,\n\tisLocalModuleIdentifier,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport type { CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isExternalModuleNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { lookUpModuleURL } from \"utils/clipboard/helpers/modules.ts\"\nimport { type ModuleComponent, getLookupQueryForModuleComponent, moduleComponents } from \"utils/moduleComponents.ts\"\n\nconst cmsModuleComponents: ModuleComponent[] = [\n\tmoduleComponents.youtube,\n\tmoduleComponents.vimeo,\n\tmoduleComponents.codeblock,\n\tmoduleComponents.twitter,\n]\n\nexport function isCanvasModuleIdentifier(engine: BaseEngine, identifier: ModuleExportIdentifierString): boolean {\n\tconst parsedIdentifier = parseModuleIdentifier(identifier)\n\n\tif (isLocalModuleIdentifier(parsedIdentifier)) {\n\t\treturn parsedIdentifier.type === ModuleType.Canvas\n\t}\n\n\tif (!isExternalModuleIdentifier(parsedIdentifier)) return false\n\n\tconst moduleNode = engine.tree.getNodeWithTrait(parsedIdentifier.moduleId, isExternalModuleNode)\n\treturn moduleNode?.type === ModuleType.Canvas\n}\n\nexport async function addModule(engine: BaseEngine, identifier: ModuleExportIdentifierString) {\n\tconst parsedIdentifier = parseModuleIdentifier(identifier)\n\n\tif (isExternalModuleIdentifier(parsedIdentifier)) {\n\t\tawait engine.stores.modulesStore.addExternalModulesToProject([parsedIdentifier], {\n\t\t\tonTreeUpdate() {},\n\t\t})\n\t}\n}\n\nconst preloadedModules = new WeakMap<ModuleComponent, ModulesAPI.ModuleWithSave>()\n\nexport async function preloadModuleComponents(engine: BaseEngine) {\n\tconst { modules } = await engine.stores.modulesStore.lookUpModules(\n\t\tcmsModuleComponents.map(getLookupQueryForModuleComponent),\n\t)\n\n\tconst moduleIdentifiers: ExternalModuleExportIdentifier[] = []\n\n\tfor (let i = 0; i < modules.length; i++) {\n\t\tconst module = modules[i]\n\t\tassert(module, \"Module must exist\")\n\n\t\tconst moduleComponent = cmsModuleComponents[i]\n\t\tassert(moduleComponent, \"Module component must exist\")\n\n\t\tpreloadedModules.set(moduleComponent, module)\n\n\t\tassert(module.files.module, \"Module must have a module file\")\n\n\t\tmoduleIdentifiers.push(\n\t\t\texternalModuleIdentifier(\n\t\t\t\tasGlobalId(module.id),\n\t\t\t\tmodule.saveId,\n\t\t\t\tmodule.files.module,\n\t\t\t\tmoduleComponent.exportSpecifier ?? \"default\",\n\t\t\t),\n\t\t)\n\t}\n\n\tawait engine.stores.modulesStore.preloadExternalModules(moduleIdentifiers)\n}\n\nexport function getPreloadedModuleIdentifier(tree: CanvasTree, moduleComponent: ModuleComponent) {\n\tconst module = preloadedModules.get(moduleComponent)\n\tassert(module, \"Preloaded module must exist\")\n\n\tconst moduleNode = tree.getNodeWithTrait(module.id, isExternalModuleNode)\n\tif (moduleNode) return moduleNode.codeComponentIdentifier\n\n\tassert(module.files.module, \"Module must have a module file\")\n\n\treturn externalModuleIdentifier(\n\t\tasGlobalId(module.id),\n\t\tmodule.saveId,\n\t\tmodule.files.module,\n\t\tmoduleComponent.exportSpecifier ?? \"default\",\n\t).value\n}\n\nexport async function getModuleIdentifierForURL(engine: BaseEngine, moduleURL: string) {\n\tconst { moduleIdentifier } = await lookUpModuleURL(engine, moduleURL)\n\n\tif (moduleIdentifier.kind === \"externalModuleExport\") {\n\t\tconst moduleNode = engine.tree.getNodeWithTrait(moduleIdentifier.moduleId, isExternalModuleNode)\n\t\tif (moduleNode) return moduleNode.codeComponentIdentifier\n\t}\n\n\treturn moduleIdentifier.value\n}\n", "import { isOnlyVisibleInCurrentVariant } from \"code-generation/utils/isOnlyVisibleInCurrentVariant.ts\"\nimport type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport type { MaybeNodeID, NodeID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { WithVisibility } from \"document/models/CanvasTree/traits/WithVisibility.ts\"\nimport { TemplateHelper, generateReplicaChildId } from \"../TemplateHelper.ts\"\nimport { updateReplicaNodeOverrides } from \"./updateReplicaOverrides.ts\"\n\n/**\n * Wraps any node-insertion code to handle inserting nodes into replicas.\n *\n * Ordinarily, you can't \"just\" insert a node into a replica. Instead, you're\n * expected to insert it into master, and tweak the replica's visbility\n * overrides for that node. This wrapper does that for you.\n *\n * @param parentId Parent to insert the node into. If the parent is part of a replica, this wrapper will do its magic.\n * @param insertNode Your code for inserting the node into the tree. Use the provided parent and props, and return the node's ID.\n */\nexport function insertNodeAccountingForReplicas(\n\ttree: CanvasTree,\n\tparentId: MaybeNodeID,\n\tinsertNode: (\n\t\ttargetParentId: MaybeNodeID,\n\t\tvisibilityProps: Partial<WithVisibility>,\n\t\taddingToReplica: boolean,\n\t) => NodeID,\n): NodeID {\n\tconst parent = parentId && tree.getNode(parentId)\n\tif (!parent || !isReplicaOrReplicaChild(parent)) {\n\t\treturn insertNode(parentId, {}, false)\n\t}\n\n\t// If the parent is only visible in its own replica, then there's no need to\n\t// apply additional visibility overrides to the new node.\n\t//\n\t// Otherwise, we need to make the new node hidden in master, and later\n\t// override its visibility in just the single replica that we're inserting\n\t// into.\n\tconst visibilityProps = isOnlyVisibleInCurrentVariant(tree, parent) ? {} : { visible: false }\n\tconst newId = insertNode(parent.originalid, visibilityProps, true)\n\n\tconst replica = TemplateHelper.getReplicaForTemplateNode(tree, parent)\n\tif (replica) {\n\t\tif (visibilityProps.visible === false) {\n\t\t\tupdateReplicaNodeOverrides(tree, replica, newId, { visible: true })\n\t\t}\n\t\treturn generateReplicaChildId(replica.id, newId)\n\t}\n\n\treturn newId\n}\n", "/**\n * @typedef CoreOptions\n * @property {ReadonlyArray<string>} [subset=[]]\n *   Whether to only escape the given subset of characters.\n * @property {boolean} [escapeOnly=false]\n *   Whether to only escape possibly dangerous characters.\n *   Those characters are `\"`, `&`, `'`, `<`, `>`, and `` ` ``.\n *\n * @typedef FormatOptions\n * @property {(code: number, next: number, options: CoreWithFormatOptions) => string} format\n *   Format strategy.\n *\n * @typedef {CoreOptions & FormatOptions & import('./util/format-smart.js').FormatSmartOptions} CoreWithFormatOptions\n */\n\nconst defaultSubsetRegex = /[\"&'<>`]/g\nconst surrogatePairsRegex = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g\nconst controlCharactersRegex =\n  // eslint-disable-next-line no-control-regex, unicorn/no-hex-escape\n  /[\\x01-\\t\\v\\f\\x0E-\\x1F\\x7F\\x81\\x8D\\x8F\\x90\\x9D\\xA0-\\uFFFF]/g\nconst regexEscapeRegex = /[|\\\\{}()[\\]^$+*?.]/g\n\n/** @type {WeakMap<ReadonlyArray<string>, RegExp>} */\nconst subsetToRegexCache = new WeakMap()\n\n/**\n * Encode certain characters in `value`.\n *\n * @param {string} value\n * @param {CoreWithFormatOptions} options\n * @returns {string}\n */\nexport function core(value, options) {\n  value = value.replace(\n    options.subset\n      ? charactersToExpressionCached(options.subset)\n      : defaultSubsetRegex,\n    basic\n  )\n\n  if (options.subset || options.escapeOnly) {\n    return value\n  }\n\n  return (\n    value\n      // Surrogate pairs.\n      .replace(surrogatePairsRegex, surrogate)\n      // BMP control characters (C0 except for LF, CR, SP; DEL; and some more\n      // non-ASCII ones).\n      .replace(controlCharactersRegex, basic)\n  )\n\n  /**\n   * @param {string} pair\n   * @param {number} index\n   * @param {string} all\n   */\n  function surrogate(pair, index, all) {\n    return options.format(\n      (pair.charCodeAt(0) - 0xd800) * 0x400 +\n        pair.charCodeAt(1) -\n        0xdc00 +\n        0x10000,\n      all.charCodeAt(index + 2),\n      options\n    )\n  }\n\n  /**\n   * @param {string} character\n   * @param {number} index\n   * @param {string} all\n   */\n  function basic(character, index, all) {\n    return options.format(\n      character.charCodeAt(0),\n      all.charCodeAt(index + 1),\n      options\n    )\n  }\n}\n\n/**\n * A wrapper function that caches the result of `charactersToExpression` with a WeakMap.\n * This can improve performance when tooling calls `charactersToExpression` repeatedly\n * with the same subset.\n *\n * @param {ReadonlyArray<string>} subset\n * @returns {RegExp}\n */\nfunction charactersToExpressionCached(subset) {\n  let cached = subsetToRegexCache.get(subset)\n\n  if (!cached) {\n    cached = charactersToExpression(subset)\n    subsetToRegexCache.set(subset, cached)\n  }\n\n  return cached\n}\n\n/**\n * @param {ReadonlyArray<string>} subset\n * @returns {RegExp}\n */\nfunction charactersToExpression(subset) {\n  /** @type {Array<string>} */\n  const groups = []\n  let index = -1\n\n  while (++index < subset.length) {\n    groups.push(subset[index].replace(regexEscapeRegex, '\\\\$&'))\n  }\n\n  return new RegExp('(?:' + groups.join('|') + ')', 'g')\n}\n", "const hexadecimalRegex = /[\\dA-Fa-f]/\n\n/**\n * Configurable ways to encode characters as hexadecimal references.\n *\n * @param {number} code\n * @param {number} next\n * @param {boolean|undefined} omit\n * @returns {string}\n */\nexport function toHexadecimal(code, next, omit) {\n  const value = '&#x' + code.toString(16).toUpperCase()\n  return omit && next && !hexadecimalRegex.test(String.fromCharCode(next))\n    ? value\n    : value + ';'\n}\n", "const decimalRegex = /\\d/\n\n/**\n * Configurable ways to encode characters as decimal references.\n *\n * @param {number} code\n * @param {number} next\n * @param {boolean|undefined} omit\n * @returns {string}\n */\nexport function toDecimal(code, next, omit) {\n  const value = '&#' + String(code)\n  return omit && next && !decimalRegex.test(String.fromCharCode(next))\n    ? value\n    : value + ';'\n}\n", "/**\n * List of legacy HTML named character references that don\u2019t need a trailing semicolon.\n *\n * @type {Array<string>}\n */\nexport const characterEntitiesLegacy = [\n  'AElig',\n  'AMP',\n  'Aacute',\n  'Acirc',\n  'Agrave',\n  'Aring',\n  'Atilde',\n  'Auml',\n  'COPY',\n  'Ccedil',\n  'ETH',\n  'Eacute',\n  'Ecirc',\n  'Egrave',\n  'Euml',\n  'GT',\n  'Iacute',\n  'Icirc',\n  'Igrave',\n  'Iuml',\n  'LT',\n  'Ntilde',\n  'Oacute',\n  'Ocirc',\n  'Ograve',\n  'Oslash',\n  'Otilde',\n  'Ouml',\n  'QUOT',\n  'REG',\n  'THORN',\n  'Uacute',\n  'Ucirc',\n  'Ugrave',\n  'Uuml',\n  'Yacute',\n  'aacute',\n  'acirc',\n  'acute',\n  'aelig',\n  'agrave',\n  'amp',\n  'aring',\n  'atilde',\n  'auml',\n  'brvbar',\n  'ccedil',\n  'cedil',\n  'cent',\n  'copy',\n  'curren',\n  'deg',\n  'divide',\n  'eacute',\n  'ecirc',\n  'egrave',\n  'eth',\n  'euml',\n  'frac12',\n  'frac14',\n  'frac34',\n  'gt',\n  'iacute',\n  'icirc',\n  'iexcl',\n  'igrave',\n  'iquest',\n  'iuml',\n  'laquo',\n  'lt',\n  'macr',\n  'micro',\n  'middot',\n  'nbsp',\n  'not',\n  'ntilde',\n  'oacute',\n  'ocirc',\n  'ograve',\n  'ordf',\n  'ordm',\n  'oslash',\n  'otilde',\n  'ouml',\n  'para',\n  'plusmn',\n  'pound',\n  'quot',\n  'raquo',\n  'reg',\n  'sect',\n  'shy',\n  'sup1',\n  'sup2',\n  'sup3',\n  'szlig',\n  'thorn',\n  'times',\n  'uacute',\n  'ucirc',\n  'ugrave',\n  'uml',\n  'uuml',\n  'yacute',\n  'yen',\n  'yuml'\n]\n", "/**\n * Map of named character references from HTML 4.\n *\n * @type {Record<string, string>}\n */\nexport const characterEntitiesHtml4 = {\n  nbsp: '\u00A0',\n  iexcl: '\u00A1',\n  cent: '\u00A2',\n  pound: '\u00A3',\n  curren: '\u00A4',\n  yen: '\u00A5',\n  brvbar: '\u00A6',\n  sect: '\u00A7',\n  uml: '\u00A8',\n  copy: '\u00A9',\n  ordf: '\u00AA',\n  laquo: '\u00AB',\n  not: '\u00AC',\n  shy: '\u00AD',\n  reg: '\u00AE',\n  macr: '\u00AF',\n  deg: '\u00B0',\n  plusmn: '\u00B1',\n  sup2: '\u00B2',\n  sup3: '\u00B3',\n  acute: '\u00B4',\n  micro: '\u00B5',\n  para: '\u00B6',\n  middot: '\u00B7',\n  cedil: '\u00B8',\n  sup1: '\u00B9',\n  ordm: '\u00BA',\n  raquo: '\u00BB',\n  frac14: '\u00BC',\n  frac12: '\u00BD',\n  frac34: '\u00BE',\n  iquest: '\u00BF',\n  Agrave: '\u00C0',\n  Aacute: '\u00C1',\n  Acirc: '\u00C2',\n  Atilde: '\u00C3',\n  Auml: '\u00C4',\n  Aring: '\u00C5',\n  AElig: '\u00C6',\n  Ccedil: '\u00C7',\n  Egrave: '\u00C8',\n  Eacute: '\u00C9',\n  Ecirc: '\u00CA',\n  Euml: '\u00CB',\n  Igrave: '\u00CC',\n  Iacute: '\u00CD',\n  Icirc: '\u00CE',\n  Iuml: '\u00CF',\n  ETH: '\u00D0',\n  Ntilde: '\u00D1',\n  Ograve: '\u00D2',\n  Oacute: '\u00D3',\n  Ocirc: '\u00D4',\n  Otilde: '\u00D5',\n  Ouml: '\u00D6',\n  times: '\u00D7',\n  Oslash: '\u00D8',\n  Ugrave: '\u00D9',\n  Uacute: '\u00DA',\n  Ucirc: '\u00DB',\n  Uuml: '\u00DC',\n  Yacute: '\u00DD',\n  THORN: '\u00DE',\n  szlig: '\u00DF',\n  agrave: '\u00E0',\n  aacute: '\u00E1',\n  acirc: '\u00E2',\n  atilde: '\u00E3',\n  auml: '\u00E4',\n  aring: '\u00E5',\n  aelig: '\u00E6',\n  ccedil: '\u00E7',\n  egrave: '\u00E8',\n  eacute: '\u00E9',\n  ecirc: '\u00EA',\n  euml: '\u00EB',\n  igrave: '\u00EC',\n  iacute: '\u00ED',\n  icirc: '\u00EE',\n  iuml: '\u00EF',\n  eth: '\u00F0',\n  ntilde: '\u00F1',\n  ograve: '\u00F2',\n  oacute: '\u00F3',\n  ocirc: '\u00F4',\n  otilde: '\u00F5',\n  ouml: '\u00F6',\n  divide: '\u00F7',\n  oslash: '\u00F8',\n  ugrave: '\u00F9',\n  uacute: '\u00FA',\n  ucirc: '\u00FB',\n  uuml: '\u00FC',\n  yacute: '\u00FD',\n  thorn: '\u00FE',\n  yuml: '\u00FF',\n  fnof: '\u0192',\n  Alpha: '\u0391',\n  Beta: '\u0392',\n  Gamma: '\u0393',\n  Delta: '\u0394',\n  Epsilon: '\u0395',\n  Zeta: '\u0396',\n  Eta: '\u0397',\n  Theta: '\u0398',\n  Iota: '\u0399',\n  Kappa: '\u039A',\n  Lambda: '\u039B',\n  Mu: '\u039C',\n  Nu: '\u039D',\n  Xi: '\u039E',\n  Omicron: '\u039F',\n  Pi: '\u03A0',\n  Rho: '\u03A1',\n  Sigma: '\u03A3',\n  Tau: '\u03A4',\n  Upsilon: '\u03A5',\n  Phi: '\u03A6',\n  Chi: '\u03A7',\n  Psi: '\u03A8',\n  Omega: '\u03A9',\n  alpha: '\u03B1',\n  beta: '\u03B2',\n  gamma: '\u03B3',\n  delta: '\u03B4',\n  epsilon: '\u03B5',\n  zeta: '\u03B6',\n  eta: '\u03B7',\n  theta: '\u03B8',\n  iota: '\u03B9',\n  kappa: '\u03BA',\n  lambda: '\u03BB',\n  mu: '\u03BC',\n  nu: '\u03BD',\n  xi: '\u03BE',\n  omicron: '\u03BF',\n  pi: '\u03C0',\n  rho: '\u03C1',\n  sigmaf: '\u03C2',\n  sigma: '\u03C3',\n  tau: '\u03C4',\n  upsilon: '\u03C5',\n  phi: '\u03C6',\n  chi: '\u03C7',\n  psi: '\u03C8',\n  omega: '\u03C9',\n  thetasym: '\u03D1',\n  upsih: '\u03D2',\n  piv: '\u03D6',\n  bull: '\u2022',\n  hellip: '\u2026',\n  prime: '\u2032',\n  Prime: '\u2033',\n  oline: '\u203E',\n  frasl: '\u2044',\n  weierp: '\u2118',\n  image: '\u2111',\n  real: '\u211C',\n  trade: '\u2122',\n  alefsym: '\u2135',\n  larr: '\u2190',\n  uarr: '\u2191',\n  rarr: '\u2192',\n  darr: '\u2193',\n  harr: '\u2194',\n  crarr: '\u21B5',\n  lArr: '\u21D0',\n  uArr: '\u21D1',\n  rArr: '\u21D2',\n  dArr: '\u21D3',\n  hArr: '\u21D4',\n  forall: '\u2200',\n  part: '\u2202',\n  exist: '\u2203',\n  empty: '\u2205',\n  nabla: '\u2207',\n  isin: '\u2208',\n  notin: '\u2209',\n  ni: '\u220B',\n  prod: '\u220F',\n  sum: '\u2211',\n  minus: '\u2212',\n  lowast: '\u2217',\n  radic: '\u221A',\n  prop: '\u221D',\n  infin: '\u221E',\n  ang: '\u2220',\n  and: '\u2227',\n  or: '\u2228',\n  cap: '\u2229',\n  cup: '\u222A',\n  int: '\u222B',\n  there4: '\u2234',\n  sim: '\u223C',\n  cong: '\u2245',\n  asymp: '\u2248',\n  ne: '\u2260',\n  equiv: '\u2261',\n  le: '\u2264',\n  ge: '\u2265',\n  sub: '\u2282',\n  sup: '\u2283',\n  nsub: '\u2284',\n  sube: '\u2286',\n  supe: '\u2287',\n  oplus: '\u2295',\n  otimes: '\u2297',\n  perp: '\u22A5',\n  sdot: '\u22C5',\n  lceil: '\u2308',\n  rceil: '\u2309',\n  lfloor: '\u230A',\n  rfloor: '\u230B',\n  lang: '\u2329',\n  rang: '\u232A',\n  loz: '\u25CA',\n  spades: '\u2660',\n  clubs: '\u2663',\n  hearts: '\u2665',\n  diams: '\u2666',\n  quot: '\"',\n  amp: '&',\n  lt: '<',\n  gt: '>',\n  OElig: '\u0152',\n  oelig: '\u0153',\n  Scaron: '\u0160',\n  scaron: '\u0161',\n  Yuml: '\u0178',\n  circ: '\u02C6',\n  tilde: '\u02DC',\n  ensp: '\u2002',\n  emsp: '\u2003',\n  thinsp: '\u2009',\n  zwnj: '\u200C',\n  zwj: '\u200D',\n  lrm: '\u200E',\n  rlm: '\u200F',\n  ndash: '\u2013',\n  mdash: '\u2014',\n  lsquo: '\u2018',\n  rsquo: '\u2019',\n  sbquo: '\u201A',\n  ldquo: '\u201C',\n  rdquo: '\u201D',\n  bdquo: '\u201E',\n  dagger: '\u2020',\n  Dagger: '\u2021',\n  permil: '\u2030',\n  lsaquo: '\u2039',\n  rsaquo: '\u203A',\n  euro: '\u20AC'\n}\n", "/**\n * List of legacy (that don\u2019t need a trailing `;`) named references which could,\n * depending on what follows them, turn into a different meaning\n *\n * @type {Array<string>}\n */\nexport const dangerous = [\n  'cent',\n  'copy',\n  'divide',\n  'gt',\n  'lt',\n  'not',\n  'para',\n  'times'\n]\n", "import {characterEntitiesLegacy} from 'character-entities-legacy'\nimport {characterEntitiesHtml4} from 'character-entities-html4'\nimport {dangerous} from '../constant/dangerous.js'\n\nconst own = {}.hasOwnProperty\n\n/**\n * `characterEntitiesHtml4` but inverted.\n *\n * @type {Record<string, string>}\n */\nconst characters = {}\n\n/** @type {string} */\nlet key\n\nfor (key in characterEntitiesHtml4) {\n  if (own.call(characterEntitiesHtml4, key)) {\n    characters[characterEntitiesHtml4[key]] = key\n  }\n}\n\nconst notAlphanumericRegex = /[^\\dA-Za-z]/\n\n/**\n * Configurable ways to encode characters as named references.\n *\n * @param {number} code\n * @param {number} next\n * @param {boolean|undefined} omit\n * @param {boolean|undefined} attribute\n * @returns {string}\n */\nexport function toNamed(code, next, omit, attribute) {\n  const character = String.fromCharCode(code)\n\n  if (own.call(characters, character)) {\n    const name = characters[character]\n    const value = '&' + name\n\n    if (\n      omit &&\n      characterEntitiesLegacy.includes(name) &&\n      !dangerous.includes(name) &&\n      (!attribute ||\n        (next &&\n          next !== 61 /* `=` */ &&\n          notAlphanumericRegex.test(String.fromCharCode(next))))\n    ) {\n      return value\n    }\n\n    return value + ';'\n  }\n\n  return ''\n}\n", "/**\n * @typedef FormatSmartOptions\n * @property {boolean} [useNamedReferences=false]\n *   Prefer named character references (`&amp;`) where possible.\n * @property {boolean} [useShortestReferences=false]\n *   Prefer the shortest possible reference, if that results in less bytes.\n *   **Note**: `useNamedReferences` can be omitted when using `useShortestReferences`.\n * @property {boolean} [omitOptionalSemicolons=false]\n *   Whether to omit semicolons when possible.\n *   **Note**: This creates what HTML calls \u201Cparse errors\u201D but is otherwise still valid HTML \u2014 don\u2019t use this except when building a minifier.\n *   Omitting semicolons is possible for certain named and numeric references in some cases.\n * @property {boolean} [attribute=false]\n *   Create character references which don\u2019t fail in attributes.\n *   **Note**: `attribute` only applies when operating dangerously with\n *   `omitOptionalSemicolons: true`.\n */\n\nimport {toHexadecimal} from './to-hexadecimal.js'\nimport {toDecimal} from './to-decimal.js'\nimport {toNamed} from './to-named.js'\n\n/**\n * Configurable ways to encode a character yielding pretty or small results.\n *\n * @param {number} code\n * @param {number} next\n * @param {FormatSmartOptions} options\n * @returns {string}\n */\nexport function formatSmart(code, next, options) {\n  let numeric = toHexadecimal(code, next, options.omitOptionalSemicolons)\n  /** @type {string|undefined} */\n  let named\n\n  if (options.useNamedReferences || options.useShortestReferences) {\n    named = toNamed(\n      code,\n      next,\n      options.omitOptionalSemicolons,\n      options.attribute\n    )\n  }\n\n  // Use the shortest numeric reference when requested.\n  // A simple algorithm would use decimal for all code points under 100, as\n  // those are shorter than hexadecimal:\n  //\n  // * `&#99;` vs `&#x63;` (decimal shorter)\n  // * `&#100;` vs `&#x64;` (equal)\n  //\n  // However, because we take `next` into consideration when `omit` is used,\n  // And it would be possible that decimals are shorter on bigger values as\n  // well if `next` is hexadecimal but not decimal, we instead compare both.\n  if (\n    (options.useShortestReferences || !named) &&\n    options.useShortestReferences\n  ) {\n    const decimal = toDecimal(code, next, options.omitOptionalSemicolons)\n\n    if (decimal.length < numeric.length) {\n      numeric = decimal\n    }\n  }\n\n  return named &&\n    (!options.useShortestReferences || named.length < numeric.length)\n    ? named\n    : numeric\n}\n", "/**\n * @typedef {import('./core.js').CoreOptions & import('./util/format-smart.js').FormatSmartOptions} Options\n * @typedef {import('./core.js').CoreOptions} LightOptions\n */\n\nimport {core} from './core.js'\nimport {formatSmart} from './util/format-smart.js'\nimport {formatBasic} from './util/format-basic.js'\n\n/**\n * Encode special characters in `value`.\n *\n * @param {string} value\n *   Value to encode.\n * @param {Options} [options]\n *   Configuration.\n * @returns {string}\n *   Encoded value.\n */\nexport function stringifyEntities(value, options) {\n  return core(value, Object.assign({format: formatSmart}, options))\n}\n\n/**\n * Encode special characters in `value` as hexadecimals.\n *\n * @param {string} value\n *   Value to encode.\n * @param {LightOptions} [options]\n *   Configuration.\n * @returns {string}\n *   Encoded value.\n */\nexport function stringifyEntitiesLight(value, options) {\n  return core(value, Object.assign({format: formatBasic}, options))\n}\n", "/**\n * @import {Comment, Parents} from 'hast'\n * @import {State} from '../index.js'\n */\n\nimport {stringifyEntities} from 'stringify-entities'\n\nconst htmlCommentRegex = /^>|^->|<!--|-->|--!>|<!-$/g\n\n// Declare arrays as variables so it can be cached by `stringifyEntities`\nconst bogusCommentEntitySubset = ['>']\nconst commentEntitySubset = ['<', '>']\n\n/**\n * Serialize a comment.\n *\n * @param {Comment} node\n *   Node to handle.\n * @param {number | undefined} _1\n *   Index of `node` in `parent.\n * @param {Parents | undefined} _2\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function comment(node, _1, _2, state) {\n  // See: <https://html.spec.whatwg.org/multipage/syntax.html#comments>\n  return state.settings.bogusComments\n    ? '<?' +\n        stringifyEntities(\n          node.value,\n          Object.assign({}, state.settings.characterReferences, {\n            subset: bogusCommentEntitySubset\n          })\n        ) +\n        '>'\n    : '<!--' + node.value.replace(htmlCommentRegex, encode) + '-->'\n\n  /**\n   * @param {string} $0\n   */\n  function encode($0) {\n    return stringifyEntities(\n      $0,\n      Object.assign({}, state.settings.characterReferences, {\n        subset: commentEntitySubset\n      })\n    )\n  }\n}\n", "/**\n * @import {Doctype, Parents} from 'hast'\n * @import {State} from '../index.js'\n */\n\n/**\n * Serialize a doctype.\n *\n * @param {Doctype} _1\n *   Node to handle.\n * @param {number | undefined} _2\n *   Index of `node` in `parent.\n * @param {Parents | undefined} _3\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function doctype(_1, _2, _3, state) {\n  return (\n    '<!' +\n    (state.settings.upperDoctype ? 'DOCTYPE' : 'doctype') +\n    (state.settings.tightDoctype ? '' : ' ') +\n    'html>'\n  )\n}\n", "/**\n * @import {Parents, RootContent} from 'hast'\n */\n\nimport {whitespace} from 'hast-util-whitespace'\n\nexport const siblingAfter = siblings(1)\nexport const siblingBefore = siblings(-1)\n\n/** @type {Array<RootContent>} */\nconst emptyChildren = []\n\n/**\n * Factory to check siblings in a direction.\n *\n * @param {number} increment\n */\nfunction siblings(increment) {\n  return sibling\n\n  /**\n   * Find applicable siblings in a direction.\n   *\n   * @template {Parents} Parent\n   *   Parent type.\n   * @param {Parent | undefined} parent\n   *   Parent.\n   * @param {number | undefined} index\n   *   Index of child in `parent`.\n   * @param {boolean | undefined} [includeWhitespace=false]\n   *   Whether to include whitespace (default: `false`).\n   * @returns {Parent extends {children: Array<infer Child>} ? Child | undefined : never}\n   *   Child of parent.\n   */\n  function sibling(parent, index, includeWhitespace) {\n    const siblings = parent ? parent.children : emptyChildren\n    let offset = (index || 0) + increment\n    let next = siblings[offset]\n\n    if (!includeWhitespace) {\n      while (next && whitespace(next)) {\n        offset += increment\n        next = siblings[offset]\n      }\n    }\n\n    // @ts-expect-error: it\u2019s a correct child.\n    return next\n  }\n}\n", "/**\n * @import {Element, Parents} from 'hast'\n */\n\n/**\n * @callback OmitHandle\n *   Check if a tag can be omitted.\n * @param {Element} element\n *   Element to check.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether to omit a tag.\n *\n */\n\nconst own = {}.hasOwnProperty\n\n/**\n * Factory to check if a given node can have a tag omitted.\n *\n * @param {Record<string, OmitHandle>} handlers\n *   Omission handlers, where each key is a tag name, and each value is the\n *   corresponding handler.\n * @returns {OmitHandle}\n *   Whether to omit a tag of an element.\n */\nexport function omission(handlers) {\n  return omit\n\n  /**\n   * Check if a given node can have a tag omitted.\n   *\n   * @type {OmitHandle}\n   */\n  function omit(node, index, parent) {\n    return (\n      own.call(handlers, node.tagName) &&\n      handlers[node.tagName](node, index, parent)\n    )\n  }\n}\n", "/**\n * @import {Element, Parents} from 'hast'\n */\n\nimport {whitespace} from 'hast-util-whitespace'\nimport {siblingAfter} from './util/siblings.js'\nimport {omission} from './omission.js'\n\nexport const closing = omission({\n  body,\n  caption: headOrColgroupOrCaption,\n  colgroup: headOrColgroupOrCaption,\n  dd,\n  dt,\n  head: headOrColgroupOrCaption,\n  html,\n  li,\n  optgroup,\n  option,\n  p,\n  rp: rubyElement,\n  rt: rubyElement,\n  tbody,\n  td: cells,\n  tfoot,\n  th: cells,\n  thead,\n  tr\n})\n\n/**\n * Macro for `</head>`, `</colgroup>`, and `</caption>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction headOrColgroupOrCaption(_, index, parent) {\n  const next = siblingAfter(parent, index, true)\n  return (\n    !next ||\n    (next.type !== 'comment' &&\n      !(next.type === 'text' && whitespace(next.value.charAt(0))))\n  )\n}\n\n/**\n * Whether to omit `</html>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction html(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || next.type !== 'comment'\n}\n\n/**\n * Whether to omit `</body>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction body(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || next.type !== 'comment'\n}\n\n/**\n * Whether to omit `</p>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction p(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return next\n    ? next.type === 'element' &&\n        (next.tagName === 'address' ||\n          next.tagName === 'article' ||\n          next.tagName === 'aside' ||\n          next.tagName === 'blockquote' ||\n          next.tagName === 'details' ||\n          next.tagName === 'div' ||\n          next.tagName === 'dl' ||\n          next.tagName === 'fieldset' ||\n          next.tagName === 'figcaption' ||\n          next.tagName === 'figure' ||\n          next.tagName === 'footer' ||\n          next.tagName === 'form' ||\n          next.tagName === 'h1' ||\n          next.tagName === 'h2' ||\n          next.tagName === 'h3' ||\n          next.tagName === 'h4' ||\n          next.tagName === 'h5' ||\n          next.tagName === 'h6' ||\n          next.tagName === 'header' ||\n          next.tagName === 'hgroup' ||\n          next.tagName === 'hr' ||\n          next.tagName === 'main' ||\n          next.tagName === 'menu' ||\n          next.tagName === 'nav' ||\n          next.tagName === 'ol' ||\n          next.tagName === 'p' ||\n          next.tagName === 'pre' ||\n          next.tagName === 'section' ||\n          next.tagName === 'table' ||\n          next.tagName === 'ul')\n    : !parent ||\n        // Confusing parent.\n        !(\n          parent.type === 'element' &&\n          (parent.tagName === 'a' ||\n            parent.tagName === 'audio' ||\n            parent.tagName === 'del' ||\n            parent.tagName === 'ins' ||\n            parent.tagName === 'map' ||\n            parent.tagName === 'noscript' ||\n            parent.tagName === 'video')\n        )\n}\n\n/**\n * Whether to omit `</li>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction li(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || (next.type === 'element' && next.tagName === 'li')\n}\n\n/**\n * Whether to omit `</dt>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction dt(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return Boolean(\n    next &&\n      next.type === 'element' &&\n      (next.tagName === 'dt' || next.tagName === 'dd')\n  )\n}\n\n/**\n * Whether to omit `</dd>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction dd(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'dt' || next.tagName === 'dd'))\n  )\n}\n\n/**\n * Whether to omit `</rt>` or `</rp>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction rubyElement(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'rp' || next.tagName === 'rt'))\n  )\n}\n\n/**\n * Whether to omit `</optgroup>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction optgroup(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || (next.type === 'element' && next.tagName === 'optgroup')\n}\n\n/**\n * Whether to omit `</option>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction option(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'option' || next.tagName === 'optgroup'))\n  )\n}\n\n/**\n * Whether to omit `</thead>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction thead(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return Boolean(\n    next &&\n      next.type === 'element' &&\n      (next.tagName === 'tbody' || next.tagName === 'tfoot')\n  )\n}\n\n/**\n * Whether to omit `</tbody>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction tbody(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'tbody' || next.tagName === 'tfoot'))\n  )\n}\n\n/**\n * Whether to omit `</tfoot>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction tfoot(_, index, parent) {\n  return !siblingAfter(parent, index)\n}\n\n/**\n * Whether to omit `</tr>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction tr(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || (next.type === 'element' && next.tagName === 'tr')\n}\n\n/**\n * Whether to omit `</td>` or `</th>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction cells(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'td' || next.tagName === 'th'))\n  )\n}\n", "/**\n * @import {Element, Parents} from 'hast'\n */\n\nimport {whitespace} from 'hast-util-whitespace'\nimport {siblingAfter, siblingBefore} from './util/siblings.js'\nimport {closing} from './closing.js'\nimport {omission} from './omission.js'\n\nexport const opening = omission({\n  body,\n  colgroup,\n  head,\n  html,\n  tbody\n})\n\n/**\n * Whether to omit `<html>`.\n *\n * @param {Element} node\n *   Element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction html(node) {\n  const head = siblingAfter(node, -1)\n  return !head || head.type !== 'comment'\n}\n\n/**\n * Whether to omit `<head>`.\n *\n * @param {Element} node\n *   Element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction head(node) {\n  /** @type {Set<string>} */\n  const seen = new Set()\n\n  // Whether `srcdoc` or not,\n  // make sure the content model at least doesn\u2019t have too many `base`s/`title`s.\n  for (const child of node.children) {\n    if (\n      child.type === 'element' &&\n      (child.tagName === 'base' || child.tagName === 'title')\n    ) {\n      if (seen.has(child.tagName)) return false\n      seen.add(child.tagName)\n    }\n  }\n\n  // \u201CMay be omitted if the element is empty,\n  // or if the first thing inside the head element is an element.\u201D\n  const child = node.children[0]\n  return !child || child.type === 'element'\n}\n\n/**\n * Whether to omit `<body>`.\n *\n * @param {Element} node\n *   Element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction body(node) {\n  const head = siblingAfter(node, -1, true)\n\n  return (\n    !head ||\n    (head.type !== 'comment' &&\n      !(head.type === 'text' && whitespace(head.value.charAt(0))) &&\n      !(\n        head.type === 'element' &&\n        (head.tagName === 'meta' ||\n          head.tagName === 'link' ||\n          head.tagName === 'script' ||\n          head.tagName === 'style' ||\n          head.tagName === 'template')\n      ))\n  )\n}\n\n/**\n * Whether to omit `<colgroup>`.\n * The spec describes some logic for the opening tag, but it\u2019s easier to\n * implement in the closing tag, to the same effect, so we handle it there\n * instead.\n *\n * @param {Element} node\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction colgroup(node, index, parent) {\n  const previous = siblingBefore(parent, index)\n  const head = siblingAfter(node, -1, true)\n\n  // Previous colgroup was already omitted.\n  if (\n    parent &&\n    previous &&\n    previous.type === 'element' &&\n    previous.tagName === 'colgroup' &&\n    closing(previous, parent.children.indexOf(previous), parent)\n  ) {\n    return false\n  }\n\n  return Boolean(head && head.type === 'element' && head.tagName === 'col')\n}\n\n/**\n * Whether to omit `<tbody>`.\n *\n * @param {Element} node\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction tbody(node, index, parent) {\n  const previous = siblingBefore(parent, index)\n  const head = siblingAfter(node, -1)\n\n  // Previous table section was already omitted.\n  if (\n    parent &&\n    previous &&\n    previous.type === 'element' &&\n    (previous.tagName === 'thead' || previous.tagName === 'tbody') &&\n    closing(previous, parent.children.indexOf(previous), parent)\n  ) {\n    return false\n  }\n\n  return Boolean(head && head.type === 'element' && head.tagName === 'tr')\n}\n", "/**\n * @import {Element, Parents, Properties} from 'hast'\n * @import {State} from '../index.js'\n */\n\nimport {ccount} from 'ccount'\nimport {stringify as commas} from 'comma-separated-tokens'\nimport {find, svg} from 'property-information'\nimport {stringify as spaces} from 'space-separated-tokens'\nimport {stringifyEntities} from 'stringify-entities'\nimport {closing} from '../omission/closing.js'\nimport {opening} from '../omission/opening.js'\n\n/**\n * Maps of subsets.\n *\n * Each value is a matrix of tuples.\n * The value at `0` causes parse errors, the value at `1` is valid.\n * Of both, the value at `0` is unsafe, and the value at `1` is safe.\n *\n * @type {Record<'double' | 'name' | 'single' | 'unquoted', Array<[Array<string>, Array<string>]>>}\n */\nconst constants = {\n  // See: <https://html.spec.whatwg.org/#attribute-name-state>.\n  name: [\n    ['\\t\\n\\f\\r &/=>'.split(''), '\\t\\n\\f\\r \"&\\'/=>`'.split('')],\n    ['\\0\\t\\n\\f\\r \"&\\'/<=>'.split(''), '\\0\\t\\n\\f\\r \"&\\'/<=>`'.split('')]\n  ],\n  // See: <https://html.spec.whatwg.org/#attribute-value-(unquoted)-state>.\n  unquoted: [\n    ['\\t\\n\\f\\r &>'.split(''), '\\0\\t\\n\\f\\r \"&\\'<=>`'.split('')],\n    ['\\0\\t\\n\\f\\r \"&\\'<=>`'.split(''), '\\0\\t\\n\\f\\r \"&\\'<=>`'.split('')]\n  ],\n  // See: <https://html.spec.whatwg.org/#attribute-value-(single-quoted)-state>.\n  single: [\n    [\"&'\".split(''), '\"&\\'`'.split('')],\n    [\"\\0&'\".split(''), '\\0\"&\\'`'.split('')]\n  ],\n  // See: <https://html.spec.whatwg.org/#attribute-value-(double-quoted)-state>.\n  double: [\n    ['\"&'.split(''), '\"&\\'`'.split('')],\n    ['\\0\"&'.split(''), '\\0\"&\\'`'.split('')]\n  ]\n}\n\n/**\n * Serialize an element node.\n *\n * @param {Element} node\n *   Node to handle.\n * @param {number | undefined} index\n *   Index of `node` in `parent.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function element(node, index, parent, state) {\n  const schema = state.schema\n  const omit = schema.space === 'svg' ? false : state.settings.omitOptionalTags\n  let selfClosing =\n    schema.space === 'svg'\n      ? state.settings.closeEmptyElements\n      : state.settings.voids.includes(node.tagName.toLowerCase())\n  /** @type {Array<string>} */\n  const parts = []\n  /** @type {string} */\n  let last\n\n  if (schema.space === 'html' && node.tagName === 'svg') {\n    state.schema = svg\n  }\n\n  const attributes = serializeAttributes(state, node.properties)\n\n  const content = state.all(\n    schema.space === 'html' && node.tagName === 'template' ? node.content : node\n  )\n\n  state.schema = schema\n\n  // If the node is categorised as void, but it has children, remove the\n  // categorisation.\n  // This enables for example `menuitem`s, which are void in W3C HTML but not\n  // void in WHATWG HTML, to be stringified properly.\n  // Note: `menuitem` has since been removed from the HTML spec, and so is no\n  // longer void.\n  if (content) selfClosing = false\n\n  if (attributes || !omit || !opening(node, index, parent)) {\n    parts.push('<', node.tagName, attributes ? ' ' + attributes : '')\n\n    if (\n      selfClosing &&\n      (schema.space === 'svg' || state.settings.closeSelfClosing)\n    ) {\n      last = attributes.charAt(attributes.length - 1)\n      if (\n        !state.settings.tightSelfClosing ||\n        last === '/' ||\n        (last && last !== '\"' && last !== \"'\")\n      ) {\n        parts.push(' ')\n      }\n\n      parts.push('/')\n    }\n\n    parts.push('>')\n  }\n\n  parts.push(content)\n\n  if (!selfClosing && (!omit || !closing(node, index, parent))) {\n    parts.push('</' + node.tagName + '>')\n  }\n\n  return parts.join('')\n}\n\n/**\n * @param {State} state\n * @param {Properties | null | undefined} properties\n * @returns {string}\n */\nfunction serializeAttributes(state, properties) {\n  /** @type {Array<string>} */\n  const values = []\n  let index = -1\n  /** @type {string} */\n  let key\n\n  if (properties) {\n    for (key in properties) {\n      if (properties[key] !== null && properties[key] !== undefined) {\n        const value = serializeAttribute(state, key, properties[key])\n        if (value) values.push(value)\n      }\n    }\n  }\n\n  while (++index < values.length) {\n    const last = state.settings.tightAttributes\n      ? values[index].charAt(values[index].length - 1)\n      : undefined\n\n    // In tight mode, don\u2019t add a space after quoted attributes.\n    if (index !== values.length - 1 && last !== '\"' && last !== \"'\") {\n      values[index] += ' '\n    }\n  }\n\n  return values.join('')\n}\n\n/**\n * @param {State} state\n * @param {string} key\n * @param {Properties[keyof Properties]} value\n * @returns {string}\n */\nfunction serializeAttribute(state, key, value) {\n  const info = find(state.schema, key)\n  const x =\n    state.settings.allowParseErrors && state.schema.space === 'html' ? 0 : 1\n  const y = state.settings.allowDangerousCharacters ? 0 : 1\n  let quote = state.quote\n  /** @type {string | undefined} */\n  let result\n\n  if (info.overloadedBoolean && (value === info.attribute || value === '')) {\n    value = true\n  } else if (\n    (info.boolean || info.overloadedBoolean) &&\n    (typeof value !== 'string' || value === info.attribute || value === '')\n  ) {\n    value = Boolean(value)\n  }\n\n  if (\n    value === null ||\n    value === undefined ||\n    value === false ||\n    (typeof value === 'number' && Number.isNaN(value))\n  ) {\n    return ''\n  }\n\n  const name = stringifyEntities(\n    info.attribute,\n    Object.assign({}, state.settings.characterReferences, {\n      // Always encode without parse errors in non-HTML.\n      subset: constants.name[x][y]\n    })\n  )\n\n  // No value.\n  // There is currently only one boolean property in SVG: `[download]` on\n  // `<a>`.\n  // This property does not seem to work in browsers (Firefox, Safari, Chrome),\n  // so I can\u2019t test if dropping the value works.\n  // But I assume that it should:\n  //\n  // ```html\n  // <!doctype html>\n  // <svg viewBox=\"0 0 100 100\">\n  //   <a href=https://example.com download>\n  //     <circle cx=50 cy=40 r=35 />\n  //   </a>\n  // </svg>\n  // ```\n  //\n  // See: <https://github.com/wooorm/property-information/blob/main/lib/svg.js>\n  if (value === true) return name\n\n  // `spaces` doesn\u2019t accept a second argument, but it\u2019s given here just to\n  // keep the code cleaner.\n  value = Array.isArray(value)\n    ? (info.commaSeparated ? commas : spaces)(value, {\n        padLeft: !state.settings.tightCommaSeparatedLists\n      })\n    : String(value)\n\n  if (state.settings.collapseEmptyAttributes && !value) return name\n\n  // Check unquoted value.\n  if (state.settings.preferUnquoted) {\n    result = stringifyEntities(\n      value,\n      Object.assign({}, state.settings.characterReferences, {\n        attribute: true,\n        subset: constants.unquoted[x][y]\n      })\n    )\n  }\n\n  // If we don\u2019t want unquoted, or if `value` contains character references when\n  // unquoted\u2026\n  if (result !== value) {\n    // If the alternative is less common than `quote`, switch.\n    if (\n      state.settings.quoteSmart &&\n      ccount(value, quote) > ccount(value, state.alternative)\n    ) {\n      quote = state.alternative\n    }\n\n    result =\n      quote +\n      stringifyEntities(\n        value,\n        Object.assign({}, state.settings.characterReferences, {\n          // Always encode without parse errors in non-HTML.\n          subset: (quote === \"'\" ? constants.single : constants.double)[x][y],\n          attribute: true\n        })\n      ) +\n      quote\n  }\n\n  // Don\u2019t add a `=` for unquoted empties.\n  return name + (result ? '=' + result : result)\n}\n", "/**\n * @import {Parents, Text} from 'hast'\n * @import {Raw} from 'mdast-util-to-hast'\n * @import {State} from '../index.js'\n */\n\nimport {stringifyEntities} from 'stringify-entities'\n\n// Declare array as variable so it can be cached by `stringifyEntities`\nconst textEntitySubset = ['<', '&']\n\n/**\n * Serialize a text node.\n *\n * @param {Raw | Text} node\n *   Node to handle.\n * @param {number | undefined} _\n *   Index of `node` in `parent.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function text(node, _, parent, state) {\n  // Check if content of `node` should be escaped.\n  return parent &&\n    parent.type === 'element' &&\n    (parent.tagName === 'script' || parent.tagName === 'style')\n    ? node.value\n    : stringifyEntities(\n        node.value,\n        Object.assign({}, state.settings.characterReferences, {\n          subset: textEntitySubset\n        })\n      )\n}\n", "/**\n * @import {Parents} from 'hast'\n * @import {Raw} from 'mdast-util-to-hast'\n * @import {State} from '../index.js'\n */\n\nimport {text} from './text.js'\n\n/**\n * Serialize a raw node.\n *\n * @param {Raw} node\n *   Node to handle.\n * @param {number | undefined} index\n *   Index of `node` in `parent.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function raw(node, index, parent, state) {\n  return state.settings.allowDangerousHtml\n    ? node.value\n    : text(node, index, parent, state)\n}\n", "/**\n * @import {Parents, Root} from 'hast'\n * @import {State} from '../index.js'\n */\n\n/**\n * Serialize a root.\n *\n * @param {Root} node\n *   Node to handle.\n * @param {number | undefined} _1\n *   Index of `node` in `parent.\n * @param {Parents | undefined} _2\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function root(node, _1, _2, state) {\n  return state.all(node)\n}\n", "/**\n * @import {Nodes, Parents} from 'hast'\n * @import {State} from '../index.js'\n */\n\nimport {zwitch} from 'zwitch'\nimport {comment} from './comment.js'\nimport {doctype} from './doctype.js'\nimport {element} from './element.js'\nimport {raw} from './raw.js'\nimport {root} from './root.js'\nimport {text} from './text.js'\n\n/**\n * @type {(node: Nodes, index: number | undefined, parent: Parents | undefined, state: State) => string}\n */\nexport const handle = zwitch('type', {\n  invalid,\n  unknown,\n  handlers: {comment, doctype, element, raw, root, text}\n})\n\n/**\n * Fail when a non-node is found in the tree.\n *\n * @param {unknown} node\n *   Unknown value.\n * @returns {never}\n *   Never.\n */\nfunction invalid(node) {\n  throw new Error('Expected node, not `' + node + '`')\n}\n\n/**\n * Fail when a node with an unknown type is found in the tree.\n *\n * @param {unknown} node_\n *  Unknown node.\n * @returns {never}\n *   Never.\n */\nfunction unknown(node_) {\n  // `type` is guaranteed by runtime JS.\n  const node = /** @type {Nodes} */ (node_)\n  throw new Error('Cannot compile unknown node `' + node.type + '`')\n}\n", "/**\n * @import {Nodes, Parents, RootContent} from 'hast'\n * @import {Schema} from 'property-information'\n * @import {Options as StringifyEntitiesOptions} from 'stringify-entities'\n */\n\n/**\n * @typedef {Omit<StringifyEntitiesOptions, 'attribute' | 'escapeOnly' | 'subset'>} CharacterReferences\n *\n * @typedef Options\n *   Configuration.\n * @property {boolean | null | undefined} [allowDangerousCharacters=false]\n *   Do not encode some characters which cause XSS vulnerabilities in older\n *   browsers (default: `false`).\n *\n *   > \u26A0\uFE0F **Danger**: only set this if you completely trust the content.\n * @property {boolean | null | undefined} [allowDangerousHtml=false]\n *   Allow `raw` nodes and insert them as raw HTML (default: `false`).\n *\n *   When `false`, `Raw` nodes are encoded.\n *\n *   > \u26A0\uFE0F **Danger**: only set this if you completely trust the content.\n * @property {boolean | null | undefined} [allowParseErrors=false]\n *   Do not encode characters which cause parse errors (even though they work),\n *   to save bytes (default: `false`).\n *\n *   Not used in the SVG space.\n *\n *   > \uD83D\uDC49 **Note**: intentionally creates parse errors in markup (how parse\n *   > errors are handled is well defined, so this works but isn\u2019t pretty).\n * @property {boolean | null | undefined} [bogusComments=false]\n *   Use \u201Cbogus comments\u201D instead of comments to save byes: `<?charlie>`\n *   instead of `<!--charlie-->` (default: `false`).\n *\n *   > \uD83D\uDC49 **Note**: intentionally creates parse errors in markup (how parse\n *   > errors are handled is well defined, so this works but isn\u2019t pretty).\n * @property {CharacterReferences | null | undefined} [characterReferences]\n *   Configure how to serialize character references (optional).\n * @property {boolean | null | undefined} [closeEmptyElements=false]\n *   Close SVG elements without any content with slash (`/`) on the opening tag\n *   instead of an end tag: `<circle />` instead of `<circle></circle>`\n *   (default: `false`).\n *\n *   See `tightSelfClosing` to control whether a space is used before the\n *   slash.\n *\n *   Not used in the HTML space.\n * @property {boolean | null | undefined} [closeSelfClosing=false]\n *   Close self-closing nodes with an extra slash (`/`): `<img />` instead of\n *   `<img>` (default: `false`).\n *\n *   See `tightSelfClosing` to control whether a space is used before the\n *   slash.\n *\n *   Not used in the SVG space.\n * @property {boolean | null | undefined} [collapseEmptyAttributes=false]\n *   Collapse empty attributes: get `class` instead of `class=\"\"` (default:\n *   `false`).\n *\n *   Not used in the SVG space.\n *\n *   > \uD83D\uDC49 **Note**: boolean attributes (such as `hidden`) are always collapsed.\n * @property {boolean | null | undefined} [omitOptionalTags=false]\n *   Omit optional opening and closing tags (default: `false`).\n *\n *   For example, in `<ol><li>one</li><li>two</li></ol>`, both `</li>` closing\n *   tags can be omitted.\n *   The first because it\u2019s followed by another `li`, the last because it\u2019s\n *   followed by nothing.\n *\n *   Not used in the SVG space.\n * @property {boolean | null | undefined} [preferUnquoted=false]\n *   Leave attributes unquoted if that results in less bytes (default: `false`).\n *\n *   Not used in the SVG space.\n * @property {boolean | null | undefined} [quoteSmart=false]\n *   Use the other quote if that results in less bytes (default: `false`).\n * @property {Quote | null | undefined} [quote='\"']\n *   Preferred quote to use (default: `'\"'`).\n * @property {Space | null | undefined} [space='html']\n *   When an `<svg>` element is found in the HTML space, this package already\n *   automatically switches to and from the SVG space when entering and exiting\n *   it (default: `'html'`).\n *\n *   > \uD83D\uDC49 **Note**: hast is not XML.\n *   > It supports SVG as embedded in HTML.\n *   > It does not support the features available in XML.\n *   > Passing SVG might break but fragments of modern SVG should be fine.\n *   > Use [`xast`][xast] if you need to support SVG as XML.\n * @property {boolean | null | undefined} [tightAttributes=false]\n *   Join attributes together, without whitespace, if possible: get\n *   `class=\"a b\"title=\"c d\"` instead of `class=\"a b\" title=\"c d\"` to save\n *   bytes (default: `false`).\n *\n *   Not used in the SVG space.\n *\n *   > \uD83D\uDC49 **Note**: intentionally creates parse errors in markup (how parse\n *   > errors are handled is well defined, so this works but isn\u2019t pretty).\n * @property {boolean | null | undefined} [tightCommaSeparatedLists=false]\n *   Join known comma-separated attribute values with just a comma (`,`),\n *   instead of padding them on the right as well (`,\u2420`, where `\u2420` represents a\n *   space) (default: `false`).\n * @property {boolean | null | undefined} [tightDoctype=false]\n *   Drop unneeded spaces in doctypes: `<!doctypehtml>` instead of\n *   `<!doctype html>` to save bytes (default: `false`).\n *\n *   > \uD83D\uDC49 **Note**: intentionally creates parse errors in markup (how parse\n *   > errors are handled is well defined, so this works but isn\u2019t pretty).\n * @property {boolean | null | undefined} [tightSelfClosing=false]\n *   Do not use an extra space when closing self-closing elements: `<img/>`\n *   instead of `<img />` (default: `false`).\n *\n *   > \uD83D\uDC49 **Note**: only used if `closeSelfClosing: true` or\n *   > `closeEmptyElements: true`.\n * @property {boolean | null | undefined} [upperDoctype=false]\n *   Use a `<!DOCTYPE\u2026` instead of `<!doctype\u2026` (default: `false`).\n *\n *   Useless except for XHTML.\n * @property {ReadonlyArray<string> | null | undefined} [voids]\n *   Tag names of elements to serialize without closing tag (default: `html-void-elements`).\n *\n *   Not used in the SVG space.\n *\n *   > \uD83D\uDC49 **Note**: It\u2019s highly unlikely that you want to pass this, because\n *   > hast is not for XML, and HTML will not add more void elements.\n *\n * @typedef {'\"' | \"'\"} Quote\n *   HTML quotes for attribute values.\n *\n * @typedef {Omit<Required<{[key in keyof Options]: Exclude<Options[key], null | undefined>}>, 'space' | 'quote'>} Settings\n *\n * @typedef {'html' | 'svg'} Space\n *   Namespace.\n *\n * @typedef State\n *   Info passed around about the current state.\n * @property {(node: Parents | undefined) => string} all\n *   Serialize the children of a parent node.\n * @property {Quote} alternative\n *   Alternative quote.\n * @property {(node: Nodes, index: number | undefined, parent: Parents | undefined) => string} one\n *   Serialize one node.\n * @property {Quote} quote\n *   Preferred quote.\n * @property {Schema} schema\n *   Current schema.\n * @property {Settings} settings\n *   User configuration.\n */\n\nimport {htmlVoidElements} from 'html-void-elements'\nimport {html, svg} from 'property-information'\nimport {handle} from './handle/index.js'\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/** @type {CharacterReferences} */\nconst emptyCharacterReferences = {}\n\n/** @type {Array<never>} */\nconst emptyChildren = []\n\n/**\n * Serialize hast as HTML.\n *\n * @param {Array<RootContent> | Nodes} tree\n *   Tree to serialize.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {string}\n *   Serialized HTML.\n */\nexport function toHtml(tree, options) {\n  const options_ = options || emptyOptions\n  const quote = options_.quote || '\"'\n  const alternative = quote === '\"' ? \"'\" : '\"'\n\n  if (quote !== '\"' && quote !== \"'\") {\n    throw new Error('Invalid quote `' + quote + '`, expected `\\'` or `\"`')\n  }\n\n  /** @type {State} */\n  const state = {\n    one,\n    all,\n    settings: {\n      omitOptionalTags: options_.omitOptionalTags || false,\n      allowParseErrors: options_.allowParseErrors || false,\n      allowDangerousCharacters: options_.allowDangerousCharacters || false,\n      quoteSmart: options_.quoteSmart || false,\n      preferUnquoted: options_.preferUnquoted || false,\n      tightAttributes: options_.tightAttributes || false,\n      upperDoctype: options_.upperDoctype || false,\n      tightDoctype: options_.tightDoctype || false,\n      bogusComments: options_.bogusComments || false,\n      tightCommaSeparatedLists: options_.tightCommaSeparatedLists || false,\n      tightSelfClosing: options_.tightSelfClosing || false,\n      collapseEmptyAttributes: options_.collapseEmptyAttributes || false,\n      allowDangerousHtml: options_.allowDangerousHtml || false,\n      voids: options_.voids || htmlVoidElements,\n      characterReferences:\n        options_.characterReferences || emptyCharacterReferences,\n      closeSelfClosing: options_.closeSelfClosing || false,\n      closeEmptyElements: options_.closeEmptyElements || false\n    },\n    schema: options_.space === 'svg' ? svg : html,\n    quote,\n    alternative\n  }\n\n  return state.one(\n    Array.isArray(tree) ? {type: 'root', children: tree} : tree,\n    undefined,\n    undefined\n  )\n}\n\n/**\n * Serialize a node.\n *\n * @this {State}\n *   Info passed around about the current state.\n * @param {Nodes} node\n *   Node to handle.\n * @param {number | undefined} index\n *   Index of `node` in `parent.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @returns {string}\n *   Serialized node.\n */\nfunction one(node, index, parent) {\n  return handle(node, index, parent, this)\n}\n\n/**\n * Serialize all children of `parent`.\n *\n * @this {State}\n *   Info passed around about the current state.\n * @param {Parents | undefined} parent\n *   Parent whose children to serialize.\n * @returns {string}\n */\nexport function all(parent) {\n  /** @type {Array<string>} */\n  const results = []\n  const children = (parent && parent.children) || emptyChildren\n  let index = -1\n\n  while (++index < children.length) {\n    results[index] = this.one(children[index], index, parent)\n  }\n\n  return results.join('')\n}\n", "/**\n * @import {Root} from 'hast'\n * @import {Options} from 'hast-util-to-html'\n * @import {Compiler, Processor} from 'unified'\n */\n\nimport {toHtml} from 'hast-util-to-html'\n\n/**\n * Plugin to add support for serializing as HTML.\n *\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {undefined}\n *   Nothing.\n */\nexport default function rehypeStringify(options) {\n  /** @type {Processor<undefined, undefined, undefined, Root, string>} */\n  // @ts-expect-error: TS in JSDoc generates wrong types if `this` is typed regularly.\n  const self = this\n  const settings = {...self.data('settings'), ...options}\n\n  self.compiler = compiler\n\n  /**\n   * @type {Compiler<Root, string>}\n   */\n  function compiler(tree) {\n    return toHtml(tree, settings)\n  }\n}\n", "/**\n * @typedef {import('mdast').Nodes} Nodes\n * @typedef {import('mdast-util-find-and-replace').ReplaceFunction} ReplaceFunction\n */\n\nimport {findAndReplace} from 'mdast-util-find-and-replace'\n\n/**\n * Turn normal line endings into hard breaks.\n *\n * @param {Nodes} tree\n *   Tree to change.\n * @returns {undefined}\n *   Nothing.\n */\nexport function newlineToBreak(tree) {\n  findAndReplace(tree, [/\\r?\\n|\\r/g, replace])\n}\n\n/**\n * Replace line endings.\n *\n * @type {ReplaceFunction}\n */\nfunction replace() {\n  return {type: 'break'}\n}\n", "/**\n * @typedef {import('mdast').Root} Root\n */\n\nimport {newlineToBreak} from 'mdast-util-newline-to-break'\n\n/**\n * Support hard breaks without needing spaces or escapes (turns enters into\n * `<br>`s).\n *\n * @returns\n *   Transform.\n */\nexport default function remarkBreaks() {\n  /**\n   * Transform.\n   *\n   * @param {Root} tree\n   *   Tree.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  return function (tree) {\n    newlineToBreak(tree)\n  }\n}\n", "/**\n * @typedef {import('mdast').Root} Root\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownOptions\n * @typedef {import('unified').Compiler<Root, string>} Compiler\n * @typedef {import('unified').Processor<undefined, undefined, undefined, Root, string>} Processor\n */\n\n/**\n * @typedef {Omit<ToMarkdownOptions, 'extensions'>} Options\n */\n\nimport {toMarkdown} from 'mdast-util-to-markdown'\n\n/**\n * Add support for serializing to markdown.\n *\n * @param {Readonly<Options> | null | undefined} [options]\n *   Configuration (optional).\n * @returns {undefined}\n *   Nothing.\n */\nexport default function remarkStringify(options) {\n  /** @type {Processor} */\n  // @ts-expect-error: TS in JSDoc generates wrong types if `this` is typed regularly.\n  const self = this\n\n  self.compiler = compiler\n\n  /**\n   * @type {Compiler}\n   */\n  function compiler(tree) {\n    return toMarkdown(tree, {\n      ...self.data('settings'),\n      ...options,\n      // Note: this option is not in the readme.\n      // The goal is for it to be set by plugins on `data` instead of being\n      // passed by users.\n      extensions: self.data('toMarkdownExtensions') || []\n    })\n  }\n}\n", "import { fromProseMirror } from \"@handlewithcare/remark-prosemirror\"\nimport type {\n\tPmMarkHandler,\n\tPmNodeHandler,\n} from \"@handlewithcare/remark-prosemirror/lib/mdast-util-from-prosemirror.js\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport type { Element } from \"hast\"\nimport { defaultHandlers } from \"mdast-util-to-markdown\"\nimport { DOMParser, type Node as PmNode, type Schema, type Slice } from \"prosemirror-model\"\nimport rehypeStringify from \"rehype-stringify\"\nimport remarkBreaks from \"remark-breaks\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkParse from \"remark-parse\"\nimport remarkRehype from \"remark-rehype\"\nimport remarkStringify from \"remark-stringify\"\nimport { unified } from \"unified\"\nimport type { FramerProseMirrorSchema } from \"../schema/index.ts\"\nimport type { MarkName, NodeName } from \"../schema/names.ts\"\nimport type { MarkdownMarkSerializerSpec, MarkdownNodeSerializerSpec } from \"../types.ts\"\n\nconst HEADER_REGEX = /^(#{1,6})\\s+(.+)$/m\nconst BOLD_REGEX = /\\*\\*(.*?)\\*\\*/\nconst ITALIC_REGEX = /\\*(.*?)\\*/\nconst BULLETED_LIST_REGEX = /^\\s*[-*+]\\s+(.+)$/m\nconst NUMBERED_LIST_REGEX = /^\\s*(\\d+)\\.\\s+(.+)$/m\nconst BLOCKQUOTE_REGEX = /^>\\s+(.+)$/m\nconst LINK_REGEX = /\\[([^\\]]+)\\]\\((https?:\\/\\/[^)]+)\\)/\nconst INLINE_CODE_REGEX = /`([^`]+)`/\nconst CODE_BLOCK_REGEX = /```[\\s\\S]*?```/\nconst TABLE_REGEX = /^\\s*\\|(.+\\|)+\\s*$/m\nconst STRIKETHROUGH_REGEX = /~~(.*?)~~/\nconst TASK_LIST_REGEX = /^\\s*[-*+]\\s+\\[[ x]\\]\\s+\\S/m // Only lowercase x or space, explicit character class\nconst HORIZONTAL_RULE_REGEX = /^(-{3,}|_{3,})\\s*$/m // Only consecutive dashes or underscores, no spaces between\nconst IMAGE_REGEX = /!\\[([^\\]]*)\\]\\((https?:\\/\\/[^)]+)\\)/\nconst AUTOLINK_REGEX = /<(https?:\\/\\/[^>]+)>/\n\n/** Cheaply verifies that the text is likely to be markdown. */\nexport function isLikelyMarkdownText(text: string | undefined): boolean {\n\t// Short-circuit for empty text\n\tif (!text || text.length === 0) return false\n\n\tconst patterns = [\n\t\tHEADER_REGEX,\n\t\tBOLD_REGEX,\n\t\tITALIC_REGEX,\n\t\tBULLETED_LIST_REGEX,\n\t\tNUMBERED_LIST_REGEX,\n\t\tBLOCKQUOTE_REGEX,\n\t\tLINK_REGEX,\n\t\tINLINE_CODE_REGEX,\n\t\tCODE_BLOCK_REGEX,\n\t\tTABLE_REGEX,\n\t\tSTRIKETHROUGH_REGEX,\n\t\tTASK_LIST_REGEX,\n\t\tHORIZONTAL_RULE_REGEX,\n\t\tIMAGE_REGEX,\n\t\tAUTOLINK_REGEX,\n\t]\n\n\treturn patterns.some(pattern => pattern.test(text))\n}\n\nexport function convertMarkdownToHTML(text: string): string {\n\treturn (\n\t\tunified()\n\t\t\t.use(remarkParse)\n\t\t\t// This ensures single-line line breaks are preserved; this matches the formatting of Notion etc better.\n\t\t\t.use(remarkBreaks)\n\t\t\t// This adds support for tables and code blocks with language tags (```javascript ... ```).\n\t\t\t.use(remarkGfm)\n\t\t\t.use(remarkRehype, {\n\t\t\t\t// The markdown might include HTML blocks. (Or, alternatively, the whole markdown might be HTML,\n\t\t\t\t// if we mis-detect an HTML string as markdown.) Without `allowDangerousHtml`, these HTML blocks\n\t\t\t\t// will get dropped.\n\t\t\t\tallowDangerousHtml: true,\n\t\t\t\t// This ensures single-line breaks are serialized as `<br>`s, rather than `<br>\\n`s (as the default serializer does: https://github.com/syntax-tree/mdast-util-to-hast/blob/f511a93817b131fb73419bf7d24d73a5b8b0f0c2/lib/handlers/break.js#L21C17-L26C2).\n\t\t\t\t// If we include the `\\n`, ProseMirror would later add extra spacing (per the HTML spec!) when parsing the HTML.\n\t\t\t\t//\n\t\t\t\t// E.g., without this handler:\n\t\t\t\t//   Markdown: > Hello\\n> World\n\t\t\t\t//   HTML: <blockquote><p>Hello<br>\\nWorld</p></blockquote>\n\t\t\t\t//   ProseMirror: blockquote(textBlock(\"Hello\"), break(), textBlock(\" World\"))  \u2190 note the extra space\n\t\t\t\t// With this handler:\n\t\t\t\t//   Markdown: > Hello\\n> World\n\t\t\t\t//   HTML: <blockquote><p>Hello<br>World</p></blockquote>\n\t\t\t\t//   ProseMirror: blockquote(textBlock(\"Hello\"), break(), textBlock(\"World\"))\n\t\t\t\thandlers: {\n\t\t\t\t\tbreak: function hardBreak(state, node) {\n\t\t\t\t\t\tconst result: Element = { type: \"element\", tagName: \"br\", properties: {}, children: [] }\n\t\t\t\t\t\tstate.patch(node, result)\n\t\t\t\t\t\treturn [state.applyData(node, result)]\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\t\t.use(rehypeStringify, {\n\t\t\t\t// Same as above\n\t\t\t\tallowDangerousHtml: true,\n\t\t\t})\n\t\t\t.processSync(text)\n\t\t\t.toString()\n\t)\n}\n\nexport function parseRichTextFromMarkdown(text: string, schema: Schema): Slice {\n\t// Note: this does a two-step conversion process (Markdown -> HTML -> ProseMirror) rather than a\n\t// single-step Markdown -> ProseMirror one (using @handlewithcare/remark-prosemirror). That\u2019s\n\t// because our HTML \u2192 ProseMirror parser is already solid, whereas implementing an extra\n\t// Markdown \u2192 ProseMirror parser would be more work. (Still, we should consider switching if it\n\t// ends up being much faster :)\n\tconst html = convertMarkdownToHTML(text)\n\tconst dom = document.createElement(\"div\")\n\tdom.innerHTML = html\n\treturn DOMParser.fromSchema(schema).parseSlice(dom, { preserveWhitespace: true })\n}\n\nexport function serializeRichTextToMarkdown(doc: PmNode, engine: BaseEngine, schema: FramerProseMirrorSchema) {\n\tconst nodeHandlers: Partial<Record<NodeName, PmNodeHandler>> = {}\n\tlet nodeName: keyof typeof schema.nodes\n\tfor (nodeName in schema.nodes) {\n\t\t// Having to do an `as` because https://stackoverflow.com/a/72326483\n\t\tconst nodeToMarkdown = schema.nodes[nodeName].spec.toMarkdown as MarkdownNodeSerializerSpec<unknown>\n\t\tnodeHandlers[nodeName] = (...args) => nodeToMarkdown(...args, engine)\n\t}\n\n\tconst markHandlers: Partial<Record<MarkName, PmMarkHandler>> = {}\n\tlet markName: keyof typeof schema.marks\n\tfor (markName in schema.marks) {\n\t\t// Having to do an `as` because https://stackoverflow.com/a/72326483\n\t\tconst markToMarkdown = schema.marks[markName].spec.toMarkdown as MarkdownMarkSerializerSpec<unknown>\n\t\tmarkHandlers[markName] = (...args) => markToMarkdown(...args, engine)\n\t}\n\n\tconst mdast = fromProseMirror(doc, {\n\t\t// `as` because FramerProseMirrorSchema does not perfectly extend Schema<NodeName, MarkName>,\n\t\t// and fromProseMirror expects the latter\n\t\tschema: schema as Schema<NodeName, MarkName>,\n\t\tnodeHandlers,\n\t\tmarkHandlers,\n\t})\n\n\treturn unified()\n\t\t.use(remarkGfm)\n\t\t.use(remarkStringify, {\n\t\t\thandlers: {\n\t\t\t\ttext(...args: Parameters<typeof defaultHandlers.text>) {\n\t\t\t\t\tconst [node] = args\n\t\t\t\t\tif (node.data?.avoidEscaping) {\n\t\t\t\t\t\treturn node.value\n\t\t\t\t\t}\n\t\t\t\t\treturn defaultHandlers.text(...args)\n\t\t\t\t},\n\t\t\t},\n\t\t\t// Stylistic preferences:\n\t\t\tbullet: \"-\", // instead of \"*\"\n\t\t\temphasis: \"_\", // instead of \"*\"\n\t\t})\n\t\t.stringify(mdast)\n}\n", "import { assert, USE_FREEZE, assertNever } from \"@framerjs/shared\"\nimport type { CanvasTree, CollectionItemNode, CollectionNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isCollectionItemNode, isCollectionNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { ContentManagementStore } from \"document/stores/ContentManagementStore.ts\"\nimport type { TreeStore } from \"document/stores/TreeStore.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isReadonlyArray } from \"utils/typeChecks.ts\"\nimport type { VekterEngine } from \"../VekterEngine.ts\"\nimport type { VariableID } from \"../models/CanvasTree/traits/WithVariables.ts\"\nimport { isArrayVariable } from \"../models/CanvasTree/traits/WithVariables.ts\"\nimport { isStaticArrayControlProp } from \"../models/controlProps/ControlProp.ts\"\nimport { ActiveMainView } from \"./ActiveEditorType.ts\"\nimport {\n\tisCollectionItemVisibleToCurrentUser,\n\tisCurrentUserPrivateDraftCollectionItem,\n} from \"./collectionItemVisibility.ts\"\n\nexport interface AddReferenceAction {\n\tparentItemCollectionId: NodeID\n\tparentItemId: NodeID\n\tvariableId: VariableID\n\ttype: \"add-reference\"\n}\n\ninterface CollectionStackElementBase {\n\tcollectionId: NodeID\n\titemId: NodeID\n\tsaveAction?: AddReferenceAction\n}\n\ninterface NewCollectionStackElementBase extends CollectionStackElementBase {\n\tshowErrors: boolean\n\tattemptedClose?: boolean\n}\n\n/**\n * @deprecated\n *\n * Legacy cache-backed new-item state used only while cmsPrivateDraftItems can be off.\n * Remove with temporaryItemCache when private draft items become the only new-item model.\n */\nexport interface TemporaryCollectionStackElement extends NewCollectionStackElementBase {\n\ttype: \"temporary\"\n}\n\nexport interface ExistingCollectionStackElement extends CollectionStackElementBase {\n\ttype: \"existing\"\n}\n\nexport interface PrivateDraftCollectionStackElement extends NewCollectionStackElementBase {\n\ttype: \"privateDraft\"\n}\n\nexport interface ArrayItemStackElement {\n\tcollectionId: NodeID\n\tcollectionItemId: NodeID\n\tarrayFieldId: VariableID\n\tarrayItemId: NodeID\n\ttype: \"arrayItem\"\n}\n\nexport type CollectionStackElement =\n\t| TemporaryCollectionStackElement\n\t| ExistingCollectionStackElement\n\t| PrivateDraftCollectionStackElement\nexport type NewCollectionStackElement = TemporaryCollectionStackElement | PrivateDraftCollectionStackElement\n\nexport type OverlayStackElement = CollectionStackElement | ArrayItemStackElement\n\nfunction isCollectionStackElement(element: OverlayStackElement): element is CollectionStackElement {\n\treturn element.type === \"existing\" || element.type === \"temporary\" || element.type === \"privateDraft\"\n}\n\nexport function getCollectionNodeFromStackElement({\n\tstackElement,\n\ttree,\n}: {\n\tstackElement: OverlayStackElement | null\n\ttree: CanvasTree\n}): CollectionNode | null {\n\tif (!stackElement) return null\n\tconst collection = tree.getNodeWithTrait(stackElement.collectionId, isCollectionNode)\n\tif (collection) return collection\n\n\tconst itemId = stackElement.type === \"arrayItem\" ? stackElement.collectionItemId : stackElement.itemId\n\tconst item = tree.getNodeWithTrait(itemId, isCollectionItemNode)\n\tif (!item?.parentid) return null\n\n\treturn tree.getNodeWithTrait(item.parentid, isCollectionNode)\n}\n\nexport function getItemNodeFromStackElement({\n\ttreeStore,\n\tcontentManagementStore,\n\tstackElement,\n}: {\n\ttreeStore: TreeStore\n\tcontentManagementStore: ContentManagementStore\n\tstackElement: OverlayStackElement | null | undefined\n}): CollectionItemNode | null {\n\tif (!stackElement) return null\n\n\tif (stackElement.type === \"existing\" || stackElement.type === \"privateDraft\") {\n\t\treturn treeStore.tree.getNodeWithTrait(stackElement.itemId, isCollectionItemNode)\n\t}\n\n\tif (stackElement.type === \"temporary\") {\n\t\treturn contentManagementStore.temporaryItemCache.get(stackElement.itemId) ?? null\n\t}\n\n\tif (stackElement.type === \"arrayItem\") {\n\t\tconst collectionItem = treeStore.tree.getNodeWithTrait(stackElement.collectionItemId, isCollectionItemNode)\n\t\tif (collectionItem) return collectionItem\n\n\t\tconst temporaryItem = contentManagementStore.temporaryItemCache.get(stackElement.collectionItemId)\n\t\treturn temporaryItem ?? null\n\t}\n\n\tassertNever(stackElement)\n}\n\nexport function getPersistedOrTemporaryCollectionItemById({\n\ttreeStore,\n\tcontentManagementStore,\n\titemId,\n}: {\n\ttreeStore: TreeStore\n\tcontentManagementStore: ContentManagementStore\n\titemId: NodeID\n}): CollectionItemNode | null {\n\treturn (\n\t\ttreeStore.tree.getNodeWithTrait(itemId, isCollectionItemNode) ??\n\t\tcontentManagementStore.temporaryItemCache.get(itemId) ??\n\t\tnull\n\t)\n}\n\nexport function getNewCollectionItemNodeFromStackElement({\n\ttreeStore,\n\tcontentManagementStore,\n\tstackElement,\n}: {\n\ttreeStore: TreeStore\n\tcontentManagementStore: ContentManagementStore\n\tstackElement: CollectionStackElement | null | undefined\n}): CollectionItemNode | null {\n\tif (!stackElement || !isNewCollectionItemStackElement(stackElement)) return null\n\treturn getItemNodeFromStackElement({\n\t\ttreeStore,\n\t\tcontentManagementStore,\n\t\tstackElement,\n\t})\n}\n\nexport function getActiveCollectionStackElement(stack: readonly OverlayStackElement[]): CollectionStackElement | null {\n\treturn stack.findLast(isCollectionStackElement) ?? null\n}\n\nexport function getCollectionStackDepth(stack: readonly OverlayStackElement[]): number {\n\treturn stack.reduce((depth, element) => {\n\t\tif (isCollectionStackElement(element)) return depth + 1\n\t\treturn depth\n\t}, 0)\n}\n\nexport function postProcessOverlayStack(\n\tengine: VekterEngine,\n\tprevStack: readonly OverlayStackElement[] = [],\n): readonly OverlayStackElement[] {\n\tconst singleSelectedId =\n\t\tengine.stores.selectionStore.ids.length === 1 ? engine.stores.selectionStore.ids.at(0) : undefined\n\n\tconst validatedStack = validateOverlayStack(engine, prevStack)\n\tconst firstElement = validatedStack.at(0)\n\n\tconst selectedCollectionItem = engine.tree.getNodeWithTrait(singleSelectedId, isCollectionItemNode)\n\tconst singleSelectedItem =\n\t\tselectedCollectionItem && isCollectionItemVisibleToSessionUser(engine, selectedCollectionItem)\n\t\t\t? selectedCollectionItem\n\t\t\t: null\n\n\tif (singleSelectedItem) {\n\t\tif (!firstElement) {\n\t\t\treturn [getCollectionStackElementForItem(engine, singleSelectedItem)]\n\t\t}\n\n\t\tif (firstElement.type === \"existing\") {\n\t\t\tif (firstElement.itemId === singleSelectedItem.id) {\n\t\t\t\treturn validatedStack\n\t\t\t}\n\n\t\t\tassert(validatedStack.length === 1, \"Must dismiss overlay stack before changing selection\")\n\n\t\t\t// Selection changed, reflect that in the overlay stack\n\t\t\treturn [getCollectionStackElementForItem(engine, singleSelectedItem)]\n\t\t}\n\n\t\tif (firstElement.type === \"privateDraft\") {\n\t\t\tif (firstElement.itemId === singleSelectedItem.id) {\n\t\t\t\treturn validatedStack\n\t\t\t}\n\n\t\t\tthrow new Error(\"Must save private draft item stack before selecting a collection item\")\n\t\t}\n\n\t\tif (firstElement.type === \"temporary\") {\n\t\t\tthrow new Error(\"Must save temporary item stack before selecting a collection item\")\n\t\t}\n\n\t\tif (firstElement.type === \"arrayItem\") {\n\t\t\treturn validatedStack\n\t\t}\n\n\t\tassertNever(firstElement)\n\t}\n\n\tif (!firstElement || firstElement.type === \"temporary\" || firstElement.type === \"privateDraft\") {\n\t\treturn validatedStack\n\t}\n\n\tif (firstElement.type === \"existing\") {\n\t\tif (engine.stores.chromeStore.mainView !== ActiveMainView.ContentManagement) return validatedStack\n\t\tassert(validatedStack.length === 1, \"Must dismiss overlay stack before de-selecting collection item\")\n\t\treturn []\n\t}\n\n\tif (firstElement.type === \"arrayItem\") {\n\t\treturn validatedStack\n\t}\n\n\tassertNever(firstElement)\n}\n\nexport function validateOverlayStack(\n\tengine: VekterEngine,\n\tstack: readonly OverlayStackElement[],\n): readonly OverlayStackElement[] {\n\tconst newStack: OverlayStackElement[] = []\n\n\tfor (let i = 0; i < stack.length; i++) {\n\t\tlet element = stack[i]\n\t\tif (!element) continue\n\n\t\tif (element.type === \"temporary\") {\n\t\t\tconst existingItem = engine.tree.getNodeWithTrait(element.itemId, isCollectionItemNode)\n\t\t\tif (existingItem) {\n\t\t\t\t// The element was added to the tree, so it is no longer cache-only.\n\t\t\t\t// This can happen if: Edit Article > New Author > Go Back + Save > Go Forward\n\t\t\t\telement = getCollectionStackElementForTreeItem(engine, existingItem, {\n\t\t\t\t\tattemptedClose: element.attemptedClose,\n\t\t\t\t\tsaveAction: element.saveAction,\n\t\t\t\t\tshowErrors: element.showErrors,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tif (element.type === \"existing\") {\n\t\t\tconst item = engine.tree.getNodeWithTrait(element.itemId, isCollectionItemNode)\n\t\t\tif (item && isPrivateDraftForSessionUser(engine, item)) {\n\t\t\t\t// Undo/redo can restore a history entry captured while this item was public after the item became private again.\n\t\t\t\telement = getCollectionStackElementForTreeItem(engine, item, {\n\t\t\t\t\tsaveAction: element.saveAction,\n\t\t\t\t\tshowErrors: false,\n\t\t\t\t})\n\t\t\t} else if (item?.parentid && element.collectionId !== item.parentid) {\n\t\t\t\t// Browser history can restore existing entries from before collectionId was persisted.\n\t\t\t\telement = getCollectionStackElementForTreeItem(engine, item, {\n\t\t\t\t\tsaveAction: element.saveAction,\n\t\t\t\t\tshowErrors: false,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tif (element.type === \"privateDraft\") {\n\t\t\tconst item = engine.tree.getNodeWithTrait(element.itemId, isCollectionItemNode)\n\t\t\tif (item && isCollectionItemVisibleToSessionUser(engine, item) && !isPrivateDraftForSessionUser(engine, item)) {\n\t\t\t\telement = getCollectionStackElementForTreeItem(engine, item, {\n\t\t\t\t\tsaveAction: element.saveAction,\n\t\t\t\t\tshowErrors: false,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tconst previousElement = newStack.at(-1) ?? null\n\t\tconst isValid = validateOverlayStackElement(engine, element, previousElement)\n\t\tif (!isValid) {\n\t\t\t// Undo/redo can make the saved overlay tail stale while keeping the earlier stack entries valid.\n\t\t\tbreak\n\t\t}\n\t\tif (i > 0 && isNewCollectionItemStackElement(element) && !element.saveAction) {\n\t\t\t// Nested new items need a save action to connect them back to their parent. Stale history can miss it.\n\t\t\tbreak\n\t\t}\n\t\tnewStack.push(USE_FREEZE ? Object.freeze(element) : element)\n\t}\n\n\treturn newStack\n}\n\nfunction validateOverlayStackElement(\n\tengine: VekterEngine,\n\telement: OverlayStackElement,\n\tpreviousElement: OverlayStackElement | null,\n) {\n\tif (element.type === \"temporary\") {\n\t\tconst privateItem = engine.tree.getNodeWithTrait(element.itemId, isCollectionItemNode)\n\t\tif (privateItem) {\n\t\t\treturn false\n\t\t}\n\n\t\treturn (\n\t\t\tengine.tree.has(element.collectionId) &&\n\t\t\tengine.stores.contentManagementStore.temporaryItemCache.has(element.itemId)\n\t\t)\n\t}\n\n\tif (element.type === \"existing\") {\n\t\tconst item = engine.tree.getNodeWithTrait(element.itemId, isCollectionItemNode)\n\t\treturn item ? Boolean(item.parentid) && isCollectionItemVisibleToSessionUser(engine, item) : false\n\t}\n\n\tif (element.type === \"privateDraft\") {\n\t\tconst item = engine.tree.getNodeWithTrait(element.itemId, isCollectionItemNode)\n\t\treturn item ? item.parentid === element.collectionId && isPrivateDraftForSessionUser(engine, item) : false\n\t}\n\n\tif (element.type === \"arrayItem\") {\n\t\tif (!previousElement) return false\n\t\tif (!isCollectionStackElement(previousElement)) return false\n\n\t\tif (previousElement.itemId !== element.collectionItemId) return false\n\t\tif (isNewCollectionItemStackElement(previousElement) && previousElement.collectionId !== element.collectionId) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst collection = engine.tree.getNodeWithTrait(element.collectionId, isCollectionNode)\n\t\tif (!collection) return false\n\n\t\tconst collectionItem =\n\t\t\tengine.tree.getNodeWithTrait(element.collectionItemId, isCollectionItemNode) ??\n\t\t\tengine.stores.contentManagementStore.temporaryItemCache.get(element.collectionItemId)\n\t\tif (!collectionItem) return false\n\t\tif (!isCollectionItemVisibleToSessionUser(engine, collectionItem)) return false\n\n\t\tif (collectionItem.parentid && collectionItem.parentid !== element.collectionId) return false\n\n\t\tconst variable = collection.getVariable(element.arrayFieldId)\n\t\tif (!variable || !isArrayVariable(variable)) return false\n\n\t\tconst arrayControlProp = collectionItem.getControlProp(element.arrayFieldId)\n\t\tif (!arrayControlProp || !isStaticArrayControlProp(arrayControlProp)) return false\n\n\t\tif (!isReadonlyArray(arrayControlProp.value)) return false\n\n\t\treturn arrayControlProp.value.some(({ type, id }) => type === ControlType.Object && id === element.arrayItemId)\n\t}\n\n\tassertNever(element)\n}\n\nfunction isPrivateDraftForSessionUser(engine: VekterEngine, item: CollectionItemNode) {\n\treturn isCurrentUserPrivateDraftCollectionItem(item, {\n\t\tcurrentUserId: engine.stores.sessionStore.user.id,\n\t})\n}\n\nfunction isCollectionItemVisibleToSessionUser(engine: VekterEngine, item: CollectionItemNode) {\n\treturn isCollectionItemVisibleToCurrentUser(item, {\n\t\tcurrentUserId: engine.stores.sessionStore.user.id,\n\t})\n}\n\nexport function isNewCollectionItemStackElement(element: OverlayStackElement): element is NewCollectionStackElement {\n\treturn element.type === \"temporary\" || element.type === \"privateDraft\"\n}\n\nfunction getCollectionStackElementForItem(\n\tengine: VekterEngine,\n\titem: CollectionItemNode,\n): ExistingCollectionStackElement | PrivateDraftCollectionStackElement {\n\treturn getCollectionStackElementForTreeItem(engine, item, { showErrors: false })\n}\n\nfunction getCollectionStackElementForTreeItem(\n\tengine: VekterEngine,\n\titem: CollectionItemNode,\n\toptions: {\n\t\tsaveAction?: AddReferenceAction\n\t\tshowErrors: boolean\n\t\tattemptedClose?: boolean\n\t},\n): ExistingCollectionStackElement | PrivateDraftCollectionStackElement {\n\tif (item.parentid && isPrivateDraftForSessionUser(engine, item)) {\n\t\tconst element: PrivateDraftCollectionStackElement = {\n\t\t\tcollectionId: item.parentid,\n\t\t\titemId: item.id,\n\t\t\tshowErrors: options.showErrors,\n\t\t\ttype: \"privateDraft\",\n\t\t}\n\t\tif (options.saveAction) element.saveAction = options.saveAction\n\t\tif (options.attemptedClose) element.attemptedClose = options.attemptedClose\n\t\treturn element\n\t}\n\n\tassert(item.parentid, \"Existing collection item must have a parent collection\")\n\tconst element: ExistingCollectionStackElement = {\n\t\tcollectionId: item.parentid,\n\t\titemId: item.id,\n\t\ttype: \"existing\",\n\t}\n\tif (options.saveAction) element.saveAction = options.saveAction\n\treturn element\n}\n", "import type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { PublishStatus } from \"document/stores/PublishStatus.ts\"\n\nexport function shouldEnableDraftStatusForNewEntity(engine: VekterEngine): boolean {\n\tconst { newContentAsDraft } = engine.stores.persistedUserDefaults\n\tif (!newContentAsDraft) return false\n\n\tconst isUnpublishedDocument = engine.stores.publishStore.publishStatus === PublishStatus.Unpublished\n\tif (isUnpublishedDocument) return false\n\n\treturn true\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, assertNever, shouldBeNever, unhandledError } from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport type {\n\tAnyWebPageNode,\n\tCanvasNode,\n\tCanvasTree,\n\tCodeComponentNode,\n\tCollectionItemNode,\n\tCollectionNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCodeComponentNode,\n\tisCollectionItemNode,\n\tisCollectionNode,\n\tisFormPlainTextInputNode,\n\tisFormSelectNode,\n\tisFrameNode,\n\tisRichTextNode,\n\tisRouteSegmentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { ComputedValue } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport { isComputedValue } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport type { ValueTransform } from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport { type WithControlProps, withControlProps } from \"document/models/CanvasTree/traits/WithControlProps.ts\"\nimport { hasLayoutTemplate } from \"document/models/CanvasTree/traits/WithLayoutTemplate.ts\"\nimport { withLink } from \"document/models/CanvasTree/traits/WithLink.ts\"\nimport type { Locale, LocaleId } from \"document/models/CanvasTree/traits/WithLocales.ts\"\nimport { hasTextFit } from \"document/models/CanvasTree/traits/WithTextFit.ts\"\nimport type { EnumVariableCase } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { type WithWebMetadata, withWebMetadata } from \"document/models/CanvasTree/traits/WithWebMetadata.ts\"\nimport {\n\tgetRichTextNodesRequiringTextFitUpdates,\n\tupdateTextFitViewBox,\n} from \"document/models/CanvasTree/traits/utils/textFitHelpers.ts\"\nimport type { LocalizedTextValue, LocalizedValue, LocalizedValues } from \"document/models/LocalizedValue.ts\"\nimport { isCollectionControlProp } from \"document/models/controlProps/CollectionControlProp.ts\"\nimport type { ControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { getControlProp } from \"document/models/controlProps/getControlProps.ts\"\nimport { isVekterEngine } from \"document/useVekterEngine.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isEqual } from \"library/render/utils/isEqual.ts\"\nimport type { Mutable } from \"utils/Mutable.ts\"\nimport { isDefined, isNumber, isObject, isReadonlyArray } from \"utils/typeChecks.ts\"\nimport { ClassDiscriminator } from \"utils/withClassDiscriminator.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport { getAncestorControlsForKeyPath } from \"./ancestorControlKeyPath.ts\"\nimport type {\n\tLocalizableValueTransformName,\n\tLocalizationSource,\n\tLocalizationSourceControlProp,\n\tLocalizationSourceValueTransform,\n} from \"./getLocalizationSources.ts\"\nimport { isImageSource, isRichTextControlPropSource, isRichTextSource } from \"./getLocalizationSources.ts\"\n\nfunction getRootControlPropForCodeComponent(\n\tcomponentLoader: ComponentLoader,\n\tnode: CodeComponentNode,\n\tsource: LocalizationSourceControlProp,\n): ControlProp | undefined {\n\tconst component = componentLoader.reactComponentForIdentifier(node.codeComponentIdentifier)\n\tif (!component) return\n\n\tconst control = component.properties[source.controlPropKey]\n\tif (!control) return\n\n\tconst controlProp = getControlProp(control, node.getRawControlProp(source.controlPropKey))\n\treturn controlProp ?? undefined\n}\n\nfunction getRootControlPropForWebPage(\n\tcomponentLoader: ComponentLoader,\n\tnode: AnyWebPageNode,\n\tsource: LocalizationSourceControlProp,\n): ControlProp | undefined {\n\tif (!hasLayoutTemplate(node)) return\n\tconst component = componentLoader.reactComponentForIdentifier(node.layoutTemplateIdentifier)\n\tif (!component) return\n\n\tconst control = component.properties[source.controlPropKey]\n\tif (!control) return\n\n\tconst controlProp = getControlProp(control, node.getRawControlProp(source.controlPropKey))\n\treturn controlProp ?? undefined\n}\n\nfunction getRootControlPropForCollectionItemNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CollectionItemNode,\n\tsource: LocalizationSourceControlProp,\n): ControlProp | undefined {\n\tconst collectionNode = tree.getNodeParent(node) as CollectionNode\n\tconst controls = collectionNode.getPropertyControls(tree, componentLoader)\n\tconst control = controls[source.controlPropKey]\n\tif (!control) return\n\tconst rawControlProp = node.getControlProp(source.controlPropKey)\n\treturn getControlProp(control, rawControlProp) ?? undefined\n}\n\nfunction getRootControlProp(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CollectionItemNode | CodeComponentNode | AnyWebPageNode,\n\tsource: LocalizationSourceControlProp,\n): ControlProp | undefined {\n\tif (isWebPageNode(node, true)) {\n\t\treturn getRootControlPropForWebPage(componentLoader, node, source)\n\t}\n\tif (isCollectionItemNode(node)) {\n\t\treturn getRootControlPropForCollectionItemNode(tree, componentLoader, node, source)\n\t}\n\tif (isCodeComponentNode(node)) {\n\t\treturn getRootControlPropForCodeComponent(componentLoader, node, source)\n\t}\n\treturn undefined\n}\n\nfunction getControlPropFromNode<T extends LocalizationSourceControlProp>(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CollectionItemNode | CodeComponentNode | AnyWebPageNode,\n\tsource: T,\n): ControlProp | undefined {\n\tlet controlProp = getRootControlProp(tree, componentLoader, node, source)\n\tif (!controlProp) return\n\n\tif (!source.ancestorControlKeyPath) {\n\t\treturn controlProp\n\t}\n\n\tconst ancestorControls = getAncestorControlsForKeyPath(source.ancestorControlKeyPath)\n\n\tfor (const ancestorControl of ancestorControls) {\n\t\tif (!controlProp) return\n\t\tassert(controlProp.type === ancestorControl.type)\n\t\tif (controlProp.type === ControlType.Object) {\n\t\t\tassert(ancestorControl.type === ControlType.Object)\n\t\t\tif (!isObject(controlProp.value)) return\n\t\t\tcontrolProp = controlProp.value[ancestorControl.key]\n\t\t} else if (controlProp.type === ControlType.Array) {\n\t\t\tassert(ancestorControl.type === ControlType.Array)\n\t\t\tif (!isReadonlyArray(controlProp.value)) return\n\t\t\tcontrolProp = controlProp.value.find(item => item.id === ancestorControl.id)\n\t\t} else {\n\t\t\tshouldBeNever(controlProp)\n\t\t\treturn\n\t\t}\n\t}\n\treturn controlProp\n}\n\nfunction setControlProp<T extends LocalizationSourceControlProp>(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CollectionItemNode | (CanvasNode & WithControlProps),\n\tsource: T,\n\tnewControlProp: ControlProp,\n) {\n\tif (!source.ancestorControlKeyPath) {\n\t\tif (withControlProps(node)) {\n\t\t\tnode.setControlProp(source.controlPropKey, newControlProp)\n\t\t} else if (isCollectionItemNode(node)) {\n\t\t\tassert(isCollectionControlProp(newControlProp), \"Invalid control prop\")\n\t\t\tnode.setControlProp(source.controlPropKey, newControlProp)\n\t\t} else {\n\t\t\tassertNever(node, \"Unsupported node\")\n\t\t}\n\t\treturn\n\t}\n\n\tassert(isWebPageNode(node, true) || isCodeComponentNode(node) || isCollectionItemNode(node))\n\n\tfunction getUpdatedControlProp<T extends ControlProp>(currentControlProp: T | undefined): T | undefined {\n\t\tif (!currentControlProp) return\n\n\t\tif (currentControlProp.type === ControlType.Array || currentControlProp.type === ControlType.Object) {\n\t\t\treturn { ...currentControlProp }\n\t\t}\n\n\t\tassert(currentControlProp.type === newControlProp.type)\n\t\treturn newControlProp as T\n\t}\n\n\tconst rootControlProp = getUpdatedControlProp(getRootControlProp(tree, componentLoader, node, source))\n\tif (!rootControlProp) return\n\n\tconst ancestorControls = getAncestorControlsForKeyPath(source.ancestorControlKeyPath)\n\n\t// The control prop is set to the current control prop while walking down the controls\n\tlet controlProp = rootControlProp\n\n\tfor (const ancestorControl of ancestorControls) {\n\t\tif (!controlProp) return\n\t\tassert(controlProp.type === ancestorControl.type)\n\t\tif (controlProp.type === ControlType.Object) {\n\t\t\tassert(ancestorControl.type === ControlType.Object, \"Current control should be of type Object\")\n\n\t\t\tif (!isObject(controlProp.value)) return\n\n\t\t\tconst currentObjectPropControlProp = controlProp.value[ancestorControl.key]\n\t\t\tconst newObjectPropControlProp = getUpdatedControlProp(currentObjectPropControlProp)\n\t\t\tif (!newObjectPropControlProp) return\n\n\t\t\t// Set the updated control prop on the object while also cloning the current value\n\t\t\tcontrolProp.value = { ...controlProp.value, [ancestorControl.key]: newObjectPropControlProp }\n\n\t\t\t// Set the control prop to be the object prop\n\t\t\tcontrolProp = newObjectPropControlProp\n\t\t} else if (controlProp.type === ControlType.Array) {\n\t\t\tassert(ancestorControl.type === ControlType.Array, \"Current control should be of type Array\")\n\n\t\t\tif (!isReadonlyArray(controlProp.value)) return\n\n\t\t\tconst currentItem = controlProp.value.find(item => item.id === ancestorControl.id)\n\t\t\tconst newItem = getUpdatedControlProp(currentItem)\n\t\t\tif (!newItem) return\n\n\t\t\t// Update the array item with the updated control prop while also cloning the value\n\t\t\tcontrolProp.value = controlProp.value.map(item => (item.id === newItem.id ? newItem : item))\n\n\t\t\t// Set the control prop to be array item\n\t\t\tcontrolProp = newItem\n\t\t} else {\n\t\t\tshouldBeNever(controlProp)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif (isWebPageNode(node, true)) {\n\t\tnode.setControlProp(source.controlPropKey, rootControlProp)\n\t} else if (isCodeComponentNode(node)) {\n\t\tnode.setControlProp(source.controlPropKey, rootControlProp)\n\t} else if (isCollectionItemNode(node)) {\n\t\tassert(isCollectionControlProp(rootControlProp), \"Invalid control prop\")\n\t\tnode.setControlProp(source.controlPropKey, rootControlProp)\n\t} else {\n\t\tassertNever(node, \"Unsupported node\")\n\t}\n}\n\nfunction updateLocalizedValues<T = string>(\n\tactiveLocaleId: LocaleId,\n\tlocalizedValues: LocalizedValues<T> | undefined,\n\ttarget: LocalizationSpecificTarget,\n\tupdate: (current: LocalizedValue<T> | undefined, target: LocalizationSpecificTarget) => LocalizedValue<T> | undefined,\n): LocalizedValues<T> | undefined {\n\tconst currentLocalizedValue = localizedValues ? localizedValues[activeLocaleId] : undefined\n\tconst newLocalizedValue = update(currentLocalizedValue, target)\n\n\tif (!localizedValues && !newLocalizedValue) return\n\n\tif (!newLocalizedValue) {\n\t\tassert(localizedValues)\n\t\tconst localizedIds = Object.keys(localizedValues)\n\t\tconst localizedIdCount = localizedIds.length\n\t\t// Return `undefined` when the localized value is removed and this is the only localized value.\n\t\tif (localizedIdCount === 0) return\n\t\tif (localizedIdCount === 1 && localizedIds[0] === activeLocaleId) return\n\n\t\tconst result = { ...localizedValues }\n\t\tdelete result[activeLocaleId]\n\t\treturn result\n\t}\n\n\treturn { ...localizedValues, [activeLocaleId]: newLocalizedValue }\n}\n\nexport const testing = { updateLocalizedValues }\n\nfunction setLocalizedComputedValue<\n\tTType extends LocalizableValueTransformName,\n\tTSource extends LocalizationSourceValueTransform<TType>,\n\tTValueTransform extends Extract<ValueTransform, { name: TSource[\"type\"] }>,\n>(\n\tengine: BaseEngine,\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tsource: TSource,\n\tupdateTransform: (transform: TValueTransform) => TValueTransform,\n) {\n\tfunction updateComputedValue(value: ComputedValue): ComputedValue {\n\t\tfunction isTValueTransform(transform: ValueTransform): transform is TValueTransform {\n\t\t\treturn transform.name === source.type\n\t\t}\n\n\t\treturn {\n\t\t\t...value,\n\t\t\ttransforms: value.transforms.map(transform => {\n\t\t\t\tif (transform.id !== source.transformId) return transform\n\t\t\t\tif (!isTValueTransform(transform)) return transform\n\n\t\t\t\treturn updateTransform(transform)\n\t\t\t}),\n\t\t}\n\t}\n\n\tif (isRichTextNode(node) && isComputedValue(node.textContent)) {\n\t\tconst textContent = updateComputedValue(node.textContent)\n\t\tnode.set({ textContent })\n\t\treturn\n\t}\n\n\tif (isFormPlainTextInputNode(node) && isComputedValue(node.formInputPlaceholder)) {\n\t\tconst formInputPlaceholder = updateComputedValue(node.formInputPlaceholder)\n\t\tnode.set({ formInputPlaceholder })\n\t\treturn\n\t}\n\n\tif (isCodeComponentNode(node)) {\n\t\tconst controlProp = getControlPropFromNode(tree, engine.componentLoader, node, source)\n\n\t\tif (!controlProp) return\n\n\t\t// Only string control props are supported for localized value transforms (for now)\n\t\tassert(controlProp.type === ControlType.String)\n\n\t\tif (!isComputedValue(controlProp.value)) return\n\n\t\tconst newControlProp = { ...controlProp }\n\t\tnewControlProp.value = updateComputedValue(controlProp.value)\n\n\t\tsetControlProp(tree, engine.componentLoader, node, source, newControlProp)\n\t}\n}\n\nfunction updateLocalizedValue(\n\tengine: BaseEngine,\n\tsource: LocalizationSource,\n\tactiveLocale: Locale,\n\ttarget: LocalizationTarget,\n\t/* Return `undefined` to clear the current value. */\n\tupdate: (current: LocalizedValue | undefined, target: LocalizationSpecificTarget) => LocalizedValue | undefined,\n\teventType?: \"nonUserEvent\",\n) {\n\tengine.scheduler.process(() => {\n\t\tconst tree = engine.stores.treeStore.getDataTreeOrPartialTree()\n\t\tconst node = tree.get(source.nodeId)\n\t\tconst sourceType = source.type\n\n\t\tswitch (sourceType) {\n\t\t\tcase ControlType.String:\n\t\t\tcase ControlType.RichText:\n\t\t\tcase ControlType.Link: {\n\t\t\t\tif (!isCollectionItemNode(node) && !isCodeComponentNode(node) && !isWebPageNode(node)) return\n\n\t\t\t\tconst controlProp = getControlPropFromNode(tree, engine.componentLoader, node, source)\n\t\t\t\tif (!controlProp) break\n\t\t\t\tassert(sourceType === controlProp.type)\n\n\t\t\t\tconst newControlProp = { ...controlProp }\n\t\t\t\tconst valueLocalized = updateLocalizedValues(activeLocale.id, controlProp.valueLocalized, \"default\", update)\n\t\t\t\tnewControlProp.valueLocalized = valueLocalized\n\t\t\t\tsetControlProp(tree, engine.componentLoader, node, source, newControlProp)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"slug\": {\n\t\t\t\tif (!isCollectionItemNode(node)) return\n\n\t\t\t\tconst controlProp = getControlPropFromNode(tree, engine.componentLoader, node, source)\n\t\t\t\tassert(controlProp?.type === ControlType.String, \"expected slug control type to be a ControlType.String\")\n\n\t\t\t\tconst newControlProp = { ...controlProp }\n\t\t\t\tconst valueLocalized = updateLocalizedValues(activeLocale.id, controlProp.valueLocalized, \"default\", update)\n\n\t\t\t\tnewControlProp.valueLocalized = valueLocalized\n\n\t\t\t\tsetControlProp(tree, engine.componentLoader, node, source, newControlProp)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.Image: {\n\t\t\t\tif (!isCollectionItemNode(node) && !isCodeComponentNode(node) && !isWebPageNode(node)) return\n\n\t\t\t\tconst controlProp = getControlPropFromNode(tree, engine.componentLoader, node, source)\n\t\t\t\tif (!controlProp) break\n\n\t\t\t\tassert(sourceType === controlProp.type)\n\n\t\t\t\tconst newControlProp = { ...controlProp }\n\n\t\t\t\tif (target === \"imageSrc\" || target === \"all\") {\n\t\t\t\t\tconst valueLocalized = updateLocalizedValues(activeLocale.id, controlProp.valueLocalized, \"imageSrc\", update)\n\t\t\t\t\tnewControlProp.valueLocalized = valueLocalized\n\t\t\t\t}\n\n\t\t\t\tif (target === \"default\" || target === \"all\") {\n\t\t\t\t\tconst altLocalized = updateLocalizedValues(activeLocale.id, controlProp.altLocalized, \"default\", update)\n\t\t\t\t\tnewControlProp.altLocalized = altLocalized\n\t\t\t\t}\n\n\t\t\t\tsetControlProp(tree, engine.componentLoader, node, source, newControlProp)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.Enum: {\n\t\t\t\tif (!isCollectionNode(node)) return\n\n\t\t\t\tconst variables = node.variables.map(variable => {\n\t\t\t\t\tif (variable.id !== source.variableId) return variable\n\n\t\t\t\t\tassert(variable.type === source.type)\n\n\t\t\t\t\tconst cases = variable.cases.map((enumCase): EnumVariableCase => {\n\t\t\t\t\t\tif (enumCase.id !== source.enumCaseId) return enumCase\n\t\t\t\t\t\tconst nameLocalized = updateLocalizedValues(activeLocale.id, enumCase.nameLocalized, \"default\", update)\n\t\t\t\t\t\treturn { ...enumCase, nameLocalized }\n\t\t\t\t\t})\n\n\t\t\t\t\treturn { ...variable, cases }\n\t\t\t\t})\n\n\t\t\t\tnode.set({ variables })\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ClassDiscriminator.RootNode:\n\t\t\tcase ClassDiscriminator.WebPageNode: {\n\t\t\t\tif (!withWebMetadata(node)) return\n\n\t\t\t\tconst key: keyof WithWebMetadata = source.key === \"title\" ? \"titleLocalized\" : \"descriptionLocalized\"\n\n\t\t\t\tconst currentValue = node[key]\n\t\t\t\tconst updatedValue = updateLocalizedValues(activeLocale.id, currentValue, \"default\", update)\n\n\t\t\t\tnode.set({ [key]: updatedValue })\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ClassDiscriminator.RichTextNode: {\n\t\t\t\tif (!isRichTextNode(node)) return\n\n\t\t\t\tconst htmlLocalized = updateLocalizedValues(activeLocale.id, node.htmlLocalized, \"default\", update)\n\t\t\t\tnode.set({ htmlLocalized })\n\n\t\t\t\t// For on page we already handle this in the OnPageRichTextEditTool\n\t\t\t\tif (hasTextFit(node) && isVekterEngine(engine)) {\n\t\t\t\t\tupdateTextFitViewBox(engine, getRichTextNodesRequiringTextFitUpdates(engine, [node.id])).catch(unhandledError)\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ClassDiscriminator.FrameNode: {\n\t\t\t\tif (!isFrameNode(node)) return\n\n\t\t\t\tif (target === \"imageSrc\" || target === \"all\") {\n\t\t\t\t\tconst fillImageLocalized = updateLocalizedValues(activeLocale.id, node.fillImageLocalized, \"imageSrc\", update)\n\t\t\t\t\tnode.set({ fillImageLocalized })\n\t\t\t\t}\n\n\t\t\t\tif (target === \"default\" || target === \"all\") {\n\t\t\t\t\tconst altAttributeLocalized = updateLocalizedValues(\n\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\tnode.altAttributeLocalized,\n\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\tupdate,\n\t\t\t\t\t)\n\t\t\t\t\tnode.set({ altAttributeLocalized })\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"nodeLink\": {\n\t\t\t\tif (!withLink(node)) break\n\t\t\t\tconst linkLocalized = updateLocalizedValues(activeLocale.id, node.linkLocalized, \"default\", update)\n\t\t\t\tnode.set({ linkLocalized })\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"prefix\":\n\t\t\tcase \"suffix\": {\n\t\t\t\tif (!node) break\n\n\t\t\t\tsetLocalizedComputedValue(engine, tree, node, source, transform => {\n\t\t\t\t\tconst newTransform = { ...transform }\n\t\t\t\t\tconst newLocalizedValues = updateLocalizedValues(activeLocale.id, transform.valueLocalized, \"default\", update)\n\n\t\t\t\t\tnewTransform.valueLocalized = newLocalizedValues\n\n\t\t\t\t\treturn newTransform\n\t\t\t\t})\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"convertFromBoolean\": {\n\t\t\t\tif (!node) break\n\n\t\t\t\tsetLocalizedComputedValue(engine, tree, node, source, transform => {\n\t\t\t\t\tconst newTransform = { ...transform }\n\t\t\t\t\tif (source.property === \"truthy\") {\n\t\t\t\t\t\tnewTransform.truthyLocalized = updateLocalizedValues(\n\t\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\t\ttransform.truthyLocalized,\n\t\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\t\tupdate,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (source.property === \"falsy\") {\n\t\t\t\t\t\tnewTransform.falsyLocalized = updateLocalizedValues(\n\t\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\t\ttransform.falsyLocalized,\n\t\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\t\tupdate,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (source.property === \"fallback\" && transform.fallback) {\n\t\t\t\t\t\tnewTransform.fallback = {\n\t\t\t\t\t\t\t...transform.fallback,\n\t\t\t\t\t\t\tvalueLocalized: updateLocalizedValues(\n\t\t\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\t\t\ttransform.fallback.valueLocalized,\n\t\t\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\t\t\tupdate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn newTransform\n\t\t\t\t})\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"convertFromEnum\": {\n\t\t\t\tif (!node) break\n\n\t\t\t\tsetLocalizedComputedValue(engine, tree, node, source, transform => {\n\t\t\t\t\tconst newTransform = { ...transform }\n\n\t\t\t\t\tif (source.isDefaultCase) {\n\t\t\t\t\t\tnewTransform.defaultLocalized = updateLocalizedValues(\n\t\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\t\ttransform.defaultLocalized,\n\t\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\t\tupdate,\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\treturn newTransform\n\t\t\t\t\t}\n\n\t\t\t\t\tnewTransform.cases = transform.cases.map(transformCase => {\n\t\t\t\t\t\tif (transformCase.id !== source.caseId) return transformCase\n\n\t\t\t\t\t\tconst newTransformCase = { ...transformCase }\n\t\t\t\t\t\tconst newLocalizedValue = updateLocalizedValues(\n\t\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\t\ttransformCase.toLocalized,\n\t\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\t\tupdate,\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\tnewTransformCase.toLocalized = newLocalizedValue\n\n\t\t\t\t\t\treturn newTransformCase\n\t\t\t\t\t})\n\n\t\t\t\t\treturn newTransform\n\t\t\t\t})\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ClassDiscriminator.FormPlainTextInputNode: {\n\t\t\t\tif (!isFormPlainTextInputNode(node)) return\n\t\t\t\tnode.set({\n\t\t\t\t\tformInputPlaceholderLocalized: updateLocalizedValues(\n\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\tnode.formInputPlaceholderLocalized,\n\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\tupdate,\n\t\t\t\t\t),\n\t\t\t\t})\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ClassDiscriminator.FormSelectNode: {\n\t\t\t\tif (!isFormSelectNode(node)) return\n\t\t\t\tif (!node.formSelectOptions) return\n\n\t\t\t\tconst { optionId } = source\n\n\t\t\t\tconst newOptions = node.formSelectOptions.map(option => {\n\t\t\t\t\tif (option.id !== optionId) return option\n\n\t\t\t\t\tconst newLocalizedValue = updateLocalizedValues(activeLocale.id, option.titleLocalized, \"default\", update)\n\n\t\t\t\t\treturn { ...option, titleLocalized: newLocalizedValue }\n\t\t\t\t})\n\t\t\t\tnode.set({\n\t\t\t\t\tformSelectOptions: newOptions,\n\t\t\t\t})\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"formSelectGenericOption\": {\n\t\t\t\tif (!isFormSelectNode(node)) return\n\n\t\t\t\tconst { key } = source\n\n\t\t\t\tswitch (key) {\n\t\t\t\t\tcase \"allItemsLabel\": {\n\t\t\t\t\t\tconst newLocalizedValue = updateLocalizedValues(\n\t\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\t\tnode.allItemsLabelLocalized,\n\t\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\t\tupdate,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tnode.set({ allItemsLabelLocalized: newLocalizedValue })\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcase \"booleanTrueLabel\": {\n\t\t\t\t\t\tconst newLocalizedValue = updateLocalizedValues(\n\t\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\t\tnode.booleanTrueLabelLocalized,\n\t\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\t\tupdate,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tnode.set({ booleanTrueLabelLocalized: newLocalizedValue })\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcase \"booleanFalseLabel\": {\n\t\t\t\t\t\tconst newLocalizedValue = updateLocalizedValues(\n\t\t\t\t\t\t\tactiveLocale.id,\n\t\t\t\t\t\t\tnode.booleanFalseLabelLocalized,\n\t\t\t\t\t\t\t\"default\",\n\t\t\t\t\t\t\tupdate,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tnode.set({ booleanFalseLabelLocalized: newLocalizedValue })\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tassertNever(key)\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ClassDiscriminator.RouteSegmentNode: {\n\t\t\t\tif (!isRouteSegmentNode(node)) return\n\n\t\t\t\tconst currentValue = node.segmentLocalized\n\t\t\t\tconst updatedValue = updateLocalizedValues(activeLocale.id, currentValue, \"default\", update)\n\n\t\t\t\tnode.set({ segmentLocalized: updatedValue })\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tshouldBeNever(sourceType)\n\t\t}\n\t}, eventType)\n}\n\nfunction updateRichTextLocalizedValue(\n\tengine: BaseEngine,\n\tsource: LocalizationSource,\n\tactiveLocale: Locale,\n\tupdate: (\n\t\tcurrent: LocalizedValue<LocalizedTextValue> | undefined,\n\t\ttarget: LocalizationSpecificTarget,\n\t) => LocalizedValue<LocalizedTextValue> | undefined,\n\teventType?: \"nonUserEvent\",\n) {\n\tassert(\n\t\tisRichTextControlPropSource(source),\n\t\t\"RichTextDocument localized values are only supported for rich-text control prop sources\",\n\t)\n\n\tengine.scheduler.process(() => {\n\t\tconst tree = engine.stores.treeStore.getDataTreeOrPartialTree()\n\t\tconst node = tree.get(source.nodeId)\n\n\t\tif (!isCollectionItemNode(node) && !isCodeComponentNode(node) && !isWebPageNode(node)) return\n\n\t\tconst controlProp = getControlPropFromNode(tree, engine.componentLoader, node, source)\n\t\tif (!controlProp) return\n\t\tassert(controlProp.type === ControlType.RichText)\n\n\t\tconst newControlProp = structuredClone(controlProp)\n\t\tnewControlProp.valueLocalized = updateLocalizedValues(\n\t\t\tactiveLocale.id,\n\t\t\tcontrolProp.valueLocalized,\n\t\t\t\"default\",\n\t\t\tupdate,\n\t\t)\n\t\tsetControlProp(tree, engine.componentLoader, node, source, newControlProp)\n\t}, eventType)\n}\n\nfunction createLocalizedValueResult<T extends LocalizedTextValue>(\n\tvalue: T | null,\n\tsource: LocalizationSource,\n\ttarget: LocalizationSpecificTarget,\n\tactiveLocale: Locale,\n\tcurrentLocalizedValue: LocalizedValue<T> | undefined,\n\t{\n\t\tneedsReview,\n\t\tgeneratedByAI,\n\t\tpluginId,\n\t\tpluginMode,\n\t\tignoreTracking,\n\t\ttrackingSource,\n\t}: Pick<\n\t\tSetLocalizedValueOptions,\n\t\t\"needsReview\" | \"generatedByAI\" | \"pluginId\" | \"pluginMode\" | \"ignoreTracking\" | \"trackingSource\"\n\t>,\n): Mutable<LocalizedValue<T>> {\n\tconst result: Mutable<LocalizedValue<T>> = {\n\t\tvalue,\n\t\thash: getCurrentHash(source, target),\n\t\tlastEdited: Date.now(),\n\t}\n\n\tif (needsReview) result.needsReview = true\n\n\tconst hasSameValue = isEqual(currentLocalizedValue?.value, value)\n\n\tif (generatedByAI || (hasSameValue && currentLocalizedValue?.generatedByAI)) {\n\t\tresult.generatedByAI = true\n\t}\n\n\tif (pluginId || isDefined(pluginMode)) {\n\t\tassert(pluginId && isDefined(pluginMode), \"Cannot set only pluginId or pluginMode\")\n\t\tresult.pluginId = pluginId\n\t\tresult.pluginMode = pluginMode\n\t} else if (hasSameValue && currentLocalizedValue?.pluginId) {\n\t\tresult.pluginId = currentLocalizedValue.pluginId\n\n\t\t// Originally we did not store `pluginMode`, so sometimes only the pluginId is known\n\t\tif (currentLocalizedValue.pluginMode) {\n\t\t\tresult.pluginMode = currentLocalizedValue.pluginMode\n\t\t}\n\t}\n\n\tif (ignoreTracking) return result\n\n\trecord(currentLocalizedValue ? \"localized_value_update\" : \"localized_value_create\", {\n\t\tcode: activeLocale.code,\n\t\tvalueLength: typeof value === \"string\" ? value.length : 0,\n\t\tgeneratedByAI: Boolean(result.generatedByAI),\n\t\tsource: trackingSource,\n\t})\n\n\treturn result\n}\n\nexport interface GeneratedByAI {\n\tgeneratedByAI: boolean\n}\n\ntype SetByPlugin = Pick<LocalizedValue, \"pluginId\" | \"pluginMode\">\n\nexport type LocalizedValueTrackingSource =\n\t| \"localization_table\"\n\t| \"localization_overlay\"\n\t| \"properties_panel\"\n\t| \"content_panel_pages\"\n\t| \"batch-translate-modal\"\n\t| \"on-page-rich-text-edit-tool\"\n\t| \"plugin-api\"\n\t| \"on-page-image-edit-tool\"\n\t| \"auto-translation\"\n\nexport interface WithLocalizedValueTrackingSource {\n\ttrackingSource: LocalizedValueTrackingSource\n}\n\n/**\n * Most localization sources correspond to a single value, except for images which can target the\n * alt text (default) or image src.\n */\nexport type LocalizationSpecificTarget = \"default\" | \"imageSrc\"\n\n/**\n * Most times you are only allowed to update a single localization source value. But in some cases\n * like clearing the complete localized value, you can target all values. For example both the alt\n * text and image src when clearing a localized image.\n */\ntype LocalizationTarget = LocalizationSpecificTarget | \"all\"\n\ninterface WithLocalizationTarget {\n\ttarget: LocalizationTarget\n}\n\ninterface WithLocalizationSpecificTarget {\n\ttarget: LocalizationSpecificTarget\n}\n\nfunction getCurrentHash(source: LocalizationSource, target: LocalizationSpecificTarget) {\n\tswitch (target) {\n\t\tcase \"default\":\n\t\t\treturn source.hash\n\t\tcase \"imageSrc\":\n\t\t\tassert(isImageSource(source))\n\t\t\treturn source.imageHash\n\t\tdefault:\n\t\t\tassertNever(target)\n\t}\n}\n\nfunction promptMarkAsReadyIfNeeded(engine: VekterEngine, activeLocale: Locale) {\n\tif (!activeLocale.draft) return\n\n\tconst currentProgress = engine.stores.localizationStore.progressPerLocale[activeLocale.id]\n\tif (!isNumber(currentProgress) || currentProgress === 1) return\n\n\tengine.scheduler.runBeforeNextFrame(() => {\n\t\tconst progressAfterUpdate = engine.stores.localizationStore.progressPerLocale[activeLocale.id]\n\t\tif (progressAfterUpdate !== 1) return\n\n\t\t// The batch translate modal handles this itself\n\t\tif (engine.stores.modalStore.stack.some(({ type }) => type === ModalType.BatchTranslate)) return\n\n\t\tengine.stores.modalStore.set({\n\t\t\ttype: ModalType.LocaleReady,\n\t\t\tactiveLocale,\n\t\t\tsource: \"automatic\",\n\t\t})\n\t})\n}\n\nfunction updateLocalizedCanvasPreviewIfNeeded(engine: VekterEngine, source: LocalizationSource) {\n\tif (!engine.stores.chromeStore.isPreviewingLocaleOnCanvas) return\n\n\tconst node = engine.stores.treeStore.getDataTreeOrPartialTree().get(source.nodeId)\n\tif (!isCollectionNode(node) && !isCollectionItemNode(node)) return\n\n\tconst collectionId = isCollectionNode(node) ? node.id : node.parentid\n\tif (!collectionId) return\n\n\tengine.stores.codeGenerationStore.updateComponent(collectionId).catch(unhandledError)\n}\n\nfunction applyLocalizedValuePostUpdateEffects(engine: BaseEngine, source: LocalizationSource, activeLocale: Locale) {\n\tif (!isVekterEngine(engine)) return\n\n\tpromptMarkAsReadyIfNeeded(engine, activeLocale)\n\tupdateLocalizedCanvasPreviewIfNeeded(engine, source)\n}\n\ninterface IgnoreTracking {\n\tignoreTracking: boolean\n}\n\ninterface SetLocalizedValueOptions\n\textends\n\t\tWithLocalizedValueTrackingSource,\n\t\tPartial<GeneratedByAI>,\n\t\tSetByPlugin,\n\t\tPartial<WithLocalizationSpecificTarget>,\n\t\tPartial<IgnoreTracking> {\n\tneedsReview?: true\n\timageFocalPoint?: LocalizedValue[\"imageFocalPoint\"]\n\t/**\n\t * For example when approving or requesting a review, we want to preserve the existing text\n\t * type. Because the existing translation isn't changed.\n\t */\n\tpreserveExistingTextType?: boolean\n\teventType?: \"nonUserEvent\"\n}\n\nexport function setLocalizedValue(\n\tengine: BaseEngine,\n\tvalue: LocalizedTextValue | null,\n\tsource: LocalizationSource,\n\tactiveLocale: Locale,\n\toptions: SetLocalizedValueOptions,\n) {\n\tconst {\n\t\tneedsReview,\n\t\tgeneratedByAI,\n\t\tpluginId,\n\t\tpluginMode,\n\t\tignoreTracking,\n\t\ttarget = \"default\",\n\t\ttrackingSource,\n\t\tpreserveExistingTextType,\n\t\teventType,\n\t} = options\n\n\tassert(\n\t\ttypeof value === \"string\" || value === null || isRichTextControlPropSource(source),\n\t\t\"RichTextDocument localized values are only supported for rich-text control prop sources\",\n\t)\n\n\tif (value !== null && typeof value !== \"string\") {\n\t\tupdateRichTextLocalizedValue(\n\t\t\tengine,\n\t\t\tsource,\n\t\t\tactiveLocale,\n\t\t\tcurrentLocalizedValue => {\n\t\t\t\treturn createLocalizedValueResult(value, source, target, activeLocale, currentLocalizedValue, {\n\t\t\t\t\tneedsReview,\n\t\t\t\t\tgeneratedByAI,\n\t\t\t\t\tpluginId,\n\t\t\t\t\tpluginMode,\n\t\t\t\t\tignoreTracking,\n\t\t\t\t\ttrackingSource,\n\t\t\t\t})\n\t\t\t},\n\t\t\teventType,\n\t\t)\n\n\t\tapplyLocalizedValuePostUpdateEffects(engine, source, activeLocale)\n\t\treturn\n\t}\n\n\tupdateLocalizedValue(\n\t\tengine,\n\t\tsource,\n\t\tactiveLocale,\n\t\ttarget,\n\t\tcurrentLocalizedValue => {\n\t\t\tconst result = createLocalizedValueResult(value, source, target, activeLocale, currentLocalizedValue, {\n\t\t\t\tneedsReview,\n\t\t\t\tgeneratedByAI,\n\t\t\t\tpluginId,\n\t\t\t\tpluginMode,\n\t\t\t\tignoreTracking,\n\t\t\t\ttrackingSource,\n\t\t\t})\n\n\t\t\tif (target === \"imageSrc\") {\n\t\t\t\tif (\"imageFocalPoint\" in options) {\n\t\t\t\t\tif (options.imageFocalPoint) result.imageFocalPoint = options.imageFocalPoint\n\t\t\t\t} else if (currentLocalizedValue?.imageFocalPoint) {\n\t\t\t\t\tresult.imageFocalPoint = currentLocalizedValue.imageFocalPoint\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (preserveExistingTextType) {\n\t\t\t\tif (target === \"default\") {\n\t\t\t\t\tconst localizedValueFromSource = source.localizedValues[activeLocale.id]\n\t\t\t\t\tconst sourceValue = localizedValueFromSource?.value ?? null\n\t\t\t\t\tassert(sourceValue === value, \"The text type can only be preserved when the source value is unchanged\")\n\t\t\t\t\tif (localizedValueFromSource?.type) {\n\t\t\t\t\t\tresult.type = localizedValueFromSource.type\n\t\t\t\t\t}\n\t\t\t\t} else if (target === \"imageSrc\") {\n\t\t\t\t\t// For `imageSrc` the type is never set. Because it can't be rich-text.\n\t\t\t\t} else {\n\t\t\t\t\tassertNever(target)\n\t\t\t\t}\n\t\t\t} else if (isRichTextSource(source) && typeof value === \"string\") {\n\t\t\t\t// TODO(richTextJson): Once JSON-backed localized rich text is stored directly, remove\n\t\t\t\t// this plain-text fallback and keep the rich-text marker for those values.\n\t\t\t\tif (!isRichTextControlPropSource(source) || typeof source.richTextValue === \"string\") {\n\t\t\t\t\tresult.type = \"rich-text\"\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result\n\t\t},\n\t\teventType,\n\t)\n\n\tapplyLocalizedValuePostUpdateEffects(engine, source, activeLocale)\n}\n\nfunction getCurrentSourceValue(source: LocalizationSource, activeLocale: Locale): LocalizedTextValue | null {\n\tconst localizedValue = source.localizedValues[activeLocale.id]\n\tif (!localizedValue) return null\n\treturn localizedValue.value\n}\n\nexport function requestReviewForLocalizedValue(\n\tengine: VekterEngine,\n\tsource: LocalizationSource,\n\tactiveLocale: Locale,\n\ttrackingSource: LocalizedValueTrackingSource,\n) {\n\tlet target: LocalizationSpecificTarget = \"default\"\n\tlet value = getCurrentSourceValue(source, activeLocale)\n\tlet localizedValue = source.localizedValues[activeLocale.id]\n\n\tif (isImageSource(source)) {\n\t\tconst imageLocalizedValue = source.imageLocalizedValues[activeLocale.id]\n\t\tif (imageLocalizedValue) {\n\t\t\ttarget = \"imageSrc\"\n\t\t\tvalue = imageLocalizedValue.value\n\t\t\tlocalizedValue = imageLocalizedValue\n\t\t}\n\t}\n\n\tsetLocalizedValue(engine, value, source, activeLocale, {\n\t\tneedsReview: true,\n\t\tignoreTracking: true,\n\t\ttarget,\n\t\ttrackingSource,\n\t\tpreserveExistingTextType: true,\n\t})\n\n\trecord(\"localized_value_request_review\", {\n\t\tcode: activeLocale.code,\n\t\tvalueLength: typeof value === \"string\" ? value.length : 0,\n\t\tgeneratedByAI: Boolean(localizedValue?.generatedByAI),\n\t\tsource: trackingSource,\n\t})\n}\n\nexport function approveLocalizedValue(\n\tengine: VekterEngine,\n\tsource: LocalizationSource,\n\tactiveLocale: Locale,\n\t{ trackingSource, ignoreTracking }: WithLocalizedValueTrackingSource & Partial<IgnoreTracking>,\n) {\n\tlet target: LocalizationSpecificTarget = \"default\"\n\tlet value = getCurrentSourceValue(source, activeLocale)\n\tlet localizedValue = source.localizedValues[activeLocale.id]\n\n\tif (isImageSource(source)) {\n\t\tconst imageLocalizedValue = source.imageLocalizedValues[activeLocale.id]\n\t\tif (imageLocalizedValue) {\n\t\t\ttarget = \"imageSrc\"\n\t\t\tvalue = imageLocalizedValue.value\n\t\t\tlocalizedValue = imageLocalizedValue\n\t\t}\n\t}\n\n\tsetLocalizedValue(engine, value, source, activeLocale, {\n\t\tignoreTracking: true,\n\t\ttarget,\n\t\ttrackingSource,\n\t\tpreserveExistingTextType: true,\n\t})\n\n\tif (!ignoreTracking) {\n\t\trecord(\"localized_value_approve\", {\n\t\t\tcode: activeLocale.code,\n\t\t\tvalueLength: typeof value === \"string\" ? value.length : 0,\n\t\t\tgeneratedByAI: Boolean(localizedValue?.generatedByAI),\n\t\t\tsource: trackingSource,\n\t\t})\n\t}\n}\n\nexport function clearLocalizedValue(\n\tengine: BaseEngine,\n\tsource: LocalizationSource,\n\tactiveLocale: Locale,\n\t{\n\t\ttarget,\n\t\tignoreTracking,\n\t\ttrackingSource,\n\t\teventType,\n\t}: WithLocalizationTarget &\n\t\tWithLocalizedValueTrackingSource &\n\t\tPartial<IgnoreTracking> & { eventType?: \"nonUserEvent\" },\n) {\n\tupdateLocalizedValue(\n\t\tengine,\n\t\tsource,\n\t\tactiveLocale,\n\t\ttarget,\n\t\tcurrent => {\n\t\t\tconst value = current?.value\n\n\t\t\tif (!ignoreTracking) {\n\t\t\t\trecord(\"localized_value_clear\", {\n\t\t\t\t\tcode: activeLocale.code,\n\t\t\t\t\tvalueLength: typeof value === \"string\" ? value.length : 0,\n\t\t\t\t\tgeneratedByAI: Boolean(current?.generatedByAI),\n\t\t\t\t\tsource: trackingSource,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn undefined\n\t\t},\n\t\teventType,\n\t)\n}\n", "import { AnnotationKey, hasAnnotation } from \"@framerjs/framer-runtime/crossorigin\"\nimport type { ExternalModuleExportIdentifier } from \"@framerjs/shared\"\nimport {\n\tModuleType,\n\temptyArray,\n\tisExternalModuleIdentifier,\n\tisLocalModuleIdentifier,\n\tparseModuleIdentifier,\n\tunhandledError,\n} from \"@framerjs/shared\"\nimport { appAccelerators } from \"app/AppAccelerators.ts\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { MenuItemOptions } from \"app/menu.ts\"\nimport { isFramerVectorInfo } from \"code-generation/utils/annotations.ts\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport { RenamedIds } from \"document/components/tools/utils/updateNodeConnections.ts\"\nimport {\n\timportExternalComponent,\n\tisImportableComponentModuleType,\n\tshowUnlinkVectorSetModal,\n\tunlinkAndReplaceAll,\n\tunlinkComponent,\n} from \"document/components/unlinking/index.ts\"\nimport { isBuiltInVectorSetFromIdentifier } from \"document/components/unlinking/utils.ts\"\nimport type { CodeComponentNode, FrameNode, MaybeNodeID, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { ExternalModuleNode } from \"document/models/CanvasTree/nodes/ExternalModuleNode.ts\"\nimport { isSmartComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { getActiveVariantIdForLocalSmartComponentInstance } from \"document/models/CanvasTree/nodes/utils/smartComponentInstanceHelpers.ts\"\nimport { convertFrameToCanvas } from \"document/models/CanvasTree/utils/geometry.ts\"\nimport type { SelectScopeOptions } from \"document/stores/ScopeStore.ts\"\nimport type { ActiveContentPanelTab } from \"document/utils/ActiveEditorType.ts\"\nimport { toast, toastProgress } from \"web/lib/toaster.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport { getIsViewOnly } from \"web/pages/project/permissions/isViewOnly.ts\"\nimport { EditBehavior } from \"../chrome/insertSidebar/types.ts\"\nimport { getEntityDefinitionFromCodeComponentIdentifier } from \"../utils/getEntityDefinitionFromCodeComponentIdentifier.ts\"\nimport { getEditInPluginLabel, getPluginManifestFromModuleIdentifier, shouldEditViaPlugin } from \"../utils/plugins.ts\"\nimport { ContextAction } from \"./contextActions.ts\"\nimport { isFramerModule } from \"./defaultComponents.ts\"\nimport { editCodeComponentInPlugin } from \"./editCodeComponentInPlugin.ts\"\n\nexport function goToLocalSourceNode(\n\tsourceNodeId: NodeID,\n\tengine: VekterEngine,\n\tvariant: MaybeNodeID,\n\toptions: SelectScopeOptions,\n) {\n\tengine.stores.canvasStore.invalidateTransformUntilRendered(() => {\n\t\ttry {\n\t\t\tengine.stores.scopeStore.select(sourceNodeId, options)\n\n\t\t\tengine.stores.codeEditorStore.closeEditor()\n\t\t} catch {\n\t\t\t// The smart component node has probably been deleted.\n\t\t\t// This uses same toast as deep linking (see zoomToActiveNode in VekterEngine.ts).\n\t\t\trecord(\"open_primary_component_fail\", {})\n\t\t\ttoast({\n\t\t\t\ttype: \"add\",\n\t\t\t\tvariant: \"error\",\n\t\t\t\tkey: \"invalid-deep-link\",\n\t\t\t\tprimaryText: \"Primary component\",\n\t\t\t\tsecondaryText: \"has been deleted.\",\n\t\t\t\ticon: \"error\",\n\t\t\t\tduration: 10_000,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tif (!variant) return\n\t\tconst variantNode = engine.tree.getNode(variant)\n\t\tif (variantNode && engine.tree.getScopeNodeFor(variantNode)?.id === sourceNodeId) {\n\t\t\tengine.stores.selectionStore.set(variantNode.id)\n\t\t\tengine.stores.canvasStore.zoomToCenter(convertFrameToCanvas(engine.tree, variantNode), {\n\t\t\t\tanimated: false,\n\t\t\t\tmaxZoom: 1,\n\t\t\t})\n\t\t}\n\t})\n}\n\n/**\n * Checks if the edit behavior is blocked for a given component:\n * - It is a framerModule and there isn't a special editBehavior override\n * - The component has the @framerDisableUnlink annotation specified\n *\n * @param engine - The engine instance\n * @param identifier - The identifier of the component\n * @returns true if the edit behavior is blocked, false otherwise\n */\nexport function checkEditBehaviorBlocked(engine: VekterEngine, identifier: ExternalModuleExportIdentifier): boolean {\n\tconst editBehavior = engine.stores.insertSidebarStore.getEditBehavior(identifier.moduleId)\n\tconst framerModule = isFramerModule(engine.stores.treeStore.tree, identifier)\n\tconst annotations = engine.componentLoader.componentForIdentifier(identifier.value)?.annotations\n\treturn (\n\t\t(framerModule && editBehavior === EditBehavior.Block) ||\n\t\thasAnnotation(annotations, AnnotationKey.FramerDisableUnlink)\n\t)\n}\n\nfunction editInfo(\n\tcodeComponentIdentifier: string,\n\tengine: VekterEngine,\n\tvariant: MaybeNodeID,\n\toptions: SelectScopeOptions & {\n\t\tnode?: CodeComponentNode\n\t\twithUnlinkModal?: boolean\n\t\texternalModuleType?: ModuleType | string\n\t\tincludeAccelerator?: boolean\n\t},\n): readonly MenuItemOptions[] {\n\tconst identifier = parseModuleIdentifier(codeComponentIdentifier)\n\tconst isViewOnly = getIsViewOnly(engine, \"canDesign\")\n\tconst { includeAccelerator = true } = options\n\n\tif (\n\t\tisLocalModuleIdentifier(identifier) &&\n\t\t(identifier.type === ModuleType.Canvas ||\n\t\t\tidentifier.type === ModuleType.Screen ||\n\t\t\tidentifier.type === ModuleType.Vector)\n\t) {\n\t\t// Extract the type and name from the\n\t\treturn [\n\t\t\t{\n\t\t\t\tlabel: isViewOnly ? Dictionary.View : Dictionary.Edit,\n\t\t\t\taccelerator: includeAccelerator ? appAccelerators.fakeSelectChildren : undefined,\n\t\t\t\tclick: () => {\n\t\t\t\t\tif (identifier.type === ModuleType.Vector) {\n\t\t\t\t\t\tconst vectorInfo = engine.stores.modulesStore\n\t\t\t\t\t\t\t.forType(ModuleType.Vector)\n\t\t\t\t\t\t\t.getByStableName(identifier.localIdName)\n\t\t\t\t\t\t\t?.annotations(null, \"default\")?.[AnnotationKey.FramerVector]\n\t\t\t\t\t\tif (!isFramerVectorInfo(vectorInfo)) return\n\t\t\t\t\t\tconst { set } = vectorInfo\n\t\t\t\t\t\tgoToLocalSourceNode(set.id, engine, identifier.localIdName, options)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// For smartComponents the part after \"/\" in the localId is the node ID.\n\t\t\t\t\tconst [, nodeId] = identifier.localId.split(\"/\")\n\t\t\t\t\tif (!nodeId) return\n\t\t\t\t\tgoToLocalSourceNode(nodeId, engine, variant, options)\n\t\t\t\t},\n\t\t\t},\n\t\t]\n\t} else if (isExternalModuleIdentifier(identifier) && identifier.kind === \"externalModuleExport\") {\n\t\tif (options.node?.isVectorInstance) {\n\t\t\tif (isBuiltInVectorSetFromIdentifier(engine, codeComponentIdentifier)) {\n\t\t\t\treturn emptyArray()\n\t\t\t}\n\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tlabel: Dictionary.Edit,\n\t\t\t\t\taccelerator: includeAccelerator ? appAccelerators.fakeSelectChildren : undefined,\n\t\t\t\t\tclick: () => showUnlinkVectorSetModal(engine, identifier.moduleId, options.node?.id),\n\t\t\t\t\tenabled: !isViewOnly,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\n\t\tconst editBehavior = engine.stores.insertSidebarStore.getEditBehavior(identifier.moduleId)\n\n\t\tconst externalModuleNode = engine.stores.treeStore.tree.getNode<ExternalModuleNode>(identifier.moduleId)\n\t\t// Editing any component coming from a Page from the insert menu should\n\t\t// unlink and replace all instances of that component.\n\t\tconst sourceProjectIdForInsertPages = \"1h0OTH9KlHTd4pyc9CLt\"\n\t\tconst shouldAutoUnlinkAndReplaceAll =\n\t\t\toptions.externalModuleType === ModuleType.Canvas &&\n\t\t\texternalModuleNode &&\n\t\t\texternalModuleNode.ownerId === sourceProjectIdForInsertPages\n\n\t\t// Early exit if either:\n\t\t// - It is a framerModule and there isn't a special editBehavior override\n\t\t// - The component has the @framerDisableUnlink annotation specified\n\t\tif (checkEditBehaviorBlocked(engine, identifier)) {\n\t\t\treturn emptyArray()\n\t\t}\n\n\t\tif (!isImportableComponentModuleType(options.externalModuleType)) {\n\t\t\treturn emptyArray()\n\t\t}\n\t\tconst { node, withUnlinkModal, externalModuleType } = options\n\n\t\tif (node && editBehavior === EditBehavior.AutoDetach) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tlabel: \"Detach Instance\",\n\t\t\t\t\tenabled: !isViewOnly,\n\t\t\t\t\tclick: async () => {\n\t\t\t\t\t\tengine.beginUndoGroup()\n\n\t\t\t\t\t\ttoastProgress(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkey: \"auto-detach\",\n\t\t\t\t\t\t\t\tprogress: {\n\t\t\t\t\t\t\t\t\tvariant: \"progress\",\n\t\t\t\t\t\t\t\t\tprimaryText: \"Detaching component\",\n\t\t\t\t\t\t\t\t\tsecondaryText: \"instance\u2026\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\t\tvariant: \"error\",\n\t\t\t\t\t\t\t\t\tprimaryText: \"Failed to detach\",\n\t\t\t\t\t\t\t\t\tsecondaryText: \"component instance.\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tawait autoDetach(node, engine, identifier, externalModuleType)\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t).catch(unhandledError)\n\n\t\t\t\t\t\tengine.endUndoGroup()\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\n\t\t// Note: components from the template pages project should auto unlink and replace all.\n\t\tif (shouldAutoUnlinkAndReplaceAll) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tlabel: Dictionary.Edit,\n\t\t\t\t\taccelerator: includeAccelerator ? appAccelerators.fakeSelectChildren : undefined,\n\t\t\t\t\tclick: () => {\n\t\t\t\t\t\tunlinkAndReplaceAll(engine, {\n\t\t\t\t\t\t\tidentifier,\n\t\t\t\t\t\t\tmoduleType: externalModuleType,\n\t\t\t\t\t\t\tinstance: node,\n\t\t\t\t\t\t\tenterIsolation: true,\n\t\t\t\t\t\t}).catch(unhandledError)\n\t\t\t\t\t},\n\t\t\t\t\tenabled: !isViewOnly,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\n\t\t// Note: `EditBehavior.AutoUnlink` is handled inside of `unlinkComponent()`\n\t\treturn [\n\t\t\t{\n\t\t\t\tlabel: Dictionary.Unlink,\n\t\t\t\tclick: () => {\n\t\t\t\t\tunlinkComponent(engine, {\n\t\t\t\t\t\tidentifier,\n\t\t\t\t\t\tmoduleType: externalModuleType,\n\t\t\t\t\t\tinstance: node,\n\t\t\t\t\t\twithUnlinkModal,\n\t\t\t\t\t\tenterIsolation: true,\n\t\t\t\t\t}).catch(unhandledError)\n\t\t\t\t},\n\t\t\t\tenabled: !isViewOnly,\n\t\t\t},\n\t\t]\n\t}\n\t// Assume that this is a code component.\n\tconst definition = getEntityDefinitionFromCodeComponentIdentifier(engine.componentLoader, codeComponentIdentifier)\n\t// Only handle code components that were made in the current project.\n\tif (!definition || definition.type !== \"component\" || definition.depth !== 0) return emptyArray()\n\n\tconst goBackIfNeeded = options.keepHistory\n\t\t? undefined\n\t\t: () => {\n\t\t\t\tengine.stores.scopeStore.goBack()\n\t\t\t}\n\n\tconst pluginManifest = getPluginManifestFromModuleIdentifier(\n\t\tengine.stores.treeStore,\n\t\tengine.stores.modulesStore,\n\t\tengine.stores.pluginStore,\n\t\tidentifier,\n\t)\n\tconst editInPlugin =\n\t\tpluginManifest &&\n\t\tshouldEditViaPlugin(engine.stores.modulesStore, identifier) &&\n\t\t!isViewOnly &&\n\t\tisLocalModuleIdentifier(codeComponentIdentifier)\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: getEditInPluginLabel(pluginManifest),\n\t\t\t\t\t\tclick: () => {\n\t\t\t\t\t\t\tgoBackIfNeeded?.()\n\t\t\t\t\t\t\tvoid editCodeComponentInPlugin(engine, codeComponentIdentifier, pluginManifest)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []\n\n\treturn [\n\t\t...editInPlugin,\n\t\t{\n\t\t\tlabel: `${isViewOnly ? Dictionary.View : Dictionary.Edit} ${Dictionary.Code}`,\n\t\t\tclick: () => {\n\t\t\t\tgoBackIfNeeded?.()\n\t\t\t\tengine.stores.codeEditorStore.editFile(definition.file)\n\t\t\t},\n\t\t\tenabled: isLocalModuleIdentifier(codeComponentIdentifier),\n\t\t},\n\t]\n}\n\nexport async function autoDetach(\n\tnode: CodeComponentNode,\n\tengine: VekterEngine,\n\tidentifier: ExternalModuleExportIdentifier,\n\texternalModuleType: ModuleType | string,\n): Promise<FrameNode | null> {\n\tconst renamedIds = new RenamedIds()\n\t// Unlink the component but dont enter isolation or create a\n\t// SmartComponentNode. Instead detach into a temporary tree.\n\tconst info = await importExternalComponent(engine, {\n\t\tidentifier,\n\t\tmoduleType: externalModuleType,\n\t\tinstance: node,\n\t\trenamedIds,\n\t\tisAutoDetach: true,\n\t\tenterIsolation: false,\n\t})\n\tif (!info) return null\n\tconst { node: newSmartComponentNode } = info\n\tif (!isSmartComponentNode(newSmartComponentNode)) return null\n\n\t// Detach the smart component.\n\treturn engine.scheduler.processWhenReadyAsync(() => {\n\t\tconst replacement = ContextAction.detachSmartComponentOrWebPageInstance(\n\t\t\tengine,\n\t\t\tnode.draftOrCurrent(),\n\t\t\tnewSmartComponentNode,\n\t\t\trenamedIds,\n\t\t)\n\t\tif (replacement) engine.stores.selectionStore.set(replacement.id)\n\t\treturn replacement\n\t})\n}\n\nfunction editActionForEditInfo(editInfo: readonly MenuItemOptions[] | undefined) {\n\t// Currently this `.find` always matches either the first item or no item, so it could\n\t// be `const [editInfo] = ...` instead, but the order of items or their `.enabled` logic\n\t// might change, so this ensures that we continue getting what we want, which is \"pick\n\t// the first enabled code action, if any\".\n\tconst editItem = editInfo?.find(item => item.enabled !== false) // \"enabled: undefined\" means \"true\"\n\treturn editItem?.click\n}\n\ninterface EditInfoForCodeComponentIdentifierOptions extends SelectScopeOptions {\n\tnode?: CodeComponentNode\n\twithUnlinkModal?: boolean\n\texternalModuleType?: ModuleType | string\n\tincludeAccelerator?: boolean\n}\n\nexport function editInfoForCodeComponentIdentifier(\n\tcodeComponentIdentifier: string,\n\tengine: VekterEngine,\n\toptions: EditInfoForCodeComponentIdentifierOptions,\n): readonly MenuItemOptions[] {\n\treturn editInfo(codeComponentIdentifier, engine, null, options)\n}\n\nexport function editActionForCodeComponentIdentifier(\n\tcodeComponentIdentifier: string,\n\tengine: VekterEngine,\n\toptions: EditInfoForCodeComponentIdentifierOptions,\n) {\n\treturn editActionForEditInfo(editInfoForCodeComponentIdentifier(codeComponentIdentifier, engine, options))\n}\n\ninterface EditInfoForCodeComponentOptions {\n\twithUnlinkModal?: boolean\n\texternalModuleType?: ModuleType | string\n\tactivateContentPanel?: ActiveContentPanelTab\n}\n\nexport function editInfoForCodeComponent(\n\tnode: CodeComponentNode,\n\tengine: VekterEngine,\n\t{ withUnlinkModal = true, externalModuleType, activateContentPanel }: EditInfoForCodeComponentOptions = {},\n): readonly MenuItemOptions[] {\n\tconst activeVariant = getActiveVariantIdForLocalSmartComponentInstance(engine.tree, node)\n\treturn editInfo(node.codeComponentIdentifier, engine, activeVariant, {\n\t\tkeepHistory: true,\n\t\tnode,\n\t\twithUnlinkModal,\n\t\texternalModuleType,\n\t\tactivateContentPanel,\n\t})\n}\n\nexport function editActionForCodeComponent(\n\tnode: CodeComponentNode,\n\tengine: VekterEngine,\n\toptions: EditInfoForCodeComponentOptions = {},\n) {\n\treturn editActionForEditInfo(editInfoForCodeComponent(node, engine, options))\n}\n", "import type { CollectionItemNode, CollectionNode } from \"document/models/CanvasTree/index.ts\"\nimport type { VariableID } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { useEffect, useMemo, useRef } from \"react\"\nimport { isShallowSetEqual } from \"utils/isShallowEqual.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\n\nexport type TakenSlugs = ReadonlyMap<VariableID, ReadonlySet<string>>\n\nexport function getTakenSlugs(collection: CollectionNode, selectedCollectionItem: CollectionItemNode): TakenSlugs {\n\tconst takenSlugs = new Map<VariableID, ReadonlySet<string>>()\n\n\tconst slugVariables = collection.variables.filter(variable => variable.type === \"slug\")\n\n\tfor (const slugVariable of slugVariables) {\n\t\tconst slugValues = new Set<string>()\n\t\ttakenSlugs.set(slugVariable.id, slugValues)\n\n\t\tfor (const item of collection.getUnsortedChildren()) {\n\t\t\tif (item.id === selectedCollectionItem.id) continue\n\n\t\t\tconst controlProp = item.getControlProp(slugVariable.id)\n\t\t\tif (!controlProp) continue\n\t\t\tif (!isString(controlProp.value)) continue\n\n\t\t\tslugValues.add(controlProp.value)\n\t\t}\n\t}\n\n\treturn takenSlugs\n}\n\nexport function useTakenSlugs(\n\tcollection: CollectionNode | undefined,\n\tselectedCollectionItem: CollectionItemNode | undefined,\n): TakenSlugs {\n\tconst previousResult = useRef<ReadonlyMap<VariableID, ReadonlySet<string>> | null>(null)\n\n\tconst result: TakenSlugs = useMemo(() => {\n\t\tif (!collection || !selectedCollectionItem) return new Map()\n\n\t\tconst latestTakenSlugs = getTakenSlugs(collection, selectedCollectionItem)\n\n\t\tconst previousTakenSlugs = previousResult.current\n\t\tif (!previousTakenSlugs) {\n\t\t\treturn latestTakenSlugs\n\t\t}\n\n\t\tconst takenSlugs = new Map<VariableID, ReadonlySet<string>>()\n\n\t\tfor (const [variableId, slugValues] of latestTakenSlugs) {\n\t\t\ttakenSlugs.set(variableId, slugValues)\n\n\t\t\tconst previousSlugValues = previousTakenSlugs.get(variableId)\n\t\t\tif (!previousSlugValues) continue\n\n\t\t\tif (!isShallowSetEqual(previousSlugValues, slugValues)) continue\n\n\t\t\ttakenSlugs.set(variableId, previousSlugValues)\n\t\t}\n\n\t\treturn takenSlugs\n\t}, [collection, selectedCollectionItem])\n\n\tuseEffect(() => {\n\t\tpreviousResult.current = result\n\t}, [result])\n\n\treturn result\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { CollectionItemNode, CollectionNode } from \"document/models/CanvasTree/index.ts\"\nimport { isSlugVariableDefinition } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport type { ControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { slugify } from \"library/utils/slugify.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport type { TakenSlugs } from \"../useTakenSlugs.ts\"\n\nexport function maybeAutoGenerateSlugForCollectionItem(\n\tcollectionNode: CollectionNode,\n\tcollectionItemNode: CollectionItemNode,\n\ttakenSlugs: TakenSlugs,\n\tpendingControlProps?: ReadonlyMap<string, ControlProp>,\n): false | { changedControlProp: string } {\n\tfor (const variable of collectionNode.variables) {\n\t\tif (variable.type === \"divider\") continue\n\t\tif (!isSlugVariableDefinition(variable)) continue\n\n\t\tconst existingSlugValueForVariable = takenSlugs.get(variable.id)\n\t\tassert(existingSlugValueForVariable, \"existingSlugValueForVariable is required for slug fields\")\n\n\t\tconst slugControlProp = pendingControlProps?.get(variable.id) ?? collectionItemNode.getControlProp(variable.id)\n\t\tconst hasNoValueEntered = !slugControlProp || !isString(slugControlProp.value) || !slugControlProp.value.length\n\n\t\tif (hasNoValueEntered && variable.associatedStringVariable) {\n\t\t\t// We have no slug value yet, let's try to create one from the associated value\n\t\t\tconst associatedControlProp =\n\t\t\t\tpendingControlProps?.get(variable.associatedStringVariable) ??\n\t\t\t\tcollectionItemNode.getControlProp(variable.associatedStringVariable)\n\t\t\tif (associatedControlProp && isString(associatedControlProp.value)) {\n\t\t\t\tconst generatedSlug = slugify(associatedControlProp.value)\n\t\t\t\tif (generatedSlug.length && !existingSlugValueForVariable.has(generatedSlug)) {\n\t\t\t\t\tcollectionItemNode.setControlProp(variable.id, {\n\t\t\t\t\t\ttype: ControlType.String,\n\t\t\t\t\t\tvalue: generat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root", "scope", "log", "key", "log", "log", "key", "meta", "key", "key", "parentId", "wrap", "name", "log", "key", "log", "log", "log", "key", "all", "siblings", "own", "html", "body", "html", "tbody", "head", "child", "key", "stringify", "handle", "emptyChildren", "handle", "text", "html", "element", "key", "option", "editInfo"]
}
