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