{
  "version": 3,
  "sources": ["../../src/document/models/CanvasTree/TreeTimeline.ts", "../../src/document/models/CanvasTree/expandScopeReplicas.ts", "../../src/document/models/CanvasTree/nodes/branches/branchName.ts", "../../src/document/crdt/sync/getScopesToLoad.ts", "../../src/document/crdt/data-tree/DataTreeProxy.ts", "../../src/document/crdt/data-tree/dataNodeSymbol.ts", "../../src/document/crdt/data-tree/dataTreeNodes.ts", "../../src/document/crdt/data-tree/DataTree.ts", "../../src/document/crdt/data-tree/PersistedNodeCaches.ts", "../../src/document/crdt/sync/CrdtBranchStoreRegistry.ts", "../../src/document/crdt/sync/nodeChangeCompat.ts", "../../src/document/crdt/sync/CrdtTreeCommitter.ts", "../../src/utils/sleep.ts", "../../src/document/utils/beforeUnloadHandler.ts", "../../src/document/components/chrome/localization/ancestorControlKeyPath.ts", "../../src/utils/getWordCount.ts", "../../src/document/components/chrome/QuickActions/utils/LocalizationScope.ts", "../../src/document/components/chrome/contentManagement/utils/fieldWarningMessages.ts", "../../src/document/components/chrome/localization/getTitleForLocalizationScope.ts", "../../src/document/components/chrome/localization/removeStylesFromRichText.ts", "../../src/document/components/chrome/localization/richTextModuleTranslation.ts", "../../src/document/components/chrome/localization/getLocalizationSources.ts", "../../src/web/lib/multiplayerService.ts", "../../src/document/components/chrome/analytics/utils/funnel-stats/getConversionRateCredibleInterval.ts", "../../src/document/components/chrome/analytics/utils/funnel-stats/getTimeRange.ts", "../../src/document/components/chrome/analytics/utils/funnel-stats/getFunnelConversionRate.ts", "../../src/document/components/chrome/analytics/utils/funnel-stats/getFunnelDropOffs.ts", "../../src/document/components/chrome/analytics/utils/funnel-stats/getGroupedFunnelPoints.ts", "../../src/document/components/chrome/analytics/utils/fetchUtils.ts", "../../src/document/base-engine/BaseHostnameStore.ts", "../../src/code-generation/components/generateArrayFromHumanReadableFunctionName.ts", "../../src/code-generation/components/createControlsTypesAndReactProps.ts", "../../src/document/models/CanvasTree/traits/utils/calculateModuleRevision.ts", "../../src/code-generation/TelemetrySession.ts", "../../src/code-generation/utils/valueTransformCollector/functions/enumToDisplayNameFromVariable.ts", "../../src/modules/binaryAssets.ts", "../../src/code-generation/components/BinaryAssetCollector.ts", "../../src/code-generation/components/cms/bundled/getRichTextJsonResolver.tsx", "../../src/code-generation/components/cms/bundled/assert.ts", "import-bundle:/Users/alex/Projects/FramerStudio/src/app/vekter/src/code-generation/components/cms/bundled/getRichTextJsonResolver.tsx?bundle", "../../src/code-generation/components/cms/RichTextJsonCollector.ts", "../../src/code-generation/components/cms/VectorCollector.ts", "../../src/code-generation/components/cms/bundled/BufferReader.ts", "../../src/code-generation/components/cms/bundled/BufferWriter.ts", "import-bundle:/Users/alex/Projects/FramerStudio/src/app/vekter/src/code-generation/components/cms/bundled/DatabaseCollection.ts?bundle", "import-bundle:/Users/alex/Projects/FramerStudio/src/app/vekter/src/code-generation/components/cms/bundled/DraftDatabaseCollection.ts?bundle", "../../src/code-generation/components/cms/bundled/models/DatabaseItemPointerModel.ts", "../../src/code-generation/components/cms/bundled/models/DatabaseValueModel.ts", "../../src/code-generation/components/cms/bundled/models/DatabaseDictionaryIndexModel.ts", "../../src/code-generation/components/cms/bundled/models/DatabaseItemModel.ts", "../../src/code-generation/components/cms/replaceBinaryModuleUrls.ts", "../../src/code-generation/components/cms/serializeDatabase.ts", "../../src/code-generation/components/GeneratedCollection.ts", "../../src/code-generation/components/serializeFonts.ts", "../../src/code-generation/components/GeneratedComponentPresets.ts", "../../src/code-generation/components/GeneratedPrototypeComponent.ts", "../../src/code-generation/components/processNodes/processRoot.ts", "../../src/code-generation/components/GeneratedPrototypeScreenComponent.ts", "../../src/code-generation/components/GeneratedStylePreset.ts", "../../src/code-generation/utils/getVariantSize.ts", "../../src/code-generation/components/processNodes/createBreakpoint.ts", "../../src/code-generation/components/GeneratedVariantComponent.ts", "../../src/code-generation/components/getGeneratedByFramerComment.ts", "../../src/code-generation/components/serializeVector.ts", "../../src/code-generation/components/serializeVectorSet.ts", "../../src/document/components/chrome/shared/VectorImport.ts", "../../src/code-generation/codeGenVersion.ts", "../../src/code-generation/textStyleVersion.ts", "../../src/document/components/chrome/shared/ModuleTooLargeToast.tsx", "../../src/document/utils/CodeGenerationPersistenceQueue.ts", "../../src/document/stores/CodeGenerationStore.ts", "../../src/document/useDeprecatedEngineState.ts", "../../src/document/models/CanvasTree/utils/moduleBackedInstanceUpdate.ts", "../../src/document/models/CanvasTree/utils/getNodeError.ts", "../../src/document/stores/formErrorReason.ts", "../../src/document/base-engine/BaseTreeStore.ts", "../../src/utils/getCollectionUtilForNode.ts", "../../src/export/collectPageEffects.ts", "../../src/export/collectNodesInPrototypeNavigationChain.ts", "../../src/web/pages/project/lib/compressionStream.ts"],
  "sourcesContent": ["import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, getLogger } from \"@framerjs/shared\"\nimport type { CrdtDebugRecord } from \"document/crdt/CRDTDebugRecord.ts\"\nimport { setTreeMode } from \"document/stores/TreeMode.ts\"\nimport { isEqual } from \"library/index.ts\"\nimport type { CanvasTree } from \"./CanvasTree.ts\"\nimport type { NodeChange, ReversibleNodeChange } from \"./TreeDiff.ts\"\nimport { jsonApplyChanges, jsonApplyReverseChanges, mergeNodeChanges, nodeChange } from \"./TreeDiff.ts\"\nimport { computeOverrideChanges } from \"./TreeDiffOverrides.ts\"\nimport { safeLoadDocument } from \"./TreeRepair.ts\"\nimport type { CommitLocalTreeResult, TreeUpdater } from \"./TreeUpdater.ts\"\nimport type { CanvasNode } from \"./nodes/CanvasNode.ts\"\nimport type { NodeID } from \"./nodes/NodeID.ts\"\n\nconst log = getLogger(\"tree:timeline\")\n\nconst LOCAL_CHANGES_VALID_FOR_MS = 60_000\nconst REMOTE_CONNECTION_VALID_FOR_MS = 60_000\ninterface NodeChangesById {\n\t[key: NodeID]: NodeChange\n}\n\nexport interface ReversibleNodeChangesById {\n\t[key: NodeID]: ReversibleNodeChange\n}\n\n/** The ChangeTrackingCursor tracks the local and remote tree pointers used to\n * create the previous diff from, so that a next request can produce the most\n * relevant diff. We need to track the remote tree pointer, because new remote\n * trees are sometimes inserted in the middle, sort-of rebasing all trees in\n * front of it. */\nexport interface ChangeTrackingCursor {\n\tepoch: number\n\tlocalTree: number\n\tremoteTree: number\n\ttree: CanvasTree\n\treadonly timeline: TreeUpdater\n}\n\n/**\n * The class should remain private but we need the type\n * for the TreeIndex and any future consumers.\n */\nexport interface NodeChangesReader {\n\tread(): Map<NodeID, NodeChange[]>\n\tclear(): void\n\tdispose(): void\n}\n\n/**\n * NodeChangesBuffer reflect all the local and remote changes based\n * on the NodeTree.previousDraftNodes just before we release memory.\n * Including Replica changes that are not tracked in a NodeChange.\n */\nexport class NodeChangesBuffer implements NodeChangesReader {\n\tconstructor(private readonly nodeChangesBuffers: Set<NodeChangesBuffer>) {\n\t\tthis.nodeChangesBuffers.add(this)\n\t}\n\n\tchanges = new Map<NodeID, NodeChange[]>()\n\n\ttrackChange(id: NodeID, change: NodeChange | null) {\n\t\tconst existing = this.changes.get(id)\n\t\tif (existing) {\n\t\t\tif (change) {\n\t\t\t\texisting.push(change)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.changes.set(id, change ? [change] : [])\n\t}\n\n\t/** It returns and resets the current tracked readers */\n\tread(): Map<NodeID, NodeChange[]> {\n\t\tconst result = this.changes\n\t\tthis.changes = new Map()\n\t\treturn result\n\t}\n\n\tclear() {\n\t\tthis.changes = new Map()\n\t}\n\n\tdispose() {\n\t\tthis.nodeChangesBuffers.delete(this)\n\t}\n}\n\nexport class TimelineEntry {\n\twasScopeInsert = false\n\tversion = 0\n\ttimestamp = performance.now()\n\n\tconstructor(\n\t\tpublic tree: CanvasTree,\n\t\tpublic changes: NodeChange[],\n\t\tpublic editReasons: string[] = [],\n\t\tpublic wasRebase = false,\n\t) {}\n\n\ttoDebugData() {\n\t\treturn {\n\t\t\tversion: this.version,\n\t\t\tchanges: this.changes,\n\t\t\teditReasons: this.editReasons,\n\t\t\twasScopeInsert: this.wasScopeInsert,\n\t\t\twasRebase: this.wasRebase,\n\t\t}\n\t}\n}\n\nexport interface TimelineFlags {\n\tignoreInUndo?: boolean\n\tignoreInCodeGeneration?: boolean\n\tisUserEdit?: boolean\n\tuserId?: string\n}\n\n/** This class keeps track of diffs seen, rolling them into one final change per node id. */\nexport class RollingDiff {\n\tidToChanges: Map<string, NodeChange> = new Map()\n\n\t/** Returns an array with the current changes per node. */\n\tgetChanges(): NodeChange[] {\n\t\treturn Array.from(this.idToChanges.values())\n\t}\n\n\taddChanges(changes: NodeChange[] | undefined) {\n\t\tif (!changes) return\n\t\tfor (const change of changes) {\n\t\t\tlet storedChange = this.idToChanges.get(change.id)\n\t\t\tif (!storedChange) {\n\t\t\t\t// The class mutates the node change object. So we have to start with an object we\n\t\t\t\t// own, not the first change we receive.\n\t\t\t\tstoredChange = { id: change.id, to: {} }\n\t\t\t\tthis.idToChanges.set(change.id, storedChange)\n\t\t\t}\n\t\t\tmergeNodeChanges(storedChange, change)\n\t\t}\n\t}\n}\n\nexport class TreeTimeline {\n\t// Safely using a non-null assertion operator (`!`) here because these fields\n\t// are set in reset() which is called in the constructor\n\ttree!: CanvasTree\n\tpublic entries!: TimelineEntry[]\n\tpublic latestReversibleNodeChanges: ReversibleNodeChange[] | null = null\n\n\tpublic enableAddRemoveOptimizations = true\n\n\trecorder?: (record: CrdtDebugRecord) => void\n\n\tconstructor(\n\t\ttree: CanvasTree,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\toptions?: { isLoading?: boolean },\n\t) {\n\t\tthis.reset(tree, options)\n\t}\n\n\t/** Tracks the amount of entries trimmed away. An external index, minus\n\t * trimmed, becomes the index of the entry in the entries array. */\n\tpublic trimmed = 0\n\tpublic isPartialLoading = false\n\n\tget length() {\n\t\treturn this.entries.length + this.trimmed\n\t}\n\n\tpublic get localTreeIndex() {\n\t\treturn this.length - 1\n\t}\n\n\t// Remote tree support.\n\tprivate internalRemoteTreeIndex = 0\n\n\tget remoteTreeIndex() {\n\t\treturn this.internalRemoteTreeIndex\n\t}\n\n\tincrementRemoteTreeIndex(delta: number) {\n\t\tthis.internalRemoteTreeIndex += delta\n\t}\n\n\t// Error recovery support.\n\tprivate inErrorRecovery = false\n\n\t// Changes reader support.\n\tprivate nodeChangesBuffers = new Set<NodeChangesBuffer>()\n\n\tlegacyMode: boolean = false\n\n\tremoteTreeVersion: number = 0\n\trecentEditReasons: string[] = []\n\n\tflagsForNextCommit: TimelineFlags | undefined\n\n\t/**\n\t * Time when timeline became online\n\t *\n\t * 0 means timeline is offline\n\t */\n\tprivate onlineStartTime = 0\n\tsetOnline(online: boolean) {\n\t\tif (this.online !== online) {\n\t\t\tthis.onlineStartTime = online ? performance.now() : 0\n\t\t}\n\t}\n\n\tprivate get online() {\n\t\treturn this.onlineStartTime !== 0\n\t}\n\n\tsetFlagsForNextCommit(flags: TimelineFlags) {\n\t\tthis.flagsForNextCommit = flags\n\t}\n\n\tvalidationEnabled = process.env.NODE_ENV !== \"test\"\n\n\tvalidateUpdatesAreSentToServer() {\n\t\t// If we are not online, no need to validate that\n\t\t// updates are sent to server\n\t\tif (!this.validationEnabled || !this.online) return\n\n\t\tconst now = performance.now()\n\n\t\tconst connectionDuration = now - this.onlineStartTime\n\t\tif (connectionDuration < REMOTE_CONNECTION_VALID_FOR_MS) return\n\n\t\tconst oldestEntry = this.getOldestLocalEntry()\n\t\tif (!oldestEntry) return\n\n\t\tconst deltaSinceOldestEntry = now - oldestEntry.timestamp\n\t\tassert(deltaSinceOldestEntry < LOCAL_CHANGES_VALID_FOR_MS, \"Local changes not been processed in a while\")\n\t}\n\n\tprivate extraChangesForNextCommit: NodeChange[] | undefined\n\n\tsetExtraChangesForNextCommit(diffs: NodeChange[]) {\n\t\tthis.extraChangesForNextCommit = diffs\n\t}\n\n\trecordEditReasons(source: string | null | undefined) {\n\t\tif (!source) return\n\t\tthis.recentEditReasons.push(source)\n\t}\n\n\tpublic trackChange(id: NodeID, change: NodeChange | null = null) {\n\t\tfor (const reader of this.nodeChangesBuffers) {\n\t\t\treader.trackChange(id, change)\n\t\t}\n\t}\n\n\tgetTreeForVersion(version: number): CanvasTree | undefined {\n\t\tif (this.isPartialLoading) return\n\t\t// there could be multiple entries with the same version, we want the last one\n\t\treturn this.entries.findLast(e => e.version === version)?.tree\n\t}\n\n\taddEntry(tree: CanvasTree, changes: NodeChange[], editReasons: string[] = [], wasRebase = false) {\n\t\tsetTreeMode(tree, \"json\")\n\t\tconst entry = new TimelineEntry(tree, changes, editReasons, wasRebase)\n\t\tthis.entries.push(entry)\n\t\tthis.tree = tree\n\t\treturn entry\n\t}\n\n\tgetLastEntry() {\n\t\tconst lastEntry = this.entries[this.entries.length - 1]\n\t\tassert(lastEntry, \"Timeline has no entries\")\n\t\treturn lastEntry\n\t}\n\n\thasLocalEdits() {\n\t\treturn this.remoteTreeIndex + 1 - this.trimmed < this.entries.length\n\t}\n\n\tgetOldestLocalEntry() {\n\t\treturn this.getEntry(this.remoteTreeIndex + 1 - this.trimmed)\n\t}\n\n\tgetEntry(index: number) {\n\t\treturn this.entries[index]\n\t}\n\n\tresetTime = 0\n\treset(tree: CanvasTree, options?: { initialChanges?: NodeChange[]; isLoading?: boolean }) {\n\t\tthis.resetTime = performance.now()\n\n\t\tif (this.inErrorRecovery && tree === this.tree) {\n\t\t\tlog.debug(\"reset for error recovery...\")\n\t\t\tthis.inErrorRecovery = false\n\t\t\tthis.invalidateAllCursors()\n\t\t\tthis.clearNodeChangesReader()\n\t\t\treturn\n\t\t}\n\n\t\tlog.debug(\"reset with tree:\", tree.root.id, \"size:\", tree.size())\n\t\tthis.entries = []\n\t\tthis.addEntry(tree, options?.initialChanges ?? [], [\"load\"])\n\t\tthis.recentEditReasons = []\n\t\tthis.flagsForNextCommit = undefined\n\t\tthis.extraChangesForNextCommit = undefined\n\n\t\t// reset other fields\n\t\tthis.latestReversibleNodeChanges = null\n\t\tthis.trimmed = 0\n\t\tthis.internalRemoteTreeIndex = 0\n\n\t\t// to support partially loading trees, we must keep all history\n\t\tthis.isPartialLoading = !!options?.isLoading\n\t\tthis.invalidateAllCursors()\n\t\tthis.clearNodeChangesReader()\n\t}\n\n\tprivate epoch = 0\n\tpublic invalidateAllCursors() {\n\t\tthis.epoch += 1\n\t}\n\n\t// Changes reader support.\n\topenNodeChangesReader(): NodeChangesBuffer {\n\t\treturn new NodeChangesBuffer(this.nodeChangesBuffers)\n\t}\n\n\tclearNodeChangesReader() {\n\t\tfor (const reader of this.nodeChangesBuffers) {\n\t\t\treader.clear()\n\t\t}\n\t}\n\n\tprivate applyFlagsToChange(change: NodeChange | null | undefined) {\n\t\tif (!change) return\n\t\tif (!this.flagsForNextCommit) return\n\n\t\tif (this.flagsForNextCommit.ignoreInUndo) {\n\t\t\tchange.ignoreInUndo = true\n\t\t}\n\t\tif (this.flagsForNextCommit.ignoreInCodeGeneration) {\n\t\t\tchange.ignoreInCodeGeneration = true\n\t\t}\n\t}\n\n\tcommitLocalTree(): CommitLocalTreeResult {\n\t\tthis.validateUpdatesAreSentToServer()\n\n\t\tconst lastEntry = this.getLastEntry()\n\t\tassert(this.tree === lastEntry.tree, \"tree out of sync\")\n\t\tconst changesById: ReversibleNodeChangesById = {}\n\n\t\tthis.tree = this.tree.commit(\n\t\t\tthis.componentLoader,\n\t\t\t(current: CanvasNode | undefined, draft: CanvasNode | undefined) => {\n\t\t\t\tif (!current && !draft) return\n\t\t\t\tconst change = nodeChange(current, draft)\n\n\t\t\t\tthis.applyFlagsToChange(change)\n\t\t\t\tthis.trackChange(current?.id ?? draft!.id, change)\n\t\t\t\tif (change) {\n\t\t\t\t\tif (change.to.parentid && change.to.parentid !== change.from?.parentid) {\n\t\t\t\t\t\tconst fromScope = this.tree.getScopeNodeAtStartFor(current)\n\t\t\t\t\t\tconst toScope = this.tree.getScopeNodeFor(draft)\n\t\t\t\t\t\tif (fromScope && fromScope?.id !== toScope?.id) {\n\t\t\t\t\t\t\tchange.previousScope = fromScope.id\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tchangesById[change.id] = change\n\t\t\t\t}\n\n\t\t\t\tconst changes: ReversibleNodeChange[] = []\n\t\t\t\tcomputeOverrideChanges(changes, current, draft)\n\t\t\t\tfor (const change of changes) {\n\t\t\t\t\tthis.applyFlagsToChange(change)\n\t\t\t\t\tthis.trackChange(change.id, change)\n\t\t\t\t\tchangesById[change.id] = change\n\t\t\t\t}\n\t\t\t},\n\t\t)\n\n\t\tthis.latestReversibleNodeChanges = Object.values(changesById)\n\t\tlet changes: NodeChange[] = this.latestReversibleNodeChanges\n\n\t\tif (this.extraChangesForNextCommit) {\n\t\t\t// Only if we have extra changes do we make a copy of the latestReversibleNodeChanges\n\t\t\tchanges = [...changes]\n\t\t\tfor (const change of this.extraChangesForNextCommit) {\n\t\t\t\tthis.applyFlagsToChange(change)\n\t\t\t\tthis.trackChange(change.id, change)\n\t\t\t\tchanges.push(change)\n\t\t\t}\n\t\t}\n\n\t\tthis.flagsForNextCommit = undefined\n\t\tthis.extraChangesForNextCommit = undefined\n\n\t\tlog.debug(\"commit local tree:\", changes.length, this.recentEditReasons)\n\t\tif (changes.length > 0) {\n\t\t\tassert(lastEntry.tree !== this.tree, \"must be a new tree\")\n\t\t\tlastEntry.tree.releaseMemory()\n\t\t\tthis.entries.push(new TimelineEntry(this.tree, changes, this.recentEditReasons))\n\t\t} else if (this.tree !== lastEntry.tree) {\n\t\t\tlastEntry.tree.releaseMemory()\n\t\t\tlastEntry.tree = this.tree\n\t\t}\n\n\t\tthis.recentEditReasons = []\n\n\t\tassert(this.tree === this.getLastEntry().tree)\n\t\treturn { tree: this.tree }\n\t}\n\n\t/** Get the forward and backward node changes belonging to the last tree.commit(). */\n\tgetLatestChangesForUndo(): ReversibleNodeChange[] | null {\n\t\treturn this.latestReversibleNodeChanges\n\t}\n\n\t/** Returns a tracking cursor that can be used to request the changes from time to time. */\n\tgetChangeTrackingCursor(): ChangeTrackingCursor {\n\t\tconst remoteTree = this.remoteTreeIndex\n\t\tconst localTree = this.localTreeIndex\n\t\treturn { remoteTree, localTree, timeline: this, tree: this.tree, epoch: this.epoch }\n\t}\n\n\tinvalidatedByLoadCompletedDocument(cursor: ChangeTrackingCursor | undefined | null): boolean {\n\t\tif (!cursor) return false\n\t\tif (this.trimmed > 0) return false\n\t\tif (cursor.timeline !== this) return false\n\n\t\t// If the epoch advanced by one, and so the remoteTree (index), only loadCompletedDocument could have caused that.\n\t\tif (cursor.epoch + 1 !== this.epoch) return false\n\t\tif (cursor.remoteTree + 1 !== this.remoteTreeIndex) return false\n\t\treturn true\n\t}\n\n\t/**\n\t * Get the forward changes for the current tracking cursor, will also update\n\t * the cursor. If the cursor is out of date this will return undefined, and\n\t * a new one has to be requested via getChangeTrackingCursor.\n\t */\n\tfetchForwardChanges(cursor: ChangeTrackingCursor | undefined | null): NodeChange[] | undefined {\n\t\t// Check if the cursor is outdated due to timeline/tree changes.\n\t\tif (!cursor) return\n\t\tif (cursor.epoch !== this.epoch) return\n\t\tif (cursor.tree.lineage !== this.tree.lineage) return\n\t\tif (cursor.tree.root.id !== this.tree.root.id) return\n\t\tif (cursor.timeline !== this) return\n\n\t\t// Check if the cursor is outdated because it is so far behind the entries were trimmed.\n\t\tif (cursor.localTree > 0 && cursor.localTree <= this.trimmed) return\n\t\tif (cursor.remoteTree > 0 && cursor.remoteTree <= this.trimmed) return\n\n\t\t// This is a corner case not checked by the two above. If an initial\n\t\t// cursor was idle for a long time.\n\t\tif (this.remoteTreeIndex > 0 && this.trimmed > 0 && cursor.remoteTree === 0) return\n\n\t\t// Otherwise we can compute a diff from cursor upto latest.\n\t\tlet startIndex = cursor.localTree\n\t\tif (this.remoteTreeIndex > 0) {\n\t\t\t// Ideally we want to return the changes from cursor.localTree to\n\t\t\t// this.entries.length. But if there was a rebase somewhere between\n\t\t\t// cursor.remoteTree and cursor.localTree, we must include that\n\t\t\t// rebase, thus start from the entry one before it.\n\t\t\tstartIndex = cursor.remoteTree - 1\n\t\t\twhile (startIndex < cursor.localTree) {\n\t\t\t\tif (this.entries[startIndex + 1 - this.trimmed]?.wasRebase) break\n\t\t\t\tstartIndex += 1\n\t\t\t}\n\t\t}\n\n\t\tassert(startIndex - this.trimmed >= 0, \"buffer cut too close to remoteTree\")\n\t\tassert(startIndex <= cursor.localTree, \"startIndex incorrectly calculated\")\n\n\t\t// We always compute to the latest entry.\n\t\tconst endIndex = this.localTreeIndex\n\t\tassert(startIndex <= endIndex, \"bad change tracking cursor\")\n\n\t\tconst baseTree = cursor.tree\n\n\t\t// Update the change tracking cursor.\n\t\tcursor.remoteTree = this.remoteTreeIndex\n\t\tcursor.localTree = endIndex\n\t\tcursor.tree = this.tree\n\n\t\treturn this.computeForwardChanges(startIndex, endIndex, baseTree)\n\t}\n\n\t// Private, but used by tests. #startIndex points to the tree from which to\n\t// start, the actual changes are inbetween the trees.\n\tcomputeForwardChanges(startIndex: number, endIndex: number, baseTree?: CanvasTree): NodeChange[] {\n\t\tif (startIndex >= endIndex) return []\n\n\t\tconst result: NodeChangesById = {}\n\t\tfor (let i = startIndex + 1; i <= endIndex; i++) {\n\t\t\tconst entry = this.entries[i - this.trimmed]!\n\t\t\tfor (const change of entry.changes) {\n\t\t\t\tconst id = change.id\n\t\t\t\tlet computed = result[id]\n\t\t\t\tif (!computed) {\n\t\t\t\t\tcomputed = result[id] = { id, to: {} }\n\t\t\t\t}\n\n\t\t\t\tconst added = computed.added\n\t\t\t\tmergeNodeChanges(computed, change)\n\n\t\t\t\t// If this is a normal forward compute, remove the nodes that were first added, then deleted.\n\t\t\t\tif (!baseTree && added && computed.removed && this.enableAddRemoveOptimizations) {\n\t\t\t\t\tdelete result[id]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Return a list of meaningful changes. Filtering and optimizing the changes using a starting tree.\n\t\tconst startTree = baseTree ?? this.entries[startIndex - this.trimmed]?.tree\n\t\tif (!startTree) throw new Error(`${startIndex} - ${this.trimmed}`)\n\t\treturn Object.values(result).filter(change => {\n\t\t\t// If this change is a removal, we don't need to track property or children changes.\n\t\t\tif (change.removed) {\n\t\t\t\tchange.to = {}\n\t\t\t\t// TODO the next line can be uncommented if treediff does the\n\t\t\t\t// same thing, but the server snapshotter needs the toChildren\n\t\t\t\t// of deleted nodes.\n\t\t\t\t// delete change.toChildren\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\t// Remove any changes that went back to their initial values.\n\t\t\tconst startingNode = startTree.getNodeAtStart(change.id)\n\t\t\tif (startingNode && this.enableAddRemoveOptimizations) {\n\t\t\t\tfor (const [key, value] of Object.entries(change.to)) {\n\t\t\t\t\tif (isEqual(startingNode[key as keyof typeof startingNode], value)) {\n\t\t\t\t\t\tdelete change.to[key]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If this change is a node being added, we keep it.\n\t\t\tif (change.added) return true\n\n\t\t\t// If there is at least one property change, we keep it.\n\t\t\tif (Object.keys(change.to).length > 0) return true\n\n\t\t\t// There are no property changes, if there is also no change to children we can ignore this change.\n\t\t\tconst toChildren = change.toChildren\n\t\t\tif (!toChildren) return false\n\n\t\t\tif (!startingNode) return true\n\n\t\t\t// If there is a difference in children, we keep the change.\n\t\t\tstartTree.beginAllowPartialScopeAccess()\n\t\t\tconst children = startingNode.children\n\t\t\tstartTree.endAllowPartialScopeAccess()\n\t\t\tif (!children || !this.enableAddRemoveOptimizations) return true\n\n\t\t\tconst length = children.length\n\t\t\tif (length !== toChildren.length) return true\n\n\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\tif (children.at(i)!.id !== toChildren[i]) return true\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t}\n\n\t// *** Remote Tree Support ***\n\tgetEditReasons(startIndex: number, endIndex: number): string {\n\t\tconst result: string[] = []\n\t\tlet last = \"\"\n\t\tfor (let i = startIndex + 1; i <= endIndex; i++) {\n\t\t\tconst reasons = this.entries[i - this.trimmed]!.editReasons\n\t\t\tfor (const reason of reasons) {\n\t\t\t\tif (!reason) continue\n\t\t\t\tif (last === reason) continue\n\t\t\t\tlast = reason\n\t\t\t\tresult.push(reason)\n\t\t\t}\n\t\t}\n\t\treturn result.join(\" \")\n\t}\n\n\tgetChangesBetweenEntries(startIndex: number, endIndex: number) {\n\t\tassert(startIndex < endIndex, \"inconsistency in getting local changes to send\")\n\t\tconst changes = this.computeForwardChanges(startIndex, endIndex)\n\t\tconst reasons = this.getEditReasons(startIndex, endIndex)\n\n\t\tconst count = endIndex - startIndex\n\t\treturn { count, changes, reasons }\n\t}\n\n\t/** Will overwrite the latest tree. */\n\tdebugOverwriteCurrentTree(tree: CanvasTree) {\n\t\tlog.debug(\"recover with tree:\", tree.root.id)\n\t\tsetTreeMode(tree, \"json\")\n\t\tthis.tree = tree\n\t\tthis.getLastEntry().tree = tree\n\t}\n\n\t/**\n\t * Will reload and repair the tree as the server has it, apply any local changes, returning\n\t * that tree. Used by our error recovery mechanism.\n\t *\n\t * @param entryIndexToReload Tree entry index to safe load again\n\t * @param numEntriesToApply Number of entries after reloaded entry to apply to the reloaded entry\n\t * @return Valid canvas tree after reload + apply\n\t */\n\tresetTreesForRecovery(entryIndexToReload: number, numEntriesToReapply: number): CanvasTree {\n\t\tlog.info(\n\t\t\t\"reset trees for recovery, remote:\",\n\t\t\tthis.remoteTreeIndex,\n\t\t\t\"local:\",\n\t\t\tthis.localTreeIndex,\n\t\t\t\"changes already sent:\",\n\t\t\tnumEntriesToReapply,\n\t\t)\n\n\t\tlet tree = this.entries[entryIndexToReload]?.tree\n\t\tassert(tree, \"unable to get remote tree\")\n\n\t\tconst loader = tree.getService(\"loader\")\n\t\tconst editHooks = tree.lineage.editHooks\n\n\t\tconst errors: string[] = []\n\t\ttry {\n\t\t\t// Deep clone the tree for recovery - this can fail for very large trees\n\t\t\tconst json: unknown = JSON.parse(JSON.stringify(tree.toJS()))\n\t\t\ttree = safeLoadDocument(json, this.componentLoader, errors)\n\t\t} catch (error) {\n\t\t\tif (error instanceof RangeError && error.message.includes(\"Invalid string length\")) {\n\t\t\t\tlog.warn(\"[recovery] Tree too large for JSON serialization, using original tree\", {\n\t\t\t\t\terror: error.message,\n\t\t\t\t\ttreeSize: tree.size(),\n\t\t\t\t})\n\t\t\t\t// For very large trees, skip the deep clone and just use the original tree\n\t\t\t\t// This is less safe but prevents the crash\n\t\t\t\terrors.push(\"Recovery skipped: tree too large for serialization\")\n\t\t\t} else {\n\t\t\t\t// Re-throw other errors\n\t\t\t\tthrow error\n\t\t\t}\n\t\t}\n\n\t\t// If there was a loader installed on the previous tree, then we need to reset it.\n\t\tif (loader) {\n\t\t\tloader.resetTreeForRecovery(tree)\n\t\t\tassert(tree.getService(\"loader\") === loader, \"tree must have the same loader\")\n\t\t}\n\n\t\tif (editHooks) {\n\t\t\ttree.lineage.editHooks = editHooks\n\t\t}\n\n\t\tif (errors.length > 0) {\n\t\t\tlog.warn(\"[recovery] encountered errors while reloading the tree:\", errors)\n\t\t}\n\n\t\t// Overwrite the recovered tree\n\t\tthis.entries[entryIndexToReload]!.tree = tree\n\n\t\t// Drop any local changes not yet sent to remote\n\t\tthis.entries.length = entryIndexToReload + numEntriesToReapply + 1\n\n\t\t// Create new trees for every entry by replaying the changes\n\t\tlet previousTree = tree\n\t\tfor (let i = entryIndexToReload + 1; i < this.entries.length; i++) {\n\t\t\tconst entryToUpdate = this.entries[i]!\n\t\t\tjsonApplyChanges(tree, entryToUpdate.changes)\n\t\t\ttree = tree.commitDiffs(this.componentLoader)\n\t\t\tentryToUpdate.tree = tree\n\t\t\tif (tree !== previousTree) {\n\t\t\t\tpreviousTree.releaseMemory()\n\t\t\t\tpreviousTree = tree\n\t\t\t}\n\t\t}\n\n\t\t// Mark the timeline as in error recovery and set the resulting tree\n\t\tthis.inErrorRecovery = true\n\t\tsetTreeMode(tree, \"json\")\n\t\tthis.tree = tree\n\t\treturn tree\n\t}\n\n\tsaveTimelineDataForRecovery() {\n\t\tif (!window.localStorage) return\n\n\t\ttry {\n\t\t\t// For debugging purposes, we store the old timeline data in localStorage. We don't\n\t\t\t// want that to immediately overwrite some previous entry, so we use a 100 random\n\t\t\t// buckets, and store the current time as well.\n\t\t\tconst key = `debugTimelineAtRecovery-${Math.floor(Math.random() * 100)}`\n\t\t\tconst data = {\n\t\t\t\tdate: new Date().toString(),\n\t\t\t\tentries: this.entries.map(entry => entry.toDebugData()),\n\t\t\t}\n\t\t\twindow.localStorage.setItem(key, JSON.stringify(data))\n\t\t} catch (e) {\n\t\t\tlog.warn(\"failed to store timeline in localStorage:\", e)\n\t\t}\n\t}\n\n\tapplyChanges(changes: ReversibleNodeChange[]) {\n\t\tjsonApplyChanges(this.tree, changes)\n\t}\n\n\tapplyReverseChanges(changes: ReversibleNodeChange[]): void {\n\t\tjsonApplyReverseChanges(this.tree, changes)\n\t}\n\n\tdiscardChangeset() {\n\t\t// TODO: Throw error here\n\t}\n\n\treplayChangeset() {\n\t\t// TODO: Throw error here\n\t}\n\n\tgetOrCreateDataTree() {\n\t\treturn undefined\n\t}\n\n\tresetDataTree() {\n\t\t// Do nothing\n\t}\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { treeLibrary } from \"./FastTreeLibrary.ts\"\nimport type { CanvasNode } from \"./nodes/CanvasNode.ts\"\nimport { CanvasChildList } from \"./nodes/ChildList.ts\"\nimport type { NodeID } from \"./nodes/NodeID.ts\"\nimport { mergeOverrides, resetUnsupportedReplicaOverrides, updateVariantName } from \"./nodes/TemplateHelper.ts\"\nimport { canvasNodeFromValue } from \"./nodes/canvasNodeFromValue.ts\"\nimport { type IsMaster, type IsReplica, type ReplicaOverrides, isMaster, isReplica } from \"./traits/WithTemplate.ts\"\nimport { isVariant } from \"./traits/WithVariant.ts\"\n\n/** Can be used to expand replicas of a scope, before it is inserted in the tree. */\nexport function expandScopeReplicas(scope: CanvasNode): void {\n\tif (!scope.children) return\n\n\tconst masters = new Map<string, { master: CanvasNode & IsMaster; replicas: Map<string, CanvasNode & IsReplica> }>()\n\n\tfor (const child of scope.children) {\n\t\tif (!isMaster(child)) continue\n\t\tmasters.set(child.id, { master: child, replicas: new Map() })\n\t}\n\n\tfor (const child of scope.children) {\n\t\tif (!isReplica(child)) continue\n\t\tconst master = masters.get(child.replicaInfo.master)\n\t\tif (!master) continue\n\t\tmaster.replicas.set(child.id, child)\n\t}\n\n\tfor (const { master, replicas } of masters.values()) {\n\t\texpandReplicas(master, replicas)\n\t}\n}\n\nfunction expandReplicas(master: CanvasNode & IsMaster, replicas: Map<string, CanvasNode & IsReplica>): void {\n\tfor (const replica of replicas.values()) {\n\t\tconst replicaInfo = replica.replicaInfo\n\t\tassert(replicaInfo.master === master.id, \"Replica must match master\")\n\n\t\tlet overrides = replicaInfo.overrides\n\t\tif (replicaInfo.inheritsFrom) {\n\t\t\tconst other = replicas.get(replicaInfo.inheritsFrom)\n\t\t\tif (other) {\n\t\t\t\toverrides = mergeOverrides(overrides, other.replicaInfo.overrides)\n\t\t\t}\n\t\t}\n\n\t\tconst nodeOverrides = overrides[master.id]\n\t\tconst duplicatedFrom = replica.duplicatedFrom\n\t\ttreeLibrary.copyToNode(replica, master, nodeOverrides)\n\t\treplica.duplicatedFrom = duplicatedFrom\n\n\t\tlet inVariant = false\n\t\tif (isVariant(replica)) {\n\t\t\tinVariant = true\n\t\t\tupdateVariantName(replica, overrides, master)\n\t\t\tresetUnsupportedReplicaOverrides(master, replica)\n\t\t}\n\n\t\tconst replicaId = replica.id\n\t\tconst children = master.children\n\t\tif (!children) return\n\n\t\tconst newChildren = new Array(children.length)\n\t\tfor (let i = 0, il = children.length; i < il; i++) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: c style loop with known bounds\n\t\t\tnewChildren[i] = expand(replicaId, overrides, children.at(i)!, replicaId, inVariant)\n\t\t}\n\t\treplica.children = new CanvasChildList(newChildren)\n\t}\n}\n\nfunction expand(\n\treplicaId: NodeID,\n\toverrides: ReplicaOverrides,\n\tpeer: CanvasNode,\n\tparentid: string,\n\tinVariant: boolean,\n): CanvasNode {\n\tconst node = canvasNodeFromValue({ __class: peer.__class, id: replicaId + peer.id, parentid })\n\tassert(node, \"Failed to create replica node\")\n\n\tconst nodeOverrides = overrides[peer.id]\n\ttreeLibrary.copyToNode(node, peer, nodeOverrides)\n\tnode.duplicatedFrom = null\n\tif (inVariant) {\n\t\tresetUnsupportedReplicaOverrides(peer, node)\n\t}\n\n\tif (peer.children) {\n\t\tconst children = peer.children\n\t\tconst newChildren = new Array(children.length)\n\t\tfor (let i = 0, il = children.length; i < il; i++) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: c style loop with known bounds\n\t\t\tnewChildren[i] = expand(replicaId, overrides, children.at(i)!, node.id, inVariant)\n\t\t}\n\t\tnode.children = new CanvasChildList(newChildren)\n\t}\n\treturn node\n}\n", "import { uniqueName } from \"document/utils/uniqueName.ts\"\nimport { createGeneratedValue, type Generated } from \"../../traits/Generated.ts\"\n\n/**\n * Friendly word lists used to compose default branch names like \"brave-cedar\".\n */\nconst ADJECTIVES = [\n\t\"amber\",\n\t\"azure\",\n\t\"bold\",\n\t\"bright\",\n\t\"chalky\",\n\t\"coral\",\n\t\"crisp\",\n\t\"dusky\",\n\t\"electric\",\n\t\"fluid\",\n\t\"frosted\",\n\t\"glassy\",\n\t\"glossy\",\n\t\"golden\",\n\t\"hazy\",\n\t\"indigo\",\n\t\"ivory\",\n\t\"linen\",\n\t\"lucid\",\n\t\"matte\",\n\t\"mellow\",\n\t\"misty\",\n\t\"muted\",\n\t\"neon\",\n\t\"opal\",\n\t\"pastel\",\n\t\"pearl\",\n\t\"plush\",\n\t\"polished\",\n\t\"satin\",\n\t\"sheer\",\n\t\"silken\",\n\t\"silver\",\n\t\"slate\",\n\t\"smoky\",\n\t\"smooth\",\n\t\"soft\",\n\t\"solid\",\n\t\"sunlit\",\n\t\"supple\",\n\t\"tactile\",\n\t\"velvet\",\n\t\"vivid\",\n\t\"warm\",\n\t\"waxy\",\n\t\"woven\",\n\t\"airy\",\n\t\"crystal\",\n\t\"dewy\",\n\t\"liquid\",\n]\n\nconst NOUNS = [\n\t\"anchor\",\n\t\"arc\",\n\t\"atlas\",\n\t\"beacon\",\n\t\"bloom\",\n\t\"canyon\",\n\t\"cove\",\n\t\"crest\",\n\t\"delta\",\n\t\"dome\",\n\t\"drift\",\n\t\"dune\",\n\t\"ember\",\n\t\"facet\",\n\t\"fjord\",\n\t\"flare\",\n\t\"foil\",\n\t\"glade\",\n\t\"glow\",\n\t\"grain\",\n\t\"grove\",\n\t\"harbor\",\n\t\"haven\",\n\t\"horizon\",\n\t\"isle\",\n\t\"lagoon\",\n\t\"lattice\",\n\t\"loop\",\n\t\"marble\",\n\t\"meadow\",\n\t\"mosaic\",\n\t\"orbit\",\n\t\"pebble\",\n\t\"plane\",\n\t\"prism\",\n\t\"quartz\",\n\t\"ridge\",\n\t\"ripple\",\n\t\"river\",\n\t\"shore\",\n\t\"slope\",\n\t\"spark\",\n\t\"spire\",\n\t\"stone\",\n\t\"tide\",\n\t\"vista\",\n\t\"wave\",\n\t\"willow\",\n\t\"halo\",\n\t\"thread\",\n]\n\nfunction pickRandom<T>(values: readonly T[]): T {\n\tconst index = Math.floor(Math.random() * values.length)\n\treturn values[index]!\n}\n\n/**\n * Generates a user-friendly branch name like \"brave-cedar\". When the random\n * pick collides with an existing branch label, falls back to {@link uniqueName}\n * for a numeric suffix (e.g. \"brave-cedar 2\").\n *\n * Returns the value wrapped as a `Generated<string>` so downstream code can\n * distinguish auto-generated names from user input.\n */\nexport function generateBranchName(existingNames: ReadonlySet<string>): Generated<string> {\n\t// Try a few random combinations before falling back to a numeric suffix.\n\tfor (let i = 0; i < 5; i++) {\n\t\tconst candidate = `${pickRandom(ADJECTIVES)}-${pickRandom(NOUNS)}`\n\t\tif (!existingNames.has(candidate)) return createGeneratedValue(candidate)\n\t}\n\n\tconst fallback = `${pickRandom(ADJECTIVES)}-${pickRandom(NOUNS)}`\n\treturn createGeneratedValue(uniqueName(fallback, existingNames))\n}\n", "import { DELETED_VALUE, type SerializableRow, type Store } from \"@framerjs/crdtree2\"\nimport { isHierarchyKey, parseParentId } from \"@framerjs/crdtree2/src/hierarchyKey.ts\"\nimport type { Row } from \"@framerjs/crdtree2/src/table/index.ts\"\nimport { ScopeNode } from \"document/models/CanvasTree/nodes/ScopeNode.ts\"\nimport { getClassByClassName } from \"document/models/CanvasTree/nodes/classList.ts\"\n\n/**\n * Applying patches requires the appropriate scopes to be loaded, this function figures out which scopes are those.\n */\nexport function getScopesToLoad(store: Store, rows: SerializableRow[] | Row[], scopeClassCache: Map<string, boolean>) {\n\tconst scopesToLoad = new Set<string>()\n\tfor (const row of rows) {\n\t\tconst scopeId = getScopeForId(store, row.id, scopeClassCache)\n\t\tif (scopeId) {\n\t\t\tscopesToLoad.add(scopeId)\n\t\t}\n\t\tif (row.key === \"parentid\" && isHierarchyKey(row.value)) {\n\t\t\tconst parentId = parseParentId(row.value)\n\t\t\tif (parentId !== DELETED_VALUE) {\n\t\t\t\tconst scopeId = getScopeForId(store, parentId, scopeClassCache)\n\t\t\t\tif (scopeId) {\n\t\t\t\t\tscopesToLoad.add(scopeId)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn scopesToLoad\n}\n\nexport function getScopeForId(store: Store, id: string, scopeClassCache: Map<string, boolean>) {\n\tlet nodeId: string = id\n\twhile (nodeId) {\n\t\tconst className = store.getObjectKey<string | undefined>(nodeId, \"__class\")\n\t\tif (className && isScopeClass(className, scopeClassCache)) return nodeId\n\n\t\tconst parentId = store.getParentId(nodeId)\n\t\tif (!parentId || parentId === DELETED_VALUE) {\n\t\t\tbreak\n\t\t}\n\n\t\tnodeId = parentId\n\t}\n\treturn undefined\n}\n\nfunction isScopeClass(className: string, scopeClassCache: Map<string, boolean>) {\n\tconst cachedValue = scopeClassCache.get(className)\n\tif (cachedValue !== undefined) return cachedValue\n\n\tconst cls = getClassByClassName(className)\n\tif (!cls) return false\n\n\tlet proto = Object.getPrototypeOf(cls)\n\twhile (proto) {\n\t\tif (proto === ScopeNode) {\n\t\t\tscopeClassCache.set(className, true)\n\t\t\treturn true\n\t\t}\n\t\tproto = Object.getPrototypeOf(proto)\n\t}\n\n\tscopeClassCache.set(className, false)\n\treturn false\n}\n", "import { type CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport type { MaybeNodeID, NodeID } from \"document/models/CanvasTree/nodes/NodeID.ts\"\nimport type { DataTree } from \"./DataTree.ts\"\n\n/**\n * Creates a CanvasTree-compatible proxy backed by a DataTree.\n *\n * Core lookup methods (get, getNode, getNodeAtStart, etc.) are intercepted to\n * return DataTree proxy nodes. All other CanvasTree methods (getRect,\n * transformMatrixToNode, getScopeNodeFor, ...) fall through to the real\n * CanvasTree implementation \u2014 but with `this` bound to the proxy, so their\n * internal `this.get()` / `this.root` calls are also intercepted.\n *\n * This means spatial, scope, and ancestor methods work automatically without\n * being re-implemented.\n */\nexport function createDataTreeProxy(dataTree: DataTree): CanvasTree {\n\tconst baseTree = CanvasTree.createEmpty({ mode: dataTree.canvasTree.lineage.mode })\n\n\tconst overrides: Record<string | symbol, unknown> = {\n\t\t// --- Core lookups: always go through DataTree ---\n\n\t\tget: (id: MaybeNodeID) => dataTree.get(id),\n\t\tgetNode: (id: MaybeNodeID) => dataTree.getNode(id),\n\t\tgetNodeAtStart: (id: MaybeNodeID) => dataTree.get(id),\n\t\tgetNodeAsDraft: (node: CanvasNode) => dataTree.getNodeAsDraft(node),\n\t\tgetCurrentOrDraft: (id: MaybeNodeID) => dataTree.get(id),\n\t\thas: (id: MaybeNodeID) => !!dataTree.get(id),\n\t\tlatestTree: () => dataTree.latestTree(),\n\n\t\tget editClosed() {\n\t\t\treturn dataTree.editClosed\n\t\t},\n\n\t\tget isViewOnly() {\n\t\t\treturn dataTree.isViewOnly\n\t\t},\n\n\t\tget inEditor() {\n\t\t\treturn dataTree.inEditor\n\t\t},\n\n\t\t// --- Mutation ---\n\n\t\tinsertNode: <T extends CanvasNode>(node: T, parentid?: MaybeNodeID, position?: number): T =>\n\t\t\tdataTree.insertNode(node, parentid, position),\n\n\t\tremoveNode: (node: CanvasNode): void => dataTree.removeNode(node),\n\n\t\tmoveNode: <T extends CanvasNode>(node: T, parentid: NodeID, position?: number): T =>\n\t\t\tdataTree.moveNode(node, parentid, position),\n\n\t\t// --- Size ---\n\n\t\tsize: () => dataTree.hierarchy.sizeWithoutReplicas(),\n\t\tsizeAtStart: () => dataTree.hierarchy.sizeWithoutReplicas(),\n\n\t\t// --- Commit / draft no-ops ---\n\n\t\thasUncommittedChanges: () => dataTree.hasUncommittedChanges(),\n\t\tunsafeGetDraftNodes: () => [],\n\t\tgetNodesChangedByCommit: () => [],\n\n\t\twithPersistedCaches: <T>(callback: () => Promise<T>) => dataTree.withPersistedCaches(callback),\n\t\tpersistCaches: () => dataTree.persistCaches(),\n\t}\n\n\tconst proxy = new Proxy(baseTree, {\n\t\tget(target, prop, receiver) {\n\t\t\tif (prop === \"isLoaded\") return () => true\n\t\t\t// Properties that need to be dynamic getters on DataTree.\n\t\t\tif (prop === \"root\" || prop === \"rootAtStart\") return dataTree.root\n\n\t\t\t// Return the proxy itself for commit making it a no-op.\n\t\t\tif (prop === \"commit\") return () => receiver\n\n\t\t\t// remove(id) and move(id, parentid, position) return `this` (the proxy).\n\t\t\tif (prop === \"remove\") {\n\t\t\t\treturn (id: NodeID) => {\n\t\t\t\t\tconst node = dataTree.get(id)\n\t\t\t\t\tif (node) dataTree.removeNode(node)\n\t\t\t\t\treturn receiver\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (prop === \"move\") {\n\t\t\t\treturn (id: NodeID, parentid: MaybeNodeID, position?: number) => {\n\t\t\t\t\tconst node = dataTree.get(id)\n\t\t\t\t\tif (!parentid) {\n\t\t\t\t\t\tparentid = dataTree.root.id\n\t\t\t\t\t}\n\t\t\t\t\tif (node) dataTree.moveNode(node, parentid, position)\n\t\t\t\t\treturn receiver\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If overridden, use that.\n\t\t\tif (prop in overrides) return overrides[prop]\n\n\t\t\t// Otherwise fall through to the real (but empty) CanvasTree.\n\t\t\tconst value = Reflect.get(target, prop, receiver)\n\t\t\tif (typeof value === \"function\") {\n\t\t\t\t// Bind to the proxy so that `this` inside CanvasTree methods is the proxy itself.\n\t\t\t\treturn value.bind(receiver)\n\t\t\t}\n\t\t\treturn value\n\t\t},\n\t})\n\n\tbaseTree.lineage.latestTree = proxy\n\treturn proxy\n}\n", "export const isDataNodeSymbol = Symbol(\"isDataNode\")\n", "// oxlint-disable typescript/no-non-null-assertion\n/* eslint-disable framer-studio/no-mutable-node-object-methods, framer-studio/no-mutable-node-property-operations, framer-studio/no-mutable-node-type-operations, framer-studio/no-mutable-node-object-operations */\nimport { DELETED_VALUE, type Store } from \"@framerjs/crdtree2\"\nimport { assert } from \"@framerjs/shared\"\nimport { getOrRegisterDriverBasedOnExperiment } from \"document/models/CanvasTree/drivers/NodeTreeDriverSelector.ts\"\nimport {\n\tDEFAULTS_FIELD,\n\tMETA_FIELD,\n\tOWN_SETTERS_FIELD,\n\ttype WithProtoData,\n} from \"document/models/CanvasTree/drivers/PrototypeTreeDriver.ts\"\nimport { type CanvasNode, isScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport type { CanvasNodeCache } from \"document/models/CanvasTree/nodes/CanvasNodeCache.ts\"\nimport { ChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport type { MutableNode, NodeAccessor } from \"document/models/CanvasTree/nodes/MutableNode.ts\"\nimport { generateReplicaChildId } from \"document/models/CanvasTree/nodes/TemplateHelper.ts\"\nimport {\n\treviveGuidesInfo,\n\treviveMaskGradients,\n\treviveReplicaInfo,\n\treviveValue,\n} from \"document/models/CanvasTree/nodes/canvasNodeFromValue.ts\"\nimport { getNodeSubclassList } from \"document/models/CanvasTree/nodes/classList.ts\"\nimport type { ReplicaInfo } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { DataTree } from \"./DataTree.ts\"\nimport { isDataNodeSymbol } from \"./dataNodeSymbol.ts\"\n\nconst dataOnlyNodeClasses = new Map<string, any>()\n\n/** Accepts all keys starting with $ */\nconst dynamicPropPredicate = (key: string) => key.startsWith(\"$\")\n\nfunction getCanvasNode(tree: DataTree, id: string): CanvasNode | undefined {\n\t// Root node is always a DataTree node\n\tif (id !== tree.canvasTree.root.id) {\n\t\t// Check if the CanvasTree has the node\n\t\tconst canvasTreeNode = tree.canvasTree.get(id)\n\t\tconst isScope = isScopeNode(canvasTreeNode)\n\t\t// Treat shallow loaded scopes as DataTree nodes\n\t\tif (canvasTreeNode && (!isScope || canvasTreeNode.isLoaded())) return canvasTreeNode\n\t}\n}\n\nexport function getOrCreateDataTreeNode<T extends CanvasNode>(tree: DataTree, id: string) {\n\tconst cachedRef = tree.nodeProxyCache.get(id)\n\tif (cachedRef) {\n\t\tconst cachedProxy = cachedRef.deref()\n\t\tif (cachedProxy) return cachedProxy as T\n\t}\n\n\tconst canvasNode = getCanvasNode(tree, id)\n\tif (canvasNode) return canvasNode as T\n\n\tconst className = tree.store.getObjectKey<string>(id, \"__class\")\n\tassert(className, id, \"does not have class\")\n\tconst cls = dataOnlyNodeClasses.get(className)\n\tassert(cls, \"node\", id, \"has invalid class name\", className)\n\n\t// sourceIds are ordered\n\tconst sourceIds: string[] = []\n\tlet replicaOwnerId: string | undefined = undefined\n\tconst originalId = tree.store.getObjectKey(`${id}.replicaInfo`, \"master\")\n\tif (originalId && typeof originalId === \"string\") {\n\t\t// Only replica owners have originalId set.\n\t\treplicaOwnerId = id\n\t\tsourceIds.push(`${replicaOwnerId}.replicaInfo.overrides.${originalId}`)\n\t\tconst inheritsFrom = tree.store.getObjectKey<string>(`${replicaOwnerId}.replicaInfo`, \"inheritsFrom\")\n\t\tif (inheritsFrom) {\n\t\t\tsourceIds.push(`${inheritsFrom}.replicaInfo.overrides.${originalId}`)\n\t\t}\n\t\tsourceIds.push(originalId)\n\t} else {\n\t\tsourceIds.push(id)\n\t}\n\n\tconst node = new cls(tree, id, sourceIds, replicaOwnerId, originalId) as T\n\ttree.nodeProxyCache.set(id, new WeakRef(node))\n\treturn node\n}\n\nexport function getOrCreateDataTreeReplicaNode<T extends CanvasNode>(\n\ttree: DataTree,\n\treplicaOwnerId: string,\n\toriginalId: string,\n) {\n\tconst id = generateReplicaChildId(replicaOwnerId, originalId)\n\n\tconst cachedRef = tree.nodeProxyCache.get(id)\n\tif (cachedRef) {\n\t\tconst cachedProxy = cachedRef.deref()\n\t\tif (cachedProxy) return cachedProxy as T\n\t}\n\n\tconst className = tree.store.getObjectKey<string>(originalId, \"__class\")\n\tif (!className) {\n\t\tconst originalObject = tree.store.getObject(originalId)\n\t\tassert(originalObject, id, \"does not exist\")\n\t\tassert(className, id, \"does not have class\")\n\t}\n\tconst cls = dataOnlyNodeClasses.get(className)\n\tassert(cls, \"node\", id, \"has invalid class name\", className)\n\n\tconst sourceIds: string[] = []\n\tsourceIds.push(`${replicaOwnerId}.replicaInfo.overrides.${originalId}`)\n\tconst inheritsFrom = tree.store.getObjectKey<string>(`${replicaOwnerId}.replicaInfo`, \"inheritsFrom\")\n\tif (inheritsFrom) {\n\t\tsourceIds.push(`${inheritsFrom}.replicaInfo.overrides.${originalId}`)\n\t}\n\tsourceIds.push(originalId)\n\n\tconst node = new cls(tree, id, sourceIds, replicaOwnerId, originalId) as T\n\ttree.nodeProxyCache.set(id, new WeakRef(node))\n\treturn node\n}\n\ninterface DataTreeNode {\n\tid: string\n\tdataTree: DataTree\n\tsourceIds: string[]\n\townerId: string | undefined\n\toriginalId: string | undefined\n\n\t$$cache$$: CanvasNodeCache\n\t$$children$$: DataChildList\n\n\t[META_FIELD]: WithProtoData<unknown>[typeof META_FIELD]\n\t[DEFAULTS_FIELD]: WithProtoData<unknown>[typeof DEFAULTS_FIELD]\n}\n\nfunction createGetterSetterForProp(target: DataTreeNode, prop: string, reviver: (fn: unknown) => unknown) {\n\tObject.defineProperty(target, prop, {\n\t\tenumerable: true,\n\t\tget(this: DataTreeNode) {\n\t\t\tlet value = this.dataTree.editedNodes.get(this.id)?.[prop]\n\t\t\tif (value !== undefined) return value\n\n\t\t\tconst actualNode = this.dataTree.canvasTree.get(this.id) as Record<string, unknown> | null\n\t\t\tif (actualNode) {\n\t\t\t\treturn actualNode[prop]\n\t\t\t}\n\n\t\t\tfor (const sourceId of this.sourceIds) {\n\t\t\t\tif (sourceId.includes(\".\")) {\n\t\t\t\t\t// Override source: an explicit value takes priority over a _deleted entry in\n\t\t\t\t\t// the same source. If neither is present, continue to the next source.\n\t\t\t\t\tvalue = this.dataTree.store.getObjectKey(sourceId, prop)\n\t\t\t\t\tif (value !== undefined) return reviver(value)\n\n\t\t\t\t\tconst deleted = this.dataTree.store.getObjectKey<string[]>(sourceId, \"_deleted\")\n\t\t\t\t\tif (Array.isArray(deleted) && deleted.includes(prop)) return undefined\n\t\t\t\t} else {\n\t\t\t\t\t// Direct node source (self or master): no _deleted applies here.\n\t\t\t\t\tvalue = this.dataTree.store.getObjectKey(sourceId, prop)\n\t\t\t\t\tif (value !== undefined) return reviver(value)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this[DEFAULTS_FIELD][prop]\n\t\t},\n\t\tset(this: DataTreeNode, value: unknown) {\n\t\t\tthis.dataTree.getOrCreateEditedNodeFor(this.id)[prop] = value\n\t\t},\n\t})\n}\n\n/**\n * Returns true if resolving `key` via the priority chain would yield a defined value.\n * Uses the same per-source logic as the property getters.\n */\nfunction resolvesDefined(store: Store, sourceIds: string[], key: string): boolean {\n\tfor (const sourceId of sourceIds) {\n\t\tif (sourceId.includes(\".\")) {\n\t\t\tif (store.getObjectKey(sourceId, key) !== undefined) return true\n\t\t\tconst deleted = store.getObjectKey<string[]>(sourceId, \"_deleted\")\n\t\t\tif (Array.isArray(deleted) && deleted.includes(key)) return false\n\t\t} else {\n\t\t\tif (store.getObjectKey(sourceId, key) !== undefined) return true\n\t\t}\n\t}\n\treturn false\n}\n\nclass DataChildList extends ChildList<CanvasNode> {\n\tconstructor(private readonly container: DataTreeNode) {\n\t\tsuper()\n\t}\n\n\tprivate getEditedChildren() {\n\t\treturn this.container.dataTree.getEditedChildrenFor(this.container.id)\n\t}\n\n\tprivate getChildIds() {\n\t\treturn this.container.dataTree.store.getChildrenIds(this.container.originalId ?? this.container.id)\n\t}\n\n\tget length() {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.length\n\n\t\treturn this.getChildIds().length\n\t}\n\n\tat(index: number): CanvasNode | undefined {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.at(index)\n\n\t\tconst id = this.getChildIds().at(index)\n\t\tif (!id) return undefined\n\n\t\treturn getOrCreateReplicaOrNormalNode(this.container, id)\n\t}\n\n\tindexOf(node: CanvasNode): number {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.indexOf(node)\n\n\t\tconst childIds = this.getChildIds()\n\t\tconst ownerId = this.container.ownerId\n\t\tif (this.container.originalId && ownerId) {\n\t\t\treturn childIds.findIndex(id => generateReplicaChildId(ownerId, id) === node.id)\n\t\t}\n\n\t\treturn childIds.findIndex(id => id === node.id)\n\t}\n\n\tsome(predicate: (node: CanvasNode, index: number) => unknown): boolean {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.some(predicate)\n\n\t\tconst childIds = this.getChildIds()\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tif (predicate(child, index)) return true\n\t\t}\n\n\t\treturn false\n\t}\n\n\tevery(predicate: (node: CanvasNode, index: number) => unknown): boolean {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.every(predicate)\n\n\t\tconst childIds = this.getChildIds()\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tif (!predicate(child, index)) return false\n\t\t}\n\n\t\treturn true\n\t}\n\n\tforEach(callback: (node: CanvasNode, index: number) => void): void {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\t// biome-ignore lint/correctness/noVoidTypeReturn: forEach return type is void as well\n\t\tif (editedChildren) return editedChildren.forEach(callback)\n\n\t\tconst childIds = this.getChildIds()\n\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tcallback(child, index)\n\t\t}\n\t}\n\n\tmap<Result>(callback: (node: CanvasNode, index: number) => Result): Result[] {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.map(callback)\n\n\t\tconst childIds = this.getChildIds()\n\t\tconst result = Array<Result>(childIds.length)\n\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tresult[index] = callback(child, index)\n\t\t}\n\n\t\treturn result\n\t}\n\n\treduce<Result>(callback: (result: Result, node: CanvasNode, index: number) => Result, initialValue: Result): Result {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.reduce(callback, initialValue)\n\n\t\tconst childIds = this.getChildIds()\n\t\tlet result = initialValue\n\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tresult = callback(result, child, index)\n\t\t}\n\n\t\treturn result\n\t}\n\n\tfilter<Search extends CanvasNode>(predicate: (node: CanvasNode, index: number) => node is Search): Search[]\n\tfilter(predicate: (node: CanvasNode, index: number) => unknown): CanvasNode[]\n\tfilter(predicate: (node: CanvasNode, index: number) => unknown): CanvasNode[] {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.filter(predicate)\n\n\t\tconst childIds = this.getChildIds()\n\t\tconst result: CanvasNode[] = []\n\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tif (predicate(child, index)) {\n\t\t\t\tresult.push(child)\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\tsort(): void {\n\t\tthrow new Error(\"Unsupported\")\n\t}\n\n\tfind<Search extends CanvasNode>(predicate: (node: CanvasNode, index: number) => node is Search): Search | undefined\n\tfind(predicate: (node: CanvasNode, index: number) => unknown): CanvasNode | undefined\n\tfind(predicate: (node: CanvasNode, index: number) => unknown): CanvasNode | undefined {\n\t\tconst index = this.findIndex(predicate)\n\t\tif (index === -1) return undefined\n\n\t\treturn this.at(index)\n\t}\n\n\tfindIndex(predicate: (node: CanvasNode, index: number) => unknown): number {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.findIndex(predicate)\n\n\t\tconst childIds = this.getChildIds()\n\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tif (predicate(child, index)) return index\n\t\t}\n\n\t\treturn -1\n\t}\n\n\tfindLast<Search extends CanvasNode>(\n\t\tpredicate: (node: CanvasNode, index: number) => node is Search,\n\t): Search | undefined\n\tfindLast(predicate: (node: CanvasNode, index: number) => unknown): CanvasNode | undefined\n\tfindLast(predicate: (node: CanvasNode, index: number) => unknown): CanvasNode | undefined {\n\t\tconst index = this.findLastIndex(predicate)\n\t\tif (index === -1) return undefined\n\n\t\treturn this.at(index)\n\t}\n\n\tfindLastIndex(predicate: (node: CanvasNode, index: number) => unknown): number {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.findLastIndex(predicate)\n\n\t\tconst childIds = this.getChildIds()\n\n\t\tfor (let index = childIds.length - 1; index >= 0; index--) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tif (predicate(child, index)) return index\n\t\t}\n\n\t\treturn -1\n\t}\n\n\tslice(start?: number, end?: number): CanvasNode[] {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.slice(start, end)\n\n\t\tconst childIds = this.getChildIds().slice(start, end)\n\t\tconst result = Array<CanvasNode>(childIds.length)\n\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tresult[index] = child\n\t\t}\n\n\t\treturn result\n\t}\n\n\tsplice(): void {\n\t\tthrow new Error(\"Unsupported\")\n\t}\n\n\tpush(): void {\n\t\tthrow new Error(\"Unsupported\")\n\t}\n\n\ttoArray(): CanvasNode[] {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return editedChildren.slice()\n\n\t\tconst childIds = this.getChildIds()\n\t\tconst result = Array<CanvasNode>(childIds.length)\n\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tresult[index] = child\n\t\t}\n\n\t\treturn result\n\t}\n\n\t*[Symbol.iterator](): IterableIterator<CanvasNode> {\n\t\tconst editedChildren = this.getEditedChildren()\n\t\tif (editedChildren) return yield* editedChildren\n\n\t\tconst childIds = this.getChildIds()\n\n\t\tfor (let index = 0; index < childIds.length; index++) {\n\t\t\tconst id = childIds[index]!\n\t\t\tconst child = getOrCreateReplicaOrNormalNode(this.container, id)\n\n\t\t\tyield child\n\t\t}\n\t}\n}\n\nexport function precomputeDataNodeClasses() {\n\tif (dataOnlyNodeClasses.size > 0) return\n\n\tconst factory = getOrRegisterDriverBasedOnExperiment()\n\tassert(factory.type === \"prototype.dynamicOverrides\")\n\n\tconst classList = getNodeSubclassList()\n\tfor (const BaseClass of classList) {\n\t\tclass DataTreeNodeProxy implements DataTreeNode {\n\t\t\tdeclare dataTree: DataTree\n\t\t\tdeclare sourceIds: string[]\n\t\t\tdeclare ownerId: string | undefined\n\t\t\tdeclare originalId: string | undefined\n\n\t\t\tdeclare $$cache$$: CanvasNodeCache\n\t\t\tdeclare $$children$$: DataChildList\n\n\t\t\tdeclare [META_FIELD]: WithProtoData<unknown>[typeof META_FIELD]\n\t\t\tdeclare [DEFAULTS_FIELD]: WithProtoData<unknown>[typeof DEFAULTS_FIELD]\n\n\t\t\tconstructor(\n\t\t\t\tdataTree: DataTree,\n\t\t\t\tpublic id: string,\n\t\t\t\tsourceIds: string[],\n\t\t\t\townerId: string | undefined,\n\t\t\t\toriginalId: string | undefined,\n\t\t\t) {\n\t\t\t\tthis.setPrivateProperty(\"dataTree\", dataTree)\n\t\t\t\tthis.setPrivateProperty(\"sourceIds\", sourceIds)\n\t\t\t\tthis.setPrivateProperty(\"ownerId\", ownerId)\n\t\t\t\tthis.setPrivateProperty(\"originalId\", originalId)\n\n\t\t\t\tfor (const sourceId of sourceIds) {\n\t\t\t\t\tconst otherKeys = dataTree.store.getObjectKeys(sourceId, dynamicPropPredicate)\n\t\t\t\t\tfor (const key of otherKeys) {\n\t\t\t\t\t\tif (key in this) continue\n\t\t\t\t\t\tif (!resolvesDefined(dataTree.store, sourceIds, key)) continue\n\n\t\t\t\t\t\tthis.createControlPropForKey(key)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprivate createControlPropForKey(key: string) {\n\t\t\t\tif (key in this) return\n\n\t\t\t\tObject.defineProperty(this, key, {\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\tget(this: DataTreeNodeProxy) {\n\t\t\t\t\t\tconst editedValue = this.dataTree.editedNodes.get(this.id)?.[key]\n\t\t\t\t\t\tif (editedValue !== undefined) return editedValue\n\n\t\t\t\t\t\tfor (const sId of this.sourceIds) {\n\t\t\t\t\t\t\tif (sId.includes(\".\")) {\n\t\t\t\t\t\t\t\tconst v = this.dataTree.store.getObjectKey(sId, key)\n\t\t\t\t\t\t\t\tif (v !== undefined) return v\n\t\t\t\t\t\t\t\tconst deleted = this.dataTree.store.getObjectKey<string[]>(sId, \"_deleted\")\n\t\t\t\t\t\t\t\tif (Array.isArray(deleted) && deleted.includes(key)) return undefined\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst v = this.dataTree.store.getObjectKey(sId, key)\n\t\t\t\t\t\t\t\tif (v !== undefined) return v\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn undefined\n\t\t\t\t\t},\n\t\t\t\t\tset(value: unknown) {\n\t\t\t\t\t\tthis.dataTree.getOrCreateEditedNodeFor(this.id)[key] = value\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tget cache() {\n\t\t\t\tif (!this.$$cache$$) {\n\t\t\t\t\tconst cache =\n\t\t\t\t\t\tthis.dataTree.getPersistedNodeCache(this.id) ??\n\t\t\t\t\t\tthis.dataTree.setPersistedNodeCache(this.id, new this[META_FIELD].cacheClass())\n\t\t\t\t\tcache.isShallowLoad = false\n\n\t\t\t\t\t// Route localizationSourceGroup through the LatestObject's cache bag so the\n\t\t\t\t\t// computed value survives across per-frame DataTree resets. The LatestObject\n\t\t\t\t\t// lives for the node's lifetime in the CRDT store, so no extra map is needed.\n\t\t\t\t\tconst nodeId = this.id\n\t\t\t\t\tconst { store } = this.dataTree\n\t\t\t\t\tObject.defineProperty(cache, \"localizationSourceGroup\", {\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tget(): object | undefined {\n\t\t\t\t\t\t\treturn store.getLatest(nodeId)?.cache?.localizationSourceGroup as object | undefined\n\t\t\t\t\t\t},\n\t\t\t\t\t\tset(value: object | undefined) {\n\t\t\t\t\t\t\tconst latest = store.getLatest(nodeId)\n\t\t\t\t\t\t\tif (!latest) return\n\t\t\t\t\t\t\tif (!latest.cache) latest.cache = {}\n\t\t\t\t\t\t\tlatest.cache.localizationSourceGroup = value\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\n\t\t\t\t\tthis.setPrivateProperty(\"$$cache$$\", cache)\n\t\t\t\t\treturn cache\n\t\t\t\t}\n\n\t\t\t\treturn this.$$cache$$\n\t\t\t}\n\n\t\t\tget loaded() {\n\t\t\t\treturn this\n\t\t\t}\n\n\t\t\tisLoaded() {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\ttree() {\n\t\t\t\treturn this.dataTree.getCanvasTreeProxy()\n\t\t\t}\n\n\t\t\tget update() {\n\t\t\t\tif (this.originalId) {\n\t\t\t\t\tconst overrideStoreId = `${this.ownerId}.replicaInfo.overrides.${this.originalId}`\n\t\t\t\t\tconst overrideUpdate = this.dataTree.store.getLatest(overrideStoreId)?.update ?? 0\n\t\t\t\t\tconst originalUpdate = this.dataTree.store.getLatest(this.originalId)?.update ?? 0\n\t\t\t\t\t// We need to notice a change if either the overrides change or the original node changes.\n\t\t\t\t\treturn overrideUpdate + originalUpdate\n\t\t\t\t}\n\t\t\t\treturn this.dataTree.store.getLatest(this.id)?.update ?? 0\n\t\t\t}\n\n\t\t\tcloneEmpty() {\n\t\t\t\treturn new BaseClass()\n\t\t\t}\n\n\t\t\t*walk() {\n\t\t\t\tconst stack: CanvasNode[] = [this as unknown as CanvasNode]\n\t\t\t\twhile (stack.length > 0) {\n\t\t\t\t\tconst node = stack.pop()\n\t\t\t\t\tassert(node)\n\n\t\t\t\t\tif (!this.dataTree.isDataNode(node)) {\n\t\t\t\t\t\tyield* node.walk()\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tyield node\n\n\t\t\t\t\tconst id = node.originalid ?? node.id\n\t\t\t\t\tconst editedChildren = this.dataTree.editedChildren.get(id)\n\t\t\t\t\tconst children = editedChildren?.map(c => c.id) ?? this.dataTree.store.getChildrenIds(id)\n\n\t\t\t\t\tfor (let i = children.length - 1; i >= 0; --i) {\n\t\t\t\t\t\tconst child = children[i]!\n\t\t\t\t\t\tstack.push(getOrCreateReplicaOrNormalNode(node as unknown as DataTreeNodeProxy, child))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Walk a subtree yielding lightweight accessors\n\t\t\t * that read directly from the CRDT store.\n\t\t\t */\n\t\t\t*fastWalk(): IterableIterator<NodeAccessor> {\n\t\t\t\tinterface FastWalkFrame {\n\t\t\t\t\townerSynthId: string\n\t\t\t\t\townerStoreId: string\n\t\t\t\t\tmasterId: string\n\t\t\t\t\tinheritsFromOwnerStoreId: string | undefined\n\t\t\t\t}\n\n\t\t\t\tconst POP_FRAME = -1 as const\n\t\t\t\tconst stack: (string | typeof POP_FRAME)[] = [this.id]\n\t\t\t\tconst frames: FastWalkFrame[] = []\n\n\t\t\t\twhile (stack.length > 0) {\n\t\t\t\t\tconst entry = stack.pop()!\n\t\t\t\t\tif (entry === POP_FRAME) {\n\t\t\t\t\t\tframes.pop()\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst stackId = entry\n\t\t\t\t\tassert(stackId, \"stackId must be set\")\n\n\t\t\t\t\tconst topFrame = frames.length > 0 ? frames[frames.length - 1] : undefined\n\t\t\t\t\tconst replicaInfoMaster = this.dataTree.store.getObjectKey<string>(`${stackId}.replicaInfo`, \"master\")\n\n\t\t\t\t\tlet synthId: string\n\t\t\t\t\tlet originalId: string\n\t\t\t\t\tlet newFrame: FastWalkFrame | undefined\n\n\t\t\t\t\tif (replicaInfoMaster) {\n\t\t\t\t\t\t// Replica owner \u2014 top-level entry or nested instance.\n\t\t\t\t\t\tsynthId = topFrame ? topFrame.ownerSynthId + stackId : stackId\n\t\t\t\t\t\toriginalId = replicaInfoMaster\n\t\t\t\t\t\tconst inheritsFromId = this.dataTree.store.getObjectKey<string>(`${stackId}.replicaInfo`, \"inheritsFrom\")\n\t\t\t\t\t\tnewFrame = {\n\t\t\t\t\t\t\townerSynthId: synthId,\n\t\t\t\t\t\t\townerStoreId: stackId,\n\t\t\t\t\t\t\tmasterId: replicaInfoMaster,\n\t\t\t\t\t\t\tinheritsFromOwnerStoreId: inheritsFromId,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (topFrame) {\n\t\t\t\t\t\tsynthId = topFrame.ownerSynthId + stackId\n\t\t\t\t\t\toriginalId = stackId\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsynthId = stackId\n\t\t\t\t\t\toriginalId = stackId\n\t\t\t\t\t}\n\n\t\t\t\t\t// Snapshot for closure \u2014 frames mutate as the walk progresses.\n\t\t\t\t\tconst snapshotFrames = newFrame ? [...frames, newFrame] : [...frames]\n\t\t\t\t\tconst isOwner = newFrame !== undefined\n\t\t\t\t\tconst ownerStoreId = stackId\n\n\t\t\t\t\tconst __class = this.dataTree.store.getObjectKey<string>(stackId, \"__class\")\n\t\t\t\t\tassert(__class)\n\t\t\t\t\tconst accessor: NodeAccessor = {\n\t\t\t\t\t\tid: synthId,\n\t\t\t\t\t\t__class,\n\t\t\t\t\t\tget: (key: string) => {\n\t\t\t\t\t\t\tif (key === \"parentid\") {\n\t\t\t\t\t\t\t\tif (isOwner) {\n\t\t\t\t\t\t\t\t\tconst ownerParentId = this.dataTree.store.getParentId(ownerStoreId)\n\t\t\t\t\t\t\t\t\tif (!ownerParentId || ownerParentId === DELETED_VALUE) return null\n\t\t\t\t\t\t\t\t\tconst outerFrame = snapshotFrames[snapshotFrames.length - 2]\n\t\t\t\t\t\t\t\t\tif (!outerFrame) return ownerParentId\n\t\t\t\t\t\t\t\t\tif (ownerParentId === outerFrame.masterId) return outerFrame.ownerSynthId\n\t\t\t\t\t\t\t\t\treturn outerFrame.ownerSynthId + ownerParentId\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst parentMasterId = this.dataTree.store.getParentId(originalId)\n\t\t\t\t\t\t\t\tif (!parentMasterId || parentMasterId === DELETED_VALUE) return null\n\n\t\t\t\t\t\t\t\tconst innermostFrame = snapshotFrames[snapshotFrames.length - 1]\n\t\t\t\t\t\t\t\tif (!innermostFrame) return parentMasterId\n\t\t\t\t\t\t\t\tif (parentMasterId === innermostFrame.masterId) return innermostFrame.ownerSynthId\n\t\t\t\t\t\t\t\treturn innermostFrame.ownerSynthId + parentMasterId\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (key === \"originalid\") {\n\t\t\t\t\t\t\t\tif (snapshotFrames.length === 0) return null\n\t\t\t\t\t\t\t\treturn originalId\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst defaults = dataOnlyNodeClasses.get(__class)?.prototype?.[DEFAULTS_FIELD]\n\t\t\t\t\t\t\tif (!key.startsWith(\"$\") && !(key in defaults)) return undefined\n\n\t\t\t\t\t\t\tif (key === \"replicaInfo\") {\n\t\t\t\t\t\t\t\treturn reviveReplicaInfo(this.dataTree.store.getObjectKey(ownerStoreId, key))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst editedNode = this.dataTree.getEditedNodeFor(synthId)\n\t\t\t\t\t\t\tif (editedNode && key in editedNode) return editedNode[key]\n\n\t\t\t\t\t\t\tlet reviver = reviveValue\n\t\t\t\t\t\t\tif (key === \"masks\") reviver = reviveMaskGradients\n\t\t\t\t\t\t\telse if (key === \"guidesX\" || key === \"guidesY\") reviver = reviveGuidesInfo\n\n\t\t\t\t\t\t\tif (snapshotFrames.length > 0) {\n\t\t\t\t\t\t\t\t// Override priority: outer frames first, innermost last, then master fallback.\n\t\t\t\t\t\t\t\tfor (let i = 0; i < snapshotFrames.length; i++) {\n\t\t\t\t\t\t\t\t\tconst frame = snapshotFrames[i]!\n\t\t\t\t\t\t\t\t\tconst isOwnFrame = isOwner && i === snapshotFrames.length - 1\n\t\t\t\t\t\t\t\t\tconst frameKey = isOwnFrame ? frame.masterId : synthId.slice(frame.ownerSynthId.length)\n\t\t\t\t\t\t\t\t\tconst sources: string[] = [`${frame.ownerStoreId}.replicaInfo.overrides.${frameKey}`]\n\t\t\t\t\t\t\t\t\tif (frame.inheritsFromOwnerStoreId) {\n\t\t\t\t\t\t\t\t\t\tsources.push(`${frame.inheritsFromOwnerStoreId}.replicaInfo.overrides.${frameKey}`)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tfor (const sourceId of sources) {\n\t\t\t\t\t\t\t\t\t\tconst value = this.dataTree.store.getObjectKey(sourceId, key)\n\t\t\t\t\t\t\t\t\t\tif (value !== undefined) return reviver(value)\n\t\t\t\t\t\t\t\t\t\tconst deleted = this.dataTree.store.getObjectKey<string[]>(sourceId, \"_deleted\")\n\t\t\t\t\t\t\t\t\t\tif (Array.isArray(deleted) && deleted.includes(key)) return undefined\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst masterValue = this.dataTree.store.getObjectKey(originalId, key)\n\t\t\t\t\t\t\t\tif (masterValue !== undefined) return reviver(masterValue)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst value = this.dataTree.store.getObjectKey(stackId, key)\n\t\t\t\t\t\t\t\tif (value !== undefined) return reviver(value)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn reviver(defaults[key as keyof typeof defaults])\n\t\t\t\t\t\t},\n\t\t\t\t\t\tskipChildren: false,\n\t\t\t\t\t}\n\n\t\t\t\t\tif (newFrame) {\n\t\t\t\t\t\tframes.push(newFrame)\n\t\t\t\t\t\tstack.push(POP_FRAME)\n\t\t\t\t\t}\n\n\t\t\t\t\tyield accessor\n\n\t\t\t\t\tif (accessor.skipChildren) {\n\t\t\t\t\t\tif (newFrame) {\n\t\t\t\t\t\t\tassert(stack.pop() === POP_FRAME)\n\t\t\t\t\t\t\tframes.pop()\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tconst childrenIds = this.dataTree.store.getChildrenIds(replicaInfoMaster ?? stackId)\n\t\t\t\t\t// Push in reverse so left-to-right order is preserved when popping\n\t\t\t\t\tfor (let i = childrenIds.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tconst child = childrenIds[i]!\n\t\t\t\t\t\tstack.push(child)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsetProp(key: string, value: unknown) {\n\t\t\t\tconst editedNode = this.dataTree.getOrCreateEditedNodeFor(this.id)\n\t\t\t\teditedNode[key] = value\n\n\t\t\t\tif (key.startsWith(\"$\")) {\n\t\t\t\t\tthis.createControlPropForKey(key)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\thasProp<Key extends keyof this>(key: Key) {\n\t\t\t\treturn key in this\n\t\t\t}\n\n\t\t\tdeleteProp(key: string) {\n\t\t\t\tdelete this[key as keyof this]\n\t\t\t\tconst editedNode = this.dataTree.getOrCreateEditedNodeFor(this.id)\n\t\t\t\teditedNode[key] = undefined\n\t\t\t}\n\n\t\t\tassign(...properties: Record<string, unknown>[]) {\n\t\t\t\tconst editedNode = this.dataTree.getOrCreateEditedNodeFor(this.id)\n\t\t\t\tObject.assign(editedNode, ...properties)\n\n\t\t\t\tfor (const prop of properties) {\n\t\t\t\t\tfor (const key in prop) {\n\t\t\t\t\t\tif (key.startsWith(\"$\")) {\n\t\t\t\t\t\t\tthis.createControlPropForKey(key)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tget [isDataNodeSymbol]() {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tsetPrivateProperty<Key extends keyof this>(key: Key, value: this[Key]) {\n\t\t\t\tObject.defineProperty(this, key, { value, enumerable: false })\n\t\t\t}\n\n\t\t\tasDraft() {\n\t\t\t\treturn this.dataTree.getNodeAsDraft(this as unknown as MutableNode)\n\t\t\t}\n\t\t}\n\t\tconst proto = BaseClass.prototype as WithProtoData<CanvasNode>\n\t\tObject.setPrototypeOf(DataTreeNodeProxy.prototype, proto)\n\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(proto)\n\t\tfor (const prop in descriptors) {\n\t\t\tif (proto[OWN_SETTERS_FIELD].includes(prop)) continue\n\n\t\t\tconst desc = descriptors[prop]!\n\t\t\tif (desc.get && desc.set) {\n\t\t\t\tif (prop === \"originalid\") {\n\t\t\t\t\tObject.defineProperty(DataTreeNodeProxy.prototype, prop, {\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tget(this: DataTreeNodeProxy) {\n\t\t\t\t\t\t\treturn this.originalId\n\t\t\t\t\t\t},\n\t\t\t\t\t\tset(this: DataTreeNodeProxy, value: unknown) {\n\t\t\t\t\t\t\tthis.dataTree.getOrCreateEditedNodeFor(this.id)[prop] = value\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} else if ([\"isMaster\", \"isExternalMaster\"].includes(prop)) {\n\t\t\t\t\tObject.defineProperty(DataTreeNodeProxy.prototype, prop, {\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tget(this: DataTreeNodeProxy) {\n\t\t\t\t\t\t\tlet value = this.dataTree.editedNodes.get(this.id)?.[prop]\n\t\t\t\t\t\t\tif (value !== undefined) return value\n\t\t\t\t\t\t\tvalue = this.dataTree.store.getObjectKey(this.id, prop)\n\t\t\t\t\t\t\tif (value !== undefined) return value\n\t\t\t\t\t\t\treturn this[DEFAULTS_FIELD][prop]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tset(this: DataTreeNodeProxy, value: unknown) {\n\t\t\t\t\t\t\tthis.dataTree.getOrCreateEditedNodeFor(this.id)[prop] = value\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} else if (prop === \"parentid\") {\n\t\t\t\t\tObject.defineProperty(DataTreeNodeProxy.prototype, prop, {\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tget(this: DataTreeNodeProxy) {\n\t\t\t\t\t\t\tconst id = this.originalId ?? this.id\n\t\t\t\t\t\t\tconst parentId = this.dataTree.store.getParentId(id)\n\t\t\t\t\t\t\tif (parentId === undefined || parentId === DELETED_VALUE) return\n\t\t\t\t\t\t\tif (this.ownerId === this.id) return parentId\n\n\t\t\t\t\t\t\tif (this.originalId && this.ownerId) {\n\t\t\t\t\t\t\t\tconst owner = getOrCreateDataTreeNode(this.dataTree, this.ownerId) as unknown as DataTreeNodeProxy\n\t\t\t\t\t\t\t\tif (parentId === owner.originalId) return this.ownerId\n\t\t\t\t\t\t\t\treturn generateReplicaChildId(owner.id, parentId)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn parentId\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} else if (prop === \"replicaInfo\") {\n\t\t\t\t\tObject.defineProperty(DataTreeNodeProxy.prototype, prop, {\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tget(this: DataTreeNode) {\n\t\t\t\t\t\t\tlet value = this.dataTree.editedNodes.get(this.id)?.[prop] as ReplicaInfo | undefined\n\t\t\t\t\t\t\tif (value !== undefined) return value\n\n\t\t\t\t\t\t\tvalue = this.dataTree.store.getObjectKey<ReplicaInfo>(this.id, prop)\n\t\t\t\t\t\t\tif (value !== undefined) return reviveReplicaInfo(value)\n\n\t\t\t\t\t\t\treturn this[DEFAULTS_FIELD][prop]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tset(this: DataTreeNode, value: unknown) {\n\t\t\t\t\t\t\tthis.dataTree.getOrCreateEditedNodeFor(this.id)[prop] = value\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} else if (prop === \"masks\") {\n\t\t\t\t\tcreateGetterSetterForProp(DataTreeNodeProxy.prototype, prop, reviveMaskGradients)\n\t\t\t\t} else if (prop === \"guidesX\" || prop === \"guidesY\") {\n\t\t\t\t\tcreateGetterSetterForProp(DataTreeNodeProxy.prototype, prop, reviveGuidesInfo)\n\t\t\t\t} else {\n\t\t\t\t\tcreateGetterSetterForProp(DataTreeNodeProxy.prototype, prop, reviveValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (proto[META_FIELD].hasChildren) {\n\t\t\tObject.defineProperty(DataTreeNodeProxy.prototype, \"children\", {\n\t\t\t\tenumerable: true,\n\t\t\t\tget(this: DataTreeNodeProxy) {\n\t\t\t\t\tif (this.$$children$$) {\n\t\t\t\t\t\treturn this.$$children$$\n\t\t\t\t\t}\n\n\t\t\t\t\tconst childList = new DataChildList(this)\n\t\t\t\t\tthis.setPrivateProperty(\"$$children$$\", childList)\n\t\t\t\t\treturn childList\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\n\t\tdataOnlyNodeClasses.set(proto.__class, DataTreeNodeProxy)\n\t}\n}\n\nfunction getOrCreateReplicaOrNormalNode(container: DataTreeNode, childId: string) {\n\tif (container.ownerId) {\n\t\treturn getOrCreateDataTreeReplicaNode(container.dataTree, container.ownerId, childId)\n\t}\n\n\treturn getOrCreateDataTreeNode(container.dataTree, childId)\n}\n", "import { DELETED_VALUE, type Store } from \"@framerjs/crdtree2\"\nimport type { Hierarchy, NodeData } from \"@framerjs/crdtree2/src/Hierarchy.ts\"\nimport { DOES_NOT_EXIST } from \"@framerjs/crdtree2/src/table/schema/nativeValues.ts\"\nimport type { WithChildren } from \"@framerjs/document-snapshotter\"\nimport type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, getLogger } from \"@framerjs/shared\"\nimport { noop } from \"@framerjs/shared/src/noop.ts\"\nimport type {\n\tBaseScopeNodes,\n\tMapArrayToLoadedOptionalScopeNodes,\n\tMapScopeNodesToShallow,\n} from \"document/models/CanvasTree/CanvasTree.ts\"\nimport { type ReversibleNodeChange, nodeChange } from \"document/models/CanvasTree/TreeDiff.ts\"\nimport { computeOverrideChanges } from \"document/models/CanvasTree/TreeDiffOverrides.ts\"\nimport {\n\ttype CanvasNode,\n\ttype CanvasTree,\n\ttype LoadedScopeNode,\n\ttype MaybeNodeID,\n\ttype NodeID,\n\ttype RootNode,\n\ttype ShallowScopeNode,\n\tisScopeNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type { ImmutableNode, MutableNode, ReadonlyChildren } from \"document/models/CanvasTree/nodes/MutableNode.ts\"\nimport { markPrimaryTextStylePresetAsDraft } from \"document/models/CanvasTree/nodes/TextStylePresetNode.ts\"\nimport { getNodeDefaultsByClassName, getNodeSubclassByClassName } from \"document/models/CanvasTree/nodes/classList.ts\"\nimport { isStylePresetBreakpoint } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { usesModuleRevision } from \"document/models/CanvasTree/traits/WithModuleRevision.ts\"\nimport type { BaseShallowType } from \"document/models/CanvasTree/traits/WithScopeLoader.ts\"\nimport { isReplicaOrReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { maybePatchItemsOrder } from \"document/utils/itemsOrderOverrideHelpers.ts\"\nimport { getScopeForId } from \"../sync/getScopesToLoad.ts\"\nimport { createDataTreeProxy } from \"./DataTreeProxy.ts\"\nimport type { PersistedNodeCaches } from \"./PersistedNodeCaches.ts\"\nimport type { TreeQueryContext } from \"./TreeQueryBuilder.ts\"\nimport { isDataNodeSymbol } from \"./dataNodeSymbol.ts\"\nimport { getOrCreateDataTreeNode, getOrCreateDataTreeReplicaNode, precomputeDataNodeClasses } from \"./dataTreeNodes.ts\"\n\ntype EditedNode = Record<string, unknown> & { children?: never }\n\nconst log = getLogger(\"data-tree\")\n\n// @ts-expect-error Data tree does not implement every method\n// TODO: If a method is missing but required, add it here\nexport class DataTree implements CanvasTree {\n\tinsertedNodes: Map<string, CanvasNode> = new Map()\n\tremovedNodes: Set<string> = new Set()\n\teditedNodes = new Map<string, EditedNode>()\n\teditedChildren = new Map<string, CanvasNode[]>()\n\n\thierarchy: Hierarchy\n\treadonly seq: number\n\n\tconstructor(\n\t\treadonly store: Store,\n\t\treadonly canvasTree: CanvasTree,\n\t\treadonly treeQueryContext?: TreeQueryContext,\n\t\treadonly persistedCaches?: PersistedNodeCaches,\n\t) {\n\t\tthis.seq = store.seq\n\t\tthis.hierarchy = store.getHierarchy()\n\t\tprecomputeDataNodeClasses()\n\t}\n\n\tequals(other: CanvasTree): boolean {\n\t\tif (!(other instanceof DataTree)) return false\n\t\tif (this.canvasTree !== other.canvasTree) return false\n\t\treturn this.seq === other.seq\n\t}\n\n\t// Delegate lineage to canvas tree for compatibility\n\tget lineage() {\n\t\treturn this.canvasTree.lineage\n\t}\n\n\t// Delegate root to canvas tree for compatibility\n\tget root() {\n\t\tconst rootNode = this.get<RootNode>(this.canvasTree.root.id)\n\t\tassert(rootNode, \"Root node must exist\")\n\t\treturn rootNode\n\t}\n\n\tget editClosed() {\n\t\treturn this.canvasTree.latestTree().editClosed\n\t}\n\n\tget isViewOnly() {\n\t\treturn this.canvasTree.latestTree().isViewOnly\n\t}\n\n\tget inEditor() {\n\t\treturn this.canvasTree.latestTree().inEditor\n\t}\n\n\tlatestTree() {\n\t\tconst dataTree = new DataTree(this.store, this.canvasTree.latestTree(), this.treeQueryContext, this.persistedCaches)\n\t\treturn dataTree.getCanvasTreeProxy()\n\t}\n\n\thasUncommittedChanges(): boolean {\n\t\treturn this.removedNodes.size > 0 || this.insertedNodes.size > 0 || this.editedNodes.size > 0\n\t}\n\n\t/**\n\t * @note Used **only** in TreeQueryBuilder because\n\t * directly importing `getOrCreateDataTreeNode`\n\t * causes circular dependency\n\t */\n\tgetOrCreateNodeById<T extends CanvasNode>(id: string) {\n\t\treturn getOrCreateDataTreeNode<T>(this, id)\n\t}\n\n\t/** @mutates changes */\n\tprivate pushChangesForNode(changes: ReversibleNodeChange[], id: string, editedNode: EditedNode | null) {\n\t\tconst original = this.store.getObject(id)\n\t\tassert(typeof original?.__class === \"string\", \"editedNode id is missing a __class\", id)\n\t\tconst nodeClassConstructor = getNodeSubclassByClassName(original.__class)\n\t\tassert(nodeClassConstructor, \"constructor not found for __class\", original.__class)\n\n\t\tconst originalAsNode = new nodeClassConstructor({ id: original.id as string, ...original })\n\t\tconst editedAsNode = editedNode\n\t\t\t? new nodeClassConstructor({ id: original.id as string, ...original, ...editedNode })\n\t\t\t: null\n\n\t\tconst change = nodeChange(originalAsNode, editedAsNode, true)\n\t\tif (change) {\n\t\t\tchanges.push(change)\n\t\t}\n\n\t\tconst overrideChanges: ReversibleNodeChange[] = []\n\t\tcomputeOverrideChanges(overrideChanges, originalAsNode, editedAsNode)\n\t\tfor (const oc of overrideChanges) {\n\t\t\tchanges.push(oc)\n\t\t}\n\t}\n\n\tcomputeReversibleChanges(): ReversibleNodeChange[] {\n\t\tconst changes: ReversibleNodeChange[] = []\n\n\t\tfor (const [_id, node] of this.insertedNodes) {\n\t\t\tconst change = nodeChange(null, node, true)\n\t\t\tif (change) {\n\t\t\t\tchanges.push(change)\n\t\t\t}\n\n\t\t\tconst overrideChanges: ReversibleNodeChange[] = []\n\t\t\tcomputeOverrideChanges(overrideChanges, null, node)\n\t\t\tfor (const oc of overrideChanges) {\n\t\t\t\tchanges.push(oc)\n\t\t\t}\n\t\t}\n\n\t\tconst removedNodeIdsInOrder: string[] = []\n\t\tconst remainingRemovedNodeIds = new Set(this.removedNodes)\n\t\tconst rootId = this.hierarchy.getRootId()\n\n\t\tconst visitRemovedNodes = (id: string) => {\n\t\t\tfor (const childId of this.hierarchy.getChildrenIds(id)) {\n\t\t\t\tvisitRemovedNodes(childId)\n\t\t\t}\n\n\t\t\tif (remainingRemovedNodeIds.has(id)) {\n\t\t\t\tremovedNodeIdsInOrder.push(id)\n\t\t\t\tremainingRemovedNodeIds.delete(id)\n\t\t\t}\n\t\t}\n\n\t\tif (rootId) {\n\t\t\tvisitRemovedNodes(rootId)\n\t\t}\n\n\t\tfor (const id of remainingRemovedNodeIds) {\n\t\t\tremovedNodeIdsInOrder.push(id)\n\t\t}\n\n\t\tconst removedNodeIdsSet = new Set(removedNodeIdsInOrder)\n\t\tconst removeOrderPrerequisites = new Map<string, string[]>()\n\t\tfor (const id of removedNodeIdsInOrder) {\n\t\t\tconst nodeData = this.store.getObject<Record<string, unknown>>(id)\n\t\t\tconst replicaInfo = nodeData?.replicaInfo as Record<string, unknown> | undefined\n\t\t\tconst masterId = typeof replicaInfo?.master === \"string\" ? replicaInfo.master : undefined\n\t\t\tif (!masterId || !removedNodeIdsSet.has(masterId)) continue\n\n\t\t\tconst prerequisites = removeOrderPrerequisites.get(masterId) ?? []\n\t\t\tprerequisites.push(id)\n\t\t\tremoveOrderPrerequisites.set(masterId, prerequisites)\n\t\t}\n\n\t\tconst orderedRemovedNodeIds: string[] = []\n\t\tconst permanentlyVisited = new Set<string>()\n\t\tconst temporarilyVisited = new Set<string>()\n\t\tconst visitRemovedNode = (id: string) => {\n\t\t\tif (permanentlyVisited.has(id)) return\n\t\t\tif (temporarilyVisited.has(id)) return\n\n\t\t\ttemporarilyVisited.add(id)\n\t\t\tfor (const prerequisiteId of removeOrderPrerequisites.get(id) ?? []) {\n\t\t\t\tvisitRemovedNode(prerequisiteId)\n\t\t\t}\n\t\t\ttemporarilyVisited.delete(id)\n\n\t\t\tpermanentlyVisited.add(id)\n\t\t\torderedRemovedNodeIds.push(id)\n\t\t}\n\n\t\tfor (const id of removedNodeIdsInOrder) {\n\t\t\tvisitRemovedNode(id)\n\t\t}\n\n\t\tfor (const id of orderedRemovedNodeIds) {\n\t\t\tthis.pushChangesForNode(changes, id, null)\n\t\t}\n\n\t\tfor (const [id, editedNode] of this.editedNodes) {\n\t\t\t// Skip if replica child, the replica will create the change.\n\t\t\tconst node = this.get(id)\n\t\t\tassert(node, \"node not in data tree, id: \", id)\n\t\t\tconst isReplicaChild = Boolean(node.originalid) && !node.replicaInfo\n\t\t\tif (isReplicaChild) continue\n\n\t\t\tthis.pushChangesForNode(changes, id, editedNode)\n\t\t}\n\n\t\treturn changes\n\t}\n\n\tpreCommit(componentLoader: AnyComponentLoader): ReversibleNodeChange[] {\n\t\tthis.moveEditsToRootOrShallowScopes()\n\t\tthis.markScopesAsDraft()\n\t\tthis.markReplicasAsDraft()\n\n\t\tfor (const [id, _] of this.editedNodes) {\n\t\t\tconst node = this.get(id)\n\t\t\tnode?.preCommit(this.getCanvasTreeProxy(), componentLoader)\n\t\t}\n\n\t\tconst changes = this.computeReversibleChanges()\n\n\t\tthis.editedNodes.clear()\n\t\tthis.removedNodes.clear()\n\t\tthis.editedChildren.clear()\n\t\tthis.insertedNodes.clear()\n\n\t\treturn changes\n\t}\n\n\t/**\n\t * When editing the root node, or a shallow scope node, the edits are not done on the actual\n\t * nodes. Because the children of these nodes need intercepting. But normal property edits\n\t * should still go to the actual canvas node.\n\t */\n\tprivate moveEditsToRootOrShallowScopes() {\n\t\tconst actualNodeEdits = new Set<string>()\n\n\t\t// Apply edits to the tree instead.\n\t\tfor (const nodeId of this.editedNodes.keys()) {\n\t\t\tif (nodeId === this.canvasTree.root.id) {\n\t\t\t\tthis.canvasTree.root.set({ ...this.editedNodes.get(nodeId) } as Partial<RootNode>)\n\t\t\t\tactualNodeEdits.add(nodeId)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst canvasNode = this.canvasTree.get(nodeId)\n\t\t\tif (!canvasNode) continue\n\t\t\tif (!isScopeNode(canvasNode)) continue\n\t\t\tif (canvasNode.isLoaded()) continue\n\n\t\t\tcanvasNode.set({ ...this.editedNodes.get(nodeId) } as Partial<typeof canvasNode>)\n\t\t\tactualNodeEdits.add(nodeId)\n\t\t}\n\n\t\t// Remove the edits from the editedNodes map.\n\t\tfor (const nodeId of actualNodeEdits) {\n\t\t\tthis.editedNodes.delete(nodeId)\n\t\t}\n\t}\n\n\t/**\n\t * Mark all scopes that have data-only changes as 'draft' so their\n\t * module revision hint is incremented during the next tree commit.\n\t */\n\tprivate markScopesAsDraft() {\n\t\tconst scopeClassCache = new Map<string, boolean>()\n\t\tconst markedScopes = new Set<string>()\n\n\t\tconst markScopeAsDraft = (nodeId: string) => {\n\t\t\t// Replica-children are not removed from the tree;\n\t\t\t// they are only set to `visible: false`. Replica-children\n\t\t\t// also do not have ids in the store. So, if we can\n\t\t\t// resolve the node from the tree - i.e. its not deleted or its\n\t\t\t// a replica-child - try to use its originalid to find the scope\n\t\t\t// and fallback to the nodeId if it doesn't exist.\n\t\t\tconst node = this.get(nodeId)\n\t\t\tconst scopeId = getScopeForId(this.store, node?.originalid ?? nodeId, scopeClassCache)\n\t\t\tif (!scopeId || markedScopes.has(scopeId)) return\n\n\t\t\tconst scopeNode = this.canvasTree.get(scopeId)\n\t\t\tif (!scopeNode || !usesModuleRevision(scopeNode, this.getCanvasTreeProxy())) return\n\n\t\t\tmarkedScopes.add(scopeId)\n\t\t\tscopeNode.asDraft(this.canvasTree)\n\t\t}\n\n\t\tfor (const [_, node] of this.insertedNodes) {\n\t\t\tassert(node.parentid, \"node must have a parent id\")\n\t\t\tmarkScopeAsDraft(node.parentid)\n\t\t}\n\t\tfor (const nodeId of this.removedNodes) {\n\t\t\tmarkScopeAsDraft(nodeId)\n\t\t}\n\t\tfor (const nodeId of this.editedNodes.keys()) {\n\t\t\tmarkScopeAsDraft(nodeId)\n\t\t}\n\t}\n\n\t/**\n\t * Mark replicas (and their masters) as draft so that `preCommit`\n\t * rebuilds replicaInfo.overrides via `rebuildFromMaster`.\n\t *\n\t * Two cases:\n\t * 1. Master child removed \u2192 mark master + all its replicas as draft.\n\t * 2. Replica child edited \u2192 mark the owning replica as draft.\n\t */\n\tprivate markReplicasAsDraft() {\n\t\tfor (const nodeId of this.removedNodes) {\n\t\t\tif (this.canvasTree.has(nodeId)) continue\n\n\t\t\tconst nodeData = this.hierarchy.getNodeData(nodeId)\n\t\t\tconst masterId = nodeData?.inMaster\n\t\t\tif (!masterId) continue\n\n\t\t\tconst master = this.get(masterId)\n\t\t\tif (!master) continue\n\t\t\tmaster.asDraft()\n\n\t\t\tconst replicasForMaster = this.hierarchy.masterIdToReplicaIds.get(masterId)\n\t\t\tif (!replicasForMaster) continue\n\n\t\t\tfor (const replicaId of replicasForMaster) {\n\t\t\t\tconst replica = this.get(replicaId)\n\t\t\t\tif (!replica) continue\n\t\t\t\tif (this.editedNodes.has(replicaId)) continue\n\t\t\t\tthis.editedNodes.set(replicaId, {})\n\t\t\t\treplica.asDraft()\n\t\t\t}\n\t\t}\n\n\t\tfor (const nodeId of this.editedNodes.keys()) {\n\t\t\tif (this.canvasTree.has(nodeId)) continue\n\n\t\t\tconst node = this.get(nodeId)\n\t\t\tassert(node, \"node not in data tree, id: \", nodeId)\n\t\t\tconst isReplicaChild = Boolean(node.originalid) && !node.replicaInfo\n\t\t\tif (!isReplicaChild) continue\n\n\t\t\tlet replica = this.get(node.parentid)\n\t\t\twhile (replica && !replica.replicaInfo) {\n\t\t\t\treplica = this.get(replica.parentid)\n\t\t\t}\n\t\t\tassert(replica, \"replica child must belong to a replica\")\n\n\t\t\tif (!this.editedNodes.has(replica.id)) {\n\t\t\t\tthis.editedNodes.set(replica.id, {})\n\t\t\t\treplica.asDraft()\n\t\t\t}\n\t\t}\n\t}\n\n\t// Set by createDataTreeProxy() \u2014 the CanvasTree-shaped proxy backed by this DataTree.\n\ttreeProxy: CanvasTree | null = null\n\n\t// We cache proxies using a map of WeakRefs. So callers holding on to nodes will keep the same.\n\tnodeProxyCache = new Map<string, WeakRef<CanvasNode>>()\n\n\tgetCanvasTreeProxy(): CanvasTree {\n\t\tif (!this.treeProxy) {\n\t\t\tthis.treeProxy = createDataTreeProxy(this)\n\t\t\tthis.treeProxy.setService(\"treeQueryContext\", this.treeQueryContext)\n\t\t}\n\t\treturn this.treeProxy\n\t}\n\n\tgetEditedNodeFor(id: string): EditedNode | undefined {\n\t\treturn this.editedNodes.get(id)\n\t}\n\n\tgetOrCreateEditedNodeFor(id: string): EditedNode {\n\t\tlet editedNode = this.editedNodes.get(id)\n\t\tif (!editedNode) {\n\t\t\teditedNode = {}\n\t\t\tthis.editedNodes.set(id, editedNode)\n\t\t}\n\t\treturn editedNode\n\t}\n\n\tgetEditedChildrenFor(id: string): CanvasNode[] | undefined {\n\t\treturn this.editedChildren.get(id)\n\t}\n\n\tisDataNode(node: CanvasNode | null | undefined): boolean {\n\t\tif (!node) return false\n\t\treturn Boolean((node as any)[isDataNodeSymbol])\n\t}\n\n\tgetScopeNodeFor(node: CanvasNode | null | undefined): LoadedScopeNode | null {\n\t\tif (!node) return null\n\n\t\twhile (node) {\n\t\t\tif (isScopeNode(node)) return node as unknown as LoadedScopeNode\n\t\t\tnode = this.get(node.parentid)\n\t\t}\n\t\treturn null\n\t}\n\n\tgetParent(id: string | null | undefined): (CanvasNode & WithChildren) | null {\n\t\tif (!id) return null\n\t\tconst parentId = this.hierarchy.getParentId(id)\n\t\tif (parentId === undefined || parentId === DELETED_VALUE) return null\n\t\treturn this.get(parentId)\n\t}\n\n\tget<T extends CanvasNode>(id: MaybeNodeID): T | null\n\tget(id: MaybeNodeID): CanvasNode | null {\n\t\tif (!id) return null\n\t\tif (this.removedNodes.has(id)) return null\n\t\tif (this.insertedNodes.has(id)) return this.insertedNodes.get(id) ?? null\n\n\t\t// Check if we have a cached proxy that hasn't been GC'd\n\t\tconst cachedRef = this.nodeProxyCache.get(id)\n\t\tif (cachedRef) {\n\t\t\tconst cachedProxy = cachedRef.deref()\n\t\t\tif (cachedProxy) return cachedProxy\n\t\t}\n\n\t\t// Create a DataTree node\n\t\tif (!this.hierarchy.inTree(id) && !this.canvasTree.has(id)) {\n\t\t\tconst result = this.hierarchy.getLatestReplicaChild(id)\n\t\t\tif (!result) return null\n\t\t\tconst [replicaOwnerId, , masterChildId] = result\n\t\t\treturn getOrCreateDataTreeReplicaNode(this, replicaOwnerId, masterChildId)\n\t\t}\n\n\t\treturn getOrCreateDataTreeNode(this, id)\n\t}\n\n\thas(id: MaybeNodeID) {\n\t\treturn !!this.get(id)\n\t}\n\n\tgetNodeWithTrait<T extends CanvasNode>(id: MaybeNodeID, trait: (node: CanvasNode) => node is T): T | null {\n\t\tconst node = this.get(id)\n\t\tif (!node) return null\n\t\tif (!trait(node)) return null\n\t\treturn node\n\t}\n\n\tgetNodesWithTrait<T extends ShallowScopeNode>(\n\t\tids: Iterable<MaybeNodeID>,\n\t\ttrait: (node: CanvasNode) => node is T & CanvasNode,\n\t): T[]\n\tgetNodesWithTrait<T extends BaseScopeNodes>(\n\t\tids: Iterable<MaybeNodeID>,\n\t\ttrait: (node: CanvasNode) => node is MapScopeNodesToShallow<T> & CanvasNode,\n\t): MapScopeNodesToShallow<T>[]\n\tgetNodesWithTrait<T extends CanvasNode>(\n\t\tids: Iterable<MaybeNodeID>,\n\t\ttrait: (node: CanvasNode) => node is T,\n\t): CanvasNode[] {\n\t\tconst result: CanvasNode[] = []\n\n\t\tfor (const id of ids) {\n\t\t\tconst node = this.get(id)\n\t\t\tif (!node || !trait(node)) continue\n\t\t\tresult.push(node)\n\t\t}\n\t\treturn result\n\t}\n\n\t// Alias for CanvasTree compatibility\n\tgetNode<T extends ShallowScopeNode>(id: MaybeNodeID): Readonly<T> | null\n\tgetNode<T extends BaseScopeNodes>(id: MaybeNodeID): Readonly<MapScopeNodesToShallow<T>> | null\n\tgetNode<T extends CanvasNode>(id: MaybeNodeID): (Readonly<T> & ReadonlyChildren) | null\n\tgetNode(id: MaybeNodeID): (Readonly<CanvasNode> & ReadonlyChildren) | null {\n\t\treturn this.get(id)\n\t}\n\n\tgetNodeAsDraft(node: ImmutableNode): MutableNode {\n\t\tif (this.isDataNode(node as CanvasNode)) {\n\t\t\tnode.cache.draft = node\n\t\t\t;(node as MutableNode).mutable = true\n\t\t\treturn node\n\t\t}\n\t\treturn this.canvasTree.getNodeAsDraft(node)\n\t}\n\n\tisGroundNode(node: CanvasNode): boolean {\n\t\tconst parent = this.get(node.parentid)\n\t\tif (!parent) return false\n\n\t\t// Check if node is a scope-type node (these are not ground nodes)\n\t\tif (isScopeNode(node)) return false\n\n\t\t// Ground nodes have scope nodes as parents\n\t\treturn isScopeNode(parent)\n\t}\n\n\tprivate insertChildrenRecursive(node: CanvasNode) {\n\t\tif (node.children) {\n\t\t\tfor (const child of node.children) {\n\t\t\t\tthis.removedNodes.delete(child.id)\n\t\t\t\tthis.insertedNodes.set(child.id, child)\n\n\t\t\t\t// We suspect this is the cause of NodeChanges being created with\n\t\t\t\t// an undefined parentid: added: \"FoobarNode\", to: { ..., parentid: undefined }.\n\t\t\t\t// This is some temporary logging to help debug the issue.\n\t\t\t\tif (!child.parentid) {\n\t\t\t\t\tlog.reportError(new Error(\"insertChildrenRecursive: child has no parentid\"), {\n\t\t\t\t\t\tchildId: child.id,\n\t\t\t\t\t\tchildClass: child.__class,\n\t\t\t\t\t\tparentidType: typeof child.parentid,\n\t\t\t\t\t\tparentidValue: String(child.parentid),\n\t\t\t\t\t\talreadyInTree: this.canvasTree.has(child.id),\n\t\t\t\t\t\toriginalid: child.originalid ?? null,\n\t\t\t\t\t\tparentNodeId: node.id,\n\t\t\t\t\t\tparentClass: node.__class,\n\t\t\t\t\t\tparentParentid: node.parentid ?? null,\n\t\t\t\t\t\tchildrenCount: node.children?.length ?? 0,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tthis.canvasTree.recordInsert({ node: child, toParent: node.id, toPosition: -1 })\n\n\t\t\t\tthis.insertChildrenRecursive(child)\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Is the node in the CanvasTree? If it's a scope, is it loaded? */\n\tprivate isLoadedInCanvasTree(nodeId: CanvasNode[\"id\"]) {\n\t\tif (!this.canvasTree.has(nodeId)) return false\n\t\tconst canvasNode = this.canvasTree.get(nodeId)\n\t\treturn !isScopeNode(canvasNode) || canvasNode.isLoaded()\n\t}\n\n\tinsertNode<T extends CanvasNode>(\n\t\tnode: T,\n\t\tparentid?: string | null,\n\t\tposition?: number,\n\t\tsourceNodeId?: NodeID /* If provided, the node will be positioned right after the source node (in each replicas) */,\n\t): T {\n\t\tparentid = parentid ?? this.canvasTree.root.id\n\t\tif (this.isLoadedInCanvasTree(parentid)) {\n\t\t\treturn this.canvasTree.insertNode(node, parentid, position, sourceNodeId)\n\t\t}\n\n\t\tassert(!this.has(node.id), \"Node already exists in tree\")\n\t\tconst parent = this.get(parentid)\n\t\tassert(parent, \"Parent:\", parentid, \"not found in tree\")\n\n\t\tmaybePatchItemsOrder(this.getCanvasTreeProxy(), node, parentid, position, sourceNodeId)\n\n\t\t/**\n\t\t * Adding a preset breakpoint should increment\n\t\t * moduleSourceRevisionHints { @see WithModuleSourceRevision } on\n\t\t * the primary preset.\n\t\t */\n\t\tif (isStylePresetBreakpoint(node)) markPrimaryTextStylePresetAsDraft(node, this.getCanvasTreeProxy())\n\n\t\tnode.parentid = parentid\n\n\t\tconst children = this.getOrMaterializeEditedChildren(parentid)\n\t\tposition = position === undefined ? children.length : position\n\t\tif (position < 0) {\n\t\t\tposition += children.length + 1\n\t\t}\n\t\tchildren.splice(position, 0, node)\n\n\t\tthis.canvasTree.recordInsert({\n\t\t\tnode: node,\n\t\t\ttoParent: node.parentid,\n\t\t\ttoPosition: position,\n\t\t})\n\n\t\tthis.insertChildrenRecursive(node)\n\n\t\tthis.removedNodes.delete(node.id)\n\t\tthis.insertedNodes.set(node.id, node)\n\n\t\treturn node\n\t}\n\n\tprivate removeChildrenRecursive(node: CanvasNode) {\n\t\tif (node.children && !isReplicaOrReplicaChild(node)) {\n\t\t\tfor (const child of node.children) {\n\t\t\t\tthis.removeChildrenRecursive(child)\n\n\t\t\t\tthis.removedNodes.add(child.id)\n\t\t\t\tthis.editedNodes.delete(child.id)\n\t\t\t\tthis.editedChildren.delete(child.id)\n\t\t\t\tthis.canvasTree.recordRemove({ node: child, fromParent: node.id, fromPosition: 0 })\n\t\t\t}\n\t\t}\n\t}\n\n\tremove(id: NodeID): this {\n\t\tconst node = this.get(id)\n\t\tif (!node) return this\n\t\tthis.removeNode(node)\n\t\treturn this\n\t}\n\n\tremoveNode(node: CanvasNode): void {\n\t\tconst canvasNode = this.canvasTree.get(node.id)\n\t\tif (canvasNode) {\n\t\t\t// If we are deleting a scope node that is not loaded, we still\n\t\t\t// need to mark descendants of scope node as deleted\n\t\t\tif (this.isDataNode(node) && isScopeNode(canvasNode) && !canvasNode.isLoaded()) {\n\t\t\t\tthis.removeChildrenRecursive(node)\n\t\t\t}\n\n\t\t\t// We need to delete the node from canvas tree even if the node\n\t\t\t// is a data tree node. This can usually happen when deleting scope\n\t\t\t// nodes.\n\t\t\t// @important In order to retain the correct hieraerchy ordering\n\t\t\t// for removing nodes, the scope **must be** removed after children\n\t\t\t// are removed\n\t\t\tthis.canvasTree.removeNode(canvasNode)\n\t\t\treturn\n\t\t}\n\n\t\tassert(node.parentid, \"Node must have a parent id\")\n\t\tassert(!node.originalid || node.replicaInfo, \"Cannot delete nodes of replica's\")\n\n\t\tmaybePatchItemsOrder(this.getCanvasTreeProxy(), node)\n\n\t\t/**\n\t\t * Removing a preset breakpoint should increment\n\t\t * moduleSourceRevisionHints { @see WithModuleSourceRevision } on\n\t\t * the primary preset.\n\t\t */\n\t\tif (isStylePresetBreakpoint(node)) {\n\t\t\tmarkPrimaryTextStylePresetAsDraft(node, this.getCanvasTreeProxy())\n\t\t}\n\n\t\tconst children = this.getOrMaterializeEditedChildren(node.parentid)\n\t\tconst index = children.findIndex(c => c.id === node.id)\n\t\tassert(index !== -1, \"Node:\", node.id, \"not found in parent:\", node.parentid)\n\t\tconst removedNode = children.splice(index, 1)[0] as CanvasNode\n\n\t\t// Don't remove replica children,\n\t\t// any overrides are cleared in the replicas' preCommit.\n\t\tif (!node.replicaInfo) {\n\t\t\tthis.removeChildrenRecursive(removedNode)\n\t\t}\n\n\t\tthis.removedNodes.add(node.id)\n\t\tthis.insertedNodes.delete(node.id)\n\t\tthis.editedNodes.delete(node.id)\n\t\tthis.editedChildren.delete(node.id)\n\t\t// TODO: abstract hierarchy changes to better share between data-tree and node-tree?\n\t\tthis.canvasTree.recordRemove({ node, fromParent: node.parentid, fromPosition: index })\n\t}\n\n\t/** Returns true if the target node is an ancestor of the source node. */\n\tprivate isAncestorOf(source: NodeID, target: NodeID): boolean {\n\t\tlet checkNode: ImmutableNode = this.get(target)!\n\t\tassert(checkNode, \"Node to check must exist\")\n\t\twhile (checkNode.id !== this.root.id) {\n\t\t\tif (checkNode.id === source) return true\n\t\t\tcheckNode = this.get(checkNode.parentid)!\n\t\t\tassert(checkNode, \"Ancestor node must exist\")\n\t\t}\n\t\tif (checkNode.id === source) return true\n\t\treturn false\n\t}\n\n\tmove(id: NodeID, parentid: MaybeNodeID, position?: number): this {\n\t\tthis.moveNode(this.get(id)!, parentid || this.root.id, position)\n\t\treturn this\n\t}\n\n\tmoveNode<T extends CanvasNode>(node: T, parentid: string, position = -1, sourceNodeId?: NodeID): T {\n\t\tconst parentLoadedInCanvasTree = this.isLoadedInCanvasTree(parentid)\n\t\tif (\n\t\t\t// We can move a shallowly loaded scope to a loaded node,\n\t\t\t// so we only need to check that if the canvas tree has the node.\n\t\t\tthis.canvasTree.has(node.id) &&\n\t\t\tparentLoadedInCanvasTree\n\t\t) {\n\t\t\treturn this.canvasTree.moveNode(node, parentid, position, sourceNodeId)\n\t\t}\n\n\t\tassert(\n\t\t\t!this.isLoadedInCanvasTree(node.id) && !parentLoadedInCanvasTree,\n\t\t\t\"cannot move a node from between loaded and unloaded scopes\",\n\t\t)\n\n\t\tmaybePatchItemsOrder(this.getCanvasTreeProxy(), node, parentid, position, sourceNodeId)\n\n\t\tassert(!node.originalid || node.replicaInfo, \"Cannot move nodes of replica's\")\n\n\t\tif (node.parentid === parentid) {\n\t\t\treturn this.moveNodeIndex(node, position) as T\n\t\t}\n\n\t\tassert(this.has(node.id), \"Node does not exist in the data tree\")\n\t\tassert(this.has(parentid), \"Parent does not exist in the data tree\")\n\t\tassert(!this.isAncestorOf(node.id, parentid), \"Node must not be an ancestor of its new parent\")\n\n\t\t// 1. Remove from previous parent\n\t\tconst fromParent = node.parentid\n\t\tassert(fromParent, \"Must be moving from a node\")\n\t\tconst currSiblings = this.getOrMaterializeEditedChildren(fromParent)\n\t\tconst fromPosition = currSiblings.findIndex(c => c.id === node.id)\n\t\tassert(fromPosition >= 0, \"Node must be known as child\")\n\t\tcurrSiblings.splice(fromPosition, 1)\n\n\t\t// 2. Add to new parent\n\t\tconst nextSiblings = this.getOrMaterializeEditedChildren(parentid)\n\t\tif (position < 0) {\n\t\t\tposition += nextSiblings.length + 1\n\t\t}\n\t\tnextSiblings.splice(position, 0, node)\n\n\t\t// This adds node to editedNodes. As node has not been moved in\n\t\t// the Store yet, this will also mark fromParents's scope as draft.\n\t\tnode.set({ parentid } as Partial<T>)\n\t\t// This will also force toParent's scope to be marked as draft.\n\t\t// Marking scopes as draft will trigger code-generation where needed.\n\t\tthis.getNodeAsDraft(this.get(parentid)!)\n\t\tif (!this.editedNodes.has(parentid)) {\n\t\t\tthis.editedNodes.set(parentid, {})\n\t\t}\n\n\t\tthis.canvasTree.recordMove({\n\t\t\tnode: node,\n\t\t\tfromParent,\n\t\t\tfromPosition,\n\t\t\ttoPosition: position,\n\t\t\ttoParent: parentid,\n\t\t})\n\n\t\treturn node\n\t}\n\n\tmoveNodeIndex(node: ImmutableNode, position: number = -1): MutableNode {\n\t\tassert(this.has(node.id), \"Node does not exist in the data tree\")\n\t\tassert(node.parentid, \"Node must have a parent id\")\n\n\t\tconst children = this.getOrMaterializeEditedChildren(node.parentid)\n\t\tif (position < 0) {\n\t\t\tposition += children.length + 1\n\t\t}\n\n\t\tconst fromPosition = children.findIndex(c => c.id === node.id)\n\t\tassert(fromPosition >= 0, \"Node to move not found in parent\")\n\t\tif (fromPosition === position) return node\n\n\t\tchildren.splice(fromPosition, 1)\n\t\tchildren.splice(position, 0, node as CanvasNode)\n\n\t\t// This will force node's scope to be marked as draft\n\t\t// which is required to trigger the moduleSourceRevisionHint bump\n\t\tthis.getNodeAsDraft(node)\n\t\tif (!this.editedNodes.has(node.id)) {\n\t\t\tthis.editedNodes.set(node.id, {})\n\t\t}\n\n\t\tthis.canvasTree.recordMove({\n\t\t\tnode: node,\n\t\t\tfromParent: node.parentid,\n\t\t\tfromPosition,\n\t\t\ttoPosition: position,\n\t\t\ttoParent: node.parentid,\n\t\t})\n\n\t\treturn node\n\t}\n\n\t/** Materializes the edited children array for a parent, copying from the hierarchy if needed. */\n\tprivate getOrMaterializeEditedChildren(parentid: string): CanvasNode[] {\n\t\tlet editedChildren = this.editedChildren.get(parentid)\n\t\tif (!editedChildren) {\n\t\t\tconst childrenIds = this.store.getChildrenIds(parentid)\n\t\t\teditedChildren = childrenIds\n\t\t\t\t.map(id => {\n\t\t\t\t\tif (this.hierarchy.inTree(id)) {\n\t\t\t\t\t\treturn getOrCreateDataTreeNode(this, id)\n\t\t\t\t\t}\n\t\t\t\t\treturn undefined\n\t\t\t\t})\n\t\t\t\t.filter((n): n is CanvasNode => n !== undefined)\n\t\t\tthis.editedChildren.set(parentid, editedChildren)\n\t\t}\n\t\treturn editedChildren\n\t}\n\n\t/** Gets the value for a property from CRDT store, falling back to the default node. */\n\tgetValueForWithDefault(nodeData: NodeData, key: string): unknown {\n\t\tconst id = nodeData.id\n\t\tif (key === \"parentid\") return this.hierarchy.getParentId(id)\n\t\tconst value = this.store.getRawObjectKey(id, key)\n\n\t\tif (value === DOES_NOT_EXIST || value === DELETED_VALUE) {\n\t\t\t// Fall back to prototype default\n\t\t\tconst __class = nodeData?.__class\n\t\t\tif (!__class) return undefined\n\n\t\t\tconst prototype = getNodeDefaultsByClassName(__class)\n\t\t\tif (!prototype) return undefined\n\n\t\t\treturn prototype[key as keyof typeof prototype]\n\t\t}\n\n\t\treturn value\n\t}\n\n\t*iterateAll(): IterableIterator<NodeData> {\n\t\tfor (const set of this.hierarchy.classToIds.values()) {\n\t\t\tfor (const id of set) {\n\t\t\t\tif (!this.hierarchy.inTree(id)) continue\n\t\t\t\tconst nodeData = this.hierarchy.getNodeData(id)\n\t\t\t\tif (!nodeData) continue\n\t\t\t\tyield nodeData\n\t\t\t}\n\t\t}\n\t}\n\n\titerateByClass(className: string): IterableIterator<NodeData> {\n\t\treturn this.iterateByClasses([className])\n\t}\n\n\t*iterateByClasses(classes: string[]): IterableIterator<NodeData> {\n\t\tfor (const className of classes) {\n\t\t\tconst ids = this.hierarchy.classToIds.get(className)\n\t\t\tif (!ids) continue\n\t\t\tfor (const id of ids) {\n\t\t\t\tif (!this.hierarchy.inTree(id)) continue\n\t\t\t\tconst nodeData = this.hierarchy.getNodeData(id)\n\t\t\t\tif (!nodeData) continue\n\t\t\t\tyield nodeData\n\t\t\t}\n\t\t}\n\t}\n\n\t*iterateWithDataIdentifier(): IterableIterator<NodeData> {\n\t\tfor (const id of this.hierarchy.withDataIdentifierIds) {\n\t\t\tif (!this.hierarchy.inTree(id)) continue\n\t\t\tconst nodeData = this.hierarchy.getNodeData(id)\n\t\t\tif (!nodeData) continue\n\t\t\tyield nodeData\n\t\t}\n\t}\n\n\t*iterateByDataIdentifier(dataIdentifier: string): IterableIterator<NodeData> {\n\t\tconst ids = this.hierarchy.dataIdentifierToIds.get(dataIdentifier)\n\t\tif (!ids) return\n\n\t\tfor (const id of ids) {\n\t\t\tif (!this.hierarchy.inTree(id)) continue\n\t\t\tconst nodeData = this.hierarchy.getNodeData(id)\n\t\t\tif (!nodeData) continue\n\t\t\tyield nodeData\n\t\t}\n\t}\n\n\tloadScopes<T extends (BaseShallowType | null | undefined)[], RT extends MapArrayToLoadedOptionalScopeNodes<T>>(\n\t\tscopes: [...T],\n\t): Promise<RT>\n\tloadScopes<T extends (BaseShallowType | null | undefined)[], RT extends MapArrayToLoadedOptionalScopeNodes<T>>(\n\t\tscopes: [...T],\n\t\tcallback: (scopes: RT) => void,\n\t): void\n\tloadScopes<T extends (BaseShallowType | null | undefined)[], RT extends MapArrayToLoadedOptionalScopeNodes<T>>(\n\t\tscopes: [...T],\n\t\tcallback?: (scopes: RT) => void,\n\t) {\n\t\tconst resolved = scopes.map(scope => (scope ? this.get(scope.id) : scope)) as unknown as RT\n\t\tif (callback) {\n\t\t\tcallback(resolved)\n\t\t\treturn\n\t\t}\n\t\treturn Promise.resolve(resolved)\n\t}\n\n\tbeginAllowPartialScopeAccess() {}\n\n\tendAllowPartialScopeAccess() {}\n\n\tgetPersistedNodeCache(id: string): unknown | undefined {\n\t\treturn this.persistedCaches?.get(id)\n\t}\n\n\tsetPersistedNodeCache<T>(id: string, cache: T): T {\n\t\tthis.persistedCaches?.set(id, cache)\n\t\treturn cache\n\t}\n\n\t/** Normally vekter will clear data only node caches after every frame. This wrapper will ensure\n\t * those caches persist for as long as the promise of the callback hasn't resolved yet. */\n\twithPersistedCaches<T>(callback: () => Promise<T>): Promise<T> {\n\t\tif (this.persistedCaches) {\n\t\t\treturn this.persistedCaches.with(callback)\n\t\t}\n\t\treturn callback()\n\t}\n\n\t/** Open-ended variant of `withPersistedCaches`. Keeps caches alive until the returned function\n\t * is called. Useful when the lifetime is tied to a long-lived view rather than a single\n\t * async operation. */\n\tpersistCaches(): () => void {\n\t\treturn this.persistedCaches?.acquire() ?? noop\n\t}\n}\n", "/**\n * Persists per-node caches across DataTree resets while at least one\n * scope is active. Owned by the CrdtTreeCommitter and shared with every\n * DataTree it constructs, so caches keyed by node id survive the\n * per-frame recreation of the DataTree.\n *\n * Outside of an active scope, `set()` is a no-op so callers can write\n * through unconditionally without leaking memory.\n */\nexport class PersistedNodeCaches {\n\tprivate activeScopes = 0\n\tprivate caches: Map<string, unknown> | undefined\n\n\tget(id: string): unknown | undefined {\n\t\treturn this.caches?.get(id)\n\t}\n\n\tset<T>(id: string, cache: T): void {\n\t\tif (!this.caches) {\n\t\t\tif (this.activeScopes <= 0) return\n\t\t\tthis.caches = new Map()\n\t\t}\n\t\tthis.caches.set(id, cache)\n\t}\n\n\t/**\n\t * Begins a scope that keeps caches alive until the returned function\n\t * is invoked. Calling the release function more than once is a no-op.\n\t */\n\tacquire(): () => void {\n\t\tthis.activeScopes += 1\n\t\tlet released = false\n\t\treturn () => {\n\t\t\tif (released) return\n\t\t\treleased = true\n\t\t\tthis.activeScopes -= 1\n\t\t\tif (this.activeScopes <= 0) {\n\t\t\t\tthis.activeScopes = 0\n\t\t\t\tthis.caches = undefined\n\t\t\t}\n\t\t}\n\t}\n\n\tasync with<T>(callback: () => Promise<T>): Promise<T> {\n\t\tconst release = this.acquire()\n\t\ttry {\n\t\t\treturn await callback()\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n}\n", "import { BRANCH_BASE_ID_KEY, MAIN_BRANCH_ID, type Store } from \"@framerjs/crdtree2\"\nimport { assert } from \"@framerjs/shared\"\n\nexport class CrdtBranchStoreRegistry {\n\tprivate _activeBranchId: string\n\tprivate stores = new Map<string, Store>()\n\n\t/** Called when a branch store is lazily created for the first time. */\n\tonStoreCreated?: (store: Store) => void\n\n\tconstructor(private readonly mainStore: Store) {\n\t\tassert(mainStore.branchId === MAIN_BRANCH_ID, \"branch store registry must be seeded with the main store\")\n\t\tthis._activeBranchId = MAIN_BRANCH_ID\n\t\tthis.stores.set(MAIN_BRANCH_ID, mainStore)\n\t}\n\n\treset(): void {\n\t\tthis._activeBranchId = MAIN_BRANCH_ID\n\t\tthis.stores = new Map([[MAIN_BRANCH_ID, this.mainStore]])\n\t}\n\n\tget activeBranchId(): string {\n\t\treturn this._activeBranchId\n\t}\n\n\tget activeStore(): Store {\n\t\treturn this.getStore(this.activeBranchId)\n\t}\n\n\tgetStore(branchId: string): Store {\n\t\treturn this.getOrCreateStore(branchId, new Set())\n\t}\n\n\tgetBranchPath(branchId = this.activeBranchId): string[] {\n\t\treturn this.resolveBranchPath(branchId, new Set())\n\t}\n\n\t/**\n\t * Reconciles a branch hierarchy against its current ancestors.\n\t *\n\t * Ancestor changes can make an untouched branch overlay stale, for example by combining\n\t * branch parentid overrides with base moves into a cycle. Resolve the path base-to-leaf so\n\t * every level is reconciled against an already-stable base. Main has no base, so it cannot\n\t * become stale this way and is skipped by the base guard.\n\t */\n\tresolveBranchHierarchy(branchId: string): void {\n\t\tfor (const pathBranchId of this.getBranchPath(branchId)) {\n\t\t\tconst pathStore = this.getStore(pathBranchId)\n\t\t\tif (pathStore.base !== undefined) {\n\t\t\t\tpathStore.getHierarchy().resolveCycles(0)\n\t\t\t}\n\t\t}\n\t}\n\n\tswitchActiveBranch(branchId: string): Store {\n\t\tconst store = this.getStore(branchId)\n\t\tthis._activeBranchId = branchId\n\t\tthis.resolveBranchHierarchy(branchId)\n\t\treturn store\n\t}\n\n\tprivate resolveBranchPath(branchId: string, resolving: Set<string>): string[] {\n\t\tif (branchId === MAIN_BRANCH_ID) return [MAIN_BRANCH_ID]\n\n\t\tassert(!resolving.has(branchId), \"BranchNode baseId cycle detected\", branchId)\n\n\t\tresolving.add(branchId)\n\t\ttry {\n\t\t\tconst baseId = this.getBaseId(branchId)\n\t\t\treturn [...this.resolveBranchPath(baseId, resolving), branchId]\n\t\t} finally {\n\t\t\tresolving.delete(branchId)\n\t\t}\n\t}\n\n\tprivate getOrCreateStore(branchId: string, resolving: Set<string>): Store {\n\t\tconst existing = this.stores.get(branchId)\n\t\tif (existing) return existing\n\n\t\tassert(branchId !== MAIN_BRANCH_ID, \"main store is missing from branch store registry\")\n\t\tassert(!resolving.has(branchId), \"BranchNode baseId cycle detected\", branchId)\n\n\t\tresolving.add(branchId)\n\t\ttry {\n\t\t\tconst baseId = this.getBaseId(branchId)\n\t\t\tconst baseStore = this.getOrCreateStore(baseId, resolving)\n\t\t\tconst store = baseStore.branch(branchId)\n\t\t\tthis.stores.set(branchId, store)\n\t\t\tthis.onStoreCreated?.(store)\n\t\t\treturn store\n\t\t} finally {\n\t\t\tresolving.delete(branchId)\n\t\t}\n\t}\n\n\tprivate getBaseId(branchId: string): string {\n\t\tconst baseId = this.mainStore.getObjectKey<string>(branchId, BRANCH_BASE_ID_KEY)\n\t\tassert(typeof baseId === \"string\" && baseId.length > 0, \"Missing metadata for branch\", branchId)\n\t\treturn baseId\n\t}\n}\n", "import type { CrdtTreePatchMap } from \"@framerjs/crdtree2\"\nimport type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport { type NodeChange, type ReversibleNodeChange, nodeChange } from \"document/models/CanvasTree/TreeDiff.ts\"\nimport { computeOverrideChanges } from \"document/models/CanvasTree/TreeDiffOverrides.ts\"\n\nexport function createChangesFromPatches(\n\tfromTree: CanvasTree,\n\ttoTree: CanvasTree,\n\tpatches: CrdtTreePatchMap,\n): NodeChange[] {\n\tconst changes: ReversibleNodeChange[] = []\n\tfor (const id of patches.keys()) {\n\t\tconst fromNode = fromTree.getNodeAtStart(id)\n\t\tconst toNode = toTree.getNodeAtStart(id)\n\t\tif (fromNode === toNode) continue\n\n\t\tconst change = nodeChange(fromNode, toNode)\n\n\t\tif (change) changes.push(change)\n\t\tcomputeOverrideChanges(changes, fromNode, toNode)\n\t}\n\n\treturn changes\n}\n", "import {\n\tBRANCH_BASE_ID_KEY,\n\ttype BranchedSerializableRow,\n\ttype CrdtTreePatchMap,\n\tDELETED_VALUE,\n\ttype Hierarchy,\n\tMAIN_BRANCH_ID,\n\tStore,\n\tcreateVekterCrdtStore,\n} from \"@framerjs/crdtree2\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, assertNever, getLogger } from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { CrdtDebugRecord } from \"document/crdt/CRDTDebugRecord.ts\"\nimport { getCrdtSession } from \"document/crdt/CrdtSession.ts\"\nimport type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport type { Changeset } from \"document/models/CanvasTree/Changeset.ts\"\nimport { MAX_VERIFY_TREE_SIZE } from \"document/models/CanvasTree/NodeTree.ts\"\nimport {\n\ttype NodeChange,\n\ttype PropsDiff,\n\ttype ReversibleNodeChange,\n\tcrdtApplyChanges,\n\tcrdtApplyReverseChanges,\n\tcreateTreeChanges,\n\tnodeChange,\n} from \"document/models/CanvasTree/TreeDiff.ts\"\nimport { computeOverrideChanges, isOverrideId, parseOverrideId } from \"document/models/CanvasTree/TreeDiffOverrides.ts\"\nimport {\n\tNodeChangesBuffer,\n\ttype CommitLocalTreeResult,\n\ttype TreeUpdater,\n} from \"document/models/CanvasTree/TreeUpdater.ts\"\nimport { expandScopeReplicas } from \"document/models/CanvasTree/expandScopeReplicas.ts\"\nimport {\n\tBRANCH_CONTRIBUTOR_KEY,\n\tBRANCH_DELETED_AT_KEY,\n\tBRANCH_LAST_EDITED_KEY,\n\ttype BranchContributor,\n\tBranchNode,\n} from \"document/models/CanvasTree/nodes/branches/BranchNode.ts\"\nimport { BRANCHES_NODE_ID, BranchesNode } from \"document/models/CanvasTree/nodes/branches/BranchesNode.ts\"\nimport { generateBranchName } from \"document/models/CanvasTree/nodes/branches/branchName.ts\"\nimport { getNodeDefaultsByClassName } from \"document/models/CanvasTree/nodes/classList.ts\"\nimport { withChildren } from \"document/models/CanvasTree/traits/WithChildren.ts\"\nimport { isReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport { environment } from \"environment/index.ts\"\nimport { ClassDiscriminator } from \"utils/withClassDiscriminator.ts\"\nimport type { ChangeTrackingCursor, TimelineFlags } from \"../../models/CanvasTree/TreeTimeline.ts\"\nimport type { CanvasNode } from \"../../models/CanvasTree/nodes/CanvasNode.ts\"\nimport { randomBranchID, type NodeID } from \"../../models/CanvasTree/nodes/NodeID.ts\"\nimport { DataTree } from \"../data-tree/DataTree.ts\"\nimport { PersistedNodeCaches } from \"../data-tree/PersistedNodeCaches.ts\"\nimport type { TreeQueryContext } from \"../data-tree/TreeQueryBuilder.ts\"\nimport { CrdtBranchStoreRegistry } from \"./CrdtBranchStoreRegistry.ts\"\nimport { applyPatchesToTheTree } from \"./crdtTreeUpdater.ts\"\nimport { createChangesFromPatches } from \"./nodeChangeCompat.ts\"\n\nconst log = getLogger(\"tree:crdt-committer\")\n\nconst LOCAL_CHANGES_VALID_FOR_MS = 60_000\nconst REMOTE_CONNECTION_VALID_FOR_MS = 60_000\nconst IGNORED_AUTO_BRANCH_CHANGE_KEYS = new Set([\"moduleSourceRevisionHint\"])\n\nclass RemoteTreeEntry {\n\tconstructor(\n\t\tpublic tree: CanvasTree,\n\t\tpublic remoteVersion: number,\n\t\tpublic containsLocalEdits: boolean,\n\t\tpublic hasHierarchyChanges: boolean,\n\t) {}\n}\n\ninterface HistoricTreeRecordOptions {\n\tcontainsLocalEdits: boolean\n\thasHierarchyChanges: boolean\n}\n\n/** Per-branch outgoing-sync bookkeeping. */\ninterface BranchDrainState {\n\tlastSeqTaken: number\n\tlastMinIndex: number\n\tdirty: boolean\n}\n\nexport function isCrdtTreeCommitter(treeUpdater: unknown): treeUpdater is CrdtTreeCommitter {\n\treturn treeUpdater instanceof CrdtTreeCommitter\n}\n\n/**\n * CRDT tree committer that implements the `TreeUpdater` for crdt.\n *\n * It keeps a history of trees as the server has confirmed them.\n *\n * And the current tree, which has the local edits merged in, if any. And these local edits are\n * either in flight, or have not been created as a message yet.\n */\nexport class CrdtTreeCommitter implements TreeUpdater {\n\ttree: CanvasTree\n\tremoteTrees: RemoteTreeEntry[] = []\n\n\t/**\n\t * Per-branch outgoing-sync state. Includes the active branch (always\n\t * present, never evicted) plus any non-active branches that still\n\t * have unsent rows. Iteration order is Map insertion order, which\n\t * means \"main\" (constructed first) drains first; subsequent branches\n\t * drain in the order they were first activated.\n\t *\n\t * Invariants:\n\t * - Active branch ID is always a key here.\n\t * - Branch swaps go through {@link switchActiveBranch}; non-active\n\t *   entries are evicted by {@link takePendingRows} once they're\n\t *   clean (active stays so {@link store} keeps a live handle).\n\t */\n\tprivate branchStates = new Map<string, BranchDrainState>()\n\n\treadonly branches: CrdtBranchStoreRegistry\n\n\tget store(): Store {\n\t\treturn this.branches.activeStore\n\t}\n\n\tprivate activeBranchDrainState(): BranchDrainState {\n\t\tconst activeBranchId = this.branches.activeBranchId\n\t\tconst drainState = this.branchStates.get(activeBranchId)\n\t\tassert(drainState, \"drain state for active branch is missing\", activeBranchId)\n\t\treturn drainState\n\t}\n\n\tprivate oldestLocalCommitTime = 0\n\n\t/** Called with the branch ID and `store.seq` after each local batch is created. */\n\tprivate afterLocalWrite?: (branchId: string, seq: number) => void\n\n\trecorder?: (record: CrdtDebugRecord) => void\n\n\t// Used by external systems.\n\tremoteTreeVersion = 0\n\tlegacyMode = false\n\n\t// Partial-loading support (kept for parity with TreeTimeline).\n\tisPartialLoading = false\n\n\t// Online validation support.\n\tvalidationEnabled = process.env.NODE_ENV !== \"test\"\n\tprivate onlineStartTime = 0\n\tsetOnline(online: boolean) {\n\t\tif ((this.onlineStartTime !== 0) !== online) {\n\t\t\tthis.onlineStartTime = online ? performance.now() : 0\n\t\t}\n\t}\n\n\tprivate get online() {\n\t\treturn this.onlineStartTime !== 0\n\t}\n\n\t// Undo support.\n\tpublic latestReversibleNodeChanges: ReversibleNodeChange[] | null = null\n\n\t// Commit flags support.\n\tflagsForNextCommit: TimelineFlags | undefined\n\tprivate extraChangesForNextCommit: NodeChange[] | undefined\n\n\t// All edit reasons for unsent commits.\n\trecentEditReasons: string[] = []\n\n\t// Changes reader support.\n\tprivate nodeChangesBuffers = new Set<NodeChangesBuffer>()\n\n\tconstructor(\n\t\ttree: CanvasTree,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\toptions?: { isLoading?: boolean; afterLocalWrite?: (branchId: string, seq: number) => void },\n\t) {\n\t\t// user is unknown at this point; outgoing rows get overwritten with actual userId later.\n\t\tconst placeholder = createVekterCrdtStore(\"\", getCrdtSession().client)\n\t\tthis.branches = new CrdtBranchStoreRegistry(placeholder)\n\t\tthis.branchStates.set(placeholder.branchId, {\n\t\t\tlastSeqTaken: 0,\n\t\t\tlastMinIndex: 0,\n\t\t\tdirty: false,\n\t\t})\n\t\tthis.afterLocalWrite = options?.afterLocalWrite\n\t\tthis.tree = tree\n\t\tthis.reset(tree, options)\n\t}\n\n\tresetTime = 0\n\treset(tree: CanvasTree, options?: { initialChanges?: NodeChange[]; isLoading?: boolean }): void {\n\t\tthis.resetTime = performance.now()\n\t\tlog.debug(\"reset with tree:\", tree.root.id, \"size:\", tree.size())\n\n\t\tthis.replaceTree(tree)\n\n\t\t// Session-level state that survives a branch swap but must be cleared on a full reset\n\t\t// (initial load, history swap, error recovery, etc.).\n\t\tthis.recentEditReasons = []\n\t\tthis.flagsForNextCommit = undefined\n\t\tthis.extraChangesForNextCommit = undefined\n\t\tthis.remoteTreeVersion = 0\n\t\t// Drop all non-active drain states and reset the active one so `activeBranchId` keeps pointing at\n\t\t// a live drain state (and `store` keeps returning the same live Store handle).\n\t\tconst active = this.activeBranchDrainState()\n\t\tactive.dirty = false\n\t\tthis.branchStates = new Map([[this.branches.activeBranchId, active]])\n\t\tthis.oldestLocalCommitTime = 0\n\n\t\tthis.isPartialLoading = Boolean(options?.isLoading) || Boolean(tree.getService(\"loader\"))\n\t}\n\n\t/**\n\t * Swap the active branch. Just moves the active branch ID\n\t * pointer; no rows are dropped because the outgoing branch's drain state\n\t * (with its watermarks + dirty bit) stays in {@link branchStates}\n\t * until {@link takePendingRows} drains it clean.\n\t *\n\t * For an existing branch activated for the first time, seeds a drain state at\n\t * `next.seq - 1` / `next.length - 1` so we don't re-emit historical rows\n\t * on its first drain. Re-activating a previously-known branch is a no-op\n\t * on watermarks \u2014 they were preserved on the previous switch-away.\n\t *\n\t * Note: Does NOT swap the visible canvas tree\n\t */\n\tswitchActiveBranch(branchId: string): Store {\n\t\tconst next = this.branches.switchActiveBranch(branchId)\n\t\tthis.getOrCreateBranchState(branchId, next)\n\t\treturn next\n\t}\n\n\treplaceTree(tree: CanvasTree): void {\n\t\tthis.tree = tree\n\t\tthis.latestReversibleNodeChanges = null\n\t\tthis.remoteTrees = []\n\t\tthis.resetDataTree()\n\t\tthis.clearNodeChangesReader()\n\t\tthis.invalidateAllCursors()\n\t\tthis.isPartialLoading = Boolean(tree.getService(\"loader\"))\n\t}\n\n\tcreateBranch(branchId: string, userId?: string, baseBranchId?: string): void {\n\t\tassert(branchId !== MAIN_BRANCH_ID, \"Can't create the main branch\")\n\n\t\tconst mainStore = this.branches.getStore(MAIN_BRANCH_ID)\n\t\tif (mainStore.getObjectKey(branchId, \"baseId\")) {\n\t\t\tthrow new Error(`Branch ${branchId} already exists`)\n\t\t}\n\n\t\tif (baseBranchId !== undefined && baseBranchId !== MAIN_BRANCH_ID) {\n\t\t\tif (!mainStore.getObjectKey(baseBranchId, \"baseId\")) {\n\t\t\t\tthrow new Error(`Base branch ${baseBranchId} does not exist`)\n\t\t\t}\n\t\t\tif (mainStore.getObjectKey(baseBranchId, BRANCH_DELETED_AT_KEY)) {\n\t\t\t\tthrow new Error(`Base branch ${baseBranchId} is deleted`)\n\t\t\t}\n\t\t}\n\n\t\tconst baseId = baseBranchId ?? this.branches.activeBranchId\n\t\tconst branchName = generateBranchName(this.collectExistingBranchNames())\n\t\tconst branchNode = new BranchNode({\n\t\t\tid: branchId,\n\t\t\tbaseId,\n\t\t\tname: branchName,\n\t\t\tcreatedBy: userId,\n\t\t\tcontributors: userId ? [{ id: userId }] : [],\n\t\t})\n\n\t\tconst drainState = this.getOrCreateBranchState(MAIN_BRANCH_ID, mainStore)\n\t\tconst lastIndex = mainStore.length\n\n\t\tmainStore.batch(() => {\n\t\t\tif (!mainStore.getObjectKey(BRANCHES_NODE_ID, \"__class\")) {\n\t\t\t\tmainStore.insertNode(new BranchesNode().toJS(), this.tree.root.id)\n\t\t\t}\n\t\t\tmainStore.insertNode(branchNode.toJS(), BRANCHES_NODE_ID)\n\t\t})\n\n\t\tthis.afterStoreWrite(mainStore, lastIndex)\n\t\tdrainState.dirty = true\n\n\t\t// Since we manually inserted the branch node into the main store, we need to update the\n\t\t// tree ourselves. This is a little awkward, but in practice it only really matters in\n\t\t// tests, because in the editor, we immediately switch to the created branch, which reloads\n\t\t// the tree.\n\t\tif (!BranchesNode.get(this.tree)) {\n\t\t\tthis.tree.insertNode(new BranchesNode(), this.tree.root.id)\n\t\t}\n\t\tthis.tree.insertNode(branchNode, BRANCHES_NODE_ID)\n\t\tthis.tree = this.tree.commit(this.componentLoader)\n\t\tthis.trackChange(BRANCHES_NODE_ID)\n\t\tthis.trackChange(branchId)\n\t}\n\n\taddBranchContributor(branchId: string, userId: string): void {\n\t\tassert(branchId !== MAIN_BRANCH_ID, \"Can't add contributor to the main branch\")\n\t\tconst mainStore = this.branches.getStore(MAIN_BRANCH_ID)\n\t\tconst existing = mainStore.getObjectKey<BranchContributor[]>(branchId, BRANCH_CONTRIBUTOR_KEY) ?? []\n\t\tif (existing.some(entry => entry.id === userId)) return\n\t\tconst next = [...existing, { id: userId }]\n\t\tconst drainState = this.getOrCreateBranchState(MAIN_BRANCH_ID, mainStore)\n\t\tconst lastIndex = mainStore.length\n\t\tmainStore.updateNode(branchId, { [BRANCH_CONTRIBUTOR_KEY]: next })\n\t\tthis.afterStoreWrite(mainStore, lastIndex)\n\t\tdrainState.dirty = true\n\t\tconst branchNode = this.tree.get<BranchNode>(branchId)\n\t\tassert(branchNode, \"Missing branch metadata node\", branchId)\n\t\tbranchNode.set({ [BRANCH_CONTRIBUTOR_KEY]: next })\n\t\tthis.tree = this.tree.commit(this.componentLoader)\n\t}\n\n\tremoveBranchContributor(branchId: string, userId: string): void {\n\t\tassert(branchId !== MAIN_BRANCH_ID, \"Can't remove contributor from the main branch\")\n\t\tconst mainStore = this.branches.getStore(MAIN_BRANCH_ID)\n\t\tconst existing = mainStore.getObjectKey<BranchContributor[]>(branchId, BRANCH_CONTRIBUTOR_KEY) ?? []\n\t\tconst next = existing.filter(entry => entry.id !== userId)\n\t\tif (next.length === existing.length) return\n\t\tconst drainState = this.getOrCreateBranchState(MAIN_BRANCH_ID, mainStore)\n\t\tconst lastIndex = mainStore.length\n\t\tmainStore.updateNode(branchId, { [BRANCH_CONTRIBUTOR_KEY]: next })\n\t\tthis.afterStoreWrite(mainStore, lastIndex)\n\t\tdrainState.dirty = true\n\t\tconst branchNode = this.tree.get<BranchNode>(branchId)\n\t\tassert(branchNode, \"Missing branch metadata node\", branchId)\n\t\tbranchNode.set({ [BRANCH_CONTRIBUTOR_KEY]: next })\n\t\tthis.tree = this.tree.commit(this.componentLoader)\n\t}\n\n\tdeleteBranch(branchId: string): void {\n\t\tassert(branchId !== MAIN_BRANCH_ID, \"Can't delete the main branch\")\n\n\t\tconst mainStore = this.branches.getStore(MAIN_BRANCH_ID)\n\t\tassert(!mainStore.getObjectKey<number>(branchId, BRANCH_DELETED_AT_KEY), \"Branch is already deleted\", branchId)\n\t\tassert(isBranchWithoutChildren(mainStore, branchId), \"Cannot delete branch with child branches\", branchId)\n\n\t\tconst now = Date.now()\n\t\tconst mainDrainState = this.getOrCreateBranchState(MAIN_BRANCH_ID, mainStore)\n\t\tconst mainLastIndex = mainStore.length\n\t\tmainStore.updateNode(branchId, { [BRANCH_DELETED_AT_KEY]: now })\n\t\tthis.afterStoreWrite(mainStore, mainLastIndex)\n\t\tmainDrainState.dirty = true\n\n\t\tconst branchNode = this.tree.get<BranchNode>(branchId)\n\t\tassert(branchNode, \"Missing branch metadata node\", branchId)\n\t\tbranchNode.set({ [BRANCH_DELETED_AT_KEY]: now })\n\t\tthis.tree = this.tree.commit(this.componentLoader)\n\t}\n\n\tmergeBranchToBase(branchId = this.branches.activeBranchId): string {\n\t\tassert(branchId !== MAIN_BRANCH_ID, \"Can't merge the main branch\")\n\n\t\tconst mainStore = this.branches.getStore(MAIN_BRANCH_ID)\n\t\tconst baseId = mainStore.getObjectKey<string>(branchId, BRANCH_BASE_ID_KEY)\n\t\tassert(typeof baseId === \"string\" && baseId.length > 0, \"Missing metadata for branch\", branchId)\n\t\tassert(!mainStore.getObjectKey<number>(branchId, BRANCH_DELETED_AT_KEY), \"Cannot merge deleted branch\", branchId)\n\t\tassert(isBranchWithoutChildren(mainStore, branchId), \"Cannot merge branch with child branches\", branchId)\n\n\t\tconst sourceStore = this.branches.getStore(branchId)\n\t\tconst baseStore = this.branches.getStore(baseId)\n\t\tconst mainDrainState = this.getOrCreateBranchState(MAIN_BRANCH_ID, mainStore)\n\n\t\tthis.switchActiveBranch(baseId)\n\n\t\tconst baseLastIndex = baseStore.length\n\t\tbaseStore.replayRows(sourceStore)\n\t\tthis.afterStoreWrite(baseStore, baseLastIndex)\n\t\tconst baseDrainState = this.getOrCreateBranchState(baseId, baseStore)\n\t\tbaseDrainState.dirty = true\n\n\t\tconst now = Date.now()\n\t\tconst mainLastIndex = mainStore.length\n\t\tmainStore.batch(() => {\n\t\t\tmainStore.updateNode(branchId, { [BRANCH_DELETED_AT_KEY]: now })\n\t\t\tif (baseId !== MAIN_BRANCH_ID) {\n\t\t\t\tmainStore.updateNode(baseId, { [BRANCH_LAST_EDITED_KEY]: now })\n\t\t\t}\n\t\t})\n\t\tthis.afterStoreWrite(mainStore, mainLastIndex)\n\t\tmainDrainState.dirty = true\n\n\t\tconst branchNode = this.tree.get<BranchNode>(branchId)\n\t\tassert(branchNode, \"Missing branch metadata node\", branchId)\n\t\tbranchNode.set({ [BRANCH_DELETED_AT_KEY]: now })\n\n\t\tif (baseId !== MAIN_BRANCH_ID) {\n\t\t\tconst baseNode = this.tree.get<BranchNode>(baseId)\n\t\t\tif (baseNode) baseNode.set({ [BRANCH_LAST_EDITED_KEY]: now })\n\t\t}\n\n\t\tthis.tree = this.tree.commit(this.componentLoader)\n\n\t\treturn baseId\n\t}\n\n\trenameBranch(branchId: string, name: string): CanvasTree {\n\t\tassert(branchId !== MAIN_BRANCH_ID, \"Can't rename the main branch\")\n\n\t\tconst mainStore = this.branches.getStore(MAIN_BRANCH_ID)\n\t\tassert(mainStore.getObjectKey(branchId, \"baseId\"), `Branch ${branchId} doesn't exist`)\n\n\t\tconst entry = this.getOrCreateBranchState(MAIN_BRANCH_ID, mainStore)\n\t\tconst lastIndex = mainStore.length\n\n\t\tmainStore.batch(() => {\n\t\t\tmainStore.updateNode(branchId, { name })\n\t\t})\n\n\t\tthis.afterStoreWrite(mainStore, lastIndex)\n\t\tentry.dirty = true\n\n\t\tconst branchNode = this.tree.get<BranchNode>(branchId)\n\t\tassert(branchNode, \"Branch metadata is missing from the canvas tree\", branchId)\n\t\tbranchNode.set({ name })\n\t\tthis.tree = this.tree.commit(this.componentLoader)\n\t\treturn this.tree\n\t}\n\n\tprivate collectExistingBranchNames(): Set<string> {\n\t\tconst names = new Set<string>()\n\t\tconst branchesNode = BranchesNode.get(this.tree)\n\t\tif (!branchesNode) return names\n\t\tfor (const child of branchesNode.children) {\n\t\t\tnames.add(child.title)\n\t\t}\n\t\treturn names\n\t}\n\n\tprivate getOrCreateBranchState(branchId: string, store: Store): BranchDrainState {\n\t\tlet drainState = this.branchStates.get(branchId)\n\t\tif (!drainState) {\n\t\t\tdrainState = {\n\t\t\t\tlastSeqTaken: Math.max(0, store.seq - 1),\n\t\t\t\tlastMinIndex: Math.max(0, store.length - 1),\n\t\t\t\tdirty: false,\n\t\t\t}\n\t\t\tthis.branchStates.set(branchId, drainState)\n\t\t}\n\t\treturn drainState\n\t}\n\n\t/** Shared with every new data tree, so sometimes node caches persist for a while. */\n\tprivate readonly persistedCaches = new PersistedNodeCaches()\n\tprivate dataTree: DataTree | undefined = undefined\n\n\tgetOrCreateDataTree(queryContext: TreeQueryContext): DataTree | undefined {\n\t\tif (!experiments.isOn(\"dataOnlyTree\")) {\n\t\t\treturn undefined\n\t\t}\n\n\t\t// When document loading fails (e.g. binary version mismatch), the store is not\n\t\t// populated but a fallback canvas tree is set. The data tree cannot function\n\t\t// without store data, so skip creating it in that case.\n\t\t//\n\t\t// Freshly-created branches are expected not to have any rows yet, so they're exempt here.\n\t\tif (this.store.branchId === MAIN_BRANCH_ID && this.store.length === 0) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (!this.dataTree) {\n\t\t\tthis.dataTree = new DataTree(this.store, this.tree, queryContext, this.persistedCaches)\n\t\t}\n\n\t\treturn this.dataTree\n\t}\n\n\tresetDataTree() {\n\t\tthis.dataTree = undefined\n\t}\n\n\thasOnlyEmptyChangesForRemote(): boolean {\n\t\tfor (const [branchId, drainState] of this.branchStates) {\n\t\t\tif (!drainState.dirty) continue\n\t\t\tconst store = this.branches.getStore(branchId)\n\t\t\tif (this.storeHasUnsentRows(store, drainState.lastSeqTaken)) return false\n\t\t}\n\t\treturn true\n\t}\n\n\tprivate storeHasUnsentRows(store: Store, lastSeq: number): boolean {\n\t\tconst minIndex = store.getFirstRowForSeq(lastSeq + 1)\n\t\tconst allRows = store.getSerializableRows(minIndex)\n\t\tfor (const row of allRows) {\n\t\t\tif (row.client !== store.client) continue\n\t\t\tif (row.seq <= lastSeq) continue\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tresetLastSeqTaken() {\n\t\t// Treat everything up to current seq on the active branch as already-synced. Non-active branches\n\t\t// keep their own watermarks.\n\t\tconst active = this.activeBranchDrainState()\n\t\tactive.lastSeqTaken = this.store.seq - 1\n\t\tactive.lastMinIndex = Math.max(0, this.store.length - 1)\n\t\tlog.debug(\n\t\t\t\"Reset last sent seq to current store seq:\",\n\t\t\tactive.lastSeqTaken,\n\t\t\t\"last index:\",\n\t\t\tactive.lastMinIndex,\n\t\t\t\"branch:\",\n\t\t\tthis.store.branchId,\n\t\t)\n\t}\n\n\t/**\n\t * Returns rows that should be sent to the server next, drained from\n\t * every dirty branch in Map insertion order (main first, then other\n\t * branches in the order they were first activated). Each emitted row\n\t * is tagged with `branchId` iff the source store is a non-main\n\t * branch \u2014 main rows stay untagged so single-branch documents emit\n\t * byte-identical wire data.\n\t *\n\t * Side effects: advances per-branch watermarks, clears dirty bits,\n\t * and evicts non-active entries that became clean (active stays so\n\t * {@link store} keeps a live handle).\n\t */\n\ttakePendingRows(userId: string): BranchedSerializableRow[] {\n\t\tthis.oldestLocalCommitTime = 0\n\t\tconst rows: BranchedSerializableRow[] = []\n\n\t\tconst stats: Record<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tlastTakenSeq: number\n\t\t\t\tstoreSeq: number\n\t\t\t\tlastMinIndex: number\n\t\t\t\tstoreLength: number\n\t\t\t}\n\t\t> = {}\n\n\t\tfor (const [branchId, drainState] of this.branchStates) {\n\t\t\tif (!drainState.dirty) continue\n\t\t\tconst store = this.branches.getStore(branchId)\n\n\t\t\tstats[branchId] = {\n\t\t\t\tlastTakenSeq: drainState.lastSeqTaken,\n\t\t\t\tlastMinIndex: drainState.lastMinIndex,\n\t\t\t\tstoreSeq: store.seq,\n\t\t\t\tstoreLength: store.length,\n\t\t\t}\n\n\t\t\tconst drained = this.drainStore(store, userId, drainState.lastSeqTaken, drainState.lastMinIndex)\n\t\t\tfor (const row of drained.rows) rows.push(row)\n\t\t\tdrainState.lastSeqTaken = drained.maxSeq\n\t\t\tdrainState.lastMinIndex = drained.minIndex\n\t\t\tdrainState.dirty = false\n\t\t\tif (branchId !== this.branches.activeBranchId) this.branchStates.delete(branchId)\n\t\t}\n\n\t\ttry {\n\t\t\tStore.verifyBatches(rows)\n\t\t} catch (e) {\n\t\t\tlog.reportError(e, {\n\t\t\t\tstats,\n\t\t\t})\n\t\t}\n\n\t\treturn rows\n\t}\n\n\t/**\n\t * Drain `store` from `lastSeq + 1` onward, returning the new\n\t * watermarks plus any rows authored by this client. Pure read \u2014 does\n\t * not mutate committer state. Called per-branch by\n\t * {@link takePendingRows}.\n\t */\n\tprivate drainStore(\n\t\tstore: Store,\n\t\tuserId: string,\n\t\tlastSeq: number,\n\t\tlastMin: number,\n\t): { rows: BranchedSerializableRow[]; maxSeq: number; minIndex: number } {\n\t\tconst rows: BranchedSerializableRow[] = []\n\t\tconst nextSeq = lastSeq + 1\n\t\tif (nextSeq === store.seq) return { rows, maxSeq: lastSeq, minIndex: lastMin }\n\n\t\tlet minIndex = store.getFirstRowForSeq(nextSeq)\n\t\tif (minIndex === 0) minIndex = lastMin\n\t\tconst allRows = store.getSerializableRows(minIndex)\n\n\t\tlet maxSeq = lastSeq\n\t\tfor (const row of allRows) {\n\t\t\tif (row.client !== store.client) continue\n\t\t\tif (row.seq <= lastSeq) continue\n\t\t\tif (maxSeq < row.seq) maxSeq = row.seq\n\n\t\t\tconst branchTaggedRow: BranchedSerializableRow = { ...row, user: userId }\n\t\t\tif (store.branchId !== MAIN_BRANCH_ID) {\n\t\t\t\tbranchTaggedRow.branchId = store.branchId\n\t\t\t}\n\t\t\trows.push(branchTaggedRow)\n\t\t}\n\n\t\treturn { rows, maxSeq, minIndex }\n\t}\n\n\t// --- Small surface parity with TreeTimeline (used by CRDT code/tests/debug tooling) ---\n\tgetLastEntry() {\n\t\tconst lastEntry = this.remoteTrees[this.remoteTrees.length - 1]\n\t\tassert(lastEntry, \"Timeline has no entries\")\n\t\treturn lastEntry\n\t}\n\n\tgetEntry(index: number) {\n\t\treturn this.remoteTrees[index]\n\t}\n\n\thasLocalEdits() {\n\t\tfor (const drainState of this.branchStates.values()) {\n\t\t\tif (drainState.dirty) return true\n\t\t}\n\t\treturn false\n\t}\n\n\tgetEditReasons(): string {\n\t\tconst result = this.recentEditReasons.join(\" \")\n\t\tthis.recentEditReasons = []\n\t\treturn result\n\t}\n\n\tgetTreeForVersion(version: number): RemoteTreeEntry | undefined {\n\t\treturn this.remoteTrees.findLast(e => e.remoteVersion === version && !e.containsLocalEdits)\n\t}\n\n\tprivate hasPendingHierarchyChanges(): boolean {\n\t\tfor (const [branchId, drainState] of this.branchStates) {\n\t\t\tif (!drainState.dirty) continue\n\t\t\tconst store = this.branches.getStore(branchId)\n\t\t\tif (this.storeHasUnsentParentidRows(store, drainState.lastSeqTaken, drainState.lastMinIndex)) return true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate storeHasUnsentParentidRows(store: Store, lastSeq: number, lastMin: number): boolean {\n\t\tconst nextSeq = lastSeq + 1\n\t\tif (nextSeq === store.seq) return false\n\n\t\tlet minIndex = store.getFirstRowForSeq(nextSeq)\n\t\tif (minIndex === 0) minIndex = lastMin\n\t\tconst allRows = store.getSerializableRows(minIndex)\n\n\t\tfor (const row of allRows) {\n\t\t\tif (row.key === \"parentid\") return true\n\t\t}\n\t\treturn false\n\t}\n\n\thasHierarchyChangesAfterVersion(version: number): boolean {\n\t\tlet hasStartingVersion = false\n\t\tfor (const entry of this.remoteTrees) {\n\t\t\tif (entry.remoteVersion === version) {\n\t\t\t\thasStartingVersion = true\n\t\t\t}\n\t\t\tif (entry.remoteVersion <= version) continue\n\t\t\tif (entry.hasHierarchyChanges) return true\n\t\t}\n\t\tif (!hasStartingVersion) return true\n\t\treturn this.hasPendingHierarchyChanges()\n\t}\n\n\t/** Record a server-version tree for verification. Call this after treeVersion advances. */\n\trecordHistoricTree(version: number, options: HistoricTreeRecordOptions) {\n\t\tthis.remoteTreeVersion = version\n\n\t\tthis.remoteTrees.push(\n\t\t\tnew RemoteTreeEntry(this.tree, version, options.containsLocalEdits, options.hasHierarchyChanges),\n\t\t)\n\n\t\t// Keep only a bounded window; verification messages only target recent versions.\n\t\tconst MAX_HISTORY = 120\n\t\tif (this.remoteTrees.length > MAX_HISTORY) {\n\t\t\tconst removeCount = this.remoteTrees.length - MAX_HISTORY\n\t\t\tconst removed = this.remoteTrees.splice(0, removeCount)\n\t\t\tfor (const entry of removed) {\n\t\t\t\t// Trees are immutable; once dropped from our history list they're no longer needed.\n\t\t\t\t// (Cursors store their own tree; they are independent of this history.)\n\t\t\t\tentry.tree.releaseMemory()\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Applies a remote CRDT patch update to the tree and records a verification snapshot for the version. */\n\thandleRemotePatches(\n\t\tpatches: CrdtTreePatchMap,\n\t\tnextVersion: number,\n\t\thistoricTreeRecordOptions: HistoricTreeRecordOptions,\n\t): NodeChange[] | undefined {\n\t\tassert(this.tree.isLatest(), \"Tree must be latest\")\n\t\tconst baseTree = this.tree\n\t\tconst isViewOnly = baseTree.isViewOnly\n\n\t\tbaseTree.editClosed = false\n\t\tbaseTree.isViewOnly = false\n\t\tbaseTree.beginAllowPartialScopeAccess()\n\t\tconst newTree = applyPatchesToTheTree(baseTree, this.componentLoader, patches)\n\n\t\tnewTree.beginAllowPartialScopeAccess()\n\t\tconst changes = createChangesFromPatches(baseTree, newTree, patches)\n\n\t\tfor (const change of changes) {\n\t\t\tthis.trackChange(change.id, change)\n\t\t}\n\t\tfor (const node of baseTree.getNodesChangedByCommit()) {\n\t\t\tthis.trackChange(node.id)\n\t\t}\n\n\t\t// Commit the remote tree state (CRDT merge already resolves concurrency).\n\t\tthis.tree = newTree\n\n\t\tthis.recordHistoricTree(nextVersion, historicTreeRecordOptions)\n\n\t\tbaseTree.endAllowPartialScopeAccess()\n\t\tnewTree.endAllowPartialScopeAccess()\n\t\tassert(!newTree.lineage.allowPartialNodeAccess, \"Partial scope access should be disabled after commit\")\n\t\tnewTree.isViewOnly = isViewOnly\n\n\t\t// Release memory on the base tree, matching the releaseMemory() call in commitLocalTree.\n\t\t// applyPatchesToTheTree mutates baseTree (e.g. removeNode), so its driver's currentNodes\n\t\t// no longer contains deleted nodes. Resetting via releaseMemory() restores currentNodes\n\t\t// from nodesAtStart, so consumers like SelectionStore.postProcess can look up deleted\n\t\t// nodes in previousTree when handling remote/multiplayer deletions.\n\t\tif (baseTree !== newTree) {\n\t\t\tbaseTree.releaseMemory()\n\t\t}\n\n\t\tif (\n\t\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\t\t!environment.benchmarkSkipTreeVerify &&\n\t\t\tthis.tree.size() < MAX_VERIFY_TREE_SIZE\n\t\t) {\n\t\t\tconst error = this.verifyTree()\n\t\t\tif (error) throw error\n\t\t}\n\n\t\treturn changes\n\t}\n\n\t/** Applies a server confirm to advance the remote pointer and records a verification snapshot for the version. */\n\thandleRemoteConfirm(nextVersion: number, historicTreeRecordOptions: HistoricTreeRecordOptions) {\n\t\tthis.recordHistoricTree(nextVersion, historicTreeRecordOptions)\n\t\tthis.oldestLocalCommitTime = 0\n\t}\n\n\tloadedAllScopes(historicTreeRecordOptions: HistoricTreeRecordOptions) {\n\t\tassert(this.isPartialLoading, \"Must be in loading mode\")\n\t\tthis.isPartialLoading = false\n\t\tthis.recordHistoricTree(this.remoteTreeVersion, historicTreeRecordOptions)\n\t}\n\n\t/** Insert one scope on top of the current tree during partial loading. */\n\tloadOneScope(scope: CanvasNode, _keepChanges: boolean): CanvasTree {\n\t\tlog.debug(\"loadOneScope:\", scope.id)\n\n\t\tassert(this.isPartialLoading, \"Must be loading\")\n\t\tassert(!scope.cache.isShallowLoad, \"Scope must not be shallow\")\n\t\tassert(this.tree.isLatest(), \"Tree must be latest\")\n\n\t\tconst isViewOnly = this.tree.isViewOnly\n\t\tthis.tree.editClosed = false\n\t\tthis.tree.isViewOnly = false\n\t\tthis.tree.inEditor = false\n\t\tthis.tree.makeLatest()\n\n\t\tconst position = this.tree.root.children.findIndex(node => node.id === scope.id)\n\t\tif (position === -1) {\n\t\t\t// The scope is loaded from the store, which mutates as the loader loads from it. After the\n\t\t\t// data is read from the store, the loader will set activelyLoadingScope to true, and we no\n\t\t\t// longer add rows to the store until done.\n\t\t\t//\n\t\t\t// That means the scope we get here is all up to date. We can add it to the tree. But it can\n\t\t\t// happen that the loader loads a scope that was deleted. In which case the scope won't be\n\t\t\t// in the root children, and won't be in the tree what soever.\n\t\t\tassert(!this.tree.get(scope.id), \"Scope must have been deleted by remote diffs\")\n\t\t} else if (scope.__class === \"WebPageNode\" || scope.__class === \"SmartComponentNode\") {\n\t\t\texpandScopeReplicas(scope)\n\t\t\tconst updated = this.tree.commitWithLoadedScope(this.componentLoader, scope)\n\t\t\tthis.tree.inEditor = true\n\t\t\tthis.tree = updated\n\t\t\tfor (const node of scope.walk()) {\n\t\t\t\tthis.trackChange(node.id)\n\t\t\t}\n\t\t\tthis.tree.loadReplicasAndCodeComponents(scope)\n\t\t} else {\n\t\t\tthis.tree.remove(scope.id)\n\t\t\tthis.tree.insertNode(scope, this.tree.root.id, position)\n\t\t\tthis.tree.loadReplicasAndCodeComponents(scope)\n\t\t}\n\n\t\tconst updated = this.tree.commit(\n\t\t\tthis.componentLoader,\n\t\t\t(current: CanvasNode | undefined, draft: CanvasNode | undefined) => {\n\t\t\t\tconst id = current?.id ?? draft?.id\n\t\t\t\tif (id) {\n\t\t\t\t\tthis.trackChange(id)\n\t\t\t\t}\n\t\t\t},\n\t\t)\n\n\t\tthis.tree.inEditor = true\n\t\tthis.tree = updated\n\t\tthis.tree.inEditor = true\n\t\tthis.tree.isViewOnly = isViewOnly\n\n\t\tif (this.legacyMode) {\n\t\t\tthis.invalidateAllCursors()\n\t\t}\n\n\t\treturn updated\n\t}\n\n\t// --- TreeUpdater interface ---\n\tdebugOverwriteCurrentTree(tree: CanvasTree): void {\n\t\tlog.debug(\"debugOverwriteCurrentTree:\", tree.root.id)\n\t\tthis.tree = tree\n\t\t// Best-effort: if we have history, keep last entry consistent.\n\t\tif (this.remoteTrees.length > 0) {\n\t\t\tthis.getLastEntry().tree = tree\n\t\t}\n\t\t// This is a destructive operation; consumers should re-request cursors.\n\t\tthis.invalidateAllCursors()\n\t}\n\n\tsaveTimelineDataForRecovery(): void {\n\t\t// Keep as no-op; CRDT recovery debugging can be implemented later if needed.\n\t}\n\n\tsetFlagsForNextCommit(flags: TimelineFlags): void {\n\t\tthis.flagsForNextCommit = flags\n\t}\n\n\tsetExtraChangesForNextCommit(changes: NodeChange[]): void {\n\t\tthis.extraChangesForNextCommit = changes\n\t}\n\n\trecordEditReasons(source: string | null | undefined): void {\n\t\tif (!source) return\n\t\tif (this.recentEditReasons.at(-1) !== source) {\n\t\t\tthis.recentEditReasons.push(source)\n\t\t}\n\t}\n\n\tgetLatestChangesForUndo(): ReversibleNodeChange[] | null {\n\t\treturn this.latestReversibleNodeChanges\n\t}\n\n\topenNodeChangesReader(): NodeChangesBuffer {\n\t\treturn new NodeChangesBuffer(this.nodeChangesBuffers)\n\t}\n\n\tprivate clearNodeChangesReader() {\n\t\tfor (const reader of this.nodeChangesBuffers) {\n\t\t\treader.clear()\n\t\t}\n\t}\n\n\tprivate applyFlagsToChange(change: NodeChange | null | undefined) {\n\t\tif (!change) return\n\t\tconst flags = this.flagsForNextCommit\n\t\tif (!flags) return\n\n\t\tif (flags.ignoreInUndo) {\n\t\t\tchange.ignoreInUndo = true\n\t\t}\n\t\tif (flags.ignoreInCodeGeneration) {\n\t\t\tchange.ignoreInCodeGeneration = true\n\t\t}\n\t}\n\n\tprivate hasAutoBranchingChanges(changes: NodeChange[]): boolean {\n\t\treturn changes.some(change => {\n\t\t\tif (this.isBranchMetadataChange(change)) return false\n\t\t\tif (change.ignoreInUndo) return false\n\t\t\tif (change.added || change.removed) return true\n\t\t\tif (change.position !== undefined || change.fromPosition !== undefined) return true\n\t\t\tif (change.toChildren || change.fromChildren) return true\n\t\t\tif (this.hasAutoBranchingPropertyChanges(change.to)) return true\n\t\t\treturn false\n\t\t})\n\t}\n\n\tprivate hasAutoBranchingPropertyChanges(props: PropsDiff | undefined): boolean {\n\t\tif (!props) return false\n\n\t\tfor (const key of Object.keys(props)) {\n\t\t\tif (key !== \"_deleted\") {\n\t\t\t\tif (!IGNORED_AUTO_BRANCH_CHANGE_KEYS.has(key)) return true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst deletedKeys = props[key]\n\t\t\tif (!deletedKeys) return true\n\t\t\tif (deletedKeys.some(deletedKey => !IGNORED_AUTO_BRANCH_CHANGE_KEYS.has(deletedKey))) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\tprivate isBranchMetadataChange(change: NodeChange): boolean {\n\t\tconst nodeClass = this.branches.getStore(MAIN_BRANCH_ID).getObjectKey(change.id, \"__class\")\n\t\treturn nodeClass === ClassDiscriminator.BranchesNode || nodeClass === ClassDiscriminator.BranchNode\n\t}\n\n\tprivate updateStoreFromNodeChanges(changes: NodeChange[]) {\n\t\tconst removedNodes = new Set<string>()\n\t\tfor (const change of changes) {\n\t\t\tif (this.store.branchId !== MAIN_BRANCH_ID && this.isBranchMetadataChange(change)) continue\n\n\t\t\tif (change.removed) {\n\t\t\t\tthis.store.removeNode(change.id)\n\t\t\t\tremovedNodes.add(change.id)\n\t\t\t}\n\n\t\t\tif (change.added) {\n\t\t\t\tconst node = { ...change.to }\n\t\t\t\tnode.id = change.id\n\t\t\t\tnode.__class = change.added\n\n\t\t\t\tconst nodeSubclass = getNodeDefaultsByClassName(node.__class)\n\t\t\t\tif (nodeSubclass && withChildren(nodeSubclass)) {\n\t\t\t\t\tnode.children = []\n\t\t\t\t}\n\n\t\t\t\tthis.store.insertNode(node, node.parentid, change.position)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (change.to.parentid || change.position !== change.fromPosition) {\n\t\t\t\tconst parentid = change.to.parentid ?? this.store.getParentId(change.id)\n\t\t\t\tif (parentid && parentid !== DELETED_VALUE) {\n\t\t\t\t\tthis.store.moveNode(change.id, parentid, change.position)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const change of changes) {\n\t\t\tif (this.store.branchId !== MAIN_BRANCH_ID && this.isBranchMetadataChange(change)) continue\n\t\t\tif (change.added || change.removed || removedNodes.has(change.id)) continue\n\n\t\t\tconst { _deleted, ...to } = change.to\n\t\t\tif (isOverrideId(change.id)) {\n\t\t\t\tfor (const key of _deleted ?? []) to[key === \"_deleted\" ? \"__deleted\" : key] = DELETED_VALUE\n\t\t\t\tconst [replicaId, originalId] = parseOverrideId(change.id)\n\t\t\t\tassert(replicaId && originalId)\n\n\t\t\t\tthis.store.updateNestedObject([replicaId, \"replicaInfo\", \"overrides\", originalId], to)\n\t\t\t} else {\n\t\t\t\tfor (const key of _deleted ?? []) to[key] = undefined\n\t\t\t\tdelete to.parentid\n\t\t\t\tif (Object.keys(to).length) {\n\t\t\t\t\tthis.store.updateNode(change.id, to)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprivate syncChanges(changes: NodeChange[]) {\n\t\tconst lastIndex = this.store.length\n\t\tthis.store.batch(() => this.updateStoreFromNodeChanges(changes))\n\t\tthis.afterStoreWrite(this.store, lastIndex)\n\t\tthis.touchActiveBranchLastEdited(this.store, lastIndex)\n\t}\n\n\tprivate touchActiveBranchLastEdited(store: Store, lastIndex: number) {\n\t\tif (lastIndex === store.length) return\n\n\t\tconst branchId = store.branchId\n\t\tif (branchId === MAIN_BRANCH_ID || branchId !== this.branches.activeBranchId) return\n\n\t\tconst now = Date.now()\n\n\t\t// Update the in-memory tree so the UI reflects the change immediately,\n\t\t// without waiting for a server roundtrip to bounce the store update back.\n\t\tconst branchNode = this.tree.get<BranchNode>(branchId)\n\t\tif (branchNode) {\n\t\t\tbranchNode.set({ lastEdited: now })\n\t\t\tthis.tree = this.tree.commit(this.componentLoader)\n\t\t}\n\n\t\tconst mainStore = this.branches.getStore(MAIN_BRANCH_ID)\n\t\tconst mainDrainState = this.getOrCreateBranchState(MAIN_BRANCH_ID, mainStore)\n\t\tconst mainLastIndex = mainStore.length\n\t\tmainStore.updateNode(branchId, { [BRANCH_LAST_EDITED_KEY]: now })\n\t\tthis.afterStoreWrite(mainStore, mainLastIndex)\n\t\tmainDrainState.dirty = true\n\t}\n\n\tprivate afterStoreWrite(store: Store, lastIndex: number) {\n\t\tif (this.oldestLocalCommitTime === 0 && lastIndex !== store.length) {\n\t\t\tthis.oldestLocalCommitTime = performance.now()\n\t\t}\n\n\t\tthis.afterLocalWrite?.(store.branchId, store.seq)\n\n\t\tif (this.recorder) {\n\t\t\tthis.recorder({\n\t\t\t\tsource: \"local\",\n\t\t\t\trows: store.getSerializableRows(lastIndex),\n\t\t\t})\n\t\t}\n\t}\n\n\tpublic trackChange(id: NodeID | undefined, change: NodeChange | null = null) {\n\t\tif (!id) return\n\t\tfor (const reader of this.nodeChangesBuffers) {\n\t\t\treader.trackChange(id, change)\n\t\t}\n\t}\n\n\tvalidateUpdatesAreSentToServer() {\n\t\tif (!this.validationEnabled || !this.online) return\n\n\t\tconst now = performance.now()\n\t\tconst connectionDuration = now - this.onlineStartTime\n\t\tif (connectionDuration < REMOTE_CONNECTION_VALID_FOR_MS) return\n\n\t\tif (this.oldestLocalCommitTime === 0) return\n\n\t\tconst deltaSinceOldestEntry = now - this.oldestLocalCommitTime\n\t\tassert(deltaSinceOldestEntry < LOCAL_CHANGES_VALID_FOR_MS, \"Local changes not been processed in a while\")\n\t}\n\n\tcommitLocalTree(): CommitLocalTreeResult {\n\t\tthis.validateUpdatesAreSentToServer()\n\n\t\tconst changeset = this.tree.lineage.getActiveChangeset()\n\n\t\tconst changesById: Record<NodeID, ReversibleNodeChange> = {}\n\n\t\tif (experiments.isOn(\"dataOnlyTree\") && this.dataTree?.hasUncommittedChanges()) {\n\t\t\tfor (const change of this.dataTree.preCommit(this.componentLoader)) {\n\t\t\t\tchangesById[change.id] = change\n\t\t\t}\n\t\t}\n\n\t\tconst newTree = this.tree.commit(\n\t\t\tthis.componentLoader,\n\t\t\t(current: CanvasNode | undefined, draft: CanvasNode | undefined) => {\n\t\t\t\tif (!current && !draft) return\n\t\t\t\tconst change = nodeChange(current, draft, true)\n\n\t\t\t\tthis.trackChange(current?.id ?? draft!.id, null)\n\t\t\t\tif (change) {\n\t\t\t\t\tchangesById[change.id] = change\n\t\t\t\t}\n\n\t\t\t\tconst overrideChanges: ReversibleNodeChange[] = []\n\t\t\t\tcomputeOverrideChanges(overrideChanges, current, draft)\n\t\t\t\tfor (const oc of overrideChanges) {\n\t\t\t\t\tchangesById[oc.id] = oc\n\t\t\t\t}\n\t\t\t},\n\t\t)\n\n\t\tconst offsetPerParent = new Map<string, { offset: number; position: number }>()\n\t\tconst changes: ReversibleNodeChange[] = []\n\t\tconst nodesWithNonSkippedMove = new Set<NodeID>()\n\t\tfor (const hierarchyChange of this.tree.hierarchyChanges) {\n\t\t\tif (hierarchyChange.type === \"move\" && !hierarchyChange.skip) {\n\t\t\t\tnodesWithNonSkippedMove.add(hierarchyChange.node)\n\t\t\t}\n\t\t}\n\n\t\tfor (const hc of this.tree.hierarchyChanges) {\n\t\t\t// Track position drift from skipped ops so later ops can\n\t\t\t// compensate (e.g. skipped insert \u2192 positions after it shift by -1).\n\t\t\tif (hc.skip) {\n\t\t\t\tif (hc.type === \"insert\") {\n\t\t\t\t\tif (nodesWithNonSkippedMove.has(hc.node)) {\n\t\t\t\t\t\tconst existingOffset = offsetPerParent.get(hc.toParent)\n\t\t\t\t\t\tif (existingOffset?.offset === 1 && existingOffset.position === hc.toPosition) {\n\t\t\t\t\t\t\toffsetPerParent.delete(hc.toParent)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tif (offsetPerParent.has(hc.toParent)) {\n\t\t\t\t\t\toffsetPerParent.delete(hc.toParent)\n\t\t\t\t\t} else {\n\t\t\t\t\t\toffsetPerParent.set(hc.toParent, { offset: -1, position: hc.toPosition })\n\t\t\t\t\t}\n\t\t\t\t} else if (hc.type === \"remove\") {\n\t\t\t\t\tif (nodesWithNonSkippedMove.has(hc.node)) {\n\t\t\t\t\t\tconst existingOffset = offsetPerParent.get(hc.fromParent)\n\t\t\t\t\t\tif (existingOffset?.offset === -1 && existingOffset.position === hc.fromPosition) {\n\t\t\t\t\t\t\toffsetPerParent.delete(hc.fromParent)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tif (offsetPerParent.has(hc.fromParent)) {\n\t\t\t\t\t\toffsetPerParent.delete(hc.fromParent)\n\t\t\t\t\t} else {\n\t\t\t\t\t\toffsetPerParent.set(hc.fromParent, { offset: 1, position: hc.fromPosition })\n\t\t\t\t\t}\n\t\t\t\t} else if (hc.type === \"move\") {\n\t\t\t\t\toffsetPerParent.set(hc.toParent, { offset: -1, position: hc.toPosition })\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlet change: ReversibleNodeChange | undefined\n\t\t\tif (hc.type === \"insert\") {\n\t\t\t\tconst existing = changesById[hc.node]!\n\n\t\t\t\tconst opp = offsetPerParent.get(hc.toParent)\n\t\t\t\tconst offset = opp ? getOffsetAtPosition(hc.toPosition, opp) : 0\n\n\t\t\t\tchange = {\n\t\t\t\t\tid: hc.node,\n\t\t\t\t\tfrom: existing.from,\n\t\t\t\t\tto: { ...existing.to, parentid: hc.toParent },\n\t\t\t\t\tposition: hc.toPosition + offset,\n\t\t\t\t\tadded: existing.added,\n\t\t\t\t\tignoreInUndo: existing.ignoreInUndo,\n\t\t\t\t}\n\n\t\t\t\tdelete changesById[hc.node]\n\t\t\t} else if (hc.type === \"move\") {\n\t\t\t\tconst toOpp = offsetPerParent.get(hc.toParent)\n\t\t\t\tconst fromOpp = offsetPerParent.get(hc.fromParent)\n\t\t\t\tconst toOffset = toOpp ? getOffsetAtPosition(hc.toPosition, toOpp) : 0\n\t\t\t\tconst fromOffset = fromOpp ? getOffsetAtPosition(hc.fromPosition, fromOpp) : 0\n\n\t\t\t\tchange = {\n\t\t\t\t\tid: hc.node,\n\t\t\t\t\tfrom: { parentid: hc.fromParent },\n\t\t\t\t\tto: { parentid: hc.toParent },\n\t\t\t\t\tfromPosition: hc.fromPosition + fromOffset,\n\t\t\t\t\tposition: hc.toPosition + toOffset,\n\t\t\t\t\tignoreInUndo: changesById[hc.node]?.ignoreInUndo,\n\t\t\t\t}\n\t\t\t} else if (hc.type === \"remove\") {\n\t\t\t\tconst existing = changesById[hc.node]!\n\n\t\t\t\tconst opp = offsetPerParent.get(hc.fromParent)\n\t\t\t\tconst offset = opp ? getOffsetAtPosition(hc.fromPosition, opp) : 0\n\n\t\t\t\tchange = {\n\t\t\t\t\tid: hc.node,\n\t\t\t\t\tfrom: { ...existing.from, parentid: hc.fromParent },\n\t\t\t\t\tto: existing.to,\n\t\t\t\t\tfromPosition: hc.fromPosition + offset,\n\t\t\t\t\tremoved: existing.removed,\n\t\t\t\t\tignoreInUndo: existing.ignoreInUndo,\n\t\t\t\t}\n\t\t\t\tdelete changesById[hc.node]\n\t\t\t} else {\n\t\t\t\tassertNever(hc)\n\t\t\t}\n\n\t\t\tchanges.push(change)\n\t\t}\n\n\t\tchanges.push(...Object.values(changesById))\n\n\t\tif (this.extraChangesForNextCommit) {\n\t\t\tfor (const extra of this.extraChangesForNextCommit) {\n\t\t\t\tchanges.push(extra as ReversibleNodeChange)\n\t\t\t}\n\t\t}\n\n\t\tfor (const change of changes) {\n\t\t\tthis.applyFlagsToChange(change)\n\t\t\tthis.trackChange(change.id, change)\n\t\t\tif (changeset) {\n\t\t\t\tthis.tree.lineage.applyChangesetFlagsToChange(change, changeset.id)\n\t\t\t}\n\t\t}\n\n\t\tthis.latestReversibleNodeChanges = changes\n\t\tconst previousTree = this.tree\n\t\tthis.tree = newTree\n\n\t\t// Release memory on the previous tree, matching what TreeTimeline.commitLocalTree does.\n\t\t// This resets the driver's currentNodes back to nodesAtStart, which restores the\n\t\t// pre-mutation state of the tree. Without this, consumers like SelectionStore.postProcess\n\t\t// that look up deleted nodes in previousTree via getNode() would get null, because\n\t\t// removeNode() had already removed them from currentNodes during the handler.\n\t\tif (previousTree !== this.tree) {\n\t\t\tpreviousTree.releaseMemory()\n\t\t}\n\n\t\tconst flagsForCommit = this.flagsForNextCommit\n\t\tthis.flagsForNextCommit = undefined\n\t\tthis.extraChangesForNextCommit = undefined\n\n\t\tlet autoCreatedBranchId: string | undefined\n\t\tif (\n\t\t\texperiments.is(\"branching\", \"autoBranching\") &&\n\t\t\tthis.branches.activeBranchId === MAIN_BRANCH_ID &&\n\t\t\tflagsForCommit?.isUserEdit &&\n\t\t\tthis.hasAutoBranchingChanges(changes)\n\t\t) {\n\t\t\tautoCreatedBranchId = randomBranchID()\n\t\t\tthis.createBranch(autoCreatedBranchId, flagsForCommit.userId)\n\t\t\tthis.switchActiveBranch(autoCreatedBranchId)\n\t\t}\n\n\t\tlog.debug(\"commit local tree:\", changes.length, this.recentEditReasons)\n\t\tthis.syncChanges(changes)\n\n\t\tif (\n\t\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\t\t!environment.benchmarkSkipTreeVerify &&\n\t\t\tthis.tree.size() < MAX_VERIFY_TREE_SIZE\n\t\t) {\n\t\t\tconst error = this.verifyTree()\n\t\t\tif (error) throw error\n\t\t}\n\n\t\tthis.activeBranchDrainState().dirty = true\n\t\treturn { tree: this.tree, autoCreatedBranchId }\n\t}\n\n\t// --- Change tracking cursor support (used by sandbox + some stores) ---\n\n\tprivate epoch = 0\n\tpublic invalidateAllCursors() {\n\t\tthis.epoch += 1\n\t}\n\n\tgetChangeTrackingCursor(): ChangeTrackingCursor {\n\t\treturn { remoteTree: 0, localTree: 0, timeline: this, tree: this.tree, epoch: this.epoch }\n\t}\n\n\tfetchForwardChanges(cursor: ChangeTrackingCursor | undefined | null): NodeChange[] | undefined {\n\t\tif (!cursor) return\n\t\tif (cursor.epoch !== this.epoch) return\n\t\tif (cursor.tree === this.tree) return []\n\n\t\tif (cursor.tree.lineage !== this.tree.lineage) return\n\t\tif (cursor.tree.root.id !== this.tree.root.id) return\n\t\tif (cursor.timeline !== this) return\n\n\t\tthis.tree.beginAllowPartialScopeAccess()\n\t\tconst result = createTreeChanges(cursor.tree, this.tree)\n\t\tthis.tree.endAllowPartialScopeAccess()\n\t\tcursor.tree = this.tree\n\t\treturn result.changes\n\t}\n\n\tinvalidatedByLoadCompletedDocument(_cursor: ChangeTrackingCursor | undefined | null): boolean {\n\t\t// CRDT committer does not perform the TreeTimeline loadCompleteTree bump that needs special casing.\n\t\treturn false\n\t}\n\n\t/** Verify the tree against the store.hierarchy. Here so it can also be called from an inspector console. */\n\tverifyTree(): Error | undefined {\n\t\treturn debugVerifyStoreTreeData(this.store.getHierarchy(), this.tree)\n\t}\n\n\tapplyChanges(changes: NodeChange[]) {\n\t\tcrdtApplyChanges(this.tree, changes, this.store, this.dataTree)\n\t}\n\n\tapplyReverseChanges(changes: ReversibleNodeChange[]): void {\n\t\tcrdtApplyReverseChanges(this.tree, changes, this.store, this.dataTree)\n\t}\n\n\tdiscardChangeset(changeset: Changeset): void {\n\t\tconst record = this.tree.lineage.getChangesetRecord(changeset.id)\n\t\tassert(record, \"Unknown changeset\")\n\t\tif (record.status === \"discarded\") return\n\n\t\tif (record.changes.length > 0) {\n\t\t\t// We want to mark reverted changes with the same flags\n\t\t\t// as changeset. For example, let's say that we mark\n\t\t\t// changeset to not add to history. The discard operation\n\t\t\t// also should not add inverted changes to history.\n\t\t\tthis.applyReverseChanges(record.changes)\n\t\t}\n\n\t\tthis.tree.lineage.setChangesetStatus(changeset.id, \"discarded\")\n\t}\n\n\treplayChangeset(changeset: Changeset) {\n\t\tconst record = this.tree.lineage.changesets[changeset.id]\n\t\tassert(record, \"Changeset record does not exist\", changeset.id)\n\n\t\t// When the changeset was previously discarded, the tree was mutated backwards by\n\t\t// `discardChangeset` via `applyReverseChanges`. Re-apply the forward changes so the\n\t\t// canvas tree state matches the hierarchy/CRDT store again, then re-open the\n\t\t// changeset so it can be discarded again later (e.g. revert -> redo -> revert).\n\t\tif (record.status === \"discarded\") {\n\t\t\tif (record.changes.length > 0) {\n\t\t\t\tthis.applyChanges(record.changes)\n\t\t\t}\n\t\t\tthis.tree.lineage.setChangesetStatus(changeset.id, \"open\")\n\t\t\treturn\n\t\t}\n\n\t\tthis.setExtraChangesForNextCommit(record.changes)\n\t\tthis.tree.root.asDraft()\n\t}\n}\n\nfunction isBranchWithoutChildren(mainStore: Store, branchId: string): boolean {\n\treturn mainStore.getChildrenIds(BRANCHES_NODE_ID).every(childBranchId => {\n\t\tif (childBranchId === branchId) return true\n\t\tif (mainStore.getObjectKey<number>(childBranchId, BRANCH_DELETED_AT_KEY)) return true\n\t\treturn mainStore.getObjectKey<string>(childBranchId, BRANCH_BASE_ID_KEY) !== branchId\n\t})\n}\n\nfunction debugVerifyStoreTreeData(hierarchy: Hierarchy, tree: CanvasTree): Error | undefined {\n\ttree.beginAllowPartialScopeAccess()\n\ttry {\n\t\tconst fail = (...message: unknown[]) => {\n\t\t\treturn new Error(message.map(value => String(value)).join(\" \"))\n\t\t}\n\t\tconst check = (condition: unknown, ...message: unknown[]) => {\n\t\t\tif (condition) return\n\t\t\treturn fail(...message)\n\t\t}\n\n\t\tconst rootId = hierarchy.getRootId()\n\t\tif (!rootId) {\n\t\t\treturn fail(\"hierarchy root does not exist\")\n\t\t}\n\t\tif (rootId !== tree.root.id) {\n\t\t\treturn fail(\"hierarchy root does not match tree root\", rootId, tree.root.id)\n\t\t}\n\n\t\tconst visited = new Set<string>()\n\t\tconst path: string[] = []\n\n\t\tconst formatPath = (leafId: string) => {\n\t\t\treturn path.length > 0 ? `${path.join(\" -> \")} -> ${leafId}` : leafId\n\t\t}\n\n\t\tconst getTreeChildIds = (nodeId: string) => {\n\t\t\tconst node = tree.get(nodeId)\n\t\t\tif (!node) return fail(\"Node missing in CanvasTree\", nodeId, \"path:\", formatPath(nodeId))\n\n\t\t\tconst children = node.children\n\t\t\tif (node.cache.isShallowLoad) return undefined\n\t\t\tif (!children) return []\n\t\t\t// Remove any replica children. They are not in the hierarchy.\n\t\t\treturn children.filter(child => !isReplicaChild(child)).map(child => child.id)\n\t\t}\n\n\t\tconst walk = (nodeId: string): Error | undefined => {\n\t\t\tconst visitedError = check(!visited.has(nodeId), \"cycle\", nodeId, \"path:\", formatPath(nodeId))\n\t\t\tif (visitedError) return visitedError\n\t\t\tvisited.add(nodeId)\n\n\t\t\tconst nodeDataError = check(\n\t\t\t\thierarchy.getNodeData(nodeId),\n\t\t\t\t\"node not in hierarchy\",\n\t\t\t\tnodeId,\n\t\t\t\t\"path:\",\n\t\t\t\tformatPath(nodeId),\n\t\t\t)\n\t\t\tif (nodeDataError) return nodeDataError\n\n\t\t\tconst hierarchyTreeError = check(\n\t\t\t\thierarchy.has(nodeId),\n\t\t\t\t\"node not in hierarchy\",\n\t\t\t\tnodeId,\n\t\t\t\t\"path:\",\n\t\t\t\tformatPath(nodeId),\n\t\t\t)\n\t\t\tif (hierarchyTreeError) return hierarchyTreeError\n\n\t\t\tconst treeNodeError = check(tree.has(nodeId), \"node not in canvas tree\", nodeId, \"path:\", formatPath(nodeId))\n\t\t\tif (treeNodeError) return treeNodeError\n\n\t\t\tconst hierarchyChildren = hierarchy.getChildrenIds(nodeId)\n\t\t\tconst treeChildren = getTreeChildIds(nodeId)\n\t\t\tif (treeChildren instanceof Error) return treeChildren\n\t\t\tif (!treeChildren) return\n\n\t\t\tif (hierarchyChildren.length !== treeChildren.length) {\n\t\t\t\treturn fail(\n\t\t\t\t\t\"Child count mismatch\",\n\t\t\t\t\t\"node:\",\n\t\t\t\t\tnodeId,\n\t\t\t\t\t\"path:\",\n\t\t\t\t\tformatPath(nodeId),\n\t\t\t\t\t\"hierarchyChildren:\",\n\t\t\t\t\tJSON.stringify(hierarchyChildren),\n\t\t\t\t\t\"canvasTreeChildren:\",\n\t\t\t\t\tJSON.stringify(treeChildren),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tfor (let i = 0; i < hierarchyChildren.length; i++) {\n\t\t\t\tconst expected = hierarchyChildren[i]\n\t\t\t\tconst actual = treeChildren[i]\n\t\t\t\tif (!expected) {\n\t\t\t\t\treturn fail(\"Missing child id in hierarchy\", \"node:\", nodeId, \"path:\", formatPath(nodeId), \"index:\", i)\n\t\t\t\t}\n\t\t\t\tif (!actual) {\n\t\t\t\t\treturn fail(\"Missing child id in canvas tree\", \"node:\", nodeId, \"path:\", formatPath(nodeId), \"index:\", i)\n\t\t\t\t}\n\n\t\t\t\tif (expected !== actual) {\n\t\t\t\t\treturn fail(\n\t\t\t\t\t\t\"Child order mismatch\",\n\t\t\t\t\t\t\"node:\",\n\t\t\t\t\t\tnodeId,\n\t\t\t\t\t\t\"path:\",\n\t\t\t\t\t\tformatPath(nodeId),\n\t\t\t\t\t\t\"index:\",\n\t\t\t\t\t\ti,\n\t\t\t\t\t\t\"hierarchyChild:\",\n\t\t\t\t\t\texpected,\n\t\t\t\t\t\t\"canvasTreeChild:\",\n\t\t\t\t\t\tactual,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpath.push(nodeId)\n\t\t\tfor (const childId of hierarchyChildren) {\n\t\t\t\tconst childError = walk(childId)\n\t\t\t\tif (childError) return childError\n\t\t\t}\n\t\t\tpath.pop()\n\t\t}\n\n\t\treturn walk(rootId)\n\t} finally {\n\t\ttree.endAllowPartialScopeAccess()\n\t}\n}\n\nfunction getOffsetAtPosition(position: number, offsetInfo: { offset: number; position: number }) {\n\t// Skipped insert operations require offset of -1\n\t// and during insert, we need to do greater than (>)\n\t// to align with insertion position in array.splice\n\tif (offsetInfo.offset < 0) {\n\t\treturn position > offsetInfo.position ? offsetInfo.offset : 0\n\t}\n\n\t// Skipped removals require offset of +1\n\t// and during remove we need to do greater than\n\t// or equal to (>=) because removing at position\n\t// unlike insert that adds items before the position\n\t// removal removes element from the position that is provided\n\t// to it.\n\treturn position >= offsetInfo.position ? offsetInfo.offset : 0\n}\n", "export function sleep(ms: number): Promise<void> {\n\treturn new Promise(resolve => {\n\t\tsetTimeout(resolve, ms)\n\t})\n}\n", "import { sleep } from \"utils/sleep.ts\"\n\ninterface BeforeUnloadHandler {\n\tcheck: () => boolean\n\teffect?: () => void\n}\n\nconst beforeUnloadHandlers = new Set<BeforeUnloadHandler>()\n\nfunction onBeforeUnload(event: BeforeUnloadEvent) {\n\tfor (const handler of beforeUnloadHandlers) {\n\t\tif (handler.check()) {\n\t\t\thandler.effect?.()\n\t\t\t// If you prevent default behavior in Mozilla Firefox prompt will always be shown\n\t\t\tevent.preventDefault()\n\t\t\t// Chrome requires returnValue to be set. This text is not\n\t\t\t// actually presented in the modal, instead browser will show\n\t\t\t// some generic copy.\n\t\t\tevent.returnValue = \"You have unsaved changes. They might be lost if you leave the page.\"\n\t\t}\n\t}\n}\n\nwindow.addEventListener(\"beforeunload\", onBeforeUnload)\n\n/**\n * Install a handler to execute before unloading the page. Usually to notify\n * the user that there are unsaved changes.\n *\n * - `check` is a pure predicate, called by `hasBeforeUnloadBlockers()` to poll\n *   without side effects and on `beforeunload` to decide whether to block.\n * - `effect` (optional) runs on `beforeunload` only when `check` returns true.\n *\n * If the handler returns true, it will alert the user the browser should not be closed yet.\n */\nexport function addBeforeUnloadHandler(handler: BeforeUnloadHandler, signal?: AbortSignal) {\n\tbeforeUnloadHandlers.add(handler)\n\tsignal?.addEventListener(\"abort\", () => beforeUnloadHandlers.delete(handler))\n}\n\nfunction runBeforeUnloadEffects(): void {\n\tfor (const handler of beforeUnloadHandlers) {\n\t\tif (handler.check()) {\n\t\t\thandler.effect?.()\n\t\t}\n\t}\n}\n\nfunction hasBeforeUnloadBlockers(): boolean {\n\tfor (const handler of beforeUnloadHandlers) {\n\t\tif (handler.check()) return true\n\t}\n\treturn false\n}\n\n/** Waits until all beforeunload handlers are unblocked or the timeout is reached. */\nexport async function waitUntilBeforeUnloadUnblocked({\n\ttimeout = 30_000,\n\tpolling = 50,\n}: { timeout?: number; polling?: number } = {}): Promise<boolean> {\n\trunBeforeUnloadEffects()\n\n\tconst deadline = Date.now() + timeout\n\twhile (Date.now() < deadline) {\n\t\tif (!hasBeforeUnloadBlockers()) return true\n\t\tawait sleep(polling)\n\t}\n\n\treturn false\n}\n", "import { assert } from \"@framerjs/shared\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\n\ninterface AncestorArrayItem {\n\ttype: ControlType.Array\n\tid: string\n}\n\ninterface AncestorObjectProp {\n\ttype: ControlType.Object\n\tkey: string\n}\n\ntype AncestorControl = AncestorArrayItem | AncestorObjectProp\n\nexport function addObjectPropToKeyPath(currentKeyPath: string | undefined, objectKey: string): string {\n\treturn `${currentKeyPath ?? \"\"}.${objectKey}`\n}\n\nexport function addArrayItemIdToKeyPath(currentKeyPath: string | undefined, itemId: string): string {\n\treturn `${currentKeyPath ?? \"\"}[${itemId}]`\n}\n\n/** Meant for updating nested control props within objects and arrays. */\nexport function getAncestorControlsForKeyPath(ancestorControlKeyPath: string): AncestorControl[] {\n\tconst result: AncestorControl[] = []\n\n\tconst objectSegments = ancestorControlKeyPath.split(\".\")\n\n\tfor (const objectSegment of objectSegments) {\n\t\tconst [objectKey, optionalArraySegment] = objectSegment.split(\"[\")\n\t\tif (objectKey.length !== 0) {\n\t\t\tresult.push({ type: ControlType.Object, key: objectKey })\n\t\t}\n\t\tif (optionalArraySegment) {\n\t\t\tconst itemId = optionalArraySegment.slice(0, -1)\n\t\t\tassert(itemId.length > 0)\n\t\t\tresult.push({ type: ControlType.Array, id: itemId })\n\t\t}\n\t}\n\n\treturn result\n}\n", "import { getHTMLTextContentCached } from \"./getHTMLTextContent.ts\"\n\nexport function getWordCount(value: string, isHTML: boolean = false): number {\n\tconst text = (isHTML ? getHTMLTextContentCached(value) : value).trim()\n\tif (text === \"\") return 0\n\treturn text.split(/\\W+\\b/).length\n}\n", "import type {\n\tCanvasNode,\n\tCollectionItemNode,\n\tCollectionNode,\n\tLoadedLayoutTemplateNode,\n\tLoadedSmartComponentNode,\n\tLoadedWebPageNode,\n\tRootNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type { RouteSegmentNode } from \"document/models/CanvasTree/nodes/RouteSegmentNode.ts\"\nimport {\n\tisCollectionItemNode,\n\tisCollectionNode,\n\tisLayoutTemplateNode,\n\tisRootNode,\n\tisRouteSegmentNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\n\nexport type CanvasLocalizationScope = LoadedSmartComponentNode | LoadedWebPageNode | LoadedLayoutTemplateNode\n\nexport type LocalizationScope =\n\t| CanvasLocalizationScope\n\t| CollectionNode\n\t| CollectionItemNode\n\t| RootNode\n\t| RouteSegmentNode\n\nexport function isCanvasLocalizationScope<T extends CanvasNode>(node: T): node is T & CanvasLocalizationScope {\n\treturn isSmartComponentNode(node) || isWebPageNode(node) || isLayoutTemplateNode(node)\n}\n\nexport function isLocalizationScope<T extends CanvasNode>(node: T): node is T & LocalizationScope {\n\treturn (\n\t\tisCanvasLocalizationScope(node) ||\n\t\tisCollectionNode(node) ||\n\t\tisCollectionItemNode(node) ||\n\t\tisRootNode(node) ||\n\t\tisRouteSegmentNode(node)\n\t)\n}\n", "import type { VerifiedArrayControlDescription } from \"@framerjs/framer-runtime\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { countAndNoun } from \"utils/countAndNoun.ts\"\nimport { isGalleryControl } from \"./arrayGalleryUtils.ts\"\n\nexport function getRequiredFieldWarningMessage(title: string | undefined) {\n\treturn `${title ?? Dictionary.Field} is required`\n}\n\nexport function getMaxLengthWarningMessage(currentLength: number, maxLength: number) {\n\treturn `Exceeded max length by ${countAndNoun(currentLength - maxLength, \"character\", \"characters\")}`\n}\n\nexport function getMinCountWarningMessage(control: VerifiedArrayControlDescription) {\n\treturn `Must have at least ${control.minCount} ${getTypeName(control)}`\n}\n\nexport function getMaxCountWarningMessage(control: VerifiedArrayControlDescription) {\n\treturn `Must have at most ${control.maxCount} ${getTypeName(control)}`\n}\n\nexport const slugTakenWarningMessage = \"Slug value is already taken and must be unique\"\n\nfunction getTypeName(control: VerifiedArrayControlDescription) {\n\treturn isGalleryControl(control) ? \"images\" : \"items\"\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assertNever } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { convertIdPathVariablesToReadable } from \"document/components/utils/convertIdPathVariablesToReadable.ts\"\nimport { getRawWebPagePath } from \"document/components/utils/getWebPagePath.ts\"\nimport type { AnyWebPageNode, CanvasTree, CollectionItemNode } from \"document/models/CanvasTree/index.ts\"\nimport type { RouteSegmentNode } from \"document/models/CanvasTree/nodes/RouteSegmentNode.ts\"\nimport { getRouteSegmentRootNode } from \"document/models/CanvasTree/nodes/RouteSegmentRootNode.utils.ts\"\nimport {\n\tisCollectionItemNode,\n\tisCollectionNode,\n\tisLayoutTemplateNode,\n\tisRootNode,\n\tisRouteSegmentNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { getCollectionItemName } from \"utils/collectionUtils.ts\"\nimport { getPathForDisplay } from \"web/pages/projects/components/Domains/validation/validateRouteNode.ts\"\nimport type { LocalizationScope } from \"../QuickActions/utils/LocalizationScope.ts\"\n\nexport function getTitleForRouteSegment(routeSegment: RouteSegmentNode, tree: CanvasTree): string {\n\tconst result = getRouteSegmentRootNode(tree).getRouteSegmentIdToRawPathMap(tree).get(routeSegment.id)\n\treturn result ? getPathForDisplay(result) : Dictionary.Unknown\n}\n\nfunction getTitleForWebPage(webPage: AnyWebPageNode, tree: CanvasTree, componentLoader: ComponentLoader): string {\n\tconst isHomePage = webPage.id === tree.root.homePageNodeId\n\tif (isHomePage) return Dictionary.Home\n\n\tconst pagePath = getRawWebPagePath(tree, webPage)\n\tif (!pagePath) return Dictionary.Unknown\n\n\tconst dataIdentifier = webPage.dataIdentifier\n\tif (!dataIdentifier) return getPathForDisplay(pagePath)\n\n\tconst data = componentLoader.dataForIdentifier(dataIdentifier)\n\treturn data ? getPathForDisplay(convertIdPathVariablesToReadable(data, pagePath)) : getPathForDisplay(pagePath)\n}\n\nfunction getTitleForCollectionItem(collectionItem: CollectionItemNode, tree: CanvasTree): string {\n\tconst collection = tree.getParent(collectionItem.id)\n\tif (!isCollectionNode(collection)) return Dictionary.Unknown\n\n\treturn getCollectionItemName(collection, collectionItem) ?? Dictionary.Unknown\n}\n\nexport function getTitleForLocalizationScope(\n\tlocalizationScope: LocalizationScope,\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n) {\n\tif (isRootNode(localizationScope)) return Dictionary.Site\n\tif (isRouteSegmentNode(localizationScope)) return getTitleForRouteSegment(localizationScope, tree)\n\tif (isCollectionNode(localizationScope)) return localizationScope.resolveValue(\"name\") || Dictionary.Unknown\n\tif (isCollectionItemNode(localizationScope)) {\n\t\treturn getTitleForCollectionItem(localizationScope, tree) || Dictionary.Unknown\n\t}\n\tif (isWebPageNode(localizationScope)) return getTitleForWebPage(localizationScope, tree, componentLoader)\n\tif (isSmartComponentNode(localizationScope)) return localizationScope.resolveValue(\"name\") || Dictionary.Unknown\n\tif (isLayoutTemplateNode(localizationScope)) return localizationScope.resolveValue(\"name\") || Dictionary.Unknown\n\n\tassertNever(localizationScope, \"Invalid localization scope\")\n}\n", "import { parseHTML } from \"utils/parseHTML.ts\"\n\nexport function removeStylesFromRichText(html: string) {\n\tconst container = parseHTML(html)\n\n\tfor (const element of container.querySelectorAll(\"*\")) {\n\t\t// We ignore <br class=\"trailing-break\"> tags when parsing the HTML into\n\t\t// a ProseMirror document. If we remove the class, ProseMirror will add\n\t\t// another <br> tag after them, causing double empty new lines.\n\t\tif (element.tagName === \"BR\") continue\n\t\telement.removeAttribute(\"class\")\n\t\telement.removeAttribute(\"style\")\n\t\telement.removeAttribute(\"data-styles-preset\")\n\t}\n\n\treturn container.innerHTML\n}\n", "import type { ComponentLoader, VerifiedPropertyControls } from \"@framerjs/framer-runtime\"\nimport { assert, stableStringify } from \"@framerjs/shared\"\nimport {\n\ttype ControlProp,\n\ttype ControlProps,\n\tisStaticArrayControlProp,\n\twithId,\n} from \"document/models/controlProps/ControlProp.ts\"\nimport {\n\ttype RawControlProp,\n\ttype RawControlProps,\n\tisRawControlProp,\n} from \"document/models/controlProps/RawControlProp.ts\"\nimport { controlsWithAutoVariantOption } from \"document/models/controlProps/controlsWithAutoVariantOption.ts\"\nimport { filterComponentPresetControls } from \"document/models/controlProps/filterComponentPresetControls.ts\"\nimport { getControlProps } from \"document/models/controlProps/getControlProps.ts\"\nimport type { RichTextDocument } from \"document/models/richText/RichTextDocument.ts\"\nimport { parseRichTextHtmlToDocument } from \"document/models/richText/richTextHtmlParser.ts\"\nimport { getHTMLFromRichTextTreeValue } from \"document/models/richText/richTextPmAdapter.ts\"\nimport { isRichTextTreeValue } from \"document/models/richText/richTextStorage.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { fullSchemaParams, makeSchema } from \"prosemirror/schema/index.ts\"\nimport { mapItemsWithStructuralSharing } from \"utils/collectionUtils.ts\"\nimport { parseHTML } from \"utils/parseHTML.ts\"\nimport { isObject, isString } from \"utils/typeChecks.ts\"\nimport {\n\taddArrayItemIdToKeyPath,\n\taddObjectPropToKeyPath,\n\tgetAncestorControlsForKeyPath,\n} from \"./ancestorControlKeyPath.ts\"\n\nconst moduleTagSelector = \"framer-module[data-module-identifier]\"\nconst moduleControlTextTag = \"framer-module-translation-text\"\nconst moduleControlRichTextTag = \"framer-module-translation-richtext\"\nconst moduleControlKeyAttribute = \"data-module-control-key\"\nconst moduleControlAncestorPathAttribute = \"data-module-control-ancestor-path\"\nconst moduleControlStorageTypeAttribute = \"data-module-control-storage-type\"\nconst richTextSchema = makeSchema(fullSchemaParams)\n\ntype RichTextStorageType = \"html\" | \"json\"\ntype TranslatedControlPropValue = string | RichTextDocument\ninterface TranslatableModuleControlValue {\n\tcontrolPropKey: string\n\tancestorControlKeyPath: string | undefined\n\ttagName: typeof moduleControlTextTag | typeof moduleControlRichTextTag\n\tstorageType: RichTextStorageType | undefined\n\tvalue: string\n}\n\nclass RichTextModuleTranslationError extends Error {\n\toverride name = \"RichTextModuleTranslationError\"\n}\n\nexport function isRichTextModuleTranslationError(error: unknown): error is RichTextModuleTranslationError {\n\treturn error instanceof RichTextModuleTranslationError\n}\n\n/**\n * Returns a stable digest of translatable values resolved from modules in `html` (including values\n * that come from component defaults). Intended to be mixed into the rich text content hash so it\n * changes when a component's translatable value changes. Returns an empty string when there are no\n * module translatable values to contribute.\n */\nexport function getRichTextModuleTranslatableDigest(html: string, componentLoader: ComponentLoader): string {\n\tconst container = parseHTML(html)\n\tconst moduleElements = container.querySelectorAll(moduleTagSelector)\n\tif (moduleElements.length === 0) return \"\"\n\n\tconst entries: TranslatableModuleControlValue[][] = []\n\n\tfor (const moduleElement of moduleElements) {\n\t\tconst identifier = moduleElement.getAttribute(\"data-module-identifier\")\n\t\tif (!isString(identifier)) continue\n\n\t\tconst serializedProps = moduleElement.getAttribute(\"data-module-props\")\n\t\tif (!isString(serializedProps)) continue\n\n\t\tlet rawControlProps: RawControlProps | undefined\n\t\ttry {\n\t\t\trawControlProps = JSON.parse(serializedProps)\n\t\t} catch {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!rawControlProps) continue\n\n\t\tconst controls = getModuleControlsForTranslation(identifier, componentLoader)\n\t\tif (!controls) continue\n\n\t\tconst controlProps = getControlProps(controls, rawControlProps)\n\t\tconst translatableValues: TranslatableModuleControlValue[] = []\n\t\tcollectTranslatableModuleControlValues(controlProps, controls, translatableValues, { suppressGeneratedIds: true })\n\n\t\tif (translatableValues.length === 0) continue\n\n\t\t// Ensure that the the hashing can be stable even if things are reordered\n\t\ttranslatableValues.sort(compareTranslatableModuleControlValues)\n\t\tentries.push(translatableValues)\n\t}\n\n\treturn entries.length === 0 ? \"\" : stableStringify(entries)\n}\n\nfunction compareTranslatableModuleControlValues(\n\tleft: TranslatableModuleControlValue,\n\tright: TranslatableModuleControlValue,\n): number {\n\treturn (\n\t\tcompareNullableStrings(left.controlPropKey, right.controlPropKey) ||\n\t\tcompareNullableStrings(left.ancestorControlKeyPath, right.ancestorControlKeyPath) ||\n\t\t// Probably not necessary, but useful for a tiebreaker just in case\n\t\tcompareNullableStrings(left.tagName, right.tagName) ||\n\t\tcompareNullableStrings(left.storageType, right.storageType)\n\t)\n}\n\nfunction compareNullableStrings(left: string | undefined, right: string | undefined): number {\n\tconst safeLeft = left ?? \"\"\n\tconst safeRight = right ?? \"\"\n\tif (safeLeft < safeRight) return -1\n\tif (safeLeft > safeRight) return 1\n\treturn 0\n}\n\nexport function prepareRichTextModulesForTranslation(html: string, componentLoader: ComponentLoader): string {\n\tconst container = parseHTML(html)\n\tconst moduleElements = container.querySelectorAll(moduleTagSelector)\n\n\tfor (const moduleElement of moduleElements) {\n\t\tconst identifier = moduleElement.getAttribute(\"data-module-identifier\")\n\t\tif (!isString(identifier)) continue\n\n\t\tconst serializedProps = moduleElement.getAttribute(\"data-module-props\")\n\t\tif (!isString(serializedProps)) continue\n\n\t\tlet rawControlProps: RawControlProps | undefined\n\t\ttry {\n\t\t\trawControlProps = JSON.parse(serializedProps)\n\t\t} catch {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!rawControlProps) continue\n\n\t\tconst controls = getModuleControlsForTranslation(identifier, componentLoader)\n\t\tif (!controls) continue\n\n\t\tconst controlProps = getControlProps(controls, rawControlProps)\n\t\tconst translatableValues: TranslatableModuleControlValue[] = []\n\t\tcollectTranslatableModuleControlValues(controlProps, controls, translatableValues)\n\n\t\tfor (const translatableValue of translatableValues) {\n\t\t\tconst translationElement = container.ownerDocument.createElement(translatableValue.tagName)\n\t\t\ttranslationElement.setAttribute(moduleControlKeyAttribute, translatableValue.controlPropKey)\n\t\t\tif (translatableValue.ancestorControlKeyPath) {\n\t\t\t\ttranslationElement.setAttribute(moduleControlAncestorPathAttribute, translatableValue.ancestorControlKeyPath)\n\t\t\t}\n\t\t\tif (translatableValue.storageType) {\n\t\t\t\ttranslationElement.setAttribute(moduleControlStorageTypeAttribute, translatableValue.storageType)\n\t\t\t}\n\n\t\t\tif (translatableValue.tagName === moduleControlRichTextTag) {\n\t\t\t\ttranslationElement.innerHTML = translatableValue.value\n\t\t\t} else {\n\t\t\t\ttranslationElement.textContent = translatableValue.value\n\t\t\t}\n\n\t\t\tmoduleElement.append(translationElement)\n\t\t}\n\t}\n\n\treturn container.innerHTML\n}\n\nexport function hydrateTranslatedRichTextModules(\n\thtml: string,\n\tcomponentLoader: ComponentLoader,\n\t{ strict = true }: { strict?: boolean } = {},\n): string {\n\tconst container = parseHTML(html)\n\tconst moduleElements = container.querySelectorAll(moduleTagSelector)\n\n\tfor (const moduleElement of moduleElements) {\n\t\tconst identifier = moduleElement.getAttribute(\"data-module-identifier\")\n\t\tif (!isString(identifier)) continue\n\n\t\tconst serializedProps = moduleElement.getAttribute(\"data-module-props\")\n\t\tif (!isString(serializedProps)) continue\n\n\t\tconst translationElements = Array.from(\n\t\t\tmoduleElement.querySelectorAll<Element>(`${moduleControlTextTag}, ${moduleControlRichTextTag}`),\n\t\t)\n\t\tif (translationElements.length === 0) continue\n\n\t\tlet rawControlProps: RawControlProps | undefined\n\t\ttry {\n\t\t\trawControlProps = JSON.parse(serializedProps)\n\t\t} catch {\n\t\t\tif (!strict) continue\n\t\t\tthrow new RichTextModuleTranslationError(\"Translated module props are no longer valid JSON.\")\n\t\t}\n\n\t\tif (!rawControlProps) continue\n\n\t\tconst controls = getModuleControlsForTranslation(identifier, componentLoader)\n\t\tif (!controls) continue\n\n\t\tlet updatedRawControlProps: RawControlProps = rawControlProps\n\n\t\tfor (const translationElement of translationElements) {\n\t\t\tif (translationElement.parentElement !== moduleElement) {\n\t\t\t\tif (!strict) continue\n\t\t\t\tthrow new RichTextModuleTranslationError(\n\t\t\t\t\t\"Translated module controls must remain direct children of the module element.\",\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst controlPropKey = translationElement.getAttribute(moduleControlKeyAttribute)\n\t\t\tif (!isString(controlPropKey) || controlPropKey.length === 0) {\n\t\t\t\tif (!strict) continue\n\t\t\t\tthrow new RichTextModuleTranslationError(\"Translated module control key is missing or invalid.\")\n\t\t\t}\n\n\t\t\tconst ancestorControlKeyPath = translationElement.getAttribute(moduleControlAncestorPathAttribute) ?? undefined\n\n\t\t\tconst tagName = translationElement.tagName.toLowerCase()\n\t\t\tconst isRichText = tagName === moduleControlRichTextTag\n\n\t\t\tif (isRichText) {\n\t\t\t\tconst storageType = parseRichTextStorage(translationElement.getAttribute(moduleControlStorageTypeAttribute))\n\t\t\t\tif (!storageType) {\n\t\t\t\t\tif (!strict) continue\n\t\t\t\t\tthrow new RichTextModuleTranslationError(\n\t\t\t\t\t\t\"Translated rich text module control storage type is missing or invalid.\",\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tupdatedRawControlProps = updateControlPropsValueAtPath(\n\t\t\t\t\tupdatedRawControlProps,\n\t\t\t\t\tcontrolPropKey,\n\t\t\t\t\tancestorControlKeyPath,\n\t\t\t\t\tserializeTranslatedRichTextValue(translationElement.innerHTML, storageType),\n\t\t\t\t\tControlType.RichText,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tupdatedRawControlProps = updateControlPropsValueAtPath(\n\t\t\t\t\tupdatedRawControlProps,\n\t\t\t\t\tcontrolPropKey,\n\t\t\t\t\tancestorControlKeyPath,\n\t\t\t\t\ttranslationElement.textContent,\n\t\t\t\t\tControlType.String,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\ttranslationElement.remove()\n\t\t}\n\n\t\tif (updatedRawControlProps !== rawControlProps) {\n\t\t\tmoduleElement.setAttribute(\"data-module-props\", JSON.stringify(updatedRawControlProps))\n\t\t}\n\t}\n\n\treturn container.innerHTML\n}\n\nfunction collectTranslatableModuleControlValues(\n\tcontrolProps: ControlProps,\n\tcontrols: Readonly<Record<string, ControlDescription>>,\n\tresult: TranslatableModuleControlValue[],\n\t{ suppressGeneratedIds = false }: { suppressGeneratedIds?: boolean } = {},\n) {\n\tfor (const [key, controlProp] of Object.entries(controlProps)) {\n\t\tif (!controlProp) continue\n\t\tconst control = controls[key]\n\t\tif (!control) continue\n\n\t\tcollectTranslatableModuleControlValue(key, controlProp, control, undefined, result, suppressGeneratedIds)\n\t}\n}\n\nfunction collectTranslatableModuleControlValue(\n\tcontrolKey: string,\n\tcontrolProp: ControlProp,\n\tcontrol: ControlDescription,\n\tancestorControlKeyPath: string | undefined,\n\tresult: TranslatableModuleControlValue[],\n\tsuppressGeneratedIds: boolean,\n): void {\n\tswitch (control.type) {\n\t\tcase ControlType.Array: {\n\t\t\tif (!isStaticArrayControlProp(controlProp)) return\n\n\t\t\tfor (const item of controlProp.value) {\n\t\t\t\tif (!withId(item)) continue\n\t\t\t\tcollectTranslatableModuleControlValue(\n\t\t\t\t\tcontrolKey,\n\t\t\t\t\titem,\n\t\t\t\t\tcontrol.control,\n\t\t\t\t\tgetArrayItemAncestorControlKeyPath(ancestorControlKeyPath, item.id, suppressGeneratedIds),\n\t\t\t\t\tresult,\n\t\t\t\t\tsuppressGeneratedIds,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcase ControlType.Object: {\n\t\t\tif (controlProp.type !== ControlType.Object || !isObject(controlProp.value)) return\n\n\t\t\tfor (const [key, childControlProp] of Object.entries(controlProp.value)) {\n\t\t\t\tconst childControl = control.controls[key]\n\t\t\t\tif (!childControl) continue\n\n\t\t\t\tcollectTranslatableModuleControlValue(\n\t\t\t\t\tcontrolKey,\n\t\t\t\t\tchildControlProp,\n\t\t\t\t\tchildControl,\n\t\t\t\t\taddObjectPropToKeyPath(ancestorControlKeyPath, key),\n\t\t\t\t\tresult,\n\t\t\t\t\tsuppressGeneratedIds,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcase ControlType.String: {\n\t\t\tif (control.preventLocalization) return\n\t\t\tif (controlProp.type !== ControlType.String || !isString(controlProp.value) || controlProp.value.length === 0) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresult.push({\n\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\tancestorControlKeyPath,\n\t\t\t\ttagName: moduleControlTextTag,\n\t\t\t\tstorageType: undefined,\n\t\t\t\tvalue: controlProp.value,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tcase ControlType.RichText: {\n\t\t\tif (control.preventLocalization) return\n\t\t\tif (controlProp.type !== ControlType.RichText || !isRichTextTreeValue(controlProp.value)) return\n\n\t\t\tconst storageType = typeof controlProp.value === \"string\" ? \"html\" : \"json\"\n\t\t\tconst value =\n\t\t\t\ttypeof controlProp.value === \"string\"\n\t\t\t\t\t? controlProp.value\n\t\t\t\t\t: getHTMLFromRichTextTreeValue(controlProp.value, richTextSchema)\n\n\t\t\tif (value.length === 0) return\n\n\t\t\tresult.push({\n\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\tancestorControlKeyPath,\n\t\t\t\ttagName: moduleControlRichTextTag,\n\t\t\t\tstorageType,\n\t\t\t\tvalue,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tdefault:\n\t\t\treturn\n\t}\n}\n\n// Ensure that if we need to compare content for hashing we don't include random ids\nfunction getArrayItemAncestorControlKeyPath(\n\tcurrentKeyPath: string | undefined,\n\titemId: string,\n\tsuppressGeneratedIds: boolean,\n): string {\n\tif (suppressGeneratedIds) return `${currentKeyPath ?? \"\"}[]`\n\treturn addArrayItemIdToKeyPath(currentKeyPath, itemId)\n}\n\nfunction parseRichTextStorage(value: unknown): RichTextStorageType | null {\n\tif (value === \"html\" || value === \"json\") return value\n\treturn null\n}\n\nfunction getModuleControlsForTranslation(\n\tidentifier: string,\n\tcomponentLoader: ComponentLoader,\n): VerifiedPropertyControls | null {\n\tconst component = componentLoader.reactComponentForIdentifier(identifier)\n\tif (!component) return null\n\n\treturn controlsWithAutoVariantOption(filterComponentPresetControls(component, \"onlyNonPresets\"))\n}\n\nfunction serializeTranslatedRichTextValue(value: string, storageType: RichTextStorageType): string | RichTextDocument {\n\tif (storageType === \"json\") {\n\t\treturn parseRichTextHtmlToDocument(value, \"collectionControlPropLocalized\")\n\t}\n\n\treturn value\n}\n\nfunction updateControlPropsValueAtPath(\n\trawControlProps: RawControlProps,\n\tcontrolPropKey: string,\n\tancestorControlKeyPath: string | undefined,\n\tvalue: TranslatedControlPropValue,\n\tcontrolType: ControlType.String | ControlType.RichText,\n): RawControlProps {\n\tconst rootControlProp = rawControlProps[controlPropKey]\n\n\t// The control uses a component default and isn't stored in the raw props yet.\n\t// Create the entry (with any nested structure the ancestor path requires) so the\n\t// translated value can be persisted.\n\tif (!rootControlProp) {\n\t\tif (!ancestorControlKeyPath) {\n\t\t\treturn { ...rawControlProps, [controlPropKey]: { type: controlType, value } }\n\t\t}\n\t\tconst ancestors = getAncestorControlsForKeyPath(ancestorControlKeyPath)\n\t\treturn { ...rawControlProps, [controlPropKey]: createControlPropForPath(ancestors, controlType, value) }\n\t}\n\n\tconst updatedRootControlProp = updateControlPropValueAtPath(\n\t\trootControlProp,\n\t\tancestorControlKeyPath,\n\t\tvalue,\n\t\tcontrolType,\n\t)\n\tif (updatedRootControlProp === rootControlProp) return rawControlProps\n\n\treturn { ...rawControlProps, [controlPropKey]: updatedRootControlProp }\n}\n\n/** Builds a minimal RawControlProp tree for the given ancestor path with a leaf value. */\nfunction createControlPropForPath(\n\tancestorControls: ReturnType<typeof getAncestorControlsForKeyPath>,\n\tcontrolType: ControlType.String | ControlType.RichText,\n\tvalue: TranslatedControlPropValue,\n): RawControlProp {\n\tif (ancestorControls.length === 0) {\n\t\treturn { type: controlType, value }\n\t}\n\n\tconst [ancestor, ...rest] = ancestorControls\n\tassert(ancestor)\n\tconst childProp = createControlPropForPath(rest, controlType, value)\n\n\tif (ancestor.type === ControlType.Array) {\n\t\treturn { type: ControlType.Array, value: [{ ...childProp, id: ancestor.id }] }\n\t}\n\n\treturn { type: ControlType.Object, value: { [ancestor.key]: childProp } }\n}\n\nfunction updateControlPropValueAtPath(\n\tcontrolProp: RawControlProp,\n\tancestorControlKeyPath: string | undefined,\n\tvalue: TranslatedControlPropValue,\n\tcontrolType: ControlType.String | ControlType.RichText,\n): RawControlProp {\n\tif (!ancestorControlKeyPath) {\n\t\treturn updateTranslatableLeafControlPropValue(controlProp, value, controlType)\n\t}\n\n\treturn updateControlPropValueAtAncestorControls(\n\t\tcontrolProp,\n\t\tgetAncestorControlsForKeyPath(ancestorControlKeyPath),\n\t\tvalue,\n\t\tcontrolType,\n\t)\n}\n\nfunction updateControlPropValueAtAncestorControls(\n\tcontrolProp: RawControlProp,\n\tancestorControls: ReturnType<typeof getAncestorControlsForKeyPath>,\n\tvalue: TranslatedControlPropValue,\n\tcontrolType: ControlType.String | ControlType.RichText,\n): RawControlProp {\n\tconst [ancestorControl, ...rest] = ancestorControls\n\tif (!ancestorControl) {\n\t\treturn updateTranslatableLeafControlPropValue(controlProp, value, controlType)\n\t}\n\n\tif (ancestorControl.type === ControlType.Array) {\n\t\tif ((controlProp.type !== ControlType.Array && controlProp.type !== null) || !Array.isArray(controlProp.value)) {\n\t\t\treturn controlProp\n\t\t}\n\n\t\tconst items = controlProp.value\n\t\tlet found = false\n\t\tlet updated = false\n\t\tconst nextValue = mapItemsWithStructuralSharing(items, item => {\n\t\t\tif (!isRawControlProp(item) || !withId(item) || item.id !== ancestorControl.id) return item\n\n\t\t\tfound = true\n\t\t\tconst updatedItem = updateControlPropValueAtAncestorControls(item, rest, value, controlType)\n\t\t\tupdated ||= updatedItem !== item\n\t\t\treturn updatedItem\n\t\t})\n\n\t\t// Legacy raw array items without ids can't be matched reliably during hydration, so drop\n\t\t// their translated value instead of appending a duplicate item.\n\t\tif (!found && items.some(item => isRawControlProp(item) && !withId(item))) {\n\t\t\treturn controlProp\n\t\t}\n\n\t\t// Item doesn't exist yet (using component default). Append a new entry.\n\t\tif (!found) {\n\t\t\tconst newItem = createControlPropForPath(rest, controlType, value)\n\t\t\treturn { ...controlProp, value: [...items, { ...newItem, id: ancestorControl.id }] }\n\t\t}\n\n\t\treturn updated ? { ...controlProp, value: nextValue } : controlProp\n\t}\n\n\tif ((controlProp.type !== ControlType.Object && controlProp.type !== null) || !isObject(controlProp.value)) {\n\t\treturn controlProp\n\t}\n\n\tconst childControlProp = controlProp.value[ancestorControl.key]\n\n\t// Child doesn't exist yet (using component default). Create the nested structure.\n\tif (!isRawControlProp(childControlProp)) {\n\t\tconst newChild = createControlPropForPath(rest, controlType, value)\n\t\treturn {\n\t\t\t...controlProp,\n\t\t\tvalue: { ...controlProp.value, [ancestorControl.key]: newChild },\n\t\t}\n\t}\n\n\tconst updatedChildControlProp = updateControlPropValueAtAncestorControls(childControlProp, rest, value, controlType)\n\tif (updatedChildControlProp === childControlProp) return controlProp\n\n\treturn {\n\t\t...controlProp,\n\t\tvalue: {\n\t\t\t...controlProp.value,\n\t\t\t[ancestorControl.key]: updatedChildControlProp,\n\t\t},\n\t}\n}\n\nfunction updateTranslatableLeafControlPropValue(\n\tcontrolProp: RawControlProp,\n\tvalue: TranslatedControlPropValue,\n\tcontrolType: ControlType.String | ControlType.RichText,\n): RawControlProp {\n\t// Match the expected control type or legacy null type (pre-type-system documents).\n\tif (controlProp.type !== controlType && controlProp.type !== null) return controlProp\n\n\tif (controlType === ControlType.String) {\n\t\treturn typeof value === \"string\" && controlProp.value !== value\n\t\t\t? { ...controlProp, type: controlType, value }\n\t\t\t: controlProp\n\t}\n\n\treturn controlProp.value !== value ? { ...controlProp, type: controlType, value } : controlProp\n}\n", "import type { ComponentLoader, DataDefinition } from \"@framerjs/framer-runtime\"\nimport type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { assert, assertNever, murmurHash, shouldBeNever } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { experiments } from \"app/experiments.ts\"\nimport { getDefaultWebPageTitle } from \"code-generation/components/generateMetadataModule.ts\"\nimport { getScopeTypeForScope } from \"document/base-engine/BaseScopeStore.ts\"\nimport { getDefaultName } from \"document/components/utils/nodes.ts\"\nimport { pathToName } from \"document/components/utils/pathToName.ts\"\nimport {\n\ttype CanvasNode,\n\ttype CanvasTree,\n\ttype CollectionItemNode,\n\ttype CollectionNode,\n\ttype ContentManagementNode,\n\ttype FrameNode,\n\ttype NodeID,\n\ttype RichTextNode,\n\ttype RootNode,\n\ttype SVGNode,\n\ttype ShallowWebPageNode,\n\ttype ShapeContainerNode,\n\tisScopeNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type {\n\tNotDependentOnComponentLoader,\n\tNotDependentOnParentVariables,\n\tSourceGroupCache,\n\tTranslatePagePathSettings,\n} from \"document/models/CanvasTree/nodes/CanvasNodeCache.ts\"\nimport {\n\tnotDependentOnComponentLoader,\n\tnotDependentOnParentVariables,\n} from \"document/models/CanvasTree/nodes/CanvasNodeCache.ts\"\nimport type { RouteSegmentNode } from \"document/models/CanvasTree/nodes/RouteSegmentNode.ts\"\nimport type { RouteSegmentRootNode } from \"document/models/CanvasTree/nodes/RouteSegmentRootNode.ts\"\nimport { checkShouldSegmentBeLocalized } from \"document/models/CanvasTree/nodes/RouteSegmentRootNode.utils.ts\"\nimport type { FormPlainTextInputNode } from \"document/models/CanvasTree/nodes/forms/FormPlainTextInputNode.ts\"\nimport type { FormSelectNode } from \"document/models/CanvasTree/nodes/forms/FormSelectNode.ts\"\nimport {\n\tisCodeComponentNode,\n\tisContentManagementNode,\n\tisFormPlainTextInputNode,\n\tisFormSelectNode,\n\tisFrameNode,\n\tisLayoutTemplateNode,\n\tisRichTextNode,\n\tisRootNode,\n\tisRouteSegmentNode,\n\tisRouteSegmentRootNode,\n\tisSVGNode,\n\tisShapeContainerNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { ComputedValue } from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport {\n\tisComputedValue,\n\tisComputedValueFromVariableReference,\n\tisComputedValueOutputType,\n} from \"document/models/CanvasTree/traits/ComputedValue.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport type {\n\tConvertFromBooleanOutputValueType,\n\tValueTransformConvertFromBoolean,\n\tValueTransformConvertFromEnum,\n\tValueTransformName,\n} from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport { isValueTransform } from \"document/models/CanvasTree/traits/ValueTransform.ts\"\nimport type { VariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { isVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport { fallbackAltText } from \"document/models/CanvasTree/traits/WithAltText.ts\"\nimport { withCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport type { WithControlProps } from \"document/models/CanvasTree/traits/WithControlProps.ts\"\nimport { hasImageFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { hasLayoutTemplate } from \"document/models/CanvasTree/traits/WithLayoutTemplate.ts\"\nimport type { IncludedLocales } from \"document/models/CanvasTree/traits/WithLocaleConfig.ts\"\nimport { withLocaleConfig } from \"document/models/CanvasTree/traits/WithLocaleConfig.ts\"\nimport type { Locale, LocaleId } from \"document/models/CanvasTree/traits/WithLocales.ts\"\nimport { defaultLocaleId } from \"document/models/CanvasTree/traits/WithLocales.ts\"\nimport { isReplicaChild } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type {\n\tEnumVariableCase,\n\tEnumVariableDefinition,\n\tLinkVariableDefinition,\n\tNodePropertyControlReferenceVariableDefinition,\n\tRichTextVariableDefinition,\n\tStringVariableDefinition,\n\tVariableDefinition,\n\tVariableID,\n\tVariableOrDivider,\n\tVariableType,\n\tVariablesAndDividers,\n\tWithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport {\n\thasAssociatedStringVariable,\n\tisOptionalVariable,\n\tisPreventingLocalization,\n\tisVariableDefinition,\n\twithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isLinkToURL } from \"document/models/CanvasTree/traits/utils/Link.ts\"\nimport type {\n\tLocalizedTextValue,\n\tLocalizedValue,\n\tLocalizedValues,\n\tNonNullLocalizedValue,\n} from \"document/models/LocalizedValue.ts\"\nimport { getLocalizedValueText, isNonNullLocalizedValue } from \"document/models/LocalizedValue.ts\"\nimport type { ControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { isObjectControlProp } from \"document/models/controlProps/ControlProp.ts\"\nimport { prefixControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport type { RichTextDocument } from \"document/models/richText/RichTextDocument.ts\"\nimport { getRichTextTreeValueHash } from \"document/models/richText/richTextHash.ts\"\nimport type { RichTextTreeValue } from \"document/models/richText/richTextStorage.ts\"\nimport { isRichTextTreeValue } from \"document/models/richText/richTextStorage.ts\"\nimport { getPlainTextFromRichTextTreeValue } from \"document/models/richText/richTextStorageDocument.ts\"\nimport { localeVariableId } from \"document/utils/LocaleVariable.ts\"\nimport type { ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport type { RelativeNumber } from \"library/render/types/RelativeNumber.ts\"\nimport { isRelativeNumber } from \"library/render/types/RelativeNumber.ts\"\nimport { isEqual } from \"library/render/utils/isEqual.ts\"\nimport type { Locale as RouterLocale } from \"library/router/types.ts\"\nimport { getCollectionItemName } from \"utils/collectionUtils.ts\"\nimport { getRouterLocales } from \"utils/getRouterLocales.ts\"\nimport { isEmptyRichTextValue } from \"utils/isEmptyRichTextValue.ts\"\nimport { isKeySetAndNotInherited } from \"utils/isKeySetAndNotInherited.ts\"\nimport { isShallowEqual } from \"utils/isShallowEqual.ts\"\nimport { memoizeOne } from \"utils/memoizeOne.ts\"\nimport { titleCase } from \"utils/titleCase.ts\"\nimport { isNull, isNullish, isNumber, isObject, isReadonlyArray, isString } from \"utils/typeChecks.ts\"\nimport { ClassDiscriminator } from \"utils/withClassDiscriminator.ts\"\nimport { getPathForDisplay } from \"web/pages/projects/components/Domains/validation/validateRouteNode.ts\"\nimport type { ContentType } from \"#framer-plugin/collections.ts\"\nimport { getHTMLTextContentCached } from \"../../../../utils/getHTMLTextContent.ts\"\nimport { getWordCount } from \"../../../../utils/getWordCount.ts\"\nimport type { LocalizationScope } from \"../QuickActions/utils/LocalizationScope.ts\"\nimport { isCanvasLocalizationScope } from \"../QuickActions/utils/LocalizationScope.ts\"\nimport {\n\tgetMaxLengthWarningMessage,\n\tgetRequiredFieldWarningMessage,\n} from \"../contentManagement/utils/fieldWarningMessages.ts\"\nimport { getTemplateVariableWarningMessage } from \"../siteSettings/templateVariables.ts\"\nimport { addArrayItemIdToKeyPath, addObjectPropToKeyPath } from \"./ancestorControlKeyPath.ts\"\nimport type { LocalizationSourceTextType } from \"./getLocalizationSourceTextType.ts\"\nimport { getLocalizationSourceTextType } from \"./getLocalizationSourceTextType.ts\"\nimport { getTitleForRouteSegment } from \"./getTitleForLocalizationScope.ts\"\nimport { getLocalizedValueForActiveLocale } from \"./getValueForActiveLocale.ts\"\nimport { getIncludedLocales } from \"./includedLocales.ts\"\nimport { removeStylesFromRichText } from \"./removeStylesFromRichText.ts\"\nimport { getRichTextModuleTranslatableDigest } from \"./richTextModuleTranslation.ts\"\n\ntype LocalizationSourceFilterStatus = \"new\" | \"done\" | \"needsReview\"\n\n// Don't show \"Warning\" as an option because it looks complicated since\n// most people won't have warnings.\nexport type LocalizationSourceStatus = LocalizationSourceFilterStatus | \"warning\"\n\nexport type LocalizationSourceOrGroupStatus =\n\t// The hidden status filter differs from a Localization SourceStatus in the\n\t// sense that this filter will only display Hidden groups. The filter is applied\n\t// at the group level and not at the source level\n\tLocalizationSourceFilterStatus | \"hidden\"\n\nexport function toSourceStatus(status: LocalizationSourceOrGroupStatus | null): LocalizationSourceFilterStatus | null {\n\t// The \"hidden\" status should not filter out any localization sources\n\tif (status === \"hidden\") return null\n\n\treturn status\n}\n\nexport const allFilterStatuses: LocalizationSourceOrGroupStatus[] = [\"new\", \"needsReview\", \"done\", \"hidden\"]\n\ntype LocalizedValueStatuses = Readonly<Record<LocaleId, LocalizationSourceStatus>>\n\nexport type LocalizableValueTransformName = Extract<\n\tValueTransformName,\n\t\"convertFromEnum\" | \"convertFromBoolean\" | \"prefix\" | \"suffix\"\n>\n\ntype LocalizationSourceType =\n\t| ControlType.String\n\t| ControlType.RichText\n\t| ControlType.Image\n\t| ControlType.Enum\n\t| ControlType.Link\n\t| ClassDiscriminator.FormPlainTextInputNode\n\t| ClassDiscriminator.FormSelectNode\n\t| ClassDiscriminator.RichTextNode\n\t| ClassDiscriminator.CodeComponentNode\n\t| ClassDiscriminator.FrameNode\n\t| ClassDiscriminator.WebPageNode\n\t| ClassDiscriminator.RootNode\n\t| ClassDiscriminator.RouteSegmentNode\n\t| LocalizableValueTransformName\n\t| \"nodeLink\"\n\t| \"slug\"\n\t| \"formSelectGenericOption\"\n\n/** Unique for each source */\nexport type LocalizationSourceKeyPath = string\n\ninterface LocalizationSourceBase {\n\tkeyPath: LocalizationSourceKeyPath\n\tnodeId: NodeID\n\tscopeId: NodeID /** See `LocalizationScope` */\n\ttype: LocalizationSourceType\n\tvalue: string\n\tvalueWordCount: number\n\thash: number\n\tlocalizedValues: LocalizedValues<LocalizedTextValue>\n\tlocalizedValueStatuses: LocalizedValueStatuses\n\tmanagedByPluginButUserEditable: boolean\n\twarnings?: LocalizationWarningMessages\n\taiTranslationDisabled?: boolean\n\tinsetLevel?: 0 | 1 // Defaults to `0`\n\t/** Whether the localized values originate from the primary or not. */\n\tinherited?: boolean\n}\n\ninterface WithLocalizationSourceControlProp {\n\tcontrolPropKey: string\n\tcontrolPropName: string | undefined\n\tancestorControlKeyPath: string | undefined\n\t/** Controls how formatted text content is processed (only for RichText fields) */\n\tcontentType?: ContentType\n}\n\nconst key: keyof WithLocalizationSourceControlProp = \"controlPropKey\"\n\nexport function withLocalizationSourceControlProp(\n\tnode: LocalizationSource,\n): node is LocalizationSource & WithLocalizationSourceControlProp {\n\treturn key in node\n}\n\ninterface LocalizationSourceImage {\n\timage: string\n\timageHash: number\n\timageLocalizedValues: LocalizedValues<LocalizedTextValue>\n\tsupportsAlt: boolean\n\tpositionX: RelativeNumber | undefined\n\tpositionY: RelativeNumber | undefined\n\tsupportsFocalPoint: boolean\n\timageInherited?: boolean\n}\n\nexport type LocalizationSourceControlProp = LocalizationSourceBase & WithLocalizationSourceControlProp\n\ninterface VariableSource extends LocalizationSourceBase {\n\tvariableId: VariableID\n}\n\nexport type LocalizationSourceValueTransform<T extends LocalizableValueTransformName> =\n\tLocalizationSourceControlProp & {\n\t\ttype: T\n\t\ttransformId: NodeID\n\t}\n\ntype LocalizationSourcePrefixSuffixTransform = LocalizationSourceValueTransform<\"prefix\" | \"suffix\">\n\ntype LocalizationSourceConvertFromBooleanTransform = LocalizationSourceValueTransform<\"convertFromBoolean\"> & {\n\tproperty: \"truthy\" | \"falsy\" | \"fallback\"\n}\n\ntype LocalizationSourceConvertFromEnumTransform = LocalizationSourceValueTransform<\"convertFromEnum\"> &\n\t({ caseId: string; isDefaultCase: false } | { caseId: null; isDefaultCase: true })\n\ninterface LocalizationSourceStringControlProp extends LocalizationSourceControlProp {\n\ttype: ControlType.String\n}\n\ninterface LocalizationSourceLinkControlProp extends LocalizationSourceControlProp {\n\ttype: ControlType.Link\n\taiTranslationDisabled: true\n}\n\ninterface LocalizationSourceRichTextControlProp extends LocalizationSourceControlProp {\n\ttype: ControlType.RichText\n\t/** The original rich text value in its native storage format (HTML string or JSON document). */\n\trichTextValue: RichTextTreeValue\n}\n\ninterface LocalizationSourceImageControlProp extends LocalizationSourceControlProp, LocalizationSourceImage {\n\ttype: ControlType.Image\n}\n\ninterface LocalizationSourceEnumControlProp extends VariableSource {\n\ttype: ControlType.Enum\n\tenumCaseId: string\n}\n\nexport interface LocalizationSourceRichTextNode extends LocalizationSourceBase {\n\ttype: ClassDiscriminator.RichTextNode\n\ttextType: LocalizationSourceTextType\n}\n\nexport interface LocalizationSourceRouteSegmentNode extends LocalizationSourceBase {\n\ttype: ClassDiscriminator.RouteSegmentNode\n}\n\ninterface LocalizationSourceFrameNode extends LocalizationSourceBase, LocalizationSourceImage {\n\ttype: ClassDiscriminator.FrameNode\n}\n\ntype LocalizationWarningMessages = Record<LocaleId, string>\n\ninterface LocalizationSourceTitleAndDescription extends LocalizationSourceBase {\n\ttype: ClassDiscriminator.RootNode | ClassDiscriminator.WebPageNode\n\tkey: \"title\" | \"description\"\n\tdataIdentifier: ModuleExportIdentifierString | undefined\n}\n\ninterface LocalizationSourceSlug extends LocalizationSourceControlProp {\n\ttype: \"slug\"\n\tcollectionItemIsDraft: boolean\n}\n\ninterface LocalizationSourceNodeLink extends LocalizationSourceBase {\n\ttype: \"nodeLink\"\n\taiTranslationDisabled: true\n}\n\n/**\n * At the moment, we only support localization of the input placeholder.\n */\ninterface LocalizationSourceFormPlainTextInputPlaceholder extends LocalizationSourceBase {\n\ttype: ClassDiscriminator.FormPlainTextInputNode\n}\n\ninterface LocalizationSourceFormSelectOption extends LocalizationSourceBase {\n\ttype: ClassDiscriminator.FormSelectNode\n\toptionId: string\n}\n\nexport type FormSelectGenericOptionKey = \"allItemsLabel\" | \"booleanTrueLabel\" | \"booleanFalseLabel\"\n\ninterface LocalizationSourceFormSelectGenericOption extends LocalizationSourceBase {\n\ttype: \"formSelectGenericOption\"\n\tkey: FormSelectGenericOptionKey\n}\n\nexport type LocalizationSource =\n\t| LocalizationSourceStringControlProp\n\t| LocalizationSourceLinkControlProp\n\t| LocalizationSourceRichTextControlProp\n\t| LocalizationSourceImageControlProp\n\t| LocalizationSourceEnumControlProp\n\t| LocalizationSourceRichTextNode\n\t| LocalizationSourceFrameNode\n\t| LocalizationSourceNodeLink\n\t| LocalizationSourceTitleAndDescription\n\t| LocalizationSourcePrefixSuffixTransform\n\t| LocalizationSourceConvertFromBooleanTransform\n\t| LocalizationSourceConvertFromEnumTransform\n\t| LocalizationSourceSlug\n\t| LocalizationSourceFormPlainTextInputPlaceholder\n\t| LocalizationSourceFormSelectOption\n\t| LocalizationSourceFormSelectGenericOption\n\t| LocalizationSourceRouteSegmentNode\n\ninterface WithLocalizationSubGroups<T extends LocalizationSourceGroup = LocalizationSourceGroup> {\n\tgroups: readonly T[]\n}\n\nexport function withLocalizationSubGroups<T extends LocalizationSourceGroup>(\n\tvalue: T,\n): value is T & WithLocalizationSubGroups<T> {\n\tconst groupsKey: keyof WithLocalizationSubGroups<T> = \"groups\"\n\treturn groupsKey in value\n}\n\ntype LocalizationSourceGroupType = \"component\" | \"page\" | \"settings\" | \"collection\" | \"collectionItem\" | \"template\"\n\nexport type LocalizationGroupID = NodeID\n\ninterface LocalizationSourceGroupBase {\n\ttype: \"sourceGroup\"\n\tnodeId: NodeID\n\tgroupType: LocalizationSourceGroupType\n\tname: string\n\tsupportsLocaleVisibility: boolean\n\tincludedLocaleIds: IncludedLocales\n\titems: readonly LocalizationSource[]\n}\n\ninterface GeneralLocalizationSourceGroup extends LocalizationSourceGroupBase {\n\tgroupType: Exclude<LocalizationSourceGroupType, \"collection\" | \"collectionItem\">\n}\n\nexport interface LocalizationSourceGroupCollectionItem extends LocalizationSourceGroupBase {\n\tgroupType: \"collectionItem\"\n\tcollectionNodeId: NodeID\n\tcollectionName: string\n}\n\ninterface LocalizationSourceGroupCollection\n\textends LocalizationSourceGroupBase, WithLocalizationSubGroups<LocalizationSourceGroupCollectionItem> {\n\tgroupType: \"collection\"\n}\n\nexport type LocalizationSourceGroup =\n\t| GeneralLocalizationSourceGroup\n\t| LocalizationSourceGroupCollectionItem\n\t| LocalizationSourceGroupCollection\n\nconst collectionNodeIdKey: keyof LocalizationSourceGroupCollectionItem = \"collectionNodeId\"\n\n// TODO: we should get rid of this now that we have nested groups\nexport function withCollectionNodeParentInfo(\n\tgroup: LocalizationSourceGroup,\n): group is LocalizationSourceGroupCollectionItem {\n\treturn collectionNodeIdKey in group\n}\n\ntype LocalizableVariableType = LocalizationSourceType & VariableType\nexport type LocalizableVariable = Exclude<\n\tExtract<VariableDefinition, { type: LocalizableVariableType }>,\n\tNodePropertyControlReferenceVariableDefinition\n>\n\nconst localizableVariableTypes: Record<LocalizableVariableType, true> = {\n\t[ControlType.String]: true,\n\t[ControlType.RichText]: true,\n\t[ControlType.Image]: true,\n\t[ControlType.Enum]: true,\n\t[ControlType.Link]: true,\n\tslug: true,\n}\n\nfunction isLocalizableVariableType(type: VariableType): type is LocalizableVariableType {\n\treturn type in localizableVariableTypes\n}\n\nfunction isLocalizableVariable(variable: VariableOrDivider): variable is LocalizableVariable {\n\treturn isVariableDefinition(variable) && isLocalizableVariableType(variable.type)\n}\n\ntype LocalizableControlPropType = Exclude<LocalizationSourceType & ControlType, ControlType.Enum>\n\nconst localizableControlPropTypes: Record<LocalizableControlPropType, true> = {\n\t[ControlType.String]: true,\n\t[ControlType.RichText]: true,\n\t[ControlType.Image]: true,\n\t[ControlType.Link]: true,\n}\n\nfunction isLocalizableControlPropType(type: ControlType): type is LocalizableControlPropType {\n\treturn type in localizableControlPropTypes\n}\n\ntype RichTextLocalizationSource =\n\t| LocalizationSourceRichTextControlProp\n\t| (LocalizationSourceRichTextNode & { textType: \"rich-text\" })\n\n/**\n * Whether this source uses rich text editing (ProseMirror overlay, not plain text input).\n * True for both HTML-backed and JSON-backed rich text sources.\n */\nexport function isRichTextSource(source: LocalizationSource | undefined): source is RichTextLocalizationSource {\n\tif (!source) return false\n\tif (source.type === ControlType.RichText) return true\n\tif (source.type === ClassDiscriminator.RichTextNode) return source.textType === \"rich-text\"\n\treturn false\n}\n\nexport function isRichTextControlPropSource(\n\tsource: LocalizationSource | undefined,\n): source is LocalizationSourceRichTextControlProp {\n\treturn source?.type === ControlType.RichText\n}\n\n/**\n * Whether this source's `richTextValue` is stored as an HTML string (not a JSON document).\n * Only HTML-backed rich text control props and canvas rich text nodes satisfy this.\n * JSON-backed rich text control props do NOT \u2014 features that require HTML should be\n * guarded by this predicate and skipped for JSON-backed sources.\n */\nexport function isHTMLBackedRichTextSource(source: LocalizationSource): boolean {\n\tif (source.type === ControlType.RichText) return typeof source.richTextValue === \"string\"\n\tif (source.type === ClassDiscriminator.RichTextNode) return true // canvas always stores HTML\n\treturn false\n}\n\n/**\n * Whether this source is a `RichTextDocument`-backed rich text control prop \u2014 i.e. its\n * `richTextValue` is a `RichTextDocument` rather than an HTML string. Used by the translation\n * save boundary to decide whether to parse HTML output into a document, and by\n * `showMatchingItemsToast` to gate document-valued bulk applies to compatible siblings. Narrows\n * `richTextValue` to `RichTextDocument` so callers can pass it to document-only helpers without\n * a cast.\n */\nexport function isRichTextDocumentControlPropSource(\n\tsource: LocalizationSource,\n): source is LocalizationSourceRichTextControlProp & { richTextValue: RichTextDocument } {\n\treturn isRichTextControlPropSource(source) && typeof source.richTextValue !== \"string\"\n}\n\n/**\n * Whether this source requires the overlay-only rich-text editor (ProseMirror).\n * True only for HTML-backed sources that use rich-text editing mode:\n * - HTML-backed rich text control props\n * - Canvas RichTextNode with textType \"rich-text\"\n * False for JSON-backed control props and plain-text RichTextNodes.\n */\nexport function isOverlayOnlyRichTextSource(source: LocalizationSource): boolean {\n\treturn isRichTextSource(source) && isHTMLBackedRichTextSource(source)\n}\n\nexport type ImageLocalizationSource = LocalizationSourceImageControlProp | LocalizationSourceFrameNode\n\nexport function isImageSource(source: LocalizationSource | undefined): source is ImageLocalizationSource {\n\tif (!source) return false\n\tif (source.type === ControlType.Image) return true\n\tif (source.type === ClassDiscriminator.FrameNode) return true\n\treturn false\n}\n\ntype LinkLocalizationSource = LocalizationSourceLinkControlProp | LocalizationSourceNodeLink\n\nexport function isLinkSource(source: LocalizationSource | undefined): source is LinkLocalizationSource {\n\tif (!source) return false\n\tif (source.type === \"nodeLink\") return true\n\tif (source.type === ControlType.Link) return true\n\treturn false\n}\n\nexport function isTitleAndDescriptionSource(\n\tsource: LocalizationSource | undefined,\n): source is LocalizationSourceTitleAndDescription {\n\tif (!source) return false\n\tif (source.type === ClassDiscriminator.RootNode) return true\n\tif (source.type === ClassDiscriminator.WebPageNode) return true\n\treturn false\n}\n\nexport function isSlugSource(\n\tsource: LocalizationSource | undefined,\n): source is LocalizationSourceSlug | LocalizationSourceRouteSegmentNode {\n\treturn source?.type === \"slug\" || isRouteSegmentSource(source)\n}\n\nexport function isRouteSegmentSource(\n\tsource: LocalizationSource | undefined,\n): source is LocalizationSourceRouteSegmentNode {\n\treturn source?.type === ClassDiscriminator.RouteSegmentNode\n}\n\nexport function isEmptyValue(value: string | null | undefined) {\n\treturn isNullish(value) || value === \"\" || isEmptyRichTextValue(value)\n}\n\nexport function isMultiLineSourceOrLocalizedValue(source: LocalizationSource | undefined, activeLocale: Locale) {\n\tif (!source) return false\n\t// Overlay-only rich text sources handle multiline via the ProseMirror editor.\n\t// Plain-text sources (including JSON-backed rich text) can still be multiline.\n\tif (isOverlayOnlyRichTextSource(source)) return false\n\tif (source.value.includes(\"\\n\")) return true\n\n\tconst localizedValue = source.localizedValues[activeLocale.id]\n\tif (!isNonNullLocalizedValue(localizedValue)) return false\n\n\tconst localizedText = getLocalizedValueText(localizedValue, { preserveNewLines: true })\n\tif (localizedText.includes(\"\\n\")) return true\n\n\treturn false\n}\n\nfunction getStatus(\n\tvalue: string,\n\tlocalizedValue: LocalizedValue<LocalizedTextValue> | undefined,\n\tlatestHash: number,\n): LocalizationSourceStatus {\n\tif (!localizedValue) {\n\t\treturn isEmptyValue(value) ? \"done\" : \"new\"\n\t}\n\tif (localizedValue.hash !== latestHash || localizedValue.needsReview) {\n\t\treturn \"needsReview\"\n\t}\n\treturn \"done\"\n}\n\ntype LocalizedValueStatusResolver = (locale: Locale) => LocalizationSourceStatus | null\n\nfunction getLocalizedValueStatuses(\n\tvalue: string,\n\tlocales: readonly Locale[],\n\tlocalizedValues: LocalizedValues<LocalizedTextValue>,\n\tlatestHash: number,\n\twarnings?: LocalizationWarningMessages,\n\tstatusResolver?: LocalizedValueStatusResolver,\n): LocalizedValueStatuses {\n\treturn Object.fromEntries(\n\t\tlocales.map(locale => {\n\t\t\tconst localizedValue = localizedValues[locale.id]\n\n\t\t\tif (warnings?.[locale.id]) {\n\t\t\t\treturn [locale.id, \"warning\"]\n\t\t\t}\n\n\t\t\tif (statusResolver) {\n\t\t\t\tconst validationMessage = statusResolver(locale)\n\t\t\t\tif (validationMessage) {\n\t\t\t\t\treturn [locale.id, validationMessage]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn [locale.id, getStatus(value, localizedValue, latestHash)]\n\t\t}),\n\t)\n}\n\nfunction slugAndLinkStatusResolver(\n\tslugLocalizedValue: LocalizedValues<LocalizedTextValue>,\n): LocalizedValueStatusResolver {\n\treturn locale => {\n\t\t// Slugs and links are not required to be translated, so if there is no localized value we\n\t\t// consider it done.\n\t\tconst localizedValue = slugLocalizedValue[locale.id]\n\t\tif (!localizedValue) {\n\t\t\treturn \"done\"\n\t\t}\n\n\t\treturn null\n\t}\n}\n\nfunction imageStatusResolver(\n\timage: string,\n\timageLocalizedValues: LocalizedValues<LocalizedTextValue>,\n\tlatestImageHash: number,\n): LocalizedValueStatusResolver {\n\treturn locale => {\n\t\t// By default the status depends on the main localized value, but image sources contain\n\t\t// both the image and alt text, and if the image is localized we use that.\n\t\tif (isString(image) && imageLocalizedValues) {\n\t\t\tconst imageLocalizedValue = imageLocalizedValues[locale.id]\n\t\t\tif (imageLocalizedValue) {\n\t\t\t\treturn getStatus(image, imageLocalizedValue, latestImageHash)\n\t\t\t}\n\t\t}\n\n\t\treturn null\n\t}\n}\n\nconst noLocalizedValues: LocalizedValues<LocalizedTextValue> = {}\nObject.freeze(noLocalizedValues)\n\nfunction collectLocalizationSourcesFromConvertFromBooleanTransform(\n\ttransform: ValueTransformConvertFromBoolean,\n\tancestorKeyPath: string,\n\tcontrolPropKey: string,\n\tscopeNode: LocalizationScope,\n\tnode: CanvasNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tconst handleTransformProperty = (\n\t\tproperty: LocalizationSourceConvertFromBooleanTransform[\"property\"],\n\t\tvalue: ConvertFromBooleanOutputValueType | VariableReference,\n\t\tlocalized: LocalizedValues<LocalizedTextValue> | undefined,\n\t) => {\n\t\t// Only booleanToString transforms are collected for localization.\n\t\tif (isVariableReference(value) || !isString(value)) return\n\n\t\t// Skip if the value is empty and there are no localized values.\n\t\tif (value.length === 0 && !localized) return\n\n\t\tconst latestHash = murmurHash(value)\n\t\tconst localizedValues = localized ?? noLocalizedValues\n\t\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash)\n\n\t\tresult.push({\n\t\t\ttype: transform.name,\n\t\t\ttransformId: transform.id,\n\t\t\tkeyPath: addObjectPropToKeyPath(ancestorKeyPath, property),\n\t\t\tnodeId: node.id,\n\t\t\tscopeId: scopeNode.id,\n\t\t\tproperty,\n\t\t\tvalue: value,\n\t\t\tcontrolPropKey,\n\t\t\tcontrolPropName: undefined,\n\t\t\tancestorControlKeyPath: undefined,\n\t\t\tvalueWordCount: getWordCount(value),\n\t\t\thash: latestHash,\n\t\t\tlocalizedValues,\n\t\t\tlocalizedValueStatuses,\n\t\t\tmanagedByPluginButUserEditable: false,\n\t\t})\n\t}\n\n\thandleTransformProperty(\"truthy\", transform.truthy, transform.truthyLocalized)\n\thandleTransformProperty(\"falsy\", transform.falsy, transform.falsyLocalized)\n\tif (transform.fallback) {\n\t\thandleTransformProperty(\"fallback\", transform.fallback.value, transform.fallback.valueLocalized)\n\t}\n}\n\nfunction collectLocalizationSourcesFromConvertFromEnumTransform(\n\tcomputedValue: ComputedValue,\n\ttransform: ValueTransformConvertFromEnum,\n\tancestorKeyPath: string,\n\tcontrolPropKey: string,\n\tscopeNode: LocalizationScope,\n\tnode: CanvasNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tif (transform.outputType !== ControlType.String) return\n\n\tfor (const transformCase of transform.cases) {\n\t\t// It does not make sense to translate an enum case that has the active locale as starting value, so we skip.\n\t\tif (isComputedValueFromVariableReference(computedValue) && computedValue.startValue.id === localeVariableId) {\n\t\t\tbreak\n\t\t}\n\n\t\t// Only enumToString transforms are collected for localization.\n\t\tif (isVariableReference(transformCase.to) || !isString(transformCase.to)) continue\n\n\t\t// Skip if the value is empty and there are no localized values.\n\t\tif (transformCase.to.length === 0 && !transformCase.toLocalized) continue\n\n\t\tconst latestHash = murmurHash(transformCase.to)\n\t\tconst localizedValues = transformCase.toLocalized ?? noLocalizedValues\n\t\tconst localizedValueStatuses = getLocalizedValueStatuses(transformCase.to, locales, localizedValues, latestHash)\n\t\tconst casesKeyPath = addObjectPropToKeyPath(ancestorKeyPath, \"cases\")\n\n\t\tresult.push({\n\t\t\ttype: \"convertFromEnum\",\n\t\t\ttransformId: transform.id,\n\t\t\tkeyPath: addArrayItemIdToKeyPath(casesKeyPath, transformCase.id),\n\t\t\tnodeId: node.id,\n\t\t\tscopeId: scopeNode.id,\n\t\t\tcaseId: transformCase.id,\n\t\t\tisDefaultCase: false,\n\t\t\tvalue: transformCase.to,\n\t\t\tancestorControlKeyPath: undefined,\n\t\t\tcontrolPropKey,\n\t\t\tcontrolPropName: undefined,\n\t\t\tvalueWordCount: getWordCount(transformCase.to),\n\t\t\thash: latestHash,\n\t\t\tlocalizedValues,\n\t\t\tlocalizedValueStatuses,\n\t\t\tmanagedByPluginButUserEditable: false,\n\t\t})\n\t}\n\n\tif (!transform.default || isVariableReference(transform.default) || !isString(transform.default)) return\n\n\tconst defaultCaseLatestHash = murmurHash(transform.default)\n\tconst defaultCaseLocalizedValues = transform.defaultLocalized ?? noLocalizedValues\n\tconst defaultCaseLocalizedValueStatuses = getLocalizedValueStatuses(\n\t\ttransform.default,\n\t\tlocales,\n\t\tdefaultCaseLocalizedValues,\n\t\tdefaultCaseLatestHash,\n\t)\n\n\tresult.push({\n\t\ttype: \"convertFromEnum\",\n\t\ttransformId: transform.id,\n\t\tkeyPath: addObjectPropToKeyPath(ancestorKeyPath, \"default\"),\n\t\tnodeId: node.id,\n\t\tscopeId: scopeNode.id,\n\t\tcaseId: null,\n\t\tisDefaultCase: true,\n\t\tancestorControlKeyPath: undefined,\n\t\tvalue: transform.default,\n\t\tcontrolPropKey,\n\t\tcontrolPropName: undefined,\n\t\tvalueWordCount: getWordCount(transform.default),\n\t\thash: defaultCaseLatestHash,\n\t\tlocalizedValues: defaultCaseLocalizedValues,\n\t\tlocalizedValueStatuses: defaultCaseLocalizedValueStatuses,\n\t\tmanagedByPluginButUserEditable: false,\n\t})\n}\n\nfunction collectLocalizationSourcesFromComputedValue(\n\tscopeNode: LocalizationScope,\n\tnode: CanvasNode,\n\tcomputedValue: ComputedValue,\n\tancestorKeyPath: string,\n\tcontrolPropKey: string,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tif (!isComputedValueOutputType(computedValue.outputType) || computedValue.outputType !== ControlType.String) return\n\n\tfor (const transform of computedValue.transforms) {\n\t\tif (!isValueTransform(transform)) continue\n\t\tswitch (transform.name) {\n\t\t\tcase \"convertFromEnum\": {\n\t\t\t\tcollectLocalizationSourcesFromConvertFromEnumTransform(\n\t\t\t\t\tcomputedValue,\n\t\t\t\t\ttransform,\n\t\t\t\t\tancestorKeyPath,\n\t\t\t\t\tcontrolPropKey,\n\t\t\t\t\tscopeNode,\n\t\t\t\t\tnode,\n\t\t\t\t\tlocales,\n\t\t\t\t\tresult,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"convertFromBoolean\": {\n\t\t\t\tcollectLocalizationSourcesFromConvertFromBooleanTransform(\n\t\t\t\t\ttransform,\n\t\t\t\t\tancestorKeyPath,\n\t\t\t\t\tcontrolPropKey,\n\t\t\t\t\tscopeNode,\n\t\t\t\t\tnode,\n\t\t\t\t\tlocales,\n\t\t\t\t\tresult,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase \"prefix\":\n\t\t\tcase \"suffix\": {\n\t\t\t\tif (isVariableReference(transform.value)) return\n\n\t\t\t\t// Skip if the value is empty and there are no localized values.\n\t\t\t\tif (transform.value.length === 0 && !transform.valueLocalized) return\n\n\t\t\t\tconst latestHash = murmurHash(transform.value)\n\t\t\t\tconst localizedValues = transform.valueLocalized ?? noLocalizedValues\n\t\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(transform.value, locales, localizedValues, latestHash)\n\n\t\t\t\tresult.push({\n\t\t\t\t\ttype: transform.name,\n\t\t\t\t\ttransformId: transform.id,\n\t\t\t\t\tkeyPath: addArrayItemIdToKeyPath(ancestorKeyPath, transform.id),\n\t\t\t\t\tcontrolPropKey,\n\t\t\t\t\tcontrolPropName: undefined,\n\t\t\t\t\tancestorControlKeyPath: undefined,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t\tscopeId: scopeNode.id,\n\t\t\t\t\tvalue: transform.value,\n\t\t\t\t\tvalueWordCount: getWordCount(transform.value),\n\t\t\t\t\thash: latestHash,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tlocalizedValueStatuses,\n\t\t\t\t\tmanagedByPluginButUserEditable: false,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdefault:\n\t\t}\n\t}\n}\n\ntype RichTextValueBehavior = \"canvasHtmlAsTextContentIfPossible\" | \"canvasHtmlAsHtml\"\n\nexport function collectLocalizationSourceFromRichTextNode(\n\ttree: CanvasTree,\n\tscopeNode: LocalizationScope,\n\tnode: RichTextNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n\tbehavior: RichTextValueBehavior,\n) {\n\tif (isComputedValue(node.textContent)) {\n\t\tif (!isKeySetAndNotInherited(tree, node, \"textContent\")) return\n\n\t\tcollectLocalizationSourcesFromComputedValue(scopeNode, node, node.textContent, node.id, node.id, locales, result)\n\t\treturn\n\t}\n\n\t// The html isn't visible when a variable is assigned.\n\tif (isDynamicValue(node.htmlContent)) return\n\tif (isDynamicValue(node.textContent)) return\n\n\t// We only want to allow localizing the html if either the html or localized html has been.\n\t// overridden within a breakpoint.\n\tconst isHTMLSet = isKeySetAndNotInherited(tree, node, \"html\")\n\tconst isHTMLLocalizedSet = isKeySetAndNotInherited(tree, node, \"htmlLocalized\")\n\tif (!isHTMLSet && !isHTMLLocalizedSet) return\n\n\tconst html: string = node.html\n\tconst htmlTextContent = getHTMLTextContentCached(html)\n\tconst textTypeFromHTML: LocalizationSourceTextType = getLocalizationSourceTextType(html)\n\tconst textType: LocalizationSourceTextType =\n\t\tbehavior === \"canvasHtmlAsTextContentIfPossible\" ? textTypeFromHTML : \"rich-text\"\n\tconst value = textType === \"text\" ? htmlTextContent : removeStylesFromRichText(html)\n\n\t// Don't display the value if localized isn't overridden and the HTML text content is the same.\n\tif (textType === \"text\" && !isHTMLLocalizedSet && isReplicaChild(node)) {\n\t\tconst originalNode = tree.getNode<RichTextNode>(node.originalid)\n\t\tif (originalNode && getHTMLTextContentCached(originalNode.html) === htmlTextContent) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Plugins always get the HTML value, but we need the hash to be the same as the canvas value,\n\t// otherwise it will immediately show as being in need of review.\n\tconst valueForHashing = textTypeFromHTML === textType ? value : htmlTextContent\n\tconst latestHash = murmurHash(valueForHashing)\n\n\tconst localizedValues = node.htmlLocalized ?? noLocalizedValues\n\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash)\n\n\tresult.push({\n\t\ttype: ClassDiscriminator.RichTextNode,\n\t\tkeyPath: getKeyPathForRichTextNodeHtml(node.id),\n\t\tnodeId: node.id,\n\t\tscopeId: scopeNode.id,\n\t\tvalue,\n\t\tvalueWordCount: getWordCount(value, true),\n\t\ttextType,\n\t\thash: latestHash,\n\t\tlocalizedValues,\n\t\tlocalizedValueStatuses,\n\t\tmanagedByPluginButUserEditable: false,\n\t\tinherited: !isHTMLLocalizedSet,\n\t})\n}\n\nexport function getKeyPathForRichTextNodeHtml(nodeId: NodeID): LocalizationSourceKeyPath {\n\treturn `${nodeId}_html`\n}\n\nfunction getRootOrWebPageNodeClassDiscriminator(node: RootNode | ShallowWebPageNode) {\n\tif (isRootNode(node)) return ClassDiscriminator.RootNode\n\tif (isWebPageNode(node)) return ClassDiscriminator.WebPageNode\n\tassertNever(node)\n}\n\nfunction getTemplateVariableWarningMessages(\n\tcomponentLoader: ComponentLoader,\n\tlocales: readonly Locale[],\n\tlocalizedValues: LocalizedValues<LocalizedTextValue>,\n\tcollectionData: DataDefinition | null,\n): LocalizationWarningMessages {\n\tconst warningMessages: Record<LocaleId, string> = {}\n\n\tfor (const locale of locales) {\n\t\tconst localizedValue = localizedValues[locale.id]\n\t\tif (!localizedValue || !isString(localizedValue.value) || !localizedValue.value) continue\n\n\t\tconst warningMessage = getTemplateVariableWarningMessage({\n\t\t\tcollectionData,\n\t\t\tcomponentLoader,\n\t\t\ttype: \"id\",\n\t\t\tvalue: localizedValue.value,\n\t\t})\n\t\tif (!warningMessage) continue\n\n\t\twarningMessages[locale.id] = warningMessage\n\t}\n\n\treturn warningMessages\n}\n\nexport function collectTitleAndDescriptionLocalizationSources(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tscopeNode: LocalizationScope,\n\tnode: RootNode | ShallowWebPageNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tlet collectionData: DataDefinition | null = null\n\n\tif (isWebPageNode(node)) {\n\t\tcollectionData = componentLoader.dataForIdentifier(node.dataIdentifier)\n\t}\n\n\tif (node.webMetadata?.title || node.titleLocalized) {\n\t\tconst value: string = node.webMetadata?.title ?? tree.root.webMetadata?.title ?? \"\"\n\t\tconst latestHash = murmurHash(value)\n\n\t\tconst localizedValues = node.titleLocalized ?? noLocalizedValues\n\t\tconst warnings = getTemplateVariableWarningMessages(componentLoader, locales, localizedValues, collectionData)\n\t\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash, warnings)\n\n\t\tresult.push({\n\t\t\ttype: getRootOrWebPageNodeClassDiscriminator(node),\n\t\t\tkeyPath: `${node.id}_title`,\n\t\t\tnodeId: node.id,\n\t\t\tscopeId: scopeNode.id,\n\t\t\tvalue,\n\t\t\tvalueWordCount: getWordCount(value),\n\t\t\thash: latestHash,\n\t\t\tlocalizedValues,\n\t\t\tlocalizedValueStatuses,\n\t\t\tmanagedByPluginButUserEditable: false,\n\t\t\tkey: \"title\",\n\t\t\tdataIdentifier: withCollectionDataSource(node) ? node.dataIdentifier : undefined,\n\t\t\twarnings,\n\t\t})\n\t}\n\n\tif (node.webMetadata?.description || node.descriptionLocalized) {\n\t\tconst value: string = node.webMetadata?.description ?? tree.root.webMetadata?.description ?? \"\"\n\t\tconst latestHash = murmurHash(value)\n\n\t\tconst localizedValues = node.descriptionLocalized ?? noLocalizedValues\n\t\tconst warnings = getTemplateVariableWarningMessages(componentLoader, locales, localizedValues, collectionData)\n\t\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash, warnings)\n\n\t\tresult.push({\n\t\t\ttype: getRootOrWebPageNodeClassDiscriminator(node),\n\t\t\tkeyPath: `${node.id}_description`,\n\t\t\tnodeId: node.id,\n\t\t\tscopeId: scopeNode.id,\n\t\t\tvalue,\n\t\t\tvalueWordCount: getWordCount(value),\n\t\t\thash: latestHash,\n\t\t\tlocalizedValues,\n\t\t\tlocalizedValueStatuses,\n\t\t\tmanagedByPluginButUserEditable: false,\n\t\t\tkey: \"description\",\n\t\t\tdataIdentifier: withCollectionDataSource(node) ? node.dataIdentifier : undefined,\n\t\t\twarnings,\n\t\t})\n\t}\n}\n\nexport function getKeyPathForFrameFillImage(nodeId: NodeID): LocalizationSourceKeyPath {\n\treturn `${nodeId}_fillImageLocalized`\n}\n\nfunction collectFillImageLocalizationSource(\n\ttree: CanvasTree,\n\tscopeNode: LocalizationScope,\n\tnode: FrameNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\t// The alt text isn't used when a variable is assigned.\n\tif (!hasImageFill(node) || !isString(node.fillImage) || node.fillImage.length === 0) return\n\n\t// We only want to allow localizing the image and alt text if either the image, localized image,\n\t// alt text, or localized alt text, has been overridden within a breakpoint.\n\tconst isFillImageSet = isKeySetAndNotInherited(tree, node, \"fillImage\")\n\tconst isFillImageLocalizedSet = isKeySetAndNotInherited(tree, node, \"fillImageLocalized\")\n\tconst isAltAttributeSet = isKeySetAndNotInherited(tree, node, \"altAttribute\")\n\tconst isAltAttributeLocalizedSet = isKeySetAndNotInherited(tree, node, \"altAttributeLocalized\")\n\tif (!isFillImageSet && !isFillImageLocalizedSet && !isAltAttributeSet && !isAltAttributeLocalizedSet) return\n\n\tconst value: string = node.altAttribute ?? fallbackAltText\n\tconst latestHash = murmurHash(value)\n\tconst localizedValues = node.altAttributeLocalized ?? noLocalizedValues\n\n\tconst image: string = node.fillImage\n\tconst imageHash = murmurHash(image)\n\tconst imageLocalizedValues = node.fillImageLocalized ?? noLocalizedValues\n\n\tconst localizedValueStatuses = getLocalizedValueStatuses(\n\t\tvalue,\n\t\tlocales,\n\t\tlocalizedValues,\n\t\tlatestHash,\n\t\tundefined,\n\t\timageStatusResolver(image, imageLocalizedValues, imageHash),\n\t)\n\n\tresult.push({\n\t\ttype: ClassDiscriminator.FrameNode,\n\t\tkeyPath: getKeyPathForFrameFillImage(node.id),\n\t\tnodeId: node.id,\n\t\tscopeId: scopeNode.id,\n\t\tvalue,\n\t\tvalueWordCount: getWordCount(value),\n\t\thash: latestHash,\n\t\tlocalizedValues,\n\t\tlocalizedValueStatuses,\n\t\tmanagedByPluginButUserEditable: false,\n\t\tinherited: !isAltAttributeLocalizedSet,\n\t\tsupportsAlt: true,\n\t\timage,\n\t\timageHash,\n\t\timageLocalizedValues,\n\t\timageInherited: !isFillImageLocalizedSet,\n\t\tpositionX: isRelativeNumber(node.fillImagePositionX) ? node.fillImagePositionX : undefined,\n\t\tpositionY: isRelativeNumber(node.fillImagePositionY) ? node.fillImagePositionY : undefined,\n\t\tsupportsFocalPoint: true,\n\t})\n}\n\nfunction collectNodeLinkLocalizationSource(\n\tscopeNode: LocalizationScope,\n\tnode: FrameNode | SVGNode | ShapeContainerNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tif (!experiments.isOn(\"localizedLinks\")) return\n\n\tconst link = node.getLink()\n\tif (!isLinkToURL(link)) return\n\n\tconst value: string = link.url\n\tconst latestHash = murmurHash(value)\n\n\tconst localizedValues = node.linkLocalized ?? noLocalizedValues\n\tconst localizedValueStatuses = getLocalizedValueStatuses(\n\t\tvalue,\n\t\tlocales,\n\t\tlocalizedValues,\n\t\tlatestHash,\n\t\tundefined,\n\t\tslugAndLinkStatusResolver(localizedValues),\n\t)\n\n\tresult.push({\n\t\ttype: \"nodeLink\",\n\t\tkeyPath: `${node.id}_linkLocalized`,\n\t\tnodeId: node.id,\n\t\tscopeId: scopeNode.id,\n\t\tvalue,\n\t\tvalueWordCount: value ? 1 : 0,\n\t\thash: latestHash,\n\t\tlocalizedValues,\n\t\tlocalizedValueStatuses,\n\t\tmanagedByPluginButUserEditable: false,\n\t\taiTranslationDisabled: true,\n\t})\n}\n\nexport function collectLocalizationSourcesFromFrameNode(\n\ttree: CanvasTree,\n\tscopeNode: LocalizationScope,\n\tnode: FrameNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tcollectFillImageLocalizationSource(tree, scopeNode, node, locales, result)\n\tcollectNodeLinkLocalizationSource(scopeNode, node, locales, result)\n}\n\nfunction controlPropCanContainLocalizedValue(type: ControlType): boolean {\n\tif (isLocalizableControlPropType(type)) return true\n\tif (type === ControlType.Array) return true\n\tif (type === ControlType.Object) return true\n\treturn false\n}\n\nexport function getKeyPathForControlProp(\n\tnodeId: NodeID,\n\tcontrolKey: string,\n\tancestorControlKeyPath: string | undefined,\n): string {\n\treturn `${nodeId}.${controlKey}.${ancestorControlKeyPath ?? \"\"}`\n}\n\nfunction getIdentifierForNode(node: CanvasNode & WithControlProps): string | undefined {\n\tif (isWebPageNode(node) && hasLayoutTemplate(node)) return node.layoutTemplateIdentifier\n\tif (isCodeComponentNode(node)) return node.codeComponentIdentifier\n\treturn undefined\n}\n\n// For HTML-backed values, keep the existing murmurHash(html) as the base so rich text without\n// modules and modules whose translatable controls all live in the raw props hash identically to\n// before. When modules contribute translatable values (including defaults), mix in a stable digest\n// so the hash moves when a component's text or default changes.\nfunction getRichTextLocalizationHash(value: RichTextTreeValue, componentLoader: ComponentLoader): number {\n\tconst base = getRichTextTreeValueHash(value)\n\tif (typeof value !== \"string\" || !value.includes(\"data-module-identifier\")) return base\n\n\tconst digest = getRichTextModuleTranslatableDigest(value, componentLoader)\n\treturn digest.length === 0 ? base : murmurHash(`${base}:${digest}`)\n}\n\nexport function collectLocalizationSourcesFromControlPropsNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tscopeNode: LocalizationScope,\n\tnode: CanvasNode & WithControlProps,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tconst identifier = getIdentifierForNode(node)\n\tif (!identifier) return\n\n\tconst component = componentLoader.componentForIdentifier(identifier)\n\tif (!component) return\n\n\tconst controlProps = node.getControlProps(component.properties)\n\n\tfunction addControlProp(\n\t\tcontrolKey: string,\n\t\tcontrolProp: ControlProp,\n\t\tcontrol: ControlDescription,\n\t\tancestorControlKeyPath?: string | undefined,\n\t) {\n\t\tconst controlType = controlProp.type\n\n\t\tif (controlType === ControlType.Array && isReadonlyArray(controlProp.value)) {\n\t\t\tif (control.type !== ControlType.Array) return\n\t\t\tconst itemControl = control.control\n\t\t\tfor (const item of controlProp.value) {\n\t\t\t\tif (!controlPropCanContainLocalizedValue(item.type)) continue\n\t\t\t\tconst ancestorControlKeyPathForItem = addArrayItemIdToKeyPath(ancestorControlKeyPath, item.id)\n\t\t\t\taddControlProp(controlKey, item, itemControl, ancestorControlKeyPathForItem)\n\t\t\t}\n\t\t}\n\n\t\tif (controlType === ControlType.Object && isObject(controlProp.value)) {\n\t\t\tif (control.type !== ControlType.Object) return\n\t\t\tfor (const objectKey in controlProp.value) {\n\t\t\t\tconst childControlProp = controlProp.value[objectKey]\n\t\t\t\tif (!childControlProp) continue\n\t\t\t\tif (!controlPropCanContainLocalizedValue(childControlProp.type)) continue\n\t\t\t\tconst ancestorControlKeyPathForItem = addObjectPropToKeyPath(ancestorControlKeyPath, objectKey)\n\t\t\t\tconst childControl = control.controls[objectKey]\n\t\t\t\tif (!childControl) continue\n\t\t\t\taddControlProp(controlKey, childControlProp, childControl, ancestorControlKeyPathForItem)\n\t\t\t}\n\t\t}\n\n\t\tif (!isLocalizableControlPropType(controlType)) return\n\n\t\tswitch (controlType) {\n\t\t\tcase ControlType.String: {\n\t\t\t\tif (!isKeySetAndNotInherited(tree, node, prefixControlPropKey(controlKey))) break\n\n\t\t\t\tif (control.type === ControlType.String) {\n\t\t\t\t\tif (control.preventLocalization) break\n\t\t\t\t\tif (control.optional && isNull(controlProp.value)) break\n\t\t\t\t}\n\n\t\t\t\t// Only string control types can have localized computed values (at the moment).\n\t\t\t\tif (isComputedValue(controlProp.value)) {\n\t\t\t\t\tcollectLocalizationSourcesFromComputedValue(\n\t\t\t\t\t\tscopeNode,\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\tcontrolProp.value,\n\t\t\t\t\t\taddObjectPropToKeyPath(node.id, controlKey),\n\t\t\t\t\t\tcontrolKey,\n\t\t\t\t\t\tlocales,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (!isString(controlProp.value)) break\n\n\t\t\t\tconst value: string = controlProp.value\n\t\t\t\tconst latestHash = murmurHash(value)\n\n\t\t\t\tconst localizedValues = controlProp.valueLocalized ?? noLocalizedValues\n\t\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash)\n\n\t\t\t\tresult.push({\n\t\t\t\t\ttype: ControlType.String,\n\t\t\t\t\tkeyPath: getKeyPathForControlProp(node.id, controlKey, ancestorControlKeyPath),\n\t\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\t\tcontrolPropName: control.title || titleCase(controlKey),\n\t\t\t\t\tancestorControlKeyPath,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t\tscopeId: scopeNode.id,\n\t\t\t\t\tvalue,\n\t\t\t\t\tvalueWordCount: getWordCount(value),\n\t\t\t\t\thash: latestHash,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tlocalizedValueStatuses,\n\t\t\t\t\tmanagedByPluginButUserEditable: false,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.Link: {\n\t\t\t\tif (!experiments.isOn(\"localizedLinks\")) break\n\t\t\t\tif (!isKeySetAndNotInherited(tree, node, prefixControlPropKey(controlKey))) break\n\n\t\t\t\tif (isComputedValue(controlProp.value)) {\n\t\t\t\t\tcollectLocalizationSourcesFromComputedValue(\n\t\t\t\t\t\tscopeNode,\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\tcontrolProp.value,\n\t\t\t\t\t\taddObjectPropToKeyPath(node.id, controlKey),\n\t\t\t\t\t\tcontrolKey,\n\t\t\t\t\t\tlocales,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (!isLinkToURL(controlProp.value)) break\n\n\t\t\t\tconst value: string = controlProp.value.url\n\t\t\t\tconst latestHash = murmurHash(value)\n\n\t\t\t\tconst localizedValues = controlProp.valueLocalized ?? noLocalizedValues\n\t\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(\n\t\t\t\t\tvalue,\n\t\t\t\t\tlocales,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tlatestHash,\n\t\t\t\t\tundefined,\n\t\t\t\t\tslugAndLinkStatusResolver(localizedValues),\n\t\t\t\t)\n\n\t\t\t\tresult.push({\n\t\t\t\t\ttype: ControlType.Link,\n\t\t\t\t\tkeyPath: getKeyPathForControlProp(node.id, controlKey, ancestorControlKeyPath),\n\t\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\t\tcontrolPropName: control.title || titleCase(controlKey),\n\t\t\t\t\tancestorControlKeyPath,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t\tscopeId: scopeNode.id,\n\t\t\t\t\tvalue,\n\t\t\t\t\tvalueWordCount: value ? 1 : 0,\n\t\t\t\t\thash: latestHash,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tlocalizedValueStatuses,\n\t\t\t\t\tmanagedByPluginButUserEditable: false,\n\t\t\t\t\taiTranslationDisabled: true,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.RichText: {\n\t\t\t\tif (controlType !== ControlType.RichText || !isRichTextTreeValue(controlProp.value)) break\n\t\t\t\tif (control.type === ControlType.RichText && control.preventLocalization) break\n\n\t\t\t\tif (!isKeySetAndNotInherited(tree, node, prefixControlPropKey(controlKey))) break\n\n\t\t\t\tconst richTextValue: RichTextTreeValue = controlProp.value\n\t\t\t\t// For HTML-backed values, keep source.value as the HTML string (unchanged behavior).\n\t\t\t\t// For JSON-backed values, source.value is plain text content.\n\t\t\t\tconst value =\n\t\t\t\t\ttypeof richTextValue === \"string\" ? richTextValue : getPlainTextFromRichTextTreeValue(richTextValue)\n\t\t\t\tconst latestHash = getRichTextLocalizationHash(richTextValue, componentLoader)\n\n\t\t\t\tconst localizedValues = controlProp.valueLocalized ?? noLocalizedValues\n\t\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash)\n\n\t\t\t\tresult.push({\n\t\t\t\t\ttype: ControlType.RichText,\n\t\t\t\t\tkeyPath: getKeyPathForControlProp(node.id, controlKey, ancestorControlKeyPath),\n\t\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\t\tcontrolPropName: control.title || titleCase(controlKey),\n\t\t\t\t\tancestorControlKeyPath,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t\tscopeId: scopeNode.id,\n\t\t\t\t\trichTextValue,\n\t\t\t\t\tvalue,\n\t\t\t\t\tvalueWordCount: getWordCount(value, typeof richTextValue === \"string\"),\n\t\t\t\t\thash: latestHash,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tlocalizedValueStatuses,\n\t\t\t\t\tmanagedByPluginButUserEditable: false,\n\t\t\t\t\tcontentType: undefined,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.Image: {\n\t\t\t\tif (!controlProp || controlProp.type !== ControlType.Image || !isString(controlProp.value)) break\n\t\t\t\tif (control.type !== ControlType.ResponsiveImage && control.type !== ControlType.Image) break\n\n\t\t\t\tif (!isKeySetAndNotInherited(tree, node, prefixControlPropKey(controlKey))) break\n\n\t\t\t\tconst supportsAlt = control.type === ControlType.ResponsiveImage\n\t\t\t\tconst value = controlProp.alt ?? fallbackAltText\n\t\t\t\tconst latestHash = murmurHash(value)\n\t\t\t\tconst localizedValues = supportsAlt ? (controlProp.altLocalized ?? noLocalizedValues) : noLocalizedValues\n\n\t\t\t\tconst image = controlProp.value\n\t\t\t\tconst imageHash = murmurHash(image)\n\t\t\t\tconst imageLocalizedValues = controlProp.valueLocalized ?? noLocalizedValues\n\n\t\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(\n\t\t\t\t\tvalue,\n\t\t\t\t\tlocales,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tlatestHash,\n\t\t\t\t\tundefined,\n\t\t\t\t\timageStatusResolver(image, imageLocalizedValues, imageHash),\n\t\t\t\t)\n\n\t\t\t\tconst supportsFocalPoint = control.type === ControlType.ResponsiveImage\n\n\t\t\t\tresult.push({\n\t\t\t\t\ttype: ControlType.Image,\n\t\t\t\t\tkeyPath: getKeyPathForControlProp(node.id, controlKey, ancestorControlKeyPath),\n\t\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\t\tcontrolPropName: control.title || titleCase(controlKey),\n\t\t\t\t\tancestorControlKeyPath,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t\tscopeId: scopeNode.id,\n\t\t\t\t\tvalue,\n\t\t\t\t\tvalueWordCount: getWordCount(value),\n\t\t\t\t\thash: latestHash,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tlocalizedValueStatuses,\n\t\t\t\t\tmanagedByPluginButUserEditable: false,\n\t\t\t\t\tsupportsAlt,\n\t\t\t\t\timage,\n\t\t\t\t\timageHash,\n\t\t\t\t\timageLocalizedValues,\n\t\t\t\t\tsupportsFocalPoint,\n\t\t\t\t\tpositionX: supportsFocalPoint ? controlProp.positionX : undefined,\n\t\t\t\t\tpositionY: supportsFocalPoint ? controlProp.positionY : undefined,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tshouldBeNever(controlType)\n\t\t}\n\t}\n\n\tfor (const controlKey in controlProps) {\n\t\tconst controlProp = controlProps[controlKey]\n\t\tif (!controlProp) continue\n\t\tconst control = component.properties[controlKey]\n\t\tif (!control) continue\n\t\taddControlProp(controlKey, controlProp, control)\n\t}\n}\n\nfunction collectLocalizationSourcesFromFormSelectNode(\n\tscopeNode: LocalizationScope,\n\tnode: FormSelectNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tswitch (node.bindingType) {\n\t\tcase \"form\": {\n\t\t\tconst options = node.formSelectOptions\n\t\t\tif (!options || options.length === 0) return\n\n\t\t\tfor (const option of options) {\n\t\t\t\tconst title = option.title\n\t\t\t\tif (!title) continue\n\t\t\t\tconst localizedValues = option.titleLocalized ?? noLocalizedValues\n\t\t\t\tconst latestHash = murmurHash(title)\n\n\t\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(title, locales, localizedValues, latestHash)\n\n\t\t\t\tresult.push({\n\t\t\t\t\ttype: ClassDiscriminator.FormSelectNode,\n\t\t\t\t\tkeyPath: `${node.id}_${option.id}`,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t\toptionId: option.id,\n\t\t\t\t\tscopeId: scopeNode.id,\n\t\t\t\t\tvalue: title,\n\t\t\t\t\tvalueWordCount: getWordCount(title),\n\t\t\t\t\thash: latestHash,\n\t\t\t\t\tlocalizedValues,\n\t\t\t\t\tlocalizedValueStatuses,\n\t\t\t\t\tmanagedByPluginButUserEditable: false,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t\tcase \"variable\": {\n\t\t\tif (!node.variableBinding) return\n\t\t\tif (!isScopeNode(scopeNode)) return\n\t\t\tif (!withVariables(scopeNode)) return\n\n\t\t\tconst variable = scopeNode.getVariable(node.variableBinding.id)\n\t\t\tif (!variable) return\n\n\t\t\tif (isOptionalVariable(variable, getScopeTypeForScope(scopeNode))) {\n\t\t\t\tresult.push(\n\t\t\t\t\tcreateFormSelectGenericOptionSource(\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\tscopeNode,\n\t\t\t\t\t\tlocales,\n\t\t\t\t\t\t\"allItemsLabel\",\n\t\t\t\t\t\tnode.allItemsLabelWithDefault,\n\t\t\t\t\t\tnode.allItemsLabelLocalized,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (variable.type === ControlType.Boolean) {\n\t\t\t\tresult.push(\n\t\t\t\t\tcreateFormSelectGenericOptionSource(\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\tscopeNode,\n\t\t\t\t\t\tlocales,\n\t\t\t\t\t\t\"booleanTrueLabel\",\n\t\t\t\t\t\tnode.booleanTrueLabelWithDefault,\n\t\t\t\t\t\tnode.booleanTrueLabelLocalized,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\tresult.push(\n\t\t\t\t\tcreateFormSelectGenericOptionSource(\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\tscopeNode,\n\t\t\t\t\t\tlocales,\n\t\t\t\t\t\t\"booleanFalseLabel\",\n\t\t\t\t\t\tnode.booleanFalseLabelWithDefault,\n\t\t\t\t\t\tnode.booleanFalseLabelLocalized,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t\tdefault:\n\t\t\tassertNever(node.bindingType)\n\t}\n}\n\nfunction createFormSelectGenericOptionSource(\n\tnode: FormSelectNode,\n\tscopeNode: LocalizationScope,\n\tlocales: readonly Locale[],\n\toptionKey: LocalizationSourceFormSelectGenericOption[\"key\"],\n\tlabel: string,\n\tlabelLocalized: LocalizedValues<LocalizedTextValue> | undefined,\n): LocalizationSourceFormSelectGenericOption {\n\tconst localizedValues = labelLocalized ?? noLocalizedValues\n\tconst latestHash = murmurHash(label)\n\tconst localizedValueStatuses = getLocalizedValueStatuses(label, locales, localizedValues, latestHash)\n\n\treturn {\n\t\ttype: \"formSelectGenericOption\",\n\t\tkeyPath: `${node.id}_${optionKey}`,\n\t\tnodeId: node.id,\n\t\tkey: optionKey,\n\t\tscopeId: scopeNode.id,\n\t\tvalue: label,\n\t\tvalueWordCount: getWordCount(label),\n\t\thash: latestHash,\n\t\tlocalizedValues,\n\t\tlocalizedValueStatuses,\n\t\tmanagedByPluginButUserEditable: false,\n\t}\n}\n\nfunction collectLocalizationSourcesFromFormPlainTextInputNode(\n\ttree: CanvasTree,\n\tscopeNode: LocalizationScope,\n\tnode: FormPlainTextInputNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n) {\n\tconst keyPath = `${node.id}_placeholder`\n\n\tif (isDynamicValue(node.formInputPlaceholder)) {\n\t\tif (isVariableReference(node.formInputPlaceholder)) return\n\t\tif (!isKeySetAndNotInherited(tree, node, \"formInputPlaceholder\")) return\n\n\t\tcollectLocalizationSourcesFromComputedValue(\n\t\t\tscopeNode,\n\t\t\tnode,\n\t\t\tnode.formInputPlaceholder,\n\t\t\tkeyPath,\n\t\t\tnode.id,\n\t\t\tlocales,\n\t\t\tresult,\n\t\t)\n\t\treturn\n\t}\n\n\tif (!node.formInputPlaceholder) return\n\tif (!isKeySetAndNotInherited(tree, node, \"formInputPlaceholder\")) return\n\tconst latestHash = murmurHash(node.formInputPlaceholder)\n\tconst localizedValues = node.formInputPlaceholderLocalized ?? noLocalizedValues\n\n\tresult.push({\n\t\tkeyPath,\n\t\ttype: ClassDiscriminator.FormPlainTextInputNode,\n\t\tnodeId: node.id,\n\t\tscopeId: scopeNode.id,\n\t\tvalue: node.formInputPlaceholder,\n\t\tvalueWordCount: getWordCount(node.formInputPlaceholder),\n\t\thash: murmurHash(node.formInputPlaceholder),\n\t\tlocalizedValues,\n\t\tlocalizedValueStatuses: getLocalizedValueStatuses(node.formInputPlaceholder, locales, localizedValues, latestHash),\n\t\tmanagedByPluginButUserEditable: false,\n\t})\n}\n\nexport function collectLocalizationSourcesFromCanvasNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tscopeNode: LocalizationScope,\n\tnode: CanvasNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n\trichTextBehavior: RichTextValueBehavior,\n) {\n\tif (isWebPageNode(node)) {\n\t\tcollectTitleAndDescriptionLocalizationSources(tree, componentLoader, scopeNode, node, locales, result)\n\t}\n\n\tif (isRichTextNode(node)) {\n\t\tcollectLocalizationSourceFromRichTextNode(tree, scopeNode, node, locales, result, richTextBehavior)\n\t}\n\n\tif (isCodeComponentNode(node) || isWebPageNode(node)) {\n\t\tcollectLocalizationSourcesFromControlPropsNode(tree, componentLoader, scopeNode, node, locales, result)\n\t}\n\n\tif (isFrameNode(node)) {\n\t\tcollectLocalizationSourcesFromFrameNode(tree, scopeNode, node, locales, result)\n\t}\n\n\tif (isSVGNode(node) || isShapeContainerNode(node)) {\n\t\tcollectNodeLinkLocalizationSource(scopeNode, node, locales, result)\n\t}\n\n\tif (isFormPlainTextInputNode(node)) {\n\t\tcollectLocalizationSourcesFromFormPlainTextInputNode(tree, scopeNode, node, locales, result)\n\t}\n\n\tif (isFormSelectNode(node)) {\n\t\tcollectLocalizationSourcesFromFormSelectNode(scopeNode, node, locales, result)\n\t}\n}\n\nconst buildUpdateString = (node: CanvasNode, additionalDependencyNode: CanvasNode | undefined): string => {\n\tif (!additionalDependencyNode) return node.update.toString()\n\treturn `${node.update}-${additionalDependencyNode.update}`\n}\n\nfunction canUseCache(richTextBehavior: RichTextValueBehavior | undefined): boolean {\n\t// The localization view is constantly re-rendering with all of the latest values. So it needs\n\t// to be fast. Plugins request this data less often. So we skip the cache for now. They can't\n\t// use the same cache because they have different behavior. Our UI uses the\n\t// `canvasHtmlAsStringIfPossible` behavior while plugins use `canvasHtmlAsHtml`.\n\tif (richTextBehavior === \"canvasHtmlAsHtml\") return false\n\treturn true\n}\n\nfunction getSourceGroupCacheIfValid(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tadditionalDependencyNode: CanvasNode | undefined,\n\tlocales: readonly Locale[],\n\tcomponentHash: string | NotDependentOnComponentLoader,\n\tvariables: VariablesAndDividers | NotDependentOnParentVariables,\n\tsubGroups: LocalizationSourceGroupCollectionItem[] | undefined,\n\tsettings: TranslatePagePathSettings | undefined,\n\trichTextBehavior: RichTextValueBehavior | undefined,\n): SourceGroupCache | undefined {\n\tif (!canUseCache(richTextBehavior)) return\n\tif (node.mutable || additionalDependencyNode?.mutable) return\n\n\tconst cache = node.cache.localizationSourceGroup\n\tif (!cache) return\n\n\tif (\n\t\tcache.update !== buildUpdateString(node, additionalDependencyNode) ||\n\t\tcache.componentHash !== componentHash ||\n\t\tcache.locales !== locales ||\n\t\tcache.parentVariables !== variables ||\n\t\t!isShallowEqual(cache.subGroups, subGroups) ||\n\t\t!isShallowEqual(cache.settings, settings)\n\t) {\n\t\treturn\n\t}\n\n\tif (withLocaleConfig(tree, node)) {\n\t\tif (cache.includedLocales !== node.includedLocales) {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn cache\n}\n\nfunction setSourceGroupCache(\n\ttree: CanvasTree,\n\tnode: CanvasNode,\n\tadditionalDependencyNode: CanvasNode | undefined,\n\tgroup: LocalizationSourceGroup | undefined,\n\tlocales: readonly Locale[],\n\tcomponentHash: string | NotDependentOnComponentLoader,\n\tvariables: VariablesAndDividers | NotDependentOnParentVariables,\n\tsubGroups: LocalizationSourceGroupCollectionItem[] | undefined,\n\tsettings: TranslatePagePathSettings | undefined,\n\trichTextBehavior: RichTextValueBehavior | undefined,\n) {\n\tif (!canUseCache(richTextBehavior)) return\n\tif (node.mutable || additionalDependencyNode?.mutable) return\n\n\tnode.cache.localizationSourceGroup = {\n\t\tupdate: buildUpdateString(node, additionalDependencyNode),\n\t\tlocales,\n\t\tcomponentHash,\n\t\tparentVariables: variables,\n\t\tgroup,\n\t\tincludedLocales: withLocaleConfig(tree, node) ? node.includedLocales : undefined,\n\t\tsubGroups,\n\t\tsettings,\n\t}\n}\n\nfunction collectLocalizationSourcesFromCanvasLocalizationScope(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tscopeNode: LocalizationScope,\n\tlocales: readonly Locale[],\n\tcomponentHash: string,\n\tresult: LocalizationSourceGroup[],\n\trichTextBehavior: RichTextValueBehavior,\n) {\n\tconst isAbTestVariant = isWebPageNode(scopeNode) && scopeNode.abTestingParentId !== undefined\n\n\t// We collect the web page nodes from the route segments, but the home page & A/B test variants\n\t// need to be handled separately as they don't have route segments\n\tif (isNonHomePageWebPageNode(tree, scopeNode) && !isAbTestVariant) {\n\t\treturn\n\t}\n\n\tconst cache = getSourceGroupCacheIfValid(\n\t\ttree,\n\t\tscopeNode,\n\t\tundefined,\n\t\tlocales,\n\t\tcomponentHash,\n\t\tnotDependentOnParentVariables,\n\t\tundefined,\n\t\tundefined,\n\t\trichTextBehavior,\n\t)\n\tif (cache) {\n\t\tif (cache.group) result.push(cache.group)\n\t\treturn\n\t}\n\n\tconst items: LocalizationSource[] = []\n\n\tfor (const node of scopeNode.walk()) {\n\t\tcollectLocalizationSourcesFromCanvasNode(tree, componentLoader, scopeNode, node, locales, items, richTextBehavior)\n\t}\n\n\tconst supportsLocaleVisibility = withLocaleConfig(tree, scopeNode)\n\n\tlet group: LocalizationSourceGroup | undefined\n\n\tif (items.length > 0) {\n\t\tlet name = isWebPageNode(scopeNode)\n\t\t\t? getDefaultWebPageTitle(tree, componentLoader, scopeNode)\n\t\t\t: (scopeNode.resolveValue(\"name\") ?? Dictionary.Unknown)\n\n\t\tif (isAbTestVariant) {\n\t\t\tname = `${name} \u00B7 ${scopeNode.resolveValue(\"name\") || getDefaultName(componentLoader, scopeNode)}`\n\t\t}\n\n\t\tgroup = {\n\t\t\ttype: \"sourceGroup\",\n\t\t\tname,\n\t\t\tgroupType: isWebPageNode(scopeNode) ? \"page\" : isLayoutTemplateNode(scopeNode) ? \"template\" : \"component\",\n\t\t\tnodeId: scopeNode.id,\n\t\t\tsupportsLocaleVisibility,\n\t\t\tincludedLocaleIds: supportsLocaleVisibility ? getIncludedLocales(tree, scopeNode) : undefined,\n\t\t\titems,\n\t\t}\n\n\t\tresult.push(group)\n\t}\n\n\tsetSourceGroupCache(\n\t\ttree,\n\t\tscopeNode,\n\t\tundefined,\n\t\tgroup,\n\t\tlocales,\n\t\tcomponentHash,\n\t\tnotDependentOnParentVariables,\n\t\tundefined,\n\t\tundefined,\n\t\trichTextBehavior,\n\t)\n}\n\nexport function getKeyPathForCollectionItemVariable(\n\tcollectionItemId: NodeID,\n\tvariableId: VariableID,\n\tancestorControlKeyPath?: string,\n): string {\n\tif (!ancestorControlKeyPath) {\n\t\treturn `${collectionItemId}.${variableId}`\n\t}\n\n\treturn `${collectionItemId}.${variableId}.${ancestorControlKeyPath}`\n}\n\nfunction getLengthOfLocalizedValue(localizedValue: NonNullLocalizedValue<LocalizedTextValue>): number {\n\treturn getLocalizedValueText(localizedValue).length\n}\n\nfunction getRequiredAndMaxLengthWarningMessages(\n\tlocales: readonly Locale[],\n\tlocalizedValues: LocalizedValues<LocalizedTextValue>,\n\tvariable: StringVariableDefinition | RichTextVariableDefinition | LinkVariableDefinition,\n): LocalizationWarningMessages | undefined {\n\tconst isRequired = variable.required\n\tconst maxLength = variable.type === ControlType.Link ? undefined : variable.options?.maxLength\n\n\tif (!isRequired && !isNumber(maxLength)) return\n\n\tconst warningMessages: Record<LocaleId, string> = {}\n\n\tfor (const locale of locales) {\n\t\tconst localizedValue = localizedValues[locale.id]\n\t\tif (!isNonNullLocalizedValue(localizedValue)) continue\n\n\t\tconst length = getLengthOfLocalizedValue(localizedValue)\n\n\t\tif (isRequired && length === 0) {\n\t\t\twarningMessages[locale.id] = getRequiredFieldWarningMessage(variable.name)\n\t\t} else if (isNumber(maxLength) && length > maxLength) {\n\t\t\twarningMessages[locale.id] = getMaxLengthWarningMessage(length, maxLength)\n\t\t}\n\t}\n\n\treturn warningMessages\n}\n\nexport type SlugOccurrencesByLocale = Record<LocaleId, Map<string, number>>\n\nfunction getDuplicateSlugWarningMessages(\n\tlocales: readonly Locale[],\n\tlocalizedValues: LocalizedValues<LocalizedTextValue>,\n\tslugsByLocale: SlugOccurrencesByLocale,\n\tmessage: string,\n): LocalizationWarningMessages {\n\tconst warningMessages: Record<LocaleId, string> = {}\n\n\tfor (const locale of locales) {\n\t\tconst localizedValue = localizedValues[locale.id]\n\t\tif (!isNonNullLocalizedValue(localizedValue)) continue\n\t\tif (!isString(localizedValue.value)) continue\n\n\t\tconst localeSlugs = slugsByLocale[locale.id]\n\n\t\tconst occurrenceCount = localeSlugs?.get(localizedValue.value)\n\t\tif (occurrenceCount && occurrenceCount > 1) {\n\t\t\twarningMessages[locale.id] = message\n\t\t}\n\t}\n\n\treturn warningMessages\n}\n\nexport function getCollectionItemNodeLocalizationSource(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tscopeId: NodeID,\n\tcollectionItemNode: CollectionItemNode,\n\tlocales: readonly Locale[],\n\tancestorControlKeyPath: string | undefined,\n\tvariable: LocalizableVariable,\n\tcontrolKey: VariableID,\n\tcontrolProp: ControlProp | undefined,\n\tslugsByLocale: SlugOccurrencesByLocale,\n): LocalizationSource | undefined {\n\tconst variableType = variable.type\n\n\tswitch (variableType) {\n\t\tcase ControlType.String: {\n\t\t\tif (isPreventingLocalization(variable)) return\n\n\t\t\tlet value: string | undefined\n\t\t\tif (controlProp) {\n\t\t\t\tif (controlProp.type !== variableType) return\n\t\t\t\tif (!isString(controlProp.value)) return\n\t\t\t\tvalue = controlProp.value\n\t\t\t} else {\n\t\t\t\tif (hasAssociatedStringVariable(variable)) return\n\t\t\t\tvalue = variable.initialValue\n\t\t\t}\n\n\t\t\tconst latestHash = murmurHash(value)\n\n\t\t\tconst localizedValues = controlProp?.valueLocalized ?? noLocalizedValues\n\t\t\tconst warnings = getRequiredAndMaxLengthWarningMessages(locales, localizedValues, variable)\n\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash, warnings)\n\n\t\t\treturn {\n\t\t\t\ttype: ControlType.String,\n\t\t\t\tkeyPath: getKeyPathForCollectionItemVariable(collectionItemNode.id, controlKey, ancestorControlKeyPath),\n\t\t\t\tnodeId: collectionItemNode.id,\n\t\t\t\tscopeId,\n\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\tcontrolPropName: variable.name,\n\t\t\t\tancestorControlKeyPath,\n\t\t\t\tvalue,\n\t\t\t\tvalueWordCount: getWordCount(value),\n\t\t\t\thash: latestHash,\n\t\t\t\tlocalizedValues,\n\t\t\t\tlocalizedValueStatuses,\n\t\t\t\tmanagedByPluginButUserEditable: variable.userEditable ?? false,\n\t\t\t\twarnings,\n\t\t\t}\n\t\t}\n\t\tcase ControlType.Link: {\n\t\t\tif (!controlProp) return\n\t\t\tif (controlProp.type !== variableType) return\n\t\t\tif (!isLinkToURL(controlProp.value)) return\n\t\t\tif (!experiments.isOn(\"localizedLinks\")) return\n\t\t\tconst value = controlProp.value.url\n\n\t\t\tconst latestHash = murmurHash(value)\n\n\t\t\tconst localizedValues = controlProp?.valueLocalized ?? noLocalizedValues\n\t\t\tconst warnings = getRequiredAndMaxLengthWarningMessages(locales, localizedValues, variable)\n\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash, warnings)\n\n\t\t\treturn {\n\t\t\t\ttype: ControlType.Link,\n\t\t\t\tkeyPath: getKeyPathForCollectionItemVariable(collectionItemNode.id, controlKey, ancestorControlKeyPath),\n\t\t\t\tnodeId: collectionItemNode.id,\n\t\t\t\tscopeId,\n\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\tcontrolPropName: variable.name,\n\t\t\t\tancestorControlKeyPath,\n\t\t\t\tvalue,\n\t\t\t\tvalueWordCount: value ? 1 : 0,\n\t\t\t\thash: latestHash,\n\t\t\t\tlocalizedValues,\n\t\t\t\tlocalizedValueStatuses,\n\t\t\t\tmanagedByPluginButUserEditable: variable.userEditable ?? false,\n\t\t\t\twarnings,\n\t\t\t\taiTranslationDisabled: true,\n\t\t\t}\n\t\t}\n\t\tcase \"slug\": {\n\t\t\tif (tree.root.translatePagePaths === \"no\") return\n\n\t\t\t// If the user has somehow managed to create a CMS item without a slug we don't want to crash the app\n\t\t\tif (!controlProp) return\n\t\t\tassert(controlProp.type === ControlType.String, \"expected slug controlType to be a string\")\n\t\t\tassert(isString(controlProp.value), \"expected slug value to be a string\")\n\n\t\t\tconst value = controlProp.value\n\t\t\tconst latestHash = murmurHash(value)\n\t\t\tconst localizedValues = controlProp?.valueLocalized ?? noLocalizedValues\n\t\t\tconst warnings = getDuplicateSlugWarningMessages(\n\t\t\t\tlocales,\n\t\t\t\tlocalizedValues,\n\t\t\t\tslugsByLocale,\n\t\t\t\t\"Each item in the Collection must have a unique slug\",\n\t\t\t)\n\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(\n\t\t\t\tvalue,\n\t\t\t\tlocales,\n\t\t\t\tlocalizedValues,\n\t\t\t\tlatestHash,\n\t\t\t\twarnings,\n\t\t\t\t// Maintain legacy behavior where CMS slugs were included if no translatePagePaths setting is set\n\t\t\t\ttree.root.translatePagePaths === \"legacy\" ? slugAndLinkStatusResolver(localizedValues) : undefined,\n\t\t\t)\n\n\t\t\treturn {\n\t\t\t\ttype: \"slug\",\n\t\t\t\tkeyPath: getKeyPathForCollectionItemVariable(collectionItemNode.id, controlKey, ancestorControlKeyPath),\n\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\tcontrolPropName: variable.name,\n\t\t\t\tancestorControlKeyPath,\n\t\t\t\tnodeId: collectionItemNode.id,\n\t\t\t\tscopeId,\n\t\t\t\tvalue,\n\t\t\t\tvalueWordCount: getWordCount(value),\n\t\t\t\thash: latestHash,\n\t\t\t\tlocalizedValues,\n\t\t\t\tlocalizedValueStatuses,\n\t\t\t\tmanagedByPluginButUserEditable: variable.userEditable ?? false,\n\t\t\t\twarnings,\n\t\t\t\taiTranslationDisabled: !tree.root.translatePagePathsWithAI,\n\t\t\t\tcollectionItemIsDraft: collectionItemNode.isDraft ?? false,\n\t\t\t}\n\t\t}\n\t\tcase ControlType.RichText: {\n\t\t\tlet richTextValue: RichTextTreeValue | undefined\n\t\t\tif (isPreventingLocalization(variable)) return\n\t\t\tif (controlProp) {\n\t\t\t\tif (controlProp.type !== variableType) return\n\t\t\t\tif (!isRichTextTreeValue(controlProp.value)) return\n\t\t\t\trichTextValue = controlProp.value\n\t\t\t} else {\n\t\t\t\trichTextValue = variable.initialValue\n\t\t\t}\n\n\t\t\tconst value = typeof richTextValue === \"string\" ? richTextValue : getPlainTextFromRichTextTreeValue(richTextValue)\n\t\t\tconst latestHash = getRichTextLocalizationHash(richTextValue, componentLoader)\n\n\t\t\tconst localizedValues = controlProp?.valueLocalized ?? noLocalizedValues\n\t\t\tconst warnings = getRequiredAndMaxLengthWarningMessages(locales, localizedValues, variable)\n\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash, warnings)\n\n\t\t\treturn {\n\t\t\t\ttype: ControlType.RichText,\n\t\t\t\tkeyPath: getKeyPathForCollectionItemVariable(collectionItemNode.id, controlKey, ancestorControlKeyPath),\n\t\t\t\tnodeId: collectionItemNode.id,\n\t\t\t\tscopeId,\n\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\tcontrolPropName: variable.name,\n\t\t\t\tancestorControlKeyPath,\n\t\t\t\trichTextValue,\n\t\t\t\tvalue,\n\t\t\t\tvalueWordCount: getWordCount(value, typeof richTextValue === \"string\"),\n\t\t\t\thash: latestHash,\n\t\t\t\tlocalizedValues,\n\t\t\t\tlocalizedValueStatuses,\n\t\t\t\tmanagedByPluginButUserEditable: variable.userEditable ?? false,\n\t\t\t\twarnings,\n\t\t\t\tcontentType: variable.type === ControlType.RichText ? variable.contentType : undefined,\n\t\t\t}\n\t\t}\n\t\tcase ControlType.Image: {\n\t\t\tlet image: string | undefined\n\t\t\tif (controlProp) {\n\t\t\t\tif (controlProp.type !== variableType) return\n\t\t\t\tif (!isString(controlProp.value)) return\n\t\t\t\timage = controlProp.value\n\t\t\t} else {\n\t\t\t\tif (!isString(variable.initialValue)) return\n\t\t\t\timage = variable.initialValue\n\t\t\t}\n\t\t\tconst imageHash = murmurHash(image)\n\t\t\tconst imageLocalizedValues = controlProp?.valueLocalized ?? noLocalizedValues\n\n\t\t\tconst value = controlProp?.alt ?? fallbackAltText\n\t\t\tconst latestHash = murmurHash(value)\n\t\t\tconst localizedValues = controlProp?.altLocalized ?? noLocalizedValues\n\n\t\t\tconst localizedValueStatuses = getLocalizedValueStatuses(\n\t\t\t\tvalue,\n\t\t\t\tlocales,\n\t\t\t\tlocalizedValues,\n\t\t\t\tlatestHash,\n\t\t\t\tundefined,\n\t\t\t\timageStatusResolver(image, imageLocalizedValues, imageHash),\n\t\t\t)\n\n\t\t\treturn {\n\t\t\t\ttype: ControlType.Image,\n\t\t\t\tkeyPath: getKeyPathForCollectionItemVariable(collectionItemNode.id, controlKey, ancestorControlKeyPath),\n\t\t\t\tnodeId: collectionItemNode.id,\n\t\t\t\tscopeId,\n\t\t\t\tcontrolPropKey: controlKey,\n\t\t\t\tcontrolPropName: variable.name,\n\t\t\t\tancestorControlKeyPath,\n\t\t\t\tvalue,\n\t\t\t\tvalueWordCount: getWordCount(value),\n\t\t\t\thash: latestHash,\n\t\t\t\tlocalizedValues,\n\t\t\t\tlocalizedValueStatuses,\n\t\t\t\tsupportsAlt: true,\n\t\t\t\timage,\n\t\t\t\timageHash,\n\t\t\t\timageLocalizedValues,\n\t\t\t\tmanagedByPluginButUserEditable: variable.userEditable ?? false,\n\t\t\t\tsupportsFocalPoint: true,\n\t\t\t\tpositionX: controlProp?.positionX,\n\t\t\t\tpositionY: controlProp?.positionY,\n\t\t\t}\n\t\t}\n\t\tcase ControlType.Enum:\n\t\t\treturn\n\t\tdefault:\n\t\t\t// All localizable variables should be handled\n\t\t\tshouldBeNever(variableType)\n\t}\n}\n\nexport function collectLocalizationSourcesFromCollectionItemNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tcollectionNode: CollectionNode,\n\tcollectionItemNode: CollectionItemNode,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSource[],\n\tslugsByLocale: SlugOccurrencesByLocale,\n) {\n\tconst scopeId = collectionItemNode.id\n\n\tfunction addControlProp(\n\t\tcontrolKey: VariableID,\n\t\tcontrolProp: ControlProp | undefined,\n\t\tvariable: VariableDefinition,\n\t\tancestorControlKeyPath?: string | undefined,\n\t) {\n\t\tif (controlProp && controlProp.type === ControlType.Array) {\n\t\t\tif (variable.type !== ControlType.Array) return\n\t\t\tif (isDynamicValue(controlProp.value)) return\n\n\t\t\tfor (const item of controlProp.value) {\n\t\t\t\tif (!controlPropCanContainLocalizedValue(item.type)) continue\n\t\t\t\tif (!isObjectControlProp(item)) continue\n\t\t\t\tif (!item.value) continue\n\n\t\t\t\tconst ancestorControlKeyPathForObject = addArrayItemIdToKeyPath(ancestorControlKeyPath, item.id)\n\n\t\t\t\tfor (const itemVariable of variable.itemVariables) {\n\t\t\t\t\tif (!isVariableDefinition(itemVariable)) continue\n\n\t\t\t\t\tconst itemControlProp = item.value[itemVariable.id]\n\t\t\t\t\tif (!itemControlProp) continue\n\t\t\t\t\tif (!controlPropCanContainLocalizedValue(itemControlProp.type)) continue\n\n\t\t\t\t\tconst ancestorControlKeyPathForItem = addObjectPropToKeyPath(ancestorControlKeyPathForObject, itemVariable.id)\n\n\t\t\t\t\taddControlProp(controlKey, itemControlProp, itemVariable, ancestorControlKeyPathForItem)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!isLocalizableVariable(variable)) return\n\n\t\tconst source = getCollectionItemNodeLocalizationSource(\n\t\t\ttree,\n\t\t\tcomponentLoader,\n\t\t\tscopeId,\n\t\t\tcollectionItemNode,\n\t\t\tlocales,\n\t\t\tancestorControlKeyPath,\n\t\t\tvariable,\n\t\t\tcontrolKey,\n\t\t\tcontrolProp,\n\t\t\tslugsByLocale,\n\t\t)\n\n\t\tif (source) {\n\t\t\tresult.push(source)\n\t\t}\n\t}\n\n\tfor (const variable of collectionNode.variables) {\n\t\tif (!isVariableDefinition(variable)) continue\n\t\tconst controlProp = collectionItemNode.getControlProp(variable.id)\n\t\taddControlProp(variable.id, controlProp, variable)\n\t}\n}\n\nconst getSourceGroupSettingsForCache = memoizeOne(\n\t(\n\t\ttranslatePagePaths: TranslatePagePathSettings[\"translatePagePaths\"],\n\t\ttranslatePagePathsWithAI: TranslatePagePathSettings[\"translatePagePathsWithAI\"],\n\t): TranslatePagePathSettings => ({\n\t\ttranslatePagePaths,\n\t\ttranslatePagePathsWithAI,\n\t}),\n)\n\nfunction collectLocalizationSourceGroupFromCollectionItemNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tcollectionNode: LocalizationScope & CollectionNode,\n\tcollectionItemNode: CollectionItemNode,\n\tlocales: readonly Locale[],\n\tcomponentHash: string,\n\tslugsByLocaleId: SlugOccurrencesByLocale,\n\tresult: LocalizationSourceGroup[],\n) {\n\tconst sourceGroupSettingsForCache = getSourceGroupSettingsForCache(\n\t\ttree.root.translatePagePaths,\n\t\ttree.root.translatePagePathsWithAI,\n\t)\n\n\tconst cache = getSourceGroupCacheIfValid(\n\t\ttree,\n\t\tcollectionItemNode,\n\t\tundefined,\n\t\tlocales,\n\t\tcomponentHash,\n\t\tcollectionNode.variables,\n\t\tundefined,\n\t\tsourceGroupSettingsForCache,\n\t\tundefined,\n\t)\n\tif (cache) {\n\t\tif (cache.group) result.push(cache.group)\n\t\treturn\n\t}\n\tconst items: LocalizationSource[] = []\n\n\tconst includedLocales = getIncludedLocales(tree, collectionItemNode)\n\n\tcollectLocalizationSourcesFromCollectionItemNode(\n\t\ttree,\n\t\tcomponentLoader,\n\t\tcollectionNode,\n\t\tcollectionItemNode,\n\t\tlocales,\n\t\titems,\n\t\tslugsByLocaleId,\n\t)\n\n\tif (items.length > 0) {\n\t\tfor (const item of items) {\n\t\t\titem.insetLevel = 1\n\t\t}\n\n\t\tconst itemGroup: LocalizationSourceGroup = {\n\t\t\ttype: \"sourceGroup\",\n\t\t\tgroupType: \"collectionItem\",\n\t\t\tcollectionName: collectionNode.resolveValue(\"name\") ?? Dictionary.Unknown,\n\t\t\tcollectionNodeId: collectionNode.id,\n\t\t\tsupportsLocaleVisibility: true,\n\t\t\tincludedLocaleIds: includedLocales,\n\t\t\tname: getCollectionItemName(collectionNode, collectionItemNode) ?? Dictionary.Unknown,\n\t\t\tnodeId: collectionItemNode.id,\n\t\t\titems,\n\t\t}\n\n\t\tsetSourceGroupCache(\n\t\t\ttree,\n\t\t\tcollectionItemNode,\n\t\t\tundefined,\n\t\t\titemGroup,\n\t\t\tlocales,\n\t\t\tcomponentHash,\n\t\t\tcollectionNode.variables,\n\t\t\tundefined,\n\t\t\tsourceGroupSettingsForCache,\n\t\t\tundefined,\n\t\t)\n\t\tresult.push(itemGroup)\n\t}\n}\n\nexport function getEnumCaseLocalizationSource(\n\tnode: CanvasNode & WithVariables,\n\tvariable: EnumVariableDefinition,\n\tenumCase: EnumVariableCase,\n\tlocales: readonly Locale[],\n): LocalizationSource {\n\tconst value: string = enumCase.name\n\tconst latestHash = murmurHash(value)\n\n\tconst localizedValues = enumCase.nameLocalized ?? noLocalizedValues\n\tconst localizedValueStatuses = getLocalizedValueStatuses(value, locales, localizedValues, latestHash)\n\n\treturn {\n\t\ttype: ControlType.Enum,\n\t\tkeyPath: `${node.id}_${variable.id}_${enumCase.id}`,\n\t\tnodeId: node.id,\n\t\tscopeId: node.id,\n\t\tvariableId: variable.id,\n\t\tenumCaseId: enumCase.id,\n\t\tvalue,\n\t\tvalueWordCount: getWordCount(value),\n\t\thash: latestHash,\n\t\tlocalizedValues,\n\t\tlocalizedValueStatuses,\n\t\tmanagedByPluginButUserEditable: false,\n\t}\n}\n\nfunction collectLocalizationSourcesFromCollectionNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tcollectionNode: CollectionNode,\n\tlocales: readonly Locale[],\n\tcomponentHash: string,\n\tresult: LocalizationSourceGroup[],\n) {\n\tconst collectionItemSourceGroups: LocalizationSourceGroupCollectionItem[] = []\n\tconst slugsByLocaleId = getCollectionSlugOccurrencesByLocaleId(locales, collectionNode)\n\n\tfor (const collectionItemNode of collectionNode.getUnsortedChildren()) {\n\t\tcollectLocalizationSourceGroupFromCollectionItemNode(\n\t\t\ttree,\n\t\t\tcomponentLoader,\n\t\t\tcollectionNode,\n\t\t\tcollectionItemNode,\n\t\t\tlocales,\n\t\t\tcomponentHash,\n\t\t\tslugsByLocaleId,\n\t\t\tcollectionItemSourceGroups,\n\t\t)\n\t}\n\n\tconst cache = getSourceGroupCacheIfValid(\n\t\ttree,\n\t\tcollectionNode,\n\t\tundefined,\n\t\tlocales,\n\t\tcomponentHash,\n\t\tnotDependentOnParentVariables,\n\t\tcollectionItemSourceGroups,\n\t\tundefined,\n\t\tundefined,\n\t)\n\tif (cache) {\n\t\tif (cache.group) result.push(cache.group)\n\t\treturn\n\t}\n\n\tconst localizableVariables = collectionNode.variables.filter(isLocalizableVariable)\n\tif (localizableVariables.length === 0) return\n\n\tconst enumItems: LocalizationSource[] = []\n\tfor (const variable of localizableVariables) {\n\t\tconst variableType = variable.type\n\n\t\tswitch (variableType) {\n\t\t\tcase ControlType.Enum: {\n\t\t\t\tif (isPreventingLocalization(variable)) break\n\n\t\t\t\tfor (const enumCase of variable.cases) {\n\t\t\t\t\tenumItems.push(getEnumCaseLocalizationSource(collectionNode, variable, enumCase, locales))\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.String:\n\t\t\tcase ControlType.RichText:\n\t\t\tcase ControlType.Image:\n\t\t\tcase ControlType.Link:\n\t\t\tcase \"slug\":\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tshouldBeNever(variableType)\n\t\t}\n\t}\n\tconst group: LocalizationSourceGroupCollection | undefined =\n\t\tenumItems.length > 0 || collectionItemSourceGroups.length > 0\n\t\t\t? {\n\t\t\t\t\ttype: \"sourceGroup\",\n\t\t\t\t\tgroupType: \"collection\",\n\t\t\t\t\tname: collectionNode.resolveValue(\"name\") ?? Dictionary.Unknown,\n\t\t\t\t\tnodeId: collectionNode.id,\n\t\t\t\t\tsupportsLocaleVisibility: false,\n\t\t\t\t\tincludedLocaleIds: undefined,\n\t\t\t\t\titems: enumItems,\n\t\t\t\t\tgroups: collectionItemSourceGroups,\n\t\t\t\t}\n\t\t\t: undefined\n\n\tsetSourceGroupCache(\n\t\ttree,\n\t\tcollectionNode,\n\t\tundefined,\n\t\tgroup,\n\t\tlocales,\n\t\tcomponentHash,\n\t\tnotDependentOnParentVariables,\n\t\tcollectionItemSourceGroups,\n\t\tundefined,\n\t\tundefined,\n\t)\n\tif (group) result.push(group)\n}\n\nexport function getCollectionSlugOccurrencesByLocaleId(\n\tlocales: readonly Locale[],\n\tcollectionNode: LocalizationScope & CollectionNode,\n): Readonly<SlugOccurrencesByLocale> {\n\tconst slugsByLocaleId: SlugOccurrencesByLocale = {}\n\tfor (const locale of locales) {\n\t\tslugsByLocaleId[locale.id] = new Map()\n\t}\n\n\tconst slugVariable = collectionNode.getSlugVariable()\n\tif (!slugVariable) return slugsByLocaleId\n\n\tfor (const collectionItemNode of collectionNode.getUnsortedChildren()) {\n\t\tconst controlProp = collectionItemNode.getControlProp(slugVariable.id)\n\n\t\tif (!controlProp) continue\n\n\t\tassert(controlProp.type === ControlType.String, \"expect slug control type to be be of type string\")\n\t\tassert(isString(controlProp.value), \"expected slug control prop value to be string\")\n\n\t\tif (!controlProp.valueLocalized) continue\n\n\t\tfor (const localeId in controlProp.valueLocalized) {\n\t\t\tconst localizedValue = controlProp.valueLocalized[localeId]\n\t\t\tconst slugsForLocale = slugsByLocaleId[localeId]\n\n\t\t\tif (!slugsForLocale || !isString(localizedValue?.value) || !localizedValue.value) continue\n\n\t\t\tconst nextCount = (slugsForLocale.get(localizedValue.value) ?? 0) + 1\n\t\t\tslugsForLocale.set(localizedValue.value, nextCount)\n\t\t}\n\t}\n\n\treturn slugsByLocaleId\n}\n\nfunction getRouteSegmentSiblingSlugOccurrencesByLocaleId(\n\ttree: CanvasTree,\n\tlocales: readonly RouterLocale[],\n\trouteSegmentNode: RouteSegmentNode,\n): Readonly<SlugOccurrencesByLocale> {\n\tconst routeSegmentSiblingNodes = tree.getParent(routeSegmentNode.id)?.children ?? []\n\n\tconst slugsByLocaleId: SlugOccurrencesByLocale = {}\n\tfor (const locale of locales) {\n\t\tif (locale.id === defaultLocaleId) continue\n\n\t\tslugsByLocaleId[locale.id] = new Map()\n\t}\n\n\tfor (const siblingNode of routeSegmentSiblingNodes) {\n\t\tif (!isRouteSegmentNode(siblingNode)) continue\n\t\tconst { segment, segmentLocalized } = siblingNode\n\n\t\t// We need to loop over all locales, not just the locales present in segmentLocalized as we\n\t\t// also need to check against default values for segments without localized values\n\t\tfor (const locale of locales) {\n\t\t\tif (locale.id === defaultLocaleId) continue\n\n\t\t\tconst segmentLocalizedValueWithFallback = getLocalizedValueForActiveLocale(locale, segmentLocalized)?.value\n\t\t\tconst localizedSegment = isString(segmentLocalizedValueWithFallback)\n\t\t\t\t? segmentLocalizedValueWithFallback\n\t\t\t\t: undefined\n\t\t\tconst value = localizedSegment || segment\n\n\t\t\tconst slugsForLocale = slugsByLocaleId[locale.id]\n\t\t\tif (!slugsForLocale) continue\n\n\t\t\tconst nextCount = (slugsForLocale.get(value) ?? 0) + 1\n\t\t\tslugsForLocale.set(value, nextCount)\n\t\t}\n\t}\n\treturn slugsByLocaleId\n}\n\nfunction collectRootNodeLocalizationSourceGroup(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tlocales: readonly Locale[],\n\tresult: LocalizationSourceGroup[],\n) {\n\tconst cache = getSourceGroupCacheIfValid(\n\t\ttree,\n\t\ttree.root,\n\t\tundefined,\n\t\tlocales,\n\t\tnotDependentOnComponentLoader,\n\t\tnotDependentOnParentVariables,\n\t\tundefined,\n\t\tundefined,\n\t\tundefined,\n\t)\n\tif (cache) {\n\t\tif (cache.group) result.push(cache.group)\n\t\treturn\n\t}\n\n\tconst items: LocalizationSource[] = []\n\n\tcollectTitleAndDescriptionLocalizationSources(tree, componentLoader, tree.root, tree.root, locales, items)\n\n\tconst group: LocalizationSourceGroup | undefined =\n\t\titems.length > 0\n\t\t\t? {\n\t\t\t\t\ttype: \"sourceGroup\",\n\t\t\t\t\tgroupType: \"settings\",\n\t\t\t\t\tname: Dictionary.SiteSettings,\n\t\t\t\t\tnodeId: tree.root.id,\n\t\t\t\t\tsupportsLocaleVisibility: false,\n\t\t\t\t\tincludedLocaleIds: undefined,\n\t\t\t\t\titems,\n\t\t\t\t}\n\t\t\t: undefined\n\n\tsetSourceGroupCache(\n\t\ttree,\n\t\ttree.root,\n\t\tundefined,\n\t\tgroup,\n\t\tlocales,\n\t\tnotDependentOnComponentLoader,\n\t\tnotDependentOnParentVariables,\n\t\tundefined,\n\t\tundefined,\n\t\tundefined,\n\t)\n\tif (group) result.push(group)\n}\n\nexport function collectLocalizationSourcesFromContentManagementNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: ContentManagementNode,\n\tlocales: readonly Locale[],\n\tcomponentHash: string,\n\tresult: LocalizationSourceGroup[],\n) {\n\tfor (const collectionNode of node.children) {\n\t\tcollectLocalizationSourcesFromCollectionNode(tree, componentLoader, collectionNode, locales, componentHash, result)\n\t}\n}\n\nexport function collectLocalizationSourcesFromRouteSegmentNode(\n\ttree: CanvasTree,\n\tscopeNode: LocalizationScope,\n\tnode: RouteSegmentNode,\n\tlocales: readonly Locale[],\n\trouterLocales: readonly RouterLocale[],\n\tresult: LocalizationSource[],\n) {\n\tif (!checkShouldSegmentBeLocalized(node)) return\n\tconst displaySegment = getPathForDisplay(node.segment)\n\tconst latestHash = murmurHash(node.segment)\n\tconst localizedValues = node.segmentLocalized ?? noLocalizedValues\n\tconst warnings = getDuplicateSlugWarningMessages(\n\t\tlocales,\n\t\tlocalizedValues,\n\t\tgetRouteSegmentSiblingSlugOccurrencesByLocaleId(tree, routerLocales, node),\n\t\t\"Sibling pages must have unique slugs\",\n\t)\n\tresult.push({\n\t\tkeyPath: node.id,\n\t\ttype: ClassDiscriminator.RouteSegmentNode,\n\t\tnodeId: node.id,\n\t\tscopeId: scopeNode.id,\n\t\tvalue: displaySegment,\n\t\tvalueWordCount: getWordCount(displaySegment),\n\t\thash: murmurHash(node.segment),\n\t\tlocalizedValues,\n\t\tlocalizedValueStatuses: getLocalizedValueStatuses(\n\t\t\tnode.segment,\n\t\t\tlocales,\n\t\t\tlocalizedValues,\n\t\t\tlatestHash,\n\t\t\twarnings,\n\t\t\tundefined,\n\t\t),\n\t\tmanagedByPluginButUserEditable: false,\n\t\twarnings,\n\t\taiTranslationDisabled: !tree.root.translatePagePathsWithAI,\n\t})\n}\n\nfunction collectLocalizationSourcesFromRouteSegmentRootNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\trootNode: RouteSegmentRootNode,\n\tlocales: readonly Locale[],\n\tcomponentHash: string,\n\tresult: LocalizationSourceGroup[],\n\trichTextBehavior: RichTextValueBehavior,\n) {\n\tconst routerLocales = getRouterLocales(tree, \"includeDrafts\")\n\tconst processedWebPageIds = new Set<NodeID>()\n\n\tfor (const routeSegmentNode of rootNode.walk()) {\n\t\tif (!isRouteSegmentNode(routeSegmentNode)) continue\n\t\tcollectLocalizationSourcesFromCombinedRouteAndWebPageNode(\n\t\t\ttree,\n\t\t\tcomponentLoader,\n\t\t\trouteSegmentNode,\n\t\t\tlocales,\n\t\t\trouterLocales,\n\t\t\tcomponentHash,\n\t\t\tresult,\n\t\t\trichTextBehavior,\n\t\t\tprocessedWebPageIds,\n\t\t)\n\t}\n}\n\nfunction collectLocalizationSourcesFromCombinedRouteAndWebPageNode(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\trouteSegmentNode: RouteSegmentNode,\n\tlocales: readonly Locale[],\n\trouterLocales: readonly RouterLocale[],\n\tcomponentHash: string,\n\tresult: LocalizationSourceGroup[],\n\trichTextBehavior: RichTextValueBehavior,\n\tprocessedWebPageIds: Set<NodeID>,\n) {\n\tconst correspondingWebPageNode = routeSegmentNode.webPageId ? tree.get(routeSegmentNode.webPageId) : undefined\n\tconst loadedWebPageNode =\n\t\tisWebPageNode(correspondingWebPageNode) && correspondingWebPageNode.isLoaded() ? correspondingWebPageNode : null\n\tconst sourceGroupSettingsForCache = getSourceGroupSettingsForCache(\n\t\ttree.root.translatePagePaths,\n\t\ttree.root.translatePagePathsWithAI,\n\t)\n\n\t// Skip if we've already processed this web page (multiplayer issue: two route nodes can reference the same web page)\n\tconst skipWebPageNodeCollection = correspondingWebPageNode && processedWebPageIds.has(correspondingWebPageNode.id)\n\n\t// If we have a web page node, use that for the scope & caching\n\tconst scopeNode: LocalizationScope = loadedWebPageNode || routeSegmentNode\n\tconst additionalCacheDependencyNode = scopeNode === loadedWebPageNode ? routeSegmentNode : undefined\n\n\tconst cache = getSourceGroupCacheIfValid(\n\t\ttree,\n\t\tscopeNode,\n\t\tadditionalCacheDependencyNode,\n\t\tlocales,\n\t\tcomponentHash,\n\t\tnotDependentOnParentVariables,\n\t\tundefined,\n\t\tsourceGroupSettingsForCache,\n\t\trichTextBehavior,\n\t)\n\tif (cache) {\n\t\tif (cache.group) result.push(cache.group)\n\t\treturn\n\t}\n\n\tconst items: LocalizationSource[] = []\n\n\tif (tree.root.translatePagePaths === \"yes\") {\n\t\tcollectLocalizationSourcesFromRouteSegmentNode(tree, scopeNode, routeSegmentNode, locales, routerLocales, items)\n\t}\n\n\tif (correspondingWebPageNode && !skipWebPageNodeCollection) {\n\t\tfor (const node of correspondingWebPageNode.walk()) {\n\t\t\tcollectLocalizationSourcesFromCanvasNode(tree, componentLoader, scopeNode, node, locales, items, richTextBehavior)\n\t\t}\n\t\tprocessedWebPageIds.add(correspondingWebPageNode.id)\n\t}\n\n\tlet group: LocalizationSourceGroup | undefined\n\n\tlet name = isWebPageNode(correspondingWebPageNode)\n\t\t? getDefaultWebPageTitle(tree, componentLoader, correspondingWebPageNode)\n\t\t: pathToName(getTitleForRouteSegment(routeSegmentNode, tree))\n\n\tif (isWebPageNode(scopeNode) && scopeNode.abTestingParentId) {\n\t\tname = `${name} \u00B7 ${scopeNode.resolveValue(\"name\") || getDefaultName(componentLoader, scopeNode)}`\n\t}\n\n\t// If we have an additional trailing slash folder it needs that in the name to distinguish from\n\t// its parent\n\tif (routeSegmentNode.segment === \"\") {\n\t\tname = `${name} /`\n\t}\n\n\tconst supportsLocaleVisibility = withLocaleConfig(tree, scopeNode)\n\n\tif (items.length > 0) {\n\t\tgroup = {\n\t\t\ttype: \"sourceGroup\",\n\t\t\tname,\n\t\t\tgroupType: \"page\",\n\t\t\tnodeId: scopeNode.id,\n\t\t\tsupportsLocaleVisibility,\n\t\t\tincludedLocaleIds: supportsLocaleVisibility ? getIncludedLocales(tree, scopeNode) : undefined,\n\t\t\titems,\n\t\t}\n\n\t\tresult.push(group)\n\t}\n\n\tsetSourceGroupCache(\n\t\ttree,\n\t\tscopeNode,\n\t\tadditionalCacheDependencyNode,\n\t\tgroup,\n\t\tlocales,\n\t\tcomponentHash,\n\t\tnotDependentOnParentVariables,\n\t\tundefined,\n\t\tsourceGroupSettingsForCache,\n\t\trichTextBehavior,\n\t)\n}\n\nexport function getLocalizationSourceGroups(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tlocales: readonly Locale[] | undefined,\n\tcomponentHash: string,\n\tcanvasRichTextBehavior: RichTextValueBehavior,\n): LocalizationSourceGroup[] {\n\tconst result: LocalizationSourceGroup[] = []\n\tif (!locales || locales.length === 0) return result\n\n\tcollectRootNodeLocalizationSourceGroup(tree, componentLoader, locales, result)\n\n\tfor (const rootChild of tree.root.children) {\n\t\t// Web page nodes with corresponding route segments are handled when collecting the route\n\t\t// segment nodes. The home page and any A/B test variants need to be handled separately as\n\t\t// they don't have route segments.\n\t\tconst isAbTestVariant = isWebPageNode(rootChild) && rootChild.abTestingParentId !== undefined\n\t\tif (isNonHomePageWebPageNode(tree, rootChild) && !isAbTestVariant) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isCanvasLocalizationScope(rootChild)) {\n\t\t\t// NOTE: Full tree loading is handled by LocalizationStore <https://github.com/framer/FramerStudio/pull/18448>\n\t\t\tassert(rootChild.isLoaded(), \"Scope node must be fully loaded\")\n\t\t\tcollectLocalizationSourcesFromCanvasLocalizationScope(\n\t\t\t\ttree,\n\t\t\t\tcomponentLoader,\n\t\t\t\trootChild,\n\t\t\t\tlocales,\n\t\t\t\tcomponentHash,\n\t\t\t\tresult,\n\t\t\t\tcanvasRichTextBehavior,\n\t\t\t)\n\t\t}\n\n\t\tif (isContentManagementNode(rootChild)) {\n\t\t\t// NOTE: Full tree loading is handled by LocalizationStore <https://github.com/framer/FramerStudio/pull/18448>\n\t\t\tassert(rootChild.isLoaded(), \"Scope node must be fully loaded\")\n\t\t\tcollectLocalizationSourcesFromContentManagementNode(\n\t\t\t\ttree,\n\t\t\t\tcomponentLoader,\n\t\t\t\trootChild,\n\t\t\t\tlocales,\n\t\t\t\tcomponentHash,\n\t\t\t\tresult,\n\t\t\t)\n\t\t}\n\n\t\tif (isRouteSegmentRootNode(rootChild)) {\n\t\t\tcollectLocalizationSourcesFromRouteSegmentRootNode(\n\t\t\t\ttree,\n\t\t\t\tcomponentLoader,\n\t\t\t\trootChild,\n\t\t\t\tlocales,\n\t\t\t\tcomponentHash,\n\t\t\t\tresult,\n\t\t\t\tcanvasRichTextBehavior,\n\t\t\t)\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunction isNonHomePageWebPageNode(tree: CanvasTree, node: CanvasNode) {\n\treturn isWebPageNode(node) && node.id !== tree.root.homePageNodeId\n}\n\nexport function isEqualLocalizationSource(a: LocalizationSource, b: LocalizationSource): boolean {\n\treturn isEqual(a, b)\n}\n\n/** Expects the group items to already be memoized. */\nexport function isEqualLocalizationGroup(a: LocalizationSourceGroup, b: LocalizationSourceGroup): boolean {\n\treturn isShallowEqual(a, b)\n}\n\nexport function isLocalizationSourceGroup(\n\tvalue: LocalizationSource | LocalizationSourceGroup,\n): value is LocalizationSourceGroup {\n\treturn value.type === \"sourceGroup\"\n}\n", "import { getServiceMap } from \"@framerjs/framer-environment/domains.ts\"\n\n/**\n * Builds an HTTP URL on the Multiplayer Service, which is mounted at\n * `/multiplayer` on the API host. `path` should start with `/`.\n *\n * Kept free of any auth-refresher import so this module can be loaded in\n * non-DOM test environments without dragging in the rest of the editor's\n * runtime (fresco, layout-transitions, etc.) via `accessTokenRefresherWeb`.\n */\nexport function getMultiplayerServiceURL(path: string): string {\n\treturn new URL(`/multiplayer${path}`, getServiceMap().api).href\n}\n\n/** Returns true when the URL targets the Multiplayer Service. */\nexport function isMultiplayerServiceURL(url: string): boolean {\n\ttry {\n\t\treturn new URL(url).pathname.startsWith(\"/multiplayer\")\n\t} catch {\n\t\treturn false\n\t}\n}\n", "/**\n * Samples from a Gamma(alpha, 1) distribution using the Marsaglia & Tsang method.\n * Uses Box-Muller for internal standard normal generation.\n */\nfunction sampleGamma(alpha: number): number {\n\tif (alpha < 1) {\n\t\treturn sampleGamma(alpha + 1) * Math.pow(Math.random(), 1 / alpha)\n\t}\n\n\tconst d = alpha - 1 / 3\n\tconst c = 1 / Math.sqrt(9 * d)\n\n\twhile (true) {\n\t\tlet x: number = 0\n\t\tlet v: number = 0\n\n\t\tdo {\n\t\t\tconst u1 = Math.random()\n\t\t\tconst u2 = Math.random()\n\t\t\tx = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2)\n\t\t\tv = 1 + c * x\n\t\t} while (v <= 0)\n\n\t\tv = v * v * v\n\t\tconst u = Math.random()\n\n\t\tif (u < 1 - 0.0331 * (x * x) * (x * x)) return d * v\n\t\tif (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v))) return d * v\n\t}\n}\n\n/**\n * Computes the Bayesian credible interval for a variant's conversion rate,\n * expressed as a percentage [lower%, upper%].\n *\n * Uses a Beta(successes+1, failures+1) posterior (uniform prior),\n * sampled via the Gamma-ratio method with Monte Carlo draws.\n *\n * @param startCount   - Number of visitors who entered the funnel (step 1)\n * @param finalCount   - Number of visitors who completed the funnel (final step)\n * @param credibleIntervalWidth - Probability mass for the interval (e.g. 0.95)\n * @param draws        - Number of Monte Carlo samples (default: 5000)\n * @returns [lowerPercent, upperPercent] or null if inputs are invalid\n */\nexport function getConversionRateCredibleInterval(\n\tstartCount: number,\n\tfinalCount: number,\n\tcredibleIntervalWidth = 0.95,\n\tdraws = 5000,\n): [number, number] {\n\t// Beta posterior parameters: Beta(alpha, beta) with uniform prior Beta(1,1)\n\tconst alpha = finalCount + 1\n\tconst beta = startCount - finalCount + 1\n\n\t// Sample from Beta(alpha, beta) via two Gamma draws\n\tconst samples: number[] = []\n\tfor (let draw = 0; draw < draws; draw++) {\n\t\tconst x = sampleGamma(alpha)\n\t\tconst y = sampleGamma(beta)\n\t\tsamples.push(x / (x + y))\n\t}\n\n\t// Sort and extract percentiles\n\tsamples.sort((a, b) => a - b)\n\tconst lowerPercentile = (1 - credibleIntervalWidth) / 2\n\tconst upperPercentile = 1 - lowerPercentile\n\n\tconst lowerBound = samples[Math.floor(samples.length * lowerPercentile)] ?? 0\n\tconst upperBound = samples[Math.floor(samples.length * upperPercentile)] ?? 0\n\n\treturn [lowerBound, upperBound]\n}\n", "import { eachDayOfInterval, eachHourOfInterval } from \"date-fns\"\nimport type { ConversionRateResponseGranularity, ConversionRateResponsePoint } from \"../fetchUtils.ts\"\nimport { getDayAsMidnightLocal } from \"../getDayAsMidnightLocal.ts\"\n\nexport type TimezoneType = \"local\" | \"utc\"\n\nconst MS_PER_DAY = 86_400_000\nconst MS_PER_HOUR = 3_600_000\n\nfunction getHoursInRangeLocal(fromDate: Date, toDate: Date) {\n\treturn eachHourOfInterval({ start: fromDate, end: toDate }).map(date => date.toISOString())\n}\n\nfunction getHoursInRangeUtc(fromDate: Date, toDate: Date) {\n\tconst hours: string[] = []\n\tlet currentTimestamp = fromDate.getTime()\n\tconst endTimestamp = toDate.getTime()\n\n\twhile (currentTimestamp <= endTimestamp) {\n\t\thours.push(new Date(currentTimestamp).toISOString())\n\t\tcurrentTimestamp += MS_PER_HOUR\n\t}\n\n\treturn hours\n}\n\nfunction getDatesInRangeLocal(fromDate: Date, toDate: Date) {\n\treturn eachDayOfInterval({ start: fromDate, end: toDate }).map(date => date.toISOString())\n}\n\nfunction getDatesInRangeUtc(fromDate: Date, toDate: Date) {\n\tconst dates: string[] = []\n\tlet currentDateTimestamp = fromDate.getTime()\n\tconst endDateTimestamp = toDate.getTime()\n\n\twhile (currentDateTimestamp <= endDateTimestamp) {\n\t\tdates.push(new Date(currentDateTimestamp).toISOString())\n\t\tcurrentDateTimestamp += MS_PER_DAY\n\t}\n\n\treturn dates\n}\n\nexport function getTimeRange(\n\tpoints: ConversionRateResponsePoint[],\n\tfromDay: string,\n\ttoDay: string,\n\tgranularity: ConversionRateResponseGranularity,\n\ttimezone: TimezoneType = \"local\",\n) {\n\tconst sortedByRequestDateTime = points\n\t\t.map(({ timestamp }) => new Date(timestamp))\n\t\t.sort((a, b) => a.getTime() - b.getTime())\n\n\tconst fromDate = timezone === \"utc\" ? new Date(fromDay) : getDayAsMidnightLocal(fromDay)\n\tconst toDate = timezone === \"utc\" ? new Date(toDay) : getDayAsMidnightLocal(toDay)\n\n\tconst earliestTimestamp = sortedByRequestDateTime[0]\n\tconst latestTimestamp = sortedByRequestDateTime[sortedByRequestDateTime.length - 1]\n\n\t// If there are results collected later than the requested from date, use the earliest timestamp.\n\tconst effectiveFromDate = earliestTimestamp && earliestTimestamp > fromDate ? earliestTimestamp : fromDate\n\t// If there are results collected later than the requested to date, use the latest timestamp.\n\tconst effectiveToDate = latestTimestamp && latestTimestamp > toDate ? latestTimestamp : toDate\n\n\tif (granularity === \"hour\") {\n\t\treturn timezone === \"utc\"\n\t\t\t? getHoursInRangeUtc(effectiveFromDate, effectiveToDate)\n\t\t\t: getHoursInRangeLocal(effectiveFromDate, effectiveToDate)\n\t}\n\n\treturn timezone === \"utc\"\n\t\t? getDatesInRangeUtc(effectiveFromDate, effectiveToDate)\n\t\t: getDatesInRangeLocal(effectiveFromDate, effectiveToDate)\n}\n", "import type { FunnelStep } from \"../../types.ts\"\nimport type {\n\tAbTestConversionRateResponsePoint,\n\tConversionRateResponseGranularity,\n\tFunnelConversionRateResponsePoint,\n} from \"../fetchUtils.ts\"\nimport { getConversionRateCredibleInterval } from \"./getConversionRateCredibleInterval.ts\"\nimport type { FunnelDropOffStep } from \"./getFunnelDropOffs.ts\"\nimport { getTimeRange, type TimezoneType } from \"./getTimeRange.ts\"\n\ninterface ConversionRatePoint {\n\ttimestamp: string\n}\n\nexport interface FunnelConversionRatePoint extends ConversionRatePoint {\n\tstartCount: number\n\tfinalCount: number\n\tconversionRate: number\n\tfunnelSteps: FunnelDropOffStep[]\n}\n\nexport interface AbTestConversionRatePointVariant {\n\tabVariantId: string\n\tstartCount: number\n\tfinalCount: number\n\tconversionRate: number\n\tconversionRateCredibleInterval: [number, number]\n}\n\nexport interface AbTestConversionRatePoint extends ConversionRatePoint {\n\tvariants: AbTestConversionRatePointVariant[]\n}\n\nfunction getFunnelConversionRatePoint(\n\ttimestamp: string,\n\ttimestampPoints: FunnelConversionRateResponsePoint[],\n\tfunnelSteps: FunnelStep[],\n) {\n\tconst firstStepId = 1\n\tconst finalStepId = funnelSteps.length\n\n\tconst stepCounts = new Map<number, number>()\n\tfor (const { step, count } of timestampPoints) {\n\t\tconst previousStepCount = stepCounts.get(step) ?? 0\n\t\tstepCounts.set(step, previousStepCount + count)\n\t}\n\n\t// Ensure step counts are consistent and calculate funnel metrics in a single pass\n\tconst startCount = stepCounts.get(firstStepId) ?? 0\n\tconst finalCount = stepCounts.get(finalStepId) ?? 0\n\tconst conversionRate = startCount > 0 ? finalCount / startCount : 0\n\tconst dateFunnelSteps: FunnelDropOffStep[] = []\n\n\t// Process steps in ascending order\n\tfor (let stepId = firstStepId; stepId <= finalStepId; stepId++) {\n\t\tconst currentCount = stepCounts.get(stepId) ?? 0\n\n\t\t// If current step has more conversions than previous step, adjust previous step\n\t\tif (stepId > firstStepId && currentCount > 0) {\n\t\t\tconst previousCount = stepCounts.get(stepId - 1) ?? 0\n\n\t\t\t// Update the previous step in funnelSteps array if we've already added it\n\t\t\tif (previousCount < currentCount) {\n\t\t\t\tconst previousStep = dateFunnelSteps[dateFunnelSteps.length - 1]\n\n\t\t\t\tif (previousStep) {\n\t\t\t\t\tpreviousStep.count = currentCount\n\t\t\t\t\tpreviousStep.cumulativeDropOff = startCount > 0 ? (startCount - currentCount) / startCount : 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst cumulativeDropOff = startCount > 0 ? (startCount - currentCount) / startCount : 0\n\t\tdateFunnelSteps.push({\n\t\t\tstep: stepId,\n\t\t\tcount: currentCount,\n\t\t\tcumulativeDropOff,\n\t\t\tstepwiseDropOff: 0,\n\t\t})\n\t}\n\n\treturn {\n\t\ttimestamp,\n\t\tstartCount,\n\t\tfinalCount,\n\t\tconversionRate,\n\t\tfunnelSteps: dateFunnelSteps,\n\t}\n}\n\nfunction getAbTestConversionRatePoint(\n\ttimestamp: string,\n\ttimestampPoints: AbTestConversionRateResponsePoint[],\n\tfunnelSteps: FunnelStep[],\n\trunningStepCounts: Map<string, Map<number, number>>,\n) {\n\tconst firstStepId = 1\n\tconst finalStepId = funnelSteps.length\n\n\tconst abTestPoints = Map.groupBy(timestampPoints, point => point.abVariantId)\n\tconst variants: AbTestConversionRatePointVariant[] = []\n\n\tfor (const [abVariantId, points] of abTestPoints) {\n\t\tlet stepCounts = runningStepCounts.get(abVariantId)\n\n\t\tif (!stepCounts) {\n\t\t\tstepCounts = new Map<number, number>()\n\t\t\trunningStepCounts.set(abVariantId, stepCounts)\n\t\t}\n\n\t\tfor (const { step, count } of points) {\n\t\t\tconst previousStepCount = stepCounts.get(step) ?? 0\n\t\t\tstepCounts.set(step, previousStepCount + count)\n\t\t}\n\n\t\tconst startCount = stepCounts.get(firstStepId) ?? 0\n\t\tconst finalCount = stepCounts.get(finalStepId) ?? 0\n\n\t\tif (startCount === 0 || finalCount > startCount) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst conversionRate = startCount > 0 ? finalCount / startCount : 0\n\n\t\tconst conversionRateCredibleInterval = getConversionRateCredibleInterval(startCount, finalCount)\n\n\t\tvariants.push({\n\t\t\tabVariantId,\n\t\t\tstartCount,\n\t\t\tfinalCount,\n\t\t\tconversionRate,\n\t\t\tconversionRateCredibleInterval,\n\t\t})\n\t}\n\n\treturn { timestamp, variants }\n}\n\nfunction isAbTestConversionRatePoints(\n\tpoints: (FunnelConversionRateResponsePoint | AbTestConversionRateResponsePoint)[],\n): points is AbTestConversionRateResponsePoint[] {\n\treturn points[0]?.abVariantId !== undefined\n}\n\nexport function getFunnelConversionRate(\n\tpoints: FunnelConversionRateResponsePoint[],\n\tgranularity: ConversionRateResponseGranularity,\n\tfunnelSteps: FunnelStep[],\n\tparams: { fromDay: string; toDay: string },\n\ttimezone?: TimezoneType,\n): FunnelConversionRatePoint[]\nexport function getFunnelConversionRate(\n\tpoints: AbTestConversionRateResponsePoint[],\n\tgranularity: ConversionRateResponseGranularity,\n\tfunnelSteps: FunnelStep[],\n\tparams: { fromDay: string; toDay: string },\n\ttimezone?: TimezoneType,\n): AbTestConversionRatePoint[]\nexport function getFunnelConversionRate(\n\tpoints: (FunnelConversionRateResponsePoint | AbTestConversionRateResponsePoint)[],\n\tgranularity: ConversionRateResponseGranularity,\n\tfunnelSteps: FunnelStep[],\n\t{ fromDay, toDay }: { fromDay: string; toDay: string },\n\ttimezone?: TimezoneType,\n): (FunnelConversionRatePoint | AbTestConversionRatePoint)[] {\n\tif (points.length === 0) return []\n\n\tconst isAbTest = isAbTestConversionRatePoints(points)\n\tconst runningStepCounts = new Map<string, Map<number, number>>()\n\tconst timeRange = getTimeRange(points, fromDay, toDay, granularity, timezone)\n\tconst pointsByTimestamp = Map.groupBy(points, point => point.timestamp)\n\n\tconst result: (FunnelConversionRatePoint | AbTestConversionRatePoint)[] = []\n\n\tfor (const timestamp of timeRange) {\n\t\tconst timestampPoints = pointsByTimestamp.get(timestamp) ?? []\n\n\t\tif (timestampPoints.length === 0 && result.length === 0) continue\n\n\t\tif (isAbTest) {\n\t\t\tresult.push(\n\t\t\t\tgetAbTestConversionRatePoint(\n\t\t\t\t\ttimestamp,\n\t\t\t\t\ttimestampPoints as AbTestConversionRateResponsePoint[],\n\t\t\t\t\tfunnelSteps,\n\t\t\t\t\trunningStepCounts,\n\t\t\t\t),\n\t\t\t)\n\t\t} else {\n\t\t\tresult.push(\n\t\t\t\tgetFunnelConversionRatePoint(timestamp, timestampPoints as FunnelConversionRateResponsePoint[], funnelSteps),\n\t\t\t)\n\t\t}\n\t}\n\n\treturn result\n}\n", "import type { FunnelStep } from \"../../types.ts\"\nimport type { AbTestDropOffResponseStep, FunnelDropOffResponseStep } from \"../fetchUtils.ts\"\n\ninterface DropOffStep {\n\tstep: number\n\tcount: number\n\tcumulativeDropOff: number\n\tstepwiseDropOff: number\n}\n\nexport interface FunnelDropOffStep extends DropOffStep {}\nexport interface AbTestDropOffStep extends DropOffStep {\n\tabVariantId: string\n}\n\nfunction getDropOffRate(currentCount: number, previousCount: number) {\n\treturn 1 - currentCount / previousCount\n}\n\nexport function getFunnelDropOffs(steps: AbTestDropOffResponseStep[], funnelSteps: FunnelStep[]): AbTestDropOffStep[]\nexport function getFunnelDropOffs(steps: FunnelDropOffResponseStep[], funnelSteps: FunnelStep[]): FunnelDropOffStep[]\nexport function getFunnelDropOffs(\n\tsteps: (FunnelDropOffResponseStep | AbTestDropOffResponseStep)[],\n\tfunnelSteps: FunnelStep[],\n): (FunnelDropOffStep | AbTestDropOffStep)[] {\n\tconst firstStep = steps[0]\n\tlet previousStepCount = 0\n\n\tif (!firstStep) {\n\t\treturn []\n\t}\n\n\tconst defaultAbVariantId = \"abVariantId\" in firstStep ? firstStep.abVariantId : undefined\n\n\treturn steps.reduce(\n\t\t(calculatedSteps, { step, count, abVariantId }, stepIdx) => {\n\t\t\tlet cumulativeDropOff = 0\n\t\t\tlet stepwiseDropOff = 0\n\n\t\t\tif (stepIdx > 0) {\n\t\t\t\tcumulativeDropOff = count === 0 ? 1 : getDropOffRate(count, firstStep.count)\n\t\t\t\tstepwiseDropOff = previousStepCount === 0 ? 1 : getDropOffRate(count, previousStepCount)\n\t\t\t}\n\n\t\t\tcalculatedSteps[stepIdx] = {\n\t\t\t\tstep,\n\t\t\t\tcount,\n\t\t\t\tcumulativeDropOff,\n\t\t\t\tstepwiseDropOff,\n\t\t\t\t...(abVariantId && { abVariantId }),\n\t\t\t}\n\n\t\t\tpreviousStepCount = count\n\t\t\treturn calculatedSteps\n\t\t},\n\t\t// the back end will not return steps which have no data associated\n\t\t// with them (ie. when no users have reached that stage of the funnel),\n\t\t// so we create placeholder items for each step defined in the funnel\n\t\tfunnelSteps.map((_, stepIdx) => ({\n\t\t\tstep: stepIdx + 1,\n\t\t\tcount: 0,\n\t\t\tcumulativeDropOff: 1,\n\t\t\tstepwiseDropOff: 1,\n\t\t\tabVariantId: defaultAbVariantId,\n\t\t})) as (FunnelDropOffStep | AbTestDropOffStep)[],\n\t)\n}\n", "import type { FetchGroupByOption } from \"../fetchUtils.ts\"\n\nexport type GroupedFunnelResponsePoint = {\n\t[key in FetchGroupByOption]?: string\n}\n\nconst allPointsGroupKey = \"all\"\nconst otherPointsGroupKey = \"other\"\n\nexport type GroupedFunnelPoints<T> = Map<string, T[]>\n\nexport function getGroupedFunnelPoints<T extends GroupedFunnelResponsePoint>(\n\tpoints: T[],\n\tgroupBy?: FetchGroupByOption,\n): GroupedFunnelPoints<T> {\n\tif (!groupBy) {\n\t\treturn new Map([[allPointsGroupKey, points]])\n\t}\n\n\treturn Map.groupBy(points, point => point[groupBy] ?? otherPointsGroupKey)\n}\n", "import { apiFetcher } from \"web/lib/apiFetcher.ts\"\nimport type {\n\tAnalyticsFunnelFilters,\n\tAnalyticsFunnelGroupByOption,\n\tAnalyticsSectionFilters,\n\tDevicesSectionKeys,\n\tFunnelStep,\n\tGeographySectionKeys,\n\tPagesSectionKeys,\n\tSiteStatPoint,\n\tSourcesSectionKeys,\n\tTopFieldRow,\n\tTrackingIdsSectionKeys,\n} from \"../types.ts\"\nimport { type FunnelConversionRatePoint, getFunnelConversionRate } from \"./funnel-stats/getFunnelConversionRate.ts\"\nimport { type AbTestDropOffStep, type FunnelDropOffStep, getFunnelDropOffs } from \"./funnel-stats/getFunnelDropOffs.ts\"\nimport {\n\ttype GroupedFunnelPoints,\n\ttype GroupedFunnelResponsePoint,\n\tgetGroupedFunnelPoints,\n} from \"./funnel-stats/getGroupedFunnelPoints.ts\"\n\nexport type FetchGroupByOption = AnalyticsFunnelGroupByOption | \"abVariantId\"\n\nexport interface AnalyticsOverviewParams {\n\t/** `yyyy-MM-dd`, in the local time zone */\n\tfromDay: string\n\t/** `yyyy-MM-dd`, in the local time zone */\n\ttoDay: string\n\tfilters?: AnalyticsSectionFilters\n}\n\nexport interface AnalyticsFunnelRequestParams {\n\t/** `yyyy-MM-dd`, in the local time zone */\n\tfromDay: string\n\t/** `yyyy-MM-dd`, in the local time zone */\n\ttoDay: string\n\tsteps: FunnelStep[]\n\tfunnelFilters: AnalyticsFunnelFilters\n\tgroupBy?: FetchGroupByOption\n}\n\nexport interface AnalyticsAbTestRequestParams {\n\t/** `yyyy-MM-dd`, in the UTC zone */\n\tfromDay: string\n\t/** `yyyy-MM-dd`, in the UTC zone */\n\ttoDay: string\n\tabTestId: string\n\tcontrolVariantId: string\n\tsteps: FunnelStep[]\n\tfunnelFilters: AnalyticsFunnelFilters\n}\n\nconst SECTION_LIMIT = 20\n\n// Site stats\n\ninterface SiteStatsResponse {\n\ttotalPageviews: number\n\ttotalUniques: number\n\tstats: SiteStatPoint[]\n}\n\nexport function fetchSiteStats(\n\tprojectId: string,\n\tparams: AnalyticsOverviewParams,\n\tsignal: AbortSignal,\n): Promise<SiteStatsResponse> {\n\tconst granularity = params.fromDay === params.toDay ? \"hour\" : \"day\"\n\treturn fetchAnalyticsData<SiteStatsResponse>(\"stats\", projectId, params, signal, { granularity })\n}\n\n// Session stats\n\nexport interface SessionResponse {\n\tbounceRate: number | null\n\tavgTimeOnPageSeconds: number | null\n}\n\nexport function fetchSessionStats(\n\tprojectId: string,\n\tparams: AnalyticsOverviewParams,\n\tsignal: AbortSignal,\n): Promise<SessionResponse> {\n\treturn fetchAnalyticsData<SessionResponse>(\"session-stats\", projectId, params, signal)\n}\n\n// Live visitors\n\ninterface LiveSessionsResponse {\n\tliveSessions: number\n}\n\nexport function fetchLiveVisitors(\n\tprojectId: string,\n\tparams: AnalyticsOverviewParams,\n\tsignal: AbortSignal,\n): Promise<LiveSessionsResponse> {\n\treturn fetchAnalyticsData<LiveSessionsResponse>(\"live-sessions\", projectId, params, signal)\n}\n\n// Top fields\n\nexport type TopFieldName =\n\t| SourcesSectionKeys\n\t| DevicesSectionKeys\n\t| GeographySectionKeys\n\t| TrackingIdsSectionKeys\n\t| PagesSectionKeys\n\ntype TopFieldResponse = Partial<Record<TopFieldName, TopFieldRow[]>>\n\nexport function fetchTopField(\n\tprojectId: string,\n\tname: TopFieldName,\n\tparams: AnalyticsOverviewParams,\n\tsignal: AbortSignal,\n\tlimit: number = SECTION_LIMIT,\n): Promise<TopFieldResponse> {\n\treturn fetchAnalyticsData<TopFieldResponse>(\"top-field\", projectId, params, signal, { name, limit: String(limit) })\n}\n\nexport function fetchTopFields(\n\tprojectId: string,\n\tnames: TopFieldName[],\n\tparams: AnalyticsOverviewParams,\n\tsignal: AbortSignal,\n\tlimit: number = SECTION_LIMIT,\n): Promise<TopFieldResponse> {\n\treturn fetchAnalyticsData<TopFieldResponse>(\"top-fields\", projectId, params, signal, { names, limit: String(limit) })\n}\n\n// Funnel drop-off\n\ninterface DropOffResponseStep {\n\tstep: number\n\tcount: number\n\tearliestTimestamp: string\n\tlatestTimestamp: string\n}\n\nexport interface FunnelDropOffResponseStep extends DropOffResponseStep, GroupedFunnelResponsePoint {}\ninterface FunnelDropOffResponse {\n\tdropOff: FunnelDropOffResponseStep[]\n}\n\nexport async function fetchFunnelDropOff(projectId: string, params: AnalyticsFunnelRequestParams, signal: AbortSignal) {\n\tif (params.steps.length === 0) return undefined\n\n\tconst { dropOff } = await fetchAnalyticsData<FunnelDropOffResponse>(\"funnel-drop-off\", projectId, params, signal)\n\tconst groupedPoints = getGroupedFunnelPoints(dropOff, params.groupBy)\n\n\tconst groupedDropOffs: GroupedFunnelPoints<FunnelDropOffStep> = new Map()\n\tgroupedPoints.forEach((value, key) => {\n\t\tgroupedDropOffs.set(key, getFunnelDropOffs(value, params.steps))\n\t})\n\n\treturn groupedDropOffs\n}\n\n// Funnel conversion rate\n\nexport interface ConversionRateResponsePoint {\n\ttimestamp: string\n\tstep: number\n\tcount: number\n}\n\nexport interface FunnelConversionRateResponsePoint extends ConversionRateResponsePoint, GroupedFunnelResponsePoint {}\n\nexport type ConversionRateResponseGranularity = \"day\" | \"hour\"\ninterface FunnelConversionRateResponse {\n\tcounts: FunnelConversionRateResponsePoint[]\n\tgranularity: ConversionRateResponseGranularity\n}\n\nexport async function fetchFunnelConversionRate(\n\tprojectId: string,\n\tparams: AnalyticsFunnelRequestParams,\n\tsignal: AbortSignal,\n) {\n\tif (params.steps.length === 0) return undefined\n\n\tconst { counts, granularity } = await fetchAnalyticsData<FunnelConversionRateResponse>(\n\t\t\"funnel-counts\",\n\t\tprojectId,\n\t\tparams,\n\t\tsignal,\n\t)\n\tconst groupedPoints = getGroupedFunnelPoints(counts, params.groupBy)\n\n\tconst groupedConversionRate: GroupedFunnelPoints<FunnelConversionRatePoint> = new Map()\n\tgroupedPoints.forEach((value, key) => {\n\t\tgroupedConversionRate.set(key, getFunnelConversionRate(value, granularity, params.steps, params))\n\t})\n\n\treturn groupedConversionRate\n}\n\n// AB test drop-off\n\nexport interface AbTestVariantMetrics {\n\tabVariantId: string\n\tstartCount: number\n\tfinalCount: number\n\trequiredSampleSize: number\n\tconversionRate: number\n\tlift: number | null\n\tconversionRateCredibleInterval: [number, number]\n\tprobabilityOfBeingBest: number\n\ttimeToSignificanceEstimateDays: number\n}\n\nexport interface AbTestDropOffResponseStep extends DropOffResponseStep, GroupedFunnelResponsePoint {\n\tabVariantId: string\n}\n\ninterface AbTestDropOffResponse {\n\tdropOff: AbTestDropOffResponseStep[]\n\tmetrics: AbTestVariantMetrics[]\n}\n\nexport interface AbTestDropOff {\n\tdropOff: Map<string, AbTestDropOffStep[]>\n\tmetrics: AbTestVariantMetrics[]\n}\n\nexport async function fetchAbTestDropOff(projectId: string, params: AnalyticsAbTestRequestParams, signal: AbortSignal) {\n\tconst { dropOff, metrics } = await fetchAnalyticsData<AbTestDropOffResponse>(\n\t\t\"funnel-drop-off\",\n\t\tprojectId,\n\t\tparams,\n\t\tsignal,\n\t)\n\n\tconst groupedPoints = getGroupedFunnelPoints(dropOff, \"abVariantId\")\n\n\tconst groupedDropOffs: GroupedFunnelPoints<AbTestDropOffStep> = new Map()\n\tgroupedPoints.forEach((value, key) => {\n\t\tgroupedDropOffs.set(key, getFunnelDropOffs(value, params.steps))\n\t})\n\n\treturn {\n\t\tdropOff: groupedDropOffs,\n\t\tmetrics,\n\t}\n}\n\n// AB test conversion rate\n\nexport interface AbTestConversionRateResponsePoint extends ConversionRateResponsePoint {\n\tabVariantId: string\n}\ninterface AbTestConversionRateResult {\n\tcounts: AbTestConversionRateResponsePoint[]\n\tgranularity: ConversionRateResponseGranularity\n}\n\nexport async function fetchAbTestConversionRate(\n\tprojectId: string,\n\tparams: AnalyticsAbTestRequestParams,\n\tsignal: AbortSignal,\n) {\n\tconst { counts, granularity } = await fetchAnalyticsData<AbTestConversionRateResult>(\n\t\t\"funnel-counts\",\n\t\tprojectId,\n\t\tparams,\n\t\tsignal,\n\t)\n\n\treturn getFunnelConversionRate(counts, granularity, params.steps, params, \"utc\")\n}\n\n// Internal\n\n/**\n * NB: The spec says the resolvedOptions().timeZone is always a string (should default to system timezone),\n * but we see sometimes it returns undefined causing the endpoints to fail with bad request.\n * (seems to be a bug in some chromium browsers where it returns undefined in case of default:\n * https://github.com/microsoft/TypeScript/issues/55869)\n * When this happens, we don't send the timezone parameter and let the backend default to UTC.\n */\nconst LOCAL_TIMEZONE: string | undefined = Intl.DateTimeFormat().resolvedOptions().timeZone\n\nasync function fetchAnalyticsData<T>(\n\tendpoint: string,\n\tprojectId: string,\n\t{\n\t\tfromDay,\n\t\ttoDay,\n\t\tfilters,\n\t\tsteps,\n\t\tfunnelFilters,\n\t\tgroupBy,\n\t\tabTestId,\n\t\tcontrolVariantId,\n\t}: {\n\t\tfromDay: string\n\t\ttoDay: string\n\t\tfilters?: AnalyticsSectionFilters\n\t\tsteps?: FunnelStep[]\n\t\tfunnelFilters?: AnalyticsFunnelFilters\n\t\tgroupBy?: FetchGroupByOption\n\t\tabTestId?: string\n\t\tcontrolVariantId?: string\n\t},\n\tsignal: AbortSignal,\n\textraParams?: Record<string, string | string[]>,\n): Promise<T> {\n\tconst queryParams = new URLSearchParams()\n\n\tif (fromDay) queryParams.set(\"startDate\", fromDay)\n\tif (toDay) queryParams.set(\"endDate\", toDay)\n\n\t// A/B test dates are sent in UTC, we should not include the timezone\n\tif (LOCAL_TIMEZONE && !abTestId) queryParams.set(\"timezone\", LOCAL_TIMEZONE)\n\n\tif (filters) {\n\t\tfor (const key in filters) {\n\t\t\tconst filter = filters[key as keyof typeof filters]\n\t\t\tif (filter) queryParams.set(key, filter.value)\n\t\t}\n\t}\n\n\tif (extraParams) {\n\t\tfor (const [key, value] of Object.entries(extraParams)) {\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\tfor (const v of value) {\n\t\t\t\t\tqueryParams.append(key, v)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tqueryParams.set(key, value)\n\t\t\t}\n\t\t}\n\t}\n\n\tif (abTestId) queryParams.set(\"abTestId\", abTestId)\n\tif (controlVariantId) queryParams.set(\"controlVariantId\", controlVariantId)\n\n\tif (steps && steps.length > 0) {\n\t\tqueryParams.set(\"steps\", JSON.stringify(steps))\n\t}\n\n\tif (funnelFilters) {\n\t\tfor (const filterKey in funnelFilters) {\n\t\t\tconst filter = funnelFilters[filterKey as keyof typeof funnelFilters]\n\n\t\t\tif (filter) {\n\t\t\t\tfor (const filterValue of filter) {\n\t\t\t\t\tqueryParams.append(filterKey, filterValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (groupBy) {\n\t\tqueryParams.set(\"groupBy\", groupBy)\n\t\tqueryParams.set(\"groupByLimit\", \"5\")\n\t}\n\n\tconst result = await apiFetcher.get(\n\t\t`/web/v3/projects/${projectId}/site-stats/${endpoint}?${queryParams.toString()}`,\n\t\tundefined,\n\t\tsignal,\n\t)\n\n\treturn result\n}\n", "import type { EnrichedHostnameWithDeployment, ServerDeployment } from \"@framerjs/app-shared\"\nimport { MAIN_BRANCH_ID } from \"@framerjs/crdtree2\"\nimport { EngineStore } from \"document/EngineStore.ts\"\nimport { apiFetcher } from \"web/lib/apiFetcher.ts\"\n\ninterface ListHostnamesResponse {\n\thostnames: HostnameResponse[]\n}\n\nexport interface HostnameResponse extends Omit<EnrichedHostnameWithDeployment, \"deployment\"> {\n\tdeployment: ServerDeployment\n}\n\nexport async function listHostnames(\n\tprojectId: string,\n\tbranchId?: string,\n\tsignal?: AbortSignal,\n): Promise<ListHostnamesResponse> {\n\t// API does not expect a branchId for the main branch\n\tconst queryParams = branchId && branchId !== MAIN_BRANCH_ID ? { branchId } : undefined\n\treturn apiFetcher.get(`/web/v1/sites/hostnames/${projectId}`, queryParams, signal)\n}\n\nexport abstract class BaseHostnameStore extends EngineStore {\n\tabstract customHostnameString: string | undefined\n\tabstract defaultHostnameString: string | undefined\n}\n", "import type { SerializableRecord } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { JSXCollectors } from \"code-generation/jsx/types.ts\"\nimport type { ArrayVariableDefinition } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { safeProperty } from \"utils/names.ts\"\nimport { arrayIdKey } from \"./cms/dataIdKeys.ts\"\n\nexport function generateArrayFromHumanReadableFunctionName(\n\tvariable: ArrayVariableDefinition,\n\tcollectors: Pick<JSXCollectors, \"declarations\" | \"bindings\">,\n): SafeJS {\n\tconst galleryImageVariable =\n\t\tvariable.itemVariables.length === 1 && variable.itemVariables[0]?.type === ControlType.Image\n\t\t\t? variable.itemVariables[0]\n\t\t\t: undefined\n\n\tconst itemBinding = js`item`\n\n\tconst staticallyMappedItem: SerializableRecord = {\n\t\t[arrayIdKey]: js`typeof ${itemBinding}?.[${arrayIdKey}] === \"string\" ? ${itemBinding}[${arrayIdKey}] : undefined`,\n\t}\n\tfor (const itemVariable of variable.itemVariables) {\n\t\t// Note: we also include non human readable names because they can be passed in when using\n\t\t// code overrides.\n\t\tconst humanReadableName = safeProperty(itemVariable.name)\n\t\tif (humanReadableName) {\n\t\t\tstaticallyMappedItem[itemVariable.id] =\n\t\t\t\tjs`${itemBinding}?.[${humanReadableName}] ?? ${itemBinding}?.[${itemVariable.id}]`\n\t\t} else {\n\t\t\tstaticallyMappedItem[itemVariable.id] = js`${itemBinding}?.[${itemVariable.id}]`\n\t\t}\n\t}\n\n\tconst fromHumanReadableFunctionName = collectors.bindings.create(\"arrayFromHumanReadable\" + variable.id)\n\n\tcollectors.declarations.file.create(\n\t\tjs.joinLines(\n\t\t\tjs`const ${fromHumanReadableFunctionName} = (value) => {${js.joinLines(\n\t\t\t\tjs`if (!Array.isArray(value)) return`,\n\t\t\t\tjs`return value.map(${itemBinding} => {${js.joinLines(\n\t\t\t\t\tgalleryImageVariable\n\t\t\t\t\t\t? js`if (typeof ${itemBinding} === \"string\") return { [${galleryImageVariable.id}]: ${itemBinding} }`\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tjs`return ${staticallyMappedItem}`,\n\t\t\t\t)}})`,\n\t\t\t)}}`,\n\t\t),\n\t)\n\n\treturn fromHumanReadableFunctionName\n}\n", "import type { AssetMap } from \"@framerjs/assets\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport {\n\tdefaultAssetReferenceKey,\n\thasDefaultAssetReference,\n\thasVekterDefault,\n\tisDefaultResponsiveImage,\n\tvekterDefaultKey,\n} from \"@framerjs/framer-runtime/sandbox\"\nimport {\n\tassert,\n\tModuleType,\n\tassertNever,\n\tisEmptyObject,\n\tisModuleExportIdentifier,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport type { SerializableRecord, SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { isSerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { JAVASCRIPT_RESERVED_KEYWORDS } from \"code-generation/js/reserved.ts\"\nimport { SafeJS, SerializableObject, SortBehavior, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport { type BindingCollector, createUnique } from \"code-generation/utils/BindingCollector.ts\"\nimport type { CSSVariableDefinitionCollector } from \"code-generation/utils/CSSVariableDefinitionCollector.ts\"\nimport type { JSXDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport { getRawWebPagePath } from \"document/components/utils/getWebPagePath.ts\"\nimport { getDefaultName } from \"document/components/utils/nodes.ts\"\nimport { isValidVariableForSetVariableValueAction } from \"document/models/CanvasTree/actions/setVariableValueActions.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isContentNode } from \"document/models/CanvasTree/nodes/TreeNode.ts\"\nimport { compileRichTextForCodeGeneration } from \"document/models/CanvasTree/nodes/utils/compileRichText.tsx\"\nimport {\n\tisCollectionNode,\n\tisLayoutTemplateNode,\n\tisSmartComponentNode,\n\tisVectorSetNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport type {\n\tVariableControlDescription,\n\tVariableDefinition,\n\tVariableID,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport {\n\tcomponentIdentifierForVariableReference,\n\tcontrolDescriptionFromVariable,\n\tisArrayItemVariableType,\n\tisOptionalVariable,\n\tisVariableDefinition,\n\tisVectorSetItemVariableInitialValue,\n\twithOptional,\n\twithVariables,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { getFallbackValue } from \"document/models/CanvasTree/traits/utils/codeComponentProps.ts\"\nimport { isTokenCSSVariable, stripMetadataFromCSSVariable } from \"document/models/CanvasTree/utils/tokens.ts\"\nimport { isControlType } from \"document/models/controlProps/isControlType.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport {\n\tgetCreatedAtVariable,\n\tgetNextItemVariable,\n\tgetPreviousItemVariable,\n\tgetUpdatedAtVariable,\n} from \"document/utils/CollectionItemVariables.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { ConvertColor } from \"library/index.ts\"\nimport type { ChangeHandlerControlDescription, ControlDescription } from \"library/render/types/PropertyControls.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { boxShadowToCSS, isListOfLibraryBoxShadow } from \"utils/boxShadowToCSS.ts\"\nimport { safeProperty } from \"utils/names.ts\"\nimport { isBoolean, isNull, isNullish, isNumber, isObject, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { Var } from \"./GeneratedVariantComponentVars.ts\"\nimport { generateArrayFromHumanReadableFunctionName } from \"./generateArrayFromHumanReadableFunctionName.ts\"\n\ninterface Context {\n\tcomponentLoader: ComponentLoader\n\tmodulesStore: ModulesStore\n\ttree: CanvasTree\n\tassetMap: AssetMap\n\tvariables: VariableCollector\n\timports: ImportCollector\n\tlinks?: LinkCollector\n\tassets?: AssetCollector\n\tdeclarations: JSXDeclarationCollector\n\tbindings: BindingCollector\n\tcssVariableDefinitions?: CSSVariableDefinitionCollector\n}\n\nfunction swapKeyAndValueInEntry<Key extends string, Value extends string>(entry: [Key, Value]): [Value, Key] {\n\treturn [entry[1], entry[0]]\n}\n\nconst controlTypeNameByType = new Map(Object.entries(ControlType).map(swapKeyAndValueInEntry))\n\nexport function getControlType(type: ControlType, imports: ImportCollector): SafeJS {\n\tconst controlTypeEnum = imports.addImport(\"framer\", { exportSpecifier: \"ControlType\" })\n\tconst controlTypeName = controlTypeNameByType.get(type)\n\tconst value = new SafeJS(controlTypeName)\n\treturn js`${controlTypeEnum}.${value}`\n}\n\nconst controlTsType: Record<ControlType, string> = {\n\t[ControlType.Boolean]: \"boolean\",\n\t[ControlType.Number]: \"number\",\n\t[ControlType.String]: \"string\",\n\t[ControlType.RichText]: \"string\",\n\t[ControlType.FusedNumber]: \"any\",\n\t[ControlType.Enum]: \"string\",\n\t[ControlType.SegmentedEnum]: \"string\",\n\t[ControlType.Color]: \"string\",\n\t[ControlType.Image]: \"string\",\n\t[ControlType.ResponsiveImage]: \"{src: string; srcSet?: string; alt?: string}\",\n\t[ControlType.File]: \"string\",\n\t[ControlType.ComponentInstance]: \"any\",\n\t[ControlType.Slot]: \"any\",\n\t[ControlType.Array]: \"any[]\",\n\t[ControlType.EventHandler]: \"any\",\n\t[ControlType.ChangeHandler]: \"(value: any) => void\",\n\t[ControlType.Transition]: \"Record<string, any>\",\n\t[ControlType.Link]: \"string\",\n\t[ControlType.LinkRelValues]: \"string[] | undefined\",\n\t[ControlType.PageScope]: \"string\",\n\t[ControlType.Date]: \"string\",\n\t[ControlType.Object]: \"Record<string, any>\",\n\t[ControlType.Font]: \"Record<string, any> | undefined\",\n\t[ControlType.ScrollSectionRef]: \"React.MutableRefObject<HTMLElement>\",\n\t[ControlType.CustomCursor]: \"string\",\n\t[ControlType.Border]: `Record<string, any>`,\n\t[ControlType.Cursor]: \"string\",\n\t[ControlType.BoxShadow]: \"string\",\n\t[ControlType.Gap]: \"string\",\n\t[ControlType.Padding]: \"string\",\n\t[ControlType.BorderRadius]: \"string\",\n\t[ControlType.CollectionReference]: \"string | undefined\",\n\t[ControlType.MultiCollectionReference]: \"string[] | undefined\",\n\t[ControlType.TrackingId]: \"string | undefined\",\n\t[ControlType.VectorSetItem]: \"React.ComponentType<any> | undefined\",\n\t[ControlType.Location]: \"Record<string, any>\",\n}\n\nfunction tsTypeForControlType(type?: ControlType): SafeJS {\n\tif (!type) return js`any`\n\treturn new SafeJS(controlTsType[type])\n}\n\n// This key maps 1:1 with the arguments of useVariantState in library.\nconst INITIAL_VARIANT_KEY = \"variant\"\n\ntype SerializableControlDescription = SafeJS | (Omit<ControlDescription, \"type\"> & { type: SafeJS })\n\ninterface WithDefaultValue {\n\tdefaultValue?: unknown\n}\n\nfunction withDefaultValue<T>(value: T): value is T & Required<WithDefaultValue> {\n\treturn !isUndefined((value as WithDefaultValue | undefined)?.defaultValue)\n}\n\n/**\n * Get the default controls for a node.\n *\n * This creates the Variant control if the node is a Smart Component node with\n * >= 2 variants.\n */\nfunction defaultControlsForNode(\n\tnode: CanvasNode,\n\tcomponentLoader: ComponentLoader,\n\timports: ImportCollector,\n): Record<string, SerializableControlDescription> {\n\tif (!isSmartComponentNode(node)) return {}\n\n\tassert(node.isLoaded(), \"Node must be loaded to generate controls\")\n\n\tconst variants = node.getTopLevelVariants()\n\tif (variants?.length < 2) return {}\n\n\tconst options: NodeID[] = []\n\tconst optionTitles: string[] = []\n\n\tfor (const variant of variants) {\n\t\tconst title = variant.resolveValue(\"name\") ?? getDefaultName(componentLoader, variant)\n\n\t\toptions.push(variant.id)\n\t\toptionTitles.push(title)\n\t}\n\n\treturn {\n\t\t[INITIAL_VARIANT_KEY]: {\n\t\t\ttype: getControlType(ControlType.Enum, imports),\n\t\t\ttitle: Dictionary.Variant,\n\t\t\toptions,\n\t\t\toptionTitles,\n\t\t} as SerializableControlDescription,\n\t}\n}\n\n/**\n * Get the default Serializable Value for a Variable Control Description,\n * resolving assets where required.\n */\nfunction getDefaultValue(\n\tcontrolDescription: VariableControlDescription,\n\tvariable: VariableDefinition | undefined,\n\tcontext: Context,\n\tscopeType: ScopeType,\n): SerializableValue | undefined {\n\tif (\n\t\tcontrolDescription.type === ControlType.ResponsiveImage &&\n\t\thasVekterDefault(controlDescription) &&\n\t\tisDefaultResponsiveImage(controlDescription.__vekterDefault)\n\t) {\n\t\tconst { assetReference, alt } = controlDescription.__vekterDefault\n\t\tconst asset = context.assets?.resolveResponsiveImage(assetReference, {\n\t\t\tfocalPoint: controlDescription.__vekterDefault,\n\t\t})\n\t\tif (asset && isString(alt)) {\n\t\t\tasset.alt = alt\n\t\t}\n\t\treturn asset\n\t} else if (hasDefaultAssetReference(controlDescription)) {\n\t\tswitch (controlDescription.type) {\n\t\t\tcase ControlType.ResponsiveImage: {\n\t\t\t\tconst asset = context.assets?.resolveResponsiveImage(controlDescription.__defaultAssetReference)\n\t\t\t\tif (!asset) return\n\t\t\t\treturn asset\n\t\t\t}\n\n\t\t\tcase ControlType.File: {\n\t\t\t\t// srcSet doesn't make sense in a File, and the (deprecated) Image control\n\t\t\t\t// doesn't support it. (Instead of Image, we use a ResponsiveImage with srcSet support.)\n\t\t\t\tconst asset = context.assets?.resolve(controlDescription.__defaultAssetReference)\n\t\t\t\tif (!asset) return\n\t\t\t\treturn asset.src\n\t\t\t}\n\t\t}\n\t} else if (variable?.type === ControlType.Array) {\n\t\tif (!variable.initialValue) return []\n\n\t\treturn variable.initialValue.map(itemControlProp => {\n\t\t\tconst item: SerializableRecord = {}\n\n\t\t\tif (!itemControlProp || itemControlProp.type !== ControlType.Object) return item\n\t\t\tif (!isObject(itemControlProp.value)) return item\n\n\t\t\tfor (const objectPropertyKey in itemControlProp.value) {\n\t\t\t\tconst objectPropertyValue = itemControlProp.value[objectPropertyKey]\n\t\t\t\tif (!objectPropertyValue) continue\n\t\t\t\tif (!isArrayItemVariableType(objectPropertyValue.type)) continue\n\n\t\t\t\tswitch (objectPropertyValue.type) {\n\t\t\t\t\tcase ControlType.Image: {\n\t\t\t\t\t\tif (!isString(objectPropertyValue.value)) continue\n\n\t\t\t\t\t\tconst asset = context.assets?.resolveResponsiveImage(objectPropertyValue.value, {\n\t\t\t\t\t\t\tfocalPoint: objectPropertyValue,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tif (!asset) continue\n\n\t\t\t\t\t\tasset.alt = objectPropertyValue.alt ?? \"\"\n\t\t\t\t\t\titem[objectPropertyKey] = asset\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcase ControlType.Boolean:\n\t\t\t\t\t\tif (isBoolean(objectPropertyValue.value)) {\n\t\t\t\t\t\t\titem[objectPropertyKey] = objectPropertyValue.value\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase ControlType.Number:\n\t\t\t\t\t\tif (isNumber(objectPropertyValue.value)) {\n\t\t\t\t\t\t\titem[objectPropertyKey] = objectPropertyValue.value\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase ControlType.String:\n\t\t\t\t\t\tif (isString(objectPropertyValue.value)) {\n\t\t\t\t\t\t\titem[objectPropertyKey] = objectPropertyValue.value\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase ControlType.Color:\n\t\t\t\t\t\tif (isString(objectPropertyValue.value)) {\n\t\t\t\t\t\t\tif (isTokenCSSVariable(objectPropertyValue.value)) {\n\t\t\t\t\t\t\t\titem[objectPropertyKey] = stripMetadataFromCSSVariable(objectPropertyValue.value)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\titem[objectPropertyKey] = ConvertColor.toFormatString(objectPropertyValue.value)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tassertNever(objectPropertyValue.type)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn item\n\t\t})\n\t} else if (withDefaultValue(controlDescription)) {\n\t\tif (variable && isOptionalVariable(variable, scopeType)) {\n\t\t\t// Optional variables should not get a default prop value, otherwise it's impossible to\n\t\t\t// set it to `undefined`.\n\t\t\treturn undefined\n\t\t}\n\n\t\tconst defaultValue = controlDescription.defaultValue\n\n\t\tif (controlDescription.type === ControlType.VectorSetItem) {\n\t\t\tassert(isVectorSetItemVariableInitialValue(defaultValue), \"Vector set item must be a module export identifier\")\n\t\t\treturn context.imports.addModuleImport(defaultValue.identifier)\n\t\t}\n\n\t\tif (controlDescription.type === ControlType.RichText && isString(defaultValue)) {\n\t\t\treturn compileRichTextForCodeGeneration(defaultValue, {\n\t\t\t\tcollectors: context,\n\t\t\t\tuseFramerMotion: scopeType === ScopeType.SmartComponent,\n\t\t\t})\n\t\t}\n\n\t\tif (controlDescription.type === ControlType.BoxShadow && isListOfLibraryBoxShadow(defaultValue)) {\n\t\t\treturn boxShadowToCSS(defaultValue, \"emptyStringWhenEmpty\", color =>\n\t\t\t\tisTokenCSSVariable(color) ? stripMetadataFromCSSVariable(color) : ConvertColor.toFormatString(color),\n\t\t\t)\n\t\t}\n\n\t\tif (isSerializableValue(defaultValue)) {\n\t\t\treturn isTokenCSSVariable(defaultValue) ? stripMetadataFromCSSVariable(defaultValue) : defaultValue\n\t\t}\n\t}\n}\n\nfunction createOptionalType(name: SafeJS, type: SafeJS) {\n\treturn js`${name}?: ${type};`\n}\n\nconst extractedProps = [\"id\", \"width\", \"height\"]\n\n/**\n * If set on a generated component, some common props would adversely impact\n * rendering. To ensure this doesn't happen, we extract them from the\n * component's props.\n */\nconst extractedComponentProps = Object.fromEntries(\n\textractedProps.map(v => {\n\t\tconst value = new SafeJS(v)\n\t\treturn [value, value]\n\t}),\n)\n\nfunction objectWithSpreadAtEnd(obj: Record<string, SerializableValue | undefined>, spread: SafeJS) {\n\tconst value = new SerializableObject(obj)\n\tSerializableObject.addSpreadAtEnd(value, spread)\n\treturn value\n}\n\nconst defaultComponentProps = [\n\t{ name: Var.style, type: js`Record<string, unknown>` },\n\t{ name: Var.className, type: js`string` },\n\t{ name: Var.layoutId, type: js`string | number` },\n]\n\ninterface TypedReactProp {\n\tkey: NodeID\n\tbinding?: SafeJS\n\ttype?: SafeJS\n\tvalue?: SafeJS\n\tname?: string\n}\n\nfunction defaultValuesAndTypesForNode(node: CanvasNode, humanReadableVariantMap: SafeJS | undefined): TypedReactProp[] {\n\tif (!isSmartComponentNode(node) && !isWebPageNode(node) && !isLayoutTemplateNode(node) && !isVectorSetNode(node)) {\n\t\treturn []\n\t}\n\n\tconst valuesAndTypes: TypedReactProp[] = defaultComponentProps.map(({ name, type }) => ({\n\t\tkey: serializeJS(name),\n\t\ttype: createOptionalType(name, type),\n\t}))\n\n\tconst key = serializeJS(Var.variant)\n\n\tif (humanReadableVariantMap && withReplicaVariants(node)) {\n\t\treturn valuesAndTypes.concat([\n\t\t\t{\n\t\t\t\tkey,\n\t\t\t\ttype: createOptionalType(Var.variant, js`keyof typeof ${humanReadableVariantMap}`),\n\t\t\t\tvalue: js`${humanReadableVariantMap}[props.${Var.variant}] ?? props.${Var.variant} ?? ${node.baseVariantId}`,\n\t\t\t},\n\t\t])\n\t}\n\n\t// If serializing less than 2 variants, just create a React prop for it, but no types or default values.\n\t// This ensures that dependent code doesn't syntax error if `variant` is not defined.\n\treturn valuesAndTypes.concat([{ key }])\n}\n\nfunction makeValue(variableId: NodeID, name: SafeJS, defaultValue?: SerializableValue) {\n\tlet value = js`props.${new SafeJS(variableId)}`\n\tif (name) value = js`${name} ?? ${value}`\n\tif (defaultValue) value = js`${value} ?? ${defaultValue}`\n\treturn value\n}\n\nfunction nodePathVariables(node: CanvasNode, componentLoader: ComponentLoader, tree: CanvasTree) {\n\tif (!isWebPageNode(node)) return\n\n\tconst pagePath = getRawWebPagePath(tree, node)\n\tif (!pagePath) return\n\n\tconst variableMap = node.getProvidedVariableMap(tree, undefined, componentLoader, componentLoader.activeBundleHash)\n\n\tif (!variableMap) return\n\n\tconst pathVariables = new Map<string, VariableDefinition>()\n\n\tfor (const [variableId, variable] of variableMap) {\n\t\tconst isURLVariable = isWebPageNode(node) && node.hasVariable(variableId)\n\t\tif (isURLVariable) continue\n\n\t\tpathVariables.set(variableId, variable)\n\t}\n\n\tif (pathVariables.size === 0) return\n\n\treturn pathVariables\n}\n\nexport const reservedPropNames = [\n\t...JAVASCRIPT_RESERVED_KEYWORDS,\n\tINITIAL_VARIANT_KEY,\n\t...extractedProps,\n\t...defaultComponentProps.map(({ name }) => name.toString()),\n\t// Framer assigns `name` too liberally to components in preview and\n\t// code-generation. Make sure that that doesn't negatively effect props that\n\t// are titled \"Name\".\n\t\"name\",\n]\n\ntype VariableAndControlById = Record<\n\tNodeID,\n\t{\n\t\tcontrol?: VariableControlDescription\n\t\tvariable?: VariableDefinition\n\t\tbinding?: SafeJS\n\t}\n>\n\nfunction serializedTypesAndReactProps(\n\tprops: VariableAndControlById,\n\tnode: CanvasNode,\n\tcontext: Context,\n\tscopeType: ScopeType,\n\thumanReadableVariantMap: SafeJS | undefined,\n): {\n\treadonly types: SafeJS\n\treadonly props: SafeJS\n\treadonly variableMap?: Record<string, string>\n} {\n\t// Track the human readable names we have generated for each variable to\n\t// ensure we create unique names. Reserve `variant` so that variables can't\n\t// overlap, and reserve `width`, `height` and `id` so that they can't be\n\t// spread onto the root element.\n\tconst names = new Set<string>(reservedPropNames)\n\n\tconst typedReactProps = Object.entries(props).map(([key, { control, variable, binding }]): TypedReactProp => {\n\t\t// If the variables doesn't have a control, return it so that it is\n\t\t// later included in the destructured return value, but not typed.\n\t\tif (!control) return { key, binding }\n\n\t\tconst name = createUnique(safeProperty(control.title) ?? key, names)\n\t\tconst safeName = new SafeJS(name)\n\n\t\tconst defaultValue = getDefaultValue(control, variable, context, scopeType)\n\n\t\tlet type = createOptionalType(safeName, tsTypeForControlType(control.type))\n\t\tlet value: SafeJS\n\n\t\tif (control.type === ControlType.Enum && control.options && control.optionTitles && safeName) {\n\t\t\tconst mappedEnums = new SerializableObject()\n\t\t\tcontrol.options.forEach((option, index) => {\n\t\t\t\tif (!isString(option) || !control.optionTitles) return\n\t\t\t\tconst optionTitle = control.optionTitles[index]\n\t\t\t\tif (!isString(optionTitle)) return\n\t\t\t\tmappedEnums[optionTitle] = option\n\t\t\t})\n\n\t\t\tconst humanReadable = context.declarations.file.dedupe(\"humanReadableEnumMap\", mappedEnums)\n\t\t\ttype = createOptionalType(safeName, js`keyof typeof ${humanReadable}`)\n\t\t\tvalue = makeValue(key, safeName, defaultValue)\n\t\t\tvalue = js`${humanReadable}[${safeName}] ?? ${value}`\n\t\t} else if (variable?.type === ControlType.Array) {\n\t\t\t// When the human readable property is used we convert the map the array value so human\n\t\t\t// readable names can be used within the array. And as Framer uses the id we don't need\n\t\t\t// to do anything expensive in most cases.\n\t\t\tconst arrayFromHumanReadableFunction = generateArrayFromHumanReadableFunctionName(variable, context)\n\t\t\tconst humanReadableGalleryToArray = SafeJS.fn(arrayFromHumanReadableFunction, safeName)\n\t\t\tvalue = makeValue(key, humanReadableGalleryToArray, defaultValue)\n\t\t} else {\n\t\t\tvalue = makeValue(key, safeName, defaultValue)\n\t\t}\n\n\t\treturn {\n\t\t\tkey,\n\t\t\tbinding,\n\t\t\tname,\n\t\t\ttype,\n\t\t\tvalue,\n\t\t}\n\t})\n\n\tlet types = \"\"\n\tconst destructuredProps: SafeJS[] = []\n\tconst declarations: SafeJS[] = []\n\tconst returnObject = new SerializableObject()\n\tconst pathVariables = nodePathVariables(node, context.componentLoader, context.tree)\n\tconst variableMap: Record<string, string> = {}\n\tconst extractedProps: Record<string, SafeJS> = { ...extractedComponentProps }\n\tconst valuesAndTypes = defaultValuesAndTypesForNode(node, humanReadableVariantMap)\n\n\tfor (const { key, binding, type, value, name } of [...valuesAndTypes, ...typedReactProps]) {\n\t\t// If the variable is a path variable, create a default value expression\n\t\t// from the data. The prop must always be added even if it doesn't have\n\t\t// a type or value to ensure there are no syntax errors.\n\t\tconst pathVariable = pathVariables?.get(key)\n\t\tconst variableBinding = binding ?? new SafeJS(key)\n\n\t\tif (pathVariable) {\n\t\t\tlet destructuredProp = js`${variableBinding} = ${Var.getFromCurrentRouteData}(${pathVariable.id})`\n\n\t\t\tif (isControlType(pathVariable.type)) {\n\t\t\t\tconst fallbackValue = getFallbackValue(pathVariable.type)\n\n\t\t\t\tif (isSerializableValue(fallbackValue)) {\n\t\t\t\t\tdestructuredProp = js`${destructuredProp} ?? ${fallbackValue}`\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdestructuredProps.push(destructuredProp)\n\t\t} else {\n\t\t\tconst setVariableBinding = context.variables.getSetterBinding(key)\n\n\t\t\tif (setVariableBinding) {\n\t\t\t\tconst onChangeKey = getOnChangeVariableKey(key)\n\n\t\t\t\tconst serializedVariableBinding = serializeJS(variableBinding)\n\t\t\t\tconst externalStateBinding = context.bindings.create(`external${serializedVariableBinding}`)\n\t\t\t\tconst setExternalStateBinding = context.bindings.create(`setExternal${serializedVariableBinding}`)\n\n\t\t\t\tdestructuredProps.push(js`${key}: ${externalStateBinding}`)\n\t\t\t\tdestructuredProps.push(js`${onChangeKey}: ${setExternalStateBinding}`)\n\n\t\t\t\tconst useStateVariableBinding = context.declarations.file.dedupe(\n\t\t\t\t\t\"useStateVariable\",\n\t\t\t\t\tjs.joinLines(\n\t\t\t\t\t\tjs`(externalState, setExternalState) => {`,\n\t\t\t\t\t\tjs`    const [internalState, setInternalState] = React.useState(externalState)`,\n\t\t\t\t\t\tjs`    const [previousExternalState, setPreviousExternalState] = React.useState(externalState)`,\n\t\t\t\t\t\tjs`    if (setExternalState) {`,\n\t\t\t\t\t\tjs`        return [externalState, setExternalState]`,\n\t\t\t\t\t\tjs`    }`,\n\t\t\t\t\t\tjs`    if (externalState !== previousExternalState) {`,\n\t\t\t\t\t\tjs`        setInternalState(externalState)`,\n\t\t\t\t\t\tjs`        setPreviousExternalState(externalState)`,\n\t\t\t\t\t\tjs`    }`,\n\t\t\t\t\t\tjs`    return [internalState, setInternalState]`,\n\t\t\t\t\t\tjs`}`,\n\t\t\t\t\t),\n\t\t\t\t)\n\n\t\t\t\tdeclarations.push(\n\t\t\t\t\tjs`const [${variableBinding}, ${setVariableBinding}] = ${SafeJS.fn(\n\t\t\t\t\t\tuseStateVariableBinding,\n\t\t\t\t\t\texternalStateBinding,\n\t\t\t\t\t\tsetExternalStateBinding,\n\t\t\t\t\t)}`,\n\t\t\t\t)\n\t\t\t} else if (serializeJS(variableBinding) !== key) {\n\t\t\t\tdestructuredProps.push(js`${key}: ${variableBinding}`)\n\t\t\t} else {\n\t\t\t\tdestructuredProps.push(variableBinding)\n\t\t\t}\n\t\t}\n\n\t\tif (type) types += type\n\t\tif (value) returnObject[key] = value\n\t\tif (name) {\n\t\t\tvariableMap[key] = name\n\t\t\textractedProps[name] = new SafeJS(name)\n\t\t}\n\t}\n\n\tif (scopeType === ScopeType.LayoutTemplate) {\n\t\tdestructuredProps.push(Var.children)\n\t}\n\n\t// Design Page screens take the style prop in the preview to override the default screen size.\n\tif (scopeType === ScopeType.DesignPage) {\n\t\tdestructuredProps.push(Var.style)\n\t}\n\n\tSerializableObject.addSpreadAtStart(returnObject, Var.props)\n\n\tconst getProps = context.declarations.file.dedupe(\n\t\t\"getProps\",\n\t\t// Extract harmful properties from props to ensure they don't impact\n\t\t// rendering if provided by a user.\n\t\tjs`(${objectWithSpreadAtEnd(extractedProps, Var.props)}) => { return ${returnObject} }`,\n\t)\n\n\t// Usually we would use `SerializableObject` here, and take advantage of the heuristic where the\n\t// key of the key-value pairs are interpreted as the binding and the alias. However, cms props\n\t// have default values which mean that destructuring pattern would not be correct. Instead we\n\t// manually serialize.\n\tconst declarationString = destructuredProps.join(\", \")\n\tconst declaration =\n\t\tdeclarationString.length > 0 ? new SafeJS(`{ ${declarationString}, ...${Var.restProps} }`) : Var.restProps\n\n\treturn {\n\t\tvariableMap: !isEmptyObject(variableMap) ? variableMap : undefined,\n\t\ttypes: new SafeJS(types),\n\t\tprops: js.joinSections(js`const ${declaration} = ${SafeJS.fn(getProps, Var.props)}`, ...declarations),\n\t}\n}\n\ninterface ReferencedVariable {\n\tid: NodeID\n\tbinding?: SafeJS\n\tdefinition?: VariableDefinition\n}\n\n/**\n * Create a list of all of the variables that have been used in the generated\n * code, including the VariableDefinition if it exists on the scope node.\n *\n * The order of the list should be the same as the order of the variables in the\n * scope node. This ensures that the resulting PropertyControls are ordered as\n * expected in the property panel.\n */\nfunction getVariablesForPropertyControls(node: CanvasNode, context: Context): ReferencedVariable[] {\n\tconst list: ReferencedVariable[] = []\n\n\t// For vector set items, we need to generate property controls for all variables, even if they\n\t// are not referenced on the current item, so that the property controls for the whole set is\n\t// consistent. If the variable is unused on the current module, we generate a hidden control\n\t// when serializing, which let us hide the control normally, but show all controls when the icon\n\t// identifier is dynamic.\n\tconst includeUnreferenced = isVectorSetNode(node)\n\n\tconst variableDefinitions = getVariablesFromNode(node)\n\tconst variableBindings = context.variables.getBindings(node.id)\n\n\t// Order is defined by the user, so first iterate through the node's ordered\n\t// variable definitions.\n\tfor (const definition of variableDefinitions) {\n\t\tif (!isVariableDefinition(definition)) continue\n\n\t\tconst binding = variableBindings.get(definition.id)\n\t\tconst setterBinding = context.variables.getSetterBinding(definition.id)\n\t\tif (!includeUnreferenced && !binding && !setterBinding) continue\n\n\t\tlist.push({ id: definition.id, binding, definition })\n\t}\n\n\tconst pathVariables = nodePathVariables(node, context.componentLoader, context.tree)\n\tif (pathVariables) {\n\t\tfor (const [variableId] of pathVariables) {\n\t\t\tconst binding = variableBindings.get(variableId)\n\t\t\tif (!binding) continue\n\n\t\t\tlist.push({ id: variableId, binding })\n\t\t}\n\t}\n\n\treturn list\n}\n\nfunction removeControlFieldsForSerialization(control: VariableControlDescription, removeDescription: boolean) {\n\t// `hidden` might be a function which is not serializable. Currently user can't create hidden\n\t// control that requires serialization in the app yet.\n\tconst { hidden: _hidden, ...props } = control\n\tif (!removeDescription) return props\n\tconst { description: _description, ...otherProps } = props\n\treturn otherProps\n}\n\n/**\n * Given a VariableDefinition and the matching VariableControlDescription,\n * create either a serializable property control, or create a reference to a\n * dependency's control by importing it.\n */\nfunction serializableControlFromDescription(\n\tnode: CanvasNode,\n\tdefinition: VariableDefinition,\n\tcontrolDescription: VariableControlDescription,\n\ttree: CanvasTree,\n\timports: ImportCollector,\n\tvariables: VariableCollector | undefined,\n\t/** The description field is stripped from collection data */\n\texcludeDescription: boolean,\n\tforModuleType: ModuleType,\n\tscopeType: ScopeType,\n): SerializableControlDescription | undefined {\n\tconst { id, type } = definition\n\tswitch (type) {\n\t\tcase \"controlReference\": {\n\t\t\t// If the variable is a control reference, replace the plain\n\t\t\t// javascript object with a reference to the actual control of\n\t\t\t// the referenced component, importing the component if it\n\t\t\t// hasn't yet been imported. If the module does not exist in the\n\t\t\t// ModulesStore for some reason, we will not replace the plain\n\t\t\t// object. Additionally, the variable entityIdentifier may be\n\t\t\t// out of date relative to the component used on the canvas, so\n\t\t\t// we must ensure we use a reference to the version of the\n\t\t\t// module used on the canvas.\n\t\t\tconst parsedIdentifier = parseModuleIdentifier(\n\t\t\t\tcomponentIdentifierForVariableReference(tree, definition.entityIdentifier),\n\t\t\t)\n\t\t\tif (!parsedIdentifier || !definition.entityIdentifier || !isModuleExportIdentifier(parsedIdentifier)) return\n\n\t\t\tconst importedControlName = imports.addModuleImport(parsedIdentifier, {\n\t\t\t\tcomposeWithImports: [\n\t\t\t\t\timports.addImport(\"framer\", {\n\t\t\t\t\t\texportSpecifier: \"getPropertyControls\",\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t})\n\n\t\t\tif (!importedControlName) return\n\n\t\t\t// Unset the hidden property for referenced component controls\n\t\t\t// because the referenced hidden function will expect to receive\n\t\t\t// a props argument in the shape of the referenced component\u2019s\n\t\t\t// props, not the shape of this component\u2019s props.\n\t\t\tconst overrides = new SerializableObject({ hidden: js`undefined`, description: js`undefined` })\n\n\t\t\t// Pull in values from imported component (we check if it's set below).\n\t\t\tSerializableObject.addSpreadAtStart(overrides, js`${importedControlName}[${definition.controlKey}]`)\n\n\t\t\tif (isString(controlDescription.title)) {\n\t\t\t\toverrides.title = controlDescription.title\n\t\t\t}\n\n\t\t\tif (isString(controlDescription.description)) {\n\t\t\t\toverrides.description = controlDescription.description\n\t\t\t}\n\n\t\t\tif (withOptional(definition, scopeType)) {\n\t\t\t\toverrides.optional = isOptionalVariable(definition, scopeType) ? true : js`undefined`\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tcontrolDescription.type === ControlType.ResponsiveImage &&\n\t\t\t\thasVekterDefault(controlDescription) &&\n\t\t\t\tisDefaultResponsiveImage(controlDescription.__vekterDefault)\n\t\t\t) {\n\t\t\t\toverrides[vekterDefaultKey] = SafeJS.fromValue(controlDescription.__vekterDefault)\n\t\t\t}\n\t\t\tif (isOptionalVariable(definition, scopeType)) {\n\t\t\t\toverrides.defaultValue = js`undefined`\n\t\t\t} else if (hasDefaultAssetReference(controlDescription)) {\n\t\t\t\toverrides[defaultAssetReferenceKey] = SafeJS.fromValue(controlDescription.__defaultAssetReference)\n\t\t\t} else if (!isNullish(definition.initialValue)) {\n\t\t\t\toverrides.defaultValue = SafeJS.fromValue(definition.initialValue)\n\t\t\t}\n\n\t\t\treturn js`${importedControlName}?.[${definition.controlKey}] && ${overrides}`\n\t\t}\n\n\t\t// If the variable is a control reference pointing to our first-class property definitions, inline the\n\t\t// hardcoded control description.\n\t\tcase \"nodePropertyControlReference\":\n\t\tcase ControlType.Array:\n\t\tcase ControlType.VectorSetItem:\n\t\tcase ControlType.Boolean:\n\t\tcase ControlType.Color:\n\t\tcase ControlType.Date:\n\t\tcase ControlType.Enum:\n\t\tcase ControlType.EventHandler:\n\t\tcase ControlType.File:\n\t\tcase ControlType.Image:\n\t\tcase ControlType.Link:\n\t\tcase ControlType.LinkRelValues:\n\t\tcase ControlType.Number:\n\t\tcase ControlType.RichText:\n\t\tcase ControlType.ScrollSectionRef:\n\t\tcase ControlType.CustomCursor:\n\t\tcase ControlType.Cursor:\n\t\tcase ControlType.Transition:\n\t\tcase ControlType.BoxShadow:\n\t\tcase ControlType.String:\n\t\tcase ControlType.Border:\n\t\tcase ControlType.BorderRadius:\n\t\tcase ControlType.Gap:\n\t\tcase ControlType.Padding:\n\t\tcase ControlType.CollectionReference:\n\t\tcase ControlType.MultiCollectionReference:\n\t\tcase ControlType.TrackingId:\n\t\tcase ControlType.Location:\n\t\tcase \"slug\": {\n\t\t\tconst serializableControl: Exclude<SerializableControlDescription, SafeJS> = {\n\t\t\t\t...removeControlFieldsForSerialization(controlDescription, excludeDescription),\n\t\t\t\ttype: getControlType(controlDescription.type, imports),\n\t\t\t}\n\n\t\t\t// For vector set items, we need to generate property controls for all variables, even\n\t\t\t// if they are not referenced on the current item, so that the property controls for the\n\t\t\t// whole set is consistent. We generate a static hidden control when serializing, so\n\t\t\t// that unreferenced controls would be hidden normally, unless the vector set identifier\n\t\t\t// is dynamic.\n\t\t\tif (forModuleType === ModuleType.Vector && variables) {\n\t\t\t\tserializableControl.hidden = !variables.getBinding(node.id, id)\n\t\t\t}\n\n\t\t\treturn serializableControl\n\t\t}\n\t\tdefault:\n\t\t\tassertNever(type)\n\t}\n}\n\nfunction getVariablesFromNode(node: CanvasNode) {\n\treturn withVariables(node) ? node.variables : []\n}\n\nexport function serializePropertyControls(\n\tnode: CanvasNode,\n\tcomponentLoader: ComponentLoader,\n\ttree: CanvasTree,\n\timports: ImportCollector,\n\tvariables: VariableCollector | undefined,\n\tmoduleType: ModuleType,\n\tscopeType: ScopeType,\n\tvariableDefinitions = getVariablesFromNode(node),\n) {\n\tconst controls = defaultControlsForNode(node, componentLoader, imports)\n\tconst supportsChangeHandlers = moduleType === ModuleType.Canvas\n\tconst shouldExcludeDescription = isContentNode(node)\n\n\tconst allVariables = [...variableDefinitions]\n\n\tif (isCollectionNode(node)) {\n\t\tconst createdAtVariable = getCreatedAtVariable()\n\t\tallVariables.push(createdAtVariable)\n\n\t\tconst updatedAtVariable = getUpdatedAtVariable()\n\t\tallVariables.push(updatedAtVariable)\n\n\t\tconst previousItemVariable = getPreviousItemVariable(node)\n\t\tallVariables.push(previousItemVariable)\n\n\t\tconst nextItemVariable = getNextItemVariable(node)\n\t\tallVariables.push(nextItemVariable)\n\t}\n\n\tfor (const definition of allVariables) {\n\t\tif (!isVariableDefinition(definition)) continue\n\n\t\tconst controlDescription = controlDescriptionFromVariable(tree, componentLoader, definition, scopeType)\n\t\tif (isNull(controlDescription)) continue\n\n\t\tassert(controlDescription.type !== ControlType.Image, \"Image variables should become responsive images\")\n\n\t\tconst control = serializableControlFromDescription(\n\t\t\tnode,\n\t\t\tdefinition,\n\t\t\tcontrolDescription,\n\t\t\ttree,\n\t\t\timports,\n\t\t\tvariables,\n\t\t\tshouldExcludeDescription,\n\t\t\tmoduleType,\n\t\t\tscopeType,\n\t\t)\n\t\tif (isUndefined(control)) continue\n\n\t\tcontrols[definition.id] = control\n\n\t\tif (!supportsChangeHandlers) continue\n\t\tif (!isValidVariableForSetVariableValueAction(definition)) continue\n\n\t\tconst changeHandlerControlDescription: ChangeHandlerControlDescription = {\n\t\t\ttype: ControlType.ChangeHandler,\n\t\t\tchanges: definition.id,\n\t\t}\n\n\t\tcontrols[getOnChangeVariableKey(definition.id)] = {\n\t\t\t...changeHandlerControlDescription,\n\t\t\ttype: getControlType(ControlType.ChangeHandler, imports),\n\t\t}\n\t}\n\n\tif (isEmptyObject(controls)) return\n\n\treturn new SerializableObject(controls as SerializableRecord, SortBehavior.Unsorted)\n}\n\n/**\n * Create the React props, Typescript types, and Framer Property Controls for a\n * node.\n *\n * Smart Components and Web Pages will receive a Variant control if they have >\n * 1 top-level variants.\n */\nexport function createControlsTypesAndReactProps(\n\tnode: CanvasNode,\n\tcontext: Context,\n\tscopeType: ScopeType,\n\tmoduleType: ModuleType,\n\thumanReadableVariantMap: SafeJS | undefined,\n): {\n\treadonly propertyControls?: SerializableObject\n\treadonly types?: SafeJS\n\treadonly props?: SafeJS\n\treadonly variableMap?: Record<string, string>\n\treadonly humanReadableVariantMap?: SafeJS\n} {\n\tconst variableAndControlById: VariableAndControlById = {}\n\n\tconst variables: VariableDefinition[] = []\n\n\tfor (const { id, binding, definition } of getVariablesForPropertyControls(node, context)) {\n\t\tconst isURLVariable = definition && isWebPageNode(node) && node.hasVariable(definition.id)\n\t\tif (isURLVariable) continue\n\n\t\tconst controlDescription = definition\n\t\t\t? controlDescriptionFromVariable(context.tree, context.componentLoader, definition, scopeType)\n\t\t\t: undefined\n\n\t\tvariableAndControlById[id] = { control: controlDescription ?? undefined, variable: definition, binding }\n\n\t\tif (definition) {\n\t\t\tvariables.push(definition)\n\t\t}\n\t}\n\n\treturn {\n\t\tpropertyControls: serializePropertyControls(\n\t\t\tnode,\n\t\t\tcontext.componentLoader,\n\t\t\tcontext.tree,\n\t\t\tcontext.imports,\n\t\t\tcontext.variables,\n\t\t\tmoduleType,\n\t\t\tscopeType,\n\t\t\tvariables,\n\t\t),\n\t\t...serializedTypesAndReactProps(variableAndControlById, node, context, scopeType, humanReadableVariantMap),\n\t}\n}\n\nfunction getOnChangeVariableKey(variableId: VariableID): string {\n\treturn `on${variableId}Change`\n}\n", "import type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport {\n\tassert,\n\tModuleType,\n\tassertNever,\n\tgetLogger,\n\tlocalModuleIdentifierForStableName,\n\tmurmurHash,\n\tstableStringify,\n} from \"@framerjs/shared\"\nimport type { SlotControlItem } from \"document/models/controlProps/ControlProp.ts\"\nimport { isRawControlProp } from \"document/models/controlProps/RawControlProp.ts\"\nimport { isPrefixedControlPropKey } from \"document/models/controlProps/controlPropKey.ts\"\nimport { ControlType } from \"library/index.ts\"\nimport { isArray, isNumber, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { ClassDiscriminator } from \"utils/withClassDiscriminator.ts\"\nimport type { CanvasTree } from \"../../CanvasTree.ts\"\nimport type { AnyCanvasNode, CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport { ChildList } from \"../../nodes/ChildList.ts\"\nimport { isLocalModuleNode } from \"../../nodes/LocalModuleNode.ts\"\nimport type { NodeID } from \"../../nodes/NodeID.ts\"\nimport type { ProxyRouteNode } from \"../../nodes/ProxyRouteNode.ts\"\nimport { generateReplicaChildId } from \"../../nodes/TemplateHelper.ts\"\nimport {\n\tisCodeComponentNode,\n\tisCollectionNode,\n\tisCustomCodeNode,\n\tisCustomCodeScopeNode,\n\tisDesignPageNode,\n\tisVectorSetNode,\n} from \"../../nodes/utils/nodeCheck.ts\"\nimport { isValidSlotItemNode } from \"../../nodes/utils/slotUtils.ts\"\nimport type { WithABTesting } from \"../WithABTesting.ts\"\nimport { hasCollectionDataSource } from \"../WithCollectionDataSource.ts\"\nimport type { WithCustomizations } from \"../WithCustomizations.ts\"\nimport type { WithKitSectionHash } from \"../WithKitSectionHash.ts\"\nimport type { WithKitSectionSource } from \"../WithKitSectionSource.ts\"\nimport type { layoutTemplateOverrideDefaults } from \"../WithLayoutTemplate.ts\"\nimport type { WithModuleSourceRevision } from \"../WithModuleRevision.ts\"\nimport { usesModuleRevision, usesModuleRevisionIncludingReplicas } from \"../WithModuleRevision.ts\"\nimport { isPrefixedPluginDataKey } from \"../WithPluginData.ts\"\nimport { isReplica } from \"../WithTemplate.ts\"\nimport type { IsVectorSetItem } from \"../WithVectorSetItem.ts\"\nimport { isVectorSetItem } from \"../WithVectorSetItem.ts\"\n\n/**\n * @TODO - Extract this to a utility that can be typed properly to factor in any\n * node property. For instance consider a function that takes a node type and\n * returns a subset of ignored keys.\n */\nconst nodePropertiesToIgnoreWhenHashing = {\n\tcache: true,\n\tmutable: true,\n\tupdate: true,\n\tparentid: true,\n\toriginalid: true,\n\tduplicatedFrom: true,\n\tmoduleSourceRevision: true,\n\tmoduleSourceRevisionHint: true,\n\tmoduleSourceRevisionCommittedHint: true,\n\tkitSectionsStructure: true,\n\tkitSectionHash: true,\n\tkitSectionSource: true,\n\tkitPageHTMLHash: true,\n\tcustomizations: true,\n\tcustomizationsDescription: true,\n\tcustomizationsSectionId: true,\n\tcustomizationsCategory: true,\n\tcustomizationsRules: true,\n\tisApplyingCustomizations: true,\n\t// Having or not having a layout template does not influence the module\n\t// source revision.\n\tlayoutTemplateIdentifierOverride: true,\n\tabTestingParentId: true,\n\tabTestingDistributionWeightPpm: true,\n} as const satisfies Partial<\n\tRecord<\n\t\tkeyof (CanvasNode &\n\t\t\tWithModuleSourceRevision &\n\t\t\tWithCustomizations &\n\t\t\tWithKitSectionHash &\n\t\t\tWithKitSectionSource &\n\t\t\tWithABTesting &\n\t\t\t// @FIXME - This is a hack to get the kit sections structure to be included in the revision.\n\t\t\ttypeof layoutTemplateOverrideDefaults & { kitSectionsStructure: true; kitPageHTMLHash: true }),\n\t\tboolean\n\t>\n>\n\nexport function filterNonHashableProperties(key: string, value: unknown): unknown {\n\tif (isUndefined(value)) return\n\tif (key === \"children\" && value instanceof ChildList) return value.toArray()\n\tif (nodePropertiesToIgnoreWhenHashing[key as keyof typeof nodePropertiesToIgnoreWhenHashing]) return\n\tif (key.startsWith(\"export\")) return\n\tif (isPrefixedPluginDataKey(key)) return\n\treturn value\n}\n\nfunction filterNonHashablePropertiesAndChildren(k: string, value: unknown): unknown {\n\tif (k === \"children\") return\n\treturn filterNonHashableProperties(k, value)\n}\n\nexport function replaceSlotReferencesWithNodes<T = unknown>(\n\tkey: string,\n\tvalue: T,\n\tnode: CanvasNode,\n\tscopeId: NodeID,\n\ttree: CanvasTree,\n) {\n\tif (!isPrefixedControlPropKey(key) || !isRawControlProp(value)) return value\n\n\tif (value.type === ControlType.Slot) {\n\t\t// If the component slots are children, there is no need to follow the reference to the node.\n\t\tif (!isArray(value.value) || (isCodeComponentNode(node) && node.slotsAreChildNodes)) return value\n\n\t\treturn value.value.map((item: SlotControlItem) => {\n\t\t\tconst reference = tree.get(item.reference)\n\t\t\treturn isValidSlotItemNode(scopeId, reference) ? reference : undefined\n\t\t})\n\t} else if (value.type === ControlType.ComponentInstance) {\n\t\tif (!isString(value.value)) return value\n\n\t\tconst reference = tree.get(value.value)\n\t\treturn isValidSlotItemNode(scopeId, reference) ? reference : undefined\n\t} else if (value.type === ControlType.Array) {\n\t\tif (!isArray(value.value)) return value\n\t\tconst result: CanvasNode[] = []\n\t\t// If the array type doesn't have any component instance types, we assume it's just a list\n\t\t// of other types, and use it as is.\n\t\tlet anyComponentInstanceTypes = false\n\n\t\tfor (const item of value.value) {\n\t\t\tif (!isRawControlProp(item)) continue\n\t\t\tif (item.type !== ControlType.ComponentInstance) continue\n\n\t\t\tanyComponentInstanceTypes = true\n\n\t\t\tif (!isString(item.value)) continue\n\t\t\tconst reference = tree.get(item.value)\n\t\t\tif (!isValidSlotItemNode(scopeId, reference)) continue\n\t\t\tresult.push(reference)\n\t\t}\n\n\t\treturn anyComponentInstanceTypes ? result : value\n\t}\n\n\treturn value\n}\n\nfunction filterDesignPageGroundNodeFollowingSlots(tree: CanvasTree, scopeId: NodeID) {\n\treturn (k: string, value: unknown, node: CanvasNode): unknown => {\n\t\treturn filterNonHashableProperties(k, replaceSlotReferencesWithNodes(k, value, node, scopeId, tree))\n\t}\n}\n\nconst log = getLogger(\"ModuleSourceRevision\")\n\n/**\n * Proxy nodes are shown in the publish changelog, so need to calculate a\n * revision to know when the change across publishes.\n */\nexport function calculateRouteRevision(node: ProxyRouteNode): number | undefined {\n\treturn murmurHash(stableStringify(node, filterNonHashableProperties))\n}\n\nexport function calculateKitSectionHash(\n\ttree: CanvasTree,\n\tnode: AnyCanvasNode & WithKitSectionHash,\n\tvariants: readonly CanvasNode[],\n): number {\n\tlet hash = murmurHash(stableStringify(node, filterNonHashableProperties))\n\tfor (const variant of variants) {\n\t\tconst replicaNode = tree.get(generateReplicaChildId(variant.id, node.id))\n\t\tif (!replicaNode) continue\n\t\thash += murmurHash(stableStringify(replicaNode, filterNonHashableProperties))\n\t}\n\treturn hash\n}\n\n/**\n * @TODO - https://github.com/framer/FramerStudio/pull/18389#discussion_r1705596945\n */\nexport function calculateModuleRevision(\n\tnode: CanvasNode & WithModuleSourceRevision,\n\ttree: CanvasTree,\n): number | undefined {\n\tswitch (node.__class) {\n\t\tcase ClassDiscriminator.CollectionItemNode:\n\t\tcase ClassDiscriminator.ImageStylePresetNode:\n\t\tcase ClassDiscriminator.InlineCodeStylePresetNode:\n\t\tcase ClassDiscriminator.LayoutTemplateNode:\n\t\tcase ClassDiscriminator.LinkStylePresetNode:\n\t\tcase ClassDiscriminator.SmartComponentNode:\n\t\tcase ClassDiscriminator.TableStylePresetNode:\n\t\tcase ClassDiscriminator.WebPageNode: {\n\t\t\treturn murmurHash(stableStringify(node, filterNonHashableProperties))\n\t\t}\n\t\tcase ClassDiscriminator.FrameNode: {\n\t\t\tconst parent = tree.get(node.parentid)\n\t\t\tif (!parent || !isDesignPageNode(parent)) return undefined\n\t\t\treturn murmurHash(stableStringify(node, filterDesignPageGroundNodeFollowingSlots(tree, parent.id)))\n\t\t}\n\t\tcase ClassDiscriminator.CollectionNode: {\n\t\t\tassert(isCollectionNode(node), \"Expected collection node\")\n\n\t\t\t// CMS Databases will generate different locale fallback chains\n\t\t\t// depending on available locales and fallbacks defined on the root\n\t\t\t// node, so the revision must factor those in to allow regeneration\n\t\t\t// if locales change but the collection does not.\n\t\t\tconst locales = stableStringify(tree.root.locales)\n\t\t\t// Also include translatePagePaths since it affects whether slugs are localized\n\t\t\tconst translatePagePaths = stableStringify(tree.root.webMetadata?.translatePagePaths)\n\t\t\tconst base = stableStringify(node, filterNonHashablePropertiesAndChildren)\n\t\t\t// Collections can be large, and its often slow to calculate\n\t\t\t// revisions for the whole collection. To optimize this, collection\n\t\t\t// item nodes also calculate revisions. Then revision of the\n\t\t\t// collection is a hash of the child revisions.\n\t\t\tconst items = stableStringify(node.getUnsortedChildren()?.map(child => child.moduleSourceRevision))\n\t\t\treturn murmurHash(locales + translatePagePaths + base + items)\n\t\t}\n\t\tcase ClassDiscriminator.PresetsListNode: {\n\t\t\t// PresetListNodes calculate a revision based on their children that\n\t\t\t// don't themselves calculate a revision, e.g. ComponentPresetNodes,\n\t\t\t// so we preemptively filter out children we don't want to include\n\t\t\t// in the calculation.\n\t\t\tconst nodes = node.children?.filter(child => !usesModuleRevisionIncludingReplicas(child, tree)) ?? []\n\t\t\treturn murmurHash(stableStringify(nodes, filterNonHashableProperties))\n\t\t}\n\t\tcase ClassDiscriminator.TextStylePresetNode:\n\t\tcase ClassDiscriminator.BlockquoteStylePresetNode: {\n\t\t\t// Text and Blockquote style preset nodes calculate a revision based\n\t\t\t// on all of their replicas.\n\t\t\tif (isReplica(node)) return node.moduleSourceRevision\n\t\t\tlet string = stableStringify(node, filterNonHashableProperties)\n\t\t\tnode.cache.replicaInstances?.forEach(id => {\n\t\t\t\tconst replica = tree.getNodeWithTrait(id, isReplica)\n\t\t\t\tif (replica) string += stableStringify(replica, filterNonHashableProperties)\n\t\t\t})\n\n\t\t\treturn murmurHash(string)\n\t\t}\n\t\tcase ClassDiscriminator.VectorSetNode: {\n\t\t\tassert(isVectorSetNode(node), \"Expected VectorSetNode\")\n\t\t\tconst items = node.getVectorSetItems().map(child => {\n\t\t\t\tconst localId = localModuleIdentifierForStableName(ModuleType.Vector, child.id, \"default\").localId\n\t\t\t\tconst localModule = tree.getNodeWithTrait(localId, isLocalModuleNode)\n\t\t\t\t// Vector items that haven't been persisted before are not included.\n\t\t\t\treturn localModule ? localModule.save.moduleId : \"\"\n\t\t\t})\n\n\t\t\treturn murmurHash(stableStringify(items) + node.name)\n\t\t}\n\t\tcase ClassDiscriminator.ShapeContainerNode: {\n\t\t\tif (!isVectorSetItem(node)) return undefined\n\t\t\tconst scope = tree.getScopeNodeFor(node)\n\t\t\tif (!isVectorSetNode(scope)) return undefined\n\t\t\t// Shape Containers in a Vector Set calculate a revision based on the variables in the\n\t\t\t// scope, and themselves, but not their sibling Vectors.\n\t\t\tconst item = stableStringify(node, filterNonHashableProperties)\n\n\t\t\treturn murmurHash(item + stableStringify(scope.variables))\n\t\t}\n\t\tcase ClassDiscriminator.CustomCodeScopeNode: {\n\t\t\t// Custom code scope nodes calculate a revision based on the properties of the node\n\t\t\t// and the data sources of the CMS pages they are associated with.\n\t\t\tassert(isCustomCodeScopeNode(node), \"Expected CustomCodeScopeNode\")\n\t\t\tconst loadedCustomCodeScopeNode = node.loaded\n\t\t\tassert(loadedCustomCodeScopeNode, \"Expected CustomCodeScopeNode to be loaded\")\n\t\t\tconst pageDataSources: Record<NodeID, ModuleExportIdentifierString> = {}\n\t\t\tfor (const customCodeNode of loadedCustomCodeScopeNode.children) {\n\t\t\t\tif (!isCustomCodeNode(customCodeNode) || !customCodeNode.pageIds) continue\n\t\t\t\tfor (const webPageId of customCodeNode.pageIds) {\n\t\t\t\t\tconst pageWithDataSource = tree.getNodeWithTrait(webPageId, hasCollectionDataSource)\n\t\t\t\t\tif (!pageWithDataSource) continue\n\t\t\t\t\tpageDataSources[webPageId] = pageWithDataSource.dataIdentifier\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst props = stableStringify(node, filterNonHashableProperties)\n\t\t\treturn murmurHash(props + stableStringify(pageDataSources))\n\t\t}\n\t\tcase ClassDiscriminator.CanvasPageNode:\n\t\tcase ClassDiscriminator.RootNode:\n\t\t\t// @TODO - Canvas Page Screens (prototype screens), CanvasPage nodes\n\t\t\t// (prototypes) and the RootNode (site metadata) will calculate a\n\t\t\t// revision in the future.\n\t\t\treturn undefined\n\t\tcase ClassDiscriminator.ComponentPresetNode:\n\t\t\t// ComponentPresetNode doesn't calculate a revision, the parent\n\t\t\t// PrestListNode does.\n\t\t\treturn undefined\n\t\tcase ClassDiscriminator.AbTestsEntityTypeRootNode:\n\t\tcase ClassDiscriminator.AgentPanelTool:\n\t\tcase ClassDiscriminator.AgentDragSelectTool:\n\t\tcase ClassDiscriminator.AgentSelectTool:\n\t\tcase ClassDiscriminator.AnalyticsScopeNode:\n\t\tcase ClassDiscriminator.BlockquoteEntityTypeRootNode:\n\t\tcase ClassDiscriminator.BooleanShapeNode:\n\t\tcase ClassDiscriminator.BoxShadow:\n\t\tcase ClassDiscriminator.BranchNode:\n\t\tcase ClassDiscriminator.BranchesNode:\n\t\tcase ClassDiscriminator.CanvasNode:\n\t\tcase ClassDiscriminator.CanvasScopeNode:\n\t\tcase ClassDiscriminator.CustomCodeNode:\n\t\tcase ClassDiscriminator.DesignPageNode:\n\t\tcase ClassDiscriminator.ChatTool:\n\t\tcase ClassDiscriminator.CMSEntityTypeRootNode:\n\t\tcase ClassDiscriminator.CodeComponentNode:\n\t\tcase ClassDiscriminator.CodeFileEntityTypeRootNode:\n\t\tcase ClassDiscriminator.CollectionReferenceVariableEditTool:\n\t\tcase ClassDiscriminator.Color:\n\t\tcase ClassDiscriminator.ColorEntityTypeRootNode:\n\t\tcase ClassDiscriminator.ColorStyleTokenListNode:\n\t\tcase ClassDiscriminator.ColorStyleTokenNode:\n\t\tcase ClassDiscriminator.ComponentEntityTypeRootNode:\n\t\tcase ClassDiscriminator.ConicGradient:\n\t\tcase ClassDiscriminator.ContentManagementNode:\n\t\tcase ClassDiscriminator.CreateCodeComponentBaseTool:\n\t\tcase ClassDiscriminator.CreateFrameBaseTool:\n\t\tcase ClassDiscriminator.CreateShapeBaseTool:\n\t\tcase ClassDiscriminator.CreateTextTool:\n\t\tcase ClassDiscriminator.EntityFolderNode:\n\t\tcase ClassDiscriminator.EntityReferenceNode:\n\t\tcase ClassDiscriminator.EntityRootNode:\n\t\tcase ClassDiscriminator.ContentManagementEntityTypeRootNode:\n\t\tcase ClassDiscriminator.ErrorListNode:\n\t\tcase ClassDiscriminator.ErrorNode:\n\t\tcase ClassDiscriminator.ExportOptions:\n\t\tcase ClassDiscriminator.ExternalModuleNode:\n\t\tcase ClassDiscriminator.ExternalModulesListNode:\n\t\tcase ClassDiscriminator.FeedbackTool:\n\t\tcase ClassDiscriminator.FormBooleanInputNode:\n\t\tcase ClassDiscriminator.FormPlainTextInputNode:\n\t\tcase ClassDiscriminator.FormSelectNode:\n\t\tcase ClassDiscriminator.FunnelNode:\n\t\tcase ClassDiscriminator.FunnelsEntityTypeRootNode:\n\t\tcase ClassDiscriminator.FunnelStepActionNode:\n\t\tcase ClassDiscriminator.FunnelStepNode:\n\t\tcase ClassDiscriminator.GapTool:\n\t\tcase ClassDiscriminator.GradientColorStop:\n\t\tcase ClassDiscriminator.GradientToolManagerTool:\n\t\tcase ClassDiscriminator.GuideMoveTool:\n\t\tcase ClassDiscriminator.HeaderRouteNode:\n\t\tcase ClassDiscriminator.HighlightStackItemTool:\n\t\tcase ClassDiscriminator.HighlightTool:\n\t\tcase ClassDiscriminator.InitialTool:\n\t\tcase ClassDiscriminator.InlineCodeEntityTypeRootNode:\n\t\tcase ClassDiscriminator.LayoutTemplateEntityTypeRootNode:\n\t\tcase ClassDiscriminator.LineAnchorMoveTool:\n\t\tcase ClassDiscriminator.LinearGradient:\n\t\tcase ClassDiscriminator.LinkEntityTypeRootNode:\n\t\tcase ClassDiscriminator.LinkTool:\n\t\tcase ClassDiscriminator.LoadingShieldTool:\n\t\tcase ClassDiscriminator.LocalizationGlossaryItemNode:\n\t\tcase ClassDiscriminator.LocalizationGlossaryNode:\n\t\tcase ClassDiscriminator.LocalModuleNode:\n\t\tcase ClassDiscriminator.LocalModulesListNode:\n\t\tcase ClassDiscriminator.MoveTool:\n\t\tcase ClassDiscriminator.MutableNode:\n\t\tcase ClassDiscriminator.OvalShapeNode:\n\t\tcase ClassDiscriminator.OverlayNode:\n\t\tcase ClassDiscriminator.PaddingTool:\n\t\tcase ClassDiscriminator.PageLinkTool:\n\t\tcase ClassDiscriminator.PanTool:\n\t\tcase ClassDiscriminator.PathCurveBendTool:\n\t\tcase ClassDiscriminator.PathDefaultTool:\n\t\tcase ClassDiscriminator.PathNode:\n\t\tcase ClassDiscriminator.PathSegment:\n\t\tcase ClassDiscriminator.PathSegmentAdditionTool:\n\t\tcase ClassDiscriminator.PathSegmentHandleMoveTool:\n\t\tcase ClassDiscriminator.PathSegmentMoveTool:\n\t\tcase ClassDiscriminator.PathSegmentSelectTool:\n\t\tcase ClassDiscriminator.PolygonShapeNode:\n\t\tcase ClassDiscriminator.PreviewSettings:\n\t\tcase ClassDiscriminator.ProxyRouteNode:\n\t\tcase ClassDiscriminator.RadialGradient:\n\t\tcase ClassDiscriminator.RadiusTool:\n\t\tcase ClassDiscriminator.RecoveryTool:\n\t\tcase ClassDiscriminator.RectangleShapeNode:\n\t\tcase ClassDiscriminator.RedirectRouteNode:\n\t\tcase ClassDiscriminator.ResizeTool:\n\t\tcase ClassDiscriminator.RewriteRouteNode:\n\t\tcase ClassDiscriminator.RichTextEditTool:\n\t\tcase ClassDiscriminator.RichTextNode:\n\t\tcase ClassDiscriminator.RichTextVariableEditTool:\n\t\tcase ClassDiscriminator.RotateTool:\n\t\tcase ClassDiscriminator.RouteNode:\n\t\tcase ClassDiscriminator.RouteLocaleNode:\n\t\tcase ClassDiscriminator.RouteSegmentNode:\n\t\tcase ClassDiscriminator.RouteSegmentRootNode:\n\t\tcase ClassDiscriminator.RoutesNode:\n\t\tcase ClassDiscriminator.SampleColorTool:\n\t\tcase ClassDiscriminator.ScaleTool:\n\t\tcase ClassDiscriminator.ScopeNode:\n\t\tcase ClassDiscriminator.SelectTool:\n\t\tcase ClassDiscriminator.ShaderNode:\n\t\tcase ClassDiscriminator.Shadow:\n\t\tcase ClassDiscriminator.ShapeGroupNode:\n\t\tcase ClassDiscriminator.SlotConnectTool:\n\t\tcase ClassDiscriminator.SlotNode:\n\t\tcase ClassDiscriminator.SlotPropertyNode:\n\t\tcase ClassDiscriminator.StarShapeNode:\n\t\tcase ClassDiscriminator.StringVariableEditTool:\n\t\tcase ClassDiscriminator.DateVariableEditTool:\n\t\tcase ClassDiscriminator.EnumVariableEditTool:\n\t\tcase ClassDiscriminator.StyledTextDraft:\n\t\tcase ClassDiscriminator.SVGNode:\n\t\tcase ClassDiscriminator.TestTool:\n\t\tcase ClassDiscriminator.TextEditTool:\n\t\tcase ClassDiscriminator.TextEntityTypeRootNode:\n\t\tcase ClassDiscriminator.TextNode:\n\t\tcase ClassDiscriminator.VectorSetEntityTypeRootNode:\n\t\tcase ClassDiscriminator.VekterGradientTool:\n\t\tcase ClassDiscriminator.VekterPathEngine:\n\t\tcase ClassDiscriminator.VekterTool:\n\t\tcase ClassDiscriminator.ViewportResizeTool:\n\t\tcase ClassDiscriminator.ZoomSelectTool:\n\t\tcase ClassDiscriminator.ZoomTool:\n\t\t\treturn undefined\n\t\tdefault:\n\t\t\tassertNever(node.__class, \"getModuleRevision: node.__class must be a valid value\")\n\t}\n}\n\n/**\n * Check if the revision hint has changed since the last time we calculated the\n * revision for this node id.\n */\nexport function hasRevisionHintChanged(tree: CanvasTree, id: NodeID) {\n\tconst sourceNode = tree.get(id)\n\tif (!sourceNode || !usesModuleRevision(sourceNode, tree)) return false\n\tif (\n\t\tisUndefined(sourceNode.moduleSourceRevisionHint) ||\n\t\tsourceNode.moduleSourceRevisionCommittedHint === sourceNode.moduleSourceRevisionHint\n\t) {\n\t\tlog.debug(`Hint hasn't changed for ${sourceNode.id}.`)\n\t\treturn false\n\t}\n\tlog.debug(`Initial Revision: ${sourceNode.moduleSourceRevision}`)\n\treturn true\n}\n\n/**\n * Assuming that the revision hint has changed, calculate the new revision for\n * this node. If the revision has changed, return the new revision. If the\n * revision hasn't changed, update the committed hint and return undefined.\n */\nfunction updateRevision(tree: CanvasTree, id: NodeID): undefined | number {\n\tconst node = tree.get(id)\n\tif (!node || !usesModuleRevision(node, tree)) return undefined\n\tconst start = performance.now()\n\tconst moduleSourceRevision = calculateModuleRevision(node, tree)\n\tlog.debug(`Spent ${performance.now() - start}ms computing module revision for ${node.id}`)\n\n\tconst isNewRevision = isNumber(moduleSourceRevision) && moduleSourceRevision !== node.moduleSourceRevision\n\tlog.debug(`Revisions: ${node.moduleSourceRevision}, ${moduleSourceRevision}`)\n\n\tconst moduleSourceRevisionCommittedHint = node.moduleSourceRevisionHint\n\tconst update = isNewRevision\n\t\t? { moduleSourceRevision, moduleSourceRevisionCommittedHint }\n\t\t: { moduleSourceRevisionCommittedHint }\n\n\tlog.debug(\n\t\tisNewRevision\n\t\t\t? `Updating moduleSourceRevision for ${node.id}.`\n\t\t\t: `Updating moduleSourceRevisionCommittedHint for ${node.id}.`,\n\t)\n\n\tnode.setIgnoringReplica(update, tree)\n\n\treturn isNewRevision ? moduleSourceRevision : undefined\n}\n\n/**\n * Update the module revision for a node. If the revision has changed, return\n * the new revision. For CollectionNodes, this means calculating the revision\n * for CollectionItemNodes with revision hint changes first.\n *\n * Consider calling { @see hasRevisionHintChanged } first to make sure this is\n * necessary. This function does not call that function internally to avoid\n * mixing canvas tree references.\n */\nexport function updateModuleRevision(\n\tid: NodeID,\n\tscheduleDocumentUpdateIgnoringUndo: <T>(task: (tree: CanvasTree) => T) => Promise<T | undefined>,\n): Promise<number | undefined> {\n\treturn scheduleDocumentUpdateIgnoringUndo(tree => {\n\t\tif (tree.isViewOnly) return\n\t\tconst node = tree.get(id)\n\t\t// If this is a CollectionNode, we need to calculate the revision for\n\t\t// all of its changed children first.\n\t\tif (isCollectionNode(node)) {\n\t\t\tnode.getUnsortedChildren()?.forEach(child => {\n\t\t\t\tif (!hasRevisionHintChanged(tree, child.id)) return\n\t\t\t\tupdateRevision(tree, child.id)\n\t\t\t})\n\t\t}\n\n\t\treturn updateRevision(tree, id)\n\t})\n}\n\n/**\n * Update the module revision for a list of vector set items in a single document update.\n */\nexport function updateVectorSetItemsModuleRevisions(\n\tnodes: (CanvasNode & IsVectorSetItem)[],\n\tscheduleDocumentUpdateIgnoringUndo: <T>(task: (tree: CanvasTree) => T) => Promise<T | undefined>,\n): Promise<Record<NodeID, number | undefined> | undefined> {\n\treturn scheduleDocumentUpdateIgnoringUndo(tree => {\n\t\tif (tree.isViewOnly) return\n\n\t\treturn nodes.reduce<Record<NodeID, number | undefined>>((acc, node) => {\n\t\t\tacc[node.id] = updateRevision(tree, node.id) ?? 1\n\t\t\treturn acc\n\t\t}, {})\n\t})\n}\n", "import type { CodeGenerationMetrics } from \"@framerjs/events\"\nimport { ModuleType, assertNever, getLogger } from \"@framerjs/shared\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport type { SourceCodeWithArtifacts } from \"./components/GeneratedComponent.ts\"\n\nconst log = getLogger(\"CodeGenerationStore\")\n\ntype Task = \"update\" | \"synchronize\" | \"serialize\" | \"transform\"\n\n/**\n * A code generation session is considered complete when the `transform` task is\n * completed.\n */\nconst completeSessionMarker: Task = \"transform\"\n\ninterface RecordHandler {\n\tend(output?: SourceCodeWithArtifacts[]): void\n}\n\n/**\n * Track the duration of async tasks during code generation, finally recording\n * the values when the module is compiled.\n *\n * @TODO - Investigate if we can \"just\" use MetricsCollector, it has similar\n * functionality.\n */\nexport class CodeGenerationTelemetrySession {\n\t#marks: [Task, number][] = []\n\t#sources: SourceCodeWithArtifacts[] | undefined = undefined\n\n\tconstructor(private readonly sourceNode: CanvasNode) {}\n\n\tstart(task: Task): RecordHandler {\n\t\tconst start = performance.now()\n\t\treturn {\n\t\t\tend: sources => {\n\t\t\t\tthis.#marks.push([task, performance.now() - start])\n\t\t\t\tthis.#sources = this.#sources ?? sources\n\t\t\t\tif (task === completeSessionMarker) this.completeSession()\n\t\t\t},\n\t\t}\n\t}\n\tprivate restartSession() {\n\t\tthis.#marks = []\n\t\tthis.#sources = undefined\n\t}\n\tprivate completeSession() {\n\t\tthis.#sources?.forEach(({ type, source, artifacts }) => {\n\t\t\tconst codeType = codeTypeForModuleType(type, this.sourceNode)\n\t\t\tif (!codeType) return\n\n\t\t\tconst metrics: CodeGenerationMetrics = {\n\t\t\t\tcodeType,\n\t\t\t\tdurationMs: 0,\n\t\t\t\tupdateCount: 0,\n\t\t\t\tupdateDurationMs: 0,\n\t\t\t\tserializationDurationMs: 0,\n\t\t\t\tcompilationDurationMs: 0,\n\t\t\t\tsynchronizationDurationMs: 0,\n\t\t\t\tsize: source.length,\n\t\t\t\tid: this.sourceNode.id,\n\t\t\t\tnodes: artifacts?.metrics?.nodes ?? 1,\n\t\t\t\tvariants: artifacts?.metrics?.variants ?? 0,\n\t\t\t\tsvgBytes: artifacts?.metrics?.svgBytes,\n\t\t\t\ttextBytes: artifacts?.metrics?.textBytes,\n\t\t\t}\n\n\t\t\tfor (const [task, duration] of this.#marks) {\n\t\t\t\tmetrics.durationMs += duration\n\t\t\t\tswitch (task) {\n\t\t\t\t\tcase \"update\":\n\t\t\t\t\t\tmetrics.updateCount++\n\t\t\t\t\t\tmetrics.updateDurationMs += duration\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase \"serialize\":\n\t\t\t\t\t\tmetrics.serializationDurationMs += duration\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase \"transform\":\n\t\t\t\t\t\tmetrics.compilationDurationMs += duration\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase \"synchronize\":\n\t\t\t\t\t\tmetrics.synchronizationDurationMs += duration\n\t\t\t\t\t\tbreak\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tassertNever(task)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet key: keyof CodeGenerationMetrics\n\t\t\tfor (key in metrics) {\n\t\t\t\tconst value = metrics[key]\n\t\t\t\tif (isNumber(value)) {\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- needed so the type doesn't become `never`\n\t\t\t\t\t;(metrics[key] as CodeGenerationMetrics[keyof CodeGenerationMetrics]) = Math.round(value)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog.trace(\"Code Generation Metrics\", metrics)\n\n\t\t\trecord(\"code_generation\", metrics)\n\t\t})\n\n\t\tthis.restartSession()\n\t}\n}\n\nfunction codeTypeForModuleType(\n\tmoduleType: ModuleType,\n\tsourceNode: CanvasNode,\n): CodeGenerationMetrics[\"codeType\"] | undefined {\n\tswitch (moduleType) {\n\t\tcase ModuleType.Canvas:\n\t\t\treturn \"smart_component\"\n\t\tcase ModuleType.CSS:\n\t\t\treturn \"styles_preset\"\n\t\tcase ModuleType.Collection:\n\t\t\treturn \"collection\"\n\t\tcase ModuleType.DraftCollection:\n\t\t\treturn \"draft_collection\"\n\t\tcase ModuleType.ComponentPresets:\n\t\t\treturn \"component_presets\"\n\t\tcase ModuleType.Screen:\n\t\t\tif (isWebPageNode(sourceNode)) return \"web_page\"\n\t\t\treturn \"prototype_screen\"\n\t\tcase ModuleType.Prototype:\n\t\t\treturn \"prototype\"\n\t\tcase ModuleType.Vector:\n\t\t\treturn \"vector\"\n\t\tcase ModuleType.VectorSet:\n\t\t\treturn \"vector_set\"\n\t\tcase ModuleType.Snippets:\n\t\t\treturn \"snippets\"\n\t\tcase ModuleType.Code:\n\t\tcase ModuleType.Config:\n\t\tcase ModuleType.SiteMetadata:\n\t\tcase ModuleType.WebPageMetadata:\n\t\tcase ModuleType.LayoutTemplate:\n\t\tcase ModuleType.Localization:\n\t\tcase ModuleType.Design:\n\t\tcase ModuleType.Kit:\n\t\tcase ModuleType.Shader:\n\t\t\t// Untracked module types.\n\t\t\treturn undefined\n\t\tdefault:\n\t\t\tassertNever(moduleType)\n\t}\n}\n", "import { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { Locale, LocaleId } from \"document/models/CanvasTree/traits/WithLocales.ts\"\nimport type { EnumVariableDefinition } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { isPreventingLocalization } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { join } from \"utils/join.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\n\ninterface LocalizedEnumCaseNames {\n\t[enumCaseId: string]: Record<LocaleId, string> | undefined\n}\n\nfunction getLocalizedEnumCaseNames(variable: EnumVariableDefinition, locales: readonly Locale[] | undefined) {\n\tconst result: LocalizedEnumCaseNames = {}\n\tif (!locales) return result\n\tif (isPreventingLocalization(variable)) return result\n\n\tfor (const enumCase of variable.cases) {\n\t\tfor (const locale of locales) {\n\t\t\tconst nameLocalized = enumCase.nameLocalized\n\t\t\tif (!nameLocalized) continue\n\n\t\t\tconst localizedValue = nameLocalized[locale.id]?.value\n\t\t\tif (!isString(localizedValue)) continue\n\n\t\t\tconst enumCaseNames = result[enumCase.id] ?? {}\n\t\t\tresult[enumCase.id] = enumCaseNames\n\n\t\t\tenumCaseNames[locale.id] = localizedValue\n\t\t}\n\t}\n\n\treturn result\n}\n\nexport function createEnumToDisplayNameFromVariable(\n\tvariable: EnumVariableDefinition,\n\tlocales: readonly Locale[] | undefined,\n\tfunctionName: SafeJS,\n): SafeJS {\n\tif (variable.cases.length === 0) return js`(value) => value`\n\n\tconst localizedEnumCaseNames = getLocalizedEnumCaseNames(variable, locales)\n\n\tconst value = js`value`\n\tconst locale = js`locale`\n\tconst fallbackLocale = js`fallbackLocale`\n\n\treturn new SafeJS(\n\t\tjoin.lines(\n\t\t\tjs`(${value}, ${locale}) => {`,\n\t\t\tjs`const ${fallbackLocale} = ${locale}?.fallback;`,\n\t\t\tjs`switch (${value}) {`,\n\t\t\t...variable.cases.map(({ id, name }) => {\n\t\t\t\tconst localizedEnumCaseName = localizedEnumCaseNames[id]\n\n\t\t\t\tif (!localizedEnumCaseName) {\n\t\t\t\t\treturn js`case ${id}: return ${name};`\n\t\t\t\t}\n\n\t\t\t\treturn new SafeJS(\n\t\t\t\t\tjoin.lines(\n\t\t\t\t\t\tjs`case ${id}:`,\n\t\t\t\t\t\tjs`switch (${locale}?.id) {`,\n\t\t\t\t\t\t...Object.entries(localizedEnumCaseName).map(([localeId, enumName]) => {\n\t\t\t\t\t\t\treturn js`case ${localeId}: return ${enumName};`\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tjs`default:`,\n\t\t\t\t\t\tjs`if (${fallbackLocale}) return ${SafeJS.fn(functionName, value, fallbackLocale)};`,\n\t\t\t\t\t\tjs`return ${name};`,\n\t\t\t\t\t\tjs`}`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}),\n\t\t\tjs`default: return \"\";`,\n\t\t\tjs`}`,\n\t\t\tjs`}`,\n\t\t),\n\t)\n}\n", "import type { NodeID } from \"document/models/CanvasTree/index.ts\"\n\nexport const framerCmsExtension = \"framercms\"\n\nexport type BinaryAssetExtension = typeof framerCmsExtension\nexport type BinaryAssetFilename = `${NodeID}-${string}.${BinaryAssetExtension}`\n\nexport function getBinaryAssetFilename(id: NodeID, name: string, extension: BinaryAssetExtension): BinaryAssetFilename {\n\treturn `${id}-${name}.${extension}`\n}\n\nexport type BinaryAssets = Record</* filename */ BinaryAssetFilename, /* bytes */ Uint8Array<ArrayBuffer>>\n", "import { js } from \"code-generation/js/js.ts\"\nimport type { NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { BinaryAssetExtension, BinaryAssets } from \"modules/binaryAssets.ts\"\nimport { getBinaryAssetFilename } from \"modules/binaryAssets.ts\"\n\nexport class BinaryAssetCollector {\n\treadonly assets: BinaryAssets = {}\n\n\tconstructor(readonly componentSourceNodeId: NodeID) {}\n\n\t/**\n\t * Create a new binary asset from a buffer.\n\t */\n\tcreate(name: string, extension: BinaryAssetExtension, bytes: Uint8Array<ArrayBuffer>) {\n\t\tconst filename = getBinaryAssetFilename(this.componentSourceNodeId, name, extension)\n\t\tthis.assets[filename] = bytes\n\t\treturn js`new URL(${`./${filename}`}, import.meta.url).href`\n\t}\n}\n", "import type { ModuleExportIdentifierString } from \"@framerjs/shared\"\nimport { AutoBreakpointVariant, ComponentPresetsConsumer, Link, motion } from \"library/index.ts\"\nimport type { LinkProps } from \"library/modules/Link/types.ts\"\nimport { isLazyComponentType } from \"library/router/lazy.tsx\"\nimport { Fragment, createElement } from \"react\"\nimport { assert } from \"./assert.ts\"\n\ntype UnknownProps = Record<string, unknown>\n\nexport enum RichTextJsonType {\n\tFragment = 1,\n\tLink = 2,\n\tModule = 3,\n\tTag = 4,\n\tText = 5,\n}\n\nexport type RichTextJsonFragment = [\n\tRichTextJsonType.Fragment,\n\t/* children */\n\t...RichTextJsonNode[],\n]\n\nexport type RichTextJsonLink = [\n\tRichTextJsonType.Link,\n\t/* props */\n\tLinkProps,\n\t/* children */\n\t...RichTextJsonNode[],\n]\n\nexport type RichTextJsonModule = [\n\tRichTextJsonType.Module,\n\t/* identifier */\n\tModuleExportIdentifierString,\n\t/* props */\n\tUnknownProps,\n\t/* rich text prop keys */\n\tstring[],\n\t/* vector set prop keys */\n\tstring[],\n]\n\nexport type RichTextJsonTag = [\n\tRichTextJsonType.Tag,\n\t/* tag name */\n\tstring,\n\t/* props */\n\tUnknownProps | undefined,\n\t/* children */\n\t...RichTextJsonNode[],\n]\n\nexport type RichTextJsonText = [\n\tRichTextJsonType.Text,\n\t/* text content */\n\tstring,\n]\n\nexport type RichTextJsonNode =\n\t| RichTextJsonFragment\n\t| RichTextJsonLink\n\t| RichTextJsonModule\n\t| RichTextJsonTag\n\t| RichTextJsonText\n\nexport type RichTextJsonComponents = Record<ModuleExportIdentifierString, React.ComponentType<Record<string, unknown>>>\n\nexport function getRichTextJsonResolver(components: RichTextJsonComponents) {\n\tconst cache = new Map<string, React.ReactNode>()\n\n\tfunction deserializeChildren(children: RichTextJsonNode[]) {\n\t\treturn children.map(deserializeNode)\n\t}\n\n\tfunction deserializeNode(node: RichTextJsonNode): React.ReactNode {\n\t\tswitch (node[0]) {\n\t\t\tcase RichTextJsonType.Fragment: {\n\t\t\t\tconst [, ...children] = node\n\t\t\t\tconst childNodes = deserializeChildren(children)\n\t\t\t\treturn createElement(Fragment, undefined, ...childNodes)\n\t\t\t}\n\n\t\t\tcase RichTextJsonType.Link: {\n\t\t\t\tconst [, props, ...children] = node\n\t\t\t\tconst childNodes = deserializeChildren(children)\n\t\t\t\treturn createElement(Link, props, ...childNodes)\n\t\t\t}\n\n\t\t\tcase RichTextJsonType.Module: {\n\t\t\t\tconst [, identifier, props, richTextKeys, vectorSetItemKeys] = node\n\n\t\t\t\t// parts of props can be RichTextJsonNode\n\t\t\t\tfor (const key of richTextKeys) {\n\t\t\t\t\tconst value = props[key]\n\t\t\t\t\tif (!value) continue\n\t\t\t\t\tprops[key] = deserializeNode(value as RichTextJsonNode)\n\t\t\t\t}\n\n\t\t\t\tfor (const key of vectorSetItemKeys) {\n\t\t\t\t\tconst value = props[key]\n\t\t\t\t\tif (typeof value !== \"string\") continue\n\n\t\t\t\t\tconst VectorSetItem = components[value as ModuleExportIdentifierString]\n\t\t\t\t\tif (!VectorSetItem) continue\n\n\t\t\t\t\tif (isLazyComponentType(VectorSetItem)) {\n\t\t\t\t\t\tvoid VectorSetItem.preload()\n\t\t\t\t\t}\n\n\t\t\t\t\tprops[key] = VectorSetItem\n\t\t\t\t}\n\n\t\t\t\tconst Component = components[identifier]\n\t\t\t\tassert(Component, \"Module not found\")\n\n\t\t\t\tif (isLazyComponentType(Component)) {\n\t\t\t\t\tvoid Component.preload()\n\t\t\t\t}\n\n\t\t\t\treturn (\n\t\t\t\t\t<ComponentPresetsConsumer componentIdentifier={identifier}>\n\t\t\t\t\t\t{presetProps => <AutoBreakpointVariant component={Component} props={{ ...presetProps, ...props }} />}\n\t\t\t\t\t</ComponentPresetsConsumer>\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tcase RichTextJsonType.Tag: {\n\t\t\t\tconst [, tag, props, ...children] = node\n\t\t\t\tconst childNodes = deserializeChildren(children)\n\n\t\t\t\tif (tag === \"a\") {\n\t\t\t\t\treturn createElement(motion.a, props, ...childNodes)\n\t\t\t\t}\n\n\t\t\t\treturn createElement(tag, props, ...childNodes)\n\t\t\t}\n\n\t\t\tcase RichTextJsonType.Text: {\n\t\t\t\tconst [, text] = node\n\t\t\t\treturn text\n\t\t\t}\n\t\t}\n\t}\n\n\treturn (pointer: string): React.ReactNode => {\n\t\tconst cached = cache.get(pointer)\n\t\tif (cached) return cached\n\n\t\tconst json = JSON.parse(pointer)\n\t\tconst result = deserializeNode(json)\n\t\tcache.set(pointer, result)\n\t\treturn result\n\t}\n}\n", "// NOTE: We can't use the assert function from @framerjs/shared as this would\n// pull in the whole package into the generated code.\n\nexport function assert(condition: unknown, ...msg: unknown[]): asserts condition {\n\tif (condition) return\n\tthrow Error(\"Assertion Error\" + (msg.length > 0 ? \": \" + msg.join(\" \") : \"\"))\n}\n\nexport function assertNever(condition: never): never {\n\tthrow new Error(`Unexpected value: ${condition}`)\n}\n", "export default \"// src/code-generation/components/cms/bundled/getRichTextJsonResolver.tsx?bundle\\nimport { AutoBreakpointVariant, ComponentPresetsConsumer, Link, motion } from \\\"framer\\\";\\n\\n// ../../library/src/router/lazy.tsx\\nimport { forwardRef, isValidElement, useEffect } from \\\"react\\\";\\n\\n// ../../library/src/utils/utils.ts\\nvar isWindow = typeof window !== \\\"undefined\\\";\\nvar supportsRequestIdleCallback = isWindow && typeof window.requestIdleCallback === \\\"function\\\";\\n\\n// ../../library/src/router/lazy.tsx\\nvar preloadKey = \\\"preload\\\";\\nfunction isLazyComponentType(componentType) {\\n  return typeof componentType === \\\"object\\\" && componentType !== null && !isValidElement(componentType) && preloadKey in componentType;\\n}\\n\\n// src/code-generation/components/cms/bundled/getRichTextJsonResolver.tsx?bundle\\nimport { Fragment, createElement } from \\\"react\\\";\\n\\n// src/code-generation/components/cms/bundled/assert.ts\\nfunction assert(condition, ...msg) {\\n  if (condition) return;\\n  throw Error(\\\"Assertion Error\\\" + (msg.length > 0 ? \\\": \\\" + msg.join(\\\" \\\") : \\\"\\\"));\\n}\\n\\n// src/code-generation/components/cms/bundled/getRichTextJsonResolver.tsx?bundle\\nvar RichTextJsonType = /* @__PURE__ */ ((RichTextJsonType2) => {\\n  RichTextJsonType2[RichTextJsonType2[\\\"Fragment\\\"] = 1] = \\\"Fragment\\\";\\n  RichTextJsonType2[RichTextJsonType2[\\\"Link\\\"] = 2] = \\\"Link\\\";\\n  RichTextJsonType2[RichTextJsonType2[\\\"Module\\\"] = 3] = \\\"Module\\\";\\n  RichTextJsonType2[RichTextJsonType2[\\\"Tag\\\"] = 4] = \\\"Tag\\\";\\n  RichTextJsonType2[RichTextJsonType2[\\\"Text\\\"] = 5] = \\\"Text\\\";\\n  return RichTextJsonType2;\\n})(RichTextJsonType || {});\\nfunction getRichTextJsonResolver(components) {\\n  const cache = /* @__PURE__ */ new Map();\\n  function deserializeChildren(children) {\\n    return children.map(deserializeNode);\\n  }\\n  function deserializeNode(node) {\\n    switch (node[0]) {\\n      case 1 /* Fragment */: {\\n        const [, ...children] = node;\\n        const childNodes = deserializeChildren(children);\\n        return createElement(Fragment, void 0, ...childNodes);\\n      }\\n      case 2 /* Link */: {\\n        const [, props, ...children] = node;\\n        const childNodes = deserializeChildren(children);\\n        return createElement(Link, props, ...childNodes);\\n      }\\n      case 3 /* Module */: {\\n        const [, identifier, props, richTextKeys, vectorSetItemKeys] = node;\\n        for (const key of richTextKeys) {\\n          const value = props[key];\\n          if (!value) continue;\\n          props[key] = deserializeNode(value);\\n        }\\n        for (const key of vectorSetItemKeys) {\\n          const value = props[key];\\n          if (typeof value !== \\\"string\\\") continue;\\n          const VectorSetItem = components[value];\\n          if (!VectorSetItem) continue;\\n          if (isLazyComponentType(VectorSetItem)) {\\n            void VectorSetItem.preload();\\n          }\\n          props[key] = VectorSetItem;\\n        }\\n        const Component = components[identifier];\\n        assert(Component, \\\"Module not found\\\");\\n        if (isLazyComponentType(Component)) {\\n          void Component.preload();\\n        }\\n        return <ComponentPresetsConsumer componentIdentifier={identifier}>\\n\\t\\t\\t\\t\\t\\t{(presetProps) => <AutoBreakpointVariant component={Component} props={{ ...presetProps, ...props }} />}\\n\\t\\t\\t\\t\\t</ComponentPresetsConsumer>;\\n      }\\n      case 4 /* Tag */: {\\n        const [, tag, props, ...children] = node;\\n        const childNodes = deserializeChildren(children);\\n        if (tag === \\\"a\\\") {\\n          return createElement(motion.a, props, ...childNodes);\\n        }\\n        return createElement(tag, props, ...childNodes);\\n      }\\n      case 5 /* Text */: {\\n        const [, text] = node;\\n        return text;\\n      }\\n    }\\n  }\\n  return (pointer) => {\\n    const cached = cache.get(pointer);\\n    if (cached) return cached;\\n    const json = JSON.parse(pointer);\\n    const result = deserializeNode(json);\\n    cache.set(pointer, result);\\n    return result;\\n  };\\n}\\nexport {\\n  RichTextJsonType,\\n  getRichTextJsonResolver\\n};\\n\"", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport {\n\tassert,\n\ttype ModuleExportIdentifierString,\n\tisModuleExportIdentifier,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { MakeSerializable } from \"code-generation/types.ts\"\nimport type { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport type { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport type { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport type { CanvasTree, CollectionNode, ScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport {\n\ttype RichTextResolvers,\n\ttype RichTextSerializers,\n\tcompileRichTextTreeValue,\n\tgetRichTextResolversForCodeGeneration,\n} from \"document/models/CanvasTree/nodes/utils/compileRichText.tsx\"\nimport type { RichTextTreeValue } from \"document/models/richText/richTextStorage.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\nimport type { SubmoduleCollector } from \"../GeneratedSubmodule.ts\"\nimport {\n\ttype RichTextJsonComponents,\n\ttype RichTextJsonFragment,\n\ttype RichTextJsonLink,\n\ttype RichTextJsonModule,\n\ttype RichTextJsonNode,\n\ttype RichTextJsonTag,\n\ttype RichTextJsonText,\n\tRichTextJsonType,\n} from \"./bundled/getRichTextJsonResolver.tsx\"\nimport getRichTextJsonResolverSource from \"./bundled/getRichTextJsonResolver.tsx?bundle\"\n\nexport class RichTextJsonCollector {\n\tprivate readonly scopeNode: ScopeNode | null\n\n\tprivate readonly cache = new Map<string, string>()\n\tprivate readonly components: MakeSerializable<RichTextJsonComponents> = {}\n\n\tprivate readonly resolvers: RichTextResolvers\n\tprivate readonly serializers: RichTextSerializers<RichTextJsonNode> = {\n\t\tfragment: (children): RichTextJsonFragment => {\n\t\t\treturn [RichTextJsonType.Fragment, ...children]\n\t\t},\n\n\t\tlink: (props, children): RichTextJsonLink => {\n\t\t\treturn [RichTextJsonType.Link, props, ...children]\n\t\t},\n\n\t\tmodule: (identifier, props): RichTextJsonModule | undefined => {\n\t\t\tconst hasModule = this.addModuleImport(identifier)\n\t\t\tif (!hasModule) return\n\n\t\t\tconst component = this.componentLoader.reactComponentForIdentifier(identifier)\n\t\t\tassert(component, \"Component must exist for module\")\n\n\t\t\tconst richTextKeys: string[] = [] // props may contain rich text json as well\n\t\t\tconst vectorSetItemKeys: string[] = []\n\n\t\t\tfor (const key in component.properties) {\n\t\t\t\tconst control = component.properties[key]\n\t\t\t\tif (!control) continue\n\n\t\t\t\tif (control.type === ControlType.RichText) {\n\t\t\t\t\trichTextKeys.push(key)\n\t\t\t\t} else if (control.type === ControlType.VectorSetItem) {\n\t\t\t\t\tconst vectorIdentifier = props[key]\n\t\t\t\t\tif (!isString(vectorIdentifier)) continue\n\t\t\t\t\tif (!isModuleExportIdentifier(vectorIdentifier)) continue\n\n\t\t\t\t\tif (!this.addModuleImport(vectorIdentifier)) continue\n\t\t\t\t\tvectorSetItemKeys.push(key)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn [RichTextJsonType.Module, identifier, props, richTextKeys, vectorSetItemKeys]\n\t\t},\n\n\t\ttag: (tag, props, children): RichTextJsonTag => {\n\t\t\treturn [RichTextJsonType.Tag, tag, props, ...children]\n\t\t},\n\n\t\ttext: (text): RichTextJsonText => {\n\t\t\treturn [RichTextJsonType.Text, text]\n\t\t},\n\t}\n\n\treadonly resolveRichTextBinding: SafeJS\n\n\tconstructor(\n\t\tprivate readonly collectionNode: CollectionNode,\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly tree: CanvasTree,\n\t\tprivate readonly imports: ImportCollector,\n\t\tprivate readonly submodules: SubmoduleCollector,\n\t\tprivate readonly bindings: BindingCollector,\n\t\tprivate readonly declarations: FileDeclarationCollector,\n\t\tprivate readonly assets: AssetCollector,\n\t\tprivate readonly links: LinkCollector,\n\t) {\n\t\tthis.resolveRichTextBinding = this.bindings.create(\"resolveRichText\")\n\t\tthis.scopeNode = this.tree.getScopeNodeFor(this.collectionNode)\n\n\t\tthis.resolvers = getRichTextResolversForCodeGeneration(this.assets, this.links, undefined, undefined)\n\t}\n\n\tprivate addModuleImport(identifier: ModuleExportIdentifierString) {\n\t\tif (identifier in this.components) return true\n\n\t\tconst parsedIdentifier = parseModuleIdentifier(identifier)\n\t\tconst ModuleBinding = this.imports.addModuleImport(parsedIdentifier, { lazy: true })\n\t\tif (!ModuleBinding) return false\n\n\t\tthis.components[identifier] = ModuleBinding\n\t\treturn true\n\t}\n\n\tadd(value: RichTextTreeValue) {\n\t\tconst cacheKey = getCacheKey(value)\n\t\tconst cached = this.cache.get(cacheKey)\n\t\tif (cached) return cached\n\n\t\tconst json = compileRichTextTreeValue(value, this.resolvers, this.serializers, {\n\t\t\tcomponentLoader: this.componentLoader,\n\t\t\tresolveVectorSetItem: identifier => identifier,\n\t\t\ttree: this.tree,\n\t\t\tnodeId: this.collectionNode.id,\n\t\t\tscopeId: this.scopeNode?.id,\n\t\t})\n\n\t\tconst serialized = JSON.stringify(json)\n\t\tthis.cache.set(cacheKey, serialized)\n\t\treturn serialized\n\t}\n\n\tserialize() {\n\t\tconst getRichTextJsonResolverBinding = this.imports.addImport(\n\t\t\tthis.submodules.create(getRichTextJsonResolverSource).submoduleImport,\n\t\t\t{ exportSpecifier: \"getRichTextJsonResolver\" },\n\t\t)\n\n\t\tconst richTextComponentsBinding = this.declarations.dedupe(\"richTextComponents\", this.components)\n\n\t\tthis.declarations.create(\n\t\t\tjs`const ${this.resolveRichTextBinding} = ${SafeJS.fn(getRichTextJsonResolverBinding, richTextComponentsBinding)}`,\n\t\t)\n\t}\n}\n\nfunction getCacheKey(value: RichTextTreeValue): string {\n\tif (typeof value === \"string\") return `html:${value}`\n\t// Use the stored document identity as the cheap cache key. Structurally equal documents with\n\t// different node IDs can miss this cache, but values are stable per collection item during one\n\t// serialization pass.\n\treturn `document:${JSON.stringify(value)}`\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, type ModuleExportIdentifierString, ModuleType, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport { moduleImportSpecifiers } from \"code-generation/utils/ImportCollector.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\n\nexport class VectorCollector {\n\tprivate values = new Map<ModuleExportIdentifierString, number>()\n\n\tadd(identifier: ModuleExportIdentifierString) {\n\t\tconst existing = this.values.get(identifier)\n\t\tif (isNumber(existing)) return existing\n\n\t\tconst index = this.values.size\n\t\tthis.values.set(identifier, index)\n\t\treturn index\n\t}\n\n\tserialize(componentLoader: ComponentLoader, modulesStore: ModulesStore, declarations: FileDeclarationCollector) {\n\t\tconst vectorBindings: SafeJS[] = []\n\n\t\tfor (const [identifier, index] of this.values) {\n\t\t\tconst parsed = parseModuleIdentifier(identifier)\n\t\t\tconst { importSpecifier } = moduleImportSpecifiers(parsed, ModuleType.Collection, componentLoader, modulesStore)\n\t\t\tassert(importSpecifier, \"Import specifier must be defined\")\n\n\t\t\tvectorBindings[index] = js`() => import(${importSpecifier})`\n\t\t}\n\n\t\tconst vectorsBinding = declarations.dedupe(\"vectors\", vectorBindings)\n\n\t\treturn declarations.dedupe(\n\t\t\t\"resolveVectorSetItem\",\n\t\t\tjs`(pointer: number) => {${js.joinLines(\n\t\t\t\tjs`const vector = ${vectorsBinding}[pointer]`,\n\t\t\t\tjs`if (vector) return vector().then(v => v.default)`,\n\t\t\t)}}`,\n\t\t)\n\t}\n}\n", "export const BYTE_LENGTH = {\n\tUint8: 1,\n\tUint16: 2,\n\tUint32: 4,\n\tBigUint64: 8,\n\tInt8: 1,\n\tInt16: 2,\n\tInt32: 4,\n\tBigInt64: 8,\n\tFloat32: 4,\n\tFloat64: 8,\n} as const satisfies Record<string, number>\n\nexport class BufferReader {\n\tprivate offset = 0\n\n\tgetOffset() {\n\t\treturn this.offset\n\t}\n\n\tprivate readonly view: DataView<ArrayBufferLike>\n\n\tprivate readonly decoder = new TextDecoder()\n\n\tconstructor(private readonly bytes: Uint8Array) {\n\t\tthis.view = getDataView(this.bytes)\n\t}\n\n\tensureLength(requiredBytes: number) {\n\t\tconst oldLength = this.bytes.length\n\t\tif (this.offset + requiredBytes <= oldLength) return\n\n\t\tthrow new Error(\"Reading out of bounds\")\n\t}\n\n\treadUint8() {\n\t\tconst size = BYTE_LENGTH.Uint8\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getUint8(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadUint16() {\n\t\tconst size = BYTE_LENGTH.Uint16\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getUint16(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadUint32() {\n\t\tconst size = BYTE_LENGTH.Uint32\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getUint32(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadUint64() {\n\t\tconst bigint = this.readBigUint64()\n\t\treturn Number(bigint)\n\t}\n\n\treadBigUint64() {\n\t\tconst size = BYTE_LENGTH.BigUint64\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getBigUint64(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadInt8() {\n\t\tconst size = BYTE_LENGTH.Int8\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getInt8(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadInt16() {\n\t\tconst size = BYTE_LENGTH.Int16\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getInt16(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadInt32() {\n\t\tconst size = BYTE_LENGTH.Int32\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getInt32(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadInt64() {\n\t\tconst bigint = this.readBigInt64()\n\t\treturn Number(bigint)\n\t}\n\n\treadBigInt64() {\n\t\tconst size = BYTE_LENGTH.BigInt64\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getBigInt64(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadFloat32() {\n\t\tconst size = BYTE_LENGTH.Float32\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getFloat32(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadFloat64() {\n\t\tconst size = BYTE_LENGTH.Float64\n\t\tthis.ensureLength(size)\n\t\tconst value = this.view.getFloat64(this.offset)\n\t\tthis.offset += size\n\t\treturn value\n\t}\n\n\treadBytes(length: number) {\n\t\tconst start = this.offset\n\t\tconst end = start + length\n\t\tconst value = this.bytes.subarray(start, end)\n\t\tthis.offset = end\n\t\treturn value\n\t}\n\n\treadString() {\n\t\tconst length = this.readUint32()\n\t\tconst bytes = this.readBytes(length)\n\t\treturn this.decoder.decode(bytes)\n\t}\n\n\treadJson<Value>(): Value {\n\t\tconst string = this.readString()\n\t\treturn JSON.parse(string)\n\t}\n}\n\nexport function getDataView(bytes: Uint8Array) {\n\treturn new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n}\n", "import { BYTE_LENGTH, getDataView } from \"./BufferReader.ts\"\nimport { assert } from \"./assert.ts\"\n\n// The initial size of the buffer. Larger values will take up more memory, but\n// will delay the need to resize the buffer. The value is taking from the\n// buffer-writer package which is used by the pg package.\nconst INITIAL_BUFFER_SIZE = 1024\n\n// The factor by which the buffer size is increased when it need to be resized.\n// Larger values will make the buffer grow faster, but will also take up more\n// memory. Smaller values will require more resizing. The value is taking from\n// the same package as above and seems to work well in practice.\nconst GROWTH_FACTOR = 1.5\n\nconst maxUnsignedNumber = (bits: number) => 2 ** bits - 1\nconst minSignedNumber = (bits: number) => -(2 ** (bits - 1))\nconst maxSignedNumber = (bits: number) => 2 ** (bits - 1) - 1\n\nexport const MIN_VALUE = {\n\tUint8: 0,\n\tUint16: 0,\n\tUint32: 0,\n\tUint64: 0,\n\tBigUint64: 0,\n\tInt8: minSignedNumber(8),\n\tInt16: minSignedNumber(16),\n\tInt32: minSignedNumber(32),\n\tInt64: Number.MIN_SAFE_INTEGER,\n\tBigInt64: -(BigInt(2) ** BigInt(63)),\n} as const\n\nexport const MAX_VALUE = {\n\tUint8: maxUnsignedNumber(8),\n\tUint16: maxUnsignedNumber(16),\n\tUint32: maxUnsignedNumber(32),\n\tUint64: Number.MAX_SAFE_INTEGER,\n\tBigUint64: BigInt(2) ** BigInt(64) - BigInt(1),\n\tInt8: maxSignedNumber(8),\n\tInt16: maxSignedNumber(16),\n\tInt32: maxSignedNumber(32),\n\tInt64: Number.MAX_SAFE_INTEGER,\n\tBigInt64: BigInt(2) ** BigInt(63) - BigInt(1),\n} as const\n\nfunction assertRange(value: number | bigint, min: number | bigint, max: number | bigint, dataType: string) {\n\tassert(value >= min, value, \"outside lower bound for\", dataType)\n\tassert(value <= max, value, \"outside upper bound for\", dataType)\n}\n\nexport class BufferWriter {\n\tprivate offset = 0\n\n\tgetOffset() {\n\t\treturn this.offset\n\t}\n\n\tprivate bytes = new Uint8Array(INITIAL_BUFFER_SIZE)\n\tprivate view = getDataView(this.bytes)\n\n\tslice(start = 0, end = this.offset) {\n\t\treturn this.bytes.slice(start, end)\n\t}\n\n\tsubarray(start = 0, end = this.offset) {\n\t\treturn this.bytes.subarray(start, end)\n\t}\n\n\tprivate readonly encoder = new TextEncoder()\n\n\tprivate ensureLength(requiredBytes: number) {\n\t\tconst oldLength = this.bytes.length\n\t\tif (this.offset + requiredBytes <= oldLength) return\n\n\t\tconst newLength = Math.ceil(oldLength * GROWTH_FACTOR) + requiredBytes\n\t\tconst newBytes = new Uint8Array(newLength)\n\n\t\tnewBytes.set(this.bytes)\n\n\t\tthis.bytes = newBytes\n\t\tthis.view = getDataView(newBytes)\n\t}\n\n\twriteUint8(value: number) {\n\t\tassertRange(value, MIN_VALUE.Uint8, MAX_VALUE.Uint8, \"Uint8\")\n\t\tconst size = BYTE_LENGTH.Uint8\n\t\tthis.ensureLength(size)\n\t\tthis.view.setUint8(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteUint16(value: number) {\n\t\tassertRange(value, MIN_VALUE.Uint16, MAX_VALUE.Uint16, \"Uint16\")\n\t\tconst size = BYTE_LENGTH.Uint16\n\t\tthis.ensureLength(size)\n\t\tthis.view.setUint16(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteUint32(value: number) {\n\t\tassertRange(value, MIN_VALUE.Uint32, MAX_VALUE.Uint32, \"Uint32\")\n\t\tconst size = BYTE_LENGTH.Uint32\n\t\tthis.ensureLength(size)\n\t\tthis.view.setUint32(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteUint64(value: number) {\n\t\tassertRange(value, MIN_VALUE.Uint64, MAX_VALUE.Uint64, \"Uint64\")\n\t\tconst bigint = BigInt(value)\n\t\tthis.writeBigUint64(bigint)\n\t}\n\n\twriteBigUint64(value: bigint) {\n\t\tassertRange(value, MIN_VALUE.BigUint64, MAX_VALUE.BigUint64, \"BigUint64\")\n\t\tconst size = BYTE_LENGTH.BigUint64\n\t\tthis.ensureLength(size)\n\t\tthis.view.setBigUint64(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteInt8(value: number) {\n\t\tassertRange(value, MIN_VALUE.Int8, MAX_VALUE.Int8, \"Int8\")\n\t\tconst size = BYTE_LENGTH.Int8\n\t\tthis.ensureLength(size)\n\t\tthis.view.setInt8(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteInt16(value: number) {\n\t\tassertRange(value, MIN_VALUE.Int16, MAX_VALUE.Int16, \"Int16\")\n\t\tconst size = BYTE_LENGTH.Int16\n\t\tthis.ensureLength(size)\n\t\tthis.view.setInt16(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteInt32(value: number) {\n\t\tassertRange(value, MIN_VALUE.Int32, MAX_VALUE.Int32, \"Int32\")\n\t\tconst size = BYTE_LENGTH.Int32\n\t\tthis.ensureLength(size)\n\t\tthis.view.setInt32(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteInt64(value: number) {\n\t\tassertRange(value, MIN_VALUE.Int64, MAX_VALUE.Int64, \"Int64\")\n\t\tconst bigint = BigInt(value)\n\t\tthis.writeBigInt64(bigint)\n\t}\n\n\twriteBigInt64(value: bigint) {\n\t\tassertRange(value, MIN_VALUE.BigInt64, MAX_VALUE.BigInt64, \"BigInt64\")\n\t\tconst size = BYTE_LENGTH.BigInt64\n\t\tthis.ensureLength(size)\n\t\tthis.view.setBigInt64(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteFloat32(value: number) {\n\t\tconst size = BYTE_LENGTH.Float32\n\t\tthis.ensureLength(size)\n\t\tthis.view.setFloat32(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteFloat64(value: number) {\n\t\tconst size = BYTE_LENGTH.Float64\n\t\tthis.ensureLength(size)\n\t\tthis.view.setFloat64(this.offset, value)\n\t\tthis.offset += size\n\t}\n\n\twriteBytes(value: Uint8Array) {\n\t\tconst size = value.length\n\t\tthis.ensureLength(size)\n\t\tthis.bytes.set(value, this.offset)\n\t\tthis.offset += size\n\t}\n\n\tprivate encodedStrings = new Map<string, Uint8Array>()\n\n\tprivate encodeString(value: string) {\n\t\t// Text encoding can be quite expensive, so we cache the encoded\n\t\t// strings. This is especially useful for strings that are repeated a\n\t\t// lot (e.g. enum values, field names).\n\t\tconst cached = this.encodedStrings.get(value)\n\t\tif (cached) return cached\n\n\t\tconst bytes = this.encoder.encode(value)\n\t\tthis.encodedStrings.set(value, bytes)\n\t\treturn bytes\n\t}\n\n\twriteString(value: string) {\n\t\tconst bytes = this.encodeString(value)\n\t\tconst size = bytes.length\n\t\tthis.writeUint32(size)\n\t\tthis.writeBytes(bytes)\n\t}\n\n\twriteJson<Value>(value: Value) {\n\t\tconst json = JSON.stringify(value)\n\t\tthis.writeString(json)\n\t}\n}\n", "export default \"var __create = Object.create;\\nvar __defProp = Object.defineProperty;\\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\\nvar __getOwnPropNames = Object.getOwnPropertyNames;\\nvar __getProtoOf = Object.getPrototypeOf;\\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\\nvar __commonJS = (cb, mod) => function __require() {\\n  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\\n};\\nvar __copyProps = (to, from, except, desc) => {\\n  if (from && typeof from === \\\"object\\\" || typeof from === \\\"function\\\") {\\n    for (let key of __getOwnPropNames(from))\\n      if (!__hasOwnProp.call(to, key) && key !== except)\\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\\n  }\\n  return to;\\n};\\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\\n  // If the importer is in node compatibility mode or this is not an ESM\\n  // file that has been converted to a CommonJS file using a Babel-\\n  // compatible transform (i.e. \\\"__esModule\\\" has not been set), then set\\n  // \\\"default\\\" to the CommonJS \\\"module.exports\\\" for node compatibility.\\n  isNodeMode || !mod || !mod.__esModule ? __defProp(target, \\\"default\\\", { value: mod, enumerable: true }) : target,\\n  mod\\n));\\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \\\"symbol\\\" ? key + \\\"\\\" : key, value);\\n\\n// ../../../node_modules/dataloader/index.js\\nvar require_dataloader = __commonJS({\\n  \\\"../../../node_modules/dataloader/index.js\\\"(exports, module) {\\n    \\\"use strict\\\";\\n    var DataLoader2 = /* @__PURE__ */ function() {\\n      function DataLoader3(batchLoadFn, options) {\\n        if (typeof batchLoadFn !== \\\"function\\\") {\\n          throw new TypeError(\\\"DataLoader must be constructed with a function which accepts \\\" + (\\\"Array<key> and returns Promise<Array<value>>, but got: \\\" + batchLoadFn + \\\".\\\"));\\n        }\\n        this._batchLoadFn = batchLoadFn;\\n        this._maxBatchSize = getValidMaxBatchSize(options);\\n        this._batchScheduleFn = getValidBatchScheduleFn(options);\\n        this._cacheKeyFn = getValidCacheKeyFn(options);\\n        this._cacheMap = getValidCacheMap(options);\\n        this._batch = null;\\n        this.name = getValidName(options);\\n      }\\n      var _proto = DataLoader3.prototype;\\n      _proto.load = function load(key) {\\n        if (key === null || key === void 0) {\\n          throw new TypeError(\\\"The loader.load() function must be called with a value, \\\" + (\\\"but got: \\\" + String(key) + \\\".\\\"));\\n        }\\n        var batch = getCurrentBatch(this);\\n        var cacheMap = this._cacheMap;\\n        var cacheKey = this._cacheKeyFn(key);\\n        if (cacheMap) {\\n          var cachedPromise = cacheMap.get(cacheKey);\\n          if (cachedPromise) {\\n            var cacheHits = batch.cacheHits || (batch.cacheHits = []);\\n            return new Promise(function(resolve) {\\n              cacheHits.push(function() {\\n                resolve(cachedPromise);\\n              });\\n            });\\n          }\\n        }\\n        batch.keys.push(key);\\n        var promise = new Promise(function(resolve, reject) {\\n          batch.callbacks.push({\\n            resolve,\\n            reject\\n          });\\n        });\\n        if (cacheMap) {\\n          cacheMap.set(cacheKey, promise);\\n        }\\n        return promise;\\n      };\\n      _proto.loadMany = function loadMany(keys) {\\n        if (!isArrayLike(keys)) {\\n          throw new TypeError(\\\"The loader.loadMany() function must be called with Array<key> \\\" + (\\\"but got: \\\" + keys + \\\".\\\"));\\n        }\\n        var loadPromises = [];\\n        for (var i = 0; i < keys.length; i++) {\\n          loadPromises.push(this.load(keys[i])[\\\"catch\\\"](function(error) {\\n            return error;\\n          }));\\n        }\\n        return Promise.all(loadPromises);\\n      };\\n      _proto.clear = function clear(key) {\\n        var cacheMap = this._cacheMap;\\n        if (cacheMap) {\\n          var cacheKey = this._cacheKeyFn(key);\\n          cacheMap[\\\"delete\\\"](cacheKey);\\n        }\\n        return this;\\n      };\\n      _proto.clearAll = function clearAll() {\\n        var cacheMap = this._cacheMap;\\n        if (cacheMap) {\\n          cacheMap.clear();\\n        }\\n        return this;\\n      };\\n      _proto.prime = function prime(key, value) {\\n        var cacheMap = this._cacheMap;\\n        if (cacheMap) {\\n          var cacheKey = this._cacheKeyFn(key);\\n          if (cacheMap.get(cacheKey) === void 0) {\\n            var promise;\\n            if (value instanceof Error) {\\n              promise = Promise.reject(value);\\n              promise[\\\"catch\\\"](function() {\\n              });\\n            } else {\\n              promise = Promise.resolve(value);\\n            }\\n            cacheMap.set(cacheKey, promise);\\n          }\\n        }\\n        return this;\\n      };\\n      return DataLoader3;\\n    }();\\n    var enqueuePostPromiseJob = typeof process === \\\"object\\\" && typeof process.nextTick === \\\"function\\\" ? function(fn) {\\n      if (!resolvedPromise) {\\n        resolvedPromise = Promise.resolve();\\n      }\\n      resolvedPromise.then(function() {\\n        process.nextTick(fn);\\n      });\\n    } : typeof setImmediate === \\\"function\\\" ? function(fn) {\\n      setImmediate(fn);\\n    } : function(fn) {\\n      setTimeout(fn);\\n    };\\n    var resolvedPromise;\\n    function getCurrentBatch(loader) {\\n      var existingBatch = loader._batch;\\n      if (existingBatch !== null && !existingBatch.hasDispatched && existingBatch.keys.length < loader._maxBatchSize) {\\n        return existingBatch;\\n      }\\n      var newBatch = {\\n        hasDispatched: false,\\n        keys: [],\\n        callbacks: []\\n      };\\n      loader._batch = newBatch;\\n      loader._batchScheduleFn(function() {\\n        dispatchBatch(loader, newBatch);\\n      });\\n      return newBatch;\\n    }\\n    function dispatchBatch(loader, batch) {\\n      batch.hasDispatched = true;\\n      if (batch.keys.length === 0) {\\n        resolveCacheHits(batch);\\n        return;\\n      }\\n      var batchPromise;\\n      try {\\n        batchPromise = loader._batchLoadFn(batch.keys);\\n      } catch (e) {\\n        return failedDispatch(loader, batch, new TypeError(\\\"DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function \\\" + (\\\"errored synchronously: \\\" + String(e) + \\\".\\\")));\\n      }\\n      if (!batchPromise || typeof batchPromise.then !== \\\"function\\\") {\\n        return failedDispatch(loader, batch, new TypeError(\\\"DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did \\\" + (\\\"not return a Promise: \\\" + String(batchPromise) + \\\".\\\")));\\n      }\\n      batchPromise.then(function(values) {\\n        if (!isArrayLike(values)) {\\n          throw new TypeError(\\\"DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did \\\" + (\\\"not return a Promise of an Array: \\\" + String(values) + \\\".\\\"));\\n        }\\n        if (values.length !== batch.keys.length) {\\n          throw new TypeError(\\\"DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.\\\" + (\\\"\\\\n\\\\nKeys:\\\\n\\\" + String(batch.keys)) + (\\\"\\\\n\\\\nValues:\\\\n\\\" + String(values)));\\n        }\\n        resolveCacheHits(batch);\\n        for (var i = 0; i < batch.callbacks.length; i++) {\\n          var value = values[i];\\n          if (value instanceof Error) {\\n            batch.callbacks[i].reject(value);\\n          } else {\\n            batch.callbacks[i].resolve(value);\\n          }\\n        }\\n      })[\\\"catch\\\"](function(error) {\\n        failedDispatch(loader, batch, error);\\n      });\\n    }\\n    function failedDispatch(loader, batch, error) {\\n      resolveCacheHits(batch);\\n      for (var i = 0; i < batch.keys.length; i++) {\\n        loader.clear(batch.keys[i]);\\n        batch.callbacks[i].reject(error);\\n      }\\n    }\\n    function resolveCacheHits(batch) {\\n      if (batch.cacheHits) {\\n        for (var i = 0; i < batch.cacheHits.length; i++) {\\n          batch.cacheHits[i]();\\n        }\\n      }\\n    }\\n    function getValidMaxBatchSize(options) {\\n      var shouldBatch = !options || options.batch !== false;\\n      if (!shouldBatch) {\\n        return 1;\\n      }\\n      var maxBatchSize = options && options.maxBatchSize;\\n      if (maxBatchSize === void 0) {\\n        return Infinity;\\n      }\\n      if (typeof maxBatchSize !== \\\"number\\\" || maxBatchSize < 1) {\\n        throw new TypeError(\\\"maxBatchSize must be a positive number: \\\" + maxBatchSize);\\n      }\\n      return maxBatchSize;\\n    }\\n    function getValidBatchScheduleFn(options) {\\n      var batchScheduleFn = options && options.batchScheduleFn;\\n      if (batchScheduleFn === void 0) {\\n        return enqueuePostPromiseJob;\\n      }\\n      if (typeof batchScheduleFn !== \\\"function\\\") {\\n        throw new TypeError(\\\"batchScheduleFn must be a function: \\\" + batchScheduleFn);\\n      }\\n      return batchScheduleFn;\\n    }\\n    function getValidCacheKeyFn(options) {\\n      var cacheKeyFn = options && options.cacheKeyFn;\\n      if (cacheKeyFn === void 0) {\\n        return function(key) {\\n          return key;\\n        };\\n      }\\n      if (typeof cacheKeyFn !== \\\"function\\\") {\\n        throw new TypeError(\\\"cacheKeyFn must be a function: \\\" + cacheKeyFn);\\n      }\\n      return cacheKeyFn;\\n    }\\n    function getValidCacheMap(options) {\\n      var shouldCache = !options || options.cache !== false;\\n      if (!shouldCache) {\\n        return null;\\n      }\\n      var cacheMap = options && options.cacheMap;\\n      if (cacheMap === void 0) {\\n        return /* @__PURE__ */ new Map();\\n      }\\n      if (cacheMap !== null) {\\n        var cacheFunctions = [\\\"get\\\", \\\"set\\\", \\\"delete\\\", \\\"clear\\\"];\\n        var missingFunctions = cacheFunctions.filter(function(fnName) {\\n          return cacheMap && typeof cacheMap[fnName] !== \\\"function\\\";\\n        });\\n        if (missingFunctions.length !== 0) {\\n          throw new TypeError(\\\"Custom cacheMap missing methods: \\\" + missingFunctions.join(\\\", \\\"));\\n        }\\n      }\\n      return cacheMap;\\n    }\\n    function getValidName(options) {\\n      if (options && options.name) {\\n        return options.name;\\n      }\\n      return null;\\n    }\\n    function isArrayLike(x) {\\n      return typeof x === \\\"object\\\" && x !== null && typeof x.length === \\\"number\\\" && (x.length === 0 || x.length > 0 && Object.prototype.hasOwnProperty.call(x, x.length - 1));\\n    }\\n    module.exports = DataLoader2;\\n  }\\n});\\n\\n// src/code-generation/components/cms/bundled/DatabaseCollection.ts?bundle\\nvar import_dataloader = __toESM(require_dataloader(), 1);\\n\\n// src/code-generation/components/cms/bundled/BufferReader.ts\\nvar BYTE_LENGTH = {\\n  Uint8: 1,\\n  Uint16: 2,\\n  Uint32: 4,\\n  BigUint64: 8,\\n  Int8: 1,\\n  Int16: 2,\\n  Int32: 4,\\n  BigInt64: 8,\\n  Float32: 4,\\n  Float64: 8\\n};\\nvar BufferReader = class {\\n  constructor(bytes) {\\n    this.bytes = bytes;\\n    __publicField(this, \\\"offset\\\", 0);\\n    __publicField(this, \\\"view\\\");\\n    __publicField(this, \\\"decoder\\\", new TextDecoder());\\n    this.view = getDataView(this.bytes);\\n  }\\n  getOffset() {\\n    return this.offset;\\n  }\\n  ensureLength(requiredBytes) {\\n    const oldLength = this.bytes.length;\\n    if (this.offset + requiredBytes <= oldLength) return;\\n    throw new Error(\\\"Reading out of bounds\\\");\\n  }\\n  readUint8() {\\n    const size = BYTE_LENGTH.Uint8;\\n    this.ensureLength(size);\\n    const value = this.view.getUint8(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readUint16() {\\n    const size = BYTE_LENGTH.Uint16;\\n    this.ensureLength(size);\\n    const value = this.view.getUint16(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readUint32() {\\n    const size = BYTE_LENGTH.Uint32;\\n    this.ensureLength(size);\\n    const value = this.view.getUint32(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readUint64() {\\n    const bigint = this.readBigUint64();\\n    return Number(bigint);\\n  }\\n  readBigUint64() {\\n    const size = BYTE_LENGTH.BigUint64;\\n    this.ensureLength(size);\\n    const value = this.view.getBigUint64(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readInt8() {\\n    const size = BYTE_LENGTH.Int8;\\n    this.ensureLength(size);\\n    const value = this.view.getInt8(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readInt16() {\\n    const size = BYTE_LENGTH.Int16;\\n    this.ensureLength(size);\\n    const value = this.view.getInt16(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readInt32() {\\n    const size = BYTE_LENGTH.Int32;\\n    this.ensureLength(size);\\n    const value = this.view.getInt32(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readInt64() {\\n    const bigint = this.readBigInt64();\\n    return Number(bigint);\\n  }\\n  readBigInt64() {\\n    const size = BYTE_LENGTH.BigInt64;\\n    this.ensureLength(size);\\n    const value = this.view.getBigInt64(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readFloat32() {\\n    const size = BYTE_LENGTH.Float32;\\n    this.ensureLength(size);\\n    const value = this.view.getFloat32(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readFloat64() {\\n    const size = BYTE_LENGTH.Float64;\\n    this.ensureLength(size);\\n    const value = this.view.getFloat64(this.offset);\\n    this.offset += size;\\n    return value;\\n  }\\n  readBytes(length) {\\n    const start = this.offset;\\n    const end = start + length;\\n    const value = this.bytes.subarray(start, end);\\n    this.offset = end;\\n    return value;\\n  }\\n  readString() {\\n    const length = this.readUint32();\\n    const bytes = this.readBytes(length);\\n    return this.decoder.decode(bytes);\\n  }\\n  readJson() {\\n    const string = this.readString();\\n    return JSON.parse(string);\\n  }\\n};\\nfunction getDataView(bytes) {\\n  return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\\n}\\n\\n// src/code-generation/components/cms/bundled/DatabaseDictionaryIndex.ts\\nimport { ControlType as ControlType2 } from \\\"framer\\\";\\n\\n// ../../library/src/utils/utils.ts\\nvar isWindow = typeof window !== \\\"undefined\\\";\\nvar supportsRequestIdleCallback = isWindow && typeof window.requestIdleCallback === \\\"function\\\";\\n\\n// src/code-generation/components/cms/bundled/assert.ts\\nfunction assert(condition, ...msg) {\\n  if (condition) return;\\n  throw Error(\\\"Assertion Error\\\" + (msg.length > 0 ? \\\": \\\" + msg.join(\\\" \\\") : \\\"\\\"));\\n}\\nfunction assertNever(condition) {\\n  throw new Error(`Unexpected value: ${condition}`);\\n}\\n\\n// src/code-generation/components/cms/bundled/BufferWriter.ts\\nvar INITIAL_BUFFER_SIZE = 1024;\\nvar GROWTH_FACTOR = 1.5;\\nvar maxUnsignedNumber = (bits) => 2 ** bits - 1;\\nvar minSignedNumber = (bits) => -(2 ** (bits - 1));\\nvar maxSignedNumber = (bits) => 2 ** (bits - 1) - 1;\\nvar MIN_VALUE = {\\n  Uint8: 0,\\n  Uint16: 0,\\n  Uint32: 0,\\n  Uint64: 0,\\n  BigUint64: 0,\\n  Int8: minSignedNumber(8),\\n  Int16: minSignedNumber(16),\\n  Int32: minSignedNumber(32),\\n  Int64: Number.MIN_SAFE_INTEGER,\\n  BigInt64: -(BigInt(2) ** BigInt(63))\\n};\\nvar MAX_VALUE = {\\n  Uint8: maxUnsignedNumber(8),\\n  Uint16: maxUnsignedNumber(16),\\n  Uint32: maxUnsignedNumber(32),\\n  Uint64: Number.MAX_SAFE_INTEGER,\\n  BigUint64: BigInt(2) ** BigInt(64) - BigInt(1),\\n  Int8: maxSignedNumber(8),\\n  Int16: maxSignedNumber(16),\\n  Int32: maxSignedNumber(32),\\n  Int64: Number.MAX_SAFE_INTEGER,\\n  BigInt64: BigInt(2) ** BigInt(63) - BigInt(1)\\n};\\nfunction assertRange(value, min, max, dataType) {\\n  assert(value >= min, value, \\\"outside lower bound for\\\", dataType);\\n  assert(value <= max, value, \\\"outside upper bound for\\\", dataType);\\n}\\nvar BufferWriter = class {\\n  constructor() {\\n    __publicField(this, \\\"offset\\\", 0);\\n    __publicField(this, \\\"bytes\\\", new Uint8Array(INITIAL_BUFFER_SIZE));\\n    __publicField(this, \\\"view\\\", getDataView(this.bytes));\\n    __publicField(this, \\\"encoder\\\", new TextEncoder());\\n    __publicField(this, \\\"encodedStrings\\\", /* @__PURE__ */ new Map());\\n  }\\n  getOffset() {\\n    return this.offset;\\n  }\\n  slice(start = 0, end = this.offset) {\\n    return this.bytes.slice(start, end);\\n  }\\n  subarray(start = 0, end = this.offset) {\\n    return this.bytes.subarray(start, end);\\n  }\\n  ensureLength(requiredBytes) {\\n    const oldLength = this.bytes.length;\\n    if (this.offset + requiredBytes <= oldLength) return;\\n    const newLength = Math.ceil(oldLength * GROWTH_FACTOR) + requiredBytes;\\n    const newBytes = new Uint8Array(newLength);\\n    newBytes.set(this.bytes);\\n    this.bytes = newBytes;\\n    this.view = getDataView(newBytes);\\n  }\\n  writeUint8(value) {\\n    assertRange(value, MIN_VALUE.Uint8, MAX_VALUE.Uint8, \\\"Uint8\\\");\\n    const size = BYTE_LENGTH.Uint8;\\n    this.ensureLength(size);\\n    this.view.setUint8(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeUint16(value) {\\n    assertRange(value, MIN_VALUE.Uint16, MAX_VALUE.Uint16, \\\"Uint16\\\");\\n    const size = BYTE_LENGTH.Uint16;\\n    this.ensureLength(size);\\n    this.view.setUint16(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeUint32(value) {\\n    assertRange(value, MIN_VALUE.Uint32, MAX_VALUE.Uint32, \\\"Uint32\\\");\\n    const size = BYTE_LENGTH.Uint32;\\n    this.ensureLength(size);\\n    this.view.setUint32(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeUint64(value) {\\n    assertRange(value, MIN_VALUE.Uint64, MAX_VALUE.Uint64, \\\"Uint64\\\");\\n    const bigint = BigInt(value);\\n    this.writeBigUint64(bigint);\\n  }\\n  writeBigUint64(value) {\\n    assertRange(value, MIN_VALUE.BigUint64, MAX_VALUE.BigUint64, \\\"BigUint64\\\");\\n    const size = BYTE_LENGTH.BigUint64;\\n    this.ensureLength(size);\\n    this.view.setBigUint64(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeInt8(value) {\\n    assertRange(value, MIN_VALUE.Int8, MAX_VALUE.Int8, \\\"Int8\\\");\\n    const size = BYTE_LENGTH.Int8;\\n    this.ensureLength(size);\\n    this.view.setInt8(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeInt16(value) {\\n    assertRange(value, MIN_VALUE.Int16, MAX_VALUE.Int16, \\\"Int16\\\");\\n    const size = BYTE_LENGTH.Int16;\\n    this.ensureLength(size);\\n    this.view.setInt16(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeInt32(value) {\\n    assertRange(value, MIN_VALUE.Int32, MAX_VALUE.Int32, \\\"Int32\\\");\\n    const size = BYTE_LENGTH.Int32;\\n    this.ensureLength(size);\\n    this.view.setInt32(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeInt64(value) {\\n    assertRange(value, MIN_VALUE.Int64, MAX_VALUE.Int64, \\\"Int64\\\");\\n    const bigint = BigInt(value);\\n    this.writeBigInt64(bigint);\\n  }\\n  writeBigInt64(value) {\\n    assertRange(value, MIN_VALUE.BigInt64, MAX_VALUE.BigInt64, \\\"BigInt64\\\");\\n    const size = BYTE_LENGTH.BigInt64;\\n    this.ensureLength(size);\\n    this.view.setBigInt64(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeFloat32(value) {\\n    const size = BYTE_LENGTH.Float32;\\n    this.ensureLength(size);\\n    this.view.setFloat32(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeFloat64(value) {\\n    const size = BYTE_LENGTH.Float64;\\n    this.ensureLength(size);\\n    this.view.setFloat64(this.offset, value);\\n    this.offset += size;\\n  }\\n  writeBytes(value) {\\n    const size = value.length;\\n    this.ensureLength(size);\\n    this.bytes.set(value, this.offset);\\n    this.offset += size;\\n  }\\n  encodeString(value) {\\n    const cached = this.encodedStrings.get(value);\\n    if (cached) return cached;\\n    const bytes = this.encoder.encode(value);\\n    this.encodedStrings.set(value, bytes);\\n    return bytes;\\n  }\\n  writeString(value) {\\n    const bytes = this.encodeString(value);\\n    const size = bytes.length;\\n    this.writeUint32(size);\\n    this.writeBytes(bytes);\\n  }\\n  writeJson(value) {\\n    const json = JSON.stringify(value);\\n    this.writeString(json);\\n  }\\n};\\n\\n// src/utils/typeChecks.ts\\nfunction isString(value) {\\n  return typeof value === \\\"string\\\";\\n}\\nfunction isNumber(value) {\\n  return Number.isFinite(value);\\n}\\nfunction isNull(value) {\\n  return value === null;\\n}\\n\\n// src/code-generation/components/cms/bundled/models/DatabaseItemPointerModel.ts\\nvar DatabaseItemPointerModel = class _DatabaseItemPointerModel {\\n  constructor(chunkId, offset, length) {\\n    this.chunkId = chunkId;\\n    this.offset = offset;\\n    this.length = length;\\n  }\\n  static fromString(value) {\\n    const [chunkId, offset, length] = value.split(\\\"/\\\").map(Number);\\n    assert(isNumber(chunkId), \\\"Invalid chunkId\\\");\\n    assert(isNumber(offset), \\\"Invalid offset\\\");\\n    assert(isNumber(length), \\\"Invalid length\\\");\\n    return new _DatabaseItemPointerModel(chunkId, offset, length);\\n  }\\n  toString() {\\n    return `${this.chunkId}/${this.offset}/${this.length}`;\\n  }\\n  static read(reader) {\\n    const chunkId = reader.readUint16();\\n    const offset = reader.readUint32();\\n    const length = reader.readUint32();\\n    return new _DatabaseItemPointerModel(chunkId, offset, length);\\n  }\\n  write(writer) {\\n    writer.writeUint16(this.chunkId);\\n    writer.writeUint32(this.offset);\\n    writer.writeUint32(this.length);\\n  }\\n  compare(other) {\\n    if (this.chunkId < other.chunkId) return -1;\\n    if (this.chunkId > other.chunkId) return 1;\\n    if (this.offset < other.offset) return -1;\\n    if (this.offset > other.offset) return 1;\\n    assert(this.length === other.length);\\n    return 0;\\n  }\\n};\\n\\n// src/code-generation/components/cms/bundled/models/DatabaseValueModel.ts\\nimport { ControlType } from \\\"framer\\\";\\nfunction getValueType(value) {\\n  if (isNull(value)) {\\n    return 0 /* Null */;\\n  }\\n  switch (value.type) {\\n    case ControlType.Array:\\n      return 1 /* Array */;\\n    case ControlType.Boolean:\\n      return 2 /* Boolean */;\\n    case ControlType.Color:\\n      return 3 /* Color */;\\n    case ControlType.Date:\\n      return 4 /* Date */;\\n    case ControlType.Enum:\\n      return 5 /* Enum */;\\n    case ControlType.File:\\n      return 6 /* File */;\\n    case ControlType.ResponsiveImage:\\n      return 10 /* ResponsiveImage */;\\n    case ControlType.Link:\\n      return 7 /* Link */;\\n    case ControlType.Number:\\n      return 8 /* Number */;\\n    case ControlType.Object:\\n      return 9 /* Object */;\\n    case ControlType.RichText:\\n      return 11 /* RichText */;\\n    case ControlType.String:\\n      return 12 /* String */;\\n    case ControlType.VectorSetItem:\\n      return 13 /* VectorSetItem */;\\n    default:\\n      assertNever(value);\\n  }\\n}\\nvar DatabaseValueModel;\\n((DatabaseValueModel2) => {\\n  function read(reader) {\\n    const type = reader.readUint8();\\n    switch (type) {\\n      case 0 /* Null */:\\n        return null;\\n      case 1 /* Array */:\\n        return readArray(reader);\\n      case 2 /* Boolean */:\\n        return readBoolean(reader);\\n      case 3 /* Color */:\\n        return readColor(reader);\\n      case 4 /* Date */:\\n        return readDate(reader);\\n      case 5 /* Enum */:\\n        return readEnum(reader);\\n      case 6 /* File */:\\n        return readFile(reader);\\n      case 7 /* Link */:\\n        return readLink(reader);\\n      case 8 /* Number */:\\n        return readNumber(reader);\\n      case 9 /* Object */:\\n        return readObject(reader);\\n      case 10 /* ResponsiveImage */:\\n        return readResponsiveImage(reader);\\n      case 11 /* RichText */:\\n        return readRichText(reader);\\n      case 12 /* String */:\\n        return readString(reader);\\n      case 13 /* VectorSetItem */:\\n        return readVectorSetItem(reader);\\n      default:\\n        assertNever(type);\\n    }\\n  }\\n  DatabaseValueModel2.read = read;\\n  function write(writer, value) {\\n    const type = getValueType(value);\\n    writer.writeUint8(type);\\n    if (isNull(value)) return;\\n    switch (value.type) {\\n      case ControlType.Array:\\n        return writeArray(writer, value);\\n      case ControlType.Boolean:\\n        return writeBoolean(writer, value);\\n      case ControlType.Color:\\n        return writeColor(writer, value);\\n      case ControlType.Date:\\n        return writeDate(writer, value);\\n      case ControlType.Enum:\\n        return writeEnum(writer, value);\\n      case ControlType.File:\\n        return writeFile(writer, value);\\n      case ControlType.Link:\\n        return writeLink(writer, value);\\n      case ControlType.Number:\\n        return writeNumber(writer, value);\\n      case ControlType.Object:\\n        return writeObject(writer, value);\\n      case ControlType.ResponsiveImage:\\n        return writeResponsiveImage(writer, value);\\n      case ControlType.RichText:\\n        return writeRichText(writer, value);\\n      case ControlType.VectorSetItem:\\n        return writeVectorSetItem(writer, value);\\n      case ControlType.String:\\n        return writeString(writer, value);\\n      default:\\n        assertNever(value);\\n    }\\n  }\\n  DatabaseValueModel2.write = write;\\n  function compare(left, right, collation) {\\n    const leftType = getValueType(left);\\n    const rightType = getValueType(right);\\n    if (leftType < rightType) return -1;\\n    if (leftType > rightType) return 1;\\n    if (isNull(left) || isNull(right)) return 0;\\n    switch (left.type) {\\n      case ControlType.Array:\\n        assert(right.type === ControlType.Array);\\n        return compareArray(left, right, collation);\\n      case ControlType.Boolean:\\n        assert(right.type === ControlType.Boolean);\\n        return compareBoolean(left, right);\\n      case ControlType.Color:\\n        assert(right.type === ControlType.Color);\\n        return compareColor(left, right);\\n      case ControlType.Date:\\n        assert(right.type === ControlType.Date);\\n        return compareDate(left, right);\\n      case ControlType.Enum:\\n        assert(right.type === ControlType.Enum);\\n        return compareEnum(left, right);\\n      case ControlType.File:\\n        assert(right.type === ControlType.File);\\n        return compareFile(left, right);\\n      case ControlType.Link:\\n        assert(right.type === ControlType.Link);\\n        return compareLink(left, right);\\n      case ControlType.Number:\\n        assert(right.type === ControlType.Number);\\n        return compareNumber(left, right);\\n      case ControlType.Object:\\n        assert(right.type === ControlType.Object);\\n        return compareObject(left, right, collation);\\n      case ControlType.ResponsiveImage:\\n        assert(right.type === ControlType.ResponsiveImage);\\n        return compareResponsiveImage(left, right);\\n      case ControlType.RichText:\\n        assert(right.type === ControlType.RichText);\\n        return compareRichText(left, right);\\n      case ControlType.VectorSetItem:\\n        assert(right.type === ControlType.VectorSetItem);\\n        return compareVectorSetItem(left, right);\\n      case ControlType.String:\\n        assert(right.type === ControlType.String);\\n        return compareString(left, right, collation);\\n      default:\\n        assertNever(left);\\n    }\\n  }\\n  DatabaseValueModel2.compare = compare;\\n})(DatabaseValueModel || (DatabaseValueModel = {}));\\nfunction readArray(reader) {\\n  const length = reader.readUint16();\\n  const value = [];\\n  for (let i = 0; i < length; i++) {\\n    const item = DatabaseValueModel.read(reader);\\n    value.push(item);\\n  }\\n  return {\\n    type: ControlType.Array,\\n    value\\n  };\\n}\\nfunction writeArray(writer, value) {\\n  writer.writeUint16(value.value.length);\\n  for (const item of value.value) {\\n    DatabaseValueModel.write(writer, item);\\n  }\\n}\\nfunction compareArray(left, right, collation) {\\n  const leftLength = left.value.length;\\n  const rightLength = right.value.length;\\n  if (leftLength < rightLength) return -1;\\n  if (leftLength > rightLength) return 1;\\n  for (let i = 0; i < leftLength; i++) {\\n    const leftItem = left.value[i];\\n    const rightItem = right.value[i];\\n    const result = DatabaseValueModel.compare(leftItem, rightItem, collation);\\n    if (result !== 0) return result;\\n  }\\n  return 0;\\n}\\nfunction readBoolean(reader) {\\n  return {\\n    type: ControlType.Boolean,\\n    value: reader.readUint8() !== 0\\n  };\\n}\\nfunction writeBoolean(writer, value) {\\n  writer.writeUint8(value.value ? 1 : 0);\\n}\\nfunction compareBoolean(left, right) {\\n  if (left.value < right.value) return -1;\\n  if (left.value > right.value) return 1;\\n  return 0;\\n}\\nfunction readColor(reader) {\\n  return {\\n    type: ControlType.Color,\\n    value: reader.readString()\\n  };\\n}\\nfunction writeColor(writer, value) {\\n  writer.writeString(value.value);\\n}\\nfunction compareColor(left, right) {\\n  if (left.value < right.value) return -1;\\n  if (left.value > right.value) return 1;\\n  return 0;\\n}\\nfunction readDate(reader) {\\n  const timestamp = reader.readInt64();\\n  const date = new Date(timestamp);\\n  return {\\n    type: ControlType.Date,\\n    value: date.toISOString()\\n  };\\n}\\nfunction writeDate(writer, value) {\\n  const date = new Date(value.value);\\n  const timestamp = date.getTime();\\n  writer.writeInt64(timestamp);\\n}\\nfunction compareDate(left, right) {\\n  const leftDate = new Date(left.value);\\n  const rightDate = new Date(right.value);\\n  if (leftDate < rightDate) return -1;\\n  if (leftDate > rightDate) return 1;\\n  return 0;\\n}\\nfunction readEnum(reader) {\\n  return {\\n    type: ControlType.Enum,\\n    value: reader.readString()\\n  };\\n}\\nfunction writeEnum(writer, value) {\\n  writer.writeString(value.value);\\n}\\nfunction compareEnum(left, right) {\\n  if (left.value < right.value) return -1;\\n  if (left.value > right.value) return 1;\\n  return 0;\\n}\\nfunction readFile(reader) {\\n  return {\\n    type: ControlType.File,\\n    value: reader.readString()\\n  };\\n}\\nfunction writeFile(writer, value) {\\n  writer.writeString(value.value);\\n}\\nfunction compareFile(left, right) {\\n  if (left.value < right.value) return -1;\\n  if (left.value > right.value) return 1;\\n  return 0;\\n}\\nfunction readLink(reader) {\\n  return {\\n    type: ControlType.Link,\\n    value: reader.readJson()\\n  };\\n}\\nfunction writeLink(writer, value) {\\n  writer.writeJson(value.value);\\n}\\nfunction compareLink(left, right) {\\n  const leftEncoded = JSON.stringify(left.value);\\n  const rightEncoded = JSON.stringify(right.value);\\n  if (leftEncoded < rightEncoded) return -1;\\n  if (leftEncoded > rightEncoded) return 1;\\n  return 0;\\n}\\nfunction readNumber(reader) {\\n  return {\\n    type: ControlType.Number,\\n    value: reader.readFloat64()\\n  };\\n}\\nfunction writeNumber(writer, value) {\\n  writer.writeFloat64(value.value);\\n}\\nfunction compareNumber(left, right) {\\n  if (left.value < right.value) return -1;\\n  if (left.value > right.value) return 1;\\n  return 0;\\n}\\nfunction readObject(reader) {\\n  const length = reader.readUint16();\\n  const result = {};\\n  for (let i = 0; i < length; i++) {\\n    const key = reader.readString();\\n    result[key] = DatabaseValueModel.read(reader);\\n  }\\n  return {\\n    type: ControlType.Object,\\n    value: result\\n  };\\n}\\nfunction writeObject(writer, value) {\\n  const entries = Object.entries(value.value);\\n  writer.writeUint16(entries.length);\\n  for (const [key, item] of entries) {\\n    writer.writeString(key);\\n    DatabaseValueModel.write(writer, item);\\n  }\\n}\\nfunction compareObject(left, right, collation) {\\n  const leftKeys = Object.keys(left.value).sort();\\n  const rightKeys = Object.keys(right.value).sort();\\n  if (leftKeys.length < rightKeys.length) return -1;\\n  if (leftKeys.length > rightKeys.length) return 1;\\n  for (let i = 0; i < leftKeys.length; i++) {\\n    const leftKey = leftKeys[i];\\n    const rightKey = rightKeys[i];\\n    if (leftKey < rightKey) return -1;\\n    if (leftKey > rightKey) return 1;\\n    const leftValue = left.value[leftKey] ?? null;\\n    const rightValue = right.value[rightKey] ?? null;\\n    const result = DatabaseValueModel.compare(leftValue, rightValue, collation);\\n    if (result !== 0) return result;\\n  }\\n  return 0;\\n}\\nfunction readResponsiveImage(reader) {\\n  return {\\n    type: ControlType.ResponsiveImage,\\n    value: reader.readJson()\\n  };\\n}\\nfunction writeResponsiveImage(writer, value) {\\n  writer.writeJson(value.value);\\n}\\nfunction compareResponsiveImage(left, right) {\\n  const leftEncoded = JSON.stringify(left.value);\\n  const rightEncoded = JSON.stringify(right.value);\\n  if (leftEncoded < rightEncoded) return -1;\\n  if (leftEncoded > rightEncoded) return 1;\\n  return 0;\\n}\\nfunction readRichText(reader) {\\n  const type = reader.readInt8();\\n  if (type === 0) {\\n    return {\\n      type: ControlType.RichText,\\n      value: reader.readUint32()\\n    };\\n  }\\n  if (type === 1) {\\n    return {\\n      type: ControlType.RichText,\\n      value: reader.readString()\\n    };\\n  }\\n  throw new Error(`Invalid rich text pointer`);\\n}\\nfunction writeRichText(writer, value) {\\n  if (isNumber(value.value)) {\\n    writer.writeInt8(0);\\n    writer.writeUint32(value.value);\\n    return;\\n  }\\n  if (isString(value.value)) {\\n    writer.writeInt8(1);\\n    writer.writeString(value.value);\\n    return;\\n  }\\n  throw new Error(`Invalid rich text pointer`);\\n}\\nfunction compareRichText(left, right) {\\n  const leftValue = left.value;\\n  const rightValue = right.value;\\n  if (isNumber(leftValue) && isNumber(rightValue)) {\\n    if (leftValue < rightValue) return -1;\\n    if (leftValue > rightValue) return 1;\\n    return 0;\\n  }\\n  if (isString(leftValue) && isString(rightValue)) {\\n    if (leftValue < rightValue) return -1;\\n    if (leftValue > rightValue) return 1;\\n    return 0;\\n  }\\n  throw new Error(`Invalid rich text pointer`);\\n}\\nfunction readString(reader) {\\n  return {\\n    type: ControlType.String,\\n    value: reader.readString()\\n  };\\n}\\nfunction writeString(writer, value) {\\n  writer.writeString(value.value);\\n}\\nfunction compareString(left, right, collation) {\\n  let leftValue = left.value;\\n  let rightValue = right.value;\\n  if (collation.type === 0 /* CaseInsensitive */) {\\n    leftValue = left.value.toLowerCase();\\n    rightValue = right.value.toLowerCase();\\n  }\\n  if (leftValue < rightValue) return -1;\\n  if (leftValue > rightValue) return 1;\\n  return 0;\\n}\\nfunction readVectorSetItem(reader) {\\n  return {\\n    type: ControlType.VectorSetItem,\\n    value: reader.readUint32()\\n  };\\n}\\nfunction writeVectorSetItem(writer, value) {\\n  writer.writeUint32(value.value);\\n}\\nfunction compareVectorSetItem(left, right) {\\n  const leftValue = left.value;\\n  const rightValue = right.value;\\n  if (leftValue < rightValue) return -1;\\n  if (leftValue > rightValue) return 1;\\n  return 0;\\n}\\n\\n// src/code-generation/components/cms/bundled/models/DatabaseDictionaryIndexModel.ts\\nvar DatabaseDictionaryIndexModel = class _DatabaseDictionaryIndexModel {\\n  constructor(fieldNames, options) {\\n    this.fieldNames = fieldNames;\\n    this.options = options;\\n    __publicField(this, \\\"entries\\\", []);\\n  }\\n  sortEntries() {\\n    this.entries.sort((left, right) => {\\n      for (let i = 0; i < this.fieldNames.length; i++) {\\n        const leftValue = left.values[i];\\n        const rightValue = right.values[i];\\n        const result = DatabaseValueModel.compare(leftValue, rightValue, this.options.collation);\\n        if (result !== 0) return result;\\n      }\\n      return left.pointer.compare(right.pointer);\\n    });\\n  }\\n  static deserialize(bytes) {\\n    const reader = new BufferReader(bytes);\\n    const collation = reader.readJson();\\n    const fieldCount = reader.readUint8();\\n    const fieldNames = [];\\n    for (let i = 0; i < fieldCount; i++) {\\n      const fieldName = reader.readString();\\n      fieldNames.push(fieldName);\\n    }\\n    const index = new _DatabaseDictionaryIndexModel(fieldNames, {\\n      collation\\n    });\\n    const entryCount = reader.readUint32();\\n    for (let i = 0; i < entryCount; i++) {\\n      const values = [];\\n      for (let j = 0; j < fieldCount; j++) {\\n        const fieldValue = DatabaseValueModel.read(reader);\\n        values.push(fieldValue);\\n      }\\n      const pointer = DatabaseItemPointerModel.read(reader);\\n      index.entries.push({ values, pointer });\\n    }\\n    return index;\\n  }\\n  serialize() {\\n    const writer = new BufferWriter();\\n    writer.writeJson(this.options.collation);\\n    writer.writeUint8(this.fieldNames.length);\\n    for (const fieldName of this.fieldNames) {\\n      writer.writeString(fieldName);\\n    }\\n    this.sortEntries();\\n    writer.writeUint32(this.entries.length);\\n    for (const entry of this.entries) {\\n      const { values, pointer } = entry;\\n      for (const value of values) {\\n        DatabaseValueModel.write(writer, value);\\n      }\\n      pointer.write(writer);\\n    }\\n    return writer.subarray();\\n  }\\n  addItem(item, pointer) {\\n    const values = this.fieldNames.map((fieldName) => {\\n      return item.getField(fieldName) ?? null;\\n    });\\n    this.entries.push({ values, pointer });\\n  }\\n};\\n\\n// src/code-generation/components/cms/bundled/fetchWithRetries.ts\\nvar maxRetries = 3;\\nvar baseDelay = 250;\\nvar retriableHTTPCodes = [\\n  408,\\n  // Request Timeout\\n  429,\\n  // Too Many Requests\\n  500,\\n  // Internal Server Error\\n  502,\\n  // Bad Gateway\\n  503,\\n  // Service Unavailable\\n  504\\n  // Gateway Timeout\\n];\\nvar fetchWithRetries = async (input, init) => {\\n  let retryCount = 0;\\n  while (true) {\\n    try {\\n      const res = await fetch(input, init);\\n      if (!retriableHTTPCodes.includes(res.status) || ++retryCount > maxRetries) {\\n        return res;\\n      }\\n    } catch (error) {\\n      if (init?.signal?.aborted || ++retryCount > maxRetries) {\\n        throw error;\\n      }\\n    }\\n    await retryDelay(retryCount);\\n  }\\n};\\nasync function retryDelay(retryCount) {\\n  const backoffExponent = retryCount - 1;\\n  const jitter = Math.random() + 1;\\n  const timeout = Math.floor(baseDelay * jitter * 2 ** backoffExponent);\\n  await new Promise((resolve) => {\\n    setTimeout(resolve, timeout);\\n  });\\n}\\n\\n// src/code-generation/components/cms/bundled/rangeRequest.ts\\nasync function rangeRequest(url, ranges) {\\n  const collapsedRanges = collapseRanges(ranges);\\n  const rangeStrings = [];\\n  let expectedLength = 0;\\n  for (const range of collapsedRanges) {\\n    rangeStrings.push(`${range.from}-${range.to - 1}`);\\n    expectedLength += range.to - range.from;\\n  }\\n  const rangeUrl = new URL(url);\\n  const rangeQuery = rangeStrings.join(\\\",\\\");\\n  rangeUrl.searchParams.set(\\\"range\\\", rangeQuery);\\n  const response = await fetchWithRetries(rangeUrl);\\n  if (response.status !== 200) {\\n    throw new Error(`Request failed: ${response.status} ${response.statusText}`);\\n  }\\n  const buffer = await response.arrayBuffer();\\n  const bytes = new Uint8Array(buffer);\\n  if (bytes.length !== expectedLength) {\\n    throw new Error(\\\"Request failed: Unexpected response length\\\");\\n  }\\n  const file = new PartialFile();\\n  let start = 0;\\n  for (const range of collapsedRanges) {\\n    const length = range.to - range.from;\\n    const end = start + length;\\n    const part = bytes.subarray(start, end);\\n    file.write(range.from, part);\\n    start = end;\\n  }\\n  return ranges.map((range) => {\\n    return file.read(range.from, range.to - range.from);\\n  });\\n}\\nvar PartialFile = class {\\n  constructor() {\\n    __publicField(this, \\\"chunks\\\", []);\\n  }\\n  read(position, length) {\\n    for (const chunk of this.chunks) {\\n      if (position < chunk.start) {\\n        throw new Error(\\\"Missing data\\\");\\n      }\\n      if (position > chunk.end) {\\n        continue;\\n      }\\n      if (position + length > chunk.end) {\\n        throw new Error(\\\"Missing data\\\");\\n      }\\n      const from = position - chunk.start;\\n      const to = from + length;\\n      return chunk.data.slice(from, to);\\n    }\\n    throw new Error(\\\"Missing data\\\");\\n  }\\n  write(position, data) {\\n    let start = position;\\n    let end = start + data.length;\\n    let fromIndex = 0;\\n    let toIndex = this.chunks.length;\\n    for (; fromIndex < toIndex; fromIndex++) {\\n      const chunk2 = this.chunks[fromIndex];\\n      assert(chunk2, \\\"Missing chunk\\\");\\n      if (start > chunk2.end) {\\n        continue;\\n      }\\n      if (start > chunk2.start) {\\n        const offset = start - chunk2.start;\\n        const prefix = chunk2.data.subarray(0, offset);\\n        data = join(prefix, data);\\n        start = chunk2.start;\\n      }\\n      break;\\n    }\\n    for (; toIndex > fromIndex; toIndex--) {\\n      const chunk2 = this.chunks[toIndex - 1];\\n      assert(chunk2, \\\"Missing chunk\\\");\\n      if (end < chunk2.start) {\\n        continue;\\n      }\\n      if (end < chunk2.end) {\\n        const offset = end - chunk2.start;\\n        const suffix = chunk2.data.subarray(offset);\\n        data = join(data, suffix);\\n        end = chunk2.end;\\n      }\\n      break;\\n    }\\n    const chunk = {\\n      start,\\n      end,\\n      data\\n    };\\n    const deleteCount = toIndex - fromIndex;\\n    this.chunks.splice(fromIndex, deleteCount, chunk);\\n  }\\n};\\nfunction join(left, right) {\\n  const length = left.length + right.length;\\n  const result = new Uint8Array(length);\\n  result.set(left, 0);\\n  result.set(right, left.length);\\n  return result;\\n}\\nfunction collapseRanges(ranges) {\\n  assert(ranges.length > 0, \\\"Must have at least one range\\\");\\n  const sorted = [...ranges].sort((a, b) => a.from - b.from);\\n  const collapsed = [];\\n  for (const range of sorted) {\\n    const index = collapsed.length - 1;\\n    const previous = collapsed[index];\\n    if (previous && range.from <= previous.to) {\\n      collapsed[index] = {\\n        from: previous.from,\\n        to: Math.max(previous.to, range.to)\\n      };\\n    } else {\\n      collapsed.push(range);\\n    }\\n  }\\n  return collapsed;\\n}\\n\\n// src/code-generation/components/cms/bundled/DatabaseDictionaryIndex.ts\\nvar DatabaseDictionaryIndex = class {\\n  constructor(options) {\\n    this.options = options;\\n    __publicField(this, \\\"schema\\\");\\n    __publicField(this, \\\"fields\\\");\\n    __publicField(this, \\\"supportedLookupTypes\\\", [\\n      \\\"All\\\" /* All */,\\n      \\\"Equals\\\" /* Equals */,\\n      \\\"NotEquals\\\" /* NotEquals */,\\n      \\\"LessThan\\\" /* LessThan */,\\n      \\\"GreaterThan\\\" /* GreaterThan */,\\n      \\\"Contains\\\" /* Contains */,\\n      \\\"StartsWith\\\" /* StartsWith */,\\n      \\\"EndsWith\\\" /* EndsWith */\\n    ]);\\n    __publicField(this, \\\"modelPromise\\\");\\n    __publicField(this, \\\"model\\\");\\n    __publicField(this, \\\"collation\\\");\\n    const schema = {};\\n    const fields = [];\\n    for (const fieldName of this.options.fieldNames) {\\n      const definition = this.options.collectionSchema[fieldName];\\n      assert(definition, \\\"Missing definition for field\\\", fieldName);\\n      schema[fieldName] = definition;\\n      fields.push({ type: \\\"Identifier\\\", name: fieldName });\\n    }\\n    this.schema = schema;\\n    this.fields = fields;\\n    this.collation = this.options.collation;\\n  }\\n  async loadModel() {\\n    const [bytes] = await rangeRequest(this.options.url, [this.options.range]);\\n    assert(bytes, \\\"Failed to load model\\\");\\n    return DatabaseDictionaryIndexModel.deserialize(bytes);\\n  }\\n  async getModel() {\\n    this.modelPromise ??= this.loadModel();\\n    this.model ??= await this.modelPromise;\\n    return this.model;\\n  }\\n  async lookupItems(queries) {\\n    assert(queries.length === this.fields.length, \\\"Invalid query length\\\");\\n    const model = await this.getModel();\\n    const chunks = queries.reduce(\\n      (memo, query, position) => memo.flatMap((entries) => {\\n        switch (query.type) {\\n          case \\\"All\\\" /* All */:\\n            return [entries];\\n          case \\\"Equals\\\" /* Equals */:\\n            return this.queryEquals(entries, query, position);\\n          case \\\"NotEquals\\\" /* NotEquals */:\\n            return this.queryNotEquals(entries, query, position);\\n          case \\\"LessThan\\\" /* LessThan */:\\n            return this.queryLessThan(entries, query, position);\\n          case \\\"GreaterThan\\\" /* GreaterThan */:\\n            return this.queryGreaterThan(entries, query, position);\\n          case \\\"Contains\\\" /* Contains */:\\n            return this.queryContains(entries, query, position);\\n          case \\\"StartsWith\\\" /* StartsWith */:\\n            return this.queryStartsWith(entries, query, position);\\n          case \\\"EndsWith\\\" /* EndsWith */:\\n            return this.queryEndsWith(entries, query, position);\\n          default:\\n            assertNever(query);\\n        }\\n      }),\\n      [model.entries]\\n    );\\n    const result = [];\\n    for (const entries of chunks) {\\n      for (const entry of entries) {\\n        const data = {};\\n        for (let i = 0; i < this.options.fieldNames.length; i++) {\\n          const fieldName = this.options.fieldNames[i];\\n          const fieldValue = entry.values[i];\\n          data[fieldName] = fieldValue;\\n        }\\n        result.push({ pointer: entry.pointer.toString(), data });\\n      }\\n    }\\n    return result;\\n  }\\n  queryEquals(entries, query, position) {\\n    const leftMost = this.getLeftMost(entries, position, query.value);\\n    const rightMost = this.getRightMost(entries, position, query.value);\\n    const slice = entries.slice(leftMost, rightMost + 1);\\n    return slice.length > 0 ? [slice] : [];\\n  }\\n  queryNotEquals(entries, query, position) {\\n    const leftMost = this.getLeftMost(entries, position, query.value);\\n    const rightMost = this.getRightMost(entries, position, query.value);\\n    const result = [];\\n    const before = entries.slice(0, leftMost);\\n    if (before.length > 0) result.push(before);\\n    const after = entries.slice(rightMost + 1);\\n    if (after.length > 0) result.push(after);\\n    return result;\\n  }\\n  queryLessThan(entries, query, position) {\\n    const nullBound = this.getRightMost(entries, position, null);\\n    entries = entries.slice(nullBound + 1);\\n    if (query.inclusive) {\\n      const rightMost = this.getRightMost(entries, position, query.value);\\n      const slice2 = entries.slice(0, rightMost + 1);\\n      return slice2.length > 0 ? [slice2] : [];\\n    }\\n    const leftMost = this.getLeftMost(entries, position, query.value);\\n    const slice = entries.slice(0, leftMost);\\n    return slice.length > 0 ? [slice] : [];\\n  }\\n  queryGreaterThan(entries, query, position) {\\n    const nullBound = this.getRightMost(entries, position, null);\\n    entries = entries.slice(nullBound + 1);\\n    if (query.inclusive) {\\n      const leftMost = this.getLeftMost(entries, position, query.value);\\n      const slice2 = entries.slice(leftMost);\\n      return slice2.length > 0 ? [slice2] : [];\\n    }\\n    const rightMost = this.getRightMost(entries, position, query.value);\\n    const slice = entries.slice(rightMost + 1);\\n    return slice.length > 0 ? [slice] : [];\\n  }\\n  queryContains(entries, query, position) {\\n    return this.findItems(entries, position, (current) => {\\n      if (current?.type !== ControlType2.String) return false;\\n      if (query.value?.type !== ControlType2.String) return false;\\n      let source = current.value;\\n      let target = query.value.value;\\n      if (this.collation.type === 0 /* CaseInsensitive */) {\\n        source = source.toLowerCase();\\n        target = target.toLowerCase();\\n      }\\n      return source.includes(target);\\n    });\\n  }\\n  queryStartsWith(entries, query, position) {\\n    return this.findItems(entries, position, (current) => {\\n      if (current?.type !== ControlType2.String) return false;\\n      if (query.value?.type !== ControlType2.String) return false;\\n      let source = current.value;\\n      let target = query.value.value;\\n      if (this.collation.type === 0 /* CaseInsensitive */) {\\n        source = source.toLowerCase();\\n        target = target.toLowerCase();\\n      }\\n      return source.startsWith(target);\\n    });\\n  }\\n  queryEndsWith(entries, query, position) {\\n    return this.findItems(entries, position, (current) => {\\n      if (current?.type !== ControlType2.String) return false;\\n      if (query.value?.type !== ControlType2.String) return false;\\n      let source = current.value;\\n      let target = query.value.value;\\n      if (this.collation.type === 0 /* CaseInsensitive */) {\\n        source = source.toLowerCase();\\n        target = target.toLowerCase();\\n      }\\n      return source.endsWith(target);\\n    });\\n  }\\n  /**\\n   * Returns the index of the left most entry that is equal to the target.\\n   *\\n   * ```text\\n   *   Left most\\n   *       \u2193\\n   * \u250C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2510\\n   * \u2502 1 \u2502 2 \u2502 2 \u2502 2 \u2502 2 \u2502 3 \u2502\\n   * \u2514\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2518\\n   * ```\\n   *\\n   * @param entries The entries array to search in.\\n   * @param position The position of the value in the entry.\\n   * @param target The target value to search for.\\n   * @returns The index of the left most entry that is equal to the target.\\n   */\\n  getLeftMost(entries, position, target) {\\n    let left = 0;\\n    let right = entries.length;\\n    while (left < right) {\\n      const middle = left + right >> 1;\\n      const entry = entries[middle];\\n      const value = entry.values[position];\\n      if (DatabaseValueModel.compare(value, target, this.collation) < 0) {\\n        left = middle + 1;\\n      } else {\\n        right = middle;\\n      }\\n    }\\n    return left;\\n  }\\n  /**\\n   * Returns the index of the right most entry that is equal to the target.\\n   *\\n   * ```text\\n   *              Right most\\n   *                   \u2193\\n   * \u250C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2510\\n   * \u2502 1 \u2502 2 \u2502 2 \u2502 2 \u2502 2 \u2502 3 \u2502\\n   * \u2514\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2518\\n   * ```\\n   *\\n   * @param entries The entries array to search in.\\n   * @param position The position of the value in the entry.\\n   * @param target The target value to search for.\\n   * @returns The index of the right most entry that is equal to the target.\\n   */\\n  getRightMost(entries, position, target) {\\n    let left = 0;\\n    let right = entries.length;\\n    while (left < right) {\\n      const middle = left + right >> 1;\\n      const entry = entries[middle];\\n      const value = entry.values[position];\\n      if (DatabaseValueModel.compare(value, target, this.collation) > 0) {\\n        right = middle;\\n      } else {\\n        left = middle + 1;\\n      }\\n    }\\n    return right - 1;\\n  }\\n  /**\\n   * Finds all items that are matching the predicate and groups adjacent items together.\\n   *\\n   * @param entries The entries array to search in.\\n   * @param position The position of the value in the entry.\\n   * @param predicate The predicate to match the values against.\\n   * @returns An array of chunks that match the predicate.\\n   */\\n  findItems(entries, position, predicate) {\\n    const result = [];\\n    let start = 0;\\n    for (let i = 0; i < entries.length; i++) {\\n      const entry = entries[i];\\n      const value = entry.values[position];\\n      const isMatching = predicate(value);\\n      if (isMatching) continue;\\n      if (start < i) {\\n        const slice = entries.slice(start, i);\\n        result.push(slice);\\n      }\\n      start = i + 1;\\n    }\\n    if (start < entries.length) {\\n      const slice = entries.slice(start);\\n      result.push(slice);\\n    }\\n    return result;\\n  }\\n};\\n\\n// src/code-generation/components/cms/bundled/models/DatabaseItemModel.ts\\nvar DatabaseItemModel = class _DatabaseItemModel {\\n  constructor() {\\n    __publicField(this, \\\"fields\\\", /* @__PURE__ */ new Map());\\n  }\\n  static read(reader) {\\n    const item = new _DatabaseItemModel();\\n    const fieldCount = reader.readUint16();\\n    for (let i = 0; i < fieldCount; i++) {\\n      const key = reader.readString();\\n      const value = DatabaseValueModel.read(reader);\\n      item.setField(key, value);\\n    }\\n    return item;\\n  }\\n  write(writer) {\\n    writer.writeUint16(this.fields.size);\\n    for (const [key, value] of this.fields) {\\n      writer.writeString(key);\\n      DatabaseValueModel.write(writer, value);\\n    }\\n  }\\n  getData() {\\n    const data = {};\\n    for (const [key, value] of this.fields) {\\n      data[key] = value;\\n    }\\n    return data;\\n  }\\n  setField(key, value) {\\n    this.fields.set(key, value);\\n  }\\n  getField(key) {\\n    return this.fields.get(key);\\n  }\\n};\\n\\n// src/code-generation/components/cms/bundled/DatabaseCollection.ts?bundle\\nvar DatabaseChunk = class {\\n  constructor(id, url) {\\n    this.id = id;\\n    this.url = url;\\n    __publicField(this, \\\"itemsPromise\\\");\\n    __publicField(this, \\\"itemLoader\\\", new import_dataloader.default(\\n      async (pointers) => {\\n        const ranges = pointers.map((pointer) => {\\n          const pointerModel = DatabaseItemPointerModel.fromString(pointer);\\n          return { from: pointerModel.offset, to: pointerModel.offset + pointerModel.length };\\n        });\\n        const rangeBytes = await rangeRequest(this.url, ranges);\\n        return rangeBytes.map((bytes, index) => {\\n          const reader = new BufferReader(bytes);\\n          const itemModel = DatabaseItemModel.read(reader);\\n          const pointer = pointers[index];\\n          assert(pointer, \\\"Missing pointer\\\");\\n          return {\\n            pointer,\\n            data: itemModel.getData()\\n          };\\n        });\\n      },\\n      { maxBatchSize: 250 }\\n    ));\\n  }\\n  scanItems() {\\n    this.itemsPromise ??= fetchWithRetries(this.url).then(async (response) => {\\n      if (!response.ok) {\\n        throw new Error(`Request failed: ${response.status} ${response.statusText}`);\\n      }\\n      const buffer = await response.arrayBuffer();\\n      const bytes = new Uint8Array(buffer);\\n      const reader = new BufferReader(bytes);\\n      const items = [];\\n      const itemCount = reader.readUint32();\\n      for (let i = 0; i < itemCount; i++) {\\n        const offset = reader.getOffset();\\n        const itemModel = DatabaseItemModel.read(reader);\\n        const length = reader.getOffset() - offset;\\n        const pointerModel = new DatabaseItemPointerModel(this.id, offset, length);\\n        const pointer = pointerModel.toString();\\n        const item = {\\n          pointer,\\n          data: itemModel.getData()\\n        };\\n        this.itemLoader.prime(pointer, item);\\n        items.push(item);\\n      }\\n      return items;\\n    });\\n    return this.itemsPromise;\\n  }\\n  resolveItem(pointer) {\\n    return this.itemLoader.load(pointer);\\n  }\\n};\\nvar DatabaseCollection = class {\\n  constructor(options) {\\n    this.options = options;\\n    __publicField(this, \\\"id\\\");\\n    __publicField(this, \\\"schema\\\");\\n    __publicField(this, \\\"indexes\\\");\\n    __publicField(this, \\\"resolveRichText\\\");\\n    __publicField(this, \\\"resolveVectorSetItem\\\");\\n    __publicField(this, \\\"chunks\\\");\\n    this.chunks = this.options.chunks.map((url, id) => {\\n      return new DatabaseChunk(id, url);\\n    });\\n    this.schema = options.schema;\\n    this.indexes = options.indexes;\\n    this.resolveRichText = options.resolveRichText;\\n    this.resolveVectorSetItem = options.resolveVectorSetItem;\\n    this.id = options.id;\\n  }\\n  async scanItems() {\\n    const chunkedItems = await Promise.all(\\n      this.chunks.map(async (chunk) => {\\n        return chunk.scanItems();\\n      })\\n    );\\n    return chunkedItems.flat();\\n  }\\n  resolveItems(pointers) {\\n    return Promise.all(\\n      pointers.map((pointer) => {\\n        const pointerModel = DatabaseItemPointerModel.fromString(pointer);\\n        const chunk = this.chunks[pointerModel.chunkId];\\n        assert(chunk, \\\"Missing chunk\\\");\\n        return chunk.resolveItem(pointer);\\n      })\\n    );\\n  }\\n  compareItems(left, right) {\\n    const leftModel = DatabaseItemPointerModel.fromString(left.pointer);\\n    const rightModel = DatabaseItemPointerModel.fromString(right.pointer);\\n    return leftModel.compare(rightModel);\\n  }\\n  compareValues(left, right, collation) {\\n    return DatabaseValueModel.compare(left, right, collation);\\n  }\\n};\\nexport {\\n  DatabaseCollection,\\n  DatabaseDictionaryIndex\\n};\\n\"", "export default \"var __defProp = Object.defineProperty;\\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \\\"symbol\\\" ? key + \\\"\\\" : key, value);\\n\\n// src/code-generation/components/cms/bundled/DraftDatabaseCollection.ts?bundle\\nimport { ControlType } from \\\"framer\\\";\\n\\n// src/utils/typeChecks.ts\\nfunction isString(value) {\\n  return typeof value === \\\"string\\\";\\n}\\nfunction isNumber(value) {\\n  return Number.isFinite(value);\\n}\\n\\n// src/code-generation/components/cms/bundled/assert.ts\\nfunction assert(condition, ...msg) {\\n  if (condition) return;\\n  throw Error(\\\"Assertion Error\\\" + (msg.length > 0 ? \\\": \\\" + msg.join(\\\" \\\") : \\\"\\\"));\\n}\\n\\n// src/code-generation/components/cms/bundled/DraftDatabaseCollection.ts?bundle\\nvar DraftDatabaseCollection = class {\\n  constructor(draftCollection, originalCollection, previousItemId, nextItemId) {\\n    this.draftCollection = draftCollection;\\n    this.originalCollection = originalCollection;\\n    this.previousItemId = previousItemId;\\n    this.nextItemId = nextItemId;\\n    __publicField(this, \\\"schema\\\");\\n    // We cannot use the original indexes because the draft items\\n    // are not in the original collection.\\n    // Having no indexes means that we perform a full collection scan for every query.\\n    __publicField(this, \\\"indexes\\\", []);\\n    __publicField(this, \\\"itemsPromise\\\");\\n    this.schema = originalCollection.schema;\\n    this.itemsPromise = this.getItems();\\n  }\\n  async getItems() {\\n    const [[...draftItems], [...originalItems]] = await Promise.all([\\n      this.draftCollection.scanItems(),\\n      this.originalCollection.scanItems()\\n    ]);\\n    const lastDraftItem = draftItems.pop();\\n    const firstOriginalItem = originalItems.shift();\\n    if (lastDraftItem) {\\n      draftItems.push({\\n        ...lastDraftItem,\\n        data: {\\n          ...lastDraftItem.data,\\n          [this.nextItemId]: firstOriginalItem?.data.id ?? null\\n        }\\n      });\\n    }\\n    if (firstOriginalItem) {\\n      originalItems.unshift({\\n        ...firstOriginalItem,\\n        data: {\\n          ...firstOriginalItem.data,\\n          [this.previousItemId]: lastDraftItem?.data.id ?? null\\n        }\\n      });\\n    }\\n    return draftItems.map(draftItem).concat(...originalItems);\\n  }\\n  /**\\n   * Get all items, updating pointers for draft items.\\n   */\\n  scanItems() {\\n    return this.itemsPromise;\\n  }\\n  /**\\n   * Depending on the pointer, resolve draft rich text from the draft\\n   * collection, and original rich text from the original collection.\\n   */\\n  resolveRichText(pointer) {\\n    if (isDraftRichTextPointer(pointer)) {\\n      const originalPointer = undraftRichTextPointer(pointer);\\n      return this.draftCollection.resolveRichText(originalPointer);\\n    }\\n    return this.originalCollection.resolveRichText(pointer);\\n  }\\n  resolveVectorSetItem(pointer) {\\n    if (isDraftVectorSetItemPointer(pointer)) {\\n      const originalPointer = undraftVectorSetItemPointer(pointer);\\n      return this.draftCollection.resolveVectorSetItem?.(originalPointer);\\n    }\\n    return this.originalCollection.resolveVectorSetItem?.(pointer);\\n  }\\n  async resolveItems(pointers) {\\n    const items = await this.itemsPromise;\\n    return pointers.map((pointer) => {\\n      const item = items.find((current) => current.pointer === pointer);\\n      assert(item, \\\"Item must exist\\\");\\n      return item;\\n    });\\n  }\\n  /**\\n   * Compare two items, the draft items should come first.\\n   */\\n  compareItems(left, right) {\\n    const leftIsDraft = isDraftPointer(left.pointer);\\n    const rightIsDraft = isDraftPointer(right.pointer);\\n    if (leftIsDraft && rightIsDraft) {\\n      const originalLeft = undraftItem(left);\\n      const originalRight = undraftItem(right);\\n      return this.draftCollection.compareItems(originalLeft, originalRight);\\n    }\\n    if (leftIsDraft) return -1;\\n    if (rightIsDraft) return 1;\\n    return this.originalCollection.compareItems(left, right);\\n  }\\n};\\nvar draftPrefix = \\\"draft:\\\";\\nfunction isDraftPointer(pointer) {\\n  return pointer.startsWith(draftPrefix);\\n}\\nfunction draftPointer(pointer) {\\n  assert(!isDraftPointer(pointer), \\\"Should be a non-draft pointer\\\");\\n  return draftPrefix + pointer;\\n}\\nfunction undraftPointer(pointer) {\\n  assert(isDraftPointer(pointer), \\\"Should be a draft pointer\\\");\\n  return pointer.slice(draftPrefix.length);\\n}\\nfunction isDraftRichTextPointer(pointer) {\\n  if (isNumber(pointer)) {\\n    return pointer < 0;\\n  }\\n  if (isString(pointer)) {\\n    return pointer.startsWith(draftPrefix);\\n  }\\n  throw new Error(\\\"Invalid rich text pointer\\\");\\n}\\nfunction draftRichTextPointer(pointer) {\\n  assert(!isDraftRichTextPointer(pointer), \\\"Should be a non-draft rich text pointer\\\");\\n  if (isNumber(pointer)) {\\n    return -pointer - 1;\\n  }\\n  if (isString(pointer)) {\\n    return draftPrefix + pointer;\\n  }\\n  throw new Error(\\\"Invalid rich text pointer\\\");\\n}\\nfunction undraftRichTextPointer(pointer) {\\n  assert(isDraftRichTextPointer(pointer), \\\"Should be a draft rich text pointer\\\");\\n  if (isNumber(pointer)) {\\n    return -pointer - 1;\\n  }\\n  if (isString(pointer)) {\\n    return pointer.slice(draftPrefix.length);\\n  }\\n  throw new Error(\\\"Invalid rich text pointer\\\");\\n}\\nfunction isDraftVectorSetItemPointer(pointer) {\\n  assert(isNumber(pointer), \\\"Invalid vector set item pointer\\\");\\n  return pointer < 0;\\n}\\nfunction draftVectorSetItemPointer(pointer) {\\n  assert(isNumber(pointer), \\\"Invalid vector set item pointer\\\");\\n  assert(!isDraftVectorSetItemPointer(pointer), \\\"Should be a non-draft vector set item pointer\\\");\\n  return -pointer - 1;\\n}\\nfunction undraftVectorSetItemPointer(pointer) {\\n  assert(isNumber(pointer), \\\"Invalid vector set item pointer\\\");\\n  assert(isDraftVectorSetItemPointer(pointer), \\\"Should be a draft vector set item pointer\\\");\\n  return -pointer - 1;\\n}\\nfunction draftItem(item) {\\n  const data = {};\\n  for (const [key, value] of Object.entries(item.data)) {\\n    if (value?.type === ControlType.RichText) {\\n      data[key] = {\\n        type: ControlType.RichText,\\n        value: draftRichTextPointer(value.value)\\n      };\\n    } else if (value?.type === ControlType.VectorSetItem) {\\n      data[key] = {\\n        type: ControlType.VectorSetItem,\\n        value: draftVectorSetItemPointer(value.value)\\n      };\\n    } else {\\n      data[key] = value;\\n    }\\n  }\\n  return {\\n    pointer: draftPointer(item.pointer),\\n    data\\n  };\\n}\\nfunction undraftItem(item) {\\n  const data = {};\\n  for (const [key, value] of Object.entries(item.data)) {\\n    if (value?.type === ControlType.RichText) {\\n      data[key] = {\\n        type: ControlType.RichText,\\n        value: undraftRichTextPointer(value.value)\\n      };\\n    } else if (value?.type === ControlType.VectorSetItem) {\\n      data[key] = {\\n        type: ControlType.VectorSetItem,\\n        value: undraftVectorSetItemPointer(value.value)\\n      };\\n    } else {\\n      data[key] = value;\\n    }\\n  }\\n  return {\\n    pointer: undraftPointer(item.pointer),\\n    data\\n  };\\n}\\nexport {\\n  DraftDatabaseCollection\\n};\\n\"", "import { isNumber } from \"utils/typeChecks.ts\"\nimport type { BufferReader } from \"../BufferReader.ts\"\nimport type { BufferWriter } from \"../BufferWriter.ts\"\nimport { assert } from \"../assert.ts\"\n\n/**\n * A pointer to an item's location in the collection's data chunks.\n *\n * ```text\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 Type    \u2502 Description                                                \u2502\n * \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n * \u2502 Uint16  \u2502 The index of the data chunk which contains the item        \u2502\n * \u2502 Uint32  \u2502 The byte offset at which the item starts in the data chunk \u2502\n * \u2502 Uint32  \u2502 The byte length of the item                                \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * ```\n */\nexport class DatabaseItemPointerModel {\n\tconstructor(\n\t\treadonly chunkId: number,\n\t\treadonly offset: number,\n\t\treadonly length: number,\n\t) {}\n\n\tstatic fromString(value: string) {\n\t\tconst [chunkId, offset, length] = value.split(\"/\").map(Number)\n\t\tassert(isNumber(chunkId), \"Invalid chunkId\")\n\t\tassert(isNumber(offset), \"Invalid offset\")\n\t\tassert(isNumber(length), \"Invalid length\")\n\t\treturn new DatabaseItemPointerModel(chunkId, offset, length)\n\t}\n\n\ttoString() {\n\t\treturn `${this.chunkId}/${this.offset}/${this.length}`\n\t}\n\n\tstatic read(reader: BufferReader) {\n\t\tconst chunkId = reader.readUint16()\n\t\tconst offset = reader.readUint32()\n\t\tconst length = reader.readUint32()\n\t\treturn new DatabaseItemPointerModel(chunkId, offset, length)\n\t}\n\n\twrite(writer: BufferWriter) {\n\t\twriter.writeUint16(this.chunkId)\n\t\twriter.writeUint32(this.offset)\n\t\twriter.writeUint32(this.length)\n\t}\n\n\tcompare(other: DatabaseItemPointerModel) {\n\t\tif (this.chunkId < other.chunkId) return -1\n\t\tif (this.chunkId > other.chunkId) return 1\n\t\tif (this.offset < other.offset) return -1\n\t\tif (this.offset > other.offset) return 1\n\t\tassert(this.length === other.length)\n\t\treturn 0\n\t}\n}\n", "import { ControlType } from \"library/index.ts\"\nimport type {\n\tDatabaseArrayValue,\n\tDatabaseBooleanValue,\n\tDatabaseColorValue,\n\tDatabaseDateValue,\n\tDatabaseEnumValue,\n\tDatabaseFileValue,\n\tDatabaseLinkValue,\n\tDatabaseNumberValue,\n\tDatabaseObjectValue,\n\tDatabaseResponsiveImageValue,\n\tDatabaseRichTextValue,\n\tDatabaseStringValue,\n\tDatabaseValue,\n\tDatabaseVectorSetItemValue,\n} from \"library/modules/cms/DatabaseValue.ts\"\nimport type { DatabaseCollation } from \"library/modules/cms/types.ts\"\nimport { DatabaseCollationType } from \"library/modules/cms/types.ts\"\nimport { isNull, isNumber, isString } from \"utils/typeChecks.ts\"\nimport type { BufferReader } from \"../BufferReader.ts\"\nimport type { BufferWriter } from \"../BufferWriter.ts\"\nimport { assert, assertNever } from \"../assert.ts\"\n\nenum ValueType {\n\tNull = 0,\n\tArray,\n\tBoolean,\n\tColor,\n\tDate,\n\tEnum,\n\tFile,\n\tLink,\n\tNumber,\n\tObject,\n\tResponsiveImage,\n\tRichText,\n\tString,\n\tVectorSetItem,\n}\n\nfunction getValueType(value: DatabaseValue) {\n\tif (isNull(value)) {\n\t\treturn ValueType.Null\n\t}\n\n\tswitch (value.type) {\n\t\tcase ControlType.Array:\n\t\t\treturn ValueType.Array\n\t\tcase ControlType.Boolean:\n\t\t\treturn ValueType.Boolean\n\t\tcase ControlType.Color:\n\t\t\treturn ValueType.Color\n\t\tcase ControlType.Date:\n\t\t\treturn ValueType.Date\n\t\tcase ControlType.Enum:\n\t\t\treturn ValueType.Enum\n\t\tcase ControlType.File:\n\t\t\treturn ValueType.File\n\t\tcase ControlType.ResponsiveImage:\n\t\t\treturn ValueType.ResponsiveImage\n\t\tcase ControlType.Link:\n\t\t\treturn ValueType.Link\n\t\tcase ControlType.Number:\n\t\t\treturn ValueType.Number\n\t\tcase ControlType.Object:\n\t\t\treturn ValueType.Object\n\t\tcase ControlType.RichText:\n\t\t\treturn ValueType.RichText\n\t\tcase ControlType.String:\n\t\t\treturn ValueType.String\n\t\tcase ControlType.VectorSetItem:\n\t\t\treturn ValueType.VectorSetItem\n\t\tdefault:\n\t\t\tassertNever(value)\n\t}\n}\n\n/**\n * An item field value.\n *\n * ```text\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 Type  \u2502 Description                                             \u2502\n * \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n * \u2502 Uint8 \u2502 Value type                                              \u2502\n * \u2502 Value \u2502 Each value type implements its own serialization format \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * ```\n */\nexport namespace DatabaseValueModel {\n\texport function read(reader: BufferReader): DatabaseValue {\n\t\tconst type = reader.readUint8() as ValueType\n\n\t\tswitch (type) {\n\t\t\tcase ValueType.Null:\n\t\t\t\treturn null\n\t\t\tcase ValueType.Array:\n\t\t\t\treturn readArray(reader)\n\t\t\tcase ValueType.Boolean:\n\t\t\t\treturn readBoolean(reader)\n\t\t\tcase ValueType.Color:\n\t\t\t\treturn readColor(reader)\n\t\t\tcase ValueType.Date:\n\t\t\t\treturn readDate(reader)\n\t\t\tcase ValueType.Enum:\n\t\t\t\treturn readEnum(reader)\n\t\t\tcase ValueType.File:\n\t\t\t\treturn readFile(reader)\n\t\t\tcase ValueType.Link:\n\t\t\t\treturn readLink(reader)\n\t\t\tcase ValueType.Number:\n\t\t\t\treturn readNumber(reader)\n\t\t\tcase ValueType.Object:\n\t\t\t\treturn readObject(reader)\n\t\t\tcase ValueType.ResponsiveImage:\n\t\t\t\treturn readResponsiveImage(reader)\n\t\t\tcase ValueType.RichText:\n\t\t\t\treturn readRichText(reader)\n\t\t\tcase ValueType.String:\n\t\t\t\treturn readString(reader)\n\t\t\tcase ValueType.VectorSetItem:\n\t\t\t\treturn readVectorSetItem(reader)\n\t\t\tdefault:\n\t\t\t\tassertNever(type)\n\t\t}\n\t}\n\n\texport function write(writer: BufferWriter, value: DatabaseValue) {\n\t\tconst type = getValueType(value)\n\t\twriter.writeUint8(type)\n\n\t\tif (isNull(value)) return\n\n\t\tswitch (value.type) {\n\t\t\tcase ControlType.Array:\n\t\t\t\treturn writeArray(writer, value)\n\t\t\tcase ControlType.Boolean:\n\t\t\t\treturn writeBoolean(writer, value)\n\t\t\tcase ControlType.Color:\n\t\t\t\treturn writeColor(writer, value)\n\t\t\tcase ControlType.Date:\n\t\t\t\treturn writeDate(writer, value)\n\t\t\tcase ControlType.Enum:\n\t\t\t\treturn writeEnum(writer, value)\n\t\t\tcase ControlType.File:\n\t\t\t\treturn writeFile(writer, value)\n\t\t\tcase ControlType.Link:\n\t\t\t\treturn writeLink(writer, value)\n\t\t\tcase ControlType.Number:\n\t\t\t\treturn writeNumber(writer, value)\n\t\t\tcase ControlType.Object:\n\t\t\t\treturn writeObject(writer, value)\n\t\t\tcase ControlType.ResponsiveImage:\n\t\t\t\treturn writeResponsiveImage(writer, value)\n\t\t\tcase ControlType.RichText:\n\t\t\t\treturn writeRichText(writer, value)\n\t\t\tcase ControlType.VectorSetItem:\n\t\t\t\treturn writeVectorSetItem(writer, value)\n\t\t\tcase ControlType.String:\n\t\t\t\treturn writeString(writer, value)\n\t\t\tdefault:\n\t\t\t\tassertNever(value)\n\t\t}\n\t}\n\n\texport function compare(left: DatabaseValue, right: DatabaseValue, collation: DatabaseCollation) {\n\t\tconst leftType = getValueType(left)\n\t\tconst rightType = getValueType(right)\n\n\t\tif (leftType < rightType) return -1\n\t\tif (leftType > rightType) return 1\n\n\t\t// If both values are null, they are equal. We already compare the type\n\t\t// of the values above, so if one of them is null the other one has to\n\t\t// be null as well. Using or instead of and here will make the code\n\t\t// below nicer.\n\t\tif (isNull(left) || isNull(right)) return 0\n\n\t\tswitch (left.type) {\n\t\t\tcase ControlType.Array:\n\t\t\t\tassert(right.type === ControlType.Array)\n\t\t\t\treturn compareArray(left, right, collation)\n\n\t\t\tcase ControlType.Boolean:\n\t\t\t\tassert(right.type === ControlType.Boolean)\n\t\t\t\treturn compareBoolean(left, right)\n\n\t\t\tcase ControlType.Color:\n\t\t\t\tassert(right.type === ControlType.Color)\n\t\t\t\treturn compareColor(left, right)\n\n\t\t\tcase ControlType.Date:\n\t\t\t\tassert(right.type === ControlType.Date)\n\t\t\t\treturn compareDate(left, right)\n\n\t\t\tcase ControlType.Enum:\n\t\t\t\tassert(right.type === ControlType.Enum)\n\t\t\t\treturn compareEnum(left, right)\n\n\t\t\tcase ControlType.File:\n\t\t\t\tassert(right.type === ControlType.File)\n\t\t\t\treturn compareFile(left, right)\n\n\t\t\tcase ControlType.Link:\n\t\t\t\tassert(right.type === ControlType.Link)\n\t\t\t\treturn compareLink(left, right)\n\n\t\t\tcase ControlType.Number:\n\t\t\t\tassert(right.type === ControlType.Number)\n\t\t\t\treturn compareNumber(left, right)\n\n\t\t\tcase ControlType.Object:\n\t\t\t\tassert(right.type === ControlType.Object)\n\t\t\t\treturn compareObject(left, right, collation)\n\n\t\t\tcase ControlType.ResponsiveImage:\n\t\t\t\tassert(right.type === ControlType.ResponsiveImage)\n\t\t\t\treturn compareResponsiveImage(left, right)\n\n\t\t\tcase ControlType.RichText:\n\t\t\t\tassert(right.type === ControlType.RichText)\n\t\t\t\treturn compareRichText(left, right)\n\n\t\t\tcase ControlType.VectorSetItem:\n\t\t\t\tassert(right.type === ControlType.VectorSetItem)\n\t\t\t\treturn compareVectorSetItem(left, right)\n\n\t\t\tcase ControlType.String:\n\t\t\t\tassert(right.type === ControlType.String)\n\t\t\t\treturn compareString(left, right, collation)\n\n\t\t\tdefault:\n\t\t\t\tassertNever(left)\n\t\t}\n\t}\n}\n\n/**\n * DatabaseArrayValue\n */\n\nfunction readArray(reader: BufferReader): DatabaseArrayValue {\n\tconst length = reader.readUint16()\n\tconst value: DatabaseValue[] = []\n\n\tfor (let i = 0; i < length; i++) {\n\t\tconst item = DatabaseValueModel.read(reader)\n\t\tvalue.push(item)\n\t}\n\n\treturn {\n\t\ttype: ControlType.Array,\n\t\tvalue,\n\t}\n}\n\nfunction writeArray(writer: BufferWriter, value: DatabaseArrayValue): void {\n\twriter.writeUint16(value.value.length)\n\n\tfor (const item of value.value) {\n\t\tDatabaseValueModel.write(writer, item)\n\t}\n}\n\nfunction compareArray(left: DatabaseArrayValue, right: DatabaseArrayValue, collation: DatabaseCollation): number {\n\tconst leftLength = left.value.length\n\tconst rightLength = right.value.length\n\n\tif (leftLength < rightLength) return -1\n\tif (leftLength > rightLength) return 1\n\n\tfor (let i = 0; i < leftLength; i++) {\n\t\t// biome-ignore lint/style/noNonNullAssertion: Guaranteed by the loop.\n\t\tconst leftItem = left.value[i]!\n\t\t// biome-ignore lint/style/noNonNullAssertion: Guaranteed by the loop.\n\t\tconst rightItem = right.value[i]!\n\n\t\tconst result = DatabaseValueModel.compare(leftItem, rightItem, collation)\n\t\tif (result !== 0) return result\n\t}\n\n\treturn 0\n}\n\n/**\n * DatabaseBooleanValue\n */\n\nfunction readBoolean(reader: BufferReader): DatabaseBooleanValue {\n\treturn {\n\t\ttype: ControlType.Boolean,\n\t\tvalue: reader.readUint8() !== 0,\n\t}\n}\n\nfunction writeBoolean(writer: BufferWriter, value: DatabaseBooleanValue): void {\n\twriter.writeUint8(value.value ? 1 : 0)\n}\n\nfunction compareBoolean(left: DatabaseBooleanValue, right: DatabaseBooleanValue): number {\n\tif (left.value < right.value) return -1\n\tif (left.value > right.value) return 1\n\treturn 0\n}\n\n/**\n * DatabaseColorValue\n */\n\nfunction readColor(reader: BufferReader): DatabaseColorValue {\n\treturn {\n\t\ttype: ControlType.Color,\n\t\tvalue: reader.readString(),\n\t}\n}\n\nfunction writeColor(writer: BufferWriter, value: DatabaseColorValue): void {\n\twriter.writeString(value.value)\n}\n\nfunction compareColor(left: DatabaseColorValue, right: DatabaseColorValue): number {\n\tif (left.value < right.value) return -1\n\tif (left.value > right.value) return 1\n\treturn 0\n}\n\n/**\n * DatabaseDateValue\n */\n\nfunction readDate(reader: BufferReader): DatabaseDateValue {\n\tconst timestamp = reader.readInt64()\n\tconst date = new Date(timestamp)\n\n\treturn {\n\t\ttype: ControlType.Date,\n\t\tvalue: date.toISOString(),\n\t}\n}\n\nfunction writeDate(writer: BufferWriter, value: DatabaseDateValue): void {\n\tconst date = new Date(value.value)\n\tconst timestamp = date.getTime()\n\twriter.writeInt64(timestamp)\n}\n\nfunction compareDate(left: DatabaseDateValue, right: DatabaseDateValue): number {\n\tconst leftDate = new Date(left.value)\n\tconst rightDate = new Date(right.value)\n\tif (leftDate < rightDate) return -1\n\tif (leftDate > rightDate) return 1\n\treturn 0\n}\n\n/**\n * DatabaseEnumValue\n */\n\nfunction readEnum(reader: BufferReader): DatabaseEnumValue {\n\treturn {\n\t\ttype: ControlType.Enum,\n\t\tvalue: reader.readString(),\n\t}\n}\n\nfunction writeEnum(writer: BufferWriter, value: DatabaseEnumValue): void {\n\twriter.writeString(value.value)\n}\n\nfunction compareEnum(left: DatabaseEnumValue, right: DatabaseEnumValue): number {\n\tif (left.value < right.value) return -1\n\tif (left.value > right.value) return 1\n\treturn 0\n}\n\n/**\n * DatabaseFileValue\n */\n\nfunction readFile(reader: BufferReader): DatabaseFileValue {\n\treturn {\n\t\ttype: ControlType.File,\n\t\tvalue: reader.readString(),\n\t}\n}\n\nfunction writeFile(writer: BufferWriter, value: DatabaseFileValue): void {\n\twriter.writeString(value.value)\n}\n\nfunction compareFile(left: DatabaseFileValue, right: DatabaseFileValue): number {\n\tif (left.value < right.value) return -1\n\tif (left.value > right.value) return 1\n\treturn 0\n}\n\n/**\n * DatabaseLinkValue\n */\n\nfunction readLink(reader: BufferReader): DatabaseLinkValue {\n\treturn {\n\t\ttype: ControlType.Link,\n\t\tvalue: reader.readJson(),\n\t}\n}\n\nfunction writeLink(writer: BufferWriter, value: DatabaseLinkValue): void {\n\twriter.writeJson(value.value)\n}\n\nfunction compareLink(left: DatabaseLinkValue, right: DatabaseLinkValue): number {\n\tconst leftEncoded = JSON.stringify(left.value)\n\tconst rightEncoded = JSON.stringify(right.value)\n\tif (leftEncoded < rightEncoded) return -1\n\tif (leftEncoded > rightEncoded) return 1\n\treturn 0\n}\n\n/**\n * DatabaseNumberValue\n */\n\nfunction readNumber(reader: BufferReader): DatabaseNumberValue {\n\treturn {\n\t\ttype: ControlType.Number,\n\t\tvalue: reader.readFloat64(),\n\t}\n}\n\nfunction writeNumber(writer: BufferWriter, value: DatabaseNumberValue): void {\n\twriter.writeFloat64(value.value)\n}\n\nfunction compareNumber(left: DatabaseNumberValue, right: DatabaseNumberValue): number {\n\tif (left.value < right.value) return -1\n\tif (left.value > right.value) return 1\n\treturn 0\n}\n\n/**\n * DatabaseObjectValue\n */\n\nfunction readObject(reader: BufferReader): DatabaseObjectValue {\n\tconst length = reader.readUint16()\n\tconst result: Record<string, DatabaseValue> = {}\n\n\tfor (let i = 0; i < length; i++) {\n\t\tconst key = reader.readString()\n\t\tresult[key] = DatabaseValueModel.read(reader)\n\t}\n\n\treturn {\n\t\ttype: ControlType.Object,\n\t\tvalue: result,\n\t}\n}\n\nfunction writeObject(writer: BufferWriter, value: DatabaseObjectValue): void {\n\tconst entries = Object.entries(value.value)\n\twriter.writeUint16(entries.length)\n\n\tfor (const [key, item] of entries) {\n\t\twriter.writeString(key)\n\t\tDatabaseValueModel.write(writer, item)\n\t}\n}\n\nfunction compareObject(left: DatabaseObjectValue, right: DatabaseObjectValue, collation: DatabaseCollation): number {\n\tconst leftKeys = Object.keys(left.value).sort()\n\tconst rightKeys = Object.keys(right.value).sort()\n\n\tif (leftKeys.length < rightKeys.length) return -1\n\tif (leftKeys.length > rightKeys.length) return 1\n\n\tfor (let i = 0; i < leftKeys.length; i++) {\n\t\t// biome-ignore lint/style/noNonNullAssertion: Guaranteed by the loop.\n\t\tconst leftKey = leftKeys[i]!\n\t\t// biome-ignore lint/style/noNonNullAssertion: Guaranteed by the loop.\n\t\tconst rightKey = rightKeys[i]!\n\n\t\tif (leftKey < rightKey) return -1\n\t\tif (leftKey > rightKey) return 1\n\n\t\tconst leftValue = left.value[leftKey] ?? null\n\t\tconst rightValue = right.value[rightKey] ?? null\n\n\t\tconst result = DatabaseValueModel.compare(leftValue, rightValue, collation)\n\t\tif (result !== 0) return result\n\t}\n\n\treturn 0\n}\n\n/**\n * DatabaseResponsiveImageValue\n */\n\nfunction readResponsiveImage(reader: BufferReader): DatabaseResponsiveImageValue {\n\treturn {\n\t\ttype: ControlType.ResponsiveImage,\n\t\tvalue: reader.readJson(),\n\t}\n}\n\nfunction writeResponsiveImage(writer: BufferWriter, value: DatabaseResponsiveImageValue): void {\n\twriter.writeJson(value.value)\n}\n\nfunction compareResponsiveImage(left: DatabaseResponsiveImageValue, right: DatabaseResponsiveImageValue): number {\n\tconst leftEncoded = JSON.stringify(left.value)\n\tconst rightEncoded = JSON.stringify(right.value)\n\tif (leftEncoded < rightEncoded) return -1\n\tif (leftEncoded > rightEncoded) return 1\n\treturn 0\n}\n\n/**\n * DatabaseRichTextValue\n */\n\nfunction readRichText(reader: BufferReader): DatabaseRichTextValue {\n\tconst type = reader.readInt8()\n\n\tif (type === 0) {\n\t\treturn {\n\t\t\ttype: ControlType.RichText,\n\t\t\tvalue: reader.readUint32(),\n\t\t}\n\t}\n\n\tif (type === 1) {\n\t\treturn {\n\t\t\ttype: ControlType.RichText,\n\t\t\tvalue: reader.readString(),\n\t\t}\n\t}\n\n\tthrow new Error(`Invalid rich text pointer`)\n}\n\nfunction writeRichText(writer: BufferWriter, value: DatabaseRichTextValue): void {\n\tif (isNumber(value.value)) {\n\t\twriter.writeInt8(0)\n\t\twriter.writeUint32(value.value)\n\t\treturn\n\t}\n\n\tif (isString(value.value)) {\n\t\twriter.writeInt8(1)\n\t\twriter.writeString(value.value)\n\t\treturn\n\t}\n\n\tthrow new Error(`Invalid rich text pointer`)\n}\n\nfunction compareRichText(left: DatabaseRichTextValue, right: DatabaseRichTextValue): number {\n\tconst leftValue = left.value\n\tconst rightValue = right.value\n\n\tif (isNumber(leftValue) && isNumber(rightValue)) {\n\t\tif (leftValue < rightValue) return -1\n\t\tif (leftValue > rightValue) return 1\n\t\treturn 0\n\t}\n\n\tif (isString(leftValue) && isString(rightValue)) {\n\t\tif (leftValue < rightValue) return -1\n\t\tif (leftValue > rightValue) return 1\n\t\treturn 0\n\t}\n\n\tthrow new Error(`Invalid rich text pointer`)\n}\n\n/**\n * DatabaseStringValue\n */\n\nfunction readString(reader: BufferReader): DatabaseStringValue {\n\treturn {\n\t\ttype: ControlType.String,\n\t\tvalue: reader.readString(),\n\t}\n}\n\nfunction writeString(writer: BufferWriter, value: DatabaseStringValue): void {\n\twriter.writeString(value.value)\n}\n\nfunction compareString(left: DatabaseStringValue, right: DatabaseStringValue, collation: DatabaseCollation): number {\n\tlet leftValue = left.value\n\tlet rightValue = right.value\n\n\tif (collation.type === DatabaseCollationType.CaseInsensitive) {\n\t\tleftValue = left.value.toLowerCase()\n\t\trightValue = right.value.toLowerCase()\n\t}\n\n\tif (leftValue < rightValue) return -1\n\tif (leftValue > rightValue) return 1\n\treturn 0\n}\n\n/**\n * DatabaseVectorSetItemValue\n */\n\nfunction readVectorSetItem(reader: BufferReader): DatabaseVectorSetItemValue {\n\treturn {\n\t\ttype: ControlType.VectorSetItem,\n\t\tvalue: reader.readUint32(),\n\t}\n}\n\nfunction writeVectorSetItem(writer: BufferWriter, value: DatabaseVectorSetItemValue): void {\n\twriter.writeUint32(value.value as number)\n}\n\nfunction compareVectorSetItem(left: DatabaseVectorSetItemValue, right: DatabaseVectorSetItemValue): number {\n\tconst leftValue = left.value as number\n\tconst rightValue = right.value as number\n\tif (leftValue < rightValue) return -1\n\tif (leftValue > rightValue) return 1\n\treturn 0\n}\n", "import type { DatabaseValue } from \"library/modules/cms/DatabaseValue.ts\"\nimport type { DatabaseCollation } from \"library/modules/cms/types.ts\"\nimport { BufferReader } from \"../BufferReader.ts\"\nimport { BufferWriter } from \"../BufferWriter.ts\"\nimport type { DatabaseIndexModel } from \"./DatabaseIndexModel.ts\"\nimport type { DatabaseItemModel } from \"./DatabaseItemModel.ts\"\nimport { DatabaseItemPointerModel } from \"./DatabaseItemPointerModel.ts\"\nimport { DatabaseValueModel } from \"./DatabaseValueModel.ts\"\n\nexport interface DatabaseDictionaryIndexEntry {\n\tvalues: DatabaseValue[]\n\tpointer: DatabaseItemPointerModel\n}\n\n/**\n * A simple index that is a map of values to lists of item pointers.\n *\n * ```text\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 Type     \u2502 Description                            \u2502\n * \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n * \u2502 JSON     \u2502 The collation being used for the index \u2502\n * \u2502 Uint8    \u2502 The number of indexed fields           \u2502\n * \u2502 String[] \u2502 Names of indexed fields                \u2502\n * \u2502 Uint32   \u2502 The number of entries in the index     \u2502\n * \u2502 Entry[]  \u2502 List of entries in the index           \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * ```\n *\n * Each entry consists of a value and a list of item pointers that have that\n * value.\n *\n * ```text\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 Type                     \u2502 Description                   \u2502\n * \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n * \u2502 DatabaseValueModel[]     \u2502 The field values of the entry \u2502\n * \u2502 DatabaseItemPointerModel \u2502 The item pointer              \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * ```\n */\nexport class DatabaseDictionaryIndexModel implements DatabaseIndexModel {\n\tconstructor(\n\t\treadonly fieldNames: string[],\n\t\treadonly options: { collation: DatabaseCollation },\n\t) {}\n\n\treadonly entries: DatabaseDictionaryIndexEntry[] = []\n\n\tsortEntries() {\n\t\tthis.entries.sort((left, right) => {\n\t\t\tfor (let i = 0; i < this.fieldNames.length; i++) {\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: Guaranteed by the `addItem` method.\n\t\t\t\tconst leftValue = left.values[i]!\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: Guaranteed by the `addItem` method.\n\t\t\t\tconst rightValue = right.values[i]!\n\n\t\t\t\tconst result = DatabaseValueModel.compare(leftValue, rightValue, this.options.collation)\n\t\t\t\tif (result !== 0) return result\n\t\t\t}\n\n\t\t\treturn left.pointer.compare(right.pointer)\n\t\t})\n\t}\n\n\tstatic deserialize(bytes: Uint8Array) {\n\t\tconst reader = new BufferReader(bytes)\n\n\t\tconst collation = reader.readJson<DatabaseCollation>()\n\t\tconst fieldCount = reader.readUint8()\n\t\tconst fieldNames: string[] = []\n\n\t\tfor (let i = 0; i < fieldCount; i++) {\n\t\t\tconst fieldName = reader.readString()\n\t\t\tfieldNames.push(fieldName)\n\t\t}\n\n\t\tconst index = new DatabaseDictionaryIndexModel(fieldNames, {\n\t\t\tcollation,\n\t\t})\n\n\t\tconst entryCount = reader.readUint32()\n\t\tfor (let i = 0; i < entryCount; i++) {\n\t\t\tconst values: DatabaseValue[] = []\n\n\t\t\tfor (let j = 0; j < fieldCount; j++) {\n\t\t\t\tconst fieldValue = DatabaseValueModel.read(reader)\n\t\t\t\tvalues.push(fieldValue)\n\t\t\t}\n\n\t\t\tconst pointer = DatabaseItemPointerModel.read(reader)\n\n\t\t\tindex.entries.push({ values, pointer })\n\t\t}\n\n\t\treturn index\n\t}\n\n\tserialize() {\n\t\tconst writer = new BufferWriter()\n\n\t\twriter.writeJson(this.options.collation)\n\t\twriter.writeUint8(this.fieldNames.length)\n\n\t\tfor (const fieldName of this.fieldNames) {\n\t\t\twriter.writeString(fieldName)\n\t\t}\n\n\t\t// Before serializing the entries we sort them to ensure that the entries are in the correct\n\t\t// order when deserializing the model. This allows us to use binary search in the\n\t\t// `DatabaseDictionaryIndex.ts`.\n\t\tthis.sortEntries()\n\n\t\twriter.writeUint32(this.entries.length)\n\n\t\tfor (const entry of this.entries) {\n\t\t\tconst { values, pointer } = entry\n\n\t\t\tfor (const value of values) {\n\t\t\t\tDatabaseValueModel.write(writer, value)\n\t\t\t}\n\n\t\t\tpointer.write(writer)\n\t\t}\n\n\t\treturn writer.subarray()\n\t}\n\n\taddItem(item: DatabaseItemModel, pointer: DatabaseItemPointerModel) {\n\t\tconst values = this.fieldNames.map(fieldName => {\n\t\t\treturn item.getField(fieldName) ?? null\n\t\t})\n\n\t\tthis.entries.push({ values, pointer })\n\t}\n}\n", "import type { DatabaseValue } from \"library/modules/cms/DatabaseValue.ts\"\nimport type { BufferReader } from \"../BufferReader.ts\"\nimport type { BufferWriter } from \"../BufferWriter.ts\"\nimport { DatabaseValueModel } from \"./DatabaseValueModel.ts\"\n\n/**\n * A single item in the database.\n *\n * ```text\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 Type                 \u2502 Description          \u2502\n * \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n * \u2502 Uint8                \u2502 Number of fields     \u2502\n * \u2502 DatabaseValueModel[] \u2502 List of field values \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * ```\n */\nexport class DatabaseItemModel {\n\tprivate fields = new Map<string, DatabaseValue>()\n\n\tstatic read(reader: BufferReader) {\n\t\tconst item = new DatabaseItemModel()\n\n\t\tconst fieldCount = reader.readUint16()\n\n\t\tfor (let i = 0; i < fieldCount; i++) {\n\t\t\tconst key = reader.readString()\n\t\t\tconst value = DatabaseValueModel.read(reader)\n\t\t\titem.setField(key, value)\n\t\t}\n\n\t\treturn item\n\t}\n\n\twrite(writer: BufferWriter) {\n\t\twriter.writeUint16(this.fields.size)\n\n\t\tfor (const [key, value] of this.fields) {\n\t\t\twriter.writeString(key)\n\t\t\tDatabaseValueModel.write(writer, value)\n\t\t}\n\t}\n\n\tgetData() {\n\t\tconst data: Record<string, DatabaseValue> = {}\n\n\t\tfor (const [key, value] of this.fields) {\n\t\t\tdata[key] = value\n\t\t}\n\n\t\treturn data\n\t}\n\n\tsetField(key: string, value: DatabaseValue) {\n\t\tthis.fields.set(key, value)\n\t}\n\n\tgetField(key: string) {\n\t\treturn this.fields.get(key)\n\t}\n}\n", "import { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\n\n/**\n * This function replaces the normal module URL with the CMS module URL for\n * binary files. We have to do this at runtime because we don't know the\n * moduleId of the CMS module when generating the module for the first time.\n *\n * Normal module files are served under:\n * https://framerusercontent.com/modules/<moduleId>/<saveId>/<filename>\n *\n * Binary files for the CMS are served under:\n * https://framerusercontent.com/cms/<moduleId>/<saveId>/<filename>\n *\n * This way we can handle range queries using the \"server-cms-files\" Lambda and\n * compress the response on the backend with Cloudfront.\n */\nexport function replaceBinaryModuleUrls(url: SafeJS) {\n\treturn js`${url}.replace(\"/modules/\", \"/cms/\")`\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { assert, ModuleType, getLogger, localModuleIdForStableName } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport { SerializableObject, SortBehavior, isSafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { MakeSerializable } from \"code-generation/types.ts\"\nimport type { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport type { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport type { ColorCollector } from \"code-generation/utils/CSSVariableDefinitionCollector.ts\"\nimport type { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport { getIncludedLocales } from \"document/components/chrome/localization/includedLocales.ts\"\nimport type { CanvasTree, CollectionNode } from \"document/models/CanvasTree/index.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport {\n\tcreatedAtVariableId,\n\tnextItemVariableId,\n\tpreviousItemVariableId,\n\tupdatedAtVariableId,\n} from \"document/utils/CollectionItemVariables.ts\"\nimport type { LinkToWebPage } from \"library/modules/LinkToWebPage.ts\"\nimport type {\n\tDatabaseCollectionByLocaleId,\n\tDatabaseSchema,\n\tLocalizedDatabaseCollection,\n} from \"library/modules/cms/types.ts\"\nimport { DatabaseCollationType } from \"library/modules/cms/types.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { framerCmsExtension } from \"modules/binaryAssets.ts\"\nimport type { Mutable } from \"utils/Mutable.ts\"\nimport { getRouterLocales } from \"utils/getRouterLocales.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport type { BinaryAssetCollector } from \"../BinaryAssetCollector.ts\"\nimport type { SubmoduleCollector } from \"../GeneratedSubmodule.ts\"\nimport { getControlType } from \"../createControlsTypesAndReactProps.ts\"\nimport { RichTextJsonCollector } from \"./RichTextJsonCollector.ts\"\nimport { VectorCollector } from \"./VectorCollector.ts\"\nimport { getDataView } from \"./bundled/BufferReader.ts\"\nimport { BufferWriter } from \"./bundled/BufferWriter.ts\"\nimport type { DatabaseOptions } from \"./bundled/DatabaseCollection.ts\"\nimport DatabaseCollectionSource from \"./bundled/DatabaseCollection.ts?bundle\"\nimport type { DatabaseDictionaryIndexOptions } from \"./bundled/DatabaseDictionaryIndex.ts\"\nimport DraftDatabaseCollectionSource from \"./bundled/DraftDatabaseCollection.ts?bundle\"\nimport { DatabaseDictionaryIndexModel } from \"./bundled/models/DatabaseDictionaryIndexModel.ts\"\nimport type { DatabaseIndexModel } from \"./bundled/models/DatabaseIndexModel.ts\"\nimport { DatabaseItemModel } from \"./bundled/models/DatabaseItemModel.ts\"\nimport { DatabaseItemPointerModel } from \"./bundled/models/DatabaseItemPointerModel.ts\"\nimport type { Range } from \"./bundled/rangeRequest.ts\"\nimport { collectionIdKey } from \"./dataIdKeys.ts\"\nimport { getCollectionControlProp, getVariableMap } from \"./getCollectionControlProp.ts\"\nimport type { DatabaseValueResolvers } from \"./getDatabaseValue.ts\"\nimport { getDatabaseValue } from \"./getDatabaseValue.ts\"\nimport { getDatabaseValueDefinition } from \"./getDatabaseValueDefinition.ts\"\nimport { replaceBinaryModuleUrls } from \"./replaceBinaryModuleUrls.ts\"\n\nconst log = getLogger(\"serializeDatabase\")\n\n// This matches the limit as set by the ModulesService:\n// https://github.com/framer/FramerModulesService/blob/master/controllers/metadata/file.go#L8\nconst FILE_SIZE_LIMIT = 4 * 1024 * 1024\n\nconst TABLE_SCAN_FALLBACK_SIZE = 5_000\n\ninterface IndexChunkEntry {\n\tmodel: DatabaseIndexModel\n\tbytes: Uint8Array\n}\n\n/**\n * Serialize a collection to a collection database.\n *\n * This converts a collection node into a collection database module that\n * implements the `LocalizedDatabaseCollection` interface. This is made up\n * of data chunk files and a series of indexes.\n *\n * Data chunks are created with the following format:\n *\n * ```text\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 Type                \u2502 Description     \u2502\n * \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n * \u2502 Uint32              \u2502 Number of items \u2502\n * \u2502 DatabaseItemModel[] \u2502 List of items   \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * ```\n */\nexport async function serializeDatabase(\n\tcollectionNode: CollectionNode,\n\tcomponentLoader: ComponentLoader,\n\ttree: CanvasTree,\n\tmodulesStore: ModulesStore,\n\tsubmodules: SubmoduleCollector,\n\tbinaryAssets: BinaryAssetCollector,\n\timports: ImportCollector,\n\tassets: AssetCollector,\n\tlinks: LinkCollector,\n\tbindings: BindingCollector,\n\tdeclarations: FileDeclarationCollector,\n\tcolors: ColorCollector,\n\tincludeDrafts: boolean,\n) {\n\tconst richTexts = new RichTextJsonCollector(\n\t\tcollectionNode,\n\t\tcomponentLoader,\n\t\ttree,\n\t\timports,\n\t\tsubmodules,\n\t\tbindings,\n\t\tdeclarations,\n\t\tassets,\n\t\tlinks,\n\t)\n\n\tconst propertyControls = collectionNode.getPropertyControls(tree, componentLoader)\n\tconst controlEntries = Object.entries(propertyControls)\n\n\t// To allow previewing translated content from the CMS on the canvas,\n\t// draft locales are always included. However, draft locales cannot be\n\t// active on a published site, so they won't be visible to visitors.\n\tconst locales = getRouterLocales(tree, \"includeDrafts\")\n\n\tconst schema: Mutable<MakeSerializable<DatabaseSchema>> = {\n\t\t[collectionIdKey]: {\n\t\t\ttype: getControlType(ControlType.String, imports),\n\t\t\tisNullable: false,\n\t\t},\n\t\t[createdAtVariableId]: {\n\t\t\ttype: getControlType(ControlType.Date, imports),\n\t\t\tisNullable: true,\n\t\t},\n\t\t[updatedAtVariableId]: {\n\t\t\ttype: getControlType(ControlType.Date, imports),\n\t\t\tisNullable: true,\n\t\t},\n\t\t[previousItemVariableId]: {\n\t\t\ttype: getControlType(ControlType.String, imports),\n\t\t\tisNullable: true,\n\t\t},\n\t\t[nextItemVariableId]: {\n\t\t\ttype: getControlType(ControlType.String, imports),\n\t\t\tisNullable: true,\n\t\t},\n\t}\n\n\tfunction resolveType<Type extends ControlType>(type: Type) {\n\t\treturn getControlType(type, imports) as unknown as Type\n\t}\n\n\tfor (const [key, control] of controlEntries) {\n\t\tconst definition = getDatabaseValueDefinition(control, resolveType)\n\t\tif (!definition) continue\n\n\t\tschema[key] = definition\n\t}\n\n\tconst schemaBinding = declarations.dedupe(\"schema\", new SerializableObject(schema, SortBehavior.Sorted))\n\n\tconst variableMap = getVariableMap(collectionNode.variables)\n\n\tconst slugVariable = collectionNode.getSlugVariable()\n\n\tconst DatabaseCollectionSubmodule = submodules.create(DatabaseCollectionSource)\n\n\tlet originalCollectionByLocaleId: SafeJS | undefined\n\tlet DraftDatabaseCollectionBinding: SafeJS | undefined\n\n\tconst draftStatus: true | undefined = includeDrafts ? true : undefined\n\tconst filteredItems = collectionNode.getSortedChildren(\"public-only\", \"group-drafts\").filter(collectionItemNode => {\n\t\treturn collectionItemNode.isDraft === draftStatus\n\t})\n\n\t// We need a UUID instead of e.g. projectId+collectionNode.id so that multiple versions of the\n\t// same collection in the same project don't cause mismatches.\n\t// See https://framer-team.slack.com/archives/C068W7EDVMY/p1758215511640599?thread_ts=1757690765.437629&cid=C068W7EDVMY\n\tconst newCollectionId = crypto.randomUUID()\n\n\tif (includeDrafts) {\n\t\tconst collectionModuleId = localModuleIdForStableName(ModuleType.Collection, collectionNode.id)\n\t\toriginalCollectionByLocaleId = js`${imports.addImport(`../${collectionModuleId}`, {\n\t\t\texportSpecifier: \"default\",\n\t\t\timportBinding: \"originalCollection\",\n\t\t})}.collectionByLocaleId`\n\n\t\tif (filteredItems.length === 0) {\n\t\t\t// Re-export the original collection if there are no draft items\n\t\t\tconst options: MakeSerializable<LocalizedDatabaseCollection> = {\n\t\t\t\tid: newCollectionId,\n\t\t\t\tdisplayName: collectionNode.resolveValue(\"name\") ?? Dictionary.Unknown,\n\t\t\t\tcollectionByLocaleId: originalCollectionByLocaleId,\n\t\t\t}\n\t\t\treturn js`${options}`\n\t\t}\n\n\t\tconst DraftDatabaseCollectionSubmodule = submodules.create(DraftDatabaseCollectionSource)\n\t\tDraftDatabaseCollectionBinding = imports.addImport(DraftDatabaseCollectionSubmodule.submoduleImport, {\n\t\t\texportSpecifier: \"DraftDatabaseCollection\",\n\t\t})\n\t}\n\n\tconst DatabaseCollectionBinding = imports.addImport(DatabaseCollectionSubmodule.submoduleImport, {\n\t\texportSpecifier: \"DatabaseCollection\",\n\t})\n\n\tconst collectionByLocaleId = {} as Mutable<MakeSerializable<DatabaseCollectionByLocaleId>>\n\n\tfor (const locale of locales) {\n\t\tconst indexes: DatabaseIndexModel[] = [\n\t\t\tnew DatabaseDictionaryIndexModel([collectionIdKey], {\n\t\t\t\tcollation: {\n\t\t\t\t\ttype: DatabaseCollationType.CaseSensitive,\n\t\t\t\t},\n\t\t\t}),\n\t\t\tnew DatabaseDictionaryIndexModel([previousItemVariableId], {\n\t\t\t\tcollation: {\n\t\t\t\t\ttype: DatabaseCollationType.CaseSensitive,\n\t\t\t\t},\n\t\t\t}),\n\t\t\tnew DatabaseDictionaryIndexModel([nextItemVariableId], {\n\t\t\t\tcollation: {\n\t\t\t\t\ttype: DatabaseCollationType.CaseSensitive,\n\t\t\t\t},\n\t\t\t}),\n\t\t]\n\n\t\tif (slugVariable) {\n\t\t\tindexes.push(\n\t\t\t\tnew DatabaseDictionaryIndexModel([collectionIdKey, slugVariable.id], {\n\t\t\t\t\tcollation: {\n\t\t\t\t\t\ttype: DatabaseCollationType.CaseSensitive,\n\t\t\t\t\t},\n\t\t\t\t}),\n\n\t\t\t\tnew DatabaseDictionaryIndexModel([slugVariable.id, collectionIdKey], {\n\t\t\t\t\tcollation: {\n\t\t\t\t\t\ttype: DatabaseCollationType.CaseSensitive,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\n\t\tfor (const [fieldName] of controlEntries) {\n\t\t\t// We include all rich text fields in all indexes so that we can\n\t\t\t// resolve rich text in parallel to resolving the items themselves.\n\t\t\tindexes.push(\n\t\t\t\tnew DatabaseDictionaryIndexModel([fieldName], {\n\t\t\t\t\tcollation: {\n\t\t\t\t\t\ttype: DatabaseCollationType.CaseInsensitive,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\n\t\tconst vectors = new VectorCollector()\n\n\t\tconst collectionItemNodes = filteredItems.filter(collectionItemNode => {\n\t\t\tconst includedLocales = getIncludedLocales(tree, collectionItemNode)\n\t\t\tif (!includedLocales) return true\n\t\t\treturn includedLocales.includes(locale.id)\n\t\t})\n\n\t\tconst databaseItems: DatabaseItemModel[] = []\n\n\t\tfor (let i = 0; i < collectionItemNodes.length; i++) {\n\t\t\tconst collectionItemNode = collectionItemNodes[i]\n\t\t\tassert(collectionItemNode, \"Node must exist\")\n\n\t\t\tconst item = new DatabaseItemModel()\n\n\t\t\titem.setField(collectionIdKey, {\n\t\t\t\ttype: ControlType.String,\n\t\t\t\tvalue: collectionItemNode.id,\n\t\t\t})\n\n\t\t\tconst createdAt = collectionItemNode.createdAt\n\t\t\tif (createdAt) {\n\t\t\t\titem.setField(createdAtVariableId, {\n\t\t\t\t\ttype: ControlType.Date,\n\t\t\t\t\tvalue: new Date(createdAt).toISOString(),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst updatedAt = collectionItemNode.updatedAt\n\t\t\tif (updatedAt) {\n\t\t\t\titem.setField(updatedAtVariableId, {\n\t\t\t\t\ttype: ControlType.Date,\n\t\t\t\t\tvalue: new Date(updatedAt).toISOString(),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst previousCollectionItemNode = collectionItemNodes[i - 1]\n\t\t\tif (previousCollectionItemNode) {\n\t\t\t\titem.setField(previousItemVariableId, {\n\t\t\t\t\ttype: ControlType.String,\n\t\t\t\t\tvalue: previousCollectionItemNode.id,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst nextCollectionItemNode = collectionItemNodes[i + 1]\n\t\t\tif (nextCollectionItemNode) {\n\t\t\t\titem.setField(nextItemVariableId, {\n\t\t\t\t\ttype: ControlType.String,\n\t\t\t\t\tvalue: nextCollectionItemNode.id,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst resolvers: DatabaseValueResolvers = {\n\t\t\t\tresolveColor(value) {\n\t\t\t\t\treturn colors.addColor(value)\n\t\t\t\t},\n\t\t\t\tresolveFile(identifier) {\n\t\t\t\t\treturn assets.resolve(identifier)?.src\n\t\t\t\t},\n\t\t\t\tresolveImage(identifier, focalPoint) {\n\t\t\t\t\treturn assets.resolveResponsiveImage(identifier, { focalPoint })\n\t\t\t\t},\n\t\t\t\tresolveLink(link) {\n\t\t\t\t\tconst resolved = links.create(link)\n\t\t\t\t\tif (isUndefined(resolved)) return\n\t\t\t\t\tif (isSafeJS(resolved)) return\n\n\t\t\t\t\treturn resolved as LinkToWebPage | string\n\t\t\t\t},\n\t\t\t\tresolveRichTextPointer(value) {\n\t\t\t\t\t// The pointer must be a string or a number, because we depend on it in\n\t\t\t\t\t// `DraftDatabaseCollection.ts`.\n\t\t\t\t\treturn richTexts.add(value)\n\t\t\t\t},\n\t\t\t\tresolveVectorSetItemPointer(identifier) {\n\t\t\t\t\t// The pointer must be a number, because we depend on it in\n\t\t\t\t\t// `DraftDatabaseCollection.ts`.\n\t\t\t\t\treturn vectors.add(identifier)\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tfor (const [key, control] of controlEntries) {\n\t\t\t\tconst controlProp = getCollectionControlProp(key, control, variableMap, propertyControls, collectionItemNode)\n\n\t\t\t\tif (isUndefined(controlProp)) continue\n\n\t\t\t\tconst value = getDatabaseValue({\n\t\t\t\t\tcontrol,\n\t\t\t\t\tcontrolProp,\n\t\t\t\t\tresolvers,\n\t\t\t\t\tlocale,\n\t\t\t\t})\n\n\t\t\t\tif (isUndefined(value)) continue\n\n\t\t\t\titem.setField(key, value)\n\t\t\t}\n\n\t\t\tdatabaseItems.push(item)\n\t\t}\n\n\t\tfunction newItemChunkWriter() {\n\t\t\tconst itemChunkWriter = new BufferWriter()\n\t\t\t// Leave space to write the chunk item count in finalizeChunk.\n\t\t\titemChunkWriter.writeUint32(0)\n\n\t\t\treturn itemChunkWriter\n\t\t}\n\n\t\tconst itemChunks: Uint8Array<ArrayBuffer>[] = []\n\t\tlet currentChunkItemCount = 0\n\t\tlet chunkWriter = newItemChunkWriter()\n\n\t\tfunction finalizeChunk(offset?: number) {\n\t\t\tconst chunk = chunkWriter.subarray(0, offset)\n\t\t\tconst view = getDataView(chunk)\n\t\t\tview.setUint32(0, currentChunkItemCount)\n\n\t\t\titemChunks.push(chunk)\n\t\t}\n\n\t\tfor (const itemModel of databaseItems) {\n\t\t\tlet offset = chunkWriter.getOffset()\n\t\t\titemModel.write(chunkWriter)\n\n\t\t\t// If the chunk is too big having added the new item then remove that item from the chunk\n\t\t\t// and push the chunk into the itemChunks array\n\t\t\tif (chunkWriter.getOffset() > FILE_SIZE_LIMIT) {\n\t\t\t\tfinalizeChunk(offset)\n\n\t\t\t\t// Create a fresh chunk and add the item that did not fit into the previous chunk\n\t\t\t\tchunkWriter = newItemChunkWriter()\n\t\t\t\toffset = chunkWriter.getOffset()\n\t\t\t\tcurrentChunkItemCount = 0\n\t\t\t\titemModel.write(chunkWriter)\n\t\t\t}\n\n\t\t\tcurrentChunkItemCount++\n\n\t\t\tconst itemLength = chunkWriter.getOffset() - offset\n\t\t\tconst pointer = new DatabaseItemPointerModel(itemChunks.length, offset, itemLength)\n\n\t\t\tfor (const index of indexes) {\n\t\t\t\tindex.addItem(itemModel, pointer)\n\t\t\t}\n\t\t}\n\n\t\tif (chunkWriter.getOffset() > 0) {\n\t\t\tfinalizeChunk()\n\t\t}\n\n\t\tconst DatabaseDictionaryIndexBinding = imports.addImport(DatabaseCollectionSubmodule.submoduleImport, {\n\t\t\texportSpecifier: \"DatabaseDictionaryIndex\",\n\t\t})\n\n\t\tconst uploadedChunks = itemChunks.map((buffer, index) =>\n\t\t\treplaceBinaryModuleUrls(binaryAssets.create(`chunk-${locale.id}-${index}`, framerCmsExtension, buffer)),\n\t\t)\n\n\t\tconst totalChunksBytes = itemChunks.reduce((total, chunk) => total + chunk.length, 0)\n\n\t\t// If the total size of all chunks is small, we clear all indexes so\n\t\t// that queries against the collection always fall back to using a\n\t\t// table scan. This is to avoid making multiple range requests into a\n\t\t// chunk when requesting the entire collection data in a single request\n\t\t// would still be a small request.\n\t\t// If we had better parallelized data fetching and batching of\n\t\t// requests, this would be unnecessary.\n\t\tif (totalChunksBytes < TABLE_SCAN_FALLBACK_SIZE && process.env.NODE_ENV !== \"test\") {\n\t\t\tindexes.length = 0\n\t\t}\n\n\t\tconst indexChunks: IndexChunkEntry[][] = []\n\t\tlet currentIndexChunkSize = Infinity\n\n\t\t// We don't want to create one file for each index because we currently\n\t\t// create (too) many indexes (one for each variable). But we can also\n\t\t// not create one large file for all indexes, because that would go over\n\t\t// the file limit in the backend. So we store as many indexes in a\n\t\t// single file until we hit the size limit in the backend.\n\t\tfor (const model of indexes) {\n\t\t\tconst bytes = model.serialize()\n\n\t\t\t// If the index is too large we skip it for now. This only has a negative effect if the\n\t\t\t// user is querying the collection by a field contained in the index as we have to fall\n\t\t\t// back to a full table scan.\n\t\t\tif (bytes.length >= FILE_SIZE_LIMIT) {\n\t\t\t\tlog.warn(\"Skipping index:\", bytes.length)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (currentIndexChunkSize + bytes.length > FILE_SIZE_LIMIT) {\n\t\t\t\tindexChunks.push([])\n\t\t\t\tcurrentIndexChunkSize = 0\n\t\t\t}\n\n\t\t\tconst chunk = indexChunks.at(-1)\n\t\t\tassert(chunk, \"Chunk must exist\")\n\n\t\t\tchunk.push({ model, bytes })\n\t\t\tcurrentIndexChunkSize += bytes.length\n\t\t}\n\n\t\tconst uploadedIndexes: SafeJS[] = []\n\n\t\tfor (let chunkIndex = 0; chunkIndex < indexChunks.length; chunkIndex++) {\n\t\t\tconst chunk = indexChunks[chunkIndex]\n\t\t\tassert(chunk, \"Chunk must exist\")\n\n\t\t\tconst chunkWriter = new BufferWriter()\n\t\t\tconst ranges: Range[] = []\n\n\t\t\tfor (const { bytes } of chunk) {\n\t\t\t\tconst from = chunkWriter.getOffset()\n\t\t\t\tchunkWriter.writeBytes(bytes)\n\t\t\t\tconst to = chunkWriter.getOffset()\n\t\t\t\tranges.push({ from, to })\n\t\t\t}\n\n\t\t\tconst chunkBytes = chunkWriter.subarray()\n\t\t\tconst chunkUrl = replaceBinaryModuleUrls(\n\t\t\t\tbinaryAssets.create(`indexes-${locale.id}-${chunkIndex}`, framerCmsExtension, chunkBytes),\n\t\t\t)\n\n\t\t\tconst chunkUploadedIndexes = chunk.map(({ model }, index): SafeJS => {\n\t\t\t\tif (model instanceof DatabaseDictionaryIndexModel) {\n\t\t\t\t\tconst range = ranges[index]\n\t\t\t\t\tassert(range, \"Can't find range for index\")\n\n\t\t\t\t\tconst options: MakeSerializable<DatabaseDictionaryIndexOptions> = {\n\t\t\t\t\t\turl: chunkUrl,\n\t\t\t\t\t\trange,\n\t\t\t\t\t\tfieldNames: declarations.dedupe(\"fieldNames\", model.fieldNames),\n\t\t\t\t\t\tcollation: declarations.dedupe(\"collation\", model.options.collation),\n\t\t\t\t\t\tcollectionSchema: schemaBinding,\n\t\t\t\t\t}\n\n\t\t\t\t\treturn js`new ${DatabaseDictionaryIndexBinding}(${options})`\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(\"Unsupported index type\")\n\t\t\t})\n\n\t\t\tuploadedIndexes.push(...chunkUploadedIndexes)\n\t\t}\n\n\t\tconst resolveVectorSetItem = vectors.serialize(componentLoader, modulesStore, declarations)\n\n\t\tconst options: MakeSerializable<DatabaseOptions> = {\n\t\t\tid: newCollectionId + locale.id,\n\t\t\tschema: schemaBinding,\n\t\t\tchunks: uploadedChunks,\n\t\t\tindexes: uploadedIndexes,\n\t\t\tresolveRichText: richTexts.resolveRichTextBinding,\n\t\t\tresolveVectorSetItem,\n\t\t}\n\n\t\tif (originalCollectionByLocaleId && DraftDatabaseCollectionBinding) {\n\t\t\tconst draftCollection = js`new ${DatabaseCollectionBinding}(${options})`\n\t\t\tconst originalCollection = js`${originalCollectionByLocaleId}[${locale.id}]`\n\t\t\tcollectionByLocaleId[locale.id] =\n\t\t\t\tjs`new ${DraftDatabaseCollectionBinding}(${draftCollection}, ${originalCollection}, ${previousItemVariableId}, ${nextItemVariableId})`\n\t\t} else {\n\t\t\tcollectionByLocaleId[locale.id] = js`new ${DatabaseCollectionBinding}(${options})`\n\t\t}\n\t}\n\n\trichTexts.serialize()\n\n\tconst options: MakeSerializable<LocalizedDatabaseCollection> = {\n\t\tid: newCollectionId,\n\t\tdisplayName: collectionNode.resolveValue(\"name\") ?? Dictionary.Unknown,\n\t\tcollectionByLocaleId,\n\t}\n\n\treturn js`${options}`\n}\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport { assert, ModuleType } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { jsdoc } from \"code-generation/js/jsdoc.ts\"\nimport { SafeJS, SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport type { MakeSerializable } from \"code-generation/types.ts\"\nimport { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport { ColorCollector } from \"code-generation/utils/CSSVariableDefinitionCollector.ts\"\nimport { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport {\n\tenumToDisplayNameFunctionsName,\n\tgetEnumToDisplayNameFunctionName,\n} from \"code-generation/utils/valueTransformCollector/functions/enumToDisplayName.ts\"\nimport { createEnumToDisplayNameFromVariable } from \"code-generation/utils/valueTransformCollector/functions/enumToDisplayNameFromVariable.ts\"\nimport type { CanvasTree, CollectionNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isCollectionNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { Locale } from \"document/models/CanvasTree/traits/WithLocales.ts\"\nimport type { VariablesAndDividers } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport type { Query } from \"library/modules/cms/types.ts\"\nimport { BinaryOperator } from \"library/modules/cms/types.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { getCollectionData, getModuleIdentifiersForCollection } from \"utils/collectionUtils.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport { BinaryAssetCollector } from \"./BinaryAssetCollector.ts\"\nimport type { SourceCodeWithArtifacts } from \"./GeneratedComponent.ts\"\nimport { sourceCodeSerializer } from \"./GeneratedComponent.ts\"\nimport { SubmoduleCollector } from \"./GeneratedSubmodule.ts\"\nimport { collectionIdKey } from \"./cms/dataIdKeys.ts\"\nimport { serializeDatabase } from \"./cms/serializeDatabase.ts\"\nimport { serializePropertyControls } from \"./createControlsTypesAndReactProps.ts\"\nimport { ensureModulesAreLoaded } from \"./helpers/ensureModulesAreLoaded.ts\"\nimport type { ProcessDependencies } from \"./processNodes/types.ts\"\n\nexport const serializeCollection = sourceCodeSerializer<CollectionNode>(async (node, dependencies, _options) => {\n\treturn Promise.all([serialize(node.id, dependencies, false), serialize(node.id, dependencies, true)])\n})\n\nasync function serialize(\n\tsourceNodeId: NodeID,\n\tdependencies: ProcessDependencies,\n\tincludeDrafts: boolean,\n): Promise<SourceCodeWithArtifacts> {\n\tconst { componentLoader, modulesStore, tree, assetMap } = dependencies\n\n\tconst moduleType = includeDrafts ? ModuleType.DraftCollection : ModuleType.Collection\n\n\tconst assets = new AssetCollector(assetMap)\n\tconst binaryAssets = new BinaryAssetCollector(sourceNodeId)\n\tconst submodules = new SubmoduleCollector(moduleType, componentLoader, modulesStore, sourceNodeId)\n\n\tconst sourceNode = tree.getNodeWithTrait(sourceNodeId, isCollectionNode)\n\tassert(sourceNode, \"Must have a source node to serialize\")\n\tconst revision = sourceNode.moduleSourceRevision\n\n\tconst moduleIdentifiers = getModuleIdentifiersForCollection(sourceNode)\n\tawait ensureModulesAreLoaded(moduleIdentifiers, modulesStore, componentLoader)\n\n\tconst { module } = getCollectionData(componentLoader, modulesStore, sourceNode)\n\trecord(\"collection_update\", {\n\t\tmoduleId: module?.id,\n\t\trecordCount: sourceNode.getItemCount(),\n\t\tsource: \"unknown\",\n\t})\n\n\tconst slugKey = sourceNode.getSlugVariable()?.id\n\n\tconst bindings = new BindingCollector()\n\tconst imports = new ImportCollector(moduleType, componentLoader, modulesStore, bindings)\n\tconst declarations = new FileDeclarationCollector(bindings)\n\tconst links = new LinkCollector(sourceNode, componentLoader, imports, bindings, undefined, tree, modulesStore)\n\tconst colors = new ColorCollector()\n\n\tconst dataDeclaration = await serializeDatabase(\n\t\tsourceNode,\n\t\tcomponentLoader,\n\t\ttree,\n\t\tmodulesStore,\n\t\tsubmodules,\n\t\tbinaryAssets,\n\t\timports,\n\t\tassets,\n\t\tlinks,\n\t\tbindings,\n\t\tdeclarations,\n\t\tcolors,\n\t\tincludeDrafts,\n\t)\n\n\tconst annotations = jsdoc(\"\", {\n\t\t[AnnotationKey.FramerRecordIdKey]: collectionIdKey,\n\t\t[AnnotationKey.FramerSlug]: slugKey,\n\t\t[AnnotationKey.FramerEnumToDisplayNameUtils]: \"2\",\n\t\t[AnnotationKey.FramerCollectionUtils]: \"1\",\n\t\t[AnnotationKey.FramerCollectionId]: sourceNode.id,\n\t\t[AnnotationKey.FramerColorSyntax]: colors.hasColorsOfType(\"wideGamut\"),\n\t\t[AnnotationKey.FramerAutoSizeImages]: true,\n\t\t[AnnotationKey.FramerData]: true,\n\t})\n\n\tconst dataBinding = bindings.create(\"data\")\n\n\t// NOTE: This needs to be above `...imports.statements`.\n\tconst serializedPropertyControls = getSerializedPropertyControls(\n\t\tsourceNode,\n\t\tdataBinding,\n\t\ttree,\n\t\tcomponentLoader,\n\t\timports,\n\t\tmoduleType,\n\t)\n\n\tconst collectionUtilsBinding = getDatabaseCollectionUtils(\n\t\timports,\n\t\tdeclarations,\n\t\tdataBinding,\n\t\tcollectionIdKey,\n\t\tslugKey,\n\t)\n\n\tconst source = js.joinLines(\n\t\t...imports.statements,\n\t\t...declarations.list(),\n\t\tannotations,\n\t\tjs`const ${dataBinding} = ${dataDeclaration}`,\n\t\tjs`export default ${dataBinding}`,\n\t\tserializedPropertyControls,\n\t\t...getEnumToDisplayNameUtils(sourceNode.variables, tree.root.locales),\n\t\tcollectionUtilsBinding,\n\t)\n\n\treturn {\n\t\ttype: moduleType,\n\t\trevision,\n\t\tsource,\n\t\tartifacts: {\n\t\t\tassets: new Set(assets.keys),\n\t\t\tbinaryAssets: binaryAssets.assets,\n\t\t\tsubmodules: submodules.serialize(),\n\t\t\tmetrics: {\n\t\t\t\tnodes: sourceNode.getItemCount(),\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunction getEnumToDisplayNameUtils(variables: VariablesAndDividers, locales: readonly Locale[] | undefined): SafeJS[] {\n\tconst lines: SafeJS[] = []\n\n\tconst enumToDisplayNameFunctions = new SerializableObject()\n\n\tfor (const variable of variables) {\n\t\tif (variable.type !== ControlType.Enum) continue\n\n\t\tconst functionName = new SafeJS(getEnumToDisplayNameFunctionName(variable.id))\n\t\tlines.push(\n\t\t\tjs`export const ${functionName} = ${createEnumToDisplayNameFromVariable(variable, locales, functionName)};`,\n\t\t)\n\t\tenumToDisplayNameFunctions[variable.id] = functionName\n\t}\n\n\t// Should always be exported, even when the object is empty, because a previously exported enum\n\t// to display function name might still be used in another module.\n\tlines.push(js`export const ${new SafeJS(enumToDisplayNameFunctionsName)} = ${enumToDisplayNameFunctions};`)\n\n\treturn lines\n}\n\nfunction getDatabaseCollectionUtils(\n\timports: ImportCollector,\n\tdeclarations: FileDeclarationCollector,\n\tdataBinding: SafeJS,\n\tidKey: string,\n\tslugKey: string | undefined,\n) {\n\treturn js.joinLines(\n\t\tjs`export const utils = {`,\n\t\tjs`async getSlugByRecordId(id, locale) {`,\n\t\tslugKey ? getDatabaseCollectionSlugByRecordIdUtil(imports, declarations, dataBinding, idKey, slugKey) : undefined,\n\t\tjs`},`,\n\t\tjs`async getRecordIdBySlug(slug, locale) {`,\n\t\tslugKey ? getDatabaseCollectionRecordIdBySlugUtil(imports, declarations, dataBinding, idKey, slugKey) : undefined,\n\t\tjs`},`,\n\t\tjs`}`,\n\t)\n}\n\nfunction getQueryEngineBinding(imports: ImportCollector, declarations: FileDeclarationCollector) {\n\tconst QueryEngineBinding = imports.addImport(\"framer\", {\n\t\texportSpecifier: \"QueryEngine\",\n\t})\n\n\treturn declarations.dedupe(\"queryEngine\", js`new ${QueryEngineBinding}()`)\n}\n\nfunction getDatabaseCollectionSlugByRecordIdUtil(\n\timports: ImportCollector,\n\tdeclarations: FileDeclarationCollector,\n\tdataBinding: SafeJS,\n\tidKey: string,\n\tslugKey: string,\n) {\n\tconst queryEngineBinding = getQueryEngineBinding(imports, declarations)\n\n\tconst query: MakeSerializable<Query> = {\n\t\tfrom: {\n\t\t\ttype: \"Collection\",\n\t\t\tdata: dataBinding as any,\n\t\t},\n\t\tselect: [\n\t\t\t{\n\t\t\t\ttype: \"Identifier\",\n\t\t\t\tname: slugKey,\n\t\t\t},\n\t\t],\n\t\twhere: {\n\t\t\ttype: \"BinaryOperation\",\n\t\t\toperator: BinaryOperator.Equals,\n\t\t\tleft: {\n\t\t\t\ttype: \"Identifier\",\n\t\t\t\tname: idKey,\n\t\t\t},\n\t\t\tright: {\n\t\t\t\ttype: \"LiteralValue\",\n\t\t\t\tvalue: js`id`,\n\t\t\t},\n\t\t},\n\t\tlimit: {\n\t\t\ttype: \"LiteralValue\",\n\t\t\tvalue: 1,\n\t\t},\n\t} satisfies Query as any // TODO: Add support for discriminated unions to MakeSerializable.\n\n\treturn js.joinLines(\n\t\tjs`const [item] = await ${queryEngineBinding}.query(${query}, locale)`,\n\t\tjs`return item?.[${slugKey}]`,\n\t)\n}\n\nfunction getDatabaseCollectionRecordIdBySlugUtil(\n\timports: ImportCollector,\n\tdeclarations: FileDeclarationCollector,\n\tdataBinding: SafeJS,\n\tidKey: string,\n\tslugKey: string,\n) {\n\tconst queryEngineBinding = getQueryEngineBinding(imports, declarations)\n\n\tconst query: MakeSerializable<Query> = {\n\t\tfrom: {\n\t\t\ttype: \"Collection\",\n\t\t\tdata: dataBinding as any,\n\t\t},\n\t\tselect: [\n\t\t\t{\n\t\t\t\ttype: \"Identifier\",\n\t\t\t\tname: idKey,\n\t\t\t},\n\t\t],\n\t\twhere: {\n\t\t\ttype: \"BinaryOperation\",\n\t\t\toperator: BinaryOperator.Equals,\n\t\t\tleft: {\n\t\t\t\ttype: \"Identifier\",\n\t\t\t\tname: slugKey,\n\t\t\t},\n\t\t\tright: {\n\t\t\t\ttype: \"LiteralValue\",\n\t\t\t\tvalue: js`slug`,\n\t\t\t},\n\t\t},\n\t\tlimit: {\n\t\t\ttype: \"LiteralValue\",\n\t\t\tvalue: 1,\n\t\t},\n\t} satisfies Query as any // TODO: Add support for discriminated unions to MakeSerializable.\n\n\treturn js.joinLines(\n\t\tjs`const [item] = await ${queryEngineBinding}.query(${query}, locale)`,\n\t\tjs`return item?.[${idKey}]`,\n\t)\n}\n\nfunction getSerializedPropertyControls(\n\tcollectionNode: CollectionNode,\n\tdataBinding: SafeJS,\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\timports: ImportCollector,\n\tmoduleType: ModuleType,\n) {\n\tconst serializedControls = serializePropertyControls(\n\t\tcollectionNode,\n\t\tcomponentLoader,\n\t\ttree,\n\t\timports,\n\t\tundefined,\n\t\tmoduleType,\n\t\tScopeType.ContentManagement,\n\t)\n\tif (isUndefined(serializedControls)) return\n\n\tconst addPropertyControlsBinding = imports.addImport(\"framer\", {\n\t\texportSpecifier: \"addPropertyControls\",\n\t})\n\n\treturn SafeJS.fn(addPropertyControlsBinding, dataBinding, serializedControls)\n}\n", "import type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport type { FontDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport type { SerializableComponentFont } from \"code-generation/utils/FontCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { ComponentFontBundle } from \"library/utils/addFonts.ts\"\nimport { SafeJS } from \"../js/serializeJS.ts\"\n\ninterface SerializableComponentFontBundle extends Omit<ComponentFontBundle, \"fonts\"> {\n\tfonts: SerializableComponentFont[]\n}\n\nexport function serializeFonts({\n\tcomponentName,\n\tfontObjects,\n\tfontReferences,\n\timports,\n\tdeclarations,\n\tsharedFontArrays = [],\n}: {\n\tcomponentName: SafeJS\n\tfontObjects: Iterable<SerializableComponentFont>\n\tfontReferences: Map<string, SafeJS>\n\timports: ImportCollector\n\tdeclarations: FontDeclarationCollector\n\tsharedFontArrays?: SafeJS[]\n}) {\n\treturn js.joinLines(\n\t\t...declarations.list(),\n\t\tSafeJS.fn(\n\t\t\timports.addImport(\"framer\", { exportSpecifier: \"addFonts\" }),\n\t\t\tcomponentName,\n\t\t\tcreateFontsArray({\n\t\t\t\tfontObjects,\n\t\t\t\tfontReferences,\n\t\t\t\tsharedFontArrays,\n\t\t\t}),\n\t\t\t{ supportsExplicitInterCodegen: true },\n\t\t),\n\t)\n}\n\nexport function createFontsArray({\n\tfontObjects,\n\tfontReferences,\n\tsharedFontArrays = [],\n}: {\n\tfontObjects: Iterable<SerializableComponentFont>\n\tfontReferences: Map<string, SafeJS>\n\tsharedFontArrays?: SafeJS[]\n}): SerializableValue[] {\n\t// Array of (ComponentFontV1|ComponentFontBundle), or expressions which evaluate to (ComponentFontV1|ComponentFontBundle).\n\tconst fontsArray: SerializableValue[] = []\n\n\tconst fontBundle: SerializableComponentFontBundle = {\n\t\t// All modern code generations will explicitly include the Inter font when it\u2019s used.\n\t\texplicitInter: true,\n\t\tfonts: [],\n\t}\n\tfor (const font of fontObjects) {\n\t\ttry {\n\t\t\tnew URL(font.url)\n\t\t} catch (err: unknown) {\n\t\t\tthrow new Error(\n\t\t\t\t`Expected URL for font \"${font.uiFamilyName}\" to be a valid, absolute URL, but got: ${font.url}`,\n\t\t\t\t{ cause: err },\n\t\t\t)\n\t\t}\n\t\tfontBundle.fonts.push(font)\n\t}\n\t// Always emit the `explicitInter: true` font bundle, even if it\u2019s empty. This indicates\n\t// that the component or the shared font array we\u2019re creating here is modern and doesn\u2019t use Inter.\n\tfontsArray.push(fontBundle as unknown as SerializableValue)\n\n\tfor (const fontReference of fontReferences.values()) {\n\t\tfontsArray.push(js`...${fontReference}`)\n\t}\n\n\tfor (const fonts of sharedFontArrays) {\n\t\tfontsArray.push(js`...${fonts}`)\n\t}\n\n\treturn fontsArray\n}\n", "import { assert, ModuleType } from \"@framerjs/shared\"\nimport type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { SerializableObject } from \"code-generation/js/serializeJS.ts\"\nimport { PreloadCollector } from \"code-generation/loader/PreloadCollector.ts\"\nimport { AssetCollector } from \"code-generation/utils/AssetCollector.ts\"\nimport { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport { FileDeclarationCollector, FontDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport { FetchDataCollector } from \"code-generation/utils/FetchDataCollector.ts\"\nimport { FontCollector } from \"code-generation/utils/FontCollector.ts\"\nimport { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport { LinkCollector } from \"code-generation/utils/LinkCollector.ts\"\nimport { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport type { PresetsListNode } from \"document/models/CanvasTree/nodes/PresetsListNode.ts\"\nimport { filterComponentPresetControls } from \"document/models/controlProps/filterComponentPresetControls.ts\"\nimport { getControlPropValuesForCodeGeneration } from \"document/models/controlProps/getControlPropValuesForCodeGeneration.ts\"\nimport { getControlProps } from \"document/models/controlProps/getControlProps.ts\"\nimport { fontStore } from \"library/render/fonts/fontStore.ts\"\nimport { sourceCodeSerializer } from \"./GeneratedComponent.ts\"\nimport { ensureModulesAreLoaded } from \"./helpers/ensureModulesAreLoaded.ts\"\nimport { createFontsArray } from \"./serializeFonts.ts\"\n\nexport const serializeComponentPresets = sourceCodeSerializer<PresetsListNode>(\n\tasync (node, { componentLoader, assetMap, tree, modulesStore }) => {\n\t\tconst bindings = new BindingCollector()\n\t\tconst assets = new AssetCollector(assetMap)\n\t\tconst imports = new ImportCollector(ModuleType.ComponentPresets, componentLoader, modulesStore, bindings)\n\t\tconst links = new LinkCollector(node, componentLoader, imports, bindings, undefined, tree, modulesStore)\n\t\tconst declarations = new FileDeclarationCollector(bindings)\n\t\tconst variables = new VariableCollector(node, bindings)\n\t\tconst preload = new PreloadCollector(node, tree, variables, declarations, bindings, imports, assets)\n\t\tconst fetches = new FetchDataCollector(bindings, variables, preload, assets, links)\n\t\tconst revision = node.moduleSourceRevision\n\n\t\tconst presetProps: Record<string, SerializableValue> = {}\n\t\tconst presetFonts: Record<string, SerializableValue> = {}\n\n\t\tconst componentPresets = node.getComponentPresets()\n\n\t\tawait ensureModulesAreLoaded(\n\t\t\tcomponentPresets.map(node => node.componentIdentifier),\n\t\t\tmodulesStore,\n\t\t\tcomponentLoader,\n\t\t)\n\n\t\tconst fontBindings = new BindingCollector()\n\t\tconst fontDeclarations = new FontDeclarationCollector(fontBindings)\n\t\tfor (const presetNode of componentPresets) {\n\t\t\tconst component = componentLoader.reactComponentForIdentifier(presetNode.componentIdentifier)\n\t\t\tassert(component, \"Can't find react component for preset\")\n\n\t\t\tconst selectors = presetNode.getFontsForCodeGeneration(componentLoader)\n\t\t\tawait fontStore.loadFonts(selectors)\n\n\t\t\tconst fonts = new FontCollector(fontDeclarations)\n\n\t\t\tconst controlProps = getControlProps(\n\t\t\t\tfilterComponentPresetControls(component, \"onlyPresets\"),\n\t\t\t\tpresetNode.getRawControlProps(),\n\t\t\t)\n\n\t\t\tconst resolvedControlProps = getControlPropValuesForCodeGeneration(\n\t\t\t\tpresetNode,\n\t\t\t\tcomponent.properties,\n\t\t\t\tcontrolProps,\n\t\t\t\t{\n\t\t\t\t\tcontext: { assets, imports, links, fonts, fetches },\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tpresetProps[presetNode.id] = new SerializableObject(resolvedControlProps as Record<string, SerializableValue>)\n\n\t\t\tif (fonts.fontObjects.size > 0 || fonts.fontReferences.size > 0) {\n\t\t\t\tpresetFonts[presetNode.id] = createFontsArray({\n\t\t\t\t\tfontObjects: fonts.fontObjects,\n\t\t\t\t\tfontReferences: fonts.fontReferences,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\treturn [\n\t\t\t{\n\t\t\t\trevision,\n\t\t\t\ttype: ModuleType.ComponentPresets,\n\t\t\t\tsource: js.joinLines(\n\t\t\t\t\t...imports.statements,\n\t\t\t\t\tjs`export const props = ${presetProps}`,\n\t\t\t\t\t...fontDeclarations.list(),\n\t\t\t\t\tjs`export const fonts = ${presetFonts}`,\n\t\t\t\t),\n\t\t\t\tartifacts: {\n\t\t\t\t\tassets: assets.keys,\n\t\t\t\t\tmetrics: {\n\t\t\t\t\t\tnodes: Object.keys(presetProps).length,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t]\n\t},\n)\n", "import { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport {\n\tassert,\n\tModuleType,\n\tgetLogger,\n\tlocalModuleIdForStableName,\n\tlocalModuleIdentifierForStableName,\n} from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { jsdoc } from \"code-generation/js/jsdoc.ts\"\nimport type { NavigationRoutes } from \"code-generation/types.ts\"\nimport { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport { waitForLoadingComponentsWithTimeout } from \"code-generation/utils/waitForLoadingComponentsWithTimeout.ts\"\nimport type { CanvasPageNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { NodeLink } from \"document/stores/TreeIndex.ts\"\nimport { join } from \"utils/join.ts\"\nimport { SafeJS, serializeJS } from \"../js/serializeJS.ts\"\nimport { sourceCodeSerializer } from \"./GeneratedComponent.ts\"\n\nconst logger = getLogger(\"CodeGenerationStore\")\n\nconst enum Variable {\n\tPrototype = \"Prototype\",\n\tdefaultLayoutId = \"defaultLayoutId\",\n\tlayoutId = \"layoutId\",\n}\n\ntype NavigationChainMap = Record<NodeID, Set<NodeID>>\n\nfunction addToChain(id: NodeID, map: NavigationChainMap, chain: Set<NodeID>) {\n\tchain.add(id)\n\n\tmap[id]?.forEach(toNodeId => {\n\t\tif (chain.has(toNodeId)) return\n\t\taddToChain(toNodeId, map, chain)\n\t})\n\n\treturn chain\n}\n\n/**\n * Given a list of links from ground node to ground node, starting with the home\n * node id, create a Set of navigable nodes, starting from the home node\n * entrypoint.\n *\n * @TODO -- We should consider replacing `getNodesInPrototypeNavigationChain`\n * with this function. It requires less iterations since it leverages the links\n * from the tree index.\n */\nexport function getNavigableScreens(homeNodeId: NodeID, links: readonly NodeLink<NodeID, NodeID>[]): Set<NodeID> {\n\tconst map: NavigationChainMap = {}\n\n\tfor (const { fromNode, toNode } of links) {\n\t\tconst from = map[fromNode] ?? new Set()\n\t\tfrom.add(toNode)\n\t\tmap[fromNode] = from\n\t}\n\n\treturn addToChain(homeNodeId, map, new Set([homeNodeId]))\n}\n\nexport const serializePrototypeComponent = sourceCodeSerializer<CanvasPageNode>(\n\tasync (node, { componentLoader, tree, treeStore, modulesStore }) => {\n\t\tconst treeIndex = treeStore.treeIndex\n\t\tconst fullDisplayName = serializeJS(`Prototype/${node.name || \"Generated Prototype\"}`)\n\t\tconst homeNode = tree.get(node.homeNodeId)\n\t\tassert(homeNode, \"Can't serialize\", fullDisplayName, \": home node must exist.\")\n\t\tconst rect = tree.getRect(homeNode)\n\n\t\tconst importCollector = new ImportCollector(ModuleType.Prototype, componentLoader, modulesStore)\n\t\timportCollector.addImport(\"react\", { exportSpecifier: \"*\", importBinding: \"React\" })\n\t\timportCollector.addImport(\"framer-motion\", { exportSpecifier: \"LayoutGroup\" })\n\t\timportCollector.addImport(\"framer\", { exportSpecifier: \"PageRoot\" })\n\t\timportCollector.addImport(\"framer\", { exportSpecifier: \"useInitialRouteComponent\" })\n\n\t\t// This maps the Routes types, only with SafeJS as page instead of a component.\n\t\tconst routes: NavigationRoutes = {}\n\t\tfor (const screenId of getNavigableScreens(homeNode.id, treeIndex.getPrototypeScreenLinks(tree, node.id))) {\n\t\t\t// This is using internal knowledge on how the relative imports of\n\t\t\t// screens should be created. Ideally we would want to look the\n\t\t\t// screenId up in the ModulesStore, but because of asynchronicity\n\t\t\t// issues, the screen module might not exist at the point that we're\n\t\t\t// generating this prototype component\n\t\t\tconst screenModuleId = localModuleIdForStableName(ModuleType.Screen, screenId)\n\t\t\tconst importSpecifier = `../${screenModuleId}`\n\t\t\t// Screens are generated asynchronously and there is no contiguous/unbroken promise\n\t\t\t// chain to ensure that completes in time. However, making this lazy *happens* to give\n\t\t\t// screen generation enough time (screen generation is pretty quick\u2014we tested a very\n\t\t\t// complicated screen, and it was still okay) to complete before this requests it.\n\t\t\ttry {\n\t\t\t\tawait waitForLoadingComponentsWithTimeout(\n\t\t\t\t\tcomponentLoader,\n\t\t\t\t\t[localModuleIdentifierForStableName(ModuleType.Screen, screenId, \"default\").value],\n\t\t\t\t\tmodulesStore,\n\t\t\t\t)\n\n\t\t\t\tconst exportBinding = importCollector.addImport(importSpecifier, {\n\t\t\t\t\texportSpecifier: \"default\",\n\t\t\t\t\timportBinding: \"Screen\",\n\t\t\t\t\tlazy: screenId !== node.homeNodeId,\n\t\t\t\t})\n\t\t\t\troutes[screenId] = { page: exportBinding, path: screenId }\n\t\t\t} catch {\n\t\t\t\t// Don't include a prototype screen we can't find.\n\t\t\t\tlogger.error(\"Missing module for prototype screen\", { screenId })\n\t\t\t}\n\t\t}\n\n\t\tconst serializedRouteId = serializeJS(node.homeNodeId)\n\t\tconst serializedRoutes = serializeJS(routes)\n\n\t\tconst useRandomIdBinding = js`${importCollector.addImport(\"react\", {\n\t\t\texportSpecifier: \"*\",\n\t\t\timportBinding: \"React\",\n\t\t})}.useId`\n\n\t\tconst source = new SafeJS(\n\t\t\tjoin.sections(\n\t\t\t\tjoin.linesFrom(importCollector.statements),\n\t\t\t\t`const routes = ${serializedRoutes}`,\n\t\t\t\tjoin.lines(\n\t\t\t\t\t`function ${Variable.Prototype}({ ${Variable.layoutId} }: { ${Variable.layoutId}?: string }): JSX.Element {`,\n\t\t\t\t\t`  const InitialRouteComponent = useInitialRouteComponent(routes, \"${node.homeNodeId}\")`,\n\t\t\t\t\t`  const ${Variable.defaultLayoutId} = ${SafeJS.fn(useRandomIdBinding)};`,\n\t\t\t\t\t`  if (!InitialRouteComponent) return null`,\n\t\t\t\t\t`  return (`,\n\t\t\t\t\t`    <LayoutGroup id={${Variable.layoutId} ?? ${Variable.defaultLayoutId}} inherit={false}>`,\n\t\t\t\t\t`      <PageRoot RootComponent={InitialRouteComponent} isWebsite={false} routeId={${serializedRouteId}} routes={routes} />`,\n\t\t\t\t\t`    </LayoutGroup>`,\n\t\t\t\t\t`  )`,\n\t\t\t\t\t\"}\",\n\t\t\t\t),\n\t\t\t\tjoin.lines(\n\t\t\t\t\tjsdoc(\"This is a generated Framer component.\", {\n\t\t\t\t\t\t[AnnotationKey.FramerIntrinsicHeight]: rect?.height,\n\t\t\t\t\t\t[AnnotationKey.FramerIntrinsicWidth]: rect?.width,\n\t\t\t\t\t\t[AnnotationKey.FramerSupportedLayoutWidth]: \"fixed\",\n\t\t\t\t\t\t[AnnotationKey.FramerSupportedLayoutHeight]: \"fixed\",\n\t\t\t\t\t\t[AnnotationKey.FramerPrototype]: true,\n\t\t\t\t\t}),\n\t\t\t\t\t`const Component: React.ComponentType<{}> = React.memo(${Variable.Prototype})`,\n\t\t\t\t\t`export default Component;`,\n\t\t\t\t),\n\t\t\t\t`Component.displayName = ${fullDisplayName};`,\n\t\t\t),\n\t\t)\n\n\t\treturn [{ type: ModuleType.Prototype, source, revision: undefined }]\n\t},\n)\n", "import { isLocalModuleIdentifier } from \"@framerjs/shared\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { withDOMLayout } from \"document/models/CanvasTree/traits/WithDOMLayout.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport { Rect, type Size } from \"library/index.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\nimport type { ProcessDependencies } from \"./types.ts\"\n\nexport async function getRootRect<T extends CanvasNode>(\n\ttree: CanvasTree,\n\tnode: T,\n\tidentifier: string | undefined,\n\tmeasureNodes: ProcessDependencies[\"measureNodes\"],\n\tmodulesStore: ProcessDependencies[\"modulesStore\"],\n\tintrinsicSize: Size | undefined,\n): Promise<Rect> {\n\t/**\n\t * If by the time we're generating an auto-sizing root and its domRect is\n\t * not initialized in the node cache, we try to update the domRect:\n\t * - do an on-demand measurement, use the measurement if it's available.\n\t * - if we can't measure the node (e.g. because it's not rendered), we try\n\t * to reuse the intrinsic size in the last-persisted module.\n\t * - if an intrinsicSize is given, use that.\n\t * If none of the above could update the domRect, tree.getRect(node) will\n\t * fallback to the default (200x200).\n\t */\n\tconst nodeUsesDomRect = withDOMLayout(node) && node.usesDOMRectCached()\n\tif (nodeUsesDomRect && !node.getDOMRect()) {\n\t\tawait updateCachedNodeDomRectOnDemand(node, measureNodes, identifier, modulesStore)\n\t\tconst domRect = node.cache.getRawDOMRect(node.id)\n\t\tif (!domRect && intrinsicSize) {\n\t\t\treturn Rect.atOrigin(intrinsicSize)\n\t\t}\n\t}\n\n\treturn tree.getRect(node)\n}\n\nasync function updateCachedNodeDomRectOnDemand(\n\tnode: CanvasNode,\n\tmeasureNodes: ProcessDependencies[\"measureNodes\"],\n\tidentifier: string | undefined,\n\tmodulesStore: ModulesStore,\n) {\n\tif (measureNodes) {\n\t\tconst measurements = await measureNodes([node.id])\n\t\tconst measurement = measurements?.[0]\n\t\tif (measurement) {\n\t\t\tconst { layoutMetrics } = measurement\n\t\t\tconst rect = Rect.from(layoutMetrics)\n\t\t\tnode.cache.setRawDOMRect(node.id, rect)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif (!identifier) return\n\n\tconst intrinsicSize = getLastCompiledIntrinsicSize(identifier, modulesStore)\n\tif (intrinsicSize) {\n\t\t// We only consume the size\n\t\tconst rect = Rect.atOrigin(intrinsicSize)\n\t\tnode.cache.setRawDOMRect(node.id, rect)\n\t}\n}\n\nfunction getLastCompiledIntrinsicSize(identifier: string, modulesStore: ModulesStore): Size | undefined {\n\t// We should not be trying to generate an external module\n\tif (!isLocalModuleIdentifier(identifier)) return\n\n\tconst module = modulesStore.getPersistedModuleByLocalIdentifier(identifier)\n\tif (!module) return\n\tconst { intrinsicWidth, intrinsicHeight } = module.metadata\n\tif (isNumber(intrinsicWidth) && isNumber(intrinsicHeight)) {\n\t\treturn {\n\t\t\twidth: intrinsicWidth,\n\t\t\theight: intrinsicHeight,\n\t\t}\n\t}\n}\n", "import hash from \"@emotion/hash\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport { assert, ModuleType, localModuleIdForStableName, localModuleIdentifierForStableName } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { jsxForNode } from \"code-generation/jsx/jsxForNode.ts\"\nimport { PreviousTarget } from \"code-generation/utils/EventCollector.ts\"\nimport type { CanvasNode, FrameNode } from \"document/models/CanvasTree/index.ts\"\nimport { isCanvasPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { COMPONENT_PRESETS_MODULE_ID } from \"utils/componentPresetUtils.ts\"\nimport { join } from \"utils/join.ts\"\nimport { SafeJS, serializeJS } from \"../js/serializeJS.ts\"\nimport { sourceCodeSerializer } from \"./GeneratedComponent.ts\"\nimport { Var as GeneratedVariantComponentVars } from \"./GeneratedVariantComponentVars.ts\"\nimport { getRootRect } from \"./processNodes/processRoot.ts\"\nimport { serializeFonts } from \"./serializeFonts.ts\"\nimport {\n\taddCSSCollectorRulesToTarget,\n\taspectRatioEnhancementRules,\n\tconvertSharedRulesToCSS,\n\tdefaultExportWithAnnotationsAndCSS,\n} from \"./shared.ts\"\n\nconst Var = {\n\tScreen: js`Screen`,\n\tactiveVariantCallback: GeneratedVariantComponentVars.activeVariantCallback,\n\tcss: GeneratedVariantComponentVars.css,\n\tdelay: GeneratedVariantComponentVars.delay,\n\tref: GeneratedVariantComponentVars.ref,\n\tserializationHash: GeneratedVariantComponentVars.serializationHash,\n\tsharedStyleClassNames: GeneratedVariantComponentVars.sharedStyleClassNames,\n\trestProps: GeneratedVariantComponentVars.restProps,\n\trefBinding: GeneratedVariantComponentVars.refBinding,\n} as const\n\nconst RESERVED = new Set(Object.values(Var).map(value => serializeJS(value)))\n\nexport const serializePrototypeScreenComponent = sourceCodeSerializer<CanvasNode>(\n\tasync (node, dependencies, { serializationId, initialIntrinsicSize }) => {\n\t\tconst { modulesStore, tree } = dependencies\n\n\t\tconst scopeNode = tree.getScopeNodeFor(node)\n\t\tif (!isCanvasPageNode(scopeNode)) return []\n\n\t\tconst sourceNode = tree.get<FrameNode>(node.id)\n\t\tassert(sourceNode, \"Must have a source node to serialize. This should be a primary variant.\")\n\n\t\tassert(isCanvasPageNode(scopeNode), \"Must have a scope node to serialize. This should be a CanvasPage Node.\")\n\n\t\tconst name = `FramerScreen${hash(node.id)}`\n\t\tconst identifier = localModuleIdentifierForStableName(ModuleType.Screen, node.id, \"default\").value\n\t\tconst { jsx: jsxFromNode, ctx } = await jsxForNode(\n\t\t\tsourceNode,\n\t\t\tscopeNode,\n\t\t\tdependencies,\n\t\t\tnew Set<string>(RESERVED).add(name),\n\t\t\tserializationId,\n\t\t)\n\t\tassert(jsxFromNode, \"There must be JSX to serialize.\")\n\n\t\tconst imports = ctx.imports\n\n\t\tconst rect = await getRootRect(\n\t\t\ttree,\n\t\t\tsourceNode,\n\t\t\tidentifier,\n\t\t\tdependencies.measureNodes,\n\t\t\tmodulesStore,\n\t\t\tinitialIntrinsicSize,\n\t\t)\n\n\t\tconst withNavigation = ctx.events.navigationTargets.size > 0\n\t\tconst withHandlers = ctx.events.handlers.size > 0\n\t\tconst appearEvent = ctx.events.variantOnAppearId.get(node.id)\n\t\tconst withKeyBinds = ctx.events.keyBindHooks.size > 0\n\n\t\tconst preload: string[] = []\n\t\tfor (const target of ctx.events.navigationTargets) {\n\t\t\tif (target !== PreviousTarget) preload.push(target)\n\t\t}\n\n\t\tconst fontObjects = ctx.fonts.fontObjects\n\t\tconst fontReferences = new Map(ctx.fonts.fontReferences)\n\n\t\tconst sharedFontArrays: SafeJS[] = []\n\t\tconst sharedStyleIds = new Set(ctx.css.sharedStyleIds)\n\t\tconst sharedStyleImports: SafeJS[] = []\n\n\t\tfor (const styleId of sharedStyleIds) {\n\t\t\tconst styleModuleId = localModuleIdForStableName(ModuleType.CSS, styleId)\n\n\t\t\tconst styleImport = imports.addImport(`../${styleModuleId}`, {\n\t\t\t\texportSpecifier: \"*\",\n\t\t\t\timportBinding: \"sharedStyle\",\n\t\t\t})\n\n\t\t\tsharedStyleImports.push(styleImport)\n\t\t\tsharedFontArrays.push(\n\t\t\t\tSafeJS.fn(\n\t\t\t\t\timports.addImport(\"framer\", {\n\t\t\t\t\t\texportSpecifier: \"getFontsFromSharedStyle\",\n\t\t\t\t\t}),\n\t\t\t\t\tjs`${styleImport}.fonts`,\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\n\t\tlet componentPresetsImport: SafeJS | undefined\n\n\t\tfor (const presetId of ctx.componentPresetIds) {\n\t\t\tcomponentPresetsImport ??= imports.addImport(`../${COMPONENT_PRESETS_MODULE_ID}`, {\n\t\t\t\texportSpecifier: \"*\",\n\t\t\t\timportBinding: \"componentPresets\",\n\t\t\t})\n\n\t\t\tconst fontsForPreset = js`${componentPresetsImport}.fonts?.[${presetId}]`\n\t\t\tsharedFontArrays.push(\n\t\t\t\tjs`(${fontsForPreset} ? ${SafeJS.fn(\n\t\t\t\t\tctx.imports.addImport(\"framer\", {\n\t\t\t\t\t\texportSpecifier: \"getFontsFromComponentPreset\",\n\t\t\t\t\t}),\n\t\t\t\t\tfontsForPreset,\n\t\t\t\t)} : [])`,\n\t\t\t)\n\t\t}\n\n\t\tconst css = new Map()\n\t\taddCSSCollectorRulesToTarget(ctx.css.get(), css)\n\n\t\tconst componentName = new SafeJS(name)\n\n\t\tconst useRef = imports.addImport(\"react\", {\n\t\t\texportSpecifier: \"useRef\",\n\t\t})\n\n\t\tconst scopeName = scopeNode.resolveValue(\"name\")\n\t\tconst template = join.lines(\n\t\t\twithNavigation && `const preload = ${serializeJS(preload)};`,\n\t\t\t// Screens don't support variables (yet?), so if somehow we ended up with any variable\n\t\t\t// references on the screen (e.g., we didn't scrub them when copy-pasting from inside a\n\t\t\t// smart component), let's make sure they're in scope to avoid an \"is not defined\"\n\t\t\t// ReferenceError. Their value will be `undefined`.\n\t\t\t...ctx.variables.fallbackDeclarations(),\n\t\t\t...ctx.declarations.file.list(),\n\t\t\tjs`const ${Var.serializationHash} = ${serializationId}`,\n\t\t\tjs`const ${Var.Screen} = ${serializeComponentFunction(\n\t\t\t\t{ props: js`style, className` },\n\t\t\t\tjs`const fallbackRef = ${SafeJS.fn(js`${useRef}<HTMLElement>`, js`null`)}`,\n\t\t\t\tjs`const ${Var.refBinding} = ${Var.ref} ?? fallbackRef`,\n\t\t\t\twithNavigation\n\t\t\t\t\t? js`const navigate = ${SafeJS.fn(imports.addImport(\"framer\", { exportSpecifier: \"usePrototypeNavigate\" }), {\n\t\t\t\t\t\t\tpreload: js`preload`,\n\t\t\t\t\t\t})}`\n\t\t\t\t\t: undefined,\n\t\t\t\twithHandlers &&\n\t\t\t\t\tjs`const { ${Var.activeVariantCallback}, ${Var.delay} } = ${SafeJS.fn(\n\t\t\t\t\t\timports.addImport(\"framer\", { exportSpecifier: \"useActiveVariantCallback\" }),\n\t\t\t\t\t)}`,\n\t\t\t\t...ctx.events.handlers.values(),\n\t\t\t\tjs`const ${Var.sharedStyleClassNames} = ${sharedStyleImports.map(i => js`${i}.className`)}`,\n\t\t\t\t...ctx.declarations.component.list(),\n\t\t\t\twithKeyBinds && join.linesFrom(ctx.events.keyBindHooks),\n\t\t\t\tappearEvent && SafeJS.fn(imports.addImport(\"framer\", { exportSpecifier: \"useOnAppear\" }), appearEvent),\n\t\t\t\tjs`return ${jsxFromNode}`,\n\t\t\t)}`,\n\t\t\tjs`const ${Var.css} = ${[\n\t\t\t\t...ctx.css.conditionalRules(serializationId),\n\t\t\t\taspectRatioEnhancementRules,\n\t\t\t\t...convertSharedRulesToCSS(css),\n\t\t\t\t...sharedStyleImports.map(styleImport => js`...${styleImport}.css`),\n\t\t\t]}`,\n\t\t\tdefaultExportWithAnnotationsAndCSS(\n\t\t\t\tcomponentName,\n\t\t\t\tserializationId,\n\t\t\t\tVar.Screen,\n\t\t\t\tVar.css,\n\t\t\t\t{\n\t\t\t\t\t[AnnotationKey.FramerIntrinsicHeight]: rect.height,\n\t\t\t\t\t[AnnotationKey.FramerIntrinsicWidth]: rect.width,\n\t\t\t\t\t[AnnotationKey.FramerSupportedLayoutWidth]: \"fixed\",\n\t\t\t\t\t[AnnotationKey.FramerSupportedLayoutHeight]: \"fixed\",\n\t\t\t\t\t[AnnotationKey.FramerScreen]: undefined,\n\t\t\t\t\t[AnnotationKey.FramerDisplayContentsDiv]: false,\n\t\t\t\t},\n\t\t\t\timports,\n\t\t\t),\n\n\t\t\tjs`${componentName}.displayName = ${`Screens/${scopeName ? scopeName.trim() : \"Generated Component\"}`};`,\n\t\t\tjs`${componentName}.defaultProps = ${{ width: rect.width, height: rect.height }};`,\n\t\t\tserializeFonts({\n\t\t\t\tcomponentName,\n\t\t\t\tfontObjects,\n\t\t\t\tfontReferences,\n\t\t\t\timports,\n\t\t\t\tdeclarations: ctx.declarations.font,\n\t\t\t\tsharedFontArrays,\n\t\t\t}),\n\t\t)\n\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: ModuleType.Screen,\n\t\t\t\trevision: undefined,\n\t\t\t\tsource: new SafeJS(join.sections(join.linesFrom(imports.statements), template)),\n\t\t\t\tartifacts: {\n\t\t\t\t\tassets: ctx.assets.keys,\n\t\t\t\t\tpackageDependencies: ctx.packages.dependencies,\n\t\t\t\t\tmetrics: ctx.metrics.get(),\n\t\t\t\t},\n\t\t\t},\n\t\t]\n\t},\n)\n\nfunction serializeComponentFunction(\n\t{ props }: { props: SafeJS },\n\t...contents: (string | SafeJS | false | undefined)[]\n): SafeJS {\n\treturn new SafeJS(\n\t\tjoin.lines(js`React.forwardRef(function({ ${props}, ...${Var.restProps} }, ${Var.ref}) {`, ...contents, js`});`),\n\t)\n}\n", "import { ModuleType } from \"@framerjs/shared\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport { ColorCollector } from \"code-generation/utils/CSSVariableDefinitionCollector.ts\"\nimport { FontDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport { FontCollector } from \"code-generation/utils/FontCollector.ts\"\nimport type { StylePresetContext } from \"code-generation/utils/collector.ts\"\nimport type { TextStylePresetNode } from \"document/models/CanvasTree/nodes/TextStylePresetNode.ts\"\nimport type { StylePresetNode } from \"document/models/CanvasTree/nodes/utils/isStylePresetNode.ts\"\nimport { isStylePresetBreakpointNode } from \"document/models/CanvasTree/nodes/utils/isStylePresetNode.ts\"\nimport { hasStylePresetBreakpoint } from \"document/models/CanvasTree/traits/WithStylePresetBreakpoint.ts\"\nimport { hasAppliedOpenTypeFeatures } from \"document/models/CanvasTree/utils/openType.ts\"\nimport { isUndefined } from \"utils/typeChecks.ts\"\nimport { sourceCodeSerializer } from \"./GeneratedComponent.ts\"\nimport { createFontsArray } from \"./serializeFonts.ts\"\n\nconst serializationIdPlaceholder = \"{serializationId}\"\n\n// We need to include a serialization id in the code, otherwise selectors from\n// old version of generated text styles will still match updated text styles\n// inside smart components on the canvas.\nfunction addSerializationIdPlaceholder(selector: string) {\n\treturn `.${serializationIdPlaceholder} ${selector}`\n}\n\nexport const serializeStylePreset = sourceCodeSerializer<StylePresetNode>(\n\tasync (node, { componentLoader, tree }, { serializationId }) => {\n\t\tconst fontBindings = new BindingCollector()\n\t\tconst fontDeclarations = new FontDeclarationCollector(fontBindings)\n\t\tconst fontCollector = new FontCollector(fontDeclarations)\n\t\tconst fontSelectors = node.getFontsForCodeGeneration()\n\t\tconst revision = node.moduleSourceRevision\n\t\tconst openType = hasAppliedOpenTypeFeatures(node)\n\n\t\tfor (const fontSelector of fontSelectors) {\n\t\t\tfontCollector.addFontObjectBySelector(fontSelector, openType)\n\t\t}\n\n\t\tconst rules: string[] = []\n\n\t\tconst colors = new ColorCollector()\n\n\t\tconst ctx: StylePresetContext = { componentLoader, colors }\n\t\tfor (const { selectors, declarations } of node.getCSS(ctx)) {\n\t\t\tconst selectorsWithPlaceholders = selectors.map(addSerializationIdPlaceholder)\n\t\t\trules.push(`${selectorsWithPlaceholders.join(\", \")} { ${declarations} }`)\n\t\t}\n\n\t\tconst breakpoints = tree\n\t\t\t.getNodesWithTrait(node.cache.replicaInstances ?? [], isStylePresetBreakpointNode)\n\t\t\t.filter(hasStylePresetBreakpoint)\n\t\t\t.sort((left, right) => (right.breakpointWidth ?? 0) - (left.breakpointWidth ?? 0))\n\n\t\tfor (let i = 0; i < breakpoints.length; i++) {\n\t\t\tconst breakpoint = breakpoints[i]\n\t\t\tif (isUndefined(breakpoint)) continue\n\t\t\tconst nextBreakpoint = breakpoints[i + 1] as TextStylePresetNode | undefined\n\n\t\t\tconst maxWidth = breakpoint.breakpointWidth - 1\n\t\t\tconst minWidth = nextBreakpoint?.breakpointWidth ?? 0\n\n\t\t\tfor (const { selectors: breakpointSelectors, declarations: breakpointDeclarations } of breakpoint.getCSS(ctx)) {\n\t\t\t\tconst breakpointSelectorsWithPlaceholders = breakpointSelectors.map(addSerializationIdPlaceholder)\n\t\t\t\tconst body = `${breakpointSelectorsWithPlaceholders.join(\", \")} { ${breakpointDeclarations} }`\n\t\t\t\trules.push(`@media (max-width: ${maxWidth}px) and (min-width: ${minWidth}px) { ${body} }`)\n\t\t\t}\n\t\t}\n\n\t\t// Some style presets, like tables and blockquotes, don't use css custom property\n\t\t// definitions, instead they create their own css declarations directly. These rules need to\n\t\t// incorporate fallbacks for rgb color.\n\t\tconst wideGamutRules = colors.getWideGamutColorRules(`.${serializationId}`)\n\t\tif (wideGamutRules.length) {\n\t\t\trules.push(`@supports (color: color(display-p3 1 1 1)) { ${wideGamutRules.join(\" \")} }`)\n\t\t}\n\n\t\tconst serializedCSS = rules.map(rule => rule.replaceAll(serializationIdPlaceholder, serializationId))\n\n\t\tconst serializedFonts = createFontsArray({\n\t\t\tfontObjects: fontCollector.fontObjects,\n\t\t\tfontReferences: fontCollector.fontReferences,\n\t\t})\n\n\t\tconst source = js.joinLines(\n\t\t\tjs`import { fontStore } from \"framer\";`,\n\t\t\tjs`fontStore.loadFonts(${fontSelectors});`,\n\t\t\t...fontDeclarations.list(),\n\t\t\tjs`export const fonts = ${serializedFonts};`,\n\t\t\tjs`export const css = ${serializedCSS};`,\n\t\t\tjs`export const className = ${serializationId};`,\n\t\t)\n\n\t\treturn [\n\t\t\t{\n\t\t\t\trevision,\n\t\t\t\ttype: ModuleType.CSS,\n\t\t\t\tsource,\n\t\t\t\tartifacts: {\n\t\t\t\t\tmetrics: {\n\t\t\t\t\t\tnodes: rules.length,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t]\n\t},\n)\n", "import type { VariantSize } from \"code-generation/types.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isPinnable } from \"document/models/CanvasTree/traits/WithPins.ts\"\nimport {\n\tsizeConstraintsDefaults,\n\tsupportsSizeConstraints,\n} from \"document/models/CanvasTree/traits/WithSizeConstraints.ts\"\n\nexport function getVariantSize(node: CanvasNode): VariantSize | undefined {\n\tif (!isPinnable(node)) return\n\treturn {\n\t\twidthType: node.widthType,\n\t\theightType: node.heightType,\n\t\t...(supportsSizeConstraints(node)\n\t\t\t? {\n\t\t\t\t\tminHeight: node.minHeight,\n\t\t\t\t\tmaxHeight: node.maxHeight,\n\t\t\t\t\tminWidth: node.minWidth,\n\t\t\t\t\tmaxWidth: node.maxWidth,\n\t\t\t\t}\n\t\t\t: sizeConstraintsDefaults),\n\t}\n}\n", "import type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isBreakpointVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\n\nexport function createBreakpoint(tree: CanvasTree, node: CanvasNode) {\n\tif (isBreakpointVariant(node)) {\n\t\tconst rect = tree.getRect(node)\n\t\treturn {\n\t\t\tmin: rect.width,\n\t\t}\n\t}\n}\n", "import hash from \"@emotion/hash\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport {\n\tassert,\n\ttype ModuleExportIdentifierString,\n\tModuleType,\n\tassertNever,\n\tisEmptyObject,\n\tisModuleExportIdentifier,\n\tlocalModuleIdForStableName,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport { type TagTransform, js, jst, jsx } from \"code-generation/js/js.ts\"\nimport type { InputAnnotations } from \"code-generation/js/jsdoc.ts\"\nimport { SafeJS, SerializableObject, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport {\n\ttype CreateDeduplicatedDynamicValueBinding,\n\tmakeCreateDeduplicatedDynamicValueBinding,\n} from \"code-generation/jsx/createDeduplicatedDynamicValueBinding.ts\"\nimport { difference } from \"code-generation/jsx/difference.ts\"\nimport { getModuleTypeForScope } from \"code-generation/jsx/jsxContext.ts\"\nimport { jsxForNode } from \"code-generation/jsx/jsxForNode.ts\"\nimport { serializesToSameValue } from \"code-generation/jsx/serializesToSameValue.ts\"\nimport type { JSXCollectors, JSXContext } from \"code-generation/jsx/types.ts\"\nimport type { PreloadCollector } from \"code-generation/loader/PreloadCollector.ts\"\nimport type {\n\tComponentVariantGesture,\n\tEnabledVariantGestures,\n\tMakeSerializable,\n\tVariantSize,\n} from \"code-generation/types.ts\"\nimport type { BindingCollector } from \"code-generation/utils/BindingCollector.ts\"\nimport { LAYOUT_TEMPLATE_ATTRIBUTE } from \"code-generation/utils/CSSCollector.ts\"\nimport { PATH_VARIABLES_BINDING } from \"code-generation/utils/EventCollector.ts\"\nimport type { ImportCollector } from \"code-generation/utils/ImportCollector.ts\"\nimport type { VariableCollector } from \"code-generation/utils/VariableCollector.ts\"\nimport { getVariantSize } from \"code-generation/utils/getVariantSize.ts\"\nimport { enumToDisplayNameFunctionsName } from \"code-generation/utils/valueTransformCollector/functions/enumToDisplayName.ts\"\nimport {\n\tgetQueryDefaultCollectionAlias,\n\tgetQueryFrom,\n\tgetQuerySelect,\n} from \"code-generation/utils/valueTransformCollector/getQueryForDataRepeater.ts\"\nimport { serializeVariantData } from \"code-generation/variantDetails.ts\"\nimport { getScopeTypeForScope } from \"document/base-engine/BaseScopeStore.ts\"\nimport { getQueryParamNameOfVariable } from \"document/components/chrome/properties/utils/getQueryParamNameOfVariable.ts\"\nimport { getRawWebPagePath } from \"document/components/utils/getWebPagePath.ts\"\nimport { getDefaultName } from \"document/components/utils/nodes.ts\"\nimport type {\n\tCanvasNode,\n\tCanvasPageNode,\n\tCanvasTree,\n\tDesignPageNode,\n\tFrameNode,\n\tNodeID,\n\tSmartComponentNode,\n\tWebPageNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport type { LayoutTemplateNode } from \"document/models/CanvasTree/nodes/LayoutTemplateNode.ts\"\nimport {\n\tisDesignPageNode,\n\tisFrameNode,\n\tisLayoutTemplateNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isDynamicValue } from \"document/models/CanvasTree/traits/DynamicValue.ts\"\nimport { emptyControlMap, type VariableProviderControlMap } from \"document/models/CanvasTree/traits/VariableProvider.ts\"\nimport { createVariableReference } from \"document/models/CanvasTree/traits/VariableReference.ts\"\nimport type { Breakpoints } from \"document/models/CanvasTree/traits/WithBreakpointVariants.ts\"\nimport { withBreakpointVariants } from \"document/models/CanvasTree/traits/WithBreakpointVariants.ts\"\nimport { hasCollectionDataSource } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport { withFill, withOptionalFill } from \"document/models/CanvasTree/traits/WithFill.ts\"\nimport { usesModuleRevision } from \"document/models/CanvasTree/traits/WithModuleRevision.ts\"\nimport { withReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport { DEFAULT_ROOT_FONT_SIZE, hasRootFontSize } from \"document/models/CanvasTree/traits/WithRootFontSize.ts\"\nimport type { Loaded } from \"document/models/CanvasTree/traits/WithScopeLoader.ts\"\nimport type { IsReplica } from \"document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { VariableID } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport {\n\tgetReferencedPropertyControl,\n\tisVariableDefinition,\n\twithQueryParam,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport type { IsVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { isGestureVariant } from \"document/models/CanvasTree/traits/WithVariant.ts\"\nimport { getCSSBackgroundValue } from \"document/models/CanvasTree/traits/collectStyles/collectBackgroundFill.ts\"\nimport { coerceToNegativeColumnGap } from \"document/models/CanvasTree/traits/collectStyles/collectGap.ts\"\nimport type { CSSDimension } from \"document/models/CanvasTree/traits/utils/CSSDimension.ts\"\nimport { createCSSDimension } from \"document/models/CanvasTree/traits/utils/CSSDimension.ts\"\nimport { getFallbackValue } from \"document/models/CanvasTree/traits/utils/codeComponentProps.ts\"\nimport { createCSSDeclarationBlock } from \"document/models/CanvasTree/traits/utils/getCSSDeclarationBlock.ts\"\nimport { ControlType, DimensionType } from \"library/index.ts\"\nimport { overlayContainerId, templateOverlayContainerId } from \"library/modules/Floating.tsx\"\nimport type { From, SelectExpression } from \"library/modules/cms/types.ts\"\nimport { VariantSelector } from \"library/modules/useVariantState.ts\"\nimport type { Rect } from \"library/render/types/Rect.ts\"\nimport type { UseEnumQueryParamOptions } from \"library/router/queryParameters.tsx\"\nimport { COMPONENT_PRESETS_MODULE_ID } from \"utils/componentPresetUtils.ts\"\nimport { getCollectionIdForIdentifier } from \"utils/getCollectionForIdentifier.ts\"\nimport { getId } from \"utils/getId.ts\"\nimport { join } from \"utils/join.ts\"\nimport { safeTagName } from \"utils/names.ts\"\nimport { isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { sourceCodeList, sourceCodeSerializer } from \"./GeneratedComponent.ts\"\nimport { Var } from \"./GeneratedVariantComponentVars.ts\"\nimport { createControlsTypesAndReactProps } from \"./createControlsTypesAndReactProps.ts\"\nimport {\n\textractVariableIdsFromMetadata,\n\tgeneratePageMetadataModule,\n\tpageMetadataModuleIdentifier,\n} from \"./generateMetadataModule.ts\"\nimport { createMediaQueriesFromBreakpoints, enhanceBreakpoints } from \"./helpers/breakpoints.ts\"\nimport { createBreakpoint } from \"./processNodes/createBreakpoint.ts\"\nimport { getRootRect } from \"./processNodes/processRoot.ts\"\nimport type { ProcessDependencies } from \"./processNodes/types.ts\"\nimport { serializeFonts } from \"./serializeFonts.ts\"\nimport {\n\taddCSSCollectorRulesToTarget,\n\taspectRatioEnhancementRules,\n\tconvertSharedRulesToCSS,\n\tdefaultExportWithAnnotationsAndCSS,\n} from \"./shared.ts\"\n\nconst RESERVED = new Set(Object.values(Var).map(value => serializeJS(value)))\n\ninterface BoundData {\n\tidentifier: ModuleExportIdentifierString\n\tcontrolMap: VariableProviderControlMap\n\tdefaultCollectionAlias: string\n}\n\ntype SourceNode = Loaded<CanvasPageNode | WebPageNode | SmartComponentNode | LayoutTemplateNode> | FrameNode\ntype SourceScope = Exclude<SourceNode, FrameNode> | Loaded<DesignPageNode>\n\nfunction getScopeNode(node: SourceNode, tree: CanvasTree): SourceScope | null {\n\tif (isFrameNode(node)) {\n\t\tconst scope = tree.get<Loaded<DesignPageNode>>(node.parentid)\n\t\tif (!isDesignPageNode(scope) || !scope.isLoaded()) return null\n\t\treturn scope\n\t}\n\n\t// It's critical to use the latest version of the node, not just the draft or current, as a\n\t// newer copy of the node may exist in the tree.\n\treturn tree.current(node)\n}\n\nexport const serializeComponentFromCanvas = sourceCodeSerializer<SourceNode>(\n\tasync (node, dependencies, { serializationId, initialIntrinsicSize }) => {\n\t\tconst { modulesStore, tree, aiGenerationStore, measureNodes } = dependencies\n\t\tconst revision = usesModuleRevision(node, tree) ? node.moduleSourceRevision : undefined\n\n\t\tconst scopeNode = getScopeNode(node, tree)\n\t\tassert(scopeNode?.isLoaded(), \"The scope node must be valid.\")\n\t\tconst type = getModuleTypeForScope(scopeNode)\n\t\tconst primaryVariantId = withReplicaVariants(scopeNode) ? scopeNode.baseVariantId : node.id\n\t\tconst sourceNode = tree.get<FrameNode>(primaryVariantId)\n\t\tassert(sourceNode, \"Must have a source node to serialize. This should be a primary variant.\")\n\n\t\tconst name = `Framer${node.id}`\n\t\tconst componentName = new SafeJS(name)\n\t\tconst { jsx: jsxFromNode, ctx } = await jsxForNode(\n\t\t\tsourceNode,\n\t\t\tscopeNode,\n\t\t\tdependencies,\n\t\t\tnew Set<string>(RESERVED).add(name),\n\t\t\tserializationId,\n\t\t)\n\n\t\tassert(jsxFromNode, \"There must be JSX to serialize.\")\n\n\t\tconst imports = ctx.imports\n\t\tconst isDesignComponent = isDesignPageNode(scopeNode)\n\t\tconst identifier = !isDesignComponent ? scopeNode.instanceIdentifier : undefined\n\n\t\tconst rect = await getRootRect(tree, sourceNode, identifier, measureNodes, modulesStore, initialIntrinsicSize)\n\n\t\tconst variants = withReplicaVariants(scopeNode) ? scopeNode.getReplicaVariants() : []\n\t\tconst { variants: variantsWithLoading, hook: preloadingHook } = ctx.preload.getHook()\n\t\tconst { gestures, breakpoints, classNames, sizes, appearEventMap } = processVariants(\n\t\t\tsourceNode,\n\t\t\tvariants,\n\t\t\tctx,\n\t\t\tvariantsWithLoading,\n\t\t)\n\n\t\tconst cycleOrder = isSmartComponentNode(scopeNode)\n\t\t\t? [scopeNode.baseVariantId, ...scopeNode.getTopLevelReplicaVariants().map(getId)]\n\t\t\t: []\n\t\tconst withCycleOrder = cycleOrder.length > 1\n\t\tconst withGestures = !isEmptyObject(gestures)\n\t\tconst withOnAppear = !isEmptyObject(appearEventMap)\n\t\tconst withBreakpoints = !isEmptyObject(breakpoints)\n\n\t\tconst useRandomIdBinding = js`${imports.addImport(\"react\", {\n\t\t\texportSpecifier: \"*\",\n\t\t\timportBinding: \"React\",\n\t\t})}.useId`\n\n\t\tconst { mediaQueries, sharedStyleImports, sharedFontArrays, css } = collateVariantCSS(\n\t\t\tserializationId,\n\t\t\tctx,\n\t\t\tvariants,\n\t\t\tbreakpoints,\n\t\t\tscopeNode,\n\t\t)\n\t\tconst humanReadableVariantMap = createHumanReadableVariantMap(scopeNode, ctx.componentLoader, ctx.declarations)\n\n\t\tconst innerJSX = jsx.applyTransforms(\n\t\t\tjsxFromNode,\n\t\t\ttransformsForJSX(\n\t\t\t\tscopeNode,\n\t\t\t\tctx,\n\t\t\t\tcreateHTMLStyle(scopeNode, sourceNode, variants, mediaQueries, tree, ctx),\n\t\t\t\twithBreakpoints ? Var.baseVariant : undefined,\n\t\t\t\thumanReadableVariantMap,\n\t\t\t),\n\t\t)\n\n\t\tconst data = processData(scopeNode, dependencies, imports, ctx.preload, ctx.variables)\n\n\t\t// Route loader code is generated from queries collected during JSX traversal\n\t\t// via ctx.preload.addRouteLoaderQuery() calls in jsxForRepeater.ts\n\t\tconst loaderCode = experiments.isOn(\"autobahnNavigation\") ? ctx.preload.getRouteLoaderCode() : undefined\n\n\t\tconst metadataVariableIds = isWebPageNode(scopeNode)\n\t\t\t? extractVariableIdsFromMetadata(scopeNode, data?.controlMap)\n\t\t\t: new Set<VariableID>()\n\n\t\tconst metadataDependencies: Record<VariableID, SafeJS> = {}\n\n\t\tfor (const variableId of metadataVariableIds) {\n\t\t\tconst reference = createVariableReference(variableId, scopeNode.id)\n\t\t\tmetadataDependencies[variableId] = ctx.variables.create(reference)\n\t\t}\n\n\t\tconst { props, types, propertyControls, variableMap } = createControlsTypesAndReactProps(\n\t\t\tscopeNode,\n\t\t\tctx,\n\t\t\tgetScopeTypeForScope(scopeNode),\n\t\t\ttype,\n\t\t\thumanReadableVariantMap,\n\t\t)\n\n\t\tconst layoutDependency =\n\t\t\t!withBreakpoints &&\n\t\t\tjs`const ${Var.layoutDependency} = ${SafeJS.fn(\n\t\t\t\tctx.declarations.file.dedupe(\n\t\t\t\t\t\"createLayoutDependency\",\n\t\t\t\t\tjs`(props, variants) => {${js.joinLines(\n\t\t\t\t\t\tjs`if (props.layoutDependency) return variants.join('-') + props.layoutDependency`,\n\t\t\t\t\t\tjs`return variants.join('-')`,\n\t\t\t\t\t)}}`,\n\t\t\t\t),\n\t\t\t\tVar.props,\n\t\t\t\tVar.variants,\n\t\t\t)}`\n\n\t\tconst { cursors } = ctx.customCursors\n\n\t\tconst useRef = imports.addImport(\"react\", {\n\t\t\texportSpecifier: \"useRef\",\n\t\t})\n\n\t\tconst queryParamNames = getQueryParamNames(scopeNode)\n\n\t\tconst template = join.sections(\n\t\t\twithGestures && js`const ${Var.enabledGestures} = ${gestures};`,\n\t\t\twithCycleOrder && `const ${Var.cycleOrder} = ${serializeJS(cycleOrder)};`,\n\t\t\twithBreakpoints && `const ${Var.breakpoints} = ${serializeJS(mediaQueries)}`,\n\t\t\twithBreakpoints && `const ${Var.isBrowser} = () => typeof document !== \"undefined\";`,\n\t\t\tisDesignComponent && js`const ${Var.variant} = undefined;`,\n\t\t\tisDesignComponent && js`const ${Var.breakpoints} = undefined;`,\n\t\t\tisDesignComponent && js`const ${Var.layoutId} = undefined;`,\n\t\t\tisDesignComponent && js`const ${Var.className} = undefined;`,\n\t\t\tisDesignComponent && js`const ${Var.style} = undefined;`,\n\t\t\tisWebPageNode(scopeNode) && js`export const ${Var.queryParamNames} = ${queryParamNames}`,\n\t\t\tjs`const ${Var.serializationHash} = ${serializationId}`,\n\t\t\t`const ${Var.variantClassNames} = ${serializeJS(classNames)};`,\n\t\t\t!withBreakpoints && addPropertyOverrides,\n\t\t\tjs.linesFrom(ctx.variables.fallbackDeclarations()),\n\t\t\t...ctx.declarations.file.list(),\n\t\t\t`export interface Props extends React.HTMLAttributes<HTMLDivElement> { ${types} }`,\n\t\t\t`const ${Var.Component} = ${serializeComponentFunction(\n\t\t\t\t/*\n\t\t\t\t * Independent variable declarations come first.\n\t\t\t\t * Order in this block does not matter.\n\t\t\t\t */\n\t\t\t\tjs`const fallbackRef = ${SafeJS.fn(js`${useRef}<HTMLElement>`, js`null`)}`,\n\t\t\t\tjs`const ${Var.refBinding} = ${Var.ref} ?? fallbackRef`,\n\t\t\t\tjs`const ${Var.defaultLayoutId} = ${SafeJS.fn(useRandomIdBinding)}`,\n\t\t\t\t`const { ${Var.activeLocale}, ${Var.setLocale} } = ${SafeJS.fn(\n\t\t\t\t\timports.addImport(\"framer\", {\n\t\t\t\t\t\texportSpecifier: \"useLocaleInfo\",\n\t\t\t\t\t}),\n\t\t\t\t)}`,\n\t\t\t\tctx.variables.shouldProvideLayoutDirection\n\t\t\t\t\t? js`const ${Var.layoutDirection} = ${SafeJS.fn(\n\t\t\t\t\t\t\timports.addImport(\"framer\", {\n\t\t\t\t\t\t\t\texportSpecifier: \"useLayoutDirection\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t)}`\n\t\t\t\t\t: undefined,\n\t\t\t\tisSmartComponentNode(scopeNode) || isWebPageNode(scopeNode)\n\t\t\t\t\t? js`const ${Var.componentViewport} = ${SafeJS.fn(\n\t\t\t\t\t\t\tctx.imports.addImport(\"framer\", {\n\t\t\t\t\t\t\t\texportSpecifier: \"useComponentViewport\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t)}`\n\t\t\t\t\t: undefined,\n\n\t\t\t\t/**\n\t\t\t\t * The order here matters - changing them might break code-gen in subtle ways.\n\t\t\t\t */\n\t\t\t\tcreateDataRecordBinding({\n\t\t\t\t\tdata,\n\t\t\t\t\timports,\n\t\t\t\t\tpreload: ctx.preload,\n\t\t\t\t}),\n\t\t\t\tisWebPageNode(scopeNode) &&\n\t\t\t\t\tcreateURLVariablesBinding(tree, dependencies.componentLoader, scopeNode, imports, ctx.variables),\n\t\t\t\tprops,\n\t\t\t\tisWebPageNode(scopeNode) &&\n\t\t\t\t\tcreateUseMetadata({\n\t\t\t\t\t\twebPageNodeId: node.id,\n\t\t\t\t\t\tmetadataDependencies,\n\t\t\t\t\t\timports,\n\t\t\t\t\t\tbindings: ctx.bindings,\n\t\t\t\t\t}),\n\t\t\t\twithBreakpoints\n\t\t\t\t\t? js.joinLines(\n\t\t\t\t\t\t\tjs`const [${Var.baseVariant}, ${Var.hydratedBaseVariant}] = ${SafeJS.fn(\n\t\t\t\t\t\t\t\timports.addImport(\"framer\", { exportSpecifier: \"useHydratedBreakpointVariants\" }),\n\t\t\t\t\t\t\t\tVar.variant,\n\t\t\t\t\t\t\t\tVar.breakpoints,\n\t\t\t\t\t\t\t\tjs`false`,\n\t\t\t\t\t\t\t)};`,\n\t\t\t\t\t\t\tjs`const ${Var.gestureVariant} = undefined;`,\n\t\t\t\t\t\t)\n\t\t\t\t\t: serializeUseVariantState(sourceNode.id, withGestures, withCycleOrder, imports),\n\t\t\t\tlayoutDependency,\n\t\t\t\tcreatePathVariablesBinding(ctx),\n\t\t\t\t...ctx.events.routeHandlers.values(),\n\t\t\t\tctx.events.handlers.size > 0 &&\n\t\t\t\t\tjs`const { ${Var.activeVariantCallback}, ${Var.delay} } = ${SafeJS.fn(\n\t\t\t\t\t\timports.addImport(\"framer\", { exportSpecifier: \"useActiveVariantCallback\" }),\n\t\t\t\t\t\twithBreakpoints ? js`undefined` : Var.baseVariant,\n\t\t\t\t\t)}`,\n\t\t\t\t...ctx.events.handlers.values(),\n\t\t\t\twithOnAppear &&\n\t\t\t\t\tSafeJS.fn(\n\t\t\t\t\t\timports.addImport(\"framer\", { exportSpecifier: \"useOnVariantChange\" }),\n\t\t\t\t\t\twithBreakpoints ? Var.hydratedBaseVariant : Var.baseVariant,\n\t\t\t\t\t\tappearEventMap,\n\t\t\t\t\t),\n\t\t\t\tjs`const ${Var.sharedStyleClassNames} = ${sharedStyleImports.map(i => js`${i}.className`)}`,\n\t\t\t\t...ctx.declarations.component.list(),\n\n\t\t\t\t/*\n\t\t\t\t * The block depends on the blocks above.\n\t\t\t\t * The order of the props here does not matter.\n\t\t\t\t */\n\t\t\t\tcursors,\n\t\t\t\tpreloadingHook?.(withGestures ? Var.enabledGestures : js`undefined`),\n\n\t\t\t\tjs`return (${innerJSX})`,\n\t\t\t)}`,\n\t\t\tcss,\n\t\t\tdefaultExportWithAnnotationsAndCSS(\n\t\t\t\tcomponentName,\n\t\t\t\tserializationId,\n\t\t\t\tVar.Component,\n\t\t\t\tVar.css,\n\t\t\t\tannotationsForNode(scopeNode, ctx, rect, sizes, variableMap),\n\t\t\t\timports,\n\t\t\t),\n\t\t\t`${name}.displayName = ${serializeJS(scopeNode.resolveValue(\"name\")?.trim() || \"Generated Component\")};`,\n\t\t\t`${name}.defaultProps = ${serializeJS({ width: rect.width, height: rect.height })};`,\n\t\t\tpropertyControls &&\n\t\t\t\tSafeJS.fn(\n\t\t\t\t\timports.addImport(\"framer\", { exportSpecifier: \"addPropertyControls\" }),\n\t\t\t\t\tcomponentName,\n\t\t\t\t\tnew SafeJS(`${serializeJS(propertyControls)} as any`),\n\t\t\t\t),\n\t\t\tserializeFonts({\n\t\t\t\tcomponentName,\n\t\t\t\tfontObjects: ctx.fonts.fontObjects,\n\t\t\t\tfontReferences: ctx.fonts.fontReferences,\n\t\t\t\timports,\n\t\t\t\tdeclarations: ctx.declarations.font,\n\t\t\t\tsharedFontArrays,\n\t\t\t}),\n\t\t\t// Attach loader if data dependencies were discovered\n\t\t\tloaderCode && js`${componentName}.loader = ${loaderCode}`,\n\t\t)\n\n\t\tconst [metadata] = isWebPageNode(scopeNode)\n\t\t\t? await generatePageMetadataModule(scopeNode, dependencies, { serializationId })\n\t\t\t: []\n\n\t\treturn sourceCodeList([\n\t\t\t{\n\t\t\t\ttype,\n\t\t\t\trevision,\n\t\t\t\t// Add imports to the top of the template. Serializing other\n\t\t\t\t// collectors may have added imports that would be dropped if\n\t\t\t\t// they were serialized with the rest of the template above.\n\t\t\t\tsource: new SafeJS(join.sections(join.linesFrom(imports.statements), template)),\n\t\t\t\tartifacts: {\n\t\t\t\t\tpackageDependencies: ctx.packages.dependencies,\n\t\t\t\t\terrors: ctx.errors.errors,\n\t\t\t\t\tassets: ctx.assets.keys,\n\t\t\t\t\tmetrics: ctx.metrics.get(),\n\t\t\t\t\tkitSectionsStructure: aiGenerationStore.cacheKitSectionsStructure(\n\t\t\t\t\t\tnode.id,\n\t\t\t\t\t\tctx.kitSectionsStructure.structure,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tmetadata,\n\t\t\tctx.localizedValues.module(revision),\n\t\t])\n\t},\n)\n\nfunction serializeUseVariantState(\n\tprimaryVariantId: string,\n\twithGestures: boolean,\n\twithCycleOrder: boolean,\n\timports: ImportCollector,\n) {\n\tconst args = SerializableObject.fromEntries([\n\t\t[Var.defaultVariant, primaryVariantId],\n\t\t[Var.variant, Var.variant],\n\t\t[Var.variantClassNames, Var.variantClassNames],\n\t\t[Var.enabledGestures, withGestures ? Var.enabledGestures : undefined],\n\t\t[Var.cycleOrder, withCycleOrder ? Var.cycleOrder : undefined],\n\t\t[Var.ref, Var.refBinding],\n\t])\n\n\tconst stateHook = SafeJS.fn(imports.addImport(\"framer\", { exportSpecifier: \"useVariantState\" }), args)\n\n\tconst variants = Var.variants\n\tconst baseVariant = Var.baseVariant\n\tconst setVariant = js`setVariant`\n\tconst gestureVariant = Var.gestureVariant\n\tconst classNames = Var.classNames\n\tconst setGestureState = Var.setGestureState\n\tconst gestureHandlers = Var.gestureHandlers\n\tconst clearLoadingGesture = Var.clearLoadingGesture\n\tconst isLoading = Var.isLoading\n\n\treturn join.lines(\n\t\tjs`const ${{\n\t\t\tvariants,\n\t\t\tbaseVariant,\n\t\t\tsetVariant,\n\t\t\tgestureVariant,\n\t\t\tclassNames,\n\t\t\tsetGestureState,\n\t\t\tgestureHandlers,\n\t\t\tclearLoadingGesture,\n\t\t\tisLoading,\n\t\t}} = ${stateHook}`,\n\t)\n}\n\nfunction serializeComponentFunction(...contents: (string | false | SafeJS | undefined)[]) {\n\treturn join.sections(\n\t\tjs`React.forwardRef<HTMLDivElement, Props>(function(${Var.props}, ${Var.ref}) {`,\n\t\t...contents,\n\t\tjs`});`,\n\t)\n}\n\nfunction annotationsForNode(\n\tnode: SourceScope,\n\tctx: JSXContext,\n\trect: Rect,\n\tvariantSizes: Record<string, VariantSize>,\n\tvariableMap: Record<string, string> | undefined,\n): InputAnnotations {\n\tconst { height, width } = rect\n\n\tconst serializedVariantDetails = {\n\t\tpropertyName: \"variant\",\n\t\tdata: Object.fromEntries(Object.entries(variantSizes).map(([id, size]) => [id, serializeVariantData(size)])),\n\t}\n\n\tconst annotations: InputAnnotations = {\n\t\t[AnnotationKey.FramerIntrinsicHeight]: height,\n\t\t[AnnotationKey.FramerIntrinsicWidth]: width,\n\t\t[AnnotationKey.FramerRootFontSize]: withBreakpointVariants(node)\n\t\t\t? node.getPrimaryVariant()?.rootFontSize\n\t\t\t: undefined,\n\t\t[AnnotationKey.FramerCanvasComponentVariantDetails]: JSON.stringify(serializedVariantDetails),\n\t\t[AnnotationKey.FramerVariables]: variableMap && JSON.stringify(variableMap),\n\t\t[AnnotationKey.FramerImmutableVariables]: true,\n\t\t[AnnotationKey.FramerDisplayContentsDiv]: false,\n\t\t[AnnotationKey.FramerAutoSizeImages]: true,\n\t\t[AnnotationKey.FramerComponentViewportWidth]: true,\n\t\t[AnnotationKey.FramerColorSyntax]: true,\n\t\t[AnnotationKey.FramerVectorSets]: ctx.vectorSets.annotation(),\n\t}\n\n\tif (isLayoutTemplateNode(node)) {\n\t\tconst breakpoints: Breakpoints = {}\n\t\tconst values = node.getBreakpointValues()\n\t\tfor (const id in values) {\n\t\t\t// Extend the breakpoint with the className which is used to set the\n\t\t\t// styles for this breakpoint when rendering without media queries\n\t\t\t// on the canvas. LayoutTemplateNode.getBreakpointValues() caches\n\t\t\t// and reuses the result so its important to create a new object\n\t\t\t// here.\n\t\t\tconst variant = ctx.tree.get<FrameNode>(id)\n\t\t\tbreakpoints[id] = {\n\t\t\t\t...values[id],\n\t\t\t\tcanvasClassName: getLayoutTemplateCanvasCSSOverrideClassName(id),\n\t\t\t\tminHeight: variant?.height,\n\t\t\t\tviewportHeight: variant?.viewportHeight,\n\t\t\t\tname: variant?.resolveValue(\"name\") ?? undefined,\n\t\t\t\twidth: variant?.widthType === DimensionType.FixedNumber ? variant?.width : undefined,\n\t\t\t\trootFontSize: variant?.rootFontSize ?? DEFAULT_ROOT_FONT_SIZE,\n\t\t\t}\n\t\t}\n\n\t\tannotations[AnnotationKey.FramerHitTargets] = ctx.hitTargets.annotation()\n\t\tannotations[AnnotationKey.FramerBreakpoints] = JSON.stringify(breakpoints)\n\t\tannotations[AnnotationKey.FramerDefaultVariant] = node.baseVariantId\n\t\tannotations[AnnotationKey.FramerTrackingIds] = ctx.trackingIds.annotation()\n\t\tannotations[AnnotationKey.FramerLayoutTemplate] = true\n\t} else if (isWebPageNode(node)) {\n\t\tannotations[AnnotationKey.FramerAcceptsLayoutTemplate] = ctx.acceptsLayoutTemplate\n\t\tannotations[AnnotationKey.FramerTrackingIds] = ctx.trackingIds.annotation()\n\t\t// Needs to be present even with no scroll sections to avoid loading the whole module. The false will not be parsed but keep the key.\n\t\tannotations[AnnotationKey.FramerScrollSections] = ctx.elementIds.annotation() ?? false\n\t\tannotations[AnnotationKey.FramerResponsiveScreen] = true\n\t\tannotations[AnnotationKey.FramerLayoutTemplateFlowEffect] = true\n\t} else if (isSmartComponentNode(node)) {\n\t\tannotations[AnnotationKey.FramerTrackingIds] = ctx.trackingIds.annotation()\n\t} else if (isDesignPageNode(node)) {\n\t\tannotations[AnnotationKey.FramerDesign] = true\n\t} else if (!isSmartComponentNode(node)) {\n\t\tannotations[AnnotationKey.FramerScreen] = true\n\t}\n\n\treturn annotations\n}\n\n/**\n * Processes CMS collection data for detail pages and registers the detail page query\n * with PreloadCollector for route preloading.\n */\nfunction processData(\n\tscopeNode: CanvasNode,\n\tdependencies: ProcessDependencies,\n\timports: ImportCollector,\n\tpreload: PreloadCollector,\n\tvariables: VariableCollector,\n): BoundData | undefined {\n\tif (!isWebPageNode(scopeNode) || !hasCollectionDataSource(scopeNode)) return undefined\n\n\tconst pagePath = getRawWebPagePath(dependencies.tree, scopeNode)\n\tif (!pagePath) return undefined\n\n\tconst controlMap =\n\t\tscopeNode.getProvidedControlMap(\n\t\t\tdependencies.tree,\n\t\t\tundefined,\n\t\t\tdependencies.componentLoader,\n\t\t\tdependencies.componentLoader.activeBundleHash,\n\t\t) ?? emptyControlMap\n\n\tconst defaultCollectionAlias = getQueryDefaultCollectionAlias(scopeNode)\n\tconst data: BoundData = {\n\t\tdefaultCollectionAlias,\n\t\tidentifier: scopeNode.dataIdentifier,\n\t\tcontrolMap,\n\t}\n\n\t// Register metadata variables so they are included in the query below.\n\tconst metadataVariableIds = extractVariableIdsFromMetadata(scopeNode, controlMap)\n\tfor (const variableId of metadataVariableIds) {\n\t\tconst reference = createVariableReference(variableId, scopeNode.id)\n\t\tvariables.create(reference)\n\t}\n\n\t// Register detail page query for route preloading\n\t// This must happen before getRouteLoaderCode() so it's included in the loader\n\tconst variableBindings = variables.getBindings(scopeNode.id)\n\tconst usedVariableIds = new Set<VariableID>()\n\tfor (const [variableId] of controlMap) {\n\t\tif (variableBindings.has(variableId)) {\n\t\t\tusedVariableIds.add(variableId)\n\t\t}\n\t}\n\n\tfunction resolveCollection(dataIdentifier: ModuleExportIdentifierString) {\n\t\tconst binding = imports.addModuleImport(dataIdentifier)\n\t\tassert(binding, \"Can't import collection\")\n\t\treturn binding\n\t}\n\n\tconst queriedVariableIds = new Set<VariableID>()\n\n\t// NOTE: We have to call `getQuerySelect` before `getQueryFrom` because it\n\t// might add variables to `queriedVariableIds`.\n\tconst querySelect = getQuerySelect(\n\t\tcontrolMap,\n\t\tusedVariableIds,\n\t\tqueriedVariableIds,\n\t\tdefaultCollectionAlias,\n\t\tresolveCollection,\n\t)\n\n\tconst queryFrom = getQueryFrom(\n\t\tscopeNode.dataIdentifier,\n\t\tcontrolMap,\n\t\tqueriedVariableIds,\n\t\tdefaultCollectionAlias,\n\t\tresolveCollection,\n\t)\n\n\tpreload.addDetailPageQuery(\n\t\tqueryFrom as MakeSerializable<From>,\n\t\tquerySelect as MakeSerializable<SelectExpression>[],\n\t\tdefaultCollectionAlias,\n\t)\n\n\treturn data\n}\n\nconst addPropertyOverrides = join.lines(\n\t`function addPropertyOverrides(overrides, ...variants) {`,\n\t`const nextOverrides = {}`,\n\t`variants?.forEach(variant => variant && Object.assign(nextOverrides, overrides[variant]))`,\n\t`return nextOverrides`,\n\t`}`,\n)\n\nfunction createUseMetadata({\n\twebPageNodeId,\n\tmetadataDependencies,\n\timports,\n\tbindings,\n}: {\n\twebPageNodeId: string\n\tmetadataDependencies: Record<VariableID, SafeJS>\n\timports: ImportCollector\n\tbindings: BindingCollector\n}) {\n\tconst metadataProvider = imports.addImport(`../${pageMetadataModuleIdentifier(webPageNodeId).localId}`, {\n\t\texportSpecifier: \"default\",\n\t\timportBinding: \"metadataProvider\",\n\t})\n\tconst metadata = bindings.create(\"metadata\")\n\n\tconst useMetadata = imports.addImport(\"framer\", { exportSpecifier: \"useMetadata\" })\n\n\tconst metadataFunctionCall = SafeJS.fn(metadataProvider, metadataDependencies, Var.activeLocale)\n\tconst memoDependencies = Object.values(metadataDependencies).concat(Var.activeLocale)\n\n\treturn join.lines(\n\t\tjs`const ${metadata} = React.useMemo(() => ${metadataFunctionCall}, ${memoDependencies})`,\n\t\tSafeJS.fn(useMetadata, metadata),\n\t)\n}\n\nfunction gestureInfo(variant: CanvasNode & IsReplica & IsVariant): ComponentVariantGesture | undefined {\n\tif (!isGestureVariant(variant)) return undefined\n\n\treturn { type: variant.gesture, topLevel: variant.replicaInfo.inheritsFrom }\n}\n\ninterface CreateDataRecordBindingOptions {\n\tdata: BoundData | undefined\n\timports: ImportCollector\n\tpreload: PreloadCollector\n}\n\nfunction createDataRecordBinding({ data, imports, preload }: CreateDataRecordBindingOptions): SafeJS | undefined {\n\tif (!data) return undefined\n\n\tconst useCurrentPathVariablesBinding = imports.addImport(\"framer\", {\n\t\texportSpecifier: \"useCurrentPathVariables\",\n\t})\n\n\tconst notFoundErrorBinding = imports.addImport(\"framer\", {\n\t\texportSpecifier: \"NotFoundError\",\n\t})\n\n\tconst useQueryDataBinding = imports.addImport(\"framer\", {\n\t\texportSpecifier: \"useQueryData\",\n\t})\n\n\tconst getWhereExpressionFromPathVariablesBinding = imports.addImport(\"framer\", {\n\t\texportSpecifier: \"getWhereExpressionFromPathVariables\",\n\t})\n\n\t// Use the deduplicated constant from PreloadCollector\n\tconst detailQueryConstant = preload.getDetailPageQueryConstant()\n\tassert(detailQueryConstant, \"Detail page query constant should be registered before createDataRecordBinding\")\n\n\t// Pass where as argument to the query function\n\tconst whereExpression = SafeJS.fn(\n\t\tgetWhereExpressionFromPathVariablesBinding,\n\t\tVar.currentPathVariables,\n\t\tdata.defaultCollectionAlias,\n\t)\n\tconst getCurrentRouteData = js`const [${Var.currentRouteData}] = ${SafeJS.fn(\n\t\tuseQueryDataBinding,\n\t\tjs`${detailQueryConstant}(${whereExpression})`,\n\t)};`\n\n\tconst code = js.joinLines(\n\t\tjs`const ${Var.currentPathVariables} = ${SafeJS.fn(useCurrentPathVariablesBinding)};`,\n\t\tgetCurrentRouteData,\n\t\tjs`const ${Var.getFromCurrentRouteData} = (key) => {\n            if (!${Var.currentRouteData}) throw new ${notFoundErrorBinding}(\\`No data matches path variables: \\${JSON.stringify(${Var.currentPathVariables})}\\`);\n            return ${Var.currentRouteData}[key];\n        };`,\n\t)\n\n\treturn code\n}\n\nfunction createURLVariablesBinding(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\twebPageNode: WebPageNode,\n\timports: ImportCollector,\n\tvariables: VariableCollector,\n): SafeJS | undefined {\n\tconst urlVariables = webPageNode.variables.filter(isVariableDefinition)\n\tif (urlVariables.length === 0) return undefined\n\n\tconst variableBindings = variables.getBindings(webPageNode.id)\n\n\tconst declarations: SafeJS[] = []\n\tfor (const variable of urlVariables) {\n\t\tif (!withQueryParam(variable)) continue\n\n\t\tconst queryParam = getQueryParamNameOfVariable(variable)\n\n\t\tlet useParameterHookCall: SafeJS | undefined\n\n\t\tswitch (variable.type) {\n\t\t\tcase ControlType.Boolean: {\n\t\t\t\tconst useBooleanQueryParam = imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"useBooleanQueryParam\",\n\t\t\t\t})\n\n\t\t\t\tconst options = new SerializableObject({\n\t\t\t\t\tinitialValue: variable.optional ? undefined : variable.initialValue,\n\t\t\t\t\tparameterName: queryParam,\n\t\t\t\t\toptional: variable.optional ? true : undefined,\n\t\t\t\t})\n\n\t\t\t\tuseParameterHookCall = SafeJS.fn(useBooleanQueryParam, options)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.String: {\n\t\t\t\tconst useStringQueryParam = imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"useStringQueryParam\",\n\t\t\t\t})\n\n\t\t\t\tconst options = new SerializableObject({\n\t\t\t\t\tinitialValue: variable.optional ? undefined : variable.initialValue,\n\t\t\t\t\tparameterName: queryParam,\n\t\t\t\t\toptional: variable.optional === true ? true : undefined,\n\t\t\t\t})\n\n\t\t\t\tuseParameterHookCall = SafeJS.fn(useStringQueryParam, options)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.Number: {\n\t\t\t\tconst useNumberQueryParam = imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"useNumberQueryParam\",\n\t\t\t\t})\n\n\t\t\t\tconst options = new SerializableObject({\n\t\t\t\t\tinitialValue: variable.optional ? undefined : variable.initialValue,\n\t\t\t\t\tparameterName: queryParam,\n\t\t\t\t\toptional: variable.optional === true ? true : undefined,\n\t\t\t\t})\n\n\t\t\t\tuseParameterHookCall = SafeJS.fn(useNumberQueryParam, options)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.Date: {\n\t\t\t\tconst useDateQueryParam = imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"useDateQueryParam\",\n\t\t\t\t})\n\n\t\t\t\tconst options = new SerializableObject({\n\t\t\t\t\tinitialValue: variable.optional ? undefined : variable.initialValue,\n\t\t\t\t\tparameterName: queryParam,\n\t\t\t\t\tdisplayTime: variable.options?.displayTime === true ? true : undefined,\n\t\t\t\t\toptional: variable.optional === true ? true : undefined,\n\t\t\t\t})\n\n\t\t\t\tuseParameterHookCall = SafeJS.fn(useDateQueryParam, options)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.CollectionReference: {\n\t\t\t\tconst useCollectionReferenceQueryParam = imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"useCollectionReferenceQueryParam\",\n\t\t\t\t})\n\n\t\t\t\tconst options = new SerializableObject({\n\t\t\t\t\tcollectionId: getCollectionIdForIdentifier(variable.dataIdentifier),\n\t\t\t\t\tinitialValue: variable.optional ? undefined : variable.initialValue,\n\t\t\t\t\tparameterName: queryParam,\n\t\t\t\t\toptional: variable.optional === true ? true : undefined,\n\t\t\t\t})\n\n\t\t\t\tuseParameterHookCall = SafeJS.fn(useCollectionReferenceQueryParam, options)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase ControlType.MultiCollectionReference: {\n\t\t\t\tconst useMultiCollectionReferenceQueryParam = imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"useMultiCollectionReferenceQueryParam\",\n\t\t\t\t})\n\n\t\t\t\tconst options = new SerializableObject({\n\t\t\t\t\tcollectionId: getCollectionIdForIdentifier(variable.dataIdentifier),\n\t\t\t\t\tinitialValue: variable.optional ? undefined : variable.initialValue,\n\t\t\t\t\tparameterName: queryParam,\n\t\t\t\t\toptional: variable.optional === true ? true : undefined,\n\t\t\t\t})\n\n\t\t\t\tuseParameterHookCall = SafeJS.fn(useMultiCollectionReferenceQueryParam, options)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"controlReference\": {\n\t\t\t\tif (variable.expectedType !== ControlType.Enum) continue\n\n\t\t\t\tconst control = getReferencedPropertyControl(tree, componentLoader, variable)\n\t\t\t\tif (!control || control.type !== ControlType.Enum) continue\n\n\t\t\t\tconst useEnumQueryParam = imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"useEnumQueryParam\",\n\t\t\t\t})\n\n\t\t\t\tconst dataIdentifier = variable.entityIdentifier\n\t\t\t\tconst parsedDataIdentifier = parseModuleIdentifier(dataIdentifier)\n\t\t\t\tif (!isModuleExportIdentifier(parsedDataIdentifier)) continue\n\n\t\t\t\tconst enumFieldKey = variable.controlKey\n\t\t\t\tconst dataDefinition = componentLoader.dataForIdentifier(dataIdentifier)\n\n\t\t\t\tconst annotationValue = dataDefinition?.annotations?.[AnnotationKey.FramerEnumToDisplayNameUtils]\n\n\t\t\t\t/**\n\t\t\t\t * {@link CodeGenerationStore.ensureReferencedCollectionsExportUpToDateEnumUtils}\n\t\t\t\t * ensures the version is up to date\n\t\t\t\t */\n\t\t\t\tassert(\n\t\t\t\t\tisString(annotationValue) && Number.parseInt(annotationValue, 10) === 2,\n\t\t\t\t\t\"Unexpected FramerEnumToDisplayNameUtils version\",\n\t\t\t\t)\n\n\t\t\t\tconst enumFunctionsBinding = imports.addModuleImport(parsedDataIdentifier, {\n\t\t\t\t\texportSpecifier: enumToDisplayNameFunctionsName,\n\t\t\t\t})\n\t\t\t\tif (!enumFunctionsBinding) continue\n\n\t\t\t\tconst collectionDataBinding = imports.addModuleImport(parsedDataIdentifier, {\n\t\t\t\t\timportBinding: `${safeTagName(enumFieldKey)}CollectionData`,\n\t\t\t\t})\n\t\t\t\tif (!collectionDataBinding) continue\n\n\t\t\t\tconst initialValue = isString(variable.initialValue)\n\t\t\t\t\t? variable.initialValue\n\t\t\t\t\t: getFallbackValue(ControlType.Enum)\n\n\t\t\t\tlet options: SerializableObject | undefined\n\n\t\t\t\tif (variable.optional === true || !initialValue) {\n\t\t\t\t\toptions = new SerializableObject({\n\t\t\t\t\t\tgetOptionTitle: js`${enumFunctionsBinding}?.[${enumFieldKey}]`,\n\t\t\t\t\t\tinitialValue: undefined as unknown as SafeJS,\n\t\t\t\t\t\toptional: true,\n\t\t\t\t\t\toptions: js`${collectionDataBinding}.propertyControls?.[${enumFieldKey}]?.options`,\n\t\t\t\t\t\tparameterName: queryParam,\n\t\t\t\t\t} satisfies MakeSerializable<UseEnumQueryParamOptions<true>>)\n\t\t\t\t} else {\n\t\t\t\t\toptions = new SerializableObject({\n\t\t\t\t\t\tgetOptionTitle: js`${enumFunctionsBinding}?.[${enumFieldKey}]`,\n\t\t\t\t\t\tinitialValue,\n\t\t\t\t\t\toptions: js`${collectionDataBinding}.propertyControls?.[${enumFieldKey}]?.options`,\n\t\t\t\t\t\tparameterName: queryParam,\n\t\t\t\t\t} satisfies MakeSerializable<UseEnumQueryParamOptions>)\n\t\t\t\t}\n\n\t\t\t\tuseParameterHookCall = SafeJS.fn(useEnumQueryParam, options)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tassertNever(variable)\n\t\t\t}\n\t\t}\n\n\t\tconst variableBinding = variableBindings.get(variable.id)\n\t\tif (!variableBinding) continue\n\n\t\tconst setterBinding = variables.getSetterBinding(variable.id)\n\t\tconst destructuredBindings = [variableBinding]\n\t\tif (setterBinding) {\n\t\t\tdestructuredBindings.push(setterBinding)\n\t\t}\n\n\t\tdeclarations.push(js`const ${destructuredBindings} = ${useParameterHookCall};`)\n\t}\n\n\treturn js.joinLines(...declarations)\n}\n\nfunction getQueryParamNames(scopeNode: SourceScope): string[] {\n\tif (!isWebPageNode(scopeNode)) return []\n\treturn scopeNode.variables.flatMap(variable => {\n\t\tif (!isVariableDefinition(variable)) return []\n\t\tif (!withQueryParam(variable)) return []\n\t\treturn [getQueryParamNameOfVariable(variable)]\n\t})\n}\n\nfunction getLayoutTemplateCanvasCSSOverrideClassName(variantId: NodeID) {\n\treturn `framer-${hash(variantId)}-override`\n}\n\nfunction getBackground(node: CanvasNode, createDeduplicatedDynamicValueBinding: CreateDeduplicatedDynamicValueBinding) {\n\tif (!withFill(node) || (withOptionalFill(node) && !node.fillEnabled)) return undefined\n\n\tif (node.fillType === \"color\" && isDynamicValue(node.fillColor)) {\n\t\treturn createDeduplicatedDynamicValueBinding(node.fillColor, node, \"fill\")\n\t}\n\n\treturn getCSSBackgroundValue(node)\n}\n\n/**\n * Users specify the base font-size in px, but we convert to a % to ensure that the base follows the\n * browsers a11y settings.\n */\nfunction getRootFontSizeForHTMLStyle(node: CanvasNode): CSSDimension | undefined {\n\tif (!hasRootFontSize(node)) return\n\tconst value = (node.rootFontSize / 16) * 100\n\n\treturn createCSSDimension(value, \"%\")\n}\n\nfunction safeCSSValue(value: string | SafeJS, collectors: JSXCollectors) {\n\treturn isString(value)\n\t\t? value\n\t\t: SafeJS.fn(collectors.imports.addImport(\"framer\", { exportSpecifier: \"safeCSSValue\" }), value)\n}\n\n/**\n * Web Pages and Layout Templates generate an inline <style> element that\n * applies a background color to the :root. This ensures that the browser navbar\n * reacts to the fill of the breakpoint. This <style> responds to bound\n * variables.\n */\nfunction createHTMLStyle(\n\tscope: SourceScope,\n\tnode: CanvasNode,\n\tvariants: (FrameNode & IsReplica & IsVariant)[],\n\tmediaQueries: Record<string, string | undefined>,\n\ttree: CanvasTree,\n\tcollectors: JSXCollectors,\n) {\n\tif (!isLayoutTemplateNode(scope) && !isWebPageNode(scope)) return\n\n\tconst createDeduplicatedDynamicValueBinding = makeCreateDeduplicatedDynamicValueBinding(\n\t\ttree,\n\t\tcollectors.declarations,\n\t\tcollectors.variables,\n\t\tcollectors.valueTransforms,\n\t)\n\n\t// Layout Template's use `:root`, while Web Pages use html as the selector.\n\t// `:root` is more specific than `html`, so Layout Templates always have\n\t// greater specificity than webpages. Additionally this specificity allows\n\t// Layout Templates to overwrite the value set by old Web Pages which set a\n\t// class name on the body element directly.\n\tconst rootSelector = isLayoutTemplateNode(scope) ? `:root` : `html`\n\tconst backgroundSelector = `${rootSelector} body`\n\n\t// For the root font size, we try get the number from the breakpoint and\n\t// convert to a pixel string. If it's not set, we do not set a rule, which\n\t// means the browser will use the default font size of 16px. The selector is\n\t// chose in the same way for background color, except at the root level. It must\n\t// be here, otherwise it cannot overwrite the browser's font size, meaning it cannot\n\t// inform `rem` units.\n\tconst rootFontSize = getRootFontSizeForHTMLStyle(node)\n\tconst background = getBackground(node, createDeduplicatedDynamicValueBinding) ?? \"none\"\n\n\tconst rootStatements: (SafeJS | string)[] = [\n\t\tjst`${backgroundSelector} { background: ${safeCSSValue(background, collectors)}; }`,\n\t]\n\tif (isString(rootFontSize)) {\n\t\trootStatements.push(`${rootSelector} { font-size: ${rootFontSize}; }`)\n\t}\n\n\tfor (const variant of variants) {\n\t\tconst mediaQuery = mediaQueries[variant.id]\n\t\tif (mediaQuery) {\n\t\t\tconst variantBackground = getBackground(variant, createDeduplicatedDynamicValueBinding) ?? \"none\"\n\t\t\tconst variantRootFontSize = getRootFontSizeForHTMLStyle(variant)\n\t\t\tconst variantRuleSets: (SafeJS | string)[] = []\n\n\t\t\tif (!serializesToSameValue(background, variantBackground)) {\n\t\t\t\tvariantRuleSets.push(jst`${backgroundSelector} { background: ${safeCSSValue(variantBackground, collectors)}; }`)\n\t\t\t}\n\n\t\t\tif (!serializesToSameValue(rootFontSize, variantRootFontSize)) {\n\t\t\t\tvariantRuleSets.push(`${rootSelector} { font-size: ${variantRootFontSize}; }`)\n\t\t\t}\n\n\t\t\tif (variantRuleSets.length === 0) continue\n\n\t\t\trootStatements.push(jst`@media ${mediaQuery} { ${jst.join(variantRuleSets, \" \")} }`)\n\t\t}\n\t}\n\n\treturn jst.join(rootStatements, \" \")\n}\n\nfunction collateVariantCSS(\n\tserializationId: string,\n\tctx: JSXContext,\n\tvariants: (FrameNode & IsReplica & IsVariant)[],\n\tbreakpoints: Record<NodeID, { min?: number; max?: number }>,\n\tscopeNode: SourceScope,\n) {\n\tconst mediaQueries = createMediaQueriesFromBreakpoints(enhanceBreakpoints(breakpoints))\n\n\tconst scopedMediaQueryRules: (string | SafeJS)[] = []\n\tconst css = new Map<string, (string | SafeJS)[]>()\n\n\t// Append the rules that allow a Layout Template to force a Web Page\n\t// designed with absolute positioning to render in the Layout Template flex\n\t// layout with position: relative.\n\tif (isLayoutTemplateNode(scopeNode)) {\n\t\t// The #overlay element that every Web Page is generated with will\n\t\t// become part of the stack layout of the Layout Template when the Web\n\t\t// Page's root div becomes display: contents. To ensure that any Web\n\t\t// Page, even one last serialized in the past, doesn't include its\n\t\t// #overlay element in the gap, we have to add negative margin to cancel\n\t\t// out the impact on the layout.\n\t\tconst primaryVariant = scopeNode.getPrimaryVariant()\n\t\tconst style = { marginBottom: coerceToNegativeColumnGap(primaryVariant, ctx) }\n\t\tctx.css.createRule(`[${LAYOUT_TEMPLATE_ATTRIBUTE}=\"true\"] > #overlay`, createCSSDeclarationBlock(style))\n\n\t\tfor (const variant of variants) {\n\t\t\tconst variantStyle = { marginBottom: coerceToNegativeColumnGap(variant, ctx) }\n\t\t\tconst diff = difference(variantStyle, style)\n\t\t\tif (!diff || isEmptyObject(diff)) continue\n\t\t\tctx.css.createRule(\n\t\t\t\t`[${LAYOUT_TEMPLATE_ATTRIBUTE}=\"true\"] > #overlay`,\n\t\t\t\tcreateCSSDeclarationBlock(diff),\n\t\t\t\tvariant.id,\n\t\t\t)\n\t\t}\n\t}\n\n\t// Create organized css rules.\n\taddCSSCollectorRulesToTarget(ctx.css.get(), css)\n\n\tconst variantRules: Record<NodeID, SerializableValue[]> = {}\n\tconst variantSelectors: Record<NodeID, string> = {}\n\n\tfor (const variant of variants) {\n\t\tconst mediaQuery = mediaQueries[variant.id]\n\t\tif (mediaQuery) {\n\t\t\tconst target = new Map<string, (string | SafeJS)[]>()\n\t\t\taddCSSCollectorRulesToTarget(ctx.css.get(variant.id), target)\n\n\t\t\tif (!target.size) continue\n\n\t\t\tif (isLayoutTemplateNode(scopeNode)) {\n\t\t\t\tvariantRules[variant.id] = convertSharedRulesToCSS(target)\n\t\t\t\tvariantSelectors[variant.id] = `.${getLayoutTemplateCanvasCSSOverrideClassName(variant.id)}`\n\t\t\t} else {\n\t\t\t\tscopedMediaQueryRules.push(jst`@media ${mediaQuery} { ${jst.join(convertSharedRulesToCSS(target), \" \")}}`)\n\t\t\t}\n\t\t} else {\n\t\t\taddCSSCollectorRulesToTarget(ctx.css.get(variant.id), css)\n\t\t}\n\t}\n\n\tconst sharedFontArrays: SafeJS[] = []\n\tconst sharedStyleImports: SafeJS[] = []\n\n\tfor (const styleId of ctx.css.sharedStyleIds) {\n\t\tconst styleModuleId = localModuleIdForStableName(ModuleType.CSS, styleId)\n\n\t\tconst styleImport = ctx.imports.addImport(`../${styleModuleId}`, {\n\t\t\texportSpecifier: \"*\",\n\t\t\timportBinding: \"sharedStyle\",\n\t\t})\n\n\t\tsharedStyleImports.push(styleImport)\n\t\tsharedFontArrays.push(\n\t\t\tSafeJS.fn(\n\t\t\t\tctx.imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"getFontsFromSharedStyle\",\n\t\t\t\t}),\n\t\t\t\tjs`${styleImport}.fonts`,\n\t\t\t),\n\t\t)\n\t}\n\n\tlet componentPresetsImport: SafeJS | undefined\n\n\tfor (const presetId of ctx.componentPresetIds) {\n\t\tcomponentPresetsImport ??= ctx.imports.addImport(`../${COMPONENT_PRESETS_MODULE_ID}`, {\n\t\t\texportSpecifier: \"*\",\n\t\t\timportBinding: \"componentPresets\",\n\t\t})\n\n\t\tconst fontsForPreset = js`${componentPresetsImport}.fonts?.[${presetId}]`\n\t\tsharedFontArrays.push(\n\t\t\tjs`(${fontsForPreset} ? ${SafeJS.fn(\n\t\t\t\tctx.imports.addImport(\"framer\", {\n\t\t\t\t\texportSpecifier: \"getFontsFromComponentPreset\",\n\t\t\t\t}),\n\t\t\t\tfontsForPreset,\n\t\t\t)} : [])`,\n\t\t)\n\t}\n\n\tconst baseRules: SerializableValue[] = [\n\t\taspectRatioEnhancementRules,\n\t\t...convertSharedRulesToCSS(css),\n\t\t...sharedStyleImports.map(styleImport => js`...${styleImport}.css`),\n\t\t...ctx.css.conditionalRules(serializationId),\n\t]\n\n\tconst definitions = getCSSDefinitions(\n\t\tscopeNode,\n\t\tctx,\n\t\tbaseRules,\n\t\tscopedMediaQueryRules,\n\t\tvariantRules,\n\t\tvariantSelectors,\n\t\tmediaQueries,\n\t)\n\n\treturn {\n\t\tsharedStyleImports,\n\t\tsharedFontArrays,\n\t\tmediaQueries,\n\t\tcss: js`const ${Var.css} = ${definitions}`,\n\t}\n}\n\nfunction getCSSDefinitions(\n\tscope: SourceScope,\n\tcollectors: JSXCollectors,\n\trules: SerializableValue[],\n\tscopedMediaQueryRules: (string | SafeJS)[],\n\tvariantRules: Record<NodeID, SerializableValue[]>,\n\tvariantSelectors: Record<NodeID, string>,\n\tmediaQueries: Record<string, string | undefined>,\n) {\n\tif (isSmartComponentNode(scope) || isDesignPageNode(scope)) {\n\t\treturn rules\n\t}\n\n\tif (isWebPageNode(scope)) {\n\t\treturn [...rules, ...scopedMediaQueryRules]\n\t}\n\n\tif (isLayoutTemplateNode(scope)) {\n\t\t// Create file declarations so we don't create values only when the css\n\t\t// function is called.\n\t\tconst breakpointRules = collectors.declarations.file.dedupe(\"breakpointRules\", variantRules)\n\t\tconst breakpointKeys = collectors.declarations.file.dedupe(\"breakpointKeys\", js`Object.keys(${breakpointRules})`)\n\t\tconst selectors = collectors.declarations.file.dedupe(\"selectors\", variantSelectors)\n\t\tconst rulesConst = collectors.declarations.file.dedupe(\"rules\", rules)\n\t\tconst queries = collectors.declarations.file.dedupe(\"mediaQueries\", mediaQueries)\n\n\t\tconst target = collectors.bindings.create(\"target\")\n\t\tconst query = collectors.bindings.create(\"query\")\n\t\tconst selector = collectors.bindings.create(\"selector\")\n\t\tconst rule = collectors.bindings.create(\"rule\")\n\t\tconst RenderTarget = collectors.imports.addImport(\"framer\", { exportSpecifier: \"RenderTarget\" })\n\n\t\treturn js`(target) => {${js.joinLines(\n\t\t\tjs`const isStaticRenderer = ${target} === ${RenderTarget}.canvas || ${target} === ${RenderTarget}.export`,\n\t\t\t// Rules for the template used on the canvas add all rules prefixed\n\t\t\t// with the selector. This allows the canvas to specify the\n\t\t\t// breakpoint without media queries.\n\t\t\tjs`if (!isStaticRenderer) {${js.joinLines(\n\t\t\t\tjs`return [...${rulesConst}, ...${breakpointKeys}.map(key => {${js.joinLines(\n\t\t\t\t\tjs`const ${query} = ${queries}[key]`,\n\t\t\t\t\tjs`return ${jst`@media ${query} { ${js`${breakpointRules}[key].join(\" \")`} }`}`,\n\t\t\t\t)}})]`,\n\t\t\t)}}`,\n\n\t\t\t// Rules for the template used on the canvas add all rules prefixed\n\t\t\t// with the selector. This allows the canvas to specify the\n\t\t\t// breakpoint without media queries.\n\t\t\tjs`return [...${rulesConst}, ...${breakpointKeys}.flatMap(key => {${js.joinLines(\n\t\t\t\tjs`const ${selector} = ${selectors}[key]`,\n\t\t\t\t// Nest all rules for a specific breakpoint in the same override selector. CSS\n\t\t\t\t// nesting support is covered by our browser support matrix for Vekter:\n\t\t\t\t// https://caniuse.com/css-nesting\n\t\t\t\tjs`return ${breakpointRules}[key].map(${rule} => ${jst`${selector} {${rule}}`})`,\n\t\t\t)}})]`,\n\t\t)}}`\n\t}\n\n\tassertNever(scope)\n}\n\nfunction createPathVariablesBinding(collectors: JSXCollectors) {\n\tif (!collectors.events.needsPathVariables) return\n\n\t// FIXME: For now we are passing down data variables with their original\n\t// names so that they can be mapped to path patterns. We use a context\n\t// to cross component boundaries (nested Smart Components) for now, but\n\t// we should use props bindings instead.\n\treturn `const ${PATH_VARIABLES_BINDING} = React.useContext(${collectors.imports.addImport(\"framer\", {\n\t\texportSpecifier: \"PathVariablesContext\",\n\t})});`\n}\n\nfunction createHumanReadableVariantMap(\n\tnode: SourceScope,\n\tcomponentLoader: ComponentLoader,\n\tdeclarations: JSXCollectors[\"declarations\"],\n): SafeJS | undefined {\n\tconst variants = withReplicaVariants(node) ? node.getTopLevelVariants() : []\n\tif (variants.length < 2) return\n\n\t// If serializing 2 or more top level variants, create an object that maps the human readable name of a variant to its id.\n\t// We will use the binding as a lookup table so that consumers of this component can reference a variant by its name.\n\t// We will also use it to create a Typescript type for allowed variants.\n\tconst mappedVariants = new SerializableObject()\n\tfor (const variant of variants) {\n\t\tconst name = variant.resolveValue(\"name\") ?? getDefaultName(componentLoader, variant)\n\t\tmappedVariants[name] = variant.id\n\t}\n\n\treturn declarations.file.dedupe(\"humanReadableVariantMap\", mappedVariants)\n}\n\nfunction processVariants(\n\tsourceNode: CanvasNode,\n\tvariants: (FrameNode & IsReplica & IsVariant)[],\n\tcontext: JSXContext,\n\tvariantsWithLoading?: Set<NodeID>,\n) {\n\tconst defaultSize = getVariantSize(sourceNode)\n\tassert(defaultSize, \"The primary variant should have a default size as it must be a FrameNode.\")\n\tconst sizes: Record<string, VariantSize> = {\n\t\tdefault: defaultSize,\n\t}\n\tconst classNames = {\n\t\t[sourceNode.id]: `framer-${VariantSelector.Variant}-${hash(sourceNode.id)}`,\n\t}\n\tconst gestures: EnabledVariantGestures = {}\n\tconst gestureMap: Record<NodeID, NodeID[]> = {}\n\n\tconst breakpoints: Record<NodeID, { min?: number; max?: number }> = {}\n\tconst primaryBreakpoint = createBreakpoint(context.tree, sourceNode)\n\tif (primaryBreakpoint) breakpoints[sourceNode.id] = primaryBreakpoint\n\n\tconst primaryAppearEvent = context.events.variantOnAppearId.get(sourceNode.id)\n\tconst appearEventMap: Record<string, SafeJS | undefined> = {}\n\tif (!isUndefined(primaryAppearEvent) && !SafeJS.isUndefined(primaryAppearEvent)) {\n\t\tappearEventMap.default = primaryAppearEvent\n\t}\n\n\tfor (const variant of variants) {\n\t\tcontext.metrics.count(\"variants\")\n\n\t\tconst gesture = gestureInfo(variant)\n\t\tif (gesture) {\n\t\t\tconst into = gestures[gesture.topLevel] ?? {}\n\t\t\t// Loading Variants are only valid if the primary variant loads some\n\t\t\t// data.\n\t\t\tinto[gesture.type] = gesture.type === \"loading\" ? variantsWithLoading?.has(gesture.topLevel) : true\n\t\t\tgestures[gesture.topLevel] = into\n\t\t\tgestureMap[gesture.topLevel] = [...(gestureMap[gesture.topLevel] ?? []), variant.id]\n\t\t} else {\n\t\t\tclassNames[variant.id] = `framer-${VariantSelector.Variant}-${hash(variant.id)}`\n\t\t}\n\t\tconst size = getVariantSize(variant)\n\t\tif (size) sizes[variant.id] = size\n\n\t\tconst variantBreakpoint = createBreakpoint(context.tree, variant)\n\t\tif (variantBreakpoint) breakpoints[variant.id] = variantBreakpoint\n\n\t\tconst appearEvent = context.events.variantOnAppearId.get(variant.id)\n\t\tconst inheritedAppearEvent = serializeJS(\n\t\t\tappearEventMap[variant.replicaInfo.inheritsFrom ?? \"\"] ?? primaryAppearEvent,\n\t\t)\n\t\tif (!isUndefined(appearEvent) && serializeJS(appearEvent) !== inheritedAppearEvent) {\n\t\t\tappearEventMap[variant.id] = appearEvent\n\t\t}\n\t}\n\n\treturn {\n\t\tgestures,\n\t\tbreakpoints,\n\t\tclassNames,\n\t\tsizes,\n\t\tappearEventMap,\n\t}\n}\n\n/**\n * Create transforms to wrap the jsx from the tree.\n */\nfunction transformsForJSX(\n\tscopeNode: SourceScope,\n\tctx: JSXCollectors,\n\thtmlStyle: SafeJS | string | undefined,\n\tactiveVariantId: SafeJS | undefined,\n\thumanReadableVariantMap: SafeJS | undefined,\n) {\n\tconst transforms: TagTransform[] = []\n\n\t// If a Layout Template or Web Page has root style, we add a <style> element\n\t// to provide a background to the document when the web page is mounted.\n\tif ((isLayoutTemplateNode(scopeNode) || isWebPageNode(scopeNode)) && htmlStyle) {\n\t\tconst Style = ctx.declarations.file.dedupe(\n\t\t\t\"HTMLStyle\",\n\t\t\tjs`({value}) => {${js.joinLines(\n\t\t\t\tjs`const onCanvas = ${SafeJS.fn(ctx.imports.addImport(\"framer\", { exportSpecifier: \"useIsOnFramerCanvas\" }))}`,\n\t\t\t\tjs`if (onCanvas) return null`,\n\t\t\t\tjs`return ${jsx.tag(\"style\", new SerializableObject({ \"data-framer-html-style\": \"\", dangerouslySetInnerHTML: { __html: js`value` } }))}`,\n\t\t\t)}}`,\n\t\t)\n\n\t\ttransforms.push(\n\t\t\tchildren => jsx`${js.joinLines(jsx.tag(Style, new SerializableObject({ value: htmlStyle })), children)}`,\n\t\t)\n\t}\n\n\t// Smart components wrap the jsx in a motion.Fragment that controls the active variant.\n\tif (isSmartComponentNode(scopeNode)) {\n\t\tconst React = ctx.imports.addImport(\"react\", { exportSpecifier: \"*\", importBinding: \"React\" })\n\t\tconst motion = ctx.imports.addImport(\"framer-motion\", { exportSpecifier: \"motion.create\" })\n\t\tconst Fragment = ctx.declarations.file.dedupe(\"Variants\", SafeJS.fn(motion, js`${React}.Fragment`))\n\n\t\ttransforms.push(children =>\n\t\t\tjsx.tag(Fragment, new SerializableObject({ initial: false, animate: Var.variants }), children),\n\t\t)\n\t}\n\n\t// Web Pages and Layout Templates add a sibling to the jsx that provides a portal root for overlays.\n\tif (isWebPageNode(scopeNode) || isLayoutTemplateNode(scopeNode) || isDesignPageNode(scopeNode)) {\n\t\tconst overlayProps = new SerializableObject({\n\t\t\tid: isLayoutTemplateNode(scopeNode) ? templateOverlayContainerId : overlayContainerId,\n\t\t})\n\n\t\ttransforms.push(children => jsx`${js.joinLines(children, jsx.tag(\"div\", overlayProps))}`)\n\t}\n\n\t// All scope types are wrapped in a LayoutGroup so that layout animations are scoped.\n\tconst LayoutGroup = ctx.imports.addImport(\"framer-motion\", { exportSpecifier: \"LayoutGroup\" })\n\ttransforms.push(children =>\n\t\tjsx.tag(LayoutGroup, new SerializableObject({ id: js`layoutId ?? ${Var.defaultLayoutId}` }), children),\n\t)\n\n\t// Web Pages and Layout Templates add a context provider that provides\n\t// additional metadata to the jsx.\n\tif (isWebPageNode(scopeNode) || isLayoutTemplateNode(scopeNode)) {\n\t\tconst GeneratedComponentContext = ctx.imports.addImport(\"framer\", {\n\t\t\texportSpecifier: \"GeneratedComponentContext\",\n\t\t})\n\n\t\ttransforms.push(children =>\n\t\t\tjsx.tag(\n\t\t\t\tjs`${GeneratedComponentContext}.Provider`,\n\t\t\t\tnew SerializableObject({\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\tprimaryVariantId: scopeNode.baseVariantId,\n\t\t\t\t\t\tvariantClassNames: Var.variantClassNames,\n\t\t\t\t\t\tactiveVariantId,\n\t\t\t\t\t\thumanReadableVariantMap,\n\t\t\t\t\t\tisLayoutTemplate: isLayoutTemplateNode(scopeNode) ? true : undefined,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\tchildren,\n\t\t\t),\n\t\t)\n\t}\n\n\treturn transforms\n}\n", "import { js } from \"code-generation/js/js.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\n\nexport function getGeneratedByFramerComment() {\n\tconst version = new SafeJS(process.env.VERSION ?? \"unknown\")\n\treturn js`// Generated by Framer (${version})`\n}\n", "import hash from \"@emotion/hash\"\nimport { AnnotationKey, SupportedLayoutOption } from \"@framerjs/framer-runtime/crossorigin\"\nimport { assert, ModuleType, localModuleIdentifierForStableName } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { jsdoc } from \"code-generation/js/jsdoc.ts\"\nimport { SafeJS, serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { SVGContext } from \"code-generation/jsx/svg/svgContext.ts\"\nimport { RenderElement } from \"code-generation/jsx/svg/svgContext.ts\"\nimport { svgForNode } from \"code-generation/jsx/svg/svgForNode.ts\"\nimport type { FramerVectorInfo, VectorColor } from \"code-generation/utils/annotations.ts\"\nimport { insertVectorSetModuleIds } from \"document/components/chrome/insertSidebar/dataSources/items/vectorSetItems.ts\"\nimport type { CanvasNode, ShapeContainerNode } from \"document/models/CanvasTree/index.ts\"\nimport { isVectorSetNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { IsVectorSetItem } from \"document/models/CanvasTree/traits/WithVectorSetItem.ts\"\nimport { ScopeType } from \"document/utils/scopeType.ts\"\nimport { join } from \"utils/join.ts\"\nimport { sourceCodeList, sourceCodeSerializer } from \"./GeneratedComponent.ts\"\nimport { Var as GeneratedVariantComponentVars } from \"./GeneratedVariantComponentVars.ts\"\nimport { createControlsTypesAndReactProps } from \"./createControlsTypesAndReactProps.ts\"\n\nconst Var = {\n\tref: GeneratedVariantComponentVars.ref,\n\trestProps: GeneratedVariantComponentVars.restProps,\n\tstyle: GeneratedVariantComponentVars.style,\n\tprops: GeneratedVariantComponentVars.props,\n\tclassName: GeneratedVariantComponentVars.className,\n\tlayoutId: GeneratedVariantComponentVars.layoutId,\n}\n\nconst css = js`css`\nconst Icon = js`Icon`\nconst Component = js`Component`\nconst Props = js`Props`\n\nconst reserved = [...Object.values(Var), css, Icon, Component, Props].map(value => serializeJS(value))\n\nexport const serializeVector = sourceCodeSerializer<CanvasNode & IsVectorSetItem>(\n\tasync (node, dependencies, options) => {\n\t\tconst { serializationId } = options\n\t\tconst { modulesStore, tree, vectorsStore } = dependencies\n\t\tconst vectorSet = tree.getScopeNodeFor(node)\n\t\tassert(isVectorSetNode(vectorSet), \"Vector set item must be in a VectorSetNode.\")\n\n\t\tconst sourceNode = tree.get<ShapeContainerNode & IsVectorSetItem>(node.id)\n\t\tassert(sourceNode, \"Must have a source node to serialize\")\n\n\t\tconst { ctx, jsx, svg, type } = svgForNode(sourceNode, vectorSet, dependencies, serializationId, reserved)\n\n\t\t// There is an interesting circular dependency here where the Vector Set can only be up to\n\t\t// date when all items have been persisted once, but the items can't be persisted until the\n\t\t// Vector Set is persisted once.\n\t\tconst localId = localModuleIdentifierForStableName(ModuleType.VectorSet, vectorSet.id, \"default\").localId\n\t\tconst module = modulesStore.getPersistedModuleByLocalId(localId)\n\t\tassert(module, \"VectorSet must be persisted.\")\n\n\t\tconst rect = tree.getRect(node)\n\n\t\tconst { propertyControls, variableMap, types, props } = createControlsTypesAndReactProps(\n\t\t\tvectorSet,\n\t\t\t{ ...dependencies, ...ctx, cssVariableDefinitions: undefined },\n\t\t\tScopeType.VectorSet,\n\t\t\tModuleType.Vector,\n\t\t\tundefined,\n\t\t)\n\n\t\tconst color = colorAnnotation(ctx)\n\t\tconst framerVectorInfo: FramerVectorInfo = {\n\t\t\tname: sourceNode.resolveValue(\"name\") ?? Dictionary.Vector,\n\t\t\t// Because Vector Sets are only serialized when items are added or removed, we must flag\n\t\t\t// that the Vector item is empty. This allows us to read the annotations of each item from\n\t\t\t// the Vector Set when rendering a list, and filter empty items.\n\t\t\tempty: isEmptyVectorSetItem(sourceNode) ? true : undefined,\n\t\t\tcolor,\n\t\t\tset: {\n\t\t\t\tlocalId,\n\t\t\t\tid: vectorSet.id,\n\t\t\t\tmoduleId: module.id,\n\t\t\t},\n\t\t}\n\n\t\tconst React = ctx.imports.addImport(\"react\", { exportSpecifier: \"*\", importBinding: \"React\" })\n\t\tconst withCSS = ctx.imports.addImport(\"framer\", { exportSpecifier: \"withCSS\" })\n\n\t\tconst ElementType = elementGenericForType[type]\n\n\t\tconst template = join.lines(\n\t\t\t...ctx.variables.fallbackDeclarations(),\n\t\t\t...ctx.declarations.file.list(),\n\t\t\tjs`interface ${Props} extends ${React}.HTMLAttributes<${React}.${ElementType}> { ${types ?? js``} }`,\n\t\t\tjs`const ${Component}: ${React}.ComponentType<${Props}> = ${React}.forwardRef<${React}.${ElementType}, ${Props}>(function(${Var.props}, ${Var.ref}) {${js.joinLines(\n\t\t\t\tprops,\n\t\t\t\t...ctx.declarations.component.list(),\n\t\t\t\tjs`return (${jsx})`,\n\t\t\t)}})`,\n\t\t\tjs`const ${css} = ${ctx.css.rules}`,\n\t\t\tjsdoc(\"This is a generated Framer component.\", {\n\t\t\t\t[AnnotationKey.FramerIntrinsicWidth]: rect.width,\n\t\t\t\t[AnnotationKey.FramerIntrinsicHeight]: rect.height,\n\t\t\t\t[AnnotationKey.FramerSupportedLayoutWidth]: SupportedLayoutOption.AnyPreferFixed,\n\t\t\t\t[AnnotationKey.FramerSupportedLayoutHeight]: SupportedLayoutOption.AnyPreferFixed,\n\t\t\t\t[AnnotationKey.FramerVariables]: variableMap && JSON.stringify(variableMap),\n\t\t\t\t[AnnotationKey.FramerImmutableVariables]: true,\n\t\t\t\t[AnnotationKey.FramerVector]: JSON.stringify(framerVectorInfo),\n\t\t\t\t[AnnotationKey.FramerDisableUnlink]: insertVectorSetModuleIds.has(framerVectorInfo.set.moduleId)\n\t\t\t\t\t? true\n\t\t\t\t\t: undefined,\n\t\t\t}),\n\t\t\tjs`const ${Icon}: ${React}.ComponentType<${Props}> = ${SafeJS.fn(withCSS, Component, css, serializationId)} as typeof ${Component};`,\n\t\t\tjs`${Icon}.displayName = ${sourceNode.resolveValue(\"name\") ?? Dictionary.Vector};`,\n\t\t\tjs`export default ${Icon}`,\n\t\t\tpropertyControls &&\n\t\t\t\tSafeJS.fn(\n\t\t\t\t\tctx.imports.addImport(\"framer\", { exportSpecifier: \"addPropertyControls\" }),\n\t\t\t\t\tIcon,\n\t\t\t\t\tnew SafeJS(`${serializeJS(propertyControls)} as any`),\n\t\t\t\t),\n\t\t)\n\n\t\t/**\n\t\t * Cache the svg preview and the dominant color annotation in memory. This allows the editor to\n\t\t * display up-to-date previews instantly, before we compile or persist the file. Since Vector\n\t\t * Sets can contain hundreds of Vectors, doing this prevents updating the icon being blocked\n\t\t * behind compilation of other vectors.\n\t\t */\n\t\tvectorsStore.cache(node.id, {\n\t\t\tsvg: serializeJS(svg),\n\t\t\tcolor,\n\t\t})\n\n\t\treturn sourceCodeList([\n\t\t\t{\n\t\t\t\trevision: sourceNode.moduleSourceRevision,\n\t\t\t\ttype: ModuleType.Vector,\n\t\t\t\tsource: new SafeJS(join.sections(join.linesFrom(ctx.imports.statements), template)),\n\t\t\t\tartifacts: {\n\t\t\t\t\tfiles: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: \"icon.svg\",\n\t\t\t\t\t\t\ttype: \"svgIcon\",\n\t\t\t\t\t\t\tcontent: serializeJS(svg),\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\nfunction colorAnnotation(ctx: SVGContext): VectorColor | undefined {\n\tif (ctx.colors.uniqueColorCount !== 1) return\n\n\tconst staticColor = ctx.colors.singleColor\n\tif (staticColor) return { type: \"static\", value: staticColor }\n\n\tconst variableColor = ctx.colors.singleVariableColor\n\tif (!variableColor) return\n\n\treturn { type: \"variable\", value: hash(variableColor) }\n}\n\nfunction isEmptyVectorSetItem(node: CanvasNode & IsVectorSetItem) {\n\tif (!node.children || node.children.length === 0) return true\n\treturn node.children.every(child => child.visible === false)\n}\n\nconst elementGenericForType = {\n\t[RenderElement.Img]: js`HTMLImageElement`,\n\t[RenderElement.Mask]: js`HTMLDivElement`,\n\t[RenderElement.Svg]: js`HTMLSVGElement`,\n\t[RenderElement.Template]: js`HTMLSVGElement`,\n} satisfies Record<RenderElement, SafeJS>\n", "import { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport { ModuleType, localModuleIdentifierForStableName } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { js } from \"code-generation/js/js.ts\"\nimport { type InputAnnotations, jsdoc } from \"code-generation/js/jsdoc.ts\"\nimport { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { VectorSetItem } from \"code-generation/utils/annotations.ts\"\nimport type { VectorSetNode } from \"document/models/CanvasTree/nodes/VectorSetNode.ts\"\nimport { join } from \"utils/join.ts\"\nimport { sourceCodeSerializer } from \"./GeneratedComponent.ts\"\n\nexport const serializeVectorSet = sourceCodeSerializer<VectorSetNode>(async (node, { modulesStore }, opts) => {\n\tconst itemsAnnotation: VectorSetItem[] = []\n\n\tfor (const vectorItem of node.getVectorSetItems()) {\n\t\tconst localId = localModuleIdentifierForStableName(ModuleType.Vector, vectorItem.id, \"default\").localId\n\t\tconst module = modulesStore.getPersistedModuleByLocalId(localId)\n\t\tif (!module) continue\n\n\t\titemsAnnotation.push({\n\t\t\tid: vectorItem.id,\n\t\t\tname: vectorItem.resolveValue(\"name\") ?? Dictionary.Vector,\n\t\t\tmoduleId: module.id,\n\t\t\tsaveId: opts.includeVectorSetSaveIds ? module.saveId : undefined,\n\t\t})\n\t}\n\n\tconst annotations: InputAnnotations = {\n\t\t[AnnotationKey.FramerVectorSet]: JSON.stringify({\n\t\t\tname: node.resolveValue(\"name\") ?? \"Set\",\n\t\t\titems: itemsAnnotation,\n\t\t}),\n\t}\n\tconst source = new SafeJS(\n\t\tjoin.lines(\n\t\t\tjsdoc(\"This is a generated Framer component.\", annotations),\n\t\t\t// VECTOR @TODO: To be an acceptable external module, it must be a component with an export.\n\t\t\tjs`const VectorSet: React.ComponentType<unknown> = function VectorSet() { return null; };`,\n\t\t\tjs`export default VectorSet;`,\n\t\t),\n\t)\n\treturn [\n\t\t{\n\t\t\trevision: node.moduleSourceRevision,\n\t\t\ttype: ModuleType.VectorSet,\n\t\t\tsource,\n\t\t},\n\t]\n})\n", "import { splitExtension } from \"@framerjs/assets\"\nimport { CanvasTree, type NodeID, type ShapeContainerNode } from \"document/models/CanvasTree/index.ts\"\nimport type { Rect, Size } from \"library/index.ts\"\nimport { capitalizeFirstLetterOfEachWord } from \"utils/capitalizeFirstLetter.ts\"\nimport { importSVG } from \"utils/paperjs/importSVG.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { calculateSizeOfSVG } from \"web/pages/project/lib/svg.ts\"\n\ntype VectorImportStatus = \"importing\" | \"done\" | \"canceled\"\ninterface ImportedVector {\n\tnode: ShapeContainerNode\n\tsize: Size\n}\nexport interface VectorImportResult {\n\tscopeId: NodeID\n\tvectors: ImportedVector[]\n\ttargetLayout?: Size | undefined\n}\n\ntype VectorImportReportProgress = (state: { status: VectorImportStatus; finishedCount: number }) => void\n\ntype VectorImportOnDone = (importResult: VectorImportResult) => Promise<void>\n\nexport function vectorImportBatchSize(count: number) {\n\treturn Math.ceil(count / Math.ceil(count / 100))\n}\n\nexport class VectorImport {\n\tstatus: VectorImportStatus | null = null\n\tresults: VectorImportResult | undefined\n\n\treadonly reportProgress: VectorImportReportProgress | undefined\n\treadonly onDone: VectorImportOnDone | undefined\n\n\tconstructor(reportProgress?: VectorImportReportProgress, onDone?: VectorImportOnDone) {\n\t\tthis.reportProgress = reportProgress\n\t\tthis.onDone = onDone\n\t}\n\n\tasync import(svgsToImport: File[], scopeId: NodeID, currentVectorLayout: Rect | undefined) {\n\t\tthis.status = \"importing\"\n\t\tthis.results = { scopeId: scopeId, vectors: [], targetLayout: currentVectorLayout }\n\n\t\tconst startingPosition = currentVectorLayout\n\t\t\t? { left: currentVectorLayout.x + currentVectorLayout.width * 2, top: currentVectorLayout.y }\n\t\t\t: { left: 0, top: 0 }\n\n\t\tfor (let i = 0; i < svgsToImport.length; i++) {\n\t\t\tconst file = svgsToImport[i]\n\t\t\tif (!file) continue\n\n\t\t\tconst result = await importSVGAsVectorSetItem(file, scopeId, startingPosition)\n\t\t\tif (this.status !== \"importing\") return\n\n\t\t\tif (result) {\n\t\t\t\tthis.results.vectors.push(result)\n\t\t\t}\n\n\t\t\tthis.reportProgress?.({ status: this.status, finishedCount: i + 1 })\n\t\t}\n\n\t\tawait this.done()\n\t}\n\n\tcancel() {\n\t\tthis.status = \"canceled\"\n\t}\n\n\tprivate async done() {\n\t\tif (this.results) await this.onDone?.(this.results)\n\n\t\tthis.status = \"done\"\n\t}\n}\n\nconst key = \"run-svgo\"\nconst maxBytesPerSvg = 1_000_000 /* 1 MB */\n\nasync function importSVGAsVectorSetItem(\n\tfile: File,\n\tparentId: NodeID,\n\tpropsOverride?: Record<string, unknown>,\n): Promise<{ node: ShapeContainerNode; size: Size } | undefined> {\n\tif (file.size > maxBytesPerSvg) {\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tvariant: \"error\",\n\t\t\tkey,\n\t\t\tprimaryText: \"SVG is too large.\",\n\t\t\tsecondaryText: \"You may need a PNG.\",\n\t\t\ticon: \"error\",\n\t\t\tduration: 5000,\n\t\t})\n\t\treturn\n\t}\n\n\ttry {\n\t\t// We upload the SVG directly without optimizing, as svgo will slow down the import process\n\t\t// by quite a lot.\n\t\tconst svg = await file.text()\n\t\tconst size = calculateSizeOfSVG(svg)\n\n\t\tconst name = prettifyFileName(file.name)\n\t\tconst shapeContainer = importSVG(svg, CanvasTree.createEmpty, size)\n\t\tif (!shapeContainer) return\n\t\tshapeContainer.parentid = parentId\n\t\tshapeContainer.set({\n\t\t\tname,\n\t\t\tisVectorSetItem: true,\n\t\t\t...propsOverride,\n\t\t})\n\t\treturn { node: shapeContainer, size }\n\t} catch (e) {\n\t\t// biome-ignore lint/suspicious/noConsole: <explanation>\n\t\tconsole.error(\"Failed to insert SVG:\", e)\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: \"your SVG.\",\n\t\t\ticon: \"error\",\n\t\t})\n\t\treturn\n\t}\n}\n\nconst reFileName = /[_-]/gu\n\nfunction prettifyFileName(filename: string) {\n\tconst [name] = splitExtension(filename)\n\treturn capitalizeFirstLetterOfEachWord(name.replace(reFileName, \" \"))\n}\n", "import { assert, ModuleType } from \"@framerjs/shared\"\nimport { moduleTypesForSourceNode } from \"code-generation/moduleTypeForSourceNode.ts\"\nimport type { CanvasTree } from \"document/models/CanvasTree/CanvasTree.ts\"\nimport type { CanvasNode } from \"document/models/CanvasTree/nodes/CanvasNode.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { PersistedModule } from \"modules/ModulesStorage.ts\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport { isNumber, isUndefined } from \"utils/typeChecks.ts\"\nimport { needsUpdateToBeCompatibleWithCms } from \"./cmsVersion.ts\"\n\nconst CurrentWebPageCodeGenVersion = 2\n\n/**\n * Returns a number we can bump when making a backward-incompatible change to\n * code generation for the given node, or undefined if code generation for the\n * given node is not being versioned.\n *\n * The number will be stored in the generated module's metadata.\n *\n * IMPORTANT: This mechanism should be used sparingly, and in particular we\n * agreed to never use it for Smart Components. Or in Adam's words, if you're\n * planning to do this for SCs, \"take a long hard look at yourself in the mirror\n * and turn back.\"\n */\nexport function getCurrentCodeGenVersion(sourceNode: CanvasNode): number | undefined {\n\tif (isWebPageNode(sourceNode)) {\n\t\treturn CurrentWebPageCodeGenVersion\n\t}\n}\n\n/**\n * Returns false if the given node and its corresponding module should be\n * considered incompatible with the current app and need re-generating.\n *\n * If the given node/module's code generation is not being versioned, it's\n * considered to be always compatible.\n *\n * IMPORTANT: This mechanism should be used sparingly, and in particular we\n * agreed to never use it for Smart Components. Or in Adam's words, if you're\n * planning to do this for SCs, \"take a long hard look at yourself in the mirror\n * and turn back.\"\n */\nexport function isCompatibleWithCurrentApp(sourceNode: CanvasNode, module: PersistedModule, tree: CanvasTree): boolean {\n\t// Metadata modules do not track compatibility.\n\tif (module.type === ModuleType.SiteMetadata || module.type === ModuleType.WebPageMetadata) return true\n\n\tconst typeMatches = moduleTypesForSourceNode(sourceNode, tree).includes(module.type as ModuleType)\n\tassert(sourceNode.id === module.name && typeMatches, \"sourceNode and module must match\")\n\n\tif (needsUpdateToBeCompatibleWithCms(module)) return false\n\n\t// At this time, for a module to be considered compatible, we require that\n\t// it was generated using the latest version.\n\tconst requiredCodeGenVersion = getCurrentCodeGenVersion(sourceNode)\n\tif (isUndefined(requiredCodeGenVersion)) {\n\t\t// ... unless this module's code-gen isn't versioned at all, then we\n\t\t// consider it always compatible.\n\t\treturn true\n\t}\n\tconst moduleCodeGenVersion = module.metadata[ModuleMetadata.CodeGenVersion]\n\treturn isNumber(moduleCodeGenVersion) && moduleCodeGenVersion >= requiredCodeGenVersion\n}\n", "import type { PersistedModule } from \"modules/ModulesStorage.ts\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport { isNumber } from \"utils/typeChecks.ts\"\n\n/**\n * This version monitors the compatibility of text styles.\n * Version 0 indicates that the module utilizes style.textWrap instead of style[\"--framer-text-wrap\"].\n * We implemented this modification in version 1 to support text balance overrides.\n */\nexport const currentTextStyleVersion = 1\n\nfunction getCompatibleTextStyleVersion(module: PersistedModule) {\n\tconst version = module.metadata[ModuleMetadata.CompatibleTextStyleVersion]\n\treturn isNumber(version) ? version : 0\n}\n\nexport function needsUpdateToBeCompatibleWithTextStyle(module: PersistedModule) {\n\treturn getCompatibleTextStyleVersion(module) < currentTextStyleVersion\n}\n", "import { openNewTab } from \"@framerjs/app-shared\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { Translatable as T } from \"@framerjs/fresco\"\nimport { getDefaultWebPageTitle } from \"code-generation/components/generateMetadataModule.ts\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport {\n\tisCanvasPageNode,\n\tisCollectionNode,\n\tisSmartComponentNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { Pages, record } from \"web/lib/tracker.ts\"\n\n// NOTE: If the toast will be used in more places, we should generalize this\n// function a bit more. See the discussion here:\n// https://github.com/framer/FramerStudio/pull/13494#pullrequestreview-1253223879\nexport function prettyTypeForNode(node: CanvasNode, tree: CanvasTree) {\n\tif (isSmartComponentNode(node)) {\n\t\treturn \"Smart Component\"\n\t} else if (isWebPageNode(node)) {\n\t\treturn \"web page\"\n\t} else if (isCanvasPageNode(tree.get(node.parentid))) {\n\t\treturn \"prototype screen\"\n\t} else if (isCanvasPageNode(node)) {\n\t\treturn \"prototype\"\n\t} else if (isCollectionNode(node)) {\n\t\treturn \"CMS collection\"\n\t}\n\t// Not all types have a pretty name\n}\n\nexport function nameForTooLargeNode(tree: CanvasTree, componentLoader: ComponentLoader, node: CanvasNode) {\n\treturn isWebPageNode(node)\n\t\t? getDefaultWebPageTitle(tree, componentLoader, node)\n\t\t: (node.resolveValue(\"name\") ?? undefined)\n}\n\n/**\n * @param id Any unique ID for this module so the toast does not repeat\n * @param type A user readable type, when not provided will be \u201Cmodule\u201D\n * @param name A name the user can use to identify the node\n */\nexport function showModuleTooLargeToast(id: string, type: string = \"module\", name?: string) {\n\tconst reasonAndConsequence = \"is too large and will not update\"\n\tconst text = name ? (\n\t\t<>\n\t\t\t<T>The {type}</T> \u201C{name}\u201D <T>{reasonAndConsequence}</T>\n\t\t</>\n\t) : (\n\t\t<T>\n\t\t\tA {type} {reasonAndConsequence}\n\t\t</T>\n\t)\n\n\ttoast({\n\t\ttype: \"add\",\n\t\tvariant: \"warning\",\n\t\ttext,\n\t\tkey: `module-too-large-${id}`,\n\t\tduration: Infinity,\n\t\textraAction: {\n\t\t\ttitle: \"Learn more\",\n\t\t\tonClick() {\n\t\t\t\trecord(\"ui_interaction\", { page: Pages.moduleTooLargeToast, id: \"learn_more\" })\n\t\t\t\topenNewTab(\"https://www.framer.com/help/articles/how-to-fix-module-too-large-warning/\")\n\t\t\t},\n\t\t},\n\t})\n\tconst page = `${Pages.moduleTooLargeToast}-${type.split(\" \").join(\"-\")}`\n\trecord(\"ui_impression\", { page })\n}\n", "import { ErrorCodes } from \"@framerjs/app-shared\"\nimport type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport type { ModulesAPI } from \"@framerjs/framer-services\"\nimport { ServiceError } from \"@framerjs/framer-services\"\nimport type { LocalModuleId, ModuleType } from \"@framerjs/shared\"\nimport { assert, DebouncedTask, getLogger, localModuleIdForStableName } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { currentCmsVersion, supportsCmsImports } from \"code-generation/cmsVersion.ts\"\nimport { getCurrentCodeGenVersion } from \"code-generation/codeGenVersion.ts\"\nimport type { SourceCodeWithArtifacts } from \"code-generation/components/GeneratedComponent.ts\"\nimport { currentTextStyleVersion } from \"code-generation/textStyleVersion.ts\"\nimport {\n\tnameForTooLargeNode,\n\tprettyTypeForNode,\n\tshowModuleTooLargeToast,\n} from \"document/components/chrome/shared/ModuleTooLargeToast.tsx\"\nimport { getDefaultName } from \"document/components/utils/nodes.ts\"\nimport type { CanvasNode, CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { ErrorListNode } from \"document/models/CanvasTree/nodes/ErrorListNode.ts\"\nimport {\n\tErrorNode,\n\tErrorNodeReason,\n\tErrorNodeType,\n\tscopeIdForErrorSourceNode,\n} from \"document/models/CanvasTree/nodes/ErrorNode.ts\"\nimport { isAnyTextNode } from \"document/models/CanvasTree/nodes/utils/isAnyTextNode.ts\"\nimport {\n\tisCanvasPageNode,\n\tisCollectionNode,\n\tisFrameNode,\n\tisPresetsListNode,\n\tisRootNode,\n\tisTextStylePresetNode,\n\tisVectorSetNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { withReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport { isVectorSetItem } from \"document/models/CanvasTree/traits/WithVectorSetItem.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport type { TreeStore } from \"document/stores/TreeStore.ts\"\nimport type { PersistOptions, PersistParams, PersistedModule } from \"modules/ModulesStorage.ts\"\nimport { ModuleMetadata } from \"modules/types.ts\"\nimport type { LockQueueItem } from \"./LockQueue.ts\"\nimport { LockQueue } from \"./LockQueue.ts\"\nimport {\n\tisPersistedModuleSourceNode,\n\tlocalModuleIdsForSourceNode,\n\tmoduleNameForSourceNode,\n} from \"./moduleSourceNodeHelpers.ts\"\n\n/**\n * Delay (in ms) for module changes during normal editing.\n * System debounce changes and persists them after 10 seconds of inactivity,\n * then waits for the engine to become idle.\n * This longer delay prioritizes rendering performance while users actively edit a document.\n */\nconst BACKGROUND_PERSISTENCE_DELAY = 10_000\n\n/**\n * Delay (in ms) for module changes when switching scopes.\n * System uses this shorter delay to save changes quickly when users switch scopes,\n * which enables:\n * 1. Users can confirm changes and close tabs safely\n * 2. System optimizes scope switches within 1s window\n * 3. System reverts to BACKGROUND_PERSISTENCE_DELAY if the user resumes editing\n */\nconst SCOPE_CHANGE_PERSISTENCE_DELAY = 1000\n\nconst log = getLogger(\"CodeGenerationStore\")\n\nfunction persistsTreeJSON(sourceNode: CanvasNode) {\n\tif (isCollectionNode(sourceNode)) return false\n\tif (isCanvasPageNode(sourceNode)) return false\n\tif (isRootNode(sourceNode)) return false\n\tif (isFrameNode(sourceNode)) return false\n\tif (isPresetsListNode(sourceNode)) return false\n\t// Vector Sets don't persist a tree json, instead each Vector persists itself, and the Vector\n\t// Set variables. When detaching, we will create a single new scope node to contain all of the\n\t// detached vectors, using the \"__vectorSetVariables\" field of each Vector.\n\tif (isVectorSetNode(sourceNode)) return false\n\n\treturn true\n}\n\nfunction createVectorSetVariables(tree: CanvasTree, node: CanvasNode) {\n\tif (!isVectorSetItem(node)) return\n\tconst vectorSet = tree.getScopeNodeFor(node)\n\tassert(isVectorSetNode(vectorSet), \"Vector set item must be in a VectorSetNode.\")\n\treturn vectorSet.variables\n}\n\nfunction getModuleTitleForNode(componentLoader: ComponentLoader, node: CanvasNode): string {\n\tconst trimmedName = node.resolveValue(\"name\")?.trim()\n\tif (trimmedName) return trimmedName\n\n\t// The default name of a text node is the text content, which is often very long, and can cause\n\t// module generation to fail.\n\tif (isAnyTextNode(node)) return Dictionary.Text\n\n\treturn getDefaultName(componentLoader, node, node.__class)\n}\n\nfunction storageUpdateForArtifacts(\n\ttree: CanvasTree,\n\tcomponentLoader: ComponentLoader,\n\tnode: CanvasNode,\n\ttype: ModuleType,\n\tname: string,\n\tartifacts: SourceCodeWithArtifacts[\"artifacts\"],\n): PersistParams {\n\tconst update: Omit<PersistOptions, \"files\"> = {}\n\n\tconst title = getModuleTitleForNode(componentLoader, node)\n\n\t// Update metadata fields on the module.\n\tif (!update.metadata) update.metadata = {}\n\n\tconst files: ModulesAPI.FileUpload[] = [...(artifacts?.files ?? [])]\n\n\t// Persist the component's isolated canvas so that users without access\n\t// to the current project can \"fork\" the source node. We don't store\n\t// this for screens on canvas pages because they tend to be too large,\n\t// and we don't actually need to support forking them anyway.\n\tif (persistsTreeJSON(node)) {\n\t\tfiles.push({\n\t\t\tname: \"tree.json\",\n\t\t\ttype: \"nodeTree\",\n\t\t\tcontent: JSON.stringify(\n\t\t\t\tObject.assign(node.toJS(), {\n\t\t\t\t\t__treeSerializationVersion: tree.serializationVersion,\n\t\t\t\t\t__vectorSetVariables: createVectorSetVariables(tree, node),\n\t\t\t\t}),\n\t\t\t),\n\t\t})\n\t}\n\n\tconst codeGenVersion = getCurrentCodeGenVersion(node)\n\tif (codeGenVersion) {\n\t\tupdate.metadata[ModuleMetadata.CodeGenVersion] = codeGenVersion\n\t}\n\n\tconst packageDependencies = artifacts?.packageDependencies\n\tif (packageDependencies) {\n\t\tupdate.metadata[ModuleMetadata.PackageDependencies] = Array.from(packageDependencies)\n\t}\n\n\tif (supportsCmsImports(type)) {\n\t\tupdate.metadata[ModuleMetadata.CompatibleCmsVersion] = currentCmsVersion\n\t}\n\n\tif (isTextStylePresetNode(node)) {\n\t\tupdate.metadata[ModuleMetadata.CompatibleTextStyleVersion] = currentTextStyleVersion\n\t}\n\n\tupdate.assets = artifacts?.assets ? Array.from(artifacts.assets) : []\n\n\treturn { ...update, title, files, errors: artifacts?.errors ?? [], type, name }\n}\n\nasync function handleError(\n\tnode: CanvasNode,\n\te: unknown,\n\tcomponentLoader: ComponentLoader,\n\ttreeStore: TreeStore,\n\tscheduleDocumentUpdateIgnoringUndo: <T>(task: (latestTree: CanvasTree) => T) => Promise<T | undefined>,\n) {\n\tif (node && e instanceof ServiceError && e.code === ErrorCodes.ClientFileTooLarge) {\n\t\tconst scopeId = scopeIdForErrorSourceNode(node, id => treeStore.treeIndex.getScopeIdFor(id)) ?? undefined\n\n\t\tconst error = new ErrorNode({\n\t\t\ttype: ErrorNodeType.CodeGeneration,\n\t\t\tnodeId: withReplicaVariants(node)\n\t\t\t\t? // Assigning the nodeId to the base variants for Smart\n\t\t\t\t\t// Components and Webpages will allow them to show a warning\n\t\t\t\t\t// in the layer panel.\n\t\t\t\t\tnode.baseVariantId\n\t\t\t\t: node.id,\n\t\t\treason: ErrorNodeReason.FileTooLarge,\n\t\t\tsourceNodeId: node.id,\n\t\t\tscopeId,\n\t\t})\n\n\t\tshowModuleTooLargeToast(\n\t\t\tnode.id,\n\t\t\tprettyTypeForNode(node, treeStore.tree),\n\t\t\tnameForTooLargeNode(treeStore.tree, componentLoader, node),\n\t\t)\n\n\t\tawait scheduleDocumentUpdateIgnoringUndo(tree => {\n\t\t\tif (tree.isViewOnly) return\n\t\t\ttree.lineage.setEditReason(\"codegeneration\")\n\t\t\tconst listNode = ErrorListNode.ensure(tree)\n\t\t\tlog.debug(\"Writing ClientFileTooLarge error to tree for\", node.id)\n\t\t\ttree.insertNode(error, listNode.id)\n\t\t})\n\t} else {\n\t\tlog.reportError(e)\n\t}\n}\n\n/**\n * Synchronize the persistence of transient modules and artifacts with the backend.\n * Only persisted modules will be shared across sessions.\n */\nexport class CodeGenerationPersistenceQueue {\n\tconstructor(\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly treeStore: TreeStore,\n\t\tprivate readonly modulesStore: ModulesStore,\n\t\tprivate readonly runWhenIdle: (task: () => void) => void,\n\t\tprivate readonly scheduleDocumentUpdateIgnoringUndo: <T>(\n\t\t\ttask: (latestTree: CanvasTree) => T,\n\t\t) => Promise<T | undefined>,\n\t\tabortSignal?: AbortSignal,\n\t) {\n\t\tthis.#debounce = new DebouncedTask({\n\t\t\tdelay: BACKGROUND_PERSISTENCE_DELAY,\n\t\t\ttask: () => this.runWhenIdle(() => void this.#lock.synchronize()),\n\t\t\tabortSignal,\n\t\t})\n\t}\n\n\t#lock = new LockQueue()\n\t#debounce: DebouncedTask\n\n\t/**\n\t * Schedule persistence of the latest transient modules for a source node,\n\t * including any metadata that was created during serialization. If\n\t * persistence of any modules for the source node fails, create an ErrorNode\n\t * if the module has grown too large.\n\t */\n\tprivate enqueue(tree: CanvasTree, id: NodeID, source: SourceCodeWithArtifacts[]) {\n\t\t// Remove requests for the id that haven't been initiated yet from the\n\t\t// queue.\n\t\tthis.#lock.snapshot((item: LockQueueItem) => {\n\t\t\tif (item.promise.isResolved()) return false\n\t\t\tif (item.id === id) return item.promise.state !== \"initial\"\n\t\t\treturn true\n\t\t})\n\n\t\tconst node = tree.get(id)\n\t\tif (!node || !isPersistedModuleSourceNode(node, tree)) {\n\t\t\treturn\n\t\t}\n\n\t\tconst name = moduleNameForSourceNode(node)\n\n\t\t// Create the updates immediately so that we don't keep\n\t\t// SourceCodeWithArtifacts[] in memory.\n\t\tconst updates: Record<LocalModuleId, PersistParams> = {}\n\t\tfor (const { type, artifacts } of source) {\n\t\t\tconst update = storageUpdateForArtifacts(tree, this.componentLoader, node, type, name, artifacts)\n\t\t\tupdates[localModuleIdForStableName(type, name)] = update\n\t\t}\n\n\t\t// Push the request to the queue that will persist the module and record\n\t\t// any errors, but don't synchronize the queue yet.\n\t\tvoid this.#lock.request(\n\t\t\tasync () => {\n\t\t\t\ttry {\n\t\t\t\t\tlog.debug(\"Persisting transient modules for\", id)\n\t\t\t\t\tawait this.modulesStore.upsertBatch(updates)\n\t\t\t\t} catch (e) {\n\t\t\t\t\tawait handleError(node, e, this.componentLoader, this.treeStore, this.scheduleDocumentUpdateIgnoringUndo)\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ id, synchronize: false },\n\t\t)\n\t}\n\n\t/**\n\t * Persist the latest transient modules for a single source node along with any\n\t * metadata created during the most recent serialization.\n\t */\n\tpersist(id: NodeID, source: SourceCodeWithArtifacts[], debounce: true): void\n\tasync persist(id: NodeID, source: SourceCodeWithArtifacts[]): Promise<(PersistedModule | undefined)[] | undefined>\n\tasync persist(\n\t\tid: NodeID,\n\t\tsource: SourceCodeWithArtifacts[],\n\t\tdebounce?: boolean,\n\t\t// biome-ignore lint/suspicious/noConfusingVoidType: This is a valid use of void in this context.\n\t): Promise<(PersistedModule | undefined)[] | undefined | void> {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tconst node = tree.get(id)\n\t\tif (!node) return\n\n\t\tthis.enqueue(tree, id, source)\n\t\tif (debounce) return this.#debounce.debounce()\n\n\t\tawait this.#lock.synchronize()\n\n\t\t// Return the PersistedModules for the source node, allowing access to\n\t\t// the exact import URL of the resource.\n\t\treturn localModuleIdsForSourceNode(node, tree).map(localId => {\n\t\t\treturn this.modulesStore.getPersistedModuleByLocalId(localId)\n\t\t})\n\t}\n\n\t/**\n\t * Persist a batch of transient modules from multiple source nodes.\n\t */\n\tasync persistBatch(sources: Record<NodeID, SourceCodeWithArtifacts[]>) {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tconst updates: Record<LocalModuleId, PersistParams> = {}\n\n\t\tlet requestId = \"batch\"\n\t\tfor (const id in sources) {\n\t\t\tconst node = tree.get(id)\n\t\t\tconst sourceWithArtifacts = sources[id]\n\t\t\tif (!node || !sourceWithArtifacts) continue\n\t\t\tconst name = moduleNameForSourceNode(node)\n\t\t\tconst seenLocalIds: Set<LocalModuleId> = new Set()\n\t\t\tfor (const { type, artifacts } of sourceWithArtifacts) {\n\t\t\t\tconst localId = localModuleIdForStableName(type, name)\n\t\t\t\t// A batch should never include duplicate results.\n\t\t\t\tassert(!seenLocalIds.has(localId), \"Duplicate local module id\", localId)\n\t\t\t\tseenLocalIds.add(localId)\n\t\t\t\tupdates[localId] = storageUpdateForArtifacts(tree, this.componentLoader, node, type, name, artifacts)\n\t\t\t\trequestId += `-${localId}`\n\t\t\t}\n\t\t}\n\n\t\t// Remove duplicate batch requests that haven't been initiated yet from the queue.\n\t\tthis.#lock.snapshot((item: LockQueueItem) => {\n\t\t\tif (item.promise.isResolved()) return false\n\t\t\tif (item.id === requestId) return item.promise.state !== \"initial\"\n\t\t\treturn true\n\t\t})\n\n\t\tawait this.#lock.request(\n\t\t\tasync () => {\n\t\t\t\tlog.debug(\"Persisting transient modules for batch: \", requestId)\n\t\t\t\ttry {\n\t\t\t\t\tawait this.modulesStore.upsertBatch(updates)\n\t\t\t\t} catch (e) {\n\t\t\t\t\tlog.reportError(e)\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ id: requestId, synchronize: true },\n\t\t)\n\t}\n\n\t/**\n\t * Await persistence of all pending transient modules.\n\t */\n\tprocess = this.#lock.synchronize\n\n\t/**\n\t * Await persistence of all pending transient modules with progress reporting.\n\t */\n\tprocessWithProgress = this.#lock.synchronizeWithProgress\n\n\t/**\n\t * Debounce persistence for 1s instead of 10s after switching scopes, then\n\t * wait for an idle engine frame. This ensures that quickly switching scopes\n\t * doesn't lock up the editor performing lots of persistence, and instead\n\t * allows the ModulesStore to prioritize evaluating modules that need to be\n\t * rerendered to reflect changes.\n\t *\n\t * This short debounce will be reset to 10s if new code is generated. That\n\t * is fine since the user is now actively editing again. We are trying to\n\t * avoid the case where you make a change, view it, then close the tab and\n\t * get prompted to wait for everything to be saved.\n\t */\n\tchangeScope = () => this.#debounce.debounce(SCOPE_CHANGE_PERSISTENCE_DELAY)\n\n\tisIdle = () => this.#lock.size === 0\n\n\tget size() {\n\t\treturn this.#lock.size\n\t}\n\n\t/**\n\t * Prevent unloading if there are any modules that are being persisted. Only\n\t * tasks with pending promises are blocking. Uninitialized tasks are not\n\t * blocking since the modules can be regenerated in a new session.\n\t */\n\tisBlocking = () => this.#lock.snapshot().some(item => item.promise.state === \"pending\")\n}\n", "import type { AssetMap } from \"@framerjs/assets\"\nimport type { AnyComponentLoader, ComponentLoader } from \"@framerjs/framer-runtime\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport {\n\tDebouncedTask,\n\tModuleType,\n\tResolvablePromise,\n\tasLocalId,\n\tassert,\n\tassertNever,\n\tgetLogger,\n\tisLocalModuleIdentifier,\n\tlocalModuleIdForStableName,\n\tparseModuleIdentifier,\n\tunhandledError,\n} from \"@framerjs/shared\"\nimport { experiments } from \"app/experiments.ts\"\nimport type { LayoutMeasurement } from \"canvas-sandbox/layout-measuring/LayoutMeasureQueue.ts\"\nimport { CodeGenerationTelemetrySession } from \"code-generation/TelemetrySession.ts\"\nimport { needsUpdateToBeCompatibleWithCms } from \"code-generation/cmsVersion.ts\"\nimport { serializeCollection } from \"code-generation/components/GeneratedCollection.ts\"\nimport type { SourceCodeSerializer, SourceCodeWithArtifacts } from \"code-generation/components/GeneratedComponent.ts\"\nimport { serializeComponentPresets } from \"code-generation/components/GeneratedComponentPresets.ts\"\nimport { serializePrototypeComponent } from \"code-generation/components/GeneratedPrototypeComponent.ts\"\nimport { serializePrototypeScreenComponent } from \"code-generation/components/GeneratedPrototypeScreenComponent.ts\"\nimport { serializeStylePreset } from \"code-generation/components/GeneratedStylePreset.ts\"\nimport { serializeComponentFromCanvas } from \"code-generation/components/GeneratedVariantComponent.ts\"\nimport { generateSiteMetadataModule } from \"code-generation/components/generateMetadataModule.ts\"\nimport { generateSnippetsModule } from \"code-generation/components/generateSnippetsModule.ts\"\nimport { getGeneratedByFramerComment } from \"code-generation/components/getGeneratedByFramerComment.ts\"\nimport type { ProcessDependencies } from \"code-generation/components/processNodes/types.ts\"\nimport { serializeVector } from \"code-generation/components/serializeVector.ts\"\nimport { serializeVectorSet } from \"code-generation/components/serializeVectorSet.ts\"\nimport { serializeJS } from \"code-generation/js/serializeJS.ts\"\nimport { moduleTypesForSourceNode } from \"code-generation/moduleTypeForSourceNode.ts\"\nimport type { EngineChanges } from \"document/EngineChanges.ts\"\nimport { EngineStore } from \"document/EngineStore.ts\"\nimport { vectorImportBatchSize } from \"document/components/chrome/shared/VectorImport.ts\"\nimport type { NodeChange } from \"document/models/CanvasTree/TreeDiff.ts\"\nimport type { NodeChangesReader, TreeUpdater } from \"document/models/CanvasTree/TreeUpdater.ts\"\nimport type {\n\tAnyScopeNode,\n\tCanvasNode,\n\tCanvasTree,\n\tCollectionNode,\n\tLayoutTemplateNode,\n\tNodeID,\n\tScopeNode,\n\tShallowScopeNode,\n\tSmartComponentNode,\n\tWebPageNode,\n} from \"document/models/CanvasTree/index.ts\"\nimport { isScopeNode } from \"document/models/CanvasTree/index.ts\"\nimport type { PresetsListNode } from \"document/models/CanvasTree/nodes/PresetsListNode.ts\"\nimport type { VectorSetNode } from \"document/models/CanvasTree/nodes/VectorSetNode.ts\"\nimport {\n\tCUSTOM_CODE_SCOPE_ID,\n\tCustomCodeScopeNode,\n} from \"document/models/CanvasTree/nodes/custom-code/CustomCodeScopeNode.ts\"\nimport type { StylePresetNode } from \"document/models/CanvasTree/nodes/utils/isStylePresetNode.ts\"\nimport { isStylePresetNode } from \"document/models/CanvasTree/nodes/utils/isStylePresetNode.ts\"\nimport {\n\tisCanvasPageNode,\n\tisCodeComponentNode,\n\tisCollectionItemNode,\n\tisCollectionNode,\n\tisContentManagementNode,\n\tisCustomCodeScopeNode,\n\tisDataRepeater,\n\tisDesignPageNode,\n\tisLayoutTemplateNode,\n\tisPresetsListNode,\n\tisRootNode,\n\tisSmartComponentNode,\n\tisVectorSetNode,\n\tisWebPageNode,\n} from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { hasCollectionDataSourceChanged } from \"document/models/CanvasTree/traits/WithCollectionDataSource.ts\"\nimport type { WithModuleSourceRevision } from \"document/models/CanvasTree/traits/WithModuleRevision.ts\"\nimport {\n\thasModuleRevisionHintChanged,\n\tusesModuleRevision,\n} from \"document/models/CanvasTree/traits/WithModuleRevision.ts\"\nimport { withReplicaVariants } from \"document/models/CanvasTree/traits/WithReplicaVariants.ts\"\nimport type { IsVectorSetItem } from \"document/models/CanvasTree/traits/WithVectorSetItem.ts\"\nimport { isVectorSetItem } from \"document/models/CanvasTree/traits/WithVectorSetItem.ts\"\nimport { webMetadataDefaults } from \"document/models/CanvasTree/traits/WithWebMetadata.ts\"\nimport {\n\thasRevisionHintChanged,\n\tupdateModuleRevision,\n\tupdateVectorSetItemsModuleRevisions,\n} from \"document/models/CanvasTree/traits/utils/calculateModuleRevision.ts\"\nimport { CodeGenerationPersistenceQueue } from \"document/utils/CodeGenerationPersistenceQueue.ts\"\nimport { addBeforeUnloadHandler } from \"document/utils/beforeUnloadHandler.ts\"\nimport { isDrawablePageGroundNode } from \"document/utils/isDrawablePageGroundNode.ts\"\nimport {\n\tallModulesExistForSourceNode,\n\tisValidModuleSourceNode,\n\tlocalModuleIdsForSourceNode,\n\tmoduleNameForSourceNode,\n} from \"document/utils/moduleSourceNodeHelpers.ts\"\nimport { environment } from \"environment/index.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport type { Size } from \"library/render/types/Size.ts\"\nimport type { HandleUpdateSourceOptions, ModuleUpdateSource } from \"modules/ModulesStorage.ts\"\nimport { splitTypeSlashName } from \"modules/utils.ts\"\nimport { randomBase62 } from \"utils/base62.ts\"\nimport { getId } from \"utils/getId.ts\"\nimport { join } from \"utils/join.ts\"\nimport { isNumber, isUndefined } from \"utils/typeChecks.ts\"\nimport { Pages, UIInteraction, record } from \"web/lib/tracker.ts\"\nimport { hasLink } from \"../models/CanvasTree/traits/WithLink.ts\"\nimport { isLinkToWebPage } from \"../models/CanvasTree/traits/utils/Link.ts\"\nimport type { AIGenerationStore } from \"./AIGenerationStore.ts\"\nimport type { ModulesStore } from \"./ModulesStore.ts\"\nimport type { TreeStore } from \"./TreeStore.ts\"\nimport type { VectorsStore } from \"./VectorsStore.ts\"\n\ninterface ComponentSourceNodeGroups {\n\tstylePresets: CanvasNode[]\n\tcomponentPresets: CanvasNode[]\n\tcollections: CanvasNode[]\n\tsmartComponents: CanvasNode[]\n\tscreens: CanvasNode[]\n\tprototypes: CanvasNode[]\n\twebpages: CanvasNode[]\n\tmetadata: CanvasNode[]\n\tlayoutTemplates: CanvasNode[]\n\tsnippets: CanvasNode[]\n}\n\nconst defaultGroups = (): ComponentSourceNodeGroups => ({\n\tstylePresets: [],\n\tcomponentPresets: [],\n\tcollections: [],\n\tsmartComponents: [],\n\tscreens: [],\n\tprototypes: [],\n\twebpages: [],\n\tmetadata: [],\n\tlayoutTemplates: [],\n\tsnippets: [],\n})\n\nconst log = getLogger(\"CodeGenerationStore\")\n\n/**\n * ID of the node which is the source for the generated component.\n *\n * These nodes can be:\n * - SmartComponentNodes\n * - WebPageNodes for responsive screens\n * - CollectionNode\n * - non-isolated Frame and CodeComponent ground nodes for regular screens\n */\ntype ComponentSourceNodeID = NodeID\n\ntype ComponentGenerationQueue = Map<ComponentSourceNodeID, true>\n\nexport enum GenerationCondition {\n\tChangedLocally = 0,\n\tChanged = 1,\n\tForced = 2,\n}\n\nconst VECTOR_SET_GENERATION_DELAY = 500\nconst GENERATION_DELAY = 1500\nconst CMS_GENERATION_DELAY = 5000\nconst MAX_DELAY = 60_000\n\n/**\n * Determines if the root node has a change that requires regenerating the\n * Metadata module\n */\nfunction hasRootNodeChange(change: NodeChange): boolean {\n\tfor (const key in change.to) {\n\t\tif (key in webMetadataDefaults) return true\n\t}\n\n\treturn false\n}\n\n/**\n * We allow vector sets to have instance of the vectors from the sets inside because to enable the\n * site team to easily see the instances in the same scope. To make it feel like they update closer\n * to real time, we reduce the debounce while in a vector set.\n */\nfunction debounceDurationForScope(scope: ScopeNode): number {\n\tif (isVectorSetNode(scope)) return VECTOR_SET_GENERATION_DELAY\n\tif (isContentManagementNode(scope) || isCollectionNode(scope)) return CMS_GENERATION_DELAY\n\treturn GENERATION_DELAY\n}\n\n/**\n * Generate code representation of variants designed on the isolated canvas.\n *\n * Lifecycle:\n * 1.   All changed nodes are passed into the store on every new tree. If they\n *      are variant nodes, they're added to a queue. If a node with the same id\n *      already existed in the queue, and hasn't been processed yet, it's\n *      updated.\n * 2.   Processing is scheduled whenever nodes are added to the queue, and\n *      delayed until the debounce duration has passed, so all changes are\n *      rolled up until there is a window of inactivity. Processing can also be\n *      immediately performed for all Smart Component's that have queued\n *      changes, or a specific SmartComponent, for example when exiting\n *      isolation or converting a tree to a new Smart Component.\n * 3.   Processing kicks off, and any Smart Component that had changes to it's\n *      variants will be regenerated and recompiled.\n * 4.   For each Smart Component, we process every node that has been added to\n *      the component queue. If the node is a Top Level, or Gesture Variant that\n *      has changed since last processing, we transform its overrides into React\n *      Props and CSS Style. If the node is a Primary Variant we transform it's\n *      CanvasNode into a tag, gather any code imports. We cache all of these\n *      results in a GeneratedComponent class.\n * 5.   Finally, we kick of code generation for each unique Smart Component by\n *      serializing the GeneratedComponent class. The end result is a JSX string\n *      that is compiled and persisted with the ModulesStore.\n */\nexport class CodeGenerationStore extends EngineStore {\n\t#pausedCodeGenerations = new Set<NodeID>()\n\t#componentGenerationQueue: ComponentGenerationQueue\n\t#queuedUpdateCallbacks = new Map<NodeID, (() => void)[]>()\n\n\t#nodeChangesReader: NodeChangesReader\n\n\tisIdle(): boolean {\n\t\treturn this.#componentGenerationQueue.size === 0 && this.serialization.isIdle() && this.persistence.isIdle()\n\t}\n\n\tgetMetrics() {\n\t\treturn {\n\t\t\tqueue: this.#componentGenerationQueue.size,\n\t\t\tpaused: this.#pausedCodeGenerations.size,\n\t\t\tserializing: this.#preparing.size,\n\t\t\tpersisting: this.persistence.size,\n\t\t}\n\t}\n\n\tconstructor(\n\t\tprivate readonly componentLoader: ComponentLoader,\n\t\tprivate readonly treeStore: TreeStore,\n\t\tprivate readonly modulesStore: ModulesStore,\n\t\tprivate readonly vectorsStore: VectorsStore,\n\t\tprivate readonly aiGenerationStore: AIGenerationStore,\n\t\tprivate readonly assetMap: AssetMap,\n\t\tprivate readonly timeline: TreeUpdater,\n\t\tprivate readonly engineChanges: EngineChanges,\n\t\tprivate readonly scheduleDocumentUpdateIgnoringUndo: <T>(\n\t\t\ttask: (latestTree: CanvasTree) => T,\n\t\t) => Promise<T | undefined>,\n\t\tprivate readonly updateTreeCache: (scopeNodeId: NodeID) => void,\n\t\tprivate readonly measureNodes: (nodeIds: NodeID[]) => Promise<LayoutMeasurement[] | undefined>,\n\t\tabortSignal?: AbortSignal,\n\t\tcomponentGenerationQueue: ComponentGenerationQueue = new Map(),\n\t) {\n\t\tsuper()\n\t\tthis.#componentGenerationQueue = componentGenerationQueue\n\n\t\tthis.#nodeChangesReader = this.timeline.openNodeChangesReader()\n\n\t\tthis.#moduleGeneration = new DebouncedTask({\n\t\t\tdelay: GENERATION_DELAY,\n\t\t\tmaxDelay: MAX_DELAY,\n\t\t\ttask: () =>\n\t\t\t\tthis.scheduler.runWhenIdle(() => {\n\t\t\t\t\tvoid this.generateAndUpdateQueuedComponents()\n\t\t\t\t}),\n\t\t\tabortSignal,\n\t\t})\n\n\t\tthis.persistence = new CodeGenerationPersistenceQueue(\n\t\t\tthis.componentLoader,\n\t\t\tthis.treeStore,\n\t\t\tthis.modulesStore,\n\t\t\t(task: () => void) => this.scheduler.runWhenIdle(task),\n\t\t\t<T>(task: (tree: CanvasTree) => T) => this.scheduleDocumentUpdateIgnoringUndo(task),\n\t\t\tabortSignal,\n\t\t)\n\n\t\taddBeforeUnloadHandler(\n\t\t\t{\n\t\t\t\t// @TODO - When all source nodes support a module revision hint, we\n\t\t\t\t// don't need to prevent unloading if code is not generated, as future\n\t\t\t\t// clients can easily know to catch up.\n\t\t\t\tcheck: () => {\n\t\t\t\t\tif (environment.isTest) return false\n\t\t\t\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\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 (tree.isViewOnly) return false\n\t\t\t\t\treturn this.hasBlockingUpdates(tree)\n\t\t\t\t},\n\t\t\t\teffect: () => {\n\t\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"Showing Unsaved Changes dialog (generation queue #: \",\n\t\t\t\t\t\tthis.#componentGenerationQueue.size,\n\t\t\t\t\t\t\", component ids to generate: \",\n\t\t\t\t\t\t[...this.#componentGenerationQueue.keys()],\n\t\t\t\t\t\t\")\",\n\t\t\t\t\t)\n\t\t\t\t\tconst metrics = this.getMetrics()\n\t\t\t\t\tif (metrics.paused > 1) {\n\t\t\t\t\t\t// Assume its abnormal to have multiple paused code generations when closing the\n\t\t\t\t\t\t// tab.\n\t\t\t\t\t\tlog.reportError(\"Tab closed with paused code generations\", metrics)\n\t\t\t\t\t} else if (metrics.persisting > 5 || metrics.serializing > 5 || metrics.queue > 5) {\n\t\t\t\t\t\t// Assume its normal to have some code generations in progress when closing the\n\t\t\t\t\t\t// tab, but 6 or more is suspicious.\n\t\t\t\t\t\tlog.reportError(\"Tab closed with multiple code generations in progress\", metrics)\n\t\t\t\t\t}\n\n\t\t\t\t\t// When we close Framer we want to finish code generation for all queued components\n\t\t\t\t\t// even if code generation for them was paused.\n\t\t\t\t\tthis.#pausedCodeGenerations.clear()\n\n\t\t\t\t\tthis.generateAndUpdateQueuedComponents()\n\t\t\t\t\t\t.then(() => {\n\t\t\t\t\t\t\tvoid this.persistence.process()\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.catch(err => log.reportError(err))\n\t\t\t\t},\n\t\t\t},\n\t\t\tabortSignal,\n\t\t)\n\n\t\twindow.addEventListener(\n\t\t\t\"blur\",\n\t\t\tasync () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.flushQueuedCodeGenerationOnWindowBlur()\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlog.reportError(err)\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ signal: abortSignal },\n\t\t)\n\t}\n\n\t/** Release some resources after the document reloads. */\n\tdocumentDidLoad() {\n\t\t// After (re)loading the document, the reasons to code generate are outdated.\n\t\tthis.#componentGenerationQueue.clear()\n\t\tthis.#queuedUpdateCallbacks.clear()\n\n\t\t// The telemetry has indirect references to old nodes and the old tree.\n\t\tthis.#telemetry.clear()\n\t}\n\n\t#moduleGeneration: DebouncedTask\n\n\t#telemetry = new Map<ComponentSourceNodeID, CodeGenerationTelemetrySession>()\n\tprivate telemetrySession(tree: CanvasTree, sourceId: ComponentSourceNodeID) {\n\t\tconst currentSession = this.#telemetry.get(sourceId)\n\t\tif (currentSession) return currentSession\n\t\tconst sourceNode = tree.get(sourceId)\n\t\tassert(sourceNode, \"TelemetrySession: source node must exist\")\n\t\tconst newSession = new CodeGenerationTelemetrySession(sourceNode)\n\t\tthis.#telemetry.set(sourceId, newSession)\n\t\treturn newSession\n\t}\n\n\t#serializationId: string | undefined = undefined\n\tprivate getSerializationId() {\n\t\tif (this.#serializationId) return `framer-${this.#serializationId}`\n\t\treturn `framer-${randomBase62(5)}`\n\t}\n\n\treadonly testing = {\n\t\tsetComponentGenerationQueue: (queue: ComponentGenerationQueue) => {\n\t\t\tthis.#componentGenerationQueue = queue\n\t\t},\n\t\tflushQueuedCallbacks: () => {\n\t\t\tthis.#queuedUpdateCallbacks.forEach(callbacks => callbacks.forEach(callback => callback()))\n\t\t},\n\t\tgenerateAndUpdateQueuedComponents: (moduleType?: ModuleType) => {\n\t\t\treturn this.generateAndUpdateQueuedComponents(moduleType)\n\t\t},\n\t\tsetSerializationId: (id: string | undefined) => {\n\t\t\tthis.#serializationId = id\n\t\t},\n\t\tsetModulesStore: (modulesStore: ModulesStore) => {\n\t\t\tObject.assign(this, { modulesStore })\n\t\t\tObject.assign(this.persistence, { modulesStore })\n\t\t},\n\t\twaitForProcessing: async (id: ComponentSourceNodeID) => {\n\t\t\tawait this.serialization.promise(id)\n\t\t},\n\t}\n\n\tpersistence: CodeGenerationPersistenceQueue\n\n\tprivate async flushQueuedCodeGenerationOnWindowBlur() {\n\t\t// Visible-window blur happens during normal CMS UI transitions, such as adding a field.\n\t\t// Ignoring that case preserves the longer CMS debounce instead of forcing code generation immediately.\n\t\tif (document.visibilityState !== \"hidden\") return\n\t\tawait this.generateAndPersistAllQueuedComponents()\n\t}\n\n\t/**\n\t * Flush the queue of everything that needs code generation and persist\n\t * them.\n\t */\n\tasync generateAndPersistAllQueuedComponents() {\n\t\t// Guarantee there is a site metadata module.\n\t\tawait this.ensureSiteMetadataModule()\n\t\t// Ensure the snippets module is generated.\n\t\tawait this.ensureSnippetsModule()\n\t\t// Ensure tree updates that haven't been serialized are generated.\n\t\tawait this.generateAndUpdateQueuedComponents()\n\t\t// Ensure any serializations that were already running before we called\n\t\t// `generateAndPersistAllQueuedComponents` are completed.\n\t\tawait this.serialization.idle()\n\t\t// Ensure all of the above are persisted.\n\t\tawait this.persistence.process()\n\t}\n\n\t/**\n\t * Get all nodes in a project that can be generated into code.\n\t */\n\tdebugGetComponentSourceNodes(): ComponentSourceNodeGroups {\n\t\tconst groups: ComponentSourceNodeGroups = defaultGroups()\n\n\t\tassert(process.env.NODE_ENV === \"test\", \"This method should only be used in tests.\")\n\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tfor (const { node, skipChildren } of tree.root.walkWithSkipChildren()) {\n\t\t\tif (isWebPageNode(node)) {\n\t\t\t\tgroups.webpages.push(node)\n\t\t\t\tgroups.metadata.push(node)\n\t\t\t\tskipChildren()\n\t\t\t} else if (isSmartComponentNode(node)) {\n\t\t\t\tgroups.smartComponents.push(node)\n\t\t\t\tskipChildren()\n\t\t\t} else if (isCollectionNode(node)) {\n\t\t\t\tgroups.collections.push(node)\n\t\t\t\tskipChildren()\n\t\t\t} else if (isStylePresetNode(node)) {\n\t\t\t\tgroups.stylePresets.push(node)\n\t\t\t\tskipChildren()\n\t\t\t} else if (isPresetsListNode(node)) {\n\t\t\t\tgroups.componentPresets.push(node)\n\t\t\t} else if (isDrawablePageGroundNode(node, tree)) {\n\t\t\t\tgroups.screens.push(node)\n\t\t\t\tskipChildren()\n\t\t\t} else if (isCanvasPageNode(node)) {\n\t\t\t\tgroups.prototypes.push(node)\n\t\t\t} else if (isRootNode(node)) {\n\t\t\t\tgroups.metadata.push(node)\n\t\t\t} else if (isLayoutTemplateNode(node)) {\n\t\t\t\tgroups.layoutTemplates.push(node)\n\t\t\t} else if (isCustomCodeScopeNode(node)) {\n\t\t\t\tgroups.snippets.push(node)\n\t\t\t}\n\t\t}\n\n\t\treturn groups\n\t}\n\n\tpostProcess(tree: CanvasTree, activeScope: ScopeNode, remote: boolean) {\n\t\tif (tree.isViewOnly) return\n\n\t\tif (remote) {\n\t\t\t// When postProcessing after remote changes, clear the reader so\n\t\t\t// that processing future local changes doesn't cause changes made\n\t\t\t// remotely to be generated.\n\t\t\tthis.#nodeChangesReader.clear()\n\t\t\treturn\n\t\t}\n\n\t\t// Ingest all changes into the store.\n\t\tthis.ingestChanges(tree)\n\n\t\t// Otherwise we debounce module generation.\n\t\tthis.#moduleGeneration.debounce(debounceDurationForScope(activeScope))\n\t}\n\n\tprivate ingestChanges(tree: CanvasTree) {\n\t\tfor (const [id, changes] of this.#nodeChangesReader.read()) {\n\t\t\tif (changes.length === 0 || changes.every(change => change.ignoreInCodeGeneration)) continue\n\n\t\t\tconst node = tree.get(id)\n\t\t\tif (!node) continue\n\n\t\t\t// When a WebPageNode\u2019s data source changes, we also need to regenerate\n\t\t\t// the snippets module, because CustomCodeNodes may contain templates\n\t\t\t// for page variables coming from the data source.\n\t\t\tif (isWebPageNode(node) && hasCollectionDataSourceChanged(changes)) {\n\t\t\t\tconst customCodeScopeNode = tree.get(CUSTOM_CODE_SCOPE_ID)\n\t\t\t\tif (customCodeScopeNode) {\n\t\t\t\t\tthis.addChangeToQueue(customCodeScopeNode)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the change is a module revision hint, and the committed hint\n\t\t\t// isn't already equal, we always queue the changed node.\n\t\t\tif (usesModuleRevision(node, tree)) {\n\t\t\t\tif (hasModuleRevisionHintChanged(node, changes)) {\n\t\t\t\t\tthis.addChangeToQueue(node)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Otherwise we still need to queue RootNodes into SiteMetadata\n\t\t\t// modules, CanvasPageNodes into Prototypes, and CanvasPageNode\n\t\t\t// ground nodes into Prototype Screens. These nodes don't implement\n\t\t\t// revision hints currently:\n\t\t\t// - RootNodes would calculate an unchanged revision on every change\n\t\t\t//   to the site, since any change makes the root node a draft,\n\t\t\t//   which would result in wasted cpu.\n\t\t\t// - CanvasPageNodes would waste cpu calculating an unchanged\n\t\t\t//   revision on every change to any prototype screen.\n\t\t\t// - PrototypeScreens are FrameNodes, we don't want every FrameNode\n\t\t\t//   to calculate a revision so we would have to limit it to ground\n\t\t\t//   nodes. This seems like unnecessary edge-cases for a part of the\n\t\t\t//   product we only expose behind a preference.\n\t\t\tif (isRootNode(node)) {\n\t\t\t\tif (!changes.some(hasRootNodeChange)) continue\n\t\t\t\tthis.addChangeToQueue(node)\n\t\t\t} else if (isCanvasPageNode(node)) {\n\t\t\t\tthis.addChangeToQueue(node)\n\t\t\t} else {\n\t\t\t\tconst groundNodeId = this.treeStore.treeIndex.getGroundNodeIdFor(id)\n\t\t\t\tconst groundNode = tree.get(groundNodeId)\n\t\t\t\tif (!groundNode || isCodeComponentNode(groundNode)) continue\n\t\t\t\tconst scopeNode = tree.getScopeNodeFor(groundNode)\n\t\t\t\tif (!isCanvasPageNode(scopeNode)) continue\n\t\t\t\tthis.queueCanvasPageNodesFollowingLinks(tree, groundNode)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Prototypes can use the old Page and Scroll components which render\n\t * content connected by noodles. When the target content is updated we want\n\t * to regenerate the screen that is linked to that content. This can\n\t * technically happen in a chain so we must recurse through these chained\n\t * links. Since any ground node can be a screen which is linked to by a\n\t * prototype, we must queue all of these ground nodes.\n\t */\n\tqueueCanvasPageNodesFollowingLinks(tree: CanvasTree, node: CanvasNode) {\n\t\tthis.addChangeToQueue(node)\n\n\t\tif (!node.cache.links || node.cache.links.size === 0) return\n\n\t\tfor (const link of node.cache.links) {\n\t\t\tconst linkedGroundNodeId = this.treeStore.treeIndex.getGroundNodeIdFor(link)\n\t\t\tconst linkedGroundNode = tree.get(linkedGroundNodeId)\n\t\t\tif (!linkedGroundNode || isCodeComponentNode(linkedGroundNode)) continue\n\t\t\tthis.queueCanvasPageNodesFollowingLinks(tree, linkedGroundNode)\n\t\t}\n\t}\n\n\t/**\n\t * When exiting a scope, prioritize code-generation and persistence to\n\t * reduce the chance that closing the tab shortly after leaving an edited\n\t * page is prevented while modules save.\n\t */\n\tchangeScope(): void {\n\t\t// If the user is a viewer, the session cannot have made changes that\n\t\t// need to be instantly compiled when they exit isolation, so we return\n\t\t// early.\n\t\tif (this.treeStore.tree.isViewOnly) return\n\t\tif (environment.isTest) return\n\t\tif (this.isIdle()) return\n\n\t\tthis.serialization\n\t\t\t.idle()\n\t\t\t// VECTOR @TODO - We should compile any visible vectors in an initial pass, like we do\n\t\t\t// for prioritized evaluation.\n\t\t\t.then(() => this.generateAndUpdateQueuedComponents())\n\t\t\t.then(() => {\n\t\t\t\tif (!experiments.isOn(\"prioritizedModuleEvaluation\")) {\n\t\t\t\t\tvoid this.persistence.process()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Only debounce if we have queued persistence. We don't want to\n\t\t\t\t// schedule a debounce that processes something edited in the\n\t\t\t\t// next 1s.\n\t\t\t\tif (this.persistence.isIdle()) return\n\n\t\t\t\tthis.persistence.changeScope()\n\t\t\t})\n\t\t\t.catch(err => log.reportError(err))\n\t}\n\n\t/**\n\t * When creating a new vector set from a list of items, optimize creation time for the batch.\n\t */\n\tasync createVectorSet(\n\t\tnodes: (CanvasNode & IsVectorSetItem)[],\n\t\treportProgress?: (phase: \"serializing\" | \"persisting\", index: number) => void,\n\t) {\n\t\tconst firstVectorSetItem = nodes[0]\n\t\tif (!firstVectorSetItem) return\n\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tconst vectorSetNode = tree.getScopeNodeFor(firstVectorSetItem)\n\t\tassert(isVectorSetNode(vectorSetNode), \"VectorSet: VectorSetNode must exist.\")\n\n\t\tconst start = performance.now()\n\n\t\tconst vectors = await this.batchSerializeVectors(nodes, reportProgress)\n\t\tif (!vectors) return\n\n\t\t// Compile each Vector Set Item in series. We can only get 1 compilation from the compiler\n\t\t// at a time, and we have to update internal state after each compilation.\n\t\tlet updates: Record<NodeID, SourceCodeWithArtifacts[]> = {}\n\t\tlet index = 0\n\n\t\tconst count = Object.keys(vectors).length\n\n\t\t// Calculate optimal batch size to get even groups of around 100 updates\n\t\tconst batchSize = vectorImportBatchSize(count)\n\t\tconst batches: Record<NodeID, SourceCodeWithArtifacts[]>[] = []\n\t\tfor (const id in vectors) {\n\t\t\tconst source = vectors[id]\n\t\t\tif (!source) continue\n\n\t\t\tupdates[id] = source\n\t\t\tindex++\n\n\t\t\tif (index % batchSize !== 0 && index !== count) continue\n\n\t\t\tbatches.push(updates)\n\t\t\tupdates = {}\n\t\t}\n\n\t\tfor (let i = 0; i < batches.length; i++) {\n\t\t\tconst batch = batches[i]\n\t\t\tif (!batch) continue\n\t\t\tawait this.persistence.persistBatch(batch)\n\t\t\treportProgress?.(\"persisting\", i)\n\t\t}\n\n\t\t// Force the scope node to be compiled to incorporate each new item.\n\t\tawait this.forceComponentUpdate(vectorSetNode.id)\n\n\t\tlog.debug(\"createVectorSet: Spent \", performance.now() - start, \"ms creating a new vector set.\")\n\t}\n\n\t/**\n\t * Immediately generate and persist a module from the component source node.\n\t * For example generating a component module after adding a new smart\n\t * component node and primary variant to the tree. This method skips the\n\t * store's 1.5s minium debounce, while also preventing the source node from\n\t * being unnecessarily regenerated in the next debounce.\n\t *\n\t * This method does not guarantee that repeated calls with an identical\n\t * source node *that has never been generated* before are deduplicated.\n\t * Calling this method many times in the same frame on the same source node\n\t * can overwhelm the modules compiler.\n\t */\n\tasync createModuleFromComponentSource(\n\t\tcomponentSourceNode:\n\t\t\t| SmartComponentNode\n\t\t\t| WebPageNode\n\t\t\t| LayoutTemplateNode\n\t\t\t| CollectionNode\n\t\t\t| StylePresetNode\n\t\t\t| PresetsListNode\n\t\t\t| VectorSetNode\n\t\t\t| (CanvasNode & IsVectorSetItem),\n\t\tintrinsicSize?: Size,\n\t) {\n\t\tlet tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tassert(!tree.isViewOnly, \"CodeGenerationStore: viewers cannot create smart components or web pages.\")\n\t\tassert(\n\t\t\tisValidModuleSourceNode(componentSourceNode, tree),\n\t\t\t\"CodeGenerationStore: componentSourceNode must be a valid component source.\",\n\t\t)\n\n\t\tconst modulesExist = allModulesExistForSourceNode(componentSourceNode, tree, this.modulesStore)\n\t\tif (modulesExist) return\n\n\t\tlog.debug(\"createModuleFromComponentSource\", componentSourceNode.id)\n\n\t\tthis.serialization.prepare(componentSourceNode.id)\n\n\t\treturn tree.withPersistedCaches(async () => {\n\t\t\tconst output = await this.generateComponent(componentSourceNode.id, GenerationCondition.Changed, undefined, {\n\t\t\t\tintrinsicSize,\n\t\t\t})\n\t\t\tif (!output) throw new Error(\"Code not generated\")\n\n\t\t\tawait this.compileOutput(componentSourceNode, output)\n\n\t\t\t// We can't guarantee this function was awaited, so ensure tree isn't stale.\n\t\t\ttree = this.treeStore.getDataTreeOrPartialTree()\n\t\t\treturn localModuleIdsForSourceNode(componentSourceNode, tree).map(localId =>\n\t\t\t\tthis.modulesStore.getPersistedModuleByLocalId(localId),\n\t\t\t)\n\t\t})\n\t}\n\n\trevisionNodes(tree: CanvasTree) {\n\t\tconst nodes: (CanvasNode & WithModuleSourceRevision)[] = []\n\t\tfor (const node of tree.root.children) {\n\t\t\tif (usesModuleRevision(node, tree)) nodes.push(node)\n\t\t\tif (isPresetsListNode(node) || isContentManagementNode(node)) {\n\t\t\t\tnode.children.forEach(child => {\n\t\t\t\t\tif (usesModuleRevision(child, tree)) nodes.push(child)\n\t\t\t\t\tif (isCollectionNode(child)) {\n\t\t\t\t\t\tchild.getUnsortedChildren().forEach(c => {\n\t\t\t\t\t\t\tif (usesModuleRevision(c, tree)) nodes.push(c)\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\treturn nodes\n\t}\n\n\t/**\n\t * Returns a list of nodes that have stale modules.\n\t *\n\t * @param filter - A filter to apply to the nodes to return a subset.\n\t * @param options - When `ignoreHint` is true, we won't include modules that have mismatched\n\t * hints, only modules whose current revision is different than the latest revision in the tree.\n\t */\n\tnodesWithStaleModules<T extends CanvasNode & WithModuleSourceRevision>(\n\t\tfilter?: (n: CanvasNode & WithModuleSourceRevision) => n is T,\n\t\toptions?: { ignoreHint?: boolean },\n\t): T[] {\n\t\tconst nodes: T[] = []\n\t\tconst ignoreHint = options?.ignoreHint ?? false\n\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tfor (const node of this.revisionNodes(tree)) {\n\t\t\tif (isCollectionItemNode(node)) continue\n\t\t\tif (filter && !filter(node)) continue\n\t\t\tif (\n\t\t\t\t// If the node had updates that haven't been factored into a\n\t\t\t\t// moduleSourceRevision we may need to generate.\n\t\t\t\t(!ignoreHint && node.moduleSourceRevisionHint !== node.moduleSourceRevisionCommittedHint) ||\n\t\t\t\t// If the node's revision is different than the latest module\n\t\t\t\t// revision, we need to generate the latest source into the\n\t\t\t\t// module, or if there are multiple revisions, we need to\n\t\t\t\t// regenerate to make them both latest.\n\t\t\t\t!this.allModulesAreAtRevision(tree, node.id)\n\t\t\t) {\n\t\t\t\tnodes.push(node as T)\n\t\t\t}\n\t\t}\n\n\t\treturn nodes\n\t}\n\n\t/**\n\t * Check if code can be serialized for a given node.\n\t * Returns false if the editor is read-only, unless the node is a frame\n\t * that is a child of a DesignPageNode (which can be serialized even in read-only mode).\n\t */\n\tpublic canSerialize(nodeId: NodeID): boolean {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tif (!tree.isViewOnly) return true\n\n\t\t// Design Pages are code-generated on-demand to avoid the build up of old local modules for\n\t\t// deleted frames, which slow projects down. This means that even if we are view-only we\n\t\t// must still generate code.\n\t\tconst node = tree.get(nodeId)\n\t\tif (!node || !tree.isGroundNode(node)) return false\n\t\tconst scope = tree.getScopeNodeFor(node)\n\t\treturn isDesignPageNode(scope)\n\t}\n\n\t/**\n\t * Instantly generate a specific component based on its queued updates. The\n\t * result will be persisted after a debounce duration if there were local\n\t * changes queued.\n\t */\n\tasync updateComponent(\n\t\tcomponentSourceNodeId: NodeID,\n\t\tcondition: GenerationCondition = GenerationCondition.ChangedLocally,\n\t): Promise<boolean> {\n\t\tassert(\n\t\t\tthis.canSerialize(componentSourceNodeId),\n\t\t\t\"CodeGenerationStore: viewers cannot generate smart component or web page updates.\",\n\t\t)\n\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tconst componentSourceNode = tree.get(componentSourceNodeId)\n\t\tif (!componentSourceNode || !isValidModuleSourceNode(componentSourceNode, tree)) return false\n\n\t\t// If the node is already about to be serialized, don't schedule another\n\t\t// serialization, instead wait for the current serialization to finish.\n\t\tif (this.serialization.preparing(componentSourceNodeId)) {\n\t\t\t// @TODO - In the future when all source nodes support a module\n\t\t\t// revision, this promise can return the revision that was being\n\t\t\t// prepared, allowing us to wait for that revision to be compiled.\n\t\t\tawait this.serialization.promise(componentSourceNodeId)\n\t\t\tawait this.untilCompiled(componentSourceNodeId)\n\t\t\treturn true\n\t\t}\n\n\t\tlog.debug(\"Update component: \", componentSourceNodeId, \", Condition: \", condition)\n\n\t\tconst changed = this.#componentGenerationQueue.get(componentSourceNodeId)\n\n\t\tthis.serialization.prepare(componentSourceNodeId)\n\n\t\treturn tree.withPersistedCaches(async () => {\n\t\t\tconst output = await this.generateComponent(componentSourceNodeId, condition, changed)\n\t\t\tif (!output) return false\n\t\t\treturn this.compileOutput(componentSourceNode, output)\n\t\t})\n\t}\n\n\t/**\n\t * forceComponentUpdate can be used instead of updateComponent when you need\n\t * to update a module before the next engine frame or when you need a module\n\t * to update but haven't changed any of the nodes that would cause it to be\n\t * regenerated naturally, for example when upgrading it's generation to make\n\t * it compatible.\n\t *\n\t * Consider if you need to use this method, for example if you just want to\n\t * update a module quickly, you can use the snippet below which will only\n\t * update the module if there are changes that require code-generation.\n\t *\n\t * ```javascript\n\t * engine.scheduler.runBeforeNextFrame(() => {\n\t *      engine.stores.codeGenerationStore.updateComponent(id)\n\t * })\n\t * ```\n\t */\n\tasync forceComponentUpdate(componentSourceNodeId: NodeID): Promise<boolean> {\n\t\tassert(\n\t\t\tthis.canSerialize(componentSourceNodeId),\n\t\t\t\"CodeGenerationStore: viewers cannot generate smart component or web page updates.\",\n\t\t)\n\n\t\tconst update = await this.updateComponent(componentSourceNodeId, GenerationCondition.Forced)\n\t\tif (!update) return false\n\t\tawait this.persistence.process()\n\t\treturn true\n\t}\n\n\t/**\n\t * Queue a callback to be run next time the flagged component is\n\t * (re)generated.\n\t *\n\t * Note, if this callback updates the tree, it will need to be wrapped in\n\t * engine.scheduler.wrapHandler, as the tree may not be editable.\n\t *\n\t * @FIXME - There is no guarantee when this callback will run. It's possible\n\t * to queue a callback after updating some CanvasNodes, but for the callback\n\t * to be invoked before the CodeGenerationStore processes the NodeChanges for\n\t * those nodes. This can happen if an update to the relevant component was\n\t * started before you queued your callback.\n\t */\n\tqueueCallbackAfterComponentCompilation(componentSourceNodeId: NodeID, callback: () => void) {\n\t\tconst queue = this.#queuedUpdateCallbacks.get(componentSourceNodeId)\n\t\tif (queue) {\n\t\t\tqueue.push(callback)\n\t\t} else {\n\t\t\tthis.#queuedUpdateCallbacks.set(componentSourceNodeId, [callback])\n\t\t}\n\t}\n\n\tuntilCompiled(componentSourceNodeId: string): Promise<void> {\n\t\treturn new Promise(resolve => {\n\t\t\tthis.queueCallbackAfterComponentCompilation(componentSourceNodeId, resolve)\n\t\t})\n\t}\n\n\t// Private API //\n\n\t/**\n\t * When a node that supports a module revision is updated, its module\n\t * revision hint will be incremented. This tells us that something inside\n\t * the source node is likely to have changed. If we detect this when we are\n\t * code-generating, we calculate the full module revision by hashing the\n\t * node and its descendants. When we do that we can wipe the hints to let\n\t * other clients know the current module revision is factors in all latest\n\t * changes.\n\t */\n\tprivate calculateNewModuleRevision(id: NodeID): Promise<number | undefined> | number | undefined {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tconst sourceNode = tree.get(id)\n\t\tif (!sourceNode || !usesModuleRevision(sourceNode, tree)) return 1\n\n\t\t// Skip the hint check for the CustomCodeScopeNode,\n\t\t// because its revision depends on the dataIdentifier of CMS pages\n\t\t// that may be referenced from CustomCodeNodes.\n\t\t// There is no logic to update the revision hint for the CustomCodeScopeNode\n\t\t// when a related WebPageNode\u2019s dataIdentifier changes.\n\t\tconst shouldCheckHint = !isCustomCodeScopeNode(sourceNode)\n\n\t\t// If the revision hint hasn't changed since the revision was last\n\t\t// calculated, there's nothing to do. This is true even for CollectionNodes,\n\t\t// where the revision of child CollectionItemNodes is calculated first.\n\t\tif ((shouldCheckHint && !hasRevisionHintChanged(tree, id)) || !tree.has(id)) {\n\t\t\treturn undefined\n\t\t}\n\n\t\treturn updateModuleRevision(id, this.scheduleDocumentUpdateIgnoringUndo)\n\t}\n\n\t/**\n\t * Check if all of the modules for a source node were generated from the\n\t * current module revision of that source node. This allows us to avoid\n\t * unnecessary generations.\n\t */\n\tprivate allModulesAreAtRevision(tree: CanvasTree, componentSourceNodeId: NodeID, nextRevision?: number): boolean {\n\t\tconst sourceNode = tree.get(componentSourceNodeId)\n\t\tif (!sourceNode || !usesModuleRevision(sourceNode, tree)) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst currentRevision = nextRevision ?? sourceNode.moduleSourceRevision\n\t\treturn moduleTypesForSourceNode(sourceNode, tree).every(type => {\n\t\t\tconst moduleHandle = this.modulesStore.forType(type).getByStableName(moduleNameForSourceNode(sourceNode))\n\t\t\treturn moduleHandle.sourceRevision() === currentRevision\n\t\t})\n\t}\n\n\tasync ensureDependencyModulesExist() {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tfor (const node of this.revisionNodes(tree)) {\n\t\t\tif (!isValidModuleSourceNode(node, tree)) continue\n\t\t\tif (allModulesExistForSourceNode(node, tree, this.modulesStore)) continue\n\t\t\ttry {\n\t\t\t\tawait this.updateComponent(node.id)\n\t\t\t} catch (error) {\n\t\t\t\tlog.error(\"Error updating dependency module\", node.id, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async ensureSourceNode(componentSourceNodeId: NodeID) {\n\t\tconst node = this.treeStore.getDataTreeOrPartialTree().get(componentSourceNodeId)\n\t\tconst sourceNode = isScopeNode(node) && !node.isLoaded() ? await node.load() : node\n\t\tif (!sourceNode) return\n\n\t\t// Ensure that the siteMetadata module exists before generating a web\n\t\t// page.\n\t\tif (isWebPageNode(sourceNode)) {\n\t\t\tawait this.ensureSiteMetadataModule()\n\t\t\tassert(sourceNode.loaded, \"WebPageNode must be loaded\")\n\t\t\tawait this.ensureReferencedCollectionsExportUpToDateEnumUtils(sourceNode.loaded)\n\t\t}\n\n\t\tif (isCollectionNode(sourceNode)) {\n\t\t\tawait this.ensureDependentModulesAreCompatibleWithCollection(sourceNode)\n\t\t}\n\n\t\tif (isVectorSetItem(sourceNode)) {\n\t\t\t// Ensure that the Set for a Vector has been persisted before generating the Vector. The\n\t\t\t// Vector includes an annotation referencing the module id of the Set.\n\t\t\tconst set = this.treeStore.getDataTreeOrPartialTree().getScopeNodeFor(sourceNode)\n\t\t\tif (!isVectorSetNode(set)) return\n\t\t\tconst localId = localModuleIdForStableName(ModuleType.VectorSet, set.id)\n\t\t\tif (this.modulesStore.getModuleEntryByLocalId(localId)) return\n\t\t\tawait this.createModuleFromComponentSource(set)\n\t\t}\n\n\t\tawait this.ensureAllNodesWithLinksHaveLinkedScopesLoaded(sourceNode)\n\t}\n\n\tprivate async ensureSiteMetadataModule() {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tif (tree.isViewOnly) return\n\t\tconst rootNode = tree.root\n\t\tconst exists = allModulesExistForSourceNode(rootNode, tree, this.modulesStore)\n\t\tif (exists) return\n\n\t\treturn this.updateComponent(rootNode.id)\n\t}\n\n\tprivate async ensureSnippetsModule() {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tif (tree.isViewOnly) return\n\t\tconst scope = CustomCodeScopeNode.get(tree)\n\t\tif (!scope) return\n\n\t\tconst loadedScope = await scope.load()\n\t\tif (!loadedScope) return\n\n\t\tconst exists = allModulesExistForSourceNode(loadedScope, tree, this.modulesStore)\n\t\tif (exists) return\n\n\t\treturn this.updateComponent(loadedScope.id)\n\t}\n\n\tprivate hasBlockingUpdates(tree: CanvasTree) {\n\t\tif (this.#componentGenerationQueue.size > 0) {\n\t\t\tfor (const [id, localChanges] of this.#componentGenerationQueue) {\n\t\t\t\tif (tree.has(id) && localChanges) return true\n\t\t\t}\n\t\t}\n\t\tif (!this.persistence.isIdle()) return true\n\t\tif (!this.serialization.isIdle()) return true\n\n\t\treturn false\n\t}\n\n\tprivate async updateModules(componentSourceNodeId: NodeID, sources: SourceCodeWithArtifacts[]): Promise<boolean> {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tconst componentSourceNode = tree.get(componentSourceNodeId)\n\t\tconst treeVersion = this.timeline.remoteTreeVersion\n\t\tif (!componentSourceNode || !isValidModuleSourceNode(componentSourceNode, tree)) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst moduleUpdates: ModuleUpdateSource[] = []\n\t\t// First pass: prepare all updates and validate\n\t\tfor (const { revision, source, type, artifacts } of sources) {\n\t\t\tconst options: HandleUpdateSourceOptions = {\n\t\t\t\tassets: artifacts?.assets,\n\t\t\t\tsubmodules: artifacts?.submodules,\n\t\t\t\tbinaryAssets: artifacts?.binaryAssets,\n\t\t\t\t// TODO: This probably shouldn't be a moduleType check?\n\t\t\t\t// And also, can responsive screens have circular imports?\n\t\t\t\tpreventCircularImports: type === ModuleType.Canvas,\n\t\t\t\ttelemetrySession: this.telemetrySession(tree, componentSourceNodeId),\n\t\t\t\ttreeVersion,\n\t\t\t\tsourceRevision: revision,\n\t\t\t\tkitSectionsStructure: artifacts?.kitSectionsStructure,\n\t\t\t\tsvgIcon: artifacts?.files?.find(file => file.type === \"svgIcon\")?.content,\n\t\t\t\tstableName: true,\n\t\t\t}\n\n\t\t\tconst moduleHandle = this.modulesStore.forType(type).getByStableName(moduleNameForSourceNode(componentSourceNode))\n\t\t\tconst needsRevisionUpdate = moduleHandle.sourceRevision() !== revision\n\n\t\t\tconst serialized = join.sections(getGeneratedByFramerComment(), source)\n\t\t\t// A module might generate the same source as before, but with a different revision, e.g., if we change\n\t\t\t// the revision function, or the revision function hashes something that doesn't end up contributing to\n\t\t\t// the generated code.\n\t\t\tif (!needsRevisionUpdate && moduleHandle.currentSourceEquals(serialized, options)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Add to batch updates\n\t\t\tmoduleUpdates.push({\n\t\t\t\tlocalId: moduleHandle.localId,\n\t\t\t\tsource: serialized,\n\t\t\t\toptions,\n\t\t\t})\n\t\t}\n\n\t\tif (moduleUpdates.length === 0) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst didUpdate = await this.modulesStore.updateSources(moduleUpdates)\n\n\t\tif (isVectorSetItem(componentSourceNode)) this.vectorsStore.delete(componentSourceNodeId)\n\t\tif (isWebPageNode(componentSourceNode)) this.aiGenerationStore.deleteKitSectionsStructure(componentSourceNodeId)\n\n\t\treturn didUpdate\n\t}\n\n\t/**\n\t * A deterministic order for modules to be generated in. This ensures that\n\t * webpages that depend on their metadata modules are generated after.\n\t */\n\tprivate moduleTypeOrder = {\n\t\t[ModuleType.Localization]: 0,\n\t\t[ModuleType.WebPageMetadata]: 1,\n\t\t[ModuleType.SiteMetadata]: 2,\n\t\t[ModuleType.Collection]: 3,\n\t\t[ModuleType.DraftCollection]: 4,\n\t\t[ModuleType.CSS]: 5,\n\t\t[ModuleType.ComponentPresets]: 6,\n\t\t[ModuleType.Vector]: 7,\n\t\t[ModuleType.VectorSet]: 8,\n\t\t[ModuleType.Canvas]: 9,\n\t\t[ModuleType.Screen]: 10,\n\t\t[ModuleType.Prototype]: 11,\n\t\t[ModuleType.Code]: 12,\n\t\t[ModuleType.Config]: 13,\n\t\t[ModuleType.LayoutTemplate]: 14,\n\t\t[ModuleType.Design]: 15,\n\t\t[ModuleType.Kit]: 16,\n\t\t[ModuleType.Snippets]: 17,\n\t\t[ModuleType.Shader]: 18,\n\t} as const satisfies Record<ModuleType, number>\n\n\tprivate allModulesExistForSources(sourceNode: CanvasNode, sourceWithArtifacts: SourceCodeWithArtifacts[]) {\n\t\tconst localIdName = moduleNameForSourceNode(sourceNode)\n\t\tfor (const source of sourceWithArtifacts) {\n\t\t\tconst moduleExists = this.modulesStore.getPersistedModuleByLocalId(\n\t\t\t\tlocalModuleIdForStableName(source.type, localIdName),\n\t\t\t)\n\t\t\tif (!moduleExists) return false\n\t\t}\n\t\treturn true\n\t}\n\n\t/**\n\t * Handoff the output of serialization to the modules store for updating,\n\t * persisting if the module doesn't exist yet.\n\t */\n\tprivate async compileOutput(\n\t\tsourceNode: CanvasNode,\n\t\tsourceWithArtifacts: SourceCodeWithArtifacts[],\n\t): Promise<boolean> {\n\t\tif (!this.canSerialize(sourceNode.id)) return false\n\n\t\t// Compile the source code by type, in the order of the module type\n\t\t// order. This ensures that dependencies exist ahead of time.\n\t\tconst orderedSources = sourceWithArtifacts\n\t\t\t.slice()\n\t\t\t.sort((a, b) => this.moduleTypeOrder[a.type] - this.moduleTypeOrder[b.type])\n\n\t\tconst allModulesExist = this.allModulesExistForSources(sourceNode, orderedSources)\n\n\t\tif (allModulesExist) {\n\t\t\t// All modules exist, we can batch update them all at once\n\t\t\tawait this.updateModules(sourceNode.id, orderedSources)\n\t\t} else {\n\t\t\t// Some modules don't exist, process individually to handle persisting\n\t\t\tfor (const source of orderedSources) {\n\t\t\t\tconst didUpdate = await this.updateModules(sourceNode.id, [source])\n\t\t\t\tconst localIdName = moduleNameForSourceNode(sourceNode)\n\t\t\t\tconst moduleExists = this.modulesStore.getPersistedModuleByLocalId(\n\t\t\t\t\tlocalModuleIdForStableName(source.type, localIdName),\n\t\t\t\t)\n\t\t\t\tif (!moduleExists && didUpdate) {\n\t\t\t\t\tawait this.persistence.persist(sourceNode.id, [source])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// After updating a collection, check the latest annotations to see if any dependent modules\n\t\t// need to be regenerated to render correctly with P3 colors.\n\t\tif (isCollectionNode(sourceNode)) await this.ensureDependentModulesCanRenderCollectionColors(sourceNode)\n\n\t\t// When all the modules for the source node are successfully updated,\n\t\t// run queued callbacks that rely on the module existing.\n\t\tthis.#queuedUpdateCallbacks.get(sourceNode.id)?.forEach(callback => callback())\n\t\tthis.#queuedUpdateCallbacks.delete(sourceNode.id)\n\n\t\t// Store the artifacts of modules that weren't immediately persisted. We\n\t\t// will persist them in batches after a debounce.\n\t\tthis.persistence.persist(sourceNode.id, sourceWithArtifacts, true)\n\n\t\treturn true\n\t}\n\n\tpauseCodeGeneration(nodeId: NodeID) {\n\t\tlog.debug(\"Pausing code generation for\", nodeId)\n\t\tthis.#pausedCodeGenerations.add(nodeId)\n\n\t\treturn () => {\n\t\t\tlog.debug(\"Resuming code generation for\", nodeId)\n\t\t\tthis.#pausedCodeGenerations.delete(nodeId)\n\t\t\tthis.#moduleGeneration.debounce()\n\t\t}\n\t}\n\n\t/**\n\t * Generate or regenerate every component in the queue, update their\n\t * modules, and schedule them for debounced persistence.\n\t */\n\tasync generateAndUpdateQueuedComponents(moduleType?: ModuleType): Promise<NodeID[]> {\n\t\tif (this.treeStore.getDataTreeOrPartialTree().isViewOnly) return []\n\n\t\t// Ensure any missing modules are generated at least once before updating existing\n\t\t// modules. If there is overlap, they will noop in the subsequent loop.\n\t\tawait this.ensureDependencyModulesExist()\n\n\t\tconst queuedComponentSourceNodes: CanvasNode[] = []\n\t\tconst queuedVectorNodes = new Map<NodeID, (CanvasNode & IsVectorSetItem)[]>()\n\t\tfor (const [id] of this.#componentGenerationQueue) {\n\t\t\tif (this.#pausedCodeGenerations.has(id)) continue\n\n\t\t\t// If the node is about to be serialized, we don't want to begin a\n\t\t\t// duplicate serialization.\n\t\t\tif (this.serialization.preparing(id)) continue\n\n\t\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\t\tconst componentSourceNode = tree.get(id)\n\t\t\tif (\n\t\t\t\t!componentSourceNode ||\n\t\t\t\t!isValidModuleSourceNode(componentSourceNode, tree) ||\n\t\t\t\t(moduleType && !moduleTypesForSourceNode(componentSourceNode, tree).includes(moduleType))\n\t\t\t) {\n\t\t\t\tthis.#componentGenerationQueue.delete(id)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Otherwise mark that we are waiting to serialize the node, and add it to the list of\n\t\t\t// nodes to be serialized in series. Removing it from the queue.\n\t\t\tthis.serialization.prepare(id)\n\n\t\t\tif (isVectorSetItem(componentSourceNode)) {\n\t\t\t\tconst scopeNode = tree.getScopeNodeFor(componentSourceNode)\n\t\t\t\tif (!scopeNode) continue\n\n\t\t\t\tconst list = queuedVectorNodes.get(scopeNode.id) ?? []\n\t\t\t\tlist.push(componentSourceNode)\n\t\t\t\tqueuedVectorNodes.set(scopeNode.id, list)\n\t\t\t} else {\n\t\t\t\tqueuedComponentSourceNodes.push(componentSourceNode)\n\t\t\t}\n\t\t}\n\n\t\tconst generatedNodes = new Set<NodeID>()\n\n\t\t// To ensure the Editor has the latest thumbnail for a vector, we batch serialize them\n\t\t// first.\n\t\tlog.debug(\"Batch generating queued vector nodes\")\n\t\tfor (const nodes of queuedVectorNodes.values()) {\n\t\t\ttry {\n\t\t\t\tconst updates = await this.batchSerializeVectors(nodes, undefined, generatedNodes)\n\t\t\t\tfor (const id in updates) this.persistence.persist(id, updates[id]!, true)\n\t\t\t} catch {\n\t\t\t\t// Swallow errors here.\n\t\t\t}\n\t\t}\n\n\t\tlog.debug(\"Generating queued components\", { ids: queuedComponentSourceNodes.map(getId) })\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\tawait tree.withPersistedCaches(async () => {\n\t\t\tfor (const sourceNode of queuedComponentSourceNodes) {\n\t\t\t\ttry {\n\t\t\t\t\tlog.debug(\"Flushing queue of \", sourceNode.id)\n\t\t\t\t\tconst output = await this.generateComponent(sourceNode.id, GenerationCondition.Changed)\n\t\t\t\t\tif (output) {\n\t\t\t\t\t\tawait this.compileOutput(sourceNode, output)\n\t\t\t\t\t\tgeneratedNodes.add(sourceNode.id)\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Swallow errors here.\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\treturn Array.from(generatedNodes)\n\t}\n\n\t#preparing = new Map<NodeID, ResolvablePromise<void>>()\n\n\tprivate async batchSerializeVectors(\n\t\tnodes: (CanvasNode & IsVectorSetItem)[],\n\t\treportProgress?: (phase: \"serializing\" | \"persisting\", index: number) => void,\n\t\tgeneratedNodes?: Set<NodeID>,\n\t) {\n\t\tconst firstVectorSetItem = nodes[0]\n\t\tif (!firstVectorSetItem) return\n\n\t\t// Force the Vector Set module to be serialized, compiled, and persisted. We need to know\n\t\t// its global id.\n\t\tawait this.ensureSourceNode(firstVectorSetItem.id)\n\t\tawait this.ensureSourceCache(firstVectorSetItem.id)\n\n\t\t// Lock the serializer for these nodes so that blurring the window doesn't try to serialize\n\t\t// them too.\n\t\tnodes.forEach(node => this.serialization.prepare(node.id))\n\n\t\t// Calculate all module revisions in a single tree commit.\n\t\tconst newModuleRevisions = await updateVectorSetItemsModuleRevisions(nodes, this.scheduleDocumentUpdateIgnoringUndo)\n\n\t\tassert(newModuleRevisions, \"VectorSet: newModuleRevisions must exist\")\n\n\t\tconst dependencies: ProcessDependencies = {\n\t\t\tcomponentLoader: this.componentLoader,\n\t\t\tassetMap: this.assetMap,\n\t\t\tmodulesStore: this.modulesStore,\n\t\t\ttreeStore: this.treeStore,\n\t\t\ttree: this.treeStore.getDataTreeOrPartialTree(),\n\t\t\tvectorsStore: this.vectorsStore,\n\t\t\taiGenerationStore: this.aiGenerationStore,\n\t\t\tengineChanges: this.engineChanges,\n\t\t\tmeasureNodes: this.measureNodes,\n\t\t}\n\n\t\t// Serialize each Vector Set Item in parallel.\n\t\tconst vectors = await Promise.all(\n\t\t\tnodes.map(async node => {\n\t\t\t\tconst revision = newModuleRevisions[node.id]\n\t\t\t\tif (!revision) return\n\n\t\t\t\tconst serializer = this.serializerForSourceNode(this.treeStore.getDataTreeOrPartialTree(), node)\n\t\t\t\tconst sources = await serializer(node, dependencies, {\n\t\t\t\t\tserializationId: this.getSerializationId(),\n\t\t\t\t})\n\t\t\t\tconst source = sources?.[0]\n\t\t\t\tassert(source, \"VectorSet: source must exist.\", node.id)\n\n\t\t\t\tthis.serialization.promise(node.id)?.resolve()\n\t\t\t\tthis.#preparing.delete(node.id)\n\n\t\t\t\treturn [node.id, source] as const\n\t\t\t}),\n\t\t)\n\n\t\tlet index = 0\n\t\tconst updates: Record<NodeID, SourceCodeWithArtifacts[]> = {}\n\t\tfor (const vector of vectors) {\n\t\t\tif (!vector) continue\n\t\t\tconst [id, source] = vector\n\t\t\tconst didUpdate = await this.updateModules(id, [source])\n\t\t\tif (!didUpdate) continue\n\t\t\tupdates[id] = [source]\n\t\t\treportProgress?.(\"serializing\", index)\n\t\t\tindex++\n\n\t\t\tgeneratedNodes?.add(id)\n\t\t}\n\n\t\treturn updates\n\t}\n\n\t/**\n\t * When an employee publishes a vector set, we generate a new module that hardcodes the current\n\t * saveids of each vector into the annotation, and publish that version.\n\t */\n\tasync createVersionedVectorSet(node: VectorSetNode): Promise<boolean> {\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\treturn tree.withPersistedCaches(async () => {\n\t\t\tawait this.generateAndPersistAllQueuedComponents()\n\n\t\t\tconst output = await this.generateComponent(node.id, GenerationCondition.Forced, undefined, {\n\t\t\t\tincludeVectorSetSaveIds: true,\n\t\t\t})\n\n\t\t\tif (!output) return false\n\n\t\t\tconst didUpdate = await this.compileOutput(node, output)\n\t\t\tif (!didUpdate) return false\n\n\t\t\tawait this.persistence.process()\n\t\t\treturn true\n\t\t})\n\t}\n\n\t/**\n\t * In may cases we don't commit to serializing a change until the engine is\n\t * in the correct state. During this time the tree could change, but those\n\t * changes are still incorporated into the new module, so there is no need\n\t * to discard the scheduled serialization. However at the point where we\n\t * commit to serializing the current tree any new tree changes will require\n\t * a new serialization to be incorporated into a module. We orchestrate this\n\t * by recording when this period begins and ends.\n\t *\n\t * @TODO - When all source nodes support a moduleRevision, we can track\n\t * which revisions are being serialized, and wait for a specific revision to\n\t * be serialized and compiled.\n\t */\n\treadonly serialization = {\n\t\tidle: async () => {\n\t\t\tconst list: (Promise<void> | undefined)[] = []\n\t\t\tfor (const id of this.#preparing.keys()) {\n\t\t\t\tlist.push(this.serialization.promise(id)?.then(() => this.untilCompiled(id)))\n\t\t\t}\n\t\t\tawait Promise.all(list)\n\t\t},\n\t\tisIdle: () => this.#preparing.size === 0,\n\t\tprepare: (id: ComponentSourceNodeID) => {\n\t\t\tthis.#componentGenerationQueue.delete(id)\n\t\t\tconst promise = this.#preparing.get(id) ?? new ResolvablePromise()\n\t\t\tthis.#preparing.set(id, promise)\n\t\t},\n\t\tcancel: (id: ComponentSourceNodeID) => {\n\t\t\tthis.#componentGenerationQueue.delete(id)\n\t\t\tthis.#preparing.get(id)?.resolve()\n\t\t\tthis.#preparing.delete(id)\n\t\t},\n\t\tpreparing: (id: ComponentSourceNodeID) => this.#preparing.has(id),\n\t\tpromise: (id: ComponentSourceNodeID) => this.#preparing.get(id),\n\t\tcommit: async (\n\t\t\tcomponentSourceNode: CanvasNode,\n\t\t\troot: CanvasNode,\n\t\t\tcondition: GenerationCondition,\n\t\t\toptions?: {\n\t\t\t\tintrinsicSize?: Size\n\t\t\t\tincludeVectorSetSaveIds?: boolean\n\t\t\t},\n\t\t): Promise<SourceCodeWithArtifacts[] | undefined> => {\n\t\t\tconst fail = () => {\n\t\t\t\tthis.#preparing.get(componentSourceNode.id)?.reject()\n\t\t\t\tthis.#preparing.delete(componentSourceNode.id)\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst output = await this.#serializeComponent(componentSourceNode, root, condition, options)\n\t\t\t\t// If we didn't generate any output because we early returned,\n\t\t\t\t// fail the processing. This ensures that any calls that were\n\t\t\t\t// awaiting this serialization to succeed will fail as well.\n\t\t\t\tif (!output) fail()\n\t\t\t\treturn output\n\t\t\t} catch (e) {\n\t\t\t\tlog.reportError(e)\n\t\t\t\tfail()\n\t\t\t\tthrow e\n\t\t\t}\n\t\t},\n\t}\n\n\tasync #serializeComponent(\n\t\tcomponentSourceNode: CanvasNode,\n\t\troot: CanvasNode,\n\t\tcondition: GenerationCondition,\n\t\toptions?: {\n\t\t\tintrinsicSize?: Size\n\t\t\tincludeVectorSetSaveIds?: boolean\n\t\t},\n\t): Promise<SourceCodeWithArtifacts[] | undefined> {\n\t\tlet tree = this.treeStore.getDataTreeOrPartialTree()\n\t\t// Double check that the root of the component exists. Since\n\t\t// serialization is debounced, it could be been deleted by a remote\n\t\t// session.\n\t\tif (!isRootNode(componentSourceNode) && !tree.has(root.id)) return\n\t\tconst telemetrySession = this.telemetrySession(tree, componentSourceNode.id)\n\n\t\t// If the modules store is locked up, there is no point trying to\n\t\t// serialize, serialization will just create errors due to dropped\n\t\t// modules.\n\t\tconst timer = telemetrySession.start(\"synchronize\")\n\t\tconst time = performance.now()\n\t\tlog.debug(\"Waiting for ModulesStore to be idle\", { id: componentSourceNode.id })\n\t\tawait this.modulesStore.whenIdle()\n\n\t\tconst modulesIdleTime = performance.now() - time\n\t\tlog.debug(\"Waited\", Math.round((modulesIdleTime / 1000) * 100) / 100, \"seconds for ModulesStore to be idle\", {\n\t\t\tid: componentSourceNode.id,\n\t\t})\n\t\ttimer.end()\n\n\t\t// We can't guarantee this function was awaited, so ensure tree isn't stale.\n\t\ttree = this.treeStore.getDataTreeOrPartialTree()\n\n\t\t// Ensure we have the latest version of the Scope node.\n\t\tif (!tree.has(root.id)) return\n\t\tconst latestComponentSourceNode = componentSourceNode.draftOrCurrent()\n\t\tif (condition !== GenerationCondition.Forced && this.isSkippedEmptyScopeNode(latestComponentSourceNode)) {\n\t\t\treturn\n\t\t}\n\n\t\tconst telemetryTask = telemetrySession.start(\"serialize\")\n\t\tif (isCollectionNode(componentSourceNode)) {\n\t\t\tmakeSureDependentScopesCanHandleResponsiveImages(componentSourceNode, this.componentLoader, tree, this)\n\t\t}\n\n\t\tconst serializer = this.serializerForSourceNode(tree, componentSourceNode)\n\n\t\t// As we are now going to transform the node into source, we resolve the\n\t\t// processing promise, and remove it from the map. This ensures that any\n\t\t// future calls to serialize this module will begin a new serialization,\n\t\t// since changes to the node after this point won't be incorporated into\n\t\t// the output of this serialization.\n\t\tthis.#preparing.get(componentSourceNode.id)?.resolve()\n\t\tthis.#preparing.delete(componentSourceNode.id)\n\n\t\tconst output = await serializer(\n\t\t\tcomponentSourceNode,\n\t\t\t{\n\t\t\t\tcomponentLoader: this.componentLoader,\n\t\t\t\tassetMap: this.assetMap,\n\t\t\t\tmodulesStore: this.modulesStore,\n\t\t\t\ttreeStore: this.treeStore,\n\t\t\t\ttree: this.treeStore.getDataTreeOrPartialTree(),\n\t\t\t\tvectorsStore: this.vectorsStore,\n\t\t\t\taiGenerationStore: this.aiGenerationStore,\n\t\t\t\tengineChanges: this.engineChanges,\n\t\t\t\tmeasureNodes: this.measureNodes,\n\t\t\t},\n\t\t\t{\n\t\t\t\tserializationId: this.getSerializationId(),\n\t\t\t\tinitialIntrinsicSize: options?.intrinsicSize,\n\t\t\t\tincludeVectorSetSaveIds: options?.includeVectorSetSaveIds,\n\t\t\t},\n\t\t)\n\n\t\toutput.forEach(({ source, artifacts }) => {\n\t\t\tlog.trace(\"serializeComponent\", \"\\n>>>> >>>>\\n\", serializeJS(source), \"\\n<<<< <<<<\")\n\t\t\t// Be careful enabling this, because logging this causes playwright to\n\t\t\t// choke, because there are circular references in this object. See\n\t\t\t// https://github.com/microsoft/playwright/issues/30307\n\t\t\t// log.debug(\"serializeComponent\", component)\n\t\t\tif (artifacts?.submodules) {\n\t\t\t\tfor (const [submoduleName, submoduleSource] of artifacts.submodules) {\n\t\t\t\t\tlog.trace(\n\t\t\t\t\t\t\"serializeComponent\",\n\t\t\t\t\t\t\"\\n>>>>\",\n\t\t\t\t\t\tsubmoduleName,\n\t\t\t\t\t\t\">>>>\\n\",\n\t\t\t\t\t\tsubmoduleSource,\n\t\t\t\t\t\t\"\\n<<<<\",\n\t\t\t\t\t\tsubmoduleName,\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\ttelemetryTask.end(output)\n\n\t\treturn output\n\t}\n\n\t/**\n\t * Determines if a node should be skipped during code generation.\n\t */\n\tprivate isSkippedEmptyScopeNode(node: CanvasNode) {\n\t\t// We want to always generate the snippets module\n\t\tif (isCustomCodeScopeNode(node)) return false\n\n\t\t// Do not serialize an empty ScopeNode\n\t\t// TODO Check and handle shallow/fully loaded scope state\n\t\tif (isScopeNode(node) && (!node.isLoaded() || node.loaded.children?.length === 0)) {\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/**\n\t * 1. If the changes are entirely remote, return early.\n\t * 2. If the Primary Variant or Scope Node has been deleted, clean up the\n\t *    cache\n\t * 3. Update the GeneratedComponent from the queued changes\n\t * 4. Serialize the component\n\t * 5. Return the results of serialization along with whether or not it\n\t *    includes local changes that need to be persisted.\n\t */\n\tprivate async generateComponent(\n\t\tcomponentSourceNodeId: NodeID,\n\t\tcondition: GenerationCondition,\n\t\tchanged?: boolean,\n\t\toptions?: {\n\t\t\tintrinsicSize?: Size\n\t\t\tincludeVectorSetSaveIds?: boolean\n\t\t},\n\t): Promise<SourceCodeWithArtifacts[] | undefined> {\n\t\t// Ensure the source node is loaded and any dependency modules are\n\t\t// generated.\n\t\tlog.debug(\"Ensure source node\", componentSourceNodeId)\n\t\tawait this.ensureSourceNode(componentSourceNodeId)\n\t\t// Ensure the scope's cache is up to date\n\t\tlog.debug(\"Ensure source cache\", componentSourceNodeId)\n\t\tawait this.ensureSourceCache(componentSourceNodeId)\n\n\t\t// Determine if a new module revision is needed.\n\t\tconst newModuleRevision = await this.calculateNewModuleRevision(componentSourceNodeId)\n\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\t// Get a reference to the latest source node, this ensures we have the\n\t\t// latest moduleRevision among other things.\n\t\tconst componentSourceNode = tree.get(componentSourceNodeId)\n\n\t\tif (\n\t\t\t// If the source node is invalid, we can skip it.\n\t\t\t!componentSourceNode ||\n\t\t\t!isValidModuleSourceNode(componentSourceNode, tree) ||\n\t\t\t// Otherwise whether or not we can skip generation depends on the\n\t\t\t// condition for generation..\n\t\t\t!this.shouldGenerateUnderCondition(tree, condition, componentSourceNode, newModuleRevision, changed)\n\t\t) {\n\t\t\t// Ensure pending serializations are cleaned up.\n\t\t\tlog.debug(\"Cancel serialization\", componentSourceNodeId)\n\t\t\tthis.serialization.cancel(componentSourceNodeId)\n\t\t\treturn\n\t\t}\n\n\t\tconst root = withReplicaVariants(componentSourceNode)\n\t\t\t? componentSourceNode.getPrimaryVariant()\n\t\t\t: componentSourceNode\n\n\t\tlog.debug(\"Serialize\", componentSourceNodeId)\n\t\treturn this.serialization.commit(componentSourceNode, root, condition, options)\n\t}\n\n\tprivate shouldGenerateUnderCondition(\n\t\ttree: CanvasTree,\n\t\tcondition: GenerationCondition,\n\t\tcomponentSourceNode: CanvasNode,\n\t\tnewModuleRevision: number | undefined,\n\t\tchanged: boolean | undefined,\n\t): boolean {\n\t\t// Ensure we factor in any changes that have been queued since we\n\t\t// initially captured the changes.\n\t\tconst sourceNodeChanges = changed ?? this.#componentGenerationQueue.get(componentSourceNode.id)\n\t\tthis.#componentGenerationQueue.delete(componentSourceNode.id)\n\n\t\t// If the module doesn't exist, always generate it. Even if another\n\t\t// client has already generated it, if it doesn't exist in this client\n\t\t// yet, we may need it as a dependency so we need to generate it again.\n\t\tif (!allModulesExistForSourceNode(componentSourceNode, tree, this.modulesStore)) return true\n\n\t\tswitch (condition) {\n\t\t\tcase GenerationCondition.Forced:\n\t\t\t\treturn true\n\t\t\tcase GenerationCondition.Changed:\n\t\t\t\treturn (\n\t\t\t\t\t!isUndefined(newModuleRevision) ||\n\t\t\t\t\t!this.allModulesAreAtRevision(tree, componentSourceNode.id, newModuleRevision)\n\t\t\t\t)\n\t\t\tcase GenerationCondition.ChangedLocally:\n\t\t\t\treturn (\n\t\t\t\t\t!isUndefined(newModuleRevision) &&\n\t\t\t\t\t!!sourceNodeChanges &&\n\t\t\t\t\t!this.allModulesAreAtRevision(tree, componentSourceNode.id, newModuleRevision)\n\t\t\t\t)\n\t\t\tdefault:\n\t\t\t\tassertNever(condition)\n\t\t}\n\t}\n\n\tprivate addChangeToQueue(componentSourceNode: CanvasNode) {\n\t\t// NOTE: Don't use this.treeStore in this method!\n\t\t//\n\t\t// This method might be called while we're processing the tree changes,\n\t\t// at which point the TreeStore hasn't yet been updated with the latest\n\t\t// tree!\n\t\tif (this.shouldSkipChange(componentSourceNode)) return\n\n\t\t// When a vector set item is queued to be serialized, mark it in the store so that the\n\t\t// Editor can wait for it to be cached in memory, instead of making a network request we\n\t\t// know will fail, or be stale.\n\t\tif (isVectorSetItem(componentSourceNode)) this.vectorsStore.queue(componentSourceNode.id)\n\n\t\t// When collection items change, we need to enqueue the collection.\n\t\tif (isCollectionItemNode(componentSourceNode)) {\n\t\t\tconst parentId = componentSourceNode.parentid\n\t\t\tassert(parentId, \"Collection node has no parent\")\n\t\t\tthis.#componentGenerationQueue.set(parentId, true)\n\t\t\treturn\n\t\t}\n\n\t\tthis.#componentGenerationQueue.set(componentSourceNode.id, true)\n\t}\n\n\tprivate serializerForSourceNode<T extends CanvasNode>(\n\t\ttree: CanvasTree,\n\t\tcomponentSourceNode: T,\n\t): SourceCodeSerializer {\n\t\tif (isCollectionNode(componentSourceNode)) return serializeCollection\n\t\tif (withReplicaVariants(componentSourceNode)) return serializeComponentFromCanvas\n\t\tif (isStylePresetNode(componentSourceNode)) return serializeStylePreset\n\t\tif (isCanvasPageNode(componentSourceNode)) return serializePrototypeComponent\n\t\tif (isRootNode(componentSourceNode)) return generateSiteMetadataModule\n\t\tif (isPresetsListNode(componentSourceNode)) return serializeComponentPresets\n\t\tif (isVectorSetNode(componentSourceNode)) return serializeVectorSet\n\t\tif (isVectorSetItem(componentSourceNode)) return serializeVector\n\t\tif (isCustomCodeScopeNode(componentSourceNode)) return generateSnippetsModule\n\t\tif (isDesignPageNode(tree.get(componentSourceNode.parentid))) {\n\t\t\treturn serializeComponentFromCanvas\n\t\t}\n\t\treturn serializePrototypeScreenComponent\n\t}\n\n\t/**\n\t * If the change is local, we need to process the change. This allows local\n\t * component instances to appear visually up to date.\n\t *\n\t * If the change is remote, and this client hasn't previously processed the\n\t * related component, we don't need to process the change. The client that\n\t * authored the change will have processed it, generated and compiled code,\n\t * and persisted it. ModulesStorage will ensure that the persisted result is\n\t * synced to this client.\n\t */\n\tprivate shouldSkipChange(componentSourceNode: CanvasNode) {\n\t\t// If this is a screen component with a CodeComponentNode for a ground\n\t\t// node, and that code component points to a local Screen module, skip\n\t\t// it. Export to HTML should use that referenced Screen module instead.\n\t\tif (isCodeComponentNode(componentSourceNode)) {\n\t\t\tconst moduleIdentifier = parseModuleIdentifier(componentSourceNode.codeComponentIdentifier)\n\t\t\tif (isLocalModuleIdentifier(moduleIdentifier) && moduleIdentifier.type === ModuleType.Screen) return true\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/**\n\t * If a source node has not been visited in the current session its caches\n\t * may not have been created yet. This can result in issues when generating\n\t * code with variables, so we need to ensure they are created before\n\t * proceeding with code generation.\n\t *\n\t * Additionally, for all source nodes that have changed changed this frame,\n\t * wait for the frame to complete before continuing. This guarantees that\n\t * local changes are reflected in the tree before serializing.\n\t */\n\tprivate async ensureSourceCache(id: NodeID): Promise<void> {\n\t\tconst node = this.treeStore.getDataTreeOrPartialTree().get(id)\n\t\tif (!node || node.update === node.cache.lastUpdate) return\n\n\t\tawait new Promise<void>(resolve => {\n\t\t\tthis.scheduler.runBeforeNextFrame(() => {\n\t\t\t\tif (isScopeNode(node) && node.update !== node.cache.lastUpdate) this.updateTreeCache(node.id)\n\t\t\t\tresolve()\n\t\t\t})\n\t\t})\n\t}\n\n\t/**\n\t * If a module that depends on the CMS was generated before the\n\t * `useQueryData` hook was introduced, we need to update that module to work\n\t * with the new CMS database format.\n\t */\n\tprivate async ensureDependentModulesAreCompatibleWithCollection(collection: CollectionNode) {\n\t\tconst typeSlashName = localModuleIdForStableName(ModuleType.Collection, collection.id)\n\t\tconst dependents = this.modulesStore.getDependentsOfModule(typeSlashName)\n\n\t\tif (!dependents || dependents.size === 0) return\n\n\t\tawait Promise.all(\n\t\t\tArray.from(dependents).map(async dependent => {\n\t\t\t\tconst localId = asLocalId(dependent)\n\t\t\t\tconst module = this.modulesStore.getPersistedModuleByLocalId(localId)\n\t\t\t\tif (!module || !needsUpdateToBeCompatibleWithCms(module)) return\n\t\t\t\treturn this.forceComponentUpdate(module.name)\n\t\t\t}),\n\t\t)\n\t}\n\n\t/**\n\t * If a module that depends on the CMS was generated before we supported P3 color fallbacks, and\n\t * the Collection is updated to include P3 Colors, we need to regenerate the module.\n\t */\n\tprivate async ensureDependentModulesCanRenderCollectionColors(collection: CollectionNode) {\n\t\tconst typeSlashName = localModuleIdForStableName(ModuleType.Collection, collection.id)\n\t\tconst dependents = this.modulesStore.getDependentsOfModule(typeSlashName)\n\n\t\tif (!dependents || dependents.size === 0) return\n\n\t\tconst handle = this.modulesStore.forType(ModuleType.Collection).getByStableName(collection.id)\n\t\tif (!handle) return\n\n\t\t// If the Collection doesn't have a wide gamut color annotation, we don't need to regenerate any dependent modules.\n\t\tif (!handle.annotations(null, \"default\")?.[AnnotationKey.FramerColorSyntax]) return\n\n\t\tawait Promise.all(\n\t\t\tArray.from(dependents).map(async dependent => {\n\t\t\t\tconst [type, name] = splitTypeSlashName(dependent)\n\t\t\t\tif (type === ModuleType.DraftCollection) return\n\t\t\t\t// Only dependents that haven't been generated with wide gamut color support need to be regenerated.\n\t\t\t\tconst supportsP3 = this.modulesStore\n\t\t\t\t\t.forType(type as ModuleType)\n\t\t\t\t\t.getByStableName(name)\n\t\t\t\t\t?.annotations(null, \"default\")?.[AnnotationKey.FramerColorSyntax]\n\n\t\t\t\tif (supportsP3) return\n\n\t\t\t\tawait this.forceComponentUpdate(name)\n\t\t\t}),\n\t\t)\n\t}\n\n\tprivate async ensureReferencedCollectionsExportUpToDateEnumUtils(webPageNode: WebPageNode) {\n\t\tconst collectionsToRegenerate = new Set<NodeID>()\n\n\t\tfor (const variable of webPageNode.variables) {\n\t\t\tif (variable.type !== \"controlReference\") continue\n\t\t\tif (variable.expectedType !== ControlType.Enum) continue\n\n\t\t\tconst parsedModuleIdentifier = parseModuleIdentifier(variable.entityIdentifier)\n\t\t\tif (!isLocalModuleIdentifier(parsedModuleIdentifier) || parsedModuleIdentifier.type !== ModuleType.Collection) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst handle = this.modulesStore\n\t\t\t\t.forType(ModuleType.Collection)\n\t\t\t\t.getByStableName(parsedModuleIdentifier.localIdName)\n\t\t\tconst annotations = handle?.annotations(null, \"default\")\n\t\t\tconst version = annotations?.[AnnotationKey.FramerEnumToDisplayNameUtils]\n\n\t\t\tif (isNumber(version) && version >= 2) continue\n\n\t\t\tcollectionsToRegenerate.add(parsedModuleIdentifier.localIdName)\n\t\t}\n\n\t\tfor (const collectionId of collectionsToRegenerate) {\n\t\t\trecord(\"ui_interaction\", { page: Pages.canvas, id: UIInteraction.regenerateCollectionForEnumUtils })\n\t\t\tawait this.forceComponentUpdate(collectionId)\n\t\t}\n\t}\n\n\tprivate async ensureAllNodesWithLinksHaveLinkedScopesLoaded(componentSourceNode: CanvasNode) {\n\t\tconst scopesToLoad = new Set<AnyScopeNode>()\n\t\tconst tree = this.treeStore.getDataTreeOrPartialTree()\n\t\ttree.beginAllowPartialScopeAccess()\n\t\tfor (const next of componentSourceNode.walkWithSkipChildren()) {\n\t\t\tif (!hasLink(next.node)) continue\n\t\t\tconst link = next.node.getLink()\n\t\t\tif (!isLinkToWebPage(link)) continue\n\n\t\t\tconst scope = tree.get<AnyScopeNode>(link.webPageId)\n\t\t\tif (!scope) continue\n\t\t\tif (scope.loaded) continue\n\n\t\t\t// When the Web Page has an annotation defining its scroll sections, we don't need the\n\t\t\t// page to be fully loaded as we can create links from the annotation.\n\t\t\tconst annotations = this.modulesStore\n\t\t\t\t.forType(ModuleType.Screen)\n\t\t\t\t.getByStableName(link.webPageId)\n\t\t\t\t?.annotations(null, \"default\")\n\t\t\tif (!isUndefined(annotations?.[AnnotationKey.FramerScrollSections])) continue\n\n\t\t\tscopesToLoad.add(scope)\n\t\t\t// We skip children cause links can't be nested.\n\t\t\tnext.skipChildren()\n\t\t}\n\t\ttree.endAllowPartialScopeAccess()\n\n\t\tawait tree.loadScopes(Array.from(scopesToLoad))\n\t}\n}\n\n/**\n * Force generate all dependent scopes when we generate a collection with responsive\n * images while the previously generated version used *non* responsive images.\n */\nexport function makeSureDependentScopesCanHandleResponsiveImages(\n\tcollectionNode: CollectionNode,\n\tcomponentLoader: AnyComponentLoader,\n\ttree: CanvasTree,\n\tcodeGenerationStore: CodeGenerationStore,\n) {\n\tconst collectionIdentifier = collectionNode.instanceIdentifier\n\tconst existingCollection = componentLoader.dataForIdentifier(collectionIdentifier)\n\tif (!existingCollection) return\n\n\tconst previouslyGeneratedUsingOldImageControls = Object.values(existingCollection.properties).some(\n\t\tcontrol => control?.type === ControlType.Image,\n\t)\n\tif (!previouslyGeneratedUsingOldImageControls) return\n\n\tconst scopesToRegenerate: Set<ShallowScopeNode> = new Set()\n\n\tfor (const scope of tree.root.children) {\n\t\tif (!isScopeNode(scope)) continue\n\n\t\tif (isWebPageNode(scope) && scope.dataIdentifier === collectionIdentifier) {\n\t\t\tscopesToRegenerate.add(scope)\n\t\t\tcontinue\n\t\t}\n\n\t\tconst collectionInUse = scope.loaded?.some(\n\t\t\tnode => isDataRepeater(node) && node.dataIdentifier === collectionIdentifier,\n\t\t)\n\t\tif (collectionInUse) {\n\t\t\t// At least one repeater in this scope is using the collection.\n\t\t\tscopesToRegenerate.add(scope)\n\t\t}\n\t}\n\n\t// Make sure dependent scopes are regenerated so they know how to handle responsive images\n\tscopesToRegenerate.forEach(scope => {\n\t\tcodeGenerationStore.forceComponentUpdate(scope.id).catch(unhandledError)\n\t})\n}\n", "import type { EngineChangeFlag } from \"document/EngineChanges.ts\"\nimport { isEqual } from \"library/index.ts\"\nimport { useEffect, useReducer, useRef } from \"react\"\nimport { isShallowEqual } from \"utils/isShallowEqual.ts\"\nimport { useBaseEngine } from \"./base-engine/BaseEngine.ts\"\n\nconst uninitializedStateSymbol = Symbol(\"uninitialized\")\n\nfunction increment(value: number): number {\n\treturn value + 1\n}\n\n/**\n * Subscribe to one or more engine stores, re-evaluating the `getState` function when something\n * changes.\n * Also allows passing an array of `dependencies` that when changed (using shallow equals) will also trigger the `getState` callback.\n * Since this connects a component to the engine rendering cycle, the component should not\n * be re-rendering on its own, or we are likely taking a performance hit.\n\n * ! @deprecated Use `useEngineState` instead. When using state, from this hook, useEffect won't detect the state changes, without manually triggering a re-render. This behaviour can produce unexpected bugs.\n *\n * @param flag One or more flags to subscribe to. Must not be dynamic.\n * @param getState A function that returns the value to provide to the caller of the hook.\n * @param [dependencies] Optional dependencies to that will be shallow-compared and trigger the `getState` callback if changed.\n * @param deepEqual Use deep equality to check if the state has changed. Must not be dynamic.\n */\nexport function useDeprecatedEngineState<T>(\n\tflag: EngineChangeFlag | EngineChangeFlag[],\n\tgetState: () => T,\n\tdependencies?: unknown,\n\tdeepEqual?: boolean,\n): T {\n\tconst engine = useBaseEngine()\n\n\tconst [, forceRender] = useReducer(increment, 0)\n\tconst stateRef = useRef<typeof uninitializedStateSymbol | T>(uninitializedStateSymbol)\n\tif (stateRef.current === uninitializedStateSymbol) {\n\t\tstateRef.current = getState()\n\t}\n\n\t// Prevent inline functions from causing a re-render.\n\tconst getStateRef = useRef(getState)\n\tgetStateRef.current = getState\n\n\tconst previousDependenciesRef = useRef(dependencies)\n\tif (!isShallowEqual(dependencies, previousDependenciesRef.current)) {\n\t\tpreviousDependenciesRef.current = dependencies\n\t\tconst previousState = stateRef.current\n\t\tconst newState = getStateRef.current()\n\t\tif (deepEqual ? !isEqual(previousState, newState) : !isShallowEqual(previousState, newState)) {\n\t\t\tstateRef.current = newState\n\t\t}\n\t}\n\n\t// We\u2019ll force React to trust us that this deps list is static.\n\tconst flags = Array.isArray(flag) ? flag : [flag]\n\tuseEffect(() => {\n\t\tconst handleChange = () => {\n\t\t\tconst previousState = stateRef.current\n\t\t\tconst newState = getStateRef.current()\n\t\t\tif (deepEqual ? isEqual(previousState, newState) : isShallowEqual(previousState, newState)) return\n\t\t\tstateRef.current = newState\n\t\t\tforceRender()\n\t\t}\n\n\t\t// TypeScript doesn't handle argument spreading well so need to explicitly cast them here\n\t\tconst observerArgs = [...flags, handleChange] as Parameters<typeof engine.scheduler.changes.observe>\n\t\tconst observer = engine.scheduler.changes.observe(...observerArgs)\n\n\t\treturn () => engine.scheduler.changes.removeObserver(observer)\n\t}, flags) // eslint-disable-line react-hooks/exhaustive-deps\n\n\treturn stateRef.current\n}\n", "import {\n\tassert,\n\ttype ExternalModuleExportIdentifier,\n\ttype ExternalModuleExportIdentifierString,\n\ttype ExternalModuleIdentifier,\n\ttype ModuleExportIdentifierString,\n\tModuleType,\n\texternalModuleIdentifier as createExternalModuleIdentifier,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport type { VekterEngine } from \"document/VekterEngine.ts\"\nimport type { MaybeCanvasNode } from \"../nodes/CanvasNode.ts\"\nimport type CodeComponentNode from \"../nodes/CodeComponentNode.ts\"\nimport type { ExternalModuleNode } from \"../nodes/ExternalModuleNode.ts\"\nimport type { NodeID } from \"../nodes/NodeID.ts\"\nimport type ShaderNode from \"../nodes/ShaderNode.ts\"\nimport { isCodeComponentNode, isExternalModuleNode, isShaderNode } from \"../nodes/utils/nodeCheck.ts\"\nimport { isReplicaOrReplicaChild } from \"../traits/WithTemplate.ts\"\n\n/**\n * Nodes that instance an external (or local) module.\n */\ntype ModuleInstanceNode = CodeComponentNode | ShaderNode\n\nfunction isModuleInstanceNode(node: MaybeCanvasNode): node is ModuleInstanceNode {\n\treturn isCodeComponentNode(node) || isShaderNode(node)\n}\n\nexport function getModuleInstanceIdentifier(node: MaybeCanvasNode): string | undefined {\n\tif (isCodeComponentNode(node)) return node.codeComponentIdentifier\n\tif (isShaderNode(node)) return node.shaderModuleIdentifier\n\treturn undefined\n}\n\nfunction setModuleInstanceIdentifier(node: ModuleInstanceNode, identifier: ModuleExportIdentifierString): void {\n\tif (isCodeComponentNode(node)) node.set({ codeComponentIdentifier: identifier })\n\tif (isShaderNode(node)) node.set({ shaderModuleIdentifier: identifier })\n\treturn\n}\n\n/** Checks whether a module-backed instance's identifier is in sync with its external module node */\nfunction moduleBackedIdentifierIsOutdated(\n\tinstanceModuleIdentifier: ExternalModuleIdentifier,\n\texternalModuleNodeIdentifier: ExternalModuleExportIdentifier,\n): boolean {\n\treturn (\n\t\texternalModuleNodeIdentifier.moduleId === instanceModuleIdentifier.moduleId &&\n\t\texternalModuleNodeIdentifier.saveId !== instanceModuleIdentifier.saveId\n\t)\n}\n\nexport function moduleBackedInstanceIsOutdated(\n\tinstanceModuleIdentifier: ExternalModuleIdentifier,\n\texternalModuleNode: ExternalModuleNode | null,\n) {\n\tswitch (externalModuleNode?.type) {\n\t\tcase ModuleType.Canvas:\n\t\tcase ModuleType.Code:\n\t\tcase ModuleType.Shader: {\n\t\t\tconst externalModuleIdentifier = parseModuleIdentifier(externalModuleNode.codeComponentIdentifier)\n\t\t\treturn moduleBackedIdentifierIsOutdated(instanceModuleIdentifier, externalModuleIdentifier)\n\t\t}\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\nfunction updateIdentifierVersion(\n\tinstanceModuleIdentifier: ExternalModuleExportIdentifierString,\n\texternalModuleIdentifier: ExternalModuleExportIdentifierString,\n): ExternalModuleExportIdentifierString {\n\tconst parsedInstanceIdentifier = parseModuleIdentifier(instanceModuleIdentifier)\n\tconst parsedExternalModuleIdentifier = parseModuleIdentifier(externalModuleIdentifier)\n\n\tassert(parsedInstanceIdentifier.moduleId === parsedExternalModuleIdentifier.moduleId, \"Module id should be the same\")\n\n\tassert(\n\t\tparsedInstanceIdentifier.saveId !== parsedExternalModuleIdentifier.saveId,\n\t\t\"Module identifier should have a different save id than the instance\",\n\t)\n\n\t// We only want to update the save id, because the export specifier could be different, one\n\t// module can export multiple things.\n\tconst newExternalModuleIdentifier = createExternalModuleIdentifier(\n\t\tparsedInstanceIdentifier.moduleId,\n\t\tparsedExternalModuleIdentifier.saveId,\n\t\tparsedInstanceIdentifier.file,\n\t\tparsedInstanceIdentifier.exportSpecifier,\n\t)\n\n\treturn newExternalModuleIdentifier.value\n}\n\n/** Updates a module-backed instance (code component or shader) to match the latest version of its external module node */\nexport function updateModuleBackedInstanceToLatestVersion(engine: VekterEngine, nodeId: NodeID) {\n\tconst node = engine.tree.getNodeWithTrait(nodeId, isModuleInstanceNode)\n\tif (!node) return\n\n\tassert(!isReplicaOrReplicaChild(node), \"Module instance node should not be a replica or replica child\")\n\n\tconst instanceIdentifier = getModuleInstanceIdentifier(node)\n\tconst moduleIdentifier = parseModuleIdentifier(instanceIdentifier)\n\tassert(moduleIdentifier?.kind === \"externalModuleExport\", \"Module identifier should be external\")\n\n\tconst externalModuleNode = engine.tree.getNodeWithTrait(moduleIdentifier.moduleId, isExternalModuleNode)\n\tassert(externalModuleNode, \"Module node should exist\")\n\n\tconst newIdentifier = updateIdentifierVersion(moduleIdentifier.value, externalModuleNode.codeComponentIdentifier)\n\n\tsetModuleInstanceIdentifier(node, newIdentifier)\n}\n\nexport const testing = { updateIdentifierVersion, moduleBackedIdentifierIsOutdated }\n", "import type { ComponentLoader } from \"@framerjs/framer-runtime\"\nimport {\n\tModuleType,\n\tassertNever,\n\tisExternalModuleIdentifier,\n\tisModuleIdentifier,\n\tparseModuleIdentifier,\n} from \"@framerjs/shared\"\nimport type { LoadedExternalModulesStore } from \"document/stores/LoadedExternalModulesStore.ts\"\nimport type { ModulesStore } from \"document/stores/ModulesStore.ts\"\nimport type { CanvasTree } from \"../CanvasTree.ts\"\nimport type { CanvasNode } from \"../nodes/CanvasNode.ts\"\nimport type { ErrorListNode } from \"../nodes/ErrorListNode.ts\"\nimport { ERROR_LIST_NODE_ID } from \"../nodes/ErrorListNode.ts\"\nimport type { ErrorNode } from \"../nodes/ErrorNode.ts\"\nimport { ErrorNodeReason, ErrorNodeType } from \"../nodes/ErrorNode.ts\"\nimport type { NodeID } from \"../nodes/NodeID.ts\"\nimport { isExternalModuleNode } from \"../nodes/utils/nodeCheck.ts\"\nimport { withCodeOverride } from \"../traits/WithCodeOverride.ts\"\nimport { getModuleInstanceIdentifier, moduleBackedInstanceIsOutdated } from \"./moduleBackedInstanceUpdate.ts\"\n\nexport enum CodeError {\n\tFileTooLarge,\n\t// Component loader errors\n\tComponentLoaderError,\n\tCodeComponentLoaderError,\n\tSmartComponentLoaderError,\n\tShaderLoaderError,\n\n\t// Missing files / exports\n\tCodeComponentMissing,\n\tShaderMissing,\n\tOverrideMissingExport,\n\tOverrideMissingFile,\n}\n\nexport type ErrorByNodeId = Record<NodeID, { type: ErrorNodeType; reason: string }>\n\ninterface ErrorKind<T extends string> {\n\treadonly kind: T\n}\n\ninterface NestedNodeError<T extends string> extends ErrorKind<T> {\n\treadonly message: string\n\treadonly otherNodeId: string\n}\n\ninterface FormDestinationError extends ErrorKind<\"form\"> {\n\treadonly reason: string\n}\n\ninterface CodeNodeError extends ErrorKind<\"code\"> {\n\treadonly codeError: CodeError\n}\n\ntype AccessibleNameError = NestedNodeError<\"accessibleName\">\n\ninterface OutdatedInstanceError extends ErrorKind<\"outdatedInstance\"> {\n\treadonly originalNodeId: NodeID\n}\n\nexport type NodeError = CodeNodeError | AccessibleNameError | FormDestinationError | OutdatedInstanceError\n\nfunction infoForIdentifier(\n\tidentifier: string | undefined,\n\tcomponentLoader: ComponentLoader,\n\ttree: CanvasTree,\n\tloadedExternalModulesStore: LoadedExternalModulesStore,\n\tmodulesStore: ModulesStore,\n):\n\t| {\n\t\t\thasDefinition: boolean\n\t\t\thasModuleEntry: boolean\n\t\t\ttype: ModuleType | string\n\t\t\toutdatedInstance: boolean\n\t  }\n\t| undefined {\n\tconst moduleIdentifier = parseModuleIdentifier(identifier)\n\tif (!isModuleIdentifier(moduleIdentifier)) return\n\n\tconst isExternal = isExternalModuleIdentifier(moduleIdentifier)\n\tif (isExternal && !moduleIdentifier.moduleId) return\n\n\tconst externalModule = isExternal ? tree.getNodeWithTrait(moduleIdentifier.moduleId, isExternalModuleNode) : null\n\tconst type = isExternal ? (externalModule?.type ?? ModuleType.Code) : moduleIdentifier.type\n\tconst hasDefinition =\n\t\ttype === ModuleType.Shader\n\t\t\t? !!componentLoader.shaderForIdentifier(moduleIdentifier.value)\n\t\t\t: !!componentLoader.componentForIdentifier(moduleIdentifier.value)\n\n\tif (isExternal) {\n\t\treturn {\n\t\t\ttype,\n\t\t\thasDefinition,\n\t\t\thasModuleEntry: loadedExternalModulesStore.hasModuleForIdentifier(moduleIdentifier),\n\t\t\toutdatedInstance: moduleBackedInstanceIsOutdated(moduleIdentifier, externalModule),\n\t\t}\n\t}\n\n\treturn {\n\t\ttype,\n\t\thasDefinition,\n\t\thasModuleEntry: !!modulesStore.getModuleEntryByLocalId(moduleIdentifier.localId),\n\t\toutdatedInstance: false,\n\t}\n}\n\nfunction getModuleInstanceError(\n\tnode: CanvasNode,\n\tcomponentLoader: ComponentLoader,\n\ttree: CanvasTree,\n\tloadedExternalModulesStore: LoadedExternalModulesStore,\n\tmodulesStore: ModulesStore,\n): NodeError | undefined {\n\tconst instanceIdentifier = getModuleInstanceIdentifier(node)\n\tif (!instanceIdentifier) return\n\n\tconst info = infoForIdentifier(instanceIdentifier, componentLoader, tree, loadedExternalModulesStore, modulesStore)\n\tif (!info) return\n\tconst { hasDefinition, hasModuleEntry, type, outdatedInstance } = info\n\n\t// NOTE: Technically, componentDefinition can have an `error` property,\n\t// but in practice there is likely no case where that will give more\n\t// information than we already have.\n\n\tif (!hasDefinition || !hasModuleEntry) {\n\t\tswitch (type) {\n\t\t\tcase ModuleType.Code:\n\t\t\t\tif (!hasModuleEntry) {\n\t\t\t\t\treturn { kind: \"code\", codeError: CodeError.CodeComponentMissing }\n\t\t\t\t} else if (!hasDefinition) {\n\t\t\t\t\treturn { kind: \"code\", codeError: CodeError.CodeComponentLoaderError }\n\t\t\t\t} else {\n\t\t\t\t\tbreak // Should never be reached\n\t\t\t\t}\n\t\t\tcase ModuleType.Shader:\n\t\t\t\tif (!hasModuleEntry) {\n\t\t\t\t\treturn { kind: \"code\", codeError: CodeError.ShaderMissing }\n\t\t\t\t} else if (!hasDefinition) {\n\t\t\t\t\treturn { kind: \"code\", codeError: CodeError.ShaderLoaderError }\n\t\t\t\t} else {\n\t\t\t\t\tbreak // Should never be reached\n\t\t\t\t}\n\t\t\tcase ModuleType.Canvas:\n\t\t\t\treturn { kind: \"code\", codeError: CodeError.SmartComponentLoaderError }\n\t\t\tdefault:\n\t\t\t\t// Generic error if we don\u2019t know better\n\t\t\t\treturn { kind: \"code\", codeError: CodeError.ComponentLoaderError }\n\t\t}\n\t}\n\n\tif (outdatedInstance) {\n\t\treturn { kind: \"outdatedInstance\", originalNodeId: node.getPrimaryId() }\n\t}\n}\n\nfunction getOverrideError(\n\tnode: CanvasNode,\n\tcomponentLoader: ComponentLoader,\n\ttree: CanvasTree,\n\tloadedExternalModulesStore: LoadedExternalModulesStore,\n\tmodulesStore: ModulesStore,\n): NodeError | undefined {\n\tif (!withCodeOverride(node)) return\n\n\tconst info = infoForIdentifier(\n\t\tnode.codeOverrideIdentifier,\n\t\tcomponentLoader,\n\t\ttree,\n\t\tloadedExternalModulesStore,\n\t\tmodulesStore,\n\t)\n\tif (!info) return\n\tconst { hasDefinition, hasModuleEntry } = info\n\n\tif (!hasDefinition) {\n\t\treturn hasModuleEntry\n\t\t\t? { kind: \"code\", codeError: CodeError.OverrideMissingExport }\n\t\t\t: { kind: \"code\", codeError: CodeError.OverrideMissingFile }\n\t}\n}\n\nfunction getErrorNodeError(node: CanvasNode, errors: ErrorByNodeId): FormDestinationError | CodeNodeError | undefined {\n\tconst error = errors[node.id]\n\tif (!error) return\n\n\tswitch (error.type) {\n\t\tcase ErrorNodeType.Form:\n\t\t\treturn { kind: \"form\", reason: error.reason }\n\t\tcase ErrorNodeType.CodeGeneration:\n\t\t\tswitch (error.reason) {\n\t\t\t\tcase ErrorNodeReason.FileTooLarge:\n\t\t\t\t\treturn { kind: \"code\", codeError: CodeError.FileTooLarge }\n\t\t\t\tdefault:\n\t\t\t\t\treturn undefined\n\t\t\t}\n\t\tdefault:\n\t\t\tassertNever(error.type)\n\t}\n}\n\nexport function getNodeError(\n\tnode: CanvasNode,\n\tcomponentLoader: ComponentLoader,\n\ttree: CanvasTree,\n\tloadedExternalModulesStore: LoadedExternalModulesStore,\n\tmodulesStore: ModulesStore,\n\terrors?: ErrorByNodeId,\n): NodeError | undefined {\n\treturn (\n\t\tgetModuleInstanceError(node, componentLoader, tree, loadedExternalModulesStore, modulesStore) ||\n\t\tgetOverrideError(node, componentLoader, tree, loadedExternalModulesStore, modulesStore) ||\n\t\t(errors && getErrorNodeError(node, errors))\n\t)\n}\n\nfunction isLayerPanelErrorNodeError(error: ErrorNode): boolean {\n\tswitch (error.type) {\n\t\tcase ErrorNodeType.Form:\n\t\t\treturn true\n\t\tcase ErrorNodeType.CodeGeneration:\n\t\t\tif (error.reason === ErrorNodeReason.FileTooLarge) return true\n\t\t\treturn false\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\n/**\n * Create a hashmap of errors by node id. The first written error wins. If there\n * are multiple errors, resolving errors will show the next error.\n *\n * Currently we only show errors for forms. In the future we will show generic\n * code-generation errors with some message.\n */\nexport function getErrorsByNodeId(tree: CanvasTree): ErrorByNodeId {\n\tconst errorsByNodeId: ErrorByNodeId = {}\n\tconst listNode = tree.get<ErrorListNode>(ERROR_LIST_NODE_ID)\n\tif (!listNode) return errorsByNodeId\n\n\tlistNode.children?.forEach(error => {\n\t\tif (!error.nodeId) return\n\t\tif (!error.type || !isLayerPanelErrorNodeError(error)) return\n\t\tif (!error.reason || error.nodeId in errorsByNodeId) return\n\t\terrorsByNodeId[error.nodeId] = { type: error.type, reason: error.reason }\n\t})\n\treturn errorsByNodeId\n}\n", "import type { ErrorNodeReason } from \"document/models/CanvasTree/nodes/ErrorNode.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\n\ninterface ParsedFormErrorReason {\n\tdestinationType: string | undefined\n\treason: string\n}\n\nexport function parseFormErrorReason(rawReason: string | ErrorNodeReason | undefined): ParsedFormErrorReason {\n\tif (!isString(rawReason)) return { destinationType: undefined, reason: \"\" }\n\n\tconst separatorIndex = rawReason.indexOf(\":\")\n\tif (separatorIndex === -1) {\n\t\treturn { destinationType: undefined, reason: rawReason.trim().toLowerCase() }\n\t}\n\n\tconst destinationType = rawReason.slice(0, separatorIndex).trim()\n\tconst reason = rawReason\n\t\t.slice(separatorIndex + 1)\n\t\t.split(\"|\")[0]\n\t\t.trim()\n\t\t.toLowerCase()\n\n\treturn { destinationType, reason }\n}\n", "import { assert } from \"@framerjs/shared\"\nimport type { SandboxRepeaterData } from \"document/SandboxRepeaterData.ts\"\nimport type { DataTree } from \"document/crdt/data-tree/DataTree.ts\"\nimport type { TreeUpdater } from \"document/models/CanvasTree/TreeUpdater.ts\"\nimport type { CanvasTree, CodeComponentNode, RichTextNode, ShaderNode } from \"document/models/CanvasTree/index.ts\"\nimport { setTreeMode, treeModeForTimeline, treeTimelineHasData, type TreeMode } from \"document/stores/TreeMode.ts\"\n\ninterface BaseTreeIndexes {\n\tcodeComponents: CodeComponentNode[]\n\tshaderNodes: ShaderNode[]\n\trichTextNodes: RichTextNode[]\n}\n\nexport interface BaseTreeStore {\n\tmode: TreeMode\n\treadonly tree: CanvasTree\n\treadonly timeline: TreeUpdater\n\treadonly remoteTreeVersion: number\n\treadonly sandboxRepeaterData: SandboxRepeaterData\n\tgetPartialIndexes(): BaseTreeIndexes\n\tgetLoadedIndexes(): BaseTreeIndexes\n\tgetDataTree(): DataTree | undefined\n\tgetDataTreeOrPartialTree(): CanvasTree\n}\n\ninterface TreeModeSwitchStore {\n\treadonly tree: CanvasTree\n\ttimeline: TreeUpdater\n}\n\nexport function getBaseTreeStoreMode(store: Pick<BaseTreeStore, \"timeline\">): TreeMode {\n\treturn treeModeForTimeline(store.timeline)\n}\n\nexport function switchBaseTreeStoreMode(\n\tstore: TreeModeSwitchStore,\n\tmode: TreeMode,\n\toptions: {\n\t\tinitialTree: CanvasTree\n\t\tcreateTimeline: (mode: TreeMode) => TreeUpdater\n\t\tresetTimeline?: boolean\n\t},\n): boolean {\n\tif (getBaseTreeStoreMode(store) === mode) return false\n\n\tassert(\n\t\tstore.tree === options.initialTree && !treeTimelineHasData(store.timeline) && !store.tree.hasUncommittedChanges(),\n\t\t\"Cannot switch tree mode after tree data has been loaded because it would reset timeline data\",\n\t)\n\n\tsetTreeMode(store.tree, mode)\n\tstore.timeline = options.createTimeline(mode)\n\tif (options.resetTimeline) store.timeline.reset(store.tree)\n\treturn true\n}\n", "import { type ModuleExportIdentifierString, isModuleExportIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport type { CanvasNode } from \"document/models/CanvasTree/index.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport {\n\ttype WithVariables,\n\tisAnyCollectionReferencingVariableDefinition,\n} from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport type { PersistedModuleProvider } from \"document/stores/ModulesStore.ts\"\n\nexport interface CollectionUtilExport {\n\texportIdentifier: string\n\tmoduleURL: string\n\tcollectionId: string\n}\n\n// Generated collections export a \"utils\" object with utility functions.\nconst collectionModuleUtilsExportIdentifier = \"utils\"\n\nexport function getCollectionUtilForDataIdentifier(\n\tmoduleProvider: PersistedModuleProvider,\n\tdataIdentifier: ModuleExportIdentifierString,\n): CollectionUtilExport | undefined {\n\tconst identifier = parseModuleIdentifier(dataIdentifier)\n\tif (!isModuleExportIdentifier(identifier)) return\n\n\t// External modules cannot by updated by users. Their slug values will not\n\t// be resolved at runtime, but instead embedded in generated code\n\tif (identifier.kind !== \"localModuleExport\") return\n\n\tconst persistedCollectionModule = moduleProvider.getPersistedModuleByLocalId(identifier.localId)\n\n\tif (!persistedCollectionModule) return\n\t// It is possible for older already collection modules to exists which don't have the export yet.\n\tif (!persistedCollectionModule.exports.includes(collectionModuleUtilsExportIdentifier)) return\n\n\treturn {\n\t\texportIdentifier: collectionModuleUtilsExportIdentifier,\n\t\tmoduleURL: persistedCollectionModule.moduleURL,\n\t\tcollectionId: identifier.localIdName,\n\t}\n}\n\nexport function getCollectionUtilForNode(\n\tmoduleProvider: PersistedModuleProvider,\n\tnode: CanvasNode,\n): CollectionUtilExport | undefined {\n\tif (!isWebPageNode(node)) return\n\tif (!node.dataIdentifier) return\n\n\treturn getCollectionUtilForDataIdentifier(moduleProvider, node.dataIdentifier)\n}\n\nexport function collectCollectionUtilsForReferencedCollections(\n\tmoduleProvider: PersistedModuleProvider,\n\tnode: WithVariables,\n\taddCollectionUtil: (collectionUtil: CollectionUtilExport) => void,\n): void {\n\tfor (const variable of node.variables) {\n\t\tif (!isAnyCollectionReferencingVariableDefinition(variable)) continue\n\n\t\tconst collectionUtil = getCollectionUtilForDataIdentifier(moduleProvider, variable.dataIdentifier)\n\t\tif (collectionUtil) {\n\t\t\taddCollectionUtil(collectionUtil)\n\t\t}\n\t}\n}\n", "import type { SerializableValue } from \"code-generation/js/SerializableValue.ts\"\nimport type { SafeJS } from \"code-generation/js/serializeJS.ts\"\nimport type { FileDeclarationCollector } from \"code-generation/utils/DeclarationCollector.ts\"\nimport type { WebPageNode } from \"document/models/CanvasTree/index.ts\"\nimport { hasPageEffects } from \"document/models/CanvasTree/traits/WithPageEffects.ts\"\nimport type { SitePageEffects } from \"library/router/pageEffects/PageEffectsContext.tsx\"\nimport type { PageEffect } from \"library/router/pageEffects/types.ts\"\n\nexport interface TokenisedSitePageEffects {\n\tglobal: PageEffect | undefined\n\n\troutes: {\n\t\t[exitRouteId: string]: {\n\t\t\t[enterRouteId: string]: SafeJS\n\t\t}\n\t}\n}\n\nexport function collectPageEffects(pageEffects: SitePageEffects, node: WebPageNode) {\n\t/**\n\t * Scrape page effects from main breakpoint. Currently we don't support\n\t * page effects per breakpoint.\n\t */\n\tconst screenNode = node.getPrimaryVariant()\n\n\tif (hasPageEffects(screenNode)) {\n\t\tpageEffects.routes[node.id] = screenNode.pageEffects\n\t}\n}\n\nexport function collectPageEffectsForPublish(\n\tpageEffects: TokenisedSitePageEffects,\n\tnode: WebPageNode,\n\tdeclarations: FileDeclarationCollector,\n) {\n\t/**\n\t * Scrape page effects from main breakpoint. Currently we don't support\n\t * page effects per breakpoint.\n\t */\n\tconst screenNode = node.getPrimaryVariant()\n\tif (hasPageEffects(screenNode)) {\n\t\tconst effects: { [key: string]: SafeJS } = {}\n\n\t\tfor (const key in screenNode.pageEffects) {\n\t\t\teffects[key] = declarations.dedupe(\"effect\", screenNode.pageEffects[key] as unknown as SerializableValue)\n\t\t}\n\n\t\tpageEffects.routes[node.id] = effects\n\t}\n}\n", "import type { AnyComponentLoader } from \"@framerjs/framer-runtime\"\nimport { getLogger } from \"@framerjs/shared\"\nimport { getNavigationActions, getNavigationTarget } from \"document/models/CanvasTree/actions/navigationActions.ts\"\nimport type { CanvasNode, CanvasTree } from \"document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { getSlotItemsBySlotKey } from \"document/models/CanvasTree/nodes/utils/slotUtils.ts\"\n\nconst log = getLogger(\"exportToHTML\")\n\n/**\n * Given an entry point node, walk the node and search for navigation targets.\n * These can be either prototype navigation actions that target any ground node\n * on a canvas page, or open url actions of type page, that point to a canvas\n * component node that is a web page.\n *\n * For each target that is found, recursively repeat the process until all the\n * nodes that can be navigated to from the original entry node have been\n * collected into a set.\n *\n * This can easily result in an infinite loop if two nodes link to each other.\n * To avoid this, we track each node that we have visited, and return early from\n * a tree walk if a node we have visited is encountered.\n */\nexport function collectNodesInPrototypeNavigationChain(\n\ttree: CanvasTree,\n\tcomponentLoader: AnyComponentLoader,\n\tentryNode: CanvasNode,\n\tnavigationTargets = new Set([entryNode]),\n\thistory = new Set<CanvasNode>(),\n): Set<CanvasNode> {\n\tfor (const { node, skipChildren } of entryNode.walkWithSkipChildren()) {\n\t\t// Avoid infinite loops by aborting a tree walk if we encounter a node\n\t\t// we have already walked.\n\t\tif (history.has(node)) {\n\t\t\tskipChildren()\n\t\t\tcontinue\n\t\t}\n\n\t\t// If we haven't walked this node, immediately record to history that we\n\t\t// now have encountered this node. This prevents subsequent recursive\n\t\t// tree walks from walking this node a second time.\n\t\thistory.add(node)\n\n\t\tfor (const action of getNavigationActions(node, componentLoader)) {\n\t\t\tconst targetId = getNavigationTarget(action)\n\t\t\tif (!targetId) continue\n\t\t\tconst targetNode = tree.getNode(targetId)\n\t\t\tif (!targetNode) continue\n\t\t\tif (!tree.isGroundNode(targetNode)) {\n\t\t\t\tlog.reportError(\"Navigation target node must be ground node\", {\n\t\t\t\t\tsourceId: node.id,\n\t\t\t\t\ttargetId: targetNode.id,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnavigationTargets.add(targetNode)\n\t\t\tcollectNodesInPrototypeNavigationChain(tree, componentLoader, targetNode, navigationTargets, history)\n\t\t}\n\n\t\tif (isCodeComponentNode(node)) {\n\t\t\tObject.values(getSlotItemsBySlotKey(tree, node, componentLoader))\n\t\t\t\t.flat()\n\t\t\t\t.forEach(slotItem =>\n\t\t\t\t\tcollectNodesInPrototypeNavigationChain(tree, componentLoader, slotItem.node, navigationTargets, history),\n\t\t\t\t)\n\t\t}\n\t}\n\n\treturn navigationTargets\n}\n", "import { isSafari } from \"@framerjs/shared\"\n\ndeclare global {\n\tinterface Window {\n\t\tCompressionStream?: {\n\t\t\tprototype: GenericTransformStream\n\t\t\tnew (format: string): GenericTransformStream\n\t\t}\n\t}\n}\n\n// We gzip module batches via the compression stream api if available. However, it seems Safari\n// 16.4, the first Safari to support it, to produce bad data, resulting in \"Unexpected EOF\" errors.\n// To be safe, we disable it for all of Safari 16 versions. When we get more data on where this\n// issue comes from, or in which version this is fixed, we can fine tune when to use compression\n// stream. See issue: https://github.com/framer/company/issues/27220\nconst isSafari16 = isSafari() && navigator.userAgent.includes(\"Version/16\")\n// eslint-disable-next-line compat/compat -- CompressionStream *is* supported in Firefox 113+, so compat is wrong here.\nexport const useCompressionStream = window.CompressionStream && !isSafari16\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ACL;AAAA,QAAQ,cACR,uCAAuC,MAAM,iBAAiB,SAAS,MAAM,mBAAmB,OAAO;AAAA,MACxG;AAAA,IACF;AAAA,EACD;AAEA,SAAO;AACR;;;ACtDA,IAAM,aAAa,SAAS,KAAK,UAAU,UAAU,SAAS,YAAY;AAEnE,IAAM,uBAAuB,OAAO,qBAAqB,CAAC;",
  "names": ["changes", "change", "key", "scopeId", "key", "log", "isReplicaChild", "key", "log", "LOCAL_CHANGES_VALID_FOR_MS", "REMOTE_CONNECTION_VALID_FOR_MS", "updated", "key", "record", "key", "key", "key", "extractedProps", "key", "log", "log", "key", "assert", "assertNever", "key", "assert", "assert", "assertNever", "DatabaseValueModel", "assert", "key", "key", "log", "key", "options", "newItemChunkWriter", "finalizeChunk", "chunkWriter", "node", "Var", "css", "useRef", "RESERVED", "css", "useRef", "serializeComponentFunction", "motion", "Fragment", "Var", "jsx", "key", "import_jsx_runtime", "log", "log", "key", "log", "tree", "import_react", "externalModuleIdentifier", "key", "log"]
}
