@superblocksteam/library 2.0.89-next.1 → 2.0.89

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.
package/dist/lib/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { n as consoleLogAttributes, t as early_console_buffer_default } from "../early-console-buffer-D4wVuyBf.js";
2
- import { A as useSuperblocksGroups, B as createManagedPropsList, C as addNewPromise, D as getAppMode, E as SuperblocksContextProvider, F as editorBridge, G as getEditStore, H as PropsCategory, I as iframeMessageHandler, L as isEmbeddedBySuperblocksFirstParty, M as useSuperblocksUser, N as sendNotification, O as useSuperblocksContext, P as colors$1, R as sendMessageImmediately, S as api_hmr_tracker_default, T as resolveById, U as Section, V as Prop, W as createPropertiesPanelDefinition, _ as root_store_default, a as FixWithClarkButton, b as createIframeSpan, c as ErrorContent, d as ErrorMessage$1, f as ErrorStack, g as StyledClarkIcon, h as SecondaryButton, i as getWidgetRectAnchorName, j as useSuperblocksProfiles, k as useSuperblocksDataTags, l as ErrorDetails, m as ErrorTitle, n as useJSXContext, o as ActionsContainer, p as ErrorSummary, r as getWidgetAnchorName, s as ErrorContainer, u as ErrorIconContainer, v as startEditorSync, w as rejectById, x as getContextFromTraceHeaders, y as generateId, z as isEditMode } from "../jsx-wrapper-C8LEtdzp.js";
2
+ import { A as useSuperblocksProfiles, B as PropsCategory, C as addNewPromise, D as getAppMode, E as SuperblocksContextProvider, F as iframeMessageHandler, H as createPropertiesPanelDefinition, I as isEmbeddedBySuperblocksFirstParty, L as isEditMode, M as sendNotification, N as colors$1, O as useSuperblocksContext, P as editorBridge, R as createManagedPropsList, S as api_hmr_tracker_default, T as resolveById, U as getEditStore, V as Section, _ as root_store_default, a as FixWithClarkButton, b as createIframeSpan, c as ErrorContent, d as ErrorMessage$1, f as ErrorStack, g as StyledClarkIcon, h as SecondaryButton, i as getWidgetRectAnchorName, j as useSuperblocksUser, k as useSuperblocksGroups, l as ErrorDetails, m as ErrorTitle, n as useJSXContext, o as ActionsContainer, p as ErrorSummary, r as getWidgetAnchorName, s as ErrorContainer, u as ErrorIconContainer, v as startEditorSync, w as rejectById, x as getContextFromTraceHeaders, y as generateId, z as Prop } from "../jsx-wrapper-DL2O6Y1G.js";
3
3
  import { n as initTracerProviderWithOrigin } from "../utils-BGEEeYie.js";
4
4
  import { action, autorun, computed, makeAutoObservable, makeObservable, observable, reaction, when } from "mobx";
5
5
  import { Dim, NATIVE_COMPONENT_TYPES, NO_SELECT_ATTRIBUTE, Property, Property as Property$1, SELECTOR_ID_ATTRIBUTE, SOURCE_ID_ATTRIBUTE, generateSourceId, getBindingIdentifier } from "@superblocksteam/library-shared";
6
6
  import { UNSAFE_DataRouterContext, generatePath, useLocation, useNavigate, useParams, useRouteError } from "react-router";
7
7
  import * as React$1 from "react";
