import { Callback, ControlType, DataType, DataTypeString, EntityDefinition, HeaderType, PropertiesPanelDisplay, PropertyForData, PropsCategory, Relation, WidgetPropertyDefinition } from "@superblocksteam/library-shared/props"; import { DataRouter, Location, Params } from "react-router"; import { EditorConfig, EvaluateOrValueComputedArgs, Property, TailwindPropertyKey } from "@superblocksteam/library-shared"; import * as React$2 from "react"; import React$1, { ReactNode, createElement } from "react"; import { OrchestratorViewMode, PlaceholderInfo, Profile } from "@superblocksteam/shared"; import { AiContextMode, AppToEditorMessage, Catalog, ComponentRegistryShareState, ConsoleLogEntry, CreateChild, CreateChild as CreateChild$1, DeleteMeLibraryApi, EditorConfig as EditorConfig$1, Entity, EntityOutputProp, ExecutionTimingBreakdown, InitData, InteractionMode, LoadErrorMessageTypesMap, PayloadAction, PropertyInfo, RuntimeErrorData, SbApiRunOptions, SbElement, SbSelector, SourceLocation, UrlState, ViteMessage, ViteMessageKind, WithBindingIdentifier } from "@superblocksteam/library-shared/types"; import * as _$react_jsx_runtime0 from "react/jsx-runtime"; import { CompiledApi, IntegrationDeclaration } from "@superblocksteam/sdk-api"; import { Graph } from "@dagrejs/graphlib"; import { XYCoord } from "react-dnd"; //#region src/lib/internal-details/scope/types.d.ts declare const AppMode: { readonly EDIT: "EDIT"; readonly PUBLISHED: "PUBLISHED"; readonly PREVIEW: "PREVIEW"; }; type AppMode = (typeof AppMode)[keyof typeof AppMode]; //#endregion //#region src/lib/internal-details/superblocks-context.d.ts type User = { name: string; email: string; id: string; groups: Group[]; username: string; metadata: Record; }; type Group = { id: string; name: string; size: number; }; /** * A data tag (formerly "profile") representing a data segment such as Staging or Production. * * Key fields: * - `key` — unique identifier, pass to `setDataTag()` * - `displayName` — human-readable label for UI display (there is no `name` field) * - `description` — optional description of the tag * - `type` — `"RESERVED"` or `"CUSTOM"` */ type DataTag = Profile; type DataTags = { available: DataTag[]; selected?: DataTag; default: DataTag; }; /** @deprecated Use DataTags instead */ type Profiles = DataTags; declare class SuperblocksAppContext { private context?; constructor(); get user(): User | undefined; get groups(): Group[] | undefined; get selectedProfile(): Profile | undefined; get profiles(): DataTags | undefined; setProfile(profileKey: string): void; updateContext(context: Partial): void; getGlobal(): { user?: User; groups?: Group[]; selectedProfileId?: string; profiles?: Profiles; viewMode?: any; app?: { id: string; name: string; }; } | undefined; } declare function useSuperblocksUser(): User | undefined; declare function useSuperblocksGroups(): Group[] | undefined; declare function useSuperblocksDataTags(): { dataTags: DataTags | undefined; setDataTag: (dataTagKey: string) => void; }; /** @deprecated Use useSuperblocksDataTags instead */ declare function useSuperblocksProfiles(): { profiles: DataTags | undefined; setProfile: (dataTagKey: string) => void; }; declare function getAppMode(): AppMode | undefined; //#endregion //#region src/lib/user-facing/sb-provider.d.ts declare const SbProvider: ({ name, children, className, context }: { name?: string; children?: React$1.ReactNode; className?: string; context?: SuperblocksAppContext; }) => _$react_jsx_runtime0.JSX.Element; //#endregion //#region src/lib/internal-details/lib/evaluator/entity-types.d.ts type SingleInputProp = T extends Callback ? Callback : T; type NestedInputProp = T extends object ? { [K in keyof T]: SingleInputProp | NestedInputProp } : never; type InputProp = SingleInputProp | NestedInputProp; type EntityFunction = (this: Entity, ...ARGS: ARGS) => R; //#endregion //#region src/edit-mode/runtime-graph/types.d.ts type ComponentNode = { selectorId: SbSelector; sourceId: SbElement; type: any; isSbComponent: boolean; isHtmlElement: boolean; noSelect?: boolean; firstRenderedTag: SbSelector | undefined; nearestSelectableAncestor: SbSelector | undefined; displayName: string; }; //#endregion //#region src/edit-mode/features/runtime-tracking-store.d.ts declare class RuntimeTrackingStore { readonly editStore: EditStore | undefined; constructor(editStore: EditStore | undefined); private graph; private jsxNodes; private sourceNodes; private disabledComponents; registerComponent(selectorId: SbSelector, params: { sourceId: SbElement; type: any; parentSelectorId?: SbSelector; isSbComponent: boolean; isHtmlElement: boolean; noSelect?: boolean; }): void; getDisplayName(selectorId: SbSelector): string; unregisterComponent(selectorId: SbSelector): void; getFirstAnchorableTag(selectorId: SbSelector): SbSelector | undefined; getNearestSelectableAncestor(selectorId: SbSelector, skipSelf?: boolean): SbSelector | undefined; setComponentDisabled(selectorId: SbSelector, disabled: boolean): void; getComponent(selectorId: SbSelector): ComponentNode | undefined; getComponentParent(selectorId: SbSelector): SbSelector; getComponentChildren(selectorId: SbSelector): SbSelector[]; getSelectorIdsForSourceId(sourceId: SbElement): Set; getSourceId(selectorId: SbSelector): SbElement | undefined; getClosestAncestorByType(selectorId: SbSelector, type: string): SbSelector | undefined; hasRenderedNodes(): boolean; getDisabledComponents(): SbSelector[]; /** * Given a selectorId that represents a DOM element, walks up the component tree * to find the outermost component whose firstRenderedTag matches this selectorId. * This is used to select the component when clicking on its root DOM element. * * IMPORTANT: This only returns a component if the anchorSelectorId is the IMMEDIATE parent * of the component (i.e., the component doesn't have any intermediate nodes between itself * and the anchor). This prevents inner HTML elements from being treated as component roots. * * Registered components win, outermost first. If none match, the nearest * unregistered component is used, so plain components (for example shadcn files * without registerComponent) stay targetable without wrappers stealing selection. * * Returns undefined if no component has this as its firstRenderedTag. */ getOutermostComponentForFirstRenderedTag(anchorSelectorId: SbSelector): SbSelector | undefined; } //#endregion //#region src/edit-mode/features/ai-store.d.ts declare class AiManager { private readonly runtimeTrackingStore; private _isTaggingEnabled; private _isEditing; private _editingComponents; private _contextMode; private _targetedComponents; private _targetedSelectors; private _hasHadSuccessfulBuild; private _hasEverHadSuccessfulBuild; constructor(runtimeTrackingStore: RuntimeTrackingStore); getIsTaggingEnabled(): boolean; getIsEditing(): boolean; getShouldShowLoader(): boolean; setIsTaggingEnabled(isTaggingEnabled: boolean): void; getAiContextMode(): AiContextMode; shouldToggleComponentInAiContext(): boolean; getTargetedComponents(): `SB-${string}`[]; getTargetedSelectors(): `S-${string}`[]; isEditingComponent(id: SbElement): boolean; isTargetingComponent(id: SbElement): boolean; startEditing(): void; setEditingComponents(components: SbElement[]): void; finishEditing(): void; setAiContextMode(mode: AiContextMode, components?: { id: SbElement; selectorId?: SbSelector; }[]): void; addTargetedSelector(selectorId: SbSelector): void; toggleTargetedSelector(selectorId: SbSelector): void; isTargetedSelector(selectorId: SbSelector): boolean; /** * Returns true if we are targeting a different selector of the same source id, since in some cases we want to keep * the same source targeted, but just highlight another selector of it */ isAlternateSourceIdTarget(sourceId: SbElement, selectorId: SbSelector): boolean; handleRuntimeError(data: RuntimeErrorData): void; clearRuntimeError(id: string): void; markFirstBuildSuccess(): void; private notifyLoaderState; private removeAllSharedSelectors; private removeAllSelectorsForSource; } //#endregion //#region src/edit-mode/features/connection-manager.d.ts type ConnectionStatus = "pre-init" | "disconnected" | "connecting" | "connected"; declare class ConnectionManager { connectionStatus: ConnectionStatus; constructor(); initializeSocket(): void; connect(): void; disconnect(): void; } //#endregion //#region src/edit-mode/features/operation-store.d.ts declare class OperationManager { ensureFilesSynced(): Promise; } //#endregion //#region src/edit-mode/features/ui-store.d.ts declare class UIStore { readonly root: RootStore; readonly editStore: EditStore; private _selectedSourceIds; private _selectedSelectorIds; private _focusedSelectorId; private _rootInstanceData; private newComponentSelectPromise; constructor(root: RootStore, editStore: EditStore); getMostRelevantSelectorIdsForSourceId(sourceId: SbElement): SbSelector[]; isSourceSelected(sourceId: SbElement): boolean; getSelectedSourceIds(): SbElement[]; getSelectedSelectorIds(): SbSelector[]; private get focusedSelectorId(); getFocusedSourceId(): SbElement | null; getFocusedSelectorId(): SbSelector | null; setSelectedSourceIds(sourceIds: SbElement[]): void; setSelectedSelectorIds(selectorIds: SbSelector[]): void; setFocusedIds(selectorId: SbSelector | null): void; selectSource(sourceId: SbElement): void; selectWidget(selectorId: SbSelector | null, _addToSelection?: boolean): void; /** * This is cursed because component selection actually needs to be done by instance ids, but * instance IDs are only guaranteed to be stable after the component is rendered, while source IDs * are assigned by the source tracker. * * If _any_ other selection comes in before we select something, we will cancel this reaction */ selectNewComponentBySourceId(sourceId: SbElement, selectorIdsToIgnore?: Set<`S-${string}`>): Promise; } //#endregion //#region src/edit-mode/edit-store.d.ts declare global { interface Window { _SB_ENABLE_SESSION_RECORDING?: boolean; __SUPERBLOCKS_EDITOR_HOOK__: InstanceType; } } declare class EditStore { ui: UIStore; operationManager: OperationManager; runtimeTrackingStore: RuntimeTrackingStore; connectionManager: ConnectionManager; ai: AiManager; isInitialized: boolean; recordingInitialized: boolean; interactionMode: InteractionMode; lastInteractionMode: InteractionMode; private viteMessageListeners; constructor(rootStore: RootStore); setIsInitialized(isInitialized: boolean): void; setInteractionMode(mode: InteractionMode, notifyEditor?: boolean): void; onViteMessage>(kind: T, callback: (message: Message) => void): () => void; triggerViteMessage>(kind: T, message: Message): void; startRecording(recording: { userId: string; appId: string; sessionRecordingKey: string; }): void; } //#endregion //#region src/lib/internal-details/lib/types.d.ts type ExecutionError = { name?: string; message: string; formPath: string; blockPath: string; handled?: boolean; }; type ExecutionEventRequest = { summary: string; metadata: { placeHoldersInfo?: Record; }; }; type Resolutions = Record; type ExecutionEvent = { name: string; type: string; timestamp: string; start?: Record; end?: { performance?: { start: string | number; finish: string | number; total: string | number; execution: string | number; overhead: string | number; }; error?: ExecutionError; output?: { result?: any; request?: string; requestV2?: ExecutionEventRequest; stdout?: Array; stderr?: Array; }; resolved?: Resolutions; }; parent: string; }; interface StreamEvent { result: { event: ExecutionEvent; execution: string; }; } type RouteInfo = Omit; /** * Schema representation for SDK API input/output/chunk schemas. * Contains both TypeScript and JSON Schema formats for display in the UI. */ interface SdkApiSchemaInfo { /** TypeScript type string representation, e.g., "{ userId: string; limit?: number }" */ typescript: string; /** JSON Schema representation for the schema */ jsonSchema: object; } /** * Metadata for an SDK API, sent from the library to ui-code-mode * when an SDK API is registered. */ interface SdkApiMetadata { /** Unique name of the API */ name: string; /** Plain-language summary of what this API does */ description?: string; /** Input schema information */ inputSchema: SdkApiSchemaInfo; /** Output schema information (for non-streaming APIs) */ outputSchema?: SdkApiSchemaInfo; /** Chunk schema information (for streaming APIs) */ chunkSchema?: SdkApiSchemaInfo; /** Whether this is a streaming API */ isStreaming: boolean; /** Declared integrations for this API */ integrations: Array<{ /** Key used in the API code to reference this integration */key: string; /** Plugin ID (e.g., "postgres", "slack") */ pluginId: string; /** Integration name (e.g., "Production Postgres") */ name: string; /** Integration ID (UUID) */ id: string; }>; /** Entry point file path relative to app root (e.g. "server/apis/GetUsers/api.ts") */ entryPoint?: string; /** Original export name in the source file (set for named exports, undefined for default exports) */ exportName?: string; /** TypeScript source code of the API */ sourceCode?: string; } type RouteChangePayload = Omit; type AiUpdatesPayload = { parentToChild: { type: "start-editing"; components?: SbElement[]; } | { type: "finish-editing"; } | { type: "update-editing-entities"; components: SbElement[]; } | { type: "set-ai-context-mode"; mode: AiContextMode; components?: { id: SbElement; selectorId?: SbSelector; }[]; } | { type: "set-tagging-enabled"; isTaggingEnabled: boolean; }; childToParent: { type: "add-component-to-context"; component: SbElement; label?: string; selectorId?: SbSelector; } | { type: "toggle-component-in-context"; component: SbElement; label?: string; selectorId: SbSelector; } | { type: "set-ai-context-mode"; mode: AiContextMode; } | { type: "ai-generate"; prompt: string; } | { type: "loader-state"; shouldShowLoader: boolean; }; }; /** * Lightweight agent metadata sent from parent to library. * Allows the library to locally filter agents by profile, * eliminating the async round-trip when profiles change. */ type AgentInfo = { url: string; tags: Record; environment: string; }; /** Profile metadata sent between parent and library for orchestrator API calls. */ type SdkProfileInfo = { id: string; name: string; key: string; }; /** * Why the app preview is (or isn't) ready for a screenshot, in increasing * readiness: * - "not-rendered": app shell (`sb-provider-root`) absent — preview hasn't * mounted (e.g. still building or migrating). Nothing meaningful to capture; * NOT a visual verdict. * - "loading": shell exists but page still loading (full-page spinner or other * significant loading indicators). Capturing is useful so the agent can see * the loading state and retry. * - "not-found": shell exists but the current route rendered the Superblocks * not-found page. This is a verification failure, not a useful screenshot. * - "ready": shell exists, no spinner or loading indicators. */ type ScreenshotReadyReason = "ready" | "loading" | "not-rendered" | "not-found"; /** * What the screenshot is for, which decides the output limits: * - "model": sized for the vision API (2000px edge, 256KB). * - "checkpoint": a stored version preview, shown at device resolution and * expanded full screen, so it keeps the retina pixels and a larger budget. */ type ScreenshotPurpose = "checkpoint" | "model"; /** * How much resolution budget a "model"-purpose capture spends. Ignored for * "checkpoint" captures, which have their own fixed limits (APPS-5714). * * "low" (default): a cheap layout/color/position glance, not reliable for * exact text. "high": the full existing ceiling, for when a capture actually * needs to be read (a focused `selector`/`region`, or an explicit request). */ type ScreenshotDetail = "low" | "high"; /** Which rectangle a capture actually used (APPS-5714). Reported in the * response so the caller knows what it did and didn't see. */ type ScreenshotCaptureMode = "viewport" | "fullPage" | "region" | "selector"; /** An explicit crop rectangle, in full-page CSS-pixel coordinates -- not * viewport-relative. The full page is always rendered regardless of scroll * position, so panning to any part of the document needs no real scrolling * (APPS-5714). */ interface ScreenshotRegion { x: number; y: number; width: number; height: number; } type FromParentToChildMessageTypesMap = { "sb-init": InitData; "sb-bootstrap-response": { userId?: string; appId: string; token: string; accessToken: string; /** * Explicit authorization for the code-mode dev server. Consumers must not * substitute API execution auth when this is null. */ devServerAuthorization: string | null; /** * Pre-filtered agent URLs for the current profile. * Used as fallback for cloud orgs where agent URLs are * derived from SUPERBLOCKS_UI_AGENT_BASE_URL, not from * agent metadata. */ agentUrls: string[]; /** * Full on-premise agent metadata (all profiles) for local * profile-based filtering, eliminating the async round-trip * when profiles change. Empty array for cloud orgs. */ agents: AgentInfo[]; logContext: Record; featureFlags?: Record; sessionRecordingKey?: string; /** Selected integration profile for API execution */ profile?: SdkProfileInfo; /** Current git branch name (editor mode only) */ branchName?: string; /** Deployed/preview commit ID (non-editor modes) */ commitId?: string; /** * Profile keys mapped to data-plane URLs when the gateway is enabled. */ dpRoutingConfig?: Record; }; "sb-editor-request-bootstrap": { forceRefreshScopedToken?: boolean; }; "sb-update-active-agents": { /** Pre-filtered URLs for current profile (cloud org fallback) */agentUrls: string[]; /** All active on-premise agents for local profile filtering */ agents: AgentInfo[]; /** * DP routing config mapping profile keys to DP URLs. * Only populated when dataPlaneGatewayEnabled is true. */ dpRoutingConfig?: Record; }; /** * Sent when execution context changes (e.g. profile or branch switch) * so the library can update its orchestrator call parameters. */ "sb-update-sdk-context": { profile?: SdkProfileInfo; branchName?: string; commitId?: string; }; "sb-update-token": { authorization: string | undefined; }; "sb-select-source": { sourceId: string; }; "sb-global-sync": { global: Record; }; "parent-action-batch": PayloadAction[]; click: void; "register-keypress": { keys: string; options?: any; }; "canvas-scale-update": { canvasScaleFactor: number; }; /** * Resolve a promise created by addNewPromise. * Note: callbackId must be at the top level, not nested in payload. * Payload contains the resolution value. */ "resolve-promise": unknown; /** * Reject a promise created by addNewPromise. * Note: callbackId must be at the top level, not nested in payload. * Payload contains the error object. */ "reject-promise": unknown; "flash-element": { elementId: string; }; "set-theme": { theme: unknown; updateRedux?: boolean; storedTypographies?: unknown; }; getDropTarget: { parentId: string; }; keypress: { keys: string; eventInfo: { code: string; key: string; altKey: boolean; ctrlKey: boolean; shiftKey: boolean; }; }; dragstart: Record & { type: string; }; "sb-create-component": { componentType: string; parent: SourceLocation; scopeName: string; baseProperties?: Record; skipSecondaryComponentsCreation?: boolean; otherComponentsUpdates?: Record>; }; "set-interaction-mode": { interactionMode: InteractionMode; }; /** * Request a route change in the child */ "route-change": RouteChangePayload; "ai-updates": AiUpdatesPayload["parentToChild"]; /** * Request a screenshot capture from the iframe */ "capture-screenshot": { callbackId: string; /** * If true, capture immediately without waiting for APIs to finish. * Useful for capturing loading-state shimmers/skeletons. */ captureLoadingState?: boolean; /** * Which output limits to apply. Defaults to "model" for older editors that * do not send it. */ purpose?: ScreenshotPurpose; /** * Optional CSS selector to target a specific element for the screenshot. * If provided, only the matched element will be captured instead of the full page. * Falls back to the root element if the selector doesn't match or the element has no dimensions. */ selector?: string; /** * Explicit crop rectangle in full-page coordinates (APPS-5714). Mutually * exclusive with `selector` and `fullPage`; the caller is responsible for * only ever setting one. */ region?: ScreenshotRegion; /** * Capture the full scroll extent instead of the viewport (APPS-5714). * Mutually exclusive with `selector` and `region`. Stays low-fidelity by * design -- a structural glance, not a legibility mechanism; use `region` * to read something specific on a long page. */ fullPage?: boolean; /** * How much resolution budget to spend on whichever rectangle is captured * (APPS-5714). Applies uniformly to the default (viewport), `region`, and * `selector` cases. Ignored for `purpose: "checkpoint"`, which has its own * fixed limits. Defaults to "low". */ detail?: ScreenshotDetail; }; /** * Ping to check if the app is ready for screenshot (sb-provider-root exists and spinner is gone) */ "ping-app-ready-for-screenshot": { callbackId: string; }; /** * Update embed properties from the external embedder */ "embed-property-change": { properties: Record; }; /** * Trigger an event inside the embedded app from the external embedder */ "embed-trigger-event": { eventName: string; payload: Record; }; /** * Request DOM metadata (bounding rect, opening tag HTML) for tagged components */ "get-tagged-element-metadata": { callbackId: string; sourceIds: string[]; }; /** * Request the TypeScript source code for an SDK API. */ "sdk-get-api-code": { name: string; callbackId: string; }; }; type FromParentToChildMessageTypes = keyof FromParentToChildMessageTypesMap; type ResourceCategory = "dependency" | "vite" | "app" | "other"; /** * How long the editor iframe took to load, sent with `sb-ready` so the parent * can draw it in its startup trace. The parent cannot read the iframe's * Performance API itself because the iframe is on another origin. Times are * milliseconds since `timeOrigin`, the iframe's navigation start (epoch ms). */ type IframeLoadTimings = { timeOrigin: number; responseStart?: number; responseEnd?: number; libraryEvaluated?: number; domContentLoaded?: number; bootstrapRequested?: number; bootstrapReceived?: number; ready: number; resourceCount: number; cachedResourceCount: number; resourceDurationSumMs: number; slowestResources: Array<{ category: ResourceCategory; startMs: number; durationMs: number; }>; }; type FromChildToParentMessageTypesMap = LoadErrorMessageTypesMap & { "sb-ready": { connectionStartTime?: number; loadTimings?: IframeLoadTimings; }; "sb-app-frame-will-reload": void; "iframe-action-batch": PayloadAction[]; /** * Navigate the parent window to a new URL */ "navigate-to": { url: string; newWindow?: boolean; }; "sb-iframe-track-changes": Record; /** * Resolve a promise created by addNewPromise. * Note: callbackId must be at the top level, not nested in payload. * Payload contains the resolution value. */ "resolve-promise": unknown; /** * Reject a promise created by addNewPromise. * Note: callbackId must be at the top level, not nested in payload. * Payload contains the error object. */ "reject-promise": unknown; "sb-editor-request-bootstrap": { forceRefreshScopedToken?: boolean; }; "reload-configs": void; "client:selectWidgets": { sourceIds: SbElement[]; selectorIdHint?: string; }; "set-interaction-mode": { interactionMode: InteractionMode; }; getDropTargetResult: { offset: XYCoord; size: { height: number; width: number; }; }; keypress: { keys: string; eventInfo: { code: string; key: string; altKey: boolean; ctrlKey: boolean; shiftKey: boolean; }; }; "register-click": { type: string; context: { clientX: number; clientY: number; sourceId: string; selectorId?: string; }; }; "api/started-execution": { apiName: string; }; "api/set-api-response": { apiName: string; response: unknown; }; "api/stream-event": { event: StreamEvent; apiName: string; }; "api/stream-message": { message: any; apiName: string; }; "authenticate-api-request": { accessToken?: string; apiId: string; callbackId: string; integrationIds?: string[]; profile?: SdkProfileInfo; }; /** * Execute an integration query as part of SDK API execution. * The parent (ui-code-mode) will dispatch executeRequestToIntegration * and resolve the promise with the result. * * For language plugins (Python, JavaScript), the input parameter contains * bindings that should be passed to the API execution request for {{}} resolution. */ "sdk-execute-query": { integrationId: string; request: Record; input?: Record; callbackId: string; }; /** * Resolve integration configs before SDK API execution. * The parent (ui-code-mode) will look up each integration by ID, * ensure it's authenticated, and return the resolved configs. * * This enables upfront auth checks before API execution starts. */ "sdk-resolve-integrations": { integrations: Array<{ key: string; pluginId: string; id: string; }>; callbackId: string; }; "set-apis-deployed-mode": { apis: Array; callbackId: string; }; /** * Notify the parent of a route change */ "route-change": RouteChangePayload; "ai-updates": AiUpdatesPayload["childToParent"]; undo: void; redo: void; "socket/error": { message: string; connectionStartTime?: number; }; "runtime-error": RuntimeErrorData; "clear-runtime-error": { id: string; }; "console-log": ConsoleLogEntry; "logout-integration": { callbackId: string; }; /** * Posted exactly once when `retryConnection` exhausts its budget and gives * up — the connection sequence is terminally abandoned and the user is * shown a refresh-required state. Deliberately a distinct type from * `app-websocket-connected` (whose unit is individual attempts): parents * that predate it ignore it entirely instead of misclassifying it as one * more per-attempt failure. */ "app-websocket-exhausted": { durationMs: number; connectionStartTime?: number; connectionType?: "initial" | "reconnect"; connectionTarget?: string; error: { message: string; type: string; }; }; "app-websocket-connected": { success: boolean; durationMs: number; connectionStartTime?: number; connectionType?: "initial" | "reconnect"; connectionTarget?: string; error?: { message: string; type: string; stack?: string; }; }; /** * Response to capture-screenshot request */ "capture-screenshot-response": { callbackId: string; dataUrl?: string; error?: string; /** Full page content dimensions (APPS-5714), so the caller can choose * sensible `region` coordinates on a follow-up capture. Absent on error. */ pageWidth?: number; pageHeight?: number; /** Which rectangle this capture actually used. Absent on error. */ mode?: ScreenshotCaptureMode; /** The part of the page the image shows, in full-page pixel coordinates. * Absent for selector captures. */ crop?: { x: number; y: number; width: number; height: number; }; uncapturedImageCount?: number; }; /** * Response to ping-app-ready-for-screenshot request */ "ping-app-ready-for-screenshot-response": { callbackId: string; isReady: boolean; /** * Why the app is (or isn't) ready. Optional for backward compatibility with * older app builds that only send `isReady`; consumers must tolerate its * absence (treat missing as "ready" when isReady, else "not-rendered"). */ reason?: ScreenshotReadyReason; }; /** * Emit an event from the embedded app to the external embedder */ "embed-emit-event": { eventName: string; payload: Record; }; /** * Notify the parent when an SDK API is registered (loaded). * Contains metadata including input/output schemas for display in the UI. */ "sdk-api-registered": { name: string; metadata: SdkApiMetadata; }; /** * Notify the parent when an SDK API is unregistered (HMR unload). */ "sdk-api-unregistered": { name: string; }; /** * Notify the parent when an SDK API's source code has been updated. * Used for HMR to update the code viewer without full re-registration. */ "sdk-api-source-updated": { name: string; sourceCode: string; }; /** * Response to sdk-get-api-code request with the TypeScript source code. */ "sdk-api-code-response": { callbackId: string; name: string; code?: string; error?: string; }; /** * Notify the parent when an SDK API execution starts (from app code). * Used for tracking executions in the SDK API editor's execution log. */ "sdk-api-execution-started": { executionId: string; apiName: string; input: Record; }; /** * Notify the parent when an SDK API execution completes successfully. */ "sdk-api-execution-completed": { executionId: string; apiName: string; output: unknown; durationMs: number; diagnostics?: unknown[]; orchestratorStartMs?: number; orchestratorDurationMs?: number; fetchStartMs?: number; timingBreakdown?: ExecutionTimingBreakdown; }; /** * Notify the parent when an SDK API execution fails. */ "sdk-api-execution-failed": { executionId: string; apiName: string; error: { code: string; message: string; }; durationMs: number; diagnostics?: unknown[]; orchestratorStartMs?: number; orchestratorDurationMs?: number; fetchStartMs?: number; timingBreakdown?: ExecutionTimingBreakdown; }; } & AppToEditorMessage; type FromChildToParentMessageTypes = keyof FromChildToParentMessageTypesMap; //#endregion //#region src/lib/internal-details/location-store.d.ts declare class LocationStore { route?: RouteInfo; rootStore: RootStore; constructor(rootStore: RootStore); updateLocation(location: Location, routes: DataRouter["routes"], params: Readonly>): void; sendLocationToEditor(): void; private matchesToRoutePattern; locationToRouteInfo(location: Location, routes: DataRouter["routes"], params: Readonly>): RouteInfo | undefined; } //#endregion //#region src/lib/internal-details/lib/features/api-store.d.ts type ApiResult = { data?: T; error?: string; }; declare class ApiManager { readonly rootStore: RootStore; /** * Pre-filtered agent URLs for the current profile, sent by the parent. * Used as fallback for cloud orgs where URLs come from * SUPERBLOCKS_UI_AGENT_BASE_URL rather than agent metadata. */ private _agentUrls; /** * Full on-premise agent metadata (all profiles) from the parent, * enabling local profile-based filtering without a postMessage * round-trip. Empty for cloud orgs. */ private _agents; /** * DP routing config mapping profile keys to DP URLs, sent by the parent. * Only populated when dataPlaneGatewayEnabled is true. */ private _dpRoutingConfig; private token; private accessToken; private runningApiControllers; private waitForInitApiPromise; private waitForBootstrapPromise; private resolveBootstrapPromise; private callContexts; /** * Flush pending file writes to DBFS, logging a warning if it blocks for * >50ms. Returns the elapsed time in ms so callers can record it in the * execution timing breakdown. */ private timedEnsureFilesSynced; constructor(rootStore: RootStore); set agentUrls(urls: string[]); set agents(agents: AgentInfo[]); set dpRoutingConfig(config: Record); setTokens(token: string, accessToken: string): void; clearTokens(): void; isInitialized(): boolean; /** * Get agent URLs for the given profile by filtering locally stored * agent metadata. Falls back to the pre-filtered `_agentUrls` when * no full agent metadata is available (cloud orgs or legacy parents). */ private getAgentUrlsForProfile; /** * Selects a random agent URL from the available agents and returns it normalized * (with trailing slash) to ensure proper URL path joining. */ private getRandomAgentBaseUrl; private awaitInitApiIfNeeded; private awaitBootstrapIfNeeded; notifyBootstrapComplete(): void; private prewarmExecutionPath; loadApiManifest({ apis }: { apis?: Record; }): void; rerunApiByCallId(callId: string): Promise; runApiByPath({ path, inputs, callId, callback, isTestRun, injectedCallerId }: { path: string; inputs: SbApiRunOptions; callId?: string; callback?: () => Promise; isTestRun?: boolean; injectedCallerId?: string; }): Promise; private getHMRCallHash; private getCachedHMRExecution; private executeApi; private executeApiInternal; private findError; private extractStatusCode; /** * Extract step-level logs from execution events. * Captures console.log (stdout), console.error (stderr), output, and errors for each step. */ private extractStepLogs; /** * Execute an SDK API directly via the orchestrator's v3/execute endpoint. * Reads execution context (profile, branch, tokens) from rootStore so the * caller doesn't need to resolve them through the parent frame. */ executeSdkApiV3(apiName: string, inputs: Record, options?: { signal?: AbortSignal; }): Promise<{ success: boolean; output?: unknown; error?: { code: string; message: string; }; diagnostics?: unknown[]; executionStartMs?: number; executionDurationMs?: number; fetchStartMs?: number; timingBreakdown?: ExecutionTimingBreakdown; }>; cancelApi(apiName: string, _scopeId?: string): Promise; } //#endregion //#region src/lib/internal-details/lib/root-store.d.ts /** * User information extracted from JWT for SDK API execution. * Matches the ApiUser interface from @superblocksteam/sdk-api. */ interface SdkApiUser { /** Unique user identifier from JWT */ readonly userId: string; /** User's email address (if available) */ readonly email?: string; /** User's display name (if available) */ readonly name?: string; /** User's group memberships from JWT */ readonly groups: string[]; /** Custom claims from JWT */ readonly customClaims: Readonly>; } declare class RootStore { apis: ApiManager; componentRegistry: ComponentRegistry; editStore?: EditStore; locationStore: LocationStore; currentPageScopeId: string | undefined; applicationId: string | undefined; userId: string | undefined; windowOriginUrl: string | undefined; /** * Current user info for SDK API execution. * Populated from JWT claims when available. */ sdkUser: SdkApiUser; /** * Whether the SDK API feature is enabled. * Derived from the application's templateName (see `isSdkApiTemplate()`). * Passed to the library via the `clark.sdk-api.enabled` bootstrap flag. * When false, the YAML-based API system is used instead. */ sdkApiEnabled: boolean; /** * Whether execute requests should be routed through the data plane gateway * endpoint instead of direct agent URLs. * Passed to the library via the ui.data-plane-gateway.enabled bootstrap flag. */ dataPlaneGatewayEnabled: boolean; orchestratorExecuteResponseSizeLimitBytes: number | undefined; /** Selected integration profile for orchestrator API calls */ profile: SdkProfileInfo | undefined; /** Current git branch name for editor-mode API execution */ branchName: string | undefined; /** Deployed/preview commit ID for non-editor API execution */ commitId: string | undefined; /** * Maps API name → entryPoint path (relative to app root). * Populated by sdk-api-discovery during edit mode. * Used by executeSdkApiV3 to resolve the correct file path for the orchestrator. */ apiEntryPoints: Map; /** * Maps API name → original export name in the source file. * Set for named exports (e.g. `export const GetUsers = api({...})`). * Undefined/absent for default exports. * Used by executeSdkApiV3 to send the correct `exportName` to the orchestrator. */ apiExportNames: Map; /** * Maps API name → statically declared integrations. * Populated during edit-mode discovery and from the deployed build manifest. */ apiIntegrations: Map; /** * Resolves when the initial SDK API discovery pass completes. * executeSdkApiV3 awaits this so callers don't race against discovery. */ private _discoveryPromise; private _resolveDiscovery; private editorRegisteredCallbacks; constructor(); /** * Updates the SDK user info from JWT claims or bootstrap data. */ setSdkUser(user: Partial): void; /** * Sets the SDK API feature flag state. * Called during bootstrap with the value from feature flags. * * When enabling, pre-initializes the discovery gate immediately so that * any component whose useEffect runs before IframeConnected's reaction * useEffect (children run before parents in React) will correctly block * on awaitDiscovery() instead of resolving immediately with no entry points. */ setSdkApiEnabled(enabled: boolean): void; setDataPlaneGatewayEnabled(enabled: boolean): void; setOrchestratorExecuteResponseSizeLimitBytes(value: unknown): void; setProfile(profile: SdkProfileInfo | undefined): void; setBranchName(branchName: string | undefined): void; setCommitId(commitId: string | undefined): void; setApiEntryPoint(apiName: string, entryPoint: string): void; getApiEntryPoint(apiName: string): string | undefined; setApiExportName(apiName: string, exportName: string): void; getApiExportName(apiName: string): string | undefined; clearApiEntryPoints(): void; setApiIntegrations(apiName: string, integrations: IntegrationDeclaration[]): void; getApiIntegrations(apiName: string): IntegrationDeclaration[] | undefined; clearApiIntegrations(): void; /** * Initialise (or re-initialise) the discovery gate. Called when discovery * starts so that executeSdkApiV3 awaits before checking entry points. * Always creates a fresh promise so HMR re-discovery is also gated. * Resolves any in-flight promise before replacing it so callers awaiting * the old gate (e.g. from before HMR re-triggered discovery) do not hang. */ initDiscoveryGate(): void; /** * Signal that the initial discovery pass has finished (success or failure). */ notifyDiscoveryComplete(): void; /** * Returns true if a discovery gate exists and has not yet been resolved. * Used by discoverAndRegisterSdkApis to avoid re-initializing the gate * when setSdkApiEnabled already pre-initialized it. */ hasUnresolvedGate(): boolean; /** * Returns a promise that resolves once initial discovery has completed. * Resolves immediately if discovery already finished or was never started. */ awaitDiscovery(): Promise; setEditStore(editStore: EditStore): void; notifyEditorRegistered(): void; onEditorRegistered(fn: () => void): void; } //#endregion //#region src/lib/internal-details/lib/features/component-registry.d.ts type DefaultTagNames = { container: string; button: string; text: string; }; /** * TODO: The component registry could be split into two a thin layer always on, and move some stuff to the EditStore. * Some of the actions (rename, delete) and some of the data (isDroppable) are editor-only. */ declare class ComponentRegistry implements ComponentRegistryShareState { readonly rootStore: RootStore; private _componentRegistry; private _componentToType; constructor(rootStore: RootStore); private getOrCreateMetadata; addComponent(type: string, rawComponent: React$2.ElementType, propertiesDefinition: PropertiesDefinition): void; deleteComponent(type: string): void; renameComponent(oldName: string, newName: string): void; addManagedProps(type: string, props: ManagedPropsList): void; getEditorConfigFromComponentType(type: any): EditorConfig$1 | undefined; addEditorConfig(type: string, config: EditorConfig$1): void; getEditorConfig(type: string): EditorConfig$1 | undefined; get entityDefinitions(): Record; get libraryComponentEditorConfigs(): Record>; getManagedProps(type: string): ManagedPropsList; /** * Get the component type string for a raw component reference. * Used for registry-based component identity checking. */ getTypeForComponent(component: React$2.ComponentType): string | undefined; /** * Check if a component or element type is registered in the component registry. * Accepts both component references and string element names (e.g., "div"). * Used for component identity checking instead of symbol-based approach. */ hasComponent(component: React$2.ElementType | string): boolean; } //#endregion //#region src/lib/internal-details/sb-wrapper.d.ts type InjectedProps = { dropTargetRef?: React$1.Ref | React$1.LegacyRef; }; type ParentInfo = { type?: string; }; interface CreationContext { parentInfo: ParentInfo; defaultTagNames: DefaultTagNames; selfTagName: string; generateUniqueName: (prefix: string) => string; } type PropertyValues

