@superblocksteam/library 2.0.42-next.43 → 2.0.42-next.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root-store-DHEbJGYN.js","names":["editMode: boolean | undefined","editMode","RunApisTrigger: Trigger<RunApisStep>","context","context","step","context","step","context","context","step","value","context","navigation","action","form: unknown","context","context","context","context","value","EventRegistry: Record<ImplementedTriggerTypes, Trigger<ValidStepDef>>","context","trigger: Trigger<any>","TriggerRegistry","sectionDefs: Array<PropertiesPanelSectionDefinition>","properties: WidgetPropertyDefinition<any>[]","VALIDATORS: VALIDATION_TYPES","children: Record<string, WidgetPropertyDefinition<DataType>>","category: PropsPanelCategory","exhaustiveCheck: never","baseControlType: ControlType","inputType: InputType | undefined","panelConfig: PropertiesPanelDefinition | undefined","contentDef: Record<string, Section>","variants: UnionVariant<typeof this.shared>[]","parentPath","internalPropsList: Array<{ path: string; factory: () => any }>","managedPropsList: ManagedPropsList","internalStores: Record<string, any>","extraLibraries: Record<string, unknown>","lodash","funcStr: string","argsStr: string","EventRegistry","isComputedProp","props","items: [string, ExecutableOrValue][]","name","id","componentRegistry: ComponentRegistry","entities: Record<string, Entity>","path: InternalScope[]","currentScope: InternalScope | undefined","scopeId","propParent: Record<string, unknown>","metaParent: Record<string, unknown>","runEventHandlers","ret: unknown","context","entity","paths: string[]","metaPropsNames: string[]","route","isString","icon: React.ReactNode","color: string","SuccessIcon","ErrorIcon","InfoIcon","WarningIcon","positionToPlacement: Record<NotificationPosition, Position>","paths: string[][]","files: Record<string, File>","pathToFiles: string[][]","entries","candidates: Record<string, string>","_","entityToSend: Record<string, unknown>","cleanedBody: Record<string, any>","init: RequestInit","jsonValues: { error?: { message: string } }[]","e: HttpError | TypeError | any","result: ApiV2ExecutionResponse","returnBlockOutput: ApiV2ExecutionResponse[\"output\"]","rootStore: RootStore","apisToSet: Array<DeleteMeLibraryApi & { scopeId: string }>","events: Array<StreamEvent>","editMode","authResult: any","diff","value","res: string[]","entry","reactionOptions: IReactionOptions<any, boolean>","initialState: OUTPUT","lastValue: unknown","disposers: IDisposer[]","dataType: EntityDefinition[\"props\"][string][\"dataType\"]","objectFields: Record<string, any>","rootStore: RootStore","entityDefinitions: Record<string, EntityDefinition>","entityDefinition: EntityDefinition","entityDefEntry: EntityDefinition[\"props\"][string]","_","DEFAULT_ANONYMOUS_SOURCE_ID: SbElement","entityManager: IEntityManager","instanceId: SbInstance","identifier","identifier: IdentifierInfo","ApiManager"],"sources":["../src/edit-mode/get-edit-store.ts","../src/lib/internal-details/is-edit-mode.ts","../src/lib/utils/clean-object.ts","../src/lib/internal-details/lib/iframe.ts","../src/edit-mode/base-editor-bridge.ts","../src/edit-mode/message-queue.ts","../src/edit-mode/superblocks-editor-bridge.ts","../src/lib/triggers/implementations/apis/cancel-apis.ts","../src/lib/triggers/implementations/apis/run-apis.ts","../src/lib/triggers/implementations/call-function.ts","../src/lib/triggers/implementations/components/control-modal.ts","../src/lib/triggers/implementations/components/control-slideout.ts","../src/lib/internal-details/lib/evaluator/names.ts","../src/lib/triggers/implementations/components/reset-component.ts","../src/lib/triggers/implementations/components/set-component-property.ts","../src/lib/triggers/implementations/navigate/navigate-to-app.ts","../src/lib/triggers/implementations/navigate/navigate-to-route.ts","../src/lib/internal-details/utils/is-local-link.ts","../src/lib/internal-details/utils/navigation.ts","../src/lib/triggers/implementations/navigate/utils.ts","../src/lib/triggers/implementations/navigate/navigate-to.ts","../src/lib/triggers/implementations/navigate/set-query-params.ts","../src/lib/triggers/implementations/run-js.ts","../src/lib/triggers/implementations/set-profile.ts","../src/lib/triggers/implementations/state/reset-state-var.ts","../src/lib/triggers/implementations/state/set-state-var.ts","../src/lib/triggers/implementations/timers/control-timer.ts","../src/lib/triggers/implementations/trigger-event.ts","../src/lib/triggers/registry.ts","../src/lib/triggers/run-event-handlers.ts","../src/lib/user-facing/properties-panel/properties-panel-definition.ts","../src/lib/user-facing/properties-panel/validators.ts","../src/lib/user-facing/properties-panel/props-builder.ts","../src/lib/user-facing/properties-panel/create-managed-props-list.ts","../src/lib/utils/fast-clone.ts","../src/lib/internal-details/lib/devtools/index.tsx","../src/lib/internal-details/lib/evaluator/create-global-object.ts","../src/lib/internal-details/lib/evaluator/pretty-print-function.ts","../src/lib/internal-details/lib/evaluator/compute-engines.ts","../src/lib/internal-details/lib/evaluator/sanitize-object.ts","../src/lib/internal-details/lib/evaluator/create-scope-proxy.ts","../src/lib/user-facing/event-flow.ts","../src/lib/internal-details/lib/evaluator/binding-strings/transform-bindings.ts","../src/lib/internal-details/lib/evaluator/lazy-function.ts","../src/lib/internal-details/lib/evaluator/to-executables-or-values.ts","../src/lib/internal-details/lib/evaluator/entity-manager.ts","../src/lib/internal-details/location-store.ts","../src/lib/user-facing/assets/icons/system-danger.svg","../src/lib/user-facing/assets/icons/system-error.svg","../src/lib/user-facing/assets/icons/system-info.svg","../src/lib/user-facing/assets/icons/system-success.svg","../src/lib/user-facing/styling/colors.ts","../src/lib/user-facing/themes/classnames.ts","../src/lib/user-facing/utils/notification.tsx","../src/lib/internal-details/lib/evaluator/file-utils.ts","../src/lib/internal-details/lib/evaluator/binding-extraction.ts","../src/lib/internal-details/lib/resolve-id-singleton.ts","../src/lib/tracing/context-utils.ts","../src/lib/utils/generate-id.ts","../src/lib/internal-details/lib/features/api-utils.ts","../src/lib/internal-details/lib/features/api-store.ts","../src/edit-mode/mobx-sync/create-patch.ts","../src/edit-mode/mobx-sync/deep-observe.ts","../src/edit-mode/mobx-sync/mobx-editor-sync.ts","../src/lib/internal-details/lib/features/type-defs-utils.ts","../src/lib/internal-details/lib/features/component-registry.ts","../src/lib/internal-details/lib/features/name-manager.ts","../src/lib/internal-details/lib/root-store.ts"],"sourcesContent":["import type { EditStore } from \"./edit-store.js\";\n\n/**\n * Get the global EditStore instance\n * @returns The EditStore instance\n */\n\nexport function getEditStore(): EditStore {\n if (\n !window.__SUPERBLOCKS_EDITOR_HOOK__ ||\n !window.__SUPERBLOCKS_EDITOR_HOOK__.isInitialized\n ) {\n throw new Error(\"EditStore not initialized\");\n }\n return (window as any).__SUPERBLOCKS_EDITOR_HOOK__;\n}\n","const getIsEditMode = () => {\n const envMode = (window as any)._SB_VIEW_MODE;\n return envMode === \"dev\";\n};\n\nlet editMode: boolean | undefined;\n\nexport const isEditMode = () => {\n if (editMode === undefined) {\n editMode = getIsEditMode();\n }\n return editMode;\n};\n","import { toJS } from \"mobx\";\n\nexport const isReactElement = (obj: any) => {\n return (\n obj &&\n (obj.$$typeof === Symbol.for(\"react.element\") ||\n (typeof Node !== \"undefined\" && obj instanceof Node))\n );\n};\n/**\n * Cleans an object by removing proxy wrappers and filtering out functions.\n * This is useful for preparing objects for JSON serialization.\n */\nexport function cleanObject<T>(obj: T): unknown {\n // sometimes its a proxy in our managers\n obj = toJS(obj);\n\n // Remove functions\n if (!obj || typeof obj !== \"object\") {\n return typeof obj === \"function\" ? undefined : obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(cleanObject).filter((item) => item !== undefined);\n }\n\n if (isReactElement(obj)) {\n return undefined;\n }\n\n return Object.entries(obj).reduce(\n (acc, [key, value]) => {\n // TODO: make this a bit more robust. a lot of theme objects are shared, so\n // using a seen set doesn't quite work, this just handles the case where we shove a\n // bind onto an entity\n if (obj === value || key === \"bind\") {\n return acc;\n }\n\n const cleaned = cleanObject(value);\n if (cleaned !== undefined) {\n acc[key] = cleaned;\n }\n return acc;\n },\n {} as Record<string, unknown>,\n );\n}\n","import { cleanObject } from \"../../utils/clean-object.js\";\nimport type {\n FromChildToParentMessageTypes,\n FromChildToParentMessageTypesMap,\n FromParentToChildMessageTypes,\n FromParentToChildMessageTypesMap,\n} from \"./types.js\";\n\nexport function isEmbeddedBySuperblocksFirstParty() {\n return typeof window !== \"undefined\" && window !== window.parent;\n}\n\n// TODO: window.opener for 'open in new tab' feature\nconst PARENT_REF =\n typeof window !== \"undefined\" && window !== window.parent\n ? window.parent\n : null;\nconst SELF_REF = typeof window !== \"undefined\" ? window : null;\n\nfunction parentMessageHandler(e: MessageEvent) {\n // Make sure the message is coming from either:\n // - The parent window\n // - The same window (for devbox)\n if (e.source !== PARENT_REF && e.source !== SELF_REF) return;\n\n const event = new SbIframeEventInternal(\n e.data.type as FromParentToChildMessageTypes,\n e.data,\n );\n iframeMessageHandler.dispatchEvent(event);\n}\n\nif (isEmbeddedBySuperblocksFirstParty() && PARENT_REF) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n typeof window !== \"undefined\" &&\n window.addEventListener(\"message\", parentMessageHandler);\n}\n\n/** @deprecated Use editorBridge instead */\nexport function sendMessageImmediately<\n MT extends FromChildToParentMessageTypes,\n>(\n message: {\n type: MT;\n payload?: FromChildToParentMessageTypesMap[MT];\n [key: string]: any;\n },\n options?: {\n // For when you have debounced the sendMessage and want better stats\n overrideStartTime: number;\n },\n) {\n if (!PARENT_REF) {\n console.warn(\n \"PARENT_REF is not set, message not delivered. Message: \",\n message,\n );\n return;\n }\n\n message = cleanObject(message) as typeof message;\n\n if (isEmbeddedBySuperblocksFirstParty()) {\n if (!PARENT_REF) throw new Error(\"Parent is not set\");\n try {\n PARENT_REF.postMessage(\n {\n ...message,\n startTime: options?.overrideStartTime ?? +new Date(),\n },\n \"*\",\n );\n } catch (e) {\n console.error(\"Error sending message to parent\", message, e);\n }\n }\n}\n\nclass SbIframeEventInternal<T = Record<string, any>> extends Event {\n data: { payload: T; startTime: number; [key: string]: any };\n constructor(\n type: FromParentToChildMessageTypes,\n data: { payload: T; startTime: number; [key: string]: any },\n ) {\n super(type);\n this.data = data;\n }\n}\n\n// We are using a custom event target so that you each of our custom postMessage types\n// is a separate handler\ninterface MessageHandler extends EventTarget {\n addEventListener<MT extends FromParentToChildMessageTypes>(\n type: MT,\n callback: IframeEventHandler<MT>,\n ): void;\n addEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n ): void;\n removeEventListener<MT extends FromParentToChildMessageTypes>(\n type: MT,\n callback: IframeEventHandler<MT>,\n ): void;\n removeEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n ): void;\n}\n\n// This is a hack to get around the fact that we can't overload the addEventListener method\nclass SbMessageHandler extends (EventTarget as {\n new (): MessageHandler;\n prototype: MessageHandler;\n}) {\n // Parent implements all functionalityza\n}\n\nexport type IframeEventHandler<MT extends FromParentToChildMessageTypes> = (\n event: SbIframeEventInternal<FromParentToChildMessageTypesMap[MT]>,\n) => void;\n\nexport const iframeMessageHandler = new SbMessageHandler();\n\nexport type IframeEvent<T> = T extends FromParentToChildMessageTypes\n ? MessageEvent<{ type: T; payload: FromParentToChildMessageTypesMap[T] }>\n : never;\n","import { sendMessageImmediately } from \"../lib/internal-details/lib/iframe.js\";\nimport type { FromChildToParentMessageTypesMap } from \"../lib/index.js\";\nimport type {\n StreamEvent,\n RouteInfo,\n} from \"../lib/internal-details/lib/types.js\";\nimport type { PropertiesPanelDefinition } from \"@superblocksteam/library-shared/props\";\nimport type {\n AiContextMode,\n EditOperationPayload,\n EditOperationType,\n RuntimeErrorData,\n SbElement,\n SbInstance,\n} from \"@superblocksteam/library-shared/types\";\n\n// interface for the public methods in SuperblocksEditorBridge\nexport interface SuperblocksParentBridgeInterface {\n // Connection methods\n connected(): void;\n sendReady(): void;\n\n // Notification methods\n sendNotification(\n type: \"success\" | \"error\" | \"info\" | \"warning\",\n message: string,\n description?: string,\n ): void;\n\n // Widget Operations\n selectWidgets(sourceIds: SbElement[]): void;\n editOpRequest<T extends EditOperationType>(\n type: T,\n payload: EditOperationPayload<T>[\"payload\"],\n ): void;\n undo(): void;\n redo(): void;\n\n // API Operations\n sendStreamedApiEvent(event: StreamEvent, apiName: string): void;\n sendStreamedApiMessage(message: any, apiName: string): void;\n setApiStarted(apiName: string): void;\n setApiResponse(apiName: string, response: unknown): void;\n\n // Navigation Operations\n navigateTo(path: string, newWindow?: boolean): void;\n\n // Properties Panel Operations\n updatePropertiesPanels(\n updates: Record<string, PropertiesPanelDefinition>,\n ): void;\n addPropertiesPanel(id: string, definition: PropertiesPanelDefinition): void;\n\n // Editor Synced Store Operations\n initializeEditorSyncedStore(\n payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/init\"],\n ): void;\n updateEditorSyncedStore(\n payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"],\n ): void;\n\n // Promise Operations\n resolvePromise(callbackId: string, payload: unknown): void;\n rejectPromise(callbackId: string, payload: unknown): void;\n\n // Click Operations\n canvasClicked(): void;\n registerContextMenuClick(\n sourceId: SbElement,\n clientX: number,\n clientY: number,\n ): void;\n\n // Route Operations\n updateRoute(routeInfo: RouteInfo): void;\n\n // Socket Operations\n socketError(message: string): void;\n\n // AI Operations\n aiGenerate(prompt: string, forceSend?: boolean): void;\n addComponentToAiContext(sourceId: SbElement, instanceId: SbInstance): void;\n toggleComponentInAiContext(\n sourceId: SbElement,\n instanceId: SbInstance,\n label?: string,\n ): void;\n setAiContextMode(mode: AiContextMode): void;\n sendRuntimeError(data: RuntimeErrorData): void;\n sendClearRuntimeError(id: string): void;\n}\n\nexport class DeployedParentBridge implements SuperblocksParentBridgeInterface {\n navigateTo(url: string, newWindow?: boolean): void {\n sendMessageImmediately({\n type: \"navigate-to\",\n payload: {\n url,\n newWindow,\n },\n });\n }\n\n connected(): void {}\n sendReady(): void {}\n sendNotification(\n _type: \"success\" | \"error\" | \"info\" | \"warning\",\n _message: string,\n _description?: string,\n ): void {}\n selectWidgets(_sourceIds: SbElement[]): void {}\n editOpRequest<T extends EditOperationType>(\n _type: T,\n _payload: EditOperationPayload<T>[\"payload\"],\n ): void {}\n undo(): void {}\n redo(): void {}\n sendStreamedApiEvent(_event: StreamEvent, _apiName: string): void {}\n sendStreamedApiMessage(_message: any, _apiName: string): void {}\n setApiStarted(_apiName: string): void {}\n setApiResponse(_apiName: string, _response: unknown): void {}\n updatePropertiesPanels(\n _updates: Record<string, PropertiesPanelDefinition>,\n ): void {}\n addPropertiesPanel(\n _id: string,\n _definition: PropertiesPanelDefinition,\n ): void {}\n initializeEditorSyncedStore(\n _payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/init\"],\n ): void {}\n updateEditorSyncedStore(\n _payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"],\n ): void {}\n resolvePromise(_callbackId: string, _payload: unknown): void {}\n rejectPromise(_callbackId: string, _payload: unknown): void {}\n canvasClicked(): void {}\n registerContextMenuClick(\n _sourceId: SbElement,\n _clientX: number,\n _clientY: number,\n ): void {}\n updateRoute(routeInfo: RouteInfo): void {\n sendMessageImmediately({\n type: \"route-change\",\n payload: routeInfo,\n });\n }\n socketError(_message: string): void {}\n aiGenerate(_prompt: string): void {}\n addComponentToAiContext(_sourceId: SbElement): void {}\n toggleComponentInAiContext(\n _sourceId: SbElement,\n _instanceId: SbInstance,\n _label?: string,\n ): void {}\n setAiContextMode(_mode: AiContextMode): void {}\n sendRuntimeError(_data: RuntimeErrorData): void {}\n sendClearRuntimeError(_id: string): void {}\n}\n","import { throttle } from \"lodash\";\nimport { sendMessageImmediately } from \"../lib/internal-details/lib/iframe.js\";\nimport type { PayloadAction } from \"@superblocksteam/library-shared/types\";\n\nconst MESSAGE_BATCH_TIME = 50;\n\nconst DEFAULT_KEY = \"default\";\n\nexport type QueueMergeOptions = {\n key: string;\n mergeFn: (\n existing: PayloadAction<unknown>[] | undefined,\n newMessage: PayloadAction<unknown>,\n ) => PayloadAction<unknown>[]; // mutations allowed\n};\n\nclass MessageQueue {\n private keyedActionQueue: Record<string, PayloadAction<unknown>[]> = {};\n\n constructor() {}\n\n private flattenKeyedQueue(): PayloadAction<unknown>[] {\n return Object.values(this.keyedActionQueue).flat();\n }\n\n private triggerSendFromQueue = throttle(() => {\n sendMessageImmediately(\n {\n type: \"iframe-action-batch\",\n payload: this.flattenKeyedQueue(),\n },\n {\n overrideStartTime: Date.now() - MESSAGE_BATCH_TIME,\n },\n );\n this.keyedActionQueue = {};\n }, MESSAGE_BATCH_TIME);\n\n public queueMessage(\n message: PayloadAction<unknown>,\n mergeOptions?: QueueMergeOptions,\n ) {\n if (mergeOptions) {\n const { key, mergeFn } = mergeOptions;\n this.keyedActionQueue[key] ??= [];\n this.keyedActionQueue[key] = mergeFn(this.keyedActionQueue[key], message);\n } else {\n this.keyedActionQueue[DEFAULT_KEY] ??= [];\n this.keyedActionQueue[DEFAULT_KEY].push(message);\n }\n\n this.triggerSendFromQueue();\n }\n}\n\nexport default new MessageQueue();\n","import { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport { sendMessageImmediately as legacySendImmediate } from \"../lib/internal-details/lib/iframe.js\";\nimport {\n DeployedParentBridge,\n type SuperblocksParentBridgeInterface,\n} from \"./base-editor-bridge.js\";\nimport { getEditStore } from \"./get-edit-store.js\";\nimport {\n type QueueMergeOptions,\n default as MessageQueue,\n} from \"./message-queue.js\";\nimport type {\n FromChildToParentMessageTypes,\n FromChildToParentMessageTypesMap,\n} from \"../lib/index.js\";\nimport type {\n StreamEvent,\n RouteInfo,\n} from \"../lib/internal-details/lib/types.js\";\nimport type { PropertiesPanelDefinition } from \"@superblocksteam/library-shared/props\";\nimport type {\n AiContextMode,\n EditOperationPayload,\n EditOperationType,\n PayloadAction,\n RuntimeErrorData,\n SbElement,\n SbInstance,\n} from \"@superblocksteam/library-shared/types\";\n\ntype MessagePayload<T extends FromChildToParentMessageTypes> = {\n type: T;\n payload: FromChildToParentMessageTypesMap[T];\n callbackId?: string;\n};\n\nexport class SuperblocksEditorBridge\n implements SuperblocksParentBridgeInterface\n{\n private static instance: SuperblocksParentBridgeInterface;\n\n private messagesToSend: Array<{\n payload: MessagePayload<any>;\n mergeOptions?: QueueMergeOptions;\n }> = [];\n private connectedToParent = false;\n\n public static getInstance(): SuperblocksParentBridgeInterface {\n const editMode = isEditMode();\n if (!SuperblocksEditorBridge.instance) {\n SuperblocksEditorBridge.instance = editMode\n ? new SuperblocksEditorBridge()\n : new DeployedParentBridge();\n }\n return SuperblocksEditorBridge.instance;\n }\n\n public connected() {\n this.connectedToParent = true;\n this.messagesToSend.forEach((message) =>\n this.queueMessage(message.payload, message.mergeOptions),\n );\n this.messagesToSend = [];\n }\n\n public sendReady() {\n this.sendImmediate<\"sb-ready\">(\n {\n type: \"sb-ready\",\n payload: void 0,\n },\n true,\n );\n }\n\n // Notifications\n public sendNotification(\n type: \"success\" | \"error\" | \"info\" | \"warning\",\n message: string,\n description?: string,\n ) {\n this.queueMessage<\"codeMode/sendNotification\">({\n type: \"codeMode/sendNotification\",\n payload: { type, message, description },\n });\n }\n\n // Widget Operations\n public selectWidgets(sourceIds: SbElement[]) {\n this.queueMessage<\"client:selectWidgets\">({\n type: \"client:selectWidgets\",\n payload: { sourceIds },\n });\n }\n\n public editOpRequest<T extends EditOperationType>(\n type: T,\n payload: EditOperationPayload<T>[\"payload\"],\n ) {\n this.sendImmediate<\"sb-edit-operation-request\">({\n type: \"sb-edit-operation-request\",\n payload: { type, payload },\n });\n }\n\n public undo() {\n this.sendImmediate<\"undo\">({\n type: \"undo\",\n payload: void 0,\n });\n }\n\n public redo() {\n this.sendImmediate<\"redo\">({\n type: \"redo\",\n payload: void 0,\n });\n }\n\n public sendStreamedApiEvent(event: StreamEvent, apiName: string) {\n this.sendImmediate<\"api/stream-event\">({\n type: \"api/stream-event\",\n payload: { event, apiName },\n });\n }\n\n public sendStreamedApiMessage(message: any, apiName: string) {\n this.sendImmediate<\"api/stream-message\">({\n type: \"api/stream-message\",\n payload: { message, apiName },\n });\n }\n\n public setApiStarted(apiName: string) {\n this.sendImmediate<\"api/started-execution\">({\n type: \"api/started-execution\",\n payload: { apiName },\n });\n }\n\n public setApiResponse(apiName: string, response: unknown) {\n this.sendImmediate<\"api/set-api-response\">({\n type: \"api/set-api-response\",\n payload: { apiName, response },\n });\n }\n\n // Navigation Operations\n public navigateTo(path: string, newWindow?: boolean) {\n this.sendImmediate<\"navigate-to\">({\n type: \"navigate-to\",\n payload: { url: path, newWindow },\n });\n }\n\n // Properties Panel Operations\n public updatePropertiesPanels(\n updates: Record<string, PropertiesPanelDefinition>,\n ) {\n this.queueMessage<\"codeMode/updatePropertiesPanels\">({\n type: \"codeMode/updatePropertiesPanels\",\n payload: updates,\n });\n }\n\n public addPropertiesPanel(id: string, definition: PropertiesPanelDefinition) {\n this.queueMessage<\"codeMode/addPropertiesPanel\">({\n type: \"codeMode/addPropertiesPanel\",\n payload: { id, definition },\n });\n }\n\n // Editor Synced Store Operations\n public initializeEditorSyncedStore(\n payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/init\"],\n ) {\n this.queueMessage<\"codeMode/editor-synced-store/init\">({\n type: \"codeMode/editor-synced-store/init\",\n payload,\n });\n }\n\n private mergeSyncedStoreUpdate(\n existingActions: PayloadAction<unknown>[] | undefined,\n newAction: PayloadAction<unknown>,\n ) {\n if (!existingActions || existingActions.length === 0) {\n return [newAction];\n }\n const firstAction = existingActions[0] as PayloadAction<\n FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"]\n >;\n const newActionPatches = (\n newAction as PayloadAction<\n FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"]\n >\n ).payload.patch;\n firstAction.payload.patch = Array.isArray(firstAction.payload.patch)\n ? firstAction.payload.patch\n : [firstAction.payload.patch];\n firstAction.payload.patch.push(\n ...(Array.isArray(newActionPatches)\n ? newActionPatches\n : [newActionPatches]),\n );\n\n return existingActions;\n }\n\n public updateEditorSyncedStore(\n payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"],\n ) {\n this.queueMessage<\"codeMode/editor-synced-store/update\">(\n {\n type: \"codeMode/editor-synced-store/update\",\n payload,\n },\n {\n key: `synced-store-update-${payload.storeId}`,\n mergeFn: this.mergeSyncedStoreUpdate,\n },\n );\n }\n\n // Promise Operations\n public resolvePromise(callbackId: string, payload: unknown) {\n this.sendImmediate<\"resolve-promise\">({\n type: \"resolve-promise\",\n callbackId,\n payload,\n });\n }\n\n public rejectPromise(callbackId: string, payload: unknown) {\n this.sendImmediate<\"reject-promise\">({\n type: \"reject-promise\",\n callbackId,\n payload,\n });\n }\n\n public canvasClicked() {\n this.sendImmediate<\"register-click\">({\n type: \"register-click\",\n payload: {\n type: \"INSIDE_IFRAME_CLICKED\",\n context: {\n sourceId: \"\",\n clientX: 0,\n clientY: 0,\n },\n },\n });\n }\n\n public registerContextMenuClick(\n sourceId: SbElement,\n clientX: number,\n clientY: number,\n ) {\n this.sendImmediate<\"register-click\">({\n type: \"register-click\",\n payload: {\n type: \"OPEN_CONTEXT_MENU\",\n context: {\n sourceId,\n clientX,\n clientY,\n },\n },\n });\n }\n\n public updateRoute(routeInfo: RouteInfo) {\n this.sendImmediate(\n {\n type: \"route-change\",\n payload: routeInfo,\n },\n // a route change might cause this.connectedToParent to be false,\n // make sure the message is always sent\n true,\n );\n }\n\n public addComponentToAiContext(sourceId: SbElement, instanceId: SbInstance) {\n const editStore = getEditStore();\n\n if (editStore?.ai.isAlternateSourceIdTarget(sourceId, instanceId)) {\n editStore.ai.addTargetedInstance(instanceId);\n return;\n }\n\n this.sendImmediate<\"ai-updates\">({\n type: \"ai-updates\",\n payload: {\n type: \"add-component-to-context\",\n component: sourceId,\n },\n });\n }\n\n public toggleComponentInAiContext(\n sourceId: SbElement,\n instanceId: SbInstance,\n label?: string,\n ) {\n const editStore = getEditStore();\n\n if (editStore?.ai.isAlternateSourceIdTarget(sourceId, instanceId)) {\n editStore.ai.toggleTargetedInstance(instanceId);\n return;\n }\n this.sendImmediate<\"ai-updates\">({\n type: \"ai-updates\",\n payload: {\n type: \"toggle-component-in-context\",\n component: sourceId,\n label: label,\n },\n });\n }\n\n public setAiContextMode(mode: AiContextMode) {\n this.sendImmediate<\"ai-updates\">({\n type: \"ai-updates\",\n payload: { type: \"set-ai-context-mode\", mode },\n });\n }\n\n public aiGenerate(prompt: string, forceSend = false) {\n const sanitizedPrompt = clampPromptLength(prompt);\n this.sendImmediate<\"ai-updates\">(\n {\n type: \"ai-updates\",\n payload: { type: \"ai-generate\", prompt: sanitizedPrompt },\n },\n forceSend,\n );\n }\n\n public socketError(message: string) {\n this.sendImmediate<\"socket/error\">({\n type: \"socket/error\",\n payload: { message },\n });\n }\n\n public sendRuntimeError(data: RuntimeErrorData) {\n this.sendImmediate<\"runtime-error\">({\n type: \"runtime-error\",\n payload: data,\n });\n }\n\n public sendClearRuntimeError(id: string) {\n this.sendImmediate<\"clear-runtime-error\">({\n type: \"clear-runtime-error\",\n payload: { id },\n });\n }\n\n // Private implementation details\n private queueMessage<T extends FromChildToParentMessageTypes>(\n message: MessagePayload<T>,\n mergeOptions?: QueueMergeOptions,\n ) {\n if (!this.connectedToParent) {\n this.messagesToSend.push({ payload: message, mergeOptions });\n } else {\n MessageQueue.queueMessage(message, mergeOptions);\n }\n }\n\n private sendImmediate<T extends FromChildToParentMessageTypes>(\n message: MessagePayload<T>,\n forceSend = false,\n ) {\n if (!this.connectedToParent && !forceSend) {\n this.messagesToSend.push({ payload: message });\n } else {\n legacySendImmediate(message);\n }\n }\n}\n\n// Roughly 4:1 chars to tokens, so 4k tokens\nconst MAX_AI_PROMPT_LENGTH = 16000;\nconst TRUNCATION_SUFFIX = \"... (truncated)\";\n\nfunction clampPromptLength(prompt: string): string {\n if (prompt.length <= MAX_AI_PROMPT_LENGTH) {\n return prompt;\n }\n\n const available = Math.max(\n MAX_AI_PROMPT_LENGTH - TRUNCATION_SUFFIX.length,\n 0,\n );\n return `${prompt.slice(0, available)}${TRUNCATION_SUFFIX}`;\n}\n\nexport const editorBridge = SuperblocksEditorBridge.getInstance();\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { EventFlow } from \"../../../user-facing/event-flow.js\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type {\n CancelApisStep,\n SbApiWithFunctions,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const CancelApisTrigger = {\n type: TriggerStepType.CANCEL_APIS,\n\n async execute(_context: ExecutionContext, step: CancelApisStep) {\n const apis = step.apis;\n await Promise.all(apis.map((api) => api.cancel()));\n },\n\n create(apis: SbApiWithFunctions[], onCancel?: EventFlow) {\n return {\n type: TriggerStepType.CANCEL_APIS,\n apis,\n onCancel,\n };\n },\n} satisfies Trigger<CancelApisStep>;\n","import {\n TriggerStepType,\n type SbApiWithFunctions,\n} from \"@superblocksteam/library-shared/types\";\nimport { runEventHandlers } from \"../../run-event-handlers.js\";\nimport type { ApiV2ExecutionResponse } from \"../../../internal-details/lib/types.js\";\nimport type { EventFlow } from \"../../../user-facing/event-flow.js\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { RunApisStep } from \"@superblocksteam/library-shared/types\";\n\nexport const RunApisTrigger: Trigger<RunApisStep> = {\n type: TriggerStepType.RUN_APIS,\n\n async execute(\n context: ExecutionContext,\n step: RunApisStep,\n onFinish?: (\n responses: PromiseSettledResult<ApiV2ExecutionResponse | undefined>[],\n ) => void,\n ) {\n const traceHeaders = context.additionalContext?.traceHeaders;\n\n const executions = step.apis.map((api) => api.run({ traceHeaders }));\n\n return Promise.allSettled(executions).then((responses) => {\n const error = responses.find(\n (response) =>\n response.status === \"rejected\" ||\n (response.value?.errors && response.value?.errors?.length > 0),\n );\n\n if (!error && step.onSuccess) {\n runEventHandlers({\n flow: step.onSuccess,\n name: context.name,\n scopeId: context.scopeId,\n additionalContext: context.additionalContext,\n });\n } else if (step.onError) {\n runEventHandlers({\n flow: step.onError,\n name: context.name,\n scopeId: context.scopeId,\n additionalContext: context.additionalContext,\n });\n }\n\n onFinish?.(responses);\n });\n },\n\n create(\n apis: SbApiWithFunctions[],\n opts?: {\n onSuccess?: EventFlow;\n onError?: EventFlow;\n },\n ) {\n return {\n type: TriggerStepType.RUN_APIS,\n apis,\n onSuccess: opts?.onSuccess,\n onError: opts?.onError,\n };\n },\n} satisfies Trigger<RunApisStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { Trigger } from \"../base.js\";\nimport type { BaseStepDef } from \"@superblocksteam/library-shared/types\";\n\ninterface InternalCallFunctionStep extends BaseStepDef {\n type: typeof TriggerStepType.CALL_FUNCTION;\n exec: () => unknown;\n}\n\nexport const CallFunctionTrigger = {\n type: TriggerStepType.CALL_FUNCTION,\n\n create(fn: () => unknown) {\n if (typeof fn !== \"function\")\n throw new Error(\"callFunction expects a function\");\n return { type: TriggerStepType.CALL_FUNCTION, exec: fn };\n },\n\n async execute(_ctx, step) {\n await Promise.resolve(step.exec());\n },\n} satisfies Trigger<InternalCallFunctionStep>;\n","import { getBindingIdentifier } from \"@superblocksteam/library-shared\";\nimport { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { ControlModalStep } from \"@superblocksteam/library-shared/types\";\nimport type { WithBindingIdentifier } from \"@superblocksteam/library-shared/types\";\n\nexport const ControlModalTrigger = {\n type: TriggerStepType.CONTROL_MODAL,\n\n async execute(context: ExecutionContext, step: ControlModalStep) {\n if (step.name === undefined) {\n return;\n }\n\n context.rootStore.entityManager.runCode({\n scopeId: context.scopeId,\n name: context.name,\n func: (state: any, step: ControlModalStep) => {\n if (!state || !step.name) return;\n if (step.action === \"open\") {\n state[step.name].isOpen = true;\n } else {\n state[step.name].isOpen = false;\n }\n },\n args: [step],\n });\n },\n\n create(modal: WithBindingIdentifier, opts: { action: \"open\" | \"close\" }) {\n const meta = getBindingIdentifier(modal);\n return {\n type: TriggerStepType.CONTROL_MODAL,\n name: meta?.entityName,\n action: opts.action,\n };\n },\n} satisfies Trigger<ControlModalStep>;\n","import { getBindingIdentifier } from \"@superblocksteam/library-shared\";\nimport { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { ControlSlideoutStep } from \"@superblocksteam/library-shared/types\";\nimport type { WithBindingIdentifier } from \"@superblocksteam/library-shared/types\";\n\nexport const ControlSlideoutTrigger = {\n type: TriggerStepType.CONTROL_SLIDEOUT,\n\n async execute(context: ExecutionContext, step: ControlSlideoutStep) {\n context.rootStore.entityManager.runCode({\n scopeId: context.scopeId,\n name: context.name,\n func: (state: any, step: ControlSlideoutStep) => {\n if (!state || !step.name) {\n return;\n }\n state[step.name].isOpen = step.action === \"open\";\n },\n args: [step],\n });\n },\n\n create(slideout: WithBindingIdentifier, opts: { action: \"open\" | \"close\" }) {\n const meta = getBindingIdentifier(slideout);\n return {\n type: TriggerStepType.CONTROL_SLIDEOUT,\n name: meta?.entityName,\n action: opts.action,\n };\n },\n} satisfies Trigger<ControlSlideoutStep>;\n","export type Name = {\n value: string;\n isAnonymous: boolean;\n};\n\nexport const getName = (name?: string): Name => {\n return {\n isAnonymous: !name,\n value: name ?? Math.random().toString(36).substring(7),\n __isName: true,\n } as unknown as Name;\n};\n\nexport const isName = (name: any): name is Name => {\n return typeof name === \"object\" && name != null && \"__isName\" in name;\n};\n\nexport const isNameEqual = (a: Name, b: Name): boolean => {\n return a.value === b.value && a.isAnonymous === b.isAnonymous;\n};\n","import { getBindingIdentifier } from \"@superblocksteam/library-shared\";\nimport { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport { getName } from \"../../../internal-details/lib/evaluator/names.js\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { WithBindingIdentifier } from \"@superblocksteam/library-shared/types\";\n\nimport type { ResetComponentStep } from \"@superblocksteam/library-shared/types\";\n\nexport const ResetComponentTrigger = {\n type: TriggerStepType.RESET_COMPONENT,\n\n async execute(context: ExecutionContext, step: ResetComponentStep) {\n if (!step.widget?.name) {\n return;\n }\n // TODO(mark) - fix scope, this needs to be able to reset any entity AVAILABLE in the scope\n // currently it only resets the entity that's at the same scope\n context.rootStore.entityManager.resetEntity({\n name: getName(step.widget?.name),\n scopeId: context.scopeId,\n key: step.propertyName,\n onlyMetaProps: true,\n });\n },\n\n create(\n component: WithBindingIdentifier,\n opts?: {\n property: string;\n // resetChildren: ValueInputProp,\n },\n ) {\n const meta = getBindingIdentifier(component);\n\n return {\n type: TriggerStepType.RESET_COMPONENT,\n widget: meta\n ? {\n name: meta.entityName,\n }\n : undefined,\n propertyName: opts?.property,\n // resetChildren,\n };\n },\n} satisfies Trigger<ResetComponentStep>;\n","import { getBindingIdentifier } from \"@superblocksteam/library-shared\";\nimport { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { ValueInputProp } from \"@superblocksteam/library-shared/types\";\nimport type { SetComponentPropertyStep } from \"@superblocksteam/library-shared/types\";\n\nexport const SetComponentPropertyTrigger = {\n type: TriggerStepType.SET_COMPONENT_PROPERTY,\n\n async execute(context: ExecutionContext, step: SetComponentPropertyStep) {\n const { propertyValue } = step;\n const value = context.rootStore.entityManager.computeValue<any>({\n scopeId: context.scopeId,\n name: context.name,\n value: propertyValue,\n args: [context.additionalContext],\n });\n context.rootStore.entityManager.runCode({\n scopeId: context.scopeId,\n name: context.name,\n func: (state, value, step) => {\n if (!state) return;\n state[step.widget?.name][step.propertyName] = value;\n },\n args: [value, step],\n });\n },\n\n create(component, opts: { property: string; value: ValueInputProp }) {\n const meta = getBindingIdentifier(component);\n return {\n type: TriggerStepType.SET_COMPONENT_PROPERTY,\n widget: meta\n ? {\n name: meta.entityName,\n }\n : undefined,\n propertyName: opts.property,\n propertyValue: opts.value,\n };\n },\n} satisfies Trigger<SetComponentPropertyStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { NavigateToAppStep } from \"@superblocksteam/library-shared/types\";\n\nexport const NavigateToAppTrigger = {\n type: TriggerStepType.NAVIGATE_TO_APP,\n\n async execute(_context: ExecutionContext, step: NavigateToAppStep) {\n // TODO: Implement app navigation logic\n console.log(\"Navigate to app\", step);\n },\n\n create(appId: string) {\n return {\n type: TriggerStepType.NAVIGATE_TO_APP,\n targetApp: { name: appId, id: appId, url: \"\" },\n queryParams: {},\n newWindowApp: false,\n };\n },\n} satisfies Trigger<NavigateToAppStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { NavigateToRouteStep } from \"@superblocksteam/library-shared/types\";\n\nexport const NavigateToRouteTrigger = {\n type: TriggerStepType.NAVIGATE_TO_ROUTE,\n\n async execute(context: ExecutionContext, step: NavigateToRouteStep) {\n const queryParams = step.queryParams\n ? context.rootStore.entityManager.computeValue({\n scopeId: context.scopeId,\n name: context.name,\n value: step.queryParams,\n args: [context.additionalContext],\n })\n : {};\n const routeParams = step.routeParams\n ? context.rootStore.entityManager.computeValue({\n scopeId: context.scopeId,\n name: context.name,\n value: step.routeParams,\n args: [context.additionalContext],\n })\n : {};\n\n // TODO: Implement route navigation logic\n console.log(\"Navigate to route\", {\n routeId: step.routeId,\n routeParams,\n queryParams,\n keepQueryParams: step.keepQueryParams,\n newWindow: step.newWindow,\n });\n },\n\n create(route: string) {\n return {\n type: TriggerStepType.NAVIGATE_TO_ROUTE,\n routeId: route,\n routePathDescriptor: route,\n newWindow: false,\n };\n },\n} satisfies Trigger<NavigateToRouteStep>;\n","// here to avoid some side effect imports\nexport function isLocalLink(href: string) {\n const url = new URL(href, window.location.origin);\n return url.origin === window.location.origin;\n}\n","export class NavigationEvent extends Event {\n destination: {\n sameDocument: boolean;\n url: string;\n };\n formData?: FormData;\n downloadRequest?: boolean;\n newWindow?: boolean;\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/NavigateEvent for these\n navigationType?: \"push\" | \"replace\" | \"reload\" | \"traverse\";\n userInitiated?: boolean;\n\n constructor({\n isSameDocument,\n targetUrl,\n formData,\n isBlob = false,\n newWindow = false,\n userInitiated = false,\n }: {\n isSameDocument: boolean;\n targetUrl: string;\n formData?: FormData;\n isBlob?: boolean;\n newWindow?: boolean;\n userInitiated?: boolean;\n }) {\n // See: https://developer.mozilla.org/en-US/docs/Web/API/Event/Event#options\n // cancelable is false by default\n super(\"navigate\", { cancelable: true });\n this.destination = {\n sameDocument: isSameDocument,\n url: targetUrl,\n };\n if (formData) this.formData = formData;\n this.downloadRequest = isBlob;\n this.newWindow = newWindow;\n this.navigationType = \"push\";\n this.userInitiated = userInitiated;\n }\n}\n\nclass NavigationPolyfill extends EventTarget {\n constructor() {\n super();\n interceptWindowClicks(this);\n patchGlobalScope(this);\n }\n}\n\nexport const navigation =\n (window as any).navigation ?? new NavigationPolyfill();\n\nfunction patchGlobalScope(navigation: NavigationPolyfill) {\n try {\n Object.defineProperty(window, \"navigation\", {\n value: navigation,\n });\n } catch {\n //\n }\n}\n\nfunction interceptWindowClicks(navigation: NavigationPolyfill) {\n function clickCallback(ev: MouseEvent, aEl: HTMLAnchorElement) {\n const isAppNavigation =\n ev.button === 0 &&\n !ev.defaultPrevented &&\n !ev.metaKey &&\n !ev.altKey &&\n !ev.ctrlKey &&\n !ev.shiftKey;\n\n if (!isAppNavigation) return;\n // If the user writes a relative link such as ?query=true\n const targetUrl = new URL(aEl.href, window.location.origin);\n const isSameDocument =\n targetUrl.origin === window.location.origin &&\n targetUrl.pathname === window.location.pathname;\n const navigationEvent = new NavigationEvent({\n isSameDocument,\n targetUrl: aEl.href,\n isBlob: targetUrl.protocol === \"blob:\",\n newWindow: aEl.target === \"_blank\",\n userInitiated: true,\n });\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent#return_value\n const wasCancelled = !navigation.dispatchEvent(navigationEvent);\n if (wasCancelled) {\n ev.preventDefault();\n }\n }\n\n function submitCallback(ev: SubmitEvent, form: HTMLFormElement) {\n if (ev.defaultPrevented) return;\n const method =\n ev.submitter && \"formMethod\" in ev.submitter && ev.submitter.formMethod\n ? (ev.submitter.formMethod as string)\n : form.method;\n if (method === \"dialog\") return;\n const action =\n ev.submitter && \"formAction\" in ev.submitter && ev.submitter.formAction\n ? (ev.submitter.formAction as string)\n : form.action;\n const navigationEvent = new NavigationEvent({\n isSameDocument: false,\n targetUrl: action,\n formData: new FormData(form),\n });\n navigation.dispatchEvent(navigationEvent);\n if (navigationEvent.defaultPrevented) {\n ev.preventDefault();\n }\n }\n window.addEventListener(\n \"click\",\n (ev: MouseEvent) => {\n const aEl = (ev.target as Element).closest?.(\"a[href]\");\n if (aEl instanceof HTMLAnchorElement) {\n clickCallback(ev, aEl);\n }\n },\n true,\n );\n window.addEventListener(\"submit\", (ev: SubmitEvent) => {\n const form: unknown = (ev.target as Element).closest?.(\"form\");\n if (form instanceof HTMLFormElement) {\n submitCallback(ev, form);\n }\n });\n}\n","export const isValidUrlScheme = (url: string): boolean => {\n return (\n // Standard http call\n url.startsWith(\"http://\") ||\n // Secure http call\n url.startsWith(\"https://\") ||\n // Mail url to directly open email app prefilled\n url.startsWith(\"mailto:\") ||\n // Tel url to directly open phone app prefilled\n url.startsWith(\"tel:\")\n );\n};\n\nexport const isValidUrl = (url: string): boolean => {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n};\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport { isLocalLink } from \"../../../internal-details/utils/is-local-link.js\";\nimport {\n navigation,\n NavigationEvent,\n} from \"../../../internal-details/utils/navigation.js\";\nimport { isValidUrl, isValidUrlScheme } from \"./utils.js\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type {\n NavigateToStep,\n ValueInputProp,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const NavigateToTrigger = {\n type: TriggerStepType.NAVIGATE_TO,\n\n async execute(context: ExecutionContext, step: NavigateToStep) {\n let url = context.rootStore.entityManager.computeValue({\n scopeId: context.scopeId,\n name: context.name,\n value: step.url,\n args: [context.additionalContext],\n });\n\n const urlWithScheme = isValidUrlScheme(url) ? url : \"https://\" + url;\n if (isValidUrl(urlWithScheme) && !url.startsWith(\"/\")) {\n url = urlWithScheme;\n }\n\n if (isLocalLink(url)) {\n navigation.dispatchEvent(\n new NavigationEvent({\n isSameDocument: true,\n targetUrl: url,\n userInitiated: true,\n }),\n );\n return;\n }\n\n // step.replaceHistory only works in multi page, implement when that is supported\n // https://github.com/superblocksteam/superblocks/pull/7347\n\n if (step.newWindow) {\n navigation.dispatchEvent(\n new NavigationEvent({\n isSameDocument: false,\n targetUrl: url,\n newWindow: true,\n userInitiated: true,\n }),\n );\n } else if (window.top) {\n window.top.location.href = url;\n } else {\n window.location.href = url;\n }\n },\n\n create(\n url: ValueInputProp<string>,\n opts?: {\n newWindow?: boolean;\n replaceHistory?: boolean;\n arguments?: string;\n },\n ) {\n return {\n type: TriggerStepType.NAVIGATE_TO,\n url,\n newWindow: opts?.newWindow ?? false,\n replaceHistory: opts?.replaceHistory,\n arguments: opts?.arguments,\n };\n },\n} satisfies Trigger<NavigateToStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { ValueInputProp } from \"@superblocksteam/library-shared/types\";\nimport type { SetQueryParamsStep } from \"@superblocksteam/library-shared/types\";\n\nexport const SetQueryParamsTrigger = {\n type: TriggerStepType.SET_QUERY_PARAMS,\n\n async execute(_context: ExecutionContext, step: SetQueryParamsStep) {\n console.log(\"SetQueryParamsTrigger\", step);\n },\n\n create(\n queryParams: Record<string, ValueInputProp<string>>,\n opts?: {\n keep?: boolean;\n },\n ) {\n return {\n type: TriggerStepType.SET_QUERY_PARAMS,\n queryParams,\n keepQueryParams: opts?.keep ?? false,\n };\n },\n} satisfies Trigger<SetQueryParamsStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../base.js\";\nimport type {\n Executable,\n RunJsStep,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const RunJsTrigger = {\n type: TriggerStepType.RUN_JS,\n\n // TODO: implement opts?: { defer?: number }\n create(handler: Executable) {\n return {\n type: TriggerStepType.RUN_JS,\n handler,\n code: handler ? handler.toString() : \"\",\n };\n },\n\n async execute(context: ExecutionContext, step: RunJsStep) {\n if (step.handler) {\n context.rootStore.entityManager.runCode({\n scopeId: context.scopeId,\n name: context.name,\n func: step.handler,\n args: [context.additionalContext],\n excludeState: true,\n });\n }\n },\n} satisfies Trigger<RunJsStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../base.js\";\nimport type { SetProfileStep } from \"@superblocksteam/library-shared/types\";\n\nexport const SetProfileTrigger = {\n type: TriggerStepType.SET_PROFILE,\n\n async execute(_context: ExecutionContext, step: SetProfileStep) {\n // TODO: Implement this\n console.log(\"SetProfileTrigger\", step);\n },\n\n create(\n profileId: string,\n opts: {\n action: \"set\" | \"unset\";\n },\n ) {\n return {\n type: TriggerStepType.SET_PROFILE,\n profileId,\n action: opts.action ?? \"set\",\n };\n },\n} satisfies Trigger<SetProfileStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type {\n ResetStateVarStep,\n WithBindingIdentifier,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const ResetStateVarTrigger = {\n type: TriggerStepType.RESET_STATE_VAR,\n\n async execute(context: ExecutionContext, step: ResetStateVarStep) {\n if (step.variable === undefined) {\n return;\n }\n\n context.rootStore.entityManager.runCode({\n scopeId: context.scopeId,\n name: context.name,\n func: () => step.variable?.set(step.variable.defaultValue),\n args: [],\n });\n },\n\n create(variable?: WithBindingIdentifier) {\n return {\n type: TriggerStepType.RESET_STATE_VAR,\n variable,\n };\n },\n} satisfies Trigger<ResetStateVarStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type { ValueInputProp } from \"@superblocksteam/library-shared/types\";\nimport type {\n SetStateVarStep,\n WithBindingIdentifier,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const SetStateVarTrigger = {\n type: TriggerStepType.SET_STATE_VAR,\n\n async execute(context: ExecutionContext, step: SetStateVarStep) {\n if (step.variable === undefined) {\n return;\n }\n\n const value = context.rootStore.entityManager.computeValue({\n scopeId: context.scopeId,\n name: context.name,\n value: step.value,\n args: [context.additionalContext],\n });\n\n context.rootStore.entityManager.runCode({\n scopeId: context.scopeId,\n name: context.name,\n func: (state: any, value: any) => {\n if (!state) return;\n\n step.variable?.set(value);\n },\n args: [value],\n });\n },\n\n create(\n variable: WithBindingIdentifier,\n opts: {\n value: ValueInputProp;\n },\n ) {\n return {\n type: TriggerStepType.SET_STATE_VAR,\n variable: variable,\n value: opts.value,\n };\n },\n} satisfies Trigger<SetStateVarStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../../base.js\";\nimport type {\n ControlTimerStep,\n WithBindingIdentifier,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const ControlTimerTrigger = {\n type: TriggerStepType.CONTROL_TIMER,\n\n async execute(_context: ExecutionContext, step: ControlTimerStep) {\n if (step.timer) {\n step.timer[step.action]();\n }\n },\n\n create(\n timer: WithBindingIdentifier,\n opts: {\n action: \"start\" | \"stop\" | \"toggle\";\n },\n ) {\n return {\n type: TriggerStepType.CONTROL_TIMER,\n timer,\n action: opts.action,\n };\n },\n} satisfies Trigger<ControlTimerStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport type { ExecutionContext, Trigger } from \"../base.js\";\nimport type {\n SelectedEventProps,\n TriggerEventStep,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const TriggerEventTrigger = {\n type: TriggerStepType.TRIGGER_EVENT,\n\n async execute(_context: ExecutionContext, step: TriggerEventStep) {\n // TODO: Implement this\n console.log(\"TriggerEventTrigger\", step);\n },\n\n create(\n eventName: string,\n opts?: {\n data: Record<string, string>;\n },\n ) {\n return {\n type: TriggerStepType.TRIGGER_EVENT,\n event: { name: eventName } as SelectedEventProps, //TODO(code-mode): this is a hack to get the name\n eventPayload: opts?.data,\n };\n },\n} satisfies Trigger<TriggerEventStep>;\n","import { TriggerStepType } from \"@superblocksteam/library-shared/types\";\nimport { CancelApisTrigger } from \"./implementations/apis/cancel-apis.js\";\nimport { RunApisTrigger } from \"./implementations/apis/run-apis.js\";\nimport { CallFunctionTrigger } from \"./implementations/call-function.js\";\nimport { ControlModalTrigger } from \"./implementations/components/control-modal.js\";\nimport { ControlSlideoutTrigger } from \"./implementations/components/control-slideout.js\";\nimport { ResetComponentTrigger } from \"./implementations/components/reset-component.js\";\nimport { SetComponentPropertyTrigger } from \"./implementations/components/set-component-property.js\";\nimport { NavigateToAppTrigger } from \"./implementations/navigate/navigate-to-app.js\";\nimport { NavigateToRouteTrigger } from \"./implementations/navigate/navigate-to-route.js\";\nimport { NavigateToTrigger } from \"./implementations/navigate/navigate-to.js\";\nimport { SetQueryParamsTrigger } from \"./implementations/navigate/set-query-params.js\";\nimport { RunJsTrigger } from \"./implementations/run-js.js\";\nimport { SetProfileTrigger } from \"./implementations/set-profile.js\";\nimport { ResetStateVarTrigger } from \"./implementations/state/reset-state-var.js\";\nimport { SetStateVarTrigger } from \"./implementations/state/set-state-var.js\";\nimport { ControlTimerTrigger } from \"./implementations/timers/control-timer.js\";\nimport { TriggerEventTrigger } from \"./implementations/trigger-event.js\";\nimport type { Trigger } from \"./base.js\";\nimport type { ValidStepDef } from \"@superblocksteam/library-shared/types\";\n\ntype ImplementedTriggerTypes = Exclude<TriggerStepType, \"showAlert\">;\n\nconst EventRegistry: Record<ImplementedTriggerTypes, Trigger<ValidStepDef>> = {\n // Code execution\n [TriggerStepType.RUN_JS]: RunJsTrigger,\n\n // Navigation\n [TriggerStepType.NAVIGATE_TO]: NavigateToTrigger,\n [TriggerStepType.NAVIGATE_TO_APP]: NavigateToAppTrigger,\n [TriggerStepType.NAVIGATE_TO_ROUTE]: NavigateToRouteTrigger,\n\n [TriggerStepType.SET_QUERY_PARAMS]: SetQueryParamsTrigger,\n\n // Widgets\n [TriggerStepType.CONTROL_SLIDEOUT]: ControlSlideoutTrigger,\n [TriggerStepType.CONTROL_MODAL]: ControlModalTrigger,\n [TriggerStepType.RESET_COMPONENT]: ResetComponentTrigger,\n\n // General entities\n [TriggerStepType.CALL_FUNCTION]: CallFunctionTrigger,\n\n // APIs\n [TriggerStepType.RUN_APIS]: RunApisTrigger,\n [TriggerStepType.CANCEL_APIS]: CancelApisTrigger,\n\n // State\n [TriggerStepType.SET_STATE_VAR]: SetStateVarTrigger,\n [TriggerStepType.SET_COMPONENT_PROPERTY]: SetComponentPropertyTrigger,\n [TriggerStepType.RESET_STATE_VAR]: ResetStateVarTrigger,\n\n // Timers\n [TriggerStepType.CONTROL_TIMER]: ControlTimerTrigger,\n\n // Profiles && Events\n [TriggerStepType.SET_PROFILE]: SetProfileTrigger,\n [TriggerStepType.TRIGGER_EVENT]: TriggerEventTrigger,\n};\n\nexport default EventRegistry;\n","import { isValidStepDef } from \"@superblocksteam/library-shared/types\";\nimport TriggerRegistry from \"./registry.js\";\nimport type { Trigger } from \"./base.js\";\nimport type { ScopeId } from \"../internal-details/lib/evaluator/base-entity-manager.js\";\nimport type { Name } from \"../internal-details/lib/evaluator/names.js\";\nimport type { RootStore } from \"../internal-details/lib/root-store.js\";\nimport type {\n IEventFlow,\n ScopedState,\n StepDef,\n ValueInputProp,\n} from \"@superblocksteam/library-shared/types\";\n\n// Here we load the root store but via dynamic import so that it doesn't get loaded until this function is called.\n// We do this mostly for testing purposes.\nconst getRootStore = (): Promise<RootStore> =>\n import(\"../internal-details/lib/root-store.js\").then(\n (module) => module.default,\n );\n\n// In our existing code, this would do a round-trip up to the parent iframe and back down to the child iframe.\n// the main reason is that we need to run evaluations, for example if a \"Run JS\" step is triggered\nexport const runEventHandlers = async ({\n flow,\n name,\n scopeId,\n additionalContext,\n}: {\n flow?: IEventFlow<StepDef, ScopedState, ValueInputProp>;\n name: Name;\n scopeId: ScopeId;\n additionalContext?: Record<string, any>;\n}) => {\n const context = {\n scopeId,\n name,\n rootStore: await getRootStore(),\n additionalContext,\n };\n\n const steps = flow?.build() ?? [];\n for (const step of steps) {\n if (!isValidStepDef(step)) continue;\n const stepType = step.type as keyof typeof TriggerRegistry;\n const trigger: Trigger<any> = TriggerRegistry[stepType];\n if (trigger) {\n await trigger.execute(context, step);\n } else {\n console.error(\n `Trigger ${step.type as keyof typeof TriggerRegistry} not found`,\n );\n }\n }\n};\n\nexport default runEventHandlers;\n","import { type Section, type Prop, CompositeProp } from \"./props-builder.js\";\nimport type {\n PropertiesPanelDefinition,\n PropertiesPanelSectionDefinition,\n WidgetPropertyDefinition,\n} from \"@superblocksteam/library-shared/props\";\nimport type {\n ScopedState,\n Entity,\n} from \"@superblocksteam/library-shared/types\";\n\nfunction createPropertiesPanelDefinition(\n sections: Record<string, Section>,\n entity?: Entity,\n scopedState?: ScopedState,\n): PropertiesPanelDefinition {\n const sectionDefs: Array<PropertiesPanelSectionDefinition> = [];\n\n const getSectionChildren = (\n props: Record<string, Prop<any, any>>,\n parentPath: string,\n ) => {\n const properties: WidgetPropertyDefinition<any>[] = [];\n\n /**\n * There are three ways we can display a Composite prop:\n * 1. Prop control + popover panel (e.g: TextStyle)\n * 2. Prop control (e.g: Border)\n * 3. Inline, without a prop control (e.g: Search prop on Table, which contains backgroundColor, borderRadius, etc.)\n *\n * isCompositeWithInlineNestedProps is used to determine if a prop is of type (3).\n */\n const isCompositeWithInlineNestedProps = (\n prop: Prop<any, any>,\n fullPath: string,\n ): prop is InstanceType<typeof CompositeProp<any>> => {\n if (\n !(prop instanceof CompositeProp) ||\n !prop.hasPropertiesPanelDisplay()\n ) {\n return false;\n }\n\n const displayMode = prop.propertiesPanelChildrenDisplayMode();\n if (!displayMode) {\n return false;\n }\n\n const resolvedDisplayMode =\n typeof displayMode === \"function\"\n ? displayMode(entity, fullPath)\n : displayMode;\n\n return resolvedDisplayMode?.type === \"inline\";\n };\n\n for (const [name, prop] of Object.entries(props)) {\n const fullPath = parentPath ? `${parentPath}.${name}` : name;\n\n if (isCompositeWithInlineNestedProps(prop, fullPath)) {\n // For case (3) we dive into the composite props, and treat nested props as regular props\n const inlinePropertiesDefs = getSectionChildren(\n prop.nestedProps,\n fullPath,\n );\n properties.push(...inlinePropertiesDefs);\n } else if (prop.hasPropertiesPanelDisplay()) {\n // For case (1) and (2) we do not dive into the composite props for panel purposes\n // because we will want to write the entire composite prop as a single update\n // for example, in the JSX if the user updates the \"topLeft\" property of a\n // \"borderRadius\" composite prop, we want to update the \"borderRadius\" prop\n // as a whole, not just the \"topLeft\" property\n\n const def = prop.setName(fullPath).toDefinition(entity, scopedState);\n if (def) {\n properties.push(def);\n }\n }\n }\n\n return properties;\n };\n\n for (const [, section] of Object.entries(sections)) {\n const children = getSectionChildren(section.props, \"\");\n if (children.length === 0) {\n continue;\n }\n sectionDefs.push({\n name: section.name,\n category: section.category,\n children,\n showHeader: section.propertiesPanelConfig.showHeader,\n isDefaultOpen: section.propertiesPanelConfig.isDefaultOpen,\n headerType: section.propertiesPanelConfig.headerType,\n subHeader: section.propertiesPanelConfig.subHeader,\n });\n }\n\n return { sections: sectionDefs };\n}\n\nexport { createPropertiesPanelDefinition };\n","import JSON5 from \"json5\";\nimport {\n isEmpty,\n isNumber,\n isObject,\n isString,\n isUndefined,\n toNumber,\n toString,\n} from \"lodash\";\nimport moment from \"moment\";\nimport type { Entity } from \"@superblocksteam/library-shared/types\";\n\ntype ValidationResult<T = any> =\n | {\n valid: false;\n message: string;\n invalidValue: any;\n }\n | {\n valid: true;\n result: T;\n };\n\ntype ValidateFn<T> = (value: any, entity: Entity) => ValidationResult<T>;\n\nconst Valid = <T>(result: T): ValidationResult<T> => {\n return { valid: true, result };\n};\n\nconst DEFAULT_INVALID_MESSAGE = \"Value does not match Required Data Format\";\nconst Invalid = <T>(\n message: string = DEFAULT_INVALID_MESSAGE,\n invalidValue: any,\n): ValidationResult<T> => {\n return { valid: false, message, invalidValue };\n};\n\ntype VALIDATION_TYPES = {\n TEXT: ValidateFn<string | undefined>;\n TEXT_EMPTY_NULL: ValidateFn<string | undefined | null>;\n TEXT_ALLOW_UNDEFINED: ValidateFn<string | undefined>;\n REGEX: ValidateFn<string | undefined>;\n NUMBER: ValidateFn<number>;\n NUMBER_ALLOW_UNDEFINED: ValidateFn<number | undefined>;\n BOOLEAN: ValidateFn<boolean>;\n BOOLEAN_ALLOW_UNDEFINED: ValidateFn<boolean | undefined>;\n OBJECT: ValidateFn<object>;\n OBJECT_OR_UNDEFINED: ValidateFn<object | undefined>;\n ARRAY: ValidateFn<any[]>;\n ARRAY_ALLOW_UNDEFINED: ValidateFn<any[] | undefined>;\n DATE: ValidateFn<string>;\n URL_OR_BASE64: ValidateFn<string>;\n URL_FOR_HYPERLINK: ValidateFn<string>;\n FRACTION_DIGITS: ValidateFn<number | undefined>;\n NUMBER_ARRAY: ValidateFn<number[]>;\n ICONS: ValidateFn<any>;\n\n // The following validation types have not been ported over:\n // NOTE: They are widget specific and SHOULD not be here\n // TABLE_DATA: ValidateFn<any>,\n // TABLE_SORT: ValidateFn<any>,\n // FILTERS_DATA: ValidateFn<any>,\n // OPTIONS_DATA: ValidateFn<any>,\n // DEFAULT_DATE: ValidateFn<any>,\n // MIN_DATE: ValidateFn<any>,\n // MAX_DATE: ValidateFn<any>,\n // TABS_DATA: ValidateFn<any>,\n // CHART_DATA: ValidateFn<any>,\n // MARKERS: ValidateFn<any>,\n // SELECTED_TAB: ValidateFn<any>,\n // DEFAULT_OPTION_VALUE: ValidateFn<any>,\n // DEFAULT_SELECTED_ROW: ValidateFn<any>,\n // COLUMN_PROPERTIES_ARRAY: ValidateFn<any>,\n // LAT_LONG: ValidateFn<any>,\n // PLOTLY_CHART_JSON: ValidateFn<any>,\n};\n\nconst VALIDATORS: VALIDATION_TYPES = {\n TEXT: (value) => {\n let parsed = value;\n if (isUndefined(value) || value === null) {\n return Valid(\"\");\n }\n if (isObject(value) || Array.isArray(value)) {\n return Valid(JSON5.stringify(value, null, 2));\n }\n let isValid = isString(value);\n if (!isValid) {\n try {\n parsed = toString(value);\n isValid = true;\n } catch (e) {\n console.error(`Error when parsing ${value} to string`);\n console.error(e);\n return Invalid(\"Invalid string\", value);\n }\n }\n return Valid(parsed);\n },\n TEXT_EMPTY_NULL: (value, props) => {\n if (value === \"\") {\n return Valid(null);\n }\n return VALIDATORS.TEXT(value, props);\n },\n TEXT_ALLOW_UNDEFINED: (value, props) => {\n if (isUndefined(value)) {\n return Valid(value);\n }\n return VALIDATORS.TEXT(value, props);\n },\n REGEX: (value, props): ValidationResult<string> => {\n const result = VALIDATORS.TEXT(value, props);\n if (result.valid && result.result !== undefined) {\n try {\n new RegExp(result.result);\n } catch (_e) {\n return Invalid(\"Invalid regex\", value);\n }\n return Valid(result.result);\n }\n return Invalid(\"Invalid regex\", value);\n },\n NUMBER: (value): ValidationResult<number> => {\n let parsed = value;\n if (isUndefined(value)) {\n return Invalid(\"Invalid number\", value);\n }\n let isValid = isNumber(value);\n if (!isValid) {\n try {\n parsed = toNumber(value);\n isValid = true;\n } catch (e) {\n console.error(`Error when parsing ${value} to number`);\n console.error(e);\n return Invalid(\"Invalid number\", value);\n }\n }\n return Valid(parsed);\n },\n NUMBER_ALLOW_UNDEFINED: (\n value,\n props,\n ): ValidationResult<number | undefined> => {\n if (isUndefined(value)) {\n return Valid(value);\n }\n return VALIDATORS.NUMBER(value, props);\n },\n BOOLEAN: (value): ValidationResult<boolean> => {\n if (isUndefined(value)) {\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n return Valid(Boolean(value));\n },\n BOOLEAN_ALLOW_UNDEFINED: (\n value,\n props,\n ): ValidationResult<boolean | undefined> => {\n if (isUndefined(value)) {\n return Valid(value);\n }\n return VALIDATORS.BOOLEAN(value, props);\n },\n OBJECT: (value): ValidationResult<object> => {\n let parsed = value;\n if (isUndefined(value)) {\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n let isValid = isObject(value);\n if (!isValid) {\n try {\n parsed = JSON.parse(value);\n isValid = true;\n } catch (e) {\n console.error(`Error when parsing ${value} to object`);\n console.error(e);\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n }\n return Valid(parsed);\n },\n OBJECT_OR_UNDEFINED: (value, props): ValidationResult<object | undefined> => {\n if (isUndefined(value)) {\n return Valid(value);\n }\n return VALIDATORS.OBJECT(value, props);\n },\n ARRAY: (value): ValidationResult<any[]> => {\n let parsed = value;\n try {\n if (isUndefined(value)) {\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n if (isString(value)) {\n parsed = JSON5.parse(parsed as string);\n }\n if (!Array.isArray(parsed)) {\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n return Valid(parsed);\n } catch (e) {\n console.error(e);\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n },\n ARRAY_ALLOW_UNDEFINED: (\n value,\n props,\n ): ValidationResult<any[] | undefined> => {\n if (isUndefined(value)) {\n return Valid(value);\n }\n return VALIDATORS.ARRAY(value, props);\n },\n NUMBER_ARRAY: (value, props): ValidationResult<number[]> => {\n const res = VALIDATORS.ARRAY(value, props);\n if (!res.valid) {\n return Invalid(\"Invalid number array\", value);\n } else if (!res.result.every((datum: any) => typeof datum === \"number\")) {\n return Invalid(\"Not all elements in the array are numbers\", value);\n }\n return Valid(res.result);\n },\n FRACTION_DIGITS: (value, props): ValidationResult<number | undefined> => {\n if (isEmpty(value)) {\n return Valid(undefined);\n }\n const result = VALIDATORS.NUMBER(value, props);\n if (!result.valid) {\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n\n if (result.result < 0 || result.result > 20) {\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n\n return Valid(result.result);\n },\n ICONS: (): ValidationResult<any> => {\n return Invalid(\"Icons validation not implemented\", undefined);\n },\n DATE: (\n value,\n props: Entity & { dateFormat?: string },\n ): ValidationResult<string> => {\n const ISO_DATE_FORMAT = \"YYYY-MM-DD\";\n const dateFormat = props.dateFormat ? props.dateFormat : ISO_DATE_FORMAT;\n\n if (value === undefined) {\n return Invalid(\n \"Value does not match Required Data Format\" +\n (props.dateFormat ? props.dateFormat : \"\"),\n value,\n );\n }\n\n const isValid = moment(value, dateFormat).isValid();\n if (!isValid) {\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n\n return Valid(value);\n },\n URL_OR_BASE64: (value): ValidationResult<string> => {\n if (!value) {\n return Invalid(DEFAULT_INVALID_MESSAGE, value);\n }\n\n const base64Regex =\n // eslint-disable-next-line no-useless-escape\n /^data:application\\/pdf;base64,[a-z0-9\\!\\$\\&\\'\\,\\(\\)\\*\\+\\,\\;\\=\\-\\.\\_\\~\\:\\@\\/\\?\\%\\s]*\\s*$/i;\n\n if (base64Regex.test(value as string)) {\n return Valid(value);\n }\n\n try {\n const newUrl = new URL(value as string);\n if (newUrl.protocol !== \"https:\") {\n return Invalid(\"Only HTTPS protocol supported\", value);\n }\n\n return Valid(newUrl.href);\n } catch {\n return Invalid(\"Provided URL / Base64 is invalid.\", value);\n }\n },\n URL_FOR_HYPERLINK: (value): ValidationResult<string> => {\n const dummyBaseUrl = \"https://superblocks.com\";\n try {\n const isRelative =\n new URL(dummyBaseUrl).origin === new URL(value, dummyBaseUrl).origin;\n\n if (!isRelative) {\n const absoluteUrl = new URL(value);\n\n if (absoluteUrl.protocol === \"javascript:\") {\n return Invalid(`Invalid protocol ${absoluteUrl.protocol}`, value);\n }\n } else if (value && value.startsWith(\"..\")) {\n return Invalid(\"Relative URLs cannot start with '..'\", value);\n }\n\n return Valid(value);\n } catch {\n return Invalid(\"Provided URL is invalid.\", value);\n }\n },\n};\n\nexport type { ValidationResult, ValidateFn };\nexport { Valid, Invalid };\nexport { VALIDATORS };\n","import {\n type ControlType,\n type DataType,\n type DataTypeString,\n type PropertiesPanelDefinition,\n type PropertiesPanelDisplay,\n type PropertyForData,\n type WidgetPropertyDefinition,\n type Relation,\n PropsPanelCategory,\n InputType,\n} from \"@superblocksteam/library-shared/props\";\nimport { createManagedPropsList } from \"./create-managed-props-list.js\";\nimport { createPropertiesPanelDefinition } from \"./properties-panel-definition.js\";\nimport { VALIDATORS } from \"./validators.js\";\nimport type { InjectedProps } from \"../../internal-details/sb-wrapper.jsx\";\nimport type { SbComponentProps } from \"./../component-base/sb-component.js\";\nimport type { ValidateFn, ValidationResult } from \"./validators.js\";\nimport type { RuntimeWidgetMeta } from \"../../../edit-mode/features/runtime-widgets-manager.js\";\nimport type {\n InputProp,\n SingleInputProp,\n EntityFunction,\n} from \"../../internal-details/lib/evaluator/base-entity-manager.js\";\nimport type { EventFlow } from \"../event-flow.js\";\nimport type {\n Dim,\n DimModes,\n EvaluateOrValueComputedArgs,\n} from \"@superblocksteam/library-shared\";\nimport type {\n EvaluatedPropertiesPanelDisplay,\n HeaderType,\n} from \"@superblocksteam/library-shared/props\";\nimport type {\n Entity,\n PropertyInfo,\n SbElement,\n ScopedState,\n} from \"@superblocksteam/library-shared/types\";\nimport type { ReactNode } from \"react\";\n\n// TODO(mark): types types types\n// TODO(mark): This might not belong here as it's specific to the custom widget\nexport type CustomComponentRenderFunction = (\n props: any,\n state: any,\n) => React.ReactNode;\n\nexport type SideEffectCallback = (params: {\n sourceId: SbElement;\n updates: Record<string, PropertyInfo<unknown>>;\n widgetMeta: RuntimeWidgetMeta;\n widgetState: Entity | ScopedState | undefined;\n propertiesDefinition: PropertiesDefinition;\n // TODO (alex): eval side effect signature may be different\n}) => Record<\n SbElement,\n {\n meta?: Record<string, unknown>;\n props?: Record<string, PropertyInfo<unknown>>;\n }\n>;\n\nfunction mergeRelations(\n existingRelations: Relation[][],\n relations: Relation[][],\n): Relation[][] {\n if (!existingRelations || existingRelations.length === 0) {\n return relations;\n }\n if (!relations || relations.length === 0) {\n return existingRelations;\n }\n const mergedRelations =\n existingRelations && existingRelations.length > 0\n ? existingRelations.flatMap((existing) =>\n relations.map((relation) => [...existing, ...relation]),\n )\n : relations;\n return mergedRelations;\n}\n\ntype ManagedProp<T extends DataType = DataType> = PropertyForData<T> & {\n validate?: ValidateFn<any>; // TODO(mark): type this\n default?: SingleInputProp<T>;\n defaultOnAdd?: SingleInputProp<T>;\n onEditProperty?: SideEffectCallback;\n onEvaluateProperty?: SideEffectCallback;\n\n /**\n * Controls binding nesting behavior:\n * - true: Allows bindings to be nested at any depth within this property\n * - false: Only allows bindings at the top level (unless the property is composite)\n */\n nestedBindings?: boolean;\n\n /**\n * Indicates this property should be evaluated per-context (e.g., per-row in tables)\n * When true, the property value will be evaluated for each context with access to context variables\n */\n contextual?: boolean;\n computedArgs?: EvaluateOrValueComputedArgs;\n\n /**\n * Custom type hint for documentation generation\n * When set, this will override the auto-generated type in generated docs\n */\n typeHint?: string;\n\n isMetaProp?: boolean;\n isFunctionProp?: boolean;\n hasActionPanel?: boolean;\n};\n\ntype ManagedPropsList = Array<\n ManagedProp & {\n propertiesPanelDisplay?: PropertiesPanelDisplay<any>;\n }\n>;\n\n/**\n * Merges shared and variant properties for union types without creating intersections\n * Variant properties override shared properties with the same key\n */\ntype MergeUnionVariant<\n SHARED extends Record<string, Prop<any, any>>,\n VARIANT extends Record<string, Prop<any, any>>,\n> = Omit<SHARED, keyof VARIANT> & VARIANT;\n\n/**\n * Converts a union type to an intersection type\n * Used to merge multiple section props into a single props type\n */\ntype UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (\n x: infer I extends U,\n) => void\n ? I\n : never;\n\n/**\n * Controls how default values affect property optionality\n * - RequiredIfDefault: Properties with default values become required\n * - AlwaysOptional: All properties become optional regardless of defaults\n */\ntype DefaultValueBehavior = \"RequiredIfDefault\" | \"AlwaysOptional\";\n\n/**\n * Extracts the concrete type from a property definition\n *\n * For evaluated props: returns the actual value type\n *\n * For non-evaluated props: returns InputProp<ValueType>\n */\n/**\n * Extracts the concrete type from a property definition\n * Enhanced to handle contextual properties\n */\ntype ExtractPropType<\n T,\n DefaultsBehavior extends DefaultValueBehavior,\n IsEvaluated extends boolean,\n> =\n T extends Record<string, Prop<any, any, any>>\n ? ExtractProps<T, DefaultsBehavior, IsEvaluated>\n : T extends RecordProp<infer U>\n ? Record<string, ExtractProps<U, DefaultsBehavior, IsEvaluated>>\n : T extends CompositeProp<infer U>\n ? IsEvaluated extends true\n ? ExtractProps<U, DefaultsBehavior, IsEvaluated>\n : InputProp<ExtractProps<U, DefaultsBehavior, true>>\n : T extends UnionProp<infer SHARED, infer VARIANTS>\n ? VARIANTS extends readonly any[]\n ? {\n [I in keyof VARIANTS]: ExtractProps<\n MergeUnionVariant<SHARED, VARIANTS[I]>,\n DefaultsBehavior,\n IsEvaluated\n >;\n }[number]\n : never\n : T extends Prop<infer V, infer _HasDefault, infer ContextualProps>\n ? IsEvaluated extends true\n ? ContextualProps extends undefined\n ? V extends EventFlow\n ? (...args: any[]) => Promise<void>\n : V\n : ContextualProps extends any[]\n ? (...args: ContextualProps) => V\n : InputProp<V>\n : InputProp<V>\n : never;\n/**\n * Extracts a flat props object from a properties definition\n * Handles optionality based on DefaultValueBehavior\n */\ntype ExtractProps<\n T,\n DefaultsBehavior extends DefaultValueBehavior,\n IsEvaluated extends boolean,\n> =\n T extends Record<string, Section>\n ? ExtractProps<MergeSections<T>, DefaultsBehavior, IsEvaluated>\n : T extends Record<string, Prop<any, any, any>>\n ? DefaultsBehavior extends \"AlwaysOptional\"\n ? {\n [K in keyof T]?: ExtractPropType<\n T[K],\n DefaultsBehavior,\n IsEvaluated\n >;\n }\n : {\n [K in keyof T as T[K] extends Prop<any, infer HasDefault, any>\n ? HasDefault extends true\n ? K\n : never\n : never]: ExtractPropType<T[K], DefaultsBehavior, IsEvaluated>;\n } & {\n [K in keyof T as T[K] extends Prop<any, infer HasDefault, any>\n ? HasDefault extends false\n ? K\n : never\n : never]?: ExtractPropType<T[K], DefaultsBehavior, IsEvaluated>;\n }\n : never;\n\n/**\n * Handles non Prop types, aka our default types and CSS props\n */\nexport type RawPropsToExternal<T = Record<string, unknown>> = {\n [K in keyof T as undefined extends T[K] ? never : K]: SingleInputProp<T[K]>;\n} & {\n [K in keyof T as undefined extends T[K] ? K : never]?: SingleInputProp<\n Exclude<T[K], undefined>\n >;\n};\n\ntype SectionPropertiesPanelConfig = {\n showHeader?: boolean;\n isDefaultOpen?: boolean;\n headerType?: HeaderType;\n subHeader?: string;\n};\n\n/**\n * Merges all sections in a properties definition into a single props type\n */\ntype MergeSections<\n T extends Record<string, Section>,\n Merged = UnionToIntersection<T[keyof T]>,\n> = Merged extends Section<infer U> ? U : never;\n\n/**\n * Identical to InternalProps but without the base props\n */\ntype EntityProps<\n Definition extends PropertiesDefinition,\n MergedSections = MergeSections<Definition>,\n> = ExtractProps<MergedSections, \"RequiredIfDefault\", true>;\n\n/**\n * Internal props used by the component implementation\n * - Properties with defaults are required\n * - Properties are fully evaluated to their final types\n */\ntype InternalProps<\n Definition extends PropertiesDefinition,\n FlattenedProps = EntityProps<Definition>,\n BaseProps = Omit<SbComponentProps, keyof FlattenedProps>,\n> = FlattenedProps & BaseProps & InjectedProps;\n\n// Make specific properties optional\ntype MakeOptional<T, K extends string> = Omit<T, K & keyof T> &\n Partial<Pick<T, K & keyof T>>;\n\n// Clean out properties that are index signatures or string-based keys, otherwise, Omit will result in a type that is basically {[x: string]: any}\ntype CleanProps<T> = {\n [K in keyof T as string extends K ? never : K]: T[K];\n};\n\ntype InternalPropsWithOptional<\n Definition extends PropertiesDefinition,\n OptionalProps extends string,\n InternalPropsWithDefinition = InternalProps<Definition>,\n> = InternalPropsWithDefinition extends infer U\n ? U extends any\n ? MakeOptional<CleanProps<U>, OptionalProps> & {\n [key: string]: any; // Add back the index signature for additional keys\n }\n : never\n : never;\n\n/**\n * External props exposed to component consumers\n * - All properties are optional regardless of defaults\n * - Properties accept InputProp values (bindings/functions)\n */\ntype ExternalProps<\n Definition extends PropertiesDefinition,\n MergedSections = MergeSections<Definition>,\n FlattenedProps = ExtractProps<MergedSections, \"AlwaysOptional\", false>,\n BaseProps = Omit<SbComponentProps, keyof FlattenedProps>,\n> = FlattenedProps & RawPropsToExternal<BaseProps>;\n\ntype PropertiesDefinition = Record<string, Section>;\n\ntype SectionDefinition<T extends Record<string, Prop<any, any>>> = {\n props: T;\n showHeader?: boolean;\n isDefaultOpen?: boolean;\n headerType?: HeaderType;\n subHeader?: string;\n};\n\nfunction getChildren(\n input: CompositeInputs,\n path: string,\n entity: Entity,\n scopedState: ScopedState,\n) {\n function getChildrenFromSection(section: Section) {\n return Object.keys(section.props).reduce(\n (acc, key) => {\n const prop = section.props[key];\n const definition = prop\n .setName(path + \".\" + key)\n .toDefinition(entity, scopedState);\n if (definition) {\n acc[key] = definition;\n }\n return acc;\n },\n {} as Record<string, WidgetPropertyDefinition<DataType>>,\n );\n }\n\n let children: Record<string, WidgetPropertyDefinition<DataType>>;\n if (input instanceof Section) {\n // Case 1: content is a Section\n children = getChildrenFromSection(input);\n } else if (Object.values(input).every((c) => c instanceof Section)) {\n // Case 2: content is a Record<string, Section>\n children = Object.values(input).reduce((acc, section) => {\n return { ...acc, ...getChildrenFromSection(section) };\n }, {});\n } else {\n // Case 3: content is a Record<string, Prop<any, any, any>>\n children = Object.fromEntries(\n Object.entries(input).map(([key, prop]) => {\n return [\n key,\n prop.setName(path + \".\" + key).toDefinition(entity, scopedState),\n ];\n }),\n );\n }\n return children;\n}\n\nclass Section<\n T extends Record<string, Prop<any, any>> = Record<string, Prop<any, any>>,\n> {\n props: T = {} as T;\n\n propertiesPanelConfig: SectionPropertiesPanelConfig = {\n showHeader: true,\n isDefaultOpen: true,\n };\n\n constructor(readonly category: PropsPanelCategory) {}\n\n static category(category: PropsPanelCategory) {\n return new Section(category);\n }\n\n children<\n INP extends\n | Record<string, Prop<any, any>>\n | CompositeProp<any>\n | UnionProp<any, any>,\n OUT extends INP extends CompositeProp<infer CU>\n ? CU\n : INP extends UnionProp<infer SHARED, infer VARIANTS>\n ? VARIANTS extends readonly any[]\n ? {\n [I in keyof VARIANTS]: MergeUnionVariant<SHARED, VARIANTS[I]>;\n }[number]\n : never\n : INP,\n >(props: INP): Section<T & OUT> {\n if (props instanceof CompositeProp || props instanceof RecordProp) {\n this.props = { ...this.props, ...props.getProps() };\n } else if (props instanceof UnionProp) {\n this.props = { ...this.props, ...props.getProps() };\n } else {\n this.props = { ...this.props, ...props };\n }\n return this as unknown as Section<T & OUT>;\n }\n\n add = this.children;\n\n propertiesPanel(config: Omit<SectionDefinition<any>, \"props\">) {\n this.propertiesPanelConfig = {\n ...this.propertiesPanelConfig,\n ...config,\n };\n return this;\n }\n\n get name() {\n switch (this.category) {\n case PropsPanelCategory.Content:\n return \"Content\";\n case PropsPanelCategory.Routing:\n return \"Routing\";\n case PropsPanelCategory.Interaction:\n return \"Interaction\";\n case PropsPanelCategory.Layout:\n return \"Layout\";\n case PropsPanelCategory.Appearance:\n return \"Appearance\";\n case PropsPanelCategory.Permissions:\n return \"Permissions\";\n case PropsPanelCategory.EventHandlers:\n return \"Event handlers\";\n case PropsPanelCategory.CustomStyles:\n return \"Custom styles\";\n case PropsPanelCategory.Uncategorized:\n return \"Uncategorized\";\n default:\n return \"Uncategorized\";\n }\n }\n}\n\nclass Prop<\n Type extends DataType,\n _HasDefault extends boolean = false,\n _ContextualArgs extends\n | any[]\n | undefined\n | ((entity: Entity) => any[] | undefined) = undefined,\n> {\n protected prop: ManagedProp<Type>;\n\n /**\n * Relations are an array of arrays\n * each sub-array is AND requirements, and each element is an OR requirement\n */\n protected relations: Relation[][] = [];\n\n protected constructor(\n typeString: DataTypeString,\n defaultValidator?: ValidateFn<Type | undefined>,\n ) {\n this.prop = {\n path: \"\",\n dataType: typeString,\n isExternallyReadable: true,\n isExternallySettable: false,\n validate: defaultValidator,\n };\n }\n\n static unset(): Prop<undefined> {\n return new Prop(\"any\") as Prop<undefined>;\n }\n\n static string<T extends string>(): Prop<T> {\n return new Prop(\"string\", VALIDATORS.TEXT_ALLOW_UNDEFINED) as Prop<T>;\n }\n\n static number<T extends number>(): Prop<T> {\n return new Prop(\"number\", VALIDATORS.NUMBER_ALLOW_UNDEFINED) as Prop<T>;\n }\n\n static boolean<T extends boolean>(): Prop<T> {\n return new Prop(\"boolean\", VALIDATORS.BOOLEAN_ALLOW_UNDEFINED) as Prop<T>;\n }\n\n static array<T = Array<any>>(): Prop<T[]> {\n return new Prop(\"array\", VALIDATORS.ARRAY_ALLOW_UNDEFINED) as Prop<T[]>;\n }\n\n static any<T = any>(): Prop<T> {\n return new Prop(\"any\") as Prop<T>;\n }\n\n static jsx<T extends ReactNode>(): Prop<T> {\n return new Prop(\"jsx\") as Prop<T>;\n }\n\n static dimension<T extends Dim<DimModes>>(): Prop<T> {\n return new Prop(\"dimension\") as Prop<T>;\n }\n\n static literal<T extends Readonly<string | number | boolean>>(\n value: T,\n ): Prop<T, true> {\n switch (typeof value) {\n case \"string\":\n return Prop.string().default(value) as Prop<T, true>;\n case \"number\":\n return Prop.number().default(value) as Prop<T, true>;\n case \"boolean\":\n return Prop.boolean().default(value) as Prop<T, true>;\n default: {\n const exhaustiveCheck: never = value;\n throw new Error(`Invalid literal value: ${exhaustiveCheck}`);\n }\n }\n }\n\n static event(): Prop<EventFlow> {\n return new Prop(\"event\");\n }\n\n static children(): Prop<any> {\n return new ChildrenProp();\n }\n\n static function<ARGS extends any[] = any[], RETURN = any>(\n implementation: EntityFunction<ARGS, RETURN>,\n ) {\n return new FunctionProp(implementation);\n }\n\n /**\n * Creates an internal property that is not exposed in the entity's public interface,\n * not tracked for reactivity/syncing, and not serialized. This is useful for\n * storing implementation details like SuspensibleAPI instances that other\n * properties can reference via `this._propertyName`.\n */\n static internal<T = any>(factory: () => T): Prop<T, true> {\n const prop = new Prop<T>(\"internal\");\n return prop.default(factory);\n }\n\n /**\n * Creates a composite property, which is a property that contains nested properties. For example,\n * the following composite property:\n *\n * ```ts\n * const prop = Prop.composite({\n * name: Prop.string(),\n * age: Prop.number(),\n * });\n * ```\n *\n * is equivalent to the following type:\n *\n * ```ts\n * type Prop = {\n * name: string;\n * age: number;\n * };\n * ```\n */\n static composite<T extends CompositeInputs>(props: T) {\n return new CompositeProp<T>(props);\n }\n\n /**\n * Creates a record property, which is a record that maps string keys to the nestedproperties. For example,\n * the following record property:\n *\n * ```ts\n * const prop = Prop.record({\n * name: Prop.string(),\n * age: Prop.number(),\n * });\n * ```\n *\n * is equivalent to the following type:\n *\n * ```ts\n * type Prop = Record<string, {\n * name: string;\n * age: number;\n * }>;\n * ```\n */\n static record<T extends CompositeInputs>(props: T) {\n return new RecordProp<T>(props);\n }\n\n static union<\n SHARED extends Record<string, Prop<unknown, boolean>>,\n VARIANTS extends UnionVariant<SHARED>[] = UnionVariant<SHARED>[],\n >(props: { shared: SHARED; variants: VARIANTS }) {\n return new UnionProp<SHARED, VARIANTS>(props.shared, props.variants);\n }\n\n readable() {\n this.prop.isExternallyReadable = true;\n return this;\n }\n\n writable() {\n this.prop.isExternallySettable = true;\n return this;\n }\n\n readAndWrite() {\n this.prop.isExternallyReadable = true;\n this.prop.isExternallySettable = true;\n return this;\n }\n\n default(de: SingleInputProp<DataType>): Prop<Type, true> {\n this.prop.default = de;\n if (\n this.prop.propertiesPanelDisplay &&\n this.prop.propertiesPanelDisplay.defaultValue === undefined\n ) {\n this.prop.propertiesPanelDisplay.defaultValue = de;\n }\n return this as unknown as Prop<Type, true>;\n }\n\n // alias for default\n computed(computeFn: SingleInputProp<DataType>): Prop<Type, true> {\n return this.default(computeFn);\n }\n\n allowNestedBindings(): Prop<Type, true> {\n this.prop.nestedBindings = true;\n throw new Error(\"Nested bindings are not supported yet\");\n // return this as unknown as Prop<Type, true>;\n }\n\n contextual<TContext extends any[] | undefined = any[]>(\n computedArgs?: EvaluateOrValueComputedArgs,\n ) {\n this.prop.contextual = true;\n this.prop.computedArgs = computedArgs;\n return this as Prop<Type, _HasDefault, TContext>;\n }\n\n validate(\n validateFn: ((value: any) => ValidationResult<Type>) | ValidateFn<any>,\n ) {\n this.prop.validate = validateFn;\n return this;\n }\n\n setName(name: string) {\n this.prop.path = name;\n return this;\n }\n\n onEdit(callback: SideEffectCallback) {\n this.prop.onEditProperty = callback;\n return this;\n }\n\n onEvaluate(callback: SideEffectCallback) {\n this.prop.onEvaluateProperty = callback;\n return this;\n }\n\n propertiesPanel<CT extends ControlType>(\n schema: Omit<\n Partial<PropertiesPanelDisplay<Type, CT>>,\n \"isTriggerProperty\"\n >,\n ) {\n // map dataType to control type\n let baseControlType: ControlType;\n let isJSConvertible = true;\n let isTriggerProperty = false;\n let inputType: InputType | undefined;\n switch (this.prop.dataType) {\n case \"string\":\n baseControlType = \"INPUT_TEXT\";\n break;\n case \"number\":\n baseControlType = \"INPUT_TEXT\";\n inputType = InputType.NUMBER;\n break;\n case \"array\":\n baseControlType = \"INPUT_TEXT\";\n break;\n case \"boolean\":\n baseControlType = \"SWITCH\";\n break;\n case \"event\":\n baseControlType = \"EVENT_TRIGGER\";\n isJSConvertible = false;\n isTriggerProperty = true;\n break;\n case \"jsx\":\n case \"children\":\n baseControlType = \"JSX\";\n break;\n case \"any\":\n default:\n baseControlType = \"INPUT_JS_EXPR\";\n break;\n }\n\n const propertiesPanelDisplay = {\n controlType: baseControlType,\n isJSConvertible,\n isTriggerProperty,\n defaultValue: schema.defaultValue ?? this.prop.default,\n defaultOnAdd: this.prop.propertiesPanelDisplay?.defaultOnAdd,\n inputType,\n ...schema,\n } as PropertiesPanelDisplay<Type>;\n\n this.prop.propertiesPanelDisplay = propertiesPanelDisplay;\n return this;\n }\n\n setDisplayProperty<K extends keyof PropertiesPanelDisplay<Type>>(\n property: K,\n value: PropertiesPanelDisplay<Type>[K],\n ) {\n if (!this.prop.propertiesPanelDisplay) return this;\n this.prop.propertiesPanelDisplay[property] = value;\n return this;\n }\n\n docs(docs: Exclude<PropertyForData<DataType>[\"docs\"], undefined>) {\n this.prop.docs = docs;\n return this;\n }\n\n /**\n * Sets a custom type hint for documentation generation.\n * This will override the auto-generated type in generated docs.\n *\n * @param typeHint The TypeScript type string to display in documentation\n * @example .typeHint(\"CSSProperties\")\n * @example .typeHint(\"Record<string, { color: string; backgroundColor?: string }>\")\n */\n typeHint(typeHint: string) {\n this.prop.typeHint = typeHint;\n return this;\n }\n\n build() {\n return this.prop;\n }\n\n toDefinition(\n entity?: Entity,\n scopedState?: ScopedState,\n ): WidgetPropertyDefinition<DataType> | undefined {\n const evaluatedProperties = Object.entries(\n this.prop.propertiesPanelDisplay ?? {},\n ).reduce(\n (acc, [key, value]) => {\n if (typeof value === \"function\") {\n try {\n acc[key] = value.bind(entity)(scopedState, this.prop.path);\n } catch (e) {\n console.error(\n `Error evaluating property ${key}, for type ${entity?.type}:`,\n e,\n );\n }\n }\n return acc;\n },\n {} as Record<string, unknown>,\n ) as Partial<EvaluatedPropertiesPanelDisplay<Type>>;\n\n if (evaluatedProperties.isVisible === false) {\n return undefined;\n }\n\n const propertiesPanelDisplay = {\n ...this.prop.propertiesPanelDisplay,\n ...evaluatedProperties,\n } as EvaluatedPropertiesPanelDisplay<Type>;\n\n if (\"treatDefaultAsNull\" in propertiesPanelDisplay) {\n if (propertiesPanelDisplay.treatDefaultAsNull) {\n if (propertiesPanelDisplay.defaultOnAdd === undefined) {\n propertiesPanelDisplay.defaultOnAdd =\n propertiesPanelDisplay.defaultValue;\n }\n\n propertiesPanelDisplay.defaultValue = undefined;\n }\n }\n\n let panelConfig: PropertiesPanelDefinition | undefined;\n\n const childrenDisplay = propertiesPanelDisplay?.childrenDisplayMode;\n const isPopover = childrenDisplay?.type === \"popover\";\n if (isPopover) {\n if (!(this instanceof CompositeProp || this instanceof RecordProp)) {\n console.error(this);\n throw new Error(\n \"Only composite properties can be used in popover properties at the moment\",\n );\n }\n const content = this.getProps();\n const { type, ...rest } = childrenDisplay;\n\n let contentDef: Record<string, Section>;\n if (content instanceof Section) {\n // Case 1: content is a Section\n contentDef = { content };\n } else if (Object.values(content).every((c) => c instanceof Section)) {\n // Case 2: content is a Record<string, Section>\n contentDef = content as Record<string, Section>;\n } else {\n // Case 3: content is a Record<string, Prop<any, any, any>>\n contentDef = {\n content: Section.category(PropsPanelCategory.Content)\n .propertiesPanel({\n showHeader: false,\n })\n .children(content as Record<string, Prop<any, any>>),\n };\n }\n panelConfig = {\n ...createPropertiesPanelDefinition(contentDef, entity, scopedState),\n ...rest,\n };\n }\n if (this.prop.computedArgs) {\n propertiesPanelDisplay.computedArgs =\n typeof this.prop.computedArgs === \"function\"\n ? this.prop.computedArgs(entity)\n : this.prop.computedArgs;\n }\n\n const propertiesPanelDisplayWithPanelConfig = {\n ...propertiesPanelDisplay,\n ...(panelConfig && { panelConfig }),\n };\n\n return {\n path: this.prop.path,\n dataType: this.prop.dataType,\n relations: this.relations,\n propertiesPanelDisplay: propertiesPanelDisplayWithPanelConfig,\n };\n }\n\n getRelations() {\n return this.relations;\n }\n\n dependsOn(relations: Relation[][]) {\n this.relations = relations;\n return this;\n }\n\n hasPropertiesPanelDisplay() {\n return this.prop.propertiesPanelDisplay !== undefined;\n }\n\n get type() {\n return this.prop.dataType;\n }\n\n get path() {\n return this.prop.path;\n }\n\n get onEditProperty() {\n return this.prop.onEditProperty;\n }\n\n get onEvaluateProperty() {\n return this.prop.onEvaluateProperty;\n }\n}\n\ntype CompositeInputs =\n | Record<string, Section>\n | Section\n | Record<string, Prop<unknown, boolean>>;\n\n/**\n * See {@link Prop.composite}\n */\nclass CompositeProp<T extends CompositeInputs> extends Prop<unknown, boolean> {\n typeString = \"composite\" as const;\n nestedProps: T;\n\n constructor(props: T) {\n super(\"composite\");\n this.nestedProps = props;\n }\n\n getProps() {\n return this.nestedProps;\n }\n\n toDefinition(\n entity: Entity,\n scopedState: ScopedState,\n ): WidgetPropertyDefinition<DataType> | undefined {\n const definition = super.toDefinition(entity, scopedState);\n if (!definition) {\n return undefined;\n }\n return {\n ...definition,\n children: getChildren(\n this.nestedProps,\n this.prop.path,\n entity,\n scopedState,\n ),\n };\n }\n\n propertiesPanelChildrenDisplayMode() {\n return this.prop.propertiesPanelDisplay?.childrenDisplayMode;\n }\n\n typeHint(typeHint: string) {\n this.prop.typeHint = typeHint;\n return this;\n }\n}\n\n/**\n * See {@link Prop.record}\n */\nclass RecordProp<T extends CompositeInputs> extends Prop<unknown, boolean> {\n typeString = \"recordOf\" as const;\n nestedProps: T;\n\n constructor(props: T) {\n super(\"recordOf\");\n this.nestedProps = props;\n }\n\n getProps() {\n return this.nestedProps;\n }\n\n toDefinition(\n entity: Entity,\n scopedState: ScopedState,\n ): WidgetPropertyDefinition<DataType> | undefined {\n const definition = super.toDefinition(entity, scopedState);\n if (!definition) {\n return undefined;\n }\n\n return {\n ...definition,\n children: getChildren(\n this.nestedProps,\n this.prop.path,\n entity,\n scopedState,\n ),\n };\n }\n\n typeHint(typeHint: string) {\n this.prop.typeHint = typeHint;\n return this;\n }\n}\n\nclass ChildrenProp extends Prop<unknown, boolean> {\n typeString = \"children\" as const;\n\n constructor() {\n super(\"children\");\n }\n}\n\nexport interface ActionPanel {\n arguments?: Record<string, Prop<any>>;\n}\nclass FunctionProp<ARGS extends any[] = any[], RETURN = any> extends Prop<\n EntityFunction<ARGS, RETURN>,\n true\n> {\n typeString = \"function\" as const;\n private _actionPanel: ActionPanel | undefined;\n\n constructor(implementation: EntityFunction<ARGS, RETURN>) {\n super(\"function\");\n this.default(implementation);\n }\n\n actionPanel(panel?: ActionPanel) {\n this._actionPanel = panel || {};\n return this;\n }\n\n getActionPanel() {\n return this._actionPanel;\n }\n\n hasActionPanel() {\n return !!this._actionPanel;\n }\n}\n\nexport type UnionVariant<SHARED extends Record<string, Prop<any>>> = {\n [K in keyof SHARED]: Prop<any>;\n};\n\nclass UnionProp<\n SHARED extends Record<string, Prop<unknown, boolean>>,\n VARIANTS extends UnionVariant<SHARED>[] = UnionVariant<SHARED>[],\n _OUTPUT = VARIANTS extends readonly any[]\n ? {\n [I in keyof VARIANTS]: SHARED & VARIANTS[I];\n }[number]\n : never,\n> extends Prop<any> {\n typeString = \"union\" as const;\n shared: SHARED;\n variants: VARIANTS;\n\n constructor(shared: SHARED, variants: VARIANTS) {\n super(\"any\");\n this.shared = shared;\n this.variants = variants;\n }\n\n getProps() {\n const sharedKeys = Object.keys(this.shared);\n const variants: UnionVariant<typeof this.shared>[] = this.variants;\n const preMergeRelationsMap = variants.reduce(\n (acc, v) => {\n Object.entries(v).forEach(([key, prop]) => {\n const existingRelations = acc[key] ?? [];\n const newRelations = prop.getRelations() ?? [];\n acc[key] = [...existingRelations, ...newRelations];\n });\n return acc;\n },\n {} as Record<string, Relation[][]>,\n );\n const mergedVariants = variants.reduce(\n (acc, v) => {\n // These are the constants that are shared between the variant and the shared props\n const variantConstants = Object.entries(v).filter(([key]) =>\n sharedKeys.includes(key),\n );\n // These are the relations that are unique to the variant\n // For example, shared has style and variant has style == \"rounded\"\n // Then the relations for the variant are the { key: style value: \"rounded\" }\n const relations = variantConstants.map(([key, prop]) => {\n // check if this v already has a relation for his key\n return {\n key,\n value: prop.build().default,\n };\n });\n // Now we filter out the shared keys and add dependencies to the variant\n const filteredVariant = Object.fromEntries(\n Object.entries(v)\n .filter(([key]) => !sharedKeys.includes(key))\n .map(([key, prop]) => {\n const existingRelations = prop?.getRelations() ?? [];\n const preMergeRelations = preMergeRelationsMap[key];\n const existingNonPreMergeRelations = existingRelations.filter(\n (r) => !preMergeRelations.some((p) => p === r),\n );\n // within a union, the conditions are OR'ed, but across unions, the conditions are AND'ed\n const newProp = prop.dependsOn([\n ...existingNonPreMergeRelations,\n ...mergeRelations(preMergeRelations, [relations]),\n ]);\n\n // If this property already exists in acc, merge the relations using OR logic\n if (acc[key]) {\n const existingPropRelations = acc[key].getRelations() ?? [];\n const newPropRelations = newProp.getRelations() ?? [];\n\n const seenHashes = new Set<string>();\n const uniqueRelations = [\n ...existingPropRelations,\n ...newPropRelations,\n ].filter((relationGroup) => {\n const hash = relationGroup\n .map((r) => `${r.key}:${String(r.value)}`)\n .sort()\n .join(\"|\");\n if (seenHashes.has(hash)) {\n return false;\n }\n seenHashes.add(hash);\n return true;\n });\n\n return [key, acc[key].dependsOn(uniqueRelations)];\n }\n\n return [key, newProp];\n }),\n );\n\n return { ...acc, ...filteredVariant };\n },\n {} as Record<string, Prop<any>>,\n );\n return { ...this.shared, ...mergedVariants };\n }\n}\n\nexport type {\n Relation,\n ManagedProp,\n ManagedPropsList,\n InternalProps,\n InternalPropsWithOptional,\n ExternalProps,\n EntityProps,\n MergeSections,\n ExtractProps,\n ExtractPropType,\n PropertiesDefinition,\n};\n\nexport {\n Prop,\n CompositeProp,\n RecordProp,\n UnionProp,\n ChildrenProp,\n FunctionProp,\n Section,\n PropsPanelCategory,\n createManagedPropsList,\n};\n","import {\n Prop,\n CompositeProp,\n UnionProp,\n RecordProp,\n Section,\n} from \"./props-builder.js\";\nimport type { ManagedPropsList, FunctionProp } from \"./props-builder.js\";\nimport type { DataType } from \"@superblocksteam/library-shared/props\";\nimport type { ScopedState } from \"@superblocksteam/library-shared/types\";\n\nexport const RECORD_PATH_IDENTIFIER = \"*\";\n\nfunction buildCompositeDefault(\n prop: Prop<any, false>,\n name: string,\n parentDefault?: Record<string, any>,\n) {\n const defaultThroughParent = parentDefault?.[name];\n const selfDefault = prop.build().default;\n // Honor parent default\n let propDefault = defaultThroughParent ?? selfDefault;\n if (!propDefault && typeof parentDefault === \"function\") {\n propDefault = function getNestedDefault(this: any, s: ScopedState) {\n return parentDefault.call(this, s)?.[name];\n };\n }\n return propDefault;\n}\n\nfunction buildPropLeafDefault(\n prop: Prop<any, false>,\n name: string,\n parentDefault?: Record<string, any>,\n) {\n const defaultThroughParent = parentDefault?.[name];\n const selfDefault = prop.build().default;\n // Honor self default\n let propDefault = selfDefault ?? defaultThroughParent;\n if (!propDefault && typeof parentDefault === \"function\") {\n propDefault = function getNestedDefault(this: any, s: ScopedState) {\n return parentDefault.call(this, s)?.[name];\n };\n }\n return propDefault;\n}\n\n/**\n * Core traversal function that walks through all properties in sections\n * and calls the provided callback for each leaf property.\n */\nfunction traverseProps(\n sections: Record<string, Section>,\n onProp: (\n prop: Prop<DataType>,\n fullPath: string,\n name: string,\n parentDefault?: Record<string, any>,\n sectionName?: string,\n ) => void,\n parentPath = \"\",\n) {\n const processProps = ({\n sectionName,\n props,\n parentPath,\n parentDefault,\n }: {\n sectionName?: string;\n props: Record<string, Prop<DataType>>;\n parentPath: string;\n parentDefault?: Record<string, any>;\n }) => {\n for (const [name, prop] of Object.entries(props)) {\n const fullPath = parentPath ? `${parentPath}.${name}` : name;\n if (prop instanceof CompositeProp) {\n const compositeDefault = buildCompositeDefault(\n prop,\n name,\n parentDefault,\n );\n\n processProps({\n sectionName,\n props: prop.nestedProps,\n parentPath: fullPath,\n parentDefault: compositeDefault,\n });\n } else if (prop instanceof RecordProp) {\n const recordPath = `${fullPath}.${RECORD_PATH_IDENTIFIER}`;\n processProps({\n sectionName,\n props: prop.nestedProps,\n parentPath: recordPath,\n parentDefault: prop.build().default as any,\n });\n } else if (prop instanceof Section) {\n // the section path is opaque, it should not be part of a property path\n processProps({\n sectionName,\n props: prop.props,\n parentPath,\n });\n } else if (prop instanceof UnionProp) {\n const sharedKeys = Object.keys(prop.shared);\n processProps({\n sectionName,\n props: prop.shared,\n parentPath: fullPath,\n });\n\n for (const variant of prop.variants) {\n const variantWithoutSharedKeys = Object.fromEntries(\n Object.entries(variant).filter(\n ([key]) => !sharedKeys.includes(key),\n ),\n ) as Record<string, Prop<DataType, any>>;\n processProps({\n sectionName,\n props: variantWithoutSharedKeys,\n parentPath: fullPath,\n });\n }\n } else if (prop instanceof Prop) {\n // Call the callback for each leaf property\n onProp(prop, fullPath, name, parentDefault, sectionName);\n } else {\n console.warn(\"Invalid prop type\", { name, prop });\n }\n }\n };\n\n for (const [sectionName, section] of Object.entries(sections)) {\n processProps({\n sectionName,\n props: section.props,\n parentPath,\n parentDefault: undefined,\n });\n }\n}\n\nexport function createInternalPropsList(\n sections: Record<string, Section>,\n parentPath = \"\",\n): Array<{ path: string; factory: () => any }> {\n const internalPropsList: Array<{ path: string; factory: () => any }> = [];\n\n traverseProps(\n sections,\n (prop, fullPath) => {\n const builtProp = prop.setName(fullPath).build();\n if (builtProp.dataType === \"internal\" && builtProp.default) {\n internalPropsList.push({\n path: fullPath,\n factory: builtProp.default as () => any,\n });\n }\n },\n parentPath,\n );\n\n return internalPropsList;\n}\n\nfunction createManagedPropsList(\n sections: Record<string, Section>,\n parentPath = \"\",\n): ManagedPropsList {\n const managedPropsList: ManagedPropsList = [];\n\n traverseProps(\n sections,\n (prop, fullPath, name, parentDefault, sectionName) => {\n let configuredProp = prop.setName(fullPath);\n\n const propDefault = buildPropLeafDefault(prop, name, parentDefault);\n if (propDefault !== undefined) {\n configuredProp = configuredProp.default(propDefault);\n }\n\n const builtProp = configuredProp.build();\n\n // Skip internal properties from managed props list\n // Internal properties are handled separately and not exposed/tracked\n if (builtProp.dataType === \"internal\") {\n return;\n }\n\n // TODO(code-mode): This spread is here because the fullPath is overwritten by other setName calls\n managedPropsList.push({\n ...builtProp,\n ...(sectionName === \"meta\" ? { isMetaProp: true } : {}),\n ...(builtProp.dataType === \"function\"\n ? {\n isFunctionProp: true,\n hasActionPanel: !!(prop as FunctionProp).getActionPanel(),\n }\n : {}),\n });\n },\n parentPath,\n );\n\n return managedPropsList;\n}\n\nexport { createManagedPropsList };\n","import clone from \"rfdc\";\n\nexport const fastClone = clone({});\n","import React, { Suspense } from \"react\";\n\nlet internalStores: Record<string, any> = {};\n\nconst SUPPORTED_MODES = [\"local-dev\"];\n\nfunction registerStores(stores: Record<string, any>) {\n internalStores = { ...internalStores, ...stores };\n\n if (SUPPORTED_MODES.includes(import.meta.env.MODE)) {\n if (Object.keys(internalStores).length === Object.keys(stores).length) {\n import(\"./devtools-consolidated.jsx\")\n .then(({ initializeCustomDevTools, setRegisteredStores }) => {\n setRegisteredStores(internalStores);\n initializeCustomDevTools();\n })\n .catch((error) => {\n console.warn(\n \"[DevTools] Failed to initialize custom devtools:\",\n error,\n );\n });\n }\n }\n}\n\nconst DevToolsInternal = React.lazy(() => {\n return import(\"./devtools-consolidated.jsx\").then((module) => ({\n default: module.CustomDevTools,\n }));\n});\n\nconst DevTools = () => {\n if (!SUPPORTED_MODES.includes(import.meta.env.MODE)) {\n return null;\n }\n\n return (\n <Suspense fallback={null}>\n <DevToolsInternal />\n </Suspense>\n );\n};\n\nexport { DevTools, registerStores };\n","import { Dim } from \"@superblocksteam/library-shared\";\nimport lodash from \"lodash\";\nimport moment from \"moment\";\nimport type { ScopedState } from \"@superblocksteam/library-shared/types\";\n\nexport const ARGS_VAR_NAME = \"$SB_args\";\nexport const USER_JS_CODE_VAR_NAME = \"$SB_userJSCode\";\nexport const SNAPSHOT_VAR_NAME = \"$SB_snapshot\";\n\n// $SB_userJSCode is the variable that evalJSStatements uses to pass the js code from outside the with statement\n// to the with statement body, so it must not be filtered out by the global proxy\n// similarily, we must preserve $SB_args and $SB_snapshot so they can be passed into the function call\nconst globalNamesToIgnore = new Set<string | symbol>([\n ARGS_VAR_NAME,\n USER_JS_CODE_VAR_NAME,\n SNAPSHOT_VAR_NAME,\n]);\n\nfunction globalProxyHasTrap(_target: unknown, name: string | symbol) {\n return !globalNamesToIgnore.has(name);\n}\n\nfunction rejectModify(): never {\n throw new TypeError(\"Cannot modify read-only object\");\n}\n\nfunction rejectGlobalAssignment(): never {\n throw new ReferenceError(\"Global assignments are not allowed\");\n}\n\n// TODO dress this up & allow users to add their own libraries\nconst extraLibraries: Record<string, unknown> = {\n _: lodash,\n moment: moment,\n Dim: Dim,\n};\n\nconst globalsRelyingOnWorkerGlobalScope = new Set([\n \"atob\",\n \"btoa\",\n \"createImageBitmap\",\n \"queueMicrotask\",\n \"reportError\",\n \"structuredClone\",\n]);\n\nconst simulateGlobalNamespace = true;\n\nexport function createGlobalObject({\n snapshot,\n}: {\n snapshot: Readonly<ScopedState>;\n}): Record<string, unknown> {\n return new Proxy(\n {},\n {\n set: rejectGlobalAssignment,\n defineProperty: rejectModify,\n setPrototypeOf: rejectModify,\n // use a function that returns always true as the has trap to make this proxy behave like\n // a global object when used in a with statement\n has: globalProxyHasTrap,\n get(_target, name: string | typeof Symbol.unscopables) {\n // no property is unscopable, so just return undefined for Symbol.unscopables\n if (name === Symbol.unscopables) return;\n\n const lib = extraLibraries[name];\n if (lib) return lib;\n\n if (simulateGlobalNamespace && name in globalThis) {\n // bind this method to the global scope so that methods that rely\n // on being bound to the WorkerGlobalScope, like atob and btoa, do not break.\n if (globalsRelyingOnWorkerGlobalScope.has(name)) {\n return globalThis[name as keyof typeof globalThis].bind(globalThis);\n }\n\n return globalThis[name as keyof typeof globalThis];\n }\n\n return snapshot[name];\n },\n },\n ) as Record<string, unknown>;\n}\n","import type { EntityDerivedProp } from \"@superblocksteam/library-shared/types\";\n\nexport const prettyPrintFunction = (\n func: EntityDerivedProp,\n args: any[],\n fnName: string,\n) => {\n // Clean up the function string by removing newlines and extra spaces\n let funcStr: string;\n try {\n funcStr = func.toString().replace(/\\s+/g, \" \").trim();\n } catch {\n funcStr = \"[Function]\";\n }\n\n // Convert args to strings, handling cases where toString might not be available\n let argsStr: string;\n try {\n argsStr = args\n .map((arg) => {\n try {\n return typeof arg === \"string\"\n ? `\"${arg.replace(/\\n/g, \"\\\\n\").replace(/\"/g, '\\\\\"')}\"`\n : String(arg).replace(/\\s+/g, \" \").trim();\n } catch {\n return String(arg);\n }\n })\n .join(\", \");\n } catch {\n argsStr = \"[Arguments]\";\n }\n\n return `${fnName}: ${funcStr}(${argsStr})`;\n};\n","import {\n createGlobalObject,\n ARGS_VAR_NAME,\n SNAPSHOT_VAR_NAME,\n USER_JS_CODE_VAR_NAME,\n} from \"./create-global-object.js\";\nimport { prettyPrintFunction } from \"./pretty-print-function.js\";\nimport type { Name } from \"./names.js\";\nimport type {\n EntityDerivedProp,\n EntityOutputProp,\n Entity,\n ScopedState,\n} from \"@superblocksteam/library-shared/types\";\n\nexport type ComputeParams<ARGS extends any[] = any[]> = {\n snapshot: Readonly<ScopedState>;\n entityName: Name;\n path?: string;\n func: EntityDerivedProp<ARGS>;\n args?: ARGS;\n excludeState?: boolean;\n};\nexport interface ComputeEngine {\n compute(params: ComputeParams): EntityOutputProp;\n}\n\nclass EvalComputeEngine implements ComputeEngine {\n private statementFunction = new Function(\n SNAPSHOT_VAR_NAME,\n ARGS_VAR_NAME,\n USER_JS_CODE_VAR_NAME,\n /*js*/ `with (${SNAPSHOT_VAR_NAME}) {\n return (() => {\n \"use strict\";\n return eval(\"(\" + ${USER_JS_CODE_VAR_NAME} + \")\").call(this, ${SNAPSHOT_VAR_NAME}, ...${ARGS_VAR_NAME});\n })()\n }`,\n );\n\n private statementFunctionNoSnapshot = new Function(\n ARGS_VAR_NAME,\n USER_JS_CODE_VAR_NAME,\n /*js*/ `return (() => {\n \"use strict\";\n return eval(\"(\" + ${USER_JS_CODE_VAR_NAME} + \")\").call(this, ...${ARGS_VAR_NAME});\n })()`,\n );\n\n compute({\n snapshot,\n entityName,\n func,\n args,\n path,\n excludeState,\n }: ComputeParams) {\n try {\n if (excludeState) {\n return this.statementFunctionNoSnapshot.call(\n snapshot[entityName.value],\n args || [],\n func.toString(),\n );\n }\n const globalScope = createGlobalObject({ snapshot });\n return this.statementFunction.call(\n snapshot[entityName.value],\n globalScope,\n args || [],\n func.toString(),\n );\n } catch (error) {\n // Re-throw promises for React Suspense\n if (error instanceof Promise) {\n throw error;\n }\n\n console.log(`Error in eval(${entityName.value}.${path})`, {\n error,\n func: prettyPrintFunction(\n func,\n args || [],\n entityName.value + \".\" + path,\n ),\n });\n return undefined;\n }\n }\n}\n\nclass DirectComputeEngine implements ComputeEngine {\n compute({\n snapshot,\n entityName,\n func,\n args,\n path,\n excludeState,\n }: ComputeParams) {\n if (!func) return undefined;\n try {\n const entity = snapshot[entityName.value] as Entity;\n\n // During entity construction, the entity might not be (fully) available in the snapshot yet.\n if (!entity) return undefined;\n\n const funcArgs = args || [];\n if (excludeState) {\n return func.call(entity, ...funcArgs);\n }\n return func.call(entity, snapshot, ...funcArgs);\n } catch (error) {\n // Re-throw promises for React Suspense\n if (error instanceof Promise) {\n throw error;\n }\n\n console.log(`Error in direct(${entityName.value}.${path})`, {\n error,\n func: prettyPrintFunction(\n func,\n args || [],\n entityName.value + \".\" + path,\n ),\n });\n return undefined;\n }\n }\n}\n\nexport { EvalComputeEngine, DirectComputeEngine };\n","import { toJS } from \"mobx\";\nimport type {\n Entity,\n ScopedState,\n} from \"@superblocksteam/library-shared/types\";\n\n// Cache for previous entity values to provide fallbacks when suspense is disabled\nconst objectFallbackCache = new WeakMap<object, Record<string, any>>();\n\nfunction sanitizeObject<T extends object>(obj: T): T {\n // Get or create fallback cache for this entity\n if (!objectFallbackCache.has(obj)) {\n objectFallbackCache.set(obj, {});\n }\n const fallbackCache = objectFallbackCache.get(obj)!;\n\n return new Proxy(obj, {\n get(target, prop) {\n try {\n const value = target[prop as keyof T];\n // Cache successful access for future fallback\n if (typeof prop === \"string\") {\n fallbackCache[prop] = value;\n }\n return value;\n } catch (error) {\n if (error instanceof Promise) {\n // Return cached value or undefined instead of throwing promise\n return typeof prop === \"string\" ? fallbackCache[prop] : undefined;\n }\n throw error;\n }\n },\n }) as T;\n}\n\nfunction sanitizeEntity<T extends Entity>(entity: T): T {\n return sanitizeObject(entity);\n}\n\nfunction sanitizeScopedState(state: ScopedState): ScopedState {\n return new Proxy(state, {\n get(target, prop) {\n const value = target[prop as keyof ScopedState];\n if (value && typeof value === \"object\" && \"type\" in value) {\n // This looks like an entity, sanitize it\n return sanitizeObject(value);\n }\n return value;\n },\n });\n}\n\nfunction sanitizedToJS<T>(value: T): T {\n if (value === null || value === undefined || typeof value !== \"object\") {\n return toJS(value);\n }\n return toJS(sanitizeObject(value));\n}\n\nexport { sanitizeObject, sanitizeEntity, sanitizeScopedState, sanitizedToJS };\n","import { sanitizeEntity, sanitizeScopedState } from \"./sanitize-object.js\";\nimport type { InternalScope } from \"./base-entity-manager.js\";\nimport type { ScopedState } from \"@superblocksteam/library-shared/types\";\n\nexport function createScopeProxy(\n scopes: InternalScope[],\n useSuspense: boolean = false,\n) {\n const proxy = new Proxy(\n {},\n {\n get: function (_target, prop, _receiver) {\n for (const scope of scopes) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n\n if (prop in scope.entities) {\n return !useSuspense\n ? sanitizeEntity(scope.entities[prop])\n : scope.entities[prop];\n }\n\n if (scope !== scopes[0] && scope.name === prop) {\n return !useSuspense\n ? sanitizeScopedState(scope.entities)\n : scope.entities;\n }\n }\n },\n ownKeys: function (_target) {\n const keys = new Set<string | symbol>();\n for (const scope of scopes) {\n for (const key of Reflect.ownKeys(scope.entities)) {\n keys.add(key);\n }\n if (scope.name) {\n keys.add(scope.name);\n }\n }\n return Array.from(keys);\n },\n has: function (_target, prop) {\n for (const scope of scopes) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (\n (scope !== scopes[0] && scope.name === prop) ||\n prop in scope.entities\n ) {\n return true;\n }\n }\n return false;\n },\n set: function (_target, _prop, _value, _receiver) {\n throw new Error(\"Cannot set state directly\");\n },\n },\n );\n\n return proxy as ScopedState;\n}\n","import { nameGenerator } from \"@superblocksteam/library-shared\";\nimport EventRegistry from \"../triggers/registry.js\";\nimport type {\n StepDef,\n ValueInputProp,\n NotificationPosition,\n NotificationType,\n ValidStepDef,\n IEventFlow,\n SbApi,\n WithBindingIdentifier,\n SbApiWithFunctions,\n ScopedState,\n} from \"@superblocksteam/library-shared/types\";\nclass EventFlow implements IEventFlow<StepDef, ScopedState, ValueInputProp> {\n steps: StepDef[] = [];\n\n private constructor() {}\n\n private addStep(step: Omit<ValidStepDef, \"id\">) {\n this.steps.push({\n ...step,\n id: nameGenerator(),\n });\n return this;\n }\n\n static start() {\n return new EventFlow();\n }\n\n // TODO(code-mode): any is for userland code, we need to figure out how to type this\n static runJS(\n handler: (\n s: ScopedState | any,\n additionalProps?: Record<string, any>,\n ) => void,\n ) {\n return EventFlow.start().runJS(handler);\n }\n\n // TODO(code-mode): any is for userland code, we need to figure out how to type this\n runJS(\n handler: (\n s: ScopedState | any,\n additionalProps?: Record<string, any>,\n ) => void,\n ) {\n return this.addStep(EventRegistry.runJs.create(handler));\n }\n\n static navigateTo(\n url: ValueInputProp<string>,\n opts?: {\n newWindow?: boolean;\n replaceHistory?: boolean;\n arguments?: string;\n },\n ) {\n return EventFlow.start().navigateTo(url, opts);\n }\n\n navigateTo(\n url: ValueInputProp<string>,\n opts?: {\n newWindow?: boolean;\n replaceHistory?: boolean;\n arguments?: string;\n },\n ) {\n return this.addStep(EventRegistry.navigateTo.create(url, opts));\n }\n\n static navigateToApp(appId: string) {\n return EventFlow.start().navigateToApp(appId);\n }\n\n navigateToApp(appId: string) {\n return this.addStep(EventRegistry.navigateToApp.create(appId));\n }\n\n static navigateToRoute(route: string) {\n return EventFlow.start().navigateToRoute(route);\n }\n\n navigateToRoute(route: string) {\n return this.addStep(EventRegistry.navigateToRoute.create(route));\n }\n\n static setQueryParams(\n params: Record<string, ValueInputProp<string>>,\n opts?: {\n keep?: boolean;\n },\n ) {\n return EventFlow.start().setQueryParams(params, opts);\n }\n\n setQueryParams(\n params: Record<string, ValueInputProp<string>>,\n opts?: {\n keep?: boolean;\n },\n ) {\n return this.addStep(EventRegistry.setQueryParams.create(params, opts));\n }\n\n static controlSlideout(\n slideout: WithBindingIdentifier,\n opts: { action: \"open\" | \"close\" },\n ) {\n return EventFlow.start().controlSlideout(slideout, opts);\n }\n\n controlSlideout(\n slideout: WithBindingIdentifier,\n opts: { action: \"open\" | \"close\" },\n ) {\n return this.addStep(EventRegistry.controlSlideout.create(slideout, opts));\n }\n\n static controlModal(\n modal: WithBindingIdentifier,\n opts: { action: \"open\" | \"close\" },\n ) {\n return EventFlow.start().controlModal(modal, opts);\n }\n\n controlModal(\n modal: WithBindingIdentifier,\n opts: { action: \"open\" | \"close\" },\n ) {\n return this.addStep(EventRegistry.controlModal.create(modal, opts));\n }\n\n static controlTimer(\n stateTimer: WithBindingIdentifier,\n opts: {\n action: \"start\" | \"stop\" | \"toggle\";\n },\n ) {\n return EventFlow.start().controlTimer(stateTimer, opts);\n }\n\n controlTimer(\n stateTimer: WithBindingIdentifier,\n opts: {\n action: \"start\" | \"stop\" | \"toggle\";\n },\n ) {\n return this.addStep(EventRegistry.controlTimer.create(stateTimer, opts));\n }\n\n static runApis(\n apis: any[],\n opts?: {\n onSuccess?: EventFlow;\n onError?: EventFlow;\n },\n ) {\n return EventFlow.start().runApis(apis as SbApi[], opts);\n }\n\n runApis(\n apis: any[],\n opts?: {\n onSuccess?: EventFlow;\n onError?: EventFlow;\n },\n ) {\n return this.addStep(\n EventRegistry.executeApi.create(apis as SbApiWithFunctions[], opts),\n );\n }\n\n static cancelApis(apis: any[], onCancel?: EventFlow) {\n return EventFlow.start().cancelApis(apis as SbApi[], onCancel);\n }\n\n cancelApis(apis: any[], onCancel?: EventFlow) {\n return this.addStep(\n EventRegistry.cancelApi.create(apis as SbApiWithFunctions[], onCancel),\n );\n }\n\n static resetComponent(\n component: WithBindingIdentifier,\n opts?: {\n property: string;\n // resetChildren: boolean,\n },\n ) {\n return EventFlow.start().resetComponent(component, opts);\n }\n\n resetComponent(\n component: WithBindingIdentifier,\n opts?: {\n property: string;\n // resetChildren: boolean,\n },\n ) {\n return this.addStep(EventRegistry.resetComponent.create(component, opts));\n }\n\n static resetStateVar(state: WithBindingIdentifier) {\n return EventFlow.start().resetStateVar(state);\n }\n\n resetStateVar(state: WithBindingIdentifier) {\n return this.addStep(EventRegistry.resetStateVar.create(state));\n }\n\n static setStateVar(\n stateVarName: WithBindingIdentifier,\n opts: {\n value: ValueInputProp;\n },\n ) {\n return EventFlow.start().setStateVar(stateVarName, opts);\n }\n\n setStateVar(\n stateVar: WithBindingIdentifier,\n opts: {\n value: ValueInputProp;\n },\n ) {\n return this.addStep(EventRegistry.setStateVar.create(stateVar, opts));\n }\n\n callFunction(component: () => unknown) {\n // TODO: missing arguments\n return this.addStep(EventRegistry.callFunction.create(component));\n }\n\n static callFunction(component: () => unknown) {\n return EventFlow.start().callFunction(component);\n }\n\n static setComponentProperty(\n component: WithBindingIdentifier,\n opts: {\n property: string;\n value: ValueInputProp;\n },\n ) {\n return EventFlow.start().setComponentProperty(component, opts);\n }\n\n setComponentProperty(\n component: WithBindingIdentifier,\n opts: {\n property: string;\n value: ValueInputProp;\n },\n ) {\n return this.addStep(\n EventRegistry.setComponentProperty.create(component, opts),\n );\n }\n\n static showAlert(\n message: ValueInputProp<string>,\n opts?: {\n type?: NotificationType;\n durationMs?: number;\n position?: NotificationPosition;\n },\n ) {\n return EventFlow.start().showAlert(message, opts);\n }\n\n showAlert(\n _message: ValueInputProp<string>,\n _opts?: {\n type?: NotificationType;\n durationMs?: number;\n position?: NotificationPosition;\n },\n ) {\n // no-op\n return this;\n }\n\n static setProfile(\n profileId: string,\n opts: {\n action: \"set\" | \"unset\";\n },\n ) {\n return EventFlow.start().setProfile(profileId, opts);\n }\n\n setProfile(\n profileId: string,\n opts: {\n action: \"set\" | \"unset\";\n },\n ) {\n return this.addStep(EventRegistry.setProfile.create(profileId, opts));\n }\n\n static triggerEvent(\n eventName: string,\n opts?: {\n data: Record<string, string>;\n },\n ) {\n return EventFlow.start().triggerEvent(eventName, opts);\n }\n\n triggerEvent(\n eventName: string,\n opts?: {\n data: Record<string, string>;\n },\n ) {\n return this.addStep(EventRegistry.triggerEvent.create(eventName, opts));\n }\n\n static sequence(eventFlows: EventFlow[]) {\n return EventFlow.start().sequence(eventFlows);\n }\n\n sequence(eventFlows: EventFlow[]) {\n this.steps = [\n ...this.steps,\n ...eventFlows.flatMap((eventFlow) => eventFlow.build()),\n ];\n return this;\n }\n\n build() {\n return this.steps;\n }\n}\n\nexport { EventFlow };\n","import { getDynamicBindings } from \"@superblocksteam/shared\";\nimport type { BindingString } from \"@superblocksteam/library-shared\";\nimport type { EntityDerivedProp } from \"@superblocksteam/library-shared/types\";\n\nconst transformBindings = (value: BindingString) => {\n const body = stringToJS(value.value);\n return new Function(`return ${body}`);\n};\n\nexport const toEvalFunc = ([prop, binding]: [string, BindingString]) => {\n const func = transformBindings(binding);\n return [prop, func] as [string, EntityDerivedProp];\n};\n\nexport const stringToJS = (string: string): string => {\n // If string is empty, the code below will return an empty string, which is not a valid JS expression.\n // So handle this case separately and return an empty string literal.\n if (string === undefined || string === \"\") return \"''\";\n\n const { stringSegments, jsSnippets } = getDynamicBindings(string);\n const shouldWrapInParentheses = jsSnippets.length > 1;\n const js = stringSegments\n .map((segment, index) => {\n if (jsSnippets[index] && jsSnippets[index].length > 0) {\n return shouldWrapInParentheses\n ? `(${jsSnippets[index]})`\n : jsSnippets[index];\n } else {\n const escaped = segment\n .replaceAll(\"\\\\\", \"\\\\\\\\\")\n .replaceAll(`\\n`, `\\\\n`);\n\n if (segment.includes(\"'\")) {\n return `\"${escaped.replaceAll(`\"`, '\\\\\\\\\"')}\"`;\n } else {\n return `'${escaped}'`;\n }\n }\n })\n .join(\" + \");\n return js;\n};\n\nexport default transformBindings;\n\n// TODO(code-mode): This code is used today to transform values,\n// we might need to match the behavior in the new code mode\n\n// export const createDynamicValueString = (\n// subBindings: string[],\n// subValues: string[],\n// ): string => {\n// // Replace the string with the data tree values\n// subBindings.forEach((_b, i) => {\n// let value = subValues[i];\n// if (Array.isArray(value) || isObject(value)) {\n// value = JSON.stringify(value);\n// }\n// try {\n// if (JSON.parse(value)) {\n// // The following regex is used to escape double quotes and backslashes\n// // Making it safe to use in a javascript context\n// value = value.replace(/\\\\([\\s\\S])|(\")/g, \"\\\\$1$2\");\n// }\n// } catch (_e: any) {\n// // do nothing\n// }\n// subValues[i] = value;\n// });\n// return subValues.map((v) => `${v}`).join(\"\");\n// };\n\n// const isObject = (value: unknown): value is Record<string, unknown> =>\n// typeof value === \"object\" && value !== null;\n","import {\n getComputedArgsString,\n type ComputedArgs,\n} from \"@superblocksteam/library-shared\";\n\nconst lazyFunctionSymbol = Symbol(\"lazy-function\");\n\nexport type LazyFunction = ((...args: unknown[]) => unknown) & {\n [lazyFunctionSymbol]: true;\n};\n\nexport const isLazyFunction = (value: unknown): value is LazyFunction => {\n return (\n typeof value === \"function\" && (value as LazyFunction)[lazyFunctionSymbol]\n );\n};\n\nexport const LazyFunction = (\n source: string,\n args: ComputedArgs = [],\n): LazyFunction => {\n const argsObj = getComputedArgsString(args);\n const func = new Function(argsObj, source);\n (func as LazyFunction)[lazyFunctionSymbol] = true;\n return func as LazyFunction;\n};\n","import {\n isBindingString,\n isComputedProperty,\n isDimension,\n} from \"@superblocksteam/library-shared\";\nimport { EventFlow } from \"../../../user-facing/event-flow.js\";\nimport { RECORD_PATH_IDENTIFIER } from \"../../../user-facing/properties-panel/create-managed-props-list.js\";\nimport { toEvalFunc } from \"./binding-strings/transform-bindings.js\";\nimport { isLazyFunction } from \"./lazy-function.js\";\nimport type {\n SingleInputProp,\n NestedInputProp,\n InputProp,\n EntityFunction,\n} from \"./base-entity-manager.js\";\nimport type { LazyFunction } from \"./lazy-function.js\";\nimport type {\n BindingString,\n ComputedProperty,\n} from \"@superblocksteam/library-shared\";\nimport type { DataTypeString } from \"@superblocksteam/library-shared/props\";\nimport type {\n EntityDerivedProp,\n EntityOutputProp,\n} from \"@superblocksteam/library-shared/types\";\n\ntype ExecutableType =\n | \"normal\"\n | \"function\"\n | \"mustache-bindings\"\n | \"external-function\"\n | \"event\"\n | \"lazy-function\";\n\nexport type ExecutableOrValue = {\n type: ExecutableType;\n} & (\n | {\n type: \"normal\";\n value: EntityOutputProp;\n }\n | {\n type: \"function\";\n value: EntityDerivedProp;\n }\n | {\n type: \"mustache-bindings\";\n value: EntityDerivedProp | EntityOutputProp;\n }\n | {\n type: \"external-function\";\n value: EntityFunction;\n }\n | {\n type: \"lazy-function\";\n value: LazyFunction;\n }\n | {\n type: \"event\";\n value: EventFlow;\n }\n);\n\ntype PathSchema = {\n path: string; // dot separated path to the property could include wildcards(*)\n};\n\ntype EntitySchema = PathSchema & {\n dataType: DataTypeString;\n};\n\nconst isFunctionProp = <T>(\n value: InputProp<T>,\n): value is InputProp<T> & EntityDerivedProp => {\n return typeof value === \"function\" && !isLazyFunction(value);\n};\n\nconst isDerivedProp = <T>(\n value: InputProp<T>,\n): value is InputProp<T> & BindingString => {\n return isBindingString(value);\n};\n\nconst isEventFlow = <T>(\n value: InputProp<T>,\n): value is InputProp<T> & EventFlow => {\n return value instanceof EventFlow;\n};\n\nconst isComputedProp = <T>(\n value: InputProp<T>,\n): value is InputProp<T> & ComputedProperty<T> => {\n return isComputedProperty(value);\n};\n\nconst isNestedInputProp = <T>(\n value: InputProp<T>,\n): value is NestedInputProp<T> => {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n !isFunctionProp(value) &&\n !isDerivedProp(value) &&\n !isEventFlow(value) &&\n !isDimension(value) &&\n !isComputedProp(value) &&\n !isLazyFunction(value)\n // NOTE: we limit events and dimensions but we should just limit classes as a whole\n );\n};\n\nexport const toExecutablesOrValues = <T>(\n props: InputProp<T>,\n propsSchema?: EntitySchema[],\n): [string, ExecutableOrValue][] => {\n const parentSchema =\n (propsSchema?.length ?? 0) > 0 ? getParentsSchema(propsSchema) : undefined;\n\n const toExecutablesOrValuesInternal = <T>(\n props: InputProp<T>,\n basePath: string = \"\",\n inRecordProp: boolean = false,\n ): [string, ExecutableOrValue][] => {\n if (!isNestedInputProp(props)) {\n return [[basePath, toExecutableOrValue(basePath, props)]];\n }\n\n const items: [string, ExecutableOrValue][] = [];\n Object.entries(props).forEach(([prop, value]) => {\n const path = basePath === \"\" ? prop : `${basePath}.${prop}`;\n\n const itemSchema = propsSchema?.find((schema) => {\n if (schema.path === path) {\n return true;\n }\n\n // if we are in a record prop, we need to look for our item schema using the record identifier\n // since `columns.columnName.label` is looked up by `columns.*.label`\n if (inRecordProp) {\n const recordKey = getRecordKey(path);\n if (recordKey) {\n return schema.path === recordKey;\n }\n }\n return false;\n });\n const isFunction =\n itemSchema?.dataType === \"function\" || itemSchema?.dataType === \"event\";\n\n const isNested = isNestedInputProp(value as InputProp<unknown>);\n\n if (\n isNested &&\n shouldTraverseNestedProp(path, propsSchema, parentSchema)\n ) {\n items.push(\n ...toExecutablesOrValuesInternal(\n value as InputProp<unknown>,\n path,\n true,\n ),\n );\n } else {\n items.push([\n path,\n toExecutableOrValue(\n path,\n value as SingleInputProp<unknown>,\n isFunction,\n ),\n ]);\n }\n });\n return items;\n };\n\n return toExecutablesOrValuesInternal(props);\n};\n\nexport const toExecutableOrValue = <T>(\n path: string,\n value: SingleInputProp<T>,\n isAnExternalFunction: boolean = false,\n): ExecutableOrValue => {\n if (isAnExternalFunction) {\n if (isEventFlow(value)) {\n return {\n value: value as EventFlow,\n type: \"event\",\n };\n } else {\n return {\n value: value as EntityFunction,\n type: \"external-function\",\n };\n }\n } else if (isFunctionProp(value)) {\n return { value: value, type: \"function\" };\n } else if (isDerivedProp(value)) {\n return {\n value: toEvalFunc([path, value])[1],\n type: \"mustache-bindings\",\n };\n } else if (isComputedProp(value)) {\n return {\n value: value.value,\n type: \"normal\",\n };\n } else if (isLazyFunction(value)) {\n return {\n value: value as LazyFunction,\n type: \"lazy-function\",\n };\n }\n return {\n value: value as EntityOutputProp,\n type: \"normal\",\n };\n};\n\nconst shouldTraverseNestedProp = (\n path: string,\n propsSchema?: EntitySchema[],\n managedPropsList?: PathSchema[],\n): boolean => {\n if (managedPropsList === undefined) {\n return true;\n }\n const pathSegments = path.split(\".\");\n\n // Trim the managedPropsList to the length of the pathSegments\n const trimmedPropsList = managedPropsList.map((prop) => {\n const managedPathSegments = prop.path.split(\".\");\n return managedPathSegments.slice(0, pathSegments.length);\n });\n\n const shouldTraverse = trimmedPropsList.some((prop) => {\n if (prop.length !== pathSegments.length) return false;\n return prop.every((segment, index) => {\n if (segment === RECORD_PATH_IDENTIFIER) return true;\n return segment === pathSegments[index];\n });\n });\n\n // we need to traverse every record object, so lets check if we are the parent\n // of any leaf props\n if (!shouldTraverse && propsSchema) {\n const hasRecordProp = propsSchema.some((prop) =>\n prop.path.startsWith(`${path}.${RECORD_PATH_IDENTIFIER}`),\n );\n if (hasRecordProp) {\n return true;\n }\n }\n\n return shouldTraverse;\n};\n\nconst getParentsSchema = (propsSchema: EntitySchema[] | undefined) =>\n propsSchema\n ?.map((prop) => prop.path.split(\".\").slice(0, -1).join(\".\"))\n .map((parentPath) => ({ path: parentPath }))\n .filter((prop) => prop.path !== \"\");\n\nconst getRecordKey = (path: string) => {\n const splitPath = path.split(\".\");\n const [parentKey, _maybeTheRecordKey, ...rest] = splitPath;\n if (rest.length == 0) {\n return undefined;\n }\n return [parentKey, RECORD_PATH_IDENTIFIER, rest.join(\".\")].join(\".\");\n};\n","import {\n nameGenerator,\n SOURCE_ID_ATTRIBUTE,\n} from \"@superblocksteam/library-shared\";\nimport {\n SbEntityType,\n type ValidationState,\n type SbElement,\n type SbInstance,\n} from \"@superblocksteam/library-shared/types\";\nimport { get } from \"lodash\";\nimport { action, computed, makeObservable, observable, createAtom } from \"mobx\";\nimport runEventHandlers from \"../../../triggers/run-event-handlers.js\";\nimport { RECORD_PATH_IDENTIFIER } from \"../../../user-facing/properties-panel/create-managed-props-list.js\";\nimport { isReactElement } from \"../../../utils/clean-object.js\";\nimport { fastClone } from \"../../../utils/fast-clone.js\";\nimport { registerStores } from \"../devtools/index.js\";\nimport { DirectComputeEngine, EvalComputeEngine } from \"./compute-engines.js\";\nimport { createScopeProxy } from \"./create-scope-proxy.js\";\nimport { getName, type Name } from \"./names.js\";\nimport { sanitizeEntity } from \"./sanitize-object.js\";\nimport {\n toExecutableOrValue,\n toExecutablesOrValues,\n} from \"./to-executables-or-values.js\";\nimport type {\n IEntityManager,\n SingleInputProp,\n InternalScope,\n ScopeId,\n InputProp,\n GetterOptions,\n} from \"./base-entity-manager.js\";\nimport type { ComputeEngine } from \"./compute-engines.js\";\nimport type { ExecutableOrValue } from \"./to-executables-or-values.js\";\nimport type { ManagedPropsList } from \"../../../user-facing/properties-panel/props-builder.js\";\nimport type { ValidateFn } from \"../../../user-facing/properties-panel/validators.js\";\nimport type { ComponentRegistry } from \"../features/component-registry.js\";\nimport type {\n Executable,\n EntityDerivedProp,\n Entity,\n ScopedState,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const GLOBAL_SCOPE_ID = \"Global\";\n\n// TODO(mrhether): scopeId should not be here, but we need it for now to\n// linear.app/superblocks/issue/ENG-337/allow-eventflows-to-be-called-like-functions\nconst PROTECTED_KEYS = new Set([\"type\", \"isAnonymous\", \"scopeId\", \"name\"]);\n\nconst isNestedPath = (path: string) => path.includes(\".\");\n\nconst buildEntityScope = (id: string, name?: string): InternalScope => ({\n id,\n name,\n entities: {},\n entityMeta: {},\n childScopes: new Set(),\n idToName: {},\n getEntity(name: Name, options?: GetterOptions) {\n const entity = this.entities[name.value];\n const useSuspense = options?.useSuspense ?? false;\n\n if (!useSuspense && entity) {\n return sanitizeEntity(entity);\n }\n\n return entity;\n },\n getEntityMeta(name: Name, options?: GetterOptions) {\n const entityMeta = this.entityMeta[name.value];\n const useSuspense = options?.useSuspense ?? false;\n\n if (!useSuspense && entityMeta) {\n return sanitizeEntity(entityMeta);\n }\n\n return entityMeta;\n },\n getEntityName(id: string) {\n return this.idToName[id];\n },\n setEntityName(id: string, name: Name, currentName?: Name) {\n this.idToName[id] = name;\n if (currentName) {\n const entity = this.entities[currentName.value];\n delete this.entities[currentName.value];\n this.entities[name.value] = entity;\n\n const entityMeta = this.entityMeta[currentName.value];\n delete this.entityMeta[currentName.value];\n this.entityMeta[name.value] = entityMeta;\n\n entity.name = name.value;\n entity.isAnonymous = name.isAnonymous;\n }\n },\n});\n\ntype ScopeAtoms = {\n [scopeId: ScopeId]: {\n [entityName: Name[\"value\"]]: {\n [propertyPath: string]: ReturnType<typeof createAtom>;\n };\n };\n};\n\nexport class EntityManager implements IEntityManager {\n private state: InternalScope;\n private allScopes: Record<string, InternalScope> = {};\n private atoms: ScopeAtoms = {};\n private validationCache: Record<string, ValidationState> = {};\n private dirComputeEngine: ComputeEngine;\n private evalComputeEngine: ComputeEngine;\n\n constructor(\n readonly componentRegistry: ComponentRegistry,\n options?: { devtools?: boolean },\n ) {\n this.state = observable(buildEntityScope(GLOBAL_SCOPE_ID));\n this.allScopes = observable(\n {\n [GLOBAL_SCOPE_ID]: this.state,\n },\n undefined,\n );\n this.validationCache = observable({});\n this.dirComputeEngine = new DirectComputeEngine();\n this.evalComputeEngine = new EvalComputeEngine();\n\n makeObservable(this, {\n createScope: action,\n deleteScope: action,\n setValidationState: action,\n getFullState: computed,\n getValidationState: computed,\n\n createEntity: action,\n updateEntity: action,\n deleteEntity: action,\n resetEntity: action,\n renameEntity: action,\n\n runCode: action,\n computeValue: action,\n });\n\n if (options?.devtools) {\n registerStores({ Entities: this.state });\n }\n }\n\n getEntity(scopeId: string, name: Name, options?: GetterOptions): Entity {\n // TODO validate you are actually getting back an Entity type otherwise throw\n return this.getState(scopeId, options)[name.value] as Entity;\n }\n\n getEntityById(\n scopeId: string,\n id: SbInstance,\n options?: GetterOptions,\n ): Entity | undefined {\n const scope = this.getScope(scopeId);\n const name = scope.getEntityName(id);\n return name ? scope.getEntity(name, options) : undefined;\n }\n\n getState(scopeId: string, options?: GetterOptions): ScopedState {\n const scope = this.getScope(scopeId);\n const useSuspense = options?.useSuspense ?? false;\n const includeParentScopes = options?.includeParentScopes ?? false;\n if (includeParentScopes) {\n const allScopes = this.getAccessibleScopes(scopeId);\n return createScopeProxy(allScopes, useSuspense);\n }\n const proxy = createScopeProxy([scope], useSuspense);\n\n return proxy;\n }\n\n getScopeName(scopeId: string): string {\n const scope = this.getScope(scopeId);\n return scope.name ?? \"\";\n }\n\n setValidationState(\n entityId: string,\n property: string,\n state: ValidationState,\n ) {\n this.validationCache[`${entityId}-${property}`] = state;\n }\n\n get getValidationState(): Record<string, ValidationState> {\n return this.validationCache;\n }\n\n get getFullState(): Record<string, Entity> {\n // Returns a id to entity map\n const entities: Record<string, Entity> = {};\n const processScope = (scope: InternalScope) => {\n for (const name of Object.keys(scope.entities)) {\n const entity = this.getEntity(scope.id, getName(name));\n const id = entity[SOURCE_ID_ATTRIBUTE] as string;\n const isNameBasedEntity =\n entity.type === SbEntityType.VARIABLE ||\n entity.type === SbEntityType.API ||\n entity.type === SbEntityType.TIMER ||\n entity.type === \"global\" ||\n entity.type === \"theme\";\n if (!id && !isNameBasedEntity)\n console.warn(`Entity has no source id. Type: ${entity?.type}`);\n if (isNameBasedEntity) {\n entities[name] = entity;\n } else {\n entities[id] = entity;\n }\n }\n for (const childScopeId of scope.childScopes) {\n const childScope = this.getScope(childScopeId);\n processScope(childScope);\n }\n };\n processScope(this.state);\n return entities;\n }\n\n private getAccessibleScopes(scopeId: string): InternalScope[] {\n const path: InternalScope[] = [];\n let currentScope: InternalScope | undefined = this.state;\n\n const isDescendant = (scope: InternalScope, scopeId: string): boolean => {\n if (scope.id === scopeId) {\n return true;\n }\n return Array.from(scope.childScopes).some((childScopeId) => {\n const childScope = this.getScope(childScopeId);\n return isDescendant(childScope, scopeId);\n });\n };\n\n while (currentScope) {\n path.unshift(currentScope);\n if (currentScope.id === scopeId) {\n break;\n }\n currentScope = Array.from(currentScope.childScopes)\n .map((childScopeId) => this.getScope(childScopeId))\n .find(\n (childScope) =>\n childScope.id === scopeId || isDescendant(childScope, scopeId),\n );\n }\n\n if (!currentScope) {\n throw new Error(`Scope with id ${scopeId} not found`);\n }\n\n return path;\n }\n\n public getScope(scopeId: string): InternalScope {\n const scope = this.allScopes[scopeId];\n if (!scope) {\n throw new Error(`Scope with id ${scopeId} not found`);\n }\n return scope;\n }\n\n public getPossibleScope(scopeId: string): InternalScope | undefined {\n try {\n return this.getScope(scopeId);\n } catch (_e) {\n return undefined;\n }\n }\n\n createScope(params: {\n name?: string;\n parentScopeId?: string;\n scopeId?: string;\n }): string {\n const { name, parentScopeId } = params;\n const scopeId = params.scopeId ?? nameGenerator();\n\n // Check if the state already has a scope with the same id\n if (this.getPossibleScope(scopeId)) {\n return scopeId;\n }\n\n const parentScope = parentScopeId\n ? this.getScope(parentScopeId)\n : this.state;\n\n const newScope = buildEntityScope(scopeId, name);\n parentScope.childScopes.add(scopeId);\n this.allScopes[scopeId] = newScope;\n return scopeId;\n }\n\n deleteScope(params: { scopeId: ScopeId }): void {\n const { scopeId } = params;\n const scopes = this.getAccessibleScopes(scopeId);\n if (scopes.length > 1) {\n delete this.allScopes[scopeId];\n const parentScope = scopes[1];\n parentScope.childScopes.delete(scopeId);\n delete this.atoms[scopeId];\n } else {\n throw new Error(`Cannot delete root scope`);\n }\n }\n\n createEntity(params: {\n scopeId: ScopeId;\n name: Name;\n props: Record<string, InputProp>;\n type: string;\n instanceId?: SbInstance;\n sourceId?: SbElement; // TODO (alex): Should we track this too or get rid of this\n }): Name {\n const { scopeId, name, props, type, instanceId } = params;\n this.createEntityStructure(scopeId, name, props, type, instanceId);\n return name;\n }\n\n private createEntityStructure(\n scopeId: string,\n name: Name,\n props: Record<string, InputProp>,\n type: string,\n instanceId?: SbInstance,\n ) {\n // Create the entity\n const scope = this.getScope(scopeId);\n scope.entities[name.value] = {\n type,\n isAnonymous: name.isAnonymous,\n scopeId,\n name: name.value,\n };\n scope.entityMeta[name.value] = { type };\n\n // Try to add the id to the name map, so we can lookup by ID when we need to\n // We need to special case APIs, because they are not bound by instance ID\n if (instanceId) {\n scope.idToName[instanceId] = name;\n } else if (!instanceId && type === SbEntityType.API) {\n scope.idToName[name.value] = name;\n }\n const managedPropsForType = this.componentRegistry.getManagedProps(type);\n if (managedPropsForType.length === 0) {\n console.log(\n `ALERT: No managed properties found for type ${type},\n this means the entire item will have leaf properties (more expensive)`,\n );\n }\n\n // Get internal properties (they're not in managedPropsForType but exist in propertiesDefinition)\n const internalProps = this.componentRegistry.getInternalProps(type);\n\n // Add internal properties first (they may be referenced by other properties)\n for (const internalProp of internalProps) {\n this.addInternalProperty(scopeId, name, internalProp);\n }\n\n // Add the properties to the entity\n const functionalProps = toExecutablesOrValues(props, managedPropsForType);\n const addedProperties = new Set<string>();\n for (const [prop, value] of functionalProps) {\n this.addProperty(scopeId, name, prop, value);\n addedProperties.add(prop);\n }\n\n // Add default values for properties that are not set\n this.addMissingProps(managedPropsForType, addedProperties, scopeId, name);\n }\n\n private addInternalProperty(\n scopeId: string,\n name: Name,\n internalProp: { path: string; factory: () => any },\n ) {\n const entity = this.getScope(scopeId).getEntity(name);\n const { path, factory } = internalProp;\n const instance = factory.call(entity);\n // Store it as a non-enumerable property so it's hidden from public interface\n Object.defineProperty(entity, path, {\n value: instance,\n writable: false,\n enumerable: false, // This hides it from Object.keys(), JSON.stringify(), etc.\n configurable: false,\n });\n }\n\n private addProperty(\n scopeId: string,\n name: Name,\n prop: string,\n eov: ExecutableOrValue,\n ) {\n if (prop.split(\".\").includes(RECORD_PATH_IDENTIFIER)) {\n return;\n }\n const entity = this.getScope(scopeId).getEntity(name);\n const entityMeta = this.getScope(scopeId).getEntityMeta(name);\n\n const pathSegments = prop.split(\".\");\n const isNested = pathSegments.length > 1;\n const finalSegment = pathSegments.pop() || \"\";\n const parentSegments = isNested ? pathSegments : [];\n // Lets make sure the entity has the properties leading up to the nested property\n // and if not, add them\n let propParent: Record<string, unknown> = entity;\n if (isNested) {\n let metaParent: Record<string, unknown> = entityMeta;\n // Process all segments except the last one\n for (const segment of parentSegments) {\n if (!(segment in propParent)) {\n propParent[segment] = {};\n metaParent[segment] = {};\n }\n propParent = propParent[segment] as Record<string, unknown>;\n metaParent = metaParent[segment] as Record<string, unknown>;\n }\n }\n\n // We use a function to get the meta parent because we don't want to hold\n // a reference to the entityMeta object, because it will not allow us to\n // clear the entityMeta when the entity is deleted.\n const getMetaParent = () =>\n isNested ? get(entityMeta, parentSegments) : entityMeta;\n\n const snapshot = this.getState.bind(this);\n const isComputed =\n typeof eov.value === \"function\" && eov.type !== \"function\";\n const computeEngine =\n eov.type === \"mustache-bindings\" || eov.type === \"lazy-function\"\n ? this.evalComputeEngine\n : this.dirComputeEngine;\n const entityType = entity.type;\n\n // Create a callable function\n // Eg. entity.reset()\n if (eov.type === \"external-function\") {\n const finalFunction = async (...args: any[]) =>\n this.dirComputeEngine.compute({\n snapshot: snapshot(scopeId, { useSuspense: true }),\n func: eov.value as EntityDerivedProp<any[]>,\n path: prop,\n args,\n excludeState: true,\n get entityName() {\n return getName(entity.name as any);\n },\n });\n entity[prop] = finalFunction;\n return;\n } else if (eov.type === \"event\") {\n const finalFunction = async (...args: any[]) => {\n await runEventHandlers({\n flow: eov.value,\n scopeId,\n additionalContext: args[0],\n get name() {\n return getName(entity.name as any);\n },\n });\n };\n if (isNested) {\n propParent[finalSegment] = finalFunction;\n } else {\n entity[prop] = finalFunction;\n }\n return;\n }\n let finalProp = prop;\n if (isNested) {\n finalProp = this.componentRegistry.getPropertyWithRecordIdentifier(\n entityType,\n prop,\n );\n }\n\n const managedProp = this.componentRegistry\n .getManagedProps(entityType)\n .find((p) => p.path === finalProp);\n\n // Create a property, with a getter and setter\n // Eg. entity.value and entity.value = 1\n const getValue = computed(() => {\n if (managedProp?.isExternallyReadable === false) {\n return;\n }\n\n let ret: unknown = null;\n try {\n const metaParent = getMetaParent();\n if (metaParent && finalSegment in metaParent) {\n ret = metaParent[finalSegment];\n } else {\n if (isComputed) {\n if (managedProp?.contextual) {\n ret = function (context: any) {\n return computeEngine.compute({\n snapshot: snapshot(scopeId, { useSuspense: true }),\n entityName: name,\n func: eov.value as EntityDerivedProp,\n path: prop,\n args: [context],\n excludeState: true,\n });\n };\n } else {\n ret = computeEngine.compute({\n snapshot: snapshot(scopeId, { useSuspense: true }),\n entityName: name,\n func: eov.value as EntityDerivedProp,\n path: prop,\n });\n }\n } else {\n ret = eov.value;\n }\n }\n\n if (managedProp?.validate && typeof ret !== \"function\") {\n const currentState = snapshot(scopeId, { useSuspense: true });\n const entity = currentState[name.value] as Entity;\n const validationResult = managedProp.validate(ret, entity);\n if (entity?.[SOURCE_ID_ATTRIBUTE]) {\n this.setValidationState(\n entity[SOURCE_ID_ATTRIBUTE] as string,\n prop,\n {\n isValid: validationResult.valid,\n message: validationResult.valid ? \"\" : validationResult.message,\n invalidValue: validationResult.valid\n ? undefined\n : validationResult.invalidValue,\n },\n );\n }\n\n if (!validationResult.valid) {\n return undefined;\n }\n ret = validationResult.result;\n }\n } catch (e) {\n // If the error is a promise, we need to throw it so that the component\n if (e instanceof Promise) {\n throw e;\n }\n console.log(\"Could not compute property value\");\n return undefined;\n }\n return ret;\n });\n\n const setValue = (value: any) => {\n if (managedProp?.isExternallySettable === false) {\n console.warn(\n `The property \"${finalSegment}\" on entity \"${name.value}\" is not settable, it will be ignored.`,\n );\n return;\n }\n const metaParent = getMetaParent();\n metaParent[finalSegment] = value;\n };\n\n const { atom, isNew } = this.getOrCreateAtom(scopeId, name, prop);\n\n Object.defineProperty(propParent, finalSegment, {\n get: () => {\n atom.reportObserved();\n return getValue.get();\n },\n set: action((value) => {\n setValue(value);\n atom.reportChanged();\n }),\n enumerable: true,\n configurable: true,\n });\n\n // If the atom is NOT new, we need to report that as a change so that\n // things that depend on this property are notified of the change.\n if (!isNew) {\n atom.reportChanged();\n }\n }\n\n deleteEntity(params: { name: Name; scopeId: string }): void {\n const scope = this.getScope(params.scopeId);\n delete scope.entities[params.name.value];\n delete scope.entityMeta[params.name.value];\n delete this.atoms?.[params.scopeId]?.[params.name.value];\n }\n\n deleteProperty(params: { scopeId: string; name: Name; prop: string }): void {\n const { scopeId, name, prop } = params;\n\n if (prop.split(\".\").includes(RECORD_PATH_IDENTIFIER)) {\n return;\n }\n\n const scope = this.getScope(scopeId);\n const entity = scope.getEntity(name);\n const entityMeta = scope.getEntityMeta(name);\n\n if (!entity || !entityMeta) {\n console.warn(`Entity ${name.value} not found in scope ${scopeId}`);\n return;\n }\n\n const pathSegments = prop.split(\".\");\n const isNested = pathSegments.length > 1;\n const finalSegment = pathSegments.pop() || \"\";\n const parentSegments = isNested ? pathSegments : [];\n\n // Get the parent objects for both entity and entityMeta\n let propParent: Record<string, unknown> = entity;\n let metaParent: Record<string, unknown> = entityMeta;\n\n if (isNested) {\n // Navigate to the parent objects\n for (const segment of parentSegments) {\n if (!(segment in propParent) || !(segment in metaParent)) {\n // Property doesn't exist, nothing to delete\n return;\n }\n propParent = propParent[segment] as Record<string, unknown>;\n metaParent = metaParent[segment] as Record<string, unknown>;\n }\n }\n\n // Delete the property descriptor and the meta\n if (finalSegment in propParent) {\n delete propParent[finalSegment];\n }\n if (finalSegment in metaParent) {\n delete metaParent[finalSegment];\n }\n\n // Clean up the atom\n if (this.atoms[scopeId]?.[name.value]?.[prop]) {\n delete this.atoms[scopeId][name.value][prop];\n }\n }\n\n /*\n This is a helper method to delete obsolete nested properties\n It handles cases like deleting custom columns on the table\n */\n private deleteObsoleteNestedProperties(\n scopeId: string,\n name: Name,\n nextProps: Record<string, InputProp>,\n entity: Record<string, unknown>,\n ): void {\n // Iterate through all keys in currentProps\n for (const [propKey, propValue] of Object.entries(nextProps)) {\n if (\n propValue &&\n typeof propValue === \"object\" &&\n !Array.isArray(propValue) &&\n !isReactElement(propValue)\n ) {\n const entityPropValue = entity[propKey] as\n | Record<string, unknown>\n | undefined;\n\n if (\n !entityPropValue ||\n typeof entityPropValue !== \"object\" ||\n Array.isArray(entityPropValue) ||\n isReactElement(entityPropValue)\n ) {\n continue;\n }\n\n const currentKeys = new Set<string>(Object.keys(propValue));\n const existingKeys = Object.keys(entityPropValue);\n const keysToDelete = existingKeys.filter(\n (key) => !currentKeys.has(key),\n );\n\n // Delete all properties for obsolete keys\n for (const keyToDelete of keysToDelete) {\n const obsoleteObj = entityPropValue[keyToDelete];\n if (\n obsoleteObj &&\n typeof obsoleteObj === \"object\" &&\n !isReactElement(obsoleteObj)\n ) {\n // Delete all nested properties under this key\n const nestedProps = this.getNestedPropertyPaths(\n `${propKey}.${keyToDelete}`,\n obsoleteObj,\n );\n for (const nestedProp of nestedProps) {\n this.deleteProperty({ scopeId, name, prop: nestedProp });\n }\n }\n // Delete the key itself\n this.deleteProperty({\n scopeId,\n name,\n prop: `${propKey}.${keyToDelete}`,\n });\n }\n }\n }\n }\n\n private getNestedPropertyPaths(basePath: string, obj: unknown): string[] {\n try {\n const paths: string[] = [];\n\n if (\n obj &&\n typeof obj === \"object\" &&\n !Array.isArray(obj) &&\n !isReactElement(obj)\n ) {\n for (const [key, value] of Object.entries(obj)) {\n const currentPath = `${basePath}.${key}`;\n paths.push(currentPath);\n\n // Recursively get nested paths\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n paths.push(...this.getNestedPropertyPaths(currentPath, value));\n }\n }\n }\n\n return paths;\n } catch (_e) {\n return [];\n }\n }\n\n deleteEntityById(params: { scopeId: string; entityId: string }): void {\n const scope = this.getScope(params.scopeId);\n const name = scope.getEntityName(params.entityId);\n if (name) {\n this.deleteEntity({ name, scopeId: params.scopeId });\n }\n }\n\n resetEntity(params: {\n scopeId: string;\n name: Name;\n key?: string;\n onlyMetaProps?: boolean;\n }): void {\n const { name, key, onlyMetaProps } = params;\n const entityMeta = this.getScope(params.scopeId).getEntityMeta(name);\n if (key) {\n if (key in entityMeta) {\n delete entityMeta[key];\n }\n } else {\n let metaPropsNames: string[] = [];\n if (onlyMetaProps) {\n const managedPropsForType = this.componentRegistry.getManagedProps(\n entityMeta.type,\n );\n metaPropsNames = managedPropsForType\n .filter((p) => p.isMetaProp)\n .map((p) => p.path);\n }\n // only reset props in meta section for reset component action\n for (const prop of Object.keys(entityMeta)) {\n if (\n !onlyMetaProps ||\n (onlyMetaProps && metaPropsNames.includes(prop))\n ) {\n delete entityMeta[prop];\n }\n }\n }\n }\n\n updateEntity(params: {\n scopeId: string;\n name: Name;\n instanceId?: SbInstance;\n props: Record<string, InputProp>;\n }) {\n const { scopeId, name, props, instanceId } = params;\n\n const scope = this.getScope(scopeId);\n const entity = scope.getEntity(name);\n if (!entity) {\n console.warn(\n `Entity with name ${name.value} not found on scope ${scopeId}. This shouldn't happen, so there is a bug somewhere that you need to track down`,\n );\n return;\n }\n const type = entity.type;\n\n if (instanceId) {\n scope.idToName[instanceId] = name;\n }\n\n this.deleteObsoleteNestedProperties(scopeId, name, props, entity);\n const managedPropsForType = this.componentRegistry.getManagedProps(type);\n const internalProps = this.componentRegistry.getInternalProps(type);\n const functionalProps = toExecutablesOrValues(props, managedPropsForType);\n\n const addedProperties = new Set<string>();\n for (const [prop, value] of functionalProps) {\n if (value.value != undefined) {\n this.addProperty(scopeId, name, prop, value);\n addedProperties.add(prop);\n }\n }\n\n const missingPropKeys = Object.keys(entity).filter((key) => {\n const propInfo = managedPropsForType.find((p) => p.path === key);\n const isInternalProp = internalProps.some((p) => p.path === key);\n return (\n !(key in props) && // not in props\n !PROTECTED_KEYS.has(key) && // not a protected key\n propInfo?.dataType !== \"function\" && // not a function (these are considered immutable)\n !isInternalProp // not an internal prop\n );\n });\n\n // delete any props that are not in the props object\n missingPropKeys.forEach((key) => delete entity[key]);\n\n // add default values for missing properties\n this.addMissingProps(managedPropsForType, addedProperties, scopeId, name);\n }\n\n private addMissingProps(\n managedProps: ManagedPropsList,\n addedProperties: Set<string>,\n scopeId: string,\n name: Name,\n ) {\n const entity = this.getScope(scopeId).getEntity(name);\n for (const prop of managedProps) {\n const isComputed =\n typeof prop.default === \"function\" && prop.dataType !== \"function\";\n\n if (\n get(entity, prop.path) == null &&\n !addedProperties.has(prop.path) &&\n // for nested properties, only set if the default is defined\n // for top-level properties, we should always add the property\n (!isNestedPath(prop.path) || prop.default !== undefined)\n ) {\n if (isComputed) {\n // Add computed properties as computed properties, not static defaults\n this.addProperty(scopeId, name, prop.path, {\n value: prop.default,\n type: \"normal\", // This will be treated as a computed function\n });\n } else {\n // Add regular properties with static defaults\n this.addProperty(\n scopeId,\n name,\n prop.path,\n toExecutableOrValue(\n prop.path,\n prop.default !== undefined ? fastClone(prop.default) : undefined,\n prop.dataType === \"function\" || prop.dataType === \"event\",\n ),\n );\n }\n }\n }\n }\n\n renameEntity(params: {\n scopeId: ScopeId;\n instanceId: SbInstance;\n newName: Name;\n isDuplicate: boolean;\n }) {\n const { scopeId, instanceId, newName, isDuplicate } = params;\n const scope = this.getScope(scopeId);\n const existingName = scope.getEntityName(instanceId);\n if (!existingName && !isDuplicate) {\n console.warn(`Entity with id ${instanceId} not found`);\n return;\n }\n scope.setEntityName(instanceId, newName, existingName);\n }\n\n runCode<ARGS extends any[] = any[]>(params: {\n scopeId: string;\n name: Name;\n func: Executable;\n excludeState?: boolean;\n args?: ARGS;\n }) {\n const { scopeId, name, func, args, excludeState } = params;\n const state = this.getState(scopeId);\n const computeEngine = this.dirComputeEngine;\n computeEngine.compute({\n snapshot: state,\n entityName: name,\n func: func as EntityDerivedProp,\n args,\n excludeState,\n });\n }\n\n computeValue<T, ARGS extends any[] = any[]>(params: {\n scopeId: ScopeId;\n name: Name;\n value: SingleInputProp<T>;\n validator?: ValidateFn<T>;\n args?: ARGS;\n }): T {\n const { scopeId, name, value, validator, args } = params;\n const { value: transformedValue, type } = toExecutableOrValue(\n name.value,\n value,\n );\n const isComputed =\n typeof transformedValue === \"function\" && type !== \"function\";\n const computeEngine =\n type === \"mustache-bindings\" || type === \"lazy-function\"\n ? this.evalComputeEngine\n : this.dirComputeEngine;\n\n const result = isComputed\n ? computeEngine.compute({\n snapshot: this.getState(scopeId),\n entityName: name,\n func: transformedValue as EntityDerivedProp,\n args,\n excludeState: true,\n })\n : transformedValue;\n if (validator) {\n const vResult = validator(result, this.getEntity(scopeId, name));\n if (!vResult.valid) {\n throw Error(`Validation error for ${name.value}: ${vResult.message}`);\n }\n return vResult.result;\n }\n return result as T;\n }\n\n private getOrCreateAtom(scopeId: string, name: Name, prop: string) {\n const isNew = !this.atoms[scopeId]?.[name.value]?.[prop];\n const scopeAtoms = (this.atoms[scopeId] ??= {});\n const entityAtoms = (scopeAtoms[name.value] ??= {});\n const atom = (entityAtoms[prop] ??= createAtom(\n `${scopeId}-${name.value}:${prop}`,\n ));\n return { atom, isNew };\n }\n}\n","import { getQueryParams } from \"@superblocksteam/library-shared\";\nimport { action } from \"mobx\";\nimport { matchPath, type DataRouter, type Location } from \"react-router\";\nimport { editorBridge } from \"../../edit-mode/superblocks-editor-bridge.js\";\nimport { GLOBAL_SCOPE_ID } from \"./lib/evaluator/entity-manager.js\";\nimport { getName } from \"./lib/evaluator/names.js\";\nimport type { RootStore } from \"./lib/root-store.js\";\nimport type { RouteInfo } from \"./lib/types.js\";\nimport type { UrlState } from \"@superblocksteam/library-shared/types\";\nimport type { Params } from \"react-router\";\n\nexport class LocationStore {\n route?: RouteInfo;\n rootStore: RootStore;\n\n constructor(rootStore: RootStore) {\n this.rootStore = rootStore;\n }\n\n @action\n updateLocation(\n location: Location,\n routes: DataRouter[\"routes\"],\n params: Readonly<Params<string>>,\n ): void {\n this.route = this.locationToRouteInfo(location, routes, params);\n this.sendLocationToEditor();\n this.updateGlobalScopeUrl();\n }\n\n sendLocationToEditor() {\n if (!this.route) return;\n editorBridge.updateRoute(this.route);\n }\n\n async updateGlobalScopeUrl() {\n if (!this.route) return;\n\n const globalName = getName(\"Global\");\n\n // Get the current Global entity to preserve existing properties\n const currentGlobalEntity = this.rootStore.entityManager.getEntity(\n GLOBAL_SCOPE_ID,\n globalName,\n );\n\n this.rootStore.entityManager.updateEntity({\n scopeId: GLOBAL_SCOPE_ID,\n name: globalName,\n props: {\n ...currentGlobalEntity,\n URL: {\n ...(currentGlobalEntity.URL as UrlState),\n ...this.route,\n },\n },\n });\n }\n\n locationToRouteInfo(\n location: Location,\n routes: DataRouter[\"routes\"],\n params: Readonly<Params<string>>,\n ): RouteInfo | undefined {\n const route = routes.find(\n (route) => !!route.path && matchPath(route.path, location.pathname),\n );\n\n if (!route?.path) return;\n\n return {\n hash: location.hash,\n pathname: location.pathname,\n queryParams: getQueryParams(location.search),\n route: route.path,\n routeParams: params,\n };\n }\n}\n","<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8 15C11.866 15 15 11.866 15 8C15 4.13401 11.866 1 8 1C4.13401 1 1 4.13401 1 8C1 11.866 4.13401 15 8 15ZM8.75001 5C8.75001 4.58579 8.41422 4.25 8.00001 4.25C7.58579 4.25 7.25001 4.58579 7.25001 5V8C7.25001 8.41421 7.58579 8.75 8.00001 8.75C8.41422 8.75 8.75001 8.41421 8.75001 8V5ZM8 9.75001C7.44772 9.75001 7 10.1977 7 10.75C7 11.3023 7.44772 11.75 8 11.75C8.55228 11.75 9 11.3023 9 10.75C9 10.1977 8.55228 9.75001 8 9.75001Z\" fill=\"currentColor\"/>\n</svg>\n","<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M15 8C15 11.866 11.866 15 8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1C11.866 1 15 4.13401 15 8ZM5.94194 5.05806C5.69786 4.81398 5.30214 4.81398 5.05806 5.05806C4.81398 5.30214 4.81398 5.69786 5.05806 5.94194L7.11612 8L5.05806 10.0581C4.81398 10.3021 4.81398 10.6979 5.05806 10.9419C5.30214 11.186 5.69786 11.186 5.94194 10.9419L8 8.88388L10.0581 10.9419C10.3021 11.186 10.6979 11.186 10.9419 10.9419C11.186 10.6979 11.186 10.3021 10.9419 10.0581L8.88388 8L10.9419 5.94194C11.186 5.69786 11.186 5.30214 10.9419 5.05806C10.6979 4.81398 10.3021 4.81398 10.0581 5.05806L8 7.11612L5.94194 5.05806Z\" fill=\"currentColor\"/>\n</svg>\n","<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M8 1C6.61553 1 5.26216 1.41054 4.11101 2.17971C2.95987 2.94888 2.06266 4.04213 1.53285 5.32122C1.00303 6.6003 0.86441 8.00776 1.13451 9.36563C1.4046 10.7235 2.07129 11.9708 3.05026 12.9497C4.02922 13.9287 5.2765 14.5954 6.63437 14.8655C7.99224 15.1356 9.3997 14.997 10.6788 14.4672C11.9579 13.9373 13.0511 13.0401 13.8203 11.889C14.5895 10.7378 15 9.38447 15 8C14.9964 6.14458 14.2578 4.36617 12.9458 3.05418C11.6338 1.7422 9.85542 1.00356 8 1ZM7.86539 4.23077C8.02513 4.23077 8.18129 4.27814 8.31412 4.36689C8.44694 4.45564 8.55046 4.58178 8.6116 4.72937C8.67273 4.87696 8.68872 5.03936 8.65756 5.19603C8.62639 5.35271 8.54947 5.49663 8.43651 5.60959C8.32355 5.72254 8.17964 5.79947 8.02296 5.83063C7.86628 5.8618 7.70388 5.8458 7.5563 5.78467C7.40871 5.72354 7.28257 5.62001 7.19381 5.48719C7.10506 5.35437 7.05769 5.19821 7.05769 5.03846C7.05769 4.82425 7.14279 4.61881 7.29426 4.46734C7.44573 4.31586 7.65117 4.23077 7.86539 4.23077ZM8.53846 11.7692H8C7.85719 11.7692 7.72023 11.7125 7.61925 11.6115C7.51827 11.5105 7.46154 11.3736 7.46154 11.2308V8C7.31873 8 7.18177 7.94327 7.08079 7.84229C6.97981 7.74131 6.92308 7.60435 6.92308 7.46154C6.92308 7.31873 6.97981 7.18177 7.08079 7.08079C7.18177 6.97981 7.31873 6.92308 7.46154 6.92308H8C8.14281 6.92308 8.27977 6.97981 8.38075 7.08079C8.48173 7.18177 8.53846 7.31873 8.53846 7.46154V10.6923C8.68127 10.6923 8.81823 10.749 8.91921 10.85C9.0202 10.951 9.07692 11.088 9.07692 11.2308C9.07692 11.3736 9.0202 11.5105 8.91921 11.6115C8.81823 11.7125 8.68127 11.7692 8.53846 11.7692Z\" fill=\"currentColor\"/>\n</svg>\n","<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8 15C11.866 15 15 11.866 15 8C15 4.13401 11.866 1 8 1C4.13401 1 1 4.13401 1 8C1 11.866 4.13401 15 8 15ZM11.4419 6.94194C11.686 6.69786 11.686 6.30214 11.4419 6.05806C11.1979 5.81398 10.8021 5.81398 10.5581 6.05806L7.5 9.11612L5.94194 7.55806C5.69786 7.31398 5.30214 7.31398 5.05806 7.55806C4.81398 7.80214 4.81398 8.19786 5.05806 8.44194L7.05806 10.4419C7.30214 10.686 7.69786 10.686 7.94194 10.4419L11.4419 6.94194Z\" fill=\"currentColor\"/>\n</svg>\n","export const colors = {\n WHITE: \"#FFFFFF\",\n BLACK: \"#000000\",\n PLATFORM_BLACK: \"#0E141B\",\n\n // TODO: Consider replace WHITE with this.\n OFF_WHITE: \"#F2F2F2\",\n DISABLED: \"rgba(0, 0, 0, 0.25)\",\n\n GREY_25: \"#F9FAFB\",\n GREY_50: \"#F3F4F6\",\n GREY_100: \"#E8EAED\",\n GREY_200: \"#C6CAD2\",\n GREY_300: \"#A4AAB7\",\n GREY_400: \"#818A9C\",\n GREY_500: \"#6C7689\",\n GREY_600: \"#5A6272\",\n GREY_700: \"#454D5F\",\n GREY_800: \"#2F3437\",\n GREY_900: \"#121517\",\n GRAY_GRID: \"#CCD3DB\",\n\n RED_500_8: \"rgba(255, 72, 72, 0.08)\",\n RED_25: \"#FF48481F\",\n RED_500: \"#FF4848\",\n RED_600: \"#DB4949\",\n RED_700: \"#C54141\",\n\n ORANGE_25: \"#FFEEC5\",\n ORANGE_600: \"#FA8A0F\",\n\n SUBTLE_BLUE: \"#29bbff14\", // Deprecated. Not defined in figma\n SUBTLE_BLUE_SOLID: \"#eefaff\", // Deprecated. Not defined in figma\n\n ACCENT_BLUE_NEW_DARKER: \"#0087E0\",\n BLUE_MINMAX_LABELS: \"#0062A3\",\n DRAG_PREVIEW_BLUE: \"rgba(0, 135, 224, 0.16)\",\n ACCENT_BLUE_500: \"#27BBFF\",\n ACCENT_BLUE_500_04: \"#27BBFF0A\",\n ACCENT_BLUE_500_25: \"#27BBFF14\",\n ACCENT_BLUE_500_50: \"#27BBFF1F\",\n ACCENT_BLUE_500_18: \"#27BBFF2E\", // Deprecated. Not defined in figma\n ACCENT_BLUE_500_24: \"#27BBFF3D\", // Deprecated. Not defined in figma\n ACCENT_BLUE_500_48: \"#27BBFF7A\", // Deprecated. Not defined in figma\n ACCENT_BLUE_600: \"#00A8F5\",\n ACCENT_BLUE_700: \"#009AE0\",\n ACCENT_ORANGE: \"#FF9F35\",\n ACCENT_ORANGE_04: \"#FF9F350A\",\n ACCENT_ORANGE_24: \"#FF9F353D\",\n LIGHT_ORANGE: \"#FF9F351E\",\n ACCENT_ORANGE_600: \"#FA8A0F\",\n SUBTLE_PURPLE: \"#643ADF14\",\n ACCENT_PURPLE: \"#643ADF\",\n LIGHT_PURPLE: \"#643ADF1E\",\n ACCENT_PURPLE_500: \"#7C4FF8\",\n ACCENT_PURPLE_600: \"#5227CE\",\n SUBTLE_GREEN: \"#14CDB714\",\n LIGHT_GREEN: \"#9BDCAD\",\n ACCENT_GREEN: \"#14CDB7\",\n ACCENT_GREEN_600: \"#08BAA5\",\n LIGHT_PINK: `rgba(255, 98, 164, 0.12)`,\n ACCENT_PINK: \"#FF62A4\",\n\n HOVER_BLUE: \"#E3F8FF\",\n HOVER_GREEN: \"#14CDB724\",\n\n CLICK_GREEN: \"#14CDB734\",\n\n INFO: \"#27BBFF\",\n WARNING: \"#FF9F35\",\n DANGER: \"#F45252\",\n DANGER_BRIGHT: \"rgba(255, 72, 72, 1.0)\",\n DANGER_SUBTLE: \"#F452521F\",\n SUCCESS: \"#0CC26D\",\n\n NONE: \"transparent\",\n} as const;\n\nexport type SuperblocksColor = keyof typeof colors;\n","export const MODIFIER_CLASSNAMES = {\n DISABLED_MODIFIER: \"sb-disabled\",\n ERROR_MODIFIER: \"sb-error\",\n ACTIVE_MODIFIER: \"sb-active\",\n};\n\nexport const CLASS_NAMES = {\n ...MODIFIER_CLASSNAMES,\n // user-controllable typefaces\n HEADING1: \"sb-heading-1\",\n HEADING2: \"sb-heading-2\",\n HEADING3: \"sb-heading-3\",\n HEADING4: \"sb-heading-4\",\n HEADING5: \"sb-heading-5\",\n HEADING6: \"sb-heading-6\",\n BODY1: \"sb-body-1\",\n BODY2: \"sb-body-2\",\n BODY3: \"sb-body-3\",\n LINK: \"sb-link\",\n INPUT_LABEL: \"sb-input-label\",\n LABEL: \"sb-label\",\n CODE_TEXT: \"sb-code\",\n INPUT_TEXT: \"sb-input-text\",\n INPUT_PLACEHOLDER: \"sb-input-placeholder\",\n BUTTON_LABEL: \"sb-button-label\",\n\n // built-in typefaces\n SYSTEM_TEXT: \"sb-system-text\",\n BUILTIN_BODY: \"sb-builtin-body\",\n ELLIPSIS_TEXT: \"sb-ellipsis-text\",\n\n // buttons\n BUTTON: \"sb-button\",\n PRIMARY_BUTTON: \"sb-button-primary\",\n SECONDARY_BUTTON: \"sb-button-secondary\",\n SECONDARY_NEUTRAL_BUTTON: \"sb-button-secondary-neutral\",\n TERTIARY_BUTTON: \"sb-button-tertiary\",\n SYSTEM_BUTTON: \"sb-button-system\",\n // inputs\n INPUT: \"sb-input\",\n SWITCH: \"sb-switch\",\n CHECKBOX: \"sb-checkbox\",\n RADIO: \"sb-radio\",\n // containers\n SECTION: \"sb-section\",\n ROUNDED_CONTAINER: \"sb-rounded-container\",\n\n CANVAS: \"sb-canvas\", // the inner canvas of a container\n DEFAULT_CONTAINER: \"sb-default-container\", // used for container-like wrappers (i.e. table, graph, etc.)\n\n DEFAULT_CONTAINER_STYLE_CARD: \"sb-default-container-style-card\", // used for container components\n DEFAULT_CONTAINER_STYLE_NONE: \"sb-default-container-style-none\", // used for container components\n\n DEFAULT_CONTAINER_BORDER: \"sb-default-container-border\", // used to render container borders, which are customizable + overlay the component\n\n CONTAINER_BORDER_OUTLINE: \"sb-container-border-overlay\",\n POPOVER_WRAPPER: \"sb-popover-wrapper\",\n TAB: \"sb-tab\",\n MODAL: \"sb-modal\",\n SLIDEOUT: \"sb-slideout\",\n BORDER_BOTTOM: \"sb-util-border-bottom\",\n BORDER_TOP: \"sb-util-border-top\",\n NOTIFICATION: \"sb-notification\",\n STYLED_SCROLLBAR: \"sb-scrollable\",\n TOOLTIP: \"sb-tooltip\",\n // menus\n DROPDOWN: \"sb-dropdown\",\n DROPDOWN_MENU: \"sb-dropdown-menu\",\n MENU_ITEM: \"sb-menu-item\",\n TAG_INPUT: \"sb-tag-input\",\n DATEPICKER: \"sb-datepicker\",\n // icons\n DROPDOWN_CLEAR_ICON: \"sb-dropdown-clear-icon\",\n CARET_ICON: \"sb-caret-icon\",\n PRIMARY_COLOR_ICON: \"sb-primary-color-icon\",\n CLOSE_ICON: \"sb-close-icon\",\n ICON: \"sb-icon\",\n // misc\n PAGINATOR: \"sb-rc-paginator\",\n CODE_EDITOR: \"sb-code-editor\",\n ERROR_INLINE_MESSAGE: \"sb-error-inline-message\",\n};\n","import { NotificationPosition } from \"@superblocksteam/library-shared/types\";\nimport isString from \"lodash/isString\";\nimport React from \"react\";\nimport { toast } from \"sonner\";\nimport styled from \"styled-components\";\nimport WarningIcon from \"../assets/icons/system-danger.svg\";\nimport ErrorIcon from \"../assets/icons/system-error.svg\";\nimport InfoIcon from \"../assets/icons/system-info.svg\";\nimport SuccessIcon from \"../assets/icons/system-success.svg\";\nimport { colors } from \"../styling/colors.js\";\nimport { CLASS_NAMES } from \"../themes/classnames.js\";\nimport type { NotificationType } from \"@superblocksteam/library-shared/types\";\nimport type { ToastT } from \"sonner\";\n\ntype NotificationConfig = {\n key?: string;\n message: JSX.Element | string;\n description?: JSX.Element | string;\n // Duration in seconds\n duration?: number;\n placement?: NotificationPosition;\n style?: React.CSSProperties;\n dataTest?: string;\n type: NotificationType;\n};\n\n// Used to keep track of active notifications and collapse them when displayed\nconst activeNotifications = new Map<string, { count: number; message: any }>();\n\nconst StatusIconWrapper = styled.div<{\n color: string;\n}>`\n color: ${(props) => props.color};\n font-size: 16px;\n margin-top: -2px;\n margin-left: -10px;\n svg {\n width: 18px;\n height: 18px;\n }\n`;\n\nconst MessageWrapper = styled.div`\n font-size: 12px;\n font-weight: 500;\n line-height: 1.3;\n margin-left: -26px;\n margin-right: 0;\n white-space: pre-wrap;\n`;\n\nconst DescriptionWrapper = styled.div`\n font-size: 12px;\n margin-left: -26px;\n margin-right: -10px;\n`;\nconst styleMessage = (\n message: string | JSX.Element,\n dataTest?: string,\n): JSX.Element => {\n return (\n <MessageWrapper data-test={dataTest ? dataTest : \"notification\"}>\n {message}\n </MessageWrapper>\n );\n};\n\nconst styleDescription = (\n description: undefined | string | JSX.Element,\n): undefined | JSX.Element => {\n if (!description) {\n return undefined;\n }\n return <DescriptionWrapper>{description}</DescriptionWrapper>;\n};\n\nconst messageWithCount = (\n key: string | undefined,\n message: string | JSX.Element,\n dataTest?: string,\n) => {\n let updatedMessage = message;\n if (key) {\n const count = (activeNotifications.get(key)?.count ?? 0) + 1;\n activeNotifications.set(key, { count: count, message });\n if (count > 1 && isString(message)) {\n // If message is a string, add count to message\n updatedMessage = `${message} (${count} times)`;\n }\n }\n return styleMessage(updatedMessage, dataTest);\n};\n\n/**\n * When a Key is used,\n * duplicate notifications are not shown but the timeout is added to the first notification.\n * @returns A string key based on inputs\n */\nconst getKey = (\n type: string,\n message: string | JSX.Element,\n description: string | JSX.Element | undefined,\n duration: number | undefined,\n) => {\n return isString(message)\n ? `${type}--${String(message)}--${description}--${duration}`\n : undefined;\n};\n\nconst removeNotificationsWithKey = (key: string) => {\n document\n .querySelectorAll(`[data-testid=\"notification_${key}\"]`)\n .forEach((el) => {\n el.remove();\n });\n};\n\nconst attrSafeKey = (str: string) => {\n return str.replace(/\\W+/g, \"_\");\n};\n\nconst getIcon = (type: NotificationType) => {\n let icon: React.ReactNode;\n let color: string;\n switch (type) {\n case \"success\":\n icon = <SuccessIcon />;\n color = colors.SUCCESS;\n break;\n case \"error\":\n icon = <ErrorIcon />;\n color = colors.DANGER;\n break;\n case \"info\":\n icon = <InfoIcon />;\n color = colors.INFO;\n break;\n case \"warning\":\n icon = <WarningIcon />;\n color = colors.WARNING;\n break;\n }\n return <StatusIconWrapper color={color}>{icon}</StatusIconWrapper>;\n};\n\nfunction onAlertClose(key: string | undefined) {\n if (key) {\n activeNotifications.delete(key);\n }\n}\n\nexport function cleanNotification() {\n toast.dismiss();\n activeNotifications.clear();\n}\n\nexport function closeNotification(key: string) {\n if (!key) {\n return;\n }\n toast.dismiss(key);\n removeNotificationsWithKey(attrSafeKey(key));\n activeNotifications.delete(key);\n}\n\ntype Position = NonNullable<ToastT[\"position\"]>;\n\nconst positionToPlacement: Record<NotificationPosition, Position> = {\n [NotificationPosition.bottom]: \"bottom-center\",\n [NotificationPosition.top]: \"top-center\",\n [NotificationPosition.topLeft]: \"top-left\",\n [NotificationPosition.topRight]: \"top-right\",\n [NotificationPosition.bottomLeft]: \"bottom-left\",\n [NotificationPosition.bottomRight]: \"bottom-right\",\n} as const;\n\nexport function sendNotification({\n message,\n description,\n duration,\n key = getKey(\"success\", message, description, duration),\n placement = NotificationPosition.bottomRight,\n style,\n dataTest,\n type,\n}: NotificationConfig) {\n const icon = getIcon(type);\n\n const handleClose = () => {\n onAlertClose(key);\n if (key) {\n removeNotificationsWithKey(attrSafeKey(`notification-${key}`));\n }\n };\n\n if (key) {\n toast.dismiss(key);\n removeNotificationsWithKey(attrSafeKey(`notification-${key}`));\n }\n\n const position = positionToPlacement[placement];\n\n toast.success(messageWithCount(key, message, dataTest), {\n id: key,\n description: styleDescription(description),\n icon,\n duration: duration ? duration * 1000 : undefined,\n position: position,\n className: CLASS_NAMES.NOTIFICATION,\n style: style,\n onDismiss: handleClose,\n onAutoClose: handleClose,\n });\n}\n","import { isReadableFile } from \"@superblocksteam/shared\";\nimport { get } from \"lodash\";\nimport { isObservableArray } from \"mobx\";\nimport type { FileMetadataPrivate } from \"@superblocksteam/shared\";\n\nexport { isReadableFile };\nexport type { FileMetadataPrivate };\n\n// Simple file storage for components that need to store files temporarily\nclass FileManagerClass {\n private static instance: FileManagerClass;\n private storage: Record<string, Record<string, File>> = {};\n\n private constructor() {\n // Private constructor to prevent direct instantiation\n }\n\n static getInstance(): FileManagerClass {\n if (!FileManagerClass.instance) {\n FileManagerClass.instance = new FileManagerClass();\n }\n return FileManagerClass.instance;\n }\n\n store(componentName: string, file: File): void {\n const fileId = getFileUploadId(file);\n if (!this.storage[componentName]) {\n this.storage[componentName] = {};\n }\n this.storage[componentName][fileId] = file;\n }\n\n get(componentName: string, fileId: string): File | undefined {\n return this.storage[componentName]?.[fileId];\n }\n\n remove(componentName: string, file: File): void {\n const fileId = getFileUploadId(file);\n if (this.storage[componentName]) {\n delete this.storage[componentName][fileId];\n }\n }\n\n clearComponent(componentName: string): void {\n delete this.storage[componentName];\n }\n\n clear(): void {\n this.storage = {};\n }\n}\n\nexport const FileManager = FileManagerClass.getInstance();\n\n// Get a deterministic file ID based on file properties\nexport function getFileUploadId(file: File): string {\n const name = file.name.replace(/[^a-zA-Z0-9.-]/g, \"_\");\n const size = file.size;\n const lastModified = file.lastModified;\n\n return `${name}-${size}-${lastModified}`;\n}\n\n/**\n * Check if the given object is a light readable file.\n * Meaning it has a $superblocksId property.\n *\n * Compare to `isReadableFile` which checks if the object is a full superblocks readable file object.\n */\nexport const isLightReadableFile = (f: unknown): f is FileMetadataPrivate => {\n if (!f || typeof f !== \"object\" || Array.isArray(f)) {\n return false;\n }\n const entries = Object.entries(f as Record<string, unknown>);\n if (entries.length === 0) {\n return false;\n }\n return \"$superblocksId\" in f;\n};\n\n// Extracts the property ordering for each nested file, which can be used\n// by lodash to extract the specific files.\n// [\n// ['FileDropzone1', 'files', '0']\n// ]\nfunction getFilePaths(root: unknown, path: string[] = []): string[][] {\n const paths: string[][] = [];\n if (!root || !(typeof root === \"object\")) {\n return paths;\n }\n if (Array.isArray(root) || isObservableArray(root)) {\n root.forEach((v, i) => {\n paths.push(...getFilePaths(v, [...path, i.toString()]));\n });\n return paths;\n }\n if (isLightReadableFile(root)) {\n return [path];\n }\n Object.entries(root as Record<string, unknown>).forEach(([key, value]) => {\n if (isLightReadableFile(value)) {\n paths.push([...path, key]);\n } else if (value && (Array.isArray(value) || isObservableArray(value))) {\n value.forEach((v, i) => {\n paths.push(...getFilePaths(v, [...path, key, i.toString()]));\n });\n } else if (value && typeof value === \"object\") {\n paths.push(...getFilePaths(value, [...path, key]));\n }\n });\n return paths;\n}\n\n/**\n * Extract Files and path to files from entities.\n * Used to retrieve files that are in an entity's state which is bound in a Backend API.\n * @param entities - The entities to extract files from\n * @returns\n */\nexport function extractFilesFromEntities(entities: Record<string, unknown>): {\n files: Record<string, File>;\n paths: string[][];\n} {\n const files: Record<string, File> = {};\n const pathToFiles: string[][] = [];\n\n Object.entries(entities).forEach(([entityName, entityValue]) => {\n const foundFiles = getFilePaths(entityValue);\n foundFiles.forEach((path) => {\n const fileObj = get(entityValue, path);\n if (isLightReadableFile(fileObj)) {\n const fileId = fileObj.$superblocksId;\n const file = FileManager.get(entityName, fileId);\n if (file) {\n files[fileId] = file;\n pathToFiles.push([entityName, ...path]);\n }\n }\n });\n });\n\n return { files, paths: pathToFiles };\n}\n\nexport async function formatFilesForRequest(\n files: Record<string, File>,\n): Promise<\n Array<{\n originalName: string;\n buffer: string;\n encoding: \"base64\";\n mimetype: \"text/plain\";\n }>\n> {\n const entries = Object.entries(files);\n\n const encodedFiles = await Promise.all(\n entries.map(async ([fileId, file]) => {\n try {\n const base64 = await new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () =>\n resolve((reader.result as string).split(\",\")[1]);\n reader.onerror = () =>\n reject(\n new Error(reader.error?.message || \"Unknown error reading file\"),\n );\n reader.readAsDataURL(file);\n });\n\n return {\n originalName: fileId,\n buffer: base64,\n encoding: \"base64\" as const,\n mimetype: \"text/plain\" as const,\n };\n } catch (error) {\n console.warn(\n `Failed to encode file ${file.name} (ID: ${fileId}):`,\n error,\n );\n throw error;\n }\n }),\n );\n\n return encodedFiles;\n}\n\nexport function getFileWithUploadId(f: File): File {\n const uploadId = getFileUploadId(f);\n Object.defineProperty(f, \"$superblocksId\", {\n value: uploadId,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n return f;\n}\n\nexport function getFileMetadata(f: File): FileMetadataPrivate {\n const superblocksId = getFileUploadId(f);\n\n const nameParts = f.name.split(\".\");\n const extension = nameParts.length > 1 ? nameParts.pop() || \"\" : \"\";\n\n return {\n $superblocksId: superblocksId,\n name: f.name,\n extension,\n type: f.type,\n size: f.size,\n encoding: \"text\" as const,\n };\n}\n","import {\n splitJSPath,\n stringifySplitPaths,\n} from \"@superblocksteam/library-shared\";\nimport { cloneDeep, get, isObject, set } from \"lodash\";\nimport {\n extractFilesFromEntities,\n FileManager,\n getFileMetadata,\n isLightReadableFile,\n} from \"./file-utils.js\";\nimport { getName } from \"./names.js\";\nimport type { IEntityManager } from \"./base-entity-manager.js\";\n\nexport function getApiDeps(\n entitiesState: IEntityManager,\n scopeId: string,\n apiDepCandidates: string[],\n): { entities: Record<string, unknown>; files: Record<string, File> } {\n const apiDepEntries = apiDepCandidates.map((candidateName) => {\n const [entityName, ...rest] = splitJSPath(candidateName) ?? [];\n return [entityName, rest.length === 0 ? \"\" : stringifySplitPaths(rest)];\n });\n\n // handle multiple paths within same entity\n const candidates: Record<string, string> = {};\n apiDepEntries.forEach(([name, rest]) => {\n if (name in candidates) {\n // take the parent path that is shared between all entity paths\n const parts = splitJSPath(rest) ?? [];\n const existingParts = splitJSPath(candidates[name]) ?? [];\n let i = 0;\n for (i = 0; i < Math.min(parts.length, existingParts.length); i++) {\n if (parts[i] === existingParts[i]) {\n continue;\n }\n }\n candidates[name] = stringifySplitPaths(parts.slice(0, i - 1));\n } else {\n candidates[name] = rest;\n }\n });\n\n const entities = Object.fromEntries(\n Object.entries(candidates)\n .map(([candidateName, path]) => [\n candidateName,\n buildEntityByPath(\n path,\n entitiesState.getEntity(\n scopeId,\n getName(candidateName), // name is always non-anonymous\n {\n includeParentScopes: true,\n },\n ),\n ),\n ])\n .filter(([_, entity]) => !!entity),\n );\n\n const { files, paths } = extractFilesFromEntities(entities);\n\n /**\n * Update entities data payload that rely on files,\n * to honor the FilePrivateMetadata type\n * which is checked on runtime in the backend.\n */\n const clonedEntities = new Set<string>();\n paths.forEach((path) => {\n const fileProps = get(entities, path);\n if (isLightReadableFile(fileProps)) {\n const file = FileManager.get(path[0], fileProps.$superblocksId);\n if (file) {\n // Clone entity before mutating to avoid modifying the original\n const entityName = path[0];\n if (!clonedEntities.has(entityName)) {\n // Use `cloneDeep` as `structuredClone` does not work with proxies\n entities[entityName] = cloneDeep(entities[entityName]);\n clonedEntities.add(entityName);\n }\n set(entities, path, getFileMetadata(file));\n }\n }\n });\n\n return { entities, files };\n}\n\nfunction buildEntityByPath(path: string, entity: unknown) {\n if (!isObject(entity) || path === \"\") {\n return entity;\n }\n\n const [pathPart, ...rest] = splitJSPath(path) ?? [];\n // walk the entity by dotted path and build minimum entity to send\n const entityToSend: Record<string, unknown> = {};\n if (isObject(entity) && pathPart in entity) {\n entityToSend[pathPart] = buildEntityByPath(\n stringifySplitPaths(rest),\n (entity as Record<string, unknown>)[pathPart],\n );\n } else {\n // deopt case\n entityToSend[pathPart] = entity;\n }\n return entityToSend;\n}\n","// TODO(code-mode): Remove import from edit-mode\nimport { editorBridge } from \"../../../edit-mode/superblocks-editor-bridge.js\";\nimport { isEmbeddedBySuperblocksFirstParty } from \"./iframe.js\";\n\nconst EMBED_STRING = `embedded-`;\n\nlet promiseCount = 0;\nconst resolverMap = new Map<string, (...args: any[]) => any>();\nconst rejectorMap = new Map<string, (...args: any[]) => any>();\n\nconst multiUseCallbacks = new Map<string, (...args: any[]) => any>();\n\nexport function addNewPromise(\n resolver: (...args: any[]) => any,\n isMultiUse = false,\n rejecter?: (...args: any[]) => any,\n) {\n const promiseId = `${\n isEmbeddedBySuperblocksFirstParty() ? EMBED_STRING : \"\"\n }p${++promiseCount}`;\n resolverMap.set(promiseId, resolver);\n if (isMultiUse) {\n multiUseCallbacks.set(promiseId, resolver);\n }\n if (rejecter) {\n rejectorMap.set(promiseId, rejecter);\n }\n return promiseId;\n}\n\nexport function resolveById(id: string, payload: any) {\n const isEmbedId = id.startsWith(EMBED_STRING);\n if (\n (isEmbeddedBySuperblocksFirstParty() && !isEmbedId) ||\n (!isEmbeddedBySuperblocksFirstParty() && isEmbedId)\n ) {\n editorBridge.resolvePromise(id, payload);\n } else {\n try {\n const resolver = resolverMap.get(id);\n if (!resolver) {\n throw new Error(`Promise not found for id ${id}`);\n }\n resolver(payload);\n if (!multiUseCallbacks.has(id)) {\n resolverMap.delete(id);\n rejectorMap.delete(id);\n }\n } catch (e) {\n console.log(\"Error resolving promise\", e);\n }\n }\n}\n\nexport function rejectById(id: string, payload: any) {\n const isEmbedId = id.startsWith(EMBED_STRING);\n if (\n (isEmbeddedBySuperblocksFirstParty() && !isEmbedId) ||\n (!isEmbeddedBySuperblocksFirstParty() && isEmbedId)\n ) {\n editorBridge.rejectPromise(id, payload);\n } else {\n try {\n const rejecter = rejectorMap.get(id);\n if (!rejecter) {\n throw new Error(`Promise not found for id ${id}`);\n }\n rejecter(payload);\n if (!multiUseCallbacks.has(id)) {\n resolverMap.delete(id);\n rejectorMap.delete(id);\n }\n } catch (e) {\n console.log(\"Error rejecting promise\", e);\n }\n }\n}\n\nexport function clearMultiCallback(id: string) {\n multiUseCallbacks.delete(id);\n}\n","import { propagation, trace, context, ROOT_CONTEXT } from \"@opentelemetry/api\";\nimport { getTracer } from \"../utils.js\";\nimport type { Context, Span } from \"@opentelemetry/api\";\n\nexport function getContextFromTraceHeaders(\n traceHeaders: Record<string, string>,\n): Context {\n let parentContext = context.active();\n\n try {\n parentContext = propagation.extract(context.active(), traceHeaders);\n } catch (error) {\n console.warn(\n \"Failed to extract parent context from headers\",\n traceHeaders,\n error,\n );\n }\n\n return parentContext;\n}\n\nexport function createIframeSpan(\n name: string,\n attributes: Record<string, any>,\n parentContext?: Context,\n) {\n const tracer = getTracer(\"superblocks-iframe\");\n return tracer.startSpan(name, { attributes }, parentContext);\n}\n\nexport function getTraceContextHeadersFromSpan(\n span: Span,\n): Record<string, string> {\n const traceContextHeaders = {};\n const contextWithSpan = trace.setSpan(ROOT_CONTEXT, span);\n propagation.inject(contextWithSpan, traceContextHeaders);\n return traceContextHeaders;\n}\n","export const generateId = () => {\n return Math.random().toString(36).substring(2, 15);\n};\n","import { context } from \"@opentelemetry/api\";\nimport {\n ViewMode,\n SUPERBLOCKS_REQUEST_ID_HEADER,\n SUPERBLOCKS_AUTHORIZATION_HEADER,\n decodeBytestrings,\n} from \"@superblocksteam/shared\";\nimport { ApiResponseType } from \"@superblocksteam/shared\";\nimport {\n getContextFromTraceHeaders,\n createIframeSpan,\n getTraceContextHeadersFromSpan,\n} from \"../../../tracing/context-utils.js\";\nimport { cleanObject } from \"../../../utils/clean-object.js\";\nimport { generateId } from \"../../../utils/generate-id.js\";\nimport type {\n ApiV2ExecutionRequest,\n ApiV2ExecutionResponse,\n ExecutionEvent,\n ExecutionResponse,\n StreamEvent,\n} from \"../types.js\";\nimport type { DeleteMeLibraryApi } from \"@superblocksteam/library-shared/types\";\nimport type { Agent } from \"@superblocksteam/shared\";\n\nexport type ExecuteV2ApiParams = {\n body: ApiV2ExecutionRequest;\n api: DeleteMeLibraryApi;\n environment: string;\n eventType: string; // TODO(code-mode/api) figure out if we need a type for this, probably not\n notifyOnSystemError: boolean;\n // organization: Organization;\n responseType: ApiResponseType;\n onMessage?: (message: any) => void;\n processStreamEvents?: (event: StreamEvent) => void;\n controlFlowOnlyFiles?: FileRequestParam[];\n abortController?: AbortController;\n baseUrl: string;\n agents: Array<Agent>;\n viewMode: ViewMode;\n accessToken: string;\n token: string;\n traceHeaders?: Record<string, string>;\n};\n\nexport async function executeV2Api(\n params: ExecuteV2ApiParams,\n): Promise<ExecutionResponse | undefined | void> {\n const {\n body,\n controlFlowOnlyFiles,\n api,\n notifyOnSystemError,\n eventType,\n onMessage,\n processStreamEvents,\n responseType,\n abortController,\n baseUrl,\n // agents,\n // organization,\n viewMode,\n accessToken,\n token,\n traceHeaders,\n } = params;\n\n let parentContext = context.active();\n\n if (traceHeaders) {\n parentContext = getContextFromTraceHeaders(traceHeaders);\n }\n\n let applicationId = \"unknown\";\n if (\"fetchByPath\" in body) {\n applicationId = body.fetchByPath.applicationId;\n }\n const span = createIframeSpan(\n \"iframe_execute_v2_api\",\n {\n \"api-name\": api?.apiPb?.metadata?.name || \"unknown\",\n \"application-id\": applicationId,\n event_type: eventType,\n response_type: responseType,\n view_mode: viewMode,\n },\n parentContext,\n );\n\n try {\n // Clean the body to handle proxy objects before stringifying\n let cleanedBody: Record<string, any>;\n try {\n cleanedBody = cleanObject(body) as Record<string, any>;\n } catch {\n cleanedBody = structuredClone(body);\n }\n\n if (controlFlowOnlyFiles && controlFlowOnlyFiles.length > 0) {\n cleanedBody = {\n ...cleanedBody,\n files: controlFlowOnlyFiles,\n };\n }\n\n // TODO(code-mode/api) deployed mode\n\n // Inject current trace context for server continuation\n const traceContextHeaders = getTraceContextHeadersFromSpan(span);\n\n const init: RequestInit = {\n method: HttpMethod.Post,\n body: JSON.stringify(cleanedBody),\n signal: abortController?.signal,\n headers: {\n [SUPERBLOCKS_AUTHORIZATION_HEADER]: `Bearer ${accessToken}`,\n Authorization: `Bearer ${token}`,\n [SUPERBLOCKS_REQUEST_ID_HEADER]: generateId(),\n // Include trace context headers for distributed tracing\n ...traceContextHeaders,\n },\n credentials: \"include\" as RequestCredentials,\n };\n\n const result =\n responseType === ApiResponseType.STREAM\n ? await fetchServerStream({\n augmentedInit: init,\n fullUrl: baseUrl,\n // TODO(code-mode/api)\n timeoutId: setTimeout(() => {}, 1000),\n onMessage,\n processStreamEvents,\n })\n : await fetchServer({\n augmentedInit: init,\n fullUrl: baseUrl,\n // TODO(code-mode/api)\n timeoutId: setTimeout(() => {}, 1000),\n });\n\n return result as ExecutionResponse | undefined;\n } catch (err) {\n const message = `Failed to execute ${\n api?.apiPb?.metadata?.name || \"API\"\n }. ${err}`;\n\n // https://app.clickup.com/t/8650101/EG-16438\n //this corresponds to \"signal is aborted without reason\" which we should not surface as it happens when switching pages\n const suppressError =\n viewMode !== ViewMode.EDITOR && (err as any)?.code === 20;\n\n if (notifyOnSystemError && !suppressError) {\n // TODO(code-mode/api)\n // sendErrorUINotification({\n // message,\n // });\n console.log(message);\n }\n return {\n systemError: message,\n };\n } finally {\n span.end();\n }\n}\n\nexport const HttpMethod = {\n Get: \"GET\",\n Post: \"POST\",\n Put: \"PUT\",\n Patch: \"PATCH\",\n Delete: \"DELETE\",\n} as const;\n\ntype HttpMethodName = (typeof HttpMethod)[keyof typeof HttpMethod];\n\ntype FileRequestParam = {\n originalName: string;\n buffer: string; // base64 encoded string\n encoding: \"base64\";\n mimetype: \"text/plain\";\n};\n\nexport interface HttpCallOptions extends BaseCallOptions {\n baseUrl?: string;\n // We do not support generic file uploads- only specific /execute calls support this\n controlFlowOnlyFiles?: FileRequestParam[];\n bodyIsFormData?: boolean;\n}\n\ninterface BaseCallOptions {\n method: HttpMethodName;\n url: string;\n body?: Record<string, any>;\n query?: Record<string, string | string[]>;\n params?: Record<string, unknown>;\n timeout?: number;\n abortController?: AbortController;\n // TODO(code-mode/api)\n // diagnosticMetadata?: AgentDiagnosticMetadata;\n // TODO(code-mode/api)\n // responseType?: ApiResponseType;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n priority?: RequestPriority;\n}\n\nexport const stream = async ({\n url,\n headers,\n body,\n onMessage,\n onComplete,\n onError,\n defaultError,\n method,\n baseUrl = \"/api/\",\n signal,\n init: overrideInit,\n}: {\n url: string;\n init?: RequestInit;\n headers?: Record<string, string>;\n body?: Record<string, any>;\n onMessage: (message: any) => void;\n onComplete: () => void;\n onError: (error: string, statusCode?: number) => void;\n defaultError?: string;\n method?: HttpMethodName;\n baseUrl?: string;\n signal?: AbortSignal;\n}): Promise<void> => {\n const init: RequestInit = overrideInit ?? {\n body: JSON.stringify(body),\n headers,\n method,\n };\n try {\n const response = await fetch(`${baseUrl}${url}`, init);\n if (!response.ok) {\n try {\n const parsed = await response.json();\n\n throw new HttpError(\n response.status,\n !response.status || response.status >= 500,\n parsed?.error?.message ??\n parsed?.responseMeta?.error?.message ??\n defaultError,\n );\n } catch (e) {\n if (e instanceof HttpError) {\n throw e;\n }\n //response cannot be parsed to json, throwing http error as it is the cause\n throw new HttpError(\n response.status,\n !response.status || response.status >= 500,\n response.statusText,\n );\n }\n }\n if (!response.body) {\n return;\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let done = false;\n\n let lastChunk = \"\";\n while (!done) {\n if (signal && signal.aborted) {\n return; // Stop processing if the fetch was cancelled\n }\n const { value, done: readerDone } = await reader.read();\n const chunk = lastChunk + decoder.decode(value);\n const messages = chunk.split(\"\\n\");\n\n let jsonValues: { error?: { message: string } }[] = [];\n try {\n jsonValues = messages\n .filter(Boolean)\n .map((message) => JSON.parse(message.trim()));\n // Reset the last chunk if we were able to parse the message\n lastChunk = \"\";\n } catch (e) {\n // If we can't parse the message, it's probably because we only got a partial message\n // Append the chunk to the last chunk and try again next time\n lastChunk = chunk;\n\n // If we fail to parse and the reader is done, then we should throw an error\n // as we won't be able to parse the message\n if (readerDone) {\n throw e;\n }\n }\n\n for (const jsonValue of jsonValues.filter(Boolean)) {\n if (jsonValue?.error) {\n onError(jsonValue.error.message ?? defaultError);\n return;\n }\n onMessage(jsonValue);\n }\n\n done = readerDone && lastChunk === \"\";\n }\n } catch (e: HttpError | TypeError | any) {\n if (e.name === \"AbortError\") {\n console.log(\"Fetch was cancelled\");\n } else {\n onError(e.message ?? defaultError, e.code);\n }\n } finally {\n onComplete();\n }\n};\n\ninterface BaseFetchOptions {\n augmentedInit: RequestInit;\n timeoutId: ReturnType<typeof setTimeout>;\n body?: Record<string, any>;\n path?: string;\n // TODO(code-mode/api)\n // diagnosticMetadata?: AgentDiagnosticMetadata;\n // errorHandlingOptions?: ErrorHandlingOptions;\n}\n\ninterface FetchOptions extends BaseFetchOptions {\n fullUrl: string;\n}\n\ninterface StreamingFetchOptions extends FetchOptions {\n onMessage?: (message: any) => void;\n processStreamEvents?: (event: any) => void;\n}\n\nconst handleError = (\n rawError: HttpError | TypeError,\n { fullUrl, augmentedInit }: FetchOptions,\n) => {\n const error =\n rawError instanceof TypeError\n ? // this is a network error\n // the code below expects that error is an instance of HttpError\n // so represent this network error as an HttpError with status=0 (which is a common convention)\n new HttpError(0, true, rawError.message)\n : rawError;\n //response with json parsed, but has error code\n console.error(\n `Request to '${fullUrl} has failed\nResponse Status: ${error.code}\nResponse Status Text: ${error.message}`,\n // {\n // superblocks_ui_error_type: getUIErrorTypeByCode(error.code),\n // superblocks_ui_error_code: error.code,\n // },\n );\n //previous try catch ensured the error captured here is HttpError\n let critical = error.critical;\n // userNotified keeps track if we've notified the user of this error. It helps\n // preventing showing multiple notifications for the same error.\n // let userNotified = false;\n // network error should not block user from editing api, we can just show error notification\n // we can add errors that are non-critical here\n if (fullUrl.match(/apis\\/.*/) && (critical || error.code === 0)) {\n critical = false;\n }\n // Do not crash page over commits or deployments 500 errors\n if (fullUrl.match(/\\/(commits|deployment).*/) && error.code === 500) {\n critical = false;\n }\n\n if (\n augmentedInit.method === HttpMethod.Get &&\n fullUrl.match(/apis\\/.*/)\n // &&\n // error.code === API_STATUS_CODES.RESOURCE_FORBIDDEN\n ) {\n // It is critical if we're not allowed to fetch an API.\n critical = true;\n } else if (\n fullUrl.match(/apis\\/.*/)\n // &&\n // error.code === API_STATUS_CODES.RESOURCE_FORBIDDEN\n ) {\n // userNotified = true;\n // sendErrorUINotification({\n // message: error.message,\n // duration: 0, // Don't auto-dismiss since this is a very confusing error\n // });\n }\n\n if (error.code && error.code < 500 && error.code >= 400) {\n if (error.code === 404) {\n //set to true to redirect to crash page\n critical = true;\n }\n // else if (errorHandlingOptions?.notifyOnError && !userNotified) {\n // userNotified = true;\n // show4XXError(`${error.message} (${error.code})`);\n // }\n }\n\n if (\n error.code >= 500 // we crash app on server 500 error normally, but explicity defining shouldCrashApp can escape it\n // &&\n // errorHandlingOptions?.shouldCrashApp === false //\n ) {\n critical = false;\n }\n\n // only modifying `critical`\n // const editedError = new HttpError(error.code, critical, error.message);\n // errorHandlingOptions?.onError?.(editedError);\n // if (errorHandlingOptions?.notifyOnError && !userNotified) {\n // throw editedError;\n // }\n};\n\nconst fetchServerStream = async ({\n augmentedInit,\n fullUrl,\n timeoutId,\n onMessage,\n processStreamEvents,\n}: StreamingFetchOptions): Promise<void> => {\n const handleMessage = (message: any) => {\n if (message?.result?.event?.data) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n onMessage && onMessage(message.result.event.data);\n } else if (message?.result?.event?.start || message?.result?.event?.end) {\n // if the message is a start or end message, we want to process it so we can show the live execution results\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n processStreamEvents && processStreamEvents(message);\n }\n };\n\n const onComplete = () => {\n clearTimeout(timeoutId);\n };\n\n const onError = (error: string, statusCode?: number) => {\n if (statusCode != null) {\n handleError(\n new HttpError(statusCode, !statusCode || statusCode >= 500, error),\n {\n fullUrl,\n augmentedInit,\n // errorHandlingOptions,\n timeoutId,\n },\n );\n } else {\n handleError(new TypeError(error), {\n fullUrl,\n augmentedInit,\n // errorHandlingOptions: {\n // ...errorHandlingOptions,\n // these are handled by the block outputs\n // TODO(Mark) the above comment should not be true, we should not be special here\n // notifyOnError:\n // false,\n // NETWORK_ERRORS.includes(error)\n // ? (errorHandlingOptions?.notifyOnError ?? false)\n // : false,\n // },\n timeoutId,\n });\n }\n };\n\n return stream({\n url: fullUrl,\n init: augmentedInit,\n onMessage: handleMessage,\n onComplete,\n onError,\n baseUrl: \"\",\n signal: augmentedInit?.signal ?? undefined,\n });\n};\n\nconst getErrorMessageFromObject = (message: object) => {\n const messageJSONString = JSON.stringify(message);\n const regex = /\"message\"\\s*:\\s*\"([^\"]*)\"/;\n const match = regex.exec(messageJSONString);\n return match ? match[1] : messageJSONString;\n};\n\nconst fetchServer = <TResult>({\n augmentedInit,\n fullUrl,\n timeoutId,\n // errorHandlingOptions,\n}: FetchOptions): Promise<TResult> => {\n return fetch(fullUrl, augmentedInit)\n .then(async (response) => {\n try {\n if (response.status === 204) {\n return null;\n }\n const json = await response.json();\n if (response.ok && json) {\n if (json.data == null) {\n return json; // v2 API endpoints do not wrap\n }\n return json.data as TResult;\n } else {\n let message = json.responseMeta?.error?.message ?? json?.message;\n if (typeof message === \"object\") {\n message = getErrorMessageFromObject(message);\n }\n throw new HttpError(\n response.status,\n !response.status || response.status >= 500,\n message,\n );\n }\n } catch (e) {\n //response with json parsed, but has error code\n if (e instanceof HttpError) {\n throw e;\n }\n //response cannot be parsed to json, throwing http error as it is the cause\n throw new HttpError(\n response.status,\n !response.status || response.status >= 500,\n response.statusText,\n );\n }\n })\n .catch((rawError: HttpError | TypeError) => {\n handleError(rawError, {\n fullUrl,\n augmentedInit,\n // errorHandlingOptions,\n timeoutId,\n });\n })\n .finally(() => clearTimeout(timeoutId));\n};\n\nexport class HttpError extends Error {\n code: number;\n critical: boolean;\n\n constructor(code: number, critical = false, m?: string) {\n super(m);\n this.code = code;\n this.critical = critical;\n }\n}\n\nexport const parseStreamResult = (\n streamResult: Array<StreamEvent>,\n options?: {\n includeFinalOutput?: boolean;\n },\n): undefined | ApiV2ExecutionResponse => {\n if (!streamResult || !Array.isArray(streamResult) || !streamResult.length) {\n return;\n }\n const execution = streamResult[0].result.execution;\n const [errors, events] = streamResult.reduce(\n (accum: [{ message: string }[], ExecutionEvent[]], event) => {\n if (event.result.event.end && event.result.event.end.error) {\n accum[0].push(event.result.event.end.error);\n }\n accum[1].push(event.result.event);\n\n return accum;\n },\n [[], []],\n );\n const result: ApiV2ExecutionResponse = {\n execution,\n events,\n errors,\n status: \"STATUS_COMPLETED\",\n };\n\n if (options?.includeFinalOutput) {\n // Check for a Return block, which should be the api result rather than just the last block\n let returnBlockOutput: ApiV2ExecutionResponse[\"output\"];\n for (let i = 0; i < streamResult.length; i++) {\n const streamEvent = streamResult[i];\n if (\n streamEvent.result.event.type === \"BLOCK_TYPE_RETURN\" &&\n streamEvent.result.event.end\n ) {\n returnBlockOutput = streamEvent.result.event.end\n ?.output as ApiV2ExecutionResponse[\"output\"];\n break;\n }\n }\n if (returnBlockOutput) {\n result.output = returnBlockOutput;\n } else {\n const output = streamResult[streamResult.length - 1].result.event.end\n ?.output as ApiV2ExecutionResponse[\"output\"];\n result.output = output;\n }\n }\n\n return result;\n};\n\nexport const isApiV2ExecutionResponse = (\n response: ExecutionResponse | undefined | void,\n): response is ApiV2ExecutionResponse => {\n return !!response && \"output\" in response && response?.output?.result != null;\n};\n\nexport const decodeBytestringsInV2ExecutionResponse = (\n response: ExecutionResponse,\n) => {\n if (!isApiV2ExecutionResponse(response)) {\n return;\n }\n if (response.output) {\n response.output.result = decodeBytestrings(response.output.result, false);\n }\n if (Array.isArray(response.events)) {\n response.events.forEach((event) => {\n const typedEvent = event as ExecutionEvent;\n if (typedEvent?.end?.output?.result != null) {\n typedEvent.end.output.result = decodeBytestrings(\n typedEvent.end.output.result,\n false,\n );\n }\n });\n }\n};\n","import {\n SbEntityType,\n type DeleteMeLibraryApi,\n type SbInstance,\n} from \"@superblocksteam/library-shared/types\";\nimport {\n ApiResponseType,\n OrchestratorViewMode,\n ViewMode,\n} from \"@superblocksteam/shared\";\nimport { action } from \"mobx\";\n// TODO(code-mode): Remove import from edit-mode\nimport { editorBridge } from \"../../../../edit-mode/superblocks-editor-bridge.js\";\nimport { sendNotification } from \"../../../user-facing/utils/notification.jsx\";\nimport { isEditMode } from \"../../is-edit-mode.js\";\nimport { getApiDeps } from \"../evaluator/binding-extraction.js\";\nimport { GLOBAL_SCOPE_ID } from \"../evaluator/entity-manager.js\";\nimport { formatFilesForRequest } from \"../evaluator/file-utils.js\";\nimport { addNewPromise } from \"../resolve-id-singleton.js\";\nimport {\n decodeBytestringsInV2ExecutionResponse,\n executeV2Api,\n isApiV2ExecutionResponse,\n parseStreamResult,\n} from \"./api-utils.js\";\nimport type { Name } from \"../evaluator/names.js\";\nimport type { RootStore } from \"../root-store.js\";\nimport type { StreamEvent, ExecutionResponse } from \"../types.js\";\nimport type { ExecuteV2ApiParams } from \"./api-utils.js\";\nimport type { Global as GlobalType } from \"../../scope/types.js\";\nimport type { SbApiRunOptions } from \"@superblocksteam/library-shared/types\";\n\nexport type ApiResult<T = any> = {\n data?: T;\n error?: string;\n};\n\ntype ApiDependency = {\n apiName: string;\n scopeId: string;\n params: string[];\n dependencies: string[];\n};\n\nclass ApiManager {\n agentUrls: string[] = [];\n private token: string | undefined;\n private accessToken: string | undefined;\n // first key is scope ID, then API name\n private apisByName: Record<string, Record<string, DeleteMeLibraryApi>> = {};\n // first key is scope ID, then API name\n private apiNameToDepCandidates: Record<string, Record<string, string[]>> = {};\n // first key is scope ID, then API name\n private apiNameToApiReferences: Record<string, Record<string, string[]>> = {};\n private runningApiControllers: Record<string, AbortController> = {};\n private waitForInitApiPromise: Promise<void> | undefined = undefined;\n\n constructor(readonly rootStore: RootStore) {}\n\n setTokens(token: string, accessToken: string) {\n this.token = token;\n this.accessToken = accessToken;\n }\n isInitialized() {\n return !!this.token && !!this.accessToken;\n }\n\n private async awaitInitApiIfNeeded() {\n if (this.waitForInitApiPromise) {\n await this.waitForInitApiPromise;\n }\n }\n\n loadApiManifest({\n apis = {},\n apiDependencies = [],\n }: {\n apis?: Record<string, { api: DeleteMeLibraryApi; scopeId: string }>;\n apiDependencies?: ApiDependency[];\n }) {\n this.setAllApis(apis);\n apiDependencies.forEach((dep: ApiDependency) => {\n this.setApiDepCandidates(dep.scopeId, dep.apiName, dep.params);\n this.setApiReferences(dep.scopeId, dep.apiName, dep.dependencies);\n });\n\n const apisToSet: Array<DeleteMeLibraryApi & { scopeId: string }> =\n Object.values(apis).map(({ api, scopeId }) => ({\n ...api,\n scopeId,\n }));\n\n const waitForInitApiPromise = new Promise((resolve) => {\n const callbackId = addNewPromise(resolve);\n window.parent.postMessage(\n {\n type: \"set-apis-deployed-mode\",\n payload: {\n apis: apisToSet,\n callbackId,\n },\n },\n \"*\",\n );\n });\n\n this.waitForInitApiPromise = waitForInitApiPromise as Promise<void>;\n }\n\n setAllApis(\n apis: Record<string, { api: DeleteMeLibraryApi; scopeId: string }>,\n ) {\n this.apisByName = {};\n Object.values(apis).forEach(({ api, scopeId }) => {\n if (!this.apisByName[scopeId]) {\n this.apisByName[scopeId] = {};\n }\n this.apisByName[scopeId][api.apiPb.metadata.name] = api;\n });\n }\n\n setApisLoaded() {\n this.rootStore.setApisLoaded();\n }\n\n setApiDepCandidates(scopeId: string, apiName: string, deps: string[]) {\n if (!this.apiNameToDepCandidates[scopeId]) {\n this.apiNameToDepCandidates[scopeId] = {};\n }\n this.apiNameToDepCandidates[scopeId][apiName] = deps;\n if (!this.rootStore.isApisLoaded) {\n this.rootStore.setApisLoaded();\n }\n }\n\n setApiReferences(scopeId: string, apiName: string, deps: string[]) {\n if (!this.apiNameToApiReferences[scopeId]) {\n this.apiNameToApiReferences[scopeId] = {};\n }\n this.apiNameToApiReferences[scopeId][apiName] = deps;\n }\n\n updateApi(api: DeleteMeLibraryApi, scopeId: string) {\n if (!this.apisByName[scopeId]) {\n this.apisByName[scopeId] = {};\n }\n this.apisByName[scopeId][api.apiPb.metadata.name] = api;\n\n const scope = this.rootStore.entityManager.getPossibleScope(scopeId);\n if (!scope) {\n console.warn(\n `Scope ${scopeId} not found. Could not update API.`,\n api.apiPb.metadata.name,\n );\n return;\n }\n\n const name = {\n value: api.apiPb.metadata.name,\n isAnonymous: false,\n } satisfies Name;\n\n const currentEntity = this.rootStore.entityManager.getEntity(scopeId, name);\n if (!currentEntity) {\n this.rootStore.entityManager.createEntity({\n name,\n scopeId,\n type: SbEntityType.API,\n props: {\n response: null,\n },\n });\n }\n }\n\n deleteApi(apiName: string, scopeId?: string) {\n if (!scopeId) {\n return;\n }\n if (this.apisByName[scopeId]) {\n delete this.apisByName[scopeId][apiName];\n }\n\n const scope = this.rootStore.entityManager.getPossibleScope(scopeId);\n if (!scope) {\n console.warn(\n `Scope ${scopeId} not found. Could not delete API.`,\n apiName,\n );\n return;\n }\n\n const name = {\n value: apiName,\n isAnonymous: false,\n } satisfies Name;\n this.rootStore.entityManager.deleteEntity({\n name,\n scopeId,\n });\n }\n\n renameApi({\n api,\n oldName,\n scopeId,\n }: {\n api: DeleteMeLibraryApi;\n oldName: string;\n scopeId: string;\n }) {\n const name = {\n value: oldName,\n isAnonymous: false,\n } satisfies Name;\n\n // There is a possible race condition where the file system is updated and processed before the socket\n // comes back, so we just need to bail early if the entity is not found\n const currentEntity = this.rootStore.entityManager.getEntity(scopeId, name);\n if (!currentEntity) {\n console.warn(`API with name ${oldName} not found`);\n return;\n }\n\n const newName = {\n value: api.apiPb.metadata.name,\n isAnonymous: false,\n } satisfies Name;\n\n this.rootStore.entityManager.renameEntity({\n newName,\n scopeId,\n isDuplicate: false,\n // APIs are not bound by instance ID, they have unique names\n instanceId: oldName as unknown as SbInstance,\n });\n }\n\n @action\n async runApi(\n apiName: string,\n scopeId: string,\n options: SbApiRunOptions = {},\n ): Promise<ApiResult> {\n await this.awaitInitApiIfNeeded();\n const api = this.apisByName[scopeId][apiName];\n\n editorBridge.setApiStarted(apiName);\n\n if (!api) {\n console.error(`Api ${apiName} not found`);\n throw new Error(`Api ${apiName} not found`);\n }\n\n if (!this.rootStore.applicationId) {\n editorBridge.setApiResponse(apiName, {\n status: \"STATUS_COMPLETED\",\n execution: null,\n errors: [\n {\n message:\n \"No application ID was found, ensure the app was bootstrap correctly.\",\n },\n ],\n });\n sendNotification({\n message:\n \"No application ID was found, ensure the app was bootstrap correctly.\",\n type: \"error\",\n });\n return {\n data: null,\n error: \"No application ID was found\",\n };\n }\n\n const apiDepCandidates =\n this.apiNameToDepCandidates[scopeId]?.[apiName] ?? [];\n const { entities: inputs, files } = getApiDeps(\n this.rootStore.entityManager,\n scopeId,\n apiDepCandidates,\n );\n\n // Format files for server request (top-level files array)\n const controlFlowOnlyFiles = await formatFilesForRequest(files);\n\n if (!this.agentUrls.length) {\n editorBridge.setApiResponse(apiName, {\n status: \"STATUS_COMPLETED\",\n execution: null,\n errors: [{ message: \"No active agent found\" }],\n });\n sendNotification({\n message: \"No active agent found\",\n type: \"error\",\n });\n return {\n data: null,\n error: \"No active agent found\",\n };\n }\n const agentBaseUrl =\n this.agentUrls[Math.floor(Math.random() * this.agentUrls.length)];\n const orchestratorUrl = new URL(\"v2/execute\", agentBaseUrl).href;\n\n const globalScope =\n this.rootStore.entityManager.getPossibleScope(GLOBAL_SCOPE_ID);\n const Global = globalScope?.entities?.Global as GlobalType | undefined;\n const profileKey = Global?.profiles?.selected?.key ?? \"staging\";\n\n const events: Array<StreamEvent> = [];\n\n await this.rootStore.editStore?.operationManager.ensureFilesSynced();\n\n // Create abort controller for this API execution\n const abortController = new AbortController();\n this.runningApiControllers[apiName] = abortController;\n\n const editMode = isEditMode();\n\n // TODO when we support streaming - this should come from the API config\n // Right now we only stream in edit mode in order to support the API editor\n const isStream = editMode ? true : false;\n const waitForAuthPromise = new Promise((resolve) => {\n const callbackId = addNewPromise(resolve);\n window.parent.postMessage(\n {\n type: \"authenticate-api-request\",\n payload: {\n apiId: api.apiPb.metadata.id,\n callbackId,\n },\n },\n \"*\",\n );\n });\n const authResult: any = await waitForAuthPromise;\n // TODO do something with authResult.errors\n if (authResult?.errors && authResult.errors.length > 0) {\n console.error(\n \"API Authentication returned with errors\",\n authResult.errors,\n );\n }\n\n const { traceHeaders, ...restArgs } = options;\n const syncResponse = await executeV2Api({\n body: {\n inputs: {\n ...restArgs,\n ...inputs,\n },\n fetchByPath: {\n path: `/pages/${api.pageName}/apis/${apiName}/api.yaml`,\n applicationId: this.rootStore.applicationId ?? \"\",\n // TODO(code-mode/api): get branch name\n branchName: \"main\",\n profile: {\n name: profileKey,\n },\n viewMode: OrchestratorViewMode.UNSPECIFIED, // TODO - deployed gives 404\n },\n options: {\n includeEventOutputs: editMode,\n includeEvents: isStream || editMode,\n includeResolved: editMode,\n },\n },\n controlFlowOnlyFiles,\n api: api,\n environment: profileKey,\n eventType: \"api\",\n notifyOnSystemError: true,\n responseType: isStream ? ApiResponseType.STREAM : ApiResponseType.SYNC,\n baseUrl: isStream ? orchestratorUrl + \"/stream\" : orchestratorUrl,\n agents: [],\n viewMode: editMode ? ViewMode.EDITOR : ViewMode.DEPLOYED,\n accessToken: this.accessToken ?? \"\",\n token: this.token ?? \"\",\n traceHeaders: traceHeaders,\n abortController,\n onMessage: (message: any) => {\n editorBridge.sendStreamedApiMessage(message, apiName);\n },\n processStreamEvents: (event: StreamEvent) => {\n events.push(event);\n editorBridge.sendStreamedApiEvent(event, apiName);\n },\n } satisfies ExecuteV2ApiParams);\n\n const parsedResult = isStream\n ? parseStreamResult(events, {\n includeFinalOutput: true,\n })\n : syncResponse;\n\n if (parsedResult) {\n decodeBytestringsInV2ExecutionResponse(parsedResult);\n }\n\n delete this.runningApiControllers[apiName];\n editorBridge.setApiResponse(apiName, parsedResult);\n\n const error = this.findError(parsedResult ?? undefined);\n const data = isApiV2ExecutionResponse(parsedResult)\n ? parsedResult?.output?.result\n : null;\n\n return { data, error };\n }\n\n private findError(apiResponse?: ExecutionResponse): string | undefined {\n if (apiResponse && \"systemError\" in apiResponse) {\n // system errors are not errors that occurred within the API and thus are not reported\n // to error triggers or the data tree.\n return undefined;\n }\n\n const firstUnhandledError = apiResponse?.errors?.find(\n (error) => !error?.handled,\n );\n\n if (!firstUnhandledError) {\n return undefined;\n }\n return `Error in API: ${firstUnhandledError?.message}`;\n }\n\n @action\n async cancelApi(apiName: string, _scopeId: string) {\n const abortController = this.runningApiControllers[apiName];\n\n if (!abortController) {\n console.warn(`No running API execution found for ${apiName}`);\n return;\n }\n\n // Abort the HTTP request\n abortController.abort();\n delete this.runningApiControllers[apiName];\n\n // Notify editor bridge of cancellation\n editorBridge.setApiResponse(apiName, {\n status: \"STATUS_CANCELLED\",\n execution: null,\n events: [],\n errors: [{ message: \"API execution was cancelled\" }],\n output: null,\n });\n }\n}\n\nexport default ApiManager;\n","import { pathStringToArray } from \"@superblocksteam/library-shared\";\nimport diff, { type Difference } from \"microdiff\";\nimport { isReactElement } from \"../../lib/utils/clean-object.js\";\nimport type { MobXPatch } from \"@superblocksteam/library-shared/types\";\n\nexport const microPatches = (\n oldValue: any,\n newValue: any,\n baseStr: string,\n): MobXPatch[] => {\n const cleanedOldValue = removeBindAndReactElements(oldValue);\n const cleanedNewValue = removeBindAndReactElements(newValue);\n if (cleanedOldValue === undefined) {\n return [\n {\n op: \"add\",\n path: pathStringToArray(baseStr),\n value: cleanedNewValue,\n },\n ];\n }\n\n // Handle primitive value changes that microdiff can't handle (microdiff only supports arrays, objects and other builtins like Regex, Date, etc.)\n if (isPrimitive(cleanedOldValue) || isPrimitive(cleanedNewValue)) {\n if (cleanedOldValue !== cleanedNewValue) {\n return [\n {\n op: \"update\",\n path: pathStringToArray(baseStr),\n value: cleanedNewValue,\n } as const,\n ] satisfies MobXPatch[];\n }\n return []; // No change\n }\n\n const diffs = diff(cleanedOldValue, cleanedNewValue);\n const basePath = pathStringToArray(baseStr);\n return diffs.map((diff) => toMobXPatchFromMicroDiff(diff, basePath));\n};\n\nfunction isPrimitive(value: any): boolean {\n return (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"undefined\"\n );\n}\n\nfunction toMobXPatchFromMicroDiff(\n diff: Difference,\n basePath: (string | number)[],\n): MobXPatch {\n const type = diff.type;\n const fullPath = [...basePath, ...diff.path];\n\n switch (type) {\n case \"CREATE\":\n return {\n op: \"add\",\n path: fullPath,\n value: diff.value,\n } satisfies MobXPatch;\n case \"CHANGE\": {\n return {\n op: \"update\",\n path: fullPath,\n value: diff.value,\n } satisfies MobXPatch;\n }\n case \"REMOVE\":\n return {\n op: \"remove\",\n path: fullPath,\n } satisfies MobXPatch;\n default:\n throw new Error(`Unhandled diff type: ${type}`);\n }\n}\n\nconst removeBindAndReactElements = (value: any): any => {\n if (!value || typeof value !== \"object\") {\n return value;\n }\n if (isReactElement(value)) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map(removeBindAndReactElements);\n }\n return Object.fromEntries(\n Object.entries(value).map(([key, value]) => {\n if (key === \"bind\") {\n return [key, undefined];\n }\n return [key, removeBindAndReactElements(value)];\n }),\n );\n};\n","import {\n observe,\n isObservableMap,\n isObservableObject,\n isObservableArray,\n values,\n entries,\n} from \"mobx\";\nimport type { IObjectDidChange, IArrayDidChange, IMapDidChange } from \"mobx\";\n\nexport type IDisposer = () => void;\n\ntype IChange = IObjectDidChange | IArrayDidChange | IMapDidChange;\n\ntype Entry = {\n dispose: IDisposer;\n path: string;\n parent: Entry | undefined;\n};\n\nexport type ObserveListener<T> = (\n change: IChange,\n path: string,\n root: T,\n) => void;\n\nfunction buildPath(entry: Entry | undefined): string {\n if (!entry) return \"ROOT\";\n const res: string[] = [];\n while (entry.parent) {\n res.push(entry.path);\n entry = entry.parent;\n }\n return res.reverse().join(\"/\");\n}\n\nfunction isRecursivelyObservable(thing: any) {\n return (\n isObservableObject(thing) ||\n isObservableArray(thing) ||\n isObservableMap(thing)\n );\n}\n\n/**\n * Given an object, deeply observes the given object.\n * It is like `observe` from mobx, but applied recursively, including all future children.\n *\n * Note that the given object cannot ever contain cycles and should be a tree.\n *\n * As benefit: path and root will be provided in the callback, so the signature of the listener is\n * (change, path, root) => void\n *\n * The returned disposer can be invoked to clean up the listener\n *\n * deepObserve cannot be used on computed values.\n *\n * @example\n * const disposer = deepObserve(target, (change, path) => {\n * console.dir(change)\n * })\n */\nexport function deepObserve<T = any>(\n target: T,\n listener: ObserveListener<T>,\n): IDisposer {\n const entrySet = new WeakMap<any, Entry>();\n\n function genericListener(change: IChange) {\n const entry = entrySet.get(change.object)!;\n processChange(change, entry);\n listener(change, buildPath(entry), target);\n }\n\n function processChange(change: IChange, parent: Entry) {\n switch (change.type) {\n // Object changes\n case \"add\": // also for map\n observeRecursively(change.newValue, parent, change.name);\n break;\n case \"update\": // also for array and map\n unobserveRecursively(change.oldValue);\n observeRecursively(\n change.newValue,\n parent,\n (change as any).name || \"\" + (change as any).index,\n );\n break;\n case \"remove\": // object\n case \"delete\": // map\n unobserveRecursively(change.oldValue);\n break;\n // Array changes\n case \"splice\":\n change.removed.map(unobserveRecursively);\n change.added.forEach((value, idx) =>\n observeRecursively(value, parent, \"\" + (change.index + idx)),\n );\n // update paths\n for (\n let i = change.index + change.addedCount;\n i < change.object.length;\n i++\n ) {\n if (isRecursivelyObservable(change.object[i])) {\n const entry = entrySet.get(change.object[i]);\n if (entry) entry.path = \"\" + i;\n }\n }\n break;\n }\n }\n\n function observeRecursively(\n thing: any,\n parent: Entry | undefined,\n path: string,\n ) {\n if (isRecursivelyObservable(thing)) {\n const entry = entrySet.get(thing);\n if (entry) {\n if (entry.parent !== parent || entry.path !== path)\n // MWE: this constraint is artificial, and this tool could be made to work with cycles,\n // but it increases administration complexity, has tricky edge cases and the meaning of 'path'\n // would become less clear. So doesn't seem to be needed for now\n throw new Error(\n `The same observable object cannot appear twice in the same tree,` +\n ` trying to assign it to '${buildPath(parent)}/${path}',` +\n ` but it already exists at '${buildPath(entry.parent)}/${entry.path}'`,\n );\n } else {\n const entry = {\n parent,\n path,\n dispose: observe(thing, genericListener),\n };\n entrySet.set(thing, entry);\n entries(thing).forEach(([key, value]) =>\n observeRecursively(value, entry, \"\" + key),\n );\n }\n }\n }\n\n function unobserveRecursively(thing: any) {\n if (isRecursivelyObservable(thing)) {\n const entry = entrySet.get(thing);\n if (!entry) return;\n entrySet.delete(thing);\n entry.dispose();\n values(thing).forEach(unobserveRecursively);\n }\n }\n\n observeRecursively(target, undefined, \"\");\n\n return () => {\n unobserveRecursively(target);\n };\n}\n","import { toMobXPatch } from \"@superblocksteam/library-shared\";\nimport { pick } from \"lodash\";\nimport { isComputedProp, reaction } from \"mobx\";\nimport { isEditMode } from \"../../lib/internal-details/is-edit-mode.js\";\nimport { sanitizedToJS } from \"../../lib/internal-details/lib/evaluator/sanitize-object.js\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport { microPatches } from \"./create-patch.js\";\nimport { deepObserve } from \"./deep-observe.js\";\nimport type { IDisposer } from \"./deep-observe.js\";\nimport type { KeyToState } from \"@superblocksteam/library-shared/types\";\nimport type { IReactionOptions } from \"mobx\";\n\nexport interface MobXEditorSyncOptions<\n SID extends keyof KeyToState = keyof KeyToState,\n OUTPUT extends KeyToState[SID] = KeyToState[SID],\n STORE = OUTPUT,\n> {\n /* A unique identifier to ensure only the intended target receives these messages */\n storeId: SID & string;\n\n /* The observable store to sync (pass your data-only store) */\n store: STORE;\n\n /**\n * A function that takes the store and returns a view/projection of the store.\n * This is useful for syncing only a subset of the store in a different shape.\n */\n projection?: (store: STORE) => OUTPUT;\n\n /**\n * When provided, only patches under these keys are forwarded.\n * Other changes are dropped.\n */\n keys?: Record<keyof OUTPUT, true>;\n\n /**\n * Debounce time in milliseconds.\n */\n debounce?: number;\n}\n\n/**\n * Syncs a mobx store to the editor automatically through postmessage\n */\nexport function startEditorSync<\n SID extends keyof KeyToState = keyof KeyToState,\n OUTPUT extends KeyToState[SID] = KeyToState[SID],\n STORE = any,\n>(options: MobXEditorSyncOptions<SID, OUTPUT, STORE>): () => void {\n if (!isEditMode()) {\n return () => {};\n }\n\n const { store, storeId, keys, projection, debounce } = options;\n\n const reactionOptions: IReactionOptions<any, boolean> = {\n delay: debounce,\n name: `editor-sync(${storeId})`,\n };\n\n // Send the initial state to the editor\n let initialState: OUTPUT;\n if (keys) {\n const p = pick(store, Object.keys(keys));\n initialState = sanitizedToJS(p as unknown as OUTPUT);\n } else if (projection) {\n initialState = sanitizedToJS(projection(store));\n } else {\n initialState = sanitizedToJS(store as unknown as OUTPUT);\n }\n\n editorBridge.initializeEditorSyncedStore({\n storeId,\n initialState,\n });\n\n // Are we using selectors?\n if (projection) {\n // Re-evaluate projection for each key in each reaction:\n const initialProjection = projection(store);\n const projectionKeys = Object.keys(initialProjection);\n const createDisposer = (key: string) => {\n let lastValue: unknown;\n\n return reaction(\n () => {\n const currentProjection = projection(store);\n return sanitizedToJS(currentProjection[key as keyof OUTPUT]);\n },\n (value) => {\n const diffs = microPatches(lastValue, value, key);\n lastValue = value;\n const isSame = diffs.length === 0;\n if (!isSame) {\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch: diffs,\n });\n }\n },\n reactionOptions,\n );\n };\n\n const projectionDisposers = projectionKeys.reduce(\n (acc, key) => {\n const disposer = createDisposer(key);\n acc[key] = disposer;\n return acc;\n },\n {} as Record<string, IDisposer>,\n );\n // add a disposer for the keys of the entire projection\n const projectionKeysDisposer = reaction(\n () => Object.keys(projection(store)),\n (newKeys: string[]) => {\n const lastKeys = Object.keys(projectionDisposers);\n const deletedKeys = lastKeys.filter((key) => !newKeys.includes(key));\n const addedKeys = newKeys.filter((key) => !lastKeys.includes(key));\n\n // Add new keys\n addedKeys.forEach((key) => {\n projectionDisposers[key] = createDisposer(key);\n // send an initial patch to the editor to create the key\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch: {\n op: \"update\",\n path: [key],\n value: sanitizedToJS(projection(store)[key as keyof OUTPUT]),\n },\n });\n });\n\n // dispose of any keys that are no longer in the projection\n deletedKeys.forEach((key) => {\n projectionDisposers[key]();\n delete projectionDisposers[key];\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch: {\n op: \"remove\",\n path: [key],\n },\n });\n });\n },\n reactionOptions,\n );\n return () => {\n projectionKeysDisposer();\n Object.values(projectionDisposers).forEach((disposer) => disposer());\n };\n }\n\n // Get all computed keys, as they are not observable by deepObserve\n const keyArr = Object.keys(keys ?? (store as any));\n const computedKeys = keyArr.filter((key) => isComputedProp(store, key));\n const observableKeys = keyArr.filter((key) => !computedKeys.includes(key));\n const disposers: IDisposer[] = [];\n // Create a reaction for each computed key\n const computedDisposers = computedKeys.map((key) =>\n reaction(\n () => store[key as keyof STORE],\n (value) => {\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch: {\n op: \"update\",\n path: [key],\n value,\n },\n });\n },\n reactionOptions,\n ),\n );\n disposers.push(...computedDisposers);\n\n // We must deepObserve if there are non-computed keys,\n // We must also deepObserve if keys are NOT supplied, because new keys may be added\n const hasNonComputedKeys = observableKeys.length > 0;\n const userRestrictedToKeys = keys !== undefined;\n if (hasNonComputedKeys || !userRestrictedToKeys) {\n const deepDisposer = deepObserve(store, (change, pathStr) => {\n // Convert change to patch using utility function\n const patch = toMobXPatch(change, pathStr);\n if (keys && !keys[patch.path[0] as keyof OUTPUT]) {\n return;\n }\n\n // Post the patch along with the unique channelId.\n try {\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch,\n });\n } catch (error) {\n console.error(\n `[startEditorSync][${storeId}] Failed to send patch:`,\n error,\n );\n }\n });\n disposers.push(deepDisposer);\n }\n\n return () => {\n disposers.forEach((disposer) => disposer());\n };\n}\n","import type { ManagedProp } from \"../../../user-facing/properties-panel/props-builder\";\nimport type { EntityDefinition } from \"@superblocksteam/library-shared/props\";\n\nexport const analyzePropertyType = (\n propData: ManagedProp,\n prop: any,\n): EntityDefinition[\"props\"][string][\"dataType\"] => {\n let dataType: EntityDefinition[\"props\"][string][\"dataType\"];\n\n if (\n propData.dataType === \"composite\" &&\n prop &&\n typeof prop.getProps === \"function\"\n ) {\n const nestedProps = prop.getProps();\n const objectFields: Record<string, any> = {};\n\n // Recursively analyze nested properties\n for (const [key, nestedProp] of Object.entries(nestedProps)) {\n if (nestedProp && typeof (nestedProp as any).build === \"function\") {\n const nestedPropData = (nestedProp as any).build();\n if (nestedPropData && nestedPropData.isExternallyReadable) {\n const nestedAnalysis = analyzePropertyType(\n nestedPropData,\n nestedProp,\n );\n objectFields[key] = nestedAnalysis;\n }\n }\n }\n\n // If we have readable nested properties, use the object structure as the dataType\n if (Object.keys(objectFields).length > 0) {\n dataType = objectFields;\n }\n } else if (propData.dataType === \"dimension\") {\n dataType = {\n mode: \"string\", // \"px\" | \"fit\" | \"fill\" | \"%\" | \"columns\" | \"rows\"\n value: \"number\", // Optional numeric value\n };\n } else if (propData.dataType === \"event\") {\n dataType = \"function\";\n } else if (\n propData.dataType === \"string\" ||\n propData.dataType === \"number\" ||\n propData.dataType === \"boolean\" ||\n propData.dataType === \"array\" ||\n propData.dataType === \"function\"\n ) {\n dataType =\n propData.dataType as EntityDefinition[\"props\"][string][\"dataType\"];\n } else {\n dataType = \"unknown\";\n }\n\n return dataType;\n};\n","import { makeAutoObservable } from \"mobx\";\nimport { startEditorSync } from \"../../../../edit-mode/mobx-sync/mobx-editor-sync.js\";\nimport { RECORD_PATH_IDENTIFIER } from \"../../../user-facing/properties-panel/create-managed-props-list.js\";\nimport { analyzePropertyType } from \"./type-defs-utils.js\";\nimport type {\n ManagedPropsList,\n PropertiesDefinition,\n} from \"../../../user-facing/properties-panel/props-builder.js\";\nimport type { EditorTemplate } from \"../../sb-wrapper.jsx\";\nimport type { RootStore } from \"../root-store.js\";\nimport type { EntityDefinition } from \"@superblocksteam/library-shared/props\";\nimport type {\n Catalog,\n ComponentRegistryShareState,\n CatalogWithInternalDetails,\n EditorConfig,\n EntityCallableFunction,\n} from \"@superblocksteam/library-shared/types\";\nimport type * as React from \"react\";\n\nexport type Type = {\n isSb: symbol;\n sbType: string;\n isDroppable?: boolean;\n propertiesDefinition?: PropertiesDefinition;\n catalog?: Catalog;\n description?: string;\n} & React.ComponentType<any>;\n\nexport type DefaultTagNames = {\n container: string;\n button: string;\n text: string;\n};\n\n/**\n * TODO: The component registry could be split into two a thin layer always on, and move some stuff to the EditStore.\n * Some of the actions (rename, delete) and some of the data (isDroppable) are editor-only.\n */\nexport class ComponentRegistry implements ComponentRegistryShareState {\n private _typeRegistry = new Map<string, Type>();\n private _customComponentRegistry = new Map<string, Type>();\n private _managedPropsRegistry = new Map<string, ManagedPropsList>();\n private _internalPropsRegistry = new Map<\n string,\n Array<{ path: string; factory: () => any }>\n >();\n private _editorTemplatesRegistry = new Map<\n string,\n Array<EditorTemplate<any>>\n >();\n private _editorConfigsRegistry = new Map<string, EditorConfig>();\n private _defaultContainerType: string | undefined;\n private _defaultButtonType: string | undefined;\n private _defaultTextType: string | undefined;\n\n constructor(readonly rootStore: RootStore) {\n makeAutoObservable(this);\n\n startEditorSync({\n store: this,\n storeId: \"component-registry\",\n keys: {\n customComponentList: true,\n libraryComponentCatalogs: true,\n libraryComponentEditorConfigs: true,\n entityDefinitions: true,\n componentsWithCallFunctions: true,\n },\n });\n }\n\n addType(type: string, component: Type) {\n this._typeRegistry.set(type, component);\n }\n\n addCustomComponent(type: string, component: Type) {\n this._customComponentRegistry.set(type, component);\n }\n\n deleteCustomComponent(type: string) {\n this._customComponentRegistry.delete(type);\n this._managedPropsRegistry.delete(type);\n this._editorTemplatesRegistry.delete(type);\n }\n\n renameCustomComponent(oldName: string, newName: string) {\n const component = this._customComponentRegistry.get(oldName);\n const managedProps = this._managedPropsRegistry.get(oldName);\n\n if (component) {\n this._customComponentRegistry.set(newName, component);\n this._customComponentRegistry.delete(oldName);\n\n if (managedProps) {\n this._managedPropsRegistry.set(newName, managedProps);\n this._managedPropsRegistry.delete(oldName);\n }\n }\n }\n\n addManagedProps(type: string, props: ManagedPropsList) {\n this._managedPropsRegistry.set(type, props);\n }\n\n deleteManagedProps(type: string) {\n this._managedPropsRegistry.delete(type);\n }\n\n addEditorTemplate(type: string, template: EditorTemplate<any>) {\n const existingTemplates = this._editorTemplatesRegistry.get(type) ?? [];\n if (\n existingTemplates.some(\n (t) =>\n t.catalog?.displayName === template.catalog?.displayName &&\n t.catalog?.category === template.catalog?.category,\n )\n ) {\n return;\n }\n this._editorTemplatesRegistry.set(type, [...existingTemplates, template]);\n }\n\n getEditorTemplates(type: string) {\n return this._editorTemplatesRegistry.get(type);\n }\n\n addEditorConfig(type: string, config: EditorConfig) {\n if (config.useAs) {\n if (config.useAs.defaultContainer) {\n this._defaultContainerType = type;\n }\n if (config.useAs.defaultButton) {\n this._defaultButtonType = type;\n }\n if (config.useAs.defaultText) {\n this._defaultTextType = type;\n }\n }\n this._editorConfigsRegistry.set(type, config);\n }\n\n addInternalProps(\n type: string,\n props: Array<{ path: string; factory: () => any }>,\n ) {\n this._internalPropsRegistry.set(type, props);\n }\n\n getInternalProps(type: string): Array<{ path: string; factory: () => any }> {\n return this._internalPropsRegistry.get(type) ?? [];\n }\n\n getEditorConfig(type: string) {\n return this._editorConfigsRegistry.get(type);\n }\n\n get entityDefinitions(): Record<string, EntityDefinition> {\n const entityDefinitions: Record<string, EntityDefinition> = {};\n\n for (const [componentType, componentData] of [\n ...this._typeRegistry.entries(),\n ...this._customComponentRegistry.entries(),\n ]) {\n const propertiesDefinition = componentData.propertiesDefinition;\n\n if (!propertiesDefinition) {\n continue;\n }\n\n const entityDefinition: EntityDefinition = {\n description: this.getEditorConfig(componentType)?.description,\n props: {},\n };\n for (const section of Object.values(propertiesDefinition)) {\n for (const [propKey, prop] of Object.entries(section.props)) {\n const propData = prop.build();\n if (propData && propData.isExternallyReadable) {\n const dataType = analyzePropertyType(propData, prop);\n\n const entityDefEntry: EntityDefinition[\"props\"][string] = {\n label: propData.docs?.label,\n description: propData.docs?.description,\n isSettable: propData.isExternallySettable,\n priority: propData.docs?.priority,\n dataType,\n };\n\n entityDefinition.props[propKey] = entityDefEntry;\n }\n }\n }\n\n entityDefinitions[componentType] = entityDefinition;\n }\n\n return entityDefinitions;\n }\n\n get libraryComponentCatalogs() {\n return Array.from(this._editorTemplatesRegistry.entries()).flatMap(\n ([componentType, templates]) => {\n return templates.reduce((acc, template) => {\n const catalog = template.catalog;\n if (catalog) {\n return [\n ...acc,\n {\n ...catalog,\n componentType,\n },\n ];\n }\n return acc;\n }, [] as Array<CatalogWithInternalDetails>);\n },\n );\n }\n\n get libraryComponentEditorConfigs() {\n return Object.fromEntries(this._editorConfigsRegistry.entries());\n }\n\n get customComponentList(): string[] {\n return Array.from(this._customComponentRegistry.keys());\n }\n\n get containerTypes() {\n // TODO - if we support more of these, add them here\n return new Set([this.defaultTagNames.container]);\n }\n\n get defaultTagNames(): DefaultTagNames {\n if (!this._defaultContainerType) {\n console.warn(\n \"No default container registered - defaulting to 'Container'.\",\n );\n }\n if (!this._defaultButtonType) {\n console.warn(\"No default button registered - defaulting to 'Button'.\");\n }\n if (!this._defaultTextType) {\n console.warn(\"No default text registered - defaulting to 'Text'.\");\n }\n return {\n container: this._defaultContainerType ?? \"Container\",\n button: this._defaultButtonType ?? \"Button\",\n text: this._defaultTextType ?? \"Text\",\n };\n }\n\n get managedPropsRegistry() {\n return this._managedPropsRegistry;\n }\n\n getManagedProps(type: string): ManagedPropsList {\n return this._managedPropsRegistry.get(type) ?? [];\n }\n\n getComponent(type: string): Type | undefined {\n return (\n this._typeRegistry.get(type) ?? this._customComponentRegistry.get(type)\n );\n }\n\n /**\n * Get the property path with the record identifier if it exists. For example,\n * `columns.columnName.label` becomes `columns.*.label`, for record properties.\n */\n getPropertyWithRecordIdentifier(type: string, path: string) {\n const managedProps = this.getManagedProps(type);\n const splitPath = path.split(\".\");\n if (splitPath.length === 1) {\n return path;\n }\n const [parentKey, _maybeTheRecordKey, ...rest] = splitPath;\n\n for (const prop of managedProps) {\n // we don't always have a managed prop for the parent, only leafs\n if (\n prop.path.startsWith(parentKey) &&\n prop.path.includes(RECORD_PATH_IDENTIFIER) &&\n rest.length > 0 &&\n prop.path.endsWith(rest.join(\".\"))\n ) {\n return [parentKey, RECORD_PATH_IDENTIFIER, rest.join(\".\")].join(\".\");\n }\n }\n return path;\n }\n\n get componentsWithCallFunctions(): Record<string, EntityCallableFunction[]> {\n return Object.fromEntries(\n Array.from(this.managedPropsRegistry.entries())\n .filter(([_, props]) => {\n return props.some((prop) => prop.isFunctionProp);\n })\n .map(([type, props]) => {\n return [\n type,\n props\n .filter((prop) => prop.isFunctionProp && prop.hasActionPanel)\n .map((prop) => ({\n functionName: prop.path,\n label: prop.docs?.label,\n priority: prop.docs?.priority,\n })),\n ];\n })\n .filter(([_, props]) => props.length > 0),\n );\n }\n}\n","import { get, set } from \"lodash\";\nimport { action, makeObservable, observable } from \"mobx\";\nimport type { IEntityManager } from \"../evaluator/base-entity-manager.js\";\nimport type { Name } from \"../evaluator/names.js\";\nimport type {\n SbElement,\n SbInstance,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const DEFAULT_ANONYMOUS_SOURCE_ID: SbElement = \"SB--anon-src\";\n\nexport type IdentifierInfo = {\n sourceId: SbElement;\n name: Name;\n type: string;\n instanceId: SbInstance;\n scopeId: string;\n};\n\nexport class NameManager {\n private _mountedIdentifiers: Record<SbInstance, IdentifierInfo> = {};\n private _allPossibleIdentifiers: Record<SbInstance, IdentifierInfo> = {};\n private _scopeToNameToIdentifiers: Record<\n string,\n Record<string, Record<SbInstance, IdentifierInfo>>\n > = {};\n private _allNamesToIdentifiers: Record<\n string,\n Record<SbInstance, IdentifierInfo>\n > = {};\n\n private _prefixAllocation: Record<\n string,\n {\n usedIndices: Set<number>;\n guaranteedIndex: number;\n optimisticIndex: number | null;\n }\n > = {};\n private _instanceIdToPrefixInfo: Record<\n SbInstance,\n {\n prefix: string;\n index: number;\n }\n > = {};\n\n constructor(readonly entityManager: IEntityManager) {\n makeObservable<\n NameManager,\n | \"_mountedIdentifiers\"\n | \"_allPossibleIdentifiers\"\n | \"_scopeToNameToIdentifiers\"\n | \"_allNamesToIdentifiers\"\n >(this, {\n _mountedIdentifiers: observable,\n _allPossibleIdentifiers: observable,\n _scopeToNameToIdentifiers: observable,\n _allNamesToIdentifiers: observable,\n registerIdentifier: action,\n unregisterIdentifier: action,\n registerAndGetIdentifiers: action,\n changeWidgetName: action,\n });\n }\n\n get scopeToNameToIds(): Record<\n string,\n Record<string, Record<SbInstance, IdentifierInfo>>\n > {\n return this._scopeToNameToIdentifiers;\n }\n\n getWidgetName(instanceId: SbInstance): undefined | Name {\n const identifier = this._mountedIdentifiers[instanceId];\n return identifier?.name;\n }\n\n // TODO this should work by having vite send us a list of all known static names, so we don't rely on what's mounted\n hasEntityWithName(name: string) {\n return Object.keys(this._allNamesToIdentifiers[name] ?? {}).length > 0;\n }\n\n hasDuplicateNames(scopeId: string, name: string) {\n return this.getSharedNameCount(scopeId, name) > 1;\n }\n\n private nextNameAndIdForCombination(params: {\n sourceId: SbElement;\n scopeId: string;\n name?: string;\n rootId?: SbInstance; // For edit mode only\n }): {\n name: Name;\n instanceId: SbInstance;\n } {\n const instancePrefix = params.rootId\n ? `${params.sourceId}-${params.scopeId}-${params.rootId}`\n : `${params.sourceId}-${params.scopeId}`;\n\n this._prefixAllocation[instancePrefix] ??= {\n usedIndices: new Set(),\n guaranteedIndex: 0,\n optimisticIndex: null,\n };\n const allocation = this._prefixAllocation[instancePrefix];\n let order = allocation.guaranteedIndex;\n if (\n allocation.optimisticIndex != null &&\n !allocation.usedIndices.has(allocation.optimisticIndex)\n ) {\n order = allocation.optimisticIndex;\n if (allocation.optimisticIndex + 1 >= allocation.guaranteedIndex) {\n allocation.optimisticIndex = null;\n } else {\n allocation.optimisticIndex += 1;\n }\n } else {\n order = allocation.guaranteedIndex;\n allocation.guaranteedIndex += 1;\n }\n\n allocation.usedIndices.add(order);\n\n const instanceStr = `${instancePrefix}-${order}`; // TODO fast hash this if it gets too long\n const instanceId: SbInstance = `I-${instanceStr}`;\n\n this._instanceIdToPrefixInfo[instanceId] = {\n prefix: instancePrefix,\n index: order,\n };\n\n const name = {\n value: params.name == null ? `anon-${instanceId}` : params.name,\n isAnonymous: params.name == null,\n __isName: true,\n } as Name;\n return {\n name,\n instanceId,\n };\n }\n\n // idempotent\n private trackIdentifier(identifier: IdentifierInfo) {\n const { scopeId, instanceId, name } = identifier;\n set(\n this._scopeToNameToIdentifiers,\n [scopeId, name.value, instanceId],\n identifier,\n );\n set(this._allNamesToIdentifiers, [name.value, instanceId], identifier);\n\n this._mountedIdentifiers[instanceId] = identifier;\n }\n\n // idempotent\n private untrackIdentifier(instanceId: SbInstance) {\n const identifier = this._mountedIdentifiers[instanceId];\n if (!identifier) {\n return;\n }\n const { scopeId, name } = identifier;\n if (\n get(this._scopeToNameToIdentifiers, [scopeId, name.value, instanceId])\n ) {\n delete this._scopeToNameToIdentifiers[scopeId][name.value][instanceId];\n }\n if (get(this._allNamesToIdentifiers, [name.value, instanceId])) {\n delete this._allNamesToIdentifiers[name.value][instanceId];\n }\n delete this._mountedIdentifiers[instanceId];\n\n const prefixInfo = this._instanceIdToPrefixInfo[instanceId];\n if (prefixInfo) {\n const allocation = this._prefixAllocation[prefixInfo.prefix];\n if (allocation) {\n allocation.usedIndices.delete(prefixInfo.index);\n if (allocation.usedIndices.size === 0) {\n delete this._prefixAllocation[prefixInfo.prefix];\n } else if (\n allocation.optimisticIndex == null ||\n allocation.optimisticIndex > prefixInfo.index\n ) {\n allocation.optimisticIndex = prefixInfo.index;\n }\n }\n delete this._instanceIdToPrefixInfo[instanceId];\n }\n }\n\n registerIdentifier(identifier: IdentifierInfo) {\n this.trackIdentifier(identifier);\n }\n\n unregisterIdentifier(instanceId: SbInstance) {\n this.untrackIdentifier(instanceId);\n }\n\n getExistingIdentifier(instanceId: SbInstance) {\n const identifier = this._allPossibleIdentifiers[instanceId];\n if (!identifier) {\n console.log(`No identifier found for instanceId ${instanceId}`);\n return undefined;\n }\n return identifier;\n }\n\n registerAndGetIdentifiers(params: {\n sourceId: SbElement | undefined;\n name: string | undefined;\n scopeId: string;\n rootId?: SbInstance;\n type: string;\n existingInstanceId?: SbInstance;\n }): IdentifierInfo {\n const {\n sourceId = DEFAULT_ANONYMOUS_SOURCE_ID,\n scopeId,\n rootId,\n existingInstanceId,\n type,\n } = params;\n if (existingInstanceId) {\n const identifier = this.getExistingIdentifier(existingInstanceId);\n if (identifier) {\n return identifier;\n }\n }\n\n const { name, instanceId } = this.nextNameAndIdForCombination({\n sourceId,\n scopeId,\n rootId,\n name: params.name,\n });\n if (this._mountedIdentifiers[instanceId]) {\n return this._mountedIdentifiers[instanceId];\n }\n\n const identifier: IdentifierInfo = {\n sourceId,\n name,\n instanceId,\n scopeId,\n type,\n };\n\n this._allPossibleIdentifiers[instanceId] = identifier;\n return identifier;\n }\n\n private getSharedNameCount(scopeId: string, name: string) {\n return Object.keys(this._scopeToNameToIdentifiers[scopeId]?.[name] ?? {})\n .length;\n }\n\n changeWidgetName(\n instanceId: SbInstance,\n _newName?: string,\n ): IdentifierInfo | null {\n const existingIdentifier = this._mountedIdentifiers[instanceId];\n if (!existingIdentifier) {\n return null;\n }\n\n const existingNameCount = this.getSharedNameCount(\n existingIdentifier.scopeId,\n existingIdentifier.name.value,\n );\n\n const newName = _newName == null ? `anon-${instanceId}` : _newName;\n\n const name = {\n value: newName,\n isAnonymous: newName == null,\n __isName: true,\n } as Name;\n\n const newIdentifier = {\n ...existingIdentifier,\n name,\n };\n this.untrackIdentifier(existingIdentifier.instanceId);\n this.trackIdentifier(newIdentifier);\n\n this.entityManager.renameEntity({\n scopeId: existingIdentifier.scopeId,\n instanceId: existingIdentifier.instanceId,\n newName: name,\n isDuplicate: existingNameCount > 1,\n });\n\n return newIdentifier;\n }\n}\n","import { action, makeObservable } from \"mobx\";\nimport { observable } from \"mobx\";\nimport { LocationStore } from \"../location-store.js\";\nimport { EntityManager, GLOBAL_SCOPE_ID } from \"./evaluator/entity-manager.js\";\nimport { getName } from \"./evaluator/names.js\";\nimport ApiManager from \"./features/api-store.js\";\nimport { ComponentRegistry } from \"./features/component-registry.js\";\nimport { NameManager } from \"./features/name-manager.js\";\nimport type { IEntityManager } from \"./evaluator/base-entity-manager.js\";\nimport type { EditStore } from \"../../../edit-mode/edit-store.js\";\n\nclass RootStore {\n apis: ApiManager;\n nameManager: NameManager;\n entityManager: IEntityManager;\n componentRegistry: ComponentRegistry;\n\n editStore?: EditStore;\n locationStore: LocationStore;\n\n currentPageScopeId: string | undefined;\n applicationId: string | undefined;\n userId: string | undefined;\n\n windowOriginUrl: string | undefined;\n\n private editorRegisteredCallbacks: (() => void)[] = [];\n\n private apisLoaded = false;\n private appLoadedCallbacks: (() => void)[] = [];\n private pageLoadedCallbacks = new Map<string, (() => void)[]>();\n\n constructor() {\n this.apis = new ApiManager(this);\n this.componentRegistry = new ComponentRegistry(this);\n this.entityManager = new EntityManager(this.componentRegistry, {\n devtools: true,\n });\n this.nameManager = new NameManager(this.entityManager);\n\n this.locationStore = new LocationStore(this);\n\n this.entityManager.createEntity({\n name: getName(\"Global\"),\n type: \"global\",\n props: {},\n scopeId: GLOBAL_SCOPE_ID,\n });\n\n makeObservable(this, {\n editStore: observable.shallow,\n setEditStore: action,\n\n applicationId: observable,\n userId: observable,\n });\n }\n\n setEditStore(editStore: EditStore) {\n if (this.editStore) return;\n this.editStore = editStore;\n this.editorRegisteredCallbacks.forEach((fn) => fn());\n this.editorRegisteredCallbacks = [];\n }\n\n // TODO: this is temporary until we have a method to ensure the editor is registered as soon as possible, i.e. before iframe messages\n onEditorRegistered(fn: () => void) {\n this.editorRegisteredCallbacks.push(fn);\n }\n\n /**\n * There is a timing problem here between when the APIs are registered and when the scope entities are registered.\n * Regardless of which one is done first, we need to wait for both before firing page load actions\n */\n setApisLoaded() {\n this.apisLoaded = true;\n this.fireAppLoadedCallbacks();\n if (this.currentPageScopeId) {\n this.firePageLoadedCallbacks(this.currentPageScopeId);\n }\n }\n\n fireAppLoadedCallbacks() {\n if (!this.apisLoaded) return;\n\n for (const fn of this.appLoadedCallbacks) {\n fn();\n }\n }\n\n onAppLoaded(fn: () => void) {\n this.appLoadedCallbacks.push(fn);\n return () => {\n this.appLoadedCallbacks.filter((cb) => cb !== fn);\n };\n }\n\n firePageLoadedCallbacks(scopeId: string) {\n if (!this.apisLoaded) {\n return;\n }\n\n this.pageLoadedCallbacks.get(scopeId)?.forEach((fn) => fn());\n }\n\n onPageLoaded(scopeId: string, fn: () => void) {\n const callbacks = this.pageLoadedCallbacks.get(scopeId) || [];\n callbacks.push(fn);\n this.pageLoadedCallbacks.set(scopeId, callbacks);\n return () => {\n this.pageLoadedCallbacks.set(\n scopeId,\n callbacks.filter((cb) => cb !== fn),\n );\n };\n }\n\n get isApisLoaded() {\n return this.apisLoaded;\n }\n}\n\nexport type { RootStore };\nexport default new RootStore();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAgB,eAA0B;AACxC,KACE,CAAC,OAAO,+BACR,CAAC,OAAO,4BAA4B,cAEpC,OAAM,IAAI,MAAM,4BAA4B;AAE9C,QAAQ,OAAe;;;;;ACdzB,MAAM,sBAAsB;AAE1B,QADiB,OAAe,kBACb;;AAGrB,IAAIA;AAEJ,MAAa,mBAAmB;AAC9B,KAAI,aAAa,OACf,YAAW,eAAe;AAE5B,QAAO;;;;;ACTT,MAAa,kBAAkB,QAAa;AAC1C,QACE,QACC,IAAI,aAAa,OAAO,IAAI,gBAAgB,IAC1C,OAAO,SAAS,eAAe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