@blinkdotnew/dev-sdk 2.1.5 → 2.1.7

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/index.mjs CHANGED
@@ -5,33 +5,6 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
5
5
  throw Error('Dynamic require of "' + x + '" is not supported');
6
6
  });
7
7
 
8
- // ../core/src/platform.ts
9
- function detectPlatform() {
10
- if (typeof Deno !== "undefined") {
11
- return "deno";
12
- }
13
- if (typeof process !== "undefined" && process.versions?.node) {
14
- if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
15
- return "react-native";
16
- }
17
- return "node";
18
- }
19
- if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
20
- return "react-native";
21
- }
22
- if (typeof window !== "undefined" && typeof document !== "undefined") {
23
- return "web";
24
- }
25
- return "node";
26
- }
27
- var platform = detectPlatform();
28
- var isWeb = platform === "web";
29
- var isReactNative = platform === "react-native";
30
- var isNode = platform === "node";
31
- var isDeno = platform === "deno";
32
- var isBrowser = isWeb || isReactNative;
33
- var isServer = isNode || isDeno;
34
-
35
8
  // ../core/src/storage-adapter.ts
36
9
  var WebStorageAdapter = class {
37
10
  getItem(key) {
@@ -117,9 +90,6 @@ var NoOpStorageAdapter = class {
117
90
  }
118
91
  };
119
92
  function getDefaultStorageAdapter() {
120
- if (isDeno) {
121
- return new NoOpStorageAdapter();
122
- }
123
93
  if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
124
94
  try {
125
95
  localStorage.setItem("__test__", "test");
@@ -131,6 +101,28 @@ function getDefaultStorageAdapter() {
131
101
  return new NoOpStorageAdapter();
132
102
  }
133
103
 
104
+ // ../core/src/platform.ts
105
+ function detectPlatform() {
106
+ if (typeof process !== "undefined" && process.versions?.node) {
107
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
108
+ return "react-native";
109
+ }
110
+ return "node";
111
+ }
112
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
113
+ return "react-native";
114
+ }
115
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
116
+ return "web";
117
+ }
118
+ return "node";
119
+ }
120
+ var platform = detectPlatform();
121
+ var isWeb = platform === "web";
122
+ var isReactNative = platform === "react-native";
123
+ var isNode = platform === "node";
124
+ var isBrowser = isWeb || isReactNative;
125
+
134
126
  // ../core/src/types.ts