> = { [K in keyof P]?: PropertyInfo | PropertyValues }; interface EditorTemplate

= React$1.ComponentProps> { catalog?: Catalog; /*** * Config for the newly created component when added to the canvas from the Editor. * @returns a single CreateRequest or an array of CreateRequests. * * When returning Array: * - The 1st CreateRequest's type must match the componentType passed to createComponent. * - The last CreateRequest's will be the selected component after drag & drop. * * Example: [Modal, Button] * A modal that when drag & dropped on the page will add a trigger button. * The modal is closed by default, so the selected component after drop will be the trigger button. */ create?: (context: CreationContext) => CreateRequest

| Array>; } interface CreateRequest

= React$1.ComponentProps> { type: string; properties?: PropertyValues

; createAt?: "root" | "dropLocation"; children?: CreateChild$1[]; } interface Chainable = React$1.ComponentProps> { addEditorTemplate: (config: EditorTemplate) => Chainable; editorConfig: (config: EditorConfig$1) => Chainable; } /** * Register a component to be used with the framework. * * @param Component - The React component or HTML element name (e.g., "div") to register. Can be a React functional component, class component, or intrinsic element string. * @param propertiesDefinition - The runtime schema for the component's managed properties. * * @returns A chainable object that provides methods for editor integration (addEditorTemplate and editorConfig). */ declare const registerComponentInternal: (Component: T, propertiesDefinition: PropertiesDefinition) => Chainable>; //#endregion //#region src/lib/user-facing/component-base/sb-component.d.ts type SbComponentProps = { name?: string; bind?: WithBindingIdentifier; sourceId?: SbElement; /** * undefined means auto, true means always loading, false means never loading */ loading?: boolean; } & Omit, "height" | "width">; //#endregion //#region src/lib/user-facing/properties-panel/props-builder.d.ts type Exact = T extends Shape ? Exclude extends never ? T : never : never; type ManagedProp = PropertyForData & { default?: SingleInputProp; defaultOnAdd?: SingleInputProp; /** * Controls binding nesting behavior: * - true: Allows bindings to be nested at any depth within this property * - false: Only allows bindings at the top level (unless the property is composite) */ nestedBindings?: boolean; /** * Indicates this property should be evaluated per-context (e.g., per-row in tables) * When true, the property value will be evaluated for each context with access to context variables */ contextual?: boolean; computedArgs?: EvaluateOrValueComputedArgs; }; type ManagedPropsList = Array; /** * Merges shared and variant properties for union types without creating intersections * Variant properties override shared properties with the same key */ type MergeUnionVariant>, VARIANT extends Record>> = Omit & VARIANT; /** * Converts a union type to an intersection type * Used to merge multiple section props into a single props type */ type UnionToIntersection = (U extends any ? (x: U) => void : never) extends ((x: infer I extends U) => void) ? I : never; /** * Controls how default values affect property optionality * - RequiredIfDefault: Properties with default values become required * - AlwaysOptional: All properties become optional regardless of defaults */ type DefaultValueBehavior = "RequiredIfDefault" | "AlwaysOptional"; /** * Extracts the concrete type from a property definition * * For evaluated props: returns the actual value type * * For non-evaluated props: returns InputProp */ /** * Extracts the concrete type from a property definition * Enhanced to handle contextual properties */ type ExtractPropType = T extends Record> ? ExtractProps : T extends RecordProp ? Record> : T extends CompositeProp ? IsEvaluated extends true ? ExtractProps : InputProp> : T extends UnionProp ? VARIANTS extends readonly any[] ? { [I in keyof VARIANTS]: ExtractProps, DefaultsBehavior, IsEvaluated> }[number] : never : T extends Prop ? IsEvaluated extends true ? ContextualProps extends undefined ? V extends Callback ? (...args: any[]) => Promise : V : ContextualProps extends any[] ? (...args: ContextualProps) => V : InputProp : InputProp : never; /** * Extracts a flat props object from a properties definition * Handles optionality based on DefaultValueBehavior */ type ExtractProps = T extends Record ? ExtractProps, DefaultsBehavior, IsEvaluated> : T extends SectionPropRecord ? DefaultsBehavior extends "AlwaysOptional" ? { [K in keyof T as T[K] extends Prop ? K : never]?: ExtractPropType } : { [K in keyof T as T[K] extends Prop ? HasDefault extends true ? K : never : never]: ExtractPropType } & { [K in keyof T as T[K] extends Prop ? HasDefault extends false ? K : never : never]?: ExtractPropType } : never; /** * Handles non Prop types, aka our default types and CSS props */ type SectionPropertiesPanelConfig = { showHeader?: boolean; isDefaultOpen?: boolean; headerType?: HeaderType; subHeader?: string; }; /** * Merges all sections in a properties definition into a single props type */ type MergeSections, Merged = UnionToIntersection> = Merged extends Section ? U : never; /** * Identical to InternalProps but without the base props */ type EntityProps> = ExtractProps; /** * Internal props used by the component implementation * - Properties with defaults are required * - Properties are fully evaluated to their final types */ type InternalProps, BaseProps = Omit> = FlattenedProps & BaseProps & InjectedProps; /** * External props exposed to component consumers * - All properties are optional regardless of defaults * - Properties accept InputProp values (bindings/functions) */ type PropertiesDefinition = Record; type SectionPropRecord> = Partial<{ [K in keyof Props]: Prop }>; declare class Section = SectionPropRecord> { readonly category: PropsCategory; props: T; propertiesPanelConfig: SectionPropertiesPanelConfig; constructor(category: PropsCategory); static category(category: PropsCategory): Section }>>; children | CompositeProp | UnionProp, OUT extends (INP extends CompositeProp ? CU : INP extends UnionProp ? VARIANTS extends readonly any[] ? { [I in keyof VARIANTS]: MergeUnionVariant }[number] : never : INP)>(props: INP extends CompositeProp | UnionProp ? INP : Exact>): Section; add: | CompositeProp | UnionProp, OUT extends (INP extends CompositeProp ? CU : INP extends UnionProp ? VARIANTS extends readonly any[] ? { [I in keyof VARIANTS]: MergeUnionVariant }[number] : never : INP)>(props: INP extends CompositeProp | UnionProp ? INP : Exact>) => Section; /** @deprecated Panel configuration is accepted for source compatibility and ignored. */ propertiesPanel(_config: SectionPropertiesPanelConfig): this; get name(): "Content" | "Routing" | "Interaction" | "Styles" | "Layout" | "Appearance" | "Permissions" | "Uncategorized" | "Actions"; } declare class Prop any[] | undefined) = undefined> { protected prop: ManagedProp; protected constructor(typeString: DataTypeString); static unset(): Prop; static string(): Prop; static number(): Prop; static boolean(): Prop; static array(): Prop>; static any(): Prop; static jsx(): Prop; static literal>(value: T): Prop; static eventHandler(): Prop; static function(implementation: EntityFunction): FunctionProp; /** * Creates a composite property, which is a property that contains nested properties. For example, * the following composite property: * * ```ts * const prop = Prop.composite({ * name: Prop.string(), * age: Prop.number(), * }); * ``` * * is equivalent to the following type: * * ```ts * type Prop = { * name: string; * age: number; * }; * ``` */ static composite(props: T): CompositeProp; /** * Creates a record property, which is a record that maps string keys to the nestedproperties. For example, * the following record property: * * ```ts * const prop = Prop.record({ * name: Prop.string(), * age: Prop.number(), * }); * ``` * * is equivalent to the following type: * * ```ts * type Prop = Record; * ``` */ static record(props: T): RecordProp; static union>, VARIANTS extends UnionVariant[] = UnionVariant[]>(props: { shared: SHARED; variants: VARIANTS; }): UnionProp; default(de: SingleInputProp): Prop; contextual(computedArgs?: EvaluateOrValueComputedArgs): Prop; setName(name: string): this; /** @deprecated Panel configuration is accepted for source compatibility and ignored. */ propertiesPanel(_schema: Omit>, "isTriggerProperty">): this; /** @deprecated Panel metadata is accepted for source compatibility and ignored. */ setDisplayProperty>(_property: K, _value: PropertiesPanelDisplay[K]): this; /** @deprecated Panel relations are accepted for source compatibility and ignored. */ dependsOn(_relations: Relation[][]): this; getRelations(): Relation[][]; hasPropertiesPanelDisplay(): boolean; toDefinition(_props: Record): WidgetPropertyDefinition | undefined; docs(docs: Exclude["docs"], undefined>): this; build(): ManagedProp; get type(): DataTypeString; get path(): string; } type CompositeInputs = Record | Section | Record>; /** * See {@link Prop.composite} */ declare class CompositeProp extends Prop { typeString: "composite"; nestedProps: T; constructor(props: T); getProps(): T; propertiesPanelChildrenDisplayMode(): PropertiesPanelDisplay["childrenDisplayMode"]; } /** * See {@link Prop.record} */ declare class RecordProp extends Prop, boolean> { typeString: "recordOf"; nestedProps: T; constructor(props: T); getProps(): T; } interface ActionPanel { arguments?: Record>; } declare class FunctionProp extends Prop, true> { typeString: "function"; constructor(implementation: EntityFunction); /** @deprecated Action panel metadata is accepted for source compatibility and ignored. */ actionPanel(_panel?: ActionPanel): this; getActionPanel(): ActionPanel | undefined; } type UnionVariant>> = { [K in keyof SHARED]: Prop }; declare class UnionProp>, VARIANTS extends UnionVariant[] = UnionVariant[], _OUTPUT = (VARIANTS extends readonly any[] ? { [I in keyof VARIANTS]: SHARED & VARIANTS[I] }[number] : never)> extends Prop { typeString: "union"; shared: SHARED; variants: VARIANTS; constructor(shared: SHARED, variants: VARIANTS); getProps(): Record>; } //#endregion //#region src/lib/user-facing/components/app/props.d.ts declare const propertiesDefinition: { contents: Section; }> & { children: Prop; }>; appearance: Section<{ className: string; }, Partial<{ className: Prop; }>>; }; //#endregion //#region src/lib/user-facing/components/app/index.d.ts declare const App: (({ children, className, context }: InternalProps & { context?: SuperblocksAppContext; }) => _$react_jsx_runtime0.JSX.Element) & { displayName: string; }; //#endregion //#region src/lib/user-facing/components/custom/register-custom-component.d.ts type PropertiesPanelDefinition> = SectionPropRecord | { [K in string]: Section> }; /** * Registers a custom React component or HTML element with Superblocks. * * @param component - The React component or HTML element name (e.g., "div") to register * @param propertiesDefinition - Optional properties panel definition, either as flat props or organized into sections * @returns The registered component * * @example * ```tsx * // Register HTML element with just defaults * registerComponent("div"); * * // Register HTML element with custom props * registerComponent("div", { * children: Prop.node(), * onClick: Prop.eventHandler(), * }); * * // Flat props (auto-categorized into Content and Event sections) * registerComponent(MyComponent, { * label: Prop.string().default("Click me"), * onClick: Prop.eventHandler(), * }); * * // Organized into sections * registerComponent(MyComponent, { * content: Section.category(PropsCategory.Content).children({ * label: Prop.string().default("Click me"), * }), * events: Section.category(PropsCategory.EventHandlers).children({ * onClick: Prop.eventHandler(), * }), * }); * ``` */ declare function registerComponent(component: T, propertiesDefinition?: PropertiesPanelDefinition>): ReturnType; //#endregion //#region src/lib/user-facing/error-pages/page-not-found.d.ts declare const PageNotFound: ({ title, errorMessage, buttonPath, buttonText, onButtonClick, hideActions }: { title?: string; errorMessage?: string | React$1.ReactElement; buttonPath?: string; buttonText?: string; onButtonClick?: () => void; hideActions?: boolean; }) => _$react_jsx_runtime0.JSX.Element; //#endregion //#region src/lib/internal-details/internal-components/route-load-error.d.ts declare function RouteLoadError(): _$react_jsx_runtime0.JSX.Element; //#endregion //#region src/lib/internal-details/use-api.d.ts declare global { interface SuperblocksAPIRegistry {} } type RegisteredAPINames = keyof SuperblocksAPIRegistry; type ApiInterfaces = Name extends keyof SuperblocksAPIRegistry ? SuperblocksAPIRegistry[Name] extends { input: infer I; output: infer O; } ? { input: I; output: O; } : { input: Record; output: any; } : { input: never; output: never; }; /** * Get the API path for an API by name. * * When SDK APIs are enabled, paths point to `/server/apis//api.ts`. * When using legacy YAML mode, paths point to `/apis//api.yaml`. */ /** Helper type to extract input type from a CompiledApi */ type ApiInput = T extends CompiledApi ? TInput : never; /** Helper type to extract output type from a CompiledApi */ type ApiOutput = T extends CompiledApi ? TOutput : never; /** Core run/cancel returned by the internal delegation hooks. */ interface UseApiCoreMethods { run: (inputs?: TInput) => Promise; cancel: () => Promise; } /** Return type for useApi hook */ interface UseApiResult extends UseApiCoreMethods { /** * Whether an API call is in flight. * * **Imperative mode** (no `inputs`): tracks only the latest `run()` * invocation. If a newer `run()` is started while an older one is pending, * `loading` reflects the newer call. `cancel()` resets it to `false`. * * **Declarative mode** (`inputs` provided): equivalent to * `useApiData.fetching` — `true` during any fetch including background * refetches, not just the initial load. */ loading: boolean; /** The most recent successful response. Persists across re-runs. */ data: TOutput | undefined; /** * The error from the last failed run(). Cleared on the next successful run. * In declarative mode, populated when the auto-fetch fails (no try/catch needed). */ error: unknown; /** * Semantic status of the last execution. * - "idle": no run has been triggered yet * - "pending": a run is in flight * - "success": last run completed successfully * - "error": last run failed */ status: "idle" | "pending" | "success" | "error"; /** * The inputs passed to the most recent run(). Useful for optimistic UI. * Undefined until the first run() is called. */ variables: TInput | undefined; /** * Reset state back to idle. Clears data, error, loading, status, and variables. * Also invalidates any in-flight run so its settlement is ignored. */ reset: () => void; } /** * API Registry interface for type inference. * * This interface is used with useTypedApi to enable automatic type inference. * Apps define their own ApiRegistry type and pass it to useTypedApi. * * @example * ```typescript * // In server/apis/index.ts * const apis = { GetUsers, CreateOrder } as const; * export type ApiRegistry = typeof apis; * * // In client/hooks/useApi.ts * import type { ApiRegistry } from "../../server/apis/index.js"; * import { useTypedApi } from "@superblocksteam/library"; * export const useApi = useTypedApi(); * ``` */ interface ApiRegistry {} /** * Conditional return type for useApi. * Returns typed result if the API name is in the registry, otherwise unknown. */ type UseApiReturnType = TName extends keyof ApiRegistry ? UseApiResult, ApiOutput> : UseApiResult; /** * React hook for executing YAML-based Superblocks APIs. * * This is the legacy API system that uses `rootStore.apis.runApiByPath`. * It remains the default when the `sdkApiEnabled` flag is off. * * @param name - The name of the registered API to execute * @returns An object with `run` and `cancel` functions */ declare function useApiStateful["input"], Response = ApiInterfaces["output"]>(name: Name): UseApiCoreMethods; declare function useApi(apiName: TName, inputs?: undefined): UseApiReturnType; /** * @deprecated Use `useApiData` for declarative data fetching. * This overload will be removed in a future major version. */ declare function useApi(apiName: TName, inputs: TName extends keyof ApiRegistry ? ApiInput : Record): UseApiReturnType; declare function useApi>(apiName: string, inputs?: ApiInput): UseApiResult, ApiOutput>; /** * Type for a registry of compiled APIs. * Used with useTypedApi to enable automatic type inference. */ type AnyApiRegistry = Record>; /** * Typed useApi function signature for a specific registry. * Supports both imperative (no inputs) and declarative (with inputs) modes. */ interface TypedUseApi { (apiName: TName): UseApiResult, ApiOutput>; /** * @deprecated Use `useApiData` for declarative data fetching. */ (apiName: TName, inputs: ApiInput): UseApiResult, ApiOutput>; } /** * Creates a typed version of useApi bound to a specific API registry type. * * This enables full type inference using only type imports from the server, * keeping backend code out of the client bundle. * * @returns A typed useApi function */ declare function useTypedApi(): TypedUseApi; //#endregion //#region src/lib/internal-details/use-api-data.d.ts interface UseApiDataResult { /** The most recent successful response. Persists across background refetches. */ data: TOutput | undefined; /** The error from the last failed fetch. Cleared on success. */ error: unknown; /** * Status of the data: * - "pending": fetching for the first time, no data yet * - "success": data has been fetched at least once * - "error": last fetch failed and there is no cached data */ status: "pending" | "success" | "error"; /** Status of the current network request. */ fetchStatus: "idle" | "fetching"; /** True when fetching for the first time with no cached data. */ loading: boolean; /** True when any fetch is in progress (including background refetch). */ fetching: boolean; /** True when the last fetch resulted in an error. */ isError: boolean; /** True when data has been fetched successfully at least once. */ isSuccess: boolean; /** * True when cached data is older than `staleTime`. * The next mount or refetch trigger will fetch fresh data. */ isStale: boolean; /** Manually trigger a fresh fetch, bypassing staleTime. */ refetch: () => Promise; /** Abort the current in-flight fetch for this component instance. */ cancel: () => void; } interface UseApiDataOptions { /** * Skip fetching when false. Useful for conditional fetching. * Default: true */ enabled?: boolean; /** * Milliseconds before cached data is considered stale. * Stale data is still shown while a background refetch completes. * Default: 0 (always refetch on mount) */ staleTime?: number; /** * Milliseconds to keep inactive (un-observed) cache entries before GC. * Default: 300_000 (5 minutes) * * @deprecated SWR manages cache lifecycle internally. This option is * accepted for backward compatibility but has no effect. */ gcTime?: number; /** * Number of retry attempts on failure. * All errors are retried except user-initiated cancellations (AbortError). * Set to `false` to disable retries entirely. * Default: 3 */ retry?: number | false; /** * Delay strategy for retries. Receives the zero-based attempt index. * Default: exponential backoff capped at 30s */ retryDelay?: (attempt: number) => number; /** * Refetch when the browser tab regains focus. * Default: false (avoids burst requests on every tab switch — Risk #6) */ refetchOnWindowFocus?: boolean; /** * Refetch when the browser reconnects to the network. * Default: true */ refetchOnReconnect?: boolean; /** * Polling interval in ms. false disables polling. * Default: false */ refetchInterval?: number | false; /** * When true, deep-compares incoming data against cached data. If equal, * preserves the old object reference to prevent unnecessary re-renders. * Default: false (opt-in to avoid breaking identity-sensitive effects — Risk #4) */ structuralSharing?: boolean; /** Shown while the real fetch is in progress, before any data arrives. */ placeholderData?: unknown; } declare function useApiData(apiName: string, inputs: Record, options?: UseApiDataOptions): UseApiDataResult; interface TypedUseApiData { (apiName: TName, inputs: ApiInput, options?: UseApiDataOptions): UseApiDataResult>; } /** * Creates a typed version of useApiData bound to a specific API registry. * * @example * ```typescript * import type { ApiRegistry } from "../../server/apis/index.js"; * import { useTypedApiData } from "@superblocksteam/library"; * export const useApiData = useTypedApiData(); * ``` */ declare function useTypedApiData(): TypedUseApiData; //#endregion //#region src/lib/internal-details/execute-api.d.ts interface ExecuteApiOptions { /** AbortSignal to cancel the request mid-flight. */ signal?: AbortSignal; /** Stable execution ID to reuse across iframe reloads. When omitted a random ID is generated. */ executionId?: string; } /** * Execute a Superblocks API as a plain Promise, without any React lifecycle. * * Routes to the SDK path (`executeSdkApiV3`) when the API has an entry point * or when `sdkApiEnabled` is set on rootStore. Falls back to the legacy YAML * path otherwise. * * Sends edit-mode tracking messages to the parent frame when in edit mode, * keeping the Requests Panel in sync even for out-of-React calls. * * @throws {DOMException} with name "AbortError" if cancelled via signal. * @throws The orchestrator error object on API failure. */ declare function executeApi(apiName: string, inputs?: Record, options?: ExecuteApiOptions): Promise; type TypedExecuteApi = (apiName: TName, inputs?: ApiInput, options?: ExecuteApiOptions) => Promise>; /** * Creates a typed version of executeApi bound to a specific API registry. * * @example * ```typescript * import type { ApiRegistry } from "../../server/apis/index.js"; * import { createTypedExecuteApi } from "@superblocksteam/library"; * export const executeApi = createTypedExecuteApi(); * ``` */ declare function createTypedExecuteApi(): TypedExecuteApi; //#endregion //#region src/lib/internal-details/query-cache.d.ts /** * Build a deterministic, string cache key from API name + inputs. * Sorts object entries so { b: 2, a: 1 } and { a: 1, b: 2 } produce * the same key. */ declare function buildCacheKey(apiName: string, inputs: Record): string; declare class QueryClient { buildCacheKey: typeof buildCacheKey; getQueryData(key: string): T | undefined; setQueryData(key: string, updater: T | ((old: T | undefined) => T)): void; invalidateQueries(keyPrefix: string): Promise; cache: { clear: () => void; }; } declare const queryClient: QueryClient; //#endregion //#region src/lib/user-facing/global-functions.d.ts /** * Logs out the user from all authenticated integrations used in APIs. * * Clears OAuth tokens and session data for integrations using oauth * so the user must re-authenticate on the next API call. Use this when * building a "Log out" or "Sign out" button in apps that use authenticated * integrations. * * @returns An object with `success: boolean` and optional `errors` array. * * @example * ```tsx * import { logoutIntegrations } from "@superblocksteam/library"; * * function LogoutButton() { * const handleLogout = async () => { * const result = await logoutIntegrations(); * if (!result.success) { * console.error("Logout failed", result.errors); * } * }; * return ; * } * ``` */ declare function logoutIntegrations(): Promise<{ success: boolean; errors?: Array<{ message: string; }>; }>; //#endregion //#region src/lib/user-facing/properties-panel/mixins/styles-category.d.ts /** @deprecated Accepted for source compatibility. Returns an empty section. */ declare const tailwindStylesCategory: (_props?: { prioritizedTailwindProperties?: TailwindPropertyKey[]; }) => Section<{ className: string; }>; //#endregion //#region src/lib/internal-details/embed-store.d.ts /** * Store for managing embed properties and events. * Used when the library is embedded in an external application (third-party embedding). * * Properties can be set by the parent window via postMessage, and events can be * emitted back to the parent window. */ declare class EmbedStore { properties: Record; constructor(); /** * Update the embed properties. Called when the parent window sends updated properties. */ setProperties(properties: Record): void; /** * Emit an event to the parent window. * The parent can listen for these events using window.addEventListener("message", ...). */ emitEvent(eventName: string, payload?: Record): void; /** * Typed helper for the platform-reserved * `superblocks:integration-auth-error` event. Emitted when an SDK API * execution fails the integration-auth gate (either reactively from a * 401/403 response or proactively from the embed shell). Hosts subscribe * via the embed SDK's `onEvent` and render their own connect/retry UX. * * `status` is the HTTP status that triggered the emit (401 or 403 for * reactive emits; the embed shell uses 401 for its proactive emit). * `integrationIds` are scoped to the integrations the host should drive * reauth for, so a host with multiple integrations can target the right * one. */ emitIntegrationAuthError(payload: { apiId: string; integrationIds: string[]; status: number; message: string; }): void; } declare const embedStore: EmbedStore; //#endregion //#region src/lib/user-facing/embed.d.ts /** * Emit a custom event to the external embedder. * This is used when the library is embedded in an iframe * to communicate events back to the parent application. * * @param eventName - The name of the event to emit * @param payload - Optional payload data to send with the event * * @example * ```ts * import { Superblocks } from "@superblocksteam/library"; * * // Emit a simple event * Superblocks.emitEvent("formSubmitted"); * * // Emit an event with payload * Superblocks.emitEvent("userSelected", { userId: "123", name: "John" }); * ``` */ declare function emitEvent(eventName: string, payload?: Record): void; /** * Get the current embed properties passed from the external embedder. * * @returns The current embed properties object * * @example * ```ts * import { Superblocks } from "@superblocksteam/library"; * * const props = Superblocks.getEmbedProperties(); * console.log(props.userId); * ``` */ declare function getEmbedProperties(): Record; /** * The Superblocks object provides utilities for interacting with * the embedding context when the library is embedded in an iframe. */ declare const Superblocks: { emitEvent: typeof emitEvent; getEmbedProperties: typeof getEmbedProperties; }; //#endregion //#region src/lib/hooks/use-embed-properties.d.ts /** * React hook for accessing embed properties passed from the external embedder. * Automatically re-renders when properties change. * * @returns The current embed properties object (reactive) * * @example * ```tsx * import { useEmbedProperties } from "@superblocksteam/library"; * * function MyComponent() { * const properties = useEmbedProperties(); * * // Access properties passed from the embedder * const userId = properties.userId as string; * const theme = properties.theme as "light" | "dark"; * * return