8
- import React, { Suspense, createElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
8
+ import React, { Suspense, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
9
9
  import { isEqual } from "lodash";
10
10
  import { ISocketWithClientAuth, OBS_TAG_APPLICATION_ID, connectWebSocket, createISocketClient } from "@superblocksteam/shared";
11
11
  import { AiContextMode, AiGenerationState, ViteMessageKind } from "@superblocksteam/library-shared/types";
@@ -16,8 +16,6 @@ import defaultTheme from "tailwindcss/defaultTheme";
16
16
  import postcss from "postcss";
17
17
  import colors from "tailwindcss/colors";
18
18
  import { Observer, observer } from "mobx-react-lite";
19
- import { execute, isStreamingApi } from "@superblocksteam/sdk-api";
20
- import zodToJsonSchema from "zod-to-json-schema";
21
19
  import * as Dialog from "@radix-ui/react-dialog";
22
20
  import posthog from "posthog-js";
23
21
  import { Graph } from "@dagrejs/graphlib";
@@ -778,102 +776,6 @@ function registerHtmlElements() {
778
776
  registerComponent("meta", htmlTagSectionsTemplate({ hasChildren: false }));
779
777
  }
780
778
 
781
- //#endregion
782
- //#region src/lib/internal-details/lib/jwt-utils.ts
783
- /**
784
- * Known claim keys that are standard or Superblocks-specific.
785
- * These are excluded from customClaims to avoid duplication.
786
- */
787
- const KNOWN_CLAIM_KEYS = new Set([
788
- "sub",
789
- "email",
790
- "user_email",
791
- "name",
792
- "groups",
793
- "iss",
794
- "aud",
795
- "exp",
796
- "nbf",
797
- "iat",
798
- "jti",
799
- "userId",
800
- "user_id",
801
- "organizationId",
802
- "org_id"
803
- ]);
804
- /**
805
- * Decodes a base64url-encoded string.
806
- *
807
- * JWT uses base64url encoding which replaces + with - and / with _.
808
- * This function handles the conversion and decoding.
809
- */
810
- function base64UrlDecode(str) {
811
- const base64 = str.replace(/-/g, "+").replace(/_/g, "/");
812
- const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
813
- try {
814
- const binaryStr = atob(padded);
815
- const bytes = Uint8Array.from(binaryStr, (c) => c.charCodeAt(0));
816
- return new TextDecoder().decode(bytes);
817
- } catch (error) {
818
- console.warn("[jwt-utils] Failed to decode base64url string -- JWT payload cannot be parsed:", error);
819
- return "";
820
- }
821
- }
822
- /**
823
- * Parses a JWT token and extracts the payload claims.
824
- *
825
- * @param token - The JWT token string (with or without "Bearer " prefix)
826
- * @returns The decoded claims object, or null if parsing fails
827
- */
828
- function parseJwtClaims(token) {
829
- if (!token) return null;
830
- const parts = (token.startsWith("Bearer ") ? token.slice(7) : token).split(".");
831
- if (parts.length !== 3) return null;
832
- try {
833
- const payloadJson = base64UrlDecode(parts[1]);
834
- return JSON.parse(payloadJson);
835
- } catch (error) {
836
- console.warn("[jwt-utils] Failed to parse JWT claims:", error);
837
- return null;
838
- }
839
- }
840
- /**
841
- * Extracts SDK user information from JWT claims.
842
- *
843
- * Maps standard JWT claims to the SdkApiUser interface expected
844
- * by the SDK's executeApi function.
845
- *
846
- * @param claims - Parsed JWT claims
847
- * @returns SdkApiUser object with extracted user info
848
- */
849
- function extractSdkUserFromClaims(claims) {
850
- const userId = claims.sub || claims.userId || claims.user_id || "anonymous";
851
- const email = claims.email ?? claims.user_email;
852
- const groups = Array.isArray(claims.groups) ? claims.groups : [];
853
- const customClaims = {};
854
- for (const [key, value] of Object.entries(claims)) if (!KNOWN_CLAIM_KEYS.has(key)) customClaims[key] = value;
855
- return {
856
- userId,
857
- email,
858
- name: claims.name,
859
- groups,
860
- customClaims: Object.freeze(customClaims)
861
- };
862
- }
863
- /**
864
- * Parses a JWT token and extracts SDK user information.
865
- *
866
- * Convenience function that combines parseJwtClaims and extractSdkUserFromClaims.
867
- *
868
- * @param token - The JWT token string
869
- * @returns SdkApiUser object, or null if parsing fails
870
- */
871
- function extractSdkUserFromJwt(token) {
872
- const claims = parseJwtClaims(token);
873
- if (!claims) return null;
874
- return extractSdkUserFromClaims(claims);
875
- }
876
-
877
779
  //#endregion
878
780
  //#region src/lib/internal-details/handle-bootstrap-response.ts
879
781
  const handleBootstrapResponse = (event) => {
@@ -881,14 +783,6 @@ const handleBootstrapResponse = (event) => {
881
783
  root_store_default.userId = event.data.payload.userId;
882
784
  root_store_default.apis.agentUrls = event.data.payload.agentUrls;
883
785
  root_store_default.apis.agents = event.data.payload.agents;
884
- const sdkApiEnabled = !!event.data.payload.featureFlags?.["clark.sdk-api.enabled"];
885
- root_store_default.setSdkApiEnabled(sdkApiEnabled);
886
- const sdkUser = extractSdkUserFromJwt(event.data.payload.token);
887
- if (sdkUser) root_store_default.setSdkUser(sdkUser);
888
- else if (event.data.payload.userId) {
889
- console.log("[handle-bootstrap-response] Auth0 JWT not available for SDK user extraction. Custom claims (groups, email) will not be available. Falling back to userId from payload.");
890
- root_store_default.setSdkUser({ userId: event.data.payload.userId });
891
- } else console.log("[handle-bootstrap-response] No user info available for SDK API execution. Neither auth0 JWT nor userId was provided in the bootstrap payload.");
892
786
  root_store_default.apis.setTokens(event.data.payload.token, event.data.payload.accessToken);
893
787
  root_store_default.apis.notifyBootstrapComplete();
894
788
  const featureFlags = event.data.payload.featureFlags;
@@ -959,294 +853,53 @@ function useGetCurrentUserQuery() {
959
853
  }
960
854
 
961
855
  //#endregion
962
- //#region src/lib/internal-details/lib/utils/zod-to-typescript.ts
963
- /**
964
- * Zod schema conversion utilities.
965
- *
966
- * Converts Zod schemas to TypeScript type strings and JSON Schema for display in the UI.
967
- */
968
- /**
969
- * Convert a Zod schema to JSON Schema format.
970
- *
971
- * @param schema - The Zod schema to convert
972
- * @returns JSON Schema representation
973
- */
974
- function convertToJsonSchema(schema) {
975
- try {
976
- return zodToJsonSchema(schema, {
977
- $refStrategy: "none",
978
- errorMessages: false
979
- });
980
- } catch (error) {
981
- console.warn("[zod-to-typescript] Failed to convert to JSON Schema:", error);
982
- return { type: "unknown" };
983
- }
984
- }
985
- /**
986
- * Convert a JSON Schema to TypeScript type string.
987
- *
988
- * @param schema - The JSON Schema to convert
989
- * @param indent - Current indentation level
990
- * @returns TypeScript type string representation
991
- */
992
- function jsonSchemaToTypescript(schema, indent = 0) {
993
- const indentStr = " ".repeat(indent);
994
- const nextIndent = " ".repeat(indent + 1);
995
- if (schema.$ref) return schema.$ref.split("/").pop() || "unknown";
996
- if (schema.const !== void 0) return typeof schema.const === "string" ? `"${schema.const}"` : String(schema.const);
997
- if (schema.enum) return schema.enum.map((v) => typeof v === "string" ? `"${v}"` : String(v)).join(" | ");
998
- if (schema.anyOf) return schema.anyOf.map((s) => jsonSchemaToTypescript(s, indent)).join(" | ");
999
- if (schema.oneOf) return schema.oneOf.map((s) => jsonSchemaToTypescript(s, indent)).join(" | ");
1000
- if (schema.allOf) return schema.allOf.map((s) => jsonSchemaToTypescript(s, indent)).join(" & ");
1001
- const nullable = schema.nullable ? " | null" : "";
1002
- switch (Array.isArray(schema.type) ? schema.type[0] : schema.type || "unknown") {
1003
- case "string": return "string" + nullable;
1004
- case "number":
1005
- case "integer": return "number" + nullable;
1006
- case "boolean": return "boolean" + nullable;
1007
- case "null": return "null";
1008
- case "array":
1009
- if (schema.items) {
1010
- if (Array.isArray(schema.items)) return `[${schema.items.map((s) => jsonSchemaToTypescript(s, indent)).join(", ")}]` + nullable;
1011
- const itemType = jsonSchemaToTypescript(schema.items, indent);
1012
- return (itemType.includes(" | ") || itemType.includes(" & ") ? `(${itemType})[]` : `${itemType}[]`) + nullable;
1013
- }
1014
- return "unknown[]" + nullable;
1015
- case "object": {
1016
- if (!schema.properties || Object.keys(schema.properties).length === 0) {
1017
- if (schema.additionalProperties) return `Record<string, ${typeof schema.additionalProperties === "object" ? jsonSchemaToTypescript(schema.additionalProperties, indent) : "unknown"}>` + nullable;
1018
- return "{}" + nullable;
1019
- }
1020
- const required = schema.required || [];
1021
- return `{\n${Object.entries(schema.properties).map(([key, propSchema]) => {
1022
- const isRequired = required.includes(key);
1023
- const propType = jsonSchemaToTypescript(propSchema, indent + 1);
1024
- return `${nextIndent}${key}${isRequired ? "" : "?"}: ${propType}`;
1025
- }).join(";\n")};\n${indentStr}}` + nullable;
1026
- }
1027
- default: return "unknown" + nullable;
1028
- }
1029
- }
1030
- /**
1031
- * Convert a Zod schema to both TypeScript string and JSON Schema.
1032
- *
1033
- * @param schema - The Zod schema to convert
1034
- * @returns Object containing both representations
1035
- */
1036
- function convertZodSchema(schema) {
1037
- const jsonSchema = convertToJsonSchema(schema);
1038
- return {
1039
- typescript: jsonSchemaToTypescript(jsonSchema),
1040
- jsonSchema
1041
- };
1042
- }
1043
-
1044
- //#endregion
1045
- //#region src/lib/internal-details/lib/sdk-api-registry.ts
1046
- /**
1047
- * SDK API Registry for the library iframe.
1048
- *
1049
- * Tracks registered SDK APIs and notifies ui-code-mode when APIs are
1050
- * registered or unregistered (for display in the sidebar).
1051
- */
1052
- /**
1053
- * Set of registered API names to prevent duplicate registrations.
1054
- */
1055
- const registeredApis = /* @__PURE__ */ new Set();
856
+ //#region src/lib/internal-details/use-api.ts
857
+ const getApiPath = (name) => {
858
+ let apiPath = name;
859
+ if (!apiPath.startsWith("/apis")) apiPath = `/apis/${name}/api.yaml`;
860
+ return apiPath;
861
+ };
1056
862
  /**
1057
- * Extract metadata from a compiled API for display in the UI.
863
+ * React hook for executing Superblocks APIs with type-safe inputs and outputs.
1058
864
  *
1059
- * @param name - The API name
1060
- * @param api - The compiled API (regular or streaming)
1061
- * @param sourceCode - Optional TypeScript source code
1062
- * @returns SdkApiMetadata for the API
1063
- */
1064
- function extractSdkApiMetadata(name, api, sourceCode) {
1065
- const streaming = isStreamingApi(api);
1066
- const inputSchema = convertZodSchema(api.inputSchema);
1067
- let outputSchema;
1068
- let chunkSchema;
1069
- if (streaming) chunkSchema = convertZodSchema(api.chunkSchema);
1070
- else outputSchema = convertZodSchema(api.outputSchema);
1071
- return {
1072
- name,
1073
- inputSchema,
1074
- outputSchema,
1075
- chunkSchema,
1076
- isStreaming: streaming,
1077
- integrations: (api.integrations ?? []).map((integration) => ({
1078
- key: integration.key,
1079
- pluginId: integration.pluginId,
1080
- name: integration.key,
1081
- id: integration.id
1082
- })),
1083
- sourceCode
1084
- };
1085
- }
1086
- /**
1087
- * Register an SDK API and notify ui-code-mode.
865
+ * @param name - The name of the registered API to execute
866
+ * @returns An object with `run` and `cancel` functions
1088
867
  *
1089
- * @param name - The API name
1090
- * @param api - The compiled API
1091
- * @param sourceCode - Optional TypeScript source code for display in the UI
1092
- * @returns true if the API was newly registered, false if already existed
1093
- */
1094
- function registerSdkApi(name, api, sourceCode) {
1095
- const isNew = !registeredApis.has(name);
1096
- registeredApis.add(name);
1097
- sendMessageImmediately({
1098
- type: "sdk-api-registered",
1099
- payload: {
1100
- name,
1101
- metadata: extractSdkApiMetadata(name, api, sourceCode)
1102
- }
1103
- });
1104
- console.debug(`[sdk-api-registry] ${isNew ? "Registered" : "Updated"} SDK API: ${name}`);
1105
- return isNew;
1106
- }
1107
- /**
1108
- * Update the source code for an already-registered SDK API.
1109
- * This is called by the dev server when an API file changes.
868
+ * @example
869
+ * ```typescript
870
+ * const myApi = useApiStateful("getUserData");
1110
871
  *
1111
- * @param name - The API name
1112
- * @param sourceCode - The new TypeScript source code
1113
- */
1114
- function updateSdkApiSourceCode(name, sourceCode) {
1115
- if (!registeredApis.has(name)) {
1116
- console.warn(`[sdk-api-registry] Cannot update source for unregistered API: ${name}`);
1117
- return;
1118
- }
1119
- sendMessageImmediately({
1120
- type: "sdk-api-source-updated",
1121
- payload: {
1122
- name,
1123
- sourceCode
1124
- }
1125
- });
1126
- console.debug(`[sdk-api-registry] Updated source code for SDK API: ${name}`);
1127
- }
1128
- /**
1129
- * Clear all registered SDK APIs.
1130
- * Useful for testing or when the application reloads.
1131
- */
1132
- function clearSdkApiRegistry() {
1133
- registeredApis.clear();
1134
- }
1135
-
1136
- //#endregion
1137
- //#region src/lib/internal-details/lib/sdk-api-discovery.ts
1138
- /**
1139
- * SDK API Discovery Module.
872
+ * try {
873
+ * const result = await myApi.run({ userId: "123" });
874
+ * console.log(result);
875
+ * } catch (error) {
876
+ * // error is a string describing what went wrong
877
+ * console.error(error);
878
+ * }
879
+ * ```
1140
880
  *
1141
- * Discovers and registers all SDK APIs by importing the app's API registry
1142
- * at server/apis/index.ts. This enables SDK APIs to appear in the sidebar
1143
- * immediately, rather than waiting for them to be executed.
1144
- */
1145
- /**
1146
- * Discover and register all SDK APIs from the app's API registry.
881
+ * ## Error Handling
1147
882
  *
1148
- * Imports server/apis/index.ts (the same registry used by useApi for type
1149
- * inference) and registers each exported API with the SDK API registry.
1150
- */
1151
- async function discoverAndRegisterSdkApis() {
1152
- if (!root_store_default.sdkApiEnabled) return;
1153
- try {
1154
- const apis = (await import(new URL("/server/apis/index.ts", window.location.origin).href)).default;
1155
- const apiNames = Object.keys(apis);
1156
- if (apiNames.length === 0) {
1157
- console.debug("[sdk-api-discovery] No SDK APIs found in registry");
1158
- return;
1159
- }
1160
- console.debug(`[sdk-api-discovery] Discovering ${apiNames.length} SDK APIs:`, apiNames);
1161
- const sourcePromises = apiNames.map(async (name) => {
1162
- try {
1163
- const resp = await fetch(`/sb-raw-source/server/apis/${name}/api.ts`);
1164
- return resp.ok ? await resp.text() : void 0;
1165
- } catch {
1166
- return;
1167
- }
1168
- });
1169
- const sources = await Promise.all(sourcePromises);
1170
- const results = await Promise.allSettled(apiNames.map(async (name, i) => {
1171
- const apiModule = apis[name];
1172
- if (!apiModule) throw new Error(`API ${name} not found in registry`);
1173
- registerSdkApi(name, apiModule, sources[i]);
1174
- }));
1175
- const succeeded = results.filter((r) => r.status === "fulfilled").length;
1176
- const failed = results.filter((r) => r.status === "rejected").length;
1177
- console.debug(`[sdk-api-discovery] Registered ${succeeded} APIs, ${failed} failed`);
1178
- } catch (error) {
1179
- console.error("[sdk-api-discovery] Failed to discover SDK APIs:", error);
1180
- }
1181
- }
1182
- if (import.meta.hot) import.meta.hot.accept("/server/apis/index.ts", () => {
1183
- if (!root_store_default.sdkApiEnabled) return;
1184
- console.debug("[sdk-api-discovery] API registry updated via HMR, re-running discovery");
1185
- clearSdkApiRegistry();
1186
- discoverAndRegisterSdkApis();
1187
- });
1188
-
1189
- //#endregion
1190
- //#region src/lib/internal-details/use-api.ts
1191
- /**
1192
- * Unified API hook module.
883
+ * When an API execution fails, the `run` function throws a **string** error message.
884
+ * The error format can be one of:
1193
885
  *
1194
- * Provides both the legacy YAML-based API system (`useApiStateful`) and the
1195
- * new SDK-based API system (`useSdkApi`). The public `useApi` hook delegates
1196
- * to one or the other based on the `sdkApiEnabled` feature flag on rootStore.
886
+ * - **Client errors (4xx)**: System error message from the server
887
+ * - Example: `"Authentication failed"`, `"Invalid request parameters"`
1197
888
  *
1198
- * The flag is set once at bootstrap time and never changes within a session,
1199
- * so the conditional hook delegation is safe.
1200
- */
1201
- /**
1202
- * Get the API path for an API by name.
889
+ * - **API execution errors**: Formatted message from unhandled API errors
890
+ * - Example: `"Error in API: Division by zero"`, `"Error in API: Database connection failed"`
1203
891
  *
1204
- * When SDK APIs are enabled, paths point to `/server/apis/<name>/api.ts`.
1205
- * When using legacy YAML mode, paths point to `/apis/<name>/api.yaml`.
1206
- */
1207
- const getApiPath = (name) => {
1208
- if (root_store_default.sdkApiEnabled) {
1209
- let apiPath$1 = name;
1210
- if (!apiPath$1.startsWith("/server/apis")) apiPath$1 = `/server/apis/${name}/api.ts`;
1211
- return apiPath$1;
1212
- }
1213
- let apiPath = name;
1214
- if (!apiPath.startsWith("/apis")) apiPath = `/apis/${name}/api.yaml`;
1215
- return apiPath;
1216
- };
1217
- /**
1218
- * Resolve integration configs from the parent before API execution.
1219
- * Only used when SDK API mode is enabled.
892
+ * - **Infrastructure errors**: High-level error messages
893
+ * - Example: `"No application ID was found"`, `"No active agent found"`
1220
894
  *
1221
- * @deprecated Kept for backward compatibility with edit mode.
1222
- */
1223
- async function resolveIntegrations(integrations) {
1224
- if (integrations.length === 0) return [];
1225
- return new Promise((resolve, reject) => {
1226
- const callbackId = addNewPromise((result) => {
1227
- resolve(result);
1228
- }, false, reject);
1229
- sendMessageImmediately({
1230
- type: "sdk-resolve-integrations",
1231
- payload: {
1232
- integrations: integrations.map((i) => ({
1233
- key: i.key,
1234
- pluginId: i.pluginId,
1235
- id: i.id
1236
- })),
1237
- callbackId
1238
- }
1239
- });
1240
- });
1241
- }
1242
- /**
1243
- * React hook for executing YAML-based Superblocks APIs.
895
+ * The error is also logged to the console before being thrown.
1244
896
  *
1245
- * This is the legacy API system that uses `rootStore.apis.runApiByPath`.
1246
- * It remains the default when the `sdkApiEnabled` flag is off.
897
+ * ## Usage Notes
1247
898
  *
1248
- * @param name - The name of the registered API to execute
1249
- * @returns An object with `run` and `cancel` functions
899
+ * - Always wrap `run()` calls in try/catch blocks to handle errors gracefully
900
+ * - Errors are thrown as strings, not Error objects
901
+ * - If the API executes successfully but returns no data, `run()` returns `undefined`
902
+ * - Use `cancel()` to abort in-flight API requests
1250
903
  */
1251
904
  function useApiStateful(name) {
1252
905
  const { sourceId } = useJSXContext();
@@ -1270,49 +923,6 @@ function useApiStateful(name) {
1270
923
  }, [name])
1271
924
  };
1272
925
  }
1273
- /**
1274
- * React hook for calling SDK-based APIs via postMessage to the parent frame.
1275
- * Only active when `rootStore.sdkApiEnabled` is true.
1276
- */
1277
- function useSdkApi(apiName) {
1278
- return {
1279
- run: useCallback(async (inputs) => {
1280
- return new Promise((resolve, reject) => {
1281
- const callbackId = addNewPromise((result) => {
1282
- const executionResult = result;
1283
- if (executionResult.success) resolve(executionResult.output);
1284
- else reject(executionResult.error ?? /* @__PURE__ */ new Error("API execution failed"));
1285
- }, false, reject);
1286
- sendMessageImmediately({
1287
- type: "sdk-execute-api",
1288
- payload: {
1289
- apiName,
1290
- input: inputs ?? {},
1291
- callbackId
1292
- }
1293
- });
1294
- });
1295
- }, [apiName]),
1296
- cancel: useCallback(async () => {
1297
- throw new Error(`Cancellation is not yet implemented for SDK APIs. API "${apiName}" will continue executing.`);
1298
- }, [apiName])
1299
- };
1300
- }
1301
- function useApi(apiName) {
1302
- if (root_store_default.sdkApiEnabled) return useSdkApi(apiName);
1303
- return useApiStateful(apiName);
1304
- }
1305
- /**
1306
- * Creates a typed version of useApi bound to a specific API registry type.
1307
- *
1308
- * This enables full type inference using only type imports from the server,
1309
- * keeping backend code out of the client bundle.
1310
- *
1311
- * @returns A typed useApi function
1312
- */
1313
- function useTypedApi() {
1314
- return useApi;
1315
- }
1316
926
 
1317
927
  //#endregion
1318
928
  //#region src/lib/internal-details/embed-store.ts
@@ -2024,21 +1634,10 @@ var AsyncSocket = class {
2024
1634
  //#endregion
2025
1635
  //#region src/edit-mode/source-update-api.ts
2026
1636
  const PING_INTERVAL_MS = 15e3;
2027
- function safeStringifyError(error) {
2028
- if (!error) return "Unknown error";
2029
- if (typeof error === "string") return error;
2030
- if (error instanceof Error) return error.message;
2031
- try {
2032
- return JSON.stringify(error);
2033
- } catch {
2034
- return String(error);
2035
- }
2036
- }
2037
1637
  var OperationAPI = class {
2038
1638
  retryAttempts = 0;
2039
1639
  asyncSocket = new AsyncSocket();
2040
1640
  isocket = null;
2041
- currentAuthorization;
2042
1641
  constructor(serverUrl) {
2043
1642
  this.serverUrl = serverUrl;
2044
1643
  }
@@ -2046,7 +1645,6 @@ var OperationAPI = class {
2046
1645
  * @throws {Error} if the websocket connection can't be initiated after 3 attempts
2047
1646
  */
2048
1647
  async connect({ peerId, userId, authorization, applicationId, traceContext, connectionType, connectionTarget }) {
2049
- this.currentAuthorization = authorization;
2050
1648
  try {
2051
1649
  const result = await connectSocket(this.serverUrl, {
2052
1650
  peerId,
@@ -2059,6 +1657,7 @@ var OperationAPI = class {
2059
1657
  onClose: this.handleSocketClose({
2060
1658
  peerId,
2061
1659
  userId,
1660
+ authorization,
2062
1661
  applicationId
2063
1662
  })
2064
1663
  });
@@ -2067,12 +1666,13 @@ var OperationAPI = class {
2067
1666
  this.asyncSocket.setSocket(result.socket);
2068
1667
  this.isocket = result.isocket;
2069
1668
  } else throw new Error("Failed to create socket connection");
2070
- } catch (error) {
1669
+ } catch {
2071
1670
  this.retryAttempts++;
2072
- console.info(`App<>Dev box initial connection failed, retrying attempt ${this.retryAttempts}...`, safeStringifyError(error));
1671
+ console.info(`App<>Dev box initial connection failed, retrying attempt ${this.retryAttempts}...`);
2073
1672
  await this.retryConnection({
2074
1673
  peerId,
2075
1674
  userId,
1675
+ authorization,
2076
1676
  applicationId
2077
1677
  });
2078
1678
  }
@@ -2089,13 +1689,12 @@ var OperationAPI = class {
2089
1689
  * This is called when the token is refreshed in the parent window.
2090
1690
  */
2091
1691
  updateAuthorization(newAuthorization) {
2092
- this.currentAuthorization = newAuthorization;
2093
1692
  if (this.isocket) {
2094
1693
  this.isocket.setAuthorization(newAuthorization);
2095
1694
  console.log("[internal] [OperationAPI] Updated iframe socket authorization token");
2096
1695
  } else console.warn("[internal] [OperationAPI] Cannot update authorization: socket not yet initialized");
2097
1696
  }
2098
- handleSocketClose({ peerId, userId, applicationId }) {
1697
+ handleSocketClose({ peerId, userId, authorization, applicationId }) {
2099
1698
  return async (event) => {
2100
1699
  if (event.code === 1008) {
2101
1700
  sendNotification({
@@ -2109,34 +1708,24 @@ var OperationAPI = class {
2109
1708
  }
2110
1709
  console.info(`[internal] [OperationAPI] App<>Dev box Socket closed, retrying attempt ${this.retryAttempts + 1}...`);
2111
1710
  root_store_default.editStore?.connectionManager.disconnect();
2112
- try {
2113
- await this.retryConnection({
2114
- peerId,
2115
- userId,
2116
- applicationId
2117
- });
2118
- } catch (error) {
2119
- console.error("[internal] [OperationAPI] Failed to reconnect after all retry attempts", safeStringifyError(error));
2120
- this.asyncSocket.clearSocket();
2121
- sendNotification({
2122
- message: "Connection lost",
2123
- description: "Failed to reconnect to the dev server. Please refresh the page.",
2124
- type: "error",
2125
- duration: 600
2126
- });
2127
- }
2128
- };
2129
- }
2130
- async retryConnection({ peerId, userId, applicationId }) {
2131
- if (this.retryAttempts < 3) {
2132
- if (!this.currentAuthorization) console.warn("[internal] [OperationAPI] Retrying connection without authorization token");
2133
- await this.connect({
1711
+ await this.retryConnection({
2134
1712
  peerId,
2135
1713
  userId,
2136
- authorization: this.currentAuthorization,
1714
+ authorization,
2137
1715
  applicationId
2138
1716
  });
2139
- } else {
1717
+ if (this.retryAttempts >= 3) this.asyncSocket.clearSocket();
1718
+ this.retryAttempts++;
1719
+ };
1720
+ }
1721
+ async retryConnection({ peerId, userId, authorization, applicationId }) {
1722
+ if (this.retryAttempts < 3) await this.connect({
1723
+ peerId,
1724
+ userId,
1725
+ authorization,
1726
+ applicationId
1727
+ });
1728
+ else {
2140
1729
  console.info(`[internal] [OperationAPI] App<>Dev box Socket closed, failed to reconnect after 3 attempts. Throwing error.`);
2141
1730
  throw new Error("Failed to reconnect after 3 attempts");
2142
1731
  }
@@ -2216,11 +1805,6 @@ async function connectSocket(serverUrl, { peerId, userId, applicationId, authori
2216
1805
  name: err.name
2217
1806
  };
2218
1807
  }
2219
- }],
2220
- sdkApiSourceUpdated: [async (payload) => {
2221
- const { apiName, sourceCode } = payload;
2222
- console.debug(`[source-update-api] SDK API source updated: ${apiName}`);
2223
- updateSdkApiSourceCode(apiName, sourceCode);
2224
1808
  }]
2225
1809
  }, [], trace.getTracer("superblocks-ui-framework"), {
2226
1810
  onClose: (event) => {
@@ -4120,15 +3704,10 @@ if (import.meta.hot) {
4120
3704
  });
4121
3705
  import.meta.hot.on("vite:beforeUpdate", (args) => {
4122
3706
  try {
4123
- const paths = (args?.updates ?? []).map((update) => update.path);
4124
- const pathStr = paths.join(", ");
3707
+ const pathStr = (args?.updates ?? []).map((update) => update.path).join(", ");
4125
3708
  console.debug("[internal] [iframe-wrappers] vite:beforeUpdate", pathStr);
4126
- if (paths.some((path) => path.includes("server/apis/index.ts")) && root_store_default.sdkApiEnabled) {
4127
- console.debug("[internal] [iframe-wrappers] API registry updated, re-discovering APIs");
4128
- discoverAndRegisterSdkApis();
4129
- }
4130
- } catch (error) {
4131
- console.warn("[internal] [iframe-wrappers] vite:beforeUpdate error:", error);
3709
+ } catch (_error) {
3710
+ console.debug("[internal] [iframe-wrappers] vite:beforeUpdate");
4132
3711
  }
4133
3712
  });
4134
3713
  }
@@ -4189,11 +3768,6 @@ const IframeConnected = observer(function IframeConnected$1(props) {
4189
3768
  console.debug("[internal] [iframe-wrappers] sending ready");
4190
3769
  editorBridge.sendReady();
4191
3770
  }, []);
4192
- useEffect(() => {
4193
- return reaction(() => root_store_default.sdkApiEnabled, (enabled) => {
4194
- if (enabled) discoverAndRegisterSdkApis();
4195
- }, { fireImmediately: true });
4196
- }, []);
4197
3771
  useEffect(() => {
4198
3772
  return linkModifierInterceptor({ isEditMode: true });
4199
3773
  }, []);
@@ -6417,174 +5991,6 @@ function RouteLoadError() {
6417
5991
  ] }) });
6418
5992
  }
6419
5993
 
6420
- //#endregion
6421
- //#region src/lib/internal-details/use-streaming-api.ts
6422
- /**
6423
- * React hook for calling streaming SDK APIs with real-time chunk delivery.
6424
- *
6425
- * Returns an AsyncGenerator that yields chunks as they arrive, allowing
6426
- * natural iteration with `for await...of`.
6427
- *
6428
- * @param api - The imported CompiledStreamingApi definition
6429
- * @returns Object with `stream` function and `cancel` function
6430
- *
6431
- * @example
6432
- * ```typescript
6433
- * import StreamChatApi from "../apis/StreamChat/api";
6434
- * import { useStreamingApi } from "@superblocksteam/library";
6435
- *
6436
- * const { stream, cancel } = useStreamingApi(StreamChatApi);
6437
- *
6438
- * // Execute and iterate over chunks
6439
- * const generator = stream({ prompt: "Hello!" });
6440
- *
6441
- * for await (const chunk of generator) {
6442
- * console.log(chunk.text);
6443
- * // Update UI with each chunk
6444
- * }
6445
- * ```
6446
- *
6447
- * @example With try/catch for error handling
6448
- * ```typescript
6449
- * const { stream } = useStreamingApi(StreamChatApi);
6450
- *
6451
- * try {
6452
- * for await (const chunk of stream({ prompt: "Hello!" })) {
6453
- * appendToOutput(chunk.text);
6454
- * }
6455
- * console.log("Stream completed!");
6456
- * } catch (error) {
6457
- * console.error("Stream error:", error);
6458
- * }
6459
- * ```
6460
- */
6461
- function useStreamingApi(api) {
6462
- const sdkApiEnabled = root_store_default.sdkApiEnabled;
6463
- const cancelRef = useRef(null);
6464
- return {
6465
- stream: useCallback((inputs) => {
6466
- if (!sdkApiEnabled) throw new Error("useStreamingApi requires SDK API mode to be enabled. This hook is only available in fullstack applications.");
6467
- return createStreamGenerator(api, inputs, cancelRef);
6468
- }, [api, sdkApiEnabled]),
6469
- cancel: useCallback(() => {
6470
- if (cancelRef.current) cancelRef.current();
6471
- }, [])
6472
- };
6473
- }
6474
- /**
6475
- * Creates an async generator for streaming API execution.
6476
- */
6477
- async function* createStreamGenerator(api, inputs, cancelRef) {
6478
- if (!isStreamingApi(api)) throw new Error("Expected a streaming API. Use useApi() for non-streaming APIs.");
6479
- const executeQuery = async (integrationId, request, input) => {
6480
- return new Promise((resolve, reject) => {
6481
- sendMessageImmediately({
6482
- type: "sdk-execute-query",
6483
- payload: {
6484
- integrationId,
6485
- request,
6486
- input,
6487
- callbackId: addNewPromise(resolve, false, reject)
6488
- }
6489
- });
6490
- });
6491
- };
6492
- const executeStreamingQuery = async function* (integrationId, request) {
6493
- const chunkQueue = [];
6494
- let resolveNext = null;
6495
- let streamComplete = false;
6496
- let streamError = null;
6497
- const streamId = `stream-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
6498
- const handleChunk = (event) => {
6499
- if (event.source !== window.parent) return;
6500
- if (event.data?.type === "sdk-stream-chunk" && event.data?.payload?.streamId === streamId) {
6501
- const { chunk, done, error } = event.data.payload;
6502
- if (error) {
6503
- streamError = new Error(error.message || "Stream error");
6504
- streamComplete = true;
6505
- if (resolveNext) {
6506
- resolveNext({
6507
- value: void 0,
6508
- done: true
6509
- });
6510
- resolveNext = null;
6511
- }
6512
- return;
6513
- }
6514
- if (done) {
6515
- streamComplete = true;
6516
- if (resolveNext) {
6517
- resolveNext({
6518
- value: void 0,
6519
- done: true
6520
- });
6521
- resolveNext = null;
6522
- }
6523
- return;
6524
- }
6525
- if (chunk !== void 0) if (resolveNext) {
6526
- resolveNext({
6527
- value: chunk,
6528
- done: false
6529
- });
6530
- resolveNext = null;
6531
- } else chunkQueue.push(chunk);
6532
- }
6533
- };
6534
- window.addEventListener("message", handleChunk);
6535
- cancelRef.current = () => {
6536
- streamComplete = true;
6537
- if (resolveNext) {
6538
- resolveNext({
6539
- value: void 0,
6540
- done: true
6541
- });
6542
- resolveNext = null;
6543
- }
6544
- window.removeEventListener("message", handleChunk);
6545
- sendMessageImmediately({
6546
- type: "sdk-cancel-stream",
6547
- payload: { streamId }
6548
- });
6549
- };
6550
- sendMessageImmediately({
6551
- type: "sdk-execute-streaming-query",
6552
- payload: {
6553
- integrationId,
6554
- request,
6555
- streamId
6556
- }
6557
- });
6558
- try {
6559
- while (!streamComplete || chunkQueue.length > 0) {
6560
- if (streamError) throw streamError;
6561
- if (chunkQueue.length > 0) yield chunkQueue.shift();
6562
- else if (!streamComplete) {
6563
- const result = await new Promise((resolve) => {
6564
- resolveNext = resolve;
6565
- });
6566
- if (!result.done) yield result.value;
6567
- }
6568
- }
6569
- if (streamError) throw streamError;
6570
- } finally {
6571
- window.removeEventListener("message", handleChunk);
6572
- cancelRef.current = null;
6573
- }
6574
- };
6575
- const resolvedIntegrations = await resolveIntegrations(api.integrations ?? []);
6576
- const generator = execute(api, {
6577
- input: inputs ?? {},
6578
- integrations: resolvedIntegrations,
6579
- executionId: `sdk-stream-${Date.now()}`,
6580
- env: {},
6581
- user: root_store_default.sdkUser,
6582
- executeQuery,
6583
- executeStreamingQuery
6584
- });
6585
- for await (const chunk of generator) yield chunk;
6586
- }
6587
-
6588
5994
  //#endregion
6589
5995
  //#region src/lib/user-facing/global-functions.ts
6590
5996
  async function logoutIntegrations() {
@@ -6764,5 +6170,5 @@ early_console_buffer_default.getInstance().patchEarly();
6764
6170
  registerHtmlElements();
6765
6171
 
6766
6172
  //#endregion
6767
- export { App, PageNotFound, Prop, Property, PropsCategory, RouteLoadError, Section, Superblocks, sb_provider_default as SuperblocksProvider, createElement, embedStore, getAppMode, logoutIntegrations, registerComponent, tailwindStylesCategory, useApi, useApiStateful, useEmbedEvent, useEmbedProperties, useEmitEmbedEvent, useStreamingApi, useSuperblocksDataTags, useSuperblocksGroups, useSuperblocksProfiles, useSuperblocksUser, useTypedApi };
6173
+ export { App, PageNotFound, Prop, Property, PropsCategory, RouteLoadError, Section, Superblocks, sb_provider_default as SuperblocksProvider, embedStore, getAppMode, logoutIntegrations, registerComponent, tailwindStylesCategory, useApiStateful as useApi, useEmbedEvent, useEmbedProperties, useEmitEmbedEvent, useSuperblocksGroups, useSuperblocksProfiles, useSuperblocksUser };
6768
6174
  //# sourceMappingURL=index.js.map