135
127
  var BlinkError = class extends Error {
136
128
  constructor(message, code, status, details) {
@@ -394,44 +386,17 @@ function convertKeysToCamelCase(obj) {
394
386
  return converted;
395
387
  }
396
388
  var HttpClient = class {
397
- authUrl = "https://blink.new";
398
- coreUrl = "https://core.blink.new";
389
+ authUrl;
390
+ coreUrl;
399
391
  projectId;
400
- publishableKey;
401
- secretKey;
402
- // Permanent, non-expiring key (like Stripe's sk_live_...)
403
392
  getToken;
404
393
  getValidToken;
405
394
  constructor(config, getToken, getValidToken) {
406
395
  this.projectId = config.projectId;
407
- this.publishableKey = config.publishableKey;
408
- this.secretKey = config.secretKey || config.serviceToken;
409
396
  this.getToken = getToken;
410
397
  this.getValidToken = getValidToken;
411
- }
412
- shouldAttachPublishableKey(path, method) {
413
- if (method !== "GET" && method !== "POST") return false;
414
- if (path.includes("/api/analytics/")) return true;
415
- if (path.includes("/api/storage/")) return true;
416
- if (path.includes("/api/db/") && path.includes("/rest/v1/")) return method === "GET";
417
- return false;
418
- }
419
- shouldSkipSecretKey(url) {
420
- try {
421
- const parsed = new URL(url);
422
- return parsed.hostname.endsWith(".functions.blink.new");
423
- } catch {
424
- return false;
425
- }
426
- }
427
- getAuthorizationHeader(url, token) {
428
- if (this.secretKey && !this.shouldSkipSecretKey(url)) {
429
- return `Bearer ${this.secretKey}`;
430
- }
431
- if (token) {
432
- return `Bearer ${token}`;
433
- }
434
- return null;
398
+ this.authUrl = config.auth?.authUrl ?? "https://blink.new";
399
+ this.coreUrl = config.auth?.coreUrl ?? "https://dev.core.blink.new";
435
400
  }
436
401
  /**
437
402
  * Make an authenticated request to the Blink API
@@ -439,23 +404,19 @@ var HttpClient = class {
439
404
  async request(path, options = {}) {
440
405
  const url = this.buildUrl(path, options.searchParams);
441
406
  const token = this.getValidToken ? await this.getValidToken() : this.getToken();
442
- const method = options.method || "GET";
443
407
  const headers = {
444
408
  "Content-Type": "application/json",
445
409
  ...options.headers
446
410
  };
447
- const auth = this.getAuthorizationHeader(url, token);
448
- if (auth) {
449
- headers.Authorization = auth;
450
- } else if (this.publishableKey && !headers["x-blink-publishable-key"] && this.shouldAttachPublishableKey(path, method)) {
451
- headers["x-blink-publishable-key"] = this.publishableKey;
411
+ if (token) {
412
+ headers.Authorization = `Bearer ${token}`;
452
413
  }
453
414
  const requestInit = {
454
- method,
415
+ method: options.method || "GET",
455
416
  headers,
456
417
  signal: options.signal
457
418
  };
458
- if (options.body && method !== "GET") {
419
+ if (options.body && options.method !== "GET") {
459
420
  requestInit.body = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
460
421
  }
461
422
  try {
@@ -609,12 +570,12 @@ var HttpClient = class {
609
570
  throw new BlinkValidationError("Unsupported file type");
610
571
  }
611
572
  formData.append("path", filePath);
573
+ if (options.upsert !== void 0) {
574
+ formData.append("options", JSON.stringify({ upsert: options.upsert }));
575
+ }
612
576
  const headers = {};
613
- const auth = this.getAuthorizationHeader(url, token);
614
- if (auth) {
615
- headers.Authorization = auth;
616
- } else if (this.publishableKey && path.includes("/api/storage/") && !headers["x-blink-publishable-key"]) {
617
- headers["x-blink-publishable-key"] = this.publishableKey;
577
+ if (token) {
578
+ headers.Authorization = `Bearer ${token}`;
618
579
  }
619
580
  try {
620
581
  if (typeof XMLHttpRequest !== "undefined" && options.onProgress) {
@@ -715,7 +676,7 @@ var HttpClient = class {
715
676
  });
716
677
  }
717
678
  /**
718
- * Stream AI text generation - uses Vercel AI SDK's pipeUIMessageStreamToResponse (Data Stream Protocol)
679
+ * Stream AI text generation with Vercel AI SDK data stream format
719
680
  */
720
681
  async streamAiText(prompt, options = {}, onChunk) {
721
682
  const url = this.buildUrl(`/api/ai/${this.projectId}/text`);
@@ -723,8 +684,9 @@ var HttpClient = class {
723
684
  const headers = {
724
685
  "Content-Type": "application/json"
725
686
  };
726
- const auth = this.getAuthorizationHeader(url, token);
727
- if (auth) headers.Authorization = auth;
687
+ if (token) {
688
+ headers.Authorization = `Bearer ${token}`;
689
+ }
728
690
  const body = {
729
691
  prompt,
730
692
  stream: true,
@@ -744,7 +706,7 @@ var HttpClient = class {
744
706
  if (!response.body) {
745
707
  throw new BlinkNetworkError("No response body for streaming");
746
708
  }
747
- return this.parseDataStreamProtocol(response.body, onChunk);
709
+ return this.parseDataStream(response.body, onChunk);
748
710
  } catch (error) {
749
711
  if (error instanceof BlinkError) {
750
712
  throw error;
@@ -769,7 +731,7 @@ var HttpClient = class {
769
731
  });
770
732
  }
771
733
  /**
772
- * Stream AI object generation - uses Vercel AI SDK's pipeTextStreamToResponse
734
+ * Stream AI object generation with Vercel AI SDK data stream format
773
735
  */
774
736
  async streamAiObject(prompt, options = {}, onPartial) {
775
737
  const url = this.buildUrl(`/api/ai/${this.projectId}/object`);
@@ -777,8 +739,9 @@ var HttpClient = class {
777
739
  const headers = {
778
740
  "Content-Type": "application/json"
779
741
  };
780
- const auth = this.getAuthorizationHeader(url, token);
781
- if (auth) headers.Authorization = auth;
742
+ if (token) {
743
+ headers.Authorization = `Bearer ${token}`;
744
+ }
782
745
  const body = {
783
746
  prompt,
784
747
  stream: true,
@@ -798,35 +761,7 @@ var HttpClient = class {
798
761
  if (!response.body) {
799
762
  throw new BlinkNetworkError("No response body for streaming");
800
763
  }
801
- const reader = response.body.getReader();
802
- const decoder = new TextDecoder();
803
- let buffer = "";
804
- let latestObject = {};
805
- try {
806
- while (true) {
807
- const { done, value } = await reader.read();
808
- if (done) break;
809
- const chunk = decoder.decode(value, { stream: true });
810
- buffer += chunk;
811
- try {
812
- const parsed = JSON.parse(buffer);
813
- latestObject = parsed;
814
- if (onPartial) {
815
- onPartial(parsed);
816
- }
817
- } catch {
818
- }
819
- }
820
- if (buffer) {
821
- try {
822
- latestObject = JSON.parse(buffer);
823
- } catch {
824
- }
825
- }
826
- return { object: latestObject };
827
- } finally {
828
- reader.releaseLock();
829
- }
764
+ return this.parseDataStream(response.body, void 0, onPartial);
830
765
  } catch (error) {
831
766
  if (error instanceof BlinkError) {
832
767
  throw error;
@@ -883,17 +818,6 @@ var HttpClient = class {
883
818
  signal
884
819
  });
885
820
  }
886
- async aiVideo(prompt, options = {}) {
887
- const { signal, ...body } = options;
888
- return this.request(`/api/ai/${this.projectId}/video`, {
889
- method: "POST",
890
- body: {
891
- prompt,
892
- ...body
893
- },
894
- signal
895
- });
896
- }
897
821
  /**
898
822
  * Data-specific requests
899
823
  */
@@ -935,38 +859,6 @@ var HttpClient = class {
935
859
  async dataSearch(projectId, request) {
936
860
  return this.post(`/api/data/${projectId}/search`, request);
937
861
  }
938
- /**
939
- * Connector requests
940
- */
941
- formatProviderForPath(provider) {
942
- return provider.replace("_", "-");
943
- }
944
- async connectorStatus(provider) {
945
- return this.request(`/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}/status`, {
946
- method: "GET"
947
- });
948
- }
949
- async connectorExecute(provider, request) {
950
- const path = request.method.startsWith("/") ? request.method : `/${request.method}`;
951
- const url = `/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}${path}`;
952
- const method = (request.http_method || "GET").toUpperCase();
953
- if (method === "GET") {
954
- return this.request(url, {
955
- method: "GET",
956
- searchParams: request.params
957
- });
958
- }
959
- return this.request(url, {
960
- method,
961
- body: request.params || {}
962
- });
963
- }
964
- async connectorSaveApiKey(provider, request) {
965
- return this.request(`/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}/api-key`, {
966
- method: "POST",
967
- body: request
968
- });
969
- }
970
862
  /**
971
863
  * Realtime-specific requests
972
864
  */
@@ -1032,94 +924,93 @@ var HttpClient = class {
1032
924
  }
1033
925
  }
1034
926
  /**
1035
- * Parse Vercel AI SDK v5 Data Stream Protocol (Server-Sent Events)
1036
- * Supports all event types from the UI Message Stream protocol
927
+ * Parse Vercel AI SDK data stream format
928
+ * Handles text chunks (0:"text"), partial objects (2:[...]), and metadata (d:, e:)
1037
929
  */
1038
- async parseDataStreamProtocol(body, onChunk) {
930
+ async parseDataStream(body, onChunk, onPartial) {
1039
931
  const reader = body.getReader();
1040
932
  const decoder = new TextDecoder();
1041
- const finalResult = {
1042
- text: "",
1043
- toolCalls: [],
1044
- toolResults: [],
1045
- sources: [],
1046
- files: [],
1047
- reasoning: []
1048
- };
1049
933
  let buffer = "";
934
+ let finalResult = {};
1050
935
  try {
1051
936
  while (true) {
1052
937
  const { done, value } = await reader.read();
1053
938
  if (done) break;
1054
939
  buffer += decoder.decode(value, { stream: true });
1055
- const lines = buffer.split("\n");
940
+ const lines = buffer.split(/\r?\n/);
1056
941
  buffer = lines.pop() || "";
1057
942
  for (const line of lines) {
1058
943
  if (!line.trim()) continue;
1059
- if (line === "[DONE]") {
1060
- continue;
1061
- }
1062
- if (!line.startsWith("data: ")) continue;
1063
944
  try {
1064
- const jsonStr = line.slice(6);
1065
- const part = JSON.parse(jsonStr);
1066
- switch (part.type) {
1067
- case "text-start":
1068
- break;
1069
- case "text-delta":
1070
- if (part.delta) {
1071
- finalResult.text += part.delta;
1072
- if (onChunk) onChunk(part.delta);
945
+ if (line.startsWith("f:")) {
946
+ const metadata = JSON.parse(line.slice(2));
947
+ finalResult.messageId = metadata.messageId;
948
+ } else if (line.startsWith("0:")) {
949
+ const textChunk = JSON.parse(line.slice(2));
950
+ if (onChunk) {
951
+ onChunk(textChunk);
952
+ }
953
+ finalResult.text = (finalResult.text || "") + textChunk;
954
+ } else if (line.startsWith("2:")) {
955
+ const data = JSON.parse(line.slice(2));
956
+ if (Array.isArray(data) && data.length > 0) {
957
+ const item = data[0];
958
+ if (typeof item === "string") {
959
+ finalResult.status = item;
960
+ } else if (typeof item === "object") {
961
+ if (onPartial) {
962
+ onPartial(item);
963
+ }
964
+ finalResult.object = item;
1073
965
  }
1074
- if (part.textDelta) {
1075
- finalResult.text += part.textDelta;
1076
- if (onChunk) onChunk(part.textDelta);
966
+ }
967
+ } else if (line.startsWith("d:")) {
968
+ const metadata = JSON.parse(line.slice(2));
969
+ if (metadata.usage) {
970
+ finalResult.usage = metadata.usage;
971
+ }
972
+ if (metadata.finishReason) {
973
+ finalResult.finishReason = metadata.finishReason;
974
+ }
975
+ } else if (line.startsWith("e:")) {
976
+ const errorData = JSON.parse(line.slice(2));
977
+ finalResult.error = errorData;
978
+ }
979
+ } catch (error) {
980
+ console.warn("Failed to parse stream line:", line, error);
981
+ }
982
+ }
983
+ }
984
+ if (buffer.trim()) {
985
+ try {
986
+ if (buffer.startsWith("0:")) {
987
+ const textChunk = JSON.parse(buffer.slice(2));
988
+ if (onChunk) {
989
+ onChunk(textChunk);
990
+ }
991
+ finalResult.text = (finalResult.text || "") + textChunk;
992
+ } else if (buffer.startsWith("2:")) {
993
+ const data = JSON.parse(buffer.slice(2));
994
+ if (Array.isArray(data) && data.length > 0) {
995
+ const item = data[0];
996
+ if (typeof item === "object") {
997
+ if (onPartial) {
998
+ onPartial(item);
1077
999
  }
1078
- break;
1079
- case "text-end":
1080
- break;
1081
- case "tool-call":
1082
- finalResult.toolCalls.push({
1083
- toolCallId: part.toolCallId,
1084
- toolName: part.toolName,
1085
- args: part.args
1086
- });
1087
- break;
1088
- case "tool-result":
1089
- finalResult.toolResults.push({
1090
- toolCallId: part.toolCallId,
1091
- toolName: part.toolName,
1092
- result: part.result
1093
- });
1094
- break;
1095
- case "source-url":
1096
- finalResult.sources.push({
1097
- id: part.id,
1098
- url: part.url,
1099
- title: part.title
1100
- });
1101
- break;
1102
- case "file":
1103
- finalResult.files.push(part.file);
1104
- break;
1105
- case "reasoning":
1106
- finalResult.reasoning.push(part.content);
1107
- break;
1108
- case "finish":
1109
- finalResult.finishReason = part.finishReason;
1110
- finalResult.usage = part.usage;
1111
- if (part.response) finalResult.response = part.response;
1112
- break;
1113
- case "error":
1114
- finalResult.error = part.error;
1115
- throw new Error(part.error);
1116
- case "data":
1117
- if (!finalResult.customData) finalResult.customData = [];
1118
- finalResult.customData.push(part.value);
1119
- break;
1000
+ finalResult.object = item;
1001
+ }
1002
+ }
1003
+ } else if (buffer.startsWith("d:")) {
1004
+ const metadata = JSON.parse(buffer.slice(2));
1005
+ if (metadata.usage) {
1006
+ finalResult.usage = metadata.usage;
1007
+ }
1008
+ if (metadata.finishReason) {
1009
+ finalResult.finishReason = metadata.finishReason;
1120
1010
  }
1121
- } catch (e) {
1122
1011
  }
1012
+ } catch (error) {
1013
+ console.warn("Failed to parse final buffer:", buffer, error);
1123
1014
  }
1124
1015
  }
1125
1016
  return finalResult;
@@ -1287,13 +1178,13 @@ var BlinkAuth = class {
1287
1178
  mode: "managed",
1288
1179
  // Default mode
1289
1180
  authUrl: "https://blink.new",
1290
- coreUrl: "https://core.blink.new",
1181
+ coreUrl: "https://dev.core.blink.new",
1291
1182
  detectSessionInUrl: true,
1292
1183
  // Default to true for web compatibility
1293
1184
  ...config.auth
1294
1185
  };
1295
1186
  this.authUrl = this.authConfig.authUrl || "https://blink.new";
1296
- this.coreUrl = this.authConfig.coreUrl || "https://core.blink.new";
1187
+ this.coreUrl = this.authConfig.coreUrl || "https://dev.core.blink.new";
1297
1188
  const hostname = getLocationHostname();
1298
1189
  if (hostname && this.authUrl === "https://blink.new" && (hostname === "localhost" || hostname === "127.0.0.1")) {
1299
1190
  console.warn("\u26A0\uFE0F Using default authUrl in development. Set auth.authUrl to your app origin for headless auth endpoints to work.");
@@ -1462,17 +1353,6 @@ var BlinkAuth = class {
1462
1353
  console.warn("Failed to parse redirect URL:", e);
1463
1354
  }
1464
1355
  }
1465
- if (isWeb && this.isIframe && hasWindow() && window.parent !== window) {
1466
- console.log("\u{1F5BC}\uFE0F In iframe, delegating login to parent window");
1467
- this.setupParentTokenListener();
1468
- window.parent.postMessage({
1469
- type: "BLINK_AUTH_LOGIN_REQUEST",
1470
- projectId: this.config.projectId,
1471
- redirectUrl: redirectUrl || "",
1472
- authUrl: this.authUrl
1473
- }, "*");
1474
- return;
1475
- }
1476
1356
  const authUrl = new URL("/auth", this.authUrl);
1477
1357
  authUrl.searchParams.set("redirect_url", redirectUrl || "");
1478
1358
  if (this.config.projectId) {
@@ -1480,34 +1360,6 @@ var BlinkAuth = class {
1480
1360
  }
1481
1361
  window.location.href = authUrl.toString();
1482
1362
  }
1483
- /**
1484
- * Set up listener for tokens from parent window (for iframe OAuth delegation)
1485
- */
1486
- setupParentTokenListener() {
1487
- if (typeof window === "undefined") return;
1488
- const messageListener = (event) => {
1489
- const { type, access_token, refresh_token, expires_in, refresh_expires_in, issued_at, projectId, error } = event.data || {};
1490
- if (type === "BLINK_AUTH_TOKENS") {
1491
- if (projectId && projectId !== this.config.projectId) {
1492
- return;
1493
- }
1494
- console.log("\u{1F4E5} Received auth tokens from parent window");
1495
- window.removeEventListener("message", messageListener);
1496
- this.setTokens({
1497
- access_token,
1498
- refresh_token,
1499
- token_type: "Bearer",
1500
- expires_in: expires_in || 3600,
1501
- refresh_expires_in,
1502
- issued_at: issued_at || Math.floor(Date.now() / 1e3)
1503
- }, true);
1504
- } else if (type === "BLINK_AUTH_ERROR") {
1505
- window.removeEventListener("message", messageListener);
1506
- console.error("Auth error from parent:", error);
1507
- }
1508
- };
1509
- window.addEventListener("message", messageListener);
1510
- }
1511
1363
  /**
1512
1364
  * Logout and clear stored tokens
1513
1365
  */
@@ -3085,11 +2937,6 @@ var BlinkAuth = class {
3085
2937
  };
3086
2938
 
3087
2939
  // src/database.ts
3088
- function assertServerOnly(methodName) {
3089
- if (typeof window !== "undefined") {
3090
- throw new Error(`${methodName} is server-only. Use Blink CRUD methods (blink.db.<table>.*) instead.`);
3091
- }
3092
- }
3093
2940
  function camelToSnake3(str) {
3094
2941
  return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
3095
2942
  }
@@ -3308,7 +3155,6 @@ var BlinkTable = class {
3308
3155
  * Raw SQL query on this table (for advanced use cases)
3309
3156
  */
3310
3157
  async sql(query, params) {
3311
- assertServerOnly("blink.db.<table>.sql");
3312
3158
  const response = await this.httpClient.dbSql(query, params);
3313
3159
  return response.data;
3314
3160
  }
@@ -3357,7 +3203,6 @@ var BlinkDatabase = class {
3357
3203
  * Execute raw SQL query
3358
3204
  */
3359
3205
  async sql(query, params) {
3360
- assertServerOnly("blink.db.sql");
3361
3206
  const response = await this.httpClient.dbSql(query, params);
3362
3207
  return response.data;
3363
3208
  }
@@ -3365,7 +3210,6 @@ var BlinkDatabase = class {
3365
3210
  * Execute batch SQL operations
3366
3211
  */
3367
3212
  async batch(statements, mode = "write") {
3368
- assertServerOnly("blink.db.batch");
3369
3213
  const response = await this.httpClient.dbBatch(statements, mode);
3370
3214
  return response.data;
3371
3215
  }
@@ -3428,6 +3272,7 @@ var BlinkStorageImpl = class {
3428
3272
  correctedPath,
3429
3273
  // Use corrected path with proper extension
3430
3274
  {
3275
+ upsert: options.upsert,
3431
3276
  onProgress: options.onProgress,
3432
3277
  contentType: detectedContentType
3433
3278
  // Pass detected content type
@@ -3447,7 +3292,7 @@ var BlinkStorageImpl = class {
3447
3292
  if (error instanceof Error && "status" in error) {
3448
3293
  const status = error.status;
3449
3294
  if (status === 409) {
3450
- throw new BlinkStorageError("File already exists.", 409);
3295
+ throw new BlinkStorageError("File already exists. Set upsert: true to overwrite.", 409);
3451
3296
  }
3452
3297
  if (status === 400) {
3453
3298
  throw new BlinkStorageError("Invalid request parameters", 400);
@@ -3492,6 +3337,7 @@ var BlinkStorageImpl = class {
3492
3337
  detectedContentType
3493
3338
  };
3494
3339
  } catch (error) {
3340
+ console.warn("File type detection failed, using original path:", error);
3495
3341
  return {
3496
3342
  correctedPath: originalPath,
3497
3343
  detectedContentType: "application/octet-stream"
@@ -3881,7 +3727,13 @@ var BlinkAIImpl = class {
3881
3727
  options.prompt || "",
3882
3728
  requestBody
3883
3729
  );
3884
- return response.data;
3730
+ if (response.data?.result) {
3731
+ return response.data.result;
3732
+ } else if (response.data?.text) {
3733
+ return response.data;
3734
+ } else {
3735
+ throw new BlinkAIError("Invalid response format: missing text");
3736
+ }
3885
3737
  } catch (error) {
3886
3738
  if (error instanceof BlinkAIError) {
3887
3739
  throw error;
@@ -3950,14 +3802,9 @@ var BlinkAIImpl = class {
3950
3802
  );
3951
3803
  return {
3952
3804
  text: result.text || "",
3953
- finishReason: result.finishReason || "stop",
3805
+ finishReason: "stop",
3954
3806
  usage: result.usage,
3955
- toolCalls: result.toolCalls,
3956
- toolResults: result.toolResults,
3957
- sources: result.sources,
3958
- files: result.files,
3959
- reasoningDetails: result.reasoning,
3960
- response: result.response
3807
+ ...result
3961
3808
  };
3962
3809
  } catch (error) {
3963
3810
  if (error instanceof BlinkAIError) {
@@ -4036,7 +3883,13 @@ var BlinkAIImpl = class {
4036
3883
  signal: options.signal
4037
3884
  }
4038
3885
  );
4039
- return response.data;
3886
+ if (response.data?.result) {
3887
+ return response.data.result;
3888
+ } else if (response.data?.object) {
3889
+ return response.data;
3890
+ } else {
3891
+ throw new BlinkAIError("Invalid response format: missing object");
3892
+ }
4040
3893
  } catch (error) {
4041
3894
  if (error instanceof BlinkAIError) {
4042
3895
  throw error;
@@ -4098,7 +3951,8 @@ var BlinkAIImpl = class {
4098
3951
  return {
4099
3952
  object: result.object || {},
4100
3953
  finishReason: "stop",
4101
- usage: result.usage
3954
+ usage: result.usage,
3955
+ ...result
4102
3956
  };
4103
3957
  } catch (error) {
4104
3958
  if (error instanceof BlinkAIError) {
@@ -4359,131 +4213,6 @@ var BlinkAIImpl = class {
4359
4213
  );
4360
4214
  }
4361
4215
  }
4362
- /**
4363
- * Generates videos from text prompts or images using AI video generation models.
4364
- *
4365
- * @param options - Object containing:
4366
- * - `prompt`: Text description of the video to generate (required)
4367
- * - `model`: Video model to use (optional). Available models:
4368
- * **Text-to-Video Models:**
4369
- * - `"fal-ai/veo3.1"` - Google Veo 3.1 (best quality)
4370
- * - `"fal-ai/veo3.1/fast"` (default) - Veo 3.1 fast mode (faster, cheaper)
4371
- * - `"fal-ai/sora-2/text-to-video/pro"` - OpenAI Sora 2
4372
- * - `"fal-ai/kling-video/v2.6/pro/text-to-video"` - Kling 2.6
4373
- * **Image-to-Video Models:**
4374
- * - `"fal-ai/veo3.1/image-to-video"` - Veo 3.1 I2V
4375
- * - `"fal-ai/veo3.1/fast/image-to-video"` - Veo 3.1 fast I2V
4376
- * - `"fal-ai/sora-2/image-to-video/pro"` - Sora 2 I2V
4377
- * - `"fal-ai/kling-video/v2.6/pro/image-to-video"` - Kling 2.6 I2V
4378
- * - `image_url`: Source image URL for image-to-video (required for I2V models)
4379
- * - `duration`: Video duration ("4s", "5s", "6s", "8s", "10s", "12s")
4380
- * - `aspect_ratio`: Aspect ratio ("16:9", "9:16", "1:1")
4381
- * - `resolution`: Resolution ("720p", "1080p") - Veo/Sora only
4382
- * - `negative_prompt`: What to avoid in generation - Veo/Kling only
4383
- * - `generate_audio`: Generate audio with video (default: true)
4384
- * - `seed`: For reproducibility - Veo only
4385
- * - `cfg_scale`: Guidance scale (0-1) - Kling only
4386
- * - Plus optional signal parameter
4387
- *
4388
- * @example
4389
- * ```ts
4390
- * // Basic text-to-video generation (uses default fast model)
4391
- * const { result } = await blink.ai.generateVideo({
4392
- * prompt: "A serene sunset over the ocean with gentle waves"
4393
- * });
4394
- * console.log("Video URL:", result.video.url);
4395
- *
4396
- * // High quality with Veo 3.1
4397
- * const { result } = await blink.ai.generateVideo({
4398
- * prompt: "A cinematic shot of a futuristic city at night",
4399
- * model: "fal-ai/veo3.1",
4400
- * resolution: "1080p",
4401
- * aspect_ratio: "16:9"
4402
- * });
4403
- *
4404
- * // Image-to-video animation
4405
- * const { result } = await blink.ai.generateVideo({
4406
- * prompt: "Animate this image with gentle camera movement",
4407
- * model: "fal-ai/veo3.1/fast/image-to-video",
4408
- * image_url: "https://example.com/my-image.jpg",
4409
- * duration: "5s"
4410
- * });
4411
- *
4412
- * // Using Sora 2 for creative videos
4413
- * const { result } = await blink.ai.generateVideo({
4414
- * prompt: "A magical forest with glowing fireflies",
4415
- * model: "fal-ai/sora-2/text-to-video/pro",
4416
- * duration: "8s"
4417
- * });
4418
- *
4419
- * // Using Kling for detailed videos
4420
- * const { result, usage } = await blink.ai.generateVideo({
4421
- * prompt: "A professional cooking tutorial scene",
4422
- * model: "fal-ai/kling-video/v2.6/pro/text-to-video",
4423
- * negative_prompt: "blur, distort, low quality",
4424
- * cfg_scale: 0.7
4425
- * });
4426
- * console.log("Credits charged:", usage?.creditsCharged);
4427
- * ```
4428
- *
4429
- * @returns Promise<VideoGenerationResponse> - Object containing:
4430
- * - `result.video.url`: URL to the generated video
4431
- * - `result.video.content_type`: MIME type (video/mp4)
4432
- * - `result.video.file_name`: Generated filename
4433
- * - `result.video.file_size`: File size in bytes
4434
- * - `metadata`: Generation metadata (projectId, timestamp, model)
4435
- * - `usage`: Credits charged and cost information
4436
- */
4437
- async generateVideo(options) {
4438
- try {
4439
- if (!options.prompt) {
4440
- throw new BlinkAIError("Prompt is required");
4441
- }
4442
- const i2vModels = [
4443
- "fal-ai/veo3.1/image-to-video",
4444
- "fal-ai/veo3.1/fast/image-to-video",
4445
- "fal-ai/sora-2/image-to-video/pro",
4446
- "fal-ai/kling-video/v2.6/pro/image-to-video"
4447
- ];
4448
- if (options.model && i2vModels.includes(options.model) && !options.image_url) {
4449
- throw new BlinkAIError("image_url is required for image-to-video models");
4450
- }
4451
- if (options.image_url) {
4452
- const validation = this.validateImageUrl(options.image_url);
4453
- if (!validation.isValid) {
4454
- throw new BlinkAIError(`Invalid image_url: ${validation.error}`);
4455
- }
4456
- }
4457
- const response = await this.httpClient.aiVideo(
4458
- options.prompt,
4459
- {
4460
- model: options.model,
4461
- image_url: options.image_url,
4462
- duration: options.duration,
4463
- aspect_ratio: options.aspect_ratio,
4464
- resolution: options.resolution,
4465
- negative_prompt: options.negative_prompt,
4466
- generate_audio: options.generate_audio,
4467
- seed: options.seed,
4468
- cfg_scale: options.cfg_scale,
4469
- signal: options.signal
4470
- }
4471
- );
4472
- if (!response.data?.result?.video?.url) {
4473
- throw new BlinkAIError("Invalid response format: missing video URL");
4474
- }
4475
- return response.data;
4476
- } catch (error) {
4477
- if (error instanceof BlinkAIError) {
4478
- throw error;
4479
- }
4480
- throw new BlinkAIError(
4481
- `Video generation failed: ${error instanceof Error ? error.message : "Unknown error"}`,
4482
- void 0,
4483
- { originalError: error }
4484
- );
4485
- }
4486
- }
4487
4216
  /**
4488
4217
  * Converts text to speech using AI voice synthesis models.
4489
4218
  *
@@ -5073,7 +4802,7 @@ var BlinkRealtimeChannel = class {
5073
4802
  return new Promise((resolve, reject) => {
5074
4803
  try {
5075
4804
  const httpClient = this.httpClient;
5076
- const coreUrl = httpClient.coreUrl || "https://core.blink.new";
4805
+ const coreUrl = httpClient.coreUrl || "https://dev.core.blink.new";
5077
4806
  const baseUrl = coreUrl.replace("https://", "wss://").replace("http://", "ws://");
5078
4807
  const wsUrl = `${baseUrl}?project_id=${this.projectId}`;
5079
4808
  console.log(`\u{1F517} Attempting WebSocket connection to: ${wsUrl}`);
@@ -5542,6 +5271,7 @@ var BlinkAnalyticsImpl = class {
5542
5271
  } catch (error) {
5543
5272
  this.queue = [...events, ...this.queue];
5544
5273
  this.persistQueue();
5274
+ console.error("Failed to send analytics events:", error);
5545
5275
  }
5546
5276
  if (this.queue.length > 0) {
5547
5277
  this.timer = setTimeout(() => this.flush(), BATCH_TIMEOUT);
@@ -5732,64 +5462,6 @@ var BlinkAnalyticsImpl = class {
5732
5462
  }
5733
5463
  };
5734
5464
 
5735
- // src/connectors.ts
5736
- var BlinkConnectorsImpl = class {
5737
- constructor(httpClient) {
5738
- this.httpClient = httpClient;
5739
- }
5740
- async status(provider, options) {
5741
- const response = await this.httpClient.connectorStatus(provider);
5742
- return response.data;
5743
- }
5744
- async execute(provider, request) {
5745
- const response = await this.httpClient.connectorExecute(provider, request);
5746
- return response.data;
5747
- }
5748
- async saveApiKey(provider, request) {
5749
- const response = await this.httpClient.connectorSaveApiKey(provider, request);
5750
- return response.data;
5751
- }
5752
- };
5753
-
5754
- // src/functions.ts
5755
- var BlinkFunctionsImpl = class {
5756
- httpClient;
5757
- projectId;
5758
- constructor(httpClient, projectId, _getToken) {
5759
- this.httpClient = httpClient;
5760
- this.projectId = projectId;
5761
- }
5762
- /**
5763
- * Get the project suffix from the full project ID.
5764
- * Project IDs are formatted as: prj_xxxxx
5765
- * The suffix is the last 8 characters used in function URLs.
5766
- */
5767
- getProjectSuffix() {
5768
- return this.projectId.slice(-8);
5769
- }
5770
- /**
5771
- * Build the full function URL
5772
- */
5773
- buildFunctionUrl(functionSlug, searchParams) {
5774
- const suffix = this.getProjectSuffix();
5775
- const baseUrl = `https://${suffix}--${functionSlug}.functions.blink.new`;
5776
- if (!searchParams || Object.keys(searchParams).length === 0) {
5777
- return baseUrl;
5778
- }
5779
- const url = new URL(baseUrl);
5780
- Object.entries(searchParams).forEach(([key, value]) => {
5781
- url.searchParams.set(key, value);
5782
- });
5783
- return url.toString();
5784
- }
5785
- async invoke(functionSlug, options = {}) {
5786
- const { method = "POST", body, headers = {}, searchParams } = options;
5787
- const url = this.buildFunctionUrl(functionSlug, searchParams);
5788
- const res = await this.httpClient.request(url, { method, body, headers });
5789
- return { data: res.data, status: res.status, headers: res.headers };
5790
- }
5791
- };
5792
-
5793
5465
  // src/client.ts
5794
5466
  var BlinkClientImpl = class {
5795
5467
  auth;
@@ -5800,13 +5472,8 @@ var BlinkClientImpl = class {
5800
5472
  realtime;
5801
5473
  notifications;
5802
5474
  analytics;
5803
- connectors;
5804
- functions;
5805
5475
  httpClient;
5806
5476
  constructor(config) {
5807
- if ((config.secretKey || config.serviceToken) && isBrowser) {
5808
- throw new Error("secretKey/serviceToken is server-only. Do not provide it in browser/React Native clients.");
5809
- }
5810
5477
  this.auth = new BlinkAuth(config);
5811
5478
  this.httpClient = new HttpClient(
5812
5479
  config,
@@ -5820,12 +5487,6 @@ var BlinkClientImpl = class {
5820
5487
  this.realtime = new BlinkRealtimeImpl(this.httpClient, config.projectId);
5821
5488
  this.notifications = new BlinkNotificationsImpl(this.httpClient);
5822
5489
  this.analytics = new BlinkAnalyticsImpl(this.httpClient, config.projectId);
5823
- this.connectors = new BlinkConnectorsImpl(this.httpClient);
5824
- this.functions = new BlinkFunctionsImpl(
5825
- this.httpClient,
5826
- config.projectId,
5827
- () => this.auth.getValidToken()
5828
- );
5829
5490
  this.auth.onAuthStateChanged((state) => {
5830
5491
  if (state.isAuthenticated && state.user) {
5831
5492
  this.analytics.setUserId(state.user.id);
@@ -5844,6 +5505,6 @@ function createClient(config) {
5844
5505
  return new BlinkClientImpl(config);
5845
5506
  }
5846
5507
 
5847
- export { AsyncStorageAdapter, BlinkAIImpl, BlinkAnalyticsImpl, BlinkConnectorsImpl, BlinkDataImpl, BlinkDatabase, BlinkRealtimeChannel, BlinkRealtimeImpl, BlinkStorageImpl, BlinkTable, NoOpStorageAdapter, WebStorageAdapter, createClient, getDefaultStorageAdapter, isBrowser, isDeno, isNode, isReactNative, isServer, isWeb, platform };
5508
+ export { AsyncStorageAdapter, BlinkAIImpl, BlinkAnalyticsImpl, BlinkDataImpl, BlinkDatabase, BlinkRealtimeChannel, BlinkRealtimeImpl, BlinkStorageImpl, BlinkTable, NoOpStorageAdapter, WebStorageAdapter, createClient, getDefaultStorageAdapter, isBrowser, isNode, isReactNative, isWeb, platform };
5848
5509
  //# sourceMappingURL=index.mjs.map
5849
5510
  //# sourceMappingURL=index.mjs.map