User: {userId}, Theme: {theme}
; * } * ``` */ declare function useEmbedProperties(): Record; //#endregion //#region src/lib/hooks/use-embed-event.d.ts /** * React hook for listening to events triggered by the external embedder. * The handler will be called whenever the embedder triggers the specified event. * * @param eventName - The name of the event to listen for * @param handler - Callback function invoked when the event is triggered * * @example * ```tsx * import { useEmbedEvent } from "@superblocksteam/library"; * * function MyComponent() { * useEmbedEvent("refreshData", (payload) => { * console.log("Embedder requested refresh:", payload); * // Refetch data, reset state, etc. * }); * * useEmbedEvent("themeChange", (payload) => { * const { theme } = payload as { theme: "light" | "dark" }; * setTheme(theme); * }); * * return
Listening for events...
; * } * ``` */ declare function useEmbedEvent(eventName: string, handler: (payload: Record) => void): void; //#endregion //#region src/lib/hooks/use-emit-embed-event.d.ts /** * React hook that returns a function to emit events to the external embedder. * Use this to communicate actions or state changes back to the parent application. * * @returns A function to emit events to the embedder * * @example * ```tsx * import { useEmitEmbedEvent } from "@superblocksteam/library"; * * function MyComponent() { * const emitEvent = useEmitEmbedEvent(); * * const handleFormSubmit = (data: FormData) => { * emitEvent("formSubmitted", { * formId: "contact-form", * timestamp: Date.now(), * data, * }); * }; * * const handleRowClick = (row: { id: string; name: string }) => { * emitEvent("rowSelected", { rowId: row.id, rowName: row.name }); * }; * * return ( * * ); * } * ``` */ declare function useEmitEmbedEvent(): (eventName: string, payload?: Record) => void; //#endregion export { type AgentInfo, type AnyApiRegistry, type ApiInput, type ApiOutput, type ApiRegistry, App, type CreateChild, type CreationContext, type DataTag, type DataTags, type EditorConfig, type EditorTemplate, type ExecuteApiOptions, type FromChildToParentMessageTypes, type FromChildToParentMessageTypesMap, type FromParentToChildMessageTypes, type FromParentToChildMessageTypesMap, type IframeLoadTimings, PageNotFound, Prop, type PropertiesPanelDefinition, Property, PropsCategory, RouteLoadError, Section, Superblocks, SbProvider as SuperblocksProvider, type TypedExecuteApi, type TypedUseApi, type TypedUseApiData, type UseApiDataOptions, type UseApiDataResult, type UseApiResult, type UseApiReturnType, createElement, createTypedExecuteApi, embedStore, executeApi, getAppMode, logoutIntegrations, queryClient, registerComponent, tailwindStylesCategory, useApi, useApiData, useApiStateful, useEmbedEvent, useEmbedProperties, useEmitEmbedEvent, useSuperblocksDataTags, useSuperblocksGroups, useSuperblocksProfiles, useSuperblocksUser, useTypedApi, useTypedApiData }; //# sourceMappingURL=index.d.ts.map