@superblocksteam/library 2.0.103 → 2.0.104-next.0

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
@@ -16,7 +16,7 @@ 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, getIntegrationDeclarations, isStreamingApi } from "@superblocksteam/sdk-api";
19
+ import { getIntegrationDeclarations } from "@superblocksteam/sdk-api";
20
20
  import zodToJsonSchema from "zod-to-json-schema";
21
21
  import * as Dialog from "@radix-ui/react-dialog";
22
22
  import posthog from "posthog-js";
@@ -1051,12 +1051,6 @@ function convertZodSchema(schema) {
1051
1051
  //#endregion
1052
1052
  //#region src/lib/internal-details/lib/sdk-api-registry.ts
1053
1053
  /**
1054
- * SDK API Registry for the library iframe.
1055
- *
1056
- * Tracks registered SDK APIs and notifies ui-code-mode when APIs are
1057
- * registered or unregistered (for display in the sidebar).
1058
- */
1059
- /**
1060
1054
  * Set of registered API names to prevent duplicate registrations.
1061
1055
  */
1062
1056
  const registeredApis = /* @__PURE__ */ new Set();
@@ -1064,25 +1058,20 @@ const registeredApis = /* @__PURE__ */ new Set();
1064
1058
  * Extract metadata from a compiled API for display in the UI.
1065
1059
  *
1066
1060
  * @param name - The API name
1067
- * @param api - The compiled API (regular or streaming)
1061
+ * @param api - The compiled API
1068
1062
  * @param sourceCode - Optional TypeScript source code
1069
1063
  * @returns SdkApiMetadata for the API
1070
1064
  */
1071
1065
  function extractSdkApiMetadata(name, api, sourceCode) {
1072
- const streaming = isStreamingApi(api);
1073
1066
  const inputSchema = convertZodSchema(api.inputSchema);
1074
- let outputSchema;
1075
- let chunkSchema;
1076
- if (streaming) chunkSchema = convertZodSchema(api.chunkSchema);
1077
- else outputSchema = convertZodSchema(api.outputSchema);
1067
+ const outputSchema = convertZodSchema(api.outputSchema);
1078
1068
  const entryPoint = "entryPoint" in api ? api.entryPoint : void 0;
1079
1069
  return {
1080
1070
  name,
1081
1071
  description: api.description,
1082
1072
  inputSchema,
1083
1073
  outputSchema,
1084
- chunkSchema,
1085
- isStreaming: streaming,
1074
+ isStreaming: false,
1086
1075
  entryPoint,
1087
1076
  integrations: (api.integrations ?? []).map((integration) => ({
1088
1077
  key: integration.key,
@@ -1246,31 +1235,6 @@ const getApiPath = (name) => {
1246
1235
  return apiPath;
1247
1236
  };
1248
1237
  /**
1249
- * Resolve integration configs from the parent before API execution.
1250
- * Only used when SDK API mode is enabled.
1251
- *
1252
- * @deprecated Kept for backward compatibility with edit mode.
1253
- */
1254
- async function resolveIntegrations(integrations) {
1255
- if (integrations.length === 0) return [];
1256
- return new Promise((resolve, reject) => {
1257
- const callbackId = addNewPromise((result) => {
1258
- resolve(result);
1259
- }, false, reject);
1260
- sendMessageImmediately({
1261
- type: "sdk-resolve-integrations",
1262
- payload: {
1263
- integrations: integrations.map((i) => ({
1264
- key: i.key,
1265
- pluginId: i.pluginId,
1266
- id: i.id
1267
- })),
1268
- callbackId
1269
- }
1270
- });
1271
- });
1272
- }
1273
- /**
1274
1238
  * React hook for executing YAML-based Superblocks APIs.
1275
1239
  *
1276
1240
  * This is the legacy API system that uses `rootStore.apis.runApiByPath`.
@@ -1454,12 +1418,14 @@ function useApi(apiName, inputs) {
1454
1418
  const { run: legacyRun, cancel: legacyCancel } = useApiStateful(apiName);
1455
1419
  const [loading, setLoading] = useState(false);
1456
1420
  const [data, setData] = useState(void 0);
1421
+ const [error, setError] = useState(void 0);
1457
1422
  const runIdRef = useRef(0);
1458
1423
  const runRef = useRef(null);
1459
1424
  const run = useCallback(async (runInputs) => {
1460
1425
  getInflightFetches().delete(inflightKey(apiName, currentFingerprintRef.current ?? ""));
1461
1426
  const thisRun = ++runIdRef.current;
1462
1427
  setLoading(true);
1428
+ setError(void 0);
1463
1429
  try {
1464
1430
  let sdkApiEnabled = root_store_default.sdkApiEnabled;
1465
1431
  let hasEntryPoint = !!root_store_default.getApiEntryPoint(apiName);
@@ -1469,8 +1435,14 @@ function useApi(apiName, inputs) {
1469
1435
  hasEntryPoint = !!root_store_default.getApiEntryPoint(apiName);
1470
1436
  }
1471
1437
  const result = sdkApiEnabled || hasEntryPoint ? await sdkRun(runInputs ?? {}) : await legacyRun(runInputs);
1472
- if (thisRun === runIdRef.current) setData(result);
1438
+ if (thisRun === runIdRef.current) {
1439
+ setData(result);
1440
+ setError(void 0);
1441
+ }
1473
1442
  return result;
1443
+ } catch (err) {
1444
+ if (thisRun === runIdRef.current) setError(err);
1445
+ throw err;
1474
1446
  } finally {
1475
1447
  if (thisRun === runIdRef.current) setLoading(false);
1476
1448
  }
@@ -1483,6 +1455,7 @@ function useApi(apiName, inputs) {
1483
1455
  const cancel = useCallback(async () => {
1484
1456
  ++runIdRef.current;
1485
1457
  setLoading(false);
1458
+ setError(void 0);
1486
1459
  getInflightFetches().delete(inflightKey(apiName, currentFingerprintRef.current ?? ""));
1487
1460
  if (root_store_default.sdkApiEnabled || !!root_store_default.getApiEntryPoint(apiName)) return sdkCancel();
1488
1461
  return legacyCancel();
@@ -1492,7 +1465,6 @@ function useApi(apiName, inputs) {
1492
1465
  legacyCancel
1493
1466
  ]);
1494
1467
  const inputRecord = inputs;
1495
- const depValues = inputRecord ? [apiName, ...Object.values(inputRecord)] : [];
1496
1468
  const inputFingerprint = inputRecord ? JSON.stringify(Object.entries(inputRecord).sort(([a], [b]) => a.localeCompare(b))) : null;
1497
1469
  const currentFingerprintRef = useRef(inputFingerprint);
1498
1470
  currentFingerprintRef.current = inputFingerprint;
@@ -1505,8 +1477,13 @@ function useApi(apiName, inputs) {
1505
1477
  setLoading(true);
1506
1478
  const thisRun = ++runIdRef.current;
1507
1479
  inflightPromise.then((result) => {
1508
- if (thisRun === runIdRef.current && result !== void 0) setData(result);
1509
- }).catch(() => {}).finally(() => {
1480
+ if (thisRun === runIdRef.current && result !== void 0) {
1481
+ setData(result);
1482
+ setError(void 0);
1483
+ }
1484
+ }).catch((err) => {
1485
+ if (thisRun === runIdRef.current) setError(err);
1486
+ }).finally(() => {
1510
1487
  if (thisRun === runIdRef.current) setLoading(false);
1511
1488
  });
1512
1489
  return () => {
@@ -1518,14 +1495,19 @@ function useApi(apiName, inputs) {
1518
1495
  }
1519
1496
  incMounts(cacheKey);
1520
1497
  let resolveFetch;
1521
- const placeholder = new Promise((resolve) => {
1498
+ let rejectFetch;
1499
+ const placeholder = new Promise((resolve, reject) => {
1522
1500
  resolveFetch = resolve;
1501
+ rejectFetch = reject;
1523
1502
  });
1503
+ placeholder.catch(() => {});
1524
1504
  getInflightFetches().set(cacheKey, placeholder);
1525
1505
  let timerFired = false;
1526
1506
  const timer = setTimeout(() => {
1527
1507
  timerFired = true;
1528
- const fetchResult = runRef.current(inputRecord).catch(() => void 0);
1508
+ const fetchResult = runRef.current(inputRecord).catch((err) => {
1509
+ rejectFetch(err);
1510
+ });
1529
1511
  getInflightFetches().set(cacheKey, placeholder);
1530
1512
  fetchResult.then((result) => {
1531
1513
  resolveFetch(result);
@@ -1543,12 +1525,13 @@ function useApi(apiName, inputs) {
1543
1525
  setLoading(false);
1544
1526
  decMounts(cacheKey);
1545
1527
  };
1546
- }, depValues);
1528
+ }, [apiName, inputFingerprint]);
1547
1529
  return {
1548
1530
  run,
1549
1531
  cancel,
1550
1532
  loading,
1551
- data
1533
+ data,
1534
+ error
1552
1535
  };
1553
1536
  }
1554
1537
  /**
@@ -6814,174 +6797,6 @@ function RouteLoadError() {
6814
6797
  ] }) });
6815
6798
  }
6816
6799
 
6817
- //#endregion
6818
- //#region src/lib/internal-details/use-streaming-api.ts
6819
- /**
6820
- * React hook for calling streaming SDK APIs with real-time chunk delivery.
6821
- *
6822
- * Returns an AsyncGenerator that yields chunks as they arrive, allowing
6823
- * natural iteration with `for await...of`.
6824
- *
6825
- * @param api - The imported CompiledStreamingApi definition
6826
- * @returns Object with `stream` function and `cancel` function
6827
- *
6828
- * @example
6829
- * ```typescript
6830
- * import StreamChatApi from "../apis/StreamChat/api";
6831
- * import { useStreamingApi } from "@superblocksteam/library";
6832
- *
6833
- * const { stream, cancel } = useStreamingApi(StreamChatApi);
6834
- *
6835
- * // Execute and iterate over chunks
6836
- * const generator = stream({ prompt: "Hello!" });
6837
- *
6838
- * for await (const chunk of generator) {
6839
- * console.log(chunk.text);
6840
- * // Update UI with each chunk
6841
- * }
6842
- * ```
6843
- *
6844
- * @example With try/catch for error handling
6845
- * ```typescript
6846
- * const { stream } = useStreamingApi(StreamChatApi);
6847
- *
6848
- * try {
6849
- * for await (const chunk of stream({ prompt: "Hello!" })) {
6850
- * appendToOutput(chunk.text);
6851
- * }
6852
- * console.log("Stream completed!");
6853
- * } catch (error) {
6854
- * console.error("Stream error:", error);
6855
- * }
6856
- * ```
6857
- */
6858
- function useStreamingApi(api) {
6859
- const sdkApiEnabled = root_store_default.sdkApiEnabled;
6860
- const cancelRef = useRef(null);
6861
- return {
6862
- stream: useCallback((inputs) => {
6863
- if (!sdkApiEnabled) throw new Error("useStreamingApi requires SDK API mode to be enabled. This hook is only available in fullstack applications.");
6864
- return createStreamGenerator(api, inputs, cancelRef);
6865
- }, [api, sdkApiEnabled]),
6866
- cancel: useCallback(() => {
6867
- if (cancelRef.current) cancelRef.current();
6868
- }, [])
6869
- };
6870
- }
6871
- /**
6872
- * Creates an async generator for streaming API execution.
6873
- */
6874
- async function* createStreamGenerator(api, inputs, cancelRef) {
6875
- if (!isStreamingApi(api)) throw new Error("Expected a streaming API. Use useApi() for non-streaming APIs.");
6876
- const executeQuery = async (integrationId, request, input) => {
6877
- return new Promise((resolve, reject) => {
6878
- sendMessageImmediately({
6879
- type: "sdk-execute-query",
6880
- payload: {
6881
- integrationId,
6882
- request,
6883
- input,
6884
- callbackId: addNewPromise(resolve, false, reject)
6885
- }
6886
- });
6887
- });
6888
- };
6889
- const executeStreamingQuery = async function* (integrationId, request) {
6890
- const chunkQueue = [];
6891
- let resolveNext = null;
6892
- let streamComplete = false;
6893
- let streamError = null;
6894
- const streamId = `stream-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
6895
- const handleChunk = (event) => {
6896
- if (event.source !== window.parent) return;
6897
- if (event.data?.type === "sdk-stream-chunk" && event.data?.payload?.streamId === streamId) {
6898
- const { chunk, done, error } = event.data.payload;
6899
- if (error) {
6900
- streamError = new Error(error.message || "Stream error");
6901
- streamComplete = true;
6902
- if (resolveNext) {
6903
- resolveNext({
6904
- value: void 0,
6905
- done: true
6906
- });
6907
- resolveNext = null;
6908
- }
6909
- return;
6910
- }
6911
- if (done) {
6912
- streamComplete = true;
6913
- if (resolveNext) {
6914
- resolveNext({
6915
- value: void 0,
6916
- done: true
6917
- });
6918
- resolveNext = null;
6919
- }
6920
- return;
6921
- }
6922
- if (chunk !== void 0) if (resolveNext) {
6923
- resolveNext({
6924
- value: chunk,
6925
- done: false
6926
- });
6927
- resolveNext = null;
6928
- } else chunkQueue.push(chunk);
6929
- }
6930
- };
6931
- window.addEventListener("message", handleChunk);
6932
- cancelRef.current = () => {
6933
- streamComplete = true;
6934
- if (resolveNext) {
6935
- resolveNext({
6936
- value: void 0,
6937
- done: true
6938
- });
6939
- resolveNext = null;
6940
- }
6941
- window.removeEventListener("message", handleChunk);
6942
- sendMessageImmediately({
6943
- type: "sdk-cancel-stream",
6944
- payload: { streamId }
6945
- });
6946
- };
6947
- sendMessageImmediately({
6948
- type: "sdk-execute-streaming-query",
6949
- payload: {
6950
- integrationId,
6951
- request,
6952
- streamId
6953
- }
6954
- });
6955
- try {
6956
- while (!streamComplete || chunkQueue.length > 0) {
6957
- if (streamError) throw streamError;
6958
- if (chunkQueue.length > 0) yield chunkQueue.shift();
6959
- else if (!streamComplete) {
6960
- const result = await new Promise((resolve) => {
6961
- resolveNext = resolve;
6962
- });
6963
- if (!result.done) yield result.value;
6964
- }
6965
- }
6966
- if (streamError) throw streamError;
6967
- } finally {
6968
- window.removeEventListener("message", handleChunk);
6969
- cancelRef.current = null;
6970
- }
6971
- };
6972
- const resolvedIntegrations = await resolveIntegrations(api.integrations ?? []);
6973
- const generator = execute(api, {
6974
- input: inputs ?? {},
6975
- integrations: resolvedIntegrations,
6976
- executionId: `sdk-stream-${Date.now()}`,
6977
- env: {},
6978
- user: root_store_default.sdkUser,
6979
- executeQuery,
6980
- executeStreamingQuery
6981
- });
6982
- for await (const chunk of generator) yield chunk;
6983
- }
6984
-
6985
6800
  //#endregion
6986
6801
  //#region src/lib/user-facing/global-functions.ts
6987
6802
  /**
@@ -7182,5 +6997,5 @@ early_console_buffer_default.getInstance().patchEarly();
7182
6997
  registerHtmlElements();
7183
6998
 
7184
6999
  //#endregion
7185
- 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 };
7000
+ 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, useSuperblocksDataTags, useSuperblocksGroups, useSuperblocksProfiles, useSuperblocksUser, useTypedApi };
7186
7001
  //# sourceMappingURL=index.js